lean-ctx 3.12.1

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
// SPDX-License-Identifier: Apache-2.0
//! On-disk stores & memory: BM25/semantic indexes, archive FTS, RAM
//! guardian, knowledge stores, capacity accounting.

#[allow(clippy::wildcard_imports)]
use crate::doctor::common::*;
use crate::doctor::{BOLD, DIM, GREEN, Outcome, RED, RST, YELLOW};

pub(crate) fn cache_safety_outcome() -> Outcome {
    use lean_ctx::core::provider_cache::ProviderCacheState;

    let mut issues = Vec::new();

    let mut state = ProviderCacheState::new();
    let section = lean_ctx::core::provider_cache::CacheableSection::new(
        "doctor_test",
        "test content".into(),
        lean_ctx::core::provider_cache::SectionPriority::System,
        true,
    );
    state.mark_sent(&section);
    if state.needs_update(&section) {
        issues.push("provider_cache: hash tracking broken");
    }

    if issues.is_empty() {
        Outcome {
            ok: true,
            line: format!(
                "{BOLD}Cache safety{RST}  {GREEN}cache_alignment + provider_cache operational{RST}"
            ),
        }
    } else {
        Outcome {
            ok: false,
            line: format!("{BOLD}Cache safety{RST}  {RED}{}{RST}", issues.join("; ")),
        }
    }
}
/// Flags a quarantined `stats.json.corrupt` (#706): the stats loader moves an
/// unparseable display cache aside instead of silently overwriting history.
/// Doctor surfaces the quarantine so the loss is visible and recoverable
/// (the savings ledger remains the source of truth for a rebuild).
pub(crate) fn stats_quarantine_outcome() -> Outcome {
    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
        return Outcome {
            ok: true,
            line: format!("{BOLD}Stats store{RST}  {DIM}skipped (no data dir){RST}"),
        };
    };
    let quarantine = data_dir.join("stats.json.corrupt");
    if quarantine.exists() {
        Outcome {
            ok: false,
            line: format!(
                "{BOLD}Stats store{RST}  {YELLOW}corrupt stats.json was quarantined at {} — \
                 history before the corruption is inside; inspect/merge it, then delete the \
                 file to clear this warning{RST}",
                quarantine.display()
            ),
        }
    } else {
        Outcome {
            ok: true,
            line: format!("{BOLD}Stats store{RST}  {GREEN}no quarantined corruption{RST}"),
        }
    }
}

