linesmith 0.1.3

A Rust status line for Claude Code and other AI coding CLIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
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
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
//! `linesmith doctor` — diagnostic subcommand. Renders a categorized
//! health report with PASS / WARN / FAIL / SKIP severities, then exits
//! with a contract-defined code (any FAIL → 1; otherwise 0). Spec:
//! `docs/specs/doctor.md`.
//!
//! Encapsulation note: `CheckResult` hides its fields behind
//! constructors because severity and hint must agree (PASS forbids
//! hints; non-PASS requires them). `Category` and `Report` have no
//! cross-field invariants, so their fields stay public — same shape
//! as `std::process::Output`. If `Category` grows a non-empty-name
//! invariant or `Report` gains check-id-uniqueness, both gain
//! constructors and seal their fields.

use std::collections::BTreeSet;
use std::io::{IsTerminal, Write};
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};

use crate::config::{Config, ConfigPath};

mod snapshot;
use snapshot::*;

/// One of four outcomes a check can report. See `docs/specs/doctor.md`
/// §Severity levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Severity {
    Pass,
    Warn,
    Fail,
    Skip,
}

impl Severity {
    /// Unicode glyph (used unless `--plain`).
    #[must_use]
    pub fn unicode_glyph(self) -> &'static str {
        match self {
            Self::Pass => "",
            Self::Warn => "",
            Self::Fail => "",
            Self::Skip => "·",
        }
    }

    /// ASCII glyph (used under `--plain`).
    #[must_use]
    pub fn ascii_glyph(self) -> &'static str {
        match self {
            Self::Pass => "OK",
            Self::Warn => "!!",
            Self::Fail => "XX",
            Self::Skip => "--",
        }
    }
}

/// One check's outcome. Construct via [`CheckResult::pass`],
/// [`CheckResult::warn`], [`CheckResult::fail`], or
/// [`CheckResult::skip`] — direct construction is not allowed so the
/// "PASS-with-hint" anti-state is unrepresentable. `id` is the stable
/// machine-readable key documented in `docs/specs/doctor.md` §JSON
/// output; reserved for v0.2 `--json` consumers but populated now so
/// adding a serializer later is purely additive.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CheckResult {
    pub(crate) severity: Severity,
    pub(crate) id: &'static str,
    pub(crate) label: String,
    /// Renders as an indented second line. PASS constructors don't
    /// accept this; non-PASS constructors require it.
    pub(crate) hint: Option<String>,
}

impl CheckResult {
    /// PASS check. Hints are not accepted — there's nothing to remediate.
    #[must_use]
    pub fn pass(id: &'static str, label: impl Into<String>) -> Self {
        Self {
            severity: Severity::Pass,
            id,
            label: label.into(),
            hint: None,
        }
    }

    /// WARN check. `hint` is required so the user has something
    /// actionable to read on the indented second line.
    #[must_use]
    pub fn warn(id: &'static str, label: impl Into<String>, hint: impl Into<String>) -> Self {
        Self {
            severity: Severity::Warn,
            id,
            label: label.into(),
            hint: Some(hint.into()),
        }
    }

    /// FAIL check. `hint` is required.
    #[must_use]
    pub fn fail(id: &'static str, label: impl Into<String>, hint: impl Into<String>) -> Self {
        Self {
            severity: Severity::Fail,
            id,
            label: label.into(),
            hint: Some(hint.into()),
        }
    }

    /// SKIP check. `reason` explains why the check didn't run (e.g.
    /// "config not loaded", "no plugins configured"); rendered on the
    /// indented second line.
    #[must_use]
    pub fn skip(id: &'static str, label: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            severity: Severity::Skip,
            id,
            label: label.into(),
            hint: Some(reason.into()),
        }
    }

    #[must_use]
    pub fn severity(&self) -> Severity {
        self.severity
    }

    /// Stable machine-readable identifier (e.g. `"env.stdout_tty"`).
    /// Reserved for v0.2 `--json` consumers and structured logging;
    /// not surfaced in the human renderer.
    #[must_use]
    pub fn id(&self) -> &'static str {
        self.id
    }

    /// Human-readable label rendered next to the severity glyph.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Remediation hint (for WARN / FAIL) or skip reason (for SKIP),
    /// or `None` for PASS. Rendered as an indented second line.
    #[must_use]
    pub fn hint(&self) -> Option<&str> {
        self.hint.as_deref()
    }
}

/// One named group of checks, e.g. `"Environment"`, `"Config"`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Category {
    pub name: &'static str,
    pub checks: Vec<CheckResult>,
}

impl Category {
    #[must_use]
    pub fn new(name: &'static str, checks: Vec<CheckResult>) -> Self {
        Self { name, checks }
    }
}

/// Aggregated severity histogram, one count per [`Severity`] variant.
/// Named fields prevent positional-destructure mistakes when the
/// renderer / JSON serializer reads them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SummaryCounts {
    pub pass: usize,
    pub warn: usize,
    pub fail: usize,
    pub skip: usize,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Report {
    pub linesmith_version: &'static str,
    pub categories: Vec<Category>,
}

impl Report {
    /// Build a `Report`. The struct is `#[non_exhaustive]` so
    /// struct-literal construction is blocked downstream; integration
    /// tests and any future out-of-crate consumers go through this so
    /// new fields land in one place.
    #[must_use]
    pub fn new(linesmith_version: &'static str, categories: Vec<Category>) -> Self {
        Self {
            linesmith_version,
            categories,
        }
    }

    /// Any FAIL → 1, otherwise 0. Usage errors (bad flags) are handled
    /// by the parser and never reach this function — don't add a `2`
    /// branch here.
    #[must_use]
    pub fn exit_code(&self) -> u8 {
        if self
            .categories
            .iter()
            .flat_map(|c| &c.checks)
            .any(|c| c.severity == Severity::Fail)
        {
            1
        } else {
            0
        }
    }

    #[must_use]
    pub fn summary_counts(&self) -> SummaryCounts {
        let mut counts = SummaryCounts::default();
        for c in self.categories.iter().flat_map(|c| &c.checks) {
            match c.severity {
                Severity::Pass => counts.pass += 1,
                Severity::Warn => counts.warn += 1,
                Severity::Fail => counts.fail += 1,
                Severity::Skip => counts.skip += 1,
            }
        }
        counts
    }
}

/// Render mode for the report. `Plain` swaps Unicode glyphs for ASCII
/// and uses an ASCII summary separator.
///
/// **Plain-mode caveat:** the renderer guarantees no Unicode bytes in
/// the strings *it* emits (glyphs, separators, fixed labels). User-
/// supplied `label` and `hint` strings (paths like `~/café/config`,
/// gix branch names, parser errors) pass through verbatim. CI scripts
/// that need byte-clean ASCII should ASCII-fold their environment, not
/// rely on `--plain` to do it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RenderMode {
    Default,
    Plain,
}

/// Render `report` to `out`. Tree-style: header + version, then each
/// category as a name line followed by indented checks. Non-PASS
/// checks emit an indented hint/reason line.
///
/// On I/O error, partial output may already have been flushed —
/// including a missing `Exit:` line. Callers that parse doctor output
/// must treat a truncated report (no `Exit:` line) as "I/O failed
/// mid-render," not as a successful run.
///
/// # Errors
///
/// Returns the first `io::Error` from a `writeln!` to `out`.
pub fn render(out: &mut dyn Write, report: &Report, mode: RenderMode) -> std::io::Result<()> {
    writeln!(out, "linesmith doctor (v{})", report.linesmith_version)?;
    for category in &report.categories {
        writeln!(out)?;
        writeln!(out, "{}", category.name)?;
        for check in &category.checks {
            let glyph = match mode {
                RenderMode::Default => check.severity.unicode_glyph(),
                RenderMode::Plain => check.severity.ascii_glyph(),
            };
            writeln!(out, "  {glyph} {}", check.label)?;
            if let Some(hint) = &check.hint {
                writeln!(out, "    -> {hint}")?;
            }
        }
    }
    writeln!(out)?;
    let counts = report.summary_counts();
    let sep = match mode {
        RenderMode::Default => "·",
        RenderMode::Plain => "/",
    };
    writeln!(
        out,
        "Summary: {} PASS {sep} {} WARN {sep} {} FAIL {sep} {} SKIP",
        counts.pass, counts.warn, counts.fail, counts.skip,
    )?;
    writeln!(out, "Exit: {}", report.exit_code())?;
    Ok(())
}

/// One environment variable's read state. Distinguishes the three
/// outcomes a check has to remediate differently: not present (set
/// it), set-to-empty (also set it), set-but-non-UTF-8 (the hint
/// "set $X" would be wrong — `$X` *is* set, it's just unreadable).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EnvVarState {
    Unset,
    Set(String),
    /// Variable is set but the value contains bytes that aren't valid
    /// UTF-8. Carries both a `lossy` preview (for hint output) and the
    /// `raw` `OsString` (for plumbing through to APIs that accept
    /// `OsStr` — e.g., the XDG cascade preserves these bytes through
    /// `Path` operations).
    NonUtf8 {
        lossy: String,
        raw: std::ffi::OsString,
    },
}

impl EnvVarState {
    fn snapshot(name: &str) -> Self {
        match std::env::var(name) {
            Ok(s) => Self::Set(s),
            Err(std::env::VarError::NotPresent) => Self::Unset,
            Err(std::env::VarError::NotUnicode(raw)) => {
                let lossy = raw.to_string_lossy().into_owned();
                Self::NonUtf8 { lossy, raw }
            }
        }
    }

    /// Test-only constructor for the `NonUtf8` variant. Real code
    /// always goes through [`Self::snapshot`].
    #[cfg(test)]
    fn non_utf8_for_test(s: impl Into<String>) -> Self {
        let lossy = s.into();
        let raw = std::ffi::OsString::from(&lossy);
        Self::NonUtf8 { lossy, raw }
    }

    /// Convenience accessor: `Some(s)` only when the variable is set
    /// AND non-empty AND valid UTF-8. Centralizes the
    /// `Some(s) if !s.is_empty()` predicate that every consumer would
    /// otherwise duplicate. Use [`Self::nonempty_os`] when the
    /// downstream API accepts `OsStr` and non-UTF-8 bytes should
    /// survive.
    #[must_use]
    pub fn nonempty(&self) -> Option<&str> {
        match self {
            Self::Set(s) if !s.is_empty() => Some(s),
            _ => None,
        }
    }

    /// `OsStr`-typed companion to [`Self::nonempty`]. Returns `Some`
    /// for both `Set` and `NonUtf8` non-empty values, preserving
    /// non-UTF-8 bytes for path-shaped consumers.
    #[must_use]
    pub fn nonempty_os(&self) -> Option<&std::ffi::OsStr> {
        match self {
            Self::Set(s) if !s.is_empty() => Some(std::ffi::OsStr::new(s)),
            Self::NonUtf8 { raw, .. } if !raw.is_empty() => Some(raw),
            _ => None,
        }
    }
}

/// State of `~/.claude/` per spec §Claude Code "directory" row.
#[derive(Debug)]
#[non_exhaustive]
pub enum ClaudeDirState {
    Ok,
    /// `metadata()` failed with `PermissionDenied`.
    PermissionDenied {
        message: String,
    },
    NotADirectory,
    Missing,
    /// Unexpected I/O error from `metadata()`. `EINTR` (transient)
    /// lands here too; doctor renders WARN so a re-run can clear.
    OtherIo {
        message: String,
    },
}

/// State of `~/.claude.json` per spec §Claude Code "parses" row.
#[derive(Debug)]
#[non_exhaustive]
pub enum ClaudeJsonState {
    /// `oauthAccount` key is present. Per spec wording "block
    /// present", any value (including `null`) counts — the WARN
    /// row triggers on the *key* being absent, not the value.
    Ok,
    NoOauthAccount,
    /// File exceeds the spec's 2 MB read cap (see
    /// `docs/specs/doctor.md` §Edge cases). Spec rules a 500 MB
    /// `~/.claude.json` is pathological / corrupt and the doctor
    /// must FAIL fast rather than spend memory + time parsing it.
    /// `actual_bytes` is the on-disk size for the diagnostic hint.
    TooLarge {
        actual_bytes: u64,
    },
    /// `serde_json::Error::Display` already includes the `at line N
    /// column M` suffix; surface the message verbatim so the spec
    /// hint stays actionable.
    ParseError {
        message: String,
    },
    Missing,
    IoError {
        message: String,
    },
}

/// State of `~/.claude/sessions/` per spec §Claude Code "Recent
/// sessions recorded" row.
#[derive(Debug)]
#[non_exhaustive]
pub enum ClaudeSessionsState {
    HasFiles { count: usize },
    Empty,
    Missing,
    NotADirectory,
    IoError { message: String },
}

/// Filesystem-side state of the Claude Code integration. Wrapped in
/// `Option` on the snapshot because the three filesystem checks all
/// depend on a resolvable `$HOME`; the binary-presence check
/// (`which claude`) walks `$PATH` and stays meaningful regardless.
#[derive(Debug)]
#[non_exhaustive]
pub struct ClaudeHomeState {
    pub dir: ClaudeDirState,
    pub claude_json: ClaudeJsonState,
    pub sessions: ClaudeSessionsState,
}

/// Snapshot of every input the Claude Code category needs. Built
/// once at the call boundary so checks stay pure.
#[derive(Debug)]
#[non_exhaustive]
pub struct DoctorClaudeCodeSnapshot {
    /// First entry in `$PATH` containing an executable named
    /// `claude` (or `claude.exe` on Windows). `None` when the
    /// binary isn't on `$PATH`.
    pub binary_path: Option<PathBuf>,
    /// Whether `$PATH` itself was readable. Carried separately so
    /// the binary check can distinguish "no claude on PATH" from
    /// "couldn't read PATH at all" — the user-facing remediation
    /// is the same, but the diagnostic is different.
    pub path_env: EnvVarState,
    /// Filesystem-side state. `None` when `$HOME` is unresolved;
    /// the dir / json / sessions checks then render SKIP.
    pub home_state: Option<ClaudeHomeState>,
}

/// Lossy summary of `CredentialError` for the doctor snapshot. The
/// raw `CredentialError` carries `serde_json::Error` whose Display
/// impl can include token bytes (parser context shows neighboring
/// JSON); doctor snapshots store only the variant tag + path so a
/// future renderer change can't accidentally leak.
#[derive(Debug)]
#[non_exhaustive]
pub enum CredentialErrorSummary {
    NoCredentials,
    SubprocessFailed { message: String },
    IoError { path: PathBuf, message: String },
    ParseError { path: PathBuf },
    MissingField { path: PathBuf },
    EmptyToken { path: PathBuf },
}

/// Resolved credentials projected to the fields doctor needs. The
/// raw token NEVER reaches this struct — only the cascade source +
/// scope list.
#[derive(Debug)]
#[non_exhaustive]
pub struct CredentialsSummary {
    pub source: crate::data_context::credentials::CredentialSource,
    pub scopes: Vec<String>,
}

/// Snapshot of the credentials cascade. Wraps the result of
/// `resolve_credentials()` minus the bearer token.
#[derive(Debug)]
#[non_exhaustive]
pub enum DoctorCredentialsSnapshot {
    /// Credentials resolved cleanly; checks render PASS.
    Resolved(CredentialsSummary),
    /// Cascade failed. The variant determines which downstream
    /// Credentials checks render FAIL vs SKIP.
    Failed(CredentialErrorSummary),
    /// `$HOME` unresolved AND macOS keychain unavailable —
    /// cascade can't even be attempted. Distinct from `Failed`
    /// because the spec §Cross-category short-circuits says all
    /// file-based Credentials checks SKIP, not FAIL, when $HOME
    /// is missing.
    Unresolvable,
}

/// State of the cache root directory. Determined by read-only stat
/// only: doctor does NOT probe-write. POSIX permission bits and
/// existence checks let us distinguish the "first-run, runtime will
/// create it" case (PASS) from the "absent under a permanently
/// non-creatable path" case (WARN), without the read-only-contract
/// violation an actual probe-write would cause.
#[derive(Debug)]
#[non_exhaustive]
pub enum CacheRootState {
    /// Directory exists and is readable.
    Exists,
    /// Directory doesn't exist and the first existing ancestor is
    /// writable. Expected first-run state — PASS with a "will be
    /// created on first fetch" hint.
    Absent,
    /// Directory doesn't exist AND the first existing ancestor is
    /// read-only (e.g. `XDG_CACHE_HOME` points into a read-only mount
    /// like `/proc`, or the user pointed it at a path under an
    /// ancestor with the user-write bit cleared). WARN: the runtime's
    /// `create_dir_all` will fail on every fetch; without this signal
    /// doctor would report all-green forever for an unfixable setup.
    /// `parent` is the read-only ancestor for the hint.
    AbsentParentReadOnly { parent: PathBuf },
    /// Path exists but as a regular file. (`std::fs::metadata` follows
    /// symlinks, so a symlink resolving to a non-directory lands here
    /// too; broken symlinks resolve to `Absent` via the NotFound arm.)
    /// Real misconfiguration — WARN so the user knows to remove it
    /// before runtime tries to use the path.
    NotADirectory,
    /// `metadata()` failed for a reason other than NotFound (e.g.
    /// permission denied on an ancestor). `message` carries the
    /// rendered `io::Error` so the hint can name the cause.
    Unreadable { message: String },
    /// `$HOME` and `$XDG_CACHE_HOME` both unresolvable; no cache
    /// path could be derived.
    Unresolved,
}

/// State of `usage.json` per spec §Cache "shape current" row.
#[derive(Debug)]
#[non_exhaustive]
pub enum UsageJsonState {
    /// File missing — first-run state, treated as PASS (the next
    /// fetch creates it). Distinct from the spec's PASS row but
    /// matches the spirit ("safe to ignore; next fetch rewrites").
    Missing,
    /// File parses as `CachedUsage`, schema matches, and
    /// `cached_at <= now`. Matches the runtime cache reader's
    /// `Some(entry)` path.
    Current { schema_version: u32 },
    /// File present with a different `schema_version` than the
    /// current code expects.
    Stale { schema_version: u32 },
    /// Parsed cleanly but `cached_at` is in the future. The
    /// runtime reader treats this as a cache miss (clock skew);
    /// doctor surfaces it so the user can fix NTP rather than
    /// puzzle over a stale-data segment.
    FutureTimestamp,
    /// Read or parse failed in a way that doesn't surface to the
    /// runtime cache reader (which silently treats these as a miss).
    /// Doctor still reports them so the user knows about latent
    /// corruption.
    Unreadable { message: String },
}

/// State of `usage.lock` per spec §Cache "Lock file is fresh" row.
#[derive(Debug)]
#[non_exhaustive]
pub enum LockState {
    /// File absent. No rate-limit backoff is currently active.
    Absent,
    /// Lock present and `blocked_until > now`.
    Active { blocked_until_secs: i64 },
    /// Lock present but `blocked_until` is in the past — the user
    /// can `rm` to clear it.
    Stale { blocked_until_secs: i64 },
    /// Read failed for a reason other than absence.
    Unreadable { message: String },
}

/// Snapshot of cache state — root dir + usage.json + lock.
#[derive(Debug)]
#[non_exhaustive]
pub struct DoctorCacheSnapshot {
    /// Resolved cache root path, or `None` when the cascade
    /// (`$XDG_CACHE_HOME`, `$HOME/.cache`) yielded nothing.
    pub root_path: Option<PathBuf>,
    pub root: CacheRootState,
    pub usage_json: UsageJsonState,
    pub lock: LockState,
}

/// Outcome of one rate-limit-endpoint probe. Doctor snapshots a
/// single dry-run probe (no cache mutation) at `from_process` time.
#[derive(Debug)]
#[non_exhaustive]
pub enum EndpointProbeOutcome {
    /// `200 OK` and the body deserialized into the expected shape
    /// (with no unexpected forward-compat keys).
    Ok,
    /// `200 OK` and shape OK, but `elapsed >= 2s`.
    Slow,
    /// Body parsed into `UsageApiResponse` but had codenamed /
    /// unknown top-level keys (forward-compat keys Anthropic
    /// added without notice).
    UnexpectedShape { extra_keys: Vec<String> },
    /// `200 OK` but body didn't deserialize — endpoint shape changed.
    ParseError,
    /// Transport-level failure: DNS, TLS, connect/read timeout,
    /// captive portal, proxy refusal.
    TransportError,
    /// `4xx` other than `429` (e.g. `401` revoked token, `403`
    /// scope missing).
    BadStatus { status: u16 },
    /// `429 Too Many Requests`. `retry_after_secs` is the parsed
    /// `Retry-After` header value, or `None` when the header was
    /// absent.
    RateLimited { retry_after_secs: Option<u64> },
}

/// Snapshot of the rate-limit endpoint probe. `probe = None`
/// when the probe couldn't even be attempted (no token, etc.).
/// `credentials_vanished = true` flags the rare race where the
/// snapshot's first `resolve_credentials()` call succeeded but
/// the probe's second call failed (keychain locked between, file
/// removed, login expired); the orchestrator renders a distinct
/// SKIP reason so the user doesn't read "Resolved" alongside
/// "endpoint probe not attempted".
#[derive(Debug)]
#[non_exhaustive]
pub struct DoctorEndpointSnapshot {
    pub probe: Option<EndpointProbe>,
    pub credentials_vanished: bool,
}

#[derive(Debug)]
#[non_exhaustive]
pub struct EndpointProbe {
    pub elapsed_ms: u128,
    pub outcome: EndpointProbeOutcome,
}

/// Snapshot of plugin discovery for the Plugins category.
///
/// Built by delegating to the runtime predicate
/// (`PluginRegistry::load_with_xdg`) — the same helper the live
/// segment loader uses — so the doctor can never report PASS for
/// a plugin set the runtime would silently reject. See
/// the doctor-runtime parity rule.
#[derive(Debug)]
#[non_exhaustive]
pub enum DoctorPluginsSnapshot {
    /// No plugin sources to scan. Either no `plugin_dirs` in the
    /// loaded config AND no `$XDG_CONFIG_HOME/linesmith/segments/`
    /// on disk, OR `$HOME` is unresolved and no XDG override
    /// exists. Per spec §Edge cases this SKIPs all 4 plugin checks.
    NoSources,
    /// Discovery ran. May have zero plugins (vacuous PASS) or load
    /// errors classified at render time per `PluginError` variant.
    Discovered(PluginsRegistrySummary),
}

/// Result of one `PluginRegistry::load_with_xdg` pass — the
/// runtime's predicate, lifted into a snapshot for the Plugins
/// checks.
#[derive(Debug)]
#[non_exhaustive]
pub struct PluginsRegistrySummary {
    /// Number of plugins that compiled successfully (one render
    /// each is what the runtime would do).
    pub compiled_count: usize,
    /// Load-time errors (`Compile`, `MalformedDataDeps`,
    /// `UnknownDataDep`, `IdCollision`). Render-time errors
    /// (Runtime / Timeout / ResourceExceeded / MalformedReturn)
    /// don't surface here — the doctor doesn't render plugins.
    pub errors: Vec<linesmith_plugin::PluginError>,
}

/// Snapshot of `gix::discover(cwd)` outcome for the Git category.
///
/// Built by delegating to `data_context::git::resolve_repo` — the
/// same predicate the runtime's `git_*` segments consume. Every
/// state the runtime distinguishes (NotInRepo / Repo / corrupt)
/// surfaces here verbatim.
#[derive(Debug)]
#[non_exhaustive]
pub enum DoctorGitSnapshot {
    /// `gix::discover(cwd)` returned `Ok(None)` — the user's cwd
    /// is not inside a repo. Spec gates the severity on whether
    /// any `git_*` segment is enabled in the config.
    NotInRepo,
    /// Repo resolved cleanly; HEAD + RepoKind are populated.
    Repo(GitContextSummary),
    /// `gix::discover` or `resolve_head` failed (corrupt repo,
    /// permission error, ceiling-dir misconfig).
    Failed { message: String },
}

/// Subset of `data_context::git::GitContext` the doctor renders.
/// Drops the lazy `dirty` / `upstream` cells (doctor doesn't need
/// to walk the full status) and the underlying `gix::Repository`
/// handle (not Send + Sync, would prevent the snapshot from being
/// freely shared).
#[derive(Debug)]
#[non_exhaustive]
pub struct GitContextSummary {
    pub repo_path: PathBuf,
    pub repo_kind: crate::data_context::git::RepoKind,
    pub head: crate::data_context::git::Head,
}

/// Outcome of probing the GitHub releases API for the latest
/// linesmith release. Per spec §Self the severity mapping is
/// `Latest` → PASS and every other variant → WARN; never FAIL, so an
/// offline doctor run still exits 0. The four-variant split lets the
/// renderer pick a hint targeted at the actual failure mode rather
/// than a generic "couldn't check upstream".
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DoctorUpdateProbe {
    /// Running on the latest release.
    Latest,
    /// A newer release is available upstream. `latest` is the upstream
    /// `tag_name` (sanitized: control bytes stripped, length capped at
    /// 64 chars) so the renderer can surface what GitHub shipped
    /// without re-canonicalizing.
    Newer { latest: String },
    /// Transport-level failure: DNS, connect, read timeout, proxy
    /// refusal, captive portal, non-2xx HTTP status, or response body
    /// exceeding `UPDATE_PROBE_MAX_BYTES`. `message` is clamped to one
    /// line + 200 chars to bound diagnostic strings (which can echo
    /// body fragments via `io::Error` / `ureq::Error`).
    TransportError { message: String },
    /// 2xx response whose body didn't carry the expected `tag_name`
    /// shape (GitHub API change, MITM proxy, mixed-parseability where
    /// one side parses as semver and the other doesn't). Distinct
    /// from `TransportError` so the WARN hint can point at "GitHub
    /// API shape changed" rather than "no network". `message` is
    /// clamped the same way as `TransportError`.
    ParseError { message: String },
}

/// Outcome of attempting to read + parse the resolved config file.
/// Snapshot-shaped: every variant carries enough state for the Config
/// checks to render PASS/WARN/FAIL/SKIP without re-touching the
/// filesystem or re-parsing TOML.
#[derive(Debug)]
#[non_exhaustive]
pub enum ConfigReadOutcome {
    /// No source resolved a config path. Distinct from `NotFound`
    /// because the cascade itself failed (e.g. `$HOME` unset and no
    /// `--config` / `XDG_CONFIG_HOME` / `LINESMITH_CONFIG`); a
    /// `NotFound` means the cascade *did* land somewhere but nothing
    /// was on disk.
    Unresolved,
    /// Resolved path doesn't exist. `explicit` is `true` when the
    /// path came from `--config` or `LINESMITH_CONFIG` (user named
    /// it directly) so the discovery check can hint differently than
    /// for the implicit XDG fallback.
    NotFound { path: PathBuf, explicit: bool },
    /// `fs::read_to_string` failed for a reason other than NotFound
    /// (e.g. permission denied). `message` carries the rendered
    /// `io::Error` so the hint can surface the actual cause —
    /// "permission denied" vs "is a directory" need different fixes.
    IoError { path: PathBuf, message: String },
    /// TOML parse failed. `message` is the rendered `toml::de::Error`
    /// which already includes line/col + the offending token. The
    /// renderer emits it verbatim; callers don't re-extract spans.
    ParseError { path: PathBuf, message: String },
    /// Read + parsed successfully. `Config` is boxed because it
    /// dwarfs the other variants (~260 bytes vs. ~48); inlining it
    /// would bloat every snapshot, including the common-case
    /// `NotFound`/`Unresolved` variants the first-run user hits.
    Loaded { path: PathBuf, config: Box<Config> },
}

/// Stat result for one entry in `config.plugin_dirs`. Captured at
/// snapshot time so the plugin-dirs check is pure: it iterates the
/// vec and renders, never touching the filesystem itself.
#[derive(Debug)]
#[non_exhaustive]
pub struct PluginDirStatus {
    pub path: PathBuf,
    pub state: PluginDirState,
}

/// Disposition of one plugin directory. `Missing` and `NotADirectory`
/// are WARN territory ("user typo'd a path"); `PermissionDenied` and
/// `OtherIo` are FAIL territory ("the user can't fix this from
/// config alone"). The split keeps the spec's WARN-vs-FAIL contract
/// explicit at the data layer instead of in the renderer.
#[derive(Debug)]
#[non_exhaustive]
pub enum PluginDirState {
    Ok,
    Missing,
    NotADirectory,
    PermissionDenied { message: String },
    OtherIo { message: String },
}

/// Snapshot of the config-resolution + read + plugin-dir-stat
/// pipeline. Lives on [`DoctorEnv`] so a test fixture can express
/// "config loaded fine" vs "parse error" vs "permission denied" by
/// constructing the variant directly, without writing files to a
/// tempdir.
#[derive(Debug)]
#[non_exhaustive]
pub struct DoctorConfigSnapshot {
    /// The CLI-supplied `--config` path, if any. Carried alongside
    /// `resolved` so a snapshot is self-describing for tests and so
    /// future checks can distinguish `--config` from `LINESMITH_CONFIG`
    /// when both could plausibly land on the same `resolved.path`.
    pub cli_override: Option<PathBuf>,
    /// Resolved config path per the cascade in
    /// `crate::config::resolve_config_path`, or `None` when no
    /// source resolved.
    pub resolved: Option<ConfigPath>,
    /// Outcome of attempting to read + parse `resolved`.
    pub read: ConfigReadOutcome,
    /// One entry per `[plugin_dirs]` element in the loaded config.
    /// Empty when no config loaded or `plugin_dirs` is empty.
    pub plugin_dirs: Vec<PluginDirStatus>,
    /// Every segment id known to the runtime: built-ins plus the
    /// `const ID` of every successfully-compiled plugin `.rhai`.
    /// Snapshotting prevents the doctor from WARNing on plugin
    /// segments that load fine — the spec hint "install the plugin
    /// that provides it" is only correct when no plugin is providing
    /// it. Built-ins are always present; plugin ids are added when
    /// `read = Loaded` and discovery succeeds.
    pub known_segment_ids: BTreeSet<String>,
    /// Every theme name known to the runtime: built-ins plus every
    /// `*.toml` loaded from the user themes directory. Same reason
    /// as `known_segment_ids` — `theme = "neon"` from a valid user
    /// theme should not WARN.
    pub known_theme_names: BTreeSet<String>,
}

impl DoctorConfigSnapshot {
    /// Built-in segment ids as a fresh `BTreeSet`. Both the
    /// production snapshot and test fixtures seed `known_segment_ids`
    /// from this so the two views can't drift.
    #[must_use]
    pub fn built_in_segment_ids() -> BTreeSet<String> {
        crate::segments::BUILT_IN_SEGMENT_IDS
            .iter()
            .map(|s| (*s).to_string())
            .collect()
    }

    /// Built-in theme names as a fresh `BTreeSet`.
    #[must_use]
    pub fn built_in_theme_names() -> BTreeSet<String> {
        crate::theme::builtin_names().map(str::to_string).collect()
    }

