openlatch-client 0.5.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
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
/// `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 relay 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::core::cloud::offset::{count_entries_from, read_offset};
use crate::error::{
    OlError, ERR_BUG, ERR_BUNDLE_FETCH_FAILED, ERR_BUNDLE_INVALID, ERR_BUNDLE_STALE,
    ERR_CLINE_SURFACE_ABSENT, ERR_CLINE_SURFACE_UNDETERMINED, 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, HookSurface, LivenessReport};
use crate::hooks::cline::{ClineAttestation, Surface, SurfaceState};

/// 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,
    /// What a Cline-lineage agent exposes on this host (PRD C-1), or `None`
    /// when nothing of that lineage is here.
    ///
    /// Held beside [`Self::report`] rather than inside it because a [`Check`]
    /// is a headline and a remedy, and this is a structured document with two
    /// dozen fields. [`Self::agents_json`] merges it into `doctor --json`;
    /// [`check_cline_surface`] is what puts the same facts in front of a human.
    pub cline: Option<ClineAttestation>,
}

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
    }

    /// The per-agent attestations, as the object `doctor --json` carries under
    /// `agents`.
    ///
    /// Built here rather than in [`Report::to_json`] deliberately: `Report`
    /// holds checks and cannot see a [`DoctorReport`], and `src/cli/report.rs`
    /// carries zero `Serialize` derives across its seven types, so teaching it
    /// this document means annotating a module rather than a struct.
    ///
    /// Always an object, empty when this host has no attested agent — a stable
    /// shape a consumer can index into, and empty exactly when the human
    /// rendering says nothing either (P7).
    pub(crate) fn agents_json(&self) -> serde_json::Value {
        let mut agents = serde_json::Map::new();
        if let Some(cline) = &self.cline {
            agents.insert("cline".to_string(), cline.to_json());
        }
        serde_json::Value::Object(agents)
    }

    /// 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 crash-report 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 metric_strings(&self, key: &str) -> Vec<&str> {
        self.metrics
            .as_ref()
            .and_then(|metrics| metrics.get(key))
            .and_then(serde_json::Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(serde_json::Value::as_str)
            .collect()
    }

    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 system proxy discover`              (or `openlatch system proxy set <url>` if the source is manual)."
        }
        ERR_PROXY_AUTH_FAILED => {
            "Re-enter the proxy credentials with `openlatch system 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 system 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 system proxy set --spn <spn>`."
        }
        _ => {
            "Check this host can reach app.openlatch.ai, or ask IT for an egress rule;              `openlatch system 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);
    // Files under `Section::Environment`: an attestation says what is PRESENT
    // ON THIS HOST, where `Section::Hooks` says what we installed — and into
    // Cline this build installs nothing.
    let cline = check_cline_surface(&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 = "model-relay")]
    check_model_relay(&cfg, &agents, &probe, &mut report);
    #[cfg(not(feature = "model-relay"))]
    report.push(Check::not_applicable(
        Section::ModelRelay,
        "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, &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,
        cline,
    })
}

// ---------------------------------------------------------------------------
// 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 (`OPENLATCH_CRASH_REPORTING=0`
    // or `[crashreport] enabled = false`) actually landed. This is the command that
    // answers the question — `openlatch status` prints no crash-reporting state at all.
    #[cfg(feature = "crash-report")]
    {
        use crate::telemetry::consent::CrashDecidedBy;
        let resolved = crate::telemetry::crash::current_state(ol_dir);
        let label = match resolved.decided_by {
            CrashDecidedBy::CrashReportingEnv => "off (OPENLATCH_CRASH_REPORTING env)",
            CrashDecidedBy::NoProjectKey => "off (no project key)",
            CrashDecidedBy::ConfigFile => {
                if resolved.enabled() {
                    "on (config.toml)"
                } else {
                    "off (config.toml)"
                }
            }
            CrashDecidedBy::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
        }
    }
}

/// Probe this host's Cline-lineage surface and file the attestation (PRD C-1).
///
/// Reads only — nothing here creates a directory or writes a byte, which is what
/// makes it safe on every `doctor`, `init` and `status` invocation.
///
/// **Both renderings or neither.** `Report::to_json` is documented as the
/// machine rendering, *isomorphic to the human one* — so the attestation that
/// [`DoctorReport::agents_json`] merges into `--json` is pushed here as real
/// [`Check`]s at the same time and under the same condition. An `agents` object
/// no human rendering mentions would break that invariant in the one file this
/// unit does not touch.
///
/// Filed under [`Section::Environment`], never `Hooks`: this says what is
/// **present on the host**, where the Hooks section says what *we installed* —
/// and into Cline this build installs nothing.
///
/// Gated on detection, and detection is **store-keyed**: no store, no
/// attestation, no probe. Two reasons, and the second is the one that bites.
/// A row about an agent this host does not have is the noise `doctor` already
/// declines to print for an undetected Claude Code or Codex CLI. And
/// `extension_roots` is derived from the real `home_dir()`, which none of the
/// three Cline seams redirects — so a gate that could fire on an extension
/// alone would make every existing fixture's exit code depend on whether the
/// developer running it happens to have Cline installed in an editor.
fn check_cline_surface(
    agents: &[hooks::DetectedAgent],
    report: &mut Report,
) -> Option<ClineAttestation> {
    let cline = crate::hooks::bindings::cline::ClineBinding::AGENT_TYPE;
    if !agents.iter().any(|agent| agent.agent_type() == cline) {
        return None;
    }

    let attestation = hooks::cline::probe();

    // Every remedy below is the one the probe already paired with that finding,
    // so `surfaces_absent[].remedy` in the JSON and the line a human reads are
    // the same sentence rather than two that can drift. The fallbacks are here
    // because `Check::validate` debug-asserts a remedy on every non-green check
    // on every rendering path, and an `Option` a constructor promises to fill is
    // still an `Option` at this call site.
    let remedy_for = |surface: Surface, fallback: &'static str| -> String {
        attestation
            .surfaces
            .iter()
            .find(|finding| finding.surface == surface)
            .and_then(|finding| finding.remedy)
            .unwrap_or(fallback)
            .to_string()
    };

    // The summary carries the resolved store root — the one string in `doctor`'s
    // output that belongs to this attestation and to nothing else. It leads the
    // check either way: as the headline when there is nothing to act on, and as
    // the first detail line when there is.
    let mut lines = attestation.human_lines();
    let summary = if lines.is_empty() {
        attestation.summary()
    } else {
        lines.remove(0)
    };

    let store = attestation.state_of_surface(Surface::Store);
    let undetermined = Surface::ALL
        .into_iter()
        .find(|surface| attestation.state_of_surface(*surface) == Some(SurfaceState::Undetermined));

    let check = if store != Some(SurfaceState::Present) {
        // Detection stat-ed this root moments ago and the probe cannot see it:
        // the store was removed mid-run, or it is there and unreadable. Either
        // way every surface below it is derived from a root we do not have, so
        // the count of present surfaces is not a claim worth rendering green.
        Check::degraded(
            Section::Environment,
            format!(
                "Cline store {}",
                store.map_or("unresolved", SurfaceState::as_str)
            ),
        )
        .code(if store == Some(SurfaceState::Absent) {
            ERR_CLINE_SURFACE_ABSENT
        } else {
            ERR_CLINE_SURFACE_UNDETERMINED
        })
        .remedy(remedy_for(
            Surface::Store,
            "Set CLINE_DIR to a store root this user can stat, then run `openlatch doctor` \
             again.",
        ))
        .detail(summary)
    } else if attestation.store_without_extension() {
        // Spec AC-4, named as its own state rather than folded into a count of
        // absent surfaces: this is the shape a rebranded fork takes, and the
        // install guide is blocked on knowing which one it is. Never green.
        Check::degraded(
            Section::Environment,
            "Cline store present, no Cline-lineage extension in any known editor root",
        )
        .code(ERR_CLINE_SURFACE_ABSENT)
        .remedy(remedy_for(
            Surface::Extension,
            "Report this host's editor root so the install guide can name it.",
        ))
        .detail(summary)
    } else if let Some(surface) = undetermined {
        // A lookup that could not answer is not an absence. Reported as its own
        // state so a permission error on one root never reads as a confident
        // "Cline is not here" — which is the finding a customer acts on.
        Check::degraded(
            Section::Environment,
            format!("Cline {} surface undetermined", surface.as_str()),
        )
        .code(ERR_CLINE_SURFACE_UNDETERMINED)
        .remedy(remedy_for(
            surface,
            "Check the permissions on Cline's roots, or set CLINE_DIR, CLINE_DATA_DIR and \
             OPENLATCH_CLINE_ASSETS_DIR to roots this user can stat.",
        ))
        .detail(summary)
    } else {
        // The store is here and so is the extension. Absent surfaces below them
        // — no `Hooks/`, no plugins, no MCP registry — are ordinary on a Cline
        // install nobody has configured, and the headline carries the count, so
        // green never hides one.
        Check::ok(Section::Environment, summary)
    };

    // Every remaining line of the human rendering, so both renderings carry the
    // same facts (P7) — the JSON object and these detail lines are built from
    // one attestation, in one function, from one probe.
    let check = lines
        .into_iter()
        .fold(check, |check, line| check.detail(line))
        .agent(cline);
    report.push(check);

    Some(attestation)
}

