lean-ctx 3.12.8

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. 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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
// SPDX-License-Identifier: Apache-2.0
use lean_ctx_time::UtcDateTime;

use lean_ctx::core::editor_registry::{EditorTarget, WriteAction, WriteOptions};
use lean_ctx::core::portable_binary::resolve_agent_binary;
use lean_ctx::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
use lean_ctx_hooks::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(lean_ctx::core::runtime_flags::scoped_quiet);
    let started_at = UtcDateTime::now();
    let home = lean_ctx::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();

    // Only the selected tools are touched; the rest are reported, not written.
    let all_targets = lean_ctx::core::editor_registry::build_targets(&home);
    let scope = super::agent_selection::scope_for_run(
        &home,
        &all_targets,
        opts.agents.as_ref(),
        opts.refresh_only,
    );
    let (targets, deselected): (Vec<EditorTarget>, Vec<EditorTarget>) = all_targets
        .into_iter()
        .partition(|t| scope.allows(&t.agent_key));
    let allows = |key: &str| scope.allows(key);

    let cfg = lean_ctx::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());

    if opts.dry_run {
        let steps = super::dry_run::plan_steps(&super::dry_run::PlanInput {
            opts,
            home: &home,
            scope: &scope,
            targets: &targets,
            deselected: &deselected,
            update_mcp,
            inject_rules: should_inject,
            inject_skills: should_install_skills,
        });
        return Ok(build_setup_report(started_at, steps));
    }

    // 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).
    lean_ctx::core::layout_pin::heal();
    // This binary writes the setup now: an older build's silent refresh
    // (a server or daemon still running after an update) yields to it.
    lean_ctx_hooks::hooks::setup_writer::record();

    // Before the MCP/rules/hook steps, which then leave a governor host alone.
    let governor_step = build_governor_step(opts, &home, &targets, &allows);
    let mut editor_step = build_editor_step(
        opts,
        &home_str,
        &binary,
        &targets,
        update_mcp,
        allow_rule_steering,
    );
    editor_step
        .items
        .extend(deselected_items(&deselected, &home_str));
    let mut steps = vec![
        build_shell_hook_step(opts, &binary),
        build_daemon_step(),
        editor_step,
        build_rules_step(opts, &home, should_inject, &allows),
    ];
    steps.extend(governor_step);

    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, &allows) {
        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(!opts.refresh_only),
        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);
    }
    if let Some(keys) = &opts.agents {
        steps.push(build_selection_step(keys));
    }

    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) =
            lean_ctx::core::telemetry_aggregate::record_setup_completion(integrations)
        {
            tracing::debug!("telemetry setup aggregate unavailable: {error}");
        }
    }

    Ok(report)
}

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

/// Installed tools outside the agent selection: reported, never written.
pub(super) fn deselected_items(deselected: &[EditorTarget], home_str: &str) -> Vec<SetupItem> {
    deselected
        .iter()
        .filter(|t| t.detect_path.exists())
        .map(|t| SetupItem {
            name: t.name.to_string(),
            status: "deselected".to_string(),
            path: Some(shorten_path(&t.config_path.to_string_lossy(), home_str)),
            note: Some(format!(
                "not in the agent selection; connect: lean-ctx init --agent {}",
                t.agent_key
            )),
        })
        .collect()
}

