mati 0.1.2

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
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
//! `mati doctor` — diagnostic health aggregator for support and CI.
//!
//! Fans out to: enforcement wiring (reused from `mati check`), daemon
//! reachability, dirty-marker presence, drift check, and recent lifecycle
//! events. Exits 0 if everything is healthy; non-zero if any check is in a
//! fail state. Intended as the "paste this output" command for support
//! requests and as a CI gate for repository health.
//!
//! Drift checks require direct store access. When the daemon holds the
//! exclusive lock, those checks report "skipped" rather than failing —
//! the daemon's own boot-time auto-drain (see `mcp::server::serve`) is
//! already running the same logic on its side.

use std::io::{self, IsTerminal};
use std::path::Path;

use anyhow::Result;
use clap::Args;
use serde::Serialize;

use super::check::{self, CheckItem, CheckStatus};
use super::daemon::{daemon_result, mati_root_for, DaemonResult};

/// Doctor command arguments.
#[derive(Args)]
pub struct DoctorArgs {
    /// Output a structured JSON report on stdout (CI-friendly).
    #[arg(long)]
    pub json: bool,

    /// Show live daemon metrics (per-command counters and p50/p95/p99
    /// latencies) instead of the health-check report. Requires the daemon
    /// to be running — exits non-zero with a clear message otherwise.
    /// SLO-relevant view (ADR-010).
    #[arg(long)]
    pub internal: bool,
}

/// Run all doctor checks, render the report, exit 1 if any FAIL.
pub async fn run(args: DoctorArgs) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let root = mati_root_for(&cwd)?;

    // `--internal` is a separate view — live daemon metrics, not the health
    // checklist. We intentionally don't run any of the health checks here:
    // those produce side effects (peer credentials, store locks) and would
    // muddy the metric numbers we're about to print.
    if args.internal {
        return run_internal(&root, args.json).await;
    }

    let report = collect(&cwd, &root).await;

    if args.json {
        // JSON goes to stdout — keep stderr quiet so consumers can pipe.
        let json = serde_json::to_string_pretty(&report)?;
        println!("{json}");
    } else {
        let use_color = io::stderr().is_terminal();
        render_human(&report, use_color);
    }

    if report.summary.fail > 0 {
        std::process::exit(1);
    }
    Ok(())
}

/// Fetch the metrics snapshot from the live daemon and render it.
///
/// Returns Ok(()) on render success, even if the daemon is unreachable —
/// in that case a one-line "daemon not running" message is printed and the
/// process exits 1 (so CI wrappers don't silently succeed).
async fn run_internal(root: &Path, json: bool) -> Result<()> {
    let resp = daemon_result(root, "metrics", serde_json::json!({})).await;
    let data = match resp {
        DaemonResult::Ok(envelope) => envelope
            .get("data")
            .cloned()
            .unwrap_or(serde_json::Value::Null),
        DaemonResult::NotRunning | DaemonResult::StaleSocket => {
            eprintln!("daemon is not running — start it with `mati daemon start`");
            std::process::exit(1);
        }
        DaemonResult::Unresponsive => {
            eprintln!("daemon socket exists but is unresponsive");
            eprintln!("  hint: mati daemon stop && mati daemon start");
            std::process::exit(1);
        }
    };

    if json {
        // JSON envelope passes through unchanged so callers see the same shape
        // the daemon emits.
        println!("{}", serde_json::to_string_pretty(&data)?);
        return Ok(());
    }

    render_internal_human(&data);
    Ok(())
}