pub(crate) fn bm25_cache_health_outcome() -> Outcome {
    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
        return Outcome {
            ok: true,
            line: format!("{BOLD}BM25 cache{RST}  {DIM}skipped (no data dir){RST}"),
        };
    };

    let vectors_dir = data_dir.join("vectors");
    let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
        return Outcome {
            ok: true,
            line: format!("{BOLD}BM25 cache{RST}  {GREEN}no vector dirs{RST}"),
        };
    };

    // Single source of truth with `save`/`load` (decoupled from the RAM profile;
    // see bm25_index::persist_ceiling_bytes) so the warning threshold here always
    // matches what is actually enforced on disk.
    let max_bytes = lean_ctx::core::bm25_index::persist_ceiling_bytes();
    let effective_mb = max_bytes / (1024 * 1024);
    let warn_bytes = max_bytes * 80 / 100; // 80% of effective limit
    let mut total_dirs = 0u32;
    let mut total_bytes = 0u64;
    let mut oversized: Vec<(String, u64)> = Vec::new();
    let mut warnings: Vec<(String, u64)> = Vec::new();
    let mut quarantined_count = 0u32;

    for entry in entries.flatten() {
        let dir = entry.path();
        if !dir.is_dir() {
            continue;
        }
        total_dirs += 1;

        if dir.join("bm25_index.json.quarantined").exists()
            || dir.join("bm25_index.bin.quarantined").exists()
            || dir.join("bm25_index.bin.zst.quarantined").exists()
        {
            quarantined_count += 1;
        }

        let index_path = if dir.join("bm25_index.bin.zst").exists() {
            dir.join("bm25_index.bin.zst")
        } else if dir.join("bm25_index.bin").exists() {
            dir.join("bm25_index.bin")
        } else {
            dir.join("bm25_index.json")
        };
        if let Ok(meta) = std::fs::metadata(&index_path) {
            let size = meta.len();
            total_bytes += size;
            let display = index_path.display().to_string();
            if size > max_bytes {
                oversized.push((display, size));
            } else if size > warn_bytes {
                warnings.push((display, size));
            }
        }
    }

    if !oversized.is_empty() {
        let details: Vec<String> = oversized
            .iter()
            .map(|(p, s)| format!("{p} ({:.1} GB)", *s as f64 / 1_073_741_824.0))
            .collect();
        return Outcome {
            ok: false,
            line: format!(
                "{BOLD}BM25 cache{RST}  {RED}{} index(es) exceed limit ({:.0} MB){RST}: {}  {DIM}(run: lean-ctx cache prune){RST}",
                oversized.len(),
                max_bytes / (1024 * 1024),
                details.join(", ")
            ),
        };
    }

    if !warnings.is_empty() {
        let details: Vec<String> = warnings
            .iter()
            .map(|(p, s)| format!("{p} ({:.0} MB)", *s as f64 / 1_048_576.0))
            .collect();
        return Outcome {
            ok: true,
            line: format!(
                "{BOLD}BM25 cache{RST}  {YELLOW}{} index(es) >80% of {effective_mb} MB limit{RST}: {}  {DIM}(consider extra_ignore_patterns){RST}",
                warnings.len(),
                details.join(", ")
            ),
        };
    }

    let quarantine_note = if quarantined_count > 0 {
        format!("  {YELLOW}{quarantined_count} quarantined (run: lean-ctx cache prune){RST}")
    } else {
        String::new()
    };

    Outcome {
        ok: true,
        line: format!(
            "{BOLD}BM25 cache{RST}  {GREEN}{total_dirs} index(es), {:.1} MB total{RST}{quarantine_note}",
            total_bytes as f64 / 1_048_576.0
        ),
    }
}
/// Doctor lines for the active project's search indexes: the BM25 index and,
/// separately, the dense semantic (embedding) index.
///
/// #1887: the BM25 status used to be labelled "Semantic index", so doctor said
/// "ready" while `index status` (which reads the dense vectors) said "not
/// built". Both lines now name what they measure, and the semantic line reads
/// the same on-disk state as `index status`.
pub(crate) fn search_index_outcomes() -> Vec<Outcome> {
    bounded_outcomes(
        "Search indexes",
        INDEX_CHECK_DEADLINE,
        collect_search_index_outcomes,
    )
}

/// How long `doctor` waits for one group of checks that read the shared
/// index stores (#2179). Such a store can be held by another process — an
/// MCP server or daemon mid-build — and `doctor` must still print its
/// Summary and exit.
pub(crate) const INDEX_CHECK_DEADLINE: std::time::Duration = std::time::Duration::from_secs(10);

/// Runs `work` on its own thread and waits at most `deadline` for it.
/// `None` when it did not answer in time (or no thread could be started);
/// the thread is then left detached — it holds no lock `doctor` needs, and
/// a detached thread does not keep the process from exiting once `main`
/// returns.
pub(crate) fn within_deadline<T: Send + 'static>(
    deadline: std::time::Duration,
    work: impl FnOnce() -> T + Send + 'static,
) -> Option<T> {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::Builder::new()
        .name("doctor-check".into())
        .spawn(move || {
            let _ = tx.send(work());
        })
        .ok()?;
    rx.recv_timeout(deadline).ok()
}

/// `work`'s outcomes, or one "skipped (busy)" line for `label` when it did
/// not answer within `deadline`. A busy store is not a broken install, so
/// the line does not fail the health gate; it says how to look again.
pub(crate) fn bounded_outcomes(
    label: &str,
    deadline: std::time::Duration,
    work: impl FnOnce() -> Vec<Outcome> + Send + 'static,
) -> Vec<Outcome> {
    within_deadline(deadline, work).unwrap_or_else(|| vec![busy_outcome(label, deadline)])
}

pub(crate) fn busy_outcome(label: &str, deadline: std::time::Duration) -> Outcome {
    Outcome {
        ok: true,
        line: format!(
            "{BOLD}{label}{RST}  {YELLOW}skipped (busy: no answer within {}s — another lean-ctx process may hold the store){RST}  {DIM}(retry: lean-ctx index status){RST}",
            deadline.as_secs()
        ),
    }
}