    /// Baseline "config loaded fine" fixture. `cfg(test)` keeps it
    /// out of the public API.
    #[cfg(test)]
    fn healthy() -> Self {
        Self {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::Loaded {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                config: Box::new(Config::default()),
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: Self::built_in_segment_ids(),
            known_theme_names: Self::built_in_theme_names(),
        }
    }
}

/// Snapshot of the process state the doctor inspects, taken once at
/// the call boundary and handed to [`build_report`]. Snapshotting
/// keeps checks pure and tests hermetic — no test races the live env
/// or sees mutations from a parallel test.
///
/// Deliberately does NOT derive `Clone`: `current_exe` carries an
/// `io::Error` which isn't `Clone`, and rebuilding the snapshot
/// (test fixture or `from_process()`) is the right pattern when a
/// caller wants a fresh one.
#[derive(Debug)]
#[non_exhaustive]
pub struct DoctorEnv {
    /// Raw `$HOME` env var. NOT the `dirs::home_dir()` resolved path
    /// — Unix `dirs` falls back to passwd entries which this snapshot
    /// does not capture. Slices that need the resolved home directory
    /// (e.g. Config) compute it themselves.
    pub home_env: EnvVarState,
    pub xdg_config_home: EnvVarState,
    pub xdg_cache_home: EnvVarState,
    /// `$LINESMITH_CONFIG` override, second in the config-path
    /// cascade after `--config`. See `crate::config::resolve_config_path`.
    pub linesmith_config: EnvVarState,
    pub term: EnvVarState,
    pub colorterm: EnvVarState,
    pub no_color: bool,
    /// `Ok(path)` when `std::env::current_exe()` succeeds; the error
    /// is preserved (rather than collapsed to `None`) so the binary-
    /// path check can render the actual cause — "permission denied"
    /// vs "broken symlink" vs "/proc unavailable" all need different
    /// remediation hints.
    pub current_exe: Result<PathBuf, std::io::Error>,
    pub stdout_is_terminal: bool,
    pub terminal_width_cells: Option<u16>,
    /// Snapshot of the config-resolution pipeline. Read + parse +
    /// plugin-dir stats happen at snapshot time so the Config-category
    /// checks render purely from this struct.
    pub config: DoctorConfigSnapshot,
    /// Snapshot of the Claude Code integration state — `which
    /// claude`, `~/.claude/`, `~/.claude.json`, and the sessions
    /// directory.
    pub claude_code: DoctorClaudeCodeSnapshot,
    /// Snapshot of the OAuth credentials cascade.
    pub credentials: DoctorCredentialsSnapshot,
    /// Snapshot of the OAuth-usage cache (root dir, `usage.json`,
    /// `usage.lock`).
    pub cache: DoctorCacheSnapshot,
    /// Snapshot of one dry-run probe against the rate-limit
    /// endpoint. `None` when the probe was skipped (no token,
    /// `$HOME` unresolved, etc.).
    pub endpoint: DoctorEndpointSnapshot,
    /// Snapshot of the plugin discovery + compile pass that the
    /// runtime would otherwise run on segment load. Built once
    /// alongside `config.known_segment_ids` so the doctor compiles
    /// each plugin only once.
    pub plugins: DoctorPluginsSnapshot,
    /// Snapshot of `gix::discover(cwd)` for the Git category.
    pub git: DoctorGitSnapshot,
    /// Snapshot of one GitHub releases API probe for the Self
    /// category's "update available" check. Always populated by
    /// `from_process` (no skip path — the spec says always-run);
    /// transport / parse failures land as `TransportError` /
    /// `ParseError` variants per spec WARN routing.
    pub update_probe: DoctorUpdateProbe,
    /// Build-time SHA captured via
    /// `option_env!("LINESMITH_BUILD_SHA")`. `None` in dev / `cargo
    /// build` flows where no release pipeline set the env var;
    /// `Some(sha)` when cargo-dist or a CI script provided it. The
    /// `self.binary_integrity` check PASSes on `Some` (binary traces
    /// to a known commit), WARNs on `None` (built from a non-canonical
    /// source — possibly fine, possibly tampered).
    pub binary_build_sha: Option<&'static str>,
}

impl DoctorEnv {
    /// Snapshot the live process env, including the config-resolution
    /// pipeline. Only the binary entry should call this; tests and any
    /// non-binary caller construct `DoctorEnv` manually to stay
    /// hermetic.
    ///
    /// `cli_config_override` is the `--config <PATH>` value (top of
    /// the config-path cascade). Threading it through the snapshot —
    /// rather than the action layer applying it after — keeps the
    /// Config checks pure: every input they need is on `DoctorEnv`.
    #[must_use]
    pub fn from_process(cli_config_override: Option<PathBuf>) -> Self {
        let home_env = EnvVarState::snapshot("HOME");
        let xdg_config_home = EnvVarState::snapshot("XDG_CONFIG_HOME");
        let linesmith_config = EnvVarState::snapshot("LINESMITH_CONFIG");
        let resolved = crate::config::resolve_config_path(
            cli_config_override.clone(),
            linesmith_config.nonempty_os(),
            xdg_config_home.nonempty_os(),
            home_env.nonempty_os(),
        );
        let read = resolved
            .as_ref()
            .map_or(ConfigReadOutcome::Unresolved, read_config_at);
        let plugin_dirs = match &read {
            ConfigReadOutcome::Loaded { config, .. } => stat_plugin_dirs(&config.plugin_dirs),
            _ => Vec::new(),
        };
        // Build the runtime XdgEnv once and reuse it across every
        // runtime predicate doctor calls — eliminates drift if
        // XdgEnv ever picks up new fields (e.g. XDG_DATA_HOME).
        //
        // Both doctor and cli land in `XdgEnv::from_os_options`,
        // which is the single empty-string filter. Both paths
        // preserve non-UTF-8 bytes: cli via `var_os` on `CliEnv`'s
        // `OsString` fields, doctor via `EnvVarState::nonempty_os`
        // (which surfaces both `Set` and `NonUtf8` raw bytes).
        let runtime_xdg_env = crate::data_context::xdg::XdgEnv::from_os_options(
            None,
            xdg_config_home.nonempty_os().map(std::ffi::OsString::from),
            home_env.nonempty_os().map(std::ffi::OsString::from),
        );
        let (known_segment_ids, plugins) = snapshot_plugins(&read, &runtime_xdg_env);
        let known_theme_names = collect_known_theme_names(&runtime_xdg_env);
        let config = DoctorConfigSnapshot {
            cli_override: cli_config_override,
            resolved,
            read,
            plugin_dirs,
            known_segment_ids,
            known_theme_names,
        };
        let path_env = EnvVarState::snapshot("PATH");
        let claude_code = DoctorClaudeCodeSnapshot {
            binary_path: find_claude_binary(path_env.nonempty_os()),
            home_state: home_env
                .nonempty_os()
                .map(|h| snapshot_claude_home(Path::new(h))),
            path_env,
        };
        let xdg_cache_home = EnvVarState::snapshot("XDG_CACHE_HOME");
        // Build the cascade env via `var_os` (preserves non-UTF-8
        // bytes; Unix paths are byte-strings) rather than threading
        // the EnvVarState lossy preview through. Without this, doctor
        // would falsely report `Unresolvable` for any user with a
        // non-UTF-8 $HOME / $XDG_CONFIG_HOME / $CLAUDE_CONFIG_DIR
        // even though the runtime cascade resolves them correctly.
        let credentials = snapshot_credentials(
            &crate::data_context::credentials::FileCascadeEnv::from_process_env(),
        );
        let cache = snapshot_cache(&xdg_cache_home, &home_env);
        // Per spec §Cross-category short-circuits: OAuth token
        // missing → endpoint SKIP. The probe runs only when
        // credentials resolved cleanly. Production timeout is 2s
        // per spec §Timing.
        let endpoint = match &credentials {
            DoctorCredentialsSnapshot::Resolved(_) => probe_endpoint_via_ureq(),
            _ => DoctorEndpointSnapshot {
                probe: None,
                credentials_vanished: false,
            },
        };
        let git = snapshot_git();
        let update_probe = snapshot_update_probe();
        Self {
            home_env,
            xdg_config_home,
            xdg_cache_home,
            linesmith_config,
            term: EnvVarState::snapshot("TERM"),
            colorterm: EnvVarState::snapshot("COLORTERM"),
            no_color: std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()),
            current_exe: std::env::current_exe(),
            stdout_is_terminal: std::io::stdout().is_terminal(),
            terminal_width_cells: terminal_size::terminal_size()
                .map(|(terminal_size::Width(w), _)| w),
            config,
            claude_code,
            credentials,
            cache,
            endpoint,
            plugins,
            git,
            update_probe,
            // `option_env!` is compile-time; resolves to the value
            // baked at build, or `None` when the env var was unset
            // for that build. cargo-dist / release CI sets it; local
            // `cargo build` does not.
            binary_build_sha: option_env!("LINESMITH_BUILD_SHA"),
        }
    }

    /// Baseline "everything healthy" fixture for tests. Mutate
    /// individual fields to exercise specific check branches.
    /// `cfg(test)` keeps it out of the public API entirely —
    /// external embedders can't fabricate a snapshot that lies
    /// about a real environment.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn healthy() -> Self {
        Self {
            home_env: EnvVarState::Set("/home/user".to_string()),
            xdg_config_home: EnvVarState::Unset,
            xdg_cache_home: EnvVarState::Unset,
            linesmith_config: EnvVarState::Unset,
            term: EnvVarState::Set("xterm-256color".to_string()),
            colorterm: EnvVarState::Set("truecolor".to_string()),
            no_color: false,
            current_exe: Ok(PathBuf::from("/usr/local/bin/linesmith")),
            stdout_is_terminal: true,
            terminal_width_cells: Some(120),
            config: DoctorConfigSnapshot::healthy(),
            claude_code: DoctorClaudeCodeSnapshot {
                binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
                path_env: EnvVarState::Set("/usr/local/bin:/usr/bin".to_string()),
                home_state: Some(ClaudeHomeState {
                    dir: ClaudeDirState::Ok,
                    claude_json: ClaudeJsonState::Ok,
                    sessions: ClaudeSessionsState::HasFiles { count: 3 },
                }),
            },
            credentials: DoctorCredentialsSnapshot::Resolved(CredentialsSummary {
                source: crate::data_context::credentials::CredentialSource::ClaudeLegacy {
                    path: PathBuf::from("/home/user/.claude/.credentials.json"),
                },
                scopes: vec!["user:inference".to_string()],
            }),
            cache: DoctorCacheSnapshot {
                root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
                root: CacheRootState::Exists,
                usage_json: UsageJsonState::Current { schema_version: 1 },
                lock: LockState::Absent,
            },
            endpoint: DoctorEndpointSnapshot {
                probe: Some(EndpointProbe {
                    elapsed_ms: 250,
                    outcome: EndpointProbeOutcome::Ok,
                }),
                credentials_vanished: false,
            },
            // Discovered with zero plugins: vacuous PASS for every
            // Plugins check (no compile failures, no collisions).
            plugins: DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
                compiled_count: 0,
                errors: Vec::new(),
            }),
            git: DoctorGitSnapshot::Repo(GitContextSummary {
                repo_path: PathBuf::from("/home/user/code/project/.git"),
                repo_kind: crate::data_context::git::RepoKind::Main,
                head: crate::data_context::git::Head::Branch("main".to_string()),
            }),
            update_probe: DoctorUpdateProbe::Latest,
            binary_build_sha: Some("abc1234"),
        }
    }
}

/// Build the diagnostic report. Catalog scope is tracked in
/// `docs/specs/doctor.md` §Check catalog.
#[must_use]
pub fn build_report(env: &DoctorEnv) -> Report {
    Report {
        linesmith_version: env!("CARGO_PKG_VERSION"),
        categories: vec![
            environment_category(env),
            config_category(env),
            claude_code_category(env),
            credentials_category(env),
            cache_category(env),
            endpoint_category(env),
            plugins_category(env),
            git_category(env),
            self_category(env),
        ],
    }
}

fn environment_category(env: &DoctorEnv) -> Category {
    Category::new(
        "Environment",
        vec![
            check_stdout_tty(env),
            check_terminal_width(env),
            check_term(env),
            check_no_color(env),
            check_home(env),
        ],
    )
}

fn check_stdout_tty(env: &DoctorEnv) -> CheckResult {
    if env.stdout_is_terminal {
        CheckResult::pass("env.stdout_tty", "Terminal is a tty (stdout fd 1)")
    } else {
        CheckResult::warn(
            "env.stdout_tty",
            "Stdout is not a tty (piped or redirected)",
            "use --plain for CI or log capture",
        )
    }
}

/// Single source for the env.terminal_width and env.term hint
/// strings — the WARN branches share the same remediation, so any
/// future wording change touches one place.
const TERMINAL_WIDTH_HINT: &str = "set $COLUMNS or use --plain; narrow widths may wrap output";
const TERM_HINT: &str = "set TERM=xterm-256color, or accept plain-mode fallback";

fn check_terminal_width(env: &DoctorEnv) -> CheckResult {
    match env.terminal_width_cells {
        Some(0) => CheckResult::warn(
            "env.terminal_width",
            "Terminal reported 0 cells (likely driver or terminfo bug)",
            "set $COLUMNS to override, or report the issue to your terminal emulator",
        ),
        Some(w) if w >= 40 => CheckResult::pass(
            "env.terminal_width",
            format!("Terminal width detected: {w} cells"),
        ),
        Some(w) => CheckResult::warn(
            "env.terminal_width",
            format!("Terminal width is {w} cells (narrow)"),
            TERMINAL_WIDTH_HINT,
        ),
        None => CheckResult::warn(
            "env.terminal_width",
            "Terminal width could not be detected",
            TERMINAL_WIDTH_HINT,
        ),
    }
}

fn check_term(env: &DoctorEnv) -> CheckResult {
    match &env.term {
        EnvVarState::Set(t) if !t.is_empty() && t != "dumb" => {
            CheckResult::pass("env.term", format!("$TERM={t}"))
        }
        EnvVarState::Set(t) if t == "dumb" => {
            CheckResult::warn("env.term", "$TERM=dumb", TERM_HINT)
        }
        EnvVarState::NonUtf8 { lossy, .. } => CheckResult::warn(
            "env.term",
            format!("$TERM is set but not valid UTF-8 (lossy: {lossy:?})"),
            "rewrite $TERM with a UTF-8 value (e.g. xterm-256color)",
        ),
        // Unset OR Set-to-empty.
        _ => CheckResult::warn("env.term", "$TERM is unset", TERM_HINT),
    }
}

fn check_no_color(env: &DoctorEnv) -> CheckResult {
    if env.no_color {
        CheckResult::pass(
            "env.no_color",
            "NO_COLOR is set — colors disabled per user preference",
        )
    } else {
        CheckResult::pass("env.no_color", "NO_COLOR is unset")
    }
}

fn check_home(env: &DoctorEnv) -> CheckResult {
    match &env.home_env {
        EnvVarState::Set(h) if !h.is_empty() => CheckResult::pass("env.home", format!("$HOME={h}")),
        EnvVarState::NonUtf8 { lossy, .. } => CheckResult::fail(
            "env.home",
            format!("$HOME is set but not valid UTF-8 (lossy: {lossy:?})"),
            "rewrite $HOME with a UTF-8 path",
        ),
        // Unset OR Set-to-empty: same remediation either way.
        _ => CheckResult::fail(
            "env.home",
            "$HOME is unset",
            "set $HOME to your user directory",
        ),
    }
}

const CONFIG_DISCOVERED_ID: &str = "config.discovered";
const CONFIG_PARSES_ID: &str = "config.parses";
const CONFIG_SEGMENTS_ID: &str = "config.segments_resolvable";
const CONFIG_THEME_ID: &str = "config.theme_installed";
const CONFIG_PLUGIN_DIRS_ID: &str = "config.plugin_dirs_readable";

fn config_category(env: &DoctorEnv) -> Category {
    // Spec §Cross-category short-circuits has a Config carve-out:
    // when `--config` / `$LINESMITH_CONFIG` / `$XDG_CONFIG_HOME`
    // resolves a path, run the checks against it even if `$HOME` is
    // unresolved. Gating on `$HOME` would silently SKIP a config the
    // user explicitly named. The `Unresolved` arm of the discovery
    // check covers the genuine "no path source" case as a WARN, with
    // a hint pointing at every cascade source.
    let snapshot = &env.config;
    let discovered = check_config_discovered(snapshot);
    let parses = check_config_parses(snapshot);

    // Spec §Cross-category short-circuits: parse failure (or "no
    // config to parse") downgrades the schema-level checks to SKIP.
    // The discovery check itself is independent — a missing file is
    // a WARN, not a propagating failure.
    let downstream_runs = matches!(snapshot.read, ConfigReadOutcome::Loaded { .. });
    let (segments_check, theme_check, plugin_dirs_check) = if downstream_runs {
        (
            check_config_segments(snapshot),
            check_config_theme(snapshot),
            check_config_plugin_dirs(snapshot),
        )
    } else {
        let reason = "config not loaded";
        (
            CheckResult::skip(CONFIG_SEGMENTS_ID, "All referenced segments exist", reason),
            CheckResult::skip(CONFIG_THEME_ID, "Theme is installed", reason),
            CheckResult::skip(CONFIG_PLUGIN_DIRS_ID, "Plugin dirs are readable", reason),
        )
    };

    Category::new(
        "Config",
        vec![
            discovered,
            parses,
            segments_check,
            theme_check,
            plugin_dirs_check,
        ],
    )
}

fn check_config_discovered(snapshot: &DoctorConfigSnapshot) -> CheckResult {
    match &snapshot.read {
        ConfigReadOutcome::Loaded { path, .. } => CheckResult::pass(
            CONFIG_DISCOVERED_ID,
            format!("Config file: {}", path.display()),
        ),
        // Parse failure is the next check's signal; double-reporting
        // it here would clutter the report with a WARN beside the FAIL.
        ConfigReadOutcome::ParseError { path, .. } => CheckResult::pass(
            CONFIG_DISCOVERED_ID,
            format!("Config file: {}", path.display()),
        ),
        ConfigReadOutcome::NotFound { path, explicit } => {
            // Explicit path users named themselves get a FAIL: they
            // asked us to use *this file*, and it isn't there. Falling
            // back to defaults silently would mask a typo. Implicit
            // XDG-cascade misses are the first-run case and stay WARN
            // per spec ("none found, using built-in defaults").
            if *explicit {
                CheckResult::fail(
                    CONFIG_DISCOVERED_ID,
                    format!("Config file not found: {}", path.display()),
                    "create the file, or remove --config / unset $LINESMITH_CONFIG",
                )
            } else {
                CheckResult::warn(
                    CONFIG_DISCOVERED_ID,
                    format!(
                        "No config file at {} (using built-in defaults)",
                        path.display()
                    ),
                    "run `linesmith init` to create a config",
                )
            }
        }
        ConfigReadOutcome::IoError { path, message } => CheckResult::fail(
            CONFIG_DISCOVERED_ID,
            format!("Config file unreadable: {} ({message})", path.display()),
            "check filesystem permissions on the config path",
        ),
        ConfigReadOutcome::Unresolved => CheckResult::warn(
            CONFIG_DISCOVERED_ID,
            "No config path resolved (using built-in defaults)",
            "set $XDG_CONFIG_HOME or $HOME, or pass --config <PATH>",
        ),
    }
}

fn check_config_parses(snapshot: &DoctorConfigSnapshot) -> CheckResult {
    match &snapshot.read {
        ConfigReadOutcome::Loaded { .. } => CheckResult::pass(CONFIG_PARSES_ID, "Config parses"),
        ConfigReadOutcome::ParseError { path, message } => CheckResult::fail(
            CONFIG_PARSES_ID,
            format!("TOML parse error in {}", path.display()),
            // toml::de::Error.to_string() already includes line/col;
            // surfacing it verbatim keeps the spec's "see line/column
            // in the error" hint actionable.
            message.clone(),
        ),
        // No file → no parse to do. The discovery check carries the
        // remediation for these cases; rendering SKIP here keeps the
        // category shape stable (5 checks, every time).
        ConfigReadOutcome::NotFound { .. }
        | ConfigReadOutcome::IoError { .. }
        | ConfigReadOutcome::Unresolved => {
            CheckResult::skip(CONFIG_PARSES_ID, "Config parses", "no config file to parse")
        }
    }
}

fn check_config_segments(snapshot: &DoctorConfigSnapshot) -> CheckResult {
    let ConfigReadOutcome::Loaded { config, .. } = &snapshot.read else {
        // Belt-and-braces: config_category already gates on Loaded.
        // SKIP keeps the user-facing contract stable if a future
        // refactor decouples the gate from this check.
        return CheckResult::skip(
            CONFIG_SEGMENTS_ID,
            "All referenced segments exist",
            "config not loaded",
        );
    };

    let known = &snapshot.known_segment_ids;
    let mut unknown: Vec<String> = Vec::new();
    let mut malformed_lines: Vec<String> = Vec::new();
    if let Some(line) = &config.line {
        // Single-line `[line].segments` walk. Mirrors the numbered-line
        // classification below: separators skip, kindless inline tables
        // surface as malformed (the runtime builder warn-and-drops the
        // same shape — doctor must agree so users get the diagnostic
        // here rather than only via the debug log).
        for entry in &line.segments {
            if entry.is_separator() {
                continue;
            }
            match entry.segment_id() {
                Some(id) => {
                    if !known.contains(id) {
                        unknown.push(id.to_string());
                    }
                }
                None => malformed_lines.push(
                    "[line].segments has an inline-table entry without a `type` field".to_string(),
                ),
            }
        }
        // `[line.N]` numbered tables: each value should be a table
        // with a `segments` array of bare strings or inline tables
        // (per ADR-0024 — `{ type = "separator" }`, `{ type = "model",
        // merge = true }`, etc.). The runtime builder warns on
        // malformed shapes and exits 0; doctor surfaces them as a
        // visible WARN at health-check time so a user fixing config
        // doesn't have to spelunk through a debug log.
        for (key, value) in &line.numbered {
            // `$schema` is the JSON-schema sentinel, not a line index.
            if key == "$schema" {
                continue;
            }
            // `NonZeroU32` rather than `u32` so `[line.0]` lands in
            // the malformed bucket — the hint reads "must be a
            // positive integer" and `0` would otherwise sneak past.
            if key.parse::<NonZeroU32>().is_err() {
                malformed_lines.push(format!("[line.{key}] (key must be a positive integer)"));
                continue;
            }
            let Some(table) = value.as_table() else {
                malformed_lines.push(format!("[line.{key}] (must be a table)"));
                continue;
            };
            match table.get("segments") {
                Some(toml::Value::Array(arr)) => {
                    for item in arr {
                        match numbered_entry_id(item) {
                            NumberedEntry::Segment(id) => {
                                if !known.contains(id) {
                                    unknown.push(id.to_string());
                                }
                            }
                            NumberedEntry::Separator => {}
                            NumberedEntry::KindlessTable => malformed_lines.push(format!(
                                "[line.{key}].segments has an inline-table entry without a `type` field"
                            )),
                            NumberedEntry::WrongShape => malformed_lines.push(format!(
                                "[line.{key}].segments contains an entry that is neither a string nor an inline table"
                            )),
                        }
                    }
                }
                Some(_) => malformed_lines.push(format!(
                    "[line.{key}].segments (must be an array of strings or inline tables)"
                )),
                None => malformed_lines.push(format!("[line.{key}] missing `segments` array")),
            }
        }
    }

    if unknown.is_empty() && malformed_lines.is_empty() {
        CheckResult::pass(CONFIG_SEGMENTS_ID, "All referenced segments exist")
    } else {
        let mut details: Vec<String> = Vec::new();
        if !unknown.is_empty() {
            details.push(format!("unknown ids: {}", unknown.join(", ")));
        }
        if !malformed_lines.is_empty() {
            details.push(format!("malformed: {}", malformed_lines.join("; ")));
        }
        CheckResult::warn(
            CONFIG_SEGMENTS_ID,
            format!("Segment references have issues ({})", details.join(" / ")),
            "remove the unknown id, or install the plugin that provides it",
        )
    }
}

fn check_config_theme(snapshot: &DoctorConfigSnapshot) -> CheckResult {
    let ConfigReadOutcome::Loaded { config, .. } = &snapshot.read else {
        return CheckResult::skip(CONFIG_THEME_ID, "Theme is installed", "config not loaded");
    };

    match config.theme.as_deref() {
        // Omitted theme → built-in default applies, which is healthy.
        None => CheckResult::pass(CONFIG_THEME_ID, "Theme: (default)"),
        Some(name) if snapshot.known_theme_names.contains(name) => {
            CheckResult::pass(CONFIG_THEME_ID, format!("Theme: {name}"))
        }
        Some(name) => CheckResult::warn(
            CONFIG_THEME_ID,
            format!("Theme `{name}` is unknown; falling back to default"),
            "run `linesmith themes list` to see available names",
        ),
    }
}

fn check_config_plugin_dirs(snapshot: &DoctorConfigSnapshot) -> CheckResult {
    if snapshot.plugin_dirs.is_empty() {
        return CheckResult::pass(CONFIG_PLUGIN_DIRS_ID, "Plugin dirs: (none configured)");
    }

    let mut perm_errors: Vec<String> = Vec::new();
    let mut other_errors: Vec<String> = Vec::new();
    let mut missing: Vec<String> = Vec::new();
    let mut not_dirs: Vec<String> = Vec::new();
    for status in &snapshot.plugin_dirs {
        let path_str = status.path.display().to_string();
        match &status.state {
            PluginDirState::Ok => {}
            PluginDirState::Missing => missing.push(path_str),
            PluginDirState::NotADirectory => not_dirs.push(path_str),
            PluginDirState::PermissionDenied { .. } => perm_errors.push(path_str),
            PluginDirState::OtherIo { .. } => other_errors.push(path_str),
        }
    }

    // FAIL beats WARN: if any dir is genuinely unusable (permission
    // or unexpected I/O), surface that — the user can't ignore it.
    if !perm_errors.is_empty() || !other_errors.is_empty() {
        let mut parts: Vec<String> = Vec::new();
        if !perm_errors.is_empty() {
            parts.push(format!("permission denied: {}", perm_errors.join(", ")));
        }
        if !other_errors.is_empty() {
            parts.push(format!("io error: {}", other_errors.join(", ")));
        }
        return CheckResult::fail(
            CONFIG_PLUGIN_DIRS_ID,
            format!("Plugin dirs unreadable ({})", parts.join("; ")),
            "fix permissions, or remove the entry from config.toml plugin_dirs",
        );
    }

    if !missing.is_empty() || !not_dirs.is_empty() {
        let mut parts: Vec<String> = Vec::new();
        if !missing.is_empty() {
            parts.push(format!("missing: {}", missing.join(", ")));
        }
        if !not_dirs.is_empty() {
            parts.push(format!("not a directory: {}", not_dirs.join(", ")));
        }
        return CheckResult::warn(
            CONFIG_PLUGIN_DIRS_ID,
            format!("Plugin dirs have issues ({})", parts.join("; ")),
            "mkdir -p <path> or remove the entry from config.toml plugin_dirs",
        );
    }

    CheckResult::pass(
        CONFIG_PLUGIN_DIRS_ID,
        format!(
            "Plugin dirs: {} configured, all readable",
            snapshot.plugin_dirs.len(),
        ),
    )
}

const CLAUDE_BINARY_ID: &str = "claude.binary_found";
const CLAUDE_DIR_ID: &str = "claude.dir";
const CLAUDE_JSON_ID: &str = "claude.json_parses";
const CLAUDE_SESSIONS_ID: &str = "claude.sessions_recorded";

fn claude_code_category(env: &DoctorEnv) -> Category {
    let snapshot = &env.claude_code;
    let binary = check_claude_binary(snapshot);
    let (dir, claude_json, sessions) = match &snapshot.home_state {
        Some(home) => (
            check_claude_dir(home),
            check_claude_json(home),
            // Spec §Cross-category short-circuits: `~/.claude/`
            // missing → sessions SKIP. Widened beyond Missing to
            // cover every dir state where `read_dir(.../sessions/)`
            // can't produce a meaningful answer; the dir check
            // already carries the right remediation for those.
            match sessions_skip_reason(&home.dir) {
                Some(reason) => {
                    CheckResult::skip(CLAUDE_SESSIONS_ID, "Recent sessions recorded", reason)
                }
                None => check_claude_sessions(home),
            },
        ),
        None => {
            let reason = "$HOME unresolved";
            (
                CheckResult::skip(CLAUDE_DIR_ID, "`~/.claude/` directory", reason),
                CheckResult::skip(CLAUDE_JSON_ID, "`~/.claude.json` parses", reason),
                CheckResult::skip(CLAUDE_SESSIONS_ID, "Recent sessions recorded", reason),
            )
        }
    };
    Category::new("Claude Code", vec![binary, dir, claude_json, sessions])
}

/// SKIP reason for the sessions check when `~/.claude/` itself is
/// in a state that prevents `read_dir(.../sessions/)` from being
/// meaningful, or `None` when the sessions check should run.
fn sessions_skip_reason(dir: &ClaudeDirState) -> Option<&'static str> {
    match dir {
        ClaudeDirState::Missing => Some("`~/.claude/` missing"),
        ClaudeDirState::PermissionDenied { .. } => Some("`~/.claude/` unreadable"),
        ClaudeDirState::NotADirectory => Some("`~/.claude/` is not a directory"),
        ClaudeDirState::OtherIo { .. } => Some("`~/.claude/` stat failed"),
        ClaudeDirState::Ok => None,
    }
}

fn check_claude_binary(snapshot: &DoctorClaudeCodeSnapshot) -> CheckResult {
    if let Some(path) = &snapshot.binary_path {
        return CheckResult::pass(
            CLAUDE_BINARY_ID,
            format!("`claude` binary: {}", path.display()),
        );
    }
    // `$PATH` itself broken (unset / empty / non-UTF-8) is a
    // different remediation from "claude not installed". Without
    // this branch the user reads "install Claude Code" when their
    // shell init wiped PATH.
    if let Some(hint) = path_env_problem_hint(&snapshot.path_env) {
        return CheckResult::fail(
            CLAUDE_BINARY_ID,
            format!(
                "`claude` binary not located ({})",
                path_env_problem(&snapshot.path_env)
            ),
            hint,
        );
    }
    // Spec §Claude Code "binary found": WARN when binary is absent
    // but `~/.claude/` is *present in any form* — Claude Code was
    // installed once and the launcher fell off PATH or the dir got
    // corrupted (the dir's own check renders the right hint for
    // PermissionDenied / NotADirectory / OtherIo). FAIL is reserved
    // for the genuinely-never-installed case.
    let dir_present = snapshot
        .home_state
        .as_ref()
        .is_some_and(|h| !matches!(h.dir, ClaudeDirState::Missing));
    if dir_present {
        CheckResult::warn(
            CLAUDE_BINARY_ID,
            "`claude` binary not on $PATH (but ~/.claude/ exists)",
            "reinstall Claude Code from https://claude.ai/code, or check $PATH",
        )
    } else {
        CheckResult::fail(
            CLAUDE_BINARY_ID,
            "`claude` binary not found and ~/.claude/ missing",
            "install Claude Code from https://claude.ai/code",
        )
    }
}