/// Render a metrics snapshot as a human-readable table on stdout.
///
/// Resilient to schema drift: if the daemon returns a shape this binary
/// doesn't understand, fall back to pretty-printing the raw JSON so the
/// user still sees something useful.
fn render_internal_human(data: &serde_json::Value) {
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, ContentArrangement, Table};

    if data.is_null() {
        println!("(daemon has no metrics yet — none recorded since startup)");
        return;
    }

    let uptime = data
        .get("uptime_secs")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let total = data
        .get("total_calls")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let errors = data
        .get("total_errors")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let err_pct = if total == 0 {
        0.0
    } else {
        (errors as f64 / total as f64) * 100.0
    };

    println!("daemon metrics");
    println!("  uptime         {}", format_duration(uptime));
    println!("  total calls    {total} (errors: {errors}, {err_pct:.2}%)");
    println!();

    let Some(commands) = data.get("commands").and_then(|v| v.as_array()) else {
        // Shape didn't match — dump raw so the user can still inspect.
        println!("(unknown metrics shape; raw payload:)");
        if let Ok(pretty) = serde_json::to_string_pretty(data) {
            println!("{pretty}");
        }
        return;
    };

    if commands.is_empty() {
        println!("(no commands recorded since startup)");
        return;
    }

    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_header(vec![
            Cell::new("command"),
            Cell::new("count"),
            Cell::new("err%"),
            Cell::new("mean"),
            Cell::new("p50"),
            Cell::new("p95"),
            Cell::new("p99"),
            Cell::new("max"),
        ]);

    for cmd in commands {
        let name = cmd.get("name").and_then(|v| v.as_str()).unwrap_or("?");
        let count = cmd.get("count").and_then(|v| v.as_u64()).unwrap_or(0);
        let errs = cmd.get("error_count").and_then(|v| v.as_u64()).unwrap_or(0);
        let cmd_err_pct = if count == 0 {
            0.0
        } else {
            (errs as f64 / count as f64) * 100.0
        };
        let mean = cmd.get("mean_us").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
        let p50 = cmd.get("p50_us").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
        let p95 = cmd.get("p95_us").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
        let p99 = cmd.get("p99_us").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
        let max = cmd.get("max_us").and_then(|v| v.as_u64()).unwrap_or(0) as u32;

        table.add_row(vec![
            Cell::new(name),
            Cell::new(count),
            Cell::new(format!("{cmd_err_pct:.1}%")),
            Cell::new(format_us(mean)),
            Cell::new(format_us(p50)),
            Cell::new(format_us(p95)),
            Cell::new(format_us(p99)),
            Cell::new(format_us(max)),
        ]);
    }

    println!("{table}");
}

/// Render a microsecond duration in the most readable unit.
fn format_us(us: u32) -> String {
    if us < 1_000 {
        format!("{us}µs")
    } else if us < 1_000_000 {
        format!("{:.1}ms", f64::from(us) / 1_000.0)
    } else {
        format!("{:.2}s", f64::from(us) / 1_000_000.0)
    }
}

/// Render a duration in seconds as a compact human-readable string.
fn format_duration(secs: u64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m {}s", secs / 60, secs % 60)
    } else if secs < 86400 {
        format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
    } else {
        format!("{}d {}h", secs / 86400, (secs % 86400) / 3600)
    }
}

// ── Report types ────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct Report {
    version: u32,
    root: String,
    checks: Vec<CheckResult>,
    lifecycle: Vec<LifecycleEntry>,
    summary: Summary,
    /// D3: per-tier accuracy of `/mati-enrich` extractions, computed from
    /// `analytics:extraction:*` records. `None` when the store wasn't
    /// reachable (e.g. uninitialized repo); empty stats when the store is
    /// reachable but no enrichment-tagged gotchas exist yet.
    #[serde(skip_serializing_if = "Option::is_none")]
    extraction: Option<mati_core::store::extraction::ExtractionStats>,
}

#[derive(Serialize)]
struct CheckResult {
    section: &'static str,
    name: &'static str,
    status: Status,
    detail: String,
    /// One-line remediation hint when status is warn/fail.
    #[serde(skip_serializing_if = "Option::is_none")]
    fix: Option<&'static str>,
}

#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Status {
    Pass,
    Warn,
    Fail,
    Info,
}

#[derive(Serialize)]
struct LifecycleEntry {
    ts: u64,
    pid: u32,
    event: String,
    detail: String,
}

#[derive(Serialize, Default)]
struct Summary {
    pass: u32,
    warn: u32,
    fail: u32,
    info: u32,
}

// ── Collection ──────────────────────────────────────────────────────────────

