Skip to main content

lean_ctx_cli/setup/
with_options.rs

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