// ---------------------------------------------------------------------------
// 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 model relay 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;
    }

    // What the per-agent loop contributes, measured rather than tracked by a
    // flag, so a new push inside the loop cannot forget to set one. Read again
    // after the loop: an unchanged count means every agent on this host was
    // skipped, and the section would otherwise be empty. See below.
    let hooks_checks_before = report.section_checks(Section::Hooks).count();

    for a in agents {
        // An agent whose hook surface this build cannot write is skipped
        // WHOLESALE — both red arms below, not one of them.
        //
        // The absent-file arm would emit `settings.json not found`, code
        // `ERR_HOOK_WRITE_FAILED`, remedying "Run `openlatch init`" — a command
        // that refuses this agent. `doctor` goes permanently red with an
        // unfollowable remedy, and `doctor --fix` is guarded so it can never
        // clear it — a diagnostic and its own fix disagreeing, which is exactly
        // what this file's contract forbids.
        //
        // **The directory half of this argument has moved.** It used to read
        // "`Path::exists()` is true for a DIRECTORY and this agent's hook path
        // is one", with Cline as the example. Cline is installable now, and a
        // directory surface is no longer something this guard catches — the
        // `hook_surface()` match below handles it by shape, which is the whole
        // point of D-01. What remains here is the narrower claim: an agent this
        // build cannot WRITE to is skipped wholesale, whatever shape its surface
        // has. No shipped binding answers `false` today; the guard stands for
        // the next one that does.
        //
        // Not a fourth `State::NotApplicable`: this is a skip, not a state. The
        // agent's hook surface is reported once, under `Section::Environment`,
        // by its own attestation.
        if !a.installable() {
            continue;
        }

        let agent = a.agent_type();

        // The SHAPE of the surface, not just its path. Everything in the
        // `ConfigFile` path below is JSON-shaped — `inspect_file`
        // `read_to_string`s it and parses it — and `Path::exists()` is true for
        // a directory, so the variant is the only thing that can keep a
        // directory out of a file reader.
        //
        // A directory surface gets the file-shaped predicate instead, and then
        // the SAME liveness rendering: *installed* and *enforcing* are two
        // different claims for every agent, and answering the second from a
        // second place is the second set of detectors this file's contract
        // forbids.
        let settings_path = match a.hook_surface() {
            HookSurface::ConfigFile(path) => path,
            HookSurface::Directory(hooks_dir) => {
                check_hook_files(ol_dir, &hooks_dir, a, report);
                check_liveness(a, report);
                continue;
            }
        };
        let settings_path = settings_path.as_path();

        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;
        }

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

        check_liveness(a, report);
    }

    // EVERY agent was skipped, so the loop above contributed nothing and
    // `Section::Hooks` is empty — which `Report::validate` fails, because every
    // section is always reported. The `agents.is_empty()` early return does not
    // catch this: there IS an agent, it is just one nothing can be written into.
    //
    // The same answer the no-agent case gives, for the same reason: one
    // `Check::unknown` pointing at `Environment`, which is where this agent's
    // hook surface is actually reported. Pushed ONCE, after the loop, and only
    // when the loop pushed nothing — per skipped agent it would put a spurious
    // cross beside a real result on a host running Claude Code AND Cline.
    //
    // The consequence, stated rather than discovered: `State::Unknown` is a
    // warning, so a host whose only agent is non-installable is `Degraded` and
    // exits `EXIT_DEGRADED`. That is honest — it moves from today's exit 1
    // (broken, "Agent not found") to exit 7, and it is deliberately not a pass.
    // We enforce nothing on that host, and off is never a pass.
    if report.section_checks(Section::Hooks).count() == hooks_checks_before {
        // `State::Unknown` for the exit code and the section-representation
        // contract — but NOT `Check::unknown`'s generated text.
        //
        // CORRECTED 2026-09-14 after review. That constructor is documented
        // "Indeterminable because `blocker` FAILED" and hardcodes "Cannot check
        // — waiting on Environment" / "Fix Environment first". On the host this
        // branch actually describes, Environment is GREEN: `check_environment`
        // pushed `Check::ok(Environment, "Agent: Cline …")` for every detected
        // agent. So the borrowed remedy sends an operator to fix something that
        // is not broken — an unfollowable remedy, which is the very defect class
        // this guard was added to remove (`doctor_fix.rs:717-725`: a diagnostic
        // and its own fix must not be allowed to disagree). The idiom is honest
        // in the `agents.is_empty()` branch above ONLY because Environment
        // genuinely fails there.
        report.push(
            Check::unknown(Section::Hooks, Section::Environment)
                .headline("No detected agent has a hook surface this build writes")
                .remedy(
                    "Nothing to fix here: the detected agent declares its hook \
                     surface cannot be installed into, so no hooks were written. \
                     Install a supported agent to enforce on this host.",
                ),
        );
    }

    // Per-HOST, not per-agent: it reads ~/.openlatch/logs/fallback.jsonl, which
    // no single agent owns. It used to be gated on at least one agent having
    // been inspected — a gate set INSIDE the loop body, so arming a
    // non-installable agent silenced a host-wide diagnostic that has nothing to
    // do with that agent. Hoisted out: one detected agent is the only condition,
    // and the `agents.is_empty()` return above already established it.
    check_fallback_activity(ol_dir, probe, report);
}

/// *Installed* and *enforcing* are two different claims, and only the binding
/// knows the difference.
///
/// One question, asked of every agent whatever the shape of its hook surface,
/// and rendered **here and nowhere else** — a second rendering path per surface
/// shape is the second set of detectors the one-question-one-set-of-detectors
/// invariant forbids, and it is how a `ConfigFile` agent and a `Directory` agent
/// would come to describe the same state in two different words.
///
/// `armed: None` pushes nothing: Claude Code has no arming concept, so installed
/// *is* armed and there is nothing to add.
fn check_liveness(a: &hooks::DetectedAgent, report: &mut Report) {
    let agent = a.agent_type();
    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),
            )
        }
    }
}

/// The `Directory` half of Check 5: are the scripts we wrote still there, still
/// ours, and still the bytes we wrote?
///
/// `health::inspect_file` cannot answer for this surface — it reads one path as
/// JSONC — so the question is asked per file, against the descriptors install
/// recorded. Same section, same codes and the same remedy as its file-shaped
/// twin, because it is the same question about a differently shaped surface.
///
/// A state file that will not load is **not** downgraded to drift: every script
/// carries a hash of its own body in its marker line, so ownership and
/// integrity are still provable without one. What is lost is only the
/// descriptor comparison, and the files that lose it are reported as
/// *unverified* rather than as broken — a host whose `hook-state.json` was
/// deleted is not a host with broken hooks.
fn check_hook_files(
    ol_dir: &std::path::Path,
    hooks_dir: &std::path::Path,
    a: &hooks::DetectedAgent,
    report: &mut Report,
) {
    let agent = a.agent_type();

    let descriptors = match crate::core::hook_state::HookStateFile::load(ol_dir) {
        Ok(Some(state)) => hooks::health::tracked_descriptors(&state, hooks_dir),
        Ok(None) => Default::default(),
        Err(e) => {
            tracing::debug!(
                error = %e.message,
                "doctor: hook state unreadable — checking ownership without descriptors"
            );
            Default::default()
        }
    };

    let health = hooks::health::inspect_directory(hooks_dir, &*a.binding, &descriptors);

    // Nothing of ours and nothing of anyone else's: this surface was never
    // written to. `init` is the remedy, exactly as it is for an absent
    // settings.json — and unlike that arm, `init` really does accept this
    // agent, so the remedy is one the reader can follow.
    if health.files == 0 && health.foreign_files.is_empty() {
        report.push(
            Check::failed(
                Section::Hooks,
                format!("Hook files not found in {}", hooks_dir.display()),
            )
            .code(ERR_HOOK_WRITE_FAILED)
            .remedy("Run `openlatch init` to install the hooks.")
            .agent(agent),
        );
        return;
    }

    if health.is_healthy() {
        let detail = (!health.unverified_files.is_empty()).then(|| {
            format!(
                "{} script(s) carry our ownership marker with no recorded descriptor: {}",
                health.unverified_files.len(),
                health.unverified_files.join(", ")
            )
        });
        report.push(
            Check::ok(
                Section::Hooks,
                format!(
                    "Hook files: all {} present in {}",
                    health.files,
                    hooks_dir.display()
                ),
            )
            .detail_opt(detail)
            .agent(agent),
        );
        return;
    }

    // Each defect named separately: "which" is the whole content of the
    // finding, and a foreign file is a different fact from a missing one — the
    // reinstall will rewrite the second and is required to leave the first
    // exactly where it is.
    let mut problems: Vec<String> = Vec::new();
    if !health.missing_files.is_empty() {
        problems.push(format!("missing: {}", health.missing_files.join(", ")));
    }
    if !health.drifted_files.is_empty() {
        problems.push(format!(
            "modified since install: {}",
            health.drifted_files.join(", ")
        ));
    }
    if !health.foreign_files.is_empty() {
        problems.push(format!(
            "not ours and left alone: {}",
            health.foreign_files.join(", ")
        ));
    }

    report.push(
        Check::failed(
            Section::Hooks,
            format!("Hook files incomplete in {}", hooks_dir.display()),
        )
        .code(ERR_HOOK_WRITE_FAILED)
        .detail(problems.join("; "))
        .source(hooks_dir.display().to_string())
        .remedy(
            "Run `openlatch doctor --fix` to rewrite them (it keeps the current \
             token, so running agent sessions keep capturing, and it never \
             overwrites a hook file it did not write).",
        )
        .agent(agent),
    );
}

/// 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),
            );
        }
    }
}

