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    let mut daemon_step = setup_step("daemon");
249    let was_running = lean_ctx::daemon::is_daemon_running();
250    if was_running {
251        let _ = lean_ctx::daemon::stop_daemon();
252        std::thread::sleep(std::time::Duration::from_millis(500));
253    }
254    match lean_ctx::daemon::start_daemon(&[]) {
255        Ok(()) => {
256            let action = if was_running { "restarted" } else { "started" };
257            daemon_step.items.push(SetupItem {
258                name: "serve --daemon".to_string(),
259                status: action.to_string(),
260                path: Some(lean_ctx::daemon::daemon_addr().display()),
261                note: Some("CLI commands can route via IPC when running".to_string()),
262            });
263        }
264        Err(e) => {
265            daemon_step
266                .warnings
267                .push(format!("daemon start failed (non-fatal): {e}"));
268            daemon_step.items.push(SetupItem {
269                name: "serve --daemon".to_string(),
270                status: "skipped".to_string(),
271                path: None,
272                note: Some(format!("optional — {e}")),
273            });
274        }
275    }
276    daemon_step
277}
278
279fn build_editor_step(
280    opts: &SetupOptions,
281    home_str: &str,
282    binary: &str,
283    targets: &[EditorTarget],
284    update_mcp: bool,
285    allow_rule_steering: bool,
286) -> SetupStepReport {
287    let mut editor_step = setup_step("editors");
288    for target in targets {
289        let short_path = shorten_path(&target.config_path.to_string_lossy(), home_str);
290        if !target.detect_path.exists() {
291            editor_step.items.push(SetupItem {
292                name: target.name.to_string(),
293                status: "not_detected".to_string(),
294                path: Some(short_path),
295                note: None,
296            });
297            continue;
298        }
299
300        let mode = lean_ctx_hooks::hooks::governor_default::display_mode(
301            &target.agent_key,
302            std::path::Path::new(home_str),
303            if target.agent_key.is_empty() {
304                HookMode::Mcp
305            } else {
306                recommend_hook_mode(&target.agent_key)
307            },
308        );
309
310        if !update_mcp {
311            editor_step.items.push(SetupItem {
312                name: target.name.to_string(),
313                status: "skipped".to_string(),
314                path: Some(short_path),
315                note: Some(format!(
316                    "mode={mode}; MCP registration skipped (auto_update_mcp=false)"
317                )),
318            });
319            continue;
320        }
321
322        let res = lean_ctx::core::editor_registry::write_config_with_options_and_rule_steering(
323            target,
324            binary,
325            WriteOptions {
326                overwrite_invalid: opts.fix,
327            },
328            allow_rule_steering,
329        );
330        match res {
331            Ok(w) => {
332                let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
333                    .into_iter()
334                    .flatten()
335                    .collect();
336                editor_step.items.push(SetupItem {
337                    name: target.name.to_string(),
338                    status: match w.action {
339                        WriteAction::Created => "created".to_string(),
340                        WriteAction::Updated => "updated".to_string(),
341                        WriteAction::Already => "already".to_string(),
342                    },
343                    path: Some(short_path),
344                    note: Some(note_parts.join("; ")),
345                });
346            }
347            Err(e) => {
348                editor_step.ok = false;
349                editor_step.items.push(SetupItem {
350                    name: target.name.to_string(),
351                    status: "error".to_string(),
352                    path: Some(short_path),
353                    note: Some(e),
354                });
355            }
356        }
357    }
358    editor_step
359}
360
361/// The governor default per host that has one (a new Claude Code install
362/// gets governor-mcp, an automatic 3.12.1 migration is switched back; every
363/// existing or pinned setup is left to the standard steps). The notice is
364/// printed once, here.
365fn build_governor_step(
366    opts: &SetupOptions,
367    home: &std::path::Path,
368    targets: &[EditorTarget],
369    allows: &dyn Fn(&str) -> bool,
370) -> Option<SetupStepReport> {
371    use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_for_targets};
372    // `[setup] manage_hooks = false` (#1879): an update leaves hand-picked
373    // hook entries alone; only an explicit setup or init switches them.
374    if opts.refresh_only && !lean_ctx::core::config::Config::load().setup.manage_hooks {
375        return None;
376    }
377    let mut step = setup_step("governor");
378    for (host, outcome) in apply_for_targets(home, targets, allows) {
379        if outcome.ran_steps() {
380            let _ = super::agent_selection::remember_connected_agent(host.key);
381        }
382        let notice = outcome.notice(host);
383        if !opts.json
384            && let Some(text) = &notice
385        {
386            eprintln!("  \u{2139} {text}");
387        }
388        let status = match &outcome {
389            Outcome::Installed(_) => "created",
390            Outcome::Restored { .. } | Outcome::RuleModesEnabled(_) | Outcome::Completed => {
391                "updated"
392            }
393            Outcome::AlreadyGovernor => "already",
394            Outcome::Pinned(_) | Outcome::Standard => "skipped",
395        };
396        let note = match &outcome {
397            Outcome::Pinned(mode) => format!("pinned mode {mode}"),
398            Outcome::Standard => "standard setup kept".to_string(),
399            Outcome::AlreadyGovernor => "governor setup".to_string(),
400            _ => notice.unwrap_or_default(),
401        };
402        step.items.push(SetupItem {
403            name: host.name.to_string(),
404            status: status.to_string(),
405            path: None,
406            note: Some(note),
407        });
408    }
409    (!step.items.is_empty()).then_some(step)
410}
411
412fn should_inject_rules(opts: &SetupOptions, config_value: bool) -> bool {
413    if opts.skip_rules {
414        false
415    } else if opts.force_inject_rules {
416        true
417    } else if opts.yes && opts.non_interactive {
418        config_value
419    } else {
420        true
421    }
422}
423
424fn should_allow_rule_steering(opts: &SetupOptions, cfg: &lean_ctx::core::config::Config) -> bool {
425    // `rules_injection=off` is absolute: #1599 established "off means off,
426    // on every channel". The setup force flag must not resurrect steering.
427    if cfg.rules_injection_effective() == lean_ctx::core::config::RulesInjection::Off {
428        return false;
429    }
430
431    // An explicit skip wins even if the caller also passed force.
432    if opts.skip_rules {
433        return false;
434    }
435
436    // `--force-inject-rules` explicitly overrides setup.auto_inject_rules=false,
437    // but not the stronger rules_injection=off policy above.
438    if opts.force_inject_rules {
439        return true;
440    }
441
442    // A fresh/default setup may intentionally skip standalone rule files,
443    // but None is not an explicit steering opt-out. Only the central
444    // decline policy (or the stronger gates above) should suppress steering.
445    !cfg.declines_rule_steering()
446}
447
448fn should_inject_skills(opts: &SetupOptions, config_value: bool) -> bool {
449    should_inject_rules(opts, config_value)
450}
451
452fn build_rules_step(
453    opts: &SetupOptions,
454    home: &std::path::Path,
455    should_inject: bool,
456    allows: &dyn Fn(&str) -> bool,
457) -> SetupStepReport {
458    let mut rules_step = setup_step("agent_rules");
459    if should_inject {
460        let rules_result = lean_ctx::rules_inject::inject_rules_where(home, allows);
461        for n in rules_result.injected {
462            rules_step.items.push(SetupItem {
463                name: n,
464                status: "injected".to_string(),
465                path: None,
466                note: None,
467            });
468        }
469        for n in rules_result.updated {
470            rules_step.items.push(SetupItem {
471                name: n,
472                status: "updated".to_string(),
473                path: None,
474                note: None,
475            });
476        }
477        for n in rules_result.already {
478            rules_step.items.push(SetupItem {
479                name: n,
480                status: "already".to_string(),
481                path: None,
482                note: None,
483            });
484        }
485        if !rules_result.backed_up.is_empty() {
486            for bak in &rules_result.backed_up {
487                rules_step.items.push(SetupItem {
488                    name: "backup".to_string(),
489                    status: "created".to_string(),
490                    path: Some(bak.clone()),
491                    note: Some("previous version backed up".to_string()),
492                });
493            }
494        }
495        for e in rules_result.errors {
496            rules_step.ok = false;
497            rules_step.errors.push(e);
498        }
499    } else {
500        let reason = if opts.skip_rules {
501            "--skip-rules flag set"
502        } else {
503            "auto_inject_rules not enabled (run `lean-ctx setup` or set auto_inject_rules = true)"
504        };
505        rules_step.items.push(SetupItem {
506            name: "agent_rules".to_string(),
507            status: "skipped".to_string(),
508            path: None,
509            note: Some(reason.to_string()),
510        });
511    }
512    rules_step
513}
514
515fn build_rules_dedup_step(home: &std::path::Path, should_inject: bool) -> Option<SetupStepReport> {
516    if !should_inject {
517        return None;
518    }
519    let mut dedup_step = setup_step("rules_dedup");
520    let project = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
521    for line in crate::cli::rules_dedup::auto_apply(home, &project) {
522        let failed = line.starts_with("FAILED");
523        if failed {
524            dedup_step.warnings.push(line.clone());
525        }
526        dedup_step.items.push(SetupItem {
527            name: "dedup".to_string(),
528            status: if failed { "failed" } else { "applied" }.to_string(),
529            path: None,
530            note: Some(line),
531        });
532    }
533    Some(dedup_step)
534}
535
536fn build_skill_step(
537    home: &std::path::Path,
538    should_install_skills: bool,
539    allows: &dyn Fn(&str) -> bool,
540) -> Option<SetupStepReport> {
541    let mut skill_step = setup_step("skill_files");
542    if should_install_skills {
543        let skill_results = lean_ctx::rules_inject::install_skills_where(home, allows);
544        for (name, is_new) in &skill_results {
545            skill_step.items.push(SetupItem {
546                name: name.clone(),
547                status: if *is_new { "installed" } else { "already" }.to_string(),
548                path: None,
549                note: Some("SKILL.md".to_string()),
550            });
551        }
552    } else {
553        skill_step.items.push(SetupItem {
554            name: "skill_files".to_string(),
555            status: "skipped".to_string(),
556            path: None,
557            note: Some("auto_inject_skills not enabled".to_string()),
558        });
559    }
560    (!skill_step.items.is_empty()).then_some(skill_step)
561}
562
563fn build_agent_hooks_step(
564    targets: &[EditorTarget],
565    update_mcp: bool,
566    allow_rule_steering: bool,
567) -> Option<SetupStepReport> {
568    let mut hooks_step = setup_step("agent_hooks");
569
570    for target in targets {
571        if !target.detect_path.exists() || target.agent_key.is_empty() {
572            continue;
573        }
574
575        // The governor step ran first (`apply_for_targets`); a host that has the
576        // governor now only gets its hooks re-rendered.
577        if let Some(home) = lean_ctx::core::home::resolve_home_dir()
578            && let Some(host) = lean_ctx_hooks::hooks::governor_default::host(&target.agent_key)
579            && (host.is_installed)(&home)
580        {
581            (host.refresh)(&home);
582            let arm = if host.key == "claude"
583                && lean_ctx_hooks::hooks::agents::claude_governor::installed_arm(&home)
584                    == Some(
585                        lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred,
586                    ) {
587                "mode=governor-mcp; lean-ctx MCP server with deferred tools"
588            } else {
589                "mode=governor; no MCP server"
590            };
591            hooks_step.items.push(SetupItem {
592                name: format!("{} hooks", target.name),
593                status: "installed".to_string(),
594                path: Some(target.detect_path.to_string_lossy().to_string()),
595                note: Some(format!("{arm} (switch back: {})", host.switch_back)),
596            });
597            continue;
598        }
599
600        let mode = recommend_hook_mode(&target.agent_key);
601
602        if allow_rule_steering {
603            lean_ctx_hooks::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
604        } else {
605            lean_ctx_hooks::hooks::install_agent_runtime_hook_with_mode(
606                &target.agent_key,
607                true,
608                mode,
609            );
610        }
611
612        let mcp_note = if update_mcp {
613            match configure_agent_mcp_with_rule_steering(&target.agent_key, allow_rule_steering) {
614                Ok(()) => "; MCP config updated".to_string(),
615                Err(e) => format!("; MCP config skipped: {e}"),
616            }
617        } else {
618            "; MCP registration skipped (auto_update_mcp=false)".to_string()
619        };
620
621        let mode = lean_ctx::core::home::resolve_home_dir().map_or_else(
622            || mode.to_string(),
623            |home| {
624                lean_ctx_hooks::hooks::governor_default::display_mode(
625                    &target.agent_key,
626                    &home,
627                    mode,
628                )
629            },
630        );
631        hooks_step.items.push(SetupItem {
632            name: format!("{} hooks", target.name),
633            status: "installed".to_string(),
634            path: Some(target.detect_path.to_string_lossy().to_string()),
635            note: Some(format!(
636                "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
637            )),
638        });
639    }
640
641    (!hooks_step.items.is_empty()).then_some(hooks_step)
642}
643
644/// The lean-ctx Claude Code mod (cockpit, wake, a focused tool surface) is set
645/// up wherever Claude Code can host it — by setup and by the post-update rewire
646/// alike — and an installed one is rolled forward to this engine. It runs
647/// inside Claude Code, so the report says what was installed and how to remove
648/// it, and a removal (`lean-ctx claude-mod uninstall`) is never undone here.
649fn build_claude_mod_step(opts: &SetupOptions, targets: &[EditorTarget]) -> Option<SetupStepReport> {
650    use lean_ctx_hooks::hooks::agents::claude_mod::{self, ModStatus};
651    let claude_present = targets
652        .iter()
653        .any(|t| t.agent_key == "claude" && t.detect_path.exists());
654    if !claude_present {
655        return None;
656    }
657    let mut step = setup_step("claude_mod");
658    let item = |status: &str, note: String| SetupItem {
659        name: claude_mod::PLUGIN_ID.to_string(),
660        status: status.to_string(),
661        path: claude_mod::marketplace_dir()
662            .ok()
663            .map(|p| p.to_string_lossy().to_string()),
664        note: Some(note),
665    };
666    let quiet = opts.json;
667    // governor-mcp: the mod front-loads its configured lean-ctx tools
668    // (`front_loaded_tools`, 9 by default), which would put their schemas back
669    // into every request. The no-MCP governor has no lean-ctx MCP tools, so
670    // there the mod adds nothing the model sees (its hooks key on the server).
671    if lean_ctx::core::home::resolve_home_dir()
672        .and_then(|h| lean_ctx_hooks::hooks::agents::claude_governor::installed_arm(&h))
673        == Some(lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred)
674    {
675        step.items.push(item(
676            "skipped",
677            "governor-mcp setup: the mod would front-load lean-ctx tool schemas \
678             (install anyway: lean-ctx claude-mod install)"
679                .to_string(),
680        ));
681        return Some(step);
682    }
683    match claude_mod::status() {
684        status @ (ModStatus::ClaudeMissing(_) | ModStatus::ClaudeTooOld(_)) => {
685            step.items.push(item("skipped", status.describe()));
686        }
687        ModStatus::Current(v) => step.items.push(item("already", v)),
688        ModStatus::Stale(_) => match claude_mod::install() {
689            Ok(msg) => step.items.push(item("updated", msg)),
690            Err(e) => {
691                step.warnings
692                    .push(format!("claude mod refresh failed: {e}"));
693                step.items.push(item("error", e));
694            }
695        },
696        ModStatus::NotInstalled if claude_mod::auto_install_declined() => step.items.push(item(
697            "skipped",
698            "removed by you — bring it back with: lean-ctx claude-mod install".to_string(),
699        )),
700        ModStatus::NotInstalled => match claude_mod::install() {
701            Ok(msg) => {
702                if !quiet {
703                    println!("\n  {}", claude_mod::INSTALLED_NOTICE);
704                }
705                step.items.push(item("created", msg));
706            }
707            Err(e) => {
708                step.warnings
709                    .push(format!("claude mod install failed: {e}"));
710                step.items.push(item("error", e));
711            }
712        },
713    }
714    Some(step)
715}
716
717fn build_tool_profile_step() -> SetupStepReport {
718    let mut tool_profile_step = setup_step("tool_profile");
719    let cfg = lean_ctx::core::config::Config::load();
720    if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
721        let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
722        tool_profile_step.items.push(SetupItem {
723            name: "tool_profile".to_string(),
724            status: "lean default".to_string(),
725            path: None,
726            note: Some(format!(
727                "{lazy_count} tools advertised, all reachable via ctx_call \
728                 (pin more with: lean-ctx tools standard|power)"
729            )),
730        });
731    } else {
732        let profile = cfg.tool_profile_effective();
733        let overhead_hint = match profile {
734            lean_ctx::core::tool_profiles::ToolProfile::Power => {
735                "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
736            }
737            _ => "",
738        };
739        tool_profile_step.items.push(SetupItem {
740            name: "tool_profile".to_string(),
741            status: "already".to_string(),
742            path: None,
743            note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
744        });
745    }
746    tool_profile_step
747}
748
749fn build_proxy_step(opts: &SetupOptions, home: &std::path::Path) -> SetupStepReport {
750    let mut proxy_step = setup_step("proxy");
751    if opts.skip_proxy {
752        proxy_step.items.push(SetupItem {
753            name: "proxy".to_string(),
754            status: "skipped".to_string(),
755            path: None,
756            note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
757        });
758    } else {
759        let proxy_cfg = lean_ctx::core::config::Config::load();
760        if proxy_cfg.proxy_enabled == Some(true) {
761            let proxy_port = crate::proxy_setup::default_port();
762            lean_ctx::proxy_autostart::install(proxy_port, true);
763            std::thread::sleep(std::time::Duration::from_millis(500));
764            crate::proxy_setup::install_proxy_env(home, proxy_port, opts.json);
765            proxy_step.items.push(SetupItem {
766                name: "proxy_autostart".to_string(),
767                status: "installed".to_string(),
768                path: None,
769                note: Some("LaunchAgent/systemd auto-start on login".to_string()),
770            });
771            proxy_step.items.push(SetupItem {
772                name: "proxy_env".to_string(),
773                status: "configured".to_string(),
774                path: None,
775                note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
776            });
777        } else {
778            proxy_step.items.push(SetupItem {
779                name: "proxy".to_string(),
780                status: "skipped".to_string(),
781                path: None,
782                note: Some(
783                    "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
784                ),
785            });
786        }
787    }
788    proxy_step
789}
790
791fn build_doctor_compact_step() -> SetupStepReport {
792    let mut env_step = setup_step("doctor_compact");
793    let (passed, total) = crate::doctor::compact_score();
794    env_step.items.push(SetupItem {
795        name: "doctor".to_string(),
796        status: format!("{passed}/{total}"),
797        path: None,
798        note: None,
799    });
800    if passed != total {
801        env_step.warnings.push(format!(
802            "doctor compact not fully passing: {passed}/{total}"
803        ));
804    }
805    env_step
806}
807
808fn maybe_add_project_root_warning(steps: &mut Vec<SetupStepReport>) {
809    let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT").is_ok_and(|v| !v.is_empty());
810    let cfg = lean_ctx::core::config::Config::load();
811    let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
812
813    if has_env_root || has_cfg_root {
814        return;
815    }
816
817    let Ok(cwd) = std::env::current_dir() else {
818        return;
819    };
820    let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
821    if !is_home {
822        return;
823    }
824
825    let mut root_step = SetupStepReport {
826        name: "project_root".to_string(),
827        ok: true,
828        items: Vec::new(),
829        warnings: vec![
830            "No project_root configured. Running from $HOME can cause excessive scanning. \
831             Set via: lean-ctx config set project_root /path/to/project"
832                .to_string(),
833        ],
834        errors: Vec::new(),
835    };
836    root_step.items.push(SetupItem {
837        name: "project_root".to_string(),
838        status: "unconfigured".to_string(),
839        path: None,
840        note: Some("Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml".to_string()),
841    });
842    steps.push(root_step);
843}
844
845fn maybe_spawn_background_index() {
846    if let Ok(cwd) = std::env::current_dir()
847        && may_autoindex_cwd(&cwd)
848        && lean_ctx::core::pathutil::has_project_marker(&cwd)
849    {
850        spawn_index_build_background(&cwd);
851    }
852}
853
854fn maybe_enable_ide_config_access(opts: &SetupOptions) {
855    if !opts.yes
856        || opts.fix
857        || lean_ctx::core::config::Config::load()
858            .allow_ide_config_dirs
859            .is_some()
860    {
861        return;
862    }
863
864    match lean_ctx::core::config::Config::update_global(|c| {
865        c.allow_ide_config_dirs = Some(true);
866    }) {
867        Ok(_) => {
868            if !opts.json {
869                println!(
870                    "  Enabled IDE config access (allow_ide_config_dirs) — \
871                     disable: lean-ctx config set allow_ide_config_dirs false"
872                );
873            }
874        }
875        Err(e) => tracing::warn!("could not enable IDE config access: {e}"),
876    }
877}
878
879fn build_setup_report(
880    started_at: chrono::DateTime<Utc>,
881    steps: Vec<SetupStepReport>,
882) -> SetupReport {
883    let finished_at = Utc::now();
884    let success = steps.iter().all(|s| s.ok);
885    SetupReport {
886        schema_version: 1,
887        started_at,
888        finished_at,
889        success,
890        platform: PlatformInfo {
891            os: std::env::consts::OS.to_string(),
892            arch: std::env::consts::ARCH.to_string(),
893        },
894        steps,
895        warnings: Vec::new(),
896        errors: Vec::new(),
897    }
898}
899
900fn persist_setup_report(report: &SetupReport) -> Result<(), String> {
901    let path = SetupReport::default_path()?;
902    let mut content =
903        serde_json::to_string_pretty(report).map_err(|e| format!("serialize report: {e}"))?;
904    content.push('\n');
905    lean_ctx::config_io::write_atomic(&path, &content)
906}
907
908#[cfg(test)]
909mod rule_steering_policy_tests {
910    use super::*;
911
912    /// `rules_injection_effective` prefers `LEAN_CTX_RULES_INJECTION` over the
913    /// config, and other tests set it concurrently. Hold the env lock and
914    /// clear it so the config under test decides.
915    fn without_rules_injection_env() -> lean_ctx::core::data_dir::TestEnvGuard {
916        let guard = lean_ctx::core::data_dir::test_env_lock();
917        lean_ctx::test_env::remove_var("LEAN_CTX_RULES_INJECTION");
918        guard
919    }
920
921    #[test]
922    fn editor_step_respects_commandcode_rule_steering_policy() {
923        let tmp = tempfile::tempdir().unwrap();
924        let detect = tmp.path().join("commandcode");
925        let config = detect.join("mcp.json");
926
927        std::fs::create_dir_all(&detect).unwrap();
928
929        let target = EditorTarget {
930            name: "Command Code",
931            agent_key: "commandcode".to_string(),
932            detect_path: detect,
933            config_path: config.clone(),
934            config_type: lean_ctx::core::editor_registry::ConfigType::CommandCode,
935        };
936
937        let report = build_editor_step(
938            &SetupOptions::default(),
939            tmp.path().to_string_lossy().as_ref(),
940            "lean-ctx",
941            &[target],
942            true,
943            false,
944        );
945
946        assert!(
947            report.ok,
948            "editor setup should configure MCP successfully: {:?}",
949            report.errors
950        );
951
952        let json: serde_json::Value =
953            serde_json::from_str(&std::fs::read_to_string(config).unwrap()).unwrap();
954
955        let entry = &json["mcpServers"]["lean-ctx"];
956
957        assert_eq!(entry["command"], "lean-ctx");
958        assert!(
959            entry.get("instructions").is_none(),
960            "the first setup editor writer must not bypass the steering opt-out"
961        );
962    }
963
964    #[test]
965    fn explicit_auto_false_declines_setup_steering() {
966        let _env = without_rules_injection_env();
967        let mut cfg = lean_ctx::core::config::Config::default();
968        cfg.setup.auto_inject_rules = Some(false);
969
970        assert!(!should_allow_rule_steering(&SetupOptions::default(), &cfg));
971    }
972
973    #[test]
974    fn force_overrides_auto_false_but_not_rules_off() {
975        let _env = without_rules_injection_env();
976        let force = SetupOptions {
977            force_inject_rules: true,
978            ..Default::default()
979        };
980
981        let mut cfg = lean_ctx::core::config::Config::default();
982        cfg.setup.auto_inject_rules = Some(false);
983
984        assert!(
985            should_allow_rule_steering(&force, &cfg),
986            "--force-inject-rules must override setup.auto_inject_rules=false"
987        );
988
989        cfg.rules_injection = Some("off".to_string());
990
991        assert!(
992            !should_allow_rule_steering(&force, &cfg),
993            "rules_injection=off remains absolute even with force"
994        );
995    }
996
997    #[test]
998    fn skip_rules_wins_over_force() {
999        let _env = without_rules_injection_env();
1000        let opts = SetupOptions {
1001            skip_rules: true,
1002            force_inject_rules: true,
1003            ..Default::default()
1004        };
1005
1006        let cfg = lean_ctx::core::config::Config::default();
1007
1008        assert!(!should_allow_rule_steering(&opts, &cfg));
1009    }
1010
1011    #[test]
1012    fn default_none_and_explicit_true_allow_setup_steering() {
1013        let _env = without_rules_injection_env();
1014        let default_cfg = lean_ctx::core::config::Config::default();
1015
1016        assert!(should_allow_rule_steering(
1017            &SetupOptions::default(),
1018            &default_cfg
1019        ));
1020
1021        let mut explicit_true = lean_ctx::core::config::Config::default();
1022        explicit_true.setup.auto_inject_rules = Some(true);
1023
1024        assert!(should_allow_rule_steering(
1025            &SetupOptions::default(),
1026            &explicit_true
1027        ));
1028    }
1029}