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        "augment" => {
1112            push(
1113                &mut targets,
1114                "Augment CLI",
1115                crate::core::editor_registry::augment_cli_settings_path(home),
1116                ConfigType::McpJson,
1117            );
1118            push(
1119                &mut targets,
1120                "Augment (VS Code)",
1121                crate::core::editor_registry::augment_vscode_mcp_path(home),
1122                ConfigType::AugmentVsCode,
1123            );
1124        }
1125        "windsurf" => push(
1126            &mut targets,
1127            "Windsurf",
1128            home.join(".codeium/windsurf/mcp_config.json"),
1129            ConfigType::McpJson,
1130        ),
1131        "codex" => {
1132            let codex_dir =
1133                crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
1134            push(
1135                &mut targets,
1136                "Codex CLI",
1137                codex_dir.join("config.toml"),
1138                ConfigType::Codex,
1139            );
1140        }
1141        "gemini" => {
1142            push(
1143                &mut targets,
1144                "Gemini CLI",
1145                home.join(".gemini/settings.json"),
1146                ConfigType::GeminiSettings,
1147            );
1148            push(
1149                &mut targets,
1150                "Antigravity",
1151                home.join(".gemini/antigravity/mcp_config.json"),
1152                ConfigType::McpJson,
1153            );
1154        }
1155        "antigravity" => push(
1156            &mut targets,
1157            "Antigravity",
1158            home.join(".gemini/antigravity/mcp_config.json"),
1159            ConfigType::McpJson,
1160        ),
1161        "copilot" => push(
1162            &mut targets,
1163            "Copilot CLI",
1164            home.join(".copilot/mcp-config.json"),
1165            ConfigType::CopilotCli,
1166        ),
1167        "crush" => push(
1168            &mut targets,
1169            "Crush",
1170            home.join(".config/crush/crush.json"),
1171            ConfigType::Crush,
1172        ),
1173        "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
1174        "qoder" => {
1175            for path in crate::core::editor_registry::qoder_all_mcp_paths(home) {
1176                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
1177            }
1178        }
1179        "qoderwork" => push(
1180            &mut targets,
1181            "QoderWork",
1182            crate::core::editor_registry::qoderwork_mcp_path(home),
1183            ConfigType::McpJson,
1184        ),
1185        "cline" => push(
1186            &mut targets,
1187            "Cline",
1188            crate::core::editor_registry::cline_mcp_path(),
1189            ConfigType::McpJson,
1190        ),
1191        "roo" => push(
1192            &mut targets,
1193            "Roo Code",
1194            crate::core::editor_registry::roo_mcp_path(),
1195            ConfigType::McpJson,
1196        ),
1197        "kiro" => push(
1198            &mut targets,
1199            "AWS Kiro",
1200            home.join(".kiro/settings/mcp.json"),
1201            ConfigType::McpJson,
1202        ),
1203        "verdent" => push(
1204            &mut targets,
1205            "Verdent",
1206            home.join(".verdent/mcp.json"),
1207            ConfigType::McpJson,
1208        ),
1209        "jetbrains" | "amp" => {
1210            // Handled by dedicated install hooks (servers[] array / amp.mcpServers)
1211        }
1212        "qwen" => push(
1213            &mut targets,
1214            "Qwen Code",
1215            home.join(".qwen/settings.json"),
1216            ConfigType::McpJson,
1217        ),
1218        "trae" => push(
1219            &mut targets,
1220            "Trae",
1221            home.join(".trae/mcp.json"),
1222            ConfigType::McpJson,
1223        ),
1224        "amazonq" => push(
1225            &mut targets,
1226            "Amazon Q Developer",
1227            home.join(".aws/amazonq/default.json"),
1228            ConfigType::McpJson,
1229        ),
1230        "opencode" => {
1231            #[cfg(windows)]
1232            let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
1233                std::path::PathBuf::from(appdata)
1234                    .join("opencode")
1235                    .join("opencode.json")
1236            } else {
1237                home.join(".config/opencode/opencode.json")
1238            };
1239            #[cfg(not(windows))]
1240            let opencode_path = home.join(".config/opencode/opencode.json");
1241            push(
1242                &mut targets,
1243                "OpenCode",
1244                opencode_path,
1245                ConfigType::OpenCode,
1246            );
1247        }
1248        "hermes" => push(
1249            &mut targets,
1250            "Hermes Agent",
1251            home.join(".hermes/config.yaml"),
1252            ConfigType::HermesYaml,
1253        ),
1254        "vscode" => push(
1255            &mut targets,
1256            "VS Code",
1257            crate::core::editor_registry::vscode_mcp_path(),
1258            ConfigType::VsCodeMcp,
1259        ),
1260        "zed" => push(
1261            &mut targets,
1262            "Zed",
1263            crate::core::editor_registry::zed_settings_path(home),
1264            ConfigType::Zed,
1265        ),
1266        "aider" => push(
1267            &mut targets,
1268            "Aider",
1269            home.join(".aider/mcp.json"),
1270            ConfigType::McpJson,
1271        ),
1272        "continue" => push(
1273            &mut targets,
1274            "Continue",
1275            home.join(".continue/mcp.json"),
1276            ConfigType::McpJson,
1277        ),
1278        "neovim" => push(
1279            &mut targets,
1280            "Neovim (mcphub.nvim)",
1281            home.join(".config/mcphub/servers.json"),
1282            ConfigType::McpJson,
1283        ),
1284        "emacs" => push(
1285            &mut targets,
1286            "Emacs (mcp.el)",
1287            home.join(".emacs.d/mcp.json"),
1288            ConfigType::McpJson,
1289        ),
1290        "sublime" => push(
1291            &mut targets,
1292            "Sublime Text",
1293            home.join(".config/sublime-text/mcp.json"),
1294            ConfigType::McpJson,
1295        ),
1296        _ => {
1297            return Err(format!("Unknown agent '{agent}'"));
1298        }
1299    }
1300
1301    Ok(targets)
1302}
1303
1304pub fn disable_agent_mcp(agent: &str, overwrite_invalid: bool) -> Result<(), String> {
1305    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
1306
1307    let mut targets = Vec::<EditorTarget>::new();
1308
1309    let push = |targets: &mut Vec<EditorTarget>,
1310                name: &'static str,
1311                config_path: PathBuf,
1312                config_type: ConfigType| {
1313        targets.push(EditorTarget {
1314            name,
1315            agent_key: agent.to_string(),
1316            detect_path: PathBuf::from("/nonexistent"),
1317            config_path,
1318            config_type,
1319        });
1320    };
1321
1322    let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
1323
1324    match agent {
1325        "cursor" => push(
1326            &mut targets,
1327            "Cursor",
1328            home.join(".cursor/mcp.json"),
1329            ConfigType::McpJson,
1330        ),
1331        "claude" | "claude-code" => push(
1332            &mut targets,
1333            "Claude Code",
1334            crate::core::editor_registry::claude_mcp_json_path(&home),
1335            ConfigType::McpJson,
1336        ),
1337        "augment" => {
1338            push(
1339                &mut targets,
1340                "Augment CLI",
1341                crate::core::editor_registry::augment_cli_settings_path(&home),
1342                ConfigType::McpJson,
1343            );
1344            push(
1345                &mut targets,
1346                "Augment (VS Code)",
1347                crate::core::editor_registry::augment_vscode_mcp_path(&home),
1348                ConfigType::AugmentVsCode,
1349            );
1350        }
1351        "windsurf" => push(
1352            &mut targets,
1353            "Windsurf",
1354            home.join(".codeium/windsurf/mcp_config.json"),
1355            ConfigType::McpJson,
1356        ),
1357        "codex" => {
1358            let codex_dir =
1359                crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
1360            push(
1361                &mut targets,
1362                "Codex CLI",
1363                codex_dir.join("config.toml"),
1364                ConfigType::Codex,
1365            );
1366        }
1367        "gemini" => {
1368            push(
1369                &mut targets,
1370                "Gemini CLI",
1371                home.join(".gemini/settings.json"),
1372                ConfigType::GeminiSettings,
1373            );
1374            push(
1375                &mut targets,
1376                "Antigravity",
1377                home.join(".gemini/antigravity/mcp_config.json"),
1378                ConfigType::McpJson,
1379            );
1380        }
1381        "antigravity" => push(
1382            &mut targets,
1383            "Antigravity",
1384            home.join(".gemini/antigravity/mcp_config.json"),
1385            ConfigType::McpJson,
1386        ),
1387        "copilot" => push(
1388            &mut targets,
1389            "Copilot CLI",
1390            home.join(".copilot/mcp-config.json"),
1391            ConfigType::CopilotCli,
1392        ),
1393        "crush" => push(
1394            &mut targets,
1395            "Crush",
1396            home.join(".config/crush/crush.json"),
1397            ConfigType::Crush,
1398        ),
1399        "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
1400        "qoder" => {
1401            for path in crate::core::editor_registry::qoder_all_mcp_paths(&home) {
1402                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
1403            }
1404        }
1405        "qoderwork" => push(
1406            &mut targets,
1407            "QoderWork",
1408            crate::core::editor_registry::qoderwork_mcp_path(&home),
1409            ConfigType::McpJson,
1410        ),
1411        "cline" => push(
1412            &mut targets,
1413            "Cline",
1414            crate::core::editor_registry::cline_mcp_path(),
1415            ConfigType::McpJson,
1416        ),
1417        "roo" => push(
1418            &mut targets,
1419            "Roo Code",
1420            crate::core::editor_registry::roo_mcp_path(),
1421            ConfigType::McpJson,
1422        ),
1423        "kiro" => push(
1424            &mut targets,
1425            "AWS Kiro",
1426            home.join(".kiro/settings/mcp.json"),
1427            ConfigType::McpJson,
1428        ),
1429        "verdent" => push(
1430            &mut targets,
1431            "Verdent",
1432            home.join(".verdent/mcp.json"),
1433            ConfigType::McpJson,
1434        ),
1435        "jetbrains" | "amp" => {
1436            // Not supported for disable via this helper.
1437        }
1438        "qwen" => push(
1439            &mut targets,
1440            "Qwen Code",
1441            home.join(".qwen/settings.json"),
1442            ConfigType::McpJson,
1443        ),
1444        "trae" => push(
1445            &mut targets,
1446            "Trae",
1447            home.join(".trae/mcp.json"),
1448            ConfigType::McpJson,
1449        ),
1450        "amazonq" => push(
1451            &mut targets,
1452            "Amazon Q Developer",
1453            home.join(".aws/amazonq/default.json"),
1454            ConfigType::McpJson,
1455        ),
1456        "opencode" => {
1457            #[cfg(windows)]
1458            let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
1459                std::path::PathBuf::from(appdata)
1460                    .join("opencode")
1461                    .join("opencode.json")
1462            } else {
1463                home.join(".config/opencode/opencode.json")
1464            };
1465            #[cfg(not(windows))]
1466            let opencode_path = home.join(".config/opencode/opencode.json");
1467            push(
1468                &mut targets,
1469                "OpenCode",
1470                opencode_path,
1471                ConfigType::OpenCode,
1472            );
1473        }
1474        "hermes" => push(
1475            &mut targets,
1476            "Hermes Agent",
1477            home.join(".hermes/config.yaml"),
1478            ConfigType::HermesYaml,
1479        ),
1480        "vscode" => push(
1481            &mut targets,
1482            "VS Code",
1483            crate::core::editor_registry::vscode_mcp_path(),
1484            ConfigType::VsCodeMcp,
1485        ),
1486        "zed" => push(
1487            &mut targets,
1488            "Zed",
1489            crate::core::editor_registry::zed_settings_path(&home),
1490            ConfigType::Zed,
1491        ),
1492        "aider" => push(
1493            &mut targets,
1494            "Aider",
1495            home.join(".aider/mcp.json"),
1496            ConfigType::McpJson,
1497        ),
1498        "continue" => push(
1499            &mut targets,
1500            "Continue",
1501            home.join(".continue/mcp.json"),
1502            ConfigType::McpJson,
1503        ),
1504        "neovim" => push(
1505            &mut targets,
1506            "Neovim (mcphub.nvim)",
1507            home.join(".config/mcphub/servers.json"),
1508            ConfigType::McpJson,
1509        ),
1510        "emacs" => push(
1511            &mut targets,
1512            "Emacs (mcp.el)",
1513            home.join(".emacs.d/mcp.json"),
1514            ConfigType::McpJson,
1515        ),
1516        "sublime" => push(
1517            &mut targets,
1518            "Sublime Text",
1519            home.join(".config/sublime-text/mcp.json"),
1520            ConfigType::McpJson,
1521        ),
1522        _ => {
1523            return Err(format!("Unknown agent '{agent}'"));
1524        }
1525    }
1526
1527    for t in &targets {
1528        crate::core::editor_registry::remove_lean_ctx_server(
1529            t,
1530            WriteOptions { overwrite_invalid },
1531        )?;
1532    }
1533
1534    Ok(())
1535}
1536
1537pub fn install_skill_files(home: &std::path::Path) -> Vec<(String, bool)> {
1538    crate::rules_inject::install_all_skills(home)
1539}
1540
1541fn install_kiro_steering(home: &std::path::Path) {
1542    let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
1543    let steering_dir = cwd.join(".kiro").join("steering");
1544    let steering_file = steering_dir.join("lean-ctx.md");
1545
1546    if steering_file.exists()
1547        && std::fs::read_to_string(&steering_file)
1548            .unwrap_or_default()
1549            .contains("lean-ctx")
1550    {
1551        println!("  Kiro steering file already exists at .kiro/steering/lean-ctx.md");
1552        return;
1553    }
1554
1555    let _ = std::fs::create_dir_all(&steering_dir);
1556    let _ = std::fs::write(&steering_file, crate::hooks::KIRO_STEERING_TEMPLATE);
1557    println!("  \x1b[32m✓\x1b[0m Created .kiro/steering/lean-ctx.md (Kiro will now prefer lean-ctx tools)");
1558}
1559
1560fn configure_plan_mode_settings(newly_configured: &[&str], already_configured: &[&str]) {
1561    use crate::terminal_ui;
1562
1563    let all_configured: Vec<&str> = newly_configured
1564        .iter()
1565        .chain(already_configured.iter())
1566        .copied()
1567        .collect();
1568
1569    let has_vscode = all_configured.contains(&"VS Code");
1570    let has_claude = all_configured.contains(&"Claude Code");
1571
1572    if !has_vscode && !has_claude {
1573        return;
1574    }
1575
1576    if has_vscode {
1577        match crate::core::editor_registry::plan_mode::write_vscode_plan_settings() {
1578            Ok(r) if r.action == WriteAction::Already => {
1579                terminal_ui::print_status_ok(
1580                    "VS Code            \x1b[2mplan mode already configured\x1b[0m",
1581                );
1582            }
1583            Ok(_) => {
1584                terminal_ui::print_status_new(
1585                    "VS Code            \x1b[2mplan mode tools configured\x1b[0m",
1586                );
1587            }
1588            Err(e) => {
1589                terminal_ui::print_status_warn(&format!("VS Code plan mode: {e}"));
1590            }
1591        }
1592    }
1593
1594    if has_claude {
1595        match crate::core::editor_registry::plan_mode::write_claude_code_plan_permissions() {
1596            Ok(r) if r.action == WriteAction::Already => {
1597                terminal_ui::print_status_ok(
1598                    "Claude Code        \x1b[2mplan mode permissions present\x1b[0m",
1599                );
1600            }
1601            Ok(_) => {
1602                terminal_ui::print_status_new(
1603                    "Claude Code        \x1b[2mplan mode permissions added\x1b[0m",
1604                );
1605            }
1606            Err(e) => {
1607                terminal_ui::print_status_warn(&format!("Claude Code plan mode: {e}"));
1608            }
1609        }
1610    }
1611}
1612
1613fn shorten_path(path: &str, home: &str) -> String {
1614    if let Some(stripped) = path.strip_prefix(home) {
1615        format!("~{stripped}")
1616    } else {
1617        path.to_string()
1618    }
1619}
1620
1621fn upsert_toml_key(content: &mut String, key: &str, value: &str) {
1622    let pattern = format!("{key} = ");
1623    if let Some(start) = content.find(&pattern) {
1624        let line_end = content[start..]
1625            .find('\n')
1626            .map_or(content.len(), |p| start + p);
1627        content.replace_range(start..line_end, &format!("{key} = \"{value}\""));
1628    } else {
1629        if !content.is_empty() && !content.ends_with('\n') {
1630            content.push('\n');
1631        }
1632        content.push_str(&format!("{key} = \"{value}\"\n"));
1633    }
1634}
1635
1636fn remove_toml_key(content: &mut String, key: &str) {
1637    let pattern = format!("{key} = ");
1638    if let Some(start) = content.find(&pattern) {
1639        let line_end = content[start..]
1640            .find('\n')
1641            .map_or(content.len(), |p| start + p + 1);
1642        content.replace_range(start..line_end, "");
1643    }
1644}
1645
1646fn configure_premium_features(home: &std::path::Path) {
1647    use crate::terminal_ui;
1648    use std::io::Write;
1649
1650    let config_dir = crate::core::data_dir::lean_ctx_data_dir()
1651        .unwrap_or_else(|_| home.join(".config/lean-ctx"));
1652    let _ = std::fs::create_dir_all(&config_dir);
1653    let config_path = config_dir.join("config.toml");
1654    let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
1655
1656    let dim = "\x1b[2m";
1657    let bold = "\x1b[1m";
1658    let cyan = "\x1b[36m";
1659    let rst = "\x1b[0m";
1660
1661    // Unified Compression Level (replaces terse_agent + output_density)
1662    println!("\n  {bold}Compression Level{rst} {dim}(controls all token optimization layers){rst}");
1663    println!("  {dim}Applies to tool output, agent prompts, and protocol mode.{rst}");
1664    println!();
1665    println!("  {cyan}off{rst}      — No compression (full verbose output)");
1666    println!("  {cyan}lite{rst}     — Light: concise output, basic terse filtering {dim}(~25% savings){rst}");
1667    println!("  {cyan}standard{rst} — Dense output + compact protocol + pattern-aware {dim}(~45% savings){rst}");
1668    println!("  {cyan}max{rst}      — Expert mode: TDD protocol, all layers active {dim}(~65% savings){rst}");
1669    println!();
1670    print!("  Compression level? {bold}[off/lite/standard/max]{rst} {dim}(default: off){rst} ");
1671    std::io::stdout().flush().ok();
1672
1673    let mut level_input = String::new();
1674    let level = if std::io::stdin().read_line(&mut level_input).is_ok() {
1675        match level_input.trim().to_lowercase().as_str() {
1676            "lite" => "lite",
1677            "standard" | "std" => "standard",
1678            "max" => "max",
1679            _ => "off",
1680        }
1681    } else {
1682        "off"
1683    };
1684
1685    let effective_level = if level != "off" {
1686        upsert_toml_key(&mut config_content, "compression_level", level);
1687        remove_toml_key(&mut config_content, "terse_agent");
1688        remove_toml_key(&mut config_content, "output_density");
1689        terminal_ui::print_status_ok(&format!("Compression: {level}"));
1690        crate::core::config::CompressionLevel::from_str_label(level)
1691    } else if config_content.contains("compression_level") {
1692        upsert_toml_key(&mut config_content, "compression_level", "off");
1693        terminal_ui::print_status_ok("Compression: off");
1694        Some(crate::core::config::CompressionLevel::Off)
1695    } else {
1696        terminal_ui::print_status_skip(
1697            "Compression: off (change later with: lean-ctx compression <level>)",
1698        );
1699        Some(crate::core::config::CompressionLevel::Off)
1700    };
1701
1702    if let Some(lvl) = effective_level {
1703        let n = crate::core::terse::rules_inject::inject(&lvl);
1704        if n > 0 {
1705            terminal_ui::print_status_ok(&format!(
1706                "Updated {n} rules file(s) with compression prompt"
1707            ));
1708        }
1709    }
1710
1711    // Tool Result Archive (unchanged)
1712    println!(
1713        "\n  {bold}Tool Result Archive{rst} {dim}(zero-loss: large outputs archived, retrievable via ctx_expand){rst}"
1714    );
1715    print!("  Enable auto-archive? {bold}[Y/n]{rst} ");
1716    std::io::stdout().flush().ok();
1717
1718    let mut archive_input = String::new();
1719    let archive_on = if std::io::stdin().read_line(&mut archive_input).is_ok() {
1720        let a = archive_input.trim().to_lowercase();
1721        a.is_empty() || a == "y" || a == "yes"
1722    } else {
1723        true
1724    };
1725
1726    if archive_on && !config_content.contains("[archive]") {
1727        if !config_content.is_empty() && !config_content.ends_with('\n') {
1728            config_content.push('\n');
1729        }
1730        config_content.push_str("\n[archive]\nenabled = true\n");
1731        terminal_ui::print_status_ok("Tool Result Archive: enabled");
1732    } else if !archive_on {
1733        terminal_ui::print_status_skip("Archive: off (enable later in config.toml)");
1734    }
1735
1736    let _ = std::fs::write(&config_path, config_content);
1737}
1738
1739#[cfg(all(test, target_os = "macos"))]
1740mod tests {
1741    use super::*;
1742
1743    #[test]
1744    #[cfg(target_os = "macos")]
1745    fn qoder_agent_targets_include_all_macos_mcp_locations() {
1746        let home = std::path::Path::new("/Users/tester");
1747        let targets = agent_mcp_targets("qoder", home).unwrap();
1748        let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1749
1750        assert_eq!(
1751            paths,
1752            vec![
1753                home.join(".qoder/mcp.json").as_path(),
1754                home.join("Library/Application Support/Qoder/User/mcp.json")
1755                    .as_path(),
1756                home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1757                    .as_path(),
1758            ]
1759        );
1760        assert!(targets
1761            .iter()
1762            .all(|t| t.config_type == ConfigType::QoderSettings));
1763    }
1764}