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 terminal_ui::print_step_header(1, 10, "Shell Hook");
79 crate::cli::cmd_init(&["--global".to_string()]);
80 crate::shell_hook::install_all(false);
81
82 terminal_ui::print_step_header(2, 10, "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 terminal_ui::print_step_header(3, 10, "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 terminal_ui::print_step_header(4, 10, "Agent Rules");
163 let rules_result = crate::rules_inject::inject_all_rules(&home);
164 for name in &rules_result.injected {
165 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
166 }
167 for name in &rules_result.updated {
168 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
169 }
170 for name in &rules_result.already {
171 terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
172 }
173 for err in &rules_result.errors {
174 terminal_ui::print_status_warn(err);
175 }
176 if rules_result.injected.is_empty()
177 && rules_result.updated.is_empty()
178 && rules_result.already.is_empty()
179 && rules_result.errors.is_empty()
180 {
181 terminal_ui::print_status_skip("No agent rules needed");
182 }
183
184 for target in &targets {
186 if !target.detect_path.exists() || target.agent_key.is_empty() {
187 continue;
188 }
189 let mode = recommend_hook_mode(&target.agent_key);
190 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
191 }
192
193 terminal_ui::print_step_header(5, 10, "API Proxy");
195 crate::proxy_setup::install_proxy_env(&home, crate::proxy_setup::default_port(), false);
196 println!();
197 println!(" \x1b[2mStart proxy for maximum token savings:\x1b[0m");
198 println!(" \x1b[1mlean-ctx proxy start\x1b[0m");
199 println!(" \x1b[2mEnable autostart:\x1b[0m");
200 println!(" \x1b[1mlean-ctx proxy start --autostart\x1b[0m");
201
202 terminal_ui::print_step_header(6, 10, "Skill Files");
204 let skill_result = install_skill_files(&home);
205 for (name, installed) in &skill_result {
206 if *installed {
207 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mSKILL.md installed\x1b[0m"));
208 } else {
209 terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"));
210 }
211 }
212 if skill_result.is_empty() {
213 terminal_ui::print_status_skip("No skill directories to install");
214 }
215
216 terminal_ui::print_step_header(7, 10, "Environment Check");
218 let lean_dir = home.join(".lean-ctx");
219 if lean_dir.exists() {
220 terminal_ui::print_status_ok("~/.lean-ctx/ ready");
221 } else {
222 let _ = std::fs::create_dir_all(&lean_dir);
223 terminal_ui::print_status_new("Created ~/.lean-ctx/");
224 }
225 crate::doctor::run_compact();
226
227 terminal_ui::print_step_header(8, 10, "Help Improve lean-ctx");
229 println!(" Share anonymous compression stats to make lean-ctx better.");
230 println!(" \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
231 println!();
232 print!(" Enable anonymous data sharing? \x1b[1m[y/N]\x1b[0m ");
233 use std::io::Write;
234 std::io::stdout().flush().ok();
235
236 let mut input = String::new();
237 let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
238 let answer = input.trim().to_lowercase();
239 answer == "y" || answer == "yes"
240 } else {
241 false
242 };
243
244 if contribute {
245 let config_dir = home.join(".lean-ctx");
246 let _ = std::fs::create_dir_all(&config_dir);
247 let config_path = config_dir.join("config.toml");
248 let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
249 if !config_content.contains("[cloud]") {
250 if !config_content.is_empty() && !config_content.ends_with('\n') {
251 config_content.push('\n');
252 }
253 config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
254 let _ = std::fs::write(&config_path, config_content);
255 }
256 terminal_ui::print_status_ok("Enabled — thank you!");
257 } else {
258 terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
259 }
260
261 terminal_ui::print_step_header(9, 10, "Premium Features");
263 configure_premium_features(&home);
264
265 terminal_ui::print_step_header(10, 10, "Code Intelligence");
267 let cwd = std::env::current_dir().ok();
268 let cwd_is_home = cwd
269 .as_ref()
270 .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
271 if cwd_is_home {
272 terminal_ui::print_status_warn(
273 "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
274 );
275 println!(
276 " \x1b[2mRun `lean-ctx setup` from inside a project for code intelligence.\x1b[0m"
277 );
278 } else {
279 let is_project = cwd.as_ref().is_some_and(|d| {
280 d.join(".git").exists()
281 || d.join("Cargo.toml").exists()
282 || d.join("package.json").exists()
283 || d.join("go.mod").exists()
284 });
285 if is_project {
286 println!(" \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
287 println!(" \x1b[2mand smart search fusion in the background...\x1b[0m");
288 if let Some(ref root) = cwd {
289 spawn_index_build_background(root);
290 }
291 terminal_ui::print_status_ok("Graph build started (background)");
292 } else {
293 println!(
294 " \x1b[2mRun `lean-ctx impact build` inside any git project to enable\x1b[0m"
295 );
296 println!(
297 " \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
298 );
299 }
300 }
301 println!();
302
303 {
305 let tools = crate::core::editor_registry::writers::auto_approve_tools();
306 println!();
307 println!(
308 " \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
309 tools.len()
310 );
311 for chunk in tools.chunks(6) {
312 let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
313 println!(" {}", names.join(", "));
314 }
315 println!(" \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
316 }
317
318 println!();
320 println!(
321 " \x1b[1;32m✓ Setup complete!\x1b[0m \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
322 newly_configured.len(),
323 already_configured.len(),
324 not_installed.len()
325 );
326
327 if !errors.is_empty() {
328 println!(
329 " \x1b[33m⚠ {} error{}: {}\x1b[0m",
330 errors.len(),
331 if errors.len() == 1 { "" } else { "s" },
332 errors.join(", ")
333 );
334 }
335
336 let shell = std::env::var("SHELL").unwrap_or_default();
338 let source_cmd = if shell.contains("zsh") {
339 "source ~/.zshrc"
340 } else if shell.contains("fish") {
341 "source ~/.config/fish/config.fish"
342 } else if shell.contains("bash") {
343 "source ~/.bashrc"
344 } else {
345 "Restart your shell"
346 };
347
348 let dim = "\x1b[2m";
349 let bold = "\x1b[1m";
350 let cyan = "\x1b[36m";
351 let yellow = "\x1b[33m";
352 let rst = "\x1b[0m";
353
354 println!();
355 println!(" {bold}Next steps:{rst}");
356 println!();
357 println!(" {cyan}1.{rst} Reload your shell:");
358 println!(" {bold}{source_cmd}{rst}");
359 println!();
360
361 let mut tools_to_restart: Vec<String> = newly_configured
362 .iter()
363 .map(std::string::ToString::to_string)
364 .collect();
365 for name in rules_result
366 .injected
367 .iter()
368 .chain(rules_result.updated.iter())
369 {
370 if !tools_to_restart.iter().any(|t| t == name) {
371 tools_to_restart.push(name.clone());
372 }
373 }
374
375 if !tools_to_restart.is_empty() {
376 println!(" {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
377 println!(" {bold}{}{rst}", tools_to_restart.join(", "));
378 println!(
379 " {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
380 );
381 println!(" {dim}Close and re-open the application completely.{rst}");
382 } else if !already_configured.is_empty() {
383 println!(
384 " {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
385 );
386 }
387
388 println!();
389 println!(
390 " {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
391 );
392 println!(" {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
393
394 println!();
396 terminal_ui::print_logo_animated();
397 terminal_ui::print_command_box();
398}
399
400#[derive(Debug, Clone, Copy, Default)]
401pub struct SetupOptions {
402 pub non_interactive: bool,
403 pub yes: bool,
404 pub fix: bool,
405 pub json: bool,
406 pub no_auto_approve: bool,
407}
408
409pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
410 let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
411 let started_at = Utc::now();
412 let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
413 let binary = resolve_portable_binary();
414 let home_str = home.to_string_lossy().to_string();
415
416 let mut steps: Vec<SetupStepReport> = Vec::new();
417
418 let mut shell_step = SetupStepReport {
420 name: "shell_hook".to_string(),
421 ok: true,
422 items: Vec::new(),
423 warnings: Vec::new(),
424 errors: Vec::new(),
425 };
426 if !opts.non_interactive || opts.yes {
427 if opts.json {
428 crate::cli::cmd_init_quiet(&["--global".to_string()]);
429 } else {
430 crate::cli::cmd_init(&["--global".to_string()]);
431 }
432 crate::shell_hook::install_all(opts.json);
433 #[cfg(not(windows))]
434 {
435 let hook_content = crate::cli::generate_hook_posix(&binary);
436 if crate::shell::is_container() {
437 crate::cli::write_env_sh_for_containers(&hook_content);
438 shell_step.items.push(SetupItem {
439 name: "env_sh".to_string(),
440 status: "created".to_string(),
441 path: Some("~/.lean-ctx/env.sh".to_string()),
442 note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
443 });
444 } else {
445 shell_step.items.push(SetupItem {
446 name: "env_sh".to_string(),
447 status: "skipped".to_string(),
448 path: None,
449 note: Some("not a container environment".to_string()),
450 });
451 }
452 }
453 shell_step.items.push(SetupItem {
454 name: "init --global".to_string(),
455 status: "ran".to_string(),
456 path: None,
457 note: None,
458 });
459 shell_step.items.push(SetupItem {
460 name: "universal_shell_hook".to_string(),
461 status: "installed".to_string(),
462 path: None,
463 note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
464 });
465 } else {
466 shell_step
467 .warnings
468 .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
469 shell_step.ok = false;
470 shell_step.items.push(SetupItem {
471 name: "init --global".to_string(),
472 status: "skipped".to_string(),
473 path: None,
474 note: Some("requires --yes in --non-interactive mode".to_string()),
475 });
476 }
477 steps.push(shell_step);
478
479 let mut daemon_step = SetupStepReport {
481 name: "daemon".to_string(),
482 ok: true,
483 items: Vec::new(),
484 warnings: Vec::new(),
485 errors: Vec::new(),
486 };
487 {
488 let was_running = crate::daemon::is_daemon_running();
489 if was_running {
490 let _ = crate::daemon::stop_daemon();
491 std::thread::sleep(std::time::Duration::from_millis(500));
492 }
493 match crate::daemon::start_daemon(&[]) {
494 Ok(()) => {
495 let action = if was_running { "restarted" } else { "started" };
496 daemon_step.items.push(SetupItem {
497 name: "serve --daemon".to_string(),
498 status: action.to_string(),
499 path: Some(crate::daemon::daemon_addr().display()),
500 note: Some("CLI commands can route via IPC when running".to_string()),
501 });
502 }
503 Err(e) => {
504 daemon_step
505 .warnings
506 .push(format!("daemon start failed (non-fatal): {e}"));
507 daemon_step.items.push(SetupItem {
508 name: "serve --daemon".to_string(),
509 status: "skipped".to_string(),
510 path: None,
511 note: Some(format!("optional — {e}")),
512 });
513 }
514 }
515 }
516 steps.push(daemon_step);
517
518 let mut editor_step = SetupStepReport {
520 name: "editors".to_string(),
521 ok: true,
522 items: Vec::new(),
523 warnings: Vec::new(),
524 errors: Vec::new(),
525 };
526
527 let targets = crate::core::editor_registry::build_targets(&home);
528 for target in &targets {
529 let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
530 if !target.detect_path.exists() {
531 editor_step.items.push(SetupItem {
532 name: target.name.to_string(),
533 status: "not_detected".to_string(),
534 path: Some(short_path),
535 note: None,
536 });
537 continue;
538 }
539
540 let mode = if target.agent_key.is_empty() {
541 HookMode::Mcp
542 } else {
543 recommend_hook_mode(&target.agent_key)
544 };
545
546 let res = crate::core::editor_registry::write_config_with_options(
547 target,
548 &binary,
549 WriteOptions {
550 overwrite_invalid: opts.fix,
551 },
552 );
553 match res {
554 Ok(w) => {
555 let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
556 .into_iter()
557 .flatten()
558 .collect();
559 editor_step.items.push(SetupItem {
560 name: target.name.to_string(),
561 status: match w.action {
562 WriteAction::Created => "created".to_string(),
563 WriteAction::Updated => "updated".to_string(),
564 WriteAction::Already => "already".to_string(),
565 },
566 path: Some(short_path),
567 note: Some(note_parts.join("; ")),
568 });
569 }
570 Err(e) => {
571 editor_step.ok = false;
572 editor_step.items.push(SetupItem {
573 name: target.name.to_string(),
574 status: "error".to_string(),
575 path: Some(short_path),
576 note: Some(e),
577 });
578 }
579 }
580 }
581 steps.push(editor_step);
582
583 let mut rules_step = SetupStepReport {
585 name: "agent_rules".to_string(),
586 ok: true,
587 items: Vec::new(),
588 warnings: Vec::new(),
589 errors: Vec::new(),
590 };
591 let rules_result = crate::rules_inject::inject_all_rules(&home);
592 for n in rules_result.injected {
593 rules_step.items.push(SetupItem {
594 name: n,
595 status: "injected".to_string(),
596 path: None,
597 note: None,
598 });
599 }
600 for n in rules_result.updated {
601 rules_step.items.push(SetupItem {
602 name: n,
603 status: "updated".to_string(),
604 path: None,
605 note: None,
606 });
607 }
608 for n in rules_result.already {
609 rules_step.items.push(SetupItem {
610 name: n,
611 status: "already".to_string(),
612 path: None,
613 note: None,
614 });
615 }
616 for e in rules_result.errors {
617 rules_step.ok = false;
618 rules_step.errors.push(e);
619 }
620 steps.push(rules_step);
621
622 let mut skill_step = SetupStepReport {
624 name: "skill_files".to_string(),
625 ok: true,
626 items: Vec::new(),
627 warnings: Vec::new(),
628 errors: Vec::new(),
629 };
630 let skill_results = crate::rules_inject::install_all_skills(&home);
631 for (name, is_new) in &skill_results {
632 skill_step.items.push(SetupItem {
633 name: name.clone(),
634 status: if *is_new { "installed" } else { "already" }.to_string(),
635 path: None,
636 note: Some("SKILL.md".to_string()),
637 });
638 }
639 if !skill_step.items.is_empty() {
640 steps.push(skill_step);
641 }
642
643 let mut hooks_step = SetupStepReport {
645 name: "agent_hooks".to_string(),
646 ok: true,
647 items: Vec::new(),
648 warnings: Vec::new(),
649 errors: Vec::new(),
650 };
651 for target in &targets {
652 if !target.detect_path.exists() || target.agent_key.is_empty() {
653 continue;
654 }
655 let mode = recommend_hook_mode(&target.agent_key);
656 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
657 hooks_step.items.push(SetupItem {
658 name: format!("{} hooks", target.name),
659 status: "installed".to_string(),
660 path: Some(target.detect_path.to_string_lossy().to_string()),
661 note: Some(format!(
662 "mode={mode}; merge-based install/repair (preserves other hooks/plugins)"
663 )),
664 });
665 }
666 if !hooks_step.items.is_empty() {
667 steps.push(hooks_step);
668 }
669
670 let mut proxy_step = SetupStepReport {
672 name: "proxy_env".to_string(),
673 ok: true,
674 items: Vec::new(),
675 warnings: Vec::new(),
676 errors: Vec::new(),
677 };
678 crate::proxy_setup::install_proxy_env(&home, crate::proxy_setup::default_port(), opts.json);
679 proxy_step.items.push(SetupItem {
680 name: "proxy_env".to_string(),
681 status: "configured".to_string(),
682 path: None,
683 note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
684 });
685 steps.push(proxy_step);
686
687 let mut env_step = SetupStepReport {
689 name: "doctor_compact".to_string(),
690 ok: true,
691 items: Vec::new(),
692 warnings: Vec::new(),
693 errors: Vec::new(),
694 };
695 let (passed, total) = crate::doctor::compact_score();
696 env_step.items.push(SetupItem {
697 name: "doctor".to_string(),
698 status: format!("{passed}/{total}"),
699 path: None,
700 note: None,
701 });
702 if passed != total {
703 env_step.warnings.push(format!(
704 "doctor compact not fully passing: {passed}/{total}"
705 ));
706 }
707 steps.push(env_step);
708
709 if let Ok(cwd) = std::env::current_dir() {
711 let is_project = cwd.join(".git").exists()
712 || cwd.join("Cargo.toml").exists()
713 || cwd.join("package.json").exists()
714 || cwd.join("go.mod").exists();
715 if is_project {
716 spawn_index_build_background(&cwd);
717 }
718 }
719
720 let finished_at = Utc::now();
721 let success = steps.iter().all(|s| s.ok);
722 let report = SetupReport {
723 schema_version: 1,
724 started_at,
725 finished_at,
726 success,
727 platform: PlatformInfo {
728 os: std::env::consts::OS.to_string(),
729 arch: std::env::consts::ARCH.to_string(),
730 },
731 steps,
732 warnings: Vec::new(),
733 errors: Vec::new(),
734 };
735
736 let path = SetupReport::default_path()?;
737 let mut content =
738 serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
739 content.push('\n');
740 crate::config_io::write_atomic(&path, &content)?;
741
742 Ok(report)
743}
744
745fn spawn_index_build_background(root: &std::path::Path) {
746 let root_str = crate::core::graph_index::normalize_project_root(&root.to_string_lossy());
747 if !crate::core::graph_index::is_safe_scan_root_public(&root_str) {
748 tracing::info!("[setup: skipping background graph build for unsafe root {root_str}]");
749 return;
750 }
751
752 let binary = std::env::current_exe().map_or_else(
753 |_| resolve_portable_binary(),
754 |p| p.to_string_lossy().to_string(),
755 );
756 let _ = std::process::Command::new(&binary)
757 .args(["index", "build-graph", "--root"])
758 .arg(root)
759 .stdout(std::process::Stdio::null())
760 .stderr(std::process::Stdio::null())
761 .stdin(std::process::Stdio::null())
762 .spawn();
763}
764
765pub fn configure_agent_mcp(agent: &str) -> Result<(), String> {
766 let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
767 let binary = resolve_portable_binary();
768
769 let targets = agent_mcp_targets(agent, &home)?;
770
771 for t in &targets {
772 crate::core::editor_registry::write_config_with_options(
773 t,
774 &binary,
775 WriteOptions {
776 overwrite_invalid: true,
777 },
778 )?;
779 }
780
781 if agent == "kiro" {
782 install_kiro_steering(&home);
783 }
784
785 Ok(())
786}
787
788fn agent_mcp_targets(agent: &str, home: &std::path::Path) -> Result<Vec<EditorTarget>, String> {
789 let mut targets = Vec::<EditorTarget>::new();
790
791 let push = |targets: &mut Vec<EditorTarget>,
792 name: &'static str,
793 config_path: PathBuf,
794 config_type: ConfigType| {
795 targets.push(EditorTarget {
796 name,
797 agent_key: agent.to_string(),
798 detect_path: PathBuf::from("/nonexistent"), config_path,
800 config_type,
801 });
802 };
803
804 let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
805
806 match agent {
807 "cursor" => push(
808 &mut targets,
809 "Cursor",
810 home.join(".cursor/mcp.json"),
811 ConfigType::McpJson,
812 ),
813 "claude" | "claude-code" => push(
814 &mut targets,
815 "Claude Code",
816 crate::core::editor_registry::claude_mcp_json_path(home),
817 ConfigType::McpJson,
818 ),
819 "windsurf" => push(
820 &mut targets,
821 "Windsurf",
822 home.join(".codeium/windsurf/mcp_config.json"),
823 ConfigType::McpJson,
824 ),
825 "codex" => {
826 let codex_dir =
827 crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
828 push(
829 &mut targets,
830 "Codex CLI",
831 codex_dir.join("config.toml"),
832 ConfigType::Codex,
833 );
834 }
835 "gemini" => {
836 push(
837 &mut targets,
838 "Gemini CLI",
839 home.join(".gemini/settings.json"),
840 ConfigType::GeminiSettings,
841 );
842 push(
843 &mut targets,
844 "Antigravity",
845 home.join(".gemini/antigravity/mcp_config.json"),
846 ConfigType::McpJson,
847 );
848 }
849 "antigravity" => push(
850 &mut targets,
851 "Antigravity",
852 home.join(".gemini/antigravity/mcp_config.json"),
853 ConfigType::McpJson,
854 ),
855 "copilot" => push(
856 &mut targets,
857 "VS Code / Copilot",
858 crate::core::editor_registry::vscode_mcp_path(),
859 ConfigType::VsCodeMcp,
860 ),
861 "crush" => push(
862 &mut targets,
863 "Crush",
864 home.join(".config/crush/crush.json"),
865 ConfigType::Crush,
866 ),
867 "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
868 "qoder" => {
869 for path in crate::core::editor_registry::qoder_all_mcp_paths(home) {
870 push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
871 }
872 }
873 "qoderwork" => push(
874 &mut targets,
875 "QoderWork",
876 crate::core::editor_registry::qoderwork_mcp_path(home),
877 ConfigType::McpJson,
878 ),
879 "cline" => push(
880 &mut targets,
881 "Cline",
882 crate::core::editor_registry::cline_mcp_path(),
883 ConfigType::McpJson,
884 ),
885 "roo" => push(
886 &mut targets,
887 "Roo Code",
888 crate::core::editor_registry::roo_mcp_path(),
889 ConfigType::McpJson,
890 ),
891 "kiro" => push(
892 &mut targets,
893 "AWS Kiro",
894 home.join(".kiro/settings/mcp.json"),
895 ConfigType::McpJson,
896 ),
897 "verdent" => push(
898 &mut targets,
899 "Verdent",
900 home.join(".verdent/mcp.json"),
901 ConfigType::McpJson,
902 ),
903 "jetbrains" | "amp" => {
904 }
906 "qwen" => push(
907 &mut targets,
908 "Qwen Code",
909 home.join(".qwen/settings.json"),
910 ConfigType::McpJson,
911 ),
912 "trae" => push(
913 &mut targets,
914 "Trae",
915 home.join(".trae/mcp.json"),
916 ConfigType::McpJson,
917 ),
918 "amazonq" => push(
919 &mut targets,
920 "Amazon Q Developer",
921 home.join(".aws/amazonq/default.json"),
922 ConfigType::McpJson,
923 ),
924 "opencode" => {
925 #[cfg(windows)]
926 let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
927 std::path::PathBuf::from(appdata)
928 .join("opencode")
929 .join("opencode.json")
930 } else {
931 home.join(".config/opencode/opencode.json")
932 };
933 #[cfg(not(windows))]
934 let opencode_path = home.join(".config/opencode/opencode.json");
935 push(
936 &mut targets,
937 "OpenCode",
938 opencode_path,
939 ConfigType::OpenCode,
940 );
941 }
942 "hermes" => push(
943 &mut targets,
944 "Hermes Agent",
945 home.join(".hermes/config.yaml"),
946 ConfigType::HermesYaml,
947 ),
948 "vscode" => push(
949 &mut targets,
950 "VS Code",
951 crate::core::editor_registry::vscode_mcp_path(),
952 ConfigType::VsCodeMcp,
953 ),
954 "zed" => push(
955 &mut targets,
956 "Zed",
957 crate::core::editor_registry::zed_settings_path(home),
958 ConfigType::Zed,
959 ),
960 "aider" => push(
961 &mut targets,
962 "Aider",
963 home.join(".aider/mcp.json"),
964 ConfigType::McpJson,
965 ),
966 "continue" => push(
967 &mut targets,
968 "Continue",
969 home.join(".continue/mcp.json"),
970 ConfigType::McpJson,
971 ),
972 "neovim" => push(
973 &mut targets,
974 "Neovim (mcphub.nvim)",
975 home.join(".config/mcphub/servers.json"),
976 ConfigType::McpJson,
977 ),
978 "emacs" => push(
979 &mut targets,
980 "Emacs (mcp.el)",
981 home.join(".emacs.d/mcp.json"),
982 ConfigType::McpJson,
983 ),
984 "sublime" => push(
985 &mut targets,
986 "Sublime Text",
987 home.join(".config/sublime-text/mcp.json"),
988 ConfigType::McpJson,
989 ),
990 _ => {
991 return Err(format!("Unknown agent '{agent}'"));
992 }
993 }
994
995 Ok(targets)
996}
997
998pub fn disable_agent_mcp(agent: &str, overwrite_invalid: bool) -> Result<(), String> {
999 let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
1000
1001 let mut targets = Vec::<EditorTarget>::new();
1002
1003 let push = |targets: &mut Vec<EditorTarget>,
1004 name: &'static str,
1005 config_path: PathBuf,
1006 config_type: ConfigType| {
1007 targets.push(EditorTarget {
1008 name,
1009 agent_key: agent.to_string(),
1010 detect_path: PathBuf::from("/nonexistent"),
1011 config_path,
1012 config_type,
1013 });
1014 };
1015
1016 let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
1017
1018 match agent {
1019 "cursor" => push(
1020 &mut targets,
1021 "Cursor",
1022 home.join(".cursor/mcp.json"),
1023 ConfigType::McpJson,
1024 ),
1025 "claude" | "claude-code" => push(
1026 &mut targets,
1027 "Claude Code",
1028 crate::core::editor_registry::claude_mcp_json_path(&home),
1029 ConfigType::McpJson,
1030 ),
1031 "windsurf" => push(
1032 &mut targets,
1033 "Windsurf",
1034 home.join(".codeium/windsurf/mcp_config.json"),
1035 ConfigType::McpJson,
1036 ),
1037 "codex" => {
1038 let codex_dir =
1039 crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
1040 push(
1041 &mut targets,
1042 "Codex CLI",
1043 codex_dir.join("config.toml"),
1044 ConfigType::Codex,
1045 );
1046 }
1047 "gemini" => {
1048 push(
1049 &mut targets,
1050 "Gemini CLI",
1051 home.join(".gemini/settings.json"),
1052 ConfigType::GeminiSettings,
1053 );
1054 push(
1055 &mut targets,
1056 "Antigravity",
1057 home.join(".gemini/antigravity/mcp_config.json"),
1058 ConfigType::McpJson,
1059 );
1060 }
1061 "antigravity" => push(
1062 &mut targets,
1063 "Antigravity",
1064 home.join(".gemini/antigravity/mcp_config.json"),
1065 ConfigType::McpJson,
1066 ),
1067 "copilot" => push(
1068 &mut targets,
1069 "VS Code / Copilot",
1070 crate::core::editor_registry::vscode_mcp_path(),
1071 ConfigType::VsCodeMcp,
1072 ),
1073 "crush" => push(
1074 &mut targets,
1075 "Crush",
1076 home.join(".config/crush/crush.json"),
1077 ConfigType::Crush,
1078 ),
1079 "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
1080 "qoder" => {
1081 for path in crate::core::editor_registry::qoder_all_mcp_paths(&home) {
1082 push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
1083 }
1084 }
1085 "qoderwork" => push(
1086 &mut targets,
1087 "QoderWork",
1088 crate::core::editor_registry::qoderwork_mcp_path(&home),
1089 ConfigType::McpJson,
1090 ),
1091 "cline" => push(
1092 &mut targets,
1093 "Cline",
1094 crate::core::editor_registry::cline_mcp_path(),
1095 ConfigType::McpJson,
1096 ),
1097 "roo" => push(
1098 &mut targets,
1099 "Roo Code",
1100 crate::core::editor_registry::roo_mcp_path(),
1101 ConfigType::McpJson,
1102 ),
1103 "kiro" => push(
1104 &mut targets,
1105 "AWS Kiro",
1106 home.join(".kiro/settings/mcp.json"),
1107 ConfigType::McpJson,
1108 ),
1109 "verdent" => push(
1110 &mut targets,
1111 "Verdent",
1112 home.join(".verdent/mcp.json"),
1113 ConfigType::McpJson,
1114 ),
1115 "jetbrains" | "amp" => {
1116 }
1118 "qwen" => push(
1119 &mut targets,
1120 "Qwen Code",
1121 home.join(".qwen/settings.json"),
1122 ConfigType::McpJson,
1123 ),
1124 "trae" => push(
1125 &mut targets,
1126 "Trae",
1127 home.join(".trae/mcp.json"),
1128 ConfigType::McpJson,
1129 ),
1130 "amazonq" => push(
1131 &mut targets,
1132 "Amazon Q Developer",
1133 home.join(".aws/amazonq/default.json"),
1134 ConfigType::McpJson,
1135 ),
1136 "opencode" => {
1137 #[cfg(windows)]
1138 let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
1139 std::path::PathBuf::from(appdata)
1140 .join("opencode")
1141 .join("opencode.json")
1142 } else {
1143 home.join(".config/opencode/opencode.json")
1144 };
1145 #[cfg(not(windows))]
1146 let opencode_path = home.join(".config/opencode/opencode.json");
1147 push(
1148 &mut targets,
1149 "OpenCode",
1150 opencode_path,
1151 ConfigType::OpenCode,
1152 );
1153 }
1154 "hermes" => push(
1155 &mut targets,
1156 "Hermes Agent",
1157 home.join(".hermes/config.yaml"),
1158 ConfigType::HermesYaml,
1159 ),
1160 "vscode" => push(
1161 &mut targets,
1162 "VS Code",
1163 crate::core::editor_registry::vscode_mcp_path(),
1164 ConfigType::VsCodeMcp,
1165 ),
1166 "zed" => push(
1167 &mut targets,
1168 "Zed",
1169 crate::core::editor_registry::zed_settings_path(&home),
1170 ConfigType::Zed,
1171 ),
1172 "aider" => push(
1173 &mut targets,
1174 "Aider",
1175 home.join(".aider/mcp.json"),
1176 ConfigType::McpJson,
1177 ),
1178 "continue" => push(
1179 &mut targets,
1180 "Continue",
1181 home.join(".continue/mcp.json"),
1182 ConfigType::McpJson,
1183 ),
1184 "neovim" => push(
1185 &mut targets,
1186 "Neovim (mcphub.nvim)",
1187 home.join(".config/mcphub/servers.json"),
1188 ConfigType::McpJson,
1189 ),
1190 "emacs" => push(
1191 &mut targets,
1192 "Emacs (mcp.el)",
1193 home.join(".emacs.d/mcp.json"),
1194 ConfigType::McpJson,
1195 ),
1196 "sublime" => push(
1197 &mut targets,
1198 "Sublime Text",
1199 home.join(".config/sublime-text/mcp.json"),
1200 ConfigType::McpJson,
1201 ),
1202 _ => {
1203 return Err(format!("Unknown agent '{agent}'"));
1204 }
1205 }
1206
1207 for t in &targets {
1208 crate::core::editor_registry::remove_lean_ctx_server(
1209 t,
1210 WriteOptions { overwrite_invalid },
1211 )?;
1212 }
1213
1214 Ok(())
1215}
1216
1217pub fn install_skill_files(home: &std::path::Path) -> Vec<(String, bool)> {
1218 crate::rules_inject::install_all_skills(home)
1219}
1220
1221fn install_kiro_steering(home: &std::path::Path) {
1222 let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
1223 let steering_dir = cwd.join(".kiro").join("steering");
1224 let steering_file = steering_dir.join("lean-ctx.md");
1225
1226 if steering_file.exists()
1227 && std::fs::read_to_string(&steering_file)
1228 .unwrap_or_default()
1229 .contains("lean-ctx")
1230 {
1231 println!(" Kiro steering file already exists at .kiro/steering/lean-ctx.md");
1232 return;
1233 }
1234
1235 let _ = std::fs::create_dir_all(&steering_dir);
1236 let _ = std::fs::write(&steering_file, crate::hooks::KIRO_STEERING_TEMPLATE);
1237 println!(" \x1b[32m✓\x1b[0m Created .kiro/steering/lean-ctx.md (Kiro will now prefer lean-ctx tools)");
1238}
1239
1240fn shorten_path(path: &str, home: &str) -> String {
1241 if let Some(stripped) = path.strip_prefix(home) {
1242 format!("~{stripped}")
1243 } else {
1244 path.to_string()
1245 }
1246}
1247
1248fn upsert_toml_key(content: &mut String, key: &str, value: &str) {
1249 let pattern = format!("{key} = ");
1250 if let Some(start) = content.find(&pattern) {
1251 let line_end = content[start..]
1252 .find('\n')
1253 .map_or(content.len(), |p| start + p);
1254 content.replace_range(start..line_end, &format!("{key} = \"{value}\""));
1255 } else {
1256 if !content.is_empty() && !content.ends_with('\n') {
1257 content.push('\n');
1258 }
1259 content.push_str(&format!("{key} = \"{value}\"\n"));
1260 }
1261}
1262
1263fn remove_toml_key(content: &mut String, key: &str) {
1264 let pattern = format!("{key} = ");
1265 if let Some(start) = content.find(&pattern) {
1266 let line_end = content[start..]
1267 .find('\n')
1268 .map_or(content.len(), |p| start + p + 1);
1269 content.replace_range(start..line_end, "");
1270 }
1271}
1272
1273fn configure_premium_features(home: &std::path::Path) {
1274 use crate::terminal_ui;
1275 use std::io::Write;
1276
1277 let config_dir = home.join(".lean-ctx");
1278 let _ = std::fs::create_dir_all(&config_dir);
1279 let config_path = config_dir.join("config.toml");
1280 let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
1281
1282 let dim = "\x1b[2m";
1283 let bold = "\x1b[1m";
1284 let cyan = "\x1b[36m";
1285 let rst = "\x1b[0m";
1286
1287 println!("\n {bold}Compression Level{rst} {dim}(controls all token optimization layers){rst}");
1289 println!(" {dim}Applies to tool output, agent prompts, and protocol mode.{rst}");
1290 println!();
1291 println!(" {cyan}off{rst} — No compression (full verbose output)");
1292 println!(" {cyan}lite{rst} — Light: concise output, basic terse filtering {dim}(~25% savings){rst}");
1293 println!(" {cyan}standard{rst} — Dense output + compact protocol + pattern-aware {dim}(~45% savings){rst}");
1294 println!(" {cyan}max{rst} — Expert mode: TDD protocol, all layers active {dim}(~65% savings){rst}");
1295 println!();
1296 print!(" Compression level? {bold}[off/lite/standard/max]{rst} {dim}(default: off){rst} ");
1297 std::io::stdout().flush().ok();
1298
1299 let mut level_input = String::new();
1300 let level = if std::io::stdin().read_line(&mut level_input).is_ok() {
1301 match level_input.trim().to_lowercase().as_str() {
1302 "lite" => "lite",
1303 "standard" | "std" => "standard",
1304 "max" => "max",
1305 _ => "off",
1306 }
1307 } else {
1308 "off"
1309 };
1310
1311 let effective_level = if level != "off" {
1312 upsert_toml_key(&mut config_content, "compression_level", level);
1313 remove_toml_key(&mut config_content, "terse_agent");
1314 remove_toml_key(&mut config_content, "output_density");
1315 terminal_ui::print_status_ok(&format!("Compression: {level}"));
1316 crate::core::config::CompressionLevel::from_str_label(level)
1317 } else if config_content.contains("compression_level") {
1318 upsert_toml_key(&mut config_content, "compression_level", "off");
1319 terminal_ui::print_status_ok("Compression: off");
1320 Some(crate::core::config::CompressionLevel::Off)
1321 } else {
1322 terminal_ui::print_status_skip(
1323 "Compression: off (change later with: lean-ctx compression <level>)",
1324 );
1325 Some(crate::core::config::CompressionLevel::Off)
1326 };
1327
1328 if let Some(lvl) = effective_level {
1329 let n = crate::core::terse::rules_inject::inject(&lvl);
1330 if n > 0 {
1331 terminal_ui::print_status_ok(&format!(
1332 "Updated {n} rules file(s) with compression prompt"
1333 ));
1334 }
1335 }
1336
1337 println!(
1339 "\n {bold}Tool Result Archive{rst} {dim}(zero-loss: large outputs archived, retrievable via ctx_expand){rst}"
1340 );
1341 print!(" Enable auto-archive? {bold}[Y/n]{rst} ");
1342 std::io::stdout().flush().ok();
1343
1344 let mut archive_input = String::new();
1345 let archive_on = if std::io::stdin().read_line(&mut archive_input).is_ok() {
1346 let a = archive_input.trim().to_lowercase();
1347 a.is_empty() || a == "y" || a == "yes"
1348 } else {
1349 true
1350 };
1351
1352 if archive_on && !config_content.contains("[archive]") {
1353 if !config_content.is_empty() && !config_content.ends_with('\n') {
1354 config_content.push('\n');
1355 }
1356 config_content.push_str("\n[archive]\nenabled = true\n");
1357 terminal_ui::print_status_ok("Tool Result Archive: enabled");
1358 } else if !archive_on {
1359 terminal_ui::print_status_skip("Archive: off (enable later in config.toml)");
1360 }
1361
1362 let _ = std::fs::write(&config_path, config_content);
1363}
1364
1365#[cfg(all(test, target_os = "macos"))]
1366mod tests {
1367 use super::*;
1368
1369 #[test]
1370 #[cfg(target_os = "macos")]
1371 fn qoder_agent_targets_include_all_macos_mcp_locations() {
1372 let home = std::path::Path::new("/Users/tester");
1373 let targets = agent_mcp_targets("qoder", home).unwrap();
1374 let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1375
1376 assert_eq!(
1377 paths,
1378 vec![
1379 home.join(".qoder/mcp.json").as_path(),
1380 home.join("Library/Application Support/Qoder/User/mcp.json")
1381 .as_path(),
1382 home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1383 .as_path(),
1384 ]
1385 );
1386 assert!(targets
1387 .iter()
1388 .all(|t| t.config_type == ConfigType::QoderSettings));
1389 }
1390}