lean-ctx 3.12.3

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
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
// SPDX-License-Identifier: Apache-2.0
//! Environment diagnostics for lean-ctx installation and integration.

/// Every doctor line goes through [`emit_line`], which drops the ANSI styling
/// under `NO_COLOR`, `TERM=dumb` or a non-TTY stdout. Shadowing `println!` for
/// this module tree keeps the many styled format strings unchanged while making
/// it impossible for a new check to leak escape codes into a pipe or log.
macro_rules! println {
    () => {
        ::std::println!()
    };
    ($($arg:tt)*) => {
        $crate::doctor::emit_line(&::std::format!($($arg)*))
    };
}

mod checks;
mod common;
mod deprecations;
mod fix;
mod integrations;
mod lint_context;
mod migrate;
mod overhead;
mod report;
mod workspace_scope;

#[allow(clippy::wildcard_imports)]
use checks::*;
pub(crate) use checks::{configured_host_coverage, shadow_hosts, shadow_status};
#[allow(clippy::wildcard_imports)]
use common::*;

pub use report::{HealthCheck, HealthLevel, HealthReport, health_report};

/// Run `doctor --fix` and return the structured `SetupReport` without printing
/// anything — the in-process entry point for the dashboard fix route (#466).
///
/// # Errors
/// Propagates any repair-step failure (e.g. an unwritable data directory).
pub fn run_fix_report() -> Result<lean_ctx::core::setup_report::SetupReport, String> {
    fix::fix_report()
}

pub(super) const GREEN: &str = "\x1b[32m";

pub(super) const RED: &str = "\x1b[31m";

pub(super) const BOLD: &str = "\x1b[1m";

pub(super) const RST: &str = "\x1b[0m";

pub(super) const DIM: &str = "\x1b[2m";

pub(super) const WHITE: &str = "\x1b[97m";

pub(super) const YELLOW: &str = "\x1b[33m";

pub(super) struct Outcome {
    pub ok: bool,
    pub line: String,
}

/// The daemon autostart service as doctor sees it.
enum DaemonAutostart {
    /// No autostart service exists on this platform (Windows, BSD): the
    /// daemon is started by `daemon start` or on demand by editors.
    Unsupported,
    Off,
    /// Installed, with its service file when known (GH #394).
    On(Option<std::path::PathBuf>),
}

/// Doctor's line for lean-ctx services of this user that this instance has
/// no record of (owner decision 02.11.): `stop`/`restart` leave them alone,
/// so doctor names each with its PID and the exact way to stop it. `None`
/// when there are none. Pure; advisory (never fails doctor).
fn unrecorded_services_outcome(lines: Option<(String, String)>) -> Option<Outcome> {
    let (what, how) = lines?;
    Some(Outcome {
        ok: true,
        line: format!("{BOLD}Unrecorded services{RST}  {YELLOW}{what}{RST}  {DIM}{how}{RST}"),
    })
}

/// Doctor's daemon line from the observed state. Pure, so the line every
/// platform prints is covered by tests on any host (#2176: Windows printed
/// "not supported on this platform" while its daemon was running).
fn daemon_outcome(running_pid: Option<u32>, autostart: &DaemonAutostart) -> Outcome {
    let autostart_tag = match autostart {
        DaemonAutostart::On(Some(p)) => format!("  {DIM}[autostart: on — {}]{RST}", p.display()),
        DaemonAutostart::On(None) => format!("  {DIM}[autostart: on]{RST}"),
        DaemonAutostart::Off | DaemonAutostart::Unsupported => String::new(),
    };
    let line = if let Some(pid) = running_pid {
        format!("{BOLD}Daemon{RST}  {GREEN}running (PID {pid}){RST}{autostart_tag}")
    } else {
        let hint = match autostart {
            DaemonAutostart::On(_) => format!("{DIM}(autostart enabled, will restart){RST}"),
            DaemonAutostart::Off => {
                format!("{DIM}(run: lean-ctx daemon start  or: lean-ctx daemon enable){RST}")
            }
            DaemonAutostart::Unsupported => {
                format!("{DIM}(run: lean-ctx daemon start — editors also start it on demand){RST}")
            }
        };
        format!("{BOLD}Daemon{RST}  {YELLOW}not running{RST}  {hint}")
    };
    Outcome { ok: true, line }
}

/// Doctor's line for Hive's background sync, which runs in the daemon: on a
/// machine connected to Hive the daemon must be supervised (start at login,
/// restart after a crash), or nothing syncs until someone starts it by
/// hand. `None` when not connected or no supervisor exists. Pure.
fn hive_sync_outcome(hive_connected: bool, autostart: &DaemonAutostart) -> Option<Outcome> {
    if !hive_connected {
        return None;
    }
    match autostart {
        DaemonAutostart::On(_) => Some(Outcome {
            ok: true,
            line: format!(
                "{BOLD}Hive sync{RST}  {GREEN}in the background (supervised daemon){RST}"
            ),
        }),
        DaemonAutostart::Off => Some(Outcome {
            ok: false,
            line: format!(
                "{BOLD}Hive sync{RST}  {YELLOW}needs a supervised daemon{RST}  {DIM}(run: lean-ctx daemon enable){RST}"
            ),
        }),
        DaemonAutostart::Unsupported => None,
    }
}

/// Accumulates doctor checks so the rendered ✓/✗ list and the summary tally can
/// never diverge (#433): every scored check is counted exactly once via
/// [`Scoreboard::check`]; only explicitly-optional advisories (LSP, "not
/// configured" notes) use [`Scoreboard::info`], which renders without counting.
/// The old hand-maintained `passed`/`effective_total` pair drifted whenever a
/// check was added without bumping the total — routing every render through the
/// board makes that class of bug structurally impossible.
#[derive(Default)]
struct Scoreboard {
    passed: u32,
    total: u32,
    json_mode: bool,
    entries: Vec<JsonCheck>,
}

/// A single doctor check entry for JSON serialization (GH #1470).
#[derive(Default, serde::Serialize)]
struct JsonCheck {
    ok: bool,
    name: String,
    scored: bool,
}

