lean-ctx 3.11.0

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
use chrono::Utc;

use crate::core::editor_registry::{EditorTarget, WriteAction, WriteOptions};
use crate::core::portable_binary::resolve_agent_binary;
use crate::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
use crate::hooks::{HookMode, recommend_hook_mode};

use super::helpers::shorten_path;
use super::index_build::{may_autoindex_cwd, spawn_index_build_background};
use super::mcp::configure_agent_mcp_with_rule_steering;
use super::options::SetupOptions;

pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
    let _quiet_guard = opts.json.then(crate::core::runtime_flags::scoped_quiet);
    let started_at = Utc::now();
    let home = crate::core::home::resolve_home_dir()
        .ok_or_else(|| "Cannot determine home directory".to_string())?;
    let binary = resolve_agent_binary();
    let home_str = home.to_string_lossy().to_string();

    // Commit to the XDG layout (and drain any residual ~/.lean-ctx) so a stray
    // marker can never re-collapse config/data/state/cache later (GL #623).
    crate::core::layout_pin::heal();

    let targets = crate::core::editor_registry::build_targets(&home);
    let cfg = crate::core::config::Config::load();
    let update_mcp = cfg.setup.should_update_mcp();
    let should_inject = should_inject_rules(opts, cfg.setup.should_inject_rules());
    let allow_rule_steering = should_allow_rule_steering(opts, &cfg);
    let should_install_skills = should_inject_skills(opts, cfg.setup.should_inject_skills());

    let mut steps = vec![
        build_shell_hook_step(opts, &binary),
        build_daemon_step(),
        build_editor_step(
            opts,
            &home_str,
            &binary,
            &targets,
            update_mcp,
            allow_rule_steering,
        ),
        build_rules_step(opts, &home, should_inject),
    ];

    if let Some(step) = build_rules_dedup_step(&home, should_inject) {
        steps.push(step);
    }
    if let Some(step) = build_skill_step(&home, should_install_skills) {
        steps.push(step);
    }
    if let Some(step) = build_agent_hooks_step(&targets, update_mcp, allow_rule_steering) {
        steps.push(step);
    }

    steps.extend([
        super::intelligence::report(),
        build_tool_profile_step(),
        build_proxy_step(opts, &home),
        build_doctor_compact_step(),
    ]);
    if let Some(step) = build_claude_mod_step(opts, &targets) {
        steps.push(step);
    }

    maybe_add_project_root_warning(&mut steps);
    maybe_spawn_background_index();
    maybe_enable_ide_config_access(opts);

    let report = build_setup_report(started_at, steps);
    persist_setup_report(&report)?;
    if report.success {
        let successful_names = report
            .steps
            .iter()
            .filter(|step| step.name == "editors")
            .flat_map(|step| &step.items)
            .filter(|item| matches!(item.status.as_str(), "created" | "updated" | "already"))
            .map(|item| item.name.as_str())
            .collect::<Vec<_>>();
        let integrations = targets
            .iter()
            .filter(|target| successful_names.contains(&target.name))
            .map(|target| target.agent_key.clone())
            .collect::<Vec<_>>();
        if let Err(error) = crate::core::telemetry_aggregate::record_setup_completion(integrations)
        {
            tracing::debug!("telemetry setup aggregate unavailable: {error}");
        }
    }

    Ok(report)
}

fn setup_step(name: &str) -> SetupStepReport {
    SetupStepReport {
        name: name.to_string(),
        ok: true,
        items: Vec::new(),
        warnings: Vec::new(),
        errors: Vec::new(),
    }
}