fn collect_search_index_outcomes() -> Vec<Outcome> {
    let Some(project_root) =
        lean_ctx::core::session::SessionState::load_latest().and_then(|s| s.project_root)
    else {
        return Vec::new();
    };
    let disk = lean_ctx::core::index_orchestrator::disk_status_for_semantic(&project_root);
    vec![
        bm25_index_outcome(&project_root),
        dense_index_outcome(&disk, cfg!(feature = "embeddings")),
    ]
}

/// Dense (embedding) index status from the vectors on disk.
fn dense_index_outcome(
    disk: &lean_ctx::core::index_orchestrator::DiskStatus,
    embeddings_build: bool,
) -> Outcome {
    if !embeddings_build {
        return Outcome {
            ok: true,
            line: format!(
                "{BOLD}Semantic index{RST}  {DIM}not available (built without embeddings){RST}"
            ),
        };
    }
    if !disk.exists {
        return Outcome {
            ok: true,
            line: format!(
                "{BOLD}Semantic index{RST}  {DIM}not built (run: lean-ctx index build-semantic; runtime: lean-ctx embeddings status){RST}"
            ),
        };
    }
    if let Some(total) = disk.partial_of {
        return Outcome {
            ok: true,
            line: format!(
                "{BOLD}Semantic index{RST}  {YELLOW}partial{RST} {DIM}({}/{total} chunks embedded — resume: lean-ctx index build-semantic){RST}",
                disk.file_count.unwrap_or(0)
            ),
        };
    }
    let mut details = Vec::new();
    if let Some(b) = disk.size_bytes {
        details.push(format!("{:.1} MB", b as f64 / 1_048_576.0));
    }
    if let Some(ref t) = disk.modified_at {
        details.push(format!("built {t}"));
    }
    let details = if details.is_empty() {
        String::new()
    } else {
        format!(" {DIM}({}){RST}", details.join(", "))
    };
    Outcome {
        ok: true,
        line: format!("{BOLD}Semantic index{RST}  {GREEN}ready{RST}{details}"),
    }
}

/// Runtime status of the BM25 index for the active project: whether it is
/// idle/building/ready/failed, how long the last build took, and — crucially
/// — *why* it might be stuck (e.g. "indexed but NOT persisted: too large").
///
/// This answers issue #249: users had no way to tell whether the index was
/// working, how fast it was, or why it kept "warming up" forever.
fn bm25_index_outcome(project_root: &str) -> Outcome {
    let summary = lean_ctx::core::index_orchestrator::bm25_summary(project_root);
    // Only the BM25 facet: the graph facets of `disk_status` are not shown
    // here and are the expensive ones (#2179).
    let bm25 = lean_ctx::core::index_orchestrator::disk_status_for_bm25(project_root);
    let persisted = if bm25.exists {
        let chunks = bm25
            .file_count
            .map(|n| format!(", {n} chunks"))
            .unwrap_or_default();
        match bm25.size_bytes {
            Some(b) => format!("persisted {:.1} MB{chunks}", b as f64 / 1_048_576.0),
            None => format!("persisted{chunks}"),
        }
    } else {
        "not persisted".to_string()
    };

    let timing = match summary.elapsed_ms {
        Some(ms) if summary.state == "building" => format!(", {:.1}s elapsed", ms as f64 / 1000.0),
        Some(ms) => format!(", built in {:.1}s", ms as f64 / 1000.0),
        None => String::new(),
    };

    match summary.state {
        "failed" => Outcome {
            ok: false,
            line: format!(
                "{BOLD}BM25 index{RST}  {RED}FAILED{RST}: {}  {DIM}(run: lean-ctx index build){RST}",
                summary
                    .last_error
                    .or(summary.note)
                    .unwrap_or_else(|| "unknown error".to_string())
            ),
        },
        "building" => Outcome {
            ok: true,
            line: format!("{BOLD}BM25 index{RST}  {YELLOW}building{timing}{RST}"),
        },
        _ if summary
            .note
            .as_deref()
            .is_some_and(|n| n.contains("NOT persisted")) =>
        {
            Outcome {
                ok: false,
                line: format!(
                    "{BOLD}BM25 index{RST}  {YELLOW}rebuilds every cold start{RST}: {}",
                    summary.note.unwrap_or_default()
                ),
            }
        }
        // #1914: a persisted index with zero chunks answers every search with
        // nothing, so it must not read as ready.
        _ if bm25.exists && bm25.file_count == Some(0) => Outcome {
            ok: true,
            line: format!(
                "{BOLD}BM25 index{RST}  {YELLOW}empty{RST} {DIM}(0 chunks on disk — run: lean-ctx index build){RST}"
            ),
        },
        "ready" => Outcome {
            ok: true,
            line: format!(
                "{BOLD}BM25 index{RST}  {GREEN}ready{RST} {DIM}({persisted}{timing}){RST}"
            ),
        },
        // idle: never asked to build this session — report disk state only.
        _ if bm25.exists => Outcome {
            ok: true,
            line: format!(
                "{BOLD}BM25 index{RST}  {GREEN}ready{RST} {DIM}({persisted}, on disk){RST}"
            ),
        },
        _ => Outcome {
            ok: true,
            line: format!(
                "{BOLD}BM25 index{RST}  {DIM}not built yet (builds on first search/compose){RST}"
            ),
        },
    }
}