async fn collect(cwd: &Path, root: &Path) -> Report {
    let mut checks: Vec<CheckResult> = Vec::new();

    // Enforcement wiring — fold in `mati check`'s pipeline probes so `mati
    // doctor` answers the #1 silent-failure question: "is enforcement actually
    // wired into the agent?" (hook scripts present + executable, settings.json
    // registers them + the mati MCP server, mati on PATH, awk float math).
    // These are side-effect-free and never touch the store, so they remain
    // available even when the daemon holds the store lock (unlike the integrity
    // checks below). `enforcement_results` drops check's own `store` and
    // `daemon` items — doctor already reports those in its own sections.
    checks.extend(enforcement_results(check::run_silent(cwd).await));

    // Daemon ping.
    let daemon_state = daemon_result(root, "ping", serde_json::json!({})).await;
    match &daemon_state {
        DaemonResult::Ok(_) => checks.push(CheckResult {
            section: "daemon",
            name: "ping",
            status: Status::Pass,
            detail: "ok".into(),
            fix: None,
        }),
        DaemonResult::Unresponsive => checks.push(CheckResult {
            section: "daemon",
            name: "ping",
            status: Status::Fail,
            detail: "socket exists but daemon is not responding".into(),
            fix: Some("mati daemon stop && mati daemon start"),
        }),
        DaemonResult::StaleSocket => checks.push(CheckResult {
            section: "daemon",
            name: "ping",
            status: Status::Warn,
            detail: "stale socket detected and cleaned up".into(),
            fix: None,
        }),
        DaemonResult::NotRunning => checks.push(CheckResult {
            section: "daemon",
            name: "ping",
            status: Status::Info,
            detail: "not running (OK if no agent session is active)".into(),
            fix: None,
        }),
    }

    // Integrity: dirty_marker + drift.
    //
    // Schema-stability invariant: always exactly two `integrity` checks —
    // `dirty_marker` then `drift`, in that order — in every scenario, so
    // `mati doctor --json` (version 2) stays index-stable.
    //
    // Routed through `StoreProxy` (read-only), so — unlike the old
    // `Store::open` path that went `skipped` — these now report even while the
    // daemon holds the store lock: the proxy routes the reads through the
    // daemon socket. On an uninitialised repo the proxy refuses to open (it
    // won't scaffold state) and we emit Info rows pointing at `mati init`.
    match crate::cli::proxy::StoreProxy::open(cwd).await {
        Ok(proxy) => {
            if mati_core::store::repair::is_dirty(&proxy).await {
                let detail = match mati_core::store::repair::read_dirty_marker(&proxy).await {
                    Some(m) => format!("{} key(s) flagged: {}", m.affected_keys.len(), m.cause),
                    None => "flagged but cause not readable".to_string(),
                };
                checks.push(CheckResult {
                    section: "integrity",
                    name: "dirty_marker",
                    status: Status::Warn,
                    detail,
                    fix: Some("mati repair --fast"),
                });
            } else {
                checks.push(CheckResult {
                    section: "integrity",
                    name: "dirty_marker",
                    status: Status::Pass,
                    detail: "not set".into(),
                    fix: None,
                });
            }

            match mati_core::store::repair::check_gotcha_indexes(&proxy).await {
                Ok(report) => {
                    if report.has_drift() {
                        let detail = format!(
                            "missing_file={}, stale_file={}, missing_edge={}, stale_edge={}",
                            report.missing_file_links.len(),
                            report.stale_file_links.len(),
                            report.missing_edges.len(),
                            report.stale_edges.len(),
                        );
                        // `mati repair` reconciles derived indexes against
                        // existing records but cannot CREATE a missing
                        // file:<path> record — that needs a `mati init`
                        // re-index. So when the drift includes missing_file
                        // links, point at init first; otherwise plain repair
                        // fixes stale links and graph edges.
                        let fix = if !report.missing_file_links.is_empty() {
                            "mati init  (re-index missing files), then mati repair"
                        } else {
                            "mati repair"
                        };
                        checks.push(CheckResult {
                            section: "integrity",
                            name: "drift",
                            status: Status::Fail,
                            detail,
                            fix: Some(fix),
                        });
                    } else {
                        checks.push(CheckResult {
                            section: "integrity",
                            name: "drift",
                            status: Status::Pass,
                            detail: "no drift detected".into(),
                            fix: None,
                        });
                    }
                }
                Err(e) => checks.push(CheckResult {
                    section: "integrity",
                    name: "drift",
                    status: Status::Fail,
                    detail: format!("check error: {e}"),
                    fix: None,
                }),
            }

            let _ = proxy.close().await;
        }
        Err(_) => {
            // Proxy refuses to open when there's no store (and no daemon) — we
            // report state, never scaffold it. Same two rows, so the JSON
            // shape stays stable across scenarios.
            let no_store_detail =
                "skipped — no store initialized for this directory (run `mati init` to set up)";
            checks.push(CheckResult {
                section: "integrity",
                name: "dirty_marker",
                status: Status::Info,
                detail: no_store_detail.into(),
                fix: Some("mati init"),
            });
            checks.push(CheckResult {
                section: "integrity",
                name: "drift",
                status: Status::Info,
                detail: no_store_detail.into(),
                fix: Some("mati init"),
            });
        }
    }

    // Audit-chain integrity — routed through StoreProxy so it runs even while
    // the daemon holds the store lock (unlike dirty_marker/drift above). Reuses
    // the frozen-contract primitive `enforcement::verify_chain`.
    checks.push(collect_chain_check(cwd).await);
    checks.push(collect_freshness_check(cwd).await);

    // Network/telemetry posture — a compile-time attestation surfaced in-tool,
    // so an auditor sees mati's headline invariant by running `mati doctor`
    // rather than reading the CI workflow. Appended last so the `--json`
    // (version 2) array stays index-stable for existing consumers.
    checks.push(collect_network_attestation());

    // Lifecycle log tail.
    let lifecycle = read_lifecycle_tail(root, 5);

    // D3: extraction-quality stats. Routes through StoreProxy so it works
    // whether the daemon owns the lock (socket-routed scan_prefix) or the
    // store is direct-accessible. Default window: last 30 days — matches
    // `mati ls tombstoned --recent`'s default and the spec.
    let extraction = collect_extraction_stats(cwd).await;

    // Summary.
    let mut summary = Summary::default();
    for c in &checks {
        match c.status {
            Status::Pass => summary.pass += 1,
            Status::Warn => summary.warn += 1,
            Status::Fail => summary.fail += 1,
            Status::Info => summary.info += 1,
        }
    }

    Report {
        version: 2,
        root: root.display().to_string(),
        checks,
        lifecycle,
        summary,
        extraction,
    }
}