fn strip_ansi(s: &str) -> String {
    // Strip ANSI escape sequences for machine-readable output
    let mut result = String::with_capacity(s.len());
    let mut in_escape = false;
    for c in s.chars() {
        if c == '\x1b' {
            in_escape = true;
        } else if in_escape {
            if c.is_ascii_alphabetic() {
                in_escape = false;
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Print one doctor line, stripped of ANSI styling when colour is off.
pub(crate) fn emit_line(line: &str) {
    if lean_ctx::core::theme::no_color() {
        ::std::println!("{}", strip_ansi(line));
    } else {
        ::std::println!("{line}");
    }
}

impl Scoreboard {
    fn new(json_mode: bool) -> Self {
        Self {
            passed: 0,
            total: 0,
            json_mode,
            entries: Vec::new(),
        }
    }

    /// A scored health check: render it and count it (pass iff `ok`).
    fn check(&mut self, outcome: &Outcome) {
        self.total += 1;
        if outcome.ok {
            self.passed += 1;
        }
        self.entries.push(JsonCheck {
            ok: outcome.ok,
            name: strip_ansi(&outcome.line),
            scored: true,
        });
        if !self.json_mode {
            print_check(outcome, true);
        }
    }

    /// An optional/advisory line: render it but never count it toward the score.
    fn info(&mut self, outcome: &Outcome) {
        self.entries.push(JsonCheck {
            ok: outcome.ok,
            name: strip_ansi(&outcome.line),
            scored: false,
        });
        if !self.json_mode {
            print_check(outcome, false);
        }
    }

    /// A free-form advisory note (daemon diagnostics): printed as-is in text
    /// mode, recorded as an unscored JSON entry with `--json`, so nothing but
    /// the JSON document reaches stdout (#2179).
    fn note(&mut self, outcome: &Outcome) {
        self.entries.push(JsonCheck {
            ok: outcome.ok,
            name: strip_ansi(outcome.line.trim()),
            scored: false,
        });
        if !self.json_mode {
            println!("{}", outcome.line);
        }
    }
}

/// A pending request older than this is flagged in doctor's request lines.
const STUCK_REQUEST_AFTER: std::time::Duration = std::time::Duration::from_secs(30);

/// Doctor's request-ledger lines (#2197), one per running server process:
/// counters, the oldest pending request with its age and stage, and the last
/// tool completion. Pure; advisory (never scored).
fn request_ledger_outcomes(
    snapshots: &[lean_ctx::core::request_ledger::RequestLedgerSnapshot],
    now_ms: u64,
) -> Vec<Outcome> {
    snapshots
        .iter()
        .map(|snapshot| {
            let stuck = snapshot
                .oldest_pending_age(now_ms)
                .is_some_and(|age| age >= STUCK_REQUEST_AFTER);
            let colour = if stuck { YELLOW } else { DIM };
            Outcome {
                ok: !stuck,
                line: format!(
                    "{BOLD}Requests{RST}  {colour}{}{RST}",
                    snapshot.render(now_ms)
                ),
            }
        })
        .collect()
}

/// Daemon diagnostics that are not checks of their own: the systemd unit
/// state and linger (Linux) and a crash-looping MCP server. Returned rather
/// than printed, so the caller decides between text and JSON.
fn daemon_diagnostic_notes() -> Vec<Outcome> {
    let mut notes = Vec::new();
    // The unit is the default install's: an instance with a directory
    // override or a sandbox HOME neither asks about it nor reports it.
    #[cfg(target_os = "linux")]
    if lean_ctx::daemon_autostart::controls_user_services() {
        if let Ok(o) = std::process::Command::new("systemctl")
            .args(["--user", "is-active", "lean-ctx-daemon.service"])
            .output()
        {
            let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if state != "active" {
                notes.push(Outcome {
                    ok: false,
                    line: format!(
                        "  {DIM}  systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
                    ),
                });
            }
        }
        let username = std::env::var("USER")
            .or_else(|_| std::env::var("LOGNAME"))
            .unwrap_or_else(|_| "$(whoami)".to_string());
        if let Ok(o) = std::process::Command::new("loginctl")
            .args(["show-user", &username, "-p", "Linger", "--value"])
            .output()
        {
            let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if val != "yes" {
                notes.push(Outcome {
                    ok: false,
                    line: format!(
                        "  {YELLOW}⚠{RST}  Linger not enabled — daemon won't start at boot without login\n     {DIM}Fix: loginctl enable-linger {username}{RST}"
                    ),
                });
            }
        }
    }
    if let Some(log_path) = lean_ctx::core::startup_guard::crash_loop_log_path(
        lean_ctx::core::startup_guard::MCP_PROCESS_NAME,
    ) && log_path.exists()
        && let Ok(contents) = std::fs::read_to_string(&log_path)
    {
        let lines: Vec<&str> = contents.lines().collect();
        if lines.len() >= 5 {
            notes.push(Outcome {
                ok: false,
                line: format!(
                    "  {YELLOW}⚠{RST}  Crash-loop log: {} recent restarts  {DIM}({}){RST}",
                    lines.len(),
                    display_user_path(&log_path)
                ),
            });
        }
    }
    notes
}

/// Run diagnostic checks and print colored results to stdout.
/// Renders the full diagnostics board and returns how many checks need
/// attention, so `lean-ctx doctor` can exit non-zero when something is wrong
/// (a health gate must fail loudly, not silently exit 0).
pub fn run() -> u32 {
    run_inner(false)
}

/// GH #1470: JSON output variant of `run()`.
pub fn run_json() -> u32 {
    run_inner(true)
}

fn run_inner(json: bool) -> u32 {
    let mut board = Scoreboard::new(json);

    if !json {
        println!("{BOLD}{WHITE}lean-ctx doctor{RST}  {DIM}diagnostics{RST}\n");
    }

    // 1) Binary on PATH
    let path_bin = resolve_lean_ctx_binary();
    let also_in_path_dirs = path_in_path_env();
    let bin_ok = path_bin.is_some() || also_in_path_dirs;
    let bin_line = if let Some(p) = path_bin {
        format!("{BOLD}lean-ctx in PATH{RST}  {WHITE}{}{RST}", p.display())
    } else if also_in_path_dirs {
        format!(
            "{BOLD}lean-ctx in PATH{RST}  {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
        )
    } else {
        format!("{BOLD}lean-ctx in PATH{RST}  {RED}not found{RST}")
    };
    board.check(&Outcome {
        ok: bin_ok,
        line: bin_line,
    });

    // 2) Version from PATH binary
    let ver = if bin_ok {
        lean_ctx_version_from_path()
    } else {
        Outcome {
            ok: false,
            line: format!("{BOLD}lean-ctx version{RST}  {RED}skipped (binary not in PATH){RST}"),
        }
    };
    board.check(&ver);

    // 3) data directory (respects LEAN_CTX_DATA_DIR)
    let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
    let dir_outcome = match &lean_dir {
        Some(p) if p.is_dir() => Outcome {
            ok: true,
            line: format!(
                "{BOLD}data dir{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
                p.display()
            ),
        },
        // A fresh install creates it on first use, like stats.json below.
        Some(p) if !p.exists() => Outcome {
            ok: true,
            line: format!(
                "{BOLD}data dir{RST}  {WHITE}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
                p.display()
            ),
        },
        Some(p) => Outcome {
            ok: false,
            line: format!(
                "{BOLD}data dir{RST}  {RED}not a directory{RST}  {DIM}{}{RST}",
                p.display()
            ),
        },
        None => Outcome {
            ok: false,
            line: format!("{BOLD}data dir{RST}  {RED}could not resolve data directory{RST}"),
        },
    };
    board.check(&dir_outcome);

    // 4) stats.json + size
    let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
    let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
        Some(m) if m.is_file() => {
            let size = m.len();
            let path_display = if let Some(p) = stats_path.as_ref() {
                p.display().to_string()
            } else {
                String::new()
            };
            Outcome {
                ok: true,
                line: format!(
                    "{BOLD}stats.json{RST}  {GREEN}exists{RST}  {WHITE}{size} bytes{RST}  {DIM}{path_display}{RST}",
                ),
            }
        }
        Some(_m) => {
            let path_display = if let Some(p) = stats_path.as_ref() {
                p.display().to_string()
            } else {
                String::new()
            };
            Outcome {
                ok: false,
                line: format!(
                    "{BOLD}stats.json{RST}  {RED}not a file{RST}  {DIM}{path_display}{RST}",
                ),
            }
        }
        None => Outcome {
            ok: true,
            line: match &stats_path {
                Some(p) => format!(
                    "{BOLD}stats.json{RST}  {WHITE}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
                    p.display()
                ),
                None => format!("{BOLD}stats.json{RST}  {RED}could not resolve path{RST}"),
            },
        },
    };
    board.check(&stats_outcome);

    let split_dirs = lean_ctx::core::data_dir::all_data_dirs_with_stats();
    if split_dirs.len() >= 2 {
        let dirs_str = split_dirs
            .iter()
            .map(|d| d.display().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        board.check(&Outcome {
            ok: false,
            line: format!(
                "{BOLD}data dir split{RST}  {RED}stats.json found in {count} locations{RST}: {dirs_str}  {DIM}(run: lean-ctx doctor --fix to merge){RST}",
                count = split_dirs.len(),
            ),
        });
    }

    // XDG layout (GH #408): a legacy/mixed single-dir install mixes config with
    // data/state/cache, which blocks a read-only config sandbox. Scored as a
    // failure while present (#433) — `doctor --fix` splits it into the four typed
    // XDG dirs, after which this check disappears.
    if let Some((src, n)) = lean_ctx::core::xdg_migrate::pending() {
        board.check(&Outcome {
            ok: false,
            line: format!(
                "{BOLD}XDG layout{RST}  {YELLOW}{n} item(s) in single dir{RST}  {DIM}{}{RST}  {DIM}(run: lean-ctx doctor --fix to split into config/data/state/cache){RST}",
                src.display()
            ),
        });
    }

    // #594: a `config.toml` stranded in the data dir means the MCP server (an
    // older `LEAN_CTX_DATA_DIR` env collapsed its layout) and the CLI were
    // reading *different* config. Flag it; `lean-ctx setup`/`update` and
    // `doctor --fix` relocate it to the config dir so both agree again.
    if let Some(stray) = lean_ctx::core::config_heal::pending() {
        board.check(&Outcome {
            ok: false,
            line: format!(
                "{BOLD}config location{RST}  {YELLOW}stray config.toml in the data dir{RST}  {DIM}{}{RST}  {DIM}(run: lean-ctx doctor --fix to unify CLI + MCP){RST}",
                stray.display()
            ),
        });
    }

    // Layout commitment (GL #623): a pinned XDG install can no longer be
    // hijacked by a stray ~/.lean-ctx. Surface the mode and flag a residual dir
    // (heal reclaims it on the next start / `doctor --fix`).
    {
        let pinned = lean_ctx::core::layout_pin::is_xdg_pinned();
        let residual = lean_ctx::core::xdg_migrate::residual_legacy_present();
        let line = if pinned && residual {
            format!(
                "{BOLD}layout{RST}  {GREEN}xdg-pinned{RST}  {YELLOW}residual ~/.lean-ctx present{RST}  {DIM}(auto-reclaimed on next start){RST}"
            )
        } else if pinned {
            format!(
                "{BOLD}layout{RST}  {GREEN}xdg-pinned{RST}  {DIM}(~/.lean-ctx can no longer hijack this install){RST}"
            )
        } else {
            format!(
                "{BOLD}layout{RST}  {WHITE}single-dir / legacy{RST}  {DIM}(run: lean-ctx doctor --fix to commit to XDG){RST}"
            )
        };
        board.check(&Outcome { ok: true, line });
    }

    // 5) config.toml (missing is OK). It lives in the CONFIG dir
    // ($XDG_CONFIG_HOME/lean-ctx after a split), not the data dir — resolve it
    // through the same path as the loader so the report matches reality
    // post-migration instead of pointing at the old location (#435).
    let config_path = lean_ctx::core::config::Config::path();
    let config_outcome = match &config_path {
        Some(p) => match std::fs::metadata(p) {
            Ok(m) if m.is_file() => Outcome {
                ok: true,
                line: format!(
                    "{BOLD}config.toml{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
                    p.display()
                ),
            },
            Ok(_) => Outcome {
                ok: false,
                line: format!(
                    "{BOLD}config.toml{RST}  {RED}exists but is not a regular file{RST}  {DIM}{}{RST}",
                    p.display()
                ),
            },
            Err(_) => Outcome {
                ok: true,
                line: format!(
                    "{BOLD}config.toml{RST}  {WHITE}not found, using defaults{RST}  {DIM}(expected at {}){RST}",
                    p.display()
                ),
            },
        },
        None => Outcome {
            ok: false,
            line: format!("{BOLD}config.toml{RST}  {RED}could not resolve path{RST}"),
        },
    };
    board.check(&config_outcome);

    // 5a1) #2175: a paused config migration, on every doctor run (the
    // warning itself is shown once per state).
    if let Some(outcome) = config_path
        .as_deref()
        .and_then(config_migration_pause_outcome)
    {
        board.check(&outcome);
    }

    // 5a2) #594: CLI<->MCP config parity — warn if any editor MCP entry still
    // pins a stale LEAN_CTX_DATA_DIR (which would make that editor's MCP server
    // read a different config.toml than this CLI), and print the resolved path.
    board.check(&config_parity_outcome());
    board.check(&project_pin_outcome());

    // 5b) Shell allowlist (effective runtime view + silent-parse-error trap, #341)
    let allowlist_outcome = shell_allowlist_outcome();
    board.check(&allowlist_outcome);

    // 5b1) GH #1419 follow-up: upgrade advisory + shadowing advisory, both
    // read-only and silent when there's nothing to report.
    if let Some(upgrade) = shell_allowlist_upgrade_advisory_outcome() {
        board.check(&upgrade);
    }
    if let Some(shadowing) = shell_allowlist_shadowing_outcome() {
        board.check(&shadowing);
    }

    // 5b2) Path jail (effective state + dead allow_paths entries, GH #392)
    let path_jail = path_jail_outcome();
    board.check(&path_jail);

    // 5b3) Workspace trust for project-local .lean-ctx.toml (security audit #4)
    let workspace_trust = workspace_trust_outcome();
    board.check(&workspace_trust);

    // 5b3b) Secret/.env redaction — the exfiltration-defense plane, independent
    // of the jail + shell gating above (#507).
    let secret_detection = secret_detection_outcome();
    board.check(&secret_detection);
    let context_gateway = context_gateway_outcome();
    board.check(&context_gateway);

    // 5b3c) Managed addon binaries (GH #725): receipt path + sha256 pin +
    // revocation, so binhash-gate refusals surface here instead of at first
    // tool call. Silent when nothing is managed.
    if let Some(managed_bins) = managed_addon_binaries_outcome() {
        board.check(&managed_bins);
    }

    // 5b3d) Managed ONNX Runtime (GH #732). The managed runtime was removed;
    // stays silent (embeddings are opt-in).
    if let Some(managed_ort) = managed_ort_outcome() {
        board.check(&managed_ort);
    }

    // 5b4) Cognition v2 activation (science subsystems wired + active)
    let cognition = cognition_activity_outcome();
    board.check(&cognition);

    // 5c) Compact-format passthrough (preserve already-compact TOON output, #342)
    let passthrough_outcome = compact_format_passthrough_outcome();
    board.check(&passthrough_outcome);

    // 5d) IDE permission inheritance (mirror host IDE bash/rm rules onto ctx_*)
    let perm_inherit_outcome = permission_inheritance_outcome();
    board.check(&perm_inherit_outcome);

    // 6) Proxy upstreams
    let proxy_outcome = proxy_upstream_outcome();
    board.check(&proxy_outcome);

    // Exit-code contract: `doctor` exits non-zero only when a scored check
    // fails. On a fresh install that was never set up (no host carries a
    // lean-ctx MCP entry, hooks or proxy route), the setup items below are the
    // next step, not errors: they render as optional (–) with the setup hint
    // and are not counted. Once any host is configured they are scored again,
    // so a half-broken setup still fails the gate.
    let setup_pending = dirs::home_dir().is_some_and(|home| {
        lean_ctx_mcp_location_names(&home).is_empty()
            && checks::configured_host_coverage(&home).is_empty()
    });
    if setup_pending && !json {
        println!(
            "  {DIM}Not set up yet — run {RST}{BOLD}lean-ctx setup{RST}{DIM} to connect your AI tools (items marked – are optional until then).{RST}"
        );
    }
    let setup_item = |board: &mut Scoreboard, outcome: &Outcome| {
        if setup_pending {
            board.info(outcome);
        } else {
            board.check(outcome);
        }
    };

    // 7) Shell aliases
    let aliases = shell_aliases_outcome();
    setup_item(&mut board, &aliases);

    // 7b) Agent aliases opt-out
    let agent_aliases = skip_agent_aliases_outcome();
    board.check(&agent_aliases);

    // 8) MCP
    let mcp = mcp_config_outcome();
    setup_item(&mut board, &mcp);
    // 8a) Claude Code: denied native tools need the MCP server that replaces them.
    if let Some(tools) = lean_ctx::core::home::resolve_home_dir()
        .and_then(|home| checks::claude_tool_access_outcome(&home))
    {
        board.check(&tools);
    }
    let user_scope_mcp_locations = dirs::home_dir()
        .map(|home| lean_ctx_mcp_location_names(&home))
        .unwrap_or_default();

    // 7b) WSL2 + VS Code: surface the upstream first-call invoke race (GH #669)
    if let Some(wsl_hint) = wsl_vscode_mcp_outcome() {
        board.check(&wsl_hint);
    }

    // 8) Workspace-scope MCP (optional; only when a project-local config exists)
    let workspace_scope = workspace_scope::workspace_scope_outcome(&user_scope_mcp_locations);
    if let Some(ref ws) = workspace_scope {
        board.check(ws);
    }

    // 9) SKILL.md
    let skill = skill_files_outcome();
    setup_item(&mut board, &skill);

    // 9a0) One lean-ctx rules channel per host (A3): advisory, names the fix.
    board.check(&overhead::rules_channels_outcome());

    // 9a) Optional Claude Code mod (informational; never fails doctor).
    if let Some(claude_mod) = checks::claude_mod_outcome() {
        board.check(&claude_mod);
    }

    // 9a') Hive org policy (HIVE-RT-D5): informational, never fails doctor.
    if let Some(hive_policy) = checks::hive_policy_outcome() {
        board.info(&hive_policy);
    }

    // 9b) Output triage (#1534): the 3.9.19 filter ran invisibly while doctor
    // reported all green — its state stays on the board whether on or off.
    let output_triage = output_triage_outcome();
    board.check(&output_triage);

    // 10) Port
    let port = port_3333_outcome();
    board.check(&port);

    // Daemon status — on every platform: Windows runs the daemon too (GL
    // #545); only the autostart service is macOS/Linux-specific (#2176).
    // An instance with a directory override or a sandbox HOME has no
    // autostart service of its own: the user-wide one runs the default
    // install's daemon, so doctor neither reports it nor advises enabling it.
    let daemon_autostart = if lean_ctx::daemon_autostart::is_supported()
        && lean_ctx::daemon_autostart::controls_user_services()
    {
        if lean_ctx::daemon_autostart::is_installed() {
            DaemonAutostart::On(lean_ctx::daemon_autostart::service_file_path())
        } else {
            DaemonAutostart::Off
        }
    } else {
        DaemonAutostart::Unsupported
    };
    // Verified, not just alive: a PID file can outlive its daemon and the
    // PID can be reused by any process (#2176 review #1).
    let daemon_pid = lean_ctx::daemon::verified_daemon().map(|daemon| daemon.pid);
    board.check(&daemon_outcome(daemon_pid, &daemon_autostart));
    let hive_connected =
        lean_ctx_hive::HiveStore::open().is_ok_and(|store| matches!(store.instance(), Ok(Some(_))));
    if let Some(sync) = hive_sync_outcome(hive_connected, &daemon_autostart) {
        board.check(&sync);
    }
    if let Some(unrecorded) =
        unrecorded_services_outcome(lean_ctx::daemon::unrecorded_services_warning())
    {
        board.info(&unrecorded);
    }

    // Daemon diagnostics: systemctl is-active, linger, crash-loop log. They go
    // through the board so `--json` keeps stdout one JSON document (#2179).
    for note in daemon_diagnostic_notes() {
        board.note(&note);
    }

    // Request ledgers of running servers (#2197): read from the files their
    // publisher threads keep, so a saturated worker still answers here.
    for outcome in request_ledger_outcomes(
        &lean_ctx::core::request_ledger::published_snapshots(),
        lean_ctx::core::request_ledger::epoch_ms(),
    ) {
        board.info(&outcome);
    }

    // Providers (advisory — presence/health varies per environment, not scored)
    let provider_outcome = provider_outcome();
    board.info(&provider_outcome);

    // MCP Bridges (advisory)
    let bridge_outcomes = mcp_bridge_outcomes();
    for bridge_check in &bridge_outcomes {
        board.info(bridge_check);
    }

    // GH #1470: Version-skew detection between CLI and agent bridges
    let skew_outcomes = version_skew_outcomes();
    for skew_check in &skew_outcomes {
        board.check(&skew_check);
    }

    // Plan mode (advisory)
    let plan_outcomes = plan_mode_outcomes();
    for plan_check in &plan_outcomes {
        board.info(plan_check);
    }

    // 9) Session state (project_root + shell_cwd)
    let session_outcome = session_state_outcome();
    board.check(&session_outcome);

    // 10) Docker env vars (optional, only in containers)
    let docker_outcomes = docker_env_outcomes();
    for docker_check in &docker_outcomes {
        board.check(docker_check);
    }

    // 11) Pi Coding Agent (optional)
    let pi = pi_outcome();
    if let Some(ref pi_check) = pi {
        board.check(pi_check);
    }

    // 12) Build integrity (canary / origin check)
    let integrity = lean_ctx::core::integrity::check();
    let integrity_ok = integrity.seed_ok && integrity.origin_ok;
    let integrity_line = if integrity_ok && integrity.build.is_official() {
        format!(
            "{BOLD}Build origin{RST}  {GREEN}official{RST}  {DIM}{}{RST}",
            integrity.repo
        )
    } else if integrity_ok {
        format!(
            "{BOLD}Build origin{RST}  {YELLOW}{}{RST}  {DIM}not a release build, {}{RST}",
            integrity.build.label(),
            integrity.repo
        )
    } else {
        format!(
            "{BOLD}Build origin{RST}  {RED}MODIFIED REDISTRIBUTION{RST}  {YELLOW}pkg={}, repo={}{RST}",
            integrity.pkg_name, integrity.repo
        )
    };
    board.check(&Outcome {
        ok: integrity_ok,
        line: integrity_line,
    });

    // 13) Cache safety
    let cache_safety = cache_safety_outcome();
    board.check(&cache_safety);

    // 14) Claude Code instruction truncation guard
    let claude_truncation = claude_truncation_outcome();
    if let Some(ref ct) = claude_truncation {
        board.check(ct);
    }

    // 14a) CodeBuddy instruction truncation guard
    let codebuddy_truncation = codebuddy_truncation_outcome();
    if let Some(ref cbt) = codebuddy_truncation {
        board.check(cbt);
    }

    // 14b) Installed addons: what the registry actually holds, which is not
    // the same question as what the store contains — `addon list` reads disk,
    // this reads the running engine.
    if let Some(ref addons) = addons_loaded_outcome() {
        board.check(addons);
    }

    // 15) BM25 cache health
    let bm25_health = bm25_cache_health_outcome();
    board.check(&bm25_health);

    // 15-pre) Quarantined corrupt stats.json (#706): the loader preserved a
    // display cache it could not parse — surface it instead of losing history.
    let stats_quarantine = stats_quarantine_outcome();
    board.check(&stats_quarantine);

    // 15a) Search indexes for the active project: the BM25 runtime status
    // (surfaces a stuck "warming" index, #249) and the dense vector index
    // on disk — reported separately so neither masquerades as the other (#1887).
    for check in search_index_outcomes() {
        board.check(&check);
    }

    // 15b) Archive FTS footprint
    let archive_footprint = archive_footprint_outcome();
    board.check(&archive_footprint);

    // 16) Memory profile
    let mem_profile = memory_profile_outcome();
    board.check(&mem_profile);

    // 17) Memory cleanup
    let mem_cleanup = memory_cleanup_outcome();
    board.check(&mem_cleanup);

    // 18) RAM Guardian
    let ram_outcome = ram_guardian_outcome();
    board.check(&ram_outcome);

    // 19) Capacity warnings (memory stores near limits)
    let cap_warnings = capacity_warnings();
    for cw in &cap_warnings {
        board.check(cw);
    }

    // 19b) Orphaned knowledge stores (deleted projects — reclaimable bloat, #615)
    let orphan_outcome = orphaned_knowledge_outcome();
    board.check(&orphan_outcome);

    // 20) Proxy health
    let proxy_health = proxy_health_outcome();
    board.check(&proxy_health);

    // 20a) Proxy upstream drift (#449): running proxy serves a different upstream
    // than config.toml resolves to (env override masking config). Only surfaces
    // when the proxy is up and actually drifting.
    let upstream_drift = proxy_upstream_drift_outcome();
    if let Some(ref check) = upstream_drift {
        board.check(check);
    }

    // 20) Stale proxy env (ANTHROPIC_BASE_URL pointing to local proxy while proxy is not enabled)
    let stale_env = stale_proxy_env_outcome();
    if let Some(ref check) = stale_env {
        board.check(check);
    }

    // 21) Claude Pro/Max subscription routed through the proxy without an API key
    let subscription_conflict = proxy_subscription_conflict_outcome();
    if let Some(ref check) = subscription_conflict {
        board.check(check);
    }

    // 21a) Removed automatic model routing: a leftover tier table routes nothing.
    if let Some(ref check) = removed_routing_tiers_outcome() {
        board.check(check);
    }

    // 21b) Context gateway coverage per configured host (G7): enforced only
    // where model traffic is proxy-routed; never claims more than it sees.
    let coverage_check = gateway_coverage_outcome();
    board.check(&coverage_check);

    // 22) Deprecation register (CONTRACTS.md policy, GL #394): warn about
    // every surface this build deprecates, with replacement and removal floor.
    let deprecation_check = deprecations::deprecations_outcome();
    board.check(&deprecation_check);

    // MCP server CWD warning (informational, only fires when running as MCP)
    let mcp_cwd = mcp_server_cwd_outcome();
    board.check(&mcp_cwd);

    // LSP servers (optional, informational)
    if !json {
        println!(
            "\n  {BOLD}{WHITE}Semantic intelligence (optional — LSP references + verified graph edges):{RST}"
        );
    }
    board.info(&semantic_mode_outcome());
    let lsp_outcomes = lsp_server_outcomes();
    for lsp_check in &lsp_outcomes {
        board.info(lsp_check);
    }
    for coverage in semantic_coverage_outcomes() {
        board.info(&coverage);
    }

    // Shadow mode status. #1280: the old single line claimed "native tools
    // denied" wholesale, but that guarantee only covers Read/Grep/Glob — shell
    // coverage depends on shell_hook_mode (rewrite hooks pass unknown commands
    // through raw). Report the two surfaces separately so users audit against
    // reality.
    let cfg = lean_ctx::core::config::Config::load();
    let shell_mode = std::env::var("LEAN_CTX_SHELL_HOOK_MODE")
        .ok()
        .filter(|v| !v.trim().is_empty())
        .or_else(|| cfg.shell_hook_mode.clone())
        .unwrap_or_default();
    let shell_desc = if shell_mode.trim().eq_ignore_ascii_case("deny") {
        format!("{GREEN}deny{RST} {DIM}(all shell via ctx_shell){RST}")
    } else {
        format!(
            "{YELLOW}rewrite{RST} {DIM}(unknown commands pass through raw — shell_hook_mode=deny closes this){RST}"
        )
    };
    // Only claim "active" when a host really has lean-ctx hooks installed —
    // `shadow_mode = true` is the default even before anything is configured.
    let shadow_hosts = dirs::home_dir()
        .map(|home| checks::shadow_hosts(&home))
        .unwrap_or_default();
    let (shadow_state, shadow_detail) = checks::shadow_status(cfg.shadow_mode, &shadow_hosts);
    let state_color = if shadow_state == "active" { GREEN } else { DIM };
    let shadow_line = if shadow_state == "not active" || shadow_state == "disabled" {
        format!(
            "{BOLD}Shadow mode{RST}  {state_color}{shadow_state}{RST}  {DIM}{shadow_detail}{RST}"
        )
    } else {
        format!(
            "{BOLD}Shadow mode{RST}  {state_color}{shadow_state}{RST}  {DIM}{shadow_detail}{RST}  shell: {shell_desc}"
        )
    };
    if !json {
        println!("  {shadow_line}");
    }

    // Tool-schema footprint (informational, not scored). With no profile pinned
    // the server runs in lean mode — only the lazy core is advertised and every
    // tool stays reachable via ctx_call — so report that, not the internal
    // `power` call-gate fallback that `from_config` returns for an empty config
    // (otherwise `doctor` claimed "power" right after the wizard chose lean, #415).
    let tool_profile_line = if lean_ctx_server::server::tool_visibility::explicit_profile(&cfg) {
        let profile = lean_ctx::core::tool_profiles::ToolProfile::from_config(&cfg);
        format!(
            "{BOLD}Tool profile{RST}  {WHITE}{profile}{RST}  {DIM}{} + ctx_call gateway{RST}",
            profile.description()
        )
    } else {
        let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
        format!(
            "{BOLD}Tool profile{RST}  {WHITE}lean (default){RST}  {DIM}{lazy_count} lazy-core tools advertised + ctx_call gateway{RST}"
        )
    };
    if !json {
        println!("  {tool_profile_line}");
    }

    // Session cache health (#361): answer "is the cache actually engaging?"
    // without external instrumentation. CEP sessions + the cross-call hit ratio
    // come from the persistent stats store; `verify-cache` proves it live.
    let cep = &lean_ctx::core::stats::load().cep;
    let hit_ratio = if cep.total_cache_reads > 0 {
        (cep.total_cache_hits as f64 / cep.total_cache_reads as f64) * 100.0
    } else {
        0.0
    };
    if !json {
        println!(
            "  {BOLD}Session cache{RST}  {WHITE}{} sessions{RST}  {DIM}{}/{} reads cached ({hit_ratio:.0}% hit) · prove: lean-ctx verify-cache{RST}",
            cep.sessions, cep.total_cache_hits, cep.total_cache_reads
        );
    }

    // The board counted exactly what it rendered — the displayed ✓/✗ list and
    // this tally can no longer drift apart (#433).
    let passed = board.passed;
    let total = board.total;
    let needs_attention = total.saturating_sub(passed);

    if json {
        let output = serde_json::json!({
            "version": env!("CARGO_PKG_VERSION"),
            "build": lean_ctx::core::integrity::build().to_json(),
            "passed": passed,
            "total": total,
            "needs_attention": needs_attention,
            "checks": board.entries,
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&output).unwrap_or_default()
        );
    } else {
        println!();
        println!(
            "  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{total}{RST} checks passed"
        );
        if needs_attention > 0 {
            println!(
                "  {YELLOW}{needs_attention} check(s) need attention.{RST}  Auto-repair what's fixable:  {BOLD}lean-ctx doctor --fix{RST}"
            );
        } else {
            println!("  {GREEN}Everything looks good.{RST}");
        }
        println!("  {DIM}LSP servers are optional enhancements (not counted in score){RST}");
        println!("  {DIM}{}{RST}", lean_ctx::core::integrity::origin_line());

        lean_ctx::core::version_check::check_background();
        if let Some(banner) = lean_ctx::core::version_check::get_update_banner() {
            println!();
            println!("{banner}");
        }
    }

    needs_attention
}

pub fn run_compact() {
    let (passed, total) = compact_score();
    print_compact_status(passed, total);
}

pub fn run_cli(args: &[String]) -> i32 {
    let (sub, rest) = match args.first().map(String::as_str) {
        Some("integrations") => ("integrations", &args[1..]),
        Some("overhead") => ("overhead", &args[1..]),
        Some("lint-context") => ("lint-context", &args[1..]),
        _ => ("", args),
    };

    let fix = rest.iter().any(|a| a == "--fix");
    let json = rest.iter().any(|a| a == "--json");
    let gate = rest.iter().any(|a| a == "--gate");
    let migrate_check = rest.iter().any(|a| a == "--migrate-check");
    let help = rest.iter().any(|a| a == "--help" || a == "-h");

    if help {
        println!("Usage:");
        println!("  lean-ctx doctor");
        println!(
            "  lean-ctx doctor overhead [--json] [--gate]   Fixed context cost per session (--gate: non-zero exit when over [context] budget_tokens)"
        );
        println!(
            "  lean-ctx doctor lint-context [--json]   Lint injected context for low-signal/dup lines"
        );
        println!("  lean-ctx doctor integrations [--json]");
        println!("  lean-ctx doctor --fix [--json]");
        println!("  lean-ctx doctor --migrate-check [--json]");
        println!();
        println!(
            "Exit status: 0 when every scored check passes (optional items and a not-yet-set-up install never fail), 1 when a check needs attention."
        );
        return 0;
    }

    if sub == "overhead" {
        return overhead::run_overhead(json, gate);
    }

    if sub == "lint-context" {
        return lint_context::run_lint_context(json);
    }

    if migrate_check {
        return migrate::run_migrate_check(json);
    }

    if sub == "integrations" {
        if fix {
            let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
        }
        return integrations::run_integrations(&integrations::IntegrationsOptions { json });
    }

    if !fix {
        // Non-zero exit when checks need attention so `lean-ctx doctor` works
        // as a CI/health gate, not just a pretty printer.
        let needs = if json { run_json() } else { run() };
        return i32::from(needs > 0);
    }

    match fix::run_fix(&fix::DoctorFixOptions { json }) {
        Ok(code) => code,
        Err(e) => {
            tracing::error!("doctor --fix failed: {e}");
            2
        }
    }
}

pub fn compact_score() -> (u32, u32) {
    let mut passed = 0u32;
    let total = 6u32;

    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
        passed += 1;
    }
    let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
        passed += 1;
    }
    if lean_dir
        .as_ref()
        .map(|d| d.join("stats.json"))
        .and_then(|p| std::fs::metadata(p).ok())
        .is_some_and(|m| m.is_file())
    {
        passed += 1;
    }
    if shell_aliases_outcome().ok {
        passed += 1;
    }
    if mcp_config_outcome().ok {
        passed += 1;
    }
    if skill_files_outcome().ok {
        passed += 1;
    }

    (passed, total)
}

pub(super) fn print_compact_status(passed: u32, total: u32) {
    let status = if passed == total {
        format!("{GREEN}✓ All {total} checks passed{RST}")
    } else {
        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
    };
    println!("  {status}");
}

/// One line for a paused config migration (#2175): the stable state, both
/// journal files and the action that works in that state.
fn config_migration_pause_outcome(config: &std::path::Path) -> Option<Outcome> {
    let pause = lean_ctx::core::config::config_migration_pause_status(config)?;
    Some(Outcome {
        ok: false,
        line: format!(
            "{BOLD}config migration{RST}  {YELLOW}paused ({}){RST}  {DIM}{} · {}{RST}  {DIM}({}){RST}",
            pause.label,
            pause.backup.display(),
            pause.receipt.display(),
            pause.action
        ),
    })
}

#[cfg(test)]
mod tests {
    use super::is_active_shell_impl;
    use super::{DaemonAutostart, daemon_outcome, hive_sync_outcome, unrecorded_services_outcome};
    use super::{request_ledger_outcomes, strip_ansi};

    #[test]
    fn hive_sync_needs_a_supervised_daemon_when_connected() {
        assert!(hive_sync_outcome(false, &DaemonAutostart::Off).is_none());
        assert!(hive_sync_outcome(true, &DaemonAutostart::Unsupported).is_none());
        let off = hive_sync_outcome(true, &DaemonAutostart::Off).unwrap();
        assert!(!off.ok);
        assert!(off.line.contains("lean-ctx daemon enable"), "{}", off.line);
        assert!(
            hive_sync_outcome(true, &DaemonAutostart::On(None))
                .unwrap()
                .ok
        );
    }

    /// #2197: doctor names each running server's counters, its oldest
    /// pending request with age and stage, and its last tool completion, and
    /// flags a request pending past the stuck threshold.
    #[test]
    fn request_ledger_lines_show_counters_oldest_pending_and_last_completion() {
        use lean_ctx::core::request_ledger::{
            CompletionRecord, Outcome as RequestOutcome, PendingRequest, RequestLedgerSnapshot,
            Stage,
        };
        let now = 1_000_000_000;
        let snapshot = RequestLedgerSnapshot {
            pid: 4242,
            kind: "http".into(),
            generation: "gen".into(),
            started_at_ms: now - 600_000,
            snapshot_at_ms: now - 1_000,
            admitted: 40,
            completed: 36,
            errored: 1,
            refused: 2,
            abandoned: 1,
            pending: 2,
            untracked_pending: 0,
            oldest_pending: Some(PendingRequest {
                method: "tools/call:ctx_read".into(),
                stage: Stage::Handler,
                admitted_at_ms: now - 74_000,
                age_ms: None,
            }),
            last_tool_completion: Some(CompletionRecord {
                method: "tools/call:ctx_search".into(),
                outcome: RequestOutcome::Completed,
                finished_at_ms: now - 3_000,
                duration_ms: 12,
                age_ms: None,
            }),
            last_initialize: None,
            current_phase: None,
            observations: lean_ctx::core::events::DetachedObservationStats::default(),
        };
        let lines = request_ledger_outcomes(std::slice::from_ref(&snapshot), now);
        assert_eq!(lines.len(), 1);
        let line = strip_ansi(&lines[0].line);
        assert!(!lines[0].ok, "a 74 s pending request is flagged: {line}");
        assert!(line.contains("pid 4242 (http), up 10m"), "{line}");
        assert!(
            line.contains(
                "admitted 40 · completed 36 · errored 1 · refused 2 · abandoned 1 · pending 2"
            ),
            "{line}"
        );
        assert!(
            line.contains("oldest pending tools/call:ctx_read 74s in handler"),
            "{line}"
        );
        assert!(
            line.contains("last tool completion 3s ago (completed, 12ms)"),
            "{line}"
        );
        assert!(line.contains("last initialize none yet"), "{line}");

        let idle = RequestLedgerSnapshot {
            pending: 0,
            oldest_pending: None,
            ..snapshot
        };
        let lines = request_ledger_outcomes(&[idle], now);
        assert!(lines[0].ok);
        assert!(strip_ansi(&lines[0].line).contains("oldest pending none"));
    }

    /// Owner decision 02.11.: services this instance did not record are
    /// listed with PID and the exact stop command; nothing when none run.
    #[test]
    fn daemon_unrecorded_services_line_lists_pids_and_the_stop_command() {
        assert!(unrecorded_services_outcome(None).is_none());
        let outcome = unrecorded_services_outcome(Some((
            "Still running, not started by this instance (left alone): proxy (PID 913).".into(),
            "Stop them with: kill 913".into(),
        )))
        .expect("listed");
        assert!(outcome.ok);
        assert!(outcome.line.contains("proxy (PID 913)"), "{}", outcome.line);
        assert!(outcome.line.contains("kill 913"), "{}", outcome.line);
    }

    /// #2176: Windows doctor said "not supported on this platform" although
    /// the daemon runs there. Every platform reports the real state now.
    #[test]
    fn daemon_line_reports_real_state_without_autostart_service() {
        let running = daemon_outcome(Some(36492), &DaemonAutostart::Unsupported);
        assert!(running.ok);
        assert!(
            running.line.contains("running (PID 36492)"),
            "{}",
            running.line
        );
        assert!(!running.line.contains("not supported"));
        assert!(!running.line.contains("autostart"));

        let stopped = daemon_outcome(None, &DaemonAutostart::Unsupported);
        assert!(stopped.line.contains("not running"), "{}", stopped.line);
        assert!(stopped.line.contains("lean-ctx daemon start"));
        assert!(!stopped.line.contains("daemon enable"), "{}", stopped.line);
        assert!(!stopped.line.contains("not supported"));
    }

    #[test]
    fn daemon_line_keeps_autostart_details_where_supported() {
        let path = std::path::PathBuf::from("/x/com.leanctx.daemon.plist");
        let on = daemon_outcome(Some(7), &DaemonAutostart::On(Some(path)));
        assert!(on.line.contains("running (PID 7)"));
        assert!(
            on.line
                .contains("autostart: on — /x/com.leanctx.daemon.plist")
        );
        let restarting = daemon_outcome(None, &DaemonAutostart::On(None));
        assert!(restarting.line.contains("autostart enabled, will restart"));
        let off = daemon_outcome(None, &DaemonAutostart::Off);
        assert!(off.line.contains("lean-ctx daemon enable"));
    }

    #[test]
    fn doctor_reports_a_paused_config_migration_with_files_and_action() {
        let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
        let path = lean_ctx::core::config::Config::path().expect("isolated config path");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        // Unique bytes: `Config::load` caches by content hash.
        std::fs::write(
            &path,
            "# doctor paused-migration test\nterse_agent = \"full\"\n",
        )
        .unwrap();
        assert!(super::config_migration_pause_outcome(&path).is_none());

        // A journal that cannot be verified pauses the migration on load.
        let backup = path.with_file_name("config.toml.v4-migration.bak");
        let receipt = path.with_file_name("config.toml.v4-migration.json");
        std::fs::write(&backup, "tampered = true\n").unwrap();
        std::fs::write(&receipt, "{ not json").unwrap();
        let _ = lean_ctx::core::config::Config::load();

        let outcome =
            super::config_migration_pause_outcome(&path).expect("doctor reports the pause");
        assert!(!outcome.ok);
        assert!(
            outcome.line.contains("receipt-unverifiable"),
            "{}",
            outcome.line
        );
        assert!(
            outcome.line.contains("config.toml.v4-migration.bak"),
            "{}",
            outcome.line
        );
        assert!(
            outcome.line.contains("config.toml.v4-migration.json"),
            "{}",
            outcome.line
        );
        assert!(
            outcome.line.contains("move both out of"),
            "{}",
            outcome.line
        );
    }

    // Mirrors the inline classification in `checks::capacity_warnings`: a store at
    // or below its cap is at most a WARN (healthy, eviction keeps it there); only
    // a store *over* cap is CRIT (eviction is not keeping up).
    fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
        if limit == 0 {
            return None;
        }
        let pct = (current as f64 / limit as f64 * 100.0) as u32;
        if pct > 100 {
            Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
        } else if pct >= 80 {
            Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
        } else {
            None
        }
    }

    #[test]
    fn capacity_below_80_no_warning() {
        assert!(make_capacity_check("facts", 100, 200).is_none());
        assert!(make_capacity_check("facts", 159, 200).is_none());
    }

    #[test]
    fn capacity_at_80_yellow_warning() {
        let result = make_capacity_check("facts", 160, 200);
        assert!(result.is_some());
        let (critical, msg) = result.unwrap();
        assert!(!critical);
        assert!(msg.contains("160/200"));
        assert!(msg.contains("80%"));
    }

    #[test]
    fn capacity_at_92_yellow_warning() {
        let result = make_capacity_check("facts", 185, 200);
        assert!(result.is_some());
        let (critical, msg) = result.unwrap();
        assert!(!critical);
        assert!(msg.contains("185/200"));
        assert!(msg.contains("92%"));
    }

    #[test]
    fn capacity_at_95_is_warning_not_critical() {
        let result = make_capacity_check("facts", 190, 200);
        assert!(result.is_some());
        let (critical, msg) = result.unwrap();
        assert!(!critical, "95% is full-but-healthy, not over cap");
        assert!(msg.contains("190/200"));
        assert!(msg.contains("95%"));
    }

    #[test]
    fn capacity_at_100_is_warning_not_critical() {
        // A store exactly at its cap is healthy — eviction keeps it there.
        let result = make_capacity_check("facts", 200, 200);
        assert!(result.is_some());
        let (critical, _) = result.unwrap();
        assert!(!critical);
    }

    #[test]
    fn capacity_over_100_is_critical() {
        // Genuinely over cap => eviction is not keeping up (regression guard for
        // the 206/200 "CRIT" that fired before lifecycle eviction was fixed).
        let result = make_capacity_check("facts", 206, 200);
        assert!(result.is_some());
        let (critical, msg) = result.unwrap();
        assert!(critical);
        assert!(msg.contains("206/200"));
        assert!(msg.contains("103%"));
    }

    #[test]
    fn capacity_zero_limit_skipped() {
        assert!(make_capacity_check("facts", 50, 0).is_none());
    }

    #[test]
    fn bashrc_active_on_non_windows_when_shell_empty() {
        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
    }

    #[test]
    fn bashrc_not_active_on_windows_when_shell_empty() {
        assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
    }

    #[test]
    fn bashrc_active_when_shell_contains_bash_on_linux() {
        assert!(is_active_shell_impl(
            "~/.bashrc",
            "/usr/bin/bash",
            false,
            false
        ));
    }

    #[test]
    fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
        let _env_lock = lean_ctx::core::data_dir::test_env_lock();
        // Issue #214: On Windows, Git Bash sets $SHELL globally to bash.exe.
        // .bashrc should NOT be flagged on Windows unless actually inside bash.
        lean_ctx::test_env::remove_var("BASH_VERSION");
        assert!(!is_active_shell_impl(
            "~/.bashrc",
            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
            true,
            false,
        ));
    }

    #[test]
    fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
        assert!(!is_active_shell_impl(
            "~/.bashrc",
            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
            true,
            true,
        ));
    }

    #[test]
    fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
        assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
    }

    #[test]
    fn zshrc_unaffected_by_powershell_flag() {
        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
    }

    #[test]
    fn bashrc_not_active_on_windows_without_powershell_detection() {
        let _env_lock = lean_ctx::core::data_dir::test_env_lock();
        // Windows + $SHELL=bash but NOT in actual bash session (no BASH_VERSION).
        // This is the exact scenario from issue #214: Git Bash sets $SHELL globally.
        lean_ctx::test_env::remove_var("BASH_VERSION");
        assert!(!is_active_shell_impl(
            "~/.bashrc",
            "/usr/bin/bash",
            true,
            false,
        ));
    }

    #[test]
    fn bashrc_active_on_linux() {
        assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
    }
}