/// Human-readable `$PATH` problem class for the binary-check label.
fn path_env_problem(path_env: &EnvVarState) -> &'static str {
    match path_env {
        EnvVarState::Unset => "$PATH is unset",
        EnvVarState::Set(s) if s.is_empty() => "$PATH is empty",
        EnvVarState::NonUtf8 { .. } => "$PATH is not valid UTF-8",
        EnvVarState::Set(_) => "$PATH searched", // reachable only if `nonempty()` is Some
    }
}

/// Hint for the `$PATH`-broken case, or `None` when `$PATH` is
/// usable (binary check should fall through to the install/dir
/// remediation).
fn path_env_problem_hint(path_env: &EnvVarState) -> Option<&'static str> {
    match path_env {
        EnvVarState::Unset => Some("set $PATH to include the directory holding `claude`"),
        EnvVarState::Set(s) if s.is_empty() => {
            Some("set $PATH to include the directory holding `claude`")
        }
        EnvVarState::NonUtf8 { .. } => {
            Some("rewrite $PATH with valid UTF-8 (check shell init for stray bytes)")
        }
        EnvVarState::Set(_) => None,
    }
}

fn check_claude_dir(home: &ClaudeHomeState) -> CheckResult {
    match &home.dir {
        ClaudeDirState::Ok => CheckResult::pass(CLAUDE_DIR_ID, "`~/.claude/` exists"),
        ClaudeDirState::PermissionDenied { message } => CheckResult::warn(
            CLAUDE_DIR_ID,
            format!("`~/.claude/` exists but is unreadable ({message})"),
            "fix filesystem permissions on ~/.claude/",
        ),
        ClaudeDirState::NotADirectory => CheckResult::warn(
            CLAUDE_DIR_ID,
            "`~/.claude/` exists but is not a directory",
            "remove the file at ~/.claude and let Claude Code recreate the directory",
        ),
        ClaudeDirState::OtherIo { message } => CheckResult::warn(
            CLAUDE_DIR_ID,
            format!("`~/.claude/` stat failed: {message}"),
            "check ~/.claude/ manually; doctor couldn't classify the failure",
        ),
        ClaudeDirState::Missing => CheckResult::fail(
            CLAUDE_DIR_ID,
            "`~/.claude/` directory missing",
            "launch Claude Code at least once to create it",
        ),
    }
}

fn check_claude_json(home: &ClaudeHomeState) -> CheckResult {
    match &home.claude_json {
        ClaudeJsonState::Ok => CheckResult::pass(
            CLAUDE_JSON_ID,
            "`~/.claude.json` parses (oauthAccount present)",
        ),
        ClaudeJsonState::NoOauthAccount => CheckResult::warn(
            CLAUDE_JSON_ID,
            "`~/.claude.json` parses but `oauthAccount` is missing",
            "run `claude` to log in and regenerate the oauthAccount block",
        ),
        ClaudeJsonState::ParseError { message } => CheckResult::fail(
            CLAUDE_JSON_ID,
            "`~/.claude.json` parse error".to_string(),
            // serde_json's Display impl already names line/col;
            // surfacing it verbatim keeps the spec hint actionable.
            message.clone(),
        ),
        ClaudeJsonState::Missing => CheckResult::fail(
            CLAUDE_JSON_ID,
            "`~/.claude.json` missing",
            "run `claude` to log in and regenerate the file",
        ),
        ClaudeJsonState::IoError { message } => CheckResult::fail(
            CLAUDE_JSON_ID,
            format!("`~/.claude.json` unreadable: {message}"),
            "check filesystem permissions on ~/.claude.json",
        ),
        ClaudeJsonState::TooLarge { actual_bytes } => CheckResult::fail(
            CLAUDE_JSON_ID,
            format!(
                "`~/.claude.json` too large to parse ({actual_bytes} bytes; cap is 2 MB)"
            ),
            "file is likely corrupt; back up and remove ~/.claude.json, then re-run `claude` to regenerate",
        ),
    }
}

fn check_claude_sessions(home: &ClaudeHomeState) -> CheckResult {
    match &home.sessions {
        ClaudeSessionsState::HasFiles { count } => CheckResult::pass(
            CLAUDE_SESSIONS_ID,
            format!("{count} recent session(s) in `~/.claude/sessions/`"),
        ),
        ClaudeSessionsState::Empty => CheckResult::warn(
            CLAUDE_SESSIONS_ID,
            "`~/.claude/sessions/` is empty",
            "open a new Claude Code session to populate",
        ),
        ClaudeSessionsState::Missing => CheckResult::fail(
            CLAUDE_SESSIONS_ID,
            "`~/.claude/sessions/` directory missing",
            "open a new Claude Code session to create the directory",
        ),
        ClaudeSessionsState::NotADirectory => CheckResult::warn(
            CLAUDE_SESSIONS_ID,
            "`~/.claude/sessions` exists but is not a directory",
            "remove the file at ~/.claude/sessions and let Claude Code recreate it",
        ),
        ClaudeSessionsState::IoError { message } => CheckResult::warn(
            CLAUDE_SESSIONS_ID,
            format!("`~/.claude/sessions/` read failed: {message}"),
            "check filesystem permissions on ~/.claude/sessions/",
        ),
    }
}

// --- Credentials ---

const CREDS_TOKEN_RESOLVABLE_ID: &str = "creds.token_resolvable";
const CREDS_SOURCE_ATTESTED_ID: &str = "creds.source_attested";
const CREDS_TOKEN_SHAPE_ID: &str = "creds.token_shape_valid";
const CREDS_SCOPES_ID: &str = "creds.scopes_present";

fn credentials_category(env: &DoctorEnv) -> Category {
    let snapshot = &env.credentials;
    Category::new(
        "Credentials",
        vec![
            check_creds_token_resolvable(snapshot),
            check_creds_source_attested(snapshot),
            check_creds_token_shape(snapshot),
            check_creds_scopes(snapshot),
        ],
    )
}

fn check_creds_token_resolvable(snapshot: &DoctorCredentialsSnapshot) -> CheckResult {
    match snapshot {
        DoctorCredentialsSnapshot::Resolved(_) => CheckResult::pass(
            CREDS_TOKEN_RESOLVABLE_ID,
            "OAuth token resolved via cascade",
        ),
        // Spec §Cross-category short-circuits: SKIP all four when
        // the cascade has nothing to attempt — no `$HOME`, no
        // `$XDG_CONFIG_HOME`, no `$CLAUDE_CONFIG_DIR`, AND we're
        // not on macOS (where the keychain is a path-independent
        // source).
        DoctorCredentialsSnapshot::Unresolvable => CheckResult::skip(
            CREDS_TOKEN_RESOLVABLE_ID,
            "OAuth token resolvable",
            "no usable credentials cascade source",
        ),
        DoctorCredentialsSnapshot::Failed(err) => CheckResult::fail(
            CREDS_TOKEN_RESOLVABLE_ID,
            format!("OAuth token cascade failed ({})", creds_error_label(err)),
            "log in to Claude Code to provision a fresh token",
        ),
    }
}

fn check_creds_source_attested(snapshot: &DoctorCredentialsSnapshot) -> CheckResult {
    match snapshot {
        DoctorCredentialsSnapshot::Resolved(s) => CheckResult::pass(
            CREDS_SOURCE_ATTESTED_ID,
            format!("Source: {}", source_label(&s.source)),
        ),
        DoctorCredentialsSnapshot::Unresolvable => CheckResult::skip(
            CREDS_SOURCE_ATTESTED_ID,
            "Token source attested",
            "no usable credentials cascade source",
        ),
        // Path-bearing failure variants (IoError / ParseError /
        // MissingField / EmptyToken) all carry the cascade-winner
        // path. The source IS identifiable even though the file
        // is unreadable / malformed; the resolvable / shape rows
        // own the FAIL signal. Only the no-path variants
        // (NoCredentials, SubprocessFailed) leave the source
        // indeterminate.
        DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::IoError { path, .. }
            | CredentialErrorSummary::ParseError { path }
            | CredentialErrorSummary::MissingField { path }
            | CredentialErrorSummary::EmptyToken { path },
        ) => CheckResult::pass(
            CREDS_SOURCE_ATTESTED_ID,
            format!("Source: {} (cascade reached this file)", path.display()),
        ),
        DoctorCredentialsSnapshot::Failed(_) => CheckResult::fail(
            CREDS_SOURCE_ATTESTED_ID,
            "Token source indeterminate",
            "rm any stale credentials file and log in again",
        ),
    }
}

fn check_creds_token_shape(snapshot: &DoctorCredentialsSnapshot) -> CheckResult {
    match snapshot {
        DoctorCredentialsSnapshot::Resolved(_) => {
            CheckResult::pass(CREDS_TOKEN_SHAPE_ID, "Token shape valid")
        }
        DoctorCredentialsSnapshot::Unresolvable => CheckResult::skip(
            CREDS_TOKEN_SHAPE_ID,
            "Token shape valid",
            "no usable credentials cascade source",
        ),
        DoctorCredentialsSnapshot::Failed(
            err @ (CredentialErrorSummary::ParseError { .. }
            | CredentialErrorSummary::MissingField { .. }
            | CredentialErrorSummary::EmptyToken { .. }),
        ) => CheckResult::fail(
            CREDS_TOKEN_SHAPE_ID,
            format!("Token shape invalid: {}", creds_error_label(err)),
            "rerun `claude` to rewrite the credentials file",
        ),
        // No usable file to evaluate; the resolvable check carries
        // the actionable hint.
        DoctorCredentialsSnapshot::Failed(_) => CheckResult::skip(
            CREDS_TOKEN_SHAPE_ID,
            "Token shape valid",
            "no credentials file to inspect",
        ),
    }
}

fn check_creds_scopes(snapshot: &DoctorCredentialsSnapshot) -> CheckResult {
    let scopes = match snapshot {
        DoctorCredentialsSnapshot::Resolved(s) => &s.scopes,
        DoctorCredentialsSnapshot::Unresolvable => {
            return CheckResult::skip(
                CREDS_SCOPES_ID,
                "Required scopes present",
                "no usable credentials cascade source",
            );
        }
        DoctorCredentialsSnapshot::Failed(_) => {
            return CheckResult::skip(
                CREDS_SCOPES_ID,
                "Required scopes present",
                "credentials not loaded",
            );
        }
    };
    if scopes.iter().any(|s| s == "user:inference") {
        CheckResult::pass(
            CREDS_SCOPES_ID,
            format!("Scopes: {} ({} total)", "user:inference", scopes.len()),
        )
    } else {
        CheckResult::fail(
            CREDS_SCOPES_ID,
            "Required scope `user:inference` absent",
            "log in again to refresh scopes",
        )
    }
}

fn creds_error_label(err: &CredentialErrorSummary) -> &'static str {
    match err {
        CredentialErrorSummary::NoCredentials => "no credentials found",
        CredentialErrorSummary::SubprocessFailed { .. } => "keychain subprocess failed",
        CredentialErrorSummary::IoError { .. } => "file unreadable",
        CredentialErrorSummary::ParseError { .. } => "JSON parse error",
        CredentialErrorSummary::MissingField { .. } => "claudeAiOauth block missing",
        CredentialErrorSummary::EmptyToken { .. } => "accessToken empty",
    }
}

fn source_label(source: &crate::data_context::credentials::CredentialSource) -> String {
    use crate::data_context::credentials::CredentialSource;
    match source {
        CredentialSource::MacosKeychainPrimary => "macOS Keychain (primary)".to_string(),
        CredentialSource::MacosKeychainMultiAccount { service, .. } => {
            format!("macOS Keychain (multi-account: {service})")
        }
        CredentialSource::EnvDir { path } => {
            format!("$CLAUDE_CONFIG_DIR file ({})", path.display())
        }
        CredentialSource::XdgConfig { path } => format!("XDG file ({})", path.display()),
        CredentialSource::ClaudeLegacy { path } => format!("legacy file ({})", path.display()),
        // CredentialSource is `#[non_exhaustive]` per ADR-0018.
        // Future variants render generically until cli wires an
        // explicit label.
        _ => "unknown credential source".to_string(),
    }
}

// --- Cache ---

const CACHE_DIR_ID: &str = "cache.dir_writable";
const CACHE_USAGE_ID: &str = "cache.usage_json_shape";
const CACHE_LOCK_ID: &str = "cache.lock_fresh";

fn cache_category(env: &DoctorEnv) -> Category {
    let snapshot = &env.cache;
    let dir = check_cache_dir(snapshot);
    // Spec §Cross-category short-circuits: when the cache root
    // can't be derived from `$XDG_CACHE_HOME` or `$HOME`, the two
    // downstream checks SKIP — there's no path to inspect.
    let (usage, lock) = if matches!(snapshot.root, CacheRootState::Unresolved) {
        let reason = "cache root unresolved";
        (
            CheckResult::skip(CACHE_USAGE_ID, "`usage.json` shape current", reason),
            CheckResult::skip(CACHE_LOCK_ID, "Lock file is fresh", reason),
        )
    } else {
        (check_cache_usage_json(snapshot), check_cache_lock(snapshot))
    };
    Category::new("Cache", vec![dir, usage, lock])
}

fn check_cache_dir(snapshot: &DoctorCacheSnapshot) -> CheckResult {
    match (&snapshot.root, &snapshot.root_path) {
        (CacheRootState::Exists, Some(path)) => {
            CheckResult::pass(CACHE_DIR_ID, format!("Cache dir: {}", path.display()))
        }
        // Absent + writable parent: expected first-run state. PASS
        // with a hint that the runtime will create the directory.
        (CacheRootState::Absent, Some(path)) => CheckResult::pass(
            CACHE_DIR_ID,
            format!(
                "Cache dir: {} (will be created on first fetch)",
                path.display()
            ),
        ),
        // Absent + read-only ancestor: runtime's `create_dir_all`
        // will fail every time. Without this WARN doctor would PASS
        // forever for setups like `XDG_CACHE_HOME=/proc/cache/...`
        // where the cache can never be created — the next-run
        // recovery path doesn't apply because the failed fetch
        // leaves the path Absent.
        (CacheRootState::AbsentParentReadOnly { parent }, Some(path)) => CheckResult::warn(
            CACHE_DIR_ID,
            format!(
                "Cache dir cannot be created: {} (read-only ancestor: {})",
                path.display(),
                parent.display(),
            ),
            "point $XDG_CACHE_HOME (or $HOME) at a writable location",
        ),
        (CacheRootState::NotADirectory, Some(path)) => CheckResult::warn(
            CACHE_DIR_ID,
            format!(
                "Cache path exists but is not a directory: {}",
                path.display()
            ),
            "remove or rename the file at the cache path so linesmith can create the cache dir",
        ),
        (CacheRootState::Unreadable { message }, Some(path)) => CheckResult::warn(
            CACHE_DIR_ID,
            format!("Cache dir unreadable: {} ({message})", path.display()),
            "check filesystem permissions on the cache path or its parents",
        ),
        (CacheRootState::Unresolved, _) | (_, None) => CheckResult::skip(
            CACHE_DIR_ID,
            "Cache dir exists or creatable",
            "cache root unresolved",
        ),
    }
}

fn check_cache_usage_json(snapshot: &DoctorCacheSnapshot) -> CheckResult {
    match &snapshot.usage_json {
        UsageJsonState::Missing => CheckResult::pass(
            CACHE_USAGE_ID,
            "`usage.json` not yet written (next fetch will create it)",
        ),
        UsageJsonState::Current { schema_version } => CheckResult::pass(
            CACHE_USAGE_ID,
            format!("`usage.json` schema_version={schema_version}"),
        ),
        UsageJsonState::Stale { schema_version } => CheckResult::warn(
            CACHE_USAGE_ID,
            format!("`usage.json` is stale (schema_version={schema_version})"),
            "safe to ignore; next fetch rewrites",
        ),
        UsageJsonState::FutureTimestamp => CheckResult::warn(
            CACHE_USAGE_ID,
            "`usage.json` has a `cached_at` in the future (clock skew)",
            "fix the system clock (sudo sntp -sS time.apple.com or equivalent); the runtime treats this as a cache miss",
        ),
        // Distinct hint from Stale: a corrupt usage.json may
        // signal real FS damage rather than a routine
        // schema-version drift. Don't tell the user to ignore it.
        UsageJsonState::Unreadable { message } => CheckResult::warn(
            CACHE_USAGE_ID,
            format!("`usage.json` unreadable: {message}"),
            "investigate filesystem corruption; rm the file if it's safe to discard",
        ),
    }
}

fn check_cache_lock(snapshot: &DoctorCacheSnapshot) -> CheckResult {
    match &snapshot.lock {
        LockState::Absent => CheckResult::pass(CACHE_LOCK_ID, "No lock file (no active backoff)"),
        LockState::Active { blocked_until_secs } => CheckResult::pass(
            CACHE_LOCK_ID,
            format!("Lock active (blocked_until={blocked_until_secs})"),
        ),
        LockState::Stale { blocked_until_secs } => CheckResult::warn(
            CACHE_LOCK_ID,
            format!("Stale lock (blocked_until={blocked_until_secs} in the past)"),
            "rm ~/.cache/linesmith/usage.lock to clear",
        ),
        LockState::Unreadable { message } => CheckResult::warn(
            CACHE_LOCK_ID,
            format!("Lock file unreadable: {message}"),
            "rm ~/.cache/linesmith/usage.lock to clear",
        ),
    }
}

// --- Rate-limit endpoint ---

const ENDPOINT_REACHABLE_ID: &str = "endpoint.reachable";
const ENDPOINT_SHAPE_ID: &str = "endpoint.shape_current";
const ENDPOINT_HEADERS_ID: &str = "endpoint.headers_sane";

fn endpoint_category(env: &DoctorEnv) -> Category {
    let Some(probe) = &env.endpoint.probe else {
        // Spec §Cross-category: OAuth token missing → SKIP all 3.
        // The race-window case (snapshot's first call resolved
        // creds, probe's second call failed) gets a distinct reason
        // so the user doesn't read "Resolved" alongside an opaque
        // "endpoint probe not attempted".
        let reason = if env.endpoint.credentials_vanished {
            "credentials became unavailable mid-probe (race)"
        } else {
            match &env.credentials {
                DoctorCredentialsSnapshot::Resolved(_) => "endpoint probe not attempted",
                DoctorCredentialsSnapshot::Unresolvable => "credentials cascade has no source",
                DoctorCredentialsSnapshot::Failed(_) => "no token to probe with",
            }
        };
        return Category::new(
            "Rate-limit endpoint",
            vec![
                CheckResult::skip(ENDPOINT_REACHABLE_ID, "Endpoint reachable", reason),
                CheckResult::skip(ENDPOINT_SHAPE_ID, "Endpoint returns expected shape", reason),
                CheckResult::skip(ENDPOINT_HEADERS_ID, "Rate-limit headers sane", reason),
            ],
        );
    };
    Category::new(
        "Rate-limit endpoint",
        vec![
            check_endpoint_reachable(probe),
            check_endpoint_shape(probe),
            check_endpoint_headers(probe),
        ],
    )
}

fn check_endpoint_reachable(probe: &EndpointProbe) -> CheckResult {
    match &probe.outcome {
        EndpointProbeOutcome::Ok => CheckResult::pass(
            ENDPOINT_REACHABLE_ID,
            format!("`/api/oauth/usage` 200 OK ({}ms)", probe.elapsed_ms),
        ),
        EndpointProbeOutcome::Slow => CheckResult::warn(
            ENDPOINT_REACHABLE_ID,
            format!("Endpoint responded slowly ({}ms)", probe.elapsed_ms),
            "check internet, or Anthropic status page",
        ),
        EndpointProbeOutcome::TransportError => CheckResult::warn(
            ENDPOINT_REACHABLE_ID,
            "Endpoint unreachable (DNS / connect / read timeout / proxy)",
            "check internet, or Anthropic status page",
        ),
        EndpointProbeOutcome::BadStatus { status } => CheckResult::fail(
            ENDPOINT_REACHABLE_ID,
            format!("Endpoint returned HTTP {status}"),
            match status {
                401 => "log in again to refresh credentials",
                403 => "verify scopes; log in again",
                _ => "report a linesmith issue with the status code",
            },
        ),
        // Shape / headers are reported by their own check rows.
        EndpointProbeOutcome::ParseError | EndpointProbeOutcome::UnexpectedShape { .. } => {
            CheckResult::pass(
                ENDPOINT_REACHABLE_ID,
                format!("`/api/oauth/usage` reachable ({}ms)", probe.elapsed_ms),
            )
        }
        EndpointProbeOutcome::RateLimited { .. } => CheckResult::pass(
            ENDPOINT_REACHABLE_ID,
            format!("`/api/oauth/usage` reachable ({}ms)", probe.elapsed_ms),
        ),
    }
}

fn check_endpoint_shape(probe: &EndpointProbe) -> CheckResult {
    match &probe.outcome {
        EndpointProbeOutcome::Ok | EndpointProbeOutcome::Slow => {
            CheckResult::pass(ENDPOINT_SHAPE_ID, "Response shape current")
        }
        EndpointProbeOutcome::UnexpectedShape { extra_keys } => CheckResult::warn(
            ENDPOINT_SHAPE_ID,
            format!(
                "Response has forward-compat keys: {}",
                extra_keys.join(", ")
            ),
            "no action needed; linesmith ignores unknown buckets",
        ),
        EndpointProbeOutcome::ParseError => CheckResult::fail(
            ENDPOINT_SHAPE_ID,
            "Response did not deserialize into `UsageApiResponse`",
            "report a linesmith issue; Anthropic changed the API",
        ),
        // The reachability check carries the FAIL/WARN; this row
        // SKIPs because there's no body to inspect. Listing every
        // variant explicitly (no `_`) so a future
        // `#[non_exhaustive]` addition fails to compile until it
        // picks a severity rather than silently SKIPing.
        EndpointProbeOutcome::TransportError
        | EndpointProbeOutcome::BadStatus { .. }
        | EndpointProbeOutcome::RateLimited { .. } => CheckResult::skip(
            ENDPOINT_SHAPE_ID,
            "Endpoint returns expected shape",
            "endpoint not reachable",
        ),
    }
}

fn check_endpoint_headers(probe: &EndpointProbe) -> CheckResult {
    match &probe.outcome {
        EndpointProbeOutcome::RateLimited { retry_after_secs } => match retry_after_secs {
            Some(secs) if *secs > 3600 => CheckResult::fail(
                ENDPOINT_HEADERS_ID,
                format!("429 with abusive Retry-After: {secs}s"),
                "slow down: you're hitting the rate limit hard",
            ),
            Some(secs) => CheckResult::warn(
                ENDPOINT_HEADERS_ID,
                format!("429 with Retry-After: {secs}s"),
                "slow down: you're hitting the rate limit",
            ),
            None => CheckResult::warn(
                ENDPOINT_HEADERS_ID,
                "429 without Retry-After header",
                "slow down: you're hitting the rate limit",
            ),
        },
        EndpointProbeOutcome::Ok
        | EndpointProbeOutcome::Slow
        | EndpointProbeOutcome::UnexpectedShape { .. }
        | EndpointProbeOutcome::ParseError => {
            CheckResult::pass(ENDPOINT_HEADERS_ID, "No 429 returned")
        }
        // Explicit list (no `_`) so a future `#[non_exhaustive]`
        // variant fails to compile until it picks a severity.
        EndpointProbeOutcome::TransportError | EndpointProbeOutcome::BadStatus { .. } => {
            CheckResult::skip(
                ENDPOINT_HEADERS_ID,
                "Rate-limit headers sane",
                "endpoint not reachable",
            )
        }
    }
}

// --- Plugins ---

const PLUGINS_COMPILE_ID: &str = "plugins.compile";
const PLUGINS_DEPS_ID: &str = "plugins.deps_valid";
const PLUGINS_ID_COLLISIONS_ID: &str = "plugins.no_id_collisions";
const PLUGINS_BUILTIN_COLLISIONS_ID: &str = "plugins.no_builtin_collisions";

fn plugins_category(env: &DoctorEnv) -> Category {
    use linesmith_plugin::{CollisionWinner, PluginError};
    let summary = match &env.plugins {
        DoctorPluginsSnapshot::NoSources => {
            // Spec §Edge cases: "Default plugin directory doesn't
            // exist (no `plugin_dirs` configured) → SKIP the
            // Plugins category with reason 'no plugins
            // configured'; not a failure."
            let reason = "no plugins configured";
            return Category::new(
                "Plugins",
                vec![
                    CheckResult::skip(PLUGINS_COMPILE_ID, "All plugins compile", reason),
                    CheckResult::skip(PLUGINS_DEPS_ID, "All `@data_deps` valid", reason),
                    CheckResult::skip(PLUGINS_ID_COLLISIONS_ID, "No id collisions", reason),
                    CheckResult::skip(
                        PLUGINS_BUILTIN_COLLISIONS_ID,
                        "No built-in collisions",
                        reason,
                    ),
                ],
            );
        }
        DoctorPluginsSnapshot::Discovered(summary) => summary,
    };

    let mut compile_errors: Vec<&PluginError> = Vec::new();
    let mut dep_errors: Vec<&PluginError> = Vec::new();
    let mut id_collisions: Vec<&PluginError> = Vec::new();
    let mut builtin_collisions: Vec<&PluginError> = Vec::new();
    let mut unexpected: Vec<&PluginError> = Vec::new();
    for err in &summary.errors {
        match err {
            PluginError::Compile { .. } => compile_errors.push(err),
            PluginError::MalformedDataDeps { .. } | PluginError::UnknownDataDep { .. } => {
                dep_errors.push(err);
            }
            PluginError::IdCollision {
                winner: CollisionWinner::BuiltIn,
                ..
            } => builtin_collisions.push(err),
            PluginError::IdCollision {
                winner: CollisionWinner::Plugin(_),
                ..
            } => id_collisions.push(err),
            // Render-time variants are constructed by `render(ctx)`
            // and shouldn't reach `load_errors()`. If one shows up
            // here a future plugin lifecycle hook (init, schema
            // validate, etc.) started running at compile time and
            // the doctor needs to pick a category. Surfacing it as
            // a FAIL on the compile row keeps the user informed
            // until the variant gets explicit routing.
            PluginError::Runtime { .. }
            | PluginError::ResourceExceeded { .. }
            | PluginError::Timeout { .. }
            | PluginError::MalformedReturn { .. } => {
                debug_assert!(
                    false,
                    "render-time PluginError reached the doctor's load-error classifier: {err:?}",
                );
                unexpected.push(err);
            }
            // PluginError is `#[non_exhaustive]` per ADR-0018.
            // Future variants from linesmith-core route to
            // `unexpected` so the doctor surfaces them on a
            // "compile" row until cli adds explicit categorization.
            _ => unexpected.push(err),
        }
    }

    Category::new(
        "Plugins",
        vec![
            check_plugins_compile(summary.compiled_count, &compile_errors, &unexpected),
            check_plugins_deps_valid(&dep_errors),
            check_plugins_id_collisions(&id_collisions),
            check_plugins_builtin_collisions(&builtin_collisions),
        ],
    )
}