/// Report the fallback spool's *current* state: how many entries are still
/// waiting to be replayed.
///
/// Spooling is the hook's designed fail-open path — it writes the envelope,
/// lets the agent continue, and the daemon replays it on the next drain
/// signal. That a spool happened says nothing about health; a backlog that is
/// not draining does. Asking "was this file written since the daemon started"
/// latched a failure for the rest of the daemon's life the first time the
/// mechanism worked as designed.
fn check_fallback_activity(ol_dir: &std::path::Path, probe: &DaemonProbe, report: &mut Report) {
    // With no daemon there is nothing to drain the spool, and the Daemon
    // check above already says so.
    if !probe.alive {
        return;
    }
    let log_dir = ol_dir.join("logs");
    let fallback_path = log_dir.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;
        }
    };
    // Everything before the daemon's committed watermark has already been
    // replayed; only the tail after it is outstanding.
    let offset_path = log_dir.join(FALLBACK_OFFSET_FILENAME);
    let pending = count_entries_from(&fallback_path, read_offset(&offset_path));

    if pending == 0 {
        report.push(Check::ok(
            Section::Hooks,
            "Fallback log: every spooled event replayed",
        ));
        return;
    }

    // Replay is driven by the cloud worker's drain signal rather than a timer,
    // so a backlog on its own is in flight, not broken. What separates the two
    // is whether replay is still *committing progress*: the watermark's mtime
    // is the last time a pass landed. Measuring the spool's own mtime instead
    // would call a backlog healthy for as long as hooks keep appending to it —
    // exactly the case where replay has died and the spool only grows.
    let progress_at = std::fs::metadata(&offset_path)
        .and_then(|offset_meta| offset_meta.modified())
        .or_else(|_| meta.modified());
    let stalled_for = progress_at
        .ok()
        .and_then(|at| at.elapsed().ok())
        .unwrap_or_default();

    if stalled_for >= FALLBACK_STALL_AFTER {
        report.push(
            Check::failed(
                Section::Hooks,
                format!(
                    "Fallback log: {pending} event(s) unreplayed for {}",
                    human_duration(stalled_for.as_secs())
                ),
            )
            .code(ERR_HOOK_CONFLICT)
            .detail(
                "The daemon is up but is not draining the spool, so these events were \
                 captured and never delivered.",
            )
            .detail(
                "Replay pauses while the cloud channel is saturated — check the Cloud check \
                 below.",
            )
            .remedy("Run `openlatch restart` to force a replay pass."),
        );
    } else {
        // Spooled, not yet drained, and replay is still keeping up. Reporting
        // the count is the state; there is nothing for an operator to do.
        report.push(Check::ok(
            Section::Hooks,
            format!("Fallback log: {pending} event(s) queued for replay"),
        ));
    }
}

/// How long the newest unreplayed entry may sit before the backlog stops being
/// "draining" and starts being "stuck". Replay is signalled, not scheduled, so
/// this is a ceiling on how long a signal may take, not a polling interval.
const FALLBACK_STALL_AFTER: std::time::Duration = std::time::Duration::from_secs(300);

/// Sibling watermark file that `fallback_replay` commits after each pass.
const FALLBACK_OFFSET_FILENAME: &str = "fallback.jsonl.offset";

/// 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 — Model relay
// ---------------------------------------------------------------------------

/// 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 = "model-relay")]
fn model_relay_endpoint_name(w: &crate::hooks::binding::ModelRelayWiring) -> String {
    use crate::hooks::binding::EndpointConvention;
    // `&w.endpoint`, not `w.endpoint`: `JsonProvider` carries an owned `String`,
    // and a `{ provider_key, .. }` arm on a borrowed wiring would move out of
    // the borrow (E0507). The two `&'static str` variants never made that
    // visible.
    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.
///
/// **Renamed from `toml_provider_proxy_note`**: the answer is per convention and
/// three conventions now reach it, so a name claiming one of them was a name
/// that would have to be wrong for the other two.
///
/// 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.
///
/// **Cline's answer is neither**, and it is empty for a reason rather than by
/// default: VS Code resolves a loopback host to `DIRECT` before any proxy logic
/// runs (`vscode-proxy-agent`), so `127.0.0.1` never reaches the corporate
/// proxy and the customer's own `http.proxy` setting keeps working untouched.
/// There is no bypass to advise and no gap to disclose.
#[cfg(feature = "model-relay")]
fn model_relay_proxy_note(w: &crate::hooks::binding::ModelRelayWiring) -> &'static str {
    use crate::hooks::binding::EndpointConvention;
    // `&w.endpoint` for the same reason as `model_relay_endpoint_name`, though
    // no arm here binds anything: matching the sibling's shape keeps the two
    // from diverging the next time one of them grows a binding.
    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 model relay's loopback base must not leave through the \
             corporate proxy."
        }
    }
}

#[cfg(feature = "model-relay")]
/// One check per provider slot served by a relay endpoint, from
/// [`crate::cli::commands::model_relay::endpoint_rows_for`] — the detector
/// `status` renders too.
///
/// Every state but `Active` carries a code and a remedy, and no remedy asks the
/// developer to set a URL by hand: OpenLatch writes the slots, a running editor
/// picks them up at its next start, and a provider that cannot be carried is
/// named as such. Returns whether anything was pushed.
pub(crate) fn check_provider_endpoints(
    rows: &[crate::cli::commands::model_relay::EndpointRow],
    report: &mut Report,
) -> bool {
    use crate::cli::commands::model_relay::EndpointState;
    use crate::error::{
        ERR_MODEL_RELAY_ENDPOINT_PORTS, ERR_MODEL_RELAY_MISCONFIGURED, ERR_MODEL_RELAY_NEXT_START,
        ERR_MODEL_RELAY_NOT_RUNNING, ERR_MODEL_RELAY_PORT_FOREIGN,
        ERR_MODEL_RELAY_PREFLIGHT_FAILED, ERR_MODEL_RELAY_STATE_FILE, ERR_MODEL_RELAY_UNCOVERED,
    };

    for row in rows {
        let at = row
            .port
            .map(|p| format!("relay endpoint 127.0.0.1:{p}"))
            .unwrap_or_else(|| "a relay endpoint".to_string());
        let source = row
            .file
            .as_deref()
            .map(crate::core::path_compat::display_path);
        let check = match &row.state {
            EndpointState::Active => {
                Check::ok(Section::ModelRelay, format!("{}{at}, in use", row.label))
            }
            EndpointState::NextStart => Check::pending(
                Section::ModelRelay,
                format!("{}{at}, waiting for the editor to restart", row.label),
            )
            .code(ERR_MODEL_RELAY_NEXT_START)
            .detail(
                "OpenLatch pointed this provider at its relay endpoint. A running editor \
                keeps the settings it read when it started, so model calls reach the relay \
                from its next start.",
            )
            .remedy("Nothing to do: Cline picks this up the next time VS Code starts."),
            EndpointState::Unwired => Check::pending(
                Section::ModelRelay,
                format!("{} is configured and not wired yet", row.label),
            )
            .code(ERR_MODEL_RELAY_NEXT_START)
            .detail("The daemon wires every configured provider on its wiring pass.")
            .remedy(
                "Nothing to do while the daemon runs — it wires this within a minute. If \
                `openlatch status` shows no daemon, run `openlatch start`.",
            ),
            EndpointState::Down => Check::failed(
                Section::ModelRelay,
                format!("{} names {at}, and nothing is listening", row.label),
            )
            .code(ERR_MODEL_RELAY_NOT_RUNNING)
            .detail(
                "Model calls for this provider fail until the daemon serves the endpoint again.",
            )
            .remedy("Run `openlatch start`."),
            EndpointState::Foreign => Check::failed(
                Section::ModelRelay,
                format!(
                    "{} names {at}, held by something that is not this endpoint",
                    row.label
                ),
            )
            .code(ERR_MODEL_RELAY_PORT_FOREIGN)
            .detail("This provider's requests, and the API key they carry, go to that process.")
            .remedy(format!(
                "Identify it (lsof -i :{}), stop it, then run `openlatch restart`.",
                row.port.unwrap_or_default()
            )),
            EndpointState::Verdict { code, detail } => {
                let headline = format!("{} is not wired — {detail}", row.label);
                let check = if *code == ERR_MODEL_RELAY_MISCONFIGURED {
                    Check::failed(Section::ModelRelay, headline).detail(
                        "The editor loaded the relay URL and is using this provider, but no \
                        request reached the endpoint: a Cline organisation's remote \
                        configuration is overriding it.",
                    )
                } else {
                    Check::degraded(Section::ModelRelay, headline).detail(
                        "The provider's calls go straight to it and keep working; nothing is \
                        captured for them until the daemon can wire the slot.",
                    )
                };
                let remedy = match *code {
                    ERR_MODEL_RELAY_PREFLIGHT_FAILED => {
                        "Nothing to do if the provider is meant to be offline; otherwise fix \
                        reachability to it — the daemon wires the slot as soon as a round \
                        trip succeeds."
                    }
                    ERR_MODEL_RELAY_ENDPOINT_PORTS => {
                        "Free the port named above (lsof -i :<port>), or run `openlatch restart`; \
                        the daemon retries on its next pass."
                    }
                    ERR_MODEL_RELAY_MISCONFIGURED => {
                        "Ask your Cline organisation administrator to leave this provider's base \
                        URL unmanaged, or accept that its calls are not observed."
                    }
                    _ => "Nothing to do: the daemon retries on its next pass.",
                };
                check.code(code).remedy(remedy)
            }
            EndpointState::Uncovered(reason) => {
                use crate::hooks::cline_providers::UncoveredReason;
                let unproven = matches!(
                    reason,
                    UncoveredReason::NextBundleOnly | UncoveredReason::ManagedOverride
                );
                Check::off(
                    Section::ModelRelay,
                    if unproven {
                        format!(
                            "{}{at}, not confirmed — {}",
                            row.label,
                            reason.describe()
                        )
                    } else {
                        format!(
                            "{} is not carried by the relay — {}",
                            row.label,
                            reason.describe()
                        )
                    },
                )
                .code(ERR_MODEL_RELAY_UNCOVERED)
                .detail(if unproven {
                    "OpenLatch pointed this provider at its relay endpoint, but Cline may not \
                     route by that setting, so its calls count as not observed until one \
                     arrives. Nothing is broken."
                } else {
                    "These model calls go straight to the provider and are not observed. \
                     Nothing is broken."
                })
                .remedy(match reason {
                    UncoveredReason::DefaultUnknown => {
                        "Nothing to do; `openlatch update` picks up support for new providers as \
                         it ships."
                    }
                    UncoveredReason::NextBundleOnly | UncoveredReason::ManagedOverride => {
                        "Nothing to do: the first request through the endpoint confirms it."
                    }
                    _ => "Nothing to do: this provider keeps working and is simply not observed.",
                })
            }
            EndpointState::StateFile(why) => Check::degraded(
                Section::ModelRelay,
                format!("Cannot read {} safely — {why}", row.label),
            )
            .code(ERR_MODEL_RELAY_STATE_FILE)
            .detail(
                "OpenLatch refuses to rewrite a settings file it cannot read whole, so the \
                providers in it are not wired and their calls go direct.",
            )
            .remedy("Nothing to do: OpenLatch wires them as soon as the file is readable again."),
        };
        let check = match source {
            Some(source) => check.source(source),
            None => check,
        };
        report.push(check.agent(row.agent));
    }
    !rows.is_empty()
}

