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