pub(crate) fn archive_footprint_outcome() -> Outcome {
    let bytes = lean_ctx::core::archive_fts::db_size_bytes();
    let cap_mb = std::env::var("LEAN_CTX_ARCHIVE_DB_MAX_MB")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|m| *m > 0)
        .unwrap_or(500);
    let cap_bytes = cap_mb * 1024 * 1024;
    let mb = bytes as f64 / 1_048_576.0;
    if bytes > cap_bytes {
        Outcome {
            ok: false,
            line: format!(
                "{BOLD}Archive FTS{RST}  {RED}{mb:.0} MB exceeds {cap_mb} MB cap{RST}  {DIM}(run: lean-ctx cache prune; auto-enforced on next session){RST}"
            ),
        }
    } else if bytes > cap_bytes * 80 / 100 {
        Outcome {
            ok: true,
            line: format!(
                "{BOLD}Archive FTS{RST}  {YELLOW}{mb:.0} MB (>80% of {cap_mb} MB cap){RST}"
            ),
        }
    } else {
        Outcome {
            ok: true,
            line: format!("{BOLD}Archive FTS{RST}  {GREEN}{mb:.1} MB / {cap_mb} MB cap{RST}"),
        }
    }
}
pub(crate) fn memory_profile_outcome() -> Outcome {
    let cfg = lean_ctx::core::config::Config::load();
    let profile = lean_ctx::core::config::MemoryProfile::effective(&cfg);
    // The BM25 *disk* ceiling is decoupled from the RAM profile (#249); show the
    // real effective ceiling rather than a hardcoded per-profile figure.
    let bm25_mb = cfg.bm25_max_cache_mb_effective();
    let (label, detail) = match profile {
        lean_ctx::core::config::MemoryProfile::Low => (
            "low",
            format!("embeddings+semantic cache disabled, BM25 disk {bm25_mb} MB"),
        ),
        lean_ctx::core::config::MemoryProfile::Balanced => (
            "balanced",
            format!("default — single embedding engine, BM25 disk {bm25_mb} MB"),
        ),
        lean_ctx::core::config::MemoryProfile::Performance => (
            "performance",
            format!("full caches, BM25 disk {bm25_mb} MB"),
        ),
    };
    let source = if lean_ctx::core::config::MemoryProfile::from_env().is_some() {
        "env"
    } else if cfg.memory_profile != lean_ctx::core::config::MemoryProfile::default() {
        "config"
    } else {
        "default"
    };
    Outcome {
        ok: true,
        line: format!(
            "{BOLD}Memory profile{RST}  {GREEN}{label}{RST}  {DIM}({source}: {detail}){RST}"
        ),
    }
}
pub(crate) fn memory_cleanup_outcome() -> Outcome {
    let cfg = lean_ctx::core::config::Config::load();
    let cleanup = lean_ctx::core::config::MemoryCleanup::effective(&cfg);
    let (label, detail) = match cleanup {
        lean_ctx::core::config::MemoryCleanup::Aggressive => (
            "aggressive",
            "cache cleared after 5 min idle, single-IDE optimized",
        ),
        lean_ctx::core::config::MemoryCleanup::Shared => (
            "shared",
            "cache retained 1 hour, multi-IDE/multi-model optimized",
        ),
    };
    let source = if lean_ctx::core::config::MemoryCleanup::from_env().is_some() {
        "env"
    } else if cfg.memory_cleanup != lean_ctx::core::config::MemoryCleanup::default() {
        "config"
    } else {
        "default"
    };
    Outcome {
        ok: true,
        line: format!(
            "{BOLD}Memory cleanup{RST}  {GREEN}{label}{RST}  {DIM}({source}: {detail}){RST}"
        ),
    }
}
pub(crate) fn ram_guardian_outcome() -> Outcome {
    // Measure the daemon's RSS (not the CLI process) when the daemon is running.
    // #2176 VM: only a verified daemon, never a reused PID from daemon.pid.
    let daemon_pid = lean_ctx::daemon::verified_daemon().map(|daemon| daemon.pid);
    let snap = match daemon_pid {
        Some(pid) => lean_ctx::core::memory_guard::MemorySnapshot::capture_for_pid(pid),
        _ => lean_ctx::core::memory_guard::MemorySnapshot::capture(),
    };
    let Some(snap) = snap else {
        return Outcome {
            ok: true,
            line: format!(
                "{BOLD}RAM Guardian{RST}  {YELLOW}not available{RST}  {DIM}(platform unsupported){RST}"
            ),
        };
    };
    let allocator = if cfg!(all(
        feature = "jemalloc",
        not(windows),
        not(target_env = "musl")
    )) {
        "jemalloc"
    } else {
        "system"
    };
    let source = if daemon_pid.is_some() {
        "daemon"
    } else {
        "self"
    };
    let ok = snap.pressure_level == lean_ctx::core::memory_guard::PressureLevel::Normal;
    let color = if ok { GREEN } else { RED };
    let pressure_hint = match snap.pressure_level {
        lean_ctx::core::memory_guard::PressureLevel::Normal => String::new(),
        level => {
            format!(
                "  {YELLOW}pressure={level:?} — reduce memory_profile, provision RAM, or enforce an OS cgroup/container limit{RST}"
            )
        }
    };
    Outcome {
        ok,
        line: format!(
            "{BOLD}RAM Guardian{RST}  {color}{:.0} MB{RST} / {:.1} GB system ({:.1}%)  {DIM}limit: {:.0} MB ({allocator}, {source}){RST}{pressure_hint}",
            snap.rss_bytes as f64 / 1_048_576.0,
            snap.system_ram_bytes as f64 / 1_073_741_824.0,
            snap.rss_percent,
            snap.rss_limit_bytes as f64 / 1_048_576.0,
        ),
    }
}
/// Reports knowledge stores whose `project_root` was deleted (removed git
/// worktrees, thrown-away projects). Such a store can never be written again, so
/// its eviction cap can never self-heal — it is pure accumulated bloat. This is
/// informational (never a hard failure); `lean-ctx doctor --fix` reclaims it (#615).
pub(crate) fn orphaned_knowledge_outcome() -> Outcome {
    let orphans = lean_ctx::core::knowledge::maintenance::find_orphaned_stores();
    if orphans.is_empty() {
        return Outcome {
            ok: true,
            line: format!("{BOLD}Knowledge stores{RST}  {GREEN}no orphaned stores{RST}"),
        };
    }
    let bytes: u64 = orphans.iter().map(|o| o.size_bytes).sum();
    Outcome {
        ok: true,
        line: format!(
            "{BOLD}Knowledge stores{RST}  {YELLOW}{} orphaned ({} reclaimable){RST}  {DIM}(deleted projects — reclaim: lean-ctx cache prune){RST}",
            orphans.len(),
            human_bytes(bytes)
        ),
    }
}
pub(crate) fn capacity_warnings() -> Vec<Outcome> {
    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
        return vec![];
    };

    let cfg = lean_ctx::core::config::Config::load();
    let policy = cfg.memory_policy_effective().unwrap_or_default();

    let knowledge_dir = data_dir.join("knowledge");
    let Ok(entries) = std::fs::read_dir(&knowledge_dir) else {
        return vec![Outcome {
            ok: true,
            line: format!("{BOLD}Capacity{RST} {GREEN}no memory stores{RST}"),
        }];
    };

    let mut results = Vec::new();

    for entry in entries.flatten() {
        let hash_dir = entry.path();
        if !hash_dir.is_dir() {
            continue;
        }
        let hash = hash_dir
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        let short_hash = &hash[..hash.len().min(8)];

        let mut checks: Vec<(String, usize, usize)> = Vec::new();

        // Facts have no count limit (owner decision 24.10.: knowledge grows
        // without limit), so they are never "over cap".
        if let Ok(content) = std::fs::read_to_string(hash_dir.join("knowledge.json"))
            && let Ok(k) =
                serde_json::from_str::<lean_ctx::core::knowledge::ProjectKnowledge>(&content)
        {
            checks.push((
                "patterns".to_string(),
                k.patterns.len(),
                policy.knowledge.max_patterns,
            ));
            checks.push((
                "history".to_string(),
                k.history.len(),
                policy.knowledge.max_history,
            ));
        }

        if let Ok(content) = std::fs::read_to_string(hash_dir.join("embeddings.json"))
            && let Ok(idx) = serde_json::from_str::<
                lean_ctx::core::knowledge_embedding::KnowledgeEmbeddingIndex,
            >(&content)
        {
            checks.push((
                "embeddings".to_string(),
                idx.entries.len(),
                policy.embeddings.max_facts,
            ));
        }

        if let Ok(content) = std::fs::read_to_string(hash_dir.join("gotchas.json"))
            && let Ok(g) =
                serde_json::from_str::<lean_ctx::core::gotcha_tracker::GotchaStore>(&content)
        {
            checks.push((
                "gotchas".to_string(),
                g.gotchas.len(),
                policy.gotcha.max_gotchas_per_project,
            ));
        }

        let mut warnings: Vec<String> = Vec::new();
        let mut critical = false;

        for (name, current, limit) in &checks {
            if *limit == 0 {
                continue;
            }
            let pct = (*current as f64 / *limit as f64 * 100.0) as u32;
            // A store sitting *at* its cap is healthy: eviction (run_lifecycle)
            // keeps it there by design. Only flag CRIT when it is genuinely
            // *over* cap, which means eviction is not keeping up.
            if pct > 100 {
                critical = true;
                warnings.push(format!("{name}: {current}/{limit} ({pct}%)"));
            } else if pct >= 80 {
                warnings.push(format!("{name}: {current}/{limit} ({pct}%)"));
            }
        }

        if !warnings.is_empty() {
            let color = if critical { RED } else { YELLOW };
            let label = if critical { "CRIT" } else { "WARN" };
            results.push(Outcome {
                ok: !critical,
                line: format!(
                    "{BOLD}Capacity [{short_hash}]{RST} {color}{label}: {}{RST}",
                    warnings.join(", ")
                ),
            });
            // Actionable guidance (#972). A store *at* its cap is healthy by
            // design — eviction keeps it there; only *over* cap means curation is
            // falling behind. Point the operator at the right lever either way.
            results.push(Outcome {
                ok: true,
                line: format!("  {DIM}→ {}{RST}", capacity_hint(critical)),
            });
        }
    }

    // Global checks (not per project hash)

    // Archive disk usage vs limit
    let archive_limit_bytes = cfg.archive_max_disk_mb_effective() * 1_048_576;
    if archive_limit_bytes > 0 {
        let archive_used = lean_ctx::core::archive::disk_usage_bytes();
        let pct = (archive_used as f64 / archive_limit_bytes as f64 * 100.0) as u32;
        if pct >= 95 {
            results.push(Outcome {
                ok: false,
                line: format!(
                    "{BOLD}Capacity [archive]{RST} {RED}CRIT: disk {}/{}MB ({pct}%){RST}",
                    archive_used / 1_048_576,
                    archive_limit_bytes / 1_048_576
                ),
            });
        } else if pct >= 80 {
            results.push(Outcome {
                ok: true,
                line: format!(
                    "{BOLD}Capacity [archive]{RST} {YELLOW}WARN: disk {}/{}MB ({pct}%){RST}",
                    archive_used / 1_048_576,
                    archive_limit_bytes / 1_048_576
                ),
            });
        }
    }

    // Context Gateway evidence store vs its ceiling (G09): always its size,
    // ceiling and last maintenance. Old unprotected receipts are removed in
    // the background; only protected evidence filling the store, as the
    // last pass counted it, refuses NEW receipts, which under protection
    // withholds releases.
    let gateway_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()
        .ok()
        .map(|dir| dir.join("gateway"))
        .filter(|dir| dir.is_dir());
    if let Some(dir) = gateway_dir {
        use lean_ctx::core::context_admission::receipt_store::{retention, store_usage};
        let megabytes = cfg.gateway_store_max_mb_effective();
        let maintained = match retention::last_pass(&dir).and_then(|at| at.elapsed().ok()) {
            Some(age) => format!("last maintained {} min ago", age.as_secs() / 60),
            None => "not maintained yet".to_owned(),
        };
        let policy = format!(
            "kept {} days, last {} h protected",
            retention::RETENTION_DAYS,
            retention::PROTECT_HOURS
        );
        match store_usage(megabytes) {
            Some(Ok(usage)) => {
                let full = retention::proven_full(&dir);
                let (color, label, size) = match usage.limit_bytes.filter(|limit| *limit > 0) {
                    Some(limit) => {
                        let pct = (usage.bytes as f64 / limit as f64 * 100.0) as u32;
                        let (color, label) = if full {
                            (RED, "CRIT")
                        } else if pct >= 100 {
                            (YELLOW, "WARN")
                        } else {
                            (GREEN, "ok")
                        };
                        let size = format!(
                            "{}/{}MB ({pct}%)",
                            usage.bytes / 1_048_576,
                            limit / 1_048_576
                        );
                        (color, label, size)
                    }
                    None => (GREEN, "ok", format!("{}MB, no ceiling", usage.bytes / 1_048_576)),
                };
                results.push(Outcome {
                    ok: !full,
                    line: format!(
                        "{BOLD}Capacity [gateway receipts]{RST} {color}{label}: {size}, {} objects, {maintained}{RST} {DIM}({policy}){RST}",
                        usage.objects
                    ),
                });
                if full || label == "WARN" {
                    results.push(Outcome {
                        ok: true,
                        line: format!(
                            "  {DIM}→ {}{RST}",
                            if full {
                                "store full of protected evidence (recent, latest-indexed, tasks in progress): no new Decision Receipt is stored; \
                                 governed/sovereign releases are withheld. Raise LEAN_CTX_GATEWAY_STORE_MAX_MB (or max_disk_mb) or lower LEAN_CTX_GATEWAY_PROTECT_HOURS."
                            } else {
                                "older unprotected receipts are removed in the background; run `lean-ctx inspect --maintain` to do it now."
                            }
                        ),
                    });
                }
            }
            Some(Err(unmeasured)) => results.push(Outcome {
                ok: false,
                line: format!(
                    "{BOLD}Capacity [gateway receipts]{RST} {YELLOW}WARN: {unmeasured}; the ceiling is not enforced until every file under <data>/gateway can be read{RST}"
                ),
            }),
            None => {}
        }
    }

    // The installation's receipt key (keyed caller and request-head
    // references): a key file that is not a key refuses required proxy
    // receipts, and lean-ctx never replaces it on its own.
    if let Err(code) = lean_ctx::core::context_admission::receipt_store::keyed::key_status() {
        results.push(Outcome {
            ok: false,
            line: format!("{BOLD}Receipt key [gateway]{RST} {RED}CRIT: {code}{RST}"),
        });
        results.push(Outcome {
            ok: true,
            line: format!(
                "  {DIM}→ <data>/gateway/receipt.key is not a readable 32-byte key; proxy requests that owe a receipt are refused. Move it aside to let lean-ctx create a new key (references made under the old one no longer match).{RST}"
            ),
        });
    }

    // Graph index file count vs limit, bounded like the search-index checks:
    // it reads the active project's graph store (#2179).
    let graph_max_files = cfg.graph_index_max_files;
    if graph_max_files > 0 {
        results.extend(bounded_outcomes(
            "Capacity [graph]",
            INDEX_CHECK_DEADLINE,
            move || {
                graph_capacity_outcome(graph_max_files)
                    .into_iter()
                    .collect()
            },
        ));
    }

    if results.is_empty() {
        results.push(Outcome {
            ok: true,
            line: format!("{BOLD}Capacity{RST} {GREEN}all stores within limits{RST}"),
        });
    }

    results
}

