Skip to main content

lean_ctx_cli/setup/
with_options.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx_time::UtcDateTime;
3
4use lean_ctx::core::editor_registry::{EditorTarget, WriteAction, WriteOptions};
5use lean_ctx::core::portable_binary::resolve_agent_binary;
6use lean_ctx_ext::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 = UtcDateTime::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(!opts.refresh_only),
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 Cloud'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    // Setup and the rewire never disable an installed mod: only an explicit
704    // `init --mode governor-mcp` does, once (a re-enabled plugin stays on).
705    if lean_ctx::core::home::resolve_home_dir()
706        .and_then(|h| lean_ctx_hooks::hooks::agents::claude_governor::installed_arm(&h))
707        == Some(lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred)
708    {
709        step.items.push(item(
710            "skipped",
711            "governor-mcp setup: the mod would front-load lean-ctx tool schemas \
712             (install anyway: lean-ctx claude-mod install)"
713                .to_string(),
714        ));
715        return Some(step);
716    }
717    match claude_mod::status() {
718        status @ (ModStatus::ClaudeMissing(_) | ModStatus::ClaudeTooOld(_)) => {
719            step.items.push(item("skipped", status.describe()));
720        }
721        ModStatus::Current(v) => step.items.push(item("already", v)),
722        ModStatus::Stale(_) => match claude_mod::install() {
723            Ok(msg) => step.items.push(item("updated", msg)),
724            Err(e) => {
725                step.warnings
726                    .push(format!("claude mod refresh failed: {e}"));
727                step.items.push(item("error", e));
728            }
729        },
730        ModStatus::NotInstalled if claude_mod::auto_install_declined() => step.items.push(item(
731            "skipped",
732            "removed by you — bring it back with: lean-ctx claude-mod install".to_string(),
733        )),
734        ModStatus::NotInstalled => match claude_mod::install() {
735            Ok(msg) => {
736                if !quiet {
737                    println!("\n  {}", claude_mod::INSTALLED_NOTICE);
738                }
739                step.items.push(item("created", msg));
740            }
741            Err(e) => {
742                step.warnings
743                    .push(format!("claude mod install failed: {e}"));
744                step.items.push(item("error", e));
745            }
746        },
747    }
748    Some(step)
749}
750
751fn build_tool_profile_step() -> SetupStepReport {
752    let mut tool_profile_step = setup_step("tool_profile");
753    let cfg = lean_ctx::core::config::Config::load();
754    if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
755        let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
756        tool_profile_step.items.push(SetupItem {
757            name: "tool_profile".to_string(),
758            status: "lean default".to_string(),
759            path: None,
760            note: Some(format!(
761                "{lazy_count} tools advertised, all reachable via ctx_call \
762                 (pin more with: lean-ctx tools standard|power)"
763            )),
764        });
765    } else {
766        let profile = cfg.tool_profile_effective();
767        let overhead_hint = match profile {
768            lean_ctx::core::tool_profiles::ToolProfile::Power => {
769                "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
770            }
771            _ => "",
772        };
773        tool_profile_step.items.push(SetupItem {
774            name: "tool_profile".to_string(),
775            status: "already".to_string(),
776            path: None,
777            note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
778        });
779    }
780    tool_profile_step
781}
782
783fn build_proxy_step(opts: &SetupOptions, home: &std::path::Path) -> SetupStepReport {
784    let mut proxy_step = setup_step("proxy");
785    if opts.skip_proxy {
786        proxy_step.items.push(SetupItem {
787            name: "proxy".to_string(),
788            status: "skipped".to_string(),
789            path: None,
790            note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
791        });
792    } else {
793        let proxy_cfg = lean_ctx::core::config::Config::load();
794        if proxy_cfg.proxy_enabled == Some(true) {
795            let proxy_port = crate::proxy_setup::default_port();
796            lean_ctx::proxy_autostart::install(proxy_port, true);
797            std::thread::sleep(std::time::Duration::from_millis(500));
798            crate::proxy_setup::install_proxy_env(home, proxy_port, opts.json);
799            proxy_step.items.push(SetupItem {
800                name: "proxy_autostart".to_string(),
801                status: "installed".to_string(),
802                path: None,
803                note: Some("LaunchAgent/systemd auto-start on login".to_string()),
804            });
805            proxy_step.items.push(SetupItem {
806                name: "proxy_env".to_string(),
807                status: "configured".to_string(),
808                path: None,
809                note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
810            });
811        } else {
812            proxy_step.items.push(SetupItem {
813                name: "proxy".to_string(),
814                status: "skipped".to_string(),
815                path: None,
816                note: Some(
817                    "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
818                ),
819            });
820        }
821    }
822    proxy_step
823}
824
825fn build_doctor_compact_step() -> SetupStepReport {
826    let mut env_step = setup_step("doctor_compact");
827    let (passed, total) = crate::doctor::compact_score();
828    env_step.items.push(SetupItem {
829        name: "doctor".to_string(),
830        status: format!("{passed}/{total}"),
831        path: None,
832        note: None,
833    });
834    if passed != total {
835        env_step.warnings.push(format!(
836            "doctor compact not fully passing: {passed}/{total}"
837        ));
838    }
839    env_step
840}
841
842fn maybe_add_project_root_warning(steps: &mut Vec<SetupStepReport>) {
843    let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT").is_ok_and(|v| !v.is_empty());
844    let cfg = lean_ctx::core::config::Config::load();
845    let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
846
847    if has_env_root || has_cfg_root {
848        return;
849    }
850
851    let Ok(cwd) = std::env::current_dir() else {
852        return;
853    };
854    let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
855    if !is_home {
856        return;
857    }
858
859    let mut root_step = SetupStepReport {
860        name: "project_root".to_string(),
861        ok: true,
862        items: Vec::new(),
863        warnings: vec![
864            "No project_root configured. Running from $HOME can cause excessive scanning. \
865             Set via: lean-ctx config set project_root /path/to/project"
866                .to_string(),
867        ],
868        errors: Vec::new(),
869    };
870    root_step.items.push(SetupItem {
871        name: "project_root".to_string(),
872        status: "unconfigured".to_string(),
873        path: None,
874        note: Some("Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml".to_string()),
875    });
876    steps.push(root_step);
877}
878
879fn maybe_spawn_background_index() {
880    if let Ok(cwd) = std::env::current_dir()
881        && may_autoindex_cwd(&cwd)
882        && lean_ctx::core::pathutil::has_project_marker(&cwd)
883    {
884        spawn_index_build_background(&cwd);
885    }
886}
887
888fn maybe_enable_ide_config_access(opts: &SetupOptions) {
889    if !opts.yes
890        || opts.fix
891        || lean_ctx::core::config::Config::load()
892            .allow_ide_config_dirs
893            .is_some()
894    {
895        return;
896    }
897
898    match lean_ctx::core::config::Config::update_global(|c| {
899        c.allow_ide_config_dirs = Some(true);
900    }) {
901        Ok(_) => {
902            if !opts.json {
903                println!(
904                    "  Enabled IDE config access (allow_ide_config_dirs) — \
905                     disable: lean-ctx config set allow_ide_config_dirs false"
906                );
907            }
908        }
909        Err(e) => tracing::warn!("could not enable IDE config access: {e}"),
910    }
911}
912
913fn build_setup_report(
914    started_at: lean_ctx_time::UtcDateTime,
915    steps: Vec<SetupStepReport>,
916) -> SetupReport {
917    let finished_at = UtcDateTime::now();
918    let success = steps.iter().all(|s| s.ok);
919    SetupReport {
920        schema_version: 1,
921        started_at,
922        finished_at,
923        success,
924        platform: PlatformInfo {
925            os: std::env::consts::OS.to_string(),
926            arch: std::env::consts::ARCH.to_string(),
927        },
928        steps,
929        warnings: Vec::new(),
930        errors: Vec::new(),
931    }
932}
933
934fn persist_setup_report(report: &SetupReport) -> Result<(), String> {
935    let path = SetupReport::default_path()?;
936    let mut content =
937        serde_json::to_string_pretty(report).map_err(|e| format!("serialize report: {e}"))?;
938    content.push('\n');
939    lean_ctx::config_io::write_atomic(&path, &content)
940}
941
942#[cfg(test)]
943mod rule_steering_policy_tests {
944    use super::*;
945
946    /// `rules_injection_effective` prefers `LEAN_CTX_RULES_INJECTION` over the
947    /// config, and other tests set it concurrently. Hold the env lock and
948    /// clear it so the config under test decides.
949    fn without_rules_injection_env() -> lean_ctx::core::data_dir::TestEnvGuard {
950        let guard = lean_ctx::core::data_dir::test_env_lock();
951        lean_ctx::test_env::remove_var("LEAN_CTX_RULES_INJECTION");
952        guard
953    }
954
955    #[test]
956    fn editor_step_respects_commandcode_rule_steering_policy() {
957        let tmp = tempfile::tempdir().unwrap();
958        let detect = tmp.path().join("commandcode");
959        let config = detect.join("mcp.json");
960
961        std::fs::create_dir_all(&detect).unwrap();
962
963        let target = EditorTarget {
964            name: "Command Code",
965            agent_key: "commandcode".to_string(),
966            detect_path: detect,
967            config_path: config.clone(),
968            config_type: lean_ctx::core::editor_registry::ConfigType::CommandCode,
969        };
970
971        let report = build_editor_step(
972            &SetupOptions::default(),
973            tmp.path().to_string_lossy().as_ref(),
974            "lean-ctx",
975            &[target],
976            true,
977            false,
978        );
979
980        assert!(
981            report.ok,
982            "editor setup should configure MCP successfully: {:?}",
983            report.errors
984        );
985
986        let json: serde_json::Value =
987            serde_json::from_str(&std::fs::read_to_string(config).unwrap()).unwrap();
988
989        let entry = &json["mcpServers"]["lean-ctx"];
990
991        assert_eq!(entry["command"], "lean-ctx");
992        assert!(
993            entry.get("instructions").is_none(),
994            "the first setup editor writer must not bypass the steering opt-out"
995        );
996    }
997
998    #[test]
999    fn explicit_auto_false_declines_setup_steering() {
1000        let _env = without_rules_injection_env();
1001        let mut cfg = lean_ctx::core::config::Config::default();
1002        cfg.setup.auto_inject_rules = Some(false);
1003
1004        assert!(!should_allow_rule_steering(&SetupOptions::default(), &cfg));
1005    }
1006
1007    #[test]
1008    fn force_overrides_auto_false_but_not_rules_off() {
1009        let _env = without_rules_injection_env();
1010        let force = SetupOptions {
1011            force_inject_rules: true,
1012            ..Default::default()
1013        };
1014
1015        let mut cfg = lean_ctx::core::config::Config::default();
1016        cfg.setup.auto_inject_rules = Some(false);
1017
1018        assert!(
1019            should_allow_rule_steering(&force, &cfg),
1020            "--force-inject-rules must override setup.auto_inject_rules=false"
1021        );
1022
1023        cfg.rules_injection = Some("off".to_string());
1024
1025        assert!(
1026            !should_allow_rule_steering(&force, &cfg),
1027            "rules_injection=off remains absolute even with force"
1028        );
1029    }
1030
1031    #[test]
1032    fn skip_rules_wins_over_force() {
1033        let _env = without_rules_injection_env();
1034        let opts = SetupOptions {
1035            skip_rules: true,
1036            force_inject_rules: true,
1037            ..Default::default()
1038        };
1039
1040        let cfg = lean_ctx::core::config::Config::default();
1041
1042        assert!(!should_allow_rule_steering(&opts, &cfg));
1043    }
1044
1045    #[test]
1046    fn default_none_and_explicit_true_allow_setup_steering() {
1047        let _env = without_rules_injection_env();
1048        let default_cfg = lean_ctx::core::config::Config::default();
1049
1050        assert!(should_allow_rule_steering(
1051            &SetupOptions::default(),
1052            &default_cfg
1053        ));
1054
1055        let mut explicit_true = lean_ctx::core::config::Config::default();
1056        explicit_true.setup.auto_inject_rules = Some(true);
1057
1058        assert!(should_allow_rule_steering(
1059            &SetupOptions::default(),
1060            &explicit_true
1061        ));
1062    }
1063}