1use chrono::Utc;
3
4use lean_ctx::core::editor_registry::{EditorTarget, WriteAction, WriteOptions};
5use lean_ctx::core::portable_binary::resolve_agent_binary;
6use lean_ctx::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
7use lean_ctx_hooks::hooks::{HookMode, recommend_hook_mode};
8
9use super::helpers::shorten_path;
10use super::index_build::{may_autoindex_cwd, spawn_index_build_background};
11use super::mcp::configure_agent_mcp_with_rule_steering;
12use super::options::SetupOptions;
13
14pub fn run_setup_with_options(opts: &SetupOptions) -> Result<SetupReport, String> {
15 let _quiet_guard = opts.json.then(lean_ctx::core::runtime_flags::scoped_quiet);
16 let started_at = Utc::now();
17 let home = lean_ctx::core::home::resolve_home_dir()
18 .ok_or_else(|| "Cannot determine home directory".to_string())?;
19 let binary = resolve_agent_binary();
20 let home_str = home.to_string_lossy().to_string();
21
22 let all_targets = lean_ctx::core::editor_registry::build_targets(&home);
24 let scope = super::agent_selection::scope_for_run(
25 &home,
26 &all_targets,
27 opts.agents.as_ref(),
28 opts.refresh_only,
29 );
30 let (targets, deselected): (Vec<EditorTarget>, Vec<EditorTarget>) = all_targets
31 .into_iter()
32 .partition(|t| scope.allows(&t.agent_key));
33 let allows = |key: &str| scope.allows(key);
34
35 let cfg = lean_ctx::core::config::Config::load();
36 let update_mcp = cfg.setup.should_update_mcp();
37 let should_inject = should_inject_rules(opts, cfg.setup.should_inject_rules());
38 let allow_rule_steering = should_allow_rule_steering(opts, &cfg);
39 let should_install_skills = should_inject_skills(opts, cfg.setup.should_inject_skills());
40
41 if opts.dry_run {
42 let steps = super::dry_run::plan_steps(&super::dry_run::PlanInput {
43 opts,
44 home: &home,
45 scope: &scope,
46 targets: &targets,
47 deselected: &deselected,
48 update_mcp,
49 inject_rules: should_inject,
50 inject_skills: should_install_skills,
51 });
52 return Ok(build_setup_report(started_at, steps));
53 }
54
55 lean_ctx::core::layout_pin::heal();
58
59 let governor_step = build_governor_step(opts, &home, &targets, &allows);
61 let mut editor_step = build_editor_step(
62 opts,
63 &home_str,
64 &binary,
65 &targets,
66 update_mcp,
67 allow_rule_steering,
68 );
69 editor_step
70 .items
71 .extend(deselected_items(&deselected, &home_str));
72 let mut steps = vec![
73 build_shell_hook_step(opts, &binary),
74 build_daemon_step(),
75 editor_step,
76 build_rules_step(opts, &home, should_inject, &allows),
77 ];
78 steps.extend(governor_step);
79
80 if let Some(step) = build_rules_dedup_step(&home, should_inject) {
81 steps.push(step);
82 }
83 if let Some(step) = build_skill_step(&home, should_install_skills, &allows) {
84 steps.push(step);
85 }
86 if let Some(step) = build_agent_hooks_step(&targets, update_mcp, allow_rule_steering) {
87 steps.push(step);
88 }
89
90 steps.extend([
91 super::intelligence::report(),
92 build_tool_profile_step(),
93 build_proxy_step(opts, &home),
94 build_doctor_compact_step(),
95 ]);
96 if let Some(step) = build_claude_mod_step(opts, &targets) {
97 steps.push(step);
98 }
99 if let Some(keys) = &opts.agents {
100 steps.push(build_selection_step(keys));
101 }
102
103 maybe_add_project_root_warning(&mut steps);
104 maybe_spawn_background_index();
105 maybe_enable_ide_config_access(opts);
106
107 let report = build_setup_report(started_at, steps);
108 persist_setup_report(&report)?;
109 if report.success {
110 let successful_names = report
111 .steps
112 .iter()
113 .filter(|step| step.name == "editors")
114 .flat_map(|step| &step.items)
115 .filter(|item| matches!(item.status.as_str(), "created" | "updated" | "already"))
116 .map(|item| item.name.as_str())
117 .collect::<Vec<_>>();
118 let integrations = targets
119 .iter()
120 .filter(|target| successful_names.contains(&target.name))
121 .map(|target| target.agent_key.clone())
122 .collect::<Vec<_>>();
123 if let Err(error) =
124 lean_ctx::core::telemetry_aggregate::record_setup_completion(integrations)
125 {
126 tracing::debug!("telemetry setup aggregate unavailable: {error}");
127 }
128 }
129
130 Ok(report)
131}
132
133pub(super) fn setup_step(name: &str) -> SetupStepReport {
134 SetupStepReport {
135 name: name.to_string(),
136 ok: true,
137 items: Vec::new(),
138 warnings: Vec::new(),
139 errors: Vec::new(),
140 }
141}
142
143pub(super) fn deselected_items(deselected: &[EditorTarget], home_str: &str) -> Vec<SetupItem> {
145 deselected
146 .iter()
147 .filter(|t| t.detect_path.exists())
148 .map(|t| SetupItem {
149 name: t.name.to_string(),
150 status: "deselected".to_string(),
151 path: Some(shorten_path(&t.config_path.to_string_lossy(), home_str)),
152 note: Some(format!(
153 "not in the agent selection; connect: lean-ctx init --agent {}",
154 t.agent_key
155 )),
156 })
157 .collect()
158}
159
160fn build_selection_step(keys: &std::collections::BTreeSet<String>) -> SetupStepReport {
162 let mut step = setup_step("agent_selection");
163 let list = keys.iter().cloned().collect::<Vec<_>>().join(",");
164 match super::agent_selection::save_selection(keys) {
165 Ok(()) => step.items.push(SetupItem {
166 name: "setup.agents".to_string(),
167 status: "saved".to_string(),
168 path: None,
169 note: Some(if list.is_empty() {
170 "none".to_string()
171 } else {
172 list
173 }),
174 }),
175 Err(e) => {
176 step.ok = false;
177 step.errors.push(e);
178 }
179 }
180 step
181}
182
183fn build_shell_hook_step(opts: &SetupOptions, _binary: &str) -> SetupStepReport {
184 let mut shell_step = setup_step("shell_hook");
185 if !opts.non_interactive || opts.yes {
186 if opts.json {
187 crate::cli::cmd_init_quiet(&["--global".to_string()]);
188 } else {
189 crate::cli::cmd_init(&["--global".to_string()]);
190 }
191 lean_ctx::shell_hook::install_all(opts.json);
192 #[cfg(not(windows))]
193 {
194 let binary = lean_ctx::core::portable_binary::stable_shell_binary(_binary);
196 let hook_content = crate::cli::generate_hook_posix(&binary);
197 if lean_ctx::shell::is_container() {
198 crate::cli::write_env_sh_for_containers(&hook_content);
199 shell_step.items.push(SetupItem {
200 name: "env_sh".to_string(),
201 status: "created".to_string(),
202 path: Some(lean_ctx::core::paths::config_dir().map_or_else(
203 |_| "~/.config/lean-ctx/env.sh".to_string(),
204 |d| d.join("env.sh").to_string_lossy().to_string(),
205 )),
206 note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
207 });
208 } else {
209 shell_step.items.push(SetupItem {
210 name: "env_sh".to_string(),
211 status: "skipped".to_string(),
212 path: None,
213 note: Some("not a container environment".to_string()),
214 });
215 }
216 }
217 shell_step.items.push(SetupItem {
218 name: "init --global".to_string(),
219 status: "ran".to_string(),
220 path: None,
221 note: None,
222 });
223 shell_step.items.push(SetupItem {
224 name: "universal_shell_hook".to_string(),
225 status: "installed".to_string(),
226 path: None,
227 note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
228 });
229 } else {
230 shell_step
231 .warnings
232 .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
233 shell_step.ok = false;
234 shell_step.items.push(SetupItem {
235 name: "init --global".to_string(),
236 status: "skipped".to_string(),
237 path: None,
238 note: Some("requires --yes in --non-interactive mode".to_string()),
239 });
240 }
241 shell_step
242}
243
244fn build_daemon_step() -> SetupStepReport {
245 let mut daemon_step = setup_step("daemon");
246 let was_running = lean_ctx::daemon::is_daemon_running();
247 if was_running {
248 let _ = lean_ctx::daemon::stop_daemon();
249 std::thread::sleep(std::time::Duration::from_millis(500));
250 }
251 match lean_ctx::daemon::start_daemon(&[]) {
252 Ok(()) => {
253 let action = if was_running { "restarted" } else { "started" };
254 daemon_step.items.push(SetupItem {
255 name: "serve --daemon".to_string(),
256 status: action.to_string(),
257 path: Some(lean_ctx::daemon::daemon_addr().display()),
258 note: Some("CLI commands can route via IPC when running".to_string()),
259 });
260 }
261 Err(e) => {
262 daemon_step
263 .warnings
264 .push(format!("daemon start failed (non-fatal): {e}"));
265 daemon_step.items.push(SetupItem {
266 name: "serve --daemon".to_string(),
267 status: "skipped".to_string(),
268 path: None,
269 note: Some(format!("optional — {e}")),
270 });
271 }
272 }
273 daemon_step
274}
275
276fn build_editor_step(
277 opts: &SetupOptions,
278 home_str: &str,
279 binary: &str,
280 targets: &[EditorTarget],
281 update_mcp: bool,
282 allow_rule_steering: bool,
283) -> SetupStepReport {
284 let mut editor_step = setup_step("editors");
285 for target in targets {
286 let short_path = shorten_path(&target.config_path.to_string_lossy(), home_str);
287 if !target.detect_path.exists() {
288 editor_step.items.push(SetupItem {
289 name: target.name.to_string(),
290 status: "not_detected".to_string(),
291 path: Some(short_path),
292 note: None,
293 });
294 continue;
295 }
296
297 let mode = lean_ctx_hooks::hooks::governor_default::display_mode(
298 &target.agent_key,
299 std::path::Path::new(home_str),
300 if target.agent_key.is_empty() {
301 HookMode::Mcp
302 } else {
303 recommend_hook_mode(&target.agent_key)
304 },
305 );
306
307 if !update_mcp {
308 editor_step.items.push(SetupItem {
309 name: target.name.to_string(),
310 status: "skipped".to_string(),
311 path: Some(short_path),
312 note: Some(format!(
313 "mode={mode}; MCP registration skipped (auto_update_mcp=false)"
314 )),
315 });
316 continue;
317 }
318
319 let res = lean_ctx::core::editor_registry::write_config_with_options_and_rule_steering(
320 target,
321 binary,
322 WriteOptions {
323 overwrite_invalid: opts.fix,
324 },
325 allow_rule_steering,
326 );
327 match res {
328 Ok(w) => {
329 let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
330 .into_iter()
331 .flatten()
332 .collect();
333 editor_step.items.push(SetupItem {
334 name: target.name.to_string(),
335 status: match w.action {
336 WriteAction::Created => "created".to_string(),
337 WriteAction::Updated => "updated".to_string(),
338 WriteAction::Already => "already".to_string(),
339 },
340 path: Some(short_path),
341 note: Some(note_parts.join("; ")),
342 });
343 }
344 Err(e) => {
345 editor_step.ok = false;
346 editor_step.items.push(SetupItem {
347 name: target.name.to_string(),
348 status: "error".to_string(),
349 path: Some(short_path),
350 note: Some(e),
351 });
352 }
353 }
354 }
355 editor_step
356}
357
358fn build_governor_step(
361 opts: &SetupOptions,
362 home: &std::path::Path,
363 targets: &[EditorTarget],
364 allows: &dyn Fn(&str) -> bool,
365) -> Option<SetupStepReport> {
366 use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_for_targets};
367 if opts.refresh_only && !lean_ctx::core::config::Config::load().setup.manage_hooks {
370 return None;
371 }
372 let mut step = setup_step("governor");
373 for (host, outcome) in apply_for_targets(home, targets, allows) {
374 if outcome.ran_steps() {
375 let _ = super::agent_selection::remember_connected_agent(host.key);
376 }
377 let notice = outcome.notice(host);
378 if !opts.json
379 && let Some(text) = ¬ice
380 {
381 eprintln!(" \u{2139} {text}");
382 }
383 let status = match &outcome {
384 Outcome::Installed => "created",
385 Outcome::Migrated(_) | Outcome::Completed => "updated",
386 Outcome::AlreadyGovernor => "already",
387 _ => "skipped",
388 };
389 let note = match &outcome {
390 Outcome::Pinned(mode) => format!("pinned mode {mode}"),
391 Outcome::SkippedThisVersion => format!(
392 "switched back after this version's migration; keep it: {}",
393 host.switch_back
394 ),
395 Outcome::AlreadyGovernor => "governor setup".to_string(),
396 _ => notice.unwrap_or_default(),
397 };
398 step.items.push(SetupItem {
399 name: host.name.to_string(),
400 status: status.to_string(),
401 path: None,
402 note: Some(note),
403 });
404 }
405 (!step.items.is_empty()).then_some(step)
406}
407
408fn should_inject_rules(opts: &SetupOptions, config_value: bool) -> bool {
409 if opts.skip_rules {
410 false
411 } else if opts.force_inject_rules {
412 true
413 } else if opts.yes && opts.non_interactive {
414 config_value
415 } else {
416 true
417 }
418}
419
420fn should_allow_rule_steering(opts: &SetupOptions, cfg: &lean_ctx::core::config::Config) -> bool {
421 if cfg.rules_injection_effective() == lean_ctx::core::config::RulesInjection::Off {
424 return false;
425 }
426
427 if opts.skip_rules {
429 return false;
430 }
431
432 if opts.force_inject_rules {
435 return true;
436 }
437
438 !cfg.declines_rule_steering()
442}
443
444fn should_inject_skills(opts: &SetupOptions, config_value: bool) -> bool {
445 should_inject_rules(opts, config_value)
446}
447
448fn build_rules_step(
449 opts: &SetupOptions,
450 home: &std::path::Path,
451 should_inject: bool,
452 allows: &dyn Fn(&str) -> bool,
453) -> SetupStepReport {
454 let mut rules_step = setup_step("agent_rules");
455 if should_inject {
456 let rules_result = lean_ctx::rules_inject::inject_rules_where(home, allows);
457 for n in rules_result.injected {
458 rules_step.items.push(SetupItem {
459 name: n,
460 status: "injected".to_string(),
461 path: None,
462 note: None,
463 });
464 }
465 for n in rules_result.updated {
466 rules_step.items.push(SetupItem {
467 name: n,
468 status: "updated".to_string(),
469 path: None,
470 note: None,
471 });
472 }
473 for n in rules_result.already {
474 rules_step.items.push(SetupItem {
475 name: n,
476 status: "already".to_string(),
477 path: None,
478 note: None,
479 });
480 }
481 if !rules_result.backed_up.is_empty() {
482 for bak in &rules_result.backed_up {
483 rules_step.items.push(SetupItem {
484 name: "backup".to_string(),
485 status: "created".to_string(),
486 path: Some(bak.clone()),
487 note: Some("previous version backed up".to_string()),
488 });
489 }
490 }
491 for e in rules_result.errors {
492 rules_step.ok = false;
493 rules_step.errors.push(e);
494 }
495 } else {
496 let reason = if opts.skip_rules {
497 "--skip-rules flag set"
498 } else {
499 "auto_inject_rules not enabled (run `lean-ctx setup` or set auto_inject_rules = true)"
500 };
501 rules_step.items.push(SetupItem {
502 name: "agent_rules".to_string(),
503 status: "skipped".to_string(),
504 path: None,
505 note: Some(reason.to_string()),
506 });
507 }
508 rules_step
509}
510
511fn build_rules_dedup_step(home: &std::path::Path, should_inject: bool) -> Option<SetupStepReport> {
512 if !should_inject {
513 return None;
514 }
515 let mut dedup_step = setup_step("rules_dedup");
516 let project = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
517 for line in crate::cli::rules_dedup::auto_apply(home, &project) {
518 let failed = line.starts_with("FAILED");
519 if failed {
520 dedup_step.warnings.push(line.clone());
521 }
522 dedup_step.items.push(SetupItem {
523 name: "dedup".to_string(),
524 status: if failed { "failed" } else { "applied" }.to_string(),
525 path: None,
526 note: Some(line),
527 });
528 }
529 Some(dedup_step)
530}
531
532fn build_skill_step(
533 home: &std::path::Path,
534 should_install_skills: bool,
535 allows: &dyn Fn(&str) -> bool,
536) -> Option<SetupStepReport> {
537 let mut skill_step = setup_step("skill_files");
538 if should_install_skills {
539 let skill_results = lean_ctx::rules_inject::install_skills_where(home, allows);
540 for (name, is_new) in &skill_results {
541 skill_step.items.push(SetupItem {
542 name: name.clone(),
543 status: if *is_new { "installed" } else { "already" }.to_string(),
544 path: None,
545 note: Some("SKILL.md".to_string()),
546 });
547 }
548 } else {
549 skill_step.items.push(SetupItem {
550 name: "skill_files".to_string(),
551 status: "skipped".to_string(),
552 path: None,
553 note: Some("auto_inject_skills not enabled".to_string()),
554 });
555 }
556 (!skill_step.items.is_empty()).then_some(skill_step)
557}
558
559fn build_agent_hooks_step(
560 targets: &[EditorTarget],
561 update_mcp: bool,
562 allow_rule_steering: bool,
563) -> Option<SetupStepReport> {
564 let mut hooks_step = setup_step("agent_hooks");
565
566 for target in targets {
567 if !target.detect_path.exists() || target.agent_key.is_empty() {
568 continue;
569 }
570
571 if let Some(home) = lean_ctx::core::home::resolve_home_dir()
574 && let Some(host) = lean_ctx_hooks::hooks::governor_default::host(&target.agent_key)
575 && (host.is_installed)(&home)
576 {
577 (host.refresh)(&home);
578 hooks_step.items.push(SetupItem {
579 name: format!("{} hooks", target.name),
580 status: "installed".to_string(),
581 path: Some(target.detect_path.to_string_lossy().to_string()),
582 note: Some(format!(
583 "mode=governor; no MCP server (switch back: {})",
584 host.switch_back
585 )),
586 });
587 continue;
588 }
589
590 let mode = recommend_hook_mode(&target.agent_key);
591
592 if allow_rule_steering {
593 lean_ctx_hooks::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
594 } else {
595 lean_ctx_hooks::hooks::install_agent_runtime_hook_with_mode(
596 &target.agent_key,
597 true,
598 mode,
599 );
600 }
601
602 let mcp_note = if update_mcp {
603 match configure_agent_mcp_with_rule_steering(&target.agent_key, allow_rule_steering) {
604 Ok(()) => "; MCP config updated".to_string(),
605 Err(e) => format!("; MCP config skipped: {e}"),
606 }
607 } else {
608 "; MCP registration skipped (auto_update_mcp=false)".to_string()
609 };
610
611 let mode = lean_ctx::core::home::resolve_home_dir().map_or_else(
612 || mode.to_string(),
613 |home| {
614 lean_ctx_hooks::hooks::governor_default::display_mode(
615 &target.agent_key,
616 &home,
617 mode,
618 )
619 },
620 );
621 hooks_step.items.push(SetupItem {
622 name: format!("{} hooks", target.name),
623 status: "installed".to_string(),
624 path: Some(target.detect_path.to_string_lossy().to_string()),
625 note: Some(format!(
626 "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
627 )),
628 });
629 }
630
631 (!hooks_step.items.is_empty()).then_some(hooks_step)
632}
633
634fn build_claude_mod_step(opts: &SetupOptions, targets: &[EditorTarget]) -> Option<SetupStepReport> {
640 use lean_ctx_hooks::hooks::agents::claude_mod::{self, ModStatus};
641 let claude_present = targets
642 .iter()
643 .any(|t| t.agent_key == "claude" && t.detect_path.exists());
644 if !claude_present {
645 return None;
646 }
647 let mut step = setup_step("claude_mod");
648 let item = |status: &str, note: String| SetupItem {
649 name: claude_mod::PLUGIN_ID.to_string(),
650 status: status.to_string(),
651 path: claude_mod::marketplace_dir()
652 .ok()
653 .map(|p| p.to_string_lossy().to_string()),
654 note: Some(note),
655 };
656 let quiet = opts.json;
657 if lean_ctx::core::home::resolve_home_dir()
662 .and_then(|h| lean_ctx_hooks::hooks::agents::claude_governor::installed_arm(&h))
663 == Some(lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred)
664 {
665 step.items.push(item(
666 "skipped",
667 "governor-mcp setup: the mod would front-load lean-ctx tool schemas \
668 (install anyway: lean-ctx claude-mod install)"
669 .to_string(),
670 ));
671 return Some(step);
672 }
673 match claude_mod::status() {
674 status @ (ModStatus::ClaudeMissing(_) | ModStatus::ClaudeTooOld(_)) => {
675 step.items.push(item("skipped", status.describe()));
676 }
677 ModStatus::Current(v) => step.items.push(item("already", v)),
678 ModStatus::Stale(_) => match claude_mod::install() {
679 Ok(msg) => step.items.push(item("updated", msg)),
680 Err(e) => {
681 step.warnings
682 .push(format!("claude mod refresh failed: {e}"));
683 step.items.push(item("error", e));
684 }
685 },
686 ModStatus::NotInstalled if claude_mod::auto_install_declined() => step.items.push(item(
687 "skipped",
688 "removed by you — bring it back with: lean-ctx claude-mod install".to_string(),
689 )),
690 ModStatus::NotInstalled => match claude_mod::install() {
691 Ok(msg) => {
692 if !quiet {
693 println!("\n {}", claude_mod::INSTALLED_NOTICE);
694 }
695 step.items.push(item("created", msg));
696 }
697 Err(e) => {
698 step.warnings
699 .push(format!("claude mod install failed: {e}"));
700 step.items.push(item("error", e));
701 }
702 },
703 }
704 Some(step)
705}
706
707fn build_tool_profile_step() -> SetupStepReport {
708 let mut tool_profile_step = setup_step("tool_profile");
709 let cfg = lean_ctx::core::config::Config::load();
710 if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
711 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
712 tool_profile_step.items.push(SetupItem {
713 name: "tool_profile".to_string(),
714 status: "lean default".to_string(),
715 path: None,
716 note: Some(format!(
717 "{lazy_count} tools advertised, all reachable via ctx_call \
718 (pin more with: lean-ctx tools standard|power)"
719 )),
720 });
721 } else {
722 let profile = cfg.tool_profile_effective();
723 let overhead_hint = match profile {
724 lean_ctx::core::tool_profiles::ToolProfile::Power => {
725 "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
726 }
727 _ => "",
728 };
729 tool_profile_step.items.push(SetupItem {
730 name: "tool_profile".to_string(),
731 status: "already".to_string(),
732 path: None,
733 note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
734 });
735 }
736 tool_profile_step
737}
738
739fn build_proxy_step(opts: &SetupOptions, home: &std::path::Path) -> SetupStepReport {
740 let mut proxy_step = setup_step("proxy");
741 if opts.skip_proxy {
742 proxy_step.items.push(SetupItem {
743 name: "proxy".to_string(),
744 status: "skipped".to_string(),
745 path: None,
746 note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
747 });
748 } else {
749 let proxy_cfg = lean_ctx::core::config::Config::load();
750 if proxy_cfg.proxy_enabled == Some(true) {
751 let proxy_port = crate::proxy_setup::default_port();
752 lean_ctx::proxy_autostart::install(proxy_port, true);
753 std::thread::sleep(std::time::Duration::from_millis(500));
754 crate::proxy_setup::install_proxy_env(home, proxy_port, opts.json);
755 proxy_step.items.push(SetupItem {
756 name: "proxy_autostart".to_string(),
757 status: "installed".to_string(),
758 path: None,
759 note: Some("LaunchAgent/systemd auto-start on login".to_string()),
760 });
761 proxy_step.items.push(SetupItem {
762 name: "proxy_env".to_string(),
763 status: "configured".to_string(),
764 path: None,
765 note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
766 });
767 } else {
768 proxy_step.items.push(SetupItem {
769 name: "proxy".to_string(),
770 status: "skipped".to_string(),
771 path: None,
772 note: Some(
773 "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
774 ),
775 });
776 }
777 }
778 proxy_step
779}
780
781fn build_doctor_compact_step() -> SetupStepReport {
782 let mut env_step = setup_step("doctor_compact");
783 let (passed, total) = crate::doctor::compact_score();
784 env_step.items.push(SetupItem {
785 name: "doctor".to_string(),
786 status: format!("{passed}/{total}"),
787 path: None,
788 note: None,
789 });
790 if passed != total {
791 env_step.warnings.push(format!(
792 "doctor compact not fully passing: {passed}/{total}"
793 ));
794 }
795 env_step
796}
797
798fn maybe_add_project_root_warning(steps: &mut Vec<SetupStepReport>) {
799 let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT").is_ok_and(|v| !v.is_empty());
800 let cfg = lean_ctx::core::config::Config::load();
801 let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
802
803 if has_env_root || has_cfg_root {
804 return;
805 }
806
807 let Ok(cwd) = std::env::current_dir() else {
808 return;
809 };
810 let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
811 if !is_home {
812 return;
813 }
814
815 let mut root_step = SetupStepReport {
816 name: "project_root".to_string(),
817 ok: true,
818 items: Vec::new(),
819 warnings: vec![
820 "No project_root configured. Running from $HOME can cause excessive scanning. \
821 Set via: lean-ctx config set project_root /path/to/project"
822 .to_string(),
823 ],
824 errors: Vec::new(),
825 };
826 root_step.items.push(SetupItem {
827 name: "project_root".to_string(),
828 status: "unconfigured".to_string(),
829 path: None,
830 note: Some("Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml".to_string()),
831 });
832 steps.push(root_step);
833}
834
835fn maybe_spawn_background_index() {
836 if let Ok(cwd) = std::env::current_dir()
837 && may_autoindex_cwd(&cwd)
838 && lean_ctx::core::pathutil::has_project_marker(&cwd)
839 {
840 spawn_index_build_background(&cwd);
841 }
842}
843
844fn maybe_enable_ide_config_access(opts: &SetupOptions) {
845 if !opts.yes
846 || opts.fix
847 || lean_ctx::core::config::Config::load()
848 .allow_ide_config_dirs
849 .is_some()
850 {
851 return;
852 }
853
854 match lean_ctx::core::config::Config::update_global(|c| {
855 c.allow_ide_config_dirs = Some(true);
856 }) {
857 Ok(_) => {
858 if !opts.json {
859 println!(
860 " Enabled IDE config access (allow_ide_config_dirs) — \
861 disable: lean-ctx config set allow_ide_config_dirs false"
862 );
863 }
864 }
865 Err(e) => tracing::warn!("could not enable IDE config access: {e}"),
866 }
867}
868
869fn build_setup_report(
870 started_at: chrono::DateTime<Utc>,
871 steps: Vec<SetupStepReport>,
872) -> SetupReport {
873 let finished_at = Utc::now();
874 let success = steps.iter().all(|s| s.ok);
875 SetupReport {
876 schema_version: 1,
877 started_at,
878 finished_at,
879 success,
880 platform: PlatformInfo {
881 os: std::env::consts::OS.to_string(),
882 arch: std::env::consts::ARCH.to_string(),
883 },
884 steps,
885 warnings: Vec::new(),
886 errors: Vec::new(),
887 }
888}
889
890fn persist_setup_report(report: &SetupReport) -> Result<(), String> {
891 let path = SetupReport::default_path()?;
892 let mut content =
893 serde_json::to_string_pretty(report).map_err(|e| format!("serialize report: {e}"))?;
894 content.push('\n');
895 lean_ctx::config_io::write_atomic(&path, &content)
896}
897
898#[cfg(test)]
899mod rule_steering_policy_tests {
900 use super::*;
901
902 fn without_rules_injection_env() -> lean_ctx::core::data_dir::TestEnvGuard {
906 let guard = lean_ctx::core::data_dir::test_env_lock();
907 lean_ctx::test_env::remove_var("LEAN_CTX_RULES_INJECTION");
908 guard
909 }
910
911 #[test]
912 fn editor_step_respects_commandcode_rule_steering_policy() {
913 let tmp = tempfile::tempdir().unwrap();
914 let detect = tmp.path().join("commandcode");
915 let config = detect.join("mcp.json");
916
917 std::fs::create_dir_all(&detect).unwrap();
918
919 let target = EditorTarget {
920 name: "Command Code",
921 agent_key: "commandcode".to_string(),
922 detect_path: detect,
923 config_path: config.clone(),
924 config_type: lean_ctx::core::editor_registry::ConfigType::CommandCode,
925 };
926
927 let report = build_editor_step(
928 &SetupOptions::default(),
929 tmp.path().to_string_lossy().as_ref(),
930 "lean-ctx",
931 &[target],
932 true,
933 false,
934 );
935
936 assert!(
937 report.ok,
938 "editor setup should configure MCP successfully: {:?}",
939 report.errors
940 );
941
942 let json: serde_json::Value =
943 serde_json::from_str(&std::fs::read_to_string(config).unwrap()).unwrap();
944
945 let entry = &json["mcpServers"]["lean-ctx"];
946
947 assert_eq!(entry["command"], "lean-ctx");
948 assert!(
949 entry.get("instructions").is_none(),
950 "the first setup editor writer must not bypass the steering opt-out"
951 );
952 }
953
954 #[test]
955 fn explicit_auto_false_declines_setup_steering() {
956 let _env = without_rules_injection_env();
957 let mut cfg = lean_ctx::core::config::Config::default();
958 cfg.setup.auto_inject_rules = Some(false);
959
960 assert!(!should_allow_rule_steering(&SetupOptions::default(), &cfg));
961 }
962
963 #[test]
964 fn force_overrides_auto_false_but_not_rules_off() {
965 let _env = without_rules_injection_env();
966 let force = SetupOptions {
967 force_inject_rules: true,
968 ..Default::default()
969 };
970
971 let mut cfg = lean_ctx::core::config::Config::default();
972 cfg.setup.auto_inject_rules = Some(false);
973
974 assert!(
975 should_allow_rule_steering(&force, &cfg),
976 "--force-inject-rules must override setup.auto_inject_rules=false"
977 );
978
979 cfg.rules_injection = Some("off".to_string());
980
981 assert!(
982 !should_allow_rule_steering(&force, &cfg),
983 "rules_injection=off remains absolute even with force"
984 );
985 }
986
987 #[test]
988 fn skip_rules_wins_over_force() {
989 let _env = without_rules_injection_env();
990 let opts = SetupOptions {
991 skip_rules: true,
992 force_inject_rules: true,
993 ..Default::default()
994 };
995
996 let cfg = lean_ctx::core::config::Config::default();
997
998 assert!(!should_allow_rule_steering(&opts, &cfg));
999 }
1000
1001 #[test]
1002 fn default_none_and_explicit_true_allow_setup_steering() {
1003 let _env = without_rules_injection_env();
1004 let default_cfg = lean_ctx::core::config::Config::default();
1005
1006 assert!(should_allow_rule_steering(
1007 &SetupOptions::default(),
1008 &default_cfg
1009 ));
1010
1011 let mut explicit_true = lean_ctx::core::config::Config::default();
1012 explicit_true.setup.auto_inject_rules = Some(true);
1013
1014 assert!(should_allow_rule_steering(
1015 &SetupOptions::default(),
1016 &explicit_true
1017 ));
1018 }
1019}