/// The active project's graph index file count against its limit, when it
/// is at 80% or more.
fn graph_capacity_outcome(graph_max_files: u64) -> Option<Outcome> {
    let project_root = lean_ctx::core::session::SessionState::load_latest()?.project_root?;
    let graph_files =
        lean_ctx::core::index_orchestrator::disk_status_for_graph(&project_root).file_count?;
    let pct = (graph_files as f64 / graph_max_files as f64 * 100.0) as u32;
    if pct >= 95 {
        Some(Outcome {
            ok: false,
            line: format!(
                "{BOLD}Capacity [graph]{RST} {RED}CRIT: files {graph_files}/{graph_max_files} ({pct}%){RST}"
            ),
        })
    } else if pct >= 80 {
        Some(Outcome {
            ok: true,
            line: format!(
                "{BOLD}Capacity [graph]{RST} {YELLOW}WARN: files {graph_files}/{graph_max_files} ({pct}%){RST}"
            ),
        })
    } else {
        None
    }
}

/// Actionable next-step for a memory capacity warning (#972). Separated from the
/// on-disk capacity scan so the messaging is unit-tested directly: a store *at*
/// its cap is healthy (eviction holds it there), while *over* cap means curation
/// is behind and the operator should compact or raise the limit.
pub(crate) fn capacity_hint(critical: bool) -> &'static str {
    if critical {
        "over cap — eviction is behind. Run `lean-ctx knowledge consolidate --all` to compact project memory now, or raise the relevant memory.* cap"
    } else {
        "at/near cap is healthy by design — lean-ctx self-curates (write-time dedup #970, scheduled consolidation, 90-day prune #972). Raise a cap only if recall quality drops (memory.*)"
    }
}

