1use crate::core::editor_registry::{WriteAction, WriteOptions};
2use crate::core::portable_binary::resolve_agent_binary;
3use crate::hooks::{HookMode, recommend_hook_mode};
4
5use super::first_run::{first_run_setup_level, persist_setup_choice};
6use super::helpers::{
7 configure_plan_mode_settings, configure_premium_features, configure_tool_profile,
8 install_skill_files, shorten_path,
9};
10use super::index_build::spawn_index_build_background;
11use super::options::SetupOptions;
12use super::with_options::run_setup_with_options;
13
14pub fn run_setup() {
15 use crate::terminal_ui;
16
17 if crate::shell::is_non_interactive() {
18 eprintln!("Non-interactive terminal detected (no TTY on stdin).");
19 eprintln!(
20 "Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)"
21 );
22 eprintln!();
23 let opts = SetupOptions {
24 non_interactive: true,
25 yes: true,
26 ..Default::default()
27 };
28 match run_setup_with_options(opts) {
29 Ok(report) => {
30 for w in &report.warnings {
31 tracing::warn!("{w}");
32 }
33 }
34 Err(e) => tracing::error!("Setup error: {e}"),
35 }
36 return;
37 }
38
39 let Some(home) = crate::core::home::resolve_home_dir() else {
40 tracing::error!("Cannot determine home directory");
41 std::process::exit(1);
42 };
43
44 let binary = resolve_agent_binary();
45
46 let home_str = home.to_string_lossy().to_string();
47
48 terminal_ui::print_setup_header();
49
50 let (inject_rules, inject_skills) = first_run_setup_level();
51 persist_setup_choice(inject_rules, inject_skills);
52
53 let allow_rule_steering =
54 inject_rules && !crate::core::config::Config::load().declines_rule_steering();
55
56 terminal_ui::print_step_header(1, 14, "Shell Hook");
57 crate::cli::cmd_init(&["--global".to_string()]);
58 crate::shell_hook::install_all(false);
59
60 terminal_ui::print_step_header(2, 14, "Daemon");
61 if crate::daemon::is_daemon_running() {
62 terminal_ui::print_status_ok("Daemon running — restarting with current binary…");
63 let _ = crate::daemon::stop_daemon();
64 std::thread::sleep(std::time::Duration::from_millis(500));
65 if let Err(e) = crate::daemon::start_daemon(&[]) {
66 terminal_ui::print_status_warn(&format!("Daemon restart failed: {e}"));
67 }
68 } else if let Err(e) = crate::daemon::start_daemon(&[]) {
69 terminal_ui::print_status_warn(&format!("Daemon start failed: {e}"));
70 }
71
72 terminal_ui::print_step_header(3, 14, "AI Tool Detection");
73
74 let targets = crate::core::editor_registry::build_targets(&home);
75 let update_mcp = crate::core::config::Config::load()
79 .setup
80 .should_update_mcp();
81 let mut newly_configured: Vec<&str> = Vec::new();
82 let mut already_configured: Vec<&str> = Vec::new();
83 let mut not_installed: Vec<&str> = Vec::new();
84 let mut mcp_skipped: Vec<&str> = Vec::new();
85 let mut errors: Vec<&str> = Vec::new();
86 let mut configured_integration_ids = Vec::new();
87
88 for target in &targets {
89 let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
90
91 if !target.detect_path.exists() {
92 not_installed.push(target.name);
93 continue;
94 }
95
96 if !update_mcp {
97 terminal_ui::print_status_ok(&format!(
98 "{:<20} \x1b[2mMCP registration skipped (auto_update_mcp=false)\x1b[0m",
99 target.name
100 ));
101 mcp_skipped.push(target.name);
102 continue;
103 }
104
105 let mode = if target.agent_key.is_empty() {
106 HookMode::Mcp
107 } else {
108 recommend_hook_mode(&target.agent_key)
109 };
110
111 match crate::core::editor_registry::write_config_with_options_and_rule_steering(
112 target,
113 &binary,
114 WriteOptions {
115 overwrite_invalid: false,
116 },
117 allow_rule_steering,
118 ) {
119 Ok(res) if res.action == WriteAction::Already => {
120 terminal_ui::print_status_ok(&format!(
121 "{:<20} \x1b[36m{mode}\x1b[0m \x1b[2m{short_path}\x1b[0m",
122 target.name
123 ));
124 already_configured.push(target.name);
125 configured_integration_ids.push(target.agent_key.clone());
126 }
127 Ok(_) => {
128 terminal_ui::print_status_new(&format!(
129 "{:<20} \x1b[36m{mode}\x1b[0m \x1b[2m{short_path}\x1b[0m",
130 target.name
131 ));
132 newly_configured.push(target.name);
133 configured_integration_ids.push(target.agent_key.clone());
134 }
135 Err(e) => {
136 terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
137 errors.push(target.name);
138 }
139 }
140 }
141
142 let total_ok = newly_configured.len() + already_configured.len();
143 if total_ok == 0 && errors.is_empty() && mcp_skipped.is_empty() {
144 terminal_ui::print_status_warn(
145 "No AI tools detected. Install one and re-run: lean-ctx setup",
146 );
147 }
148
149 if !not_installed.is_empty() {
150 println!(
151 " \x1b[2m○ {} not detected: {}\x1b[0m",
152 not_installed.len(),
153 not_installed.join(", ")
154 );
155 }
156
157 configure_plan_mode_settings(&newly_configured, &already_configured);
158
159 terminal_ui::print_step_header(4, 14, "Agent Rules");
160 let rules_result = if inject_rules {
161 let r = crate::rules_inject::inject_all_rules(&home);
162 for name in &r.injected {
163 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
164 }
165 for name in &r.updated {
166 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
167 }
168 for name in &r.already {
169 terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
170 }
171 for err in &r.errors {
172 terminal_ui::print_status_warn(err);
173 }
174 if !r.backed_up.is_empty() {
175 for bak in &r.backed_up {
176 println!(" \x1b[2m ↳ backup: {bak}\x1b[0m");
177 }
178 }
179 if r.injected.is_empty()
180 && r.updated.is_empty()
181 && r.already.is_empty()
182 && r.errors.is_empty()
183 {
184 terminal_ui::print_status_skip("No agent rules needed");
185 }
186 r
187 } else {
188 terminal_ui::print_status_skip(
189 "Skipped (run `lean-ctx setup` or set auto_inject_rules = true in config)",
190 );
191 crate::rules_inject::InjectResult::default()
192 };
193
194 for target in &targets {
195 if !target.detect_path.exists() || target.agent_key.is_empty() {
196 continue;
197 }
198
199 let mode = recommend_hook_mode(&target.agent_key);
200
201 if allow_rule_steering {
202 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
203 } else {
204 crate::hooks::install_agent_runtime_hook_with_mode(&target.agent_key, true, mode);
205 }
206 }
207
208 terminal_ui::print_step_header(5, 14, "API Proxy (optional)");
209 {
210 let cfg = crate::core::config::Config::load();
211 let proxy_port = crate::proxy_setup::default_port();
212
213 match cfg.proxy_enabled {
214 Some(true) => {
215 crate::proxy_autostart::install(proxy_port, false);
216 std::thread::sleep(std::time::Duration::from_millis(500));
217 crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
218 terminal_ui::print_status_ok("Proxy active (opted in)");
219 }
220 Some(false) => {
221 terminal_ui::print_status_skip(
222 "Proxy disabled (run `lean-ctx proxy enable` to change)",
223 );
224 }
225 None => {
226 println!(
227 " \x1b[2mThe API proxy routes LLM requests through lean-ctx for additional\x1b[0m"
228 );
229 println!(
230 " \x1b[2mtool-result compression and precise token analytics in the dashboard.\x1b[0m"
231 );
232 println!();
233 println!(
234 " \x1b[2mWithout it: MCP tools, shell hooks, gain tracking, and memory\x1b[0m"
235 );
236 println!(
237 " \x1b[2mall work normally. The proxy compresses API traffic on top.\x1b[0m"
238 );
239 println!();
240 print!(" Enable the API proxy? [y/N] ");
241 let _ = std::io::Write::flush(&mut std::io::stdout());
242 let mut input = String::new();
243 let _ = std::io::stdin().read_line(&mut input);
244 let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
245 if let Err(e) =
246 crate::core::config::Config::update_global(|c| c.proxy_enabled = Some(answer))
247 {
248 tracing::warn!("could not persist proxy choice: {e}");
249 }
250 if answer {
251 crate::proxy_autostart::install(proxy_port, false);
252 std::thread::sleep(std::time::Duration::from_millis(500));
253 crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
254 terminal_ui::print_status_new("Proxy enabled");
255 } else {
256 terminal_ui::print_status_skip(
257 "Proxy skipped (run `lean-ctx proxy enable` anytime)",
258 );
259 }
260 }
261 }
262 }
263
264 terminal_ui::print_step_header(6, 14, "IDE Config Access (optional)");
265 {
266 let cfg = crate::core::config::Config::load();
267 match cfg.allow_ide_config_dirs {
268 Some(true) => {
269 terminal_ui::print_status_ok(
270 "Enabled — the agent can read your editors' config dirs",
271 );
272 }
273 Some(false) => {
274 terminal_ui::print_status_skip(
275 "Off (enable: lean-ctx config set allow_ide_config_dirs true)",
276 );
277 }
278 None => {
279 println!(
280 " \x1b[2mlean-ctx tools are jailed to the current project. Enabling this lets\x1b[0m"
281 );
282 println!(
283 " \x1b[2mthe agent read every supported editor's config dir (~/.cursor, VS Code,\x1b[0m"
284 );
285 println!(
286 " \x1b[2mCline/Roo, JetBrains, …) to manage MCP setup across editors.\x1b[0m"
287 );
288 println!();
289 println!(
290 " \x1b[33mTrade-off:\x1b[0m \x1b[2mthose dirs can hold other agents' sessions & credentials.\x1b[0m"
291 );
292 println!();
293 print!(" Allow the agent to read IDE config dirs? [y/N] ");
294 let _ = std::io::Write::flush(&mut std::io::stdout());
295 let mut input = String::new();
296 let _ = std::io::stdin().read_line(&mut input);
297 let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
298 if let Err(e) = crate::core::config::Config::update_global(|c| {
299 c.allow_ide_config_dirs = Some(answer);
300 }) {
301 tracing::warn!("could not persist IDE-config-access choice: {e}");
302 }
303 if answer {
304 terminal_ui::print_status_new("IDE config access enabled");
305 } else {
306 terminal_ui::print_status_skip(
307 "Skipped (enable later: lean-ctx config set allow_ide_config_dirs true)",
308 );
309 }
310 }
311 }
312 }
313
314 terminal_ui::print_step_header(7, 14, "Skill Files");
315 if inject_skills {
316 let skill_result = install_skill_files(&home);
317 for (name, installed) in &skill_result {
318 if *installed {
319 terminal_ui::print_status_new(&format!(
320 "{name:<20} \x1b[2mSKILL.md installed\x1b[0m"
321 ));
322 } else {
323 terminal_ui::print_status_ok(&format!(
324 "{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"
325 ));
326 }
327 }
328 if skill_result.is_empty() {
329 terminal_ui::print_status_skip("No skill directories to install");
330 }
331 } else {
332 terminal_ui::print_status_skip(
333 "Skipped (skill files install with the rules opt-in; choose Standard/Full in `lean-ctx setup`)",
334 );
335 }
336
337 terminal_ui::print_step_header(8, 14, "Environment Check");
338 let lean_dir = crate::core::data_dir::lean_ctx_data_dir()
339 .unwrap_or_else(|_| home.join(".config/lean-ctx"));
340 if lean_dir.exists() {
341 terminal_ui::print_status_ok(&format!("{} ready", lean_dir.display()));
342 } else {
343 let _ = std::fs::create_dir_all(&lean_dir);
344 terminal_ui::print_status_new(&format!("Created {}", lean_dir.display()));
345 }
346 if let Some(report) = crate::core::data_consolidate::consolidate()
347 && report.files_moved > 0
348 {
349 terminal_ui::print_status_new(&format!(
350 "Consolidated {} file(s) from a split data dir into {}",
351 report.files_moved,
352 report.canonical.display()
353 ));
354 }
355 if let Some(report) = crate::core::config_heal::heal() {
358 match report.action {
359 crate::core::config_heal::HealAction::Adopted => {
360 terminal_ui::print_status_new(&format!(
361 "Recovered your config into {}",
362 report.to.display()
363 ));
364 }
365 crate::core::config_heal::HealAction::Superseded => {
366 terminal_ui::print_status_ok("Unified config (archived a stale data-dir copy)");
367 }
368 }
369 }
370 crate::doctor::run_compact();
371
372 crate::core::layout_pin::heal();
375
376 terminal_ui::print_step_header(9, 14, "Help Improve lean-ctx");
377 println!(" lean-ctx sends anonymous usage telemetry (on by default):");
378 for line in crate::core::telemetry_consent::disclosure_lines() {
379 println!(" [2m {line}[0m");
380 }
381 println!(" [2mSee the exact payload anytime: lean-ctx telemetry show[0m");
382 println!();
383 print!(" Keep anonymous telemetry on? [1m[Y/n][0m ");
384 use std::io::Write;
385 std::io::stdout().flush().ok();
386
387 let mut input = String::new();
390 let keep = match std::io::stdin().read_line(&mut input) {
391 Ok(_) => !matches!(input.trim().to_lowercase().as_str(), "n" | "no"),
392 Err(_) => true,
393 };
394 match crate::core::telemetry_consent::persist_choice(keep) {
395 Ok(()) => {
396 crate::core::telemetry_consent::mark_notice_seen();
397 if keep {
398 terminal_ui::print_status_ok(
399 "On — thank you! Turn off anytime: lean-ctx telemetry off",
400 );
401 } else {
402 terminal_ui::print_status_skip(
403 "Off — nothing is sent. Re-enable: lean-ctx telemetry on",
404 );
405 }
406 }
407 Err(error) => terminal_ui::print_status_skip(&format!(
408 "Could not save your choice ({error}); run lean-ctx telemetry {}",
409 if keep { "on" } else { "off" }
410 )),
411 }
412
413 terminal_ui::print_step_header(10, 14, "Auto-Updates");
414 println!(" Keep lean-ctx up to date automatically.");
415 println!(" \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
416 println!(
417 " \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
418 );
419 println!();
420 print!(" Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
421 std::io::stdout().flush().ok();
422
423 let mut auto_input = String::new();
424 let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
425 let answer = auto_input.trim().to_lowercase();
426 answer == "y" || answer == "yes"
427 } else {
428 false
429 };
430
431 if auto_update {
432 let cfg = crate::core::config::Config::load();
433 let hours = cfg.updates.check_interval_hours;
434 match crate::core::update_scheduler::install_schedule(hours) {
435 Ok(info) => {
436 crate::core::update_scheduler::set_auto_update(true, false, hours);
437 terminal_ui::print_status_ok(&format!("Enabled — {info}"));
438 }
439 Err(e) => {
440 terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
441 terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
442 }
443 }
444 } else {
445 crate::core::update_scheduler::set_auto_update(false, false, 6);
446 terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
447 }
448
449 terminal_ui::print_step_header(11, 14, "Tool Profile");
450 configure_tool_profile();
451
452 terminal_ui::print_step_header(12, 14, "Advanced Tuning (optional)");
453 configure_premium_features(&home);
454
455 terminal_ui::print_step_header(13, 14, "Code Intelligence");
456 let cwd = std::env::current_dir().ok();
457 let cwd_is_home = cwd
458 .as_ref()
459 .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
460 if cwd_is_home {
461 terminal_ui::print_status_warn(
462 "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
463 );
464 println!();
465 println!(" \x1b[1mSet a default project root to avoid this:\x1b[0m");
466 println!(" \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
467 print!(" \x1b[1m>\x1b[0m ");
468 use std::io::Write;
469 std::io::stdout().flush().ok();
470 let mut root_input = String::new();
471 if std::io::stdin().read_line(&mut root_input).is_ok() {
472 let root_trimmed = root_input.trim();
473 if root_trimmed.is_empty() {
474 terminal_ui::print_status_skip(
475 "No project root set. Set later: lean-ctx config set project_root /path/to/project",
476 );
477 } else {
478 let root_path = std::path::Path::new(root_trimmed);
479 if root_path.exists() && root_path.is_dir() {
480 let config_path = crate::core::config::Config::path()
481 .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
482 let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
483 if content.contains("project_root") {
484 if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
485 content = re
486 .replace(&content, &format!("project_root = \"{root_trimmed}\""))
487 .to_string();
488 }
489 } else {
490 if !content.is_empty() && !content.ends_with('\n') {
491 content.push('\n');
492 }
493 content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
494 }
495 let _ = crate::config_io::write_atomic_with_backup(&config_path, &content);
496 terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
497 if crate::core::pathutil::has_project_marker(root_path) {
498 spawn_index_build_background(root_path);
499 terminal_ui::print_status_ok("Graph build started (background)");
500 }
501 } else {
502 terminal_ui::print_status_warn(&format!(
503 "Path not found: {root_trimmed} — skipped"
504 ));
505 }
506 }
507 }
508 } else {
509 let is_project = cwd
510 .as_ref()
511 .is_some_and(|d| crate::core::pathutil::has_project_marker(d));
512 if is_project {
513 println!(" \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
514 println!(" \x1b[2mand smart search fusion in the background...\x1b[0m");
515 if let Some(ref root) = cwd {
516 spawn_index_build_background(root);
517 }
518 terminal_ui::print_status_ok("Graph build started (background)");
519 } else {
520 println!(" \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
521 println!(
522 " \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
523 );
524 }
525 }
526 println!();
527
528 {
529 let tools = crate::core::editor_registry::writers::auto_approve_tools();
530 println!();
531 println!(
532 " \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
533 tools.len()
534 );
535 for chunk in tools.chunks(6) {
536 let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
537 println!(" {}", names.join(", "));
538 }
539 println!(" \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
540 }
541
542 terminal_ui::print_step_header(14, 14, "Intelligence Runtime (optional)");
543 super::intelligence::configure_runtime();
544
545 println!();
546 println!(
547 " \x1b[1;32m✓ Setup complete!\x1b[0m \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
548 newly_configured.len(),
549 already_configured.len(),
550 not_installed.len()
551 );
552
553 if !errors.is_empty() {
554 println!(
555 " \x1b[33m⚠ {} error{}: {}\x1b[0m",
556 errors.len(),
557 if errors.len() == 1 { "" } else { "s" },
558 errors.join(", ")
559 );
560 }
561
562 let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
563
564 let dim = "\x1b[2m";
565 let bold = "\x1b[1m";
566 let cyan = "\x1b[36m";
567 let yellow = "\x1b[33m";
568 let rst = "\x1b[0m";
569
570 println!();
571 println!(" {bold}Next steps:{rst}");
572 println!();
573 println!(" {cyan}1.{rst} Reload your shell:");
574 println!(" {bold}{source_cmd}{rst}");
575 println!();
576
577 let mut tools_to_restart: Vec<String> = newly_configured
578 .iter()
579 .map(std::string::ToString::to_string)
580 .collect();
581 for name in rules_result
582 .injected
583 .iter()
584 .chain(rules_result.updated.iter())
585 {
586 if !tools_to_restart.contains(name) {
587 tools_to_restart.push(name.clone());
588 }
589 }
590
591 if !tools_to_restart.is_empty() {
592 println!(" {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
593 println!(" {bold}{}{rst}", tools_to_restart.join(", "));
594 println!(
595 " {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
596 );
597 println!(" {dim}Close and re-open the application completely.{rst}");
598 } else if !already_configured.is_empty() {
599 println!(
600 " {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
601 );
602 }
603
604 println!();
605 println!(
606 " {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
607 );
608 println!(" {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
609
610 println!();
611 terminal_ui::print_logo_animated();
612 terminal_ui::print_command_box();
613
614 if errors.is_empty() {
615 if let Err(error) =
616 crate::core::telemetry_aggregate::record_setup_completion(configured_integration_ids)
617 {
618 tracing::debug!("telemetry setup aggregate unavailable: {error}");
619 }
620 }
621
622 crate::cli::show_first_run_wow();
623}