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::{HookMode, recommend_hook_mode};
7use chrono::Utc;
8use std::ffi::OsString;
9mod mcp;
10pub use mcp::*;
11mod helpers;
12pub use helpers::*;
13
14pub fn claude_config_json_path(home: &std::path::Path) -> PathBuf {
15 crate::core::editor_registry::claude_mcp_json_path(home)
16}
17
18pub fn claude_config_dir(home: &std::path::Path) -> PathBuf {
19 crate::core::editor_registry::claude_state_dir(home)
20}
21
22pub(crate) struct EnvVarGuard {
23 key: &'static str,
24 previous: Option<OsString>,
25}
26
27impl EnvVarGuard {
28 pub(crate) fn set(key: &'static str, value: &str) -> Self {
29 let previous = std::env::var_os(key);
30 unsafe { std::env::set_var(key, value) };
34 Self { key, previous }
35 }
36}
37
38impl Drop for EnvVarGuard {
39 fn drop(&mut self) {
40 if let Some(previous) = &self.previous {
41 unsafe { std::env::set_var(self.key, previous) };
44 } else {
45 unsafe { std::env::remove_var(self.key) };
48 }
49 }
50}
51
52fn first_run_setup_level() -> (bool, bool) {
55 use std::io::Write;
56
57 let cfg = crate::core::config::Config::load();
58 if cfg.setup.auto_inject_rules.is_some() {
59 return (
60 cfg.setup.should_inject_rules(),
61 cfg.setup.should_inject_skills(),
62 );
63 }
64
65 println!();
66 println!(" \x1b[1mWelcome to lean-ctx!\x1b[0m");
67 println!();
68 println!(" lean-ctx compresses AI context by 60-99%, saving tokens and money.");
69 println!();
70 println!(" Choose your setup level:");
71 println!(
72 " \x1b[36m[1]\x1b[0m Minimal \x1b[2m— Just MCP tools, no config file changes (recommended)\x1b[0m"
73 );
74 println!(
75 " \x1b[36m[2]\x1b[0m Standard \x1b[2m— MCP tools + agent instructions for optimal mode selection\x1b[0m"
76 );
77 println!(
78 " \x1b[36m[3]\x1b[0m Full \x1b[2m— Everything (tools + rules + skills + shell hooks)\x1b[0m"
79 );
80 println!();
81 print!(" Your choice \x1b[1m[1]\x1b[0m: ");
82 std::io::stdout().flush().ok();
83
84 let mut input = String::new();
85 let choice = if std::io::stdin().read_line(&mut input).is_ok() {
86 input.trim().parse::<u8>().unwrap_or(1)
87 } else {
88 1
89 };
90
91 match choice {
92 3 => (true, true),
93 2 => (true, false),
94 _ => (false, false),
95 }
96}
97
98fn persist_setup_choice(inject_rules: bool, inject_skills: bool) {
100 if let Err(e) = crate::core::config::Config::update_global(|cfg| {
101 cfg.setup.auto_inject_rules = Some(inject_rules);
102 cfg.setup.auto_inject_skills = Some(inject_skills);
103 }) {
104 tracing::warn!("could not persist setup choice: {e}");
105 }
106}
107
108pub fn run_setup() {
109 use crate::terminal_ui;
110
111 if crate::shell::is_non_interactive() {
112 eprintln!("Non-interactive terminal detected (no TTY on stdin).");
113 eprintln!(
114 "Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)"
115 );
116 eprintln!();
117 let opts = SetupOptions {
118 non_interactive: true,
119 yes: true,
120 ..Default::default()
121 };
122 match run_setup_with_options(opts) {
123 Ok(report) => {
124 for w in &report.warnings {
125 tracing::warn!("{w}");
126 }
127 }
128 Err(e) => tracing::error!("Setup error: {e}"),
129 }
130 return;
131 }
132
133 let Some(home) = dirs::home_dir() else {
134 tracing::error!("Cannot determine home directory");
135 std::process::exit(1);
136 };
137
138 let binary = resolve_portable_binary();
139
140 let home_str = home.to_string_lossy().to_string();
141
142 terminal_ui::print_setup_header();
143
144 let (inject_rules, inject_skills) = first_run_setup_level();
145 persist_setup_choice(inject_rules, inject_skills);
146
147 terminal_ui::print_step_header(1, 12, "Shell Hook");
148 crate::cli::cmd_init(&["--global".to_string()]);
149 crate::shell_hook::install_all(false);
150
151 terminal_ui::print_step_header(2, 12, "Daemon");
152 if crate::daemon::is_daemon_running() {
153 terminal_ui::print_status_ok("Daemon running — restarting with current binary…");
154 let _ = crate::daemon::stop_daemon();
155 std::thread::sleep(std::time::Duration::from_millis(500));
156 if let Err(e) = crate::daemon::start_daemon(&[]) {
157 terminal_ui::print_status_warn(&format!("Daemon restart failed: {e}"));
158 }
159 } else if let Err(e) = crate::daemon::start_daemon(&[]) {
160 terminal_ui::print_status_warn(&format!("Daemon start failed: {e}"));
161 }
162
163 terminal_ui::print_step_header(3, 12, "AI Tool Detection");
164
165 let targets = crate::core::editor_registry::build_targets(&home);
166 let update_mcp = crate::core::config::Config::load()
170 .setup
171 .should_update_mcp();
172 let mut newly_configured: Vec<&str> = Vec::new();
173 let mut already_configured: Vec<&str> = Vec::new();
174 let mut not_installed: Vec<&str> = Vec::new();
175 let mut mcp_skipped: Vec<&str> = Vec::new();
176 let mut errors: Vec<&str> = Vec::new();
177
178 for target in &targets {
179 let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
180
181 if !target.detect_path.exists() {
182 not_installed.push(target.name);
183 continue;
184 }
185
186 if !update_mcp {
187 terminal_ui::print_status_ok(&format!(
188 "{:<20} \x1b[2mMCP registration skipped (auto_update_mcp=false)\x1b[0m",
189 target.name
190 ));
191 mcp_skipped.push(target.name);
192 continue;
193 }
194
195 let mode = if target.agent_key.is_empty() {
196 HookMode::Mcp
197 } else {
198 recommend_hook_mode(&target.agent_key)
199 };
200
201 match crate::core::editor_registry::write_config_with_options(
202 target,
203 &binary,
204 WriteOptions {
205 overwrite_invalid: false,
206 },
207 ) {
208 Ok(res) if res.action == WriteAction::Already => {
209 terminal_ui::print_status_ok(&format!(
210 "{:<20} \x1b[36m{mode}\x1b[0m \x1b[2m{short_path}\x1b[0m",
211 target.name
212 ));
213 already_configured.push(target.name);
214 }
215 Ok(_) => {
216 terminal_ui::print_status_new(&format!(
217 "{:<20} \x1b[36m{mode}\x1b[0m \x1b[2m{short_path}\x1b[0m",
218 target.name
219 ));
220 newly_configured.push(target.name);
221 }
222 Err(e) => {
223 terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
224 errors.push(target.name);
225 }
226 }
227 }
228
229 let total_ok = newly_configured.len() + already_configured.len();
230 if total_ok == 0 && errors.is_empty() && mcp_skipped.is_empty() {
231 terminal_ui::print_status_warn(
232 "No AI tools detected. Install one and re-run: lean-ctx setup",
233 );
234 }
235
236 if !not_installed.is_empty() {
237 println!(
238 " \x1b[2m○ {} not detected: {}\x1b[0m",
239 not_installed.len(),
240 not_installed.join(", ")
241 );
242 }
243
244 configure_plan_mode_settings(&newly_configured, &already_configured);
245
246 terminal_ui::print_step_header(4, 12, "Agent Rules");
247 let rules_result = if inject_rules {
248 let r = crate::rules_inject::inject_all_rules(&home);
249 for name in &r.injected {
250 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
251 }
252 for name in &r.updated {
253 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
254 }
255 for name in &r.already {
256 terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
257 }
258 for err in &r.errors {
259 terminal_ui::print_status_warn(err);
260 }
261 if !r.backed_up.is_empty() {
262 for bak in &r.backed_up {
263 println!(" \x1b[2m ↳ backup: {bak}\x1b[0m");
264 }
265 }
266 if r.injected.is_empty()
267 && r.updated.is_empty()
268 && r.already.is_empty()
269 && r.errors.is_empty()
270 {
271 terminal_ui::print_status_skip("No agent rules needed");
272 }
273 r
274 } else {
275 terminal_ui::print_status_skip("Skipped (run `lean-ctx setup --inject-rules` to enable)");
276 crate::rules_inject::InjectResult::default()
277 };
278
279 for target in &targets {
280 if !target.detect_path.exists() || target.agent_key.is_empty() {
281 continue;
282 }
283 let mode = recommend_hook_mode(&target.agent_key);
284 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
285 }
286
287 terminal_ui::print_step_header(5, 12, "API Proxy (optional)");
288 {
289 let cfg = crate::core::config::Config::load();
290 let proxy_port = crate::proxy_setup::default_port();
291
292 match cfg.proxy_enabled {
293 Some(true) => {
294 crate::proxy_autostart::install(proxy_port, false);
295 std::thread::sleep(std::time::Duration::from_millis(500));
296 crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
297 terminal_ui::print_status_ok("Proxy active (opted in)");
298 }
299 Some(false) => {
300 terminal_ui::print_status_skip(
301 "Proxy disabled (run `lean-ctx proxy enable` to change)",
302 );
303 }
304 None => {
305 println!(
306 " \x1b[2mThe API proxy routes LLM requests through lean-ctx for additional\x1b[0m"
307 );
308 println!(
309 " \x1b[2mtool-result compression and precise token analytics in the dashboard.\x1b[0m"
310 );
311 println!();
312 println!(
313 " \x1b[2mWithout it: MCP tools, shell hooks, gain tracking, and memory\x1b[0m"
314 );
315 println!(
316 " \x1b[2mall work normally. The proxy adds ~5-15% extra savings on top.\x1b[0m"
317 );
318 println!();
319 print!(" Enable the API proxy? [y/N] ");
320 let _ = std::io::Write::flush(&mut std::io::stdout());
321 let mut input = String::new();
322 let _ = std::io::stdin().read_line(&mut input);
323 let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
324 if let Err(e) =
325 crate::core::config::Config::update_global(|c| c.proxy_enabled = Some(answer))
326 {
327 tracing::warn!("could not persist proxy choice: {e}");
328 }
329 if answer {
330 crate::proxy_autostart::install(proxy_port, false);
331 std::thread::sleep(std::time::Duration::from_millis(500));
332 crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
333 terminal_ui::print_status_new("Proxy enabled");
334 } else {
335 terminal_ui::print_status_skip(
336 "Proxy skipped (run `lean-ctx proxy enable` anytime)",
337 );
338 }
339 }
340 }
341 }
342
343 terminal_ui::print_step_header(6, 12, "Skill Files");
344 if inject_skills {
345 let skill_result = install_skill_files(&home);
346 for (name, installed) in &skill_result {
347 if *installed {
348 terminal_ui::print_status_new(&format!(
349 "{name:<20} \x1b[2mSKILL.md installed\x1b[0m"
350 ));
351 } else {
352 terminal_ui::print_status_ok(&format!(
353 "{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"
354 ));
355 }
356 }
357 if skill_result.is_empty() {
358 terminal_ui::print_status_skip("No skill directories to install");
359 }
360 } else {
361 terminal_ui::print_status_skip(
362 "Skipped (skill files install with the rules opt-in; choose Standard/Full in `lean-ctx setup`)",
363 );
364 }
365
366 terminal_ui::print_step_header(7, 12, "Environment Check");
367 let lean_dir = crate::core::data_dir::lean_ctx_data_dir()
368 .unwrap_or_else(|_| home.join(".config/lean-ctx"));
369 if lean_dir.exists() {
370 terminal_ui::print_status_ok(&format!("{} ready", lean_dir.display()));
371 } else {
372 let _ = std::fs::create_dir_all(&lean_dir);
373 terminal_ui::print_status_new(&format!("Created {}", lean_dir.display()));
374 }
375 if let Some(report) = crate::core::data_consolidate::consolidate()
376 && report.files_moved > 0
377 {
378 terminal_ui::print_status_new(&format!(
379 "Consolidated {} file(s) from a split data dir into {}",
380 report.files_moved,
381 report.canonical.display()
382 ));
383 }
384 crate::doctor::run_compact();
385
386 crate::core::layout_pin::heal();
389
390 terminal_ui::print_step_header(8, 12, "Help Improve lean-ctx");
391 println!(" Share anonymous compression stats to make lean-ctx better.");
392 println!(" \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
393 println!();
394 print!(" Enable anonymous data sharing? \x1b[1m[y/N]\x1b[0m ");
395 use std::io::Write;
396 std::io::stdout().flush().ok();
397
398 let mut input = String::new();
399 let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
400 let answer = input.trim().to_lowercase();
401 answer == "y" || answer == "yes"
402 } else {
403 false
404 };
405
406 if contribute {
407 let config_path = crate::core::config::Config::path()
408 .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
409 if let Some(dir) = config_path.parent() {
410 let _ = std::fs::create_dir_all(dir);
411 }
412 let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
413 if !config_content.contains("[cloud]") {
414 if !config_content.is_empty() && !config_content.ends_with('\n') {
415 config_content.push('\n');
416 }
417 config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
418 let _ = crate::config_io::write_atomic_with_backup(&config_path, &config_content);
419 }
420 terminal_ui::print_status_ok("Enabled — thank you!");
421 } else {
422 terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
423 }
424
425 terminal_ui::print_step_header(9, 12, "Auto-Updates");
426 println!(" Keep lean-ctx up to date automatically.");
427 println!(" \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
428 println!(
429 " \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
430 );
431 println!();
432 print!(" Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
433 std::io::stdout().flush().ok();
434
435 let mut auto_input = String::new();
436 let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
437 let answer = auto_input.trim().to_lowercase();
438 answer == "y" || answer == "yes"
439 } else {
440 false
441 };
442
443 if auto_update {
444 let cfg = crate::core::config::Config::load();
445 let hours = cfg.updates.check_interval_hours;
446 match crate::core::update_scheduler::install_schedule(hours) {
447 Ok(info) => {
448 crate::core::update_scheduler::set_auto_update(true, false, hours);
449 terminal_ui::print_status_ok(&format!("Enabled — {info}"));
450 }
451 Err(e) => {
452 terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
453 terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
454 }
455 }
456 } else {
457 crate::core::update_scheduler::set_auto_update(false, false, 6);
458 terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
459 }
460
461 terminal_ui::print_step_header(10, 12, "Tool Profile");
462 configure_tool_profile();
463
464 terminal_ui::print_step_header(11, 12, "Advanced Tuning (optional)");
465 configure_premium_features(&home);
466
467 terminal_ui::print_step_header(12, 12, "Code Intelligence");
468 let cwd = std::env::current_dir().ok();
469 let cwd_is_home = cwd
470 .as_ref()
471 .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
472 if cwd_is_home {
473 terminal_ui::print_status_warn(
474 "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
475 );
476 println!();
477 println!(" \x1b[1mSet a default project root to avoid this:\x1b[0m");
478 println!(" \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
479 print!(" \x1b[1m>\x1b[0m ");
480 use std::io::Write;
481 std::io::stdout().flush().ok();
482 let mut root_input = String::new();
483 if std::io::stdin().read_line(&mut root_input).is_ok() {
484 let root_trimmed = root_input.trim();
485 if root_trimmed.is_empty() {
486 terminal_ui::print_status_skip(
487 "No project root set. Set later: lean-ctx config set project_root /path/to/project",
488 );
489 } else {
490 let root_path = std::path::Path::new(root_trimmed);
491 if root_path.exists() && root_path.is_dir() {
492 let config_path = crate::core::config::Config::path()
493 .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
494 let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
495 if content.contains("project_root") {
496 if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
497 content = re
498 .replace(&content, &format!("project_root = \"{root_trimmed}\""))
499 .to_string();
500 }
501 } else {
502 if !content.is_empty() && !content.ends_with('\n') {
503 content.push('\n');
504 }
505 content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
506 }
507 let _ = crate::config_io::write_atomic_with_backup(&config_path, &content);
508 terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
509 if crate::core::pathutil::has_project_marker(root_path) {
510 spawn_index_build_background(root_path);
511 terminal_ui::print_status_ok("Graph build started (background)");
512 }
513 } else {
514 terminal_ui::print_status_warn(&format!(
515 "Path not found: {root_trimmed} — skipped"
516 ));
517 }
518 }
519 }
520 } else {
521 let is_project = cwd
522 .as_ref()
523 .is_some_and(|d| crate::core::pathutil::has_project_marker(d));
524 if is_project {
525 println!(" \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
526 println!(" \x1b[2mand smart search fusion in the background...\x1b[0m");
527 if let Some(ref root) = cwd {
528 spawn_index_build_background(root);
529 }
530 terminal_ui::print_status_ok("Graph build started (background)");
531 } else {
532 println!(" \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
533 println!(
534 " \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
535 );
536 }
537 }
538 println!();
539
540 {
541 let tools = crate::core::editor_registry::writers::auto_approve_tools();
542 println!();
543 println!(
544 " \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
545 tools.len()
546 );
547 for chunk in tools.chunks(6) {
548 let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
549 println!(" {}", names.join(", "));
550 }
551 println!(" \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
552 }
553
554 println!();
555 println!(
556 " \x1b[1;32m✓ Setup complete!\x1b[0m \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
557 newly_configured.len(),
558 already_configured.len(),
559 not_installed.len()
560 );
561
562 if !errors.is_empty() {
563 println!(
564 " \x1b[33m⚠ {} error{}: {}\x1b[0m",
565 errors.len(),
566 if errors.len() == 1 { "" } else { "s" },
567 errors.join(", ")
568 );
569 }
570
571 let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
572
573 let dim = "\x1b[2m";
574 let bold = "\x1b[1m";
575 let cyan = "\x1b[36m";
576 let yellow = "\x1b[33m";
577 let rst = "\x1b[0m";
578
579 println!();
580 println!(" {bold}Next steps:{rst}");
581 println!();
582 println!(" {cyan}1.{rst} Reload your shell:");
583 println!(" {bold}{source_cmd}{rst}");
584 println!();
585
586 let mut tools_to_restart: Vec<String> = newly_configured
587 .iter()
588 .map(std::string::ToString::to_string)
589 .collect();
590 for name in rules_result
591 .injected
592 .iter()
593 .chain(rules_result.updated.iter())
594 {
595 if !tools_to_restart.contains(name) {
596 tools_to_restart.push(name.clone());
597 }
598 }
599
600 if !tools_to_restart.is_empty() {
601 println!(" {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
602 println!(" {bold}{}{rst}", tools_to_restart.join(", "));
603 println!(
604 " {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
605 );
606 println!(" {dim}Close and re-open the application completely.{rst}");
607 } else if !already_configured.is_empty() {
608 println!(
609 " {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
610 );
611 }
612
613 println!();
614 println!(
615 " {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
616 );
617 println!(" {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
618
619 println!();
620 terminal_ui::print_logo_animated();
621 terminal_ui::print_command_box();
622
623 crate::cli::show_first_run_wow();
624}
625
626pub fn run_onboard() {
634 use crate::terminal_ui;
635
636 let dim = "\x1b[2m";
637 let bold = "\x1b[1m";
638 let cyan = "\x1b[36m";
639 let green = "\x1b[1;32m";
640 let yellow = "\x1b[33m";
641 let rst = "\x1b[0m";
642
643 println!();
644 println!(" {bold}Connecting lean-ctx to your AI tools…{rst}");
645 println!(
646 " {dim}No questions — using recommended defaults. Run `lean-ctx setup` for full control.{rst}"
647 );
648 println!();
649
650 let opts = SetupOptions {
651 non_interactive: true,
652 yes: true,
653 fix: true,
654 ..Default::default()
655 };
656
657 let report = match run_setup_with_options(opts) {
658 Ok(r) => r,
659 Err(e) => {
660 eprintln!(" {yellow}Onboarding could not complete: {e}{rst}");
661 eprintln!(" {dim}Try the guided setup instead: lean-ctx setup{rst}");
662 std::process::exit(1);
663 }
664 };
665
666 let connected: Vec<String> = report
667 .steps
668 .iter()
669 .find(|s| s.name == "editors")
670 .map(|s| {
671 s.items
672 .iter()
673 .filter(|i| matches!(i.status.as_str(), "created" | "updated" | "already"))
674 .map(|i| i.name.clone())
675 .collect()
676 })
677 .unwrap_or_default();
678
679 let data_dir = crate::core::data_dir::lean_ctx_data_dir()
680 .map_or_else(|_| "~/.lean-ctx".to_string(), |p| p.display().to_string());
681
682 println!();
683 if connected.is_empty() {
684 println!(" {yellow}No AI tools detected yet.{rst}");
685 println!(
686 " {dim}Install Cursor, Claude Code, VS Code, etc., then re-run: lean-ctx onboard{rst}"
687 );
688 } else {
689 println!(" {green}✓ lean-ctx is connected.{rst}");
690 println!();
691 println!(" {bold}Connected:{rst} {}", connected.join(", "));
692 }
693 println!(" {dim}Data dir:{rst} {data_dir}");
694
695 let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
696 println!();
697 println!(" {bold}One last step:{rst}");
698 println!(" {cyan}1.{rst} Reload your shell: {bold}{source_cmd}{rst}");
699 if !connected.is_empty() {
700 println!(
701 " {cyan}2.{rst} {yellow}Fully restart your AI tool{rst} {dim}(so it reconnects to lean-ctx){rst}"
702 );
703 println!(
704 " {cyan}3.{rst} Ask your AI to read a file — lean-ctx optimizes it automatically."
705 );
706 }
707 println!();
708 println!(
709 " {dim}Check anytime:{rst} {bold}lean-ctx doctor{rst} {dim}·{rst} {bold}lean-ctx gain{rst}"
710 );
711 println!();
712 terminal_ui::print_command_box();
713
714 crate::cli::show_first_run_wow();
715}
716
717#[derive(Debug, Clone, Copy, Default)]
718pub struct SetupOptions {
719 pub non_interactive: bool,
720 pub yes: bool,
721 pub fix: bool,
722 pub json: bool,
723 pub no_auto_approve: bool,
724 pub skip_proxy: bool,
725 pub skip_rules: bool,
726 pub force_inject_rules: bool,
728}
729
730pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
731 let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
732 let started_at = Utc::now();
733 let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
734 let binary = resolve_portable_binary();
735 let home_str = home.to_string_lossy().to_string();
736
737 crate::core::layout_pin::heal();
740
741 let mut steps: Vec<SetupStepReport> = Vec::new();
742
743 let mut shell_step = SetupStepReport {
745 name: "shell_hook".to_string(),
746 ok: true,
747 items: Vec::new(),
748 warnings: Vec::new(),
749 errors: Vec::new(),
750 };
751 if !opts.non_interactive || opts.yes {
752 if opts.json {
753 crate::cli::cmd_init_quiet(&["--global".to_string()]);
754 } else {
755 crate::cli::cmd_init(&["--global".to_string()]);
756 }
757 crate::shell_hook::install_all(opts.json);
758 #[cfg(not(windows))]
759 {
760 let hook_content = crate::cli::generate_hook_posix(&binary);
761 if crate::shell::is_container() {
762 crate::cli::write_env_sh_for_containers(&hook_content);
763 shell_step.items.push(SetupItem {
764 name: "env_sh".to_string(),
765 status: "created".to_string(),
766 path: Some(crate::core::paths::config_dir().map_or_else(
767 |_| "~/.config/lean-ctx/env.sh".to_string(),
768 |d| d.join("env.sh").to_string_lossy().to_string(),
769 )),
770 note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
771 });
772 } else {
773 shell_step.items.push(SetupItem {
774 name: "env_sh".to_string(),
775 status: "skipped".to_string(),
776 path: None,
777 note: Some("not a container environment".to_string()),
778 });
779 }
780 }
781 shell_step.items.push(SetupItem {
782 name: "init --global".to_string(),
783 status: "ran".to_string(),
784 path: None,
785 note: None,
786 });
787 shell_step.items.push(SetupItem {
788 name: "universal_shell_hook".to_string(),
789 status: "installed".to_string(),
790 path: None,
791 note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
792 });
793 } else {
794 shell_step
795 .warnings
796 .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
797 shell_step.ok = false;
798 shell_step.items.push(SetupItem {
799 name: "init --global".to_string(),
800 status: "skipped".to_string(),
801 path: None,
802 note: Some("requires --yes in --non-interactive mode".to_string()),
803 });
804 }
805 steps.push(shell_step);
806
807 let mut daemon_step = SetupStepReport {
809 name: "daemon".to_string(),
810 ok: true,
811 items: Vec::new(),
812 warnings: Vec::new(),
813 errors: Vec::new(),
814 };
815 {
816 let was_running = crate::daemon::is_daemon_running();
817 if was_running {
818 let _ = crate::daemon::stop_daemon();
819 std::thread::sleep(std::time::Duration::from_millis(500));
820 }
821 match crate::daemon::start_daemon(&[]) {
822 Ok(()) => {
823 let action = if was_running { "restarted" } else { "started" };
824 daemon_step.items.push(SetupItem {
825 name: "serve --daemon".to_string(),
826 status: action.to_string(),
827 path: Some(crate::daemon::daemon_addr().display()),
828 note: Some("CLI commands can route via IPC when running".to_string()),
829 });
830 }
831 Err(e) => {
832 daemon_step
833 .warnings
834 .push(format!("daemon start failed (non-fatal): {e}"));
835 daemon_step.items.push(SetupItem {
836 name: "serve --daemon".to_string(),
837 status: "skipped".to_string(),
838 path: None,
839 note: Some(format!("optional — {e}")),
840 });
841 }
842 }
843 }
844 steps.push(daemon_step);
845
846 let mut editor_step = SetupStepReport {
848 name: "editors".to_string(),
849 ok: true,
850 items: Vec::new(),
851 warnings: Vec::new(),
852 errors: Vec::new(),
853 };
854
855 let targets = crate::core::editor_registry::build_targets(&home);
856 let update_mcp = crate::core::config::Config::load()
859 .setup
860 .should_update_mcp();
861 for target in &targets {
862 let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
863 if !target.detect_path.exists() {
864 editor_step.items.push(SetupItem {
865 name: target.name.to_string(),
866 status: "not_detected".to_string(),
867 path: Some(short_path),
868 note: None,
869 });
870 continue;
871 }
872
873 let mode = if target.agent_key.is_empty() {
874 HookMode::Mcp
875 } else {
876 recommend_hook_mode(&target.agent_key)
877 };
878
879 if !update_mcp {
880 editor_step.items.push(SetupItem {
881 name: target.name.to_string(),
882 status: "skipped".to_string(),
883 path: Some(short_path),
884 note: Some(format!(
885 "mode={mode}; MCP registration skipped (auto_update_mcp=false)"
886 )),
887 });
888 continue;
889 }
890
891 let res = crate::core::editor_registry::write_config_with_options(
892 target,
893 &binary,
894 WriteOptions {
895 overwrite_invalid: opts.fix,
896 },
897 );
898 match res {
899 Ok(w) => {
900 let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
901 .into_iter()
902 .flatten()
903 .collect();
904 editor_step.items.push(SetupItem {
905 name: target.name.to_string(),
906 status: match w.action {
907 WriteAction::Created => "created".to_string(),
908 WriteAction::Updated => "updated".to_string(),
909 WriteAction::Already => "already".to_string(),
910 },
911 path: Some(short_path),
912 note: Some(note_parts.join("; ")),
913 });
914 }
915 Err(e) => {
916 editor_step.ok = false;
917 editor_step.items.push(SetupItem {
918 name: target.name.to_string(),
919 status: "error".to_string(),
920 path: Some(short_path),
921 note: Some(e),
922 });
923 }
924 }
925 }
926 steps.push(editor_step);
927
928 let mut rules_step = SetupStepReport {
930 name: "agent_rules".to_string(),
931 ok: true,
932 items: Vec::new(),
933 warnings: Vec::new(),
934 errors: Vec::new(),
935 };
936 let setup_cfg = crate::core::config::Config::load().setup;
937 let should_inject = if opts.skip_rules {
938 false
939 } else if opts.force_inject_rules {
940 true
941 } else if opts.yes && opts.non_interactive {
942 setup_cfg.should_inject_rules()
943 } else {
944 true
945 };
946
947 if should_inject {
948 let rules_result = crate::rules_inject::inject_all_rules(&home);
949 for n in rules_result.injected {
950 rules_step.items.push(SetupItem {
951 name: n,
952 status: "injected".to_string(),
953 path: None,
954 note: None,
955 });
956 }
957 for n in rules_result.updated {
958 rules_step.items.push(SetupItem {
959 name: n,
960 status: "updated".to_string(),
961 path: None,
962 note: None,
963 });
964 }
965 for n in rules_result.already {
966 rules_step.items.push(SetupItem {
967 name: n,
968 status: "already".to_string(),
969 path: None,
970 note: None,
971 });
972 }
973 if !rules_result.backed_up.is_empty() {
974 for bak in &rules_result.backed_up {
975 rules_step.items.push(SetupItem {
976 name: "backup".to_string(),
977 status: "created".to_string(),
978 path: Some(bak.clone()),
979 note: Some("previous version backed up".to_string()),
980 });
981 }
982 }
983 for e in rules_result.errors {
984 rules_step.ok = false;
985 rules_step.errors.push(e);
986 }
987 } else {
988 let reason = if opts.skip_rules {
989 "--skip-rules flag set"
990 } else {
991 "auto_inject_rules not enabled (run `lean-ctx setup --inject-rules`)"
992 };
993 rules_step.items.push(SetupItem {
994 name: "agent_rules".to_string(),
995 status: "skipped".to_string(),
996 path: None,
997 note: Some(reason.to_string()),
998 });
999 }
1000 steps.push(rules_step);
1001
1002 let mut skill_step = SetupStepReport {
1004 name: "skill_files".to_string(),
1005 ok: true,
1006 items: Vec::new(),
1007 warnings: Vec::new(),
1008 errors: Vec::new(),
1009 };
1010 let should_install_skills = if opts.skip_rules {
1011 false
1012 } else if opts.force_inject_rules {
1013 true
1014 } else if opts.yes && opts.non_interactive {
1015 setup_cfg.should_inject_skills()
1016 } else {
1017 true
1018 };
1019 if should_install_skills {
1020 let skill_results = crate::rules_inject::install_all_skills(&home);
1021 for (name, is_new) in &skill_results {
1022 skill_step.items.push(SetupItem {
1023 name: name.clone(),
1024 status: if *is_new { "installed" } else { "already" }.to_string(),
1025 path: None,
1026 note: Some("SKILL.md".to_string()),
1027 });
1028 }
1029 } else {
1030 skill_step.items.push(SetupItem {
1031 name: "skill_files".to_string(),
1032 status: "skipped".to_string(),
1033 path: None,
1034 note: Some("auto_inject_skills not enabled".to_string()),
1035 });
1036 }
1037 if !skill_step.items.is_empty() {
1038 steps.push(skill_step);
1039 }
1040
1041 let mut hooks_step = SetupStepReport {
1043 name: "agent_hooks".to_string(),
1044 ok: true,
1045 items: Vec::new(),
1046 warnings: Vec::new(),
1047 errors: Vec::new(),
1048 };
1049 for target in &targets {
1050 if !target.detect_path.exists() || target.agent_key.is_empty() {
1051 continue;
1052 }
1053 let mode = recommend_hook_mode(&target.agent_key);
1054 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
1055 let mcp_note = if setup_cfg.should_update_mcp() {
1058 match configure_agent_mcp(&target.agent_key) {
1059 Ok(()) => "; MCP config updated".to_string(),
1060 Err(e) => format!("; MCP config skipped: {e}"),
1061 }
1062 } else {
1063 "; MCP registration skipped (auto_update_mcp=false)".to_string()
1064 };
1065 hooks_step.items.push(SetupItem {
1066 name: format!("{} hooks", target.name),
1067 status: "installed".to_string(),
1068 path: Some(target.detect_path.to_string_lossy().to_string()),
1069 note: Some(format!(
1070 "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
1071 )),
1072 });
1073 }
1074 if !hooks_step.items.is_empty() {
1075 steps.push(hooks_step);
1076 }
1077
1078 let mut tool_profile_step = SetupStepReport {
1084 name: "tool_profile".to_string(),
1085 ok: true,
1086 items: Vec::new(),
1087 warnings: Vec::new(),
1088 errors: Vec::new(),
1089 };
1090 {
1091 let cfg = crate::core::config::Config::load();
1092 if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
1093 let lazy_count = crate::tool_defs::core_tool_names().len();
1094 tool_profile_step.items.push(SetupItem {
1095 name: "tool_profile".to_string(),
1096 status: "lean default".to_string(),
1097 path: None,
1098 note: Some(format!(
1099 "{lazy_count} tools advertised, all reachable via ctx_call \
1100 (pin more with: lean-ctx tools standard|power)"
1101 )),
1102 });
1103 } else {
1104 let profile = cfg.tool_profile_effective();
1105 let overhead_hint = match profile {
1106 crate::core::tool_profiles::ToolProfile::Power => {
1107 "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
1108 }
1109 _ => "",
1110 };
1111 tool_profile_step.items.push(SetupItem {
1112 name: "tool_profile".to_string(),
1113 status: "already".to_string(),
1114 path: None,
1115 note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
1116 });
1117 }
1118 }
1119 steps.push(tool_profile_step);
1120
1121 let mut proxy_step = SetupStepReport {
1123 name: "proxy".to_string(),
1124 ok: true,
1125 items: Vec::new(),
1126 warnings: Vec::new(),
1127 errors: Vec::new(),
1128 };
1129 if opts.skip_proxy {
1130 proxy_step.items.push(SetupItem {
1131 name: "proxy".to_string(),
1132 status: "skipped".to_string(),
1133 path: None,
1134 note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
1135 });
1136 } else {
1137 let proxy_cfg = crate::core::config::Config::load();
1138 if proxy_cfg.proxy_enabled == Some(true) {
1139 let proxy_port = crate::proxy_setup::default_port();
1140 crate::proxy_autostart::install(proxy_port, true);
1141 std::thread::sleep(std::time::Duration::from_millis(500));
1142 crate::proxy_setup::install_proxy_env(&home, proxy_port, opts.json);
1143 proxy_step.items.push(SetupItem {
1144 name: "proxy_autostart".to_string(),
1145 status: "installed".to_string(),
1146 path: None,
1147 note: Some("LaunchAgent/systemd auto-start on login".to_string()),
1148 });
1149 proxy_step.items.push(SetupItem {
1150 name: "proxy_env".to_string(),
1151 status: "configured".to_string(),
1152 path: None,
1153 note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
1154 });
1155 } else {
1156 proxy_step.items.push(SetupItem {
1157 name: "proxy".to_string(),
1158 status: "skipped".to_string(),
1159 path: None,
1160 note: Some(
1161 "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
1162 ),
1163 });
1164 }
1165 }
1166 steps.push(proxy_step);
1167
1168 let mut env_step = SetupStepReport {
1170 name: "doctor_compact".to_string(),
1171 ok: true,
1172 items: Vec::new(),
1173 warnings: Vec::new(),
1174 errors: Vec::new(),
1175 };
1176 let (passed, total) = crate::doctor::compact_score();
1177 env_step.items.push(SetupItem {
1178 name: "doctor".to_string(),
1179 status: format!("{passed}/{total}"),
1180 path: None,
1181 note: None,
1182 });
1183 if passed != total {
1184 env_step.warnings.push(format!(
1185 "doctor compact not fully passing: {passed}/{total}"
1186 ));
1187 }
1188 steps.push(env_step);
1189
1190 {
1192 let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT").is_ok_and(|v| !v.is_empty());
1193 let cfg = crate::core::config::Config::load();
1194 let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
1195 if !has_env_root
1196 && !has_cfg_root
1197 && let Ok(cwd) = std::env::current_dir()
1198 {
1199 let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
1200 if is_home {
1201 let mut root_step = SetupStepReport {
1202 name: "project_root".to_string(),
1203 ok: true,
1204 items: Vec::new(),
1205 warnings: vec![
1206 "No project_root configured. Running from $HOME can cause excessive scanning. \
1207 Set via: lean-ctx config set project_root /path/to/project".to_string()
1208 ],
1209 errors: Vec::new(),
1210 };
1211 root_step.items.push(SetupItem {
1212 name: "project_root".to_string(),
1213 status: "unconfigured".to_string(),
1214 path: None,
1215 note: Some(
1216 "Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml".to_string(),
1217 ),
1218 });
1219 steps.push(root_step);
1220 }
1221 }
1222 }
1223
1224 if let Ok(cwd) = std::env::current_dir()
1229 && may_autoindex_cwd(&cwd)
1230 && crate::core::pathutil::has_project_marker(&cwd)
1231 {
1232 spawn_index_build_background(&cwd);
1233 }
1234
1235 let finished_at = Utc::now();
1236 let success = steps.iter().all(|s| s.ok);
1237 let report = SetupReport {
1238 schema_version: 1,
1239 started_at,
1240 finished_at,
1241 success,
1242 platform: PlatformInfo {
1243 os: std::env::consts::OS.to_string(),
1244 arch: std::env::consts::ARCH.to_string(),
1245 },
1246 steps,
1247 warnings: Vec::new(),
1248 errors: Vec::new(),
1249 };
1250
1251 let path = SetupReport::default_path()?;
1252 let mut content =
1253 serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
1254 content.push('\n');
1255 crate::config_io::write_atomic(&path, &content)?;
1256
1257 Ok(report)
1258}
1259
1260fn may_autoindex_cwd(cwd: &std::path::Path) -> bool {
1269 !crate::core::pathutil::is_under_tcc_protected_dir(cwd)
1270}
1271
1272fn spawn_index_build_background(root: &std::path::Path) {
1273 if std::env::var("LEAN_CTX_DISABLED").is_ok()
1274 || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1")
1275 {
1276 return;
1277 }
1278 let root_str = crate::core::graph_index::normalize_project_root(&root.to_string_lossy());
1279 if !crate::core::graph_index::is_safe_scan_root_public(&root_str) {
1280 tracing::info!("[setup: skipping background graph build for unsafe root {root_str}]");
1281 return;
1282 }
1283
1284 let binary = resolve_portable_binary();
1285
1286 #[cfg(unix)]
1287 {
1288 let mut cmd = std::process::Command::new("nice");
1289 cmd.args(["-n", "19"]);
1290 if which_ionice_available() {
1291 cmd.arg("ionice").args(["-c", "3"]);
1292 }
1293 cmd.arg(&binary)
1294 .args(["index", "build", "--root"])
1295 .arg(root)
1296 .stdout(std::process::Stdio::null())
1297 .stderr(std::process::Stdio::null())
1298 .stdin(std::process::Stdio::null());
1299 let _ = cmd.spawn();
1300 }
1301
1302 #[cfg(windows)]
1303 {
1304 use std::os::windows::process::CommandExt;
1305 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
1306 const CREATE_NO_WINDOW: u32 = 0x0800_0000;
1307 let _ = std::process::Command::new(&binary)
1308 .args(["index", "build", "--root"])
1309 .arg(root)
1310 .stdout(std::process::Stdio::null())
1311 .stderr(std::process::Stdio::null())
1312 .stdin(std::process::Stdio::null())
1313 .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
1314 .spawn();
1315 }
1316}
1317
1318#[cfg(unix)]
1319fn which_ionice_available() -> bool {
1320 std::process::Command::new("ionice")
1321 .arg("--version")
1322 .stdout(std::process::Stdio::null())
1323 .stderr(std::process::Stdio::null())
1324 .status()
1325 .is_ok()
1326}
1327
1328#[cfg(all(test, target_os = "macos"))]
1329mod tests {
1330 use super::*;
1331
1332 #[test]
1336 fn may_autoindex_cwd_skips_tcc_protected_dirs() {
1337 let Some(home) = dirs::home_dir() else {
1338 return;
1339 };
1340 assert!(!may_autoindex_cwd(&home.join("Documents/proj")));
1341 assert!(!may_autoindex_cwd(&home.join("Desktop/proj")));
1342 assert!(!may_autoindex_cwd(&home.join("Downloads/proj")));
1343 assert!(may_autoindex_cwd(&home.join("code/proj")));
1344 assert!(may_autoindex_cwd(std::path::Path::new("/tmp/proj")));
1345 }
1346
1347 #[test]
1348 #[cfg(target_os = "macos")]
1349 fn qoder_agent_targets_include_all_macos_mcp_locations() {
1350 let home = std::path::Path::new("/Users/tester");
1351 let targets = agent_mcp_targets("qoder", home).unwrap();
1352 let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1353
1354 assert_eq!(
1355 paths,
1356 vec![
1357 home.join(".qoder/mcp.json").as_path(),
1358 home.join("Library/Application Support/Qoder/User/mcp.json")
1359 .as_path(),
1360 home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1361 .as_path(),
1362 ]
1363 );
1364 assert!(
1365 targets
1366 .iter()
1367 .all(|t| t.config_type == ConfigType::QoderSettings)
1368 );
1369 }
1370}