fn build_shell_hook_step(opts: SetupOptions, _binary: &str) -> SetupStepReport {
    let mut shell_step = setup_step("shell_hook");
    if !opts.non_interactive || opts.yes {
        if opts.json {
            crate::cli::cmd_init_quiet(&["--global".to_string()]);
        } else {
            crate::cli::cmd_init(&["--global".to_string()]);
        }
        crate::shell_hook::install_all(opts.json);
        #[cfg(not(windows))]
        {
            // Same stable PATH entry `init` embeds in the hook (#1851).
            let binary = crate::core::portable_binary::stable_shell_binary(_binary);
            let hook_content = crate::cli::generate_hook_posix(&binary);
            if crate::shell::is_container() {
                crate::cli::write_env_sh_for_containers(&hook_content);
                shell_step.items.push(SetupItem {
                    name: "env_sh".to_string(),
                    status: "created".to_string(),
                    path: Some(crate::core::paths::config_dir().map_or_else(
                        |_| "~/.config/lean-ctx/env.sh".to_string(),
                        |d| d.join("env.sh").to_string_lossy().to_string(),
                    )),
                    note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
                });
            } else {
                shell_step.items.push(SetupItem {
                    name: "env_sh".to_string(),
                    status: "skipped".to_string(),
                    path: None,
                    note: Some("not a container environment".to_string()),
                });
            }
        }
        shell_step.items.push(SetupItem {
            name: "init --global".to_string(),
            status: "ran".to_string(),
            path: None,
            note: None,
        });
        shell_step.items.push(SetupItem {
            name: "universal_shell_hook".to_string(),
            status: "installed".to_string(),
            path: None,
            note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
        });
    } else {
        shell_step
            .warnings
            .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
        shell_step.ok = false;
        shell_step.items.push(SetupItem {
            name: "init --global".to_string(),
            status: "skipped".to_string(),
            path: None,
            note: Some("requires --yes in --non-interactive mode".to_string()),
        });
    }
    shell_step
}

fn build_daemon_step() -> SetupStepReport {
    let mut daemon_step = setup_step("daemon");
    let was_running = crate::daemon::is_daemon_running();
    if was_running {
        let _ = crate::daemon::stop_daemon();
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    match crate::daemon::start_daemon(&[]) {
        Ok(()) => {
            let action = if was_running { "restarted" } else { "started" };
            daemon_step.items.push(SetupItem {
                name: "serve --daemon".to_string(),
                status: action.to_string(),
                path: Some(crate::daemon::daemon_addr().display()),
                note: Some("CLI commands can route via IPC when running".to_string()),
            });
        }
        Err(e) => {
            daemon_step
                .warnings
                .push(format!("daemon start failed (non-fatal): {e}"));
            daemon_step.items.push(SetupItem {
                name: "serve --daemon".to_string(),
                status: "skipped".to_string(),
                path: None,
                note: Some(format!("optional — {e}")),
            });
        }
    }
    daemon_step
}

fn build_editor_step(
    opts: SetupOptions,
    home_str: &str,
    binary: &str,
    targets: &[EditorTarget],
    update_mcp: bool,
    allow_rule_steering: bool,
) -> SetupStepReport {
    let mut editor_step = setup_step("editors");
    for target in targets {
        let short_path = shorten_path(&target.config_path.to_string_lossy(), home_str);
        if !target.detect_path.exists() {
            editor_step.items.push(SetupItem {
                name: target.name.to_string(),
                status: "not_detected".to_string(),
                path: Some(short_path),
                note: None,
            });
            continue;
        }

        let mode = if target.agent_key.is_empty() {
            HookMode::Mcp
        } else {
            recommend_hook_mode(&target.agent_key)
        };

        if !update_mcp {
            editor_step.items.push(SetupItem {
                name: target.name.to_string(),
                status: "skipped".to_string(),
                path: Some(short_path),
                note: Some(format!(
                    "mode={mode}; MCP registration skipped (auto_update_mcp=false)"
                )),
            });
            continue;
        }

        let res = crate::core::editor_registry::write_config_with_options_and_rule_steering(
            target,
            binary,
            WriteOptions {
                overwrite_invalid: opts.fix,
            },
            allow_rule_steering,
        );
        match res {
            Ok(w) => {
                let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
                    .into_iter()
                    .flatten()
                    .collect();
                editor_step.items.push(SetupItem {
                    name: target.name.to_string(),
                    status: match w.action {
                        WriteAction::Created => "created".to_string(),
                        WriteAction::Updated => "updated".to_string(),
                        WriteAction::Already => "already".to_string(),
                    },
                    path: Some(short_path),
                    note: Some(note_parts.join("; ")),
                });
            }
            Err(e) => {
                editor_step.ok = false;
                editor_step.items.push(SetupItem {
                    name: target.name.to_string(),
                    status: "error".to_string(),
                    path: Some(short_path),
                    note: Some(e),
                });
            }
        }
    }
    editor_step
}

fn should_inject_rules(opts: SetupOptions, config_value: bool) -> bool {
    if opts.skip_rules {
        false
    } else if opts.force_inject_rules {
        true
    } else if opts.yes && opts.non_interactive {
        config_value
    } else {
        true
    }
}

fn should_allow_rule_steering(opts: SetupOptions, cfg: &crate::core::config::Config) -> bool {
    // `rules_injection=off` is absolute: #1599 established "off means off,
    // on every channel". The setup force flag must not resurrect steering.
    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
        return false;
    }

    // An explicit skip wins even if the caller also passed force.
    if opts.skip_rules {
        return false;
    }

    // `--force-inject-rules` explicitly overrides setup.auto_inject_rules=false,
    // but not the stronger rules_injection=off policy above.
    if opts.force_inject_rules {
        return true;
    }

    // A fresh/default setup may intentionally skip standalone rule files,
    // but None is not an explicit steering opt-out. Only the central
    // decline policy (or the stronger gates above) should suppress steering.
    !cfg.declines_rule_steering()
}

