openlatch-client 0.5.4

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
//! The single diagnostic model shared by `init`, `doctor`, `status` and the
//! per-subsystem status commands.
//!
//! Before this module every command answered "is OpenLatch healthy?" its own
//! way, and the answers disagreed. `doctor` reported a disabled model relay
//! as a **pass** while `status` printed it as `disabled` and `model-relay status`
//! called the same state `down` and suggested a command that could not fix it.
//! One model, one renderer, one exit code.
//!
//! ## The contract
//!
//! - **P1** Green means *enabled AND proven working*. Nothing else is green.
//! - **P2** Deliberately disabled is a warning, never silence.
//! - **P3** Enabled but not working is a failure, even when the failure is
//!   tolerated at runtime.
//! - **P6** The same [`Section`]s are always reported, in the same order, even
//!   when empty — "I don't know" is a state, not an omission.
//! - **P7** Everything in the human rendering exists in the JSON rendering.
//!
//! ## Anti-cascade
//!
//! A failure does not propagate. When the daemon is dead, the sections that
//! depend on it report [`State::Unknown`] — a *warning* naming the blocker —
//! rather than each inventing a failure of its own. One outage, one cross.

use crate::cli::color;
use crate::cli::output::{OutputConfig, OutputFormat};

/// Display width of the field [`State::mark`] always occupies, separator
/// included.
const MARK_WIDTH: usize = 5;

/// Width of the section-title cell in the grouped rendering. The longest title
/// is `Environment` / `Persistence`, both eleven.
const TITLE_WIDTH: usize = 11;

/// Indent for a check's continuation lines — detail, source, remedy — in the
/// single-section view.
///
/// Two spaces of indent plus [`MARK_WIDTH`], so a continuation starts exactly
/// under the headline it belongs to rather than a space further in.
const CONTINUATION: &str = "       ";

/// Pad `text` out to `width` display columns, told its visible width.
///
/// `format!("{text:<width$}")` counts bytes, and a dimmed cell carries eight of
/// them before the first visible character. That aligns the columns in no-color
/// mode — the mode a test runs in — and leaves them ragged for everyone
/// actually reading the output.
fn pad_to(text: &str, visible: usize, width: usize) -> String {
    format!("{text}{}", " ".repeat(width.saturating_sub(visible)))
}

/// The agent cell that precedes a check's headline, `width` columns wide.
///
/// A host-wide check inside an otherwise per-agent section is padded rather
/// than named, so the headlines stay in one column and the absence of a name is
/// itself the statement that the finding belongs to no single agent.
fn agent_cell(check: &Check, width: usize, color_enabled: bool) -> String {
    if width == 0 {
        return String::new();
    }
    match check.agent {
        Some(agent) => pad_to(
            &color::dim(agent, color_enabled),
            agent.chars().count(),
            width,
        ),
        None => " ".repeat(width),
    }
}

/// Everything requested is running, but at least one subsystem is switched off
/// or not at full capability.
///
/// **Why 7 and not 2.** The exit-code table in `.claude/rules/error-handling.md`
/// is a public contract, and it already spends 2 on usage errors — which clap
/// produces itself for a mistyped flag, before any of our code runs. Reusing it
/// would leave a script unable to tell `openlatch doctor --bogus` from
/// `openlatch doctor` on a host with the model relay switched off. 3
/// (not found), 4 (permission), 5 (conflict — reserved for `OL-1501`, which
/// `systemd`'s `RestartPreventExitStatus=5` keys off) and 6 (`update`'s
/// daemon-unreachable) are likewise taken. 7 is the first free number.
///
/// It is deliberately NOT 0: `openlatch doctor && deploy` succeeding on a host
/// where nothing is captured or enforced is the failure mode this whole
/// contract exists to close.
pub const EXIT_DEGRADED: i32 = 7;

/// Process-level verdict recorded by a diagnostic rendering, read by `main`
/// when the command itself returned `Ok`.
///
/// Exists because a command can succeed at *running* and still need to report
/// that the machine is degraded: `doctor` finding a disabled model relay is not an
/// `OlError` — printing "Error:" in front of it would be a lie — but it must
/// not exit 0 either, or `openlatch doctor && deploy` ships with enforcement
/// off. `update` solves the same problem by calling `process::exit` directly,
/// which silently skips the `command_invoked` telemetry; this keeps the normal
/// return path intact.
mod verdict {
    use std::sync::atomic::{AtomicI32, Ordering};

    static PENDING: AtomicI32 = AtomicI32::new(0);

    /// Severity of an exit status, since the numbers do not order themselves:
    /// `1` (failure) outranks `7` (degraded), which outranks `0`.
    fn severity(code: i32) -> u8 {
        match code {
            0 => 0,
            super::EXIT_DEGRADED => 1,
            _ => 2,
        }
    }

    /// Record the exit status a successful command wants the process to carry.
    /// Worst wins, so a later benign rendering cannot clear an earlier failure.
    pub fn record(code: i32) {
        let mut current = PENDING.load(Ordering::SeqCst);
        while severity(code) > severity(current) {
            match PENDING.compare_exchange(current, code, Ordering::SeqCst, Ordering::SeqCst) {
                Ok(_) => return,
                Err(observed) => current = observed,
            }
        }
    }

    /// The recorded status, or 0 when nothing was recorded.
    pub fn pending() -> i32 {
        PENDING.load(Ordering::SeqCst)
    }

    /// Reset — tests only; the process runs one command.
    #[cfg(test)]
    pub fn reset() {
        PENDING.store(0, Ordering::SeqCst);
    }
}

#[cfg(test)]
pub use verdict::reset as reset_exit_code;
pub use verdict::{pending as pending_exit_code, record as record_exit_code};

// ---------------------------------------------------------------------------
// Groups
// ---------------------------------------------------------------------------

/// The three questions a reader asks, in the order they ask them.
///
/// Eleven flat sections is a bad ratio — eleven headings for twenty lines of
/// content, and the marks scattered across as many columns. Grouping puts every
/// section on one scan column and lets the green ones collapse to a line, so
/// what is left on screen is mostly the things that need attention.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Group {
    /// Is it running, and will it keep running?
    Runtime,
    /// Is it seeing everything, and is it enforcing?
    Coverage,
    /// Is any of what it sees leaving this machine?
    Platform,
}

impl Group {
    pub const ALL: [Group; 3] = [Group::Runtime, Group::Coverage, Group::Platform];

    pub fn title(self) -> &'static str {
        match self {
            Group::Runtime => "Runtime",
            Group::Coverage => "Coverage",
            Group::Platform => "Platform",
        }
    }

    pub fn key(self) -> &'static str {
        match self {
            Group::Runtime => "runtime",
            Group::Coverage => "coverage",
            Group::Platform => "platform",
        }
    }
}

// ---------------------------------------------------------------------------
// Sections
// ---------------------------------------------------------------------------

/// A subsystem of the install, ordered from most fundamental to most
/// peripheral. A section whose upstream dependency failed reports
/// [`State::Unknown`] rather than a failure of its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Section {
    /// Agent detection, `~/.claude`, `~/.openlatch`, config readability, build.
    Environment,
    /// The daemon process: alive, bound, healthy, and serving the installed
    /// version.
    Daemon,
    /// `settings.json` entries, the staged hook binary, token and port match.
    Hooks,
    /// The model-relay listener and the agent's `ANTHROPIC_BASE_URL`.
    ModelRelay,
    /// OS-native supervision (launchd / systemd-user / Task Scheduler).
    Persistence,
    /// How this host reaches the platform: direct, or through a proxy. Owns the
    /// first hop, so "cannot reach the proxy" and "cannot reach the platform"
    /// are two rows rather than one collapsed `Cloud` failure.
    Connection,
    /// Forwarding to the OpenLatch platform. Never [`State::Off`] — the
    /// forwarding is constitutive of the product and cannot be switched off.
    Cloud,
    /// Local policy bundle: present, fresh, enforcing.
    Policy,
    /// The configuration plane monitor.
    Inventory,
    /// Anonymous usage telemetry consent.
    Telemetry,
    /// Drift between the installed binary and the one being served.
    Update,
    /// HMAC key, tamper log, hook markers.
    Integrity,
}

