openlatch-client 0.3.3

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
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
/// `openlatch doctor` command handler.
///
/// Runs diagnostic checks and reports results.
/// All path references use `config::openlatch_dir()` per PLAT-02.
///
/// `--fix`, `--restore`, and `--rescue` dispatch to sibling modules
/// (`doctor_fix`, `doctor_restore`, `doctor_rescue`). The shared
/// `run_all_checks` helper returns a structured `DoctorReport` so those
/// modules can re-run diagnostics for before/after deltas without
/// duplicating ~600 LOC of probe logic.
///
/// ## The section contract
///
/// Findings are filed into the eleven [`Section`]s of [`crate::cli::report`],
/// which own the marks, the exit code and both renderings. The rule that shapes
/// every branch below: **green means enabled and proven working**. A subsystem
/// switched off is a warning, not a pass — this command used to report a
/// disabled model boundary as `OK`, which is how a machine ran for two days
/// with every model call bypassing OpenLatch while `doctor` said it was fine.
use crate::cli::commands::lifecycle;
use crate::cli::commands::{doctor_fix, doctor_rescue, doctor_restore};
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::report::{Check, Report, Section, State};
use crate::cli::DoctorArgs;
use crate::config;
use crate::error::{
    OlError, ERR_BUG, ERR_BUNDLE_FETCH_FAILED, ERR_BUNDLE_STALE, ERR_CLOUD_AUTH_FAILED,
    ERR_CLOUD_UNREACHABLE, ERR_CONFIG_NOT_APPLIED, ERR_DAEMON_START_FAILED, ERR_DIRECT_FORBIDDEN,
    ERR_EGRESS_TLS_FAILED, ERR_EGRESS_UNREACHABLE, ERR_HMAC_KEY_UNAVAILABLE,
    ERR_HOOK_AGENT_NOT_FOUND, ERR_HOOK_BINARY_UNRESOLVABLE, ERR_HOOK_CONFLICT,
    ERR_HOOK_MALFORMED_JSONC, ERR_HOOK_WRITE_FAILED, ERR_INVALID_CONFIG, ERR_INVENTORY_DISABLED,
    ERR_INVENTORY_INIT_FAILED, ERR_NEGOTIATE_NO_TICKET, ERR_NO_CREDENTIALS, ERR_NO_SUPERVISOR,
    ERR_PAC_UNAVAILABLE, ERR_POLICY_DISABLED, ERR_PROXY_AUTH_FAILED, ERR_PROXY_CONFIG_INVALID,
    ERR_PROXY_SCHEME_UNSUPPORTED, ERR_PROXY_UNREACHABLE, ERR_SUBSYSTEM_DEGRADED,
    ERR_TAMPER_DETECTED, ERR_VERSION_OUTDATED,
};
use crate::hooks;
use crate::hooks::binding::{DaemonChannel, LivenessReport};

/// Aggregate diagnostic snapshot returned by [`run_all_checks`].
///
/// Carries enough state for `--fix` and `--rescue` flows to inspect
/// daemon liveness and the originally-configured port without re-probing.
#[allow(dead_code)] // fields consumed by doctor_fix / doctor_rescue
pub(crate) struct DoctorReport {
    /// Every finding, sectioned. Owns the rendering and the exit code.
    pub report: Report,
    pub daemon_alive: bool,
    pub daemon_uptime_secs: Option<u64>,
    pub port: u16,
}

impl DoctorReport {
    /// `true` when no check failed. Warnings do not disqualify — they move the
    /// exit code to 2, which is a different statement from "broken".
    pub(crate) fn all_pass(&self) -> bool {
        self.report.counts().failed == 0
    }

    /// Number of failing checks.
    pub(crate) fn fail_count(&self) -> usize {
        self.report.counts().failed
    }

    /// Number of green checks.
    pub(crate) fn pass_count(&self) -> usize {
        self.report.counts().ok
    }

    /// Headlines of everything that is not green, for `--fix` to report as
    /// what it could not heal.
    pub(crate) fn unresolved(&self) -> Vec<String> {
        self.report
            .checks()
            .iter()
            .filter(|c| c.state.requires_remedy())
            .map(|c| format!("{}: {}", c.section.title(), c.headline))
            .collect()
    }
}

/// Run the `openlatch doctor` command.
///
/// Default invocation (no flags): runs diagnostic checks and reports results.
/// `--fix`, `--restore`, `--rescue` dispatch to the matching sibling module.
/// Combined `--fix --rescue` and `--restore --rescue` are allowed —
/// rescue runs first to snapshot pre-fix state.
///
/// # Errors
///
/// Returns an error only if a fix/restore/rescue helper itself fails —
/// individual diagnostic check failures are reported through the exit code,
/// not returned.
pub fn run_doctor(args: &DoctorArgs, output: &OutputConfig) -> Result<(), OlError> {
    // Hidden self-test: deliberately panic to exercise the Sentry pipeline.
    // Used once per release during smoke validation — see brainstorm
    // Decision 14. Panics after crash-report init has already completed
    // at the top of main(), so the panic hook is live.
    if args.trigger_panic {
        panic!("openlatch crash-report validation panic");
    }

    // Combined-flag composition: rescue first to capture pre-fix state.
    if args.rescue && args.fix {
        doctor_rescue::run(args, output, /* fix_applied_after = */ true)?;
        return doctor_fix::run(args, output);
    }
    if args.rescue && args.restore {
        doctor_rescue::run(args, output, false)?;
        return doctor_restore::run(args, output);
    }
    if args.fix {
        return doctor_fix::run(args, output);
    }
    if args.restore {
        return doctor_restore::run(args, output);
    }
    if args.rescue {
        return doctor_rescue::run(args, output, false);
    }

    crate::cli::header::print(output, &["doctor"]);

    let report = run_all_checks(output)?;
    print_diagnostic_results(&report, output);
    Ok(())
}

// ---------------------------------------------------------------------------
// Probe results shared across sections
// ---------------------------------------------------------------------------

/// What one round of daemon probing found. Gathered once so the eleven section
/// builders below read the same instant rather than each re-probing and
/// disagreeing.
struct DaemonProbe {
    /// The PID in `daemon.pid` names a live process.
    alive: bool,
    /// `/health` answered 200.
    reachable: bool,
    /// Parsed `/health` body.
    health: Option<serde_json::Value>,
    /// Parsed `/metrics` body.
    metrics: Option<serde_json::Value>,
    /// Parsed `/admin/egress/status` body.
    ///
    /// Fetched separately, and authenticated, because `/metrics` deliberately
    /// carries no proxy URL — it is unauthenticated. Re-deriving the route from
    /// the CLI's own environment instead would reintroduce exactly the
    /// CLI-env-versus-daemon-env confusion the identity check above exists to
    /// catch. `None` when the token is unavailable or the fetch fails; every
    /// egress *state* decision then still comes from `/metrics`, and only the
    /// route detail line is dropped.
    egress: Option<serde_json::Value>,
    uptime_secs: Option<u64>,
}

impl DaemonProbe {
    fn metric_str<'a>(&'a self, key: &str) -> Option<&'a str> {
        self.metrics.as_ref()?.get(key)?.as_str()
    }

    fn metric_u64(&self, key: &str) -> Option<u64> {
        self.metrics.as_ref()?.get(key)?.as_u64()
    }

    fn metric_bool(&self, key: &str) -> Option<bool> {
        self.metrics.as_ref()?.get(key)?.as_bool()
    }

    fn egress_str<'a>(&'a self, key: &str) -> Option<&'a str> {
        self.egress.as_ref()?.get(key)?.as_str()
    }

    /// The masked `OL-122x` message the daemon last recorded.
    fn egress_error_message(&self) -> Option<String> {
        Some(
            self.egress
                .as_ref()?
                .get("last_error")?
                .get("message")?
                .as_str()?
                .to_string(),
        )
    }

    /// The daemon's configuration warnings, joined into one line.
    fn egress_warnings(&self) -> Vec<String> {
        self.egress
            .as_ref()
            .and_then(|e| e.get("warnings"))
            .and_then(|w| w.as_array())
            .map(|entries| {
                entries
                    .iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default()
    }
}

// ---------------------------------------------------------------------------
// Egress rendering (shared by the Cloud section)
// ---------------------------------------------------------------------------

/// The `OL-122x` behind a failed egress, narrowed back to a `'static` code.
///
/// The wire value is a string, and `Check::code` takes a `&'static str` on
/// purpose: a code an operator can look up has to be one this build knows. An
/// unrecognised value falls back to the generic unreachable code rather than
/// being echoed through — the alternative is a support ticket about a code that
/// exists nowhere in the docs.
fn egress_error_code(probe: &DaemonProbe) -> &'static str {
    match probe
        .egress
        .as_ref()
        .and_then(|e| e.get("last_error"))
        .and_then(|e| e.get("code"))
        .and_then(|c| c.as_str())
    {
        Some(ERR_PROXY_UNREACHABLE) => ERR_PROXY_UNREACHABLE,
        Some(ERR_PROXY_AUTH_FAILED) => ERR_PROXY_AUTH_FAILED,
        Some(ERR_PROXY_SCHEME_UNSUPPORTED) => ERR_PROXY_SCHEME_UNSUPPORTED,
        Some(ERR_EGRESS_TLS_FAILED) => ERR_EGRESS_TLS_FAILED,
        Some(ERR_PAC_UNAVAILABLE) => ERR_PAC_UNAVAILABLE,
        Some(ERR_PROXY_CONFIG_INVALID) => ERR_PROXY_CONFIG_INVALID,
        Some(ERR_DIRECT_FORBIDDEN) => ERR_DIRECT_FORBIDDEN,
        Some(ERR_NEGOTIATE_NO_TICKET) => ERR_NEGOTIATE_NO_TICKET,
        _ => ERR_EGRESS_UNREACHABLE,
    }
}