/// Surface the build's network/telemetry posture as a first-class doctor row.
///
/// This is the in-tool face of mati's headline invariant ("zero network calls,
/// never phones home"): an auditor running `mati doctor` sees the posture
/// directly instead of having to read the CI workflow. It is a *compile-time*
/// attestation, deliberately NOT a runtime probe — a probe would itself be a
/// network call, contradicting the very property being attested. The hard proof
/// lives in CI (the build-time dep-ban + the runtime syscall audit); this row
/// reports which build you are running.
///
/// Accurate via `cfg!(feature = "semantic")`: the default (enforcement) build
/// links no network/HTTP-client crate; the opt-in `semantic` feature is the one
/// documented exception — it fetches the embedding model via hf-hub on first
/// use — and is disclosed honestly rather than hidden.
fn collect_network_attestation() -> CheckResult {
    if cfg!(feature = "semantic") {
        CheckResult {
            section: "attestation",
            name: "network",
            status: Status::Info,
            detail: "semantic feature enabled — embedding-model fetch via hf-hub \
                     is linked (opt-in; downloads all-MiniLM-L6-v2 on first use). \
                     Enforcement decisions remain local and make no outbound \
                     connection."
                .into(),
            fix: None,
        }
    } else {
        CheckResult {
            section: "attestation",
            name: "network",
            status: Status::Pass,
            detail: "no network/HTTP-client dependency linked in this build; the \
                     enforcement path makes no outbound connection (verified in \
                     CI: build-time dep-ban + runtime syscall audit). mati never \
                     phones home."
                .into(),
            fix: None,
        }
    }
}

/// Map `mati check`'s enforcement-pipeline probes into doctor `CheckResult`s.
///
/// Drops the `store` and `daemon` items — doctor already reports those via its
/// own `integrity` and `daemon` sections, so folding them in would duplicate
/// rows. The remaining probes (git repo, mati-on-PATH, awk float math, hook
/// scripts, settings.json wiring) answer the question doctor couldn't before:
/// "is enforcement actually wired into the agent?" None of them open the store,
/// so they stay available even when the daemon holds the lock. Names are
/// normalized to snake_case to match doctor's existing convention (`ping`,
/// `dirty_marker`, `drift`).
fn enforcement_results(items: Vec<CheckItem>) -> Vec<CheckResult> {
    items
        .into_iter()
        .filter_map(|item| {
            let name: &'static str = match item.label {
                "git repo" => "git_repo",
                "mati in PATH" => "mati_on_path",
                "awk float math" => "awk_float_math",
                "agent host" => "agent_host",
                "claude hooks" => "claude_hooks",
                "claude config" => "claude_config",
                "codex hooks" => "codex_hooks",
                "codex config" => "codex_config",
                // `store` and `daemon` are already covered by doctor's own
                // integrity/daemon sections — skip to avoid duplicate rows.
                _ => return None,
            };
            let (status, detail) = match item.status {
                CheckStatus::Pass(extra) => {
                    (Status::Pass, extra.unwrap_or_else(|| "ok".to_string()))
                }
                CheckStatus::Warn(msg) => (Status::Warn, msg),
                CheckStatus::Fail(msg) => (Status::Fail, msg),
            };
            // `detail` already carries the specifics (e.g. "missing:
            // pre-read.sh"); `fix` is a static, name-keyed one-liner.
            let fix = if matches!(status, Status::Pass) {
                None
            } else {
                Some(match name {
                    "git_repo" => "run mati from inside a git repository",
                    "mati_on_path" => "ensure the mati binary is on PATH",
                    "awk_float_math" => "install awk/gawk and ensure it is on PATH",
                    "agent_host" => "mati hooks --claude  (or --codex)",
                    "codex_hooks" | "codex_config" => "mati hooks --codex",
                    // claude_hooks / claude_config
                    _ => "mati hooks --claude",
                })
            };
            Some(CheckResult {
                section: "enforcement",
                name,
                status,
                detail,
                fix,
            })
        })
        .collect()
}