impl Section {
    /// Every section, in reporting order. Rendering walks this, not the order
    /// checks happened to be pushed in.
    pub const ALL: [Section; 12] = [
        // Runtime
        Section::Environment,
        Section::Daemon,
        Section::Persistence,
        Section::Update,
        // Coverage
        Section::Hooks,
        Section::ModelRelay,
        Section::Policy,
        Section::Inventory,
        Section::Integrity,
        // Platform — Connection first: it is the hop Cloud travels over, so a
        // reader meets the route before the thing at the end of it.
        Section::Connection,
        Section::Cloud,
        Section::Telemetry,
    ];

    /// Which question this section answers.
    ///
    /// `Policy` sits in `Coverage` rather than `Platform` on purpose: the
    /// bundle arrives from the cloud, but the evaluation is local and
    /// authoritative — it is about what this host enforces, not about what
    /// leaves it. `Inventory` is local observation for the same reason, and
    /// `Update` is in `Runtime` because version drift answers "which binary is
    /// actually running".
    pub fn group(self) -> Group {
        match self {
            Section::Environment | Section::Daemon | Section::Persistence | Section::Update => {
                Group::Runtime
            }
            Section::Hooks
            | Section::ModelRelay
            | Section::Policy
            | Section::Inventory
            | Section::Integrity => Group::Coverage,
            Section::Connection | Section::Cloud | Section::Telemetry => Group::Platform,
        }
    }

    /// Every section in a group, in reading order.
    pub fn of_group(group: Group) -> impl Iterator<Item = Section> {
        Section::ALL.into_iter().filter(move |s| s.group() == group)
    }

    /// Human-facing section title.
    pub fn title(self) -> &'static str {
        match self {
            Section::Environment => "Environment",
            Section::Daemon => "Daemon",
            Section::Hooks => "Hooks",
            Section::ModelRelay => "Model Relay",
            Section::Persistence => "Persistence",
            Section::Connection => "Connection",
            Section::Cloud => "Cloud",
            Section::Policy => "Policy",
            Section::Inventory => "Inventory",
            Section::Telemetry => "Telemetry",
            Section::Update => "Update",
            Section::Integrity => "Integrity",
        }
    }

    /// Stable machine key for the JSON rendering.
    pub fn key(self) -> &'static str {
        match self {
            Section::Environment => "environment",
            Section::Daemon => "daemon",
            Section::Hooks => "hooks",
            Section::ModelRelay => "model_relay",
            Section::Persistence => "persistence",
            Section::Connection => "connection",
            Section::Cloud => "cloud",
            Section::Policy => "policy",
            Section::Inventory => "inventory",
            Section::Telemetry => "telemetry",
            Section::Update => "update",
            Section::Integrity => "integrity",
        }
    }
}

// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------

/// What one check found.
///
/// The mapping to marks and exit codes is normative — see [`State::mark`] and
/// [`Report::exit_code`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    /// Enabled and proven working. The only green state.
    Ok,
    /// Deliberately switched off — config, flag, or an explicit user opt-out.
    /// A warning: the user is entitled to this state, and entitled to be
    /// reminded they are in it.
    Off,
    /// Enabled, working, losing nothing — but not at full capability.
    Degraded,
    /// Enabled, verification still in flight. Ask again shortly.
    Pending,
    /// Enabled and not working.
    Failed,
    /// Indeterminable because the named section failed. Warns, never fails —
    /// this is what keeps one outage from printing eight crosses.
    Unknown(Section),
    /// Absent from this build or irrelevant on this platform. Not a problem,
    /// and not a success either.
    NotApplicable,
}

impl State {
    /// Severity for "worst wins" aggregation. Not a public ordering: it exists
    /// only to fold a section's checks into one state.
    fn severity(self) -> u8 {
        match self {
            State::NotApplicable => 0,
            State::Ok => 1,
            State::Pending => 2,
            State::Off => 3,
            State::Degraded => 4,
            State::Unknown(_) => 5,
            State::Failed => 6,
        }
    }

    /// Stable machine key for the JSON rendering.
    pub fn key(self) -> &'static str {
        match self {
            State::Ok => "ok",
            State::Off => "off",
            State::Degraded => "degraded",
            State::Pending => "pending",
            State::Failed => "failed",
            State::Unknown(_) => "unknown",
            State::NotApplicable => "not_applicable",
        }
    }

    /// Does this state count as a failure for the exit code?
    pub fn is_failure(self) -> bool {
        self == State::Failed
    }

    /// Does this state count as a warning for the exit code?
    pub fn is_warning(self) -> bool {
        matches!(
            self,
            State::Off | State::Degraded | State::Pending | State::Unknown(_)
        )
    }

    /// Must this state carry a code and a remedy?
    ///
    /// Everything the operator is expected to act on must say what to do. The
    /// rule is enforced by [`Check::validate`] and asserted in tests, not left
    /// to review.
    pub fn requires_remedy(self) -> bool {
        self.is_failure() || self.is_warning()
    }

    /// The mark plus its separator, as a fixed five-column field so section
    /// blocks line up in both color and no-color mode.
    ///
    /// The separator is part of the field rather than the format string
    /// because the no-color labels are not all the same length: `WARN` fills
    /// four columns and `OK` two, so a single space in the caller renders
    /// `WARNDisabled` next to `OK  Running`.
    pub fn mark(self, color_enabled: bool) -> String {
        if color_enabled {
            let glyph = match self {
                State::Ok => color::checkmark(true).to_string(),
                State::Failed => color::cross(true).to_string(),
                State::NotApplicable => color::dim("\u{00b7}", true),
                _ => color::warning_mark(true).to_string(),
            };
            format!("{glyph}    ")
        } else {
            let label = match self {
                State::Ok => "OK   ",
                State::Failed => "ERR  ",
                State::NotApplicable => "--   ",
                _ => "WARN ",
            };
            label.to_string()
        }
    }
}

// ---------------------------------------------------------------------------
// Check
// ---------------------------------------------------------------------------

/// One diagnostic finding, belonging to exactly one [`Section`].
///
/// A section holds one or more of these; its state is the worst among them.
#[derive(Debug, Clone)]
pub struct Check {
    pub section: Section,
    pub state: State,
    /// One factual line. No remediation, no hedging.
    pub headline: String,
    /// Extra context lines, rendered indented under the headline.
    pub detail: Vec<String>,
    /// `OL-XXXX`. Required whenever [`State::requires_remedy`].
    pub code: Option<&'static str>,
    /// An exact command or edit. Required whenever [`State::requires_remedy`].
    pub remedy: Option<String>,
    /// Where the state came from — `config.toml:59`, `--no-persistence`,
    /// `keychain`. This is the field that turns "the model relay is off" into
    /// "the model relay is off *because of this line in this file*".
    pub source: Option<String>,
    /// Which agent this check is about — the CloudEvents `source` wire value
    /// (`"claude-code"`). `None` for a host-wide check that belongs to no
    /// single agent. Serialized only when set: absent, never `null`.
    pub agent: Option<&'static str>,
    /// Whether `headline` is still the one [`Check::unknown`] generated, which
    /// already names the blocker. Decides whether the block rendering adds the
    /// separate `waiting on :` line — without it, the default headline and that
    /// line said the same thing twice, one under the other.
    generated_headline: bool,
}

impl Check {
    fn new(section: Section, state: State, headline: impl Into<String>) -> Self {
        Self {
            section,
            state,
            headline: headline.into(),
            detail: Vec::new(),
            code: None,
            remedy: None,
            source: None,
            agent: None,
            generated_headline: false,
        }
    }

