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 if crate::core::telemetry_consent::telemetry_would_send() {
380 for line in crate::core::telemetry_consent::hint_lines() {
381 println!(" \x1b[2m{line}\x1b[0m");
382 }
383 } else {
384 terminal_ui::print_status_skip(
385 "Telemetry is off — nothing is sent. Turn on: lean-ctx telemetry on",
386 );
387 }
388 crate::core::telemetry_consent::mark_notice_seen();
389
390 terminal_ui::print_step_header(10, 14, "Auto-Updates");
391 println!(" Keep lean-ctx up to date automatically.");
392 println!(" \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
393 println!(
394 " \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
395 );
396 println!();
397 print!(" Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
398 use std::io::Write;
399 std::io::stdout().flush().ok();
400
401 let mut auto_input = String::new();
402 let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
403 let answer = auto_input.trim().to_lowercase();
404 answer == "y" || answer == "yes"
405 } else {
406 false
407 };
408
409 if auto_update {
410 let cfg = crate::core::config::Config::load();
411 let hours = cfg.updates.check_interval_hours;
412 match crate::core::update_scheduler::install_schedule(hours) {
413 Ok(info) => {
414 crate::core::update_scheduler::set_auto_update(true, false, hours);
415 terminal_ui::print_status_ok(&format!("Enabled — {info}"));
416 }
417 Err(e) => {
418 terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
419 terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
420 }
421 }
422 } else {
423 crate::core::update_scheduler::set_auto_update(false, false, 6);
424 terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
425 }
426
427 terminal_ui::print_step_header(11, 14, "Tool Profile");
428 configure_tool_profile();
429
430 terminal_ui::print_step_header(12, 14, "Advanced Tuning (optional)");
431 configure_premium_features(&home);
432
433 terminal_ui::print_step_header(13, 14, "Code Intelligence");
434 let cwd = std::env::current_dir().ok();
435 let cwd_is_home = cwd
436 .as_ref()
437 .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
438 if cwd_is_home {
439 terminal_ui::print_status_warn(
440 "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
441 );
442 println!();
443 println!(" \x1b[1mSet a default project root to avoid this:\x1b[0m");
444 println!(" \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
445 print!(" \x1b[1m>\x1b[0m ");
446 use std::io::Write;
447 std::io::stdout().flush().ok();
448 let mut root_input = String::new();
449 if std::io::stdin().read_line(&mut root_input).is_ok() {
450 let root_trimmed = root_input.trim();
451 if root_trimmed.is_empty() {
452 terminal_ui::print_status_skip(
453 "No project root set. Set later: lean-ctx config set project_root /path/to/project",
454 );
455 } else {
456 let root_path = std::path::Path::new(root_trimmed);
457 if root_path.exists() && root_path.is_dir() {
458 let config_path = crate::core::config::Config::path()
459 .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
460 let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
461 if content.contains("project_root") {
462 if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
463 content = re
464 .replace(&content, &format!("project_root = \"{root_trimmed}\""))
465 .to_string();
466 }
467 } else {
468 if !content.is_empty() && !content.ends_with('\n') {
469 content.push('\n');
470 }
471 content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
472 }
473 let _ = crate::config_io::write_atomic_with_backup(&config_path, &content);
474 terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
475 if crate::core::pathutil::has_project_marker(root_path) {
476 spawn_index_build_background(root_path);
477 terminal_ui::print_status_ok("Graph build started (background)");
478 }
479 } else {
480 terminal_ui::print_status_warn(&format!(
481 "Path not found: {root_trimmed} — skipped"
482 ));
483 }
484 }
485 }
486 } else {
487 let is_project = cwd
488 .as_ref()
489 .is_some_and(|d| crate::core::pathutil::has_project_marker(d));
490 if is_project {
491 println!(" \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
492 println!(" \x1b[2mand smart search fusion in the background...\x1b[0m");
493 if let Some(ref root) = cwd {
494 spawn_index_build_background(root);
495 }
496 terminal_ui::print_status_ok("Graph build started (background)");
497 } else {
498 println!(" \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
499 println!(
500 " \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
501 );
502 }
503 }
504 println!();
505
506 {
507 let tools = crate::core::editor_registry::writers::auto_approve_tools();
508 println!();
509 println!(
510 " \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
511 tools.len()
512 );
513 for chunk in tools.chunks(6) {
514 let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
515 println!(" {}", names.join(", "));
516 }
517 println!(" \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
518 }
519
520 terminal_ui::print_step_header(14, 14, "Intelligence Runtime (optional)");
521 super::intelligence::configure_runtime();
522
523 println!();
524 println!(
525 " \x1b[1;32m✓ Setup complete!\x1b[0m \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
526 newly_configured.len(),
527 already_configured.len(),
528 not_installed.len()
529 );
530
531 if !errors.is_empty() {
532 println!(
533 " \x1b[33m⚠ {} error{}: {}\x1b[0m",
534 errors.len(),
535 if errors.len() == 1 { "" } else { "s" },
536 errors.join(", ")
537 );
538 }
539
540 let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
541
542 let dim = "\x1b[2m";
543 let bold = "\x1b[1m";
544 let cyan = "\x1b[36m";
545 let yellow = "\x1b[33m";
546 let rst = "\x1b[0m";
547
548 println!();
549 println!(" {bold}Next steps:{rst}");
550 println!();
551 println!(" {cyan}1.{rst} Reload your shell:");
552 println!(" {bold}{source_cmd}{rst}");
553 println!();
554
555 let mut tools_to_restart: Vec<String> = newly_configured
556 .iter()
557 .map(std::string::ToString::to_string)
558 .collect();
559 for name in rules_result
560 .injected
561 .iter()
562 .chain(rules_result.updated.iter())
563 {
564 if !tools_to_restart.contains(name) {
565 tools_to_restart.push(name.clone());
566 }
567 }
568
569 if !tools_to_restart.is_empty() {
570 println!(" {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
571 println!(" {bold}{}{rst}", tools_to_restart.join(", "));
572 println!(
573 " {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
574 );
575 println!(" {dim}Close and re-open the application completely.{rst}");
576 } else if !already_configured.is_empty() {
577 println!(
578 " {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
579 );
580 }
581
582 println!();
583 println!(
584 " {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
585 );
586 println!(" {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
587
588 println!();
589 terminal_ui::print_logo_animated();
590 terminal_ui::print_command_box();
591
592 if errors.is_empty() {
593 if let Err(error) =
594 crate::core::telemetry_aggregate::record_setup_completion(configured_integration_ids)
595 {
596 tracing::debug!("telemetry setup aggregate unavailable: {error}");
597 }
598 }
599
600 crate::cli::show_first_run_wow();
601}