/// Verify the enforcement audit chain. Routed through `StoreProxy`, so unlike
/// the `Store::open`-based dirty_marker/drift checks it runs even while the
/// daemon holds the store lock. Reuses `enforcement::verify_chain` — the single
/// source of truth for the frozen hash contract (same primitive as
/// `mati verify-chain`). Read-only, zero-network.
async fn collect_chain_check(cwd: &Path) -> CheckResult {
    let proxy = match crate::cli::proxy::StoreProxy::open(cwd).await {
        Ok(p) => p,
        Err(_) => {
            return CheckResult {
                section: "integrity",
                name: "chain",
                status: Status::Info,
                detail: "skipped — no store initialized for this directory".to_string(),
                fix: None,
            };
        }
    };
    let events = proxy
        .scan_enforcement_events(0, u64::MAX)
        .await
        .unwrap_or_default();
    let _ = proxy.close().await;

    let total = events.len();
    let result = mati_core::store::enforcement::verify_chain(&events);
    if result.is_valid() {
        CheckResult {
            section: "integrity",
            name: "chain",
            status: Status::Pass,
            detail: format!("intact — {total} event(s), every hash verified"),
            fix: None,
        }
    } else {
        CheckResult {
            section: "integrity",
            name: "chain",
            status: Status::Fail,
            detail: format!(
                "BROKEN — {} tampered, {} linkage break(s), {} unknown-schema of {total} event(s)",
                result.tampered_events, result.linkage_breaks, result.unknown_schema
            ),
            fix: Some("mati verify-chain --verbose"),
        }
    }
}

/// Knowledge freshness — how many records have gone stale relative to the code.
/// Reads the write-seq-validated stale cache via StoreProxy (cheap; no full
/// scan). `Info` when the cache is cold (run `mati stale`); `Warn` when records
/// are stale — advisory, since stale knowledge degrades enforcement quality but
/// doesn't break it, so this never fails the CI gate.
async fn collect_freshness_check(cwd: &Path) -> CheckResult {
    let proxy = match crate::cli::proxy::StoreProxy::open(cwd).await {
        Ok(p) => p,
        Err(_) => {
            return CheckResult {
                section: "knowledge",
                name: "freshness",
                status: Status::Info,
                detail: "skipped — no store initialized for this directory".to_string(),
                fix: None,
            };
        }
    };
    let summary = crate::cli::stale::cached_stale_summary(&proxy).await;
    let _ = proxy.close().await;
    match summary {
        None => CheckResult {
            section: "knowledge",
            name: "freshness",
            status: Status::Info,
            detail: "unknown — run `mati stale` for a current count".to_string(),
            fix: None,
        },
        Some(s) if s.total == 0 => CheckResult {
            section: "knowledge",
            name: "freshness",
            status: Status::Pass,
            detail: "no stale records".to_string(),
            fix: None,
        },
        Some(s) => CheckResult {
            section: "knowledge",
            name: "freshness",
            status: Status::Warn,
            detail: format!(
                "{} stale record(s) ({} stale, {} liability, {} tombstone)",
                s.total, s.stale, s.liability, s.tombstone
            ),
            fix: Some("mati stale  (then mati init / mati reparse to refresh)"),
        },
    }
}