/// `--agents` records the choice so later updates refresh exactly these tools.
fn build_selection_step(keys: &std::collections::BTreeSet<String>) -> SetupStepReport {
    let mut step = setup_step("agent_selection");
    let list = keys.iter().cloned().collect::<Vec<_>>().join(",");
    match super::agent_selection::save_selection(keys) {
        Ok(()) => step.items.push(SetupItem {
            name: "setup.agents".to_string(),
            status: "saved".to_string(),
            path: None,
            note: Some(if list.is_empty() {
                "none".to_string()
            } else {
                list
            }),
        }),
        Err(e) => {
            step.ok = false;
            step.errors.push(e);
        }
    }
    step
}

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()]);
        }
        lean_ctx::shell_hook::install_all(opts.json);
        #[cfg(not(windows))]
        {
            // Same stable PATH entry `init` embeds in the hook (#1851).
            let binary = lean_ctx::core::portable_binary::stable_shell_binary(_binary);
            let hook_content = crate::cli::generate_hook_posix(&binary);
            if lean_ctx::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(lean_ctx::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 {
    use lean_ctx::daemon_autostart::{self as autostart, Supervision};
    let mut daemon_step = setup_step("daemon");
    // Supervised where the platform has a supervisor: the daemon starts at
    // login and restarts after a crash, so Cloud's background sync never
    // depends on a daemon started by hand. A supervised daemon is
    // restarted to load this build.
    let supervision = if cfg!(test) {
        Supervision::Skipped
    } else {
        autostart::ensure_supervised(true)
    };
    match supervision {
        Supervision::Already | Supervision::Installed => {
            daemon_step.items.push(SetupItem {
                name: "serve --daemon".to_string(),
                status: if supervision == Supervision::Already {
                    "restarted"
                } else {
                    "supervised"
                }
                .to_string(),
                path: autostart::service_file_path().map(|p| p.display().to_string()),
                note: Some(autostart::supervision_line(supervision).unwrap_or_else(|| {
                    "supervised: starts at login and restarts after a crash".to_string()
                })),
            });
            return daemon_step;
        }
        Supervision::Failed => daemon_step.warnings.push(
            "the daemon could not be set up to start by itself (run `lean-ctx daemon enable`); started without supervision".to_string(),
        ),
        Supervision::Skipped => {}
    }
    let was_running = lean_ctx::daemon::is_daemon_running();
    if was_running {
        let _ = lean_ctx::daemon::stop_daemon();
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    match lean_ctx::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(lean_ctx::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 = lean_ctx_hooks::hooks::governor_default::display_mode(
            &target.agent_key,
            std::path::Path::new(home_str),
            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 = lean_ctx::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
}

/// The governor default per host that has one (a new Claude Code install
/// gets governor-mcp, an automatic 3.12.1 migration is switched back; every
/// existing or pinned setup is left to the standard steps). The notice is
/// printed once, here.
fn build_governor_step(
    opts: &SetupOptions,
    home: &std::path::Path,
    targets: &[EditorTarget],
    allows: &dyn Fn(&str) -> bool,
) -> Option<SetupStepReport> {
    use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_for_targets};
    // `[setup] manage_hooks = false` (#1879): an update leaves hand-picked
    // hook entries alone; only an explicit setup or init switches them.
    if opts.refresh_only && !lean_ctx::core::config::Config::load().setup.manage_hooks {
        return None;
    }
    let mut step = setup_step("governor");
    for (host, outcome) in apply_for_targets(home, targets, allows) {
        if outcome.ran_steps() {
            let _ = super::agent_selection::remember_connected_agent(host.key);
        }
        let notice = outcome.notice(host);
        if !opts.json
            && let Some(text) = &notice
        {
            eprintln!("  \u{2139} {text}");
        }
        let status = match &outcome {
            Outcome::Installed(_) => "created",
            Outcome::Restored { .. } | Outcome::RuleModesEnabled(_) | Outcome::Completed => {
                "updated"
            }
            Outcome::AlreadyGovernor => "already",
            Outcome::Pinned(_) | Outcome::Standard => "skipped",
        };
        let note = match &outcome {
            Outcome::Pinned(mode) => format!("pinned mode {mode}"),
            Outcome::Standard => "standard setup kept".to_string(),
            Outcome::AlreadyGovernor => "governor setup".to_string(),
            _ => notice.unwrap_or_default(),
        };
        step.items.push(SetupItem {
            name: host.name.to_string(),
            status: status.to_string(),
            path: None,
            note: Some(note),
        });
    }
    (!step.items.is_empty()).then_some(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: &lean_ctx::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() == lean_ctx::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,
    allows: &dyn Fn(&str) -> bool,
) -> SetupStepReport {
    let mut rules_step = setup_step("agent_rules");
    if should_inject {
        let rules_result = lean_ctx::rules_inject::inject_rules_where(home, allows);
        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,
    allows: &dyn Fn(&str) -> bool,
) -> Option<SetupStepReport> {
    let mut skill_step = setup_step("skill_files");
    if should_install_skills {
        let skill_results = lean_ctx::rules_inject::install_skills_where(home, allows);
        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;
        }

        // The governor step ran first (`apply_for_targets`); a host that has the
        // governor now only gets its hooks re-rendered.
        if let Some(home) = lean_ctx::core::home::resolve_home_dir()
            && let Some(host) = lean_ctx_hooks::hooks::governor_default::host(&target.agent_key)
            && (host.is_installed)(&home)
        {
            (host.refresh)(&home);
            let arm = if host.key == "claude"
                && lean_ctx_hooks::hooks::agents::claude_governor::installed_arm(&home)
                    == Some(
                        lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred,
                    ) {
                "mode=governor-mcp; lean-ctx MCP server with deferred tools"
            } else {
                "mode=governor; no MCP server"
            };
            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!("{arm} (switch back: {})", host.switch_back)),
            });
            continue;
        }

        let mode = recommend_hook_mode(&target.agent_key);

        if allow_rule_steering {
            lean_ctx_hooks::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
        } else {
            lean_ctx_hooks::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()
        };

        let mode = lean_ctx::core::home::resolve_home_dir().map_or_else(
            || mode.to_string(),
            |home| {
                lean_ctx_hooks::hooks::governor_default::display_mode(
                    &target.agent_key,
                    &home,
                    mode,
                )
            },
        );
        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 (cockpit, wake, a focused tool surface) is set
/// up wherever Claude Code can host it — by setup and by the post-update rewire
/// alike — and an installed one is rolled forward to this engine. It runs
/// inside Claude Code, so the report says what was installed and how to remove
/// it, and a removal (`lean-ctx claude-mod uninstall`) is never undone here.
fn build_claude_mod_step(opts: &SetupOptions, targets: &[EditorTarget]) -> Option<SetupStepReport> {
    use lean_ctx_hooks::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),
    };
    let quiet = opts.json;
    // governor-mcp: the mod front-loads its configured lean-ctx tools
    // (`front_loaded_tools`, 9 by default), which would put their schemas back
    // into every request. The no-MCP governor has no lean-ctx MCP tools, so
    // there the mod adds nothing the model sees (its hooks key on the server).
    // Setup and the rewire never disable an installed mod: only an explicit
    // `init --mode governor-mcp` does, once (a re-enabled plugin stays on).
    if lean_ctx::core::home::resolve_home_dir()
        .and_then(|h| lean_ctx_hooks::hooks::agents::claude_governor::installed_arm(&h))
        == Some(lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred)
    {
        step.items.push(item(
            "skipped",
            "governor-mcp setup: the mod would front-load lean-ctx tool schemas \
             (install anyway: lean-ctx claude-mod install)"
                .to_string(),
        ));
        return Some(step);
    }
    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 claude_mod::auto_install_declined() => step.items.push(item(
            "skipped",
            "removed by you — bring it back with: lean-ctx claude-mod install".to_string(),
        )),
        ModStatus::NotInstalled => match claude_mod::install() {
            Ok(msg) => {
                if !quiet {
                    println!("\n  {}", claude_mod::INSTALLED_NOTICE);
                }
                step.items.push(item("created", msg));
            }
            Err(e) => {
                step.warnings
                    .push(format!("claude mod install failed: {e}"));
                step.items.push(item("error", e));
            }
        },
    }
    Some(step)
}

fn build_tool_profile_step() -> SetupStepReport {
    let mut tool_profile_step = setup_step("tool_profile");
    let cfg = lean_ctx::core::config::Config::load();
    if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
        let lazy_count = lean_ctx::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 {
            lean_ctx::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 = lean_ctx::core::config::Config::load();
        if proxy_cfg.proxy_enabled == Some(true) {
            let proxy_port = crate::proxy_setup::default_port();
            lean_ctx::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 = lean_ctx::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)
        && lean_ctx::core::pathutil::has_project_marker(&cwd)
    {
        spawn_index_build_background(&cwd);
    }
}

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

    match lean_ctx::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: lean_ctx_time::UtcDateTime,
    steps: Vec<SetupStepReport>,
) -> SetupReport {
    let finished_at = UtcDateTime::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');
    lean_ctx::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() -> lean_ctx::core::data_dir::TestEnvGuard {
        let guard = lean_ctx::core::data_dir::test_env_lock();
        lean_ctx::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: lean_ctx::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 = lean_ctx::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 = lean_ctx::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 = lean_ctx::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 = lean_ctx::core::config::Config::default();

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

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

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