#[cfg(test)]
mod tests {
    use super::{bounded_outcomes, dense_index_outcome};
    use lean_ctx::core::index_orchestrator::DiskStatus;

    #[test]
    fn dense_index_outcome_reports_vectors_not_bm25() {
        let absent = dense_index_outcome(&DiskStatus::default(), true);
        assert!(absent.line.contains("Semantic index"));
        assert!(absent.line.contains("not built"));
        assert!(absent.line.contains("build-semantic"));

        let built = DiskStatus {
            exists: true,
            size_bytes: Some(3 * 1_048_576),
            file_count: None,
            modified_at: Some("2026-09-28 10:00".into()),
            partial_of: None,
        };
        let ready = dense_index_outcome(&built, true);
        assert!(ready.ok);
        assert!(ready.line.contains("ready"));
        assert!(ready.line.contains("3.0 MB"));
        assert!(ready.line.contains("built 2026-09-28 10:00"));

        let checkpoint = DiskStatus {
            exists: true,
            file_count: Some(1200),
            partial_of: Some(5000),
            ..DiskStatus::default()
        };
        let partial = dense_index_outcome(&checkpoint, true);
        assert!(partial.line.contains("partial"));
        assert!(partial.line.contains("1200/5000"));
        assert!(partial.line.contains("build-semantic"));
        assert!(!partial.line.contains("ready"));

        let no_feature = dense_index_outcome(&built, false);
        assert!(no_feature.line.contains("built without embeddings"));
    }