fn should_inject_skills(opts: SetupOptions, config_value: bool) -> bool {
    should_inject_rules(opts, config_value)
}

fn build_rules_step(
    opts: SetupOptions,
    home: &std::path::Path,
    should_inject: bool,
) -> SetupStepReport {
    let mut rules_step = setup_step("agent_rules");
    if should_inject {
        let rules_result = crate::rules_inject::inject_all_rules(home);
        for n in rules_result.injected {
            rules_step.items.push(SetupItem {
                name: n,
                status: "injected".to_string(),
                path: None,
                note: None,
            });
        }
        for n in rules_result.updated {
            rules_step.items.push(SetupItem {
                name: n,
                status: "updated".to_string(),
                path: None,
                note: None,
            });
        }
        for n in rules_result.already {
            rules_step.items.push(SetupItem {
                name: n,
                status: "already".to_string(),
                path: None,
                note: None,
            });
        }
        if !rules_result.backed_up.is_empty() {
            for bak in &rules_result.backed_up {
                rules_step.items.push(SetupItem {
                    name: "backup".to_string(),
                    status: "created".to_string(),
                    path: Some(bak.clone()),
                    note: Some("previous version backed up".to_string()),
                });
            }
        }
        for e in rules_result.errors {
            rules_step.ok = false;
            rules_step.errors.push(e);
        }
    } else {
        let reason = if opts.skip_rules {
            "--skip-rules flag set"
        } else {
            "auto_inject_rules not enabled (run `lean-ctx setup` or set auto_inject_rules = true)"
        };
        rules_step.items.push(SetupItem {
            name: "agent_rules".to_string(),
            status: "skipped".to_string(),
            path: None,
            note: Some(reason.to_string()),
        });
    }
    rules_step
}

fn build_rules_dedup_step(home: &std::path::Path, should_inject: bool) -> Option<SetupStepReport> {
    if !should_inject {
        return None;
    }
    let mut dedup_step = setup_step("rules_dedup");
    let project = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
    for line in crate::cli::rules_dedup::auto_apply(home, &project) {
        let failed = line.starts_with("FAILED");
        if failed {
            dedup_step.warnings.push(line.clone());
        }
        dedup_step.items.push(SetupItem {
            name: "dedup".to_string(),
            status: if failed { "failed" } else { "applied" }.to_string(),
            path: None,
            note: Some(line),
        });
    }
    Some(dedup_step)
}

fn build_skill_step(
    home: &std::path::Path,
    should_install_skills: bool,
) -> Option<SetupStepReport> {
    let mut skill_step = setup_step("skill_files");
    if should_install_skills {
        let skill_results = crate::rules_inject::install_all_skills(home);
        for (name, is_new) in &skill_results {
            skill_step.items.push(SetupItem {
                name: name.clone(),
                status: if *is_new { "installed" } else { "already" }.to_string(),
                path: None,
                note: Some("SKILL.md".to_string()),
            });
        }
    } else {
        skill_step.items.push(SetupItem {
            name: "skill_files".to_string(),
            status: "skipped".to_string(),
            path: None,
            note: Some("auto_inject_skills not enabled".to_string()),
        });
    }
    (!skill_step.items.is_empty()).then_some(skill_step)
}