/// Read all `analytics:extraction:*` records via StoreProxy and aggregate.
/// Returns `None` when the proxy can't be opened (uninitialized repo); an
/// empty `ExtractionStats` (total=0) is a valid Some(stats) — means "no
/// enrichment-tagged gotchas have been written yet."
///
/// Window: last 30 days, matching `mati ls tombstoned --recent`'s default
/// and ENRICH_QUALITY.md Section 8.
async fn collect_extraction_stats(
    cwd: &Path,
) -> Option<mati_core::store::extraction::ExtractionStats> {
    use mati_core::store::extraction::{aggregate_stats, ExtractionRecord, EXTRACTION_PREFIX};

    let proxy = match crate::cli::proxy::StoreProxy::open(cwd).await {
        Ok(p) => p,
        Err(_) => return None,
    };
    let records = proxy
        .scan_prefix(EXTRACTION_PREFIX)
        .await
        .unwrap_or_default();
    let _ = proxy.close().await;

    let extractions: Vec<ExtractionRecord> = records
        .into_iter()
        .filter_map(|r| r.payload.and_then(|p| serde_json::from_value(p).ok()))
        .collect();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let since = now.saturating_sub(30 * 86_400);
    Some(aggregate_stats(&extractions, since, now))
}

fn read_lifecycle_tail(root: &Path, n: usize) -> Vec<LifecycleEntry> {
    let path = root.join("lifecycle.log");
    let contents = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    let lines: Vec<&str> = contents.lines().collect();
    let start = lines.len().saturating_sub(n);
    lines[start..]
        .iter()
        .filter_map(|line| {
            let cols: Vec<&str> = line.splitn(4, '\t').collect();
            if cols.len() != 4 {
                return None;
            }
            Some(LifecycleEntry {
                ts: cols[0].parse().unwrap_or(0),
                pid: cols[1].parse().unwrap_or(0),
                event: cols[2].to_string(),
                detail: cols[3].to_string(),
            })
        })
        .collect()
}

// ── Human renderer ──────────────────────────────────────────────────────────

fn render_human(report: &Report, use_color: bool) {
    println!();
    println!("mati doctor — {}", report.root);
    println!();

    let mut current_section: &str = "";
    for c in &report.checks {
        if c.section != current_section {
            if !current_section.is_empty() {
                println!();
            }
            let title = match c.section {
                "enforcement" => "Enforcement",
                "daemon" => "Daemon",
                "integrity" => "Integrity",
                "knowledge" => "Knowledge",
                "attestation" => "Attestation",
                other => other,
            };
            println!("{title}");
            current_section = c.section;
        }
        let symbol = symbol_for(c.status, use_color);
        println!("  {:18} {}  {}", c.name, symbol, c.detail);
        if let Some(fix) = c.fix {
            println!("                       fix: {fix}");
        }
    }

    println!();
    println!("Lifecycle (last {} events)", report.lifecycle.len());
    if report.lifecycle.is_empty() {
        println!("  (no lifecycle.log yet — log fills as the daemon runs)");
    } else {
        for e in &report.lifecycle {
            println!(
                "  {:<14}  pid={:<6} {:<18} {}",
                relative_ts(e.ts),
                e.pid,
                e.event,
                e.detail
            );
        }
    }

    if let Some(extraction) = &report.extraction {
        render_extraction_section(extraction);
    }

    println!();
    let s = &report.summary;
    if s.fail > 0 {
        println!(
            "Result: {} fail, {} warn, {} pass — see fixes above",
            s.fail, s.warn, s.pass
        );
    } else if s.warn > 0 {
        println!("Result: clean with {} warn ({} pass)", s.warn, s.pass);
    } else {
        println!("Result: all checks passed ({} pass)", s.pass);
    }
}