    /// #2179: a check blocked on a store another holder keeps (here a held
    /// lock) yields one bounded "busy" line instead of hanging `doctor`.
    #[test]
    fn a_blocked_index_check_reports_busy_within_its_deadline() {
        use std::sync::{Arc, Mutex};
        use std::time::{Duration, Instant};

        let store = Arc::new(Mutex::new(()));
        let held = store.lock().expect("hold the store");
        let worker_store = Arc::clone(&store);
        let deadline = Duration::from_millis(200);

        let started = Instant::now();
        let outcomes = bounded_outcomes("Search indexes", deadline, move || {
            let _waits = worker_store.lock();
            vec![super::Outcome {
                ok: true,
                line: "answered".into(),
            }]
        });
        let waited = started.elapsed();

        assert_eq!(outcomes.len(), 1);
        assert!(outcomes[0].ok, "a busy store must not fail the health gate");
        assert!(outcomes[0].line.contains("Search indexes"));
        assert!(outcomes[0].line.contains("skipped (busy"));
        assert!(!outcomes[0].line.contains("answered"));
        assert!(
            waited < Duration::from_secs(5),
            "doctor waited {waited:?} on a held store"
        );
        drop(held);
    }

    #[test]
    fn an_index_check_that_answers_in_time_is_reported_as_is() {
        let outcomes =
            bounded_outcomes("Search indexes", std::time::Duration::from_secs(5), || {
                vec![super::Outcome {
                    ok: false,
                    line: "BM25 index FAILED".into(),
                }]
            });
        assert_eq!(outcomes.len(), 1);
        assert!(!outcomes[0].ok);
        assert_eq!(outcomes[0].line, "BM25 index FAILED");
    }
}