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