/// Render the D3 extraction-quality section. Skipped entirely when no
/// extractions have been recorded (`total == 0`) — keeps the doctor
/// output clean on fresh installs.
fn render_extraction_section(s: &mati_core::store::extraction::ExtractionStats) {
    if s.total == 0 {
        return;
    }
    println!();
    println!("Extraction quality (last 30d, /mati-enrich pipeline)");
    println!("  total           {:>4}", s.total);
    println!(
        "  confirmed       {:>4}  ({})",
        s.confirmed,
        rate_label(s.confirmed, s.total)
    );
    println!(
        "  tombstoned      {:>4}  ({})",
        s.tombstoned,
        rate_label(s.tombstoned, s.total)
    );
    println!("  pending         {:>4}", s.pending);
    if s.expired > 0 {
        println!("  expired (>90d)  {:>4}", s.expired);
    }

    // Per-tier breakdown — only render tiers with non-zero data.
    let tiers = [
        ("fast    ", &s.per_tier.fast),
        ("standard", &s.per_tier.standard),
        ("deep    ", &s.per_tier.deep),
        ("unknown ", &s.per_tier.unknown),
    ];
    let any_tier_used = tiers.iter().any(|(_, t)| t.total > 0);
    if any_tier_used {
        println!();
        println!("  Per-tier:");
        for (label, tier) in &tiers {
            if tier.total == 0 {
                continue;
            }
            let rate = tier.confirmed_rate().map_or_else(
                || "".to_string(),
                |r| format!("{:>3.0}% confirmed", r * 100.0),
            );
            println!("    {label}  {:>3} extractions, {rate}", tier.total);
        }
    }

    // SOTA-δ: per-config A/B breakdown. Hidden when only one config has
    // data (the comparison is meaningless until at least two configs
    // have extractions). Useful for proving the SOTA pipeline (`ast+*`)
    // outperforms the legacy LLM-driven scan (`llm+*`).
    let active_configs: Vec<_> = s.per_config.iter().filter(|(_, t)| t.total > 0).collect();
    if active_configs.len() >= 2 {
        println!();
        println!("  Per-config (A/B):");
        // Render in stable order: BTreeMap iteration is alphabetical
        // which is fine — `ast+*` sorts before `llm+*`.
        for (label, tier) in &active_configs {
            let rate = tier.confirmed_rate().map_or_else(
                || "".to_string(),
                |r| format!("{:>3.0}% confirmed", r * 100.0),
            );
            println!("    {label:>11}  {:>3} extractions, {rate}", tier.total);
        }
    }
}

fn rate_label(n: u64, total: u64) -> String {
    (n * 100)
        .checked_div(total)
        .map(|pct| format!("{pct}%"))
        .unwrap_or_else(|| "0%".to_string())
}

fn symbol_for(status: Status, use_color: bool) -> String {
    let s = match status {
        Status::Pass => "ok",
        Status::Warn => "WARN",
        Status::Fail => "FAIL",
        Status::Info => "",
    };
    if !use_color {
        return s.to_string();
    }
    match status {
        Status::Pass => format!("\x1b[32m{s}\x1b[0m"),
        Status::Warn => format!("\x1b[33m{s}\x1b[0m"),
        Status::Fail => format!("\x1b[31m{s}\x1b[0m"),
        Status::Info => format!("\x1b[90m{s}\x1b[0m"),
    }
}

