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    ]
375}
376
377fn detect_claude_path() -> PathBuf {
378    if let Ok(output) = std::process::Command::new("which").arg("claude").output() {
379        if output.status.success() {
380            return PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
381        }
382    }
383    if let Some(home) = dirs::home_dir() {
384        let claude_json = home.join(".claude.json");
385        if claude_json.exists() {
386            return claude_json;
387        }
388    }
389    PathBuf::from("/nonexistent")
390}
391
392fn detect_codex_path(home: &std::path::Path) -> PathBuf {
393    let codex_dir = home.join(".codex");
394    if codex_dir.exists() {
395        return codex_dir;
396    }
397    if let Ok(output) = std::process::Command::new("which").arg("codex").output() {
398        if output.status.success() {
399            return codex_dir;
400        }
401    }
402    PathBuf::from("/nonexistent")
403}
404
405fn zed_settings_path(home: &std::path::Path) -> PathBuf {
406    home.join(".config/zed/settings.json")
407}
408
409fn zed_config_dir(home: &std::path::Path) -> PathBuf {
410    home.join(".config/zed")
411}
412
413fn write_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
414    if let Some(parent) = target.config_path.parent() {
415        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
416    }
417
418    match target.config_type {
419        ConfigType::McpJson => write_mcp_json(target, binary),
420        ConfigType::Zed => write_zed_config(target, binary),
421        ConfigType::Codex => write_codex_config(target, binary),
422        ConfigType::VsCodeMcp => write_vscode_mcp(target, binary),
423        ConfigType::OpenCode => write_opencode_config(target, binary),
424    }
425}
426
427fn lean_ctx_server_entry(binary: &str) -> serde_json::Value {
428    serde_json::json!({
429        "command": binary,
430        "autoApprove": [
431            "ctx_read", "ctx_shell", "ctx_search", "ctx_tree",
432            "ctx_overview", "ctx_compress", "ctx_metrics", "ctx_session",
433            "ctx_knowledge", "ctx_agent", "ctx_analyze", "ctx_benchmark",
434            "ctx_cache", "ctx_discover", "ctx_smart_read", "ctx_delta",
435            "ctx_dedup", "ctx_fill", "ctx_intent", "ctx_response",
436            "ctx_context", "ctx_graph", "ctx_wrapped", "ctx_multi_read",
437            "ctx_semantic_search", "ctx"
438        ]
439    })
440}
441
442fn write_mcp_json(target: &EditorTarget, binary: &str) -> Result<(), String> {
443    if target.config_path.exists() {
444        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
445
446        if content.contains("lean-ctx") {
447            return Ok(());
448        }
449
450        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
451            if let Some(obj) = json.as_object_mut() {
452                let servers = obj
453                    .entry("mcpServers")
454                    .or_insert_with(|| serde_json::json!({}));
455                if let Some(servers_obj) = servers.as_object_mut() {
456                    servers_obj.insert("lean-ctx".to_string(), lean_ctx_server_entry(binary));
457                }
458                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
459                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
460                return Ok(());
461            }
462        }
463        return Err(format!(
464            "Could not parse existing config at {}. Please add lean-ctx manually:\n\
465             Add to \"mcpServers\": \"lean-ctx\": {{ \"command\": \"{}\" }}",
466            target.config_path.display(),
467            binary
468        ));
469    }
470
471    let content = serde_json::to_string_pretty(&serde_json::json!({
472        "mcpServers": {
473            "lean-ctx": lean_ctx_server_entry(binary)
474        }
475    }))
476    .map_err(|e| e.to_string())?;
477
478    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
479}
480
481fn write_zed_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
482    if target.config_path.exists() {
483        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
484
485        if content.contains("lean-ctx") {
486            return Ok(());
487        }
488
489        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
490            if let Some(obj) = json.as_object_mut() {
491                let servers = obj
492                    .entry("context_servers")
493                    .or_insert_with(|| serde_json::json!({}));
494                if let Some(servers_obj) = servers.as_object_mut() {
495                    servers_obj.insert(
496                        "lean-ctx".to_string(),
497                        serde_json::json!({
498                            "source": "custom",
499                            "command": binary,
500                            "args": [],
501                            "env": {}
502                        }),
503                    );
504                }
505                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
506                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
507                return Ok(());
508            }
509        }
510        return Err(format!(
511            "Could not parse existing config at {}. Please add lean-ctx manually to \"context_servers\".",
512            target.config_path.display()
513        ));
514    }
515
516    let content = serde_json::to_string_pretty(&serde_json::json!({
517        "context_servers": {
518            "lean-ctx": {
519                "source": "custom",
520                "command": binary,
521                "args": [],
522                "env": {}
523            }
524        }
525    }))
526    .map_err(|e| e.to_string())?;
527
528    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
529}
530
531fn write_codex_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
532    if target.config_path.exists() {
533        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
534
535        if content.contains("lean-ctx") {
536            return Ok(());
537        }
538
539        let mut new_content = content.clone();
540        if !new_content.ends_with('\n') {
541            new_content.push('\n');
542        }
543        new_content.push_str(&format!(
544            "\n[mcp_servers.lean-ctx]\ncommand = \"{}\"\nargs = []\n",
545            binary
546        ));
547        std::fs::write(&target.config_path, new_content).map_err(|e| e.to_string())?;
548        return Ok(());
549    }
550
551    let content = format!(
552        "[mcp_servers.lean-ctx]\ncommand = \"{}\"\nargs = []\n",
553        binary
554    );
555    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
556}
557
558fn write_vscode_mcp(target: &EditorTarget, binary: &str) -> Result<(), String> {
559    if target.config_path.exists() {
560        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
561        if content.contains("lean-ctx") {
562            return Ok(());
563        }
564        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
565            if let Some(obj) = json.as_object_mut() {
566                let servers = obj
567                    .entry("servers")
568                    .or_insert_with(|| serde_json::json!({}));
569                if let Some(servers_obj) = servers.as_object_mut() {
570                    servers_obj.insert(
571                        "lean-ctx".to_string(),
572                        serde_json::json!({ "command": binary, "args": [] }),
573                    );
574                }
575                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
576                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
577                return Ok(());
578            }
579        }
580        return Err(format!(
581            "Could not parse existing config at {}. Please add lean-ctx manually to \"servers\".",
582            target.config_path.display()
583        ));
584    }
585
586    if let Some(parent) = target.config_path.parent() {
587        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
588    }
589
590    let content = serde_json::to_string_pretty(&serde_json::json!({
591        "servers": {
592            "lean-ctx": {
593                "command": binary,
594                "args": []
595            }
596        }
597    }))
598    .map_err(|e| e.to_string())?;
599
600    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
601}
602
603fn write_opencode_config(target: &EditorTarget, binary: &str) -> Result<(), String> {
604    if target.config_path.exists() {
605        let content = std::fs::read_to_string(&target.config_path).map_err(|e| e.to_string())?;
606        if content.contains("lean-ctx") {
607            return Ok(());
608        }
609        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
610            if let Some(obj) = json.as_object_mut() {
611                let mcp = obj.entry("mcp").or_insert_with(|| serde_json::json!({}));
612                if let Some(mcp_obj) = mcp.as_object_mut() {
613                    mcp_obj.insert(
614                        "lean-ctx".to_string(),
615                        serde_json::json!({
616                            "type": "local",
617                            "command": [binary],
618                            "enabled": true
619                        }),
620                    );
621                }
622                let formatted = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
623                std::fs::write(&target.config_path, formatted).map_err(|e| e.to_string())?;
624                return Ok(());
625            }
626        }
627        return Err(format!(
628            "Could not parse existing config at {}. Please add lean-ctx manually:\n\
629             Add to the \"mcp\" section: \"lean-ctx\": {{ \"type\": \"local\", \"command\": [\"{}\"], \"enabled\": true }}",
630            target.config_path.display(),
631            binary
632        ));
633    }
634
635    if let Some(parent) = target.config_path.parent() {
636        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
637    }
638
639    let content = serde_json::to_string_pretty(&serde_json::json!({
640        "$schema": "https://opencode.ai/config.json",
641        "mcp": {
642            "lean-ctx": {
643                "type": "local",
644                "command": [binary],
645                "enabled": true
646            }
647        }
648    }))
649    .map_err(|e| e.to_string())?;
650
651    std::fs::write(&target.config_path, content).map_err(|e| e.to_string())
652}
653
654fn detect_vscode_path() -> PathBuf {
655    #[cfg(target_os = "macos")]
656    {
657        if let Some(home) = dirs::home_dir() {
658            let vscode = home.join("Library/Application Support/Code/User/settings.json");
659            if vscode.exists() {
660                return vscode;
661            }
662        }
663    }
664    #[cfg(target_os = "linux")]
665    {
666        if let Some(home) = dirs::home_dir() {
667            let vscode = home.join(".config/Code/User/settings.json");
668            if vscode.exists() {
669                return vscode;
670            }
671        }
672    }
673    #[cfg(target_os = "windows")]
674    {
675        if let Ok(appdata) = std::env::var("APPDATA") {
676            let vscode = PathBuf::from(appdata).join("Code/User/settings.json");
677            if vscode.exists() {
678                return vscode;
679            }
680        }
681    }
682    if let Ok(output) = std::process::Command::new("which").arg("code").output() {
683        if output.status.success() {
684            return PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
685        }
686    }
687    PathBuf::from("/nonexistent")
688}
689
690fn vscode_mcp_path() -> PathBuf {
691    if let Some(home) = dirs::home_dir() {
692        #[cfg(target_os = "macos")]
693        {
694            return home.join("Library/Application Support/Code/User/mcp.json");
695        }
696        #[cfg(target_os = "linux")]
697        {
698            return home.join(".config/Code/User/mcp.json");
699        }
700        #[cfg(target_os = "windows")]
701        {
702            if let Ok(appdata) = std::env::var("APPDATA") {
703                return PathBuf::from(appdata).join("Code/User/mcp.json");
704            }
705        }
706        #[allow(unreachable_code)]
707        home.join(".config/Code/User/mcp.json")
708    } else {
709        PathBuf::from("/nonexistent")
710    }
711}
712
713fn detect_jetbrains_path(home: &std::path::Path) -> PathBuf {
714    #[cfg(target_os = "macos")]
715    {
716        let lib = home.join("Library/Application Support/JetBrains");
717        if lib.exists() {
718            return lib;
719        }
720    }
721    #[cfg(target_os = "linux")]
722    {
723        let cfg = home.join(".config/JetBrains");
724        if cfg.exists() {
725            return cfg;
726        }
727    }
728    if home.join(".jb-mcp.json").exists() {
729        return home.join(".jb-mcp.json");
730    }
731    PathBuf::from("/nonexistent")
732}
733
734fn cline_mcp_path() -> PathBuf {
735    if let Some(home) = dirs::home_dir() {
736        #[cfg(target_os = "macos")]
737        {
738            return home.join("Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
739        }
740        #[cfg(target_os = "linux")]
741        {
742            return home.join(".config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
743        }
744        #[cfg(target_os = "windows")]
745        {
746            if let Ok(appdata) = std::env::var("APPDATA") {
747                return PathBuf::from(appdata).join("Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
748            }
749        }
750    }
751    PathBuf::from("/nonexistent")
752}
753
754fn detect_cline_path() -> PathBuf {
755    if let Some(home) = dirs::home_dir() {
756        #[cfg(target_os = "macos")]
757        {
758            let p = home
759                .join("Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev");
760            if p.exists() {
761                return p;
762            }
763        }
764        #[cfg(target_os = "linux")]
765        {
766            let p = home.join(".config/Code/User/globalStorage/saoudrizwan.claude-dev");
767            if p.exists() {
768                return p;
769            }
770        }
771    }
772    PathBuf::from("/nonexistent")
773}
774
775fn roo_mcp_path() -> PathBuf {
776    if let Some(home) = dirs::home_dir() {
777        #[cfg(target_os = "macos")]
778        {
779            return home.join("Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
780        }
781        #[cfg(target_os = "linux")]
782        {
783            return home.join(".config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
784        }
785        #[cfg(target_os = "windows")]
786        {
787            if let Ok(appdata) = std::env::var("APPDATA") {
788                return PathBuf::from(appdata).join("Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
789            }
790        }
791    }
792    PathBuf::from("/nonexistent")
793}
794
795fn detect_roo_path() -> PathBuf {
796    if let Some(home) = dirs::home_dir() {
797        #[cfg(target_os = "macos")]
798        {
799            let p = home.join(
800                "Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline",
801            );
802            if p.exists() {
803                return p;
804            }
805        }
806        #[cfg(target_os = "linux")]
807        {
808            let p = home.join(".config/Code/User/globalStorage/rooveterinaryinc.roo-cline");
809            if p.exists() {
810                return p;
811            }
812        }
813    }
814    PathBuf::from("/nonexistent")
815}