/// The model-relay 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 = "model-relay")]
fn check_model_relay(
    cfg: &config::Config,
    agents: &[hooks::DetectedAgent],
    probe: &DaemonProbe,
    report: &mut Report,
) {
    use crate::cli::commands::model_relay::{
        classify_model_relay, read_agent_wiring, ModelRelayState,
    };
    use crate::error::{
        ERR_MODEL_RELAY_NOT_RUNNING, ERR_MODEL_RELAY_PORT_FOREIGN, ERR_MODEL_RELAY_PORT_IN_USE,
        ERR_MODEL_RELAY_PREFLIGHT_FAILED,
    };

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

    // Whether the loop pushed anything at all. An empty Model relay 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 = check_provider_endpoints(
        &crate::cli::commands::model_relay::endpoint_rows_for(
            cfg,
            agents,
            &crate::cli::commands::model_relay::verify_endpoint_ownership,
        ),
        report,
    );

    for a in agents {
        // An agent with NO request plane contributes no Model relay 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.
        //
        // An agent with provider slots (Cline) has no single plane here: each
        // slot is its own endpoint, reported by `check_provider_endpoints`
        // above from the one detector `status` renders too.
        //
        // Per plane: what it is wired to; the file the WIRING is in (Claude
        // Code's hooks and model relay share one `settings.json`, Codex's do
        // not — naming the hooks file sends the operator to a file we never
        // wrote); and the endpoint and
        // upstream in THIS agent's own vocabulary. The 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 Some(w) = a.binding.model_relay_wiring() else {
            continue;
        };
        let (wired, wiring_path, endpoint_name, upstream, proxy_note) = (
            read_agent_wiring(&*a.binding),
            crate::hooks::model_relay_config_path(&*a.binding).unwrap_or_else(|| a.settings_path()),
            model_relay_endpoint_name(&w),
            cfg.model_relay.upstream_for(w.wire_format),
            model_relay_proxy_note(&w),
        );
        pushed_any = true;
        let wiring_path = wiring_path.as_path();
        let agent = a.agent_type();
        let display_name = a.binding.display_name();
        let url = wired.as_deref().unwrap_or_default().to_string();

        match classify_model_relay(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.
            ModelRelayState::Disabled => {
                report.push(
                    Check::off(
                        Section::ModelRelay,
                        "Disabled in config — model calls bypass OpenLatch entirely",
                    )
                    .code(ERR_MODEL_RELAY_NOT_RUNNING)
                    .source(format!(
                        "{} [model_relay] enabled = false",
                        config_source.display()
                    ))
                    .detail("Nothing is captured and no policy is enforced on model traffic.")
                    .remedy(
                        "Run `openlatch system model-relay 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.
            ModelRelayState::Isolated => {
                report.push(
                    Check::ok(
                        Section::ModelRelay,
                        format!("Isolated instance on port {port}"),
                    )
                    .detail(format!(
                        "{} is machine-global and is not managed by this instance.",
                        wiring_path.display()
                    ))
                    .agent(agent),
                );
            }
            ModelRelayState::Wired => {
                report.push(
                    Check::ok(
                        Section::ModelRelay,
                        format!("Agent wired to {url} and the listener is up"),
                    )
                    .agent(agent),
                );
            }
            ModelRelayState::WiredButDown => {
                report.push(
                    Check::failed(
                        Section::ModelRelay,
                        format!("Agent is wired to {url} but nothing is listening there"),
                    )
                    .code(ERR_MODEL_RELAY_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 model relay back up, or `openlatch stop` \
                         to clear the wiring and go direct.{proxy_note}"
                    ))
                    .agent(agent),
                );
            }
            ModelRelayState::WiredToForeign => {
                report.push(
                    Check::failed(
                        Section::ModelRelay,
                        format!("Agent is wired to {url}, held by a process that is NOT OpenLatch"),
                    )
                    .code(ERR_MODEL_RELAY_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),
                );
            }
            ModelRelayState::PreflightFailed(why) => {
                report.push(
                    Check::failed(
                        Section::ModelRelay,
                        format!("Listener is up but its preflight failed — {why}"),
                    )
                    .code(ERR_MODEL_RELAY_PREFLIGHT_FAILED)
                    .detail(format!(
                        "The model_relay 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),
                );
            }
            ModelRelayState::PreflightPending => {
                report.push(
                    Check::pending(
                        Section::ModelRelay,
                        "Listener is up, its preflight has not finished yet",
                    )
                    .code(ERR_MODEL_RELAY_PREFLIGHT_FAILED)
                    .detail(format!(
                        "The model_relay 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),
                );
            }
            ModelRelayState::UpUnwired => {
                report.push(
                    Check::degraded(
                        Section::ModelRelay,
                        "Listener is up but the agent is not wired to it",
                    )
                    .code(ERR_MODEL_RELAY_NOT_RUNNING)
                    .detail(format!(
                        "The model relay 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.
            ModelRelayState::Down => {
                let (state_check, why) = if probe.alive {
                    (
                        Check::failed(
                            Section::ModelRelay,
                            "Enabled in config, but no listener holds the port",
                        ),
                        "The daemon is up and the model relay is not — its listener task did not bind.",
                    )
                } else {
                    (
                        Check::unknown(Section::ModelRelay, Section::Daemon)
                            .headline("Listener down — the daemon that owns it is not running"),
                        "The daemon is down, so its model relay listener is too.",
                    )
                };
                report.push(
                    state_check
                        .code(ERR_MODEL_RELAY_NOT_RUNNING)
                        .detail(why)
                        .remedy(if probe.alive {
                            "Check the newest ~/.openlatch/logs/daemon.log.<date> for OL-RELAY-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.
            ModelRelayState::ForeignIdle => {
                report.push(
                    Check::failed(
                        Section::ModelRelay,
                        format!("127.0.0.1:{port} is held by another process"),
                    )
                    .code(ERR_MODEL_RELAY_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::ModelRelay, 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 system 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 system 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 system 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 system 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 system 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 system 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 system 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 system 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 system 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 system 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 system 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;
    }

    // A fresh install can be below floor before it has ever activated a
    // bundle, so this check deliberately precedes the no-bundle branch.
    let has_bundle = probe.metric_bool("policy_has_bundle").unwrap_or(false);
    let floor_blocked = probe.metric_bool("policy_floor_blocked").unwrap_or(false);
    if floor_blocked {
        let installed = probe.metric_str("policy_installed_version").unwrap_or("?");
        let minimum = probe.metric_str("policy_min_client_version").unwrap_or("?");
        report.push(
            Check::failed(Section::Policy, "Client upgrade required")
                .code(ERR_BUNDLE_FETCH_FAILED)
                .detail(if has_bundle {
                    format!("Installed {installed}; minimum {minimum}. The last-known-good bundle remains active.")
                } else {
                    format!("Installed {installed}; minimum {minimum}. No bundle has been activated on this install.")
                })
                .remedy("Run `openlatch update`, then restart the daemon."),
        );
    }

    // `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 !has_bundle {
        if floor_blocked {
            return;
        }
        /// 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());
    let schema = probe.metric_u64("policy_schema_version").unwrap_or(0);
    let digest = probe.metric_str("policy_bundle_digest").unwrap_or("?");

    let omitted = probe.metric_strings("policy_omitted_kinds");
    if !omitted.is_empty() {
        report.push(
            Check::degraded(
                Section::Policy,
                "Some policy kinds are not enforced on this client version",
            )
            .code(ERR_BUNDLE_INVALID)
            .detail(format!("Omitted kinds: {}", omitted.join(", ")))
            .remedy("Run `openlatch update` to install the newest policy capabilities."),
        );
    }
    let skipped = probe.metric_u64("policy_skipped_items").unwrap_or(0);
    if skipped > 0 {
        report.push(
            Check::degraded(
                Section::Policy,
                format!("{skipped} bundle item(s) skipped; the rest of the bundle activated"),
            )
            .code(ERR_BUNDLE_INVALID)
            .remedy("Inspect the daemon policy logs for the skipped item ids and reasons."),
        );
    }

    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!("Schema {schema} bundle {revision} fresh (polled {secs}s ago)"),
                )
                .detail(format!("Active digest: {digest}")),
            );
        }
        None => {
            report.push(
                Check::degraded(
                    Section::Policy,
                    format!(
                        "Schema {schema} bundle {revision} is enforcing, but no poll has ever succeeded"
                    ),
                )
                .code(ERR_BUNDLE_STALE)
                .detail(format!("Active digest: {digest}"))
                .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);
            match body.get("state").and_then(|value| value.as_str()) {
                Some("pending") => report.push(Check::pending(
                    Section::Inventory,
                    "Monitor initialization is still in progress",
                )),
                Some("failed") | Some("stopped") => {
                    let mut check = Check::failed(
                        Section::Inventory,
                        "Monitor failed to initialize or stopped unexpectedly",
                    )
                    .code(ERR_INVENTORY_INIT_FAILED)
                    .remedy("Check the newest ~/.openlatch/logs/daemon.log.<date>, then `openlatch restart`.");
                    if let Some(error) = body.get("error").and_then(|value| value.as_str()) {
                        check = check.detail(error);
                    }
                    report.push(check);
                }
                Some("running") | None if manifest => report.push(Check::ok(
                    Section::Inventory,
                    format!("Monitor up, {sources} source(s) tracked"),
                )),
                _ => {
                    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 system 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, 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."),
        );
    }

    // The tamper log is a history, and history is not state: the reconciler
    // rewrites the same hook entry in place, so a detection followed by a
    // successful heal is settled. Report the entries whose *latest* record is
    // still unhealed — those are the ones broken right now.
    let tamper_path = ol_dir.join("tamper.jsonl");
    let Ok(contents) = std::fs::read_to_string(&tamper_path) else {
        return;
    };
    let (records, unhealed) = summarise_tamper(&contents);
    if records == 0 {
        return;
    }
    if unhealed == 0 {
        report.push(Check::ok(
            Section::Integrity,
            format!("Hook entries intact — {records} tamper event(s) healed"),
        ));
    } else {
        report.push(
            Check::degraded(
                Section::Integrity,
                format!("{unhealed} hook entry(s) rewritten and still unhealed"),
            )
            .code(ERR_TAMPER_DETECTED)
            .detail(
                "Something rewrote the agent's hook entries and the reconciler could not \
                 restore them, so those events are not being captured.",
            )
            .remedy("Inspect them with `openlatch logs --tamper`, then run `openlatch init`."),
        );
    }
}

/// Fold the append-only tamper log into current state.
///
/// Keyed by the hook entry each record describes, because the reconciler heals
/// that entry in place — the last record for a key is that entry's state now.
/// Returns `(records parsed, entries whose latest record is unhealed)`.
fn summarise_tamper(contents: &str) -> (usize, usize) {
    let mut latest: std::collections::HashMap<(String, String), bool> =
        std::collections::HashMap::new();
    let mut records = 0usize;
    for line in contents.lines() {
        let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
            continue;
        };
        let Some(tamper) = value.get("tamper") else {
            continue;
        };
        // Relay wiring states share the log, not the meaning: a slot waiting
        // on an editor restart is not a hook entry someone rewrote.
        if tamper
            .get("detection_method")
            .and_then(serde_json::Value::as_str)
            .is_some_and(crate::core::cloud::tamper::is_relay_wiring_method)
        {
            continue;
        }
        records += 1;
        let field = |name: &str| {
            tamper
                .get(name)
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string()
        };
        let healed = tamper
            .get("heal")
            .and_then(|heal| heal.get("outcome"))
            .and_then(serde_json::Value::as_str)
            == Some("succeeded");
        latest.insert((field("settings_path_hash"), field("hook_event")), healed);
    }
    (records, latest.values().filter(|healed| !**healed).count())
}

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

/// The whole of `doctor --json`: the section report, plus the per-agent
/// attestations under `agents`.
///
/// Merged here rather than taught to `Report::to_json`. `Report` holds checks
/// and cannot see a [`DoctorReport`], and `src/cli/report.rs` carries zero
/// `Serialize` derives across its seven types — so the derive route means
/// annotating a module rather than a struct, for a document only this command
/// produces. The checks carry the same facts in `checks[]`, which is what keeps
/// the two renderings isomorphic (P7); `agents` is the structured form a
/// platform consumer indexes into.
///
/// **Merged into `agents`, not over it.** `Report::to_json` already keys that
/// object by agent, carrying each one's per-section rollup, and the attestation
/// is a second thing to say about the same agent — so it joins that agent's
/// object rather than replacing the map. Replacing it is not a hypothetical:
/// an `insert` here erased the rollup and shipped `"agents": {}` on a host with
/// two agents detected, because the two producers agreed on the key and on
/// nothing else.
fn json_document(report: &DoctorReport) -> serde_json::Value {
    let mut document = report.report.to_json();
    let Some(object) = document.as_object_mut() else {
        return document;
    };
    let rollups = object
        .get_mut("agents")
        .and_then(serde_json::Value::as_object_mut);
    let Some(rollups) = rollups else {
        // No rollup to merge into — the report had no agent-tagged check at
        // all. The attestations are still the whole answer.
        object.insert("agents".to_string(), report.agents_json());
        return document;
    };
    if let serde_json::Value::Object(attested) = report.agents_json() {
        for (agent, attestation) in attested {
            let entry = rollups
                .entry(agent)
                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
            match (entry.as_object_mut(), attestation) {
                (Some(target), serde_json::Value::Object(fields)) => {
                    target.extend(fields);
                }
                // An attestation that is not an object cannot be merged field
                // by field, and losing it silently is worse than nesting it.
                (_, other) => {
                    *entry = other;
                }
            }
        }
    }
    document
}

/// 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(&json_document(report));
        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 system 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 model relay 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 system auth login") {
        Some(
            "run 'openlatch system auth login' — nothing reaches the platform without a credential",
        )
    } else if mentions("openlatch system model-relay enable") {
        Some("run 'openlatch system model-relay enable' to route model calls through OpenLatch")
    } else if mentions("openlatch system supervision") {
        Some("run 'openlatch system 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::{non_installable_agent, 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 daemon that *is* running, so `check_fallback_activity` reaches a
    /// verdict instead of returning early.
    fn live_probe() -> DaemonProbe {
        DaemonProbe {
            alive: true,
            reachable: true,
            health: None,
            metrics: None,
            egress: None,
            uptime_secs: Some(600),
        }
    }

    #[test]
    fn fresh_install_floor_is_reported_before_no_bundle() {
        let probe = DaemonProbe {
            metrics: Some(serde_json::json!({
                "policy_floor_blocked": true,
                "policy_installed_version": "0.4.0",
                "policy_min_client_version": "0.5.0",
                "policy_has_bundle": false
            })),
            ..live_probe()
        };
        let mut report = Report::new();
        check_policy(&config::Config::defaults(), &probe, &mut report);
        let checks: Vec<_> = report.section_checks(Section::Policy).collect();
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].headline, "Client upgrade required");
        assert_eq!(checks[0].state, State::Failed);
        assert!(checks[0]
            .detail
            .iter()
            .any(|line| line.contains("No bundle has been activated")));
    }

    #[test]
    fn omitted_and_skipped_bundle_items_are_both_visible() {
        let probe = DaemonProbe {
            metrics: Some(serde_json::json!({
                "policy_floor_blocked": false,
                "policy_has_bundle": true,
                "policy_revision": 12,
                "policy_last_poll_ok_secs": 2,
                "policy_omitted_kinds": ["t3_hold"],
                "policy_skipped_items": 2
            })),
            ..live_probe()
        };
        let mut report = Report::new();
        check_policy(&config::Config::defaults(), &probe, &mut report);
        let headlines: Vec<_> = report
            .section_checks(Section::Policy)
            .map(|check| check.headline.as_str())
            .collect();
        assert!(headlines.contains(&"Some policy kinds are not enforced on this client version"));
        assert!(headlines.contains(&"2 bundle item(s) skipped; the rest of the bundle activated"));
    }

    /// Write a spool of `lines` envelopes under `dir` and return its length,
    /// which is also the offset a fully-drained replay would have committed.
    fn write_spool(dir: &std::path::Path, lines: usize) -> u64 {
        let log_dir = dir.join("logs");
        std::fs::create_dir_all(&log_dir).expect("log dir");
        let body: String = (0..lines).map(|i| format!("{{\"id\":{i}}}\n")).collect();
        std::fs::write(log_dir.join("fallback.jsonl"), &body).expect("write spool");
        body.len() as u64
    }

    fn fallback_checks(dir: &std::path::Path) -> Vec<Check> {
        let mut report = Report::new();
        check_fallback_activity(dir, &live_probe(), &mut report);
        report.section_checks(Section::Hooks).cloned().collect()
    }

    /// The regression. A spool the daemon has already drained is the fail-open
    /// path working, not a fault. The previous check compared the file's mtime
    /// against daemon start, so the first successful spool-and-replay latched
    /// `Failed` for the rest of the daemon's life — on a host where nothing
    /// was wrong and no event was lost.
    #[test]
    fn replayed_spool_is_not_a_finding() {
        let dir = tempfile::tempdir().expect("temp dir");
        let len = write_spool(dir.path(), 3);
        std::fs::write(
            dir.path().join("logs").join("fallback.jsonl.offset"),
            format!("{len}\n"),
        )
        .expect("write offset");

        let checks = fallback_checks(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].state, State::Ok, "{:?}", checks[0]);
    }

    /// An undrained backlog is worth stating, but replay is signalled rather
    /// than scheduled: a fresh one is in flight, not broken, and there is
    /// nothing for an operator to do about it.
    #[test]
    fn undrained_spool_is_reported_but_passes_while_draining() {
        let dir = tempfile::tempdir().expect("temp dir");
        write_spool(dir.path(), 2);

        let checks = fallback_checks(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].state, State::Ok, "{:?}", checks[0]);
        assert!(checks[0].headline.contains('2'), "{:?}", checks[0]);
    }

    /// Once the newest entry has outlived any plausible drain signal, the
    /// daemon is up and still not draining: events captured, never delivered.
    /// That is the failure the old check was reaching for and never measured.
    #[test]
    fn stale_backlog_fails() {
        let dir = tempfile::tempdir().expect("temp dir");
        write_spool(dir.path(), 1);
        let aged = std::time::SystemTime::now()
            .checked_sub(FALLBACK_STALL_AFTER + std::time::Duration::from_secs(60))
            .expect("aged timestamp");
        std::fs::File::options()
            .write(true)
            .open(dir.path().join("logs").join("fallback.jsonl"))
            .expect("open spool")
            .set_modified(aged)
            .expect("age spool");

        let checks = fallback_checks(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].state, State::Failed, "{:?}", checks[0]);
    }

    /// The case that measuring the spool's own mtime would miss: replay has
    /// died so the watermark is frozen, while hooks keep appending and keep the
    /// spool's mtime fresh. A backlog nothing is draining is a fault however
    /// recently it grew.
    #[test]
    fn frozen_watermark_fails_even_while_the_spool_grows() {
        let dir = tempfile::tempdir().expect("temp dir");
        write_spool(dir.path(), 4);
        let offset = dir.path().join("logs").join("fallback.jsonl.offset");
        std::fs::write(&offset, "0\n").expect("write offset");
        let aged = std::time::SystemTime::now()
            .checked_sub(FALLBACK_STALL_AFTER + std::time::Duration::from_secs(60))
            .expect("aged timestamp");
        std::fs::File::options()
            .write(true)
            .open(&offset)
            .expect("open offset")
            .set_modified(aged)
            .expect("age watermark");

        let checks = fallback_checks(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].state, State::Failed, "{:?}", checks[0]);
    }

    /// No spool at all stays the quiet pass it always was.
    #[test]
    fn absent_spool_is_ok() {
        let dir = tempfile::tempdir().expect("temp dir");
        let checks = fallback_checks(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].state, State::Ok, "{:?}", checks[0]);
    }

    fn tamper_line(event: &str, outcome: &str) -> String {
        serde_json::json!({
            "tamper": {
                "settings_path_hash": "sha256:abc",
                "hook_event": event,
                "heal": { "outcome": outcome, "attempt": 1, "circuit": "closed" }
            }
        })
        .to_string()
    }

    /// Healed drift is settled history. Counting it as a live finding is what
    /// made a routine `init` rewrite sit in the Integrity section for hours
    /// after the reconciler had already put the entries back.
    #[test]
    fn healed_tamper_records_leave_nothing_unhealed() {
        let log = format!(
            "{}\n{}\n",
            tamper_line("Stop", "succeeded"),
            tamper_line("PreToolUse", "succeeded")
        );
        assert_eq!(summarise_tamper(&log), (2, 0));
    }

    /// The last record for an entry wins: a failure healed afterwards is not
    /// still broken.
    #[test]
    fn later_heal_supersedes_earlier_failure() {
        let log = format!(
            "{}\n{}\n",
            tamper_line("Stop", "failed"),
            tamper_line("Stop", "succeeded")
        );
        assert_eq!(summarise_tamper(&log), (2, 0));
    }

    /// And the converse, counted once however often the entry was rewritten.
    #[test]
    fn latest_unhealed_entry_is_counted_once() {
        let log = format!(
            "{}\n{}\n{}\n",
            tamper_line("Stop", "succeeded"),
            tamper_line("Stop", "failed"),
            tamper_line("PreToolUse", "succeeded")
        );
        assert_eq!(summarise_tamper(&log), (3, 1));
    }

    /// A relay wiring waiting on an editor restart shares the tamper log but is
    /// not a rewritten hook entry, so it never lands in the Integrity section.
    #[test]
    fn relay_wiring_records_are_not_hook_tampering() {
        let pending = serde_json::json!({
            "tamper": {
                "settings_path_hash": "sha256:state",
                "hook_event": crate::core::cloud::tamper::RELAY_WIRING_HOOK_EVENT,
                "detection_method": crate::core::cloud::tamper::DETECTION_RELAY_WIRING_PENDING,
                "heal": { "outcome": "pending", "attempt": 0, "circuit": "closed" }
            }
        })
        .to_string();
        let log = format!("{pending}\n{}\n", tamper_line("Stop", "succeeded"));
        assert_eq!(summarise_tamper(&log), (1, 0));
    }

    /// Every state a provider slot can be in renders with a code and a remedy,
    /// and none of those remedies asks for a URL to be set by hand.
    #[cfg(feature = "model-relay")]
    #[test]
    fn every_endpoint_state_carries_code_and_remedy() {
        use crate::cli::commands::model_relay::{EndpointRow, EndpointState};
        use crate::hooks::cline_providers::UncoveredReason;
        let states = [
            EndpointState::Active,
            EndpointState::NextStart,
            EndpointState::Unwired,
            EndpointState::Down,
            EndpointState::Foreign,
            EndpointState::Verdict {
                code: crate::error::ERR_MODEL_RELAY_PREFLIGHT_FAILED,
                detail: "no round trip".into(),
            },
            EndpointState::Verdict {
                code: crate::error::ERR_MODEL_RELAY_ENDPOINT_PORTS,
                detail: "port 7601 is taken".into(),
            },
            EndpointState::Verdict {
                code: crate::error::ERR_MODEL_RELAY_MISCONFIGURED,
                detail: "no traffic".into(),
            },
            EndpointState::Uncovered(UncoveredReason::SignedHost),
            EndpointState::Uncovered(UncoveredReason::DefaultUnknown),
            EndpointState::Uncovered(UncoveredReason::NextBundleOnly),
            EndpointState::Uncovered(UncoveredReason::ManagedOverride),
            EndpointState::StateFile("too large".into()),
        ];
        let rows: Vec<EndpointRow> = states
            .into_iter()
            .map(|state| EndpointRow {
                agent: "cline",
                key: "cline:gs:shared:geminiBaseUrl".into(),
                label: "gemini (geminiBaseUrl)".into(),
                file: None,
                port: Some(7601),
                state,
            })
            .collect();
        let mut report = Report::new();
        assert!(check_provider_endpoints(&rows, &mut report));
        let checks: Vec<_> = report.checks().to_vec();
        assert_eq!(checks.len(), rows.len());
        for check in &checks {
            assert_eq!(check.validate(), None, "{check:?}");
            // A string wrapped without its `\` continuation prints the source
            // indentation mid-sentence.
            for text in std::iter::once(&check.headline)
                .chain(&check.detail)
                .chain(&check.remedy)
            {
                assert!(!text.contains("  "), "a run of spaces in {text:?}");
            }
            if check.state != State::Ok {
                let remedy = check.remedy.as_deref().unwrap_or_default().to_lowercase();
                assert!(
                    !remedy.contains("set the base url") && !remedy.contains("in cline's settings"),
                    "a remedy must never ask for wiring by hand: {remedy}"
                );
            }
        }
        assert_eq!(checks[0].state, State::Ok);
        assert_eq!(checks[1].state, State::Pending);
        assert!(
            checks.iter().filter(|c| c.state == State::Ok).count() == 1,
            "only a proven slot is green"
        );
    }

    /// The log is append-only and a crash can tear a line mid-write. A torn
    /// line is skipped, not counted and not fatal.
    #[test]
    fn malformed_tamper_lines_are_skipped() {
        let log = format!("not json\n\n{}\n", tamper_line("Stop", "succeeded"));
        assert_eq!(summarise_tamper(&log), (1, 0));
    }

    /// 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 = "model-relay")]
    fn model_relay_check_skips_an_agent_without_a_request_plane() {
        let agents = vec![DetectedAgent {
            kind: AgentKind::ClaudeCode,
            binding: Arc::new(FakeBinding {
                agent_type: "cursor",
                // `model_relay_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_model_relay(
            &config::Config::defaults(),
            &agents,
            &dead_probe(),
            &mut report,
        );

        let checks: Vec<&Check> = report.section_checks(Section::ModelRelay).collect();
        assert!(
            !checks.iter().any(|c| c.agent == Some("cursor")),
            "no per-agent Model relay 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 Model relay 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 = "model-relay")]
    fn model_relay_check_reads_the_toml_convention() {
        use crate::hooks::binding::{EndpointConvention, ModelRelayWiring};
        use crate::model_relay::wire_format::WireFormat;

        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(),
                    model_relay_wiring: Some(ModelRelayWiring {
                        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 model_relay\"\n\
             base_url = \"http://127.0.0.1:7600/v1\"\n",
        )
        .expect("seed config.toml");

        let mut report = Report::new();
        check_model_relay(&cfg, &[codex_agent(tmp.path())], &dead_probe(), &mut report);
        let checks: Vec<&Check> = report.section_checks(Section::ModelRelay).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_model_relay(&cfg, &[codex_agent(tmp.path())], &dead_probe(), &mut report);
        let checks: Vec<&Check> = report.section_checks(Section::ModelRelay).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 Model relay 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 system 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::ModelRelay, "Disabled in config")
                .code(crate::error::ERR_MODEL_RELAY_NOT_RUNNING)
                .remedy("`openlatch system model-relay enable`"),
        );
        report.push(
            Check::off(Section::Persistence, "Disabled at your request")
                .code(ERR_NO_SUPERVISOR)
                .remedy("`openlatch system supervision enable`"),
        );
        report.push(
            Check::off(Section::Policy, "Disabled in config")
                .code(ERR_POLICY_DISABLED)
                .remedy("remove [policy] enabled = false"),
        );

        for section in [Section::ModelRelay, 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"
        );
    }

    /// Issue #306, contract 1: a daemon whose cloud worker has latched
    /// `auth_error` must not read as healthy anywhere. `status` and `doctor`
    /// share this exact builder through `run_all_checks` (the "one question,
    /// one set of detectors" invariant), and `report.exit_code()` is what
    /// `record_verdict()` turns into the process's actual exit status — so
    /// proving both here proves the whole surface, not just the printed line.
    #[test]
    fn a_latched_auth_error_fails_the_cloud_section_not_green() {
        use crate::cli::report::State;

        let cfg = config::Config::defaults();
        let probe = DaemonProbe {
            alive: true,
            reachable: true,
            health: None,
            metrics: Some(serde_json::json!({
                "cloud_status": "auth_error",
                "cloud_api_url": "https://app.openlatch.ai",
                "egress_status": "ok",
            })),
            egress: Some(serde_json::json!({})),
            uptime_secs: Some(60),
        };

        let mut report = Report::new();
        check_cloud(&cfg, &probe, &mut report);
        let check = report
            .section_checks(Section::Cloud)
            .next()
            .expect("Cloud is always reported once the daemon answers");

        assert_eq!(
            check.state,
            State::Failed,
            "a latched auth_error must fail the section, never pass: {check:?}"
        );
        assert_eq!(check.code, Some(ERR_CLOUD_AUTH_FAILED));
        assert_eq!(
            report.exit_code(),
            1,
            "a failed section must not exit 0 — this is the number status and \
             doctor's process exit actually carries via record_verdict()"
        );
    }

    /// `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
        );
    }

    // -----------------------------------------------------------------------
    // The eighth guard site: `check_hooks` and an agent it cannot write into
    // -----------------------------------------------------------------------

    fn run_check_hooks(agents: &[DetectedAgent], ol_dir: &std::path::Path) -> Report {
        let mut report = Report::new();
        check_hooks(
            ol_dir,
            agents,
            None,
            &config::Config::defaults(),
            &dead_probe(),
            &mut report,
        );
        report
    }

    /// Neither red arm fires for an agent this build cannot write into.
    ///
    /// **Both arms, in one fixture, because guarding one leaves the other.**
    /// The first agent's hook path is absent — today that is
    /// `settings.json not found`, `ERR_HOOK_WRITE_FAILED`, remedying "Run
    /// `openlatch init`", a command that now refuses this very agent. The
    /// second's is a DIRECTORY, which `Path::exists()` answers `true` for, so
    /// control reaches `inspect_file`, which `read_to_string`s it and errors
    /// into `ERR_HOOK_MALFORMED_JSONC`.
    ///
    /// The control is the same two paths with `installable()` flipped: both
    /// redden, one per arm. Without it these assertions would pass against a
    /// `check_hooks` that had stopped looking at agents altogether.
    #[test]
    fn check_hooks_skips_non_installable_agents() {
        let ol = tempfile::tempdir().expect("temp dir");
        let absent = tempfile::tempdir().expect("temp dir");
        let directory = tempfile::tempdir().expect("temp dir");
        std::fs::create_dir_all(directory.path().join("settings.json")).expect("a hook DIRECTORY");

        // The helper creates neither hook path, so this caller arranges both:
        // nothing under the first, a DIRECTORY under the second. Those are the
        // two red arms.
        let skipped = vec![
            non_installable_agent("cline", absent.path()),
            non_installable_agent("cline-dir", directory.path()),
        ];
        assert!(
            !skipped[0].settings_path().exists() && skipped[1].settings_path().is_dir(),
            "the fixture must carry one absent path and one directory, or neither arm is reached"
        );

        let report = run_check_hooks(&skipped, ol.path());
        let stamped: Vec<&Check> = report
            .section_checks(Section::Hooks)
            .filter(|c| c.agent.is_some())
            .collect();
        assert!(
            stamped.is_empty(),
            "no per-agent Hooks finding may be raised for an agent this build \
             writes nothing into: {:?}",
            stamped.iter().map(|c| &c.headline).collect::<Vec<_>>()
        );

        // The control: identical paths, `installable()` flipped — one red per
        // arm, each stamped with its agent.
        let armed: Vec<DetectedAgent> = skipped
            .iter()
            .map(|a| DetectedAgent {
                kind: a.kind,
                binding: Arc::new(FakeBinding {
                    agent_type: a.agent_type(),
                    display_name: "Cline",
                    config_dir: a.config_dir(),
                    installable: true,
                    ..Default::default()
                }),
            })
            .collect();
        let control = run_check_hooks(&armed, ol.path());
        let codes: Vec<Option<&str>> = control
            .section_checks(Section::Hooks)
            .filter(|c| c.agent.is_some())
            .map(|c| c.code)
            .collect();
        assert_eq!(
            codes,
            vec![Some(ERR_HOOK_WRITE_FAILED), Some(ERR_HOOK_MALFORMED_JSONC)],
            "both arms are live for an installable agent at these very paths — \
             the guard is the only thing keeping them quiet above"
        );
    }

    /// The blocker the guard itself creates: `Section::Hooks` must not be empty.
    ///
    /// On a host whose ONLY agent is non-installable, every iteration is
    /// skipped, the `agents.is_empty()` early return does not fire — there IS
    /// an agent — and `Report::validate` fails a section with no check. One
    /// `Check::unknown` pointing at `Environment` is the answer the file
    /// already gives for the no-agent case, and `Environment` is where this
    /// agent's hook surface is actually reported.
    ///
    /// The second half is what keeps it from being pushed per skipped agent: on
    /// a host with a working agent AND a non-installable one, the section
    /// already has a real result and a cross beside it would be a cascade.
    #[test]
    fn hooks_section_is_not_empty_when_cline_is_the_only_agent() {
        let ol = tempfile::tempdir().expect("temp dir");
        let cline = tempfile::tempdir().expect("temp dir");

        let report = run_check_hooks(&[non_installable_agent("cline", cline.path())], ol.path());
        let checks: Vec<&Check> = report.section_checks(Section::Hooks).collect();
        assert_eq!(
            checks.len(),
            1,
            "exactly one check — the section is neither empty nor doubled: {:?}",
            checks.iter().map(|c| &c.headline).collect::<Vec<_>>()
        );
        assert_eq!(
            checks[0].state,
            State::Unknown(Section::Environment),
            "it points at the section that actually carries this agent's answer"
        );
        assert_eq!(
            checks[0].agent, None,
            "it is a statement about the section, not a finding against an agent"
        );

        // The remedy must be FOLLOWABLE. `Check::unknown`'s generated text says
        // "Fix Environment first" — and on this host Environment is green
        // (`check_environment` pushed `Check::ok(Environment, "Agent: …")`), so
        // that remedy points at nothing. Sending an operator to fix a section
        // that is passing is the defect class this guard exists to remove.
        let remedy = checks[0].remedy.as_deref().unwrap_or_default();
        assert!(
            !remedy.contains("Fix Environment first"),
            "the generated remedy is untrue here — Environment is green on a \
             host whose only agent is non-installable; got: {remedy}"
        );
        assert!(
            !remedy.is_empty() && checks[0].code.is_some(),
            "State::Unknown is a warning, so it still owes a code and a remedy"
        );

        // A working agent in front of it: the real result stands alone, with no
        // spurious cross beside it.
        let installed = tempfile::tempdir().expect("temp dir");
        let mixed = vec![
            installed_agent(
                installed.path(),
                LivenessReport {
                    armed: None,
                    detail: None,
                    remedy: None,
                    code: None,
                },
            ),
            non_installable_agent("cline", cline.path()),
        ];
        let mixed_report = run_check_hooks(&mixed, ol.path());
        assert!(
            !mixed_report
                .section_checks(Section::Hooks)
                .any(|c| matches!(c.state, State::Unknown(_))),
            "the loop pushed a real result, so nothing may be added after it: {:?}",
            mixed_report
                .section_checks(Section::Hooks)
                .map(|c| &c.headline)
                .collect::<Vec<_>>()
        );
    }

    /// A host whose only agent is one this build cannot write into is
    /// **degraded**, not broken — and deliberately not a pass.
    ///
    /// `State::Unknown` is a warning, so the report is `Degraded` and
    /// `exit_code()` is `EXIT_DEGRADED` (7). Asserting `0` here would report a
    /// host we protect nothing on as healthy, which the output contract
    /// forbids; asserting `1` would claim a breakage there is no remedy for.
    /// Today such a host exits 1 — "Agent not found" from Environment — so this
    /// is a move from broken to degraded, and it stays degraded until
    /// enforcement exists.
    ///
    /// Asserted on a CONSTRUCTED report, never through a sandbox: a sandbox has
    /// no daemon, so `doctor` exits non-zero there for reasons that have nothing
    /// to do with this branch.
    #[test]
    fn doctor_reports_degraded_not_failed_on_a_cline_only_host() {
        let ol = tempfile::tempdir().expect("temp dir");
        let cline = tempfile::tempdir().expect("temp dir");

        // Every other section green, so the exit code is decided by Hooks alone.
        let mut report = Report::new();
        for section in Section::ALL {
            if section != Section::Hooks {
                report.push(Check::ok(section, "fine"));
            }
        }
        check_hooks(
            ol.path(),
            &[non_installable_agent("cline", cline.path())],
            None,
            &config::Config::defaults(),
            &dead_probe(),
            &mut report,
        );

        assert!(
            report.validate().is_empty(),
            "every section must be reported — the empty-Hooks failure is the whole \
             reason the unknown is pushed: {:?}",
            report.validate()
        );
        assert_eq!(
            report.exit_code(),
            crate::cli::report::EXIT_DEGRADED,
            "a host whose only agent cannot be enforced is degraded, not healthy \
             and not broken"
        );
    }
    // -----------------------------------------------------------------------
    // The Cline attestation's two renderings (PRD C-1, DD-07)
    // -----------------------------------------------------------------------

    use crate::hooks::cline::{
        cline_isolated, ClineSeam, ASSETS_DIR_ENV, DATA_DIR_ENV, STORE_DIR_ENV,
    };

    /// A host whose `HOME` and all three Cline seams point inside one temp
    /// directory, with the seam guard held for the whole test.
    ///
    /// `HOME` is redirected as well as the seams because the six editor roots
    /// derive from `home_dir()`, which no seam covers — against the developer's
    /// real machine the AC-4 case below would invert depending on whether they
    /// happen to run Cursor. `cline_isolated` is what makes the rest fail
    /// loudly rather than by convention: a seam left unset panics here instead
    /// of quietly reading `~/.cline` (spec AC-8).
    ///
    /// **Field order is drop order.** The overrides go back before either lock
    /// is released, so a test blocked on the seam lock never observes another
    /// test's redirection.
    struct ClineHost {
        _seam: ClineSeam,
        _home_lock: std::sync::MutexGuard<'static, ()>,
        // Read only by the unix-gated accessors below. On Windows it is pure
        // RAII: the TempDir has to outlive the guard or the fixture directory
        // is removed before the test that depends on it finishes.
        #[cfg_attr(not(unix), allow(dead_code))]
        root: tempfile::TempDir,
    }

    impl ClineHost {
        /// A store root that exists, an empty home, and no extension anywhere.
        fn with_store() -> Self {
            let home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let root = tempfile::tempdir().expect("tempdir");
            std::fs::create_dir_all(root.path().join("home")).expect("home");
            std::fs::create_dir_all(root.path().join("store")).expect("store");

            let seam = cline_isolated([
                ("HOME", Some(root.path().join("home").into_os_string())),
                (
                    STORE_DIR_ENV,
                    Some(root.path().join("store").into_os_string()),
                ),
                (
                    DATA_DIR_ENV,
                    Some(root.path().join("data").into_os_string()),
                ),
                (
                    ASSETS_DIR_ENV,
                    Some(root.path().join("assets").into_os_string()),
                ),
            ]);

            Self {
                _seam: seam,
                _home_lock: home_lock,
                root,
            }
        }
    }

    // These accessors are pure temp-path arithmetic and compile everywhere;
    // what varies is whether any *caller* reaches them on a given platform.
    // Most of the tests that use them assert `$HOME`-relative layouts, so they
    // are `#[cfg(unix)]`, which on Windows can leave the whole group with no
    // callers and `-D warnings` failing `windows-cross` on dead code.
    //
    // `allow`, not `#[cfg(unix)]`, deliberately. Gating the definitions couples
    // them to how their callers happen to be gated today: the moment one
    // ungated test calls one — as `the_rollup_survives_the_attestation_being_
    // merged_into_it` does — a `cfg` gate turns into "no method named ...` on
    // Windows only. This keeps them compiled and type-checked on every
    // platform and simply forgives the unused ones.
    #[cfg_attr(not(unix), allow(dead_code))]
    impl ClineHost {
        fn home(&self) -> std::path::PathBuf {
            self.root.path().join("home")
        }

        fn store(&self) -> std::path::PathBuf {
            self.root.path().join("store")
        }

        /// Where Cline keeps the three config files the probe may open. The
        /// data root is a seam of its own, so this is NOT under `store()`.
        fn settings(&self) -> std::path::PathBuf {
            self.root.path().join("data").join("settings")
        }

        /// A Cline-lineage extension under one editor root.
        fn install_extension(&self) {
            std::fs::create_dir_all(
                self.home()
                    .join(".cursor")
                    .join("extensions")
                    .join("saoudrizwan.claude-dev-3.0.0"),
            )
            .expect("extension");
        }

        /// The agent list `doctor` would hold on this host.
        fn agents(&self) -> Vec<DetectedAgent> {
            vec![non_installable_agent("cline", &self.store())]
        }
    }

    /// The attestation is store-keyed: no Cline, no rows and no probe.
    ///
    /// The silence `doctor` already keeps about an undetected Codex CLI. Run
    /// under the seam guard deliberately — if the gate ever regresses, the
    /// probe it lets through reads the developer's real `~/.cline` rather than
    /// this fixture, and the guard is what says so.
    #[test]
    fn cline_attestation_is_silent_when_no_cline_is_detected() {
        let _host = ClineHost::with_store();
        let mut report = Report::new();

        let attestation = check_cline_surface(&[], &mut report);

        assert!(
            attestation.is_none(),
            "nothing detected, so there is nothing to attest"
        );
        assert_eq!(
            report.section_checks(Section::Environment).count(),
            0,
            "a row about an agent this host does not have is noise"
        );
    }

    /// Spec **AC-4**: the store is here and no editor root holds a
    /// Cline-lineage extension — `doctor` warns naming that state, and never
    /// renders green.
    #[cfg(unix)]
    #[test]
    fn cline_attestation_warns_when_the_store_has_no_extension() {
        let host = ClineHost::with_store();
        let mut report = Report::new();

        let attestation =
            check_cline_surface(&host.agents(), &mut report).expect("a detected Cline attests");
        assert!(
            attestation.store_without_extension(),
            "the fixture failed to produce AC-4's state, so this case proves nothing"
        );

        let checks: Vec<&Check> = report.section_checks(Section::Environment).collect();
        assert_eq!(checks.len(), 1, "one attestation, one row");
        let check = checks[0];

        assert_ne!(check.state, State::Ok, "never green (AC-4)");
        assert!(
            check.state.requires_remedy(),
            "a state nobody is asked to act on is not a warning"
        );
        assert!(
            check.headline.contains("no Cline-lineage extension"),
            "the warning must name the state, not just count absences: {}",
            check.headline
        );
        assert_eq!(check.code, Some(ERR_CLINE_SURFACE_ABSENT));
        assert!(
            check
                .remedy
                .as_deref()
                .is_some_and(|remedy| remedy.contains("editor root")),
            "the remedy must be followable — report the fork's editor root: {:?}",
            check.remedy
        );
        assert!(
            check.validate().is_none(),
            "a non-green check must carry both a code and a remedy: {:?}",
            check.validate()
        );
        assert_eq!(check.agent, Some("cline"), "the row names its agent");

        // The store root is the one string this attestation emits that no other
        // line in `doctor` carries, which is what an acceptance step greps for.
        let store = crate::core::path_compat::display_path(&host.store());
        assert!(
            check.detail.iter().any(|line| line.contains(&store)),
            "the human rendering must carry the resolved store root: {:?}",
            check.detail
        );
    }

    /// **DD-11**: `doctor` never renders green over a surface it could not
    /// read.
    ///
    /// The regression this pins: a surface classified from its `metadata()`
    /// alone, so a registry that is on disk and unparseable reported `present`,
    /// the row reached the green branch, and the detail line directly beneath
    /// it read `servers: undetermined`. One run, two renderings, two answers.
    /// No permissions dance is needed — the file is there and it is not JSON.
    #[cfg(unix)]
    #[test]
    fn cline_attestation_is_not_green_when_a_surface_could_not_be_read() {
        let host = ClineHost::with_store();
        host.install_extension();
        std::fs::create_dir_all(host.settings()).expect("settings dir");
        let registry = host.settings().join("cline_mcp_settings.json");
        std::fs::write(&registry, r#"{"mcpServers": "#).expect("a truncated registry");
        assert!(
            registry.is_file(),
            "the registry has to BE there, or this case is about a missing file instead"
        );

        let mut report = Report::new();
        let attestation =
            check_cline_surface(&host.agents(), &mut report).expect("a detected Cline attests");
        assert_eq!(
            attestation.state_of_surface(Surface::McpSettings),
            Some(SurfaceState::Undetermined),
            "the fixture failed to produce an unreadable surface, so this case proves nothing"
        );
        assert_eq!(
            attestation.state_of_surface(Surface::Extension),
            Some(SurfaceState::Present),
            "and the AC-4 warning is NOT what is being asserted below"
        );

        let checks: Vec<&Check> = report.section_checks(Section::Environment).collect();
        assert_eq!(checks.len(), 1, "one attestation, one row");
        let check = checks[0];

        assert_ne!(
            check.state,
            State::Ok,
            "green over a surface we could not read, beside a detail line that says so, is \
             the machine rendering and the human one disagreeing inside one run: {:?}",
            check.detail
        );
        assert_eq!(check.code, Some(ERR_CLINE_SURFACE_UNDETERMINED));
        assert!(
            check.validate().is_none(),
            "a non-green check must carry both a code and a remedy: {:?}",
            check.validate()
        );
        assert!(
            check
                .detail
                .iter()
                .chain(std::iter::once(&check.headline))
                .any(|line| line.contains("servers: undetermined")),
            "and the human rendering still names the list it could not read: {:?}",
            check.detail
        );
    }

    /// The store and the extension are both here: green, and the row still
    /// carries every fact the JSON does (DD-07 / P7).
    #[cfg(unix)]
    #[test]
    fn cline_attestation_is_green_when_the_extension_is_there_too() {
        let host = ClineHost::with_store();
        host.install_extension();
        let mut report = Report::new();

        let attestation =
            check_cline_surface(&host.agents(), &mut report).expect("a detected Cline attests");
        assert_eq!(
            attestation.state_of_surface(Surface::Extension),
            Some(SurfaceState::Present),
            "the fixture failed to install an extension, so green here would prove nothing"
        );

        let checks: Vec<&Check> = report.section_checks(Section::Environment).collect();
        assert_eq!(checks.len(), 1, "one attestation, one row");
        let check = checks[0];

        assert_eq!(check.state, State::Ok);
        let store = crate::core::path_compat::display_path(&host.store());
        assert!(
            check.headline.contains(&store),
            "the green headline carries the store root: {}",
            check.headline
        );
        // Isomorphism, the direction that catches the regression: every line of
        // the human rendering is on the check a human reads.
        let rendered: Vec<&str> = std::iter::once(check.headline.as_str())
            .chain(check.detail.iter().map(String::as_str))
            .collect();
        for line in attestation.human_lines() {
            assert!(
                rendered.contains(&line.as_str()),
                "the attestation says `{line}`, and the check a human reads does not: {rendered:?}"
            );
        }
    }

    /// The `--json` merge: `agents` beside the sections, never instead of them.
    #[cfg(unix)]
    #[test]
    fn json_document_carries_the_attestation_beside_the_sections() {
        let host = ClineHost::with_store();
        let mut report = Report::new();
        let cline = check_cline_surface(&host.agents(), &mut report);
        assert!(cline.is_some(), "the fixture must produce an attestation");

        let document = json_document(&DoctorReport {
            report,
            daemon_alive: false,
            daemon_uptime_secs: None,
            port: 0,
            cline,
        });

        assert!(
            document["sections"].is_array(),
            "the section report is untouched: {document}"
        );
        assert!(
            document["agents"]["cline"]["as_of"].is_string(),
            "the attestation is merged under agents.cline: {document}"
        );
        assert_eq!(
            document["agents"]["cline"]["store_root"]["path"],
            serde_json::json!(crate::core::path_compat::display_path(&host.store())),
        );
    }

    /// The rollup and the attestation are two things to say about one agent,
    /// and both have to survive being said.
    ///
    /// They are written by different producers — `Report::to_json` keys
    /// `agents` by agent and fills in `sections`; this module adds the probe —
    /// and they agreed on the key and on nothing else. An `insert` here erased
    /// the rollup and shipped `"agents": {}` on a host with two agents
    /// detected. The type assertions are the point: the contents were right
    /// both times, and the shape was what was lost.
    #[test]
    fn the_rollup_survives_the_attestation_being_merged_into_it() {
        let host = ClineHost::with_store();
        let mut report = Report::new();
        // A rollup for a DIFFERENT agent, so the test fails if the merge
        // replaces the map rather than joining it.
        report.push(crate::cli::report::Check::ok(Section::Hooks, "Enforced").agent("claude-code"));
        let cline = check_cline_surface(&host.agents(), &mut report);

        let document = json_document(&DoctorReport {
            report,
            daemon_alive: false,
            daemon_uptime_secs: None,
            port: 0,
            cline,
        });

        let agents = document["agents"]
            .as_object()
            .unwrap_or_else(|| panic!("agents must stay an object: {document}"));
        assert!(
            agents["claude-code"]["sections"].is_array(),
            "another agent's rollup must survive the merge: {document}"
        );
        assert!(
            agents["cline"]["as_of"].is_string(),
            "and the attestation must land beside it: {document}"
        );
    }

    /// No attested agent is an empty object, never a missing key: a consumer
    /// indexes into one shape on every host.
    ///
    /// `Report::new()` also has no agent-tagged check, so there is no rollup to
    /// merge into — the other half of the same claim.
    #[test]
    fn json_document_carries_an_empty_agents_object_without_cline() {
        let document = json_document(&DoctorReport {
            report: Report::new(),
            daemon_alive: false,
            daemon_uptime_secs: None,
            port: 0,
            cline: None,
        });

        assert_eq!(document["agents"], serde_json::json!({}));
    }
}