fn relative_ts(ts: u64) -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let ago = now.saturating_sub(ts);
    if ago == 0 {
        "just now".into()
    } else if ago < 60 {
        format!("{ago}s ago")
    } else if ago < 3600 {
        format!("{}m ago", ago / 60)
    } else if ago < 86400 {
        format!("{}h ago", ago / 3600)
    } else {
        format!("{}d ago", ago / 86400)
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    #[test]
    fn read_lifecycle_tail_parses_well_formed_lines() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("lifecycle.log"),
            "100\t111\tserve_start\tpid=111 owner=mcp\n\
             200\t111\tserve_shutdown\tclean\n",
        )
        .unwrap();
        let entries = read_lifecycle_tail(dir.path(), 5);
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].ts, 100);
        assert_eq!(entries[0].event, "serve_start");
        assert_eq!(entries[1].detail, "clean");
    }

    #[test]
    fn read_lifecycle_tail_returns_last_n_only() {
        let dir = tempfile::tempdir().unwrap();
        let body: String = (0..10)
            .map(|i| format!("{i}\t{i}\tevent{i}\tdetail{i}\n"))
            .collect();
        std::fs::write(dir.path().join("lifecycle.log"), body).unwrap();
        let entries = read_lifecycle_tail(dir.path(), 3);
        assert_eq!(entries.len(), 3);
        // Last three: 7, 8, 9
        assert_eq!(entries[0].ts, 7);
        assert_eq!(entries[2].ts, 9);
    }

    #[test]
    fn read_lifecycle_tail_skips_malformed_lines() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("lifecycle.log"),
            "100\t111\tserve_start\tok\n\
             not\ta\tvalid\n\
             200\t111\tserve_shutdown\tclean\n",
        )
        .unwrap();
        let entries = read_lifecycle_tail(dir.path(), 5);
        // Malformed line has only 3 tab-separated fields → skipped.
        assert_eq!(entries.len(), 2);
    }

    #[test]
    fn read_lifecycle_tail_returns_empty_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        let entries = read_lifecycle_tail(dir.path(), 5);
        assert!(entries.is_empty());
    }

    /// End-to-end round trip: events written by the canonical writer
    /// (`mcp::metadata::record_lifecycle_event`) must parse back through the
    /// doctor reader without losing fields. The other reader-side tests use
    /// hand-rolled fixture strings — if the writer's column layout, separator,
    /// or escaping ever drifts, those tests would still pass while doctor's
    /// "Lifecycle (last N events)" panel silently goes blank in the field.
    /// Pass 24 caught this exact pattern in `fail_open.log`; this test guards
    /// the lifecycle.log surface against the same class of regression.
    #[test]
    fn lifecycle_log_round_trip_writer_reader() {
        use mati_core::mcp::metadata::record_lifecycle_event;
        let dir = tempfile::tempdir().unwrap();
        // Three events through the real writer — including a payload with
        // tabs/newlines so we cover the writer's escaping path.
        record_lifecycle_event(dir.path(), "serve_start", "owner=mcp");
        record_lifecycle_event(dir.path(), "panic", "boom\twith\ttabs\nand newline");
        record_lifecycle_event(dir.path(), "serve_shutdown", "reason=signal");

        let entries = read_lifecycle_tail(dir.path(), 5);
        assert_eq!(
            entries.len(),
            3,
            "doctor reader must parse all 3 writer-emitted lines, got {}",
            entries.len()
        );
        assert_eq!(entries[0].event, "serve_start");
        assert_eq!(entries[0].detail, "owner=mcp");
        assert_eq!(entries[1].event, "panic");
        // Writer replaces tabs/newlines with spaces so each event stays one line.
        assert!(
            !entries[1].detail.contains('\t') && !entries[1].detail.contains('\n'),
            "writer must scrub tabs/newlines; reader saw: {:?}",
            entries[1].detail
        );
        assert!(
            entries[1].detail.contains("boom") && entries[1].detail.contains("tabs"),
            "writer must preserve detail content (modulo separator scrubbing); got {:?}",
            entries[1].detail
        );
        assert_eq!(entries[2].event, "serve_shutdown");
        assert_eq!(entries[2].detail, "reason=signal");
        // Timestamps are real Unix seconds — must be non-zero, monotonic.
        assert!(entries[0].ts > 0, "writer must emit a real Unix timestamp");
        assert!(
            entries[0].ts <= entries[2].ts,
            "timestamps must be monotonic"
        );
        // PID must round-trip as the current process id.
        let pid = std::process::id();
        for e in &entries {
            assert_eq!(e.pid, pid, "writer→reader pid round-trip must be stable");
        }
    }

    /// Schema-stability invariant for `mati doctor --json`:
    /// every scenario (no-daemon-no-store, no-daemon-with-store,
    /// daemon-running, daemon-unresponsive, store-open-failed) must emit
    /// the five `enforcement/*` probes first, then exactly one `daemon/ping`
    /// check followed by `integrity/dirty_marker` then `integrity/drift`, in
    /// that order. CI consumers parse the report by name and by index, and a
    /// `version: 2` schema must keep both stable.
    ///
    /// This is a hermetic test: it drives `collect()` against a tempdir
    /// with no daemon and no `knowledge.db`, exercising the no-store
    /// branch. The other branches are exercised by the smoke tests in
    /// audit pass 18; their schema parity is guaranteed by code review of
    /// the single match arm in `collect()` that always pushes
    /// `dirty_marker` before `drift`.
    #[tokio::test]
    async fn doctor_json_shape_is_stable_across_scenarios() {
        let dir = tempfile::tempdir().unwrap();
        // No `knowledge.db` here — exercises the "no store" branch.
        let report = collect(dir.path(), dir.path()).await;
        let names: Vec<(&str, &str)> = report.checks.iter().map(|c| (c.section, c.name)).collect();
        assert_eq!(
            names,
            vec![
                ("enforcement", "git_repo"),
                ("enforcement", "mati_on_path"),
                ("enforcement", "awk_float_math"),
                ("enforcement", "agent_host"),
                ("enforcement", "claude_hooks"),
                ("enforcement", "claude_config"),
                ("enforcement", "codex_hooks"),
                ("enforcement", "codex_config"),
                ("daemon", "ping"),
                ("integrity", "dirty_marker"),
                ("integrity", "drift"),
                ("integrity", "chain"),
                ("knowledge", "freshness"),
                ("attestation", "network"),
            ],
            "doctor JSON check sequence must be the enforcement probes \
             (git_repo → mati_on_path → awk_float_math → agent_host → \
             claude_hooks → claude_config → codex_hooks → codex_config) then \
             ping → dirty_marker → drift → chain → freshness → network \
             (the network attestation is appended last so the --json array \
             stays index-stable for existing consumers)"
        );
        assert_eq!(report.version, 2);
    }
}