    /// Enabled and proven working.
    pub fn ok(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Ok, headline)
    }

    /// Deliberately switched off.
    pub fn off(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Off, headline)
    }

    /// Working but not at full capability.
    pub fn degraded(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Degraded, headline)
    }

    /// Verification still in flight.
    pub fn pending(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Pending, headline)
    }

    /// Enabled and not working.
    pub fn failed(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::Failed, headline)
    }

    /// Indeterminable because `blocker` failed. Carries its own code and
    /// remedy, so it satisfies the remedy rule without every call site
    /// repeating the same two strings.
    pub fn unknown(section: Section, blocker: Section) -> Self {
        Self {
            section,
            state: State::Unknown(blocker),
            headline: format!("Cannot check — waiting on {}", blocker.title()),
            detail: Vec::new(),
            code: Some(crate::error::ERR_SUBSYSTEM_DEGRADED),
            remedy: Some(format!(
                "Fix {} first, then run `openlatch doctor` again.",
                blocker.title()
            )),
            source: None,
            agent: None,
            generated_headline: true,
        }
    }

    /// Absent from the build or irrelevant on this platform.
    pub fn not_applicable(section: Section, headline: impl Into<String>) -> Self {
        Self::new(section, State::NotApplicable, headline)
    }

    /// Attach the `OL-XXXX` code.
    #[must_use]
    pub fn code(mut self, code: &'static str) -> Self {
        self.code = Some(code);
        self
    }

    /// Attach the exact command or edit that resolves this.
    #[must_use]
    pub fn remedy(mut self, remedy: impl Into<String>) -> Self {
        self.remedy = Some(remedy.into());
        self
    }

    /// Attach where the state came from.
    #[must_use]
    pub fn source(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// Replace the headline.
    ///
    /// Mostly for [`Check::unknown`], whose generated wording says only that
    /// something is blocked. In a section that also holds green checks, the
    /// compact one-line rendering shows the worst check — so "not determinable"
    /// with no subject reads as if nothing about the section is known, when in
    /// fact one cross-check out of four is waiting on the daemon.
    ///
    /// Overriding it moves the blocker onto its own line in the block
    /// rendering, so it is named exactly once either way.
    #[must_use]
    pub fn headline(mut self, headline: impl Into<String>) -> Self {
        self.headline = headline.into();
        self.generated_headline = false;
        self
    }

    /// Attach one context line.
    #[must_use]
    pub fn detail(mut self, line: impl Into<String>) -> Self {
        self.detail.push(line.into());
        self
    }

    /// Attach one context line when there is one, and nothing when there is not.
    ///
    /// For call sites holding an `Option<String>` a binding already answered —
    /// [`crate::hooks::binding::LivenessReport::detail`] is the one in the tree.
    #[must_use]
    pub fn detail_opt(mut self, line: Option<impl Into<String>>) -> Self {
        if let Some(line) = line {
            self.detail.push(line.into());
        }
        self
    }

    /// Attach the agent this check is about — the wire `agent_type()`.
    ///
    /// A check left unstamped is host-wide, and its JSON carries no `agent`
    /// key at all.
    #[must_use]
    pub fn agent(mut self, agent: &'static str) -> Self {
        self.agent = Some(agent);
        self
    }

    /// Why this check violates the contract, if it does.
    ///
    /// Returns `None` for a well-formed check. Used by [`Report::validate`],
    /// which every rendering path runs under `debug_assert`.
    pub fn validate(&self) -> Option<String> {
        if !self.state.requires_remedy() {
            return None;
        }
        match (self.code, &self.remedy) {
            (Some(_), Some(_)) => None,
            (None, Some(_)) => Some(format!(
                "{}: '{}' is {} but carries no OL-XXXX code",
                self.section.title(),
                self.headline,
                self.state.key()
            )),
            (Some(_), None) => Some(format!(
                "{}: '{}' is {} but carries no remedy",
                self.section.title(),
                self.headline,
                self.state.key()
            )),
            (None, None) => Some(format!(
                "{}: '{}' is {} but carries neither code nor remedy",
                self.section.title(),
                self.headline,
                self.state.key()
            )),
        }
    }

    pub fn to_json(&self) -> serde_json::Value {
        let mut value = serde_json::json!({
            "section": self.section.key(),
            "state": self.state.key(),
            "blocked_by": match self.state {
                State::Unknown(b) => Some(b.key()),
                _ => None,
            },
            // Kept for consumers written against the pre-contract `doctor
            // --json`, where `pass` meant "not a failure" and warnings counted
            // as passes. `state` carries the detail.
            "pass": !self.state.is_failure(),
            "headline": self.headline,
            "detail": self.detail,
            "code": self.code,
            "remedy": self.remedy,
            "source": self.source,
        });
        // Absent, never null: a host-wide check emits no `agent` key at all.
        if let (Some(agent), Some(object)) = (self.agent, value.as_object_mut()) {
            object.insert("agent".into(), serde_json::json!(agent));
        }
        value
    }
}

// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------

/// How the machine is doing, as one word.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Overall {
    /// Nothing failed, nothing warned.
    Healthy,
    /// Nothing failed, something warned.
    Degraded,
    /// Something failed.
    Broken,
}

impl Overall {
    pub fn key(self) -> &'static str {
        match self {
            Overall::Healthy => "healthy",
            Overall::Degraded => "degraded",
            Overall::Broken => "broken",
        }
    }

    fn label(self) -> &'static str {
        match self {
            Overall::Healthy => "HEALTHY",
            Overall::Degraded => "DEGRADED",
            Overall::Broken => "BROKEN",
        }
    }
}

/// Tally of check outcomes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
    pub ok: usize,
    pub warned: usize,
    pub failed: usize,
}

/// An ordered set of [`Check`]s covering the install.
#[derive(Debug, Clone, Default)]
pub struct Report {
    checks: Vec<Check>,
}

impl Report {
    pub fn new() -> Self {
        Self::default()
    }

    /// Record one finding.
    pub fn push(&mut self, check: Check) {
        debug_assert!(
            check.validate().is_none(),
            "contract violation: {}",
            check.validate().unwrap_or_default()
        );
        self.checks.push(check);
    }

    /// Record one finding, chainable.
    #[must_use]
    pub fn with(mut self, check: Check) -> Self {
        self.push(check);
        self
    }

    /// Drop everything filed under `section` and file `check` instead.
    ///
    /// For the caller that knows something the detectors cannot: `init
    /// --no-start` deliberately leaves the daemon down, and a report that calls
    /// that a failure is describing the flag, not the machine.
    pub fn replace_section(&mut self, section: Section, check: Check) {
        self.checks.retain(|c| c.section != section);
        self.push(check);
    }

    pub fn is_empty(&self) -> bool {
        self.checks.is_empty()
    }

    pub fn checks(&self) -> &[Check] {
        &self.checks
    }

    /// Every check filed under `section`, in push order.
    pub fn section_checks(&self, section: Section) -> impl Iterator<Item = &Check> {
        self.checks.iter().filter(move |c| c.section == section)
    }

    /// The worst state among a section's checks.
    ///
    /// A section with no checks is [`State::NotApplicable`]: the caller either
    /// had nothing to say or the section is absent from the build. Sections are
    /// never silently dropped from the rendering — see [`Report::validate`].
    pub fn section_state(&self, section: Section) -> State {
        self.section_checks(section)
            .map(|c| c.state)
            .max_by_key(|s| s.severity())
            .unwrap_or(State::NotApplicable)
    }

