Skip to main content

lean_ctx/
setup.rs

1use std::path::PathBuf;
2
3struct EditorTarget {
4    name: &'static str,
5    agent_key: &'static str,
6    config_path: PathBuf,
7    detect_path: PathBuf,
8    config_type: ConfigType,
9}
10
11enum ConfigType {
12    McpJson,
13    Zed,
14    Codex,
15    VsCodeMcp,
16    OpenCode,
17}
18
19pub fn run_setup() {
20    use crate::terminal_ui;
21
22    let home = match dirs::home_dir() {
23        Some(h) => h,
24        None => {
25            eprintln!("Cannot determine home directory");
26            std::process::exit(1);
27        }
28    };
29
30    let binary = std::env::current_exe()
31        .map(|p| p.to_string_lossy().to_string())
32        .unwrap_or_else(|_| "lean-ctx".to_string());
33
34    let home_str = home.to_string_lossy().to_string();
35
36    terminal_ui::print_setup_header();
37
38    // Step 1: Shell hook
39    terminal_ui::print_step_header(1, 5, "Shell Hook");
40    crate::cli::cmd_init(&["--global".to_string()]);
41
42    // Step 2: Editor auto-detection + configuration
43    terminal_ui::print_step_header(2, 5, "AI Tool Detection");
44
45    let targets = build_targets(&home, &binary);
46    let mut newly_configured: Vec<&str> = Vec::new();
47    let mut already_configured: Vec<&str> = Vec::new();
48    let mut not_installed: Vec<&str> = Vec::new();
49    let mut errors: Vec<&str> = Vec::new();
50
51    for target in &targets {
52        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
53
54        if !target.detect_path.exists() {
55            not_installed.push(target.name);
56            continue;
57        }
58
59        let has_config = target.config_path.exists()
60            && std::fs::read_to_string(&target.config_path)
61                .map(|c| c.contains("lean-ctx"))
62                .unwrap_or(false);
63
64        if has_config {
65            terminal_ui::print_status_ok(&format!(
66                "{:<20} \x1b[2m{short_path}\x1b[0m",
67                target.name
68            ));
69            already_configured.push(target.name);
70            continue;
71        }
72
73        match write_config(target, &binary) {
74            Ok(()) => {
75                terminal_ui::print_status_new(&format!(
76                    "{:<20} \x1b[2m{short_path}\x1b[0m",
77                    target.name
78                ));
79                newly_configured.push(target.name);
80            }
81            Err(e) => {
82                terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
83                errors.push(target.name);
84            }
85        }
86    }
87
88    let total_ok = newly_configured.len() + already_configured.len();
89    if total_ok == 0 && errors.is_empty() {
90        terminal_ui::print_status_warn(
91            "No AI tools detected. Install one and re-run: lean-ctx setup",
92        );
93    }
94
95    if !not_installed.is_empty() {
96        println!(
97            "  \x1b[2m○ {} not detected: {}\x1b[0m",
98            not_installed.len(),
99            not_installed.join(", ")
100        );
101    }
102
103    // Step 3: Agent rules injection
104    terminal_ui::print_step_header(3, 5, "Agent Rules");
105    let rules_result = crate::rules_inject::inject_all_rules(&home);
106    for name in &rules_result.injected {
107        terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
108    }
109    for name in &rules_result.updated {
110        terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
111    }
112    for name in &rules_result.already {
113        terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
114    }
115    for err in &rules_result.errors {
116        terminal_ui::print_status_warn(err);
117    }
118    if rules_result.injected.is_empty()
119        && rules_result.updated.is_empty()
120        && rules_result.already.is_empty()
121        && rules_result.errors.is_empty()
122    {
123        terminal_ui::print_status_skip("No agent rules needed");
124    }
125
126    // Legacy agent hooks
127    for target in &targets {
128        if !target.detect_path.exists() || target.agent_key.is_empty() {
129            continue;
130        }
131        crate::hooks::install_agent_hook(target.agent_key, true);
132    }
133
134    // Step 4: Data directory + diagnostics
135    terminal_ui::print_step_header(4, 5, "Environment Check");
136    let lean_dir = home.join(".lean-ctx");
137    if !lean_dir.exists() {
138        let _ = std::fs::create_dir_all(&lean_dir);
139        terminal_ui::print_status_new("Created ~/.lean-ctx/");
140    } else {
141        terminal_ui::print_status_ok("~/.lean-ctx/ ready");
142    }
143    crate::doctor::run();
144
145    // Step 5: Data sharing
146    terminal_ui::print_step_header(5, 5, "Help Improve lean-ctx");
147    println!("  Share anonymous compression stats to make lean-ctx better.");
148    println!("  \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
149    println!();
150    print!("  Enable anonymous data sharing? \x1b[1m[Y/n]\x1b[0m ");
151    use std::io::Write;
152    std::io::stdout().flush().ok();
153
154    let mut input = String::new();
155    let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
156        let answer = input.trim().to_lowercase();
157        answer.is_empty() || answer == "y" || answer == "yes"
158    } else {
159        false
160    };
161
162    if contribute {
163        let config_dir = home.join(".lean-ctx");
164        let _ = std::fs::create_dir_all(&config_dir);
165        let config_path = config_dir.join("config.toml");
166        let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
167        if !config_content.contains("[cloud]") {
168            if !config_content.is_empty() && !config_content.ends_with('\n') {
169                config_content.push('\n');
170            }
171            config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
172            let _ = std::fs::write(&config_path, config_content);
173        }
174        terminal_ui::print_status_ok("Enabled — thank you!");
175    } else {
176        terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
177    }
178
179    // Summary
180    println!();
181    println!(
182        "  \x1b[1;32m✓ Setup complete!\x1b[0m  \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
183        newly_configured.len(),
184        already_configured.len(),
185        not_installed.len()
186    );
187
188    if !errors.is_empty() {
189        println!(
190            "  \x1b[33m⚠ {} error{}: {}\x1b[0m",
191            errors.len(),
192            if errors.len() != 1 { "s" } else { "" },
193            errors.join(", ")
194        );
195    }
196
197    // Next steps
198    let shell = std::env::var("SHELL").unwrap_or_default();
199    let source_cmd = if shell.contains("zsh") {
200        "source ~/.zshrc"
201    } else if shell.contains("fish") {
202        "source ~/.config/fish/config.fish"
203    } else if shell.contains("bash") {
204        "source ~/.bashrc"
205    } else {
206        "Restart your shell"
207    };
208
209    let dim = "\x1b[2m";
210    let bold = "\x1b[1m";
211    let cyan = "\x1b[36m";
212    let yellow = "\x1b[33m";
213    let rst = "\x1b[0m";
214
215    println!();
216    println!("  {bold}Next steps:{rst}");
217    println!();
218    println!("  {cyan}1.{rst} Reload your shell:");
219    println!("     {bold}{source_cmd}{rst}");
220    println!();
221
222    let mut tools_to_restart: Vec<String> =
223        newly_configured.iter().map(|s| s.to_string()).collect();
224    for name in rules_result
225        .injected
226        .iter()
227        .chain(rules_result.updated.iter())
228    {
229        if !tools_to_restart.iter().any(|t| t == name) {
230            tools_to_restart.push(name.clone());
231        }
232    }
233
234    if !tools_to_restart.is_empty() {
235        println!("  {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
236        println!("     {bold}{}{rst}", tools_to_restart.join(", "));
237        println!(
238            "     {dim}The MCP connection must be re-established for changes to take effect.{rst}"
239        );
240        println!("     {dim}Close and re-open the application completely.{rst}");
241    } else if !already_configured.is_empty() {
242        println!(
243            "  {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
244        );
245    }
246
247    println!();
248    println!(
249        "  {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
250    );
251    println!("  {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
252
253    // Logo + commands
254    println!();
255    terminal_ui::print_logo_animated();
256    terminal_ui::print_command_box();
257}
258
259fn shorten_path(path: &str, home: &str) -> String {
260    if let Some(stripped) = path.strip_prefix(home) {
261        format!("~{stripped}")
262    } else {
263        path.to_string()
264    }
265}
266
267fn build_targets(home: &std::path::Path, _binary: &str) -> Vec<EditorTarget> {
268    vec![
269        EditorTarget {
270            name: "Cursor",
271            agent_key: "cursor",
272            config_path: home.join(".cursor/mcp.json"),
273            detect_path: home.join(".cursor"),
274            config_type: ConfigType::McpJson,
275        },
276        EditorTarget {
277            name: "Claude Code",
278            agent_key: "claude",
279            config_path: home.join(".claude.json"),
280            detect_path: detect_claude_path(),
281            config_type: ConfigType::McpJson,
282        },
283        EditorTarget {
284            name: "Windsurf",
285            agent_key: "windsurf",
286            config_path: home.join(".codeium/windsurf/mcp_config.json"),
287            detect_path: home.join(".codeium/windsurf"),
288            config_type: ConfigType::McpJson,
289        },
290        EditorTarget {
291            name: "Codex CLI",
292            agent_key: "codex",
293            config_path: home.join(".codex/config.toml"),
294            detect_path: detect_codex_path(home),
295            config_type: ConfigType::Codex,
296        },
297        EditorTarget {
298            name: "Gemini CLI",
299            agent_key: "gemini",
300            config_path: home.join(".gemini/settings/mcp.json"),
301            detect_path: home.join(".gemini"),
302            config_type: ConfigType::McpJson,
303        },
304        EditorTarget {
305            name: "Antigravity",
306            agent_key: "gemini",
307            config_path: home.join(".gemini/antigravity/mcp_config.json"),
308            detect_path: home.join(".gemini/antigravity"),
309            config_type: ConfigType::McpJson,
310        },
311        EditorTarget {
312            name: "Zed",
313            agent_key: "",
314            config_path: zed_settings_path(home),
315            detect_path: zed_config_dir(home),
316            config_type: ConfigType::Zed,
317        },
318        EditorTarget {
319            name: "VS Code / Copilot",
320            agent_key: "copilot",
321            config_path: vscode_mcp_path(),
322            detect_path: detect_vscode_path(),
323            config_type: ConfigType::VsCodeMcp,
324        },
325        EditorTarget {
326            name: "OpenCode",
327            agent_key: "",
328            config_path: home.join(".config/opencode/opencode.json"),
329            detect_path: home.join(".config/opencode"),
330            config_type: ConfigType::OpenCode,
331        },
332        EditorTarget {
333            name: "Qwen Code",
334            agent_key: "qwen",
335            config_path: home.join(".qwen/mcp.json"),
336            detect_path: home.join(".qwen"),
337            config_type: ConfigType::McpJson,
338        },
339        EditorTarget {
340            name: "Trae",
341            agent_key: "trae",
342            config_path: home.join(".trae/mcp.json"),
343            detect_path: home.join(".trae"),
344            config_type: ConfigType::McpJson,
345        },
346        EditorTarget {
347            name: "Amazon Q Developer",
348            agent_key: "amazonq",
349            config_path: home.join(".aws/amazonq/mcp.json"),
350            detect_path: home.join(".aws/amazonq"),
351            config_type: ConfigType::McpJson,
352        },
353        EditorTarget {
354            name: "JetBrains IDEs",
355            agent_key: "jetbrains",
356            config_path: home.join(".jb-mcp.json"),
357            detect_path: detect_jetbrains_path(home),
358            config_type: ConfigType::McpJson,
359        },
360        EditorTarget {
361            name: "Cline",
362            agent_key: "cline",
363            config_path: cline_mcp_path(),
364            detect_path: detect_cline_path(),
365            config_type: ConfigType::McpJson,
366        },
367        EditorTarget {
368            name: "Roo Code",
369            agent_key: "roo",
370            config_path: roo_mcp_path(),
371            detect_path: detect_roo_path(),
372            config_type: ConfigType::McpJson,
373        },
374        EditorTarget {
375            name: "AWS Kiro",
376            agent_key: "kiro",
377            config_path: home.join(".kiro/settings/mcp.json"),
378            detect_path: home.join(".kiro"),
379            config_type: ConfigType::McpJson,
380        },
381    ]
382}
383
384fn detect_claude_path() -> PathBuf {
385    if let Ok(output) = std::process::Command::new("which").arg("claude").output() {
386        if output.status.success() {
387            return PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
388        }
389    }
390    if let Some(home) = dirs::home_dir() {
391        let claude_json = home.join(".claude.json");
392        if claude_json.exists() {
393            return claude_json;
394        }
395    }
396    PathBuf::from("/nonexistent")
397}
398
399fn detect_codex_path(home: &std::path::Path) -> PathBuf {
400    let codex_dir = home.join(".codex");
401    if codex_dir.exists() {
402        return codex_dir;
403    }
404    if let Ok(output) = std::process::Command::new("which").arg("codex").output() {
405        if output.status.success() {
406            return codex_dir;
407        }
408    }
409    PathBuf::from("/nonexistent")
410}
411
412fn zed_settings_path(home: &std::path::Path) -> PathBuf {
413    home.join(".config/zed/settings.json")
414}
415
416fn zed_config_dir(home: &std::path::Path) -> PathBuf {
417    home.join(".config/zed")
418}
419
420fn write_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
421    if let Some(parent) = target.config_path.parent() {
422        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
423    }
424
425    match target.config_type {
426        ConfigType::McpJson => write_mcp_json(target, binary),
427        ConfigType::Zed => write_zed_config(target, binary),
428        ConfigType::Codex => write_codex_config(target, binary),
429        ConfigType::VsCodeMcp => write_vscode_mcp(target, binary),
430        ConfigType::OpenCode => write_opencode_config(target, binary),
431    }
432}
433
434fn lean_ctx_server_entry(binary: &str) -> serde_json::Value {
435    serde_json::json!({
436        "command": binary,
437        "autoApprove": [
438            "ctx_read", "ctx_shell", "ctx_search", "ctx_tree",
439            "ctx_overview", "ctx_compress", "ctx_metrics", "ctx_session",
440            "ctx_knowledge", "ctx_agent", "ctx_analyze", "ctx_benchmark",
441            "ctx_cache", "ctx_discover", "ctx_smart_read", "ctx_delta",
442            "ctx_dedup", "ctx_fill", "ctx_intent", "ctx_response",
443            "ctx_context", "ctx_graph", "ctx_wrapped", "ctx_multi_read",
444            "ctx_semantic_search", "ctx"
445        ]
446    })
447}
448
449fn write_mcp_json(target: &EditorTarget, binary: &str) -> Result<(), String> {
450    if target.config_path.exists() {
451        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
452
453        if content.contains("lean-ctx") {
454            return Ok(());
455        }
456
457        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
458            if let Some(obj) = json.as_object_mut() {
459                let servers = obj
460                    .entry("mcpServers")
461                    .or_insert_with(|| serde_json::json!({}));
462                if let Some(servers_obj) = servers.as_object_mut() {
463                    servers_obj.insert("lean-ctx".to_string(), lean_ctx_server_entry(binary));
464                }
465                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
466                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
467                return Ok(());
468            }
469        }
470        return Err(format!(
471            "Could not parse existing config at {}. Please add lean-ctx manually:\n\
472             Add to \"mcpServers\": \"lean-ctx\": {{ \"command\": \"{}\" }}",
473            target.config_path.display(),
474            binary
475        ));
476    }
477
478    let content = serde_json::to_string_pretty(&serde_json::json!({
479        "mcpServers": {
480            "lean-ctx": lean_ctx_server_entry(binary)
481        }
482    }))
483    .map_err(|e| e.to_string())?;
484
485    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
486}
487
488fn write_zed_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
489    if target.config_path.exists() {
490        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
491
492        if content.contains("lean-ctx") {
493            return Ok(());
494        }
495
496        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
497            if let Some(obj) = json.as_object_mut() {
498                let servers = obj
499                    .entry("context_servers")
500                    .or_insert_with(|| serde_json::json!({}));
501                if let Some(servers_obj) = servers.as_object_mut() {
502                    servers_obj.insert(
503                        "lean-ctx".to_string(),
504                        serde_json::json!({
505                            "source": "custom",
506                            "command": binary,
507                            "args": [],
508                            "env": {}
509                        }),
510                    );
511                }
512                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
513                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
514                return Ok(());
515            }
516        }
517        return Err(format!(
518            "Could not parse existing config at {}. Please add lean-ctx manually to \"context_servers\".",
519            target.config_path.display()
520        ));
521    }
522
523    let content = serde_json::to_string_pretty(&serde_json::json!({
524        "context_servers": {
525            "lean-ctx": {
526                "source": "custom",
527                "command": binary,
528                "args": [],
529                "env": {}
530            }
531        }
532    }))
533    .map_err(|e| e.to_string())?;
534
535    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
536}
537
538fn write_codex_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
539    if target.config_path.exists() {
540        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
541
542        if content.contains("lean-ctx") {
543            return Ok(());
544        }
545
546        let mut new_content = content.clone();
547        if !new_content.ends_with('\n') {
548            new_content.push('\n');
549        }
550        new_content.push_str(&format!(
551            "\n[mcp_servers.lean-ctx]\ncommand = \"{}\"\nargs = []\n",
552            binary
553        ));
554        std::fs::write(&target.config_path, new_content).map_err(|e| e.to_string())?;
555        return Ok(());
556    }
557
558    let content = format!(
559        "[mcp_servers.lean-ctx]\ncommand = \"{}\"\nargs = []\n",
560        binary
561    );
562    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
563}
564
565fn write_vscode_mcp(target: &EditorTarget, binary: &str) -> Result<(), String> {
566    if target.config_path.exists() {
567        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
568        if content.contains("lean-ctx") {
569            return Ok(());
570        }
571        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
572            if let Some(obj) = json.as_object_mut() {
573                let servers = obj
574                    .entry("servers")
575                    .or_insert_with(|| serde_json::json!({}));
576                if let Some(servers_obj) = servers.as_object_mut() {
577                    servers_obj.insert(
578                        "lean-ctx".to_string(),
579                        serde_json::json!({ "command": binary, "args": [] }),
580                    );
581                }
582                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
583                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
584                return Ok(());
585            }
586        }
587        return Err(format!(
588            "Could not parse existing config at {}. Please add lean-ctx manually to \"servers\".",
589            target.config_path.display()
590        ));
591    }
592
593    if let Some(parent) = target.config_path.parent() {
594        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
595    }
596
597    let content = serde_json::to_string_pretty(&serde_json::json!({
598        "servers": {
599            "lean-ctx": {
600                "command": binary,
601                "args": []
602            }
603        }
604    }))
605    .map_err(|e| e.to_string())?;
606
607    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
608}
609
610fn write_opencode_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
611    if target.config_path.exists() {
612        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
613        if content.contains("lean-ctx") {
614            return Ok(());
615        }
616        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
617            if let Some(obj) = json.as_object_mut() {
618                let mcp = obj.entry("mcp").or_insert_with(|| serde_json::json!({}));
619                if let Some(mcp_obj) = mcp.as_object_mut() {
620                    mcp_obj.insert(
621                        "lean-ctx".to_string(),
622                        serde_json::json!({
623                            "type": "local",
624                            "command": [binary],
625                            "enabled": true
626                        }),
627                    );
628                }
629                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
630                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
631                return Ok(());
632            }
633        }
634        return Err(format!(
635            "Could not parse existing config at {}. Please add lean-ctx manually:\n\
636             Add to the \"mcp\" section: \"lean-ctx\": {{ \"type\": \"local\", \"command\": [\"{}\"], \"enabled\": true }}",
637            target.config_path.display(),
638            binary
639        ));
640    }
641
642    if let Some(parent) = target.config_path.parent() {
643        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
644    }
645
646    let content = serde_json::to_string_pretty(&serde_json::json!({
647        "$schema": "https://opencode.ai/config.json",
648        "mcp": {
649            "lean-ctx": {
650                "type": "local",
651                "command": [binary],
652                "enabled": true
653            }
654        }
655    }))
656    .map_err(|e| e.to_string())?;
657
658    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
659}
660
661fn detect_vscode_path() -> PathBuf {
662    #[cfg(target_os = "macos")]
663    {
664        if let Some(home) = dirs::home_dir() {
665            let vscode = home.join("Library/Application Support/Code/User/settings.json");
666            if vscode.exists() {
667                return vscode;
668            }
669        }
670    }
671    #[cfg(target_os = "linux")]
672    {
673        if let Some(home) = dirs::home_dir() {
674            let vscode = home.join(".config/Code/User/settings.json");
675            if vscode.exists() {
676                return vscode;
677            }
678        }
679    }
680    #[cfg(target_os = "windows")]
681    {
682        if let Ok(appdata) = std::env::var("APPDATA") {
683            let vscode = PathBuf::from(appdata).join("Code/User/settings.json");
684            if vscode.exists() {
685                return vscode;
686            }
687        }
688    }
689    if let Ok(output) = std::process::Command::new("which").arg("code").output() {
690        if output.status.success() {
691            return PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
692        }
693    }
694    PathBuf::from("/nonexistent")
695}
696
697fn vscode_mcp_path() -> PathBuf {
698    if let Some(home) = dirs::home_dir() {
699        #[cfg(target_os = "macos")]
700        {
701            return home.join("Library/Application Support/Code/User/mcp.json");
702        }
703        #[cfg(target_os = "linux")]
704        {
705            return home.join(".config/Code/User/mcp.json");
706        }
707        #[cfg(target_os = "windows")]
708        {
709            if let Ok(appdata) = std::env::var("APPDATA") {
710                return PathBuf::from(appdata).join("Code/User/mcp.json");
711            }
712        }
713        #[allow(unreachable_code)]
714        home.join(".config/Code/User/mcp.json")
715    } else {
716        PathBuf::from("/nonexistent")
717    }
718}
719
720fn detect_jetbrains_path(home: &std::path::Path) -> PathBuf {
721    #[cfg(target_os = "macos")]
722    {
723        let lib = home.join("Library/Application Support/JetBrains");
724        if lib.exists() {
725            return lib;
726        }
727    }
728    #[cfg(target_os = "linux")]
729    {
730        let cfg = home.join(".config/JetBrains");
731        if cfg.exists() {
732            return cfg;
733        }
734    }
735    if home.join(".jb-mcp.json").exists() {
736        return home.join(".jb-mcp.json");
737    }
738    PathBuf::from("/nonexistent")
739}
740
741fn cline_mcp_path() -> PathBuf {
742    if let Some(home) = dirs::home_dir() {
743        #[cfg(target_os = "macos")]
744        {
745            return home.join("Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
746        }
747        #[cfg(target_os = "linux")]
748        {
749            return home.join(".config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
750        }
751        #[cfg(target_os = "windows")]
752        {
753            if let Ok(appdata) = std::env::var("APPDATA") {
754                return PathBuf::from(appdata).join("Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
755            }
756        }
757    }
758    PathBuf::from("/nonexistent")
759}
760
761fn detect_cline_path() -> PathBuf {
762    if let Some(home) = dirs::home_dir() {
763        #[cfg(target_os = "macos")]
764        {
765            let p = home
766                .join("Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev");
767            if p.exists() {
768                return p;
769            }
770        }
771        #[cfg(target_os = "linux")]
772        {
773            let p = home.join(".config/Code/User/globalStorage/saoudrizwan.claude-dev");
774            if p.exists() {
775                return p;
776            }
777        }
778    }
779    PathBuf::from("/nonexistent")
780}
781
782fn roo_mcp_path() -> PathBuf {
783    if let Some(home) = dirs::home_dir() {
784        #[cfg(target_os = "macos")]
785        {
786            return home.join("Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
787        }
788        #[cfg(target_os = "linux")]
789        {
790            return home.join(".config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
791        }
792        #[cfg(target_os = "windows")]
793        {
794            if let Ok(appdata) = std::env::var("APPDATA") {
795                return PathBuf::from(appdata).join("Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
796            }
797        }
798    }
799    PathBuf::from("/nonexistent")
800}
801
802fn detect_roo_path() -> PathBuf {
803    if let Some(home) = dirs::home_dir() {
804        #[cfg(target_os = "macos")]
805        {
806            let p = home.join(
807                "Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline",
808            );
809            if p.exists() {
810                return p;
811            }
812        }
813        #[cfg(target_os = "linux")]
814        {
815            let p = home.join(".config/Code/User/globalStorage/rooveterinaryinc.roo-cline");
816            if p.exists() {
817                return p;
818            }
819        }
820    }
821    PathBuf::from("/nonexistent")
822}