/// The executable remedy for one `OL-122x`, from the frozen error table.
fn egress_remedy(code: &'static str) -> &'static str {
    match code {
        ERR_PROXY_UNREACHABLE => {
            "Check the proxy host and port are reachable, then `openlatch proxy discover`              (or `openlatch proxy set <url>` if the source is manual)."
        }
        ERR_PROXY_AUTH_FAILED => {
            "Re-enter the proxy credentials with `openlatch proxy set <url>`; for Kerberos,              check the ticket with `klist`."
        }
        ERR_PROXY_SCHEME_UNSUPPORTED => {
            "The proxy is demanding a scheme this client cannot speak (NTLM, SAML). Ask IT for              a Kerberos-capable or unauthenticated policy for this binary."
        }
        ERR_EGRESS_TLS_FAILED => {
            "Likely TLS interception — install the intercepting CA in the OS trust store, or              `openlatch proxy set --ca-bundle <pem>`."
        }
        ERR_PAC_UNAVAILABLE => {
            "Fix `[proxy] pac_url`, or set `[proxy] url` directly (PAC is not supported on Linux)."
        }
        ERR_PROXY_CONFIG_INVALID => {
            "Fix the `[proxy]` key or environment variable named in the message, then              `openlatch restart`."
        }
        ERR_DIRECT_FORBIDDEN => {
            "`[proxy] allow_direct = false` forbids a direct connection and no proxy candidate              works. Set a working `[proxy] url`, or allow direct."
        }
        ERR_NEGOTIATE_NO_TICKET => {
            "Get a Kerberos ticket with `kinit`, or override the SPN with              `openlatch proxy set --spn <spn>`."
        }
        _ => {
            "Check this host can reach app.openlatch.ai, or ask IT for an egress rule;              `openlatch proxy test` shows which hop fails."
        }
    }
}

/// The daemon's configuration warnings, or a pointer when they cannot be read.
fn egress_warning_line(probe: &DaemonProbe) -> String {
    let warnings = probe.egress_warnings();
    if warnings.is_empty() {
        "The daemon resolved the proxy configuration with warnings.".to_string()
    } else {
        warnings.join("; ")
    }
}

/// Run every diagnostic check and assemble a [`DoctorReport`].
///
/// Pure read-only — never mutates state. Reusable by `doctor_fix` (for
/// before/after deltas) and `doctor_rescue` (for the bundled health
/// snapshot).
pub(crate) fn run_all_checks(_output: &OutputConfig) -> Result<DoctorReport, OlError> {
    let cfg = config::Config::load(None, None, false)?;
    let ol_dir = config::openlatch_dir();
    let mut report = Report::new();

    // Plural is the primitive: every per-agent check loops this list, and the
    // empty case keeps today's single anti-cascade check rather than an empty
    // section.
    let agents = hooks::detect_agents();
    let daemon_token = check_environment(&cfg, &ol_dir, &agents, &mut report);
    let probe = probe_daemon(&cfg, daemon_token.as_deref(), &mut report);

    check_hooks(
        &ol_dir,
        &agents,
        daemon_token.as_deref(),
        &cfg,
        &probe,
        &mut report,
    );

    #[cfg(feature = "boundary")]
    check_boundary(&cfg, &agents, &probe, &mut report);
    #[cfg(not(feature = "boundary"))]
    report.push(Check::not_applicable(
        Section::Boundary,
        "Not compiled into this build",
    ));

    check_persistence(&cfg, &mut report);
    check_connection(&cfg, &probe, &mut report);
    check_cloud(&cfg, &probe, &mut report);
    check_policy(&cfg, &probe, &mut report);
    check_inventory(&cfg, &probe, &mut report);
    check_telemetry(&ol_dir, &mut report);
    check_update(&cfg, &probe, &mut report);
    check_integrity(&ol_dir, &probe, &mut report);

    // Safety net for P6. A section that collected nothing is a bug in one of
    // the builders above, and `Report::validate` fails the test suite over it —
    // but a release build must still print twelve sections rather than silently
    // shrink the report.
    for section in Section::ALL {
        if report.section_checks(section).next().is_none() {
            report.push(Check::not_applicable(
                section,
                format!("no check ran — please report this ({ERR_BUG})"),
            ));
        }
    }

    Ok(DoctorReport {
        report,
        daemon_alive: probe.alive,
        daemon_uptime_secs: probe.uptime_secs,
        port: cfg.port,
    })
}

// ---------------------------------------------------------------------------
// Section 1 — Environment
// ---------------------------------------------------------------------------

/// Agent detection, config readability, crash-report consent and the local
/// daemon token. Returns the token so the hook cross-checks can compare against
/// it without re-reading the file.
fn check_environment(
    _cfg: &config::Config,
    ol_dir: &std::path::Path,
    agents: &[hooks::DetectedAgent],
    report: &mut Report,
) -> Option<String> {
    if agents.is_empty() {
        // No `OlError` to interpolate a message from once the parameter is a
        // list, and the remedy names every agent this build can detect rather
        // than Claude Code alone.
        report.push(
            Check::failed(Section::Environment, "Agent not found")
                .code(ERR_HOOK_AGENT_NOT_FOUND)
                .remedy(format!(
                    "Install a supported agent ({}), then run `openlatch init`.",
                    hooks::binding::DETECTABLE_AGENT_NAMES.join(", ")
                )),
        );
    }
    for a in agents {
        report.push(
            Check::ok(
                Section::Environment,
                format!("Agent: {} ({})", a.display_name(), a.config_dir().display()),
            )
            .agent(a.agent_type()),
        );
    }

    let config_path = ol_dir.join("config.toml");
    if config_path.exists() {
        match config::Config::load(None, None, false) {
            Ok(_) => report.push(Check::ok(
                Section::Environment,
                format!("Config: {}", config_path.display()),
            )),
            Err(e) => report.push(
                Check::failed(
                    Section::Environment,
                    format!("Config invalid: {} ({})", e.message, e.code),
                )
                .code(ERR_INVALID_CONFIG)
                .source(config_path.display().to_string())
                .remedy("Delete config.toml and re-run `openlatch init`."),
            ),
        }
    } else {
        report.push(
            Check::failed(
                Section::Environment,
                format!("Config missing: {}", config_path.display()),
            )
            .code(ERR_INVALID_CONFIG)
            .remedy("Run `openlatch init` to create it."),
        );
    }

    // Crash-report consent. Diagnostic only — never a fail condition. Reports
    // the resolved state so users can verify their opt-out (`SENTRY_DISABLED=1`
    // or `[crashreport] enabled = false`) actually landed.
    #[cfg(feature = "crash-report")]
    {
        let resolved = crate::crash_report::current_state(ol_dir);
        let label = match resolved.decided_by {
            crate::crash_report::consent::DecidedBy::SentryDisabledEnv => {
                "off (SENTRY_DISABLED env)"
            }
            crate::crash_report::consent::DecidedBy::NoBakedDsn => "off (no DSN baked)",
            crate::crash_report::consent::DecidedBy::ConfigFile => {
                if resolved.enabled() {
                    "on (config.toml)"
                } else {
                    "off (config.toml)"
                }
            }
            crate::crash_report::consent::DecidedBy::DefaultEnabled => "on (default)",
        };
        // Crash reporting is an opt-out, like telemetry: reporting the user's
        // own choice back as a warning is how a diagnostic teaches people to
        // stop reading it.
        if resolved.enabled() {
            report.push(Check::ok(
                Section::Environment,
                format!("Crash reporting: {label}"),
            ));
        } else {
            report.push(Check::not_applicable(
                Section::Environment,
                format!("Crash reporting: {label}"),
            ));
        }
    }
    #[cfg(not(feature = "crash-report"))]
    report.push(Check::not_applicable(
        Section::Environment,
        "Crash reporting: not compiled in",
    ));

    // The bearer token the hook subprocess presents to the daemon.
    let token_path = ol_dir.join("daemon.token");
    if !token_path.exists() {
        report.push(
            Check::failed(
                Section::Environment,
                format!("Auth token missing: {}", token_path.display()),
            )
            .code(ERR_INVALID_CONFIG)
            .remedy("Run `openlatch init` to generate one."),
        );
        return None;
    }
    match std::fs::read_to_string(&token_path) {
        Ok(content) if !content.trim().is_empty() => {
            report.push(Check::ok(
                Section::Environment,
                format!("Auth token: {}", token_path.display()),
            ));
            Some(content.trim().to_string())
        }
        Ok(_) => {
            report.push(
                Check::failed(
                    Section::Environment,
                    format!("Auth token empty: {}", token_path.display()),
                )
                .code(ERR_INVALID_CONFIG)
                .remedy("Run `openlatch init` to regenerate it."),
            );
            None
        }
        Err(e) => {
            report.push(
                Check::failed(
                    Section::Environment,
                    format!("Auth token unreadable: {}{e}", token_path.display()),
                )
                .code(ERR_INVALID_CONFIG)
                .remedy("Check the file permissions on ~/.openlatch/daemon.token."),
            );
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Section 2 — Daemon
// ---------------------------------------------------------------------------

/// Probe the daemon once and file the Daemon section.
fn probe_daemon(
    cfg: &config::Config,
    daemon_token: Option<&str>,
    report: &mut Report,
) -> DaemonProbe {
    let pid = lifecycle::read_pid_file();
    let alive = pid.map(lifecycle::is_process_alive).unwrap_or(false);

    // The PID comes from <dir>/daemon.pid, the port from config/env — two
    // independent sources that are only equal by convention. <dir>/daemon.port
    // records the port the daemon in THIS directory actually bound, so a
    // disagreement means the /health probe below is answered by some OTHER
    // daemon while we report the local PID next to it.
    //
    // Seen in practice with two instances up: `OPENLATCH_PORT=7543` with
    // OPENLATCH_DIR left at the default made doctor print "running on port
    // 7543 (PID 1115226)" — but 1115226 was on 7443, and 7543 belonged to an
    // entirely different process. Every downstream check then compared against
    // an instance the operator was not looking at.
    let bound_port = config::read_port_file();
    if let (true, Some(bound)) = (alive, bound_port) {
        if bound != cfg.port {
            report.push(
                Check::failed(
                    Section::Daemon,
                    format!(
                        "Identity: daemon.port says this instance is on {bound}, configured port is {}",
                        cfg.port
                    ),
                )
                .code(ERR_INVALID_CONFIG)
                .detail(format!(
                    "PID {} belongs to the daemon on port {bound}; port {} is served by a different process.",
                    pid.unwrap_or(0),
                    cfg.port
                ))
                .remedy("Re-run with OPENLATCH_DIR set to the instance you mean."),
            );
        }
    }

    let mut probe = DaemonProbe {
        alive,
        reachable: false,
        health: None,
        metrics: None,
        egress: None,
        uptime_secs: None,
    };

    if !alive {
        report.push(
            Check::failed(Section::Daemon, format!("Not running (port {})", cfg.port))
                .code(ERR_DAEMON_START_FAILED)
                .remedy("Run `openlatch start`."),
        );
        return probe;
    }

    // Keep the body, not just the status: `/health` carries the version the
    // daemon is actually serving, which is the only way to see an upgrade that
    // landed on disk without reaching the running process.
    // A bare `reqwest::blocking::get` carries no timeout at all: a daemon that accepts
    // the connection and then stalls would wedge `doctor` forever, which is the one
    // command an operator reaches for when things are already wrong.
    let probe_client = crate::egress::blocking_client_builder()
        .timeout(std::time::Duration::from_secs(2))
        .build()
        .ok();
    let probe_get = |path: &str| {
        probe_client
            .as_ref()?
            .get(format!("http://127.0.0.1:{}/{path}", cfg.port))
            .send()
            .ok()
    };

    probe.health = probe_get("health")
        .filter(|r| r.status().is_success())
        .and_then(|r| r.json::<serde_json::Value>().ok());
    probe.reachable = probe.health.is_some();

    if !probe.reachable {
        report.push(
            Check::failed(
                Section::Daemon,
                format!(
                    "Process alive (PID {}) but /health unreachable on port {}",
                    pid.unwrap_or(0),
                    cfg.port
                ),
            )
            .code(ERR_DAEMON_START_FAILED)
            .remedy("Run `openlatch restart`."),
        );
        return probe;
    }

    // Only claim the PID and the port describe one process when daemon.port
    // agrees (or is absent, i.e. nothing to contradict).
    let same_instance = bound_port.map(|b| b == cfg.port).unwrap_or(true);
    if same_instance {
        report.push(Check::ok(
            Section::Daemon,
            format!("Running: PID {} on port {}", pid.unwrap_or(0), cfg.port),
        ));
    } else {
        report.push(Check::ok(
            Section::Daemon,
            format!(
                "Port {} is serving (PID unknown — local daemon.pid {} is on port {})",
                cfg.port,
                pid.unwrap_or(0),
                bound_port.unwrap_or(0)
            ),
        ));
    }

    probe.metrics = probe_get("metrics").and_then(|r| r.json::<serde_json::Value>().ok());
    probe.uptime_secs = probe.metric_u64("uptime_secs");

    // The masked route, from the daemon's own resolution. Authenticated like
    // every other `/admin/*` call; a missing token or a failed fetch simply
    // leaves the detail line off.
    probe.egress = daemon_token.and_then(|token| {
        probe_client
            .as_ref()?
            .get(format!("http://127.0.0.1:{}/admin/egress/status", cfg.port))
            .bearer_auth(token)
            .send()
            .ok()
            .filter(|r| r.status().is_success())
            .and_then(|r| r.json::<serde_json::Value>().ok())
    });

    // In-process supervision. A degraded subsystem is a real capability loss
    // that no other check sees: the daemon answers 200 with its boundary task
    // dead, and every other signal on the machine looks healthy.
    let degraded = probe.metric_u64("subsystem_degraded_count").unwrap_or(0);
    let restarts = probe.metric_u64("subsystem_restarts_total").unwrap_or(0);
    if degraded > 0 {
        let names = probe
            .health
            .as_ref()
            .and_then(|h| h.get("subsystems"))
            .and_then(|s| s.as_object())
            .map(|m| {
                m.iter()
                    .filter(|(_, v)| v.get("state").and_then(|s| s.as_str()) != Some("running"))
                    .map(|(k, _)| k.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| format!("{degraded} subsystem(s)"));
        report.push(
            Check::failed(Section::Daemon, format!("Subsystems down: {names}"))
                .code(ERR_SUBSYSTEM_DEGRADED)
                .detail(format!("{restarts} restart(s) since start"))
                .remedy("Check the newest ~/.openlatch/logs/daemon.log.<date>, then `openlatch restart`."),
        );
    } else if probe.metrics.is_some() {
        report.push(Check::ok(Section::Daemon, "Subsystems: all healthy"));
    }

    probe
}

// ---------------------------------------------------------------------------
// Section 3 — Hooks
// ---------------------------------------------------------------------------

fn check_hooks(
    ol_dir: &std::path::Path,
    agents: &[hooks::DetectedAgent],
    daemon_token: Option<&str>,
    cfg: &config::Config,
    probe: &DaemonProbe,
    report: &mut Report,
) {
    if agents.is_empty() {
        // No agent — Environment already carries the failure. Repeating it here
        // as a second cross is the cascade this contract exists to prevent.
        report.push(Check::unknown(Section::Hooks, Section::Environment));
        return;
    }

    // `check_fallback_activity` is per-HOST, not per-agent — it reads
    // ~/.openlatch/logs/fallback.jsonl and has nothing to do with any one
    // agent. It also used to be skipped whenever the single agent's settings
    // file was missing or unreadable, because both of those paths returned
    // early. Hoisting it out of the loop unconditionally would make it run on a
    // host it does not run on today, so it stays gated on at least one agent
    // having been inspected.
    let mut any_inspected = false;

    for a in agents {
        let settings_path = a.settings_path();
        let settings_path = settings_path.as_path();
        let agent = a.agent_type();

        if !settings_path.exists() {
            report.push(
                Check::failed(
                    Section::Hooks,
                    format!("settings.json not found at {}", settings_path.display()),
                )
                .code(ERR_HOOK_WRITE_FAILED)
                .remedy("Run `openlatch init` to install the hooks.")
                .agent(agent),
            );
            continue;
        }

        // Parsed, not substring-matched. `content.contains("Stop")` is true for
        // a settings.json whose only OpenLatch entry is `SubagentStop`, or
        // whose `Stop` array holds somebody else's hook — the marker and the
        // event were never checked on the same entry.
        //
        // Judged against THIS agent's load-bearing events, read off its own
        // binding: an agent that registers a different set is not broken for
        // failing to register Claude Code's.
        let inspected = match crate::hooks::health::inspect_file(settings_path, &*a.binding) {
            Ok(health) if health.missing_events.is_empty() => {
                report.push(
                    Check::ok(
                        Section::Hooks,
                        format!("Entries: all present in {}", settings_path.display()),
                    )
                    .agent(agent),
                );
                true
            }
            Ok(health) => {
                report.push(
                    Check::failed(
                        Section::Hooks,
                        format!("Entries missing: {}", health.missing_events.join(", ")),
                    )
                    .code(ERR_HOOK_WRITE_FAILED)
                    .source(settings_path.display().to_string())
                    .remedy(
                        "Run `openlatch doctor --fix` to reinstall them (it keeps the current \
                         token, so running agent sessions keep capturing).",
                    )
                    .agent(agent),
                );
                true
            }
            Err(e) => {
                report.push(
                    Check::failed(
                        Section::Hooks,
                        format!("Cannot read {}{}", settings_path.display(), e.message),
                    )
                    .code(ERR_HOOK_MALFORMED_JSONC)
                    .remedy("Check the file permissions and that settings.json is valid JSONC.")
                    .agent(agent),
                );
                false
            }
        };
        if !inspected {
            continue;
        }
        any_inspected = true;

        check_hook_binding(
            settings_path,
            &*a.binding,
            daemon_token,
            cfg.port,
            probe.reachable,
            report,
        );

        // *Installed* and *enforcing* are two different claims, and only the
        // binding knows the difference. One question, asked of every agent,
        // rendered here and nowhere else — a second rendering path per agent is
        // the second detector the one-set-of-detectors invariant forbids.
        //
        // `armed: None` pushes nothing: Claude Code has no arming concept, so
        // installed *is* armed and there is nothing to add.
        match a.binding.liveness() {
            LivenessReport { armed: None, .. } => {}
            LivenessReport {
                armed: Some(true),
                detail,
                ..
            } => report.push(
                Check::ok(Section::Hooks, "Enforced")
                    .detail_opt(detail)
                    .agent(agent),
            ),
            LivenessReport {
                armed: Some(false),
                detail,
                remedy,
                code,
            } => {
                // Both fields are mandatory in this state (see `LivenessReport`), but a binding
                // that omits one is a defect in THAT binding, and `doctor` answers one question
                // for the whole host — a single malformed binding must not take the other ten
                // sections down with it. So: caught in development by the same `debug_assert`
                // every rendering path already runs over `Report::validate` (`report.rs:548`),
                // and in release degraded to the repo's existing "please report this" shape
                // (`ERR_BUG`, as at `:361` and `:1721`) rather than panicking the CLI.
                debug_assert!(
                    code.is_some() && remedy.is_some(),
                    "a Some(false) liveness MUST carry a code and a remedy — see LivenessReport"
                );
                report.push(
                    Check::failed(
                        Section::Hooks,
                        "Monitored — installed and capturing, enforcing nothing",
                    )
                    .code(code.unwrap_or(ERR_BUG))
                    .detail_opt(detail)
                    .remedy(remedy.unwrap_or_else(|| {
                        format!(
                            "this agent's binding reported enforcement off without a remedy — \
                             please report this ({ERR_BUG})"
                        )
                    }))
                    .agent(agent),
                )
            }
        }
    }

    if any_inspected {
        check_fallback_activity(ol_dir, probe, report);
    }
}

/// Verify the hook command in settings.json still points at a usable binary,
/// that the bearer token the hook subprocess will receive matches the one the
/// daemon has loaded, and that the hook will resolve the port this daemon is
/// actually listening on.
fn check_hook_binding(
    settings_path: &std::path::Path,
    binding: &dyn crate::hooks::binding::AgentBinding,
    daemon_token: Option<&str>,
    daemon_port: u16,
    daemon_reachable: bool,
    report: &mut Report,
) {
    let agent = binding.agent_type();
    // The two cross-checks below read named environment keys out of the agent's
    // own config file. That is a question only an agent whose daemon channel
    // *is* environment variables can be asked — for one on `OpenlatchDirArg`
    // there is no key to read, and the honest answer is to push nothing: not a
    // pass, not a failure, the question does not apply.
    let (token_env, port_env) = match binding.daemon_channel() {
        DaemonChannel::EnvVars { token, port } => (Some(token), Some(port)),
        DaemonChannel::OpenlatchDirArg => (None, None),
    };

    let raw = match std::fs::read_to_string(settings_path) {
        Ok(s) => s,
        // Read-error already reported above; don't double-count.
        Err(_) => return,
    };
    let parsed = match crate::hooks::jsonc::parse_settings_value(&raw) {
        Ok(v) => v,
        Err(e) => {
            report.push(
                Check::failed(
                    Section::Hooks,
                    format!("Cannot parse settings.json ({})", e.code),
                )
                .code(ERR_HOOK_MALFORMED_JSONC)
                .remedy("Repair the JSON, then run `openlatch doctor --fix`.")
                .agent(agent),
            );
            return;
        }
    };

    let health = crate::hooks::health::inspect(&parsed, binding);
    if health.commands == 0 {
        // No _openlatch entries — already flagged above.
        return;
    }
    let expected_bin = &health.expected_bin;

    if health.missing_bin.is_empty() && health.drifted_bin.is_empty() {
        report.push(
            Check::ok(
                Section::Hooks,
                format!("Binary: {}", expected_bin.display()),
            )
            .agent(agent),
        );
    }
    // The remediation is `doctor --fix`, not `init`.
    //
    // `init` regenerates the daemon token unconditionally. Agent sessions
    // already running hold the previous `OPENLATCH_TOKEN` in their process env,
    // so after the rotation their hooks authenticate with a stale token and get
    // rejected — silently, because the hook fails open and spools to
    // fallback.jsonl. Sending an operator to `init` to repair a dangling hook
    // command therefore costs them capture on every session currently running.
    // `doctor --fix` reinstalls with the token already on disk.
    if !health.missing_bin.is_empty() {
        report.push(
            Check::failed(
                Section::Hooks,
                format!("Binary missing: {}", health.missing_bin.join(", ")),
            )
            .code(ERR_HOOK_BINARY_UNRESOLVABLE)
            .remedy(
                "Run `openlatch doctor --fix` to stage the binary and rewrite the hook command \
                 (it keeps the current token, so running agent sessions keep capturing).",
            )
            .agent(agent),
        );
    }
    if !health.drifted_bin.is_empty() {
        report.push(
            Check::failed(
                Section::Hooks,
                format!(
                    "Binary drift: settings.json uses {}, current install is {}",
                    health.drifted_bin.join(", "),
                    expected_bin.display()
                ),
            )
            .code(ERR_HOOK_BINARY_UNRESOLVABLE)
            .remedy("Run `openlatch doctor --fix` to re-link settings.json to the current install.")
            .agent(agent),
        );
    }

    // Token cross-check — the agent's env.<token key> vs daemon.token. Runs
    // only for a binding whose channel names that key.
    if let (Some(token_env), Some(token)) = (token_env, daemon_token) {
        let settings_token = parsed
            .get("env")
            .and_then(|e| e.get(token_env))
            .and_then(|v| v.as_str());
        match settings_token {
            Some(t) if t == token => {
                report.push(Check::ok(Section::Hooks, "Token: matches daemon.token").agent(agent));
            }
            Some(_) => {
                report.push(
                    Check::failed(
                        Section::Hooks,
                        format!("Token: settings.json {token_env} does not match daemon.token"),
                    )
                    .code(ERR_HOOK_CONFLICT)
                    .detail("Hook subprocesses will be rejected with 401 and fail open silently.")
                    .remedy("Run `openlatch init` to re-sync the token.")
                    .agent(agent),
                );
            }
            None => {
                report.push(
                    Check::failed(
                        Section::Hooks,
                        format!("Token: {token_env} not set in settings.json env"),
                    )
                    .code(ERR_HOOK_CONFLICT)
                    .remedy("Run `openlatch init` to install it.")
                    .agent(agent),
                );
            }
        }
    }

    // Port cross-check — the agent's env.<port key> vs the port the daemon is
    // actually listening on. Runs only for a binding whose channel names that
    // key, for the same reason as the token check above.
    //
    // The hook resolves its port as: OPENLATCH_PORT (its own env, populated by
    // the agent from settings.json) -> <openlatch_dir>/daemon.port -> 7443.
    // `openlatch init` writes OPENLATCH_TOKEN but NOT OPENLATCH_PORT, and
    // OPENLATCH_DIR is not in the hook entry's allowedEnvVars, so a daemon on
    // a non-default OPENLATCH_DIR is invisible to the hook: it reads the
    // DEFAULT dir's daemon.port and silently talks to the wrong daemon (or
    // none). Because the hook fails open — prints `{}`, exits 0, spools to
    // fallback.jsonl — nothing surfaces the breakage.
    let Some(port_env) = port_env else {
        return;
    };
    let settings_port = parsed
        .get("env")
        .and_then(|e| e.get(port_env))
        // Accept both "7543" and 7543 — hand-edited settings use either.
        .and_then(|v| {
            v.as_str()
                .and_then(|s| s.trim().parse::<u16>().ok())
                .or_else(|| v.as_u64().and_then(|n| u16::try_from(n).ok()))
        });

    let dir_is_default = std::env::var("OPENLATCH_DIR")
        .ok()
        .filter(|d| !d.is_empty())
        .is_none();

    match settings_port {
        // `0` is never a port a hook can reach. It got into settings.json
        // because `OPENLATCH_PORT` parsed as any u16, the daemon then bound an
        // ephemeral port, and `install_hooks` pinned the configured `0` into
        // all 12 entries. Both sides then held `0` and this check reported a
        // green line directly under `Daemon: not running (port 0)`. Equality is
        // not health.
        Some(p) if p < config::MIN_USER_PORT || daemon_port < config::MIN_USER_PORT => {
            report.push(
                Check::failed(
                    Section::Hooks,
                    format!("Port: {p} in settings.json / {daemon_port} configured — not usable"),
                )
                .code(ERR_HOOK_CONFLICT)
                .remedy(format!(
                    "{port_env} must be between {} and {}. Re-run `openlatch init` with a \
                     valid {port_env}, or unset it to probe automatically.",
                    config::MIN_USER_PORT,
                    u16::MAX
                ))
                .agent(agent),
            );
        }
        // A match against a port nobody is serving proves nothing. Say what we
        // actually verified rather than borrowing the confidence of a real
        // round trip.
        Some(p) if p == daemon_port && !daemon_reachable => {
            report.push(
                Check::unknown(Section::Hooks, Section::Daemon)
                    .headline(format!(
                        "Port {daemon_port} matches settings.json, but no daemon answered there"
                    ))
                    .agent(agent),
            );
        }
        Some(p) if p == daemon_port => {
            report.push(
                Check::ok(
                    Section::Hooks,
                    format!("Port: matches daemon port ({daemon_port})"),
                )
                .agent(agent),
            );
        }
        Some(p) => {
            report.push(
                Check::failed(
                    Section::Hooks,
                    format!("Port: settings.json says {p}, daemon is on {daemon_port}"),
                )
                .code(ERR_HOOK_CONFLICT)
                .detail("Hook subprocesses connect to the wrong port and fail open silently.")
                .remedy(format!(
                    "Set {port_env} to {daemon_port} in the agent's settings env."
                ))
                .agent(agent),
            );
        }
        // Unset is fine on a default install: the hook falls back to
        // <default dir>/daemon.port, which IS this daemon's port file.
        None if dir_is_default => {
            report.push(
                Check::ok(
                    Section::Hooks,
                    format!("Port: resolved from daemon.port ({daemon_port})"),
                )
                .agent(agent),
            );
        }
        None => {
            report.push(
                Check::failed(
                    Section::Hooks,
                    format!("Port: {port_env} unset while OPENLATCH_DIR is non-default"),
                )
                .code(ERR_HOOK_CONFLICT)
                .detail(
                    "The hook cannot see OPENLATCH_DIR, so it reads the default directory's \
                     daemon.port instead of this instance's and fails open silently.",
                )
                .remedy(format!(
                    "Set {port_env} to {daemon_port} in the agent's settings env."
                ))
                .agent(agent),
            );
        }
    }
}

/// Flag fallback.jsonl as a problem when any of its bytes were written after
/// the currently-running daemon started. That's the on-disk trace of a hook
/// subprocess failing to reach its own daemon.
fn check_fallback_activity(ol_dir: &std::path::Path, probe: &DaemonProbe, report: &mut Report) {
    // Without a live daemon there's no "since daemon start" reference point,
    // and any fallback activity is expected.
    if !probe.alive {
        return;
    }
    let Some(uptime) = probe.uptime_secs else {
        return;
    };
    let fallback_path = ol_dir.join("logs").join("fallback.jsonl");
    if !fallback_path.exists() {
        report.push(Check::ok(
            Section::Hooks,
            "Fallback log: no offline events recorded",
        ));
        return;
    }

    let meta = match std::fs::metadata(&fallback_path) {
        Ok(m) => m,
        Err(e) => {
            report.push(
                Check::failed(
                    Section::Hooks,
                    format!(
                        "Fallback log: cannot stat {}{e}",
                        fallback_path.display()
                    ),
                )
                .code(ERR_HOOK_CONFLICT)
                .remedy("Check the permissions on ~/.openlatch/logs/."),
            );
            return;
        }
    };
    let Ok(mtime) = meta.modified() else {
        return;
    };
    let daemon_start = std::time::SystemTime::now()
        .checked_sub(std::time::Duration::from_secs(uptime))
        .unwrap_or(std::time::UNIX_EPOCH);

    if mtime > daemon_start {
        let age_secs = mtime
            .duration_since(daemon_start)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        report.push(
            Check::failed(
                Section::Hooks,
                format!(
                    "Fallback log: last written {} into the daemon's uptime",
                    human_duration(age_secs)
                ),
            )
            .code(ERR_HOOK_CONFLICT)
            .detail(
                "The hook binary is spooling to fallback.jsonl while the daemon is up — it \
                 cannot reach its own daemon.",
            )
            .detail("Likely causes: token mismatch, wrong port, or stale settings.json.")
            .remedy("Fix the Token/Port checks above, then run `openlatch init` to repair."),
        );
    } else {
        report.push(Check::ok(
            Section::Hooks,
            "Fallback log: quiet since daemon start",
        ));
    }
}

/// Seconds as something an operator reads at a glance. Raw seconds are exact
/// and unreadable: "written 115836s after daemon start" is a number nobody
/// converts in their head.
fn human_duration(secs: u64) -> String {
    match secs {
        0..=90 => format!("{secs}s"),
        91..=5400 => format!("{}m", secs / 60),
        5401..=172_800 => format!("{}h", secs / 3600),
        _ => format!("{}d", secs / 86_400),
    }
}

// ---------------------------------------------------------------------------
// Section 4 — Boundary
// ---------------------------------------------------------------------------

/// What this agent calls the thing that points it at us, in its own words.
///
/// `ANTHROPIC_BASE_URL` for Claude Code, `model_provider = "openlatch"` for
/// Codex. Telling a Codex user to check a variable their agent does not have is
/// the same defect as telling them to fix reachability to Anthropic's host: a
/// non-null remedy that cannot be acted on.
#[cfg(feature = "boundary")]
fn boundary_endpoint_name(w: &crate::hooks::binding::BoundaryWiring) -> String {
    use crate::hooks::binding::EndpointConvention;
    match w.endpoint {
        EndpointConvention::EnvVars { base_url, .. } => base_url.to_string(),
        EndpointConvention::TomlProvider { provider_name, .. } => {
            format!("`model_provider = \"{provider_name}\"`")
        }
    }
}

/// The proxy stop-gap, for a convention whose writer cannot merge a bypass
/// itself.
///
/// The `EnvVars` writer merges `127.0.0.1,localhost` into `NO_PROXY`/`no_proxy`
/// on the agent's behalf, so its remedies say nothing. Codex's `config.toml`
/// has no environment block and no proxy field, so this build writes no bypass
/// for it at all — which makes a proxied estate a live cause of exactly the two
/// states this note is attached to. Until the config-level question is
/// answered, saying so is what keeps the remedy actionable.
#[cfg(feature = "boundary")]
fn toml_provider_proxy_note(w: &crate::hooks::binding::BoundaryWiring) -> &'static str {
    use crate::hooks::binding::EndpointConvention;
    match w.endpoint {
        EndpointConvention::EnvVars { .. } => "",
        EndpointConvention::TomlProvider { .. } => {
            " If Codex runs behind a proxy, export NO_PROXY=127.0.0.1,localhost in the shell \
             that launches it — the boundary's loopback base must not leave through the \
             corporate proxy."
        }
    }
}

/// The model-boundary invariant, made observable: `ANTHROPIC_BASE_URL` is in the
/// agent's settings.json IF AND ONLY IF a listener holds the pinned port.
///
/// Both halves are worth reporting and they fail very differently:
///
/// - **Disabled in config** — model calls bypass OpenLatch entirely. Nothing is
///   broken; nothing is captured or enforced either. A warning, and for two
///   days it was reported as a pass, which is the bug this whole contract
///   exists to close.
/// - **Wired, nothing listening** — every Claude Code session on this machine
///   dies on ECONNREFUSED. A failure.
/// - **Wired, someone ELSE listening** — the agent is sending its provider
///   credential to a process that is not us. A failure, and the more urgent one.
/// - **Listening, not wired** — agents talk straight to the provider. Nothing
///   breaks; nothing is captured either. A warning.
#[cfg(feature = "boundary")]
fn check_boundary(
    cfg: &config::Config,
    agents: &[hooks::DetectedAgent],
    probe: &DaemonProbe,
    report: &mut Report,
) {
    use crate::cli::commands::boundary::{classify_boundary, read_agent_wiring, BoundaryState};
    use crate::error::{
        ERR_BOUNDARY_NOT_RUNNING, ERR_BOUNDARY_PORT_FOREIGN, ERR_BOUNDARY_PORT_IN_USE,
        ERR_BOUNDARY_PREFLIGHT_FAILED,
    };

    let port = cfg.boundary.port;
    let config_source = config::openlatch_dir().join("config.toml");

    // Whether the loop pushed anything at all. An empty Boundary section would
    // trip `run_all_checks`' safety net and print a bug-report string on a host
    // that is behaving perfectly — and a `not_applicable` fallback would be a
    // fourth NotApplicable carve-out, which the contract forbids.
    let mut pushed_any = false;

    for a in agents {
        // An agent with NO request plane contributes no Boundary row at all.
        // It can never be wired to us, and judging it by a wiring predicate
        // reports a correct install as "not wired to it" — an actionable-
        // sounding headline for a condition the developer cannot act on.
        //
        // Every agent that HAS one is read, in its own convention:
        // `read_agent_wiring` is the one reader, so the two conventions cannot
        // disagree about what "wired to us" means. There is no Codex branch
        // below — one rendering path, fed per agent by the binding.
        let Some(w) = a.binding.boundary_wiring() else {
            continue;
        };
        pushed_any = true;

        // The file the WIRING is in: Claude Code's hooks and boundary share one
        // `settings.json`, Codex's do not. Naming the hooks file in a boundary
        // remedy sends the operator to a file we never wrote.
        let wiring_path =
            crate::hooks::boundary_config_path(&*a.binding).unwrap_or_else(|| a.settings_path());
        let wiring_path = wiring_path.as_path();
        let agent = a.agent_type();
        let display_name = a.binding.display_name();
        // The endpoint THIS agent names, in its own vocabulary, and the
        // upstream ITS wire format is checked against. Both arms below are
        // parameterised on these rather than on Claude Code's literals: a
        // remedy pointing a Codex user at `api.anthropic.com`, or at an
        // `ANTHROPIC_BASE_URL` its agent does not have, is not actionable —
        // and "off is never a pass" is about an ACTIONABLE remedy.
        let endpoint_name = boundary_endpoint_name(&w);
        let upstream = cfg.boundary.upstream_for(w.wire_format);
        let proxy_note = toml_provider_proxy_note(&w);
        let wired = read_agent_wiring(&*a.binding);
        let url = wired.as_deref().unwrap_or_default().to_string();

        match classify_boundary(cfg, agent, wired.as_deref()) {
            // Switched off. The agent talks straight to the provider: nothing is
            // captured, no policy is enforced on model traffic. The operator may
            // well want this — they are still told.
            BoundaryState::Disabled => {
                report.push(
                    Check::off(
                        Section::Boundary,
                        "Disabled in config — model calls bypass OpenLatch entirely",
                    )
                    .code(ERR_BOUNDARY_NOT_RUNNING)
                    .source(format!(
                        "{} [boundary] enabled = false",
                        config_source.display()
                    ))
                    .detail("Nothing is captured and no policy is enforced on model traffic.")
                    .remedy(
                        "Run `openlatch boundary enable` (it offers the restart that applies it).",
                    )
                    .agent(agent),
                );
            }
            // An isolated instance (non-default port) deliberately does not write
            // the machine-global agent config, so "wired" and "listening" are not
            // supposed to line up here — checking the invariant would report a
            // designed state as a defect.
            BoundaryState::Isolated => {
                report.push(
                    Check::ok(
                        Section::Boundary,
                        format!("Isolated instance on port {port}"),
                    )
                    .detail(format!(
                        "{} is machine-global and is not managed by this instance.",
                        wiring_path.display()
                    ))
                    .agent(agent),
                );
            }
            BoundaryState::Wired => {
                report.push(
                    Check::ok(
                        Section::Boundary,
                        format!("Agent wired to {url} and the listener is up"),
                    )
                    .agent(agent),
                );
            }
            BoundaryState::WiredButDown => {
                report.push(
                    Check::failed(
                        Section::Boundary,
                        format!("Agent is wired to {url} but nothing is listening there"),
                    )
                    .code(ERR_BOUNDARY_PORT_IN_USE)
                    .detail(format!(
                        "{display_name} is pointed at 127.0.0.1:{port} — its model calls fail \
                         with ECONNREFUSED."
                    ))
                    .remedy(format!(
                        "Run `openlatch start` to bring the boundary back up, or `openlatch stop` \
                         to clear the wiring and go direct.{proxy_note}"
                    ))
                    .agent(agent),
                );
            }
            BoundaryState::WiredToForeign => {
                report.push(
                    Check::failed(
                        Section::Boundary,
                        format!("Agent is wired to {url}, held by a process that is NOT OpenLatch"),
                    )
                    .code(ERR_BOUNDARY_PORT_FOREIGN)
                    .detail("Your provider API key is being sent to that process.")
                    .remedy(format!(
                        "Identify it (lsof -i :{port}), stop it, then run `openlatch restart`."
                    ))
                    .agent(agent),
                );
            }
            BoundaryState::PreflightFailed(why) => {
                report.push(
                    Check::failed(
                        Section::Boundary,
                        format!("Listener is up but its preflight failed — {why}"),
                    )
                    .code(ERR_BOUNDARY_PREFLIGHT_FAILED)
                    .detail(format!(
                        "The boundary on 127.0.0.1:{port} cannot reach the provider, so the agent \
                         was deliberately left unwired: model calls go direct and keep working, but \
                         nothing is captured."
                    ))
                    .remedy(format!(
                        "Fix reachability to {upstream} (proxy, VPN, TLS interception) — the \
                         daemon re-wires itself as soon as the check passes.{proxy_note}"
                    ))
                    .agent(agent),
                );
            }
            BoundaryState::PreflightPending => {
                report.push(
                    Check::pending(
                        Section::Boundary,
                        "Listener is up, its preflight has not finished yet",
                    )
                    .code(ERR_BOUNDARY_PREFLIGHT_FAILED)
                    .detail(format!(
                        "The boundary on 127.0.0.1:{port} is still verifying it can reach the \
                         provider; the agent is wired only once it can."
                    ))
                    .remedy("Re-run `openlatch doctor` in a moment.")
                    .agent(agent),
                );
            }
            BoundaryState::UpUnwired => {
                report.push(
                    Check::degraded(
                        Section::Boundary,
                        "Listener is up but the agent is not wired to it",
                    )
                    .code(ERR_BOUNDARY_NOT_RUNNING)
                    .detail(format!(
                        "The boundary is listening on 127.0.0.1:{port} but {display_name} has no \
                         {endpoint_name} pointing at it, so model calls bypass it entirely."
                    ))
                    .remedy("Run `openlatch restart` to re-wire.")
                    .agent(agent),
                );
            }
            // Enabled in config, consistent — and still not doing anything, because
            // nothing is listening. Consistency is not capability: this is the
            // state a stopped daemon leaves behind, and it is not green.
            BoundaryState::Down => {
                let (state_check, why) = if probe.alive {
                    (
                        Check::failed(
                            Section::Boundary,
                            "Enabled in config, but no listener holds the port",
                        ),
                        "The daemon is up and the boundary is not — its listener task did not bind.",
                    )
                } else {
                    (
                        Check::unknown(Section::Boundary, Section::Daemon)
                            .headline("Listener down — the daemon that owns it is not running"),
                        "The daemon is down, so its boundary listener is too.",
                    )
                };
                report.push(
                    state_check
                        .code(ERR_BOUNDARY_NOT_RUNNING)
                        .detail(why)
                        .remedy(if probe.alive {
                            "Check the newest ~/.openlatch/logs/daemon.log.<date> for OL-BND-PORT, \
                             then `openlatch restart`."
                        } else {
                            "Run `openlatch start`."
                        })
                        .agent(agent),
                );
            }
            // Not our port and not our wiring: someone else's process on 7600 is
            // their business, and the agent is not pointed at it. Worth saying out
            // loud, because it is also the reason the next `openlatch start` will
            // refuse to come up.
            BoundaryState::ForeignIdle => {
                report.push(
                    Check::failed(
                        Section::Boundary,
                        format!("127.0.0.1:{port} is held by another process"),
                    )
                    .code(ERR_BOUNDARY_PORT_FOREIGN)
                    .detail("The agent is not wired to it, but the next `openlatch start` will refuse to bind.")
                    .remedy(format!("Identify it (lsof -i :{port}) and stop it."))
                    .agent(agent),
                );
            }
        }
    }

    if !pushed_any {
        // Either there is no agent at all, or none whose wiring convention this
        // check knows how to read. Both are the same honest answer: the wiring
        // state is unknown. `Unknown` is still a warning — off is never a pass,
        // and a `not_applicable` here would be a fourth carve-out.
        report.push(
            Check::unknown(Section::Boundary, Section::Environment)
                .headline("Wiring state unknown — no agent config to read"),
        );
    }
}

// ---------------------------------------------------------------------------
// Section 5 — Persistence
// ---------------------------------------------------------------------------

/// Probe the OS-native supervisor and compare its actual state against
/// `config.supervision`. The comparison catches drift in both directions:
/// the user manually deleted the plist/task/unit, OR the config was never
/// updated but the supervisor is still alive.
fn check_persistence(cfg: &config::Config, report: &mut Report) {
    use crate::supervision::{select_supervisor, SupervisionMode, SupervisorKind};
    let backend = match cfg.supervision.backend {
        SupervisorKind::Launchd => "launchd",
        SupervisorKind::Systemd => "systemd",
        SupervisorKind::TaskScheduler => "task_scheduler",
        SupervisorKind::None => "none",
    };

    match (&cfg.supervision.mode, select_supervisor()) {
        (SupervisionMode::Active, Some(sup)) => match sup.status() {
            // Registered, running, but generated by an older release — the
            // restart semantics on disk are that release's, not this one's.
            // Reported, never silently rewritten: an OS-registered unit is not
            // something `doctor` should replace without being asked.
            Ok(s) if s.installed && s.running && !s.unit_current => {
                report.push(
                    Check::failed(
                        Section::Persistence,
                        format!("Running an outdated unit ({backend}, {})", s.description),
                    )
                    .code(ERR_NO_SUPERVISOR)
                    .detail(
                        "The installed unit predates this client's restart semantics — it may \
                         still use the old never-fires restart policy.",
                    )
                    .remedy("Run `openlatch supervision install` to regenerate it."),
                );
            }
            Ok(s) if s.installed && s.running => {
                report.push(Check::ok(
                    Section::Persistence,
                    format!("Active ({backend}, {})", s.description),
                ));
            }
            Ok(s) if s.installed => {
                report.push(
                    Check::failed(
                        Section::Persistence,
                        format!("Installed but the supervisor is not running ({backend})"),
                    )
                    .code(ERR_NO_SUPERVISOR)
                    .remedy(
                        "Check the OS logs, or run `openlatch supervision install` to rebuild \
                         the artifact.",
                    ),
                );
            }
            Ok(_) => {
                report.push(
                    Check::failed(
                        Section::Persistence,
                        format!("Config says active but the OS artifact is missing ({backend})"),
                    )
                    .code(ERR_NO_SUPERVISOR)
                    .detail("The artifact was deleted while config still expects it.")
                    .remedy("Run `openlatch supervision install`, or `openlatch doctor --fix`."),
                );
            }
            Err(e) => {
                report.push(
                    Check::failed(
                        Section::Persistence,
                        format!("Cannot query the supervisor ({}) — {}", e.code, e.message),
                    )
                    .code(ERR_NO_SUPERVISOR)
                    .remedy("Check that the OS supervisor is reachable from this session."),
                );
            }
        },
        // Deferred is never a choice — an install tried to register a
        // supervisor and could not.
        (SupervisionMode::Deferred, _) => {
            let reason = cfg
                .supervision
                .disabled_reason
                .as_deref()
                .unwrap_or("unknown");
            report.push(
                Check::degraded(Section::Persistence, format!("Deferred — {reason}"))
                    .code(ERR_NO_SUPERVISOR)
                    .source(format!("[supervision] disabled_reason = \"{reason}\""))
                    .detail(
                        "Nothing will restart the daemon after a crash or a reboot — and you \
                         did not choose this.",
                    )
                    .remedy(
                        "Run `openlatch supervision install` once the underlying condition is \
                         resolved (headless session, missing systemd, and so on).",
                    ),
            );
        }
        // Deliberate or not, the daemon will not survive a logout. That is a
        // real capability loss and it is reported as one; what changes with
        // deliberateness is the wording, not the mark.
        (SupervisionMode::Disabled, _) => {
            let reason = cfg
                .supervision
                .disabled_reason
                .as_deref()
                .unwrap_or("user_opt_out");
            // An isolated instance cannot be supervised at all: the unit is
            // machine-global and carries no environment, so one installed here
            // would supervise the machine's install instead. That is a property
            // of what this instance IS, not a capability it is missing — a
            // warning on every sandbox `doctor` would be noise you learn to
            // scroll past.
            if reason == "isolated_instance" {
                report.push(
                    Check::not_applicable(
                        Section::Persistence,
                        "Not applicable — an isolated instance is not machine-global",
                    )
                    .detail(
                        "Bring it up with `openlatch start`; it is not meant to survive a reboot.",
                    ),
                );
                return;
            }
            let deliberate = crate::supervision::absence_is_deliberate(Some(reason));
            let headline = if deliberate {
                format!("Disabled at your request ({reason})")
            } else {
                format!("Disabled ({reason})")
            };
            report.push(
                Check::off(Section::Persistence, headline)
                    .code(ERR_NO_SUPERVISOR)
                    .source(format!("[supervision] disabled_reason = \"{reason}\""))
                    .detail("The daemon will not restart after a logout, a reboot, or a crash.")
                    .remedy("Run `openlatch supervision enable` to re-arm it."),
            );
        }
        (SupervisionMode::Active, None) => {
            report.push(
                Check::failed(
                    Section::Persistence,
                    "Config says active but no supervisor is available on this OS",
                )
                .code(ERR_NO_SUPERVISOR)
                .remedy("Run `openlatch supervision disable` to clear the stale state."),
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Section 6 — Connection
// ---------------------------------------------------------------------------

/// How this host reaches the platform, and whether that first hop works.
///
/// Split out of `Cloud` because one section could not say which hop broke: a
/// dead proxy and a dead platform both rendered as `Cloud ✗ Egress failed`, and
/// the operator could not tell "my proxy is refusing me" from "OpenLatch is
/// down". Two rows, one outage each.
///
/// The **route** is resolved in this process from `config.toml` plus this
/// shell's environment, so it renders with or without a daemon. That is the
/// point: the proxy is the likeliest thing to be broken on a corporate host and
/// is often *why* the daemon will not start, so a row that goes blank exactly
/// then is worse than no row. The **health** of that route can only come from
/// the daemon, which is the one process actually making the calls — hence
/// `Unknown(Daemon)` rather than a guess when it is not answering.
fn check_connection(cfg: &config::Config, probe: &DaemonProbe, report: &mut Report) {
    let route = cli_route_line(cfg);

    if !probe.alive {
        report.push(
            Check::unknown(Section::Connection, Section::Daemon)
                .headline(format!("{route} (not confirmed)")),
        );
        return;
    }

    match probe.metric_str("egress_status").unwrap_or("unknown") {
        "failed" => {
            let code = egress_error_code(probe);
            let mut check = Check::failed(Section::Connection, connection_failure(cfg, code))
                .code(code)
                .remedy(egress_remedy(code))
                .detail(route);
            if let Some(message) = probe.egress_error_message() {
                check = check.detail(message);
            }
            report.push(check);
        }
        // A route that works but whose configuration resolved with warnings:
        // something the operator wrote is not doing what they think it does.
        "degraded" => report.push(
            Check::degraded(Section::Connection, route)
                .code(ERR_PROXY_CONFIG_INVALID)
                .detail(egress_warning_line(probe))
                .remedy(
                    "Run `openlatch proxy status` for the full resolution, then fix the                      setting it names.",
                ),
        ),
        _ => {
            // The route that carries this host's traffic is the one the running
            // daemon resolved, not the one in `config.toml`: `proxy set` writes
            // the file and the live process keeps its old route until it
            // restarts. Headline the daemon's, exactly as `check_update`
            // headlines the version the daemon is *serving* rather than the one
            // on disk — same disk-versus-process gap, same answer.
            if cfg.egress.url.as_deref() == probe.egress_str("proxy_url") {
                // They agree, so the file describes the live route too — and it
                // is the richer of the two renderings: only the file knows which
                // setting put the route there.
                report.push(Check::ok(Section::Connection, route));
                return;
            }
            let live = daemon_route_line(probe);
            // The two disagree. Either the file was edited since the daemon
            // started, or — on Windows — the service account resolves different
            // environment variables from an interactive shell. A restart settles
            // both: it applies an edit, and if the split survives one it is the
            // environment, which the surviving line then names.
            report.push(
                Check::degraded(Section::Connection, live)
                    .code(ERR_CONFIG_NOT_APPLIED)
                    .detail(format!("configured, not yet in use: {route}"))
                    .remedy("Run `openlatch restart` to apply it."),
            );
        }
    }
}

/// The route as *this* process resolves it — `config.toml` plus this shell's
/// environment, no daemon and no network.
///
/// Deliberately not [`daemon_route_line`], which reads what the running daemon
/// resolved: `proxy set` writes this file without restarting the process, and on
/// Windows a service account genuinely sees different environment variables from
/// an interactive shell. Collapsing the two hides both gaps.
pub fn cli_route_line(cfg: &config::Config) -> String {
    let Some(url) = cfg.egress.url.as_deref() else {
        return "direct — no proxy set".to_string();
    };
    let via = format!("via HTTP proxy {}", crate::egress::mask_userinfo(url));
    match cfg.egress.source {
        Some(source) => format!(
            "{via} (set by: {})",
            crate::cli::commands::proxy::source_str(source)
        ),
        None => via,
    }
}

/// The route the **running daemon** resolved, in the same words
/// [`cli_route_line`] uses for the file's, so a reader comparing the two is not
/// also translating between two vocabularies.
///
/// Masked, always. Falls back to a state-only line when `/admin/egress/status`
/// could not be read, so the verdict never invents a route from the CLI's own
/// environment. The auth scheme, CA source and TLS issuer the daemon also
/// reports belong in `proxy status --json`, not in a one-line verdict.
fn daemon_route_line(probe: &DaemonProbe) -> String {
    if let Some(url) = probe.egress_str("proxy_url") {
        return format!("via HTTP proxy {}", crate::egress::mask_userinfo(url));
    }
    if probe.metric_bool("proxy_in_use").unwrap_or(false) {
        return "via a proxy (run `openlatch proxy status` for the route)".to_string();
    }
    "direct — no proxy set".to_string()
}

/// What broke on the first hop, named so it cannot be confused with the second.
///
/// `OL-1231` is the platform being unreachable *through* a working proxy; every
/// other `OL-122x` is the proxy itself refusing, rejecting or failing to answer.
fn connection_failure(cfg: &config::Config, code: &'static str) -> String {
    let hop = match cfg.egress.url.as_deref() {
        Some(url) => format!("proxy {}", crate::egress::mask_userinfo(url)),
        None => "the network".to_string(),
    };
    if code == ERR_CLOUD_UNREACHABLE {
        format!("Cannot reach {} through {hop}", cfg.cloud.api_url)
    } else {
        format!("Cannot reach {hop}")
    }
}

// ---------------------------------------------------------------------------
// Section 6 — Cloud
// ---------------------------------------------------------------------------

fn check_cloud(cfg: &config::Config, probe: &DaemonProbe, report: &mut Report) {
    if !probe.alive {
        report.push(
            Check::unknown(Section::Cloud, Section::Daemon)
                .headline("Forwarding state unknown — the daemon is not answering"),
        );
        return;
    }
    let Some(_) = probe.metrics.as_ref() else {
        report.push(
            Check::failed(
                Section::Cloud,
                "Could not read the daemon's /metrics — the daemon may be unhealthy",
            )
            .code(ERR_DAEMON_START_FAILED)
            .remedy("Run `openlatch restart`."),
        );
        return;
    };

    let status = probe.metric_str("cloud_status").unwrap_or("unknown");
    let api_url = probe
        .metric_str("cloud_api_url")
        .unwrap_or(cfg.cloud.api_url.as_str())
        .to_string();
    let drops = probe.metric_u64("cloud_drop_count").unwrap_or(0);
    let pending = probe.metric_u64("outbox_pending_count").unwrap_or(0);

    // TRANSPORT BEFORE CREDENTIAL. A host behind a dead proxy has no working
    // route to the platform, so `cloud_status` reads `no_credential` or
    // `network_error` for a reason that has nothing to do with either — and
    // "run `openlatch auth login`" is then the single least useful sentence the
    // tool can print. Whoever is actually broken renders first.
    let egress = probe.metric_str("egress_status").unwrap_or("unknown");
    if egress == "failed" {
        report.push(
            Check::unknown(Section::Cloud, Section::Connection)
                .headline("Cannot confirm — this host has no working route out"),
        );
        return;
    }

    match status {
        "connected" => {
            let forwarded = probe.metric_u64("cloud_forwarded_count").unwrap_or(0);
            // The route and any warning about it belong to `Connection`; this
            // row is only about the thing at the far end of it.
            let mut check = Check::ok(
                Section::Cloud,
                format!("Connected: {api_url} ({forwarded} event(s) forwarded)"),
            );
            if pending > 0 {
                check = check.detail(format!("{pending} event(s) still draining from the outbox"));
            }
            report.push(check);
        }
        // Unreachable is degraded, not failed, *while the outbox is holding*:
        // nothing is lost, the events replay when the platform comes back. It
        // becomes a failure only once the spool is gone.
        "network_error" => {
            let outbox_on = cfg.cloud.outbox_enabled;
            let headline = format!("Cannot reach {api_url}");
            let check = if outbox_on {
                Check::degraded(Section::Cloud, headline)
                    .detail(format!("{pending} event(s) buffered — nothing lost yet"))
            } else {
                Check::failed(Section::Cloud, headline)
                    .detail(format!("{drops} event(s) dropped — the outbox is disabled"))
            };
            report.push(
                check
                    .code(ERR_CLOUD_UNREACHABLE)
                    .remedy(format!("Check network connectivity to {api_url}.")),
            );
        }
        "auth_error" => {
            report.push(
                Check::failed(Section::Cloud, format!("Credential rejected by {api_url}"))
                    .code(ERR_CLOUD_AUTH_FAILED)
                    .remedy("Run `openlatch auth login` to refresh the credential."),
            );
        }
        // No credential is a failure, not an "off" — see the doc comment.
        "no_credential" | "not_configured" => {
            report.push(
                Check::failed(
                    Section::Cloud,
                    format!("No credential — forwarding paused ({api_url})"),
                )
                .code(ERR_NO_CREDENTIALS)
                .detail(format!(
                    "{pending} event(s) are accumulating locally and reach nobody."
                ))
                .remedy("Run `openlatch auth login` to store an API key."),
            );
        }
        other => {
            report.push(
                Check::failed(Section::Cloud, format!("Unknown status '{other}'"))
                    .code(ERR_BUG)
                    .remedy("Please report this with `openlatch doctor --rescue`."),
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Section 7 — Policy
// ---------------------------------------------------------------------------

/// The local policy plane: on, armed with a bundle, and polling.
fn check_policy(cfg: &config::Config, probe: &DaemonProbe, report: &mut Report) {
    if !cfg.policy.enabled {
        report.push(
            Check::off(
                Section::Policy,
                "Disabled in config — no rule is evaluated on this host",
            )
            .code(ERR_POLICY_DISABLED)
            .source("[policy] enabled = false")
            .detail("Every action is allowed; any bundle on disk is not consulted.")
            .remedy("Remove `enabled = false` from the [policy] block, then `openlatch restart`."),
        );
        return;
    }
    if !probe.alive || probe.metrics.is_none() {
        report.push(
            Check::unknown(Section::Policy, Section::Daemon)
                .headline("Enforcement state unknown — the daemon is not answering"),
        );
        return;
    }

    // `has_bundle == false` is not the same as a stale bundle: it means nothing
    // has ever been activated, so the host allows everything. Conflating the
    // two is how a client silently disarms on first boot and nobody notices.
    //
    // Which of the three shapes it takes depends on *why* there is no bundle,
    // and the difference matters: a daemon thirty seconds old has not finished
    // its first poll, a host that cannot reach the platform cannot have one at
    // all, and only the third case — connected, settled, still empty — is a
    // defect this host can act on.
    if !probe.metric_bool("policy_has_bundle").unwrap_or(false) {
        /// How long a fresh daemon gets to complete its first poll before an
        /// empty policy plane counts as a defect. Generous on purpose: the
        /// first poll competes with everything else a daemon does at boot, and
        /// a diagnostic that cries wolf during startup gets ignored during
        /// steady state.
        const FIRST_POLL_GRACE_SECS: u64 = 120;

        let check = if report.section_state(Section::Cloud) != State::Ok {
            // No platform, no bundle. One outage, one cross — and it is the
            // Cloud section's.
            Check::unknown(Section::Policy, Section::Cloud)
                .detail("No bundle can be fetched while the platform is unreachable.")
        } else if probe.uptime_secs.unwrap_or(u64::MAX) < FIRST_POLL_GRACE_SECS {
            Check::pending(Section::Policy, "First bundle poll has not landed yet")
                .code(ERR_BUNDLE_FETCH_FAILED)
                .remedy("Re-run `openlatch doctor` in a moment.")
        } else {
            Check::failed(
                Section::Policy,
                "No bundle resident — nothing is being enforced",
            )
            .code(ERR_BUNDLE_FETCH_FAILED)
            .detail("The platform is reachable but no bundle has ever been activated.")
            .remedy("Check the newest ~/.openlatch/logs/daemon.log.<date> for `target=policy`.")
        };
        report.push(check);
        return;
    }

    let revision = probe
        .metrics
        .as_ref()
        .and_then(|m| m.get("policy_revision"))
        .map(|v| v.to_string())
        .unwrap_or_else(|| "?".into());

    match probe.metric_u64("policy_last_poll_ok_secs") {
        // A resident bundle keeps enforcing whatever it last activated, so a
        // stale poll is a freshness problem, not an enforcement outage.
        Some(secs) if secs > cfg.policy.stale_warn_after_secs => {
            report.push(
                Check::degraded(
                    Section::Policy,
                    format!(
                        "Bundle {revision} is enforcing, but no successful poll for {}h",
                        secs / 3600
                    ),
                )
                .code(ERR_BUNDLE_STALE)
                .detail("The resident bundle keeps enforcing; it may no longer match the platform.")
                .remedy("Fix cloud connectivity above — the poller recovers on its own."),
            );
        }
        Some(secs) => {
            report.push(Check::ok(
                Section::Policy,
                format!("Bundle {revision} fresh (polled {secs}s ago)"),
            ));
        }
        None => {
            report.push(
                Check::degraded(
                    Section::Policy,
                    format!("Bundle {revision} is enforcing, but no poll has ever succeeded"),
                )
                .code(ERR_BUNDLE_STALE)
                .remedy("Fix cloud connectivity above — the poller recovers on its own."),
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Section 8 — Inventory
// ---------------------------------------------------------------------------

/// The configuration-plane monitor.
fn check_inventory(cfg: &config::Config, probe: &DaemonProbe, report: &mut Report) {
    if !cfg.inventory_monitor.enabled {
        report.push(
            Check::off(
                Section::Inventory,
                "Disabled in config — config drift is not observed",
            )
            .code(ERR_INVENTORY_DISABLED)
            .source("[inventory_monitor] enabled = false")
            .remedy(
                "Remove `enabled = false` from the [inventory_monitor] block, then \
                 `openlatch restart`.",
            ),
        );
        return;
    }
    if !probe.alive || !probe.reachable {
        report.push(
            Check::unknown(Section::Inventory, Section::Daemon)
                .headline("Monitor state unknown — the daemon is not answering"),
        );
        return;
    }

    let token = std::fs::read_to_string(config::openlatch_dir().join("daemon.token"))
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    let url = format!("http://127.0.0.1:{}/admin/inventory/status", cfg.port);
    let res = crate::egress::blocking_client()
        .get(&url)
        .bearer_auth(&token)
        .timeout(std::time::Duration::from_secs(2))
        .send();

    match res {
        Ok(r) if r.status().is_success() => {
            let body: serde_json::Value = r.json().unwrap_or(serde_json::json!({}));
            let sources = body.get("cache_size").and_then(|v| v.as_u64()).unwrap_or(0);
            let manifest = body
                .get("manifest_loaded")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            if manifest {
                report.push(Check::ok(
                    Section::Inventory,
                    format!("Monitor up, {sources} source(s) tracked"),
                ));
            } else {
                report.push(
                    Check::degraded(
                        Section::Inventory,
                        format!("Monitor up but no manifest loaded ({sources} source(s) cached)"),
                    )
                    .code(ERR_INVENTORY_INIT_FAILED)
                    .remedy("Run `openlatch inventory rescan`."),
                );
            }
        }
        // A 401 here is a token drift, not a monitor problem — and it used to
        // print "Daemon responded with HTTP 401 Unauthorized" and exit 0.
        Ok(r) if r.status().as_u16() == 401 => {
            report.push(
                Check::failed(
                    Section::Inventory,
                    "Daemon rejected the admin token (401) — daemon.token has drifted",
                )
                .code(ERR_HOOK_CONFLICT)
                .detail(
                    "The running daemon loaded a different token than the one now on disk; \
                     `init` regenerates it without restarting an already-running daemon.",
                )
                .remedy("Run `openlatch restart`."),
            );
        }
        Ok(r) => {
            report.push(
                Check::failed(
                    Section::Inventory,
                    format!("Daemon responded HTTP {}", r.status().as_u16()),
                )
                .code(ERR_INVENTORY_INIT_FAILED)
                .remedy("Check the newest ~/.openlatch/logs/daemon.log.<date>."),
            );
        }
        Err(e) => {
            report.push(
                Check::failed(
                    Section::Inventory,
                    format!("Cannot reach the monitor — {e}"),
                )
                .code(ERR_INVENTORY_INIT_FAILED)
                .remedy("Run `openlatch restart`."),
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Section 9 — Telemetry
// ---------------------------------------------------------------------------

/// Anonymous usage telemetry consent.
///
/// Deliberately [`State::NotApplicable`] when off, not [`State::Off`]. Every
/// other section warns about a disabled feature because the disabled state
/// costs the operator something. Telemetry is the opposite: it is a privacy
/// opt-out, it costs them nothing, and nagging about an exercised opt-out is a
/// dark pattern.
fn check_telemetry(ol_dir: &std::path::Path, report: &mut Report) {
    let consent_path = crate::telemetry::consent_file_path(ol_dir);
    let resolved = crate::telemetry::consent::resolve(&consent_path);
    if resolved.enabled() {
        report.push(Check::ok(Section::Telemetry, "Enabled — thank you"));
    } else {
        report.push(Check::not_applicable(
            Section::Telemetry,
            "Disabled by user (opt-out honoured)",
        ));
    }
}

// ---------------------------------------------------------------------------
// Section 10 — Update
// ---------------------------------------------------------------------------

/// Drift between what is installed and what is running, plus the auto-update
/// install-state canary.
fn check_update(cfg: &config::Config, probe: &DaemonProbe, report: &mut Report) {
    // An upgrade that reached the disk but not the process. Every other signal
    // on the machine looks healthy — the package manager succeeded, the binary
    // on disk really is new, and the daemon answers 200 — so nothing but this
    // comparison catches it. On a security client it means a fix the user
    // installed is not running.
    let installed = env!("OPENLATCH_VERSION");
    match probe
        .health
        .as_ref()
        .and_then(|h| h.get("version"))
        .and_then(|v| v.as_str())
    {
        Some(running) if running != installed => {
            report.push(
                Check::degraded(
                    Section::Update,
                    format!("Daemon is serving {running}, {installed} is installed on disk"),
                )
                .code(ERR_VERSION_OUTDATED)
                .detail("A package manager replaces the binary; it does not restart the process.")
                .remedy("Run `openlatch restart`."),
            );
        }
        Some(_) => report.push(Check::ok(
            Section::Update,
            format!("Daemon is serving the installed version ({installed})"),
        )),
        None => report.push(Check::ok(
            Section::Update,
            format!("Installed version {installed}"),
        )),
    }

    check_auto_update_drift(cfg, report);
}

/// Auto-update install-state drift check (P2 § 6).
///
/// Warns when:
/// 1. install-state.json reports `install_method == npm`, AND
/// 2. `actual_binary_version != npm_reported_version`, AND
/// 3. `last_updated_at` is more than 30 days in the past, AND
/// 4. `auto_update == true` in config.
///
/// The 30-day threshold is the canary: if auto-update is supposedly on but no
/// apply has happened in a month, the worker is likely silently broken — and
/// the user is exposed.
fn check_auto_update_drift(cfg: &config::Config, report: &mut Report) {
    use crate::install_state::{InstallMethod, InstallState};
    let state = InstallState::load_or_default();
    let (Some(actual), Some(npm)) = (
        state.actual_binary_version.as_deref(),
        state.npm_reported_version.as_deref(),
    ) else {
        // Nothing to compare yet — fresh install, or no auto-update has ever
        // applied.
        return;
    };
    // Drift detection is only meaningful for npm-managed installs.
    if !matches!(state.install_method, InstallMethod::Npm) {
        return;
    }
    if actual == npm {
        report.push(Check::ok(
            Section::Update,
            format!("Auto-update in sync (npm={npm}, binary={actual})"),
        ));
        return;
    }

    let last_update = state.last_updated_at.as_deref();
    let stale_drift = last_update
        .and_then(|ts| chrono::DateTime::parse_from_rfc3339(ts).ok())
        .map(|t| (chrono::Utc::now() - t.with_timezone(&chrono::Utc)).num_days() > 30)
        .unwrap_or(false);

    if stale_drift && cfg.update.auto_update {
        report.push(
            Check::failed(
                Section::Update,
                format!(
                    "Auto-update drift unchanged for >30d (npm={npm}, binary={actual}, last={})",
                    last_update.unwrap_or("?")
                ),
            )
            .code(ERR_VERSION_OUTDATED)
            .detail("Auto-update appears stalled.")
            .remedy(format!(
                "Run `npm install -g @openlatch/client@{actual}` to resync, then check the \
                 daemon log for `target=update` errors."
            )),
        );
    } else {
        // Drift exists but is fresh — that's the *expected* state right after
        // an auto-update.
        report.push(
            Check::degraded(
                Section::Update,
                format!("Cosmetic drift (binary {actual} > npm {npm})"),
            )
            .code(ERR_VERSION_OUTDATED)
            .detail("Expected right after an auto-update.")
            .remedy(format!(
                "Run `npm install -g @openlatch/client@{actual}` to sync the package manager."
            )),
        );
    }
}

// ---------------------------------------------------------------------------
// Section 11 — Integrity
// ---------------------------------------------------------------------------

/// The tamper-evidence plane: the HMAC key that signs hook markers, and whether
/// anything has rewritten `settings.json` behind the reconciler's back.
fn check_integrity(ol_dir: &std::path::Path, probe: &DaemonProbe, report: &mut Report) {
    let key_path = ol_dir.join("hmac.key");
    if key_path.exists() {
        report.push(Check::ok(
            Section::Integrity,
            "HMAC key present — hook markers are signed",
        ));
    } else {
        report.push(
            Check::failed(
                Section::Integrity,
                format!("HMAC key missing: {}", key_path.display()),
            )
            .code(ERR_HMAC_KEY_UNAVAILABLE)
            .detail("Hook markers cannot be verified, so tampering cannot be detected.")
            .remedy("Run `openlatch init` to regenerate it."),
        );
    }

    // Tamper events since the daemon came up. A heal is the happy path, but a
    // machine that keeps producing them has something else rewriting
    // settings.json, and the next write may land where the reconciler is not
    // looking.
    let tamper_path = ol_dir.join("tamper.jsonl");
    let Some(uptime) = probe.uptime_secs else {
        return;
    };
    let Ok(meta) = std::fs::metadata(&tamper_path) else {
        return;
    };
    let Ok(mtime) = meta.modified() else {
        return;
    };
    let daemon_start = std::time::SystemTime::now()
        .checked_sub(std::time::Duration::from_secs(uptime))
        .unwrap_or(std::time::UNIX_EPOCH);
    if mtime > daemon_start {
        report.push(
            Check::degraded(
                Section::Integrity,
                "Tamper events recorded since the daemon started",
            )
            .code(ERR_TAMPER_DETECTED)
            .detail("Something rewrote the agent's hook entries; the reconciler healed them.")
            .remedy("Inspect them with `openlatch logs --tamper`."),
        );
    }
}

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

/// Render a [`DoctorReport`] using the configured output format, and record the
/// exit status it implies.
pub(crate) fn print_diagnostic_results(report: &DoctorReport, output: &OutputConfig) {
    // Recorded whatever the format: a `--json` consumer gates on the exit code
    // exactly like a human reads the marks.
    report.report.record_verdict();

    if output.format == OutputFormat::Json {
        output.print_json(&report.report.to_json());
        return;
    }
    if output.quiet {
        return;
    }

    report.report.render(output);

    // No per-issue footer. Each section block above already carries its own
    // cause, source and remedy — reprinting them here doubled the output and
    // put the same sentence on screen twice, which is how the one line that
    // mattered got lost. What the footer adds is the single next move.
    let counts = report.report.counts();
    if counts.failed == 0 && counts.warned == 0 {
        eprintln!("All checks passed.");
        return;
    }

    if let Some(next) = suggested_next_step(report) {
        eprintln!("Next: {next}");
    }
}

/// Render one section in full, for the per-subsystem status commands.
///
/// `openlatch hooks status` and friends each need the detail of exactly one
/// section, with its codes and remedies. Re-deriving that per command is how
/// `hooks status` ended up an alias of `status` — it was easier than writing a
/// fourth hook inspector — and how the three boundary commands came to
/// disagree. One set of detectors, sliced.
///
/// # Errors
///
/// Propagates a config that cannot be loaded; the sections themselves report
/// their own failures rather than returning them.
pub fn run_section(section: Section, output: &OutputConfig) -> Result<(), OlError> {
    run_section_inner(section, output, true)
}

/// Append one section's verdict to a command that already printed its own
/// detail — `supervision status`, `inventory status`.
///
/// Same detectors, same marks, same exit contract; the command keeps the
/// subsystem-specific facts it is good at and stops having a private opinion
/// about whether they add up to healthy.
///
/// # Errors
///
/// Propagates a config that cannot be loaded.
/// In JSON mode this records the verdict and prints NOTHING. The caller already
/// printed a document, and `--json` is one document per invocation — appending a
/// second is how `supervision status --json` came to emit `{...}{...}`, which no
/// parser accepts. JSON callers merge instead, with [`with_section_verdict`].
pub fn append_section_verdict(section: Section, output: &OutputConfig) -> Result<(), OlError> {
    let one = section_report(section, output)?;
    if output.format == OutputFormat::Json || output.quiet {
        return Ok(());
    }
    one.render_section(section, output);
    Ok(())
}

/// Carry one section's verdict *inside* a body the caller is about to print.
///
/// The JSON counterpart of [`append_section_verdict`]: same detectors, same
/// recorded exit code, but the verdict lands under `verdict` in the caller's own
/// object instead of in a second document after it. A non-object body is nested
/// under `body` rather than dropped, so the verdict always has somewhere to go.
///
/// # Errors
///
/// Propagates a config that cannot be loaded.
pub fn with_section_verdict(
    body: serde_json::Value,
    section: Section,
    output: &OutputConfig,
) -> Result<serde_json::Value, OlError> {
    let one = section_report(section, output)?;
    Ok(merge_verdict(body, section_verdict_value(&one, section)))
}

/// Nest *verdict* inside *body*. Split out of [`with_section_verdict`] so the
/// merge can be tested without a host for the detectors to run against.
fn merge_verdict(body: serde_json::Value, verdict: serde_json::Value) -> serde_json::Value {
    let mut doc = match body {
        serde_json::Value::Object(map) => serde_json::Value::Object(map),
        other => serde_json::json!({ "body": other }),
    };
    doc["verdict"] = verdict;
    doc
}

/// The one-section report every entry point above renders, with its verdict
/// already recorded against the process exit code.
fn section_report(section: Section, output: &OutputConfig) -> Result<Report, OlError> {
    let full = run_all_checks(output)?;
    let mut one = Report::new();
    for check in full.report.section_checks(section) {
        one.push(check.clone());
    }

    // Sections this view defers its verdict to. `State::Unknown(blocker)` says
    // "the verdict is not mine to give, it is theirs" — so the blocker's real
    // checks have to be in the report the exit code is computed from. Filling
    // them with `not_applicable` instead is what let `proxy status` exit 7
    // (degraded) on a host `doctor` calls broken (1): the `Daemon` `Failed` that
    // owned the verdict was dropped, leaving the anti-cascade warning as the
    // whole answer. One outage, two exit codes, from the module whose contract
    // is one.
    //
    // Walked transitively — `Policy` defers to `Cloud`, which defers to `Daemon`
    // — behind a visited set, because nothing structurally forbids a cycle.
    // `render_section` prints only `section`, so carrying the blockers moves the
    // exit code and nothing on screen.
    let blockers = blockers_of(&full.report, section);

    // Fill the rest so the shared renderer's own P6 assertion holds; only the
    // requested section is printed.
    for other in Section::ALL {
        if other == section {
            continue;
        }
        // Empty when `other` is not a blocker, and also when it is one that
        // contributed no checks — a blocker with nothing to say must still be
        // represented, or P6 fails on a report nobody can see.
        let carried: Vec<&Check> = if blockers.contains(&other) {
            full.report.section_checks(other).collect()
        } else {
            Vec::new()
        };
        if carried.is_empty() {
            one.push(Check::not_applicable(other, "not part of this view"));
        } else {
            for check in carried {
                one.push(check.clone());
            }
        }
    }

    one.record_verdict();
    Ok(one)
}

/// The sections *section*'s own checks hand their verdict to — one hop, not the
/// whole chain. Split out so [`blockers_of`] can walk it transitively.
fn deferred_to(report: &Report, section: Section) -> Vec<Section> {
    report
        .section_checks(section)
        .filter_map(|c| match c.state {
            State::Unknown(blocker) => Some(blocker),
            _ => None,
        })
        .collect()
}

/// Every section *section* ultimately depends on for its verdict, following the
/// chain to the end.
///
/// Transitive because the chain is: `Policy` defers to `Cloud`, which defers to
/// `Daemon`, and only `Daemon` holds the failure that owns the exit code. Guarded
/// by a visited set — nothing structurally forbids a cycle, and one would hang
/// the CLI rather than fail it. *section* itself is never a blocker of itself.
fn blockers_of(report: &Report, section: Section) -> Vec<Section> {
    let mut seen: Vec<Section> = Vec::new();
    let mut pending = deferred_to(report, section);
    while let Some(blocker) = pending.pop() {
        if blocker == section || seen.contains(&blocker) {
            continue;
        }
        seen.push(blocker);
        pending.extend(deferred_to(report, blocker));
    }
    seen
}

/// One section's verdict as JSON — the same object `run_section` prints alone
/// and `with_section_verdict` nests.
fn section_verdict_value(one: &Report, section: Section) -> serde_json::Value {
    let checks: Vec<serde_json::Value> = one.section_checks(section).map(|c| c.to_json()).collect();
    serde_json::json!({
        "section": section.key(),
        "state": one.section_state(section).key(),
        "checks": checks,
        "exit_code": one.exit_code(),
    })
}

fn run_section_inner(
    section: Section,
    output: &OutputConfig,
    with_header: bool,
) -> Result<(), OlError> {
    let one = section_report(section, output)?;

    if output.format == OutputFormat::Json {
        output.print_json(&section_verdict_value(&one, section));
        return Ok(());
    }
    if output.quiet {
        return Ok(());
    }

    if with_header {
        crate::cli::header::print(output, &[section.key(), "status"]);
    }
    one.render_section(section, output);
    Ok(())
}

/// The one command most likely to move the user forward, derived from the
/// issues actually present.
///
/// Replaces a hardcoded "Run 'openlatch init' to fix hook installation", which
/// was printed for every issue including the many that `init` does not touch. A
/// suggestion that is wrong most of the time is worse than none, so this returns
/// `None` when the issues do not point anywhere in particular — the per-issue
/// lines above already carry their own instructions.
fn suggested_next_step(report: &DoctorReport) -> Option<&'static str> {
    let issues = report.report.issues();
    let mentions = |needle: &str| issues.iter().any(|i| i.contains(needle));

    // Ordered by how much each command resolves at once, not by how the checks
    // happen to be listed. `restart` comes first because a daemon running an
    // older binary — or an older token — is a single root cause that surfaces
    // as several unrelated-looking failures at once: a 401 from the admin
    // endpoints, hooks spooling to fallback.jsonl, and a version drift. Sending
    // that operator to `init` instead, as this used to, rotates the token and
    // breaks capture in every session currently running.
    if mentions("openlatch restart") {
        Some("run 'openlatch restart' — a daemon out of step with the installed binary explains several of these at once")
    } else if mentions("openlatch start") {
        Some("run 'openlatch start' to bring the daemon back up")
    } else if mentions("openlatch auth login") {
        Some("run 'openlatch auth login' — nothing reaches the platform without a credential")
    } else if mentions("openlatch boundary enable") {
        Some("run 'openlatch boundary enable' to route model calls through OpenLatch")
    } else if mentions("openlatch supervision") {
        Some("run 'openlatch supervision enable' to make the daemon survive a reboot")
    } else if mentions("openlatch init") {
        Some("run 'openlatch init' to repair the hook installation")
    } else if report.fail_count() > 0 {
        Some("run 'openlatch doctor --fix' to attempt an automatic repair")
    } else {
        None
    }
}

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

    // -----------------------------------------------------------------------
    // Per-agent checks, driven through the test-only second binding
    // -----------------------------------------------------------------------
    //
    // Claude Code's own binding cannot exercise these two rows: it answers
    // `armed: None` and an `EnvVars` endpoint convention by definition, which
    // are precisely the answers the rows leave alone. A settable fake is the
    // only way to reach the branches that behave differently.

    use crate::hooks::binding::test_support::FakeBinding;
    use crate::hooks::binding::LivenessReport;
    use crate::hooks::{AgentKind, DetectedAgent};
    use std::sync::Arc;

    /// A daemon that is not running: `check_fallback_activity` returns
    /// immediately without a live daemon, so nothing in these fixtures depends
    /// on the machine the tests run on.
    fn dead_probe() -> DaemonProbe {
        DaemonProbe {
            alive: false,
            reachable: false,
            health: None,
            metrics: None,
            egress: None,
            uptime_secs: None,
        }
    }

    /// A settings.json holding an OpenLatch-owned entry for each of the three
    /// load-bearing events, so `health::inspect_file` reports a complete
    /// install and `check_hooks` reaches the liveness renderer.
    fn installed_agent(dir: &std::path::Path, liveness: LivenessReport) -> DetectedAgent {
        let entry = || {
            serde_json::json!({
                "matcher": "",
                "_openlatch": { "v": 1, "id": "x" },
                "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event x" }]
            })
        };
        std::fs::write(
            dir.join("settings.json"),
            serde_json::json!({
                "hooks": {
                    "PreToolUse": [entry()],
                    "UserPromptSubmit": [entry()],
                    "Stop": [entry()],
                }
            })
            .to_string(),
        )
        .expect("write settings.json");

        DetectedAgent {
            kind: AgentKind::ClaudeCode,
            binding: Arc::new(FakeBinding {
                agent_type: "cursor",
                display_name: "Cursor",
                config_dir: dir.to_path_buf(),
                liveness,
                ..Default::default()
            }),
        }
    }

    fn hooks_checks(liveness: LivenessReport) -> Vec<Check> {
        let dir = tempfile::tempdir().expect("temp dir");
        let agents = vec![installed_agent(dir.path(), liveness)];
        let mut report = Report::new();
        check_hooks(
            dir.path(),
            &agents,
            None,
            &config::Config::defaults(),
            &dead_probe(),
            &mut report,
        );
        report.section_checks(Section::Hooks).cloned().collect()
    }

    /// `armed: None` means *this agent has no arming concept* — installed is
    /// armed — and the renderer must add **nothing** for it. That is what keeps
    /// a single-Claude-Code host's report byte-identical to the one before the
    /// liveness question existed.
    ///
    /// Asserted as a difference rather than an absence: the same fixture with
    /// `Some(true)` gains exactly one check, so "adds zero" is measured, not
    /// inferred from a headline that could be renamed.
    #[test]
    fn liveness_none_pushes_no_check() {
        let silent = hooks_checks(LivenessReport {
            armed: None,
            detail: None,
            remedy: None,
            code: None,
        });
        let armed = hooks_checks(LivenessReport {
            armed: Some(true),
            detail: Some("policy bundle is enforcing".into()),
            remedy: None,
            code: None,
        });

        assert_eq!(
            armed.len(),
            silent.len() + 1,
            "a proven-armed binding adds exactly one check, so `None` added none"
        );
        assert!(
            !silent.iter().any(|c| c.headline == "Enforced"),
            "`None` must not be rendered as a proven `true`: {:?}",
            silent.iter().map(|c| &c.headline).collect::<Vec<_>>()
        );
        let enforced = armed
            .iter()
            .find(|c| c.headline == "Enforced")
            .expect("the extra check is the Enforced one");
        assert_eq!(enforced.state, State::Ok);
        assert_eq!(enforced.agent, Some("cursor"));
        assert_eq!(
            enforced.detail,
            vec!["policy bundle is enforcing".to_string()]
        );
    }

    /// Installed and capturing while enforcing nothing is a **failure**, not a
    /// pass with a note — and `Check::validate` refuses a failure without a code
    /// and a remedy, so the report's own `code` has to survive onto the check.
    #[test]
    fn liveness_some_false_is_failed_and_carries_its_code() {
        let checks = hooks_checks(LivenessReport {
            armed: Some(false),
            detail: Some("the agent has not trusted this project".into()),
            remedy: Some("Trust this project in the agent, then re-run `openlatch doctor`.".into()),
            code: Some(ERR_HOOK_CONFLICT),
        });

        let monitored = checks
            .iter()
            .find(|c| c.headline.starts_with("Monitored"))
            .expect("a Some(false) liveness renders a Monitored check");

        assert_eq!(monitored.state, State::Failed);
        assert_eq!(monitored.code, Some(ERR_HOOK_CONFLICT));
        assert_eq!(
            monitored.remedy.as_deref(),
            Some("Trust this project in the agent, then re-run `openlatch doctor`.")
        );
        assert_eq!(
            monitored.detail,
            vec!["the agent has not trusted this project".to_string()]
        );
        assert_eq!(monitored.agent, Some("cursor"));
        assert!(
            monitored.validate().is_none(),
            "a failed check must satisfy the code+remedy contract"
        );
    }

    /// An agent with no request plane at all cannot carry a base-URL
    /// environment key, so asking whether it does and reporting "the agent is
    /// not wired to it" diagnoses a correct install as broken. The check is
    /// skipped, and the honest section-level answer — wiring state unknown —
    /// is what remains.
    #[test]
    #[cfg(feature = "boundary")]
    fn boundary_check_skips_an_agent_without_a_request_plane() {
        let agents = vec![DetectedAgent {
            kind: AgentKind::ClaudeCode,
            binding: Arc::new(FakeBinding {
                agent_type: "cursor",
                // `boundary_wiring` defaults to `None` — an agent with no
                // request plane. The `TomlProvider` case is a later unit's.
                ..Default::default()
            }),
        }];
        let mut report = Report::new();
        check_boundary(
            &config::Config::defaults(),
            &agents,
            &dead_probe(),
            &mut report,
        );

        let checks: Vec<&Check> = report.section_checks(Section::Boundary).collect();
        assert!(
            !checks.iter().any(|c| c.agent == Some("cursor")),
            "no per-agent Boundary check may be pushed for an agent with no request plane: {:?}",
            checks.iter().map(|c| &c.headline).collect::<Vec<_>>()
        );
        assert_eq!(
            checks.len(),
            1,
            "the section still carries exactly one check — an empty section trips the ERR_BUG net"
        );
        assert_eq!(
            checks[0].headline,
            "Wiring state unknown — no agent config to read"
        );
        assert_eq!(checks[0].state, State::Unknown(Section::Environment));
        assert_eq!(checks[0].agent, None, "the fallback belongs to no agent");
    }

    /// The `TomlProvider` convention gets a Boundary row of its own, read
    /// through the same one reader and rendered through the same arms — and
    /// those arms speak the AGENT'S vocabulary, not Claude Code's.
    ///
    /// "Off is never a pass" is about an ACTIONABLE remedy. A Codex row
    /// rendered through the untouched arms tells the user to fix reachability
    /// to `api.anthropic.com` and to look for an `ANTHROPIC_BASE_URL` its agent
    /// does not have. `.remedy != null` is satisfied by exactly that wrong
    /// answer, so the strings are asserted too.
    #[test]
    #[cfg(feature = "boundary")]
    fn boundary_check_reads_the_toml_convention() {
        use crate::boundary::wire_format::WireFormat;
        use crate::hooks::binding::{BoundaryWiring, EndpointConvention};

        fn codex_agent(dir: &std::path::Path) -> DetectedAgent {
            DetectedAgent {
                kind: AgentKind::ClaudeCode,
                binding: Arc::new(FakeBinding {
                    agent_type: "codex-cli",
                    display_name: "Codex CLI",
                    config_dir: dir.to_path_buf(),
                    boundary_wiring: Some(BoundaryWiring {
                        wire_format: WireFormat::OpenAiResponses,
                        endpoint: EndpointConvention::TomlProvider {
                            provider_name: "openlatch",
                            wire_api: "responses",
                        },
                        install_id_header: "x-openlatch-install-id",
                    }),
                    ..Default::default()
                }),
            }
        }

        let tmp = tempfile::tempdir().expect("tempdir");
        let config_toml = tmp.path().join("config.toml");
        let cfg = config::Config::defaults();

        // --- wired: our loopback provider table is in `config.toml` ---------
        std::fs::write(
            &config_toml,
            "model_provider = \"openlatch\"\n\n\
             [model_providers.openlatch]\n\
             name = \"OpenLatch boundary\"\n\
             base_url = \"http://127.0.0.1:7600/v1\"\n",
        )
        .expect("seed config.toml");

        let mut report = Report::new();
        check_boundary(&cfg, &[codex_agent(tmp.path())], &dead_probe(), &mut report);
        let checks: Vec<&Check> = report.section_checks(Section::Boundary).collect();
        assert_eq!(checks.len(), 1, "one row for the one agent with a plane");
        assert_eq!(checks[0].agent, Some("codex-cli"));
        assert!(
            checks[0].headline.contains("127.0.0.1:7600"),
            "the row must name what the agent is wired to, read through the TOML \
             convention: {:?}",
            checks[0].headline
        );

        // --- not wired: the table is gone -----------------------------------
        std::fs::write(&config_toml, "model = \"gpt-5-codex\"\n").expect("rewrite");
        let mut report = Report::new();
        check_boundary(&cfg, &[codex_agent(tmp.path())], &dead_probe(), &mut report);
        let checks: Vec<&Check> = report.section_checks(Section::Boundary).collect();
        assert_eq!(checks.len(), 1);
        let row = checks[0];
        assert_eq!(row.agent, Some("codex-cli"));
        assert_ne!(
            row.state,
            State::Ok,
            "an absent request plane is never green"
        );
        let remedy = row.remedy.clone().unwrap_or_default();
        let detail = row.detail.join(" ");
        assert!(
            !remedy.is_empty(),
            "a non-green Boundary row must carry a remedy"
        );
        assert!(
            !remedy.contains("api.anthropic.com"),
            "a Codex row must not send the user at Anthropic's host: {remedy}"
        );
        assert!(
            !remedy.contains("ANTHROPIC_BASE_URL") && !detail.contains("ANTHROPIC_BASE_URL"),
            "Codex has no such variable — its pointer is `model_provider`: {detail} / {remedy}"
        );
        assert!(
            row.validate().is_none(),
            "the row must satisfy the code+remedy contract"
        );
    }

    /// A single-section view must inherit the verdict of whatever its section is
    /// waiting on, all the way down the chain.
    ///
    /// `Unknown(blocker)` means "the verdict is not mine to give, it is theirs".
    /// Filling the blocker in as `not_applicable` — which is what a one-section
    /// report used to do — dropped the `Failed` that owned the exit code and left
    /// the anti-cascade *warning* as the whole answer: `proxy status` exited 7
    /// (degraded) on a host `doctor` called broken (1). Same host, same instant,
    /// two verdicts, from the module whose contract is one.
    #[test]
    fn a_section_inherits_the_verdict_of_the_chain_it_waits_on() {
        let mut report = Report::new();
        report.push(
            Check::failed(Section::Daemon, "not running")
                .code(ERR_DAEMON_START_FAILED)
                .remedy("Run `openlatch start`."),
        );
        report.push(Check::unknown(Section::Cloud, Section::Daemon));
        report.push(Check::unknown(Section::Policy, Section::Cloud));

        // One hop.
        assert_eq!(blockers_of(&report, Section::Cloud), vec![Section::Daemon]);

        // Two hops: Policy waits on Cloud, which waits on Daemon — and Daemon is
        // the only section here holding an actual failure.
        let chain = blockers_of(&report, Section::Policy);
        assert!(
            chain.contains(&Section::Cloud) && chain.contains(&Section::Daemon),
            "the walk must reach past the first hop: {chain:?}"
        );

        // A section nobody is waiting on has an empty chain.
        assert!(blockers_of(&report, Section::Daemon).is_empty());
    }

    /// A deferral cycle must terminate rather than hang the CLI.
    ///
    /// Nothing in the type system forbids two sections naming each other, and an
    /// unguarded walk would spin forever inside a status command.
    #[test]
    fn a_deferral_cycle_terminates() {
        let mut report = Report::new();
        report.push(Check::unknown(Section::Cloud, Section::Policy));
        report.push(Check::unknown(Section::Policy, Section::Cloud));

        let chain = blockers_of(&report, Section::Cloud);
        assert_eq!(
            chain,
            vec![Section::Policy],
            "self is never its own blocker"
        );
    }

    /// `supervision status --json` and `inventory status --json` print their own
    /// body and owe the shared section verdict. They used to print the verdict
    /// AFTER it, as a second document — `{...}{...}`, which no parser accepts.
    /// Six E2E supervision scenarios reported `invalid JSON: Extra data: line 9
    /// column 1`, and only the release matrix runs that suite, so it surfaced by
    /// blocking a publish.
    ///
    /// The verdict must therefore live inside the caller's object.
    #[test]
    fn a_section_verdict_is_carried_inside_the_body_not_after_it() {
        let mut one = Report::new();
        one.push(
            Check::off(Section::Persistence, "Disabled at your request")
                .code(ERR_NO_SUPERVISOR)
                .remedy("`openlatch supervision enable`"),
        );
        for other in Section::ALL {
            if other != Section::Persistence {
                one.push(Check::not_applicable(other, "not part of this view"));
            }
        }

        let doc = merge_verdict(
            serde_json::json!({"mode": "active", "installed": true}),
            section_verdict_value(&one, Section::Persistence),
        );

        // The caller's own fields survive the merge.
        assert_eq!(doc["mode"], "active");
        assert_eq!(doc["installed"], true);

        // The verdict is nested, carrying the same keys `run_section` prints.
        let verdict = &doc["verdict"];
        assert_eq!(verdict["section"], Section::Persistence.key());
        assert_eq!(verdict["state"], State::Off.key());
        assert!(verdict["checks"].is_array(), "verdict carries its checks");
        assert_eq!(verdict["exit_code"], one.exit_code());

        // The whole point: it renders as ONE document.
        let rendered = serde_json::to_string(&doc).expect("serializes");
        let mut stream =
            serde_json::Deserializer::from_str(&rendered).into_iter::<serde_json::Value>();
        assert!(stream.next().is_some(), "one document parses");
        assert!(
            stream.next().is_none(),
            "a second document would be the bug this test exists for"
        );
    }

    /// Two pretty-printed documents back to back is what the old code emitted.
    /// Pinned here so the shape this test rejects stays legible: the parser
    /// stops at the first character of the second document, exactly as the E2E
    /// harness reported.
    #[test]
    fn two_documents_back_to_back_are_not_parseable() {
        let concatenated = format!(
            "{}
{}",
            serde_json::to_string_pretty(&serde_json::json!({"mode": "active"})).unwrap(),
            serde_json::to_string_pretty(&serde_json::json!({"section": "persistence"})).unwrap(),
        );
        let err = serde_json::from_str::<serde_json::Value>(&concatenated)
            .expect_err("two documents must not parse as one");
        assert!(
            err.to_string().contains("trailing characters"),
            "unexpected parse error: {err}"
        );
    }

    /// A daemon that answers with something that is not an object still leaves
    /// the verdict somewhere to live, rather than dropping it or panicking.
    #[test]
    fn a_non_object_body_is_nested_rather_than_dropped() {
        let doc = merge_verdict(
            serde_json::json!(["one", "two"]),
            serde_json::json!({"section": "inventory"}),
        );

        assert_eq!(doc["body"], serde_json::json!(["one", "two"]));
        assert_eq!(doc["verdict"]["section"], "inventory");
    }

    /// The three states that used to be reported green. Each is now a warning
    /// or a failure with a code and a remedy — the regression this contract
    /// exists to prevent.
    #[test]
    fn a_disabled_subsystem_is_never_a_pass() {
        let mut report = Report::new();
        // Stand-ins for the real builders: the point under test is the state
        // each one is required to produce, not how it detects it.
        report.push(
            Check::off(Section::Boundary, "Disabled in config")
                .code(crate::error::ERR_BOUNDARY_NOT_RUNNING)
                .remedy("`openlatch boundary enable`"),
        );
        report.push(
            Check::off(Section::Persistence, "Disabled at your request")
                .code(ERR_NO_SUPERVISOR)
                .remedy("`openlatch supervision enable`"),
        );
        report.push(
            Check::off(Section::Policy, "Disabled in config")
                .code(ERR_POLICY_DISABLED)
                .remedy("remove [policy] enabled = false"),
        );

        for section in [Section::Boundary, Section::Persistence, Section::Policy] {
            assert_eq!(
                report.section_state(section),
                State::Off,
                "{} must warn when switched off, never pass",
                section.title()
            );
        }
        assert_eq!(report.counts().failed, 0);
        assert_eq!(
            report.exit_code(),
            crate::cli::report::EXIT_DEGRADED,
            "warnings must not exit 0"
        );
    }

    /// Telemetry is the documented exception: an exercised privacy opt-out is
    /// not a defect and must not nag.
    #[test]
    fn telemetry_opt_out_is_neutral_not_a_warning() {
        let mut report = Report::new();
        report.push(Check::not_applicable(
            Section::Telemetry,
            "Disabled by user (opt-out honoured)",
        ));
        assert_eq!(
            report.section_state(Section::Telemetry),
            State::NotApplicable
        );
        assert_eq!(report.counts().warned, 0);
    }

    #[test]
    fn cloud_has_no_off_state() {
        // D-6: the forwarding cannot be switched off, so nothing in the Cloud
        // builder may produce `Off`. Guarded here because the temptation to add
        // it back returns every time someone wants an air-gapped install.
        let source = include_str!("doctor.rs");
        let cloud_fn = source
            .split("fn check_cloud(")
            .nth(1)
            .expect("check_cloud must exist")
            .split("\n// ---")
            .next()
            .unwrap_or_default();
        assert!(
            !cloud_fn.contains("Check::off("),
            "Cloud must never report Off — see AC-CLOUD-01"
        );
    }

    /// `proxy set` writes the file; the running daemon keeps the route it loaded
    /// at start-up. The verdict has to describe the route carrying traffic *now*.
    ///
    /// It described the file instead, and demoted the live route to a dim aside —
    /// so a host pointed at a proxy thirty seconds ago reported a green "via HTTP
    /// proxy 10.0.0.1:1254" while every byte was still leaving direct. Green is
    /// "enabled and proven working", and nothing had been proven through a proxy
    /// no request had touched. Same disk-versus-process gap `check_update`
    /// already reports for the binary, and now reported the same way.
    #[test]
    fn a_route_written_but_not_yet_loaded_is_degraded_not_green() {
        use crate::cli::report::State;

        let mut cfg = config::Config::defaults();
        cfg.egress.url = Some("http://10.0.0.1:1254".into());
        cfg.egress.source = Some(crate::egress::ProxySource::Manual);

        // A daemon that started before the write resolved no proxy at all.
        let probe = DaemonProbe {
            alive: true,
            reachable: true,
            health: None,
            metrics: Some(serde_json::json!({
                "egress_status": "ok",
                "proxy_in_use": false,
            })),
            egress: Some(serde_json::json!({})),
            uptime_secs: Some(60),
        };

        let mut report = Report::new();
        check_connection(&cfg, &probe, &mut report);
        let check = report
            .section_checks(Section::Connection)
            .next()
            .expect("Connection is always reported (P6)");

        assert_eq!(check.state, State::Degraded, "not a pass: {check:?}");
        assert_eq!(check.code, Some(ERR_CONFIG_NOT_APPLIED));
        assert!(
            check.headline.contains("direct"),
            "the headline is the route traffic takes now: {}",
            check.headline
        );
        assert!(
            check.detail.iter().any(|d| d.contains("10.0.0.1:1254")),
            "and the configured route is still named, as not yet in use: {:?}",
            check.detail
        );
        assert!(
            check
                .remedy
                .as_deref()
                .unwrap_or_default()
                .contains("openlatch restart"),
            "with the one command that closes the gap: {:?}",
            check.remedy
        );
    }

    /// The agreeing case stays a one-line pass, with no pending noise.
    #[test]
    fn a_route_the_daemon_already_loaded_is_green() {
        use crate::cli::report::State;

        let mut cfg = config::Config::defaults();
        cfg.egress.url = Some("http://10.0.0.1:1254".into());

        let probe = DaemonProbe {
            alive: true,
            reachable: true,
            health: None,
            metrics: Some(serde_json::json!({ "egress_status": "ok" })),
            egress: Some(serde_json::json!({ "proxy_url": "http://10.0.0.1:1254" })),
            uptime_secs: Some(60),
        };

        let mut report = Report::new();
        check_connection(&cfg, &probe, &mut report);
        let check = report.section_checks(Section::Connection).next().unwrap();

        assert_eq!(check.state, State::Ok);
        assert!(
            check.detail.is_empty(),
            "no aside to add: {:?}",
            check.detail
        );
    }
}