    /// Every agent any check is stamped with, in first-seen order.
    ///
    /// Read off the checks rather than handed in: `check_environment` pushes one
    /// row per detected agent before any other detector runs, so this *is* the
    /// detected set, in detection order. Taking it as a second input would be a
    /// second source of truth about which agents the host has, free to disagree
    /// with the one every check already carries.
    pub fn agents(&self) -> Vec<&'static str> {
        let mut seen: Vec<&'static str> = Vec::new();
        for agent in self.checks.iter().filter_map(|c| c.agent) {
            if !seen.contains(&agent) {
                seen.push(agent);
            }
        }
        seen
    }

    /// The worst state among `agent`'s checks in `section`, or `None` when it
    /// files none there.
    ///
    /// `None` is absence, and deliberately not [`State::NotApplicable`]: that
    /// variant has exactly three sanctioned carve-outs
    /// (`.claude/rules/cli-output-contract.md`), and "this agent has nothing to
    /// say in this section" is not a fourth. The matrix renders it as an em
    /// dash for the same reason.
    pub fn agent_section_state(&self, agent: &str, section: Section) -> Option<State> {
        self.section_checks(section)
            .filter(|c| c.agent.is_some_and(|a| a == agent))
            .map(|c| c.state)
            .max_by_key(|s| s.severity())
    }

    /// The sections carrying at least one agent-tagged check — the matrix's
    /// rows.
    ///
    /// A host-wide check never puts its section on this list. That is what
    /// keeps the relay *listener*, which belongs to the host, out of a table
    /// about per-agent *wiring* — while leaving it exactly where it was in the
    /// section list above.
    fn agent_sections(&self) -> Vec<Section> {
        Section::ALL
            .into_iter()
            .filter(|s| self.section_checks(*s).any(|c| c.agent.is_some()))
            .collect()
    }

    /// Width of the agent-name column on a check row, or `0` when there is no
    /// column to draw.
    ///
    /// Zero on a single-agent host by construction: one agent's name repeated
    /// down every row is a column of the same word, and the rendering there has
    /// to stay byte-identical to a build that had never heard of agents.
    fn agent_column_width(&self) -> usize {
        let agents = self.agents();
        if agents.len() < 2 {
            return 0;
        }
        agents.iter().map(|a| a.chars().count()).max().unwrap_or(0) + 2
    }

    /// Tally across every check.
    pub fn counts(&self) -> Counts {
        let mut counts = Counts::default();
        for check in &self.checks {
            if check.state.is_failure() {
                counts.failed += 1;
            } else if check.state.is_warning() {
                counts.warned += 1;
            } else if check.state == State::Ok {
                counts.ok += 1;
            }
        }
        counts
    }

    pub fn overall(&self) -> Overall {
        let counts = self.counts();
        if counts.failed > 0 {
            Overall::Broken
        } else if counts.warned > 0 {
            Overall::Degraded
        } else {
            Overall::Healthy
        }
    }

    /// The process exit status this report implies.
    ///
    /// `0` healthy · [`EXIT_DEGRADED`] warnings only · `1` at least one
    /// failure.
    pub fn exit_code(&self) -> i32 {
        match self.overall() {
            Overall::Healthy => 0,
            Overall::Degraded => EXIT_DEGRADED,
            Overall::Broken => 1,
        }
    }

    /// Record [`Report::exit_code`] as the process verdict.
    pub fn record_verdict(&self) {
        record_exit_code(self.exit_code());
    }

    /// Every way this report violates the contract.
    ///
    /// Two rules: each non-`Ok`, non-`NotApplicable` check carries a code and a
    /// remedy, and all eleven sections are represented. Empty means conforming.
    pub fn validate(&self) -> Vec<String> {
        let mut problems: Vec<String> = self.checks.iter().filter_map(Check::validate).collect();
        for section in Section::ALL {
            if self.section_checks(section).next().is_none() {
                problems.push(format!(
                    "{} has no check — every section is always reported (P6)",
                    section.title()
                ));
            }
        }
        problems
    }

    /// The actionable half of every non-green check, ready to print under the
    /// section blocks.
    pub fn issues(&self) -> Vec<String> {
        self.checks
            .iter()
            .filter(|c| c.state.requires_remedy())
            .map(|c| {
                let mut line = format!("{}{}", c.section.title(), c.headline);
                if let Some(remedy) = &c.remedy {
                    line.push(' ');
                    line.push_str(remedy);
                }
                line
            })
            .collect()
    }

    // -----------------------------------------------------------------------
    // Rendering
    // -----------------------------------------------------------------------

    /// The full section-by-section rendering used by `doctor` and by the report
    /// half of `init`.
    ///
    /// A section holding exactly one `Ok` or `NotApplicable` check collapses to
    /// a single padded line; anything the operator might need to act on gets a
    /// full block with its source and remedy. The rule is mechanical, so the
    /// same state always renders the same way.
    pub fn render(&self, output: &OutputConfig) {
        debug_assert!(
            self.validate().is_empty(),
            "contract violations: {:?}",
            self.validate()
        );
        if output.format == OutputFormat::Json || output.quiet {
            return;
        }

        let counts = self.counts();
        let overall = self.overall();
        let headline = format!(
            "Overall: {}{} failed, {} warning{}, {} ok",
            overall.label(),
            counts.failed,
            counts.warned,
            if counts.warned == 1 { "" } else { "s" },
            counts.ok,
        );
        eprintln!(
            "{}",
            match overall {
                Overall::Healthy => color::green(&headline, output.color),
                Overall::Degraded => headline.clone(),
                Overall::Broken => color::red(&headline, output.color),
            }
        );
        eprintln!();

        // Three group headings, eleven section lines, and detail only where
        // something needs attention.
        //
        // The flat form gave every section its own heading, which is eleven
        // headings for twenty lines of content — and once the sections that
        // held a single check collapsed onto their title line, the marks
        // scattered across as many columns as there were title lengths.
        // Grouping fixes both: one scan column for the marks, and the green
        // sections fold into a line each, so what stays on screen is mostly
        // the things that do not pass. `--verbose` unfolds everything.
        for group in Group::ALL {
            eprintln!("{}", color::bold(group.title(), output.color));
            for section in Section::of_group(group) {
                self.render_section_line(section, output);
            }
            eprintln!();
        }

        // Which agent, on a host with more than one. The section lines above
        // answer "is anything wrong"; a worst-wins rollup cannot also answer
        // "wrong for whom", and on a two-agent host that is most of the
        // question.
        let matrix = self.agent_matrix_lines(0, 2, output);
        if !matrix.is_empty() {
            for line in &matrix {
                eprintln!("{line}");
            }
            eprintln!();
        }
    }

    /// One section as a line under its group, plus whatever needs saying.
    fn render_section_line(&self, section: Section, output: &OutputConfig) {
        for line in self.section_lines(section, output) {
            eprintln!("{line}");
        }
    }

    /// One section's lines under its group heading, ready to print.
    ///
    /// A green section is a line. A section with anything else on it lists each
    /// non-green check, every mark in the same column, each followed by its own
    /// detail, source and remedy.
    ///
    /// Built rather than printed because the claim this rendering now carries —
    /// a single-agent host looks exactly as it did, a multi-agent one names the
    /// agent on every row belonging to one — is a claim about bytes, and bytes
    /// on a process's stderr are not assertable from a unit test.
    fn section_lines(&self, section: Section, output: &OutputConfig) -> Vec<String> {
        let state = self.section_state(section);
        let title_cell = format!("  {:<TITLE_WIDTH$}  ", section.title());
        // Blank cell of the same width, so a second finding in one section puts
        // its mark under the first rather than after the title.
        let blank_cell = " ".repeat(title_cell.len());

        let interesting: Vec<&Check> = if output.verbose {
            self.section_checks(section).collect()
        } else {
            self.section_checks(section)
                .filter(|c| c.state.requires_remedy())
                .collect()
        };

        if interesting.is_empty() {
            return vec![format!(
                "{title_cell}{}{}",
                state.mark(output.color),
                self.section_summary(section)
            )];
        }

        // The agent column is drawn only where there is an agent to name. A
        // section whose findings are all host-wide — Daemon, Cloud, Persistence
        // — renders exactly as it does on a one-agent host, rather than carrying
        // an empty column for a distinction it does not have.
        let agent_width = if interesting.iter().any(|c| c.agent.is_some()) {
            self.agent_column_width()
        } else {
            0
        };
        let indent = " ".repeat(title_cell.len() + MARK_WIDTH + agent_width);

        let mut lines = Vec::new();
        for (index, check) in interesting.iter().enumerate() {
            let cell = if index == 0 { &title_cell } else { &blank_cell };
            lines.push(format!(
                "{cell}{}{}{}{}",
                check.state.mark(output.color),
                agent_cell(check, agent_width, output.color),
                check.headline,
                match check.code {
                    Some(code) if check.state.requires_remedy() =>
                        format!("   {}", color::dim(&format!("[{code}]"), output.color)),
                    _ => String::new(),
                }
            ));
            lines.extend(self.continuation_lines(check, &indent, output));
        }
        lines
    }

    /// The agent × subsystem matrix: which agent is in what state, where.
    ///
    /// Empty on a single-agent host — one column is a list, and the section
    /// lines above already are that list — and empty when nothing is tagged.
    ///
    /// A cell is the worst state among that agent's checks in that section: the
    /// same rollup [`Report::section_state`] applies to a section as a whole,
    /// applied per agent. That is the whole point of the table. `section_state`
    /// stays worst-wins, because if one agent is broken something *is* broken;
    /// this says *which*.
    ///
    /// A cell for an agent that files nothing in that section is an em dash — a
    /// rendering fact about absence, not [`State::NotApplicable`].
    fn agent_matrix_lines(
        &self,
        heading_indent: usize,
        row_indent: usize,
        output: &OutputConfig,
    ) -> Vec<String> {
        let agents = self.agents();
        let sections = self.agent_sections();
        if agents.len() < 2 || sections.is_empty() {
            return Vec::new();
        }

        // Each column as wide as its own heading, and never narrower than the
        // mark it has to hold.
        let widths: Vec<usize> = agents
            .iter()
            .map(|a| a.chars().count().max(MARK_WIDTH) + 2)
            .collect();

        let mut lines = vec![format!(
            "{}{}",
            " ".repeat(heading_indent),
            color::bold("Agents", output.color)
        )];

        let row = " ".repeat(row_indent);
        let mut header = format!("{row}{}", " ".repeat(TITLE_WIDTH + 2));
        for (agent, width) in agents.iter().zip(&widths) {
            header.push_str(&pad_to(
                &color::dim(agent, output.color),
                agent.chars().count(),
                *width,
            ));
        }
        lines.push(header.trim_end().to_string());

        for section in sections {
            let mut line = format!("{row}{:<TITLE_WIDTH$}  ", section.title());
            for (agent, width) in agents.iter().zip(&widths) {
                line.push_str(&match self.agent_section_state(agent, section) {
                    Some(state) => pad_to(&state.mark(output.color), MARK_WIDTH, *width),
                    None => pad_to(&color::dim("\u{2014}", output.color), 1, *width),
                });
            }
            lines.push(line.trim_end().to_string());
        }
        lines
    }

    /// The one line a section that needs no attention gets.
    ///
    /// A single check speaks for itself. Several collapse to a count — and the
    /// count separates "passed" from "not applicable", because a build without
    /// crash reporting has not passed a crash-reporting check, it has skipped
    /// one.
    fn section_summary(&self, section: Section) -> String {
        let checks: Vec<&Check> = self.section_checks(section).collect();
        match checks.as_slice() {
            [] => "no data".to_string(),
            [only] => only.headline.clone(),
            many => {
                let passed = many.iter().filter(|c| c.state == State::Ok).count();
                let skipped = many.len() - passed;
                if skipped == 0 {
                    format!("{passed} checks passed")
                } else {
                    format!("{passed} passed, {skipped} not applicable")
                }
            }
        }
    }

    /// A check's detail, source and remedy, at a caller-chosen indent.
    fn continuation_lines(
        &self,
        check: &Check,
        indent: &str,
        output: &OutputConfig,
    ) -> Vec<String> {
        let mut lines = Vec::new();
        // Structural, not prose: an `Unknown` whose headline was replaced names
        // its blocker on its own line, so a reader — and a test — can rely on
        // the line rather than on a phrase surviving an edit. Skipped when the
        // headline is still the generated one, which already carries the
        // blocker; printing both put the same sentence twice.
        if let (State::Unknown(blocker), false) = (check.state, check.generated_headline) {
            lines.push(format!(
                "{indent}{}",
                color::dim(&format!("waiting on : {}", blocker.title()), output.color)
            ));
        }
        for line in &check.detail {
            lines.push(format!("{indent}{}", color::dim(line, output.color)));
        }
        if let Some(source) = &check.source {
            lines.push(format!(
                "{indent}{}",
                color::dim(&format!("found in : {source}"), output.color)
            ));
        }
        if let Some(remedy) = &check.remedy {
            lines.push(format!(
                "{indent}{}",
                color::dim(&format!("to fix : {remedy}"), output.color)
            ));
        }
        lines
    }

    /// Print one section's block — title, every check, sources and remedies.
    ///
    /// The building block behind both [`Report::render`] and the
    /// per-subsystem status commands, so `openlatch system hooks status` and the Hooks
    /// block of `openlatch doctor` are the same text by construction.
    pub fn render_section(&self, section: Section, output: &OutputConfig) {
        if output.format == OutputFormat::Json || output.quiet {
            return;
        }
        eprintln!("{}", color::bold(section.title(), output.color));
        let checks: Vec<&Check> = self.section_checks(section).collect();
        // Same rule as the grouped rendering: name the agent wherever there is
        // one to name, and leave a section of host-wide findings alone.
        let agent_width = if checks.iter().any(|c| c.agent.is_some()) {
            self.agent_column_width()
        } else {
            0
        };
        let indent = format!("{CONTINUATION}{}", " ".repeat(agent_width));
        for check in checks {
            eprintln!(
                "  {}{}{}{}",
                check.state.mark(output.color),
                agent_cell(check, agent_width, output.color),
                check.headline,
                match check.code {
                    Some(code) if check.state.requires_remedy() =>
                        format!("   {}", color::dim(&format!("[{code}]"), output.color)),
                    _ => String::new(),
                }
            );
            for line in self.continuation_lines(check, &indent, output) {
                eprintln!("{line}");
            }
        }
    }

    /// One line per section, worst state wins — the `status` rendering.
    ///
    /// Carries no remedies on purpose: `status` is the glance, `doctor` is the
    /// diagnosis. A non-green section here points at `doctor`.
    pub fn render_compact(&self, output: &OutputConfig) {
        if output.format == OutputFormat::Json || output.quiet {
            return;
        }
        // Same groups and the same columns as `doctor`, one line per section
        // and nothing else. `status` is the glance; a reader who wants the
        // cause and the remedy is one command away, and told so.
        for group in Group::ALL {
            eprintln!("  {}", color::bold(group.title(), output.color));
            for section in Section::of_group(group) {
                let state = self.section_state(section);
                // The worst check is the one worth summarising; ties go to the
                // first pushed, which is the most fundamental by construction.
                let headline = if state.requires_remedy() {
                    self.section_checks(section)
                        .filter(|c| c.state == state)
                        .map(|c| c.headline.clone())
                        .next()
                        .unwrap_or_else(|| "no data".to_string())
                } else {
                    self.section_summary(section)
                };
                eprintln!(
                    "    {:<TITLE_WIDTH$}  {}{}",
                    section.title(),
                    state.mark(output.color),
                    headline
                );
            }
        }

        // `status` is the glance, so it gets the matrix and not the labelled
        // rows: the rows it prints are section rollups, and a rollup belongs to
        // no single agent. The matrix is the whole per-agent answer at a glance.
        let matrix = self.agent_matrix_lines(2, 4, output);
        if !matrix.is_empty() {
            eprintln!();
            for line in &matrix {
                eprintln!("{line}");
            }
        }

        if self.overall() != Overall::Healthy {
            eprintln!();
            eprintln!("  Run `openlatch doctor` for causes and remedies.");
        }
    }

    /// The machine rendering. Isomorphic to the human one (P7).
    pub fn to_json(&self) -> serde_json::Value {
        let counts = self.counts();

        // The per-agent rollup, keyed by agent rather than listed, so a
        // consumer indexes into it — and so everything else `doctor` has to say
        // about one agent lands in the same object rather than in a second
        // top-level key about the same subject.
        //
        // Built here rather than inline in the `json!` below: a multi-line
        // expression carrying a turbofish in a `json!` value position is a
        // tt-muncher away from silently producing the wrong shape, and this one
        // was — it emitted `{}` in the shipped binary while this module's own
        // tests saw the right thing.
        //
        // A section an agent files nothing in is absent from its list rather
        // than null: the rule the per-check `agent` tag follows, and the JSON of
        // the matrix's em dash.
        let mut agents = serde_json::Map::new();
        for agent in self.agents() {
            let sections: Vec<serde_json::Value> = Section::ALL
                .iter()
                .filter_map(|section| {
                    self.agent_section_state(agent, *section).map(|state| {
                        serde_json::json!({
                            "section": section.key(),
                            "state": state.key(),
                        })
                    })
                })
                .collect();
            agents.insert(
                agent.to_string(),
                serde_json::json!({ "sections": sections }),
            );
        }
        let sections: Vec<serde_json::Value> = Section::ALL
            .iter()
            .map(|section| {
                serde_json::json!({
                    "section": section.key(),
                    "group": section.group().key(),
                    "state": self.section_state(*section).key(),
                    "summary": self.section_summary(*section),
                    "checks": self
                        .section_checks(*section)
                        .map(Check::to_json)
                        .collect::<Vec<_>>(),
                })
            })
            .collect();

        serde_json::json!({
            "overall": self.overall().key(),
            "exit_code": self.exit_code(),
            "groups": Group::ALL
                .iter()
                .map(|g| serde_json::json!({
                    "group": g.key(),
                    "sections": Section::of_group(*g)
                        .map(|s| s.key())
                        .collect::<Vec<_>>(),
                }))
                .collect::<Vec<_>>(),
            "summary": {
                "ok": counts.ok,
                "warned": counts.warned,
                "failed": counts.failed,
            },
            "sections": sections,
            "issues": self.issues(),
            // Additive and last: every key above keeps its shape and its
            // position. An empty object on a host with no agent, never a
            // missing key, so a consumer indexes into one shape everywhere.
            "agents": serde_json::Value::Object(agents),
        })
    }
}

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

    fn plain() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: true, // rendering is exercised separately; keep tests silent
            color: false,
        }
    }

    /// Fill every section with a passing check so a test can then override the
    /// one section it cares about.
    fn all_green() -> Report {
        let mut report = Report::new();
        for section in Section::ALL {
            report.push(Check::ok(section, "fine"));
        }
        report
    }

    #[test]
    fn a_healthy_report_exits_zero() {
        let report = all_green();
        assert_eq!(report.overall(), Overall::Healthy);
        assert_eq!(report.exit_code(), 0);
    }

    #[test]
    fn a_disabled_feature_warns_and_exits_two() {
        let mut report = all_green();
        report.push(
            Check::off(Section::ModelRelay, "Disabled in config")
                .code(crate::error::ERR_MODEL_RELAY_NOT_RUNNING)
                .remedy("set [model_relay] enabled = true, then `openlatch restart`"),
        );
        assert_eq!(report.section_state(Section::ModelRelay), State::Off);
        assert_eq!(report.overall(), Overall::Degraded);
        assert_eq!(report.exit_code(), EXIT_DEGRADED);
    }

    #[test]
    fn a_failure_outranks_a_warning() {
        let mut report = all_green();
        report.push(
            Check::off(Section::Persistence, "Disabled")
                .code(crate::error::ERR_NO_SUPERVISOR)
                .remedy("`openlatch system supervision enable`"),
        );
        report.push(
            Check::failed(Section::ModelRelay, "Cannot bind 7600")
                .code(crate::error::ERR_MODEL_RELAY_PORT_IN_USE)
                .remedy("free the port"),
        );
        assert_eq!(report.overall(), Overall::Broken);
        assert_eq!(report.exit_code(), 1);
    }

    #[test]
    fn a_section_takes_the_worst_state_of_its_checks() {
        let mut report = all_green();
        report.push(Check::ok(Section::Daemon, "port bound"));
        report.push(
            Check::degraded(Section::Daemon, "one subsystem restarting")
                .code(crate::error::ERR_SUBSYSTEM_DEGRADED)
                .remedy("check the daemon log"),
        );
        assert_eq!(report.section_state(Section::Daemon), State::Degraded);
    }

    #[test]
    fn every_non_ok_check_carries_a_code_and_a_remedy() {
        // The rule, exercised over every constructor that can produce a
        // remedy-requiring state.
        let offenders = [
            Check::off(Section::Cloud, "x"),
            Check::degraded(Section::Cloud, "x"),
            Check::pending(Section::Cloud, "x"),
            Check::failed(Section::Cloud, "x"),
        ];
        for check in offenders {
            assert!(
                check.validate().is_some(),
                "{} without code/remedy must be rejected",
                check.state.key()
            );
        }
        // `unknown` supplies its own, so it is well-formed out of the box.
        assert!(Check::unknown(Section::Cloud, Section::Daemon)
            .validate()
            .is_none());
        // As are the two states that need no action.
        assert!(Check::ok(Section::Cloud, "x").validate().is_none());
        assert!(Check::not_applicable(Section::Cloud, "x")
            .validate()
            .is_none());
    }

    #[test]
    fn a_dead_daemon_produces_exactly_one_failure() {
        // Anti-cascade: the daemon fails, the seven sections behind it report
        // Unknown, and the report still shows a single cross.
        let mut report = Report::new();
        report.push(Check::ok(Section::Environment, "fine"));
        report.push(
            Check::failed(Section::Daemon, "not running")
                .code(crate::error::ERR_DAEMON_START_FAILED)
                .remedy("`openlatch start`"),
        );
        for section in [
            Section::Hooks,
            Section::ModelRelay,
            Section::Connection,
            Section::Cloud,
            Section::Policy,
            Section::Inventory,
            Section::Integrity,
        ] {
            report.push(Check::unknown(section, Section::Daemon));
        }
        report.push(Check::ok(Section::Persistence, "fine"));
        report.push(Check::not_applicable(Section::Telemetry, "opt-out"));
        report.push(Check::ok(Section::Update, "current"));

        assert_eq!(report.counts().failed, 1);
        assert_eq!(report.overall(), Overall::Broken);
        assert!(report.validate().is_empty(), "{:?}", report.validate());
    }

    #[test]
    fn validate_rejects_a_missing_section() {
        let mut report = Report::new();
        report.push(Check::ok(Section::Daemon, "fine"));
        let problems = report.validate();
        assert!(
            problems.iter().any(|p| p.contains("Model Relay")),
            "a missing section must be reported: {problems:?}"
        );
    }

    #[test]
    fn every_section_belongs_to_exactly_one_non_empty_group() {
        // The taxonomy has to partition the sections: a section in no group
        // would vanish from the rendering, and an empty group would print a
        // heading with nothing under it.
        let grouped: Vec<Section> = Group::ALL
            .iter()
            .flat_map(|g| Section::of_group(*g))
            .collect();
        assert_eq!(
            grouped.len(),
            Section::ALL.len(),
            "every section belongs to exactly one group"
        );
        for group in Group::ALL {
            assert!(
                Section::of_group(group).next().is_some(),
                "{} has no sections",
                group.title()
            );
        }
    }

    #[test]
    fn section_order_follows_group_order() {
        // The rendering walks groups and then sections; `Section::ALL` is what
        // the JSON walks. If the two disagree, a reader comparing `doctor` with
        // `doctor --json` sees the same sections in two different orders.
        let grouped: Vec<Section> = Group::ALL
            .iter()
            .flat_map(|g| Section::of_group(*g))
            .collect();
        assert_eq!(grouped, Section::ALL.to_vec());
    }

    #[test]
    fn a_green_section_collapses_and_a_problem_does_not() {
        let mut report = Report::new();
        for section in Section::ALL {
            report.push(Check::ok(section, "fine"));
        }
        report.push(Check::ok(Section::Hooks, "also fine"));
        assert_eq!(
            report.section_summary(Section::Hooks),
            "2 checks passed",
            "several green checks collapse to a count"
        );
        assert_eq!(
            report.section_summary(Section::Daemon),
            "fine",
            "a lone check speaks for itself"
        );

        // "Passed" and "skipped" are different claims: a build without crash
        // reporting has not passed a crash-reporting check.
        report.push(Check::not_applicable(Section::Update, "not compiled in"));
        assert_eq!(
            report.section_summary(Section::Update),
            "1 passed, 1 not applicable"
        );
    }

    #[test]
    fn human_and_json_carry_the_same_sections() {
        let report = all_green();
        let json = report.to_json();
        let sections = json["sections"].as_array().expect("sections array");
        assert_eq!(sections.len(), Section::ALL.len());
        for (rendered, expected) in sections.iter().zip(Section::ALL) {
            assert_eq!(rendered["section"], expected.key());
        }
    }

    #[test]
    fn json_keeps_the_legacy_pass_field_meaning_not_a_failure() {
        let warn = Check::off(Section::ModelRelay, "off")
            .code(crate::error::ERR_MODEL_RELAY_NOT_RUNNING)
            .remedy("x");
        assert_eq!(warn.to_json()["pass"], serde_json::Value::Bool(true));
        let fail = Check::failed(Section::ModelRelay, "broken")
            .code(crate::error::ERR_MODEL_RELAY_PORT_IN_USE)
            .remedy("x");
        assert_eq!(fail.to_json()["pass"], serde_json::Value::Bool(false));
    }

    #[test]
    fn check_agent_is_absent_not_null_when_unset() {
        // A host-wide check emits no `agent` key at all — an unconditional
        // `"agent": null` on every check would move the JSON of every existing
        // consumer, which is what the byte-diff gate exists to catch.
        let host_wide = Check::ok(Section::ModelRelay, "listening");
        let json = host_wide.to_json();
        assert!(
            json.get("agent").is_none(),
            "an unstamped check must carry no `agent` key, not a null one: {json}"
        );

        let stamped = Check::ok(Section::Hooks, "installed").agent("claude-code");
        assert_eq!(stamped.to_json()["agent"], serde_json::json!("claude-code"));
    }

    #[test]
    fn a_blocker_is_named_exactly_once() {
        // Two renderings, one fact. The generated headline carries the blocker
        // and the structural line is suppressed; an overridden headline says
        // something more useful and the structural line supplies the blocker.
        let generated = Check::unknown(Section::Policy, Section::Cloud);
        assert!(
            generated.headline.contains("Cloud"),
            "the generated headline must name the blocker for the compact view"
        );
        assert!(
            generated.generated_headline,
            "an untouched `unknown` keeps its generated headline"
        );

        let overridden = Check::unknown(Section::Policy, Section::Cloud)
            .headline("Enforcement state unknown — the platform is unreachable");
        assert!(
            !overridden.generated_headline,
            "overriding the headline hands the blocker to the structural line"
        );
        assert!(
            !overridden.headline.contains("Cloud"),
            "an overridden headline is free not to repeat the blocker"
        );
    }

    #[test]
    fn marks_are_five_columns_wide_in_no_color_mode() {
        for state in [
            State::Ok,
            State::Off,
            State::Degraded,
            State::Pending,
            State::Failed,
            State::Unknown(Section::Daemon),
            State::NotApplicable,
        ] {
            assert_eq!(state.mark(false).len(), 5, "{:?} misaligns", state);
        }
    }

    #[test]
    fn the_recorded_verdict_keeps_the_worst_code() {
        // Severity, not numeric order: a failure must survive a later warning.
        reset_exit_code();
        record_exit_code(EXIT_DEGRADED);
        record_exit_code(1);
        assert_eq!(pending_exit_code(), 1, "failure outranks degraded");

        reset_exit_code();
        record_exit_code(1);
        record_exit_code(EXIT_DEGRADED);
        assert_eq!(pending_exit_code(), 1, "degraded cannot clear a failure");

        reset_exit_code();
        record_exit_code(EXIT_DEGRADED);
        record_exit_code(0);
        assert_eq!(
            pending_exit_code(),
            EXIT_DEGRADED,
            "success cannot clear a warning"
        );

        reset_exit_code();
        assert_eq!(pending_exit_code(), 0);
    }

    #[test]
    fn rendering_is_silent_in_quiet_mode() {
        // Not an output assertion — a smoke test that the guarded paths do not
        // panic on a fully-populated report.
        let report = all_green();
        report.render(&plain());
        report.render_compact(&plain());
        // The same, with the per-agent renderings live.
        let two = two_agent_report();
        two.render(&plain());
        two.render_compact(&plain());
    }

    // -----------------------------------------------------------------------
    // Per-agent reporting
    // -----------------------------------------------------------------------

    /// Everything unfolded: the non-verbose rendering shows only what needs
    /// acting on, and half of what these tests assert is how a *passing* row
    /// renders.
    fn unfolded() -> OutputConfig {
        OutputConfig {
            verbose: true,
            ..plain()
        }
    }

    /// A two-agent host: hooks enforcing for one and dead for the other, a
    /// model relay wired for one and unread for the other, and every section
    /// also carrying the untagged host-wide check `all_green` pushes.
    fn two_agent_report() -> Report {
        let mut report = all_green();
        report.push(Check::ok(Section::Environment, "Agent: Claude Code").agent("claude-code"));
        report.push(Check::ok(Section::Environment, "Agent: Codex CLI").agent("codex-cli"));
        report.push(Check::ok(Section::Hooks, "Enforced").agent("claude-code"));
        report.push(
            Check::failed(
                Section::Hooks,
                "Monitored — installed and capturing, enforcing nothing",
            )
            .code(crate::error::ERR_HOOK_CONFLICT)
            .remedy("Trust the hook group.")
            .agent("codex-cli"),
        );
        report.push(
            Check::ok(Section::ModelRelay, "Agent wired to the listener").agent("claude-code"),
        );
        report
    }

    #[test]
    fn agents_are_named_once_each_in_detection_order() {
        // Order is detection order because Environment pushes one row per
        // detected agent first. A set would sort them, and the columns would
        // stop matching the Environment rows a reader just scanned.
        let report = two_agent_report();
        assert_eq!(report.agents(), vec!["claude-code", "codex-cli"]);
        assert_eq!(
            all_green().agents(),
            Vec::<&str>::new(),
            "a report with nothing tagged names no agents"
        );
    }

    #[test]
    fn a_cell_is_the_worst_of_that_agents_checks_in_that_section() {
        let mut report = two_agent_report();
        report.push(
            Check::degraded(Section::Hooks, "Staged binary is a release behind")
                .code(crate::error::ERR_HOOK_CONFLICT)
                .remedy("`openlatch doctor --fix`")
                .agent("claude-code"),
        );
        // Degraded now outranks the Ok, for that agent only.
        assert_eq!(
            report.agent_section_state("claude-code", Section::Hooks),
            Some(State::Degraded)
        );
        assert_eq!(
            report.agent_section_state("codex-cli", Section::Hooks),
            Some(State::Failed)
        );
        // And the section rollup stays worst-wins across both, unchanged: the
        // matrix answers *which*, the section answers *is anything wrong*.
        assert_eq!(report.section_state(Section::Hooks), State::Failed);
    }

    #[test]
    fn an_agent_that_files_nothing_in_a_section_has_no_state() {
        // Absence, not a state — and specifically not `NotApplicable`, which has
        // three sanctioned carve-outs and no room for a fourth.
        let report = two_agent_report();
        assert_eq!(
            report.agent_section_state("codex-cli", Section::ModelRelay),
            None
        );
        let matrix = report.agent_matrix_lines(0, 2, &plain()).join("\n");
        let relay = matrix
            .lines()
            .find(|l| l.contains(Section::ModelRelay.title()))
            .expect("the matrix must carry a Model Relay row");
        assert!(
            relay.contains('\u{2014}'),
            "an agent with no check there renders an em dash: {relay:?}"
        );
        assert!(
            !relay.contains(State::NotApplicable.mark(false).trim()),
            "the em dash must not be a NotApplicable mark in disguise: {relay:?}"
        );
    }

    #[test]
    fn a_host_wide_check_never_reaches_the_matrix() {
        // The relay listener belongs to the host; the wiring belongs to an
        // agent. The matrix renders only the tagged half — and the untagged
        // half stays exactly where it was, in the section list.
        let mut report = all_green();
        report.push(Check::ok(Section::Environment, "Agent: Claude Code").agent("claude-code"));
        report.push(Check::ok(Section::Environment, "Agent: Codex CLI").agent("codex-cli"));
        report.push(Check::ok(
            Section::ModelRelay,
            "Listening on 127.0.0.1:7600",
        ));

        let matrix = report.agent_matrix_lines(0, 2, &plain()).join("\n");
        assert!(
            !matrix.contains(Section::ModelRelay.title()),
            "an untagged section has no matrix row: {matrix}"
        );
        assert!(
            matrix.contains(Section::Environment.title()),
            "the tagged section does: {matrix}"
        );
        assert!(
            report
                .section_lines(Section::ModelRelay, &unfolded())
                .iter()
                .any(|l| l.contains("Listening on")),
            "the host-wide check still renders in its own section"
        );
    }

    #[test]
    fn a_single_agent_host_renders_exactly_as_an_untagged_one() {
        // The whole per-agent rendering is switched off below two agents: one
        // name repeated down every row is a column of the same word, and a
        // matrix with one column is the list that is already above it.
        let mut tagged = all_green();
        tagged.push(Check::ok(Section::Environment, "Agent: Claude Code").agent("claude-code"));
        tagged.push(Check::ok(Section::Hooks, "Enforced").agent("claude-code"));

        let mut untagged = all_green();
        untagged.push(Check::ok(Section::Environment, "Agent: Claude Code"));
        untagged.push(Check::ok(Section::Hooks, "Enforced"));

        for section in Section::ALL {
            assert_eq!(
                tagged.section_lines(section, &unfolded()),
                untagged.section_lines(section, &unfolded()),
                "{} renders differently once a single agent is tagged",
                section.title()
            );
        }
        assert_eq!(tagged.agent_column_width(), 0);
        assert!(tagged.agent_matrix_lines(0, 2, &unfolded()).is_empty());
    }

    #[test]
    fn both_agents_are_named_on_the_rows_that_belong_to_them() {
        // The symptom this closes: `✓ Enforced` over `✗ Monitored`, under one
        // heading, with nothing saying which agent is which.
        let report = two_agent_report();
        let hooks = report.section_lines(Section::Hooks, &unfolded());
        let enforced = hooks
            .iter()
            .find(|l| l.contains("Enforced"))
            .expect("the passing row");
        let monitored = hooks
            .iter()
            .find(|l| l.contains("Monitored"))
            .expect("the failing row");
        assert!(enforced.contains("claude-code"), "{enforced:?}");
        assert!(monitored.contains("codex-cli"), "{monitored:?}");

        // The host-wide check in the same section is padded, not named, and the
        // headlines all start in one column.
        let host_wide = hooks
            .iter()
            .find(|l| l.contains("fine"))
            .expect("the untagged row");
        assert!(!host_wide.contains("claude-code") && !host_wide.contains("codex-cli"));
        let column = |line: &str, needle: &str| line.find(needle).expect("headline");
        assert_eq!(
            column(enforced, "Enforced"),
            column(monitored, "Monitored"),
            "headlines must share a column"
        );
        assert_eq!(column(enforced, "Enforced"), column(host_wide, "fine"));
    }

    #[test]
    fn the_matrix_has_one_column_per_agent_and_one_row_per_tagged_section() {
        let report = two_agent_report();
        let lines = report.agent_matrix_lines(0, 2, &plain());
        let header = &lines[1];
        assert!(header.contains("claude-code") && header.contains("codex-cli"));

        let rows: Vec<&String> = lines[2..].iter().collect();
        let titles: Vec<&str> = rows
            .iter()
            .map(|l| l.trim_start().split("  ").next().unwrap_or_default())
            .collect();
        assert_eq!(
            titles,
            vec![
                Section::Environment.title(),
                Section::Hooks.title(),
                Section::ModelRelay.title()
            ],
            "only the sections carrying agent-tagged checks get a row, in section order"
        );
    }

    #[test]
    fn three_agents_still_fit_eighty_columns() {
        let mut report = all_green();
        for agent in ["claude-code", "codex-cli", "cline"] {
            report.push(Check::ok(Section::Environment, format!("Agent: {agent}")).agent(agent));
            report.push(Check::ok(Section::Hooks, "Enforced").agent(agent));
        }
        for line in report.agent_matrix_lines(2, 4, &plain()) {
            assert!(
                line.chars().count() <= 80,
                "the matrix must not overflow 80 columns: {} wide — {line:?}",
                line.chars().count()
            );
        }
    }

    #[test]
    fn json_gains_a_per_agent_rollup_and_moves_nothing() {
        let report = two_agent_report();
        let before = all_green().to_json();
        let json = report.to_json();

        // Every pre-existing key keeps its shape.
        for key in [
            "overall",
            "exit_code",
            "groups",
            "summary",
            "sections",
            "issues",
        ] {
            assert!(json.get(key).is_some(), "{key} must survive");
        }
        // An empty OBJECT, never a missing key: a consumer indexes into one
        // shape on every host, including one with no agent at all.
        assert_eq!(before["agents"], serde_json::json!({}));

        let agents = json["agents"].as_object().expect("an agents object");
        assert_eq!(agents.len(), 2);
        assert!(agents.contains_key("claude-code") && agents.contains_key("codex-cli"));

        let codex: Vec<(&str, &str)> = agents["codex-cli"]["sections"]
            .as_array()
            .expect("sections")
            .iter()
            .map(|s| {
                (
                    s["section"].as_str().unwrap_or_default(),
                    s["state"].as_str().unwrap_or_default(),
                )
            })
            .collect();
        assert_eq!(
            codex,
            vec![("environment", "ok"), ("hooks", "failed")],
            "a section the agent files nothing in is absent, not null"
        );
    }

    #[test]
    fn the_rollup_is_an_object_a_consumer_can_index() {
        // Pinned because it was wrong once, and silently. The rollup began as an
        // inline expression in a `json!` value position, and the macro produced
        // `{}` in the shipped binary while this module's own tests saw the right
        // thing — the shape was never asserted, only its contents. Assert the
        // type.
        let json = two_agent_report().to_json();
        assert!(
            json["agents"].is_object(),
            "the rollup is keyed by agent, not listed: {}",
            json["agents"]
        );
        assert!(json["agents"]["claude-code"]["sections"].is_array());
    }
}