fn build_agent_hooks_step(
    targets: &[EditorTarget],
    update_mcp: bool,
    allow_rule_steering: bool,
) -> Option<SetupStepReport> {
    let mut hooks_step = setup_step("agent_hooks");

    for target in targets {
        if !target.detect_path.exists() || target.agent_key.is_empty() {
            continue;
        }

        let mode = recommend_hook_mode(&target.agent_key);

        if allow_rule_steering {
            crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
        } else {
            crate::hooks::install_agent_runtime_hook_with_mode(&target.agent_key, true, mode);
        }

        let mcp_note = if update_mcp {
            match configure_agent_mcp_with_rule_steering(&target.agent_key, allow_rule_steering) {
                Ok(()) => "; MCP config updated".to_string(),
                Err(e) => format!("; MCP config skipped: {e}"),
            }
        } else {
            "; MCP registration skipped (auto_update_mcp=false)".to_string()
        };

        hooks_step.items.push(SetupItem {
            name: format!("{} hooks", target.name),
            status: "installed".to_string(),
            path: Some(target.detect_path.to_string_lossy().to_string()),
            note: Some(format!(
                "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
            )),
        });
    }

    (!hooks_step.items.is_empty()).then_some(hooks_step)
}

/// The lean-ctx Claude Code mod is code that runs inside Claude Code, so it is
/// only ever *installed* on an interactive yes (or `lean-ctx claude-mod
/// install`). Unattended runs — `--non-interactive`, `--yes`, `--json` and the
/// post-update rewire — only roll an existing install forward to this engine.
fn build_claude_mod_step(opts: SetupOptions, targets: &[EditorTarget]) -> Option<SetupStepReport> {
    use crate::hooks::agents::claude_mod::{self, ModStatus};
    let claude_present = targets
        .iter()
        .any(|t| t.agent_key == "claude" && t.detect_path.exists());
    if !claude_present {
        return None;
    }
    let mut step = setup_step("claude_mod");
    let item = |status: &str, note: String| SetupItem {
        name: claude_mod::PLUGIN_ID.to_string(),
        status: status.to_string(),
        path: claude_mod::marketplace_dir()
            .ok()
            .map(|p| p.to_string_lossy().to_string()),
        note: Some(note),
    };
    // `--yes` approves the setup's own changes, not running new code inside
    // Claude Code; without a TTY there is nobody to ask (and the generic
    // refusal would wrongly suggest `--yes`).
    let unattended = opts.non_interactive
        || opts.json
        || opts.yes
        || !std::io::IsTerminal::is_terminal(&std::io::stdin());
    match claude_mod::status() {
        status @ (ModStatus::ClaudeMissing | ModStatus::ClaudeTooOld(_)) => {
            step.items.push(item("skipped", status.describe()));
        }
        ModStatus::Current(v) => step.items.push(item("already", v)),
        ModStatus::Stale(_) => match claude_mod::install() {
            Ok(msg) => step.items.push(item("updated", msg)),
            Err(e) => {
                step.warnings
                    .push(format!("claude mod refresh failed: {e}"));
                step.items.push(item("error", e));
            }
        },
        ModStatus::NotInstalled if unattended => step.items.push(item(
            "skipped",
            "optional — install with: lean-ctx claude-mod install".to_string(),
        )),
        ModStatus::NotInstalled => {
            println!(
                "\n  lean-ctx Claude Code mod: wakes the model when background jobs finish \
                 (no sleep/status polling), keeps lean-ctx's core tools in front, and adds \
                 /leanctx with this session's real token usage. Runs inside Claude Code; \
                 remove anytime with `lean-ctx claude-mod uninstall`."
            );
            if crate::cli::prompt::confirm("  Install it?", false) {
                match claude_mod::install() {
                    Ok(msg) => step.items.push(item("created", msg)),
                    Err(e) => {
                        step.warnings
                            .push(format!("claude mod install failed: {e}"));
                        step.items.push(item("error", e));
                    }
                }
            } else {
                step.items.push(item(
                    "skipped",
                    "declined — install later with: lean-ctx claude-mod install".to_string(),
                ));
            }
        }
    }
    Some(step)
}

