Skip to main content

lean_ctx/
setup.rs

1use std::path::PathBuf;
2
3use crate::core::editor_registry::{ConfigType, EditorTarget, WriteAction, WriteOptions};
4use crate::core::portable_binary::resolve_portable_binary;
5use crate::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
6use crate::hooks::{recommend_hook_mode, HookMode};
7use chrono::Utc;
8use std::ffi::OsString;
9
10pub fn claude_config_json_path(home: &std::path::Path) -> PathBuf {
11    crate::core::editor_registry::claude_mcp_json_path(home)
12}
13
14pub fn claude_config_dir(home: &std::path::Path) -> PathBuf {
15    crate::core::editor_registry::claude_state_dir(home)
16}
17
18pub(crate) struct EnvVarGuard {
19    key: &'static str,
20    previous: Option<OsString>,
21}
22
23impl EnvVarGuard {
24    pub(crate) fn set(key: &'static str, value: &str) -> Self {
25        let previous = std::env::var_os(key);
26        std::env::set_var(key, value);
27        Self { key, previous }
28    }
29}
30
31impl Drop for EnvVarGuard {
32    fn drop(&mut self) {
33        if let Some(previous) = &self.previous {
34            std::env::set_var(self.key, previous);
35        } else {
36            std::env::remove_var(self.key);
37        }
38    }
39}
40
41pub fn run_setup() {
42    use crate::terminal_ui;
43
44    if crate::shell::is_non_interactive() {
45        eprintln!("Non-interactive terminal detected (no TTY on stdin).");
46        eprintln!("Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)");
47        eprintln!();
48        let opts = SetupOptions {
49            non_interactive: true,
50            yes: true,
51            ..Default::default()
52        };
53        match run_setup_with_options(opts) {
54            Ok(report) => {
55                if !report.warnings.is_empty() {
56                    for w in &report.warnings {
57                        tracing::warn!("{w}");
58                    }
59                }
60            }
61            Err(e) => tracing::error!("Setup error: {e}"),
62        }
63        return;
64    }
65
66    let Some(home) = dirs::home_dir() else {
67        tracing::error!("Cannot determine home directory");
68        std::process::exit(1);
69    };
70
71    let binary = resolve_portable_binary();
72
73    let home_str = home.to_string_lossy().to_string();
74
75    terminal_ui::print_setup_header();
76
77    // Step 1: Shell hook (legacy aliases + universal shell hook)
78    terminal_ui::print_step_header(1, 11, "Shell Hook");
79    crate::cli::cmd_init(&["--global".to_string()]);
80    crate::shell_hook::install_all(false);
81
82    // Step 2: Daemon (optional acceleration for CLI routing)
83    terminal_ui::print_step_header(2, 11, "Daemon");
84    if crate::daemon::is_daemon_running() {
85        terminal_ui::print_status_ok("Daemon running — restarting with current binary…");
86        let _ = crate::daemon::stop_daemon();
87        std::thread::sleep(std::time::Duration::from_millis(500));
88        if let Err(e) = crate::daemon::start_daemon(&[]) {
89            terminal_ui::print_status_warn(&format!("Daemon restart failed: {e}"));
90        }
91    } else if let Err(e) = crate::daemon::start_daemon(&[]) {
92        terminal_ui::print_status_warn(&format!("Daemon start failed: {e}"));
93    }
94
95    // Step 3: Editor auto-detection + configuration
96    terminal_ui::print_step_header(3, 11, "AI Tool Detection");
97
98    let targets = crate::core::editor_registry::build_targets(&home);
99    let mut newly_configured: Vec<&str> = Vec::new();
100    let mut already_configured: Vec<&str> = Vec::new();
101    let mut not_installed: Vec<&str> = Vec::new();
102    let mut errors: Vec<&str> = Vec::new();
103
104    for target in &targets {
105        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
106
107        if !target.detect_path.exists() {
108            not_installed.push(target.name);
109            continue;
110        }
111
112        let mode = if target.agent_key.is_empty() {
113            HookMode::Mcp
114        } else {
115            recommend_hook_mode(&target.agent_key)
116        };
117
118        match crate::core::editor_registry::write_config_with_options(
119            target,
120            &binary,
121            WriteOptions {
122                overwrite_invalid: false,
123            },
124        ) {
125            Ok(res) if res.action == WriteAction::Already => {
126                terminal_ui::print_status_ok(&format!(
127                    "{:<20} \x1b[36m{mode}\x1b[0m  \x1b[2m{short_path}\x1b[0m",
128                    target.name
129                ));
130                already_configured.push(target.name);
131            }
132            Ok(_) => {
133                terminal_ui::print_status_new(&format!(
134                    "{:<20} \x1b[36m{mode}\x1b[0m  \x1b[2m{short_path}\x1b[0m",
135                    target.name
136                ));
137                newly_configured.push(target.name);
138            }
139            Err(e) => {
140                terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
141                errors.push(target.name);
142            }
143        }
144    }
145
146    let total_ok = newly_configured.len() + already_configured.len();
147    if total_ok == 0 && errors.is_empty() {
148        terminal_ui::print_status_warn(
149            "No AI tools detected. Install one and re-run: lean-ctx setup",
150        );
151    }
152
153    if !not_installed.is_empty() {
154        println!(
155            "  \x1b[2m○ {} not detected: {}\x1b[0m",
156            not_installed.len(),
157            not_installed.join(", ")
158        );
159    }
160
161    configure_plan_mode_settings(&newly_configured, &already_configured);
162
163    // Step 4: Agent rules injection
164    terminal_ui::print_step_header(4, 11, "Agent Rules");
165    let rules_result = crate::rules_inject::inject_all_rules(&home);
166    for name in &rules_result.injected {
167        terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
168    }
169    for name in &rules_result.updated {
170        terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
171    }
172    for name in &rules_result.already {
173        terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
174    }
175    for err in &rules_result.errors {
176        terminal_ui::print_status_warn(err);
177    }
178    if rules_result.injected.is_empty()
179        && rules_result.updated.is_empty()
180        && rules_result.already.is_empty()
181        && rules_result.errors.is_empty()
182    {
183        terminal_ui::print_status_skip("No agent rules needed");
184    }
185
186    // Agent hooks (mode-aware)
187    for target in &targets {
188        if !target.detect_path.exists() || target.agent_key.is_empty() {
189            continue;
190        }
191        let mode = recommend_hook_mode(&target.agent_key);
192        crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
193    }
194
195    // Step 5: API Proxy (opt-in)
196    terminal_ui::print_step_header(5, 11, "API Proxy (optional)");
197    {
198        let mut cfg = crate::core::config::Config::load();
199        let proxy_port = crate::proxy_setup::default_port();
200
201        match cfg.proxy_enabled {
202            Some(true) => {
203                crate::proxy_autostart::install(proxy_port, false);
204                std::thread::sleep(std::time::Duration::from_millis(500));
205                crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
206                terminal_ui::print_status_ok("Proxy active (opted in)");
207            }
208            Some(false) => {
209                terminal_ui::print_status_skip(
210                    "Proxy disabled (run `lean-ctx proxy enable` to change)",
211                );
212            }
213            None => {
214                println!(
215                    "  \x1b[2mThe API proxy routes LLM requests through lean-ctx for additional\x1b[0m"
216                );
217                println!(
218                    "  \x1b[2mtool-result compression and precise token analytics in the dashboard.\x1b[0m"
219                );
220                println!();
221                println!(
222                    "  \x1b[2mWithout it: MCP tools, shell hooks, gain tracking, and memory\x1b[0m"
223                );
224                println!(
225                    "  \x1b[2mall work normally. The proxy adds ~5-15% extra savings on top.\x1b[0m"
226                );
227                println!();
228                print!("  Enable the API proxy? [y/N] ");
229                let _ = std::io::Write::flush(&mut std::io::stdout());
230                let mut input = String::new();
231                let _ = std::io::stdin().read_line(&mut input);
232                let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
233                cfg.proxy_enabled = Some(answer);
234                let _ = cfg.save();
235                if answer {
236                    crate::proxy_autostart::install(proxy_port, false);
237                    std::thread::sleep(std::time::Duration::from_millis(500));
238                    crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
239                    terminal_ui::print_status_new("Proxy enabled");
240                } else {
241                    terminal_ui::print_status_skip(
242                        "Proxy skipped (run `lean-ctx proxy enable` anytime)",
243                    );
244                }
245            }
246        }
247    }
248
249    // Step 6: SKILL.md installation
250    terminal_ui::print_step_header(6, 11, "Skill Files");
251    let skill_result = install_skill_files(&home);
252    for (name, installed) in &skill_result {
253        if *installed {
254            terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mSKILL.md installed\x1b[0m"));
255        } else {
256            terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"));
257        }
258    }
259    if skill_result.is_empty() {
260        terminal_ui::print_status_skip("No skill directories to install");
261    }
262
263    // Step 7: Data directory + diagnostics
264    terminal_ui::print_step_header(7, 11, "Environment Check");
265    let lean_dir = crate::core::data_dir::lean_ctx_data_dir()
266        .unwrap_or_else(|_| home.join(".config/lean-ctx"));
267    if lean_dir.exists() {
268        terminal_ui::print_status_ok(&format!("{} ready", lean_dir.display()));
269    } else {
270        let _ = std::fs::create_dir_all(&lean_dir);
271        terminal_ui::print_status_new(&format!("Created {}", lean_dir.display()));
272    }
273    if let Some(tokens) = crate::core::data_dir::migrate_if_split() {
274        terminal_ui::print_status_new(&format!(
275            "Migrated stats from split data dir ({tokens} tokens recovered)"
276        ));
277    }
278    crate::doctor::run_compact();
279
280    // Step 8: Data sharing
281    terminal_ui::print_step_header(8, 11, "Help Improve lean-ctx");
282    println!("  Share anonymous compression stats to make lean-ctx better.");
283    println!("  \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
284    println!();
285    print!("  Enable anonymous data sharing? \x1b[1m[y/N]\x1b[0m ");
286    use std::io::Write;
287    std::io::stdout().flush().ok();
288
289    let mut input = String::new();
290    let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
291        let answer = input.trim().to_lowercase();
292        answer == "y" || answer == "yes"
293    } else {
294        false
295    };
296
297    if contribute {
298        let config_dir = crate::core::data_dir::lean_ctx_data_dir()
299            .unwrap_or_else(|_| home.join(".config/lean-ctx"));
300        let _ = std::fs::create_dir_all(&config_dir);
301        let config_path = config_dir.join("config.toml");
302        let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
303        if !config_content.contains("[cloud]") {
304            if !config_content.is_empty() && !config_content.ends_with('\n') {
305                config_content.push('\n');
306            }
307            config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
308            let _ = std::fs::write(&config_path, config_content);
309        }
310        terminal_ui::print_status_ok("Enabled — thank you!");
311    } else {
312        terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
313    }
314
315    // Step 9: Auto-Update opt-in
316    terminal_ui::print_step_header(9, 11, "Auto-Updates");
317    println!("  Keep lean-ctx up to date automatically.");
318    println!("  \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
319    println!(
320        "  \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
321    );
322    println!();
323    print!("  Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
324    std::io::stdout().flush().ok();
325
326    let mut auto_input = String::new();
327    let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
328        let answer = auto_input.trim().to_lowercase();
329        answer == "y" || answer == "yes"
330    } else {
331        false
332    };
333
334    if auto_update {
335        let cfg = crate::core::config::Config::load();
336        let hours = cfg.updates.check_interval_hours;
337        match crate::core::update_scheduler::install_schedule(hours) {
338            Ok(info) => {
339                crate::core::update_scheduler::set_auto_update(true, false, hours);
340                terminal_ui::print_status_ok(&format!("Enabled — {info}"));
341            }
342            Err(e) => {
343                terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
344                terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
345            }
346        }
347    } else {
348        crate::core::update_scheduler::set_auto_update(false, false, 6);
349        terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
350    }
351
352    // Step 10: Premium Features Configuration
353    terminal_ui::print_step_header(10, 11, "Premium Features");
354    configure_premium_features(&home);
355
356    // Step 11: Code Intelligence — build graph in background
357    terminal_ui::print_step_header(11, 11, "Code Intelligence");
358    let cwd = std::env::current_dir().ok();
359    let cwd_is_home = cwd
360        .as_ref()
361        .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
362    if cwd_is_home {
363        terminal_ui::print_status_warn(
364            "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
365        );
366        println!();
367        println!("  \x1b[1mSet a default project root to avoid this:\x1b[0m");
368        println!("  \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
369        print!("  \x1b[1m>\x1b[0m ");
370        use std::io::Write;
371        std::io::stdout().flush().ok();
372        let mut root_input = String::new();
373        if std::io::stdin().read_line(&mut root_input).is_ok() {
374            let root_trimmed = root_input.trim();
375            if root_trimmed.is_empty() {
376                terminal_ui::print_status_skip("No project root set. Set later: lean-ctx config set project_root /path/to/project");
377            } else {
378                let root_path = std::path::Path::new(root_trimmed);
379                if root_path.exists() && root_path.is_dir() {
380                    let config_path = crate::core::data_dir::lean_ctx_data_dir()
381                        .unwrap_or_else(|_| home.join(".config/lean-ctx"))
382                        .join("config.toml");
383                    let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
384                    if content.contains("project_root") {
385                        if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
386                            content = re
387                                .replace(&content, &format!("project_root = \"{root_trimmed}\""))
388                                .to_string();
389                        }
390                    } else {
391                        if !content.is_empty() && !content.ends_with('\n') {
392                            content.push('\n');
393                        }
394                        content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
395                    }
396                    let _ = std::fs::write(&config_path, &content);
397                    terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
398                    if root_path.join(".git").exists()
399                        || root_path.join("Cargo.toml").exists()
400                        || root_path.join("package.json").exists()
401                    {
402                        spawn_index_build_background(root_path);
403                        terminal_ui::print_status_ok("Graph build started (background)");
404                    }
405                } else {
406                    terminal_ui::print_status_warn(&format!(
407                        "Path not found: {root_trimmed} — skipped"
408                    ));
409                }
410            }
411        }
412    } else {
413        let is_project = cwd.as_ref().is_some_and(|d| {
414            d.join(".git").exists()
415                || d.join("Cargo.toml").exists()
416                || d.join("package.json").exists()
417                || d.join("go.mod").exists()
418        });
419        if is_project {
420            println!("  \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
421            println!("  \x1b[2mand smart search fusion in the background...\x1b[0m");
422            if let Some(ref root) = cwd {
423                spawn_index_build_background(root);
424            }
425            terminal_ui::print_status_ok("Graph build started (background)");
426        } else {
427            println!(
428                "  \x1b[2mRun `lean-ctx impact build` inside any git project to enable\x1b[0m"
429            );
430            println!(
431                "  \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
432            );
433        }
434    }
435    println!();
436
437    // Auto-approve transparency banner
438    {
439        let tools = crate::core::editor_registry::writers::auto_approve_tools();
440        println!();
441        println!(
442            "  \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
443            tools.len()
444        );
445        for chunk in tools.chunks(6) {
446            let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
447            println!("    {}", names.join(", "));
448        }
449        println!("  \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
450    }
451
452    // Summary
453    println!();
454    println!(
455        "  \x1b[1;32m✓ Setup complete!\x1b[0m  \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
456        newly_configured.len(),
457        already_configured.len(),
458        not_installed.len()
459    );
460
461    if !errors.is_empty() {
462        println!(
463            "  \x1b[33m⚠ {} error{}: {}\x1b[0m",
464            errors.len(),
465            if errors.len() == 1 { "" } else { "s" },
466            errors.join(", ")
467        );
468    }
469
470    // Next steps
471    let shell = std::env::var("SHELL").unwrap_or_default();
472    let source_cmd = if shell.contains("zsh") {
473        "source ~/.zshrc"
474    } else if shell.contains("fish") {
475        "source ~/.config/fish/config.fish"
476    } else if shell.contains("bash") {
477        "source ~/.bashrc"
478    } else {
479        "Restart your shell"
480    };
481
482    let dim = "\x1b[2m";
483    let bold = "\x1b[1m";
484    let cyan = "\x1b[36m";
485    let yellow = "\x1b[33m";
486    let rst = "\x1b[0m";
487
488    println!();
489    println!("  {bold}Next steps:{rst}");
490    println!();
491    println!("  {cyan}1.{rst} Reload your shell:");
492    println!("     {bold}{source_cmd}{rst}");
493    println!();
494
495    let mut tools_to_restart: Vec<String> = newly_configured
496        .iter()
497        .map(std::string::ToString::to_string)
498        .collect();
499    for name in rules_result
500        .injected
501        .iter()
502        .chain(rules_result.updated.iter())
503    {
504        if !tools_to_restart.iter().any(|t| t == name) {
505            tools_to_restart.push(name.clone());
506        }
507    }
508
509    if !tools_to_restart.is_empty() {
510        println!("  {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
511        println!("     {bold}{}{rst}", tools_to_restart.join(", "));
512        println!(
513            "     {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
514        );
515        println!("     {dim}Close and re-open the application completely.{rst}");
516    } else if !already_configured.is_empty() {
517        println!(
518            "  {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
519        );
520    }
521
522    println!();
523    println!(
524        "  {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
525    );
526    println!("  {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
527
528    // Logo + commands
529    println!();
530    terminal_ui::print_logo_animated();
531    terminal_ui::print_command_box();
532}
533
534#[derive(Debug, Clone, Copy, Default)]
535pub struct SetupOptions {
536    pub non_interactive: bool,
537    pub yes: bool,
538    pub fix: bool,
539    pub json: bool,
540    pub no_auto_approve: bool,
541    pub skip_proxy: bool,
542}
543
544pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
545    let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
546    let started_at = Utc::now();
547    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
548    let binary = resolve_portable_binary();
549    let home_str = home.to_string_lossy().to_string();
550
551    let mut steps: Vec<SetupStepReport> = Vec::new();
552
553    // Step: Shell Hook
554    let mut shell_step = SetupStepReport {
555        name: "shell_hook".to_string(),
556        ok: true,
557        items: Vec::new(),
558        warnings: Vec::new(),
559        errors: Vec::new(),
560    };
561    if !opts.non_interactive || opts.yes {
562        if opts.json {
563            crate::cli::cmd_init_quiet(&["--global".to_string()]);
564        } else {
565            crate::cli::cmd_init(&["--global".to_string()]);
566        }
567        crate::shell_hook::install_all(opts.json);
568        #[cfg(not(windows))]
569        {
570            let hook_content = crate::cli::generate_hook_posix(&binary);
571            if crate::shell::is_container() {
572                crate::cli::write_env_sh_for_containers(&hook_content);
573                shell_step.items.push(SetupItem {
574                    name: "env_sh".to_string(),
575                    status: "created".to_string(),
576                    path: Some("~/.lean-ctx/env.sh".to_string()),
577                    note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
578                });
579            } else {
580                shell_step.items.push(SetupItem {
581                    name: "env_sh".to_string(),
582                    status: "skipped".to_string(),
583                    path: None,
584                    note: Some("not a container environment".to_string()),
585                });
586            }
587        }
588        shell_step.items.push(SetupItem {
589            name: "init --global".to_string(),
590            status: "ran".to_string(),
591            path: None,
592            note: None,
593        });
594        shell_step.items.push(SetupItem {
595            name: "universal_shell_hook".to_string(),
596            status: "installed".to_string(),
597            path: None,
598            note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
599        });
600    } else {
601        shell_step
602            .warnings
603            .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
604        shell_step.ok = false;
605        shell_step.items.push(SetupItem {
606            name: "init --global".to_string(),
607            status: "skipped".to_string(),
608            path: None,
609            note: Some("requires --yes in --non-interactive mode".to_string()),
610        });
611    }
612    steps.push(shell_step);
613
614    // Step: Daemon (optional acceleration for CLI routing)
615    let mut daemon_step = SetupStepReport {
616        name: "daemon".to_string(),
617        ok: true,
618        items: Vec::new(),
619        warnings: Vec::new(),
620        errors: Vec::new(),
621    };
622    {
623        let was_running = crate::daemon::is_daemon_running();
624        if was_running {
625            let _ = crate::daemon::stop_daemon();
626            std::thread::sleep(std::time::Duration::from_millis(500));
627        }
628        match crate::daemon::start_daemon(&[]) {
629            Ok(()) => {
630                let action = if was_running { "restarted" } else { "started" };
631                daemon_step.items.push(SetupItem {
632                    name: "serve --daemon".to_string(),
633                    status: action.to_string(),
634                    path: Some(crate::daemon::daemon_addr().display()),
635                    note: Some("CLI commands can route via IPC when running".to_string()),
636                });
637            }
638            Err(e) => {
639                daemon_step
640                    .warnings
641                    .push(format!("daemon start failed (non-fatal): {e}"));
642                daemon_step.items.push(SetupItem {
643                    name: "serve --daemon".to_string(),
644                    status: "skipped".to_string(),
645                    path: None,
646                    note: Some(format!("optional — {e}")),
647                });
648            }
649        }
650    }
651    steps.push(daemon_step);
652
653    // Step: Editor MCP config
654    let mut editor_step = SetupStepReport {
655        name: "editors".to_string(),
656        ok: true,
657        items: Vec::new(),
658        warnings: Vec::new(),
659        errors: Vec::new(),
660    };
661
662    let targets = crate::core::editor_registry::build_targets(&home);
663    for target in &targets {
664        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
665        if !target.detect_path.exists() {
666            editor_step.items.push(SetupItem {
667                name: target.name.to_string(),
668                status: "not_detected".to_string(),
669                path: Some(short_path),
670                note: None,
671            });
672            continue;
673        }
674
675        let mode = if target.agent_key.is_empty() {
676            HookMode::Mcp
677        } else {
678            recommend_hook_mode(&target.agent_key)
679        };
680
681        let res = crate::core::editor_registry::write_config_with_options(
682            target,
683            &binary,
684            WriteOptions {
685                overwrite_invalid: opts.fix,
686            },
687        );
688        match res {
689            Ok(w) => {
690                let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
691                    .into_iter()
692                    .flatten()
693                    .collect();
694                editor_step.items.push(SetupItem {
695                    name: target.name.to_string(),
696                    status: match w.action {
697                        WriteAction::Created => "created".to_string(),
698                        WriteAction::Updated => "updated".to_string(),
699                        WriteAction::Already => "already".to_string(),
700                    },
701                    path: Some(short_path),
702                    note: Some(note_parts.join("; ")),
703                });
704            }
705            Err(e) => {
706                editor_step.ok = false;
707                editor_step.items.push(SetupItem {
708                    name: target.name.to_string(),
709                    status: "error".to_string(),
710                    path: Some(short_path),
711                    note: Some(e),
712                });
713            }
714        }
715    }
716    steps.push(editor_step);
717
718    // Step: Agent rules
719    let mut rules_step = SetupStepReport {
720        name: "agent_rules".to_string(),
721        ok: true,
722        items: Vec::new(),
723        warnings: Vec::new(),
724        errors: Vec::new(),
725    };
726    let rules_result = crate::rules_inject::inject_all_rules(&home);
727    for n in rules_result.injected {
728        rules_step.items.push(SetupItem {
729            name: n,
730            status: "injected".to_string(),
731            path: None,
732            note: None,
733        });
734    }
735    for n in rules_result.updated {
736        rules_step.items.push(SetupItem {
737            name: n,
738            status: "updated".to_string(),
739            path: None,
740            note: None,
741        });
742    }
743    for n in rules_result.already {
744        rules_step.items.push(SetupItem {
745            name: n,
746            status: "already".to_string(),
747            path: None,
748            note: None,
749        });
750    }
751    for e in rules_result.errors {
752        rules_step.ok = false;
753        rules_step.errors.push(e);
754    }
755    steps.push(rules_step);
756
757    // Step: Skill files
758    let mut skill_step = SetupStepReport {
759        name: "skill_files".to_string(),
760        ok: true,
761        items: Vec::new(),
762        warnings: Vec::new(),
763        errors: Vec::new(),
764    };
765    let skill_results = crate::rules_inject::install_all_skills(&home);
766    for (name, is_new) in &skill_results {
767        skill_step.items.push(SetupItem {
768            name: name.clone(),
769            status: if *is_new { "installed" } else { "already" }.to_string(),
770            path: None,
771            note: Some("SKILL.md".to_string()),
772        });
773    }
774    if !skill_step.items.is_empty() {
775        steps.push(skill_step);
776    }
777
778    // Step: Agent-specific hooks (all detected agents)
779    let mut hooks_step = SetupStepReport {
780        name: "agent_hooks".to_string(),
781        ok: true,
782        items: Vec::new(),
783        warnings: Vec::new(),
784        errors: Vec::new(),
785    };
786    for target in &targets {
787        if !target.detect_path.exists() || target.agent_key.is_empty() {
788            continue;
789        }
790        let mode = recommend_hook_mode(&target.agent_key);
791        crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
792        let mcp_note = match configure_agent_mcp(&target.agent_key) {
793            Ok(()) => "; MCP config updated".to_string(),
794            Err(e) => format!("; MCP config skipped: {e}"),
795        };
796        hooks_step.items.push(SetupItem {
797            name: format!("{} hooks", target.name),
798            status: "installed".to_string(),
799            path: Some(target.detect_path.to_string_lossy().to_string()),
800            note: Some(format!(
801                "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
802            )),
803        });
804    }
805    if !hooks_step.items.is_empty() {
806        steps.push(hooks_step);
807    }
808
809    // Step: Proxy autostart + env vars (respects opt-in)
810    let mut proxy_step = SetupStepReport {
811        name: "proxy".to_string(),
812        ok: true,
813        items: Vec::new(),
814        warnings: Vec::new(),
815        errors: Vec::new(),
816    };
817    if opts.skip_proxy {
818        proxy_step.items.push(SetupItem {
819            name: "proxy".to_string(),
820            status: "skipped".to_string(),
821            path: None,
822            note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
823        });
824    } else {
825        let proxy_port = crate::proxy_setup::default_port();
826        crate::proxy_autostart::install(proxy_port, true);
827        std::thread::sleep(std::time::Duration::from_millis(500));
828        crate::proxy_setup::install_proxy_env(&home, proxy_port, opts.json);
829        proxy_step.items.push(SetupItem {
830            name: "proxy_autostart".to_string(),
831            status: "installed".to_string(),
832            path: None,
833            note: Some("LaunchAgent/systemd auto-start on login".to_string()),
834        });
835        proxy_step.items.push(SetupItem {
836            name: "proxy_env".to_string(),
837            status: "configured".to_string(),
838            path: None,
839            note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
840        });
841    }
842    steps.push(proxy_step);
843
844    // Step: Environment / doctor (compact)
845    let mut env_step = SetupStepReport {
846        name: "doctor_compact".to_string(),
847        ok: true,
848        items: Vec::new(),
849        warnings: Vec::new(),
850        errors: Vec::new(),
851    };
852    let (passed, total) = crate::doctor::compact_score();
853    env_step.items.push(SetupItem {
854        name: "doctor".to_string(),
855        status: format!("{passed}/{total}"),
856        path: None,
857        note: None,
858    });
859    if passed != total {
860        env_step.warnings.push(format!(
861            "doctor compact not fully passing: {passed}/{total}"
862        ));
863    }
864    steps.push(env_step);
865
866    // Project root validation: warn if no root is configured and cwd is broad
867    {
868        let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
869            .ok()
870            .is_some_and(|v| !v.is_empty());
871        let cfg = crate::core::config::Config::load();
872        let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
873        if !has_env_root && !has_cfg_root {
874            if let Ok(cwd) = std::env::current_dir() {
875                let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
876                if is_home {
877                    let mut root_step = SetupStepReport {
878                        name: "project_root".to_string(),
879                        ok: true,
880                        items: Vec::new(),
881                        warnings: vec![
882                            "No project_root configured. Running from $HOME can cause excessive scanning. \
883                             Set via: lean-ctx config set project_root /path/to/project".to_string()
884                        ],
885                        errors: Vec::new(),
886                    };
887                    root_step.items.push(SetupItem {
888                        name: "project_root".to_string(),
889                        status: "unconfigured".to_string(),
890                        path: None,
891                        note: Some(
892                            "Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml"
893                                .to_string(),
894                        ),
895                    });
896                    steps.push(root_step);
897                }
898            }
899        }
900    }
901
902    // Auto-build property graph if inside any recognized project
903    if let Ok(cwd) = std::env::current_dir() {
904        let is_project = cwd.join(".git").exists()
905            || cwd.join("Cargo.toml").exists()
906            || cwd.join("package.json").exists()
907            || cwd.join("go.mod").exists();
908        if is_project {
909            spawn_index_build_background(&cwd);
910        }
911    }
912
913    let finished_at = Utc::now();
914    let success = steps.iter().all(|s| s.ok);
915    let report = SetupReport {
916        schema_version: 1,
917        started_at,
918        finished_at,
919        success,
920        platform: PlatformInfo {
921            os: std::env::consts::OS.to_string(),
922            arch: std::env::consts::ARCH.to_string(),
923        },
924        steps,
925        warnings: Vec::new(),
926        errors: Vec::new(),
927    };
928
929    let path = SetupReport::default_path()?;
930    let mut content =
931        serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
932    content.push('\n');
933    crate::config_io::write_atomic(&path, &content)?;
934
935    Ok(report)
936}
937
938fn spawn_index_build_background(root: &std::path::Path) {
939    if std::env::var("LEAN_CTX_DISABLED").is_ok()
940        || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1")
941    {
942        return;
943    }
944    let root_str = crate::core::graph_index::normalize_project_root(&root.to_string_lossy());
945    if !crate::core::graph_index::is_safe_scan_root_public(&root_str) {
946        tracing::info!("[setup: skipping background graph build for unsafe root {root_str}]");
947        return;
948    }
949
950    let binary = resolve_portable_binary();
951
952    #[cfg(unix)]
953    {
954        let mut cmd = std::process::Command::new("nice");
955        cmd.args(["-n", "19"]);
956        if which_ionice_available() {
957            cmd.arg("ionice").args(["-c", "3"]);
958        }
959        cmd.arg(&binary)
960            .args(["index", "build-graph", "--root"])
961            .arg(root)
962            .stdout(std::process::Stdio::null())
963            .stderr(std::process::Stdio::null())
964            .stdin(std::process::Stdio::null());
965        let _ = cmd.spawn();
966    }
967
968    #[cfg(windows)]
969    {
970        use std::os::windows::process::CommandExt;
971        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
972        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
973        let _ = std::process::Command::new(&binary)
974            .args(["index", "build-graph", "--root"])
975            .arg(root)
976            .stdout(std::process::Stdio::null())
977            .stderr(std::process::Stdio::null())
978            .stdin(std::process::Stdio::null())
979            .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
980            .spawn();
981    }
982}
983
984#[cfg(unix)]
985fn which_ionice_available() -> bool {
986    std::process::Command::new("ionice")
987        .arg("--version")
988        .stdout(std::process::Stdio::null())
989        .stderr(std::process::Stdio::null())
990        .status()
991        .is_ok()
992}
993
994/// Result of setting up a single agent with all steps.
995#[derive(Debug, Default)]
996pub struct AgentSetupResult {
997    pub mcp_ok: bool,
998    pub rules: crate::rules_inject::InjectResult,
999    pub skill_installed: bool,
1000    pub errors: Vec<String>,
1001}
1002
1003/// Complete per-agent setup: MCP config + global rules + skill + hook.
1004/// Single source of truth — called by both `init --agent` and `setup`.
1005pub fn setup_single_agent(
1006    agent_name: &str,
1007    global: bool,
1008    mode: crate::hooks::HookMode,
1009) -> AgentSetupResult {
1010    let home = dirs::home_dir().unwrap_or_default();
1011    let mut result = AgentSetupResult::default();
1012
1013    crate::hooks::install_agent_hook_with_mode(agent_name, global, mode);
1014
1015    match configure_agent_mcp(agent_name) {
1016        Ok(()) => result.mcp_ok = true,
1017        Err(e) => result.errors.push(format!("MCP config: {e}")),
1018    }
1019
1020    result.rules = crate::rules_inject::inject_rules_for_agent(&home, agent_name);
1021
1022    if let Ok(path) = crate::rules_inject::install_skill_for_agent(&home, agent_name) {
1023        result.skill_installed = path.exists();
1024    }
1025
1026    result
1027}
1028
1029pub fn configure_agent_mcp(agent: &str) -> Result<(), String> {
1030    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
1031    let binary = resolve_portable_binary();
1032
1033    let targets = agent_mcp_targets(agent, &home)?;
1034
1035    let mut errors = Vec::new();
1036    for t in &targets {
1037        if let Err(e) = crate::core::editor_registry::write_config_with_options(
1038            t,
1039            &binary,
1040            WriteOptions {
1041                overwrite_invalid: true,
1042            },
1043        ) {
1044            eprintln!(
1045                "\x1b[33m⚠\x1b[0m  Could not configure {}: {}",
1046                t.config_path.display(),
1047                e
1048            );
1049            errors.push(e);
1050        }
1051    }
1052
1053    if agent == "kiro" {
1054        install_kiro_steering(&home);
1055    }
1056
1057    if agent == "vscode" || agent == "copilot" {
1058        if let Err(e) = crate::core::editor_registry::plan_mode::write_vscode_plan_settings() {
1059            eprintln!("\x1b[33m⚠\x1b[0m  VS Code plan mode: {e}");
1060        }
1061    }
1062    if agent == "claude" || agent == "claude-code" {
1063        if let Err(e) =
1064            crate::core::editor_registry::plan_mode::write_claude_code_plan_permissions()
1065        {
1066            eprintln!("\x1b[33m⚠\x1b[0m  Claude Code plan mode: {e}");
1067        }
1068    }
1069
1070    if errors.is_empty() {
1071        Ok(())
1072    } else {
1073        Err(format!(
1074            "{} config(s) could not be written. See warnings above.",
1075            errors.len()
1076        ))
1077    }
1078}
1079
1080fn agent_mcp_targets(agent: &str, home: &std::path::Path) -> Result<Vec<EditorTarget>, String> {
1081    let mut targets = Vec::<EditorTarget>::new();
1082
1083    let push = |targets: &mut Vec<EditorTarget>,
1084                name: &'static str,
1085                config_path: PathBuf,
1086                config_type: ConfigType| {
1087        targets.push(EditorTarget {
1088            name,
1089            agent_key: agent.to_string(),
1090            detect_path: PathBuf::from("/nonexistent"), // not used in direct agent config
1091            config_path,
1092            config_type,
1093        });
1094    };
1095
1096    let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
1097
1098    match agent {
1099        "cursor" => push(
1100            &mut targets,
1101            "Cursor",
1102            home.join(".cursor/mcp.json"),
1103            ConfigType::McpJson,
1104        ),
1105        "claude" | "claude-code" => push(
1106            &mut targets,
1107            "Claude Code",
1108            crate::core::editor_registry::claude_mcp_json_path(home),
1109            ConfigType::McpJson,
1110        ),
1111        "windsurf" => push(
1112            &mut targets,
1113            "Windsurf",
1114            home.join(".codeium/windsurf/mcp_config.json"),
1115            ConfigType::McpJson,
1116        ),
1117        "codex" => {
1118            let codex_dir =
1119                crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
1120            push(
1121                &mut targets,
1122                "Codex CLI",
1123                codex_dir.join("config.toml"),
1124                ConfigType::Codex,
1125            );
1126        }
1127        "gemini" => {
1128            push(
1129                &mut targets,
1130                "Gemini CLI",
1131                home.join(".gemini/settings.json"),
1132                ConfigType::GeminiSettings,
1133            );
1134            push(
1135                &mut targets,
1136                "Antigravity",
1137                home.join(".gemini/antigravity/mcp_config.json"),
1138                ConfigType::McpJson,
1139            );
1140        }
1141        "antigravity" => push(
1142            &mut targets,
1143            "Antigravity",
1144            home.join(".gemini/antigravity/mcp_config.json"),
1145            ConfigType::McpJson,
1146        ),
1147        "copilot" => push(
1148            &mut targets,
1149            "Copilot CLI",
1150            home.join(".copilot/mcp-config.json"),
1151            ConfigType::CopilotCli,
1152        ),
1153        "crush" => push(
1154            &mut targets,
1155            "Crush",
1156            home.join(".config/crush/crush.json"),
1157            ConfigType::Crush,
1158        ),
1159        "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
1160        "qoder" => {
1161            for path in crate::core::editor_registry::qoder_all_mcp_paths(home) {
1162                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
1163            }
1164        }
1165        "qoderwork" => push(
1166            &mut targets,
1167            "QoderWork",
1168            crate::core::editor_registry::qoderwork_mcp_path(home),
1169            ConfigType::McpJson,
1170        ),
1171        "cline" => push(
1172            &mut targets,
1173            "Cline",
1174            crate::core::editor_registry::cline_mcp_path(),
1175            ConfigType::McpJson,
1176        ),
1177        "roo" => push(
1178            &mut targets,
1179            "Roo Code",
1180            crate::core::editor_registry::roo_mcp_path(),
1181            ConfigType::McpJson,
1182        ),
1183        "kiro" => push(
1184            &mut targets,
1185            "AWS Kiro",
1186            home.join(".kiro/settings/mcp.json"),
1187            ConfigType::McpJson,
1188        ),
1189        "verdent" => push(
1190            &mut targets,
1191            "Verdent",
1192            home.join(".verdent/mcp.json"),
1193            ConfigType::McpJson,
1194        ),
1195        "jetbrains" | "amp" => {
1196            // Handled by dedicated install hooks (servers[] array / amp.mcpServers)
1197        }
1198        "qwen" => push(
1199            &mut targets,
1200            "Qwen Code",
1201            home.join(".qwen/settings.json"),
1202            ConfigType::McpJson,
1203        ),
1204        "trae" => push(
1205            &mut targets,
1206            "Trae",
1207            home.join(".trae/mcp.json"),
1208            ConfigType::McpJson,
1209        ),
1210        "amazonq" => push(
1211            &mut targets,
1212            "Amazon Q Developer",
1213            home.join(".aws/amazonq/default.json"),
1214            ConfigType::McpJson,
1215        ),
1216        "opencode" => {
1217            #[cfg(windows)]
1218            let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
1219                std::path::PathBuf::from(appdata)
1220                    .join("opencode")
1221                    .join("opencode.json")
1222            } else {
1223                home.join(".config/opencode/opencode.json")
1224            };
1225            #[cfg(not(windows))]
1226            let opencode_path = home.join(".config/opencode/opencode.json");
1227            push(
1228                &mut targets,
1229                "OpenCode",
1230                opencode_path,
1231                ConfigType::OpenCode,
1232            );
1233        }
1234        "hermes" => push(
1235            &mut targets,
1236            "Hermes Agent",
1237            home.join(".hermes/config.yaml"),
1238            ConfigType::HermesYaml,
1239        ),
1240        "vscode" => push(
1241            &mut targets,
1242            "VS Code",
1243            crate::core::editor_registry::vscode_mcp_path(),
1244            ConfigType::VsCodeMcp,
1245        ),
1246        "zed" => push(
1247            &mut targets,
1248            "Zed",
1249            crate::core::editor_registry::zed_settings_path(home),
1250            ConfigType::Zed,
1251        ),
1252        "aider" => push(
1253            &mut targets,
1254            "Aider",
1255            home.join(".aider/mcp.json"),
1256            ConfigType::McpJson,
1257        ),
1258        "continue" => push(
1259            &mut targets,
1260            "Continue",
1261            home.join(".continue/mcp.json"),
1262            ConfigType::McpJson,
1263        ),
1264        "neovim" => push(
1265            &mut targets,
1266            "Neovim (mcphub.nvim)",
1267            home.join(".config/mcphub/servers.json"),
1268            ConfigType::McpJson,
1269        ),
1270        "emacs" => push(
1271            &mut targets,
1272            "Emacs (mcp.el)",
1273            home.join(".emacs.d/mcp.json"),
1274            ConfigType::McpJson,
1275        ),
1276        "sublime" => push(
1277            &mut targets,
1278            "Sublime Text",
1279            home.join(".config/sublime-text/mcp.json"),
1280            ConfigType::McpJson,
1281        ),
1282        _ => {
1283            return Err(format!("Unknown agent '{agent}'"));
1284        }
1285    }
1286
1287    Ok(targets)
1288}
1289
1290pub fn disable_agent_mcp(agent: &str, overwrite_invalid: bool) -> Result<(), String> {
1291    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
1292
1293    let mut targets = Vec::<EditorTarget>::new();
1294
1295    let push = |targets: &mut Vec<EditorTarget>,
1296                name: &'static str,
1297                config_path: PathBuf,
1298                config_type: ConfigType| {
1299        targets.push(EditorTarget {
1300            name,
1301            agent_key: agent.to_string(),
1302            detect_path: PathBuf::from("/nonexistent"),
1303            config_path,
1304            config_type,
1305        });
1306    };
1307
1308    let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
1309
1310    match agent {
1311        "cursor" => push(
1312            &mut targets,
1313            "Cursor",
1314            home.join(".cursor/mcp.json"),
1315            ConfigType::McpJson,
1316        ),
1317        "claude" | "claude-code" => push(
1318            &mut targets,
1319            "Claude Code",
1320            crate::core::editor_registry::claude_mcp_json_path(&home),
1321            ConfigType::McpJson,
1322        ),
1323        "windsurf" => push(
1324            &mut targets,
1325            "Windsurf",
1326            home.join(".codeium/windsurf/mcp_config.json"),
1327            ConfigType::McpJson,
1328        ),
1329        "codex" => {
1330            let codex_dir =
1331                crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
1332            push(
1333                &mut targets,
1334                "Codex CLI",
1335                codex_dir.join("config.toml"),
1336                ConfigType::Codex,
1337            );
1338        }
1339        "gemini" => {
1340            push(
1341                &mut targets,
1342                "Gemini CLI",
1343                home.join(".gemini/settings.json"),
1344                ConfigType::GeminiSettings,
1345            );
1346            push(
1347                &mut targets,
1348                "Antigravity",
1349                home.join(".gemini/antigravity/mcp_config.json"),
1350                ConfigType::McpJson,
1351            );
1352        }
1353        "antigravity" => push(
1354            &mut targets,
1355            "Antigravity",
1356            home.join(".gemini/antigravity/mcp_config.json"),
1357            ConfigType::McpJson,
1358        ),
1359        "copilot" => push(
1360            &mut targets,
1361            "Copilot CLI",
1362            home.join(".copilot/mcp-config.json"),
1363            ConfigType::CopilotCli,
1364        ),
1365        "crush" => push(
1366            &mut targets,
1367            "Crush",
1368            home.join(".config/crush/crush.json"),
1369            ConfigType::Crush,
1370        ),
1371        "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
1372        "qoder" => {
1373            for path in crate::core::editor_registry::qoder_all_mcp_paths(&home) {
1374                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
1375            }
1376        }
1377        "qoderwork" => push(
1378            &mut targets,
1379            "QoderWork",
1380            crate::core::editor_registry::qoderwork_mcp_path(&home),
1381            ConfigType::McpJson,
1382        ),
1383        "cline" => push(
1384            &mut targets,
1385            "Cline",
1386            crate::core::editor_registry::cline_mcp_path(),
1387            ConfigType::McpJson,
1388        ),
1389        "roo" => push(
1390            &mut targets,
1391            "Roo Code",
1392            crate::core::editor_registry::roo_mcp_path(),
1393            ConfigType::McpJson,
1394        ),
1395        "kiro" => push(
1396            &mut targets,
1397            "AWS Kiro",
1398            home.join(".kiro/settings/mcp.json"),
1399            ConfigType::McpJson,
1400        ),
1401        "verdent" => push(
1402            &mut targets,
1403            "Verdent",
1404            home.join(".verdent/mcp.json"),
1405            ConfigType::McpJson,
1406        ),
1407        "jetbrains" | "amp" => {
1408            // Not supported for disable via this helper.
1409        }
1410        "qwen" => push(
1411            &mut targets,
1412            "Qwen Code",
1413            home.join(".qwen/settings.json"),
1414            ConfigType::McpJson,
1415        ),
1416        "trae" => push(
1417            &mut targets,
1418            "Trae",
1419            home.join(".trae/mcp.json"),
1420            ConfigType::McpJson,
1421        ),
1422        "amazonq" => push(
1423            &mut targets,
1424            "Amazon Q Developer",
1425            home.join(".aws/amazonq/default.json"),
1426            ConfigType::McpJson,
1427        ),
1428        "opencode" => {
1429            #[cfg(windows)]
1430            let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
1431                std::path::PathBuf::from(appdata)
1432                    .join("opencode")
1433                    .join("opencode.json")
1434            } else {
1435                home.join(".config/opencode/opencode.json")
1436            };
1437            #[cfg(not(windows))]
1438            let opencode_path = home.join(".config/opencode/opencode.json");
1439            push(
1440                &mut targets,
1441                "OpenCode",
1442                opencode_path,
1443                ConfigType::OpenCode,
1444            );
1445        }
1446        "hermes" => push(
1447            &mut targets,
1448            "Hermes Agent",
1449            home.join(".hermes/config.yaml"),
1450            ConfigType::HermesYaml,
1451        ),
1452        "vscode" => push(
1453            &mut targets,
1454            "VS Code",
1455            crate::core::editor_registry::vscode_mcp_path(),
1456            ConfigType::VsCodeMcp,
1457        ),
1458        "zed" => push(
1459            &mut targets,
1460            "Zed",
1461            crate::core::editor_registry::zed_settings_path(&home),
1462            ConfigType::Zed,
1463        ),
1464        "aider" => push(
1465            &mut targets,
1466            "Aider",
1467            home.join(".aider/mcp.json"),
1468            ConfigType::McpJson,
1469        ),
1470        "continue" => push(
1471            &mut targets,
1472            "Continue",
1473            home.join(".continue/mcp.json"),
1474            ConfigType::McpJson,
1475        ),
1476        "neovim" => push(
1477            &mut targets,
1478            "Neovim (mcphub.nvim)",
1479            home.join(".config/mcphub/servers.json"),
1480            ConfigType::McpJson,
1481        ),
1482        "emacs" => push(
1483            &mut targets,
1484            "Emacs (mcp.el)",
1485            home.join(".emacs.d/mcp.json"),
1486            ConfigType::McpJson,
1487        ),
1488        "sublime" => push(
1489            &mut targets,
1490            "Sublime Text",
1491            home.join(".config/sublime-text/mcp.json"),
1492            ConfigType::McpJson,
1493        ),
1494        _ => {
1495            return Err(format!("Unknown agent '{agent}'"));
1496        }
1497    }
1498
1499    for t in &targets {
1500        crate::core::editor_registry::remove_lean_ctx_server(
1501            t,
1502            WriteOptions { overwrite_invalid },
1503        )?;
1504    }
1505
1506    Ok(())
1507}
1508
1509pub fn install_skill_files(home: &std::path::Path) -> Vec<(String, bool)> {
1510    crate::rules_inject::install_all_skills(home)
1511}
1512
1513fn install_kiro_steering(home: &std::path::Path) {
1514    let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
1515    let steering_dir = cwd.join(".kiro").join("steering");
1516    let steering_file = steering_dir.join("lean-ctx.md");
1517
1518    if steering_file.exists()
1519        && std::fs::read_to_string(&steering_file)
1520            .unwrap_or_default()
1521            .contains("lean-ctx")
1522    {
1523        println!("  Kiro steering file already exists at .kiro/steering/lean-ctx.md");
1524        return;
1525    }
1526
1527    let _ = std::fs::create_dir_all(&steering_dir);
1528    let _ = std::fs::write(&steering_file, crate::hooks::KIRO_STEERING_TEMPLATE);
1529    println!("  \x1b[32m✓\x1b[0m Created .kiro/steering/lean-ctx.md (Kiro will now prefer lean-ctx tools)");
1530}
1531
1532fn configure_plan_mode_settings(newly_configured: &[&str], already_configured: &[&str]) {
1533    use crate::terminal_ui;
1534
1535    let all_configured: Vec<&str> = newly_configured
1536        .iter()
1537        .chain(already_configured.iter())
1538        .copied()
1539        .collect();
1540
1541    let has_vscode = all_configured.contains(&"VS Code");
1542    let has_claude = all_configured.contains(&"Claude Code");
1543
1544    if !has_vscode && !has_claude {
1545        return;
1546    }
1547
1548    if has_vscode {
1549        match crate::core::editor_registry::plan_mode::write_vscode_plan_settings() {
1550            Ok(r) if r.action == WriteAction::Already => {
1551                terminal_ui::print_status_ok(
1552                    "VS Code            \x1b[2mplan mode already configured\x1b[0m",
1553                );
1554            }
1555            Ok(_) => {
1556                terminal_ui::print_status_new(
1557                    "VS Code            \x1b[2mplan mode tools configured\x1b[0m",
1558                );
1559            }
1560            Err(e) => {
1561                terminal_ui::print_status_warn(&format!("VS Code plan mode: {e}"));
1562            }
1563        }
1564    }
1565
1566    if has_claude {
1567        match crate::core::editor_registry::plan_mode::write_claude_code_plan_permissions() {
1568            Ok(r) if r.action == WriteAction::Already => {
1569                terminal_ui::print_status_ok(
1570                    "Claude Code        \x1b[2mplan mode permissions present\x1b[0m",
1571                );
1572            }
1573            Ok(_) => {
1574                terminal_ui::print_status_new(
1575                    "Claude Code        \x1b[2mplan mode permissions added\x1b[0m",
1576                );
1577            }
1578            Err(e) => {
1579                terminal_ui::print_status_warn(&format!("Claude Code plan mode: {e}"));
1580            }
1581        }
1582    }
1583}
1584
1585fn shorten_path(path: &str, home: &str) -> String {
1586    if let Some(stripped) = path.strip_prefix(home) {
1587        format!("~{stripped}")
1588    } else {
1589        path.to_string()
1590    }
1591}
1592
1593fn upsert_toml_key(content: &mut String, key: &str, value: &str) {
1594    let pattern = format!("{key} = ");
1595    if let Some(start) = content.find(&pattern) {
1596        let line_end = content[start..]
1597            .find('\n')
1598            .map_or(content.len(), |p| start + p);
1599        content.replace_range(start..line_end, &format!("{key} = \"{value}\""));
1600    } else {
1601        if !content.is_empty() && !content.ends_with('\n') {
1602            content.push('\n');
1603        }
1604        content.push_str(&format!("{key} = \"{value}\"\n"));
1605    }
1606}
1607
1608fn remove_toml_key(content: &mut String, key: &str) {
1609    let pattern = format!("{key} = ");
1610    if let Some(start) = content.find(&pattern) {
1611        let line_end = content[start..]
1612            .find('\n')
1613            .map_or(content.len(), |p| start + p + 1);
1614        content.replace_range(start..line_end, "");
1615    }
1616}
1617
1618fn configure_premium_features(home: &std::path::Path) {
1619    use crate::terminal_ui;
1620    use std::io::Write;
1621
1622    let config_dir = crate::core::data_dir::lean_ctx_data_dir()
1623        .unwrap_or_else(|_| home.join(".config/lean-ctx"));
1624    let _ = std::fs::create_dir_all(&config_dir);
1625    let config_path = config_dir.join("config.toml");
1626    let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
1627
1628    let dim = "\x1b[2m";
1629    let bold = "\x1b[1m";
1630    let cyan = "\x1b[36m";
1631    let rst = "\x1b[0m";
1632
1633    // Unified Compression Level (replaces terse_agent + output_density)
1634    println!("\n  {bold}Compression Level{rst} {dim}(controls all token optimization layers){rst}");
1635    println!("  {dim}Applies to tool output, agent prompts, and protocol mode.{rst}");
1636    println!();
1637    println!("  {cyan}off{rst}      — No compression (full verbose output)");
1638    println!("  {cyan}lite{rst}     — Light: concise output, basic terse filtering {dim}(~25% savings){rst}");
1639    println!("  {cyan}standard{rst} — Dense output + compact protocol + pattern-aware {dim}(~45% savings){rst}");
1640    println!("  {cyan}max{rst}      — Expert mode: TDD protocol, all layers active {dim}(~65% savings){rst}");
1641    println!();
1642    print!("  Compression level? {bold}[off/lite/standard/max]{rst} {dim}(default: off){rst} ");
1643    std::io::stdout().flush().ok();
1644
1645    let mut level_input = String::new();
1646    let level = if std::io::stdin().read_line(&mut level_input).is_ok() {
1647        match level_input.trim().to_lowercase().as_str() {
1648            "lite" => "lite",
1649            "standard" | "std" => "standard",
1650            "max" => "max",
1651            _ => "off",
1652        }
1653    } else {
1654        "off"
1655    };
1656
1657    let effective_level = if level != "off" {
1658        upsert_toml_key(&mut config_content, "compression_level", level);
1659        remove_toml_key(&mut config_content, "terse_agent");
1660        remove_toml_key(&mut config_content, "output_density");
1661        terminal_ui::print_status_ok(&format!("Compression: {level}"));
1662        crate::core::config::CompressionLevel::from_str_label(level)
1663    } else if config_content.contains("compression_level") {
1664        upsert_toml_key(&mut config_content, "compression_level", "off");
1665        terminal_ui::print_status_ok("Compression: off");
1666        Some(crate::core::config::CompressionLevel::Off)
1667    } else {
1668        terminal_ui::print_status_skip(
1669            "Compression: off (change later with: lean-ctx compression <level>)",
1670        );
1671        Some(crate::core::config::CompressionLevel::Off)
1672    };
1673
1674    if let Some(lvl) = effective_level {
1675        let n = crate::core::terse::rules_inject::inject(&lvl);
1676        if n > 0 {
1677            terminal_ui::print_status_ok(&format!(
1678                "Updated {n} rules file(s) with compression prompt"
1679            ));
1680        }
1681    }
1682
1683    // Tool Result Archive (unchanged)
1684    println!(
1685        "\n  {bold}Tool Result Archive{rst} {dim}(zero-loss: large outputs archived, retrievable via ctx_expand){rst}"
1686    );
1687    print!("  Enable auto-archive? {bold}[Y/n]{rst} ");
1688    std::io::stdout().flush().ok();
1689
1690    let mut archive_input = String::new();
1691    let archive_on = if std::io::stdin().read_line(&mut archive_input).is_ok() {
1692        let a = archive_input.trim().to_lowercase();
1693        a.is_empty() || a == "y" || a == "yes"
1694    } else {
1695        true
1696    };
1697
1698    if archive_on && !config_content.contains("[archive]") {
1699        if !config_content.is_empty() && !config_content.ends_with('\n') {
1700            config_content.push('\n');
1701        }
1702        config_content.push_str("\n[archive]\nenabled = true\n");
1703        terminal_ui::print_status_ok("Tool Result Archive: enabled");
1704    } else if !archive_on {
1705        terminal_ui::print_status_skip("Archive: off (enable later in config.toml)");
1706    }
1707
1708    let _ = std::fs::write(&config_path, config_content);
1709}
1710
1711#[cfg(all(test, target_os = "macos"))]
1712mod tests {
1713    use super::*;
1714
1715    #[test]
1716    #[cfg(target_os = "macos")]
1717    fn qoder_agent_targets_include_all_macos_mcp_locations() {
1718        let home = std::path::Path::new("/Users/tester");
1719        let targets = agent_mcp_targets("qoder", home).unwrap();
1720        let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1721
1722        assert_eq!(
1723            paths,
1724            vec![
1725                home.join(".qoder/mcp.json").as_path(),
1726                home.join("Library/Application Support/Qoder/User/mcp.json")
1727                    .as_path(),
1728                home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1729                    .as_path(),
1730            ]
1731        );
1732        assert!(targets
1733            .iter()
1734            .all(|t| t.config_type == ConfigType::QoderSettings));
1735    }
1736}