fn check_plugins_compile(
    compiled_count: usize,
    errors: &[&linesmith_plugin::PluginError],
    unexpected: &[&linesmith_plugin::PluginError],
) -> CheckResult {
    use linesmith_plugin::PluginError;
    // `unexpected` carries render-time variants that shouldn't be
    // in `load_errors()`. Surface them as FAIL on the compile row
    // (the closest fit) with a "report this as a doctor bug" hint
    // so the user knows to file an issue rather than chase a
    // phantom config problem. Render via `kind()` rather than
    // `Display`/`Debug` because Runtime / MalformedReturn variants
    // carry plugin-author-controlled `message` strings that could
    // include secrets from a hostile `throw("...")`.
    if !unexpected.is_empty() {
        let detail = unexpected
            .iter()
            .map(|e| format!("unexpected variant: {}", e.kind()))
            .collect::<Vec<_>>()
            .join("; ");
        return CheckResult::fail(
            PLUGINS_COMPILE_ID,
            format!(
                "{} unexpected plugin error(s) at load time",
                unexpected.len()
            ),
            format!("file a linesmith bug; doctor saw: {detail}"),
        );
    }
    if errors.is_empty() {
        return CheckResult::pass(
            PLUGINS_COMPILE_ID,
            format!("{compiled_count} plugin(s) compiled cleanly"),
        );
    }
    let detail = errors
        .iter()
        .filter_map(|e| match e {
            PluginError::Compile { path, message } => {
                Some(format!("{}: {}", path.display(), message))
            }
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("; ");
    CheckResult::fail(
        PLUGINS_COMPILE_ID,
        format!("{} plugin(s) failed to compile", errors.len()),
        // serde_rhai's Display already includes line/col for compile
        // errors; surface the path + message verbatim.
        detail,
    )
}

fn check_plugins_deps_valid(errors: &[&linesmith_plugin::PluginError]) -> CheckResult {
    use linesmith_plugin::PluginError;
    if errors.is_empty() {
        return CheckResult::pass(PLUGINS_DEPS_ID, "All `@data_deps` valid");
    }
    let detail = errors
        .iter()
        .map(|e| match e {
            PluginError::UnknownDataDep { path, name } => {
                format!("{} declares unknown dep `{name}`", path.display())
            }
            PluginError::MalformedDataDeps { path, message } => {
                format!("{}: {message}", path.display())
            }
            // The classifier never routes other variants here.
            other => format!("{other}"),
        })
        .collect::<Vec<_>>()
        .join("; ");
    CheckResult::fail(
        PLUGINS_DEPS_ID,
        format!("{} plugin(s) declared invalid `@data_deps`", errors.len()),
        detail,
    )
}

fn check_plugins_id_collisions(errors: &[&linesmith_plugin::PluginError]) -> CheckResult {
    use linesmith_plugin::PluginError;
    if errors.is_empty() {
        return CheckResult::pass(PLUGINS_ID_COLLISIONS_ID, "No id collisions");
    }
    let detail = errors
        .iter()
        .filter_map(|e| match e {
            PluginError::IdCollision {
                id,
                winner,
                loser_path,
            } => Some(format!(
                "id `{id}` claimed by both {winner} and {} (loser dropped)",
                loser_path.display()
            )),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("; ");
    CheckResult::fail(
        PLUGINS_ID_COLLISIONS_ID,
        format!("{} plugin id collision(s)", errors.len()),
        detail,
    )
}

fn check_plugins_builtin_collisions(errors: &[&linesmith_plugin::PluginError]) -> CheckResult {
    use linesmith_plugin::PluginError;
    if errors.is_empty() {
        return CheckResult::pass(PLUGINS_BUILTIN_COLLISIONS_ID, "No built-in collisions");
    }
    let detail = errors
        .iter()
        .filter_map(|e| match e {
            PluginError::IdCollision { id, loser_path, .. } => Some(format!(
                "plugin id `{id}` shadows a built-in segment ({})",
                loser_path.display()
            )),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("; ");
    CheckResult::fail(
        PLUGINS_BUILTIN_COLLISIONS_ID,
        format!("{} plugin(s) shadow a built-in", errors.len()),
        detail,
    )
}

// --- Git ---

const GIT_REPO_DETECTED_ID: &str = "git.repo_detected";
const GIT_HEAD_RESOLVES_ID: &str = "git.head_resolves";
const GIT_REPO_KIND_ID: &str = "git.repo_kind";

fn git_category(env: &DoctorEnv) -> Category {
    Category::new(
        "Git",
        vec![
            check_git_repo_detected(env),
            check_git_head_resolves(&env.git),
            check_git_repo_kind(&env.git),
        ],
    )
}

fn check_git_repo_detected(env: &DoctorEnv) -> CheckResult {
    match &env.git {
        DoctorGitSnapshot::Repo(ctx) => CheckResult::pass(
            GIT_REPO_DETECTED_ID,
            format!("Repo detected: {}", ctx.repo_path.display()),
        ),
        DoctorGitSnapshot::Failed { message } => CheckResult::fail(
            GIT_REPO_DETECTED_ID,
            format!("`gix::discover` failed: {message}"),
            "repair the repo, or move out of this directory",
        ),
        DoctorGitSnapshot::NotInRepo => {
            // Spec §Git "cwd git status" carve-out: WARN by
            // default, SKIP when no `git_*` segment is enabled
            // in the user's config (the segment would silently
            // hide; not a doctor concern).
            if any_git_segment_enabled(&env.config.read) {
                CheckResult::warn(
                    GIT_REPO_DETECTED_ID,
                    "Not inside a git repo (a git segment is configured)",
                    "cd into a repo, or remove `git_*` from `[line.segments]`",
                )
            } else {
                CheckResult::skip(
                    GIT_REPO_DETECTED_ID,
                    "cwd is in a git repo",
                    "no `git_*` segment configured",
                )
            }
        }
    }
}

fn check_git_head_resolves(snapshot: &DoctorGitSnapshot) -> CheckResult {
    match snapshot {
        DoctorGitSnapshot::Repo(ctx) => {
            // Every `Head` variant the runtime constructs is, by
            // definition, resolvable — `resolve_head` collapses
            // all unresolvable cases into the `Failed` arm above.
            // The spec's PASS condition ("Branch / Detached /
            // Unborn") plus the live `OtherRef` variant all PASS;
            // the FAIL row is unreachable from this snapshot.
            //
            // Exception: `OtherRef.full_name` comes from gix's
            // lossy-UTF-8 path (`as_bstr().to_string()` substitutes
            // U+FFFD for invalid bytes). A name carrying a
            // replacement character means the underlying refname is
            // corrupt; PASS would silently hide it.
            if let crate::data_context::git::Head::OtherRef { full_name } = &ctx.head {
                if full_name.contains('\u{FFFD}') {
                    return CheckResult::warn(
                        GIT_HEAD_RESOLVES_ID,
                        format!("HEAD points at a ref with non-UTF-8 bytes (lossy: {full_name})"),
                        "repair the refname (`git update-ref`); the ref is unreadable as UTF-8",
                    );
                }
            }
            let label = match &ctx.head {
                crate::data_context::git::Head::Branch(name) => format!("HEAD -> {name}"),
                crate::data_context::git::Head::Detached(oid) => {
                    format!("HEAD detached at {oid}")
                }
                crate::data_context::git::Head::Unborn { symbolic_ref } => {
                    format!("HEAD unborn (would point at {symbolic_ref})")
                }
                crate::data_context::git::Head::OtherRef { full_name } => {
                    format!("HEAD -> {full_name}")
                }
                // Head is `#[non_exhaustive]` per ADR-0018. A future
                // variant in linesmith-core renders generically
                // until cli adds an explicit label.
                _ => "HEAD (unrecognized)".to_string(),
            };
            CheckResult::pass(GIT_HEAD_RESOLVES_ID, label)
        }
        DoctorGitSnapshot::Failed { .. } => CheckResult::skip(
            GIT_HEAD_RESOLVES_ID,
            "HEAD resolves",
            "repo discovery failed",
        ),
        DoctorGitSnapshot::NotInRepo => {
            CheckResult::skip(GIT_HEAD_RESOLVES_ID, "HEAD resolves", "not in a git repo")
        }
    }
}

fn check_git_repo_kind(snapshot: &DoctorGitSnapshot) -> CheckResult {
    use crate::data_context::git::RepoKind;
    match snapshot {
        DoctorGitSnapshot::Repo(ctx) => {
            let label = match &ctx.repo_kind {
                RepoKind::Main => "RepoKind: main",
                RepoKind::Bare => "RepoKind: bare",
                RepoKind::Submodule => "RepoKind: submodule",
                RepoKind::LinkedWorktree { .. } => "RepoKind: linked worktree",
                // RepoKind is `#[non_exhaustive]` per ADR-0018.
                // Future variants render generically.
                _ => "RepoKind: unrecognized",
            };
            // Worktree carries a name field; surface it in the
            // label so a user can tell which worktree.
            let label = if let RepoKind::LinkedWorktree { name } = &ctx.repo_kind {
                format!("{label} ({name})")
            } else {
                label.to_string()
            };
            CheckResult::pass(GIT_REPO_KIND_ID, label)
        }
        DoctorGitSnapshot::Failed { .. } => CheckResult::skip(
            GIT_REPO_KIND_ID,
            "RepoKind detected",
            "repo discovery failed",
        ),
        DoctorGitSnapshot::NotInRepo => {
            CheckResult::skip(GIT_REPO_KIND_ID, "RepoKind detected", "not in a git repo")
        }
    }
}

/// Whether any built-in `git_*` segment id appears in the loaded
/// config's segment lists. Used by the git-not-in-repo
/// SKIP-vs-WARN gate.
///
/// Gates against `BUILT_IN_SEGMENT_IDS` filtered by the `git_`
/// prefix rather than a raw `starts_with("git_")` lens — a user
/// plugin id like `git_typo` shouldn't trigger the runtime's
/// "you're not in a repo" WARN, since the plugin is the one
/// rendering and it has its own error path. Forward-compat: a
/// future built-in `git_status` / `git_stash` automatically picks
/// up the carve-out without doctor edits, since they'd land in
/// `BUILT_IN_SEGMENT_IDS`.
fn any_git_segment_enabled(read: &ConfigReadOutcome) -> bool {
    let ConfigReadOutcome::Loaded { config, .. } = read else {
        return false;
    };
    let Some(line) = &config.line else {
        return false;
    };
    let is_builtin_git = |id: &str| {
        crate::segments::BUILT_IN_SEGMENT_IDS
            .iter()
            .any(|b| *b == id && b.starts_with("git_"))
    };
    if line
        .segments
        .iter()
        .filter_map(|e| e.segment_id())
        .any(is_builtin_git)
    {
        return true;
    }
    line.numbered.values().any(|v| {
        v.as_table()
            .and_then(|t| t.get("segments"))
            .and_then(|s| s.as_array())
            .is_some_and(|arr| {
                arr.iter().any(|item| match numbered_entry_id(item) {
                    NumberedEntry::Segment(id) => is_builtin_git(id),
                    NumberedEntry::Separator
                    | NumberedEntry::KindlessTable
                    | NumberedEntry::WrongShape => false,
                })
            })
    })
}

/// Classify one entry inside a `[line.N].segments` array per
/// ADR-0024: bare string or inline table with a `type` field.
/// `Segment(id)` carries the borrowed id (stripped of `"separator"`
/// — separators don't count as segments here). The `KindlessTable`
/// and `WrongShape` variants surface as malformed-line warnings.
enum NumberedEntry<'a> {
    Segment(&'a str),
    Separator,
    KindlessTable,
    WrongShape,
}

fn numbered_entry_id(item: &toml::Value) -> NumberedEntry<'_> {
    if let Some(s) = item.as_str() {
        return NumberedEntry::Segment(s);
    }
    if let Some(table) = item.as_table() {
        match table.get("type").and_then(|v| v.as_str()) {
            Some("separator") => NumberedEntry::Separator,
            Some(id) => NumberedEntry::Segment(id),
            None => NumberedEntry::KindlessTable,
        }
    } else {
        NumberedEntry::WrongShape
    }
}

fn self_category(env: &DoctorEnv) -> Category {
    Category::new(
        "Self",
        vec![
            check_self_version(),
            check_binary_path(env),
            check_self_update_available(&env.update_probe),
            check_self_binary_integrity(env.binary_build_sha),
        ],
    )
}

fn check_self_version() -> CheckResult {
    CheckResult::pass(
        "self.version",
        format!("linesmith {}", env!("CARGO_PKG_VERSION")),
    )
}

fn check_binary_path(env: &DoctorEnv) -> CheckResult {
    match &env.current_exe {
        Ok(p) => CheckResult::pass("self.binary_path", format!("Binary: {}", p.display())),
        // Preserve the underlying error so the user sees whether it
        // was a missing /proc, a deleted exe, a permission issue,
        // etc. Generic "reinstall" advice is only right for some of
        // those.
        Err(err) => CheckResult::warn(
            "self.binary_path",
            format!("Could not resolve binary path: {err}"),
            "std::env::current_exe failed (unusual; check sandbox / permissions or reinstall)",
        ),
    }
}

fn check_self_binary_integrity(build_sha: Option<&'static str>) -> CheckResult {
    // Trim before checking emptiness. CI pipelines that pipe `git
    // rev-parse HEAD` through a buggy substitution can produce
    // whitespace-only SHAs (`" "`, `"\n"`, `"\t"`); these are NOT
    // traceability and rendering them as PASS produces a tell-tale
    // double-space "Built from   (linesmith ...)" line that's worse
    // than the WARN — it falsely claims provenance.
    let trimmed = build_sha.map(str::trim).filter(|s| !s.is_empty());
    match trimmed {
        // Build-time SHA present and non-blank → traceable back to a
        // known commit through whatever pipeline (cargo-dist, GitHub
        // Actions, etc.) set the env var. Surface a 7-char prefix in
        // the label so the user can copy it into bug reports without
        // a follow-up round trip.
        Some(sha) => {
            let short = sha.get(..sha.len().min(7)).unwrap_or(sha);
            CheckResult::pass(
                "self.binary_integrity",
                format!(
                    "Built from {short} (linesmith {})",
                    env!("CARGO_PKG_VERSION")
                ),
            )
        }
        // No build metadata, or a blank value → almost always a local
        // `cargo build` (a dev environment doesn't set
        // `LINESMITH_BUILD_SHA`); rarely, a binary patched after the
        // fact. Spec WARN, not FAIL — most users hit this by building
        // from source rather than by being attacked.
        None => CheckResult::warn(
            "self.binary_integrity",
            "Build metadata missing (LINESMITH_BUILD_SHA not set at compile time)",
            "reinstall from a canonical source (cargo-dist release / package manager) to verify provenance",
        ),
    }
}

fn check_self_update_available(probe: &DoctorUpdateProbe) -> CheckResult {
    match probe {
        DoctorUpdateProbe::Latest => CheckResult::pass(
            "self.update_available",
            format!("Running on latest release (v{})", env!("CARGO_PKG_VERSION")),
        ),
        DoctorUpdateProbe::Newer { latest } => CheckResult::warn(
            "self.update_available",
            format!(
                "New release available: {latest} (running v{})",
                env!("CARGO_PKG_VERSION")
            ),
            "run `brew upgrade linesmith` (or your equivalent install path)",
        ),
        // Per spec §Self: transport errors WARN rather than FAIL —
        // air-gapped CI / corporate proxy / GitHub outage shouldn't
        // gate exit-1 on a setup-verification command.
        DoctorUpdateProbe::TransportError { message } => CheckResult::warn(
            "self.update_available",
            format!("Could not reach GitHub releases API: {message}"),
            "no network or GitHub unreachable; re-run when online to verify version",
        ),
        DoctorUpdateProbe::ParseError { message } => CheckResult::warn(
            "self.update_available",
            format!("GitHub releases response unrecognized: {message}"),
            "GitHub releases API may have changed shape; file a linesmith bug if this persists",
        ),
    }
}

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

    #[test]
    fn glyphs_within_a_mode_are_pairwise_distinct() {
        // Reader must distinguish PASS from FAIL at a glance — the
        // user-facing contract is intra-mode distinctness, not
        // cross-mode (which would still allow collisions like
        // PASS_unicode == SKIP_unicode).
        let unicode: Vec<_> = [
            Severity::Pass,
            Severity::Warn,
            Severity::Fail,
            Severity::Skip,
        ]
        .iter()
        .map(|s| s.unicode_glyph())
        .collect();
        let ascii: Vec<_> = [
            Severity::Pass,
            Severity::Warn,
            Severity::Fail,
            Severity::Skip,
        ]
        .iter()
        .map(|s| s.ascii_glyph())
        .collect();
        for (i, a) in unicode.iter().enumerate() {
            for (j, b) in unicode.iter().enumerate() {
                if i != j {
                    assert_ne!(a, b, "unicode glyph collision: {a} == {b}");
                }
            }
        }
        for (i, a) in ascii.iter().enumerate() {
            for (j, b) in ascii.iter().enumerate() {
                if i != j {
                    assert_ne!(a, b, "ascii glyph collision: {a} == {b}");
                }
            }
        }
    }

    #[test]
    fn check_result_constructors_round_trip_id_and_severity() {
        let p = CheckResult::pass("p.id", "label");
        assert_eq!(p.id(), "p.id");
        assert_eq!(p.severity(), Severity::Pass);
        assert!(p.hint.is_none(), "PASS must not carry a hint");

        let w = CheckResult::warn("w.id", "label", "do thing");
        assert_eq!(w.id(), "w.id");
        assert_eq!(w.severity(), Severity::Warn);
        assert_eq!(w.hint.as_deref(), Some("do thing"));

        let f = CheckResult::fail("f.id", "label", "fix");
        assert_eq!(f.severity(), Severity::Fail);
        assert_eq!(f.hint.as_deref(), Some("fix"));

        let s = CheckResult::skip("s.id", "label", "no $HOME");
        assert_eq!(s.severity(), Severity::Skip);
        assert_eq!(s.hint.as_deref(), Some("no $HOME"));
    }

    #[test]
    fn ascii_glyphs_contain_no_unicode() {
        for s in [
            Severity::Pass,
            Severity::Warn,
            Severity::Fail,
            Severity::Skip,
        ] {
            assert!(
                s.ascii_glyph().is_ascii(),
                "ascii glyph for {s:?} contains non-ASCII bytes",
            );
        }
    }

    fn fail_only_report() -> Report {
        Report {
            linesmith_version: "0.1.0",
            categories: vec![Category::new(
                "Self",
                vec![CheckResult::fail("self.broken", "broken", "fix it")],
            )],
        }
    }

    #[test]
    fn exit_code_is_one_on_any_fail() {
        assert_eq!(fail_only_report().exit_code(), 1);
    }

    #[test]
    fn exit_code_is_zero_on_warn_only() {
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![Category::new(
                "Self",
                vec![CheckResult::warn("self.warn", "degraded", "do thing")],
            )],
        };
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn exit_code_is_zero_on_all_pass() {
        assert_eq!(build_report(&DoctorEnv::healthy()).exit_code(), 0);
    }

    #[test]
    fn exit_code_skip_does_not_fail() {
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![Category::new(
                "Self",
                vec![CheckResult::skip("self.na", "n/a", "not applicable")],
            )],
        };
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn exit_code_is_one_when_fail_mixed_with_other_severities() {
        // Defends against `.any() → .all()` typo: every other exit-
        // code test uses a homogeneous report, so the `.any()` could
        // be silently swapped without detection.
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![
                Category::new(
                    "A",
                    vec![
                        CheckResult::pass("a.ok", "ok"),
                        CheckResult::warn("a.warn", "degraded", "do thing"),
                    ],
                ),
                Category::new(
                    "B",
                    vec![
                        CheckResult::skip("b.na", "n/a", "skipped"),
                        CheckResult::fail("b.broken", "broken", "fix"),
                    ],
                ),
            ],
        };
        assert_eq!(r.exit_code(), 1);
    }

    #[test]
    fn exit_code_is_zero_when_no_fail_in_mixed_report() {
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![
                Category::new(
                    "A",
                    vec![
                        CheckResult::pass("a.ok", "ok"),
                        CheckResult::warn("a.warn", "degraded", "do thing"),
                    ],
                ),
                Category::new("B", vec![CheckResult::skip("b.na", "n/a", "skipped")]),
            ],
        };
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn summary_counts_aggregate_across_categories() {
        // Distinct counts per severity (2/3/1/4) so any positional
        // swap in the renderer's format string surfaces — equal
        // counts would let a `{} WARN` ↔ `{} FAIL` swap slip through.
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![
                Category::new(
                    "A",
                    vec![
                        CheckResult::pass("a.1", "ok"),
                        CheckResult::pass("a.2", "ok"),
                        CheckResult::warn("a.3", "deg", "hint"),
                        CheckResult::warn("a.4", "deg", "hint"),
                        CheckResult::warn("a.5", "deg", "hint"),
                    ],
                ),
                Category::new(
                    "B",
                    vec![
                        CheckResult::fail("b.1", "broken", "fix"),
                        CheckResult::skip("b.2", "na", "reason"),
                        CheckResult::skip("b.3", "na", "reason"),
                        CheckResult::skip("b.4", "na", "reason"),
                        CheckResult::skip("b.5", "na", "reason"),
                    ],
                ),
            ],
        };
        let counts = r.summary_counts();
        assert_eq!(counts.pass, 2);
        assert_eq!(counts.warn, 3);
        assert_eq!(counts.fail, 1);
        assert_eq!(counts.skip, 4);

        // Pin the field-to-position mapping in the format string —
        // catches typos like `{} WARN` interpolating counts.fail.
        let mut out = Vec::new();
        render(&mut out, &r, RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("2 PASS"), "wrong PASS count rendered:\n{s}");
        assert!(s.contains("3 WARN"), "wrong WARN count rendered:\n{s}");
        assert!(s.contains("1 FAIL"), "wrong FAIL count rendered:\n{s}");
        assert!(s.contains("4 SKIP"), "wrong SKIP count rendered:\n{s}");
    }

    #[test]
    fn plain_mode_emits_no_unicode() {
        // Walk every renderer-emitted label across every check
        // through `RenderMode::Plain` and assert ASCII for each.
        // Each `DoctorEnv` snapshot holds one state per slot, so
        // covering the full label surface requires N rendered
        // reports — `plain_mode_coverage_envs()` enumerates them.
        // The previous version of this test rendered only one
        // synthetic fixture covering nothing real, then a
        // healthy-baseline (PASS-only) walk; FAIL/WARN labels
        // could ship with Unicode and slip the tripwire.
        for (name, env) in plain_mode_coverage_envs() {
            let mut out = Vec::new();
            render(&mut out, &build_report(&env), RenderMode::Plain).expect("render ok");
            let s = String::from_utf8(out).expect("utf8");
            assert!(
                s.is_ascii(),
                "plain output contains non-ASCII bytes for `{name}`:\n{s}",
            );
        }
    }

    /// Enumerate `DoctorEnv` fixtures that, between them, exercise
    /// every label-producing branch in every check. Returns
    /// `(name, env)` pairs so the failing assertion can name the
    /// scenario rather than dumping a wall of text. Each branch
    /// needs at least one fixture; some fixtures exercise several
    /// where the snapshot shape allows it.
    fn plain_mode_coverage_envs() -> Vec<(&'static str, DoctorEnv)> {
        use crate::data_context::credentials::CredentialSource;
        use crate::data_context::git::{Head, RepoKind};
        use linesmith_plugin::{CollisionWinner, PluginError};

        let mut envs: Vec<(&'static str, DoctorEnv)> = Vec::new();

        // Healthy baseline covers every PASS-class label.
        envs.push(("healthy", DoctorEnv::healthy()));

        // --- Environment FAIL/WARN labels ---
        let mut env = DoctorEnv::healthy();
        // ASCII-only payload — `EnvVarState::NonUtf8` fires the
        // FAIL branch on the variant tag, not the value bytes,
        // and any Unicode in the value would correctly pass
        // through per the renderer's user-content caveat.
        env.home_env = EnvVarState::non_utf8_for_test("nonutf8-placeholder");
        envs.push(("env.home_non_utf8", env));

        let mut env = DoctorEnv::healthy();
        env.term = EnvVarState::Set(String::new());
        envs.push(("env.term_empty", env));

        let mut env = DoctorEnv::healthy();
        env.terminal_width_cells = Some(0);
        envs.push(("env.term_width_zero", env));

        let mut env = DoctorEnv::healthy();
        env.current_exe = Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "denied",
        ));
        envs.push(("self.binary_path_err", env));

        // --- Config FAIL/WARN labels ---
        let mut env = DoctorEnv::healthy();
        env.config.read = ConfigReadOutcome::ParseError {
            path: PathBuf::from("/etc/linesmith/config.toml"),
            message: "TOML parse error at line 3, column 7".to_string(),
        };
        envs.push(("config.parse_error", env));

        let mut env = DoctorEnv::healthy();
        env.config.read = ConfigReadOutcome::IoError {
            path: PathBuf::from("/etc/linesmith/config.toml"),
            message: "Permission denied".to_string(),
        };
        envs.push(("config.io_error", env));

        let mut env = DoctorEnv::healthy();
        env.config.plugin_dirs = vec![PluginDirStatus {
            path: PathBuf::from("/etc/missing"),
            state: PluginDirState::Missing,
        }];
        envs.push(("config.plugin_dirs_missing", env));

        // --- Claude Code FAIL/WARN labels ---
        let mut env = DoctorEnv::healthy();
        env.claude_code.binary_path = None;
        envs.push(("claude.binary_missing", env));

        let mut env = DoctorEnv::healthy();
        env.claude_code.path_env = EnvVarState::non_utf8_for_test("nonutf8-placeholder");
        env.claude_code.binary_path = None;
        envs.push(("claude.path_env_non_utf8", env));

        let mut env = DoctorEnv::healthy();
        if let Some(home) = &mut env.claude_code.home_state {
            home.dir = ClaudeDirState::PermissionDenied {
                message: "EACCES".to_string(),
            };
            home.claude_json = ClaudeJsonState::ParseError {
                message: "expected `:` at line 4 column 12".to_string(),
            };
            home.sessions = ClaudeSessionsState::Empty;
        }
        envs.push(("claude.permission_denied_and_parse_error", env));

        // --- Credentials FAIL/WARN labels ---
        let mut env = DoctorEnv::healthy();
        env.credentials = DoctorCredentialsSnapshot::Failed(CredentialErrorSummary::IoError {
            path: PathBuf::from("/home/user/.claude/.credentials.json"),
            message: "Permission denied".to_string(),
        });
        envs.push(("creds.io_error", env));

        let mut env = DoctorEnv::healthy();
        env.credentials = DoctorCredentialsSnapshot::Failed(CredentialErrorSummary::ParseError {
            path: PathBuf::from("/home/user/.claude/.credentials.json"),
        });
        envs.push(("creds.parse_error", env));

        let mut env = DoctorEnv::healthy();
        env.credentials =
            DoctorCredentialsSnapshot::Failed(CredentialErrorSummary::SubprocessFailed {
                message: "security: locked".to_string(),
            });
        envs.push(("creds.subprocess_failed", env));

        let mut env = DoctorEnv::healthy();
        env.credentials = DoctorCredentialsSnapshot::Resolved(CredentialsSummary {
            source: CredentialSource::MacosKeychainMultiAccount {
                service: "Claude Code-credentials-2".to_string(),
                mdat: Some("12345".to_string()),
            },
            scopes: vec!["user:profile".to_string()], // missing user:inference
        });
        envs.push(("creds.scopes_missing", env));

        // --- Cache FAIL/WARN labels ---
        let mut env = DoctorEnv::healthy();
        env.cache.usage_json = UsageJsonState::Stale { schema_version: 0 };
        envs.push(("cache.usage_stale", env));

        let mut env = DoctorEnv::healthy();
        env.cache.usage_json = UsageJsonState::FutureTimestamp;
        envs.push(("cache.usage_future_timestamp", env));

        let mut env = DoctorEnv::healthy();
        env.cache.usage_json = UsageJsonState::Unreadable {
            message: "filesystem corruption".to_string(),
        };
        env.cache.lock = LockState::Stale {
            blocked_until_secs: 1,
        };
        envs.push(("cache.unreadable_and_stale_lock", env));

        let mut env = DoctorEnv::healthy();
        env.cache.root = CacheRootState::NotADirectory;
        envs.push(("cache.not_a_directory", env));

        let mut env = DoctorEnv::healthy();
        env.cache.root = CacheRootState::Unreadable {
            message: "Permission denied (os error 13)".to_string(),
        };
        envs.push(("cache.unreadable", env));

        let mut env = DoctorEnv::healthy();
        env.cache.root = CacheRootState::Absent;
        envs.push(("cache.absent_first_run", env));

        let mut env = DoctorEnv::healthy();
        env.cache.root = CacheRootState::AbsentParentReadOnly {
            parent: PathBuf::from("/proc"),
        };
        envs.push(("cache.absent_parent_read_only", env));

        // --- Endpoint FAIL/WARN labels ---
        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 2500,
            outcome: EndpointProbeOutcome::Slow,
        });
        envs.push(("endpoint.slow", env));

        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 150,
            outcome: EndpointProbeOutcome::BadStatus { status: 401 },
        });
        envs.push(("endpoint.bad_status", env));

        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 100,
            outcome: EndpointProbeOutcome::TransportError,
        });
        envs.push(("endpoint.transport_error", env));

        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 200,
            outcome: EndpointProbeOutcome::UnexpectedShape {
                extra_keys: vec!["omelette_5h".to_string(), "iguana_7d".to_string()],
            },
        });
        envs.push(("endpoint.unexpected_shape", env));

        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 300,
            outcome: EndpointProbeOutcome::ParseError,
        });
        envs.push(("endpoint.parse_error", env));

        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 250,
            outcome: EndpointProbeOutcome::RateLimited {
                retry_after_secs: Some(60),
            },
        });
        envs.push(("endpoint.rate_limited_warn", env));

        let mut env = DoctorEnv::healthy();
        env.endpoint.probe = Some(EndpointProbe {
            elapsed_ms: 250,
            outcome: EndpointProbeOutcome::RateLimited {
                retry_after_secs: Some(7200),
            },
        });
        envs.push(("endpoint.rate_limited_fail", env));

        // --- Plugins FAIL labels (every load-time PluginError variant) ---
        let mut env = DoctorEnv::healthy();
        env.plugins = DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 0,
            errors: vec![
                PluginError::Compile {
                    path: PathBuf::from("/p/compile.rhai"),
                    message: "syntax error".to_string(),
                },
                PluginError::UnknownDataDep {
                    path: PathBuf::from("/p/dep.rhai"),
                    name: "credentialz".to_string(),
                },
                PluginError::MalformedDataDeps {
                    path: PathBuf::from("/p/header.rhai"),
                    message: "expected array".to_string(),
                },
                PluginError::IdCollision {
                    id: "shared".to_string(),
                    winner: CollisionWinner::Plugin(PathBuf::from("/p/first.rhai")),
                    loser_path: PathBuf::from("/p/second.rhai"),
                },
                PluginError::IdCollision {
                    id: "model".to_string(),
                    winner: CollisionWinner::BuiltIn,
                    loser_path: PathBuf::from("/p/shadow.rhai"),
                },
            ],
        });
        envs.push(("plugins.all_load_errors", env));

        let env = with_plugins(DoctorPluginsSnapshot::NoSources);
        envs.push(("plugins.no_sources", env));

        // --- Git FAIL/WARN labels ---
        let env = with_git(DoctorGitSnapshot::Failed {
            message: "InvalidFormat: expected git_dir".to_string(),
        });
        envs.push(("git.failed", env));

        let env = with_git(DoctorGitSnapshot::Repo(GitContextSummary {
            repo_path: PathBuf::from("/repo/.git"),
            repo_kind: RepoKind::LinkedWorktree {
                name: "feature-x".to_string(),
            },
            head: Head::Detached(gix::ObjectId::null(gix::hash::Kind::Sha1)),
        }));
        envs.push(("git.detached_worktree", env));

        let env = with_git(DoctorGitSnapshot::Repo(GitContextSummary {
            repo_path: PathBuf::from("/repo/.git"),
            repo_kind: RepoKind::Bare,
            head: Head::Unborn {
                symbolic_ref: "main".to_string(),
            },
        }));
        envs.push(("git.bare_unborn", env));

        let env = with_git(DoctorGitSnapshot::Repo(GitContextSummary {
            repo_path: PathBuf::from("/repo/.git"),
            repo_kind: RepoKind::Submodule,
            head: Head::OtherRef {
                full_name: "refs/tags/v1.0".to_string(),
            },
        }));
        envs.push(("git.submodule_otherref", env));

        // --- Self/update_available WARN labels ---
        let mut env = DoctorEnv::healthy();
        env.update_probe = DoctorUpdateProbe::Newer {
            latest: "v99.0.0".to_string(),
        };
        envs.push(("self.update_newer", env));

        let mut env = DoctorEnv::healthy();
        env.update_probe = DoctorUpdateProbe::TransportError {
            message: "dns lookup failed".to_string(),
        };
        envs.push(("self.update_transport_error", env));

        let mut env = DoctorEnv::healthy();
        env.update_probe = DoctorUpdateProbe::ParseError {
            message: "missing tag_name".to_string(),
        };
        envs.push(("self.update_parse_error", env));

        // --- Self/binary_integrity WARN label ---
        let mut env = DoctorEnv::healthy();
        env.binary_build_sha = None;
        envs.push(("self.binary_integrity_missing", env));

        // --- Claude Code/json_parses TooLarge FAIL label ---
        let mut env = DoctorEnv::healthy();
        if let Some(home) = &mut env.claude_code.home_state {
            home.claude_json = ClaudeJsonState::TooLarge {
                actual_bytes: 500 * 1024 * 1024,
            };
        }
        envs.push(("claude.json_too_large", env));

        envs
    }

    #[test]
    fn plain_mode_summary_separator_is_ascii() {
        let mut out = Vec::new();
        render(
            &mut out,
            &build_report(&DoctorEnv::healthy()),
            RenderMode::Plain,
        )
        .expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(
            s.contains("PASS / "),
            "plain summary should use '/' separator:\n{s}"
        );
    }

    #[test]
    fn default_mode_emits_unicode_glyphs() {
        let mut out = Vec::new();
        render(&mut out, &fail_only_report(), RenderMode::Default).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains(''), "expected ✗ glyph in default render:\n{s}");
    }

    #[test]
    fn default_mode_summary_separator_is_middle_dot() {
        let mut out = Vec::new();
        render(
            &mut out,
            &build_report(&DoctorEnv::healthy()),
            RenderMode::Default,
        )
        .expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(
            s.contains("PASS · "),
            "default summary should use '·' separator:\n{s}"
        );
    }

    #[test]
    fn render_includes_summary_and_exit_lines() {
        let mut out = Vec::new();
        render(
            &mut out,
            &build_report(&DoctorEnv::healthy()),
            RenderMode::Plain,
        )
        .expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("Summary:"), "missing Summary line:\n{s}");
        assert!(s.contains("Exit: 0"), "missing Exit line:\n{s}");
    }

    #[test]
    fn fail_check_renders_hint_indented_after_fail_line() {
        let mut out = Vec::new();
        render(&mut out, &fail_only_report(), RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        // Intent: hint appears indented after the failure line.
        // Exact arrow / spacing is presentation detail covered by
        // snapshot tests in the integration suite.
        assert!(s.contains("fix it"), "hint text missing:\n{s}");
        let fail_idx = s.find("XX broken").expect("FAIL line missing");
        let hint_idx = s.find("fix it").expect("hint missing");
        assert!(hint_idx > fail_idx, "hint must follow the FAIL line");
    }

    #[test]
    fn warn_and_skip_checks_render_their_hint() {
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![Category::new(
                "X",
                vec![
                    CheckResult::warn("x.w", "deg", "warn-hint"),
                    CheckResult::skip("x.s", "na", "skip-reason"),
                ],
            )],
        };
        let mut out = Vec::new();
        render(&mut out, &r, RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("warn-hint"), "WARN hint missing:\n{s}");
        assert!(s.contains("skip-reason"), "SKIP reason missing:\n{s}");
    }

    #[test]
    fn render_includes_category_header() {
        let mut out = Vec::new();
        render(
            &mut out,
            &build_report(&DoctorEnv::healthy()),
            RenderMode::Plain,
        )
        .expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("\nSelf\n"), "missing category header:\n{s}");
    }

    #[test]
    fn render_emits_blank_line_between_categories() {
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![
                Category::new("A", vec![CheckResult::pass("a.1", "a-line")]),
                Category::new("B", vec![CheckResult::pass("b.1", "b-line")]),
            ],
        };
        let mut out = Vec::new();
        render(&mut out, &r, RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(
            s.contains("a-line\n\nB\n"),
            "expected blank line separating categories:\n{s}"
        );
    }

    #[test]
    fn plain_mode_passes_user_supplied_unicode_through_verbatim() {
        // Contract pin: per docs/specs/doctor.md §plain caveat, --plain
        // guarantees no Unicode in *renderer-emitted* strings only.
        // User-supplied label/hint (paths like ~/café/config) pass
        // through verbatim. A future "fix" that ASCII-folds user
        // content would be a contract change, not a bug fix.
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![Category::new(
                "X",
                vec![CheckResult::warn("x.cfg", "config at ~/café", "edit ☃")],
            )],
        };
        let mut out = Vec::new();
        render(&mut out, &r, RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("~/café"), "user label must pass through:\n{s}");
        assert!(s.contains(''), "user hint must pass through:\n{s}");
    }

    #[test]
    fn empty_report_renders_summary_and_exits_zero() {
        // Guards against a future regression: code that asserts
        // non-empty categories would slip through every existing test
        // since none currently exercise the empty case.
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![],
        };
        let mut out = Vec::new();
        render(&mut out, &r, RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("Summary: 0 PASS"), "missing summary:\n{s}");
        assert!(s.contains("Exit: 0"), "missing exit line:\n{s}");
        assert_eq!(r.exit_code(), 0);
        assert_eq!(r.summary_counts(), SummaryCounts::default());
    }

    #[test]
    fn empty_category_renders_header_with_no_checks() {
        // E.g. Plugins category when no plugins are configured, or
        // Git category outside a repo. Header must still render so
        // the user can see the category was considered.
        let r = Report {
            linesmith_version: "0.1.0",
            categories: vec![Category::new("Plugins", vec![])],
        };
        let mut out = Vec::new();
        render(&mut out, &r, RenderMode::Plain).expect("render ok");
        let s = String::from_utf8(out).expect("utf8");
        assert!(
            s.contains("\nPlugins\n"),
            "missing empty-category header:\n{s}"
        );
    }

    #[test]
    fn label_and_hint_accessors_return_constructor_inputs() {
        let p = CheckResult::pass("p.id", "label-p");
        assert_eq!(p.label(), "label-p");
        assert_eq!(p.hint(), None);

        let w = CheckResult::warn("w.id", "label-w", "warn-hint");
        assert_eq!(w.label(), "label-w");
        assert_eq!(w.hint(), Some("warn-hint"));

        let f = CheckResult::fail("f.id", "label-f", "fail-hint");
        assert_eq!(f.label(), "label-f");
        assert_eq!(f.hint(), Some("fail-hint"));

        let s = CheckResult::skip("s.id", "label-s", "skip-reason");
        assert_eq!(s.label(), "label-s");
        assert_eq!(s.hint(), Some("skip-reason"));
    }

    // --- Environment / Self check categories ---

    fn find_check<'a>(report: &'a Report, id: &str) -> &'a CheckResult {
        report
            .categories
            .iter()
            .flat_map(|c| &c.checks)
            .find(|c| c.id() == id)
            .unwrap_or_else(|| panic!("check {id} not present in report"))
    }

    #[test]
    fn healthy_env_produces_only_pass_checks() {
        let r = build_report(&DoctorEnv::healthy());
        for check in r.categories.iter().flat_map(|c| &c.checks) {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "check {} should be PASS in healthy env, got {:?}",
                check.id(),
                check.severity(),
            );
        }
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn report_categories_run_in_spec_order() {
        let r = build_report(&DoctorEnv::healthy());
        let names: Vec<_> = r.categories.iter().map(|c| c.name).collect();
        // Spec §Check ordering pins Environment → Config → Claude
        // Code → … → Self. As each category lands, slot it here so a
        // refactor that swaps order trips this test rather than
        // surfacing as a confusing report layout.
        assert_eq!(
            names,
            vec![
                "Environment",
                "Config",
                "Claude Code",
                "Credentials",
                "Cache",
                "Rate-limit endpoint",
                "Plugins",
                "Git",
                "Self",
            ],
        );
    }

    #[test]
    fn home_unset_fails_and_promotes_exit_code() {
        let mut env = DoctorEnv::healthy();
        env.home_env = EnvVarState::Unset;
        let r = build_report(&env);
        let home = find_check(&r, "env.home");
        assert_eq!(home.severity(), Severity::Fail);
        assert!(home.hint().unwrap().contains("$HOME"));
        assert_eq!(r.exit_code(), 1);
    }

    #[test]
    fn home_empty_string_fails() {
        // Empty $HOME is the same shape as missing — `dirs::home_dir`
        // returns None on Unix when $HOME is empty, and the check
        // mirrors that.
        let mut env = DoctorEnv::healthy();
        env.home_env = EnvVarState::Set(String::new());
        let r = build_report(&env);
        assert_eq!(find_check(&r, "env.home").severity(), Severity::Fail);
    }

    #[test]
    fn home_non_utf8_fails_with_distinct_hint() {
        // Critical: the user-facing hint must NOT say "$HOME is unset"
        // when $HOME is in fact set but unreadable. Misleading
        // remediation makes the user fight a phantom problem.
        let mut env = DoctorEnv::healthy();
        env.home_env = EnvVarState::non_utf8_for_test("/home/\u{FFFD}");
        let r = build_report(&env);
        let home = find_check(&r, "env.home");
        assert_eq!(home.severity(), Severity::Fail);
        assert!(
            home.label().contains("UTF-8"),
            "label should mention UTF-8: {}",
            home.label()
        );
        assert!(
            home.hint().unwrap().contains("UTF-8") || home.hint().unwrap().contains("rewrite"),
            "hint should point at the real fix: {:?}",
            home.hint()
        );
    }

    #[test]
    fn no_color_set_or_unset_both_pass() {
        for no_color in [true, false] {
            let mut env = DoctorEnv::healthy();
            env.no_color = no_color;
            let r = build_report(&env);
            assert_eq!(find_check(&r, "env.no_color").severity(), Severity::Pass);
        }
    }

    #[test]
    fn term_dumb_warns_not_fails() {
        let mut env = DoctorEnv::healthy();
        env.term = EnvVarState::Set("dumb".to_string());
        let r = build_report(&env);
        assert_eq!(find_check(&r, "env.term").severity(), Severity::Warn);
    }

    #[test]
    fn term_unset_warns() {
        let mut env = DoctorEnv::healthy();
        env.term = EnvVarState::Unset;
        let r = build_report(&env);
        assert_eq!(find_check(&r, "env.term").severity(), Severity::Warn);
    }

    #[test]
    fn term_empty_warns() {
        let mut env = DoctorEnv::healthy();
        env.term = EnvVarState::Set(String::new());
        let r = build_report(&env);
        assert_eq!(find_check(&r, "env.term").severity(), Severity::Warn);
    }

    #[test]
    fn term_non_utf8_warns_with_distinct_hint() {
        let mut env = DoctorEnv::healthy();
        env.term = EnvVarState::non_utf8_for_test("xterm-\u{FFFD}");
        let r = build_report(&env);
        let term = find_check(&r, "env.term");
        assert_eq!(term.severity(), Severity::Warn);
        assert!(term.label().contains("UTF-8"));
    }

    #[test]
    fn stdout_not_a_tty_warns_not_fails() {
        // Critical contract: piped/CI stdout is WARN, never FAIL, so
        // `linesmith doctor --plain | tee log.txt` in CI doesn't gate
        // exit-1. Per spec §Cross-category short-circuits.
        let mut env = DoctorEnv::healthy();
        env.stdout_is_terminal = false;
        let r = build_report(&env);
        assert_eq!(find_check(&r, "env.stdout_tty").severity(), Severity::Warn);
        assert_eq!(r.exit_code(), 0, "non-tty must not promote exit code");
    }

    #[test]
    fn terminal_width_unknown_warns() {
        let mut env = DoctorEnv::healthy();
        env.terminal_width_cells = None;
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "env.terminal_width").severity(),
            Severity::Warn
        );
    }

    #[test]
    fn terminal_width_under_threshold_warns() {
        // Spec §Environment: Some((W, _)) with W < 40 → WARN.
        let mut env = DoctorEnv::healthy();
        env.terminal_width_cells = Some(39);
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "env.terminal_width").severity(),
            Severity::Warn
        );
    }

    #[test]
    fn terminal_width_at_threshold_passes() {
        let mut env = DoctorEnv::healthy();
        env.terminal_width_cells = Some(40);
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "env.terminal_width").severity(),
            Severity::Pass
        );
    }

    #[test]
    fn terminal_width_zero_warns_with_distinct_hint() {
        // 0 cells is qualitatively different from "narrow" — it's a
        // driver / terminfo bug. The hint must point at the terminal
        // emulator, not "set $COLUMNS".
        let mut env = DoctorEnv::healthy();
        env.terminal_width_cells = Some(0);
        let r = build_report(&env);
        let w = find_check(&r, "env.terminal_width");
        assert_eq!(w.severity(), Severity::Warn);
        let hint = w.hint().unwrap();
        assert!(
            hint.contains("terminal emulator") || hint.contains("driver"),
            "hint should distinguish driver bug from narrow width: {hint}"
        );
    }

    #[test]
    fn binary_path_resolves_passes() {
        let env = DoctorEnv::healthy();
        let r = build_report(&env);
        let bin = find_check(&r, "self.binary_path");
        assert_eq!(bin.severity(), Severity::Pass);
        assert!(bin.label().contains("Binary"));
    }

    #[test]
    fn binary_path_failure_preserves_io_error_in_label() {
        // Generic "current_exe failed" hides the cause. The label
        // must include the underlying io::Error so a user sees
        // whether it's permission-denied vs broken-symlink etc.
        let mut env = DoctorEnv::healthy();
        env.current_exe = Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "no access to /proc/self/exe",
        ));
        let r = build_report(&env);
        let bin = find_check(&r, "self.binary_path");
        assert_eq!(bin.severity(), Severity::Warn);
        assert!(
            bin.label().contains("no access to /proc/self/exe"),
            "io::Error message must surface in label: {}",
            bin.label()
        );
    }

    #[test]
    fn self_version_check_includes_crate_version() {
        let r = build_report(&DoctorEnv::healthy());
        let v = find_check(&r, "self.version");
        assert_eq!(v.severity(), Severity::Pass);
        assert!(v.label().contains(env!("CARGO_PKG_VERSION")));
    }

    #[test]
    fn self_update_available_pass_when_probe_is_latest() {
        let r = build_report(&DoctorEnv::healthy());
        let u = find_check(&r, "self.update_available");
        assert_eq!(u.severity(), Severity::Pass);
        assert!(
            u.label().contains("latest"),
            "label should mention 'latest': {}",
            u.label()
        );
    }

    #[test]
    fn self_update_available_warns_when_newer_release_exists() {
        let mut env = DoctorEnv::healthy();
        env.update_probe = DoctorUpdateProbe::Newer {
            latest: "v99.0.0".to_string(),
        };
        let r = build_report(&env);
        let u = find_check(&r, "self.update_available");
        assert_eq!(u.severity(), Severity::Warn);
        assert!(u.label().contains("v99.0.0"), "label: {}", u.label());
        assert!(
            u.hint().is_some_and(|h| h.contains("brew upgrade")),
            "hint should reference upgrade path: {:?}",
            u.hint()
        );
        assert_eq!(
            r.exit_code(),
            0,
            "newer-release WARN must not promote exit code"
        );
    }

    #[test]
    fn self_update_available_warns_on_transport_error() {
        let mut env = DoctorEnv::healthy();
        env.update_probe = DoctorUpdateProbe::TransportError {
            message: "dns failure".to_string(),
        };
        let r = build_report(&env);
        let u = find_check(&r, "self.update_available");
        assert_eq!(u.severity(), Severity::Warn);
        assert!(u.label().contains("dns failure"), "label: {}", u.label());
        assert_eq!(
            r.exit_code(),
            0,
            "offline / transport error must not gate exit-1"
        );
    }

    #[test]
    fn self_update_available_warns_on_parse_error() {
        let mut env = DoctorEnv::healthy();
        env.update_probe = DoctorUpdateProbe::ParseError {
            message: "missing tag_name".to_string(),
        };
        let r = build_report(&env);
        let u = find_check(&r, "self.update_available");
        assert_eq!(u.severity(), Severity::Warn);
        assert!(
            u.hint().is_some_and(|h| h.contains("file a linesmith bug")),
            "parse-error hint should point at filing a bug: {:?}",
            u.hint()
        );
    }

    #[test]
    fn self_binary_integrity_passes_when_build_sha_present() {
        let r = build_report(&DoctorEnv::healthy());
        let bi = find_check(&r, "self.binary_integrity");
        assert_eq!(bi.severity(), Severity::Pass);
        // Healthy fixture sets sha = "abc1234"; label should surface
        // a short prefix so users can copy it into bug reports.
        assert!(
            bi.label().contains("abc1234"),
            "label should include the SHA: {}",
            bi.label()
        );
    }

    #[test]
    fn self_binary_integrity_warns_when_build_sha_missing() {
        let mut env = DoctorEnv::healthy();
        env.binary_build_sha = None;
        let r = build_report(&env);
        let bi = find_check(&r, "self.binary_integrity");
        assert_eq!(bi.severity(), Severity::Warn);
        assert!(
            bi.hint().is_some_and(|h| h.contains("reinstall")),
            "hint should suggest reinstalling: {:?}",
            bi.hint()
        );
        assert_eq!(
            r.exit_code(),
            0,
            "missing build metadata is WARN, must not gate exit-1"
        );
    }

    #[test]
    fn self_binary_integrity_warns_on_empty_sha_same_as_missing() {
        // `LINESMITH_BUILD_SHA=""` (a CI mistake — env var exported
        // but never set) is NOT traceability. Without this guard the
        // PASS line would render as "Built from  (linesmith …)" with
        // a tell-tale double space and no commit. Fold into the same
        // WARN as `None` so the WARN-vs-PASS boundary tracks the
        // spec's "matches build metadata" contract instead of
        // `Option::is_some`.
        let mut env = DoctorEnv::healthy();
        env.binary_build_sha = Some("");
        let r = build_report(&env);
        let bi = find_check(&r, "self.binary_integrity");
        assert_eq!(
            bi.severity(),
            Severity::Warn,
            "empty SHA must WARN, not PASS; got label {:?}",
            bi.label()
        );
    }

    #[test]
    fn self_binary_integrity_warns_on_whitespace_only_sha() {
        // CI pipelines that do `LINESMITH_BUILD_SHA=$(some-cmd)`
        // where some-cmd outputs only whitespace (newline-only
        // git output, broken trim, etc.) must NOT render as PASS
        // with a "Built from   " double-space line. Same WARN class
        // as the empty-string fix.
        for blank in [" ", "\t", "\n", "  \t\n  "] {
            let mut env = DoctorEnv::healthy();
            env.binary_build_sha = Some(blank);
            let r = build_report(&env);
            let bi = find_check(&r, "self.binary_integrity");
            assert_eq!(
                bi.severity(),
                Severity::Warn,
                "whitespace-only SHA {blank:?} must WARN; got label {:?}",
                bi.label()
            );
        }
    }

    #[test]
    fn self_binary_integrity_handles_multibyte_sha_without_panicking() {
        // Defensive UTF-8 boundary check: `sha.get(..n)` returns
        // `None` (rather than panicking) when `n` lands inside a
        // codepoint, and the `unwrap_or(sha)` arm catches that case.
        // Pin the contract so a future "simplification" to
        // `&sha[..7]` (which DOES panic on a codepoint boundary)
        // gets caught.
        let mut env = DoctorEnv::healthy();
        // "é" is 2 bytes; "é12" has len() = 4. `..min(7)` = `..4`
        // happens to fit, but `..3` would land inside "é".
        env.binary_build_sha = Some("é12");
        let r = build_report(&env);
        let bi = find_check(&r, "self.binary_integrity");
        assert_eq!(bi.severity(), Severity::Pass);
    }

    #[test]
    fn self_binary_integrity_truncates_long_sha_to_seven_chars() {
        // Real git SHAs are 40 hex chars; the renderer should show
        // only the conventional 7-char prefix so the label stays
        // tight at the standard tree width.
        let mut env = DoctorEnv::healthy();
        env.binary_build_sha = Some("0123456789abcdef0123456789abcdef01234567");
        let r = build_report(&env);
        let bi = find_check(&r, "self.binary_integrity");
        // Pin the boundary exactly: the rendered prefix is "0123456 "
        // (7 chars then a space), not 6 ("012345 ") or 8 ("01234567").
        assert!(
            bi.label().contains("0123456 (linesmith"),
            "expected exactly 7-char prefix followed by ' (linesmith': {}",
            bi.label()
        );
        assert!(
            !bi.label().contains("01234567"),
            "label must stop at 7 chars, not include the 8th: {}",
            bi.label()
        );
    }

    #[test]
    fn self_binary_integrity_handles_short_sha_without_panicking_and_passes() {
        // Defensive: if a build script supplies a SHA shorter than
        // 7 chars (some test pipelines do), the truncation slice
        // must not panic AND the check must still PASS — short SHAs
        // are still traceability, just less of it.
        let mut env = DoctorEnv::healthy();
        env.binary_build_sha = Some("abc");
        let r = build_report(&env);
        let bi = find_check(&r, "self.binary_integrity");
        assert_eq!(bi.severity(), Severity::Pass, "short SHA must still PASS");
        assert!(bi.label().contains("abc"));
    }

    #[test]
    fn doctor_env_from_process_does_not_panic() {
        // Smoke: the production env-snapshot path must not panic
        // regardless of the host's env state. (The actual values are
        // host-dependent so we don't assert on them.) Pass `None`
        // since we don't want to read a real --config off disk.
        let _ = DoctorEnv::from_process(None);
    }

    #[test]
    fn env_var_state_nonempty_filters_unset_empty_and_nonutf8() {
        assert_eq!(EnvVarState::Unset.nonempty(), None);
        assert_eq!(EnvVarState::Set(String::new()).nonempty(), None);
        assert_eq!(
            EnvVarState::non_utf8_for_test("garbage").nonempty(),
            None,
            "non-UTF-8 must not surface as Some — caller would treat the lossy preview as the real value"
        );
        assert_eq!(EnvVarState::Set("x".into()).nonempty(), Some("x"));
    }

    #[test]
    fn check_ids_follow_namespacing_convention() {
        // Spec §JSON output: ids are <category>.<check_name> in
        // snake_case. Extend the prefix allowlist as new categories
        // ship per spec §Check catalog — this test is a tripwire,
        // not a free pass.
        let r = build_report(&DoctorEnv::healthy());
        for check in r.categories.iter().flat_map(|c| &c.checks) {
            let id = check.id();
            assert!(id.contains('.'), "id `{id}` missing dotted namespace",);
            let prefix = id.split('.').next().unwrap();
            assert!(
                matches!(
                    prefix,
                    "env"
                        | "config"
                        | "claude"
                        | "creds"
                        | "cache"
                        | "endpoint"
                        | "plugins"
                        | "git"
                        | "self"
                ),
                "id `{id}` has unknown category prefix `{prefix}`",
            );
            assert!(
                id.chars()
                    .all(|c| c.is_ascii_lowercase() || c == '_' || c == '.'),
                "id `{id}` not snake_case",
            );
        }
    }

    // --- Config category ---

    use crate::config::{Config, ConfigPath, LineConfig};

    fn config_snapshot_loaded(config: Config) -> DoctorConfigSnapshot {
        let path = PathBuf::from("/home/user/.config/linesmith/config.toml");
        DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: path.clone(),
                explicit: false,
            }),
            read: ConfigReadOutcome::Loaded {
                path,
                config: Box::new(config),
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        }
    }

    #[test]
    fn config_category_with_default_loaded_config_passes_every_check() {
        let r = build_report(&DoctorEnv::healthy());
        let category = r
            .categories
            .iter()
            .find(|c| c.name == "Config")
            .expect("Config category present");
        for check in &category.checks {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "{} should be PASS in healthy env, got {:?}",
                check.id(),
                check.severity(),
            );
        }
    }

    #[test]
    fn config_category_emits_five_checks_in_spec_order() {
        // Spec §Config table: Config file discovered → Config parses
        // → All referenced segments exist → Theme is installed →
        // Plugin dirs are readable. Order matters because the parse
        // short-circuit propagates SKIPs downstream.
        let r = build_report(&DoctorEnv::healthy());
        let ids: Vec<_> = r
            .categories
            .iter()
            .find(|c| c.name == "Config")
            .expect("Config category present")
            .checks
            .iter()
            .map(|c| c.id())
            .collect();
        assert_eq!(
            ids,
            vec![
                "config.discovered",
                "config.parses",
                "config.segments_resolvable",
                "config.theme_installed",
                "config.plugin_dirs_readable",
            ]
        );
    }

    #[test]
    fn config_runs_when_home_unset_but_explicit_path_loaded() {
        // Spec §Cross-category short-circuits Config carve-out: when
        // `--config` / `$LINESMITH_CONFIG` / `$XDG_CONFIG_HOME` has
        // already resolved a path, run the checks against it even if
        // `$HOME` is unresolved. Gating on `$HOME` would silently
        // SKIP a config the user explicitly named — exactly the
        // false-negative the carve-out exists to prevent.
        let mut env = DoctorEnv::healthy();
        env.home_env = EnvVarState::Unset;
        // healthy()'s config snapshot is Loaded, simulating a
        // successful `--config /tmp/foo.toml` resolution.
        let r = build_report(&env);
        let category = r.categories.iter().find(|c| c.name == "Config").unwrap();
        for check in &category.checks {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "{} should PASS; $HOME unset must not gate explicit overrides",
                check.id(),
            );
        }
    }

    #[test]
    fn config_unresolved_warns_and_skips_downstream() {
        // The genuine "no config path source" case — discovery
        // WARNs (using built-in defaults is a normal first-run
        // state, not a failure); the four downstream checks SKIP
        // because there's nothing to load. This test pins the
        // Config-category-only behavior; `env.home_env` stays Set
        // so the Environment category's exit code doesn't bleed
        // into the assertion.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: None,
            read: ConfigReadOutcome::Unresolved,
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        let discovered = find_check(&r, "config.discovered");
        assert_eq!(discovered.severity(), Severity::Warn);
        assert!(
            discovered.label().contains("No config path resolved"),
            "label should describe the unresolved cascade: {}",
            discovered.label(),
        );
        for id in [
            "config.parses",
            "config.segments_resolvable",
            "config.theme_installed",
            "config.plugin_dirs_readable",
        ] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Skip,
                "{id} should SKIP when no config is loaded",
            );
        }
        assert_eq!(r.exit_code(), 0, "no config is WARN, not FAIL");
    }

    #[test]
    fn config_segments_pass_for_plugin_discovered_id() {
        // Without `known_segment_ids` carrying plugin ids, doctor
        // WARNs on every legitimate plugin segment — a real
        // false-negative for any plugin user. Snapshot-as-source-
        // of-truth means a plugin that compiles registers its id
        // and the check passes.
        let config = Config {
            line: Some(LineConfig {
                segments: vec!["my_plugin".into(), "model".into()],
                ..LineConfig::default()
            }),
            ..Config::default()
        };
        let mut snapshot = config_snapshot_loaded(config);
        snapshot.known_segment_ids.insert("my_plugin".to_string());
        let mut env = DoctorEnv::healthy();
        env.config = snapshot;
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.segments_resolvable").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn config_theme_pass_for_user_theme_in_registry() {
        // User-installed themes (loaded by `ThemeRegistry::with_user_themes`)
        // must not WARN. Snapshot the name, the check resolves it.
        let config = Config {
            theme: Some("neon".to_string()),
            ..Config::default()
        };
        let mut snapshot = config_snapshot_loaded(config);
        snapshot.known_theme_names.insert("neon".to_string());
        let mut env = DoctorEnv::healthy();
        env.config = snapshot;
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.theme_installed").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn config_segments_warn_on_line_zero_index() {
        // `[line.0]` is the boundary case `key.parse::<u32>()` would
        // accept but the hint ("must be a positive integer") rejects.
        // Use `NonZeroU32` so the zero key lands in the malformed
        // bucket, matching what the user reads.
        let raw = r#"
            [line]
            segments = ["model"]

            [line.0]
            segments = ["workspace"]
        "#;
        let parsed: Config = raw.parse().expect("parse ok");
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(parsed);
        let r = build_report(&env);
        let check = find_check(&r, "config.segments_resolvable");
        assert_eq!(
            check.severity(),
            Severity::Warn,
            "[line.0] must be flagged as malformed",
        );
        assert!(
            check.label().contains("[line.0]") && check.label().contains("positive integer"),
            "label must name the offending key and the constraint: {}",
            check.label(),
        );
    }

    #[test]
    fn config_discovered_warns_for_implicit_missing() {
        // First-run users have no config; spec §Config table maps
        // this to WARN ("none found, using built-in defaults"). FAIL
        // would gate `linesmith doctor` exit-1 behind an entirely
        // normal first-run state.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::NotFound {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.discovered").severity(),
            Severity::Warn,
        );
        assert_eq!(r.exit_code(), 0, "first-run WARN must not gate exit-1");
    }

    #[test]
    fn config_discovered_fails_for_explicit_missing() {
        // The user named --config /path/to/file. Falling back to
        // defaults silently — same WARN as the implicit case —
        // would mask the typo. FAIL with a hint pointed at the
        // exact path keeps the user pointed at the real fix.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: Some(PathBuf::from("/etc/linesmith/typo.toml")),
            resolved: Some(ConfigPath {
                path: PathBuf::from("/etc/linesmith/typo.toml"),
                explicit: true,
            }),
            read: ConfigReadOutcome::NotFound {
                path: PathBuf::from("/etc/linesmith/typo.toml"),
                explicit: true,
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        let discovered = find_check(&r, "config.discovered");
        assert_eq!(discovered.severity(), Severity::Fail);
        assert!(
            discovered.label().contains("/etc/linesmith/typo.toml"),
            "label must name the missing path: {}",
            discovered.label(),
        );
        assert_eq!(r.exit_code(), 1);
    }

    #[test]
    fn config_discovered_fails_on_io_error() {
        // Permission denied / is-a-directory / etc. is a real
        // problem — fall back to defaults silently and the user
        // never learns why their config doesn't apply.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::IoError {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                message: "Permission denied (os error 13)".to_string(),
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        let discovered = find_check(&r, "config.discovered");
        assert_eq!(discovered.severity(), Severity::Fail);
        assert!(
            discovered.label().contains("Permission denied"),
            "io::Error message must surface in label: {}",
            discovered.label(),
        );
    }

    #[test]
    fn config_parse_error_fails_with_line_col() {
        // Spec hint is "see line/column in the error for the invalid
        // key". toml::de::Error.to_string() already names line/col, so
        // surfacing it verbatim covers the contract; a reformat that
        // strips the message would silently break it.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::ParseError {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                message: "TOML parse error at line 3, column 7".to_string(),
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        let parses = find_check(&r, "config.parses");
        assert_eq!(parses.severity(), Severity::Fail);
        assert!(
            parses.hint().unwrap().contains("line 3, column 7"),
            "hint should carry the parser's line/col: {:?}",
            parses.hint(),
        );
    }

    #[test]
    fn config_parse_error_short_circuits_downstream_checks_to_skip() {
        // Spec §Cross-category short-circuits: parse fail → skip
        // segment / theme / plugin-dirs. Without this, doctor would
        // try to interpret a half-parsed config and surface
        // distracting / wrong WARNs alongside the real FAIL.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::ParseError {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                message: "broken".to_string(),
            },
            plugin_dirs: Vec::new(),
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        for id in [
            "config.segments_resolvable",
            "config.theme_installed",
            "config.plugin_dirs_readable",
        ] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Skip,
                "{id} must SKIP when parse fails",
            );
        }
    }

    #[test]
    fn config_segments_pass_when_every_id_is_a_known_built_in() {
        let config = Config {
            line: Some(LineConfig {
                segments: vec!["model".into(), "workspace".into(), "git_branch".into()],
                ..LineConfig::default()
            }),
            ..Config::default()
        };
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(config);
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.segments_resolvable").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn config_segments_warn_on_unknown_id_with_id_in_label() {
        let config = Config {
            line: Some(LineConfig {
                segments: vec!["model".into(), "not_a_real_segment".into()],
                ..LineConfig::default()
            }),
            ..Config::default()
        };
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(config);
        let r = build_report(&env);
        let check = find_check(&r, "config.segments_resolvable");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("not_a_real_segment"),
            "label must name the unknown id so the user can fix it: {}",
            check.label(),
        );
    }

    #[test]
    fn config_segments_warn_on_unknown_id_in_numbered_line_table() {
        // [line.1] / [line.2] segment ids must be validated too —
        // multi-line layouts hit the same plugin-id-typo problem
        // single-line does, and skipping them would create a doctor
        // blind spot for any user on multi-line.
        let raw = r#"
            [line]
            segments = ["model"]

            [line.1]
            segments = ["workspace", "bogus_id"]
        "#;
        let parsed: Config = raw.parse().expect("parse ok");
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(parsed);
        let r = build_report(&env);
        let check = find_check(&r, "config.segments_resolvable");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("bogus_id"),
            "label must name the unknown numbered-line id: {}",
            check.label(),
        );
    }

    #[test]
    fn config_segments_pass_on_inline_table_entries_in_numbered_line() {
        // Pin that the doctor's numbered-line check accepts inline-
        // table entries (`{ type = "separator" }`, `{ type =
        // "git_branch", merge = true }`) per ADR-0024. A regression
        // to "must be an array of strings" would surface a false
        // WARN for every multi-line config that adopts the mixed-
        // array shape.
        let raw = r#"
            layout = "multi-line"
            [line]

            [line.1]
            segments = [
                "model",
                { type = "separator", character = " | " },
                { type = "git_branch", merge = true },
            ]
        "#;
        let parsed: Config = raw.parse().expect("parse ok");
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(parsed);
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.segments_resolvable").severity(),
            Severity::Pass,
            "valid inline-table entries must not warn",
        );
    }

    #[test]
    fn config_segments_warn_on_kindless_inline_table_in_single_line() {
        // The single-line walk must classify inline-table entries
        // the same way the numbered-line walk does. Without it,
        // `[line] segments = [{ character = " | " }]` (kindless)
        // silently passes the check even though the runtime warns
        // and drops the entry — a misleading "all green" result
        // for a config the renderer rejects.
        let raw = r#"
            [line]
            segments = ["model", { character = " | " }]
        "#;
        let parsed: Config = raw.parse().expect("parse ok");
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(parsed);
        let r = build_report(&env);
        let check = find_check(&r, "config.segments_resolvable");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("`type`"),
            "label must mention the missing type field: {}",
            check.label(),
        );
    }

    #[test]
    fn config_segments_warn_on_kindless_inline_table_in_numbered_line() {
        // The flip side: a kindless inline table (`{ character = " | " }`
        // with no `type`) is malformed per ADR-0024 and the doctor
        // should surface it as a WARN, distinct from the unknown-id
        // case so the user gets a targeted hint about adding `type`.
        let raw = r#"
            layout = "multi-line"
            [line]

            [line.1]
            segments = ["model", { character = " | " }]
        "#;
        let parsed: Config = raw.parse().expect("parse ok");
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(parsed);
        let r = build_report(&env);
        let check = find_check(&r, "config.segments_resolvable");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("`type`"),
            "label must mention the missing type field: {}",
            check.label(),
        );
    }

    #[test]
    fn config_segments_warn_on_malformed_numbered_line_table() {
        // `[line.foo]` (non-integer key) and `[line.1] segments = "x"`
        // (non-array) are runtime-warning cases in the builder; doctor
        // surfaces them up-front so a user fixing config doesn't have
        // to spelunk through a debug log to find them.
        let raw = r#"
            [line]
            segments = ["model"]

            [line.foo]
            segments = ["workspace"]
        "#;
        let parsed: Config = raw.parse().expect("parse ok");
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(parsed);
        let r = build_report(&env);
        let check = find_check(&r, "config.segments_resolvable");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("foo"),
            "label must name the malformed line key: {}",
            check.label(),
        );
    }

    #[test]
    fn config_theme_pass_when_omitted_or_built_in() {
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(Config::default());
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.theme_installed").severity(),
            Severity::Pass,
        );

        // Pick a known built-in theme. `default` always exists; the
        // builtin_names() list defines the source of truth.
        let theme_name = crate::theme::builtin_names()
            .next()
            .expect("at least one built-in theme")
            .to_string();
        let config = Config {
            theme: Some(theme_name),
            ..Config::default()
        };
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(config);
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.theme_installed").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn config_theme_warn_on_unknown_name() {
        let config = Config {
            theme: Some("not-a-theme".to_string()),
            ..Config::default()
        };
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(config);
        let r = build_report(&env);
        let check = find_check(&r, "config.theme_installed");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("not-a-theme"),
            "label must name the unknown theme: {}",
            check.label(),
        );
    }

    #[test]
    fn config_plugin_dirs_pass_when_none_configured() {
        let mut env = DoctorEnv::healthy();
        env.config = config_snapshot_loaded(Config::default());
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.plugin_dirs_readable").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn config_plugin_dirs_warn_on_missing_or_not_directory() {
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::Loaded {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                config: Box::new(Config::default()),
            },
            plugin_dirs: vec![
                PluginDirStatus {
                    path: PathBuf::from("/etc/linesmith/plugins"),
                    state: PluginDirState::Missing,
                },
                PluginDirStatus {
                    path: PathBuf::from("/etc/linesmith/plugins.toml"),
                    state: PluginDirState::NotADirectory,
                },
            ],
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        let check = find_check(&r, "config.plugin_dirs_readable");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(check.label().contains("/etc/linesmith/plugins"));
        assert_eq!(r.exit_code(), 0, "missing dirs are WARN, not FAIL");
    }

    #[test]
    fn config_plugin_dirs_fail_on_permission_denied() {
        // Permission denied beats the WARN cases — the user can't
        // ignore it and a silent fallback would hide the cause of
        // missing plugin segments at runtime.
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::Loaded {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                config: Box::new(Config::default()),
            },
            plugin_dirs: vec![
                PluginDirStatus {
                    path: PathBuf::from("/root/secret-plugins"),
                    state: PluginDirState::PermissionDenied {
                        message: "permission denied".to_string(),
                    },
                },
                // A WARN-class entry alongside should not downgrade
                // the FAIL — prove FAIL beats WARN in the aggregator.
                PluginDirStatus {
                    path: PathBuf::from("/etc/missing"),
                    state: PluginDirState::Missing,
                },
            ],
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.plugin_dirs_readable").severity(),
            Severity::Fail,
        );
        assert_eq!(r.exit_code(), 1);
    }

    #[test]
    fn config_plugin_dirs_pass_when_all_ok() {
        let mut env = DoctorEnv::healthy();
        env.config = DoctorConfigSnapshot {
            cli_override: None,
            resolved: Some(ConfigPath {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                explicit: false,
            }),
            read: ConfigReadOutcome::Loaded {
                path: PathBuf::from("/home/user/.config/linesmith/config.toml"),
                config: Box::new(Config::default()),
            },
            plugin_dirs: vec![PluginDirStatus {
                path: PathBuf::from("/home/user/.config/linesmith/plugins"),
                state: PluginDirState::Ok,
            }],
            known_segment_ids: DoctorConfigSnapshot::built_in_segment_ids(),
            known_theme_names: DoctorConfigSnapshot::built_in_theme_names(),
        };
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "config.plugin_dirs_readable").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn read_config_at_round_trips_a_real_temp_file() {
        // Smoke for the production read+parse helper. A tempfile
        // here is the only way to assert the IoError vs ParseError
        // vs Loaded distinction without relying on a host config.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let valid = tempdir.path().join("valid.toml");
        std::fs::write(&valid, r#"theme = "default""#).expect("write");
        let cp = ConfigPath {
            path: valid.clone(),
            explicit: false,
        };
        match read_config_at(&cp) {
            ConfigReadOutcome::Loaded { config, path } => {
                assert_eq!(path, valid);
                assert_eq!(config.theme.as_deref(), Some("default"));
            }
            other => panic!("expected Loaded, got {other:?}"),
        }

        let parse_err = tempdir.path().join("invalid.toml");
        std::fs::write(&parse_err, "this = is not = valid toml").expect("write");
        let cp = ConfigPath {
            path: parse_err.clone(),
            explicit: false,
        };
        match read_config_at(&cp) {
            ConfigReadOutcome::ParseError { path, message } => {
                assert_eq!(path, parse_err);
                assert!(!message.is_empty(), "parse error message must be populated");
            }
            other => panic!("expected ParseError, got {other:?}"),
        }

        let missing = tempdir.path().join("nope.toml");
        let cp = ConfigPath {
            path: missing.clone(),
            explicit: true,
        };
        match read_config_at(&cp) {
            ConfigReadOutcome::NotFound { path, explicit } => {
                assert_eq!(path, missing);
                assert!(explicit, "explicit flag must propagate");
            }
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[test]
    fn stat_plugin_dirs_distinguishes_ok_missing_and_not_a_directory() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let dir = tempdir.path().join("dir");
        std::fs::create_dir(&dir).expect("mkdir");
        let file = tempdir.path().join("file");
        std::fs::write(&file, "").expect("touch");
        let missing = tempdir.path().join("nope");

        let statuses = stat_plugin_dirs(&[dir.clone(), file.clone(), missing.clone()]);
        assert_eq!(statuses.len(), 3);
        assert!(matches!(statuses[0].state, PluginDirState::Ok));
        assert!(matches!(statuses[1].state, PluginDirState::NotADirectory));
        assert!(matches!(statuses[2].state, PluginDirState::Missing));
    }

    // --- Claude Code category ---

    fn claude_home_state(
        dir: ClaudeDirState,
        claude_json: ClaudeJsonState,
        sessions: ClaudeSessionsState,
    ) -> ClaudeHomeState {
        ClaudeHomeState {
            dir,
            claude_json,
            sessions,
        }
    }

    fn with_claude_snapshot(snapshot: DoctorClaudeCodeSnapshot) -> DoctorEnv {
        let mut env = DoctorEnv::healthy();
        env.claude_code = snapshot;
        env
    }

    #[test]
    fn claude_code_category_emits_four_checks_in_spec_order() {
        // Spec §Claude Code table order: binary → dir → json →
        // sessions. Order matters because the dir-missing
        // short-circuit only triggers on the row above sessions.
        let r = build_report(&DoctorEnv::healthy());
        let ids: Vec<_> = r
            .categories
            .iter()
            .find(|c| c.name == "Claude Code")
            .expect("Claude Code category present")
            .checks
            .iter()
            .map(|c| c.id())
            .collect();
        assert_eq!(
            ids,
            vec![
                "claude.binary_found",
                "claude.dir",
                "claude.json_parses",
                "claude.sessions_recorded",
            ]
        );
    }

    #[test]
    fn claude_code_category_with_healthy_snapshot_passes_every_check() {
        let r = build_report(&DoctorEnv::healthy());
        let category = r
            .categories
            .iter()
            .find(|c| c.name == "Claude Code")
            .unwrap();
        for check in &category.checks {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "{} should PASS in healthy env, got {:?}",
                check.id(),
                check.severity(),
            );
        }
    }

    #[test]
    fn claude_code_category_skips_filesystem_checks_when_home_unresolved() {
        // Spec §Cross-category short-circuits: $HOME unresolved →
        // Claude Code SKIPs (no override sources for ~/.claude/).
        // The binary check still runs because $PATH resolution is
        // independent of $HOME.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: None,
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.binary_found").severity(),
            Severity::Pass
        );
        for id in [
            "claude.dir",
            "claude.json_parses",
            "claude.sessions_recorded",
        ] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Skip,
                "{id} should SKIP when $HOME unresolved",
            );
        }
    }

    #[test]
    fn claude_binary_warns_when_dir_exists_but_path_lookup_fails() {
        // Spec WARN row: "Not found, but `~/.claude/` exists
        // anyway." The user has used Claude Code before but the
        // launcher fell off `$PATH` (pkg manager glitch, env
        // wipe). FAIL would over-state the problem when the user's
        // state is recoverable without reinstalling.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::Set("/usr/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let binary = find_check(&r, "claude.binary_found");
        assert_eq!(binary.severity(), Severity::Warn);
        assert!(
            binary.label().contains("$PATH"),
            "label should mention $PATH so the user knows where to look: {}",
            binary.label(),
        );
    }

    #[test]
    fn claude_binary_fails_when_neither_binary_nor_dir_present() {
        // Spec FAIL row: "Neither binary nor `~/.claude/` present."
        // Claude Code was never installed, or both surfaces were
        // wiped — the right hint points at the install page.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::Set("/usr/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Missing,
                ClaudeJsonState::Missing,
                ClaudeSessionsState::Missing,
            )),
        });
        let r = build_report(&env);
        let binary = find_check(&r, "claude.binary_found");
        assert_eq!(binary.severity(), Severity::Fail);
        assert!(
            binary.hint().unwrap().contains("install Claude Code"),
            "hint should point at the install page: {:?}",
            binary.hint(),
        );
    }

    #[test]
    fn claude_dir_warns_on_permission_denied() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::PermissionDenied {
                    message: "Permission denied (os error 13)".to_string(),
                },
                ClaudeJsonState::Ok,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let dir = find_check(&r, "claude.dir");
        assert_eq!(dir.severity(), Severity::Warn);
        assert!(
            dir.label().contains("Permission denied"),
            "label should surface the os error: {}",
            dir.label(),
        );
    }

    #[test]
    fn claude_dir_missing_short_circuits_sessions_to_skip() {
        // Spec §Cross-category short-circuits: `~/.claude/` missing
        // → Recent sessions SKIP. Without this propagation, doctor
        // would emit a redundant FAIL on sessions for the same
        // root cause (no claude dir at all).
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::Set("/usr/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Missing,
                ClaudeJsonState::Missing,
                // Sessions state is Missing too in reality, but
                // the short-circuit should SKIP regardless of this
                // value — pin the gating logic explicitly.
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let sessions = find_check(&r, "claude.sessions_recorded");
        assert_eq!(sessions.severity(), Severity::Skip);
        assert!(
            sessions.hint().unwrap().contains("`~/.claude/` missing"),
            "skip reason should name the upstream cause: {:?}",
            sessions.hint(),
        );
    }

    #[test]
    fn claude_json_warn_when_oauth_account_missing() {
        // Spec WARN row: "JSON valid but `oauthAccount` missing".
        // The hint says regenerate via `claude` — the JSON is
        // structurally fine but the user isn't logged in.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::NoOauthAccount,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let json = find_check(&r, "claude.json_parses");
        assert_eq!(json.severity(), Severity::Warn);
        assert!(
            json.hint().unwrap().contains("oauthAccount")
                || json.hint().unwrap().contains("log in"),
            "hint should explain the oauth gap: {:?}",
            json.hint(),
        );
    }

    #[test]
    fn claude_json_fail_on_parse_error_carries_message() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::ParseError {
                    message: "expected `:` at line 4, column 12".to_string(),
                },
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let json = find_check(&r, "claude.json_parses");
        assert_eq!(json.severity(), Severity::Fail);
        assert!(
            json.hint().unwrap().contains("line 4, column 12"),
            "hint should carry the parser's line/col: {:?}",
            json.hint(),
        );
    }

    #[test]
    fn claude_json_fail_when_missing() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Missing,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.json_parses").severity(),
            Severity::Fail
        );
    }

    #[test]
    fn claude_sessions_warn_when_directory_empty() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::Empty,
            )),
        });
        let r = build_report(&env);
        let sessions = find_check(&r, "claude.sessions_recorded");
        assert_eq!(sessions.severity(), Severity::Warn);
    }

    #[test]
    fn claude_sessions_fail_when_directory_missing_but_dir_ok() {
        // The short-circuit only triggers when `~/.claude/` itself
        // is missing. Sessions can be missing while the parent dir
        // exists (user deleted just the sessions subdir).
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::Missing,
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.sessions_recorded").severity(),
            Severity::Fail,
        );
    }

    // --- Claude Code snapshot helpers ---

    /// Touch a runnable `claude` (or `claude.exe`) under `dir` and
    /// return the resulting path. On Unix, sets the executable bit
    /// — a 0644 file is now correctly ignored by `find_claude_binary`.
    fn touch_runnable_claude(dir: &Path) -> PathBuf {
        let exe_name = if cfg!(windows) {
            "claude.exe"
        } else {
            "claude"
        };
        let path = dir.join(exe_name);
        std::fs::write(&path, "").expect("touch claude");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&path).expect("metadata").permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&path, perms).expect("chmod");
        }
        path
    }

    #[test]
    fn find_claude_binary_returns_first_path_match() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let dir1 = tempdir.path().join("a");
        let dir2 = tempdir.path().join("b");
        std::fs::create_dir(&dir1).expect("mkdir a");
        std::fs::create_dir(&dir2).expect("mkdir b");
        // The binary lives in dir2 only; `find` should still
        // discover it by walking past dir1.
        let bin = touch_runnable_claude(&dir2);
        let path_var = std::env::join_paths([&dir1, &dir2])
            .expect("join_paths")
            .into_string()
            .expect("utf8");
        let found =
            find_claude_binary(Some(std::ffi::OsStr::new(&path_var))).expect("found claude");
        assert_eq!(found, bin);
    }

    #[test]
    #[cfg(unix)]
    fn find_claude_binary_skips_non_executable_file() {
        // Contract: a 0644 regular file named `claude` in $PATH is
        // not a runnable binary. Reporting PASS would greenlight a
        // stale placeholder; the user then sees `Permission denied`
        // from the shell with no doctor diagnostic.
        use std::os::unix::fs::PermissionsExt;
        let tempdir = tempfile::tempdir().expect("tempdir");
        let dir = tempdir.path().join("a");
        std::fs::create_dir(&dir).expect("mkdir");
        let stale = dir.join("claude");
        std::fs::write(&stale, "").expect("touch");
        // Verify the fixture is actually non-executable so a future
        // umask shift can't silently make this test vacuous.
        let mode = std::fs::metadata(&stale)
            .expect("metadata")
            .permissions()
            .mode();
        assert_eq!(
            mode & 0o111,
            0,
            "fixture must be non-executable; tempfile gave mode {mode:o}",
        );
        let path_var = dir.to_string_lossy().into_owned();
        assert!(
            find_claude_binary(Some(std::ffi::OsStr::new(&path_var))).is_none(),
            "non-executable file must not be reported as the claude binary",
        );
    }

    #[test]
    fn find_claude_binary_returns_none_when_path_unset() {
        assert!(find_claude_binary(None).is_none());
        // Empty PATH entries (which arise from shell expansions
        // like `:$NEWPATH`) should not be resolved as the
        // current working directory by accident.
        assert!(find_claude_binary(Some(std::ffi::OsStr::new(":"))).is_none());
    }

    #[test]
    fn snapshot_claude_home_classifies_real_filesystem_state() {
        // End-to-end smoke for the helper trio. Assembles a fake
        // ~/.claude/ with a valid claude.json + sessions and asserts
        // every state-classifier picks the right variant.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let home = tempdir.path();
        std::fs::create_dir(home.join(".claude")).expect("mkdir .claude");
        std::fs::create_dir(home.join(".claude").join("sessions")).expect("mkdir sessions");
        std::fs::write(
            home.join(".claude")
                .join("sessions")
                .join("session-1.jsonl"),
            "",
        )
        .expect("touch session");
        std::fs::write(
            home.join(".claude.json"),
            r#"{ "oauthAccount": { "accountUuid": "x" } }"#,
        )
        .expect("write claude.json");

        let snapshot = snapshot_claude_home(home);
        assert!(matches!(snapshot.dir, ClaudeDirState::Ok));
        assert!(matches!(snapshot.claude_json, ClaudeJsonState::Ok));
        assert!(matches!(
            snapshot.sessions,
            ClaudeSessionsState::HasFiles { count: 1 }
        ));
    }

    #[test]
    fn read_claude_json_distinguishes_missing_parse_error_and_no_oauth() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let missing = tempdir.path().join("nope.json");
        assert!(matches!(
            read_claude_json(&missing),
            ClaudeJsonState::Missing
        ));

        let bad = tempdir.path().join("bad.json");
        std::fs::write(&bad, "{ this is not json").expect("write bad");
        assert!(matches!(
            read_claude_json(&bad),
            ClaudeJsonState::ParseError { .. }
        ));

        let no_oauth = tempdir.path().join("no_oauth.json");
        std::fs::write(&no_oauth, r#"{ "other": 1 }"#).expect("write no_oauth");
        assert!(matches!(
            read_claude_json(&no_oauth),
            ClaudeJsonState::NoOauthAccount
        ));

        let ok = tempdir.path().join("ok.json");
        std::fs::write(&ok, r#"{ "oauthAccount": null }"#).expect("write ok");
        // `oauthAccount: null` still counts as "block present" per
        // the spec — the WARN row is for the *key* being absent.
        assert!(matches!(read_claude_json(&ok), ClaudeJsonState::Ok));
    }

    #[test]
    fn read_claude_json_parse_error_contains_real_serde_format() {
        // Pin the actual format produced by `serde_json::Error::Display`
        // so the spec hint ("see line/column in the error") survives a
        // serde_json upgrade. The original test asserted a hand-rolled
        // `"line N, column M"` string with a comma, but real
        // serde_json output is `"... at line N column M"` with no
        // comma — so the prior test was vacuously passing against a
        // fixture, not the live format.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("malformed.json");
        std::fs::write(&path, "{ unbalanced").expect("write");
        match read_claude_json(&path) {
            ClaudeJsonState::ParseError { message } => {
                assert!(
                    message.contains(" at line ") && message.contains(" column "),
                    "serde_json error format changed; refresh the substring assertion: {message}",
                );
            }
            other => panic!("expected ParseError, got {other:?}"),
        }
    }

    #[test]
    fn read_claude_json_returns_too_large_above_2mb_cap() {
        // Spec §Edge cases (`docs/specs/doctor.md:333`): "`~/.claude.json`
        // is a 500MB file (pathological) → Cap read at 2MB; FAIL with
        // 'file too large — likely corrupt'". The doctor must fail
        // fast on oversized files rather than burn memory + time
        // parsing them. Use a 2 MB + 1 byte file (smallest case
        // that crosses the cap) to keep the test cheap.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("huge.json");
        std::fs::write(&path, vec![b'x'; 2 * 1024 * 1024 + 1]).expect("write");
        match read_claude_json(&path) {
            ClaudeJsonState::TooLarge { actual_bytes } => {
                assert_eq!(actual_bytes, 2 * 1024 * 1024 + 1);
            }
            other => panic!("expected TooLarge, got {other:?}"),
        }
    }

    #[test]
    fn check_claude_json_too_large_renders_fail_with_corruption_hint() {
        let mut env = DoctorEnv::healthy();
        if let Some(home) = &mut env.claude_code.home_state {
            home.claude_json = ClaudeJsonState::TooLarge {
                actual_bytes: 500 * 1024 * 1024,
            };
        }
        let r = build_report(&env);
        let check = find_check(&r, "claude.json_parses");
        assert_eq!(check.severity(), Severity::Fail);
        assert!(
            check.label().contains("too large"),
            "label should name the cap violation: {}",
            check.label()
        );
        assert!(
            check
                .hint()
                .is_some_and(|h| h.contains("corrupt") && h.contains("claude")),
            "hint should point at corruption + remediation: {:?}",
            check.hint()
        );
    }

    #[test]
    fn stat_claude_sessions_counts_files_only_not_subdirs_or_dotfiles() {
        // Spec §Claude Code "Recent sessions recorded": "At least one file".
        // A populated-but-fileless dir (only subdirs and dotfile
        // junk like a stray `.DS_Store`) must not PASS.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let sessions = tempdir.path().join("sessions");
        std::fs::create_dir(&sessions).expect("mkdir sessions");
        std::fs::create_dir(sessions.join("archive")).expect("mkdir archive");
        // A real session file → counts toward the total.
        std::fs::write(sessions.join("session-1.jsonl"), "").expect("touch");
        match stat_claude_sessions(&sessions) {
            ClaudeSessionsState::HasFiles { count } => assert_eq!(
                count, 1,
                "subdir must not contribute to session count; got {count}",
            ),
            other => panic!("expected HasFiles, got {other:?}"),
        }
    }

    #[test]
    fn stat_claude_sessions_reports_empty_when_only_subdirs() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let sessions = tempdir.path().join("sessions");
        std::fs::create_dir(&sessions).expect("mkdir");
        std::fs::create_dir(sessions.join("staging")).expect("mkdir staging");
        assert!(matches!(
            stat_claude_sessions(&sessions),
            ClaudeSessionsState::Empty
        ));
    }

    #[test]
    fn stat_claude_sessions_reports_empty_when_only_dotfiles() {
        // `.DS_Store` is the canonical macOS Finder noise; `.gitkeep`
        // appears whenever someone version-controls an empty dir.
        // Counting either would falsely report "session(s) recorded"
        // when the user has never actually opened Claude Code.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let sessions = tempdir.path().join("sessions");
        std::fs::create_dir(&sessions).expect("mkdir");
        std::fs::write(sessions.join(".DS_Store"), "").expect("touch");
        std::fs::write(sessions.join(".gitkeep"), "").expect("touch");
        assert!(matches!(
            stat_claude_sessions(&sessions),
            ClaudeSessionsState::Empty
        ));
    }

    #[test]
    fn stat_claude_sessions_skips_dotfiles_but_counts_real_session_files() {
        // Mixed content: real session JSONLs alongside Finder junk.
        // The count should reflect only the genuine session files.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let sessions = tempdir.path().join("sessions");
        std::fs::create_dir(&sessions).expect("mkdir");
        std::fs::write(sessions.join(".DS_Store"), "").expect("touch");
        std::fs::write(sessions.join("session-1.jsonl"), "").expect("touch");
        std::fs::write(sessions.join("session-2.jsonl"), "").expect("touch");
        match stat_claude_sessions(&sessions) {
            ClaudeSessionsState::HasFiles { count } => assert_eq!(count, 2),
            other => panic!("expected HasFiles {{ count: 2 }}, got {other:?}"),
        }
    }

    // --- Cross-category gating + PATH-broken hint ---

    #[test]
    fn claude_binary_warns_when_dir_permission_denied() {
        // Pin the WARN-vs-FAIL boundary at the dir_present predicate
        // — `PermissionDenied` counts as "the dir is there, we just
        // can't peek." A regression that drops `PermissionDenied`
        // from the predicate would silently flip this from WARN to
        // FAIL on a real user surface.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::PermissionDenied {
                    message: "Permission denied (os error 13)".to_string(),
                },
                ClaudeJsonState::Ok,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.binary_found").severity(),
            Severity::Warn
        );
    }

    #[test]
    fn claude_binary_warns_when_dir_not_a_directory() {
        // `~/.claude` exists as a *file* — Claude Code state was
        // corrupted, but the user is recoverable (delete the file +
        // launch claude). Reporting "neither present" → install
        // hint would be misleading.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::NotADirectory,
                ClaudeJsonState::Missing,
                ClaudeSessionsState::Missing,
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.binary_found").severity(),
            Severity::Warn
        );
    }

    #[test]
    fn claude_binary_fail_with_path_unset_hint_when_path_env_unset() {
        // `$PATH` itself is the problem. Reporting "install Claude
        // Code from https://claude.ai/code" would be wrong remediation
        // — the user has Claude Code installed; their shell init
        // wiped PATH.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::Unset,
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let binary = find_check(&r, "claude.binary_found");
        assert_eq!(binary.severity(), Severity::Fail);
        assert!(
            binary.label().contains("$PATH is unset"),
            "label should name the PATH problem class: {}",
            binary.label(),
        );
        assert!(
            binary.hint().unwrap().contains("$PATH"),
            "hint should redirect the user to fix PATH: {:?}",
            binary.hint(),
        );
    }

    #[test]
    fn claude_binary_fail_with_path_nonutf8_hint() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: None,
            path_env: EnvVarState::non_utf8_for_test("/usr/bin\u{FFFD}"),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let binary = find_check(&r, "claude.binary_found");
        assert_eq!(binary.severity(), Severity::Fail);
        assert!(
            binary.label().contains("UTF-8"),
            "label should name UTF-8 as the failure class: {}",
            binary.label(),
        );
    }

    // --- Missing severity branches per pr-test-analyzer ---

    #[test]
    fn claude_dir_warns_on_not_a_directory() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::NotADirectory,
                ClaudeJsonState::Missing,
                ClaudeSessionsState::Missing,
            )),
        });
        let r = build_report(&env);
        assert_eq!(find_check(&r, "claude.dir").severity(), Severity::Warn);
    }

    #[test]
    fn claude_dir_warns_on_other_io() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::OtherIo {
                    message: "ELOOP".to_string(),
                },
                ClaudeJsonState::Missing,
                ClaudeSessionsState::Missing,
            )),
        });
        let r = build_report(&env);
        assert_eq!(find_check(&r, "claude.dir").severity(), Severity::Warn);
    }

    #[test]
    fn claude_json_fail_on_io_error() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::IoError {
                    message: "Permission denied (os error 13)".to_string(),
                },
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        let json = find_check(&r, "claude.json_parses");
        assert_eq!(json.severity(), Severity::Fail);
        assert!(
            json.label().contains("Permission denied"),
            "label should surface the io::Error message: {}",
            json.label(),
        );
    }

    #[test]
    fn claude_sessions_warn_on_not_a_directory() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::NotADirectory,
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.sessions_recorded").severity(),
            Severity::Warn,
        );
    }

    #[test]
    fn claude_sessions_warn_on_io_error() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::Ok,
                ClaudeJsonState::Ok,
                ClaudeSessionsState::IoError {
                    message: "EIO".to_string(),
                },
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.sessions_recorded").severity(),
            Severity::Warn,
        );
    }

    #[test]
    fn claude_sessions_skips_when_dir_permission_denied() {
        // Cross-category gate widening: PermissionDenied on the
        // parent dir means `read_dir` of sessions/ would also fail
        // — surfacing both errors is redundant and points at the
        // same root cause. The dir check carries the right hint;
        // sessions just SKIPs.
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::PermissionDenied {
                    message: "Permission denied".to_string(),
                },
                ClaudeJsonState::Ok,
                ClaudeSessionsState::HasFiles { count: 99 },
            )),
        });
        let r = build_report(&env);
        let sessions = find_check(&r, "claude.sessions_recorded");
        assert_eq!(sessions.severity(), Severity::Skip);
        assert!(
            sessions.hint().unwrap().contains("unreadable"),
            "skip reason should match the parent dir state: {:?}",
            sessions.hint(),
        );
    }

    #[test]
    fn claude_sessions_skips_when_dir_not_a_directory() {
        let env = with_claude_snapshot(DoctorClaudeCodeSnapshot {
            binary_path: Some(PathBuf::from("/usr/local/bin/claude")),
            path_env: EnvVarState::Set("/usr/local/bin".to_string()),
            home_state: Some(claude_home_state(
                ClaudeDirState::NotADirectory,
                ClaudeJsonState::Missing,
                ClaudeSessionsState::HasFiles { count: 1 },
            )),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "claude.sessions_recorded").severity(),
            Severity::Skip,
        );
    }

    // --- Credentials category ---

    use crate::data_context::credentials::CredentialSource;

    fn with_credentials(snapshot: DoctorCredentialsSnapshot) -> DoctorEnv {
        let mut env = DoctorEnv::healthy();
        env.credentials = snapshot;
        env
    }

    #[test]
    fn credentials_category_with_resolved_credentials_passes_all_four() {
        let r = build_report(&DoctorEnv::healthy());
        let category = r
            .categories
            .iter()
            .find(|c| c.name == "Credentials")
            .expect("Credentials category present");
        for check in &category.checks {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "{} should PASS in healthy env, got {:?}",
                check.id(),
                check.severity(),
            );
        }
    }

    #[test]
    fn credentials_no_credentials_fails_resolvable_and_source() {
        let env = with_credentials(DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::NoCredentials,
        ));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "creds.token_resolvable").severity(),
            Severity::Fail,
        );
        assert_eq!(
            find_check(&r, "creds.source_attested").severity(),
            Severity::Fail,
        );
        // Shape and scopes can't be evaluated without a token —
        // they SKIP rather than double-FAIL.
        assert_eq!(
            find_check(&r, "creds.token_shape_valid").severity(),
            Severity::Skip,
        );
        assert_eq!(
            find_check(&r, "creds.scopes_present").severity(),
            Severity::Skip,
        );
    }

    #[test]
    fn credentials_parse_error_passes_source_fails_shape() {
        // ParseError carries the cascade-winner path → source IS
        // identifiable even though the file is unusable. The shape
        // check is the right place for the FAIL.
        let env = with_credentials(DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::ParseError {
                path: PathBuf::from("/home/user/.claude/.credentials.json"),
            },
        ));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "creds.token_resolvable").severity(),
            Severity::Fail,
        );
        assert_eq!(
            find_check(&r, "creds.source_attested").severity(),
            Severity::Pass,
        );
        assert_eq!(
            find_check(&r, "creds.token_shape_valid").severity(),
            Severity::Fail,
        );
    }

    #[test]
    fn credentials_scopes_fail_when_user_inference_absent() {
        let env = with_credentials(DoctorCredentialsSnapshot::Resolved(CredentialsSummary {
            source: CredentialSource::ClaudeLegacy {
                path: PathBuf::from("/home/user/.claude/.credentials.json"),
            },
            // No `user:inference` — the spec FAIL row.
            scopes: vec!["user:profile".to_string()],
        }));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "creds.scopes_present").severity(),
            Severity::Fail,
        );
    }

    #[test]
    fn credentials_unresolvable_skips_all_four() {
        let env = with_credentials(DoctorCredentialsSnapshot::Unresolvable);
        let r = build_report(&env);
        for id in [
            "creds.token_resolvable",
            "creds.source_attested",
            "creds.token_shape_valid",
            "creds.scopes_present",
        ] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Skip,
                "{id} should SKIP when cascade unresolvable",
            );
        }
    }

    #[test]
    fn credentials_source_attested_label_redacts_token_bytes() {
        // Pin the redaction contract: the source label includes a
        // path / service description but never the bearer token.
        // A future refactor that surfaces `Credentials::token` here
        // would silently leak.
        let label = source_label(&CredentialSource::ClaudeLegacy {
            path: PathBuf::from("/some/file"),
        });
        assert!(
            !label.contains("Bearer ") && !label.contains("eyJ"),
            "source label must never contain bearer-token shapes: {label}",
        );
    }

    // --- Cache category ---

    fn with_cache(snapshot: DoctorCacheSnapshot) -> DoctorEnv {
        let mut env = DoctorEnv::healthy();
        env.cache = snapshot;
        env
    }

    #[test]
    fn cache_category_with_healthy_snapshot_passes_all_three() {
        let r = build_report(&DoctorEnv::healthy());
        let category = r.categories.iter().find(|c| c.name == "Cache").unwrap();
        for check in &category.checks {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "{} should PASS in healthy env, got {:?}",
                check.id(),
                check.severity(),
            );
        }
    }

    #[test]
    fn cache_dir_passes_when_absent_with_creatable_hint() {
        // Doctor stat-only, no probe-write. Expected first-run
        // case: directory doesn't exist yet AND first existing
        // ancestor is writable. PASS with a hint that the runtime
        // will create it. If the ancestor is read-only, that's a
        // separate `AbsentParentReadOnly` WARN — see
        // `cache_dir_warns_when_absent_parent_read_only`.
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Absent,
            usage_json: UsageJsonState::Missing,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let dir = find_check(&r, "cache.dir_writable");
        assert_eq!(dir.severity(), Severity::Pass);
        assert!(
            dir.label().contains("will be created"),
            "label should explain the creatable state: {}",
            dir.label(),
        );
        // Guard against a revert that re-introduces the old
        // probe-write "parent writable" phrasing without the
        // current "will be created" semantics.
        assert!(
            !dir.label().contains("parent writable"),
            "label should not carry the old probe-write phrasing: {}",
            dir.label(),
        );
        assert_eq!(r.exit_code(), 0, "Absent must not gate exit-1");
    }

    #[test]
    fn cache_dir_warns_when_absent_parent_read_only() {
        // Invariant: an Absent cache root under a permanently
        // non-creatable parent (read-only mount, /proc, unwritable
        // XDG_CACHE_HOME) must WARN, not silently PASS. A failed
        // first-fetch leaves the path Absent so neither usage.json
        // nor usage.lock rows catch it on the next run; the
        // AbsentParentReadOnly variant carries the only signal the
        // user gets from doctor for this misconfig.
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/proc/cache/linesmith")),
            root: CacheRootState::AbsentParentReadOnly {
                parent: PathBuf::from("/proc"),
            },
            usage_json: UsageJsonState::Missing,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let dir = find_check(&r, "cache.dir_writable");
        assert_eq!(dir.severity(), Severity::Warn);
        assert!(
            dir.label().contains("Cache dir cannot be created"),
            "label should name the failure mode: {}",
            dir.label()
        );
        assert!(
            dir.label().contains("/proc"),
            "label should name the read-only ancestor: {}",
            dir.label()
        );
        assert!(
            dir.hint().is_some_and(|h| h.contains("XDG_CACHE_HOME")),
            "hint should point at the env var to fix: {:?}",
            dir.hint()
        );
        assert_eq!(r.exit_code(), 0, "AbsentParentReadOnly is WARN, not FAIL");
    }

    #[test]
    fn stat_cache_root_returns_exists_for_a_real_directory() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        match stat_cache_root(tempdir.path()) {
            CacheRootState::Exists => {}
            other => panic!("expected Exists for real directory, got {other:?}"),
        }
    }

    #[test]
    fn stat_cache_root_returns_not_a_directory_when_path_is_a_file() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let file = tempdir.path().join("cache");
        std::fs::write(&file, b"not a dir").expect("write");
        match stat_cache_root(&file) {
            CacheRootState::NotADirectory => {}
            other => panic!("expected NotADirectory for a regular file, got {other:?}"),
        }
    }

    #[test]
    fn stat_cache_root_returns_absent_parent_read_only_when_intermediate_is_a_file() {
        // The classify_absent_cache_root walk handles three cases on
        // top of the writable-directory PASS: readonly directory,
        // file-in-the-middle, and PermissionDenied during walk.
        // Pin the file-in-the-middle case directly: stat
        // `tempdir/middle/sub/cache` where `tempdir/middle` is a
        // regular file. The walk should land on `tempdir/middle`
        // and return AbsentParentReadOnly with that path.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let middle = tempdir.path().join("middle");
        std::fs::write(&middle, b"file in the middle of the chain").expect("write");
        let cache = middle.join("sub").join("cache");
        match stat_cache_root(&cache) {
            CacheRootState::AbsentParentReadOnly { parent } => {
                assert_eq!(
                    parent, middle,
                    "parent should point at the file blocking the chain"
                );
            }
            other => panic!("expected AbsentParentReadOnly with file ancestor, got {other:?}"),
        }
    }

    #[test]
    fn stat_cache_root_returns_absent_when_path_missing_under_writable_parent() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let missing = tempdir.path().join("cache").join("linesmith");
        match stat_cache_root(&missing) {
            // Tempdirs default to 0700 — writable by the user, so the
            // parent walk lands in `Absent`, not `AbsentParentReadOnly`.
            CacheRootState::Absent => {}
            other => {
                panic!("expected Absent for missing path under writable parent, got {other:?}")
            }
        }
    }

    #[test]
    fn cache_dir_check_never_produces_fail_severity_for_any_variant() {
        // Spec contract guard: the cache.dir_writable row has no
        // FAIL column (see §Cache row "Cache dir exists or
        // creatable"). A future patch that re-introduces FAIL on
        // any CacheRootState variant must fail this test. Drives
        // every variant through build_report and asserts no Fail
        // surfaces — including the Unresolved/SKIP path.
        //
        // The exhaustive `match` below makes a 6th variant a
        // compile error here, forcing a corresponding addition
        // to the iterated list — without it, a new variant
        // could silently slip past this guard and re-introduce
        // FAIL semantics undetected.
        fn _exhaustiveness_tripwire(v: &CacheRootState) {
            match v {
                CacheRootState::Exists
                | CacheRootState::Absent
                | CacheRootState::AbsentParentReadOnly { .. }
                | CacheRootState::NotADirectory
                | CacheRootState::Unreadable { .. }
                | CacheRootState::Unresolved => {}
            }
        }
        let path = Some(PathBuf::from("/home/user/.cache/linesmith"));
        let variants: [(&'static str, CacheRootState); 5] = [
            ("Exists", CacheRootState::Exists),
            ("Absent", CacheRootState::Absent),
            (
                "AbsentParentReadOnly",
                CacheRootState::AbsentParentReadOnly {
                    parent: PathBuf::from("/proc"),
                },
            ),
            ("NotADirectory", CacheRootState::NotADirectory),
            (
                "Unreadable",
                CacheRootState::Unreadable {
                    message: "Permission denied".to_string(),
                },
            ),
        ];
        for (name, root) in variants {
            let env = with_cache(DoctorCacheSnapshot {
                root_path: path.clone(),
                root,
                usage_json: UsageJsonState::Missing,
                lock: LockState::Absent,
            });
            let r = build_report(&env);
            let dir = find_check(&r, "cache.dir_writable");
            assert_ne!(
                dir.severity(),
                Severity::Fail,
                "{name} variant must not produce FAIL on cache.dir_writable",
            );
        }
        // Unresolved (no path) variant rendered through SKIP.
        let env = with_cache(DoctorCacheSnapshot {
            root_path: None,
            root: CacheRootState::Unresolved,
            usage_json: UsageJsonState::Missing,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let dir = find_check(&r, "cache.dir_writable");
        assert_ne!(
            dir.severity(),
            Severity::Fail,
            "Unresolved variant must not produce FAIL"
        );
    }

    #[test]
    fn cache_dir_warns_when_path_is_a_file_not_a_directory() {
        // Real read-only-detectable misconfiguration: a stale leftover
        // where the user has `~/.cache/linesmith` as a file. Runtime
        // would fail to use it, so WARN preemptively.
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::NotADirectory,
            usage_json: UsageJsonState::Missing,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let dir = find_check(&r, "cache.dir_writable");
        assert_eq!(dir.severity(), Severity::Warn);
        assert!(
            dir.hint().is_some_and(|h| h.contains("remove")),
            "hint should suggest removal: {:?}",
            dir.hint()
        );
        assert_eq!(r.exit_code(), 0, "NotADirectory is WARN, not FAIL");
    }

    #[test]
    fn cache_dir_warns_when_unreadable_with_io_message() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Unreadable {
                message: "Permission denied (os error 13)".to_string(),
            },
            usage_json: UsageJsonState::Missing,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let dir = find_check(&r, "cache.dir_writable");
        assert_eq!(dir.severity(), Severity::Warn);
        assert!(
            dir.label().contains("Cache dir unreadable"),
            "label should carry the spec-required prefix: {}",
            dir.label()
        );
        assert!(
            dir.label().contains("Permission denied"),
            "label should surface the io::Error message: {}",
            dir.label()
        );
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn cache_skips_all_three_when_unresolved() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: None,
            root: CacheRootState::Unresolved,
            usage_json: UsageJsonState::Missing,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        for id in [
            "cache.dir_writable",
            "cache.usage_json_shape",
            "cache.lock_fresh",
        ] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Skip,
                "{id} should SKIP when cache root unresolved",
            );
        }
    }

    #[test]
    fn cache_usage_json_warns_on_stale_schema() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Exists,
            usage_json: UsageJsonState::Stale { schema_version: 0 },
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let usage = find_check(&r, "cache.usage_json_shape");
        assert_eq!(usage.severity(), Severity::Warn);
        assert!(
            usage.hint().unwrap().contains("safe to ignore"),
            "hint should reassure that stale cache self-heals: {:?}",
            usage.hint(),
        );
    }

    #[test]
    fn cache_lock_warns_when_stale() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Exists,
            usage_json: UsageJsonState::Missing,
            lock: LockState::Stale {
                blocked_until_secs: 1,
            },
        });
        let r = build_report(&env);
        let lock = find_check(&r, "cache.lock_fresh");
        assert_eq!(lock.severity(), Severity::Warn);
        assert!(
            lock.hint().unwrap().contains("rm"),
            "hint should tell user how to clear: {:?}",
            lock.hint(),
        );
    }

    #[test]
    fn cache_lock_active_passes() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Exists,
            usage_json: UsageJsonState::Missing,
            // Far-future timestamp so the test doesn't break in 50
            // years.
            lock: LockState::Active {
                blocked_until_secs: i64::MAX,
            },
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "cache.lock_fresh").severity(),
            Severity::Pass
        );
    }

    // --- Rate-limit endpoint category ---

    fn with_endpoint(snapshot: DoctorEndpointSnapshot) -> DoctorEnv {
        let mut env = DoctorEnv::healthy();
        env.endpoint = snapshot;
        env
    }

    fn endpoint_probe(outcome: EndpointProbeOutcome, elapsed_ms: u128) -> DoctorEndpointSnapshot {
        DoctorEndpointSnapshot {
            credentials_vanished: false,
            probe: Some(EndpointProbe {
                elapsed_ms,
                outcome,
            }),
        }
    }

    #[test]
    fn endpoint_category_with_healthy_probe_passes_all_three() {
        let r = build_report(&DoctorEnv::healthy());
        let category = r
            .categories
            .iter()
            .find(|c| c.name == "Rate-limit endpoint")
            .unwrap();
        for check in &category.checks {
            assert_eq!(
                check.severity(),
                Severity::Pass,
                "{} should PASS in healthy env",
                check.id(),
            );
        }
    }

    #[test]
    fn endpoint_skips_when_credentials_failed() {
        // Spec §Cross-category: missing token → endpoint SKIP.
        // The skip-reason should reflect the credentials failure,
        // not "endpoint not reachable".
        let mut env = DoctorEnv::healthy();
        env.credentials = DoctorCredentialsSnapshot::Failed(CredentialErrorSummary::NoCredentials);
        env.endpoint = DoctorEndpointSnapshot {
            probe: None,
            credentials_vanished: false,
        };
        let r = build_report(&env);
        for id in [
            "endpoint.reachable",
            "endpoint.shape_current",
            "endpoint.headers_sane",
        ] {
            let check = find_check(&r, id);
            assert_eq!(check.severity(), Severity::Skip, "{id} should SKIP");
            assert!(
                check.hint().unwrap().contains("token"),
                "skip reason should name the missing token: {:?}",
                check.hint(),
            );
        }
    }

    #[test]
    fn endpoint_transport_error_warns_keeps_exit_zero() {
        // Spec §Rate-limit endpoint: transport-level errors are
        // WARN, not FAIL. CI runs without network egress must NOT
        // exit-1.
        let env = with_endpoint(endpoint_probe(EndpointProbeOutcome::TransportError, 250));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "endpoint.reachable").severity(),
            Severity::Warn,
        );
        assert_eq!(r.exit_code(), 0, "transport error must not gate exit-1");
    }

    #[test]
    fn endpoint_bad_status_fails_with_per_status_hint() {
        let env = with_endpoint(endpoint_probe(
            EndpointProbeOutcome::BadStatus { status: 401 },
            150,
        ));
        let r = build_report(&env);
        let reachable = find_check(&r, "endpoint.reachable");
        assert_eq!(reachable.severity(), Severity::Fail);
        assert!(
            reachable.hint().unwrap().contains("log in"),
            "401 should hint at re-login: {:?}",
            reachable.hint(),
        );
    }

    #[test]
    fn endpoint_slow_response_warns_with_elapsed() {
        let env = with_endpoint(endpoint_probe(EndpointProbeOutcome::Slow, 2500));
        let r = build_report(&env);
        let reachable = find_check(&r, "endpoint.reachable");
        assert_eq!(reachable.severity(), Severity::Warn);
        assert!(
            reachable.label().contains("2500ms"),
            "label should report elapsed time: {}",
            reachable.label(),
        );
    }

    #[test]
    fn endpoint_unexpected_shape_warns_with_extra_keys() {
        let env = with_endpoint(endpoint_probe(
            EndpointProbeOutcome::UnexpectedShape {
                extra_keys: vec!["omelette_5h".into(), "iguana_7d".into()],
            },
            300,
        ));
        let r = build_report(&env);
        let shape = find_check(&r, "endpoint.shape_current");
        assert_eq!(shape.severity(), Severity::Warn);
        assert!(
            shape.label().contains("omelette_5h") && shape.label().contains("iguana_7d"),
            "label should name the forward-compat keys: {}",
            shape.label(),
        );
    }

    #[test]
    fn endpoint_parse_error_fails_shape_check() {
        let env = with_endpoint(endpoint_probe(EndpointProbeOutcome::ParseError, 400));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "endpoint.shape_current").severity(),
            Severity::Fail,
        );
    }

    #[test]
    fn endpoint_rate_limited_warns_with_reasonable_retry_after() {
        let env = with_endpoint(endpoint_probe(
            EndpointProbeOutcome::RateLimited {
                retry_after_secs: Some(60),
            },
            200,
        ));
        let r = build_report(&env);
        let headers = find_check(&r, "endpoint.headers_sane");
        assert_eq!(headers.severity(), Severity::Warn);
    }

    #[test]
    fn endpoint_rate_limited_fails_on_abusive_retry_after() {
        // >1 hour Retry-After per spec FAIL row.
        let env = with_endpoint(endpoint_probe(
            EndpointProbeOutcome::RateLimited {
                retry_after_secs: Some(3601),
            },
            200,
        ));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "endpoint.headers_sane").severity(),
            Severity::Fail,
        );
    }

    // --- Snapshot helper smoke tests ---

    #[test]
    fn classify_endpoint_response_maps_2xx_with_extra_keys_to_unexpected_shape() {
        use crate::data_context::fetcher::HttpResponse;
        let body = br#"{"five_hour":null,"omelette_extra":{"x":1}}"#;
        let resp = HttpResponse {
            status: 200,
            body: body.to_vec(),
            retry_after: None,
        };
        let outcome = classify_endpoint_response(Ok(resp), std::time::Duration::from_millis(300));
        assert!(
            matches!(outcome, EndpointProbeOutcome::UnexpectedShape { ref extra_keys } if extra_keys == &vec!["omelette_extra".to_string()]),
            "expected UnexpectedShape, got {outcome:?}",
        );
    }

    #[test]
    fn classify_endpoint_response_maps_401_to_bad_status() {
        use crate::data_context::fetcher::HttpResponse;
        let resp = HttpResponse {
            status: 401,
            body: vec![],
            retry_after: None,
        };
        let outcome = classify_endpoint_response(Ok(resp), std::time::Duration::from_millis(50));
        assert!(matches!(
            outcome,
            EndpointProbeOutcome::BadStatus { status: 401 }
        ));
    }

    #[test]
    fn classify_endpoint_response_maps_io_error_to_transport_error() {
        let outcome = classify_endpoint_response(
            Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "read timeout",
            )),
            std::time::Duration::from_secs(2),
        );
        assert!(matches!(outcome, EndpointProbeOutcome::TransportError));
    }

    #[test]
    fn classify_endpoint_response_maps_5xx_to_transport_error() {
        // Spec §Rate-limit endpoint reserves FAIL for "4xx other than 429".
        // 5xx is the upstream broken (Anthropic outage); a doctor
        // run during an incident must not exit-1.
        use crate::data_context::fetcher::HttpResponse;
        for status in [500u16, 502, 503, 504] {
            let resp = HttpResponse {
                status,
                body: vec![],
                retry_after: None,
            };
            let outcome =
                classify_endpoint_response(Ok(resp), std::time::Duration::from_millis(50));
            assert!(
                matches!(outcome, EndpointProbeOutcome::TransportError),
                "{status} should map to TransportError, got {outcome:?}",
            );
        }
    }

    #[test]
    fn classify_endpoint_response_maps_3xx_to_transport_error() {
        // ureq follows redirects; a 3xx leaking here means redirect
        // handling exhausted or disabled — same user-actionability
        // as a transport error.
        use crate::data_context::fetcher::HttpResponse;
        let resp = HttpResponse {
            status: 301,
            body: vec![],
            retry_after: None,
        };
        let outcome = classify_endpoint_response(Ok(resp), std::time::Duration::from_millis(50));
        assert!(matches!(outcome, EndpointProbeOutcome::TransportError));
    }

    #[test]
    fn classify_endpoint_response_at_2s_boundary_classifies_as_slow() {
        // Pin the spec's WARN threshold so a `>` vs `>=` swap or a
        // ms/s unit drift in `classify_endpoint_response` would
        // surface as a test failure. Read from `DOCTOR_SLOW_THRESHOLD`
        // (not a literal) so the test follows the constant if it ever
        // moves — and so a regression that re-points the classifier
        // at `DEFAULT_TIMEOUT` (the request budget, which doctor
        // intentionally splits from the user-facing slow signal)
        // doesn't silently still pass.
        use crate::data_context::fetcher::HttpResponse;
        let threshold = DOCTOR_SLOW_THRESHOLD;
        let just_under = threshold - std::time::Duration::from_millis(1);
        let body = br#"{}"#;
        let resp = HttpResponse {
            status: 200,
            body: body.to_vec(),
            retry_after: None,
        };
        assert!(matches!(
            classify_endpoint_response(Ok(resp), just_under),
            EndpointProbeOutcome::Ok
        ));
        let resp = HttpResponse {
            status: 200,
            body: body.to_vec(),
            retry_after: None,
        };
        assert!(matches!(
            classify_endpoint_response(Ok(resp), threshold),
            EndpointProbeOutcome::Slow
        ));
    }

    #[test]
    fn endpoint_5xx_warns_keeps_exit_zero() {
        // End-to-end: an Anthropic 503 must not gate exit-1 in CI.
        use crate::data_context::fetcher::HttpResponse;
        let resp = HttpResponse {
            status: 503,
            body: vec![],
            retry_after: None,
        };
        let outcome = classify_endpoint_response(Ok(resp), std::time::Duration::from_millis(100));
        let env = with_endpoint(DoctorEndpointSnapshot {
            credentials_vanished: false,
            probe: Some(EndpointProbe {
                elapsed_ms: 100,
                outcome,
            }),
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "endpoint.reachable").severity(),
            Severity::Warn,
            "5xx must be WARN per spec §Rate-limit endpoint",
        );
        assert_eq!(r.exit_code(), 0, "Anthropic incident must not gate exit-1");
    }

    #[test]
    fn endpoint_rate_limited_warns_when_no_retry_after_header() {
        // Pin the distinct WARN branch ("429 without Retry-After
        // header") so a refactor that collapses the None arm into
        // the abusive-Some arm flips the user-visible severity.
        let env = with_endpoint(endpoint_probe(
            EndpointProbeOutcome::RateLimited {
                retry_after_secs: None,
            },
            200,
        ));
        let r = build_report(&env);
        let headers = find_check(&r, "endpoint.headers_sane");
        assert_eq!(headers.severity(), Severity::Warn);
        assert!(
            headers.label().contains("without"),
            "label should distinguish the missing-header case: {}",
            headers.label(),
        );
    }

    // --- Credential-error branch coverage ---

    #[test]
    fn credentials_subprocess_failed_fails_resolvable_and_source() {
        // Spec §Credentials explicitly cites SubprocessFailed as a FAIL
        // trigger for `creds.token_resolvable`. macOS keychain
        // locked / `security` binary missing falls here.
        let env = with_credentials(DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::SubprocessFailed {
                message: "security: SecKeychainSearchCopyNext: locked".to_string(),
            },
        ));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "creds.token_resolvable").severity(),
            Severity::Fail,
        );
        assert_eq!(
            find_check(&r, "creds.source_attested").severity(),
            Severity::Fail,
        );
    }

    #[test]
    fn credentials_io_error_fails_resolvable_passes_source_attested() {
        // IoError carries the cascade-winner path (e.g.,
        // `chmod 000 ~/.claude/.credentials.json`) — the source
        // IS identifiable, the file is just unreadable. Same
        // shape as ParseError. The resolvable check carries the
        // FAIL; source PASSes with the path so the user sees
        // exactly which file to fix.
        let env = with_credentials(DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::IoError {
                path: PathBuf::from("/home/user/.claude/.credentials.json"),
                message: "Permission denied (os error 13)".to_string(),
            },
        ));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "creds.token_resolvable").severity(),
            Severity::Fail,
        );
        let source = find_check(&r, "creds.source_attested");
        assert_eq!(source.severity(), Severity::Pass);
        assert!(
            source
                .label()
                .contains("/home/user/.claude/.credentials.json"),
            "source label should name the file that failed: {}",
            source.label(),
        );
    }

    #[test]
    fn credentials_missing_field_renders_distinct_label() {
        let env = with_credentials(DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::MissingField {
                path: PathBuf::from("/home/user/.claude/.credentials.json"),
            },
        ));
        let r = build_report(&env);
        let shape = find_check(&r, "creds.token_shape_valid");
        assert_eq!(shape.severity(), Severity::Fail);
        assert!(
            shape.label().contains("claudeAiOauth"),
            "MissingField label should name the missing block: {}",
            shape.label(),
        );
    }

    #[test]
    fn credentials_empty_token_renders_distinct_label() {
        let env = with_credentials(DoctorCredentialsSnapshot::Failed(
            CredentialErrorSummary::EmptyToken {
                path: PathBuf::from("/home/user/.claude/.credentials.json"),
            },
        ));
        let r = build_report(&env);
        let shape = find_check(&r, "creds.token_shape_valid");
        assert_eq!(shape.severity(), Severity::Fail);
        assert!(
            shape.label().contains("accessToken"),
            "EmptyToken label should name the empty field: {}",
            shape.label(),
        );
    }

    #[test]
    fn source_label_redacts_token_bytes_for_every_credential_source_variant() {
        // Iterate every CredentialSource variant; the source label
        // must NEVER contain bearer-shaped substrings, even when an
        // attacker controls path / service / mdat strings (e.g.
        // `service` on MacosKeychainMultiAccount is technically
        // attacker-influenceable since it's parsed from
        // `security dump-keychain` output).
        let attacker_path = PathBuf::from("/sk-ant-secrettoken/eyJabc");
        let attacker_service = "Bearer eyJabc-evil-service".to_string();
        let attacker_mdat = Some("eyJ-mdat-bytes".to_string());
        let cases = [
            CredentialSource::MacosKeychainPrimary,
            CredentialSource::MacosKeychainMultiAccount {
                service: attacker_service,
                mdat: attacker_mdat,
            },
            CredentialSource::EnvDir {
                path: attacker_path.clone(),
            },
            CredentialSource::XdgConfig {
                path: attacker_path.clone(),
            },
            CredentialSource::ClaudeLegacy {
                path: attacker_path,
            },
        ];
        for source in cases {
            let label = source_label(&source);
            // The substrings here are attacker-controlled, so the
            // label SHOULD contain them (pass-through is correct).
            // What must NOT happen: a future refactor adds the
            // bearer token from `Credentials::token()` into the
            // label. Pin that boundary by asserting label length is
            // bounded and doesn't grow disproportionately on
            // pathological inputs (no template injection).
            assert!(
                label.len() < 1024,
                "source label grew unexpectedly long ({} bytes) for {:?}; possible token interpolation: {}",
                label.len(),
                source,
                label,
            );
        }
    }

    // --- Cache: usage.json + lock branch coverage ---

    #[test]
    fn cache_usage_json_warns_on_unreadable_distinct_from_stale() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Exists,
            usage_json: UsageJsonState::Unreadable {
                message: "filesystem corruption".to_string(),
            },
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let usage = find_check(&r, "cache.usage_json_shape");
        assert_eq!(usage.severity(), Severity::Warn);
        assert!(
            usage.hint().unwrap().contains("filesystem"),
            "Unreadable hint must distinguish corruption from stale: {:?}",
            usage.hint(),
        );
    }

    #[test]
    fn cache_usage_json_warns_on_future_timestamp() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Exists,
            usage_json: UsageJsonState::FutureTimestamp,
            lock: LockState::Absent,
        });
        let r = build_report(&env);
        let usage = find_check(&r, "cache.usage_json_shape");
        assert_eq!(usage.severity(), Severity::Warn);
        assert!(
            usage.hint().unwrap().contains("clock"),
            "FutureTimestamp hint should point at clock skew: {:?}",
            usage.hint(),
        );
    }

    #[test]
    fn cache_lock_warns_on_unreadable() {
        let env = with_cache(DoctorCacheSnapshot {
            root_path: Some(PathBuf::from("/home/user/.cache/linesmith")),
            root: CacheRootState::Exists,
            usage_json: UsageJsonState::Missing,
            lock: LockState::Unreadable {
                message: "Permission denied".to_string(),
            },
        });
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "cache.lock_fresh").severity(),
            Severity::Warn
        );
    }

    // --- Endpoint: credential-race short-circuit ---

    #[test]
    fn endpoint_skips_with_race_reason_when_credentials_vanished() {
        let mut env = DoctorEnv::healthy();
        env.endpoint = DoctorEndpointSnapshot {
            probe: None,
            credentials_vanished: true,
        };
        let r = build_report(&env);
        for id in [
            "endpoint.reachable",
            "endpoint.shape_current",
            "endpoint.headers_sane",
        ] {
            let check = find_check(&r, id);
            assert_eq!(check.severity(), Severity::Skip);
            assert!(
                check.hint().unwrap().contains("race"),
                "skip reason should name the race: {:?}",
                check.hint(),
            );
        }
    }

    // --- Credentials: cascade-source short-circuit ---

    #[test]
    #[cfg(target_os = "macos")]
    fn snapshot_credentials_does_not_short_circuit_on_macos_without_env() {
        // The cfg gate in `snapshot_credentials`'s short-circuit is
        // load-bearing rather than decorative: on macOS the
        // `security` subprocess can resolve from the user's Keychain
        // even with no env vars set, so the function MUST run the
        // cascade rather than reporting Unresolvable. A future
        // refactor that drops the `cfg!(target_os = "macos")` guard
        // would silently regress macOS users with no configured
        // env vars but valid Keychain entries.
        use crate::data_context::credentials::FileCascadeEnv;
        let snapshot = snapshot_credentials(&FileCascadeEnv::default());
        // On macOS without env vars the cascade still runs; result
        // is Resolved (real Keychain hit) or Failed (no Keychain
        // entry, NoCredentials). Both are valid; what's NOT valid
        // is short-circuiting to Unresolvable.
        assert!(
            !matches!(snapshot, DoctorCredentialsSnapshot::Unresolvable),
            "macOS must run the cascade even with no env vars; got {snapshot:?}"
        );
    }

    #[test]
    #[cfg(not(target_os = "macos"))]
    fn snapshot_credentials_returns_unresolvable_when_no_path_source_non_macos() {
        // On non-macOS hosts with no `$HOME`, no `$XDG_CONFIG_HOME`,
        // and no `$CLAUDE_CONFIG_DIR`, the file cascade has no root
        // and there's no keychain — the cascade can't even be
        // attempted. Per spec §Cross-category short-circuits this
        // is SKIP, not FAIL.
        use crate::data_context::credentials::FileCascadeEnv;
        let snapshot = snapshot_credentials(&FileCascadeEnv::default());
        assert!(
            matches!(snapshot, DoctorCredentialsSnapshot::Unresolvable),
            "expected Unresolvable, got {snapshot:?}",
        );
    }

    #[test]
    #[cfg(not(target_os = "macos"))]
    fn snapshot_credentials_attempts_cascade_when_xdg_or_claude_dir_overrides_home() {
        // CI / service environments commonly omit `$HOME` but set
        // one of the override env vars (`$XDG_CONFIG_HOME`,
        // `$CLAUDE_CONFIG_DIR`). The file cascade still has a root
        // in those cases, so the snapshot must NOT short-circuit
        // to Unresolvable. The actual `resolve_credentials_with`
        // call will likely return `Failed(NoCredentials)` on a CI
        // host without real credentials, but that's the correct
        // outcome, not a doctor false-negative.
        use crate::data_context::credentials::FileCascadeEnv;
        // `FileCascadeEnv` is `#[non_exhaustive]` in linesmith-core,
        // so cross-crate struct-literal construction is blocked
        // (E0639). Build via the public constructor instead.
        for env in [
            FileCascadeEnv::new(None, Some("/etc/xdg".into()), None),
            FileCascadeEnv::new(Some("/etc/claude".into()), None, None),
        ] {
            let snapshot = snapshot_credentials(&env);
            assert!(
                !matches!(snapshot, DoctorCredentialsSnapshot::Unresolvable),
                "override env should keep the cascade attemptable; got Unresolvable for env={env:?}",
            );
        }
    }

    #[test]
    fn stat_usage_json_distinguishes_current_stale_and_missing() {
        use crate::data_context::cache::CACHE_SCHEMA_VERSION;
        let tempdir = tempfile::tempdir().expect("tempdir");
        let missing = tempdir.path().join("missing.json");
        assert!(matches!(stat_usage_json(&missing), UsageJsonState::Missing));

        let current = tempdir.path().join("current.json");
        std::fs::write(
            &current,
            format!(
                r#"{{"schema_version":{CACHE_SCHEMA_VERSION},"cached_at":"2026-04-30T00:00:00Z"}}"#
            ),
        )
        .expect("write");
        assert!(matches!(
            stat_usage_json(&current),
            UsageJsonState::Current { .. }
        ));

        let stale = tempdir.path().join("stale.json");
        std::fs::write(&stale, r#"{"schema_version":0}"#).expect("write");
        assert!(matches!(
            stat_usage_json(&stale),
            UsageJsonState::Stale { schema_version: 0 }
        ));
    }

    #[test]
    fn stat_usage_lock_distinguishes_active_stale_and_absent() {
        // `stat_usage_lock` now takes the cache ROOT and delegates
        // to `LockStore::read`; place each fixture's `usage.lock`
        // inside its own root subdir so the per-root LockStore
        // sees the right file.
        let tempdir = tempfile::tempdir().expect("tempdir");

        let absent_root = tempdir.path().join("absent");
        std::fs::create_dir(&absent_root).expect("mkdir");
        assert!(matches!(stat_usage_lock(&absent_root), LockState::Absent));

        let active_root = tempdir.path().join("active");
        std::fs::create_dir(&active_root).expect("mkdir");
        std::fs::write(
            active_root.join("usage.lock"),
            r#"{"blocked_until":99999999999}"#,
        )
        .expect("write");
        assert!(matches!(
            stat_usage_lock(&active_root),
            LockState::Active { .. }
        ));

        let stale_root = tempdir.path().join("stale");
        std::fs::create_dir(&stale_root).expect("mkdir");
        std::fs::write(stale_root.join("usage.lock"), r#"{"blocked_until":1}"#).expect("write");
        assert!(matches!(
            stat_usage_lock(&stale_root),
            LockState::Stale { .. }
        ));
    }

    #[test]
    fn stat_usage_lock_legacy_non_json_falls_back_to_mtime_via_lockstore() {
        // Parity-rule pin: doctor must agree with the runtime on
        // legacy non-JSON lock files (which the runtime treats as
        // Active via mtime + LEGACY_LOCK_TTL). Without delegating
        // to `LockStore::read`, doctor would WARN Unreadable
        // here while the runtime quietly treats the lock as
        // Active.
        let tempdir = tempfile::tempdir().expect("tempdir");
        let root = tempdir.path().to_path_buf();
        std::fs::write(root.join("usage.lock"), b"not json bytes").expect("write");
        match stat_usage_lock(&root) {
            LockState::Active { .. } => {}
            other => panic!("expected Active via mtime fallback, got {other:?}"),
        }
    }

    // --- Plugins category ---

    use linesmith_plugin::{CollisionWinner, PluginError};

    fn with_plugins(snapshot: DoctorPluginsSnapshot) -> DoctorEnv {
        let mut env = DoctorEnv::healthy();
        env.plugins = snapshot;
        env
    }

    #[test]
    fn plugins_category_with_no_sources_skips_all_four() {
        // Spec §Edge cases: "Default plugin directory doesn't
        // exist (no `plugin_dirs` configured) → SKIP the Plugins
        // category with reason 'no plugins configured'; not a
        // failure." A first-run user without `~/.config/linesmith/
        // segments/` shouldn't get a non-zero exit just for
        // that.
        let env = with_plugins(DoctorPluginsSnapshot::NoSources);
        let r = build_report(&env);
        for id in [
            "plugins.compile",
            "plugins.deps_valid",
            "plugins.no_id_collisions",
            "plugins.no_builtin_collisions",
        ] {
            let check = find_check(&r, id);
            assert_eq!(check.severity(), Severity::Skip, "{id} should SKIP");
            assert!(
                check.hint().unwrap().contains("no plugins"),
                "skip reason should name the empty-sources state: {:?}",
                check.hint(),
            );
        }
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn plugins_category_with_zero_plugins_passes_vacuously() {
        // Discovery ran but found no `.rhai` files. Spec PASS:
        // "every discovered .rhai parses" — the empty set
        // satisfies. Distinct from NoSources (which SKIPs); this
        // is the "user created the plugin dir but hasn't dropped
        // a file in yet" case.
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 0,
            errors: Vec::new(),
        }));
        let r = build_report(&env);
        for id in [
            "plugins.compile",
            "plugins.deps_valid",
            "plugins.no_id_collisions",
            "plugins.no_builtin_collisions",
        ] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Pass,
                "{id} should PASS (vacuous)",
            );
        }
    }

    #[test]
    fn plugins_compile_fails_with_path_and_message_in_hint() {
        // Spec hint: "the reported plugin file has a syntax
        // error at line N". `PluginError::Compile.message`
        // already includes the line/col from rhai's parser; the
        // doctor renders it verbatim so the hint stays
        // actionable.
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 0,
            errors: vec![PluginError::Compile {
                path: PathBuf::from("/home/user/.config/linesmith/segments/broken.rhai"),
                message: "Syntax error at line 7, position 3".to_string(),
            }],
        }));
        let r = build_report(&env);
        let compile = find_check(&r, "plugins.compile");
        assert_eq!(compile.severity(), Severity::Fail);
        let hint = compile.hint().unwrap();
        assert!(
            hint.contains("broken.rhai") && hint.contains("line 7"),
            "hint must surface the path and the parser line/col: {hint}",
        );
    }

    #[test]
    fn plugins_deps_valid_fails_on_unknown_dep() {
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 0,
            errors: vec![PluginError::UnknownDataDep {
                path: PathBuf::from("/plugins/dep-typo.rhai"),
                name: "credentialz".to_string(),
            }],
        }));
        let r = build_report(&env);
        let check = find_check(&r, "plugins.deps_valid");
        assert_eq!(check.severity(), Severity::Fail);
        assert!(
            check.hint().unwrap().contains("credentialz"),
            "hint must surface the offending dep name: {:?}",
            check.hint(),
        );
    }

    #[test]
    fn plugins_deps_valid_fails_on_malformed_header() {
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 0,
            errors: vec![PluginError::MalformedDataDeps {
                path: PathBuf::from("/plugins/bad-header.rhai"),
                message: "expected JSON array, got string".to_string(),
            }],
        }));
        let r = build_report(&env);
        assert_eq!(
            find_check(&r, "plugins.deps_valid").severity(),
            Severity::Fail,
        );
    }

    #[test]
    fn plugins_no_id_collisions_fails_when_two_plugins_share_id() {
        // Built-in collision goes to a different check; pin that
        // a plugin-vs-plugin collision lands on the right row.
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 1,
            errors: vec![PluginError::IdCollision {
                id: "my_segment".to_string(),
                winner: CollisionWinner::Plugin(PathBuf::from("/plugins/first.rhai")),
                loser_path: PathBuf::from("/plugins/second.rhai"),
            }],
        }));
        let r = build_report(&env);
        let check = find_check(&r, "plugins.no_id_collisions");
        assert_eq!(check.severity(), Severity::Fail);
        assert!(
            check.hint().unwrap().contains("first.rhai")
                && check.hint().unwrap().contains("second.rhai"),
            "hint must name both winner and loser: {:?}",
            check.hint(),
        );
        // Built-in collisions check stays clean — collisions are
        // partitioned correctly.
        assert_eq!(
            find_check(&r, "plugins.no_builtin_collisions").severity(),
            Severity::Pass,
        );
    }

    #[test]
    fn plugins_no_builtin_collisions_fails_when_plugin_id_shadows_builtin() {
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 0,
            errors: vec![PluginError::IdCollision {
                id: "model".to_string(),
                winner: CollisionWinner::BuiltIn,
                loser_path: PathBuf::from("/plugins/model.rhai"),
            }],
        }));
        let r = build_report(&env);
        let check = find_check(&r, "plugins.no_builtin_collisions");
        assert_eq!(check.severity(), Severity::Fail);
        assert!(
            check.label().contains("shadow") || check.hint().unwrap().contains("model.rhai"),
            "label or hint should make the shadowing concrete: label={} hint={:?}",
            check.label(),
            check.hint(),
        );
        // Plugin-vs-plugin collision check stays clean.
        assert_eq!(
            find_check(&r, "plugins.no_id_collisions").severity(),
            Severity::Pass,
        );
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "render-time PluginError reached")]
    fn plugins_render_time_error_panics_in_debug_builds() {
        // In debug builds the doctor `debug_assert!`s on
        // render-time variants in `load_errors()` because their
        // presence indicates a runtime bug — the spec puts doctor
        // panics in the bug-report bucket, not the
        // graceful-degradation bucket. Release behavior (FAIL +
        // hint) is pinned by the sibling test below, which drives
        // `check_plugins_compile` directly so it doesn't trip the
        // debug_assert and runs in any build mode.
        let env = with_plugins(DoctorPluginsSnapshot::Discovered(PluginsRegistrySummary {
            compiled_count: 1,
            errors: vec![PluginError::Runtime {
                id: "my_seg".to_string(),
                message: "should not surface here".to_string(),
            }],
        }));
        let _ = build_report(&env);
    }

    #[test]
    fn check_plugins_compile_fails_loud_on_unexpected_variants() {
        // Drive `check_plugins_compile` directly with a populated
        // `unexpected` slice, bypassing the orchestrator's
        // debug_assert. This is the release-build behavior: route
        // render-time variants through the "unexpected" bucket and
        // surface a FAIL on `plugins.compile` with a "file a
        // linesmith bug" hint. Loop covers all 4 render-time
        // variants so a future refactor that splits one out by
        // accident (catching only Runtime, leaving the other 3
        // silent) trips here. Runs in any build mode.
        let cases = [
            PluginError::Runtime {
                id: "x".to_string(),
                message: "boom".to_string(),
            },
            PluginError::Timeout {
                id: "x".to_string(),
            },
            PluginError::ResourceExceeded {
                id: "x".to_string(),
                limit: linesmith_plugin::ResourceLimit::MaxOperations,
            },
            PluginError::MalformedReturn {
                id: "x".to_string(),
                message: "boom".to_string(),
            },
        ];
        for err in &cases {
            let unexpected: Vec<&PluginError> = vec![err];
            let result = check_plugins_compile(0, &[], &unexpected);
            assert_eq!(
                result.severity(),
                Severity::Fail,
                "render-time variant {err:?} should FAIL the compile row",
            );
            assert!(
                result.hint().unwrap().contains("file a linesmith bug"),
                "hint should direct the user to file a bug: {:?}",
                result.hint(),
            );
        }
    }

    // --- Git category ---

    use crate::data_context::git::{Head, RepoKind};

    fn with_git(snapshot: DoctorGitSnapshot) -> DoctorEnv {
        let mut env = DoctorEnv::healthy();
        env.git = snapshot;
        env
    }

    fn git_summary(repo_kind: RepoKind, head: Head) -> GitContextSummary {
        GitContextSummary {
            repo_path: PathBuf::from("/home/user/code/project/.git"),
            repo_kind,
            head,
        }
    }

    #[test]
    fn git_repo_detected_passes_when_repo_present() {
        let r = build_report(&DoctorEnv::healthy());
        for id in ["git.repo_detected", "git.head_resolves", "git.repo_kind"] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Pass,
                "{id} should PASS in healthy env",
            );
        }
    }

    #[test]
    fn git_not_in_repo_skips_all_three_when_no_git_segment_configured() {
        // Spec carve-out: "Not in a repo (SKIP if no git_*
        // segment enabled)". A user who's outside any repo and
        // hasn't enabled `git_branch` shouldn't see a WARN —
        // their config doesn't ask for git data.
        let env = with_git(DoctorGitSnapshot::NotInRepo);
        let r = build_report(&env);
        // Healthy fixture has no config.line, so no segments
        // configured; expect SKIP across all three.
        for id in ["git.repo_detected", "git.head_resolves", "git.repo_kind"] {
            assert_eq!(
                find_check(&r, id).severity(),
                Severity::Skip,
                "{id} should SKIP when not-in-repo + no git_* segment",
            );
        }
        assert_eq!(r.exit_code(), 0);
    }

    #[test]
    fn git_not_in_repo_warns_when_git_segment_configured() {
        // Same spec carve-out, opposite branch: `git_branch` is
        // configured, so doctor surfaces the WARN — the segment
        // would silently hide otherwise and the user might wonder
        // where their branch went.
        let mut env = with_git(DoctorGitSnapshot::NotInRepo);
        let config = Config {
            line: Some(LineConfig {
                segments: vec!["git_branch".into()],
                ..LineConfig::default()
            }),
            ..Config::default()
        };
        env.config = config_snapshot_loaded(config);
        let r = build_report(&env);
        let detected = find_check(&r, "git.repo_detected");
        assert_eq!(detected.severity(), Severity::Warn);
        assert!(
            detected.hint().unwrap().contains("git_"),
            "hint should reference the configured git segment: {:?}",
            detected.hint(),
        );
    }

    #[test]
    fn git_failed_on_corrupt_repo_renders_message() {
        let env = with_git(DoctorGitSnapshot::Failed {
            message: "InvalidFormat: expected git_dir".to_string(),
        });
        let r = build_report(&env);
        let detected = find_check(&r, "git.repo_detected");
        assert_eq!(detected.severity(), Severity::Fail);
        assert!(
            detected.label().contains("InvalidFormat"),
            "label should surface the gix error message: {}",
            detected.label(),
        );
        // Downstream rows SKIP when discover failed — no point
        // asking about HEAD when we couldn't open the repo.
        assert_eq!(
            find_check(&r, "git.head_resolves").severity(),
            Severity::Skip,
        );
        assert_eq!(find_check(&r, "git.repo_kind").severity(), Severity::Skip);
    }

    #[test]
    fn git_repo_kind_label_includes_worktree_name() {
        let env = with_git(DoctorGitSnapshot::Repo(git_summary(
            RepoKind::LinkedWorktree {
                name: "feature-x".to_string(),
            },
            Head::Branch("feature-x".to_string()),
        )));
        let r = build_report(&env);
        let kind = find_check(&r, "git.repo_kind");
        assert_eq!(kind.severity(), Severity::Pass);
        assert!(
            kind.label().contains("feature-x"),
            "worktree label must name the worktree: {}",
            kind.label(),
        );
    }

    #[test]
    fn git_head_resolves_renders_each_variant_distinctly() {
        // Pin the label rendering for each Head variant so a
        // refactor that swaps formatting strings shows up here.
        // gix::ObjectId::null() is the documented "no commit"
        // sentinel; works for the Detached-rendering pin since
        // the doctor doesn't validate the OID against any object
        // database.
        let cases = [
            (Head::Branch("main".to_string()), "HEAD -> main".to_string()),
            (
                Head::Detached(gix::ObjectId::null(gix::hash::Kind::Sha1)),
                "HEAD detached at".to_string(),
            ),
            (
                Head::Unborn {
                    symbolic_ref: "main".to_string(),
                },
                "HEAD unborn".to_string(),
            ),
            (
                Head::OtherRef {
                    full_name: "refs/tags/v1.0".to_string(),
                },
                "HEAD -> refs/tags/v1.0".to_string(),
            ),
        ];
        for (head, expected_substr) in cases {
            let env = with_git(DoctorGitSnapshot::Repo(git_summary(RepoKind::Main, head)));
            let r = build_report(&env);
            let check = find_check(&r, "git.head_resolves");
            assert_eq!(check.severity(), Severity::Pass);
            assert!(
                check.label().contains(&expected_substr),
                "label `{}` should contain `{}`",
                check.label(),
                expected_substr,
            );
        }
    }

    #[test]
    fn git_head_resolves_warns_on_lossy_otherref() {
        // gix decodes refnames via `as_bstr().to_string()`, which
        // substitutes U+FFFD for invalid bytes. A `\u{FFFD}` in
        // `OtherRef.full_name` means the underlying refname is
        // corrupt; PASS would silently hide the problem and the
        // user would chase phantom segment misbehavior.
        let env = with_git(DoctorGitSnapshot::Repo(git_summary(
            RepoKind::Main,
            Head::OtherRef {
                full_name: "refs/heads/bad\u{FFFD}name".to_string(),
            },
        )));
        let r = build_report(&env);
        let check = find_check(&r, "git.head_resolves");
        assert_eq!(check.severity(), Severity::Warn);
        assert!(
            check.label().contains("non-UTF-8") || check.hint().unwrap().contains("UTF-8"),
            "label/hint should call out the UTF-8 issue: label={} hint={:?}",
            check.label(),
            check.hint(),
        );
    }

    #[test]
    fn any_git_segment_enabled_returns_false_when_unloaded() {
        assert!(!any_git_segment_enabled(&ConfigReadOutcome::Unresolved));
        assert!(!any_git_segment_enabled(&ConfigReadOutcome::NotFound {
            path: PathBuf::from("/nope"),
            explicit: false,
        }));
    }

    #[test]
    fn any_git_segment_enabled_ignores_plugin_namespace_collisions() {
        // A plugin author can register an id like `git_typo` —
        // that's a plugin's segment, not the runtime's `git_*`
        // suite. A naive `starts_with("git_")` lens would trigger
        // the WARN ("not in a repo, but a git segment is
        // configured") for users who never asked the runtime to
        // surface git data. Gating against `BUILT_IN_SEGMENT_IDS`
        // keeps the gate tight without breaking forward-compat
        // for future built-in `git_status` / `git_stash`.
        let parsed: Config = r#"[line]
segments = ["model", "git_typo", "git_my_plugin", "cost"]
"#
        .parse()
        .expect("parse");
        let snap = config_snapshot_loaded(parsed);
        assert!(!any_git_segment_enabled(&snap.read));
    }

    #[test]
    fn any_git_segment_enabled_handles_malformed_numbered_line_tables() {
        // Pin the `.is_some_and` chain's short-circuit behavior:
        // malformed `[line.N]` shapes (non-table value, missing
        // `segments` array, non-string array entry) all degrade
        // to `false`. A refactor to `unwrap()` would surface
        // here.
        let cases: &[&str] = &[
            // [line.1] is a string, not a table.
            "[line]\nsegments = [\"model\"]\n[line]\n1 = \"not-a-table\"\n",
            // [line.1].segments is an integer.
            "[line]\nsegments = [\"model\"]\n[line.1]\nsegments = 42\n",
            // [line.1].segments contains a non-string.
            "[line]\nsegments = [\"model\"]\n[line.1]\nsegments = [42]\n",
            // [line.1] table missing `segments` entirely.
            "[line]\nsegments = [\"model\"]\n[line.1]\nfoo = \"bar\"\n",
        ];
        for raw in cases {
            // Some inputs may not parse as TOML; skip those — the
            // doctor's parse-error short-circuit handles them
            // earlier in the chain. We're only testing what
            // `any_git_segment_enabled` does once the value DID
            // parse.
            let Ok(parsed) = raw.parse::<Config>() else {
                continue;
            };
            let snap = config_snapshot_loaded(parsed);
            assert!(
                !any_git_segment_enabled(&snap.read),
                "malformed input should yield false; raw was:\n{raw}",
            );
        }
    }

    #[test]
    fn any_git_segment_enabled_finds_id_in_main_line() {
        let parsed: Config = r#"[line]
segments = ["model", "git_branch", "cost"]
"#
        .parse()
        .expect("parse");
        let snap = config_snapshot_loaded(parsed);
        assert!(any_git_segment_enabled(&snap.read));
    }

    #[test]
    fn any_git_segment_enabled_finds_id_in_numbered_line() {
        let parsed: Config = r#"
[line]
segments = ["model"]

[line.1]
segments = ["git_branch"]
"#
        .parse()
        .expect("parse");
        let snap = config_snapshot_loaded(parsed);
        assert!(any_git_segment_enabled(&snap.read));
    }

    #[test]
    fn any_git_segment_enabled_returns_false_for_no_git_config() {
        let parsed: Config = r#"[line]
segments = ["model", "cost", "context_window"]
"#
        .parse()
        .expect("parse");
        let snap = config_snapshot_loaded(parsed);
        assert!(!any_git_segment_enabled(&snap.read));
    }

    #[test]
    fn any_git_segment_enabled_finds_id_in_inline_table_numbered_entry() {
        // Pin that a multi-line config enabling git via
        // `{ type = "git_branch", merge = true }` in a numbered
        // line registers as a git config (per ADR-0024 — inline-
        // table segment entries count). Otherwise doctor skips the
        // repo-warning checks when run outside a repo and the user
        // gets no diagnostic for an actually-git-segment-using
        // config.
        let parsed: Config = r#"
layout = "multi-line"
[line]

[line.1]
segments = ["model", { type = "git_branch", merge = true }]
"#
        .parse()
        .expect("parse");
        let snap = config_snapshot_loaded(parsed);
        assert!(
            any_git_segment_enabled(&snap.read),
            "inline-table git_branch in numbered line must count as git-enabled",
        );
    }

    // --- Self/update_available classifier ---
    //
    // Pure-input tests for `classify_update_response`; the network-
    // touching `snapshot_update_probe` is exercised via its end-to-
    // end smoke test (DoctorEnv::from_process must not panic) since
    // its outcome is host-dependent.

    #[test]
    fn classify_update_response_returns_latest_when_tag_matches_local() {
        let body = br#"{"tag_name":"v1.2.3","name":"linesmith 1.2.3"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::Latest => {}
            other => panic!("expected Latest, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_latest_when_local_is_newer() {
        // Dev pull from main, ahead of the latest published release
        // (local 1.3.0 vs published 1.2.3).
        let body = br#"{"tag_name":"v1.2.3"}"#;
        match classify_update_response(body, "1.3.0") {
            DoctorUpdateProbe::Latest => {}
            other => panic!("expected Latest (local newer), got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_newer_when_remote_is_higher() {
        let body = br#"{"tag_name":"v2.0.0"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::Newer { latest } => {
                assert_eq!(latest, "v2.0.0", "tag_name preserved verbatim");
            }
            other => panic!("expected Newer, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_parse_error_on_invalid_json() {
        let body = b"<html>captive portal</html>";
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::ParseError { message } => {
                assert!(!message.is_empty(), "parse error needs a diagnostic");
            }
            other => panic!("expected ParseError, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_parse_error_when_tag_name_missing() {
        let body = br#"{"name":"some release"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::ParseError { message } => {
                assert!(message.contains("tag_name"), "diagnostic: {message}");
            }
            other => panic!("expected ParseError for missing tag_name, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_strips_v_prefix_for_comparison() {
        // GitHub conventionally uses `v1.2.3`; CARGO_PKG_VERSION never
        // does. Equality must hold after the parser strips the `v`.
        let body = br#"{"tag_name":"v0.1.1"}"#;
        match classify_update_response(body, "0.1.1") {
            DoctorUpdateProbe::Latest => {}
            other => panic!("expected Latest after v-prefix strip, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_parse_error_when_remote_unparseable_but_local_parses() {
        // Mixed-parseability path: comparing local semver against an
        // unparseable remote tag (`v1.foo.0`, `nightly`) is undefined.
        // Earlier code fell back to string equality, which silently
        // produced an unverified Newer claim or — when string-equal —
        // a Latest PASS the comparator never validated. Spec WARN
        // with a clear "couldn't compare" diagnostic instead.
        let body = br#"{"tag_name":"nightly-build-2026-04-30"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::ParseError { message } => {
                assert!(
                    message.contains("nightly-build-2026-04-30"),
                    "diagnostic should name the offending tag: {message}"
                );
                assert!(
                    message.contains("MAJOR.MINOR.PATCH"),
                    "diagnostic should explain the expected shape: {message}"
                );
            }
            other => panic!("expected ParseError for unparseable remote tag, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_newer_when_both_unparseable_and_unequal() {
        // Monorepo / non-semver tags on both sides — string equality
        // is the only meaningful comparator. Inequality falls to
        // Newer with the verbatim tag so the user can decide.
        let body = br#"{"tag_name":"linesmith-stable"}"#;
        match classify_update_response(body, "nightly") {
            DoctorUpdateProbe::Newer { latest } => {
                assert_eq!(latest, "linesmith-stable");
            }
            other => panic!("expected Newer fallback for both-unparseable, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_latest_when_both_unparseable_and_equal() {
        // String-equality fallback's PASS branch — both sides ship
        // the same non-semver tag.
        let body = br#"{"tag_name":"nightly"}"#;
        match classify_update_response(body, "nightly") {
            DoctorUpdateProbe::Latest => {}
            other => panic!("expected Latest for both-unparseable + string-equal, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_returns_parse_error_when_local_version_invalid() {
        // Defensive: if our own CARGO_PKG_VERSION came out malformed,
        // surface that as a probe ParseError rather than silently
        // PASSing on a bogus comparison.
        let body = br#"{"tag_name":"v1.2.3"}"#;
        match classify_update_response(body, "not-a-version") {
            DoctorUpdateProbe::ParseError { message } => {
                assert!(message.contains("not-a-version"), "diagnostic: {message}");
            }
            other => panic!("expected ParseError, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_clamps_serde_error_to_one_line_under_200_chars() {
        // Defensive guard: serde_json::Error::to_string() can echo
        // body fragments (an HTML error body whose first line carries
        // a long token-bearing URL, a multi-line proxy splash, etc.).
        // clamp_diag should drop everything past the first newline
        // and cap at 200 chars + ellipsis.
        let body = b"<html>\n<a href=\"https://evil/?token=secret\">click</a>\nbody...";
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::ParseError { message } => {
                assert!(
                    !message.contains('\n'),
                    "message must be single-line: {message:?}"
                );
                assert!(
                    !message.contains("token="),
                    "post-newline content must be dropped: {message:?}"
                );
                assert!(
                    message.len() <= 203,
                    "message too long: {} bytes",
                    message.len()
                );
            }
            other => panic!("expected ParseError, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_strips_control_chars_from_remote_tag() {
        // Defensive ANSI-injection guard: a compromised response
        // body could JSON-escape terminal escape sequences in
        // `tag_name`; serde_json decodes `\u001b` and `\u0007` into
        // raw ESC and BEL bytes that would render straight to stdout
        // via the WARN line. sanitize_tag drops them before storing.
        let body = br#"{"tag_name":"v9.9.9\u001b[2J\u0007hostile"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::Newer { latest } => {
                assert!(!latest.contains('\x1b'), "ESC must be stripped: {latest:?}");
                assert!(!latest.contains('\x07'), "BEL must be stripped: {latest:?}");
                assert!(
                    latest.contains("v9.9.9"),
                    "printable content kept: {latest:?}"
                );
            }
            other => panic!("expected Newer with sanitized tag, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_caps_remote_tag_at_64_chars() {
        // Bounded length so a tag the size of the body cap can't
        // paint the user's terminal with screenfuls of "upgrade to ...".
        // Use a non-semver shape (no dots) so the comparator falls
        // through to the both-unparseable Newer branch where
        // sanitize_tag actually applies.
        let huge_tag: String = std::iter::repeat_n('x', 1000).collect();
        let body = format!(r#"{{"tag_name":"{huge_tag}"}}"#);
        match classify_update_response(body.as_bytes(), "nightly") {
            DoctorUpdateProbe::Newer { latest } => {
                assert!(
                    latest.chars().count() <= 64,
                    "got {} chars",
                    latest.chars().count()
                );
            }
            other => panic!("expected Newer with capped tag, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_handles_u32_overflow_in_remote_major() {
        // u32::MAX + 1 = 4294967296. parse_three_part_version returns
        // None → mixed-parseability arm → ParseError, not a silent
        // string-equality fallback.
        let body = br#"{"tag_name":"4294967296.0.0"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::ParseError { message } => {
                assert!(message.contains("4294967296"), "diagnostic: {message}");
            }
            other => panic!("expected ParseError for u32 overflow, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_handles_leading_zeros_as_equal() {
        // "v01.02.03" parses as (1, 2, 3) per u32::from_str's leading-
        // zero acceptance. Equal-tuple compare → Latest.
        let body = br#"{"tag_name":"v01.02.03"}"#;
        match classify_update_response(body, "1.2.3") {
            DoctorUpdateProbe::Latest => {}
            other => panic!("expected Latest for leading-zero remote, got {other:?}"),
        }
    }

    #[test]
    fn classify_update_response_inner_returns_transport_error_when_body_truncated() {
        // Regression test for the 32 KiB → 256 KiB cap bump. If the
        // body cap is exhausted (truncation flag true), the result
        // must be a TransportError with a "bump the cap" pointer —
        // NOT a ParseError pointing the user at a "GitHub API shape
        // changed" red herring (the original symptom that smoke
        // testing the live binary surfaced). Without this guard, a
        // future cap-tuner who lowers the constant introduces the
        // same silent misclassification all over again.
        //
        // The synthetic body must exceed `UPDATE_PROBE_MAX_BYTES` to
        // satisfy the `debug_assert!` linking `truncated` to body
        // length — caller can't claim "truncated" without actually
        // having overshot the cap.
        let body = vec![b'x'; 256 * 1024 + 1];
        match classify_update_response_inner(&body, "0.1.1", true) {
            DoctorUpdateProbe::TransportError { message } => {
                assert!(
                    message.contains("UPDATE_PROBE_MAX_BYTES"),
                    "diagnostic should name the constant to bump: {message}"
                );
            }
            other => panic!("expected TransportError on truncation, got {other:?}"),
        }
    }
}