fn build_tool_profile_step() -> SetupStepReport {
    let mut tool_profile_step = setup_step("tool_profile");
    let cfg = crate::core::config::Config::load();
    if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
        let lazy_count = crate::tool_defs::core_tool_names().len();
        tool_profile_step.items.push(SetupItem {
            name: "tool_profile".to_string(),
            status: "lean default".to_string(),
            path: None,
            note: Some(format!(
                "{lazy_count} tools advertised, all reachable via ctx_call \
                 (pin more with: lean-ctx tools standard|power)"
            )),
        });
    } else {
        let profile = cfg.tool_profile_effective();
        let overhead_hint = match profile {
            crate::core::tool_profiles::ToolProfile::Power => {
                "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
            }
            _ => "",
        };
        tool_profile_step.items.push(SetupItem {
            name: "tool_profile".to_string(),
            status: "already".to_string(),
            path: None,
            note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
        });
    }
    tool_profile_step
}

fn build_proxy_step(opts: SetupOptions, home: &std::path::Path) -> SetupStepReport {
    let mut proxy_step = setup_step("proxy");
    if opts.skip_proxy {
        proxy_step.items.push(SetupItem {
            name: "proxy".to_string(),
            status: "skipped".to_string(),
            path: None,
            note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
        });
    } else {
        let proxy_cfg = crate::core::config::Config::load();
        if proxy_cfg.proxy_enabled == Some(true) {
            let proxy_port = crate::proxy_setup::default_port();
            crate::proxy_autostart::install(proxy_port, true);
            std::thread::sleep(std::time::Duration::from_millis(500));
            crate::proxy_setup::install_proxy_env(home, proxy_port, opts.json);
            proxy_step.items.push(SetupItem {
                name: "proxy_autostart".to_string(),
                status: "installed".to_string(),
                path: None,
                note: Some("LaunchAgent/systemd auto-start on login".to_string()),
            });
            proxy_step.items.push(SetupItem {
                name: "proxy_env".to_string(),
                status: "configured".to_string(),
                path: None,
                note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
            });
        } else {
            proxy_step.items.push(SetupItem {
                name: "proxy".to_string(),
                status: "skipped".to_string(),
                path: None,
                note: Some(
                    "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
                ),
            });
        }
    }
    proxy_step
}

fn build_doctor_compact_step() -> SetupStepReport {
    let mut env_step = setup_step("doctor_compact");
    let (passed, total) = crate::doctor::compact_score();
    env_step.items.push(SetupItem {
        name: "doctor".to_string(),
        status: format!("{passed}/{total}"),
        path: None,
        note: None,
    });
    if passed != total {
        env_step.warnings.push(format!(
            "doctor compact not fully passing: {passed}/{total}"
        ));
    }
    env_step
}

fn maybe_add_project_root_warning(steps: &mut Vec<SetupStepReport>) {
    let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT").is_ok_and(|v| !v.is_empty());
    let cfg = crate::core::config::Config::load();
    let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());

    if has_env_root || has_cfg_root {
        return;
    }

    let Ok(cwd) = std::env::current_dir() else {
        return;
    };
    let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
    if !is_home {
        return;
    }

    let mut root_step = SetupStepReport {
        name: "project_root".to_string(),
        ok: true,
        items: Vec::new(),
        warnings: vec![
            "No project_root configured. Running from $HOME can cause excessive scanning. \
             Set via: lean-ctx config set project_root /path/to/project"
                .to_string(),
        ],
        errors: Vec::new(),
    };
    root_step.items.push(SetupItem {
        name: "project_root".to_string(),
        status: "unconfigured".to_string(),
        path: None,
        note: Some("Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml".to_string()),
    });
    steps.push(root_step);
}

fn maybe_spawn_background_index() {
    if let Ok(cwd) = std::env::current_dir()
        && may_autoindex_cwd(&cwd)
        && crate::core::pathutil::has_project_marker(&cwd)
    {
        spawn_index_build_background(&cwd);
    }
}

fn maybe_enable_ide_config_access(opts: SetupOptions) {
    if !opts.yes
        || opts.fix
        || crate::core::config::Config::load()
            .allow_ide_config_dirs
            .is_some()
    {
        return;
    }

    match crate::core::config::Config::update_global(|c| {
        c.allow_ide_config_dirs = Some(true);
    }) {
        Ok(_) => {
            if !opts.json {
                println!(
                    "  Enabled IDE config access (allow_ide_config_dirs) — \
                     disable: lean-ctx config set allow_ide_config_dirs false"
                );
            }
        }
        Err(e) => tracing::warn!("could not enable IDE config access: {e}"),
    }
}

fn build_setup_report(
    started_at: chrono::DateTime<Utc>,
    steps: Vec<SetupStepReport>,
) -> SetupReport {
    let finished_at = Utc::now();
    let success = steps.iter().all(|s| s.ok);
    SetupReport {
        schema_version: 1,
        started_at,
        finished_at,
        success,
        platform: PlatformInfo {
            os: std::env::consts::OS.to_string(),
            arch: std::env::consts::ARCH.to_string(),
        },
        steps,
        warnings: Vec::new(),
        errors: Vec::new(),
    }
}

fn persist_setup_report(report: &SetupReport) -> Result<(), String> {
    let path = SetupReport::default_path()?;
    let mut content =
        serde_json::to_string_pretty(report).map_err(|e| format!("serialize report: {e}"))?;
    content.push('\n');
    crate::config_io::write_atomic(&path, &content)
}

#[cfg(test)]
mod rule_steering_policy_tests {
    use super::*;

    /// `rules_injection_effective` prefers `LEAN_CTX_RULES_INJECTION` over the
    /// config, and other tests set it concurrently. Hold the env lock and
    /// clear it so the config under test decides.
    fn without_rules_injection_env() -> crate::core::data_dir::TestEnvGuard {
        let guard = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("LEAN_CTX_RULES_INJECTION");
        guard
    }

    #[test]
    fn editor_step_respects_commandcode_rule_steering_policy() {
        let tmp = tempfile::tempdir().unwrap();
        let detect = tmp.path().join("commandcode");
        let config = detect.join("mcp.json");

        std::fs::create_dir_all(&detect).unwrap();

        let target = EditorTarget {
            name: "Command Code",
            agent_key: "commandcode".to_string(),
            detect_path: detect,
            config_path: config.clone(),
            config_type: crate::core::editor_registry::ConfigType::CommandCode,
        };

        let report = build_editor_step(
            SetupOptions::default(),
            tmp.path().to_string_lossy().as_ref(),
            "lean-ctx",
            &[target],
            true,
            false,
        );

        assert!(
            report.ok,
            "editor setup should configure MCP successfully: {:?}",
            report.errors
        );

        let json: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(config).unwrap()).unwrap();

        let entry = &json["mcpServers"]["lean-ctx"];

        assert_eq!(entry["command"], "lean-ctx");
        assert!(
            entry.get("instructions").is_none(),
            "the first setup editor writer must not bypass the steering opt-out"
        );
    }

    #[test]
    fn explicit_auto_false_declines_setup_steering() {
        let _env = without_rules_injection_env();
        let mut cfg = crate::core::config::Config::default();
        cfg.setup.auto_inject_rules = Some(false);

        assert!(!should_allow_rule_steering(SetupOptions::default(), &cfg));
    }

    #[test]
    fn force_overrides_auto_false_but_not_rules_off() {
        let _env = without_rules_injection_env();
        let force = SetupOptions {
            force_inject_rules: true,
            ..Default::default()
        };

        let mut cfg = crate::core::config::Config::default();
        cfg.setup.auto_inject_rules = Some(false);

        assert!(
            should_allow_rule_steering(force, &cfg),
            "--force-inject-rules must override setup.auto_inject_rules=false"
        );

        cfg.rules_injection = Some("off".to_string());

        assert!(
            !should_allow_rule_steering(force, &cfg),
            "rules_injection=off remains absolute even with force"
        );
    }

    #[test]
    fn skip_rules_wins_over_force() {
        let _env = without_rules_injection_env();
        let opts = SetupOptions {
            skip_rules: true,
            force_inject_rules: true,
            ..Default::default()
        };

        let cfg = crate::core::config::Config::default();

        assert!(!should_allow_rule_steering(opts, &cfg));
    }

    #[test]
    fn default_none_and_explicit_true_allow_setup_steering() {
        let _env = without_rules_injection_env();
        let default_cfg = crate::core::config::Config::default();

        assert!(should_allow_rule_steering(
            SetupOptions::default(),
            &default_cfg
        ));

        let mut explicit_true = crate::core::config::Config::default();
        explicit_true.setup.auto_inject_rules = Some(true);

        assert!(should_allow_rule_steering(
            SetupOptions::default(),
            &explicit_true
        ));
    }
}