car-inference 0.61.2

Local model inference for CAR — Candle backend with Qwen3 models
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
//! `car doctor` — an offline health check + repair for a CAR install.
//!
//! Built to run *when things are broken*. It touches only the local filesystem
//! (`~/.car` and the shared HuggingFace model cache), never the daemon, so it
//! still works after a half-finished reinstall or when `car-server` won't even
//! start. It surfaces — and, in `--repair` mode, fixes what's safe to fix — the
//! failure modes that successive installs and a shared, externally-mutated cache
//! produce:
//!
//!   * **Corrupt model weights** — truncated/byte-rotted/externally-deleted files
//!     in the model cache (reuses the Task-1/2 integrity primitives in
//!     [`crate::download`]).
//!   * **Incomplete installs** — a managed model dir whose manifest was symlinked
//!     into the HuggingFace snapshot but whose weights never arrived, i.e. what
//!     an interrupted `car models pull` leaves behind (Parslee-ai/car#616).
//!   * **Unparseable state files** — a `~/.car/*.json` an older version wrote in a
//!     shape this binary can't read, or a partially-written file.
//!   * **Version skew** — state last written by a different CAR version than the
//!     binary now running (read from the `version.json` stamp).
//!   * **Abandoned partial downloads** — `*.sync.part` blobs stranded in the
//!     HuggingFace cache. Reported with sizes and ages; `--repair` deletes only
//!     the ones that are provably abandoned and CAR's (see [`find_leftovers_in`]).
//!   * **Empty event journals** — a zero-byte journal per session that never
//!     executed anything; reaped under `--repair` (see [`find_empty_journals`]).
//!   * **Entries this version does not write** — top-level state-root entries
//!     no writer in this version of CAR creates. Reported neutrally, never
//!     removed: an earlier CAR or another tool may still use them.
//!   * **An unusable daemon `TMPDIR`** — the daemon probes the temp directory it
//!     inherited when it starts and records the result under `<CAR_HOME>/doctor/`
//!     ([`record_daemon_tmpdir_probe`]). Doctor reads that record from disk, so a
//!     daemon handed a torn-down installer-sandbox `TMPDIR` is visible without
//!     contacting it (Parslee-ai/car#1494).
//!
//! Repair is deliberately conservative: it purges *provably* corrupt cache files
//! (so the next daemon run re-downloads them), clears a managed model directory
//! an interrupted pull left with no resolvable weights (links only — the shared
//! HuggingFace cache it points into is never touched, see
//! [`purge_interrupted_install`]), backs up unparseable state files to
//! `<name>.corrupt.bak` rather than deleting them, removes provably-empty
//! journals, removes partial downloads that are provably abandoned in repos CAR
//! fetches whole (no lock held, untouched for a day — the concierge's rule), and
//! refreshes the version stamp (reporting that only when the stamp actually
//! moved). It never deletes unrecognized entries, a partial download that may
//! still be running or is not CAR's, or anything else it can't prove is bad —
//! diagnosis names them and leaves the decision to the operator.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::download::{
    cache_file_usable, purge_corrupt_cache_files_in, verify_cache_file, CacheIntegrity,
};

/// JSON state files CAR writes directly under `~/.car/`. Used both to validate
/// each (does it parse? what schema version?) and to tell recognized files from
/// possible leftovers. Owned across several crates, but the check is generic
/// (parse as JSON), so no cross-crate type dependency is needed.
const KNOWN_STATE_FILES: &[&str] = &[
    "messaging.json",
    "models.json",
    "connectors.json",
    "car-connectors.json",
    "agents.json",
    "routing.json",
    "declagents.json",
    "lane-defaults.json",
    "update-prefs.json",
    "upgrade-cache.json",
    "catalog-cache.json",
    "discovered_models.json",
    "a2a-peers.json",
    "external-agents.jsonl",
    "nudge-state.json",
    "benchmark_priors.json",
    "key_pool_stats.json",
    "model_profiles.json",
    "agent-permissions.json",
    "version.json",
    // Names-only index for the OS-keychain secret store (car-ffi-common's
    // `INDEX_FILE`), written on every platform whenever a secret is stored —
    // and load-bearing on Windows/Linux, whose keychains have no portable
    // enumeration. Absent on a fresh install with no stored secrets, which is
    // why its omission here only surfaced once `car auth login` / `car keys`
    // had run (e.g. validating on Windows): doctor wrongly flagged the live
    // file as a possible older-install leftover and invited its removal.
    "secret_index.json",
    // Durable "this Parslee environment has no OpenRouter upstream" observation
    // (car#786). Written by whichever process first gets that gateway answer, so
    // it is absent until one does — same shape as secret_index.json above, and
    // the same reason it belongs here: an unrecognized live state file gets
    // reported as possible debris from an older install and the user is invited
    // to delete it.
    "gateway-state.json",
    // Durable "the Parslee server rejected this credential" observation
    // (car#887), the sibling of gateway-state.json above and here for exactly
    // the same reason: written only once some process has actually been
    // rejected, so it is absent on a healthy install and would otherwise be
    // reported as older-install debris on precisely the machines where it is
    // doing its job.
    "parslee-credential-state.json",
    // Written by car-inference::resource_policy for the local-model resource policy.
    "model-resource-policy.json",
    // Written by car-auth::authority_hint for prompt-free Parslee auth discovery.
    "parslee-auth-authority.json",
    // The iMessage inbound poller's high-water ROWID
    // (`car_integrations::messages::Watermark::path_in`), seeded by
    // car-messaging's orchestrator on the first poll after Messages is
    // enabled. Absent until then, which is why a fresh install only showed it
    // once messaging was on (car-releases#86).
    "messages-inbound-watermark.json",
    // The signed-catalog check record (`car_inference::catalog::STATUS_FILE`),
    // which this very report reads for its catalog-freshness line.
    "catalog-status.json",
    // The assistant's chosen name and wake spellings (`car_identity::FILE_NAME`).
    "identity.json",
    // The person's default organization (`car_auth::work_contexts::WORK_CONTEXTS_FILE`).
    "work-contexts.json",
    // Each supervised agent's last `server.handshake`, beside the manifest
    // (`car_registry::handshake::FILE_NAME`).
    "agent-handshakes.json",
    // Rows a newer signed catalog withdrew that this machine still keeps, and
    // the names of revoked rows (`car_inference::catalog::RETAINED_FILE`,
    // `REVOKED_NAMES_FILE`, `REVOKED_MODELS_FILE`). Written only once a
    // catalog withdraws or revokes something.
    "catalog-retained.json",
    "catalog-revoked.json",
    "catalog-revoked-models.json",
    // Whether this machine runs peers' coding subtasks
    // (`car_server_core::fleet::FleetWorkerConfig`), written by
    // `fleet.worker.set`.
    "fleet-worker.json",
    // Marks the saved resource policy as the concierge's choice rather than
    // the user's (`car_inference::resource_policy::CONCIERGE_POLICY_MARKER`).
    "model-resource-policy.concierge.json",
    // Standing chat goals set with `goal.set`, beside `journals/`
    // (`car_server_core::session`).
    "chat-goals.json",
    // `car dream`'s default memory file. CAR reads it; it is there only when
    // someone exported memory to it.
    "memory.json",
];

/// Recognized files that are deliberately NOT JSON and must never be parsed or
/// moved aside. `env` is a leftover dotenv `KEY=VALUE` file that CAR no longer
/// reads (the daemon moves it into the secret store, `car secrets
/// migrate-from-env` does the same on request) — JSON-validating it would flag
/// it as corrupt and, under `--repair`, rename a file that may still hold keys
/// to `env.corrupt.bak`.
const KNOWN_NON_JSON_FILES: &[&str] = &[
    "env",
    // Marks that the daemon's one-time move of `env` into the store is over,
    // and what it recorded for `car doctor` (names only).
    ".env-retired",
    ".env-migration.json",
    // Written by car-server for the daemon's persistent peer signing identity.
    "peer-identity.key",
    // `[coder]` settings, TOML (`car_server_core::coder::config`).
    "coder.toml",
    // When the unchosen default `Auto` update policy first ran maintenance
    // (`AUTO_GRACE_FILE` in this crate): a bare timestamp.
    "concierge-auto-since",
    // CarHost's setup progress and Chat model (`apps/host-macos`,
    // `CarHomeDefaults`). Owned by the app, so doctor never JSON-validates or
    // moves it aside.
    "host-state.json",
    // The worker-label HMAC key, 32 raw bytes
    // (`car_registry::workers::label_secret`).
    "label-secret",
    // The operator's own settings, TOML: the self-heal auto-fix switch and
    // the source checkout (`car_server_core::selfheal`). CAR reads it and
    // never writes it.
    "config.toml",
    // The coder's repository trust list beside `coder.toml`, TOML
    // (`car_server_core::coder::repo_trust`), saved by `car coder trust add`
    // and `car coder trust remove`.
    "coder-trust.toml",
    // Which repositories the self-healing loop watches, TOML
    // (`car_server_core::coder::heal_config`). CAR reads it and never writes
    // it.
    "heal.toml",
    // CarHost's multiplayer stages (`apps/host-macos`, `MultiplayerStore`;
    // the Windows host writes the same file). Owned by the app.
    "host-multiplayer-stages.json",
    // Where CarHost sets aside a `host-state.json` it could not read
    // (`CarHomeDefaults`). Never parsed or moved: it is the copy kept for a
    // person to look at.
    "host-state.json.corrupt",
];

/// Subdirectories CAR creates under `~/.car/`. Anything else at the top level is
/// reported as unrecognized (a possible leftover), never auto-removed.
const KNOWN_DIRS: &[&str] = &[
    // The headless Linux key store: one owner-only file per key.
    "secrets",
    "models",
    "journals",
    "logs",
    "agents",
    "runs",
    "run",
    "workflow-runs",
    "workflows",
    "tasks",
    "trajectories",
    "registry",
    "meetings",
    "speech-runtime",
    "visual-runtime",
    "coder",
    "projects",
    "memory",
    // `car reason` state — created by car-cli, holds model_profiles.json. CAR
    // makes it on the in-process path, so it exists on any machine that has run
    // `car reason` once, and doctor was reporting a live directory as possible
    // leftover debris from an older install.
    "reason",
    "doctor",
    "bin",
    "voiceprints",
    "sync",
    // Written by car-server-core::run_store for completed-proposal owner indexes.
    "proposal-completed-index",
    // Written by car-server's self-healing detection ledger.
    "selfheal",
    // The shared contribution graph's append-only JSONL log
    // (`car_commons::log::LOG_SUBDIR`).
    "commons",
    // Coordination-topology run records (`car_topology::journal::JOURNAL_SUBDIR`).
    "topology",
    // The `car feedback` spool (`car_cli::feedback::FEEDBACK_OUTBOX_DIR`), drained
    // by the daemon. This one is not merely noise: an entry here is a report the
    // person wrote and CAR has not yet been able to send, so inviting them to
    // "remove manually if you know they're stale" invites discarding it.
    "feedback-outbox",
    // Persistent Chromium profiles for the assistant's browser tools
    // (`car_server_core::assistant::browser_tools::BrowserProfile::dir`), one per
    // profile kind. Both exist as soon as the corresponding surface is used once.
    "browser-profile",
    "browser-profile-user",
    // Cross-daemon coordination root for model management — lock sentinels,
    // receipts and tombstones (`car_inference::model_management`). It sits beside
    // `models/` because it is derived from that directory's parent.
    ".car-model-management",
    // Install receipts, tombstones and journals for CAR-managed models
    // (`ModelManagementStore::management_state_dir`).
    "model-management",
    // CAR Lattice connections, pins and relay directory (car-server-core's
    // `lattice_connect` / `lattice_org`, beside the peer audit journal).
    "lattice",
    // Device certificates (`car_parslee::device_cert::CERT_DIR`).
    "peer-certs",
    // Private stores of runs bound to an organization
    // (`car_home::WORK_CONTEXTS_DIR`); doctor already walks their journals.
    "work-contexts",
    // Release-operator tool cache: `scripts/generate-appcast-entry.sh` keeps
    // the pinned Sparkle signing tools in `tools/sparkle`.
    "tools",
    // The default cache of `scripts/stage-onnxruntime.sh` (`ORT_STAGE_DIR`):
    // the pinned static ONNX Runtime that `car-voice` builds link offline
    // instead of downloading. A build cache, not debris (car-releases#90).
    "onnxruntime",
    // Per-agent log-scrub markers from a release before per-run log files
    // (`car_registry::supervisor::scrub_marker_path`). The supervisor never
    // reads one: it withholds that agent's old logs, then removes it.
    "agent-log-scrubs",
    // Supervised workers' specs, homes and records
    // (`car_registry::workers::WORKERS_DIR`, `worker_root`).
    "workers",
    // Staged worker bundle versions (`car_registry::workers::bundle_dir`).
    "bundles",
    // Worker label jobs and epochs (`car_registry::workers::labels_root`).
    "labels",
    // Per-caller refusal rows (`car_registry::workers::record_caller_refusal`).
    "agent-refusals",
    // The spend meter's keys, ledgers and clock (`car_registry::spend::SPEND_DIR`).
    "spend",
    // Declarative-agent run records, beside `declagents.json`
    // (`car_registry::agent_runs::AgentRunStore::beside_registry`).
    "agent-runs",
    // The auth- and host-token directory when `CAR_HOME` relocates the state
    // root (`car_daemon_client::auth_token::default_dir_in`). Holds the
    // credentials the running daemon checks every client against.
    "ai.parslee.car",
    // Per-agent start records, beside the manifest
    // (`car_registry::agent_env::starts_dir`).
    "agent-starts",
    // Signed-in dashboard browsers' public keys and the sign-in generation
    // (`car_server_core::dashboard_sign_in::sign_ins_dir`).
    "ui-sign-ins",
    // Outside credentials the daemon admits
    // (`car_server_core::credential_store::CredentialStore::open`).
    "credentials",
    // Worktrees for peers' coding subtasks (`car_server_core::fleet`).
    "fleet-worker",
    // A run's proposal bookkeeping, beside `runs/` and
    // `proposal-completed-index/` (`car_server_core::run_store`): pending
    // finalizations, execution markers, retry rollbacks, proposal-id claims
    // and completed responses.
    "proposal-finalization",
    "proposal-execution",
    "proposal-retry-rollbacks",
    "proposal-id-claims",
    "proposal-completed",
    // CarHost's chats and work when `CAR_HOME` relocates the state root
    // (`apps/host-macos`, `HostSupportDirectory`); otherwise they live in
    // Application Support.
    "CarHost",
    // Workflow `Dedup` steps' seen-sets (`car_workflow`'s default dedup dir).
    "workflow-dedup",
    // The operator's own policy rules, read by the tool gate
    // (`car_policy::tool_gate`) and when the daemon resolves an agent's
    // secrets. CAR reads them and never writes them.
    "policies",
];

/// File-name suffixes for volatile/runtime artifacts that are never "leftovers":
/// lockfiles, temp/backup files, binary caches, and append-only logs.
const TOLERATED_SUFFIXES: &[&str] = &[".lock", ".tmp", ".bak", ".bin", ".jsonl"];

/// The on-disk version stamp (`~/.car/version.json`). Written by the daemon on
/// boot and refreshed by `doctor --repair`; read by `doctor` to detect skew
/// between the binary and the state it's operating on.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionStamp {
    /// The CAR package version (`CARGO_PKG_VERSION`) that last wrote state.
    pub car_version: String,
    /// The state-schema generation. Bumped only on a breaking change to the
    /// on-disk layout, independent of the package version. A reader newer than
    /// this can migrate; older than this should refuse rather than corrupt.
    pub state_schema_version: u32,
    /// The version that wrote the state THIS stamp replaced — the predecessor
    /// carried across the most recent upgrade.
    ///
    /// Without it, skew detection was dead on arrival (car#881): the daemon
    /// stamps on every boot and CarHost is a login item, so by the time anyone
    /// runs `car doctor` the stamp already reads as the running binary and the
    /// evidence that older state exists is gone. Observed directly — a stamp
    /// saying `0.47.0` beside an `agents.json` last written in the v0.39 era.
    ///
    /// Only updated when the version actually CHANGES. Rewriting it on every
    /// boot would collapse it to the current version and lose the real
    /// predecessor after one restart, which is the same bug one level down.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_car_version: Option<String>,
    /// The schema generation of the state this stamp replaced. Same update rule.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_state_schema_version: Option<u32>,
}

/// The current state-schema generation this binary writes/expects. Start at 1;
/// bump when a `~/.car` layout change requires migration.
pub const STATE_SCHEMA_VERSION: u32 = 1;

impl VersionStamp {
    /// The stamp this binary would write on a machine with no prior state.
    pub fn current() -> Self {
        VersionStamp {
            car_version: env!("CARGO_PKG_VERSION").to_string(),
            state_schema_version: STATE_SCHEMA_VERSION,
            previous_car_version: None,
            previous_state_schema_version: None,
        }
    }

    /// The stamp to write now, given what is already on disk.
    ///
    /// Carries the predecessor forward rather than overwriting it: an upgrade
    /// records what it replaced, and every later boot on the same version keeps
    /// that record instead of collapsing it to itself.
    pub fn succeeding(existing: Option<&VersionStamp>) -> Self {
        let mut next = VersionStamp::current();
        if let Some(prior) = existing {
            if prior.car_version != next.car_version
                || prior.state_schema_version != next.state_schema_version
            {
                next.previous_car_version = Some(prior.car_version.clone());
                next.previous_state_schema_version = Some(prior.state_schema_version);
            } else {
                next.previous_car_version = prior.previous_car_version.clone();
                next.previous_state_schema_version = prior.previous_state_schema_version;
            }
        }
        next
    }
}

/// What stamping observed. Returned so the daemon can act on an upgrade instead
/// of silently erasing the evidence of one.
#[derive(Debug, Clone)]
pub struct StampTransition {
    /// The stamp found on disk, if any. `None` on a fresh install — or when the
    /// file was unreadable, which is deliberately not distinguished here: both
    /// mean "no usable predecessor", and doctor reports an unparseable stamp
    /// separately.
    pub previous: Option<VersionStamp>,
    /// What was written.
    pub current: VersionStamp,
}

impl StampTransition {
    /// The package version changed since state was last written.
    pub fn upgraded(&self) -> bool {
        self.previous
            .as_ref()
            .is_some_and(|p| p.car_version != self.current.car_version)
    }

    /// On-disk state uses a schema generation NEWER than this binary
    /// understands — i.e. a downgrade.
    ///
    /// This is the case `STATE_SCHEMA_VERSION`'s own contract calls out ("older
    /// than this should refuse rather than corrupt") and that nothing acted on.
    /// A user reverting to an older CAR would silently operate on state written
    /// to a layout it does not know.
    pub fn schema_from_the_future(&self) -> bool {
        self.previous
            .as_ref()
            .is_some_and(|p| p.state_schema_version > self.current.state_schema_version)
    }
}

/// Canonical CAR **state** directory. Mirrors the resolution every other part
/// of CAR uses so `car doctor` always inspects the *same* directory the daemon
/// and registry write to.
///
/// That invariant is the whole point, and it is why this now honors `CAR_HOME`.
/// It used to refuse one, on the reasoning that "nothing else in CAR honors an
/// override, and a doctor that diagnoses a different dir than the real install
/// could report a corrupt install as healthy". The premise stopped being true
/// when `CAR_HOME` shipped: for a relocated daemon, `$CAR_HOME` *is* the real
/// install, and it is a doctor still reading `~/.car` that would grade the
/// wrong directory. The conclusion is unchanged — diagnose the install that is
/// actually running — so the resolution follows [`car_home::root_or_relative`]
/// wherever it goes.
///
/// State only, though. The same "diagnose what is running" argument cuts the
/// other way for model **weights**, which stay in the machine-shared
/// `~/.car/models` no matter where the state root points: following the
/// override there would make `car doctor` stop looking at the very cache the
/// relocated daemon loads from. [`diagnose`] therefore pairs this with
/// [`crate::default_models_dir`] instead of joining `models` onto it.
pub fn car_home() -> PathBuf {
    // `::` — this function shares its name with the crate it calls.
    ::car_home::root_or_relative()
}

/// Write/refresh the `version.json` stamp under `car_home`. Called on daemon
/// boot and by `doctor --repair`. Best-effort: a failure to stamp must never
/// block startup, so the caller logs and continues.
pub fn write_version_stamp(car_home: &Path) -> std::io::Result<()> {
    stamp_version(car_home).map(|_| ())
}

/// Read the existing stamp, write the succeeding one, and return both.
///
/// Read-before-write is the whole point (car#881). The old `write_version_stamp`
/// overwrote unconditionally, so the daemon destroyed the record of what wrote
/// the state before anything could look at it — and `car doctor`, the only
/// reader, runs solely when a human asks. Callers that care about an upgrade
/// call this and inspect [`StampTransition`].
pub fn stamp_version(car_home: &Path) -> std::io::Result<StampTransition> {
    std::fs::create_dir_all(car_home)?;
    let previous = read_version_stamp(car_home);
    let stamp = VersionStamp::succeeding(previous.as_ref());
    let json = serde_json::to_string_pretty(&stamp)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    // Atomic-ish: write a per-process temp file in the same dir, then rename
    // over. The pid-scoped name keeps two concurrent boots (or boot + repair)
    // from interleaving writes to one shared temp and tearing version.json.
    let tmp = car_home.join(format!("version.json.{}.tmp", std::process::id()));
    std::fs::write(&tmp, json)?;
    std::fs::rename(&tmp, car_home.join("version.json"))?;
    Ok(StampTransition {
        previous,
        current: stamp,
    })
}

/// Subdirectory of the state root for doctor-facing status records. It is in
/// [`KNOWN_DIRS`], so nothing written here is reported as older-install debris.
const DOCTOR_DIR: &str = "doctor";

/// The daemon's startup TMPDIR probe record, under [`DOCTOR_DIR`].
const DAEMON_TMPDIR_MARKER_FILE: &str = "daemon-tmpdir.json";

/// The daemon's startup host-role record, under [`DOCTOR_DIR`] (car#3404).
const DAEMON_AUTH_MODE_FILE: &str = "daemon-auth-mode.json";

/// Bytes the TMPDIR probe writes. Tiny on purpose: the probe proves the
/// directory accepts create and write (plus identity-safe remove on Unix and
/// delete-on-close cleanup on Windows).
const TMPDIR_PROBE_BYTES: &[u8] = b"car tmpdir probe\n";

/// What a daemon found when it probed its inherited `TMPDIR` at startup
/// (Parslee-ai/car#1494).
///
/// Every agent invocation creates a fresh scratch directory under the daemon's
/// `TMPDIR`. A daemon launched from inside the macOS installer can inherit a
/// `PKInstallSandbox` path that disappears when the install ends, and it keeps
/// that dead path for its whole lifetime, so every invocation fails while
/// `car doctor`, which never contacts the daemon, could not see why. The daemon
/// now leaves this record at `<CAR_HOME>/doctor/daemon-tmpdir.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonTmpdirMarker {
    /// Process id of the daemon that ran the probe.
    pub pid: u32,
    /// When that daemon ran the probe at startup, in Unix seconds.
    pub booted_at_unix: u64,
    /// CAR version of that daemon.
    pub car_version: String,
    /// Display form of the temp directory the daemon resolved
    /// (`std::env::temp_dir()`, which follows `TMPDIR` on Unix). Retained for
    /// human output and compatibility with legacy records.
    pub checked_path: String,
    /// Exact absolute path used for later rechecks, when it can be represented
    /// losslessly as UTF-8. Older records and non-UTF-8 paths omit this field;
    /// doctor then skips the recheck rather than guessing from `checked_path`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checked_path_absolute: Option<String>,
    /// The create/write probe succeeded. Cleanup failures are also failures,
    /// except when handle stat itself failed and cleanup could not be attempted;
    /// that narrower case is retained in [`Self::note`].
    pub ok: bool,
    /// The failing step and its OS error, when `ok` is false.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// A non-failing diagnostic, such as a handle-stat failure after create and
    /// write had already proved that the TMPDIR works.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// How doctor classifies a daemon TMPDIR record without contacting the daemon.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum DaemonTmpdirStatus {
    /// The daemon that wrote the record is still running, so this is the
    /// running daemon's result. A failed probe here makes the report unhealthy.
    Current { marker: DaemonTmpdirMarker },
    /// The running daemon's probe succeeded, but the checked directory has
    /// disappeared since startup. This makes the report unhealthy without
    /// misreporting the original probe as failed.
    CurrentPathGone { marker: DaemonTmpdirMarker },
    /// The running daemon's probe succeeded, but doctor could not stat the
    /// exact path later. Failing closed prevents a permission error from being
    /// rendered as OK while agent scratch creation fails.
    CurrentPathRecheckFailed {
        marker: DaemonTmpdirMarker,
        error: String,
    },
    /// The daemon that wrote the record is no longer running: no daemon is up,
    /// or a later one has not recorded. Shown, never a health failure.
    Stale { marker: DaemonTmpdirMarker },
    /// This platform has no liveness check, so the record cannot be tied to a
    /// running daemon. Shown with its result, never a health failure.
    Unverified { marker: DaemonTmpdirMarker },
    /// A record exists but could not be read or parsed. Informational: the
    /// next daemon start replaces it.
    Unreadable { error: String },
}

/// The daemon TMPDIR record as `car doctor` reports it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonTmpdirCheck {
    /// Where the record lives (`<CAR_HOME>/doctor/daemon-tmpdir.json`).
    pub marker_path: String,
    #[serde(flatten)]
    pub status: DaemonTmpdirStatus,
}

impl DaemonTmpdirCheck {
    /// A running daemon's failed probe, vanished TMPDIR, or failed path recheck
    /// is a problem. Stale, unverified and unreadable records are informational.
    pub fn is_failing(&self) -> bool {
        matches!(
            &self.status,
            DaemonTmpdirStatus::Current { marker } if !marker.ok
        ) || matches!(
            &self.status,
            DaemonTmpdirStatus::CurrentPathGone { .. }
                | DaemonTmpdirStatus::CurrentPathRecheckFailed { .. }
        )
    }
}

/// Where the daemon TMPDIR record lives under a state root.
pub fn daemon_tmpdir_marker_path(car_home: &Path) -> PathBuf {
    car_home.join(DOCTOR_DIR).join(DAEMON_TMPDIR_MARKER_FILE)
}

/// Probe `tmpdir` and record the result under `<car_home>/doctor/`. The daemon
/// calls this once at startup with `std::env::temp_dir()`.
///
/// The probe exclusively creates one uniquely named file in `tmpdir` (an
/// existing entry, symlink or not, is never opened) and writes a few bytes. On
/// Unix it removes that file only after checking the path still names the file
/// it created; on Windows the open handle requests delete-on-close, avoiding a
/// second path lookup. Other platforms leave the tiny probe file behind because
/// stable `std` exposes no portable file identity. The record is written to a
/// private temporary file beside the previous one and atomically replaced with
/// CAR's no-follow state helpers, so a reader sees the old record or the new
/// one, never a torn one.
///
/// A failed probe is still a successful record: `Ok` with `ok: false`. `Err`
/// means the record itself could not be written. Either way the caller carries
/// on, because this is a diagnostic and never a startup gate.
pub fn record_daemon_tmpdir_probe(
    car_home: &Path,
    tmpdir: &Path,
) -> std::io::Result<DaemonTmpdirMarker> {
    record_daemon_tmpdir_probe_result(car_home, tmpdir, probe_daemon_tmpdir(tmpdir))
}

/// Run only the filesystem round trip for the daemon TMPDIR probe.
///
/// Startup runs this on a dedicated thread, then records the returned outcome
/// itself. Keeping marker publication on the startup side prevents an abandoned
/// timed-out worker from later replacing the timeout record if its filesystem
/// operation eventually returns.
pub fn probe_daemon_tmpdir(tmpdir: &Path) -> Result<Option<String>, String> {
    probe_tmpdir(tmpdir, std::process::id())
}

/// Record an already-completed (or timed-out) daemon TMPDIR probe.
///
/// `result` is `Ok(None)` for an unqualified success, `Ok(Some(note))` for a
/// working TMPDIR with a non-failing diagnostic, and `Err(error)` for failure.
/// This is separate from [`probe_daemon_tmpdir`] so startup can impose a
/// deadline on TMPDIR I/O and still persist a timeout result from the
/// non-blocked side.
pub fn record_daemon_tmpdir_probe_result(
    car_home: &Path,
    tmpdir: &Path,
    result: Result<Option<String>, String>,
) -> std::io::Result<DaemonTmpdirMarker> {
    record_daemon_tmpdir_probe_result_with_cwd(car_home, tmpdir, result, std::env::current_dir())
}

fn record_daemon_tmpdir_probe_result_with_cwd(
    car_home: &Path,
    tmpdir: &Path,
    result: Result<Option<String>, String>,
    current_dir: std::io::Result<PathBuf>,
) -> std::io::Result<DaemonTmpdirMarker> {
    let (error, mut note) = match result {
        Ok(note) => (None, note),
        Err(error) => (Some(error), None),
    };
    let (checked_path_absolute, path_note) = exact_absolute_tmpdir_path(tmpdir, current_dir);
    append_note(&mut note, path_note);
    let marker = DaemonTmpdirMarker {
        pid: std::process::id(),
        booted_at_unix: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        car_version: env!("CARGO_PKG_VERSION").to_string(),
        checked_path: tmpdir.display().to_string(),
        checked_path_absolute,
        ok: error.is_none(),
        error,
        note,
    };
    write_daemon_tmpdir_marker(car_home, &marker)?;
    Ok(marker)
}

fn exact_absolute_tmpdir_path(
    tmpdir: &Path,
    current_dir: std::io::Result<PathBuf>,
) -> (Option<String>, Option<String>) {
    let absolute = if tmpdir.is_absolute() {
        tmpdir.to_path_buf()
    } else {
        let current_dir = match current_dir {
            Ok(current_dir) => current_dir,
            Err(error) => {
                return (
                    None,
                    Some(format!(
                        "TMPDIR recheck skipped: could not capture the daemon working directory: {error}"
                    )),
                );
            }
        };
        current_dir.join(tmpdir)
    };
    match absolute.to_str() {
        Some(path) => (Some(path.to_string()), None),
        None => (
            None,
            Some(
                "TMPDIR recheck skipped: the exact absolute probe path is not valid UTF-8"
                    .to_string(),
            ),
        ),
    }
}

fn append_note(note: &mut Option<String>, additional: Option<String>) {
    let Some(additional) = additional else {
        return;
    };
    match note {
        Some(note) => {
            note.push_str("; ");
            note.push_str(&additional);
        }
        None => *note = Some(additional),
    }
}

/// Read the daemon TMPDIR record: `None` when there is none, `Some(Err)` when
/// one exists but cannot be read or parsed.
pub fn read_daemon_tmpdir_marker(car_home: &Path) -> Option<Result<DaemonTmpdirMarker, String>> {
    let text = match std::fs::read_to_string(daemon_tmpdir_marker_path(car_home)) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
        Err(e) => return Some(Err(e.to_string())),
    };
    Some(serde_json::from_str(&text).map_err(|e| e.to_string()))
}

/// A name suffix no earlier probe or record write used: the pid plus the
/// current time in nanoseconds.
fn unique_probe_suffix(pid: u32) -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{pid}.{nanos}")
}

/// One create/write/remove round trip in `tmpdir`, the operations an agent
/// scratch workspace needs. A successful result may carry a non-failing note.
fn probe_tmpdir(tmpdir: &Path, pid: u32) -> Result<Option<String>, String> {
    use std::io::Write;

    let path = tmpdir.join(format!(".car-tmpdir-probe.{}", unique_probe_suffix(pid)));
    // Follow directory symlinks by design: macOS normally reports TMPDIR below
    // /var/folders, while /var itself is a symlink to /private/var. The probe
    // must exercise the directory the daemon will actually use. Only the new
    // probe entry itself is protected against symlink substitution.
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        use windows::Win32::Storage::FileSystem::FILE_FLAG_DELETE_ON_CLOSE;

        // The kernel removes exactly this newly-created file when the handle
        // closes, so Windows needs no race-prone second path lookup.
        options.custom_flags(FILE_FLAG_DELETE_ON_CLOSE.0);
    }
    let mut file = options
        .open(&path)
        .map_err(|e| format!("create failed: {e}"))?;
    let created = file.metadata().map_err(|e| format!("stat failed: {e}"));
    let wrote = file
        .write_all(TMPDIR_PROBE_BYTES)
        .map_err(|e| format!("write failed: {e}"));
    drop(file);

    // A failed handle stat must not short-circuit cleanup handling. Unix cannot
    // safely unlink without the identity; Windows already armed delete-on-close.
    let removed = cleanup_probe_file(&path, &created);
    combine_probe_results(created.map(|_| ()), wrote, removed)
}

fn cleanup_probe_file(
    path: &Path,
    created: &Result<std::fs::Metadata, String>,
) -> Result<(), String> {
    match created {
        Ok(created) => remove_probe_file(path, created),
        #[cfg(windows)]
        Err(_) => Ok(()),
        #[cfg(not(windows))]
        Err(_) => Err(format!(
            "cleanup skipped: probe file identity could not be proven; left {}",
            path.display()
        )),
    }
}

fn combine_probe_results(
    stat: Result<(), String>,
    write: Result<(), String>,
    cleanup: Result<(), String>,
) -> Result<Option<String>, String> {
    match (stat, write, cleanup) {
        (Ok(()), Ok(()), Ok(())) => Ok(None),
        (Err(stat), Ok(()), Ok(())) => Ok(Some(stat)),
        (Err(stat), Ok(()), Err(cleanup)) => Ok(Some(format!("{stat}; {cleanup}"))),
        (Ok(()), Ok(()), Err(cleanup)) => Err(cleanup),
        (stat, Err(write), cleanup) => {
            let mut errors = Vec::new();
            if let Err(stat) = stat {
                errors.push(stat);
            }
            errors.push(write);
            if let Err(cleanup) = cleanup {
                errors.push(cleanup);
            }
            Err(errors.join("; "))
        }
    }
}

/// Remove the probe file, but only while `path` still names the regular file
/// the probe created. Anything else at that path is left alone.
#[cfg(unix)]
fn remove_probe_file(path: &Path, created: &std::fs::Metadata) -> Result<(), String> {
    use std::os::unix::fs::MetadataExt;

    // This is intentionally the last check before unlink: compare the open
    // handle's (dev, ino) with no-follow path metadata, and reject symlinks.
    let on_disk = std::fs::symlink_metadata(path).map_err(|e| format!("remove failed: {e}"))?;
    if !on_disk.file_type().is_file()
        || created.dev() != on_disk.dev()
        || created.ino() != on_disk.ino()
    {
        return Err(
            "remove skipped: the probe path no longer names the file the probe created".to_string(),
        );
    }
    std::fs::remove_file(path).map_err(|e| format!("remove failed: {e}"))
}

#[cfg(not(unix))]
fn remove_probe_file(_path: &Path, _created: &std::fs::Metadata) -> Result<(), String> {
    // Windows already requested delete-on-close on the open handle. Other
    // non-Unix platforms have no portable identity comparison in stable std,
    // so a successful create/write leaves the tiny uniquely named file rather
    // than unlinking a path an attacker could have substituted.
    Ok(())
}

/// Write `marker` to a new private temporary file beside the record and use
/// CAR's no-follow atomic state-file replacement to publish it.
fn write_daemon_tmpdir_marker(car_home: &Path, marker: &DaemonTmpdirMarker) -> std::io::Result<()> {
    write_doctor_record(car_home, DAEMON_TMPDIR_MARKER_FILE, marker.pid, marker)
}

/// Publish one doctor-facing record as `<car_home>/doctor/<file_name>`: a new
/// private temporary file beside it, then CAR's no-follow atomic replacement.
fn write_doctor_record<T: Serialize>(
    car_home: &Path,
    file_name: &str,
    pid: u32,
    record: &T,
) -> std::io::Result<()> {
    use std::io::Write;

    let dir = car_home.join(DOCTOR_DIR);
    // Unlike TMPDIR, CAR state directories must never be followed through a
    // symlink. This helper securely walks and validates the path on Unix and
    // Windows rather than relying on a check followed by a path-based open.
    car_secrets::ensure_private_dir(&dir)?;
    let mut json = serde_json::to_vec_pretty(record)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    json.push(b'\n');
    let tmp = dir.join(format!("{file_name}.{}.tmp", unique_probe_suffix(pid)));
    // The state helper uses create-new plus O_NOFOLLOW/reparse-point checks and
    // validates the opened file. On a later error the private temp is left in
    // place: path-based cleanup would reintroduce the substitution race these
    // helpers close.
    let mut file = car_secrets::create_private_file(&tmp)?;
    file.write_all(&json)?;
    car_secrets::atomic_replace_private_file(&tmp, &dir.join(file_name))
}

/// What a daemon recorded at startup about its host role (car#3404).
///
/// A daemon with no host token installed is in single-principal mode: its
/// host-management gate admits every authenticated client. `car doctor` never
/// contacts the daemon, so the daemon leaves this record at
/// `<CAR_HOME>/doctor/daemon-auth-mode.json` on every start, written once its
/// auth setup is done. Every start rewrites it, so a later start with a host
/// token replaces an earlier single-principal record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonAuthModeMarker {
    /// Process id of the daemon that wrote the record.
    pub pid: u32,
    /// When that daemon wrote it at startup, in Unix seconds.
    pub booted_at_unix: u64,
    /// CAR version of that daemon.
    pub car_version: String,
    /// No host token is installed, so no session is the host and every
    /// host-management method refuses.
    pub single_principal: bool,
    /// Why no host token is installed: `--no-auth`, or the failed host-token
    /// write and its error. Absent from records written before PR 6d.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cause: Option<String>,
}

/// Where the daemon host-role record lives under a state root.
pub fn daemon_auth_mode_marker_path(car_home: &Path) -> PathBuf {
    car_home.join(DOCTOR_DIR).join(DAEMON_AUTH_MODE_FILE)
}

/// Record this daemon's host-role mode under `<car_home>/doctor/`. The daemon
/// calls this once at startup, after its auth setup, holding the primary-daemon
/// lock for `car_home`. `Err` means the record could not be written; the
/// caller logs it and carries on, because this is a diagnostic and never a
/// startup gate. An embedder that builds its own server state gets the
/// `single_principal_mode` result field but no doctor record unless it calls
/// this itself.
pub fn record_daemon_auth_mode(
    car_home: &Path,
    single_principal: bool,
    cause: Option<String>,
) -> std::io::Result<DaemonAuthModeMarker> {
    let marker = DaemonAuthModeMarker {
        pid: std::process::id(),
        booted_at_unix: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        car_version: env!("CARGO_PKG_VERSION").to_string(),
        single_principal,
        cause: if single_principal { cause } else { None },
    };
    write_doctor_record(car_home, DAEMON_AUTH_MODE_FILE, marker.pid, &marker)?;
    Ok(marker)
}

/// Whether the daemon running on `car_home` recorded single-principal mode.
///
/// True only for a readable record whose writer is still running: a record
/// left by a daemon that has exited describes no daemon at all, and an
/// unreadable one is replaced by the next start. Liveness is the pid check the
/// TMPDIR record uses, with the same accepted pid-reuse imprecision.
pub fn running_daemon_is_single_principal(car_home: &Path) -> bool {
    running_daemon_host_role_unavailable(car_home).is_some()
}

/// When the daemon running on `car_home` recorded that it has no host token:
/// `Some(cause)`, where the cause is `None` for a record that predates causes.
/// `None` when it has one, or under the same rules as
/// [`running_daemon_is_single_principal`].
pub fn running_daemon_host_role_unavailable(car_home: &Path) -> Option<Option<String>> {
    use std::io::Read;

    // CAR's no-follow private reader: a symlink planted at the record path is
    // refused rather than followed.
    let mut text = String::new();
    let read = car_secrets::open_private_read(&daemon_auth_mode_marker_path(car_home))
        .and_then(|mut file| file.read_to_string(&mut text));
    if read.is_err() {
        return None;
    }
    let marker = serde_json::from_str::<DaemonAuthModeMarker>(&text).ok()?;
    (marker.single_principal && daemon_writer_alive(marker.pid) == Some(true))
        .then_some(marker.cause)
}

/// Classify a record. `writer_alive` is `Some` where this platform can check
/// the writer's pid, `None` where it cannot.
fn classify_daemon_tmpdir_marker(
    marker: DaemonTmpdirMarker,
    writer_alive: Option<bool>,
) -> DaemonTmpdirStatus {
    match writer_alive {
        Some(true) => DaemonTmpdirStatus::Current { marker },
        Some(false) => DaemonTmpdirStatus::Stale { marker },
        None => DaemonTmpdirStatus::Unverified { marker },
    }
}

/// Whether the daemon that wrote a record is still running, where that can be
/// checked without contacting it.
///
/// Staleness rests on the pid alone, never on the recorded time. A daemon
/// records only after it holds the primary-daemon lock for its `CAR_HOME`, so a
/// later boot replaces the record, and a record whose writer is gone means no
/// daemon is running or the running one has not recorded.
fn daemon_writer_alive(pid: u32) -> Option<bool> {
    process_alive(pid)
}

/// Whether process `pid` is running: `kill(pid, 0)` on Unix, `OpenProcess` plus
/// the exit code on Windows, and `None` where neither exists. Pid reuse reads
/// as alive on both, so a caller deciding whether to clean up after a process
/// errs toward keeping what it would remove.
pub fn process_alive(pid: u32) -> Option<bool> {
    #[cfg(unix)]
    {
        Some(unix_pid_alive(pid))
    }
    #[cfg(windows)]
    {
        Some(windows_pid_alive(pid))
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        None
    }
}

/// `kill(pid, 0)`, the same rule as `wait_for_parent_exit` in
/// `car-server/src/main.rs`: signal 0 sends nothing and only checks existence;
/// 0 or `EPERM` (alive, but not ours to signal) means alive, anything else
/// means gone.
///
/// Not proof against pid reuse, accepted exactly as that code accepts it: if
/// the writer exited and the OS recycled its pid onto an unrelated process,
/// this reads "alive" and a dead daemon's result is reported as current. Pids
/// are allocated sequentially, so that needs the counter to wrap onto the old
/// value, and re-running `car doctor` after relaunching CarHost clears it.
#[cfg(unix)]
fn unix_pid_alive(pid: u32) -> bool {
    // kill(2) reads 0 and negative pids as process groups, not a process.
    let Ok(pid) = libc::pid_t::try_from(pid) else {
        return false;
    };
    if pid <= 0 {
        return false;
    }
    // SAFETY: signal 0 delivers nothing; kill only checks that `pid` exists.
    let rc = unsafe { libc::kill(pid, 0) };
    rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

/// The Windows counterpart of `unix_pid_alive`, and the reason `car doctor` no
/// longer says "this platform cannot check whether that daemon is still
/// running" on the platform where a stale record is most likely.
///
/// (Deliberately not an intra-doc link: `unix_pid_alive` is `#[cfg(unix)]`, so
/// a link to it has no ungated definition and
/// `scripts/check-platform-gated-doc-links.py` rejects it.)
///
/// `OpenProcess` succeeding is **not** on its own proof of life: a process that
/// has exited keeps a queryable handle for as long as anyone holds one, so the
/// exit code has to be read as well. `STILL_ACTIVE` distinguishes them.
///
/// `ERROR_ACCESS_DENIED` means the process exists but this token may not query
/// it — the same situation `EPERM` describes on Unix, and read the same way.
///
/// Two inherited imprecisions, both matching the Unix side rather than being new:
/// pid reuse reads as alive, and a process that genuinely exited with code 259
/// is indistinguishable from a running one. Re-running `car doctor` after
/// relaunching the daemon clears either.
#[cfg(windows)]
fn windows_pid_alive(pid: u32) -> bool {
    use windows::Win32::Foundation::{CloseHandle, ERROR_ACCESS_DENIED, STILL_ACTIVE};
    use windows::Win32::System::Threading::{
        GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
    };

    if pid == 0 {
        return false;
    }

    // SAFETY: OpenProcess only opens a handle; an unknown pid is an error
    // return, not undefined behaviour.
    let handle = match unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } {
        Ok(handle) => handle,
        Err(error) if error.code() == ERROR_ACCESS_DENIED.to_hresult() => return true,
        Err(_) => return false,
    };

    let mut exit_code = 0u32;
    // SAFETY: `handle` was just returned by OpenProcess and is still open.
    let queried = unsafe { GetExitCodeProcess(handle, &mut exit_code) };
    // SAFETY: closing the handle this function opened, exactly once.
    let _ = unsafe { CloseHandle(handle) };

    queried.is_ok() && exit_code == STILL_ACTIVE.0 as u32
}

fn recheck_current_tmpdir_with<F>(status: DaemonTmpdirStatus, stat: F) -> DaemonTmpdirStatus
where
    F: FnOnce(&Path) -> std::io::Result<()>,
{
    let mut marker = match status {
        DaemonTmpdirStatus::Current { marker } => marker,
        status => return status,
    };
    if !marker.ok {
        return DaemonTmpdirStatus::Current { marker };
    }
    let Some(exact_path) = marker.checked_path_absolute.clone() else {
        append_note(
            &mut marker.note,
            Some(
                "TMPDIR recheck skipped: the startup record has no exact absolute probe path"
                    .to_string(),
            ),
        );
        return DaemonTmpdirStatus::Current { marker };
    };
    match stat(Path::new(&exact_path)) {
        Ok(()) => DaemonTmpdirStatus::Current { marker },
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            DaemonTmpdirStatus::CurrentPathGone { marker }
        }
        Err(error) => DaemonTmpdirStatus::CurrentPathRecheckFailed {
            marker,
            error: error.to_string(),
        },
    }
}

/// The daemon TMPDIR record as doctor reports it; `None` when there is none.
fn check_daemon_tmpdir(home: &Path) -> Option<DaemonTmpdirCheck> {
    let status = match read_daemon_tmpdir_marker(home)? {
        Ok(marker) => {
            let writer_alive = daemon_writer_alive(marker.pid);
            let status = classify_daemon_tmpdir_marker(marker, writer_alive);
            recheck_current_tmpdir_with(status, |path| std::fs::metadata(path).map(|_| ()))
        }
        Err(error) => DaemonTmpdirStatus::Unreadable { error },
    };
    Some(DaemonTmpdirCheck {
        marker_path: daemon_tmpdir_marker_path(home).display().to_string(),
        status,
    })
}

/// Options controlling a diagnosis run.
#[derive(Debug, Clone, Default)]
pub struct DoctorOptions {
    /// Deep-verify model weights (recompute sha256 vs etag) instead of the cheap
    /// resolves-and-non-empty check. Slow (hashes every weight) but catches
    /// truncated-but-non-empty corruption.
    pub deep: bool,
    /// Apply safe repairs: purge corrupt cache files, back up unparseable state,
    /// refresh the version stamp.
    pub repair: bool,
}

/// Verdict for a single `~/.car` JSON state file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum StateFileStatus {
    /// Not present — fine; most state files are created on first use.
    Absent,
    /// Present and parses as JSON.
    Ok { schema_version: Option<u32> },
    /// Present but does not parse — corrupt or written by an incompatible
    /// version. `backed_up_to` is set when `--repair` moved it aside.
    Unparseable {
        error: String,
        backed_up_to: Option<String>,
    },
}

/// One state-file check.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateFileCheck {
    pub name: String,
    #[serde(flatten)]
    pub status: StateFileStatus,
}

/// Verdict for one installed model directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum ModelStatus {
    /// Weight files present and (for `--deep`) hash-verified.
    Healthy,
    /// At least one weight file is corrupt/missing. `purged` is how many were
    /// removed in `--repair` mode (so the next pull re-downloads them).
    Corrupt {
        bad_files: Vec<String>,
        purged: usize,
    },
    /// The directory looks like a model install — it has `config.json` /
    /// tokenizer stubs — but carries no resolvable weights at all. This is what
    /// an interrupted `car models pull` leaves behind, and it used to be
    /// invisible: `check_one_model` returned `None` for any dir with no weight
    /// files, so the report dropped it and `car doctor` said "none installed /
    /// Healthy" over a broken install (Parslee-ai/car#616).
    ///
    /// Note the loader already knew: `registry::ensure_local` gates reuse on
    /// `mlx_dir_has_weights` and re-downloads a config-only stub
    /// (car-releases#391). The diagnostic just disagreed with the runtime.
    Incomplete {
        detail: String,
        /// `--repair` cleared the directory (its links into the HuggingFace
        /// cache, never the cache itself), so `car models pull` starts clean.
        #[serde(default)]
        purged: bool,
        /// A curated upgrade rule (`car models upgrades`) replaces this model,
        /// and the replacement is installed. Such an install is removable,
        /// not something to re-pull (car-releases#90).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        superseded_by: Option<String>,
    },
}

/// A file left behind by an interrupted download.
///
/// Reported; `--repair` deletes only the ones marked `reclaimable` — see
/// [`find_leftovers_in`] for why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Leftover {
    pub path: String,
    pub bytes: u64,
    /// Seconds since the file was last written, when the filesystem says. A
    /// partial nothing has written to in days is almost certainly abandoned;
    /// one written a minute ago probably belongs to a pull still running.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub age_secs: Option<u64>,
    /// Abandoned and CAR's to remove: in a repo CAR fetches whole, no writer
    /// holds its lock, and nothing has written it for
    /// [`crate::retire::ABANDONED_PARTIAL_SECS`]
    /// ([`crate::retire::abandoned_partials`]). `car doctor --repair` removes
    /// exactly these; every other partial may be a download still running or
    /// another tool's, and is left alone.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub reclaimable: bool,
}

/// One model check.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelCheck {
    pub name: String,
    #[serde(flatten)]
    pub status: ModelStatus,
}

/// Health of one CAR-managed Python runtime venv (`speech-runtime`,
/// `visual-runtime`).
///
/// These venvs are how CAR runs every model architecture its in-process Rust
/// MLX backend does not implement, so a broken one silently removes the entire
/// external-runtime shelf — vision, speech, and every newer LLM family — while
/// the directory still looks fully populated on disk. A venv's `bin/python` is
/// an absolute symlink into the interpreter that built it, so an ordinary
/// Homebrew upgrade (`python@3.13` rotated away) is enough to do it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeCheck {
    /// Directory name under `CAR_HOME` (e.g. `visual-runtime`).
    pub name: String,
    pub root: String,
    /// The venv directory exists. A runtime that was never provisioned is not
    /// unhealthy — it is simply absent, and provisions on first use.
    pub present: bool,
    /// The venv's interpreter actually runs. Only meaningful when `present`.
    pub interpreter_ok: bool,
}

impl RuntimeCheck {
    /// A runtime is broken when it exists but cannot run anything. Absent is
    /// fine (lazy-provisioned); present-and-working is fine.
    pub fn is_broken(&self) -> bool {
        self.present && !self.interpreter_ok
    }
}

/// The full diagnosis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoctorReport {
    pub car_home: String,
    /// The version of the binary that produced this report.
    pub binary_version: String,
    /// The version stamp found on disk, if any (None ⇒ never stamped).
    pub on_disk_stamp: Option<VersionStamp>,
    /// True when the on-disk stamp's version differs from the binary.
    ///
    /// Near-useless on a machine that runs the daemon: it stamps at boot, so
    /// this reads false from then on. [`DoctorReport::carried_from_version`] is
    /// the field that survives (car#881).
    pub version_skew: bool,
    /// The version that wrote the state this install carried across its most
    /// recent upgrade, when the stamp recorded one.
    ///
    /// Unlike `version_skew` this outlives the daemon's boot stamp, so "state
    /// here predates the running binary" stays answerable rather than being
    /// erased seconds after it became true.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub carried_from_version: Option<String>,
    /// On-disk state uses a schema generation NEWER than this binary knows —
    /// a downgrade. `STATE_SCHEMA_VERSION` documents that a reader older than
    /// the state "should refuse rather than corrupt"; nothing enforced it.
    #[serde(default)]
    pub schema_from_the_future: bool,
    pub state_files: Vec<StateFileCheck>,
    pub models: Vec<ModelCheck>,
    /// Models whose CAR-managed weights are physically ready, using the same
    /// registry predicate as `models.list_unified`.
    #[serde(default)]
    pub installed_models: usize,
    /// Partial downloads abandoned in the HuggingFace cache. Informational —
    /// they waste disk but nothing is broken, so they don't affect
    /// [`DoctorReport::is_healthy`].
    #[serde(default)]
    pub leftovers: Vec<Leftover>,
    /// Directories named for models the signed catalog revoked that still hold
    /// real files. Informational like `leftovers`: a revocation never deletes
    /// real bytes, so these wait for the user.
    #[serde(default)]
    pub revoked_copies: Vec<crate::retire::RevokedCopy>,
    /// Whether signed-catalog updates reach this machine, from the daemon's
    /// recorded checks. Informational: unreachable updates do not make the
    /// install unhealthy, and doctor never fetches.
    #[serde(default)]
    pub catalog: crate::catalog::CatalogFreshness,
    /// Health of the CAR-managed Python runtime venvs. Absent runtimes are
    /// omitted; only ones that exist are reported.
    #[serde(default)]
    pub runtimes: Vec<RuntimeCheck>,
    /// Top-level `~/.car` entries this version doesn't recognize.
    pub unrecognized: Vec<String>,
    /// Human-readable actions taken in `--repair` mode (empty otherwise).
    pub repairs: Vec<String>,
    /// The daemon's startup TMPDIR probe (Parslee-ai/car#1494), read from
    /// `<CAR_HOME>/doctor/daemon-tmpdir.json`. `None` when no daemon has
    /// recorded one, which is not an error; the key is then omitted, so a report
    /// without a record serializes exactly as before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daemon_tmpdir: Option<DaemonTmpdirCheck>,
    /// The running daemon recorded that it has no host token (car#3404), so
    /// nobody holds the host role and host-management methods refuse. Read
    /// from `<CAR_HOME>/doctor/daemon-auth-mode.json`. Informational, never a
    /// health failure: `--no-auth` is a supported posture. Omitted when false,
    /// so a report without it serializes exactly as before.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub daemon_single_principal: bool,
    /// Why that daemon has no host token, when it recorded a cause.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daemon_host_role_cause: Option<String>,
}

impl DoctorReport {
    /// True when nothing actionable was found (modulo unrecognized entries,
    /// which are informational).
    pub fn is_healthy(&self) -> bool {
        // `carried_from_version` is deliberately NOT a health signal — carrying
        // state across an upgrade is the normal case, and flagging it would make
        // every upgraded install permanently "unhealthy". Running against state
        // from a schema this binary does not know IS a problem.
        !self.schema_from_the_future
            && !self.version_skew
            && self
                .state_files
                .iter()
                .all(|f| !matches!(f.status, StateFileStatus::Unparseable { .. }))
            && self
                .models
                .iter()
                .all(|m| matches!(m.status, ModelStatus::Healthy))
            && self.runtimes.iter().all(|r| !r.is_broken())
            // A running daemon's failed probe, vanished TMPDIR, or failed
            // recheck counts. Stale/unverified/unreadable is informational.
            && !self
                .daemon_tmpdir
                .as_ref()
                .is_some_and(DaemonTmpdirCheck::is_failing)
    }
}

/// Run a diagnosis (and, if `opts.repair`, repairs) against the install that is
/// actually running: state under [`car_home`](fn@car_home), weights under the shared cache.
///
/// The two are the same tree by default and separate under `CAR_HOME`, which is
/// why they are passed separately. A relocated daemon still loads its weights
/// from `~/.car/models` — that cache is machine-global on purpose — so a doctor
/// that only looked under the state root would silently stop checking the
/// weights, which is the failure mode `car doctor` mainly exists to catch.
pub fn diagnose(opts: &DoctorOptions) -> DoctorReport {
    diagnose_at(&car_home(), &crate::default_models_dir(), opts)
}

/// Diagnosis against an explicit base dir, weights assumed at `<home>/models` —
/// the testable core, and the shape every caller wanted before `CAR_HOME` could
/// separate the two.
pub fn diagnose_in(home: &Path, opts: &DoctorOptions) -> DoctorReport {
    diagnose_at(home, &home.join("models"), opts)
}

/// Diagnosis with the state root and the weights cache named independently.
pub fn diagnose_at(home: &Path, models_dir: &Path, opts: &DoctorOptions) -> DoctorReport {
    let catalog_public_key = crate::catalog::catalog_public_key();
    let registry = crate::registry::UnifiedRegistry::new_with_session(
        home.to_path_buf(),
        models_dir.to_path_buf(),
        Some(&catalog_public_key),
        crate::registry::SessionProbe::Inert,
    );
    diagnose_at_with_registry(home, models_dir, opts, &registry, None)
}

/// Deterministic diagnosis seam for cross-crate tests.
///
/// This stays `#[doc(hidden)]` instead of feature-gated because dependency
/// crates' integration tests link `car-inference` without inheriting `cfg(test)`.
/// Unlike [`diagnose_at`], this loads only local models discovered below the
/// explicit weights directory, scans only the explicit Hugging Face hub root,
/// and never consults a credential/session probe. Production feedback and
/// doctor paths deliberately continue to use [`diagnose_at`].
#[doc(hidden)]
pub fn diagnose_at_isolated(
    home: &Path,
    models_dir: &Path,
    huggingface_hub_root: &Path,
    opts: &DoctorOptions,
) -> DoctorReport {
    let registry = crate::registry::UnifiedRegistry::new_isolated_for_diagnosis(
        home.to_path_buf(),
        models_dir.to_path_buf(),
    );
    diagnose_at_with_registry(
        home,
        models_dir,
        opts,
        &registry,
        Some(huggingface_hub_root),
    )
}

fn diagnose_at_with_registry(
    home: &Path,
    models_dir: &Path,
    opts: &DoctorOptions,
    registry: &crate::registry::UnifiedRegistry,
    huggingface_hub_root: Option<&Path>,
) -> DoctorReport {
    let mut repairs = Vec::new();

    // --- version stamp / skew ------------------------------------------------
    let on_disk_stamp = read_version_stamp(home);
    let binary = VersionStamp::current();
    let version_skew = on_disk_stamp
        .as_ref()
        .map(|s| {
            s.car_version != binary.car_version
                || s.state_schema_version != binary.state_schema_version
        })
        .unwrap_or(false);
    // Survives the daemon's boot stamp; `version_skew` does not.
    let carried_from_version = on_disk_stamp
        .as_ref()
        .and_then(|s| s.previous_car_version.clone());
    let schema_from_the_future = on_disk_stamp
        .as_ref()
        .is_some_and(|s| s.state_schema_version > binary.state_schema_version);

    // --- state files ---------------------------------------------------------
    let mut state_files = Vec::new();
    for name in KNOWN_STATE_FILES {
        state_files.push(check_state_file(home, name, opts, &mut repairs));
    }

    // --- models --------------------------------------------------------------
    // The isolated seam judges "inside the hub" against its own hub root.
    let default_hub = crate::hf_cache::hub_dir();
    let hub = huggingface_hub_root.unwrap_or(&default_hub);
    let facts = |name: &str| -> ManagedDirFacts {
        let Some(schema) = registry.all().find(|schema| schema.name == name) else {
            return ManagedDirFacts::default();
        };
        // An unreadable receipt counts as one: doctor never clears a directory
        // CAR's own ownership record might still name.
        let has_receipt = !matches!(
            crate::model_management::read_receipt(home, &schema.id),
            Ok(None)
        );
        let superseded_by = registry
            .curated_replacement(&schema.id)
            .filter(|to| {
                crate::registry::physical_weights_ready_with_huggingface_hub(
                    to,
                    models_dir,
                    huggingface_hub_root,
                )
            })
            .map(|to| to.id.clone());
        ManagedDirFacts {
            model_id: Some(schema.id.clone()),
            has_receipt,
            superseded_by,
            state_root: Some(home.to_path_buf()),
        }
    };
    let models = check_models_with(models_dir, hub, opts, &mut repairs, &facts);
    // Kept separate from `models`: those entries are per-directory integrity
    // checks, while this is the registry's physical installed-model count.
    let installed_models = registry
        .list()
        .into_iter()
        .filter(|schema| {
            schema.downloads_weights()
                && crate::registry::physical_weights_ready_with_huggingface_hub(
                    schema,
                    models_dir,
                    huggingface_hub_root,
                )
        })
        .count();

    // --- leftovers -----------------------------------------------------------
    // Ownership is the concierge's: builtin catalog rows plus what CAR
    // recorded downloading. Under `--repair` the abandoned partials in those
    // repos go first, through the same rule and the same re-check before each
    // unlink that concierge maintenance uses; what remains is reported.
    let owned = crate::retire::ownership(
        crate::retire::catalog_ownership(),
        crate::retire::recorded_files(home, hub),
    );
    if opts.repair {
        let (discarded, errors) = crate::retire::discard_abandoned_partials(hub, &owned);
        if !discarded.is_empty() {
            let bytes: u64 = discarded.iter().map(|(_, b)| b).sum();
            repairs.push(format!(
                "removed {} abandoned partial download(s) of CAR's ({bytes} bytes) from the HuggingFace cache",
                discarded.len()
            ));
        }
        for error in errors {
            repairs.push(format!(
                "could not remove an abandoned partial download: {error}"
            ));
        }
    }
    let leftovers = find_leftovers_in(hub, &owned);
    let revoked_copies = crate::retire::revoked_copies(home, models_dir);
    let catalog = crate::catalog::catalog_freshness_with_liveness(
        &crate::catalog::load_status(&crate::catalog::status_path(home)),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
    );
    let unrecognized = find_unrecognized(home);

    // --- refresh stamp on repair --------------------------------------------
    if opts.repair {
        // Only *report* a stamp refresh when the stamp actually moved. It was
        // rewritten and announced unconditionally, so `car doctor --repair` on
        // a perfectly healthy install always printed a line under "Repairs:",
        // implying something had been wrong (Parslee-ai/car#626). The write
        // still happens either way — it's cheap and makes a missing stamp
        // appear — but a no-op write is not a repair.
        let already_current = on_disk_stamp
            .as_ref()
            .map(|s| {
                s.car_version == binary.car_version
                    && s.state_schema_version == binary.state_schema_version
            })
            .unwrap_or(false);
        match write_version_stamp(home) {
            Ok(()) if !already_current => repairs.push(format!(
                "refreshed version stamp to {} (schema v{})",
                binary.car_version, binary.state_schema_version
            )),
            Ok(()) => {}
            Err(e) => repairs.push(format!("failed to refresh version stamp: {e}")),
        }
    }

    // --- reap empty journals on repair ---------------------------------------
    let empty_journals = find_empty_journals(home);
    if opts.repair && !empty_journals.is_empty() {
        let mut removed = 0usize;
        for p in &empty_journals {
            if std::fs::remove_file(p).is_ok() {
                removed += 1;
            }
        }
        if removed > 0 {
            repairs.push(format!(
                "removed {removed} empty event journal(s) from journals/"
            ));
        }
    }

    // --- managed Python runtimes --------------------------------------------
    let runtimes = check_runtimes(home);

    // --- daemon TMPDIR probe record (car#1494) --------------------------------
    let daemon_tmpdir = check_daemon_tmpdir(home);

    // --- daemon host-role record (car#3404) -----------------------------------
    let host_role_unavailable = running_daemon_host_role_unavailable(home);
    let daemon_single_principal = host_role_unavailable.is_some();
    let daemon_host_role_cause = host_role_unavailable.flatten();

    DoctorReport {
        car_home: home.display().to_string(),
        binary_version: binary.car_version,
        on_disk_stamp,
        version_skew,
        carried_from_version,
        schema_from_the_future,
        state_files,
        models,
        installed_models,
        leftovers,
        revoked_copies,
        catalog,
        runtimes,
        unrecognized,
        repairs,
        daemon_tmpdir,
        daemon_single_principal,
        daemon_host_role_cause,
    }
}

/// Directory names under `CAR_HOME` that hold a CAR-managed `uv` venv.
const MANAGED_RUNTIMES: &[&str] = &["speech-runtime", "visual-runtime"];

/// Check each managed Python runtime that has actually been provisioned.
///
/// Absent runtimes are skipped rather than reported unhealthy: they provision
/// on first use, so "not there yet" is the normal state on a fresh install and
/// flagging it would make every new machine read as broken.
fn check_runtimes(home: &Path) -> Vec<RuntimeCheck> {
    MANAGED_RUNTIMES
        .iter()
        .filter_map(|name| {
            let root = home.join(name);
            if !root.exists() {
                return None;
            }
            Some(RuntimeCheck {
                name: (*name).to_string(),
                root: root.display().to_string(),
                present: true,
                interpreter_ok: crate::managed_venv::interpreter_healthy(&root),
            })
        })
        .collect()
}

fn read_version_stamp(home: &Path) -> Option<VersionStamp> {
    let text = std::fs::read_to_string(home.join("version.json")).ok()?;
    serde_json::from_str(&text).ok()
}

fn check_state_file(
    home: &Path,
    name: &str,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
) -> StateFileCheck {
    let path = home.join(name);
    let is_jsonl = name.ends_with(".jsonl");
    let status = match std::fs::read_to_string(&path) {
        Err(_) => StateFileStatus::Absent,
        Ok(text) if text.trim().is_empty() => StateFileStatus::Ok {
            schema_version: None,
        },
        // JSONL (one JSON value per line) must be validated line-by-line — the
        // whole file is not a single JSON document.
        Ok(text) if is_jsonl => match jsonl_first_bad_line(&text) {
            None => StateFileStatus::Ok {
                schema_version: None,
            },
            Some(e) => unparseable(&path, name, e, opts, repairs),
        },
        Ok(text) => match serde_json::from_str::<serde_json::Value>(&text) {
            Ok(value) => StateFileStatus::Ok {
                schema_version: value
                    .get("schema_version")
                    .and_then(serde_json::Value::as_u64)
                    .map(|v| v as u32),
            },
            Err(e) => unparseable(&path, name, e.to_string(), opts, repairs),
        },
    };
    StateFileCheck {
        name: name.to_string(),
        status,
    }
}

/// Validate each non-empty line of a JSONL file; return the first parse error
/// (with its line number) or `None` if all lines are valid JSON.
fn jsonl_first_bad_line(text: &str) -> Option<String> {
    for (i, line) in text.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        if let Err(e) = serde_json::from_str::<serde_json::Value>(line) {
            return Some(format!("line {}: {e}", i + 1));
        }
    }
    None
}

/// Shared handling for an unparseable state file: in repair mode, move it aside
/// to `<name>.corrupt.bak` (never delete) so the owning crate writes a fresh
/// default on next run; otherwise just record the error.
fn unparseable(
    path: &Path,
    name: &str,
    error: String,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
) -> StateFileStatus {
    let backed_up_to = if opts.repair {
        // Don't clobber a previous backup — keeps the "never delete" promise
        // honest if the same file goes corrupt twice. First backup gets the
        // plain name; a collision falls back to an epoch-suffixed one.
        let plain = path.with_file_name(format!("{name}.corrupt.bak"));
        let bak = if plain.exists() {
            let epoch = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            path.with_file_name(format!("{name}.corrupt.{epoch}.bak"))
        } else {
            plain
        };
        match std::fs::rename(path, &bak) {
            Ok(()) => {
                repairs.push(format!("backed up unparseable {name} → {}", bak.display()));
                Some(bak.display().to_string())
            }
            Err(err) => {
                repairs.push(format!("failed to back up {name}: {err}"));
                None
            }
        }
    } else {
        None
    };
    StateFileStatus::Unparseable {
        error,
        backed_up_to,
    }
}

/// What the registry knows about a managed model directory, by directory name.
/// Empty for a directory no registered row names.
#[derive(Debug, Clone, Default)]
struct ManagedDirFacts {
    /// The registry row whose `name` is this directory.
    model_id: Option<String>,
    /// CAR holds an install receipt for that row: removal belongs to
    /// `car models remove`, which owns the receipt, never to doctor.
    has_receipt: bool,
    /// The curated replacement, when it is installed.
    superseded_by: Option<String>,
    /// The state root whose model-management store holds this model's
    /// receipts and whose locks a clearing must take.
    state_root: Option<PathBuf>,
}

/// [`check_models_with`] with nothing known from the registry.
#[cfg(test)]
fn check_models(
    models_dir: &Path,
    hub: &Path,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
) -> Vec<ModelCheck> {
    check_models_with(models_dir, hub, opts, repairs, &|_| {
        ManagedDirFacts::default()
    })
}

fn check_models_with(
    models_dir: &Path,
    hub: &Path,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
    facts: &dyn Fn(&str) -> ManagedDirFacts,
) -> Vec<ModelCheck> {
    let Ok(entries) = std::fs::read_dir(models_dir) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for entry in entries.filter_map(Result::ok) {
        let dir = entry.path();
        if !dir.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        // `.car-install-*` is a pull's private staging directory and
        // `.car-retire-*` a removal's quarantine. Neither is an install: a
        // staging dir holds symlinked manifests and no weights for the whole of
        // a live download, so judging it here would report — and under
        // `--repair` clear — a pull that is still running.
        if name.starts_with(".car-") {
            continue;
        }
        // Skip dirs with no weight files of their own: a managed MLX dir is
        // often just a config stub whose weights live in the HF snapshot cache,
        // and flagging that as broken would be a false positive. We only assess
        // weights that are actually present here.
        if let Some(status) = check_one_model(&dir, hub, opts, &name, repairs, &facts(&name)) {
            out.push(ModelCheck { name, status });
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

fn check_one_model(
    dir: &Path,
    hub: &Path,
    opts: &DoctorOptions,
    name: &str,
    repairs: &mut Vec<String>,
    facts: &ManagedDirFacts,
) -> Option<ModelStatus> {
    let weights = weight_files(dir);
    if weights.is_empty() {
        // No weight file of any kind — not even a dangling symlink (those DO
        // show up in `weight_files` and are caught as Corrupt below). Two very
        // different situations share this shape:
        //
        //   1. the dir isn't a model install at all — none of our business, and
        //      flagging it would be the false positive the old blanket `None`
        //      was protecting against;
        //   2. an install that got interrupted before its weights landed:
        //      `config.json` and the tokenizer stubs are there, the
        //      `*.safetensors` never arrived.
        //
        // Case 2 is exactly what a Ctrl-C'd `car models pull` leaves, and
        // returning `None` for it is what made a broken install read as
        // "Healthy" (Parslee-ai/car#616). Tell them apart on whether the dir
        // carries a model manifest.
        if is_interrupted_install(dir) {
            return Some(incomplete_status(dir, hub, opts, name, repairs, facts));
        }
        return None;
    }
    let mut bad_files = Vec::new();
    for w in &weights {
        let corrupt = if opts.deep {
            verify_cache_file(w) == CacheIntegrity::Corrupt
        } else {
            !cache_file_usable(w)
        };
        if corrupt {
            bad_files.push(
                w.file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
            );
        }
    }
    if bad_files.is_empty() {
        return Some(ModelStatus::Healthy);
    }
    // A model dir the person linked to their own storage is repaired there
    // too: only its own corrupt files go, and a link inside it loses at most
    // the link unless it resolves to a blob in the hub (Parslee-ai/car#2507).
    let purged = if opts.repair {
        let n = purge_corrupt_cache_files_in(dir, hub);
        if n > 0 {
            repairs.push(format!(
                "purged {n} corrupt file(s) from model '{name}' — re-pull with `car models pull {name}`"
            ));
        }
        n
    } else {
        0
    };
    Some(ModelStatus::Corrupt { bad_files, purged })
}

/// The report for an interrupted install, clearing it under `--repair`.
///
/// The remedy names commands that work from the state doctor found
/// (car-releases#87): `car models pull` alone used to be the advice, and it
/// refused the very directory doctor had just diagnosed.
fn incomplete_status(
    dir: &Path,
    hub: &Path,
    opts: &DoctorOptions,
    name: &str,
    repairs: &mut Vec<String>,
    facts: &ManagedDirFacts,
) -> ModelStatus {
    let pull_target = facts.model_id.as_deref().unwrap_or(name);
    let superseded_by = facts.superseded_by.clone();
    if facts.has_receipt {
        // CAR's receipt says it installed this; `car models remove` owns that
        // receipt and its journaled removal. Clearing the directory behind the
        // store's back would leave a receipt naming nothing.
        return ModelStatus::Incomplete {
            detail: format!(
                "installed by CAR, but no weights resolve — `car models remove {pull_target}`, \
                 then `car models pull {pull_target}`"
            ),
            purged: false,
            superseded_by,
        };
    }
    let mut purged = false;
    let mut refusal = None;
    if opts.repair {
        let models_dir = dir.parent().unwrap_or(dir);
        match clear_interrupted_install(models_dir, name, hub, facts) {
            Ok(()) => {
                purged = true;
                repairs.push(match &superseded_by {
                    Some(by) => format!(
                        "removed the interrupted install of '{name}' (superseded by {by}, which is installed; nothing to re-pull)"
                    ),
                    None => format!(
                        "removed the interrupted install of '{name}' — if you still want it, `car models pull {pull_target}`"
                    ),
                });
            }
            Err(reason) => {
                repairs.push(format!(
                    "left the interrupted install of '{name}' in place: {reason}"
                ));
                refusal = Some(reason);
            }
        }
    }
    let detail = match (purged, &superseded_by, refusal) {
        (true, Some(by), _) => format!(
            "no weights resolved; removed — superseded by {by}, which is installed, so there is nothing to re-pull"
        ),
        (true, None, _) => format!(
            "no weights resolved; removed — if you still want it, `car models pull {pull_target}`"
        ),
        (false, _, Some(reason)) => format!(
            "manifest linked into the HuggingFace cache but no weights resolve; not removed ({reason})"
        ),
        (false, Some(by), None) => format!(
            "manifest linked into the HuggingFace cache but no weights resolve, and {by} \
             (installed) supersedes it — remove it with `car doctor --repair`"
        ),
        (false, None, None) => format!(
            "manifest linked into the HuggingFace cache but no weights resolve — \
             `car doctor --repair` clears it; then, if you still want it, \
             `car models pull {pull_target}`"
        ),
    };
    ModelStatus::Incomplete {
        detail,
        purged,
        superseded_by,
    }
}

/// [`purge_interrupted_install`] for doctor, which, unlike `car models pull`
/// and a forced `car models remove`, does not already hold the model's
/// cross-process mutation lock. It takes it, so a pull, adoption or removal
/// of the same model in any process cannot run in between, and re-reads the
/// receipt under it: an install that finished since diagnosis owns the
/// directory now. A directory no registry row names has no lock to take and
/// no receipt to have, and is cleared on the purge's own checks.
fn clear_interrupted_install(
    models_dir: &Path,
    name: &str,
    hub: &Path,
    facts: &ManagedDirFacts,
) -> Result<(), String> {
    let (Some(state_root), Some(model_id)) = (&facts.state_root, &facts.model_id) else {
        return purge_interrupted_install(models_dir, name, hub);
    };
    let store = crate::model_management::ModelManagementStore::new(
        state_root.clone(),
        models_dir.to_path_buf(),
    );
    let _guard = match store.begin_mutation(model_id) {
        Ok(guard) => guard,
        Err(crate::model_management::ModelManagementError::MutationInProgress { .. }) => {
            return Err(
                "a pull, adoption or removal of it is running right now; run `car doctor --repair` again once it finishes"
                    .into(),
            )
        }
        Err(error) => return Err(format!("cannot take its model lock: {error}")),
    };
    match store.load_receipt(model_id) {
        Ok(None) => {}
        Ok(Some(_)) => {
            return Err(format!(
                "CAR now holds an install receipt for it; `car models remove {model_id}` owns it"
            ))
        }
        Err(error) => return Err(format!("its install receipt cannot be read: {error}")),
    }
    purge_interrupted_install(models_dir, name, hub)
}

/// Clear `models_dir/<name>`, a managed directory an interrupted pull left
/// with no resolvable weights, so the next `car models pull` starts clean
/// (car-releases#87). Shared by `car doctor --repair`, `car models pull` and a
/// forced `car models remove`, so all three clear exactly the same thing.
///
/// What it removes is only what a pull put there: links, and the manifest and
/// tokenizer files the copy fallback writes when a link cannot be made
/// ([`PULLED_REGULAR_FILES`], plus that fallback's own `.car-install-*.tmp`
/// staging copies). A real directory is emptied one entry at a time, never
/// recursively — regular files first and the links last, so a purge that
/// stops partway still leaves a linked manifest and is still recognized as an
/// interrupted install the next time — and the directory itself goes last
/// with `remove_dir`, which fails rather than delete anything left in it.
/// Anything a pull does not write — a subdirectory, any other regular file
/// (`weights.npz`, `pytorch_model.bin`, an adapter, someone's notes), a large
/// one — refuses the whole purge before anything is touched. The HuggingFace blobs those links point
/// at are never touched: the hub is shared with every other tool, and a
/// partial there may belong to a download still running.
///
/// A leaf that is itself a link (or a Windows junction) is removed as a link,
/// and only when it resolves into the HuggingFace hub — CAR's own projection.
/// A link to the person's own storage is theirs (Parslee-ai/car#2507) and is
/// left in place.
pub(crate) fn purge_interrupted_install(
    models_dir: &Path,
    name: &str,
    hub: &Path,
) -> Result<(), String> {
    use crate::model_management::{unlink_checked, UnlinkKind};

    let single_component = matches!(
        Path::new(name).components().collect::<Vec<_>>().as_slice(),
        [std::path::Component::Normal(_)]
    );
    if !single_component || name.starts_with('.') {
        return Err(format!("{name:?} is not a managed model directory name"));
    }
    let leaf = models_dir.join(name);
    let meta = std::fs::symlink_metadata(&leaf).map_err(|e| format!("cannot read it: {e}"))?;
    if !is_interrupted_install(&leaf) {
        return Err(
            "it is not an interrupted install (weights resolve, or no linked manifest)".into(),
        );
    }
    if is_link_or_junction(&meta) {
        let inside_hub = match (
            car_winenv::canonicalize(&leaf),
            car_winenv::canonicalize(hub),
        ) {
            (Ok(target), Ok(hub)) => target.starts_with(hub),
            _ => false,
        };
        if !inside_hub {
            return Err(
                "it links outside the HuggingFace cache, to storage that is not CAR's".into(),
            );
        }
        return unlink_checked(&leaf, UnlinkKind::Link).map_err(|e| format!("unlink failed: {e}"));
    }
    if !meta.is_dir() {
        return Err("it is not a directory".into());
    }
    for (path, kind) in purge_plan(&leaf)? {
        unlink_checked(&path, kind)
            .map_err(|e| format!("could not remove {}: {e}", path.display()))?;
    }
    std::fs::remove_dir(&leaf).map_err(|e| format!("could not remove the directory: {e}"))
}

/// Every removal [`purge_interrupted_install`] makes inside the real directory
/// `leaf`, in order, planned before any is made so a refusal leaves it intact.
/// Regular files come first and links last: the links are what marks this as
/// an interrupted install, so a purge that stops partway still leaves one, and
/// the next doctor, pull or forced remove still recognizes the directory.
fn purge_plan(leaf: &Path) -> Result<Vec<(PathBuf, crate::model_management::UnlinkKind)>, String> {
    use crate::model_management::UnlinkKind;

    // Generous for a `tokenizer.json`, far below any weight shard.
    const MAX_MANIFEST_BYTES: u64 = 64 * 1024 * 1024;

    let mut files = Vec::new();
    let mut links = Vec::new();
    let entries = std::fs::read_dir(leaf).map_err(|e| format!("cannot list it: {e}"))?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("cannot list it: {e}"))?;
        let path = entry.path();
        let meta = std::fs::symlink_metadata(&path)
            .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
        if is_link_or_junction(&meta) {
            links.push((path, UnlinkKind::Link));
        } else if meta.is_file() {
            let pulled = entry
                .file_name()
                .to_str()
                .is_some_and(is_pulled_regular_file);
            if !pulled || meta.len() > MAX_MANIFEST_BYTES {
                return Err(format!(
                    "it holds {}, which a pull does not leave behind",
                    path.display()
                ));
            }
            files.push((path, UnlinkKind::File));
        } else {
            return Err(format!(
                "it holds {}, which a pull does not leave behind",
                path.display()
            ));
        }
    }
    files.extend(links);
    Ok(files)
}

/// The regular files a pull can leave in a managed model directory: the
/// manifests [`is_interrupted_install`] looks for, the tokenizer assets the
/// pull fetches ([`crate::registry::TOKENIZER_FILENAMES`]), and the small
/// metadata files that sit beside them in the repos CAR pulls. A pull links
/// these into the HuggingFace cache and writes a regular file only through
/// its copy fallback, so this is the whole list.
const PULLED_REGULAR_FILES: &[&str] = &[
    "config.json",
    "model_index.json",
    "tokenizer.json",
    "tokenizer_config.json",
    "model.safetensors.index.json",
    "generation_config.json",
    "special_tokens_map.json",
    "added_tokens.json",
    "preprocessor_config.json",
    "chat_template.jinja",
    "chat_template.json",
];

/// Whether a regular file named `name` is one a pull writes: a
/// [`PULLED_REGULAR_FILES`] or tokenizer name, or the copy fallback's
/// `.<name>.car-install-<pid>-<n>.tmp` staging copy of one.
fn is_pulled_regular_file(name: &str) -> bool {
    let known = |n: &str| {
        PULLED_REGULAR_FILES.contains(&n) || crate::registry::TOKENIZER_FILENAMES.contains(&n)
    };
    if known(name) {
        return true;
    }
    name.strip_prefix('.')
        .and_then(|rest| rest.strip_suffix(".tmp"))
        .and_then(|rest| rest.split_once(".car-install-"))
        .is_some_and(|(original, _)| known(original))
}

/// A symbolic link, or on Windows any reparse point — a directory junction
/// made with `mklink /J` is not a symlink to `FileType`, and treating one as a
/// directory would walk into storage that is not CAR's.
fn is_link_or_junction(meta: &std::fs::Metadata) -> bool {
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
        if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return true;
        }
    }
    meta.file_type().is_symlink()
}

/// Weight files (`.safetensors` / `.gguf`) anywhere under a model dir. Recurses
/// to full depth so detection matches `purge_corrupt_cache_files`' recursion —
/// a corrupt weight nested ≥2 levels down (uncommon but possible) is still seen.
/// Cheap: no hashing here, just extension matching.
/// Is this a managed dir left half-built by an interrupted pull?
///
/// Called only for dirs with no weight file of any kind. Distinguishing an
/// interrupted install from a directory that was never a model needs care,
/// because over-eager flagging here is a known past false positive — see
/// `config_only_stub_is_skipped_not_flagged`, which pins a hand-made
/// config-only dir as *not* broken.
///
/// The discriminator is **how the manifest got there**. `car models pull`
/// populates a managed dir by symlinking into the HuggingFace snapshot cache
/// (`registry.rs`, "try symlink first"), writing the small config/tokenizer
/// files before the multi-gigabyte weights. So a dir that holds symlinked
/// manifest files but no resolvable weights is one CAR built and did not
/// finish — the exact residue of a Ctrl-C'd pull. A hand-made stub, or one
/// created by the copy fallback, has real files and no symlinks, and is left
/// alone.
///
/// Deliberately conservative: it under-reports (a stub whose links were later
/// cleaned up reads as "not a model") rather than resurrecting the false
/// positive. Weight *presence* uses the same `mlx_dir_has_weights` predicate
/// the loader gates on, so the diagnosis and the runtime agree — the whole
/// point of Parslee-ai/car#616, where `ensure_local` re-downloaded a stub the
/// doctor was calling healthy.
pub(crate) fn is_interrupted_install(dir: &Path) -> bool {
    const MANIFESTS: &[&str] = &[
        "config.json",
        "model_index.json",
        "tokenizer.json",
        "tokenizer_config.json",
        "model.safetensors.index.json",
    ];
    let has_symlinked_manifest = MANIFESTS.iter().any(|m| {
        let p = dir.join(m);
        std::fs::symlink_metadata(&p)
            .map(|meta| meta.file_type().is_symlink())
            .unwrap_or(false)
    });
    has_symlinked_manifest && !crate::registry::mlx_dir_has_weights(dir)
}

/// Zero-byte `*.jsonl` files in every journal directory inside the state root:
/// `<CAR_HOME>/journals/` and each work context's private `journals/`, as
/// listed by [`car_home::journal_dirs`], which never follows a symlink out of
/// the root. A linked journal file is not a regular file here either.
///
/// The daemon opens a journal per session; one that never executes a proposal
/// leaves an empty file behind and nothing reaps it, so they accumulate
/// indefinitely — 35 of 43 on the install that prompted this
/// (Parslee-ai/car#626).
///
/// Unlike the HuggingFace partials, these ARE safe for `--repair` to delete:
/// they live in CAR's own directory, a zero-length journal provably holds no
/// events, and `EventLog::load` on a missing file behaves the same as on an
/// empty one. Only exactly-zero-length files qualify — anything with a byte in
/// it is left alone.
fn find_empty_journals(home: &Path) -> Vec<PathBuf> {
    // Every journal directory, including the private ones of runs bound to an
    // organization.
    let mut out: Vec<PathBuf> = car_home::journal_dirs(home)
        .iter()
        .filter_map(|dir| std::fs::read_dir(dir).ok())
        .flatten()
        .filter_map(Result::ok)
        .filter(|e| {
            e.path().extension().and_then(|x| x.to_str()) == Some("jsonl")
                && e.metadata()
                    .map(|m| m.is_file() && m.len() == 0)
                    .unwrap_or(false)
        })
        .map(|e| e.path())
        .collect();
    out.sort();
    out
}

/// Partial downloads in the HuggingFace cache (`*.sync.part`, `.incomplete`).
///
/// Every one is reported with its size and age. Only those marked
/// `reclaimable` may be deleted, and only by `--repair`: a partial in a repo
/// CAR fetches whole (`owned`, the concierge's ownership), whose lock no writer
/// holds, untouched for [`crate::retire::ABANDONED_PARTIAL_SECS`]
/// ([`crate::retire::abandoned_partials`]). The rest stay. The shared HF cache
/// belongs to every tool on the machine, not just CAR, and a partial written
/// recently, or with its lock held, may belong to a download running *right
/// now* — removing it would corrupt a live transfer. In a repo CAR does not
/// own, it may be someone's paused download (Parslee-ai/car#616,
/// car-releases#87, car-releases#90).
///
/// Scans only `<cache>/hub/*/blobs/`, where hf-hub puts them, so this stays
/// cheap on a large cache rather than walking the whole tree.
fn find_leftovers_in(hub: &Path, owned: &crate::retire::Ownership) -> Vec<Leftover> {
    let reclaimable: std::collections::BTreeSet<PathBuf> =
        crate::retire::abandoned_partials(hub, owned)
            .into_iter()
            .collect();
    let mut out = Vec::new();
    let Ok(repos) = std::fs::read_dir(hub) else {
        return out;
    };
    for repo in repos.filter_map(Result::ok) {
        let blobs = repo.path().join("blobs");
        let Ok(entries) = std::fs::read_dir(&blobs) else {
            continue;
        };
        for e in entries.filter_map(Result::ok) {
            let p = e.path();
            let is_partial = p
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.ends_with(".sync.part") || n.ends_with(".incomplete"))
                .unwrap_or(false);
            if !is_partial {
                continue;
            }
            // Apparent size can far exceed blocks actually allocated (these are
            // written sparsely); `len()` is what the operator sees in `ls -lh`.
            let meta = e.metadata().ok();
            let bytes = meta.as_ref().map(|m| m.len()).unwrap_or(0);
            let age_secs = meta
                .and_then(|m| m.modified().ok())
                .and_then(|written| std::time::SystemTime::now().duration_since(written).ok())
                .map(|age| age.as_secs());
            out.push(Leftover {
                reclaimable: reclaimable.contains(&p),
                path: p.display().to_string(),
                bytes,
                age_secs,
            });
        }
    }
    out.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.path.cmp(&b.path)));
    out
}

fn weight_files(dir: &Path) -> Vec<PathBuf> {
    fn is_weight(p: &Path) -> bool {
        matches!(
            p.extension().and_then(|e| e.to_str()),
            Some("safetensors") | Some("gguf")
        )
    }
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return out;
    };
    for entry in entries.filter_map(Result::ok) {
        let p = entry.path();
        // `file_type` doesn't follow symlinks, so weight *symlinks* (the normal
        // case) are seen as files, not recursed into — only real subdirs recurse.
        if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            out.extend(weight_files(&p));
        } else if is_weight(&p) {
            out.push(p);
        }
    }
    out
}

fn find_unrecognized(home: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(home) else {
        return Vec::new();
    };
    let mut out: Vec<String> = entries
        .filter_map(Result::ok)
        .filter_map(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
            let known = if is_dir {
                KNOWN_DIRS.contains(&name.as_str())
            } else {
                KNOWN_STATE_FILES.contains(&name.as_str())
                    || KNOWN_NON_JSON_FILES.contains(&name.as_str())
                    // Volatile runtime artifacts (locks, temps, backups, binary
                    // caches, append-only logs) are not "leftovers".
                    || TOLERATED_SUFFIXES.iter().any(|s| name.ends_with(s))
                    // Hidden dotfiles are config/runtime, not leftovers.
                    || name.starts_with('.')
            };
            if known {
                None
            } else {
                Some(name)
            }
        })
        .collect();
    out.sort();
    out
}

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

    fn opts(deep: bool, repair: bool) -> DoctorOptions {
        DoctorOptions { deep, repair }
    }

    fn diagnose_repair_with_isolated_model_roots(home: &Path) -> DoctorReport {
        let models_dir = TempDir::new().unwrap();
        let huggingface_hub = TempDir::new().unwrap();
        let blobs = huggingface_hub.path().join("models--fixture/blobs");
        std::fs::create_dir_all(&blobs).unwrap();
        std::fs::write(blobs.join("isolated.sync.part"), b"partial").unwrap();

        let report = diagnose_at_isolated(
            home,
            models_dir.path(),
            huggingface_hub.path(),
            &opts(false, true),
        );
        assert_eq!(
            report.leftovers.len(),
            1,
            "the isolated seam must scan its injected Hugging Face root, not skip leftovers"
        );
        assert!(
            Path::new(&report.leftovers[0].path).starts_with(huggingface_hub.path()),
            "the leftover must come from the test-owned Hugging Face root"
        );
        report
    }

    #[test]
    fn clean_home_is_healthy() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("models.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join("models")).unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(r.is_healthy(), "clean home should be healthy: {r:?}");
        assert!(r.unrecognized.is_empty());
    }

    #[test]
    fn secret_index_is_recognized_not_a_leftover() {
        // The names-only secret index is a live current-version file (written by
        // the OS-keychain store on every platform). doctor once flagged it as a
        // possible older-install leftover and told the user to remove it — only
        // visible once a secret had been stored, e.g. after `car auth login` on
        // Windows. It must be recognized state, and it must parse as JSON.
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("models.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join("models")).unwrap();
        std::fs::write(tmp.path().join("secret_index.json"), r#"{"entries":[]}"#).unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(
            !r.unrecognized.contains(&"secret_index.json".to_string()),
            "secret_index.json must not be flagged as unrecognized: {:?}",
            r.unrecognized
        );
        assert!(
            r.is_healthy(),
            "home with a secret index should be healthy: {r:?}"
        );
    }

    #[test]
    fn unparseable_state_file_is_flagged_and_backed_up_on_repair() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("connectors.json"), "{not json").unwrap();

        // Read-only: flagged, not moved.
        let r = diagnose_in(tmp.path(), &opts(false, false));
        let c = r
            .state_files
            .iter()
            .find(|f| f.name == "connectors.json")
            .unwrap();
        assert!(matches!(
            c.status,
            StateFileStatus::Unparseable {
                backed_up_to: None,
                ..
            }
        ));
        assert!(!r.is_healthy());
        assert!(
            tmp.path().join("connectors.json").exists(),
            "untouched without --repair"
        );

        // Repair: moved to .corrupt.bak, original gone.
        let r = diagnose_in(tmp.path(), &opts(false, true));
        let c = r
            .state_files
            .iter()
            .find(|f| f.name == "connectors.json")
            .unwrap();
        assert!(matches!(
            c.status,
            StateFileStatus::Unparseable {
                backed_up_to: Some(_),
                ..
            }
        ));
        assert!(!tmp.path().join("connectors.json").exists());
        assert!(tmp.path().join("connectors.json.corrupt.bak").exists());
    }

    #[test]
    fn dotenv_env_file_is_never_parsed_or_moved() {
        // ~/.car/env is dotenv (KEY=VALUE), not JSON. It must be recognized
        // (not a leftover), never flagged Unparseable, and never moved aside by
        // --repair (it may still hold secrets).
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("env"),
            "ANTHROPIC_API_KEY=sk-secret\nFOO=bar\n",
        )
        .unwrap();

        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            r.is_healthy(),
            "dotenv env must not make the install unhealthy"
        );
        assert!(
            !r.unrecognized.contains(&"env".to_string()),
            "env is recognized"
        );
        assert!(
            r.state_files.iter().all(|f| f.name != "env"),
            "env is never JSON-checked"
        );
        assert!(
            tmp.path().join("env").exists(),
            "repair must not move the secrets file"
        );
        assert!(!tmp.path().join("env.corrupt.bak").exists());
    }

    #[test]
    fn empty_state_file_is_ok() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("messaging.json"), "").unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        let c = r
            .state_files
            .iter()
            .find(|f| f.name == "messaging.json")
            .unwrap();
        assert!(matches!(c.status, StateFileStatus::Ok { .. }));
    }

    /// Parslee-ai/car#616 — the residue of an interrupted `car models pull`:
    /// the small manifest files got symlinked into the HF snapshot, the weights
    /// never arrived. Observed live as `~/.car/models/Qwen3-4B-MLX/` holding
    /// three symlinks and nothing else, while `car doctor --deep --repair`
    /// reported "none installed / ✓ Healthy".
    #[test]
    #[cfg(unix)]
    fn interrupted_pull_is_reported_not_skipped() {
        let tmp = TempDir::new().unwrap();
        // Stand in for the HF snapshot the manifests link into.
        let snap = tmp.path().join("hfsnap");
        std::fs::create_dir_all(&snap).unwrap();
        std::fs::write(snap.join("config.json"), "{}").unwrap();
        std::fs::write(snap.join("tokenizer.json"), "{}").unwrap();

        let m = tmp.path().join("models").join("Qwen3-4B-MLX");
        std::fs::create_dir_all(&m).unwrap();
        std::os::unix::fs::symlink(snap.join("config.json"), m.join("config.json")).unwrap();
        std::os::unix::fs::symlink(snap.join("tokenizer.json"), m.join("tokenizer.json")).unwrap();
        // No *.safetensors anywhere — the pull died before the weights.

        let r = diagnose_in(tmp.path(), &opts(false, false));
        let check = r
            .models
            .iter()
            .find(|c| c.name == "Qwen3-4B-MLX")
            .expect("an interrupted install must appear in the report, not be dropped");
        assert!(
            matches!(check.status, ModelStatus::Incomplete { .. }),
            "expected Incomplete, got {:?}",
            check.status
        );
        assert!(
            !r.is_healthy(),
            "a half-installed model must not read as healthy"
        );
    }

    /// The other half of #616: abandoned partial downloads were invisible.
    /// Reported with sizes, and deliberately never deleted — the HF cache is
    /// shared, and a `.sync.part` may belong to a live transfer.
    #[test]
    fn abandoned_partial_downloads_are_reported_never_deleted() {
        let hf = TempDir::new().unwrap();
        let blobs = hf.path().join("hub").join("models--x--y").join("blobs");
        std::fs::create_dir_all(&blobs).unwrap();
        let part = blobs.join("deadbeef.sync.part");
        std::fs::write(&part, vec![0u8; 4096]).unwrap();
        std::fs::write(blobs.join("finished"), b"whole").unwrap();

        let home = TempDir::new().unwrap();
        // The hub is named explicitly rather than through the environment:
        // `HF_HUB_CACHE` on the machine running the suite would otherwise win.
        let r = diagnose_at_isolated(
            home.path(),
            &home.path().join("models"),
            &hf.path().join("hub"),
            &opts(false, true),
        );

        assert_eq!(
            r.leftovers.len(),
            1,
            "expected one partial: {:?}",
            r.leftovers
        );
        assert_eq!(r.leftovers[0].bytes, 4096);
        assert!(r.leftovers[0].path.ends_with("deadbeef.sync.part"));
        assert!(
            part.exists(),
            "--repair must NOT delete a partial: the HF cache is shared and the \
             transfer may still be running"
        );
        // Wasted disk is informational, not breakage.
        assert!(r.is_healthy());
    }

    /// Parslee-ai/car#626 — `--repair` on a healthy install listed "refreshed
    /// version stamp" every time, implying it had fixed something.
    #[test]
    fn repair_does_not_report_an_unchanged_version_stamp() {
        let tmp = TempDir::new().unwrap();
        // First repair on an unstamped home: the stamp genuinely appears.
        let first = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            first.repairs.iter().any(|r| r.contains("version stamp")),
            "writing a missing stamp IS a repair: {:?}",
            first.repairs
        );
        // Second repair, nothing changed: silence.
        let second = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            !second.repairs.iter().any(|r| r.contains("version stamp")),
            "an unchanged stamp is not a repair: {:?}",
            second.repairs
        );
    }

    /// Parslee-ai/car#626 — a journal per session that never executed anything
    /// left an empty file nobody reaped (35 of 43 on the reporting install).
    /// Safe for `--repair`: zero length provably means zero events.
    #[test]
    fn empty_journals_are_reaped_on_repair_only() {
        let tmp = TempDir::new().unwrap();
        let journals = tmp.path().join("journals");
        std::fs::create_dir_all(&journals).unwrap();
        let empty = journals.join("aaaaaaaaaaaa.jsonl");
        let full = journals.join("bbbbbbbbbbbb.jsonl");
        let other = journals.join("notes.txt");
        // A run bound to an organization journals in its private store.
        let private = tmp.path().join("work-contexts/work-fly/journals");
        std::fs::create_dir_all(&private).unwrap();
        let empty_private = private.join("cccccccccccc.jsonl");
        std::fs::write(&empty_private, b"").unwrap();
        std::fs::write(&empty, b"").unwrap();
        std::fs::write(&full, b"{\"kind\":\"proposal_received\"}\n").unwrap();
        std::fs::write(&other, b"").unwrap();

        // Read-only: nothing removed.
        let _ = diagnose_in(tmp.path(), &opts(false, false));
        assert!(empty.exists(), "no --repair, no deletion");

        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(!empty.exists(), "empty journal should be reaped");
        assert!(!empty_private.exists(), "a private store's too");
        assert!(full.exists(), "a journal with events must be kept");
        assert!(other.exists(), "non-.jsonl files are not ours to remove");
        assert!(
            r.repairs.iter().any(|x| x.contains("empty event journal")),
            "the reap should be reported: {:?}",
            r.repairs
        );
    }

    /// Parslee-ai/car#2507: a linked personal `journals/`, a linked work
    /// context, or a context whose `journals/` is a link, points outside the
    /// state root. Repair must not delete the empty `.jsonl` files there; a
    /// real context is still reaped.
    #[cfg(unix)]
    #[test]
    fn repair_never_follows_a_linked_work_context() {
        use std::os::unix::fs::symlink;
        let tmp = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        std::fs::create_dir_all(outside.path().join("journals")).unwrap();
        let keep = outside.path().join("journals/keep.jsonl");
        std::fs::write(&keep, b"").unwrap();

        let contexts = tmp.path().join("work-contexts");
        let real = contexts.join("work-real/journals");
        std::fs::create_dir_all(&real).unwrap();
        let empty_real = real.join("dddddddddddd.jsonl");
        std::fs::write(&empty_real, b"").unwrap();
        symlink(outside.path(), contexts.join("work-linked")).unwrap();
        std::fs::create_dir_all(contexts.join("work-journals-linked")).unwrap();
        symlink(
            outside.path().join("journals"),
            contexts.join("work-journals-linked/journals"),
        )
        .unwrap();

        // The personal `journals/` a link too (#2507 r1): its target's empty
        // journal is not CAR's either.
        let personal_target = outside.path().join("personal");
        std::fs::create_dir_all(&personal_target).unwrap();
        let foreign = personal_target.join("foreign.jsonl");
        std::fs::write(&foreign, b"").unwrap();
        symlink(&personal_target, tmp.path().join("journals")).unwrap();

        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            foreign.exists(),
            "a file behind a linked journals/ is not CAR's"
        );
        assert!(keep.exists(), "a file behind a linked context is not CAR's");
        assert!(!empty_real.exists(), "a real context is still reaped");
        assert!(
            r.repairs
                .iter()
                .any(|x| x.contains("removed 1 empty event journal")),
            "only the real context's journal is counted: {:?}",
            r.repairs
        );
    }

    /// A directory junction at `link` pointing at `target`, made the way a
    /// person would: `mklink /J` needs no privilege, where `symlink_dir` makes
    /// a symlink instead. Fails unless `link` is a reparse point that resolves.
    #[cfg(windows)]
    fn junction(target: &Path, link: &Path) {
        use std::os::windows::fs::MetadataExt;
        let status = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(link)
            .arg(target)
            .status()
            .unwrap();
        assert!(status.success(), "mklink /J {}", link.display());
        let meta = std::fs::symlink_metadata(link).unwrap();
        assert_ne!(
            meta.file_attributes() & 0x400,
            0,
            "{link:?} is a reparse point"
        );
        assert!(
            std::fs::metadata(link).unwrap().is_dir(),
            "{link:?} resolves"
        );
    }

    /// Parslee-ai/car#3125: the Windows form of the case above. A junctioned
    /// personal `journals/`, context entry or context `journals/` leads
    /// outside the state root; repair deletes no empty `.jsonl` behind any of
    /// them, and a real context is still reaped.
    #[cfg(windows)]
    #[test]
    fn repair_never_follows_a_junctioned_work_context() {
        let tmp = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let outside_journals = outside.path().join("journals");
        std::fs::create_dir_all(&outside_journals).unwrap();
        let keep = outside_journals.join("keep.jsonl");
        std::fs::write(&keep, b"").unwrap();

        let contexts = tmp.path().join("work-contexts");
        let real = contexts.join("work-real").join("journals");
        std::fs::create_dir_all(&real).unwrap();
        let empty_real = real.join("dddddddddddd.jsonl");
        std::fs::write(&empty_real, b"").unwrap();
        junction(outside.path(), &contexts.join("work-linked"));
        std::fs::create_dir_all(contexts.join("work-journals-linked")).unwrap();
        junction(
            &outside_journals,
            &contexts.join("work-journals-linked").join("journals"),
        );

        let personal_target = outside.path().join("personal");
        std::fs::create_dir_all(&personal_target).unwrap();
        let foreign = personal_target.join("foreign.jsonl");
        std::fs::write(&foreign, b"").unwrap();
        junction(&personal_target, &tmp.path().join("journals"));

        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            foreign.exists(),
            "a file behind a junctioned journals/ is not CAR's"
        );
        assert!(
            keep.exists(),
            "a file behind a junctioned context is not CAR's"
        );
        assert!(!empty_real.exists(), "a real context is still reaped");
        assert!(
            r.repairs
                .iter()
                .any(|x| x.contains("removed 1 empty event journal")),
            "only the real context's journal is counted: {:?}",
            r.repairs
        );
    }

    /// Parslee-ai/car#3125: a model dir junctioned to the person's own storage
    /// is still repaired there, but a junction inside it is not descended:
    /// the zero-length weight in the unrelated directory it leads to survives.
    #[cfg(windows)]
    #[test]
    fn repair_purges_a_junctioned_model_without_deleting_outside_its_target() {
        let tmp = TempDir::new().unwrap();
        let models = tmp.path().join("models");
        let hub = tmp.path().join("hub");
        std::fs::create_dir_all(&models).unwrap();
        std::fs::create_dir_all(&hub).unwrap();
        let external_dir = tmp.path().join("external-drive").join("Out");
        std::fs::create_dir_all(&external_dir).unwrap();
        let external = external_dir.join("model.safetensors");
        std::fs::write(&external, b"").unwrap();
        let unrelated_dir = tmp.path().join("unrelated");
        std::fs::create_dir_all(&unrelated_dir).unwrap();
        let unrelated = unrelated_dir.join("model.safetensors");
        std::fs::write(&unrelated, b"").unwrap();
        junction(&unrelated_dir, &external_dir.join("sub"));
        junction(&external_dir, &models.join("Out"));

        let mut repairs = Vec::new();
        let checks = check_models(&models, &hub, &opts(false, true), &mut repairs);
        let out = checks.iter().find(|c| c.name == "Out").unwrap();
        assert!(
            matches!(out.status, ModelStatus::Corrupt { purged, .. } if purged >= 1),
            "a junctioned model dir is diagnosed and repaired: {:?}",
            out.status
        );
        assert!(!external.exists(), "its own corrupt weight goes");
        assert!(
            unrelated.exists(),
            "a file behind a junction inside the model is not CAR's"
        );
    }

    #[test]
    fn config_only_stub_is_skipped_not_flagged() {
        // A managed dir with only a config (weights live in the HF cache) must
        // NOT be reported as broken — that was a false positive.
        let tmp = TempDir::new().unwrap();
        let m = tmp.path().join("models").join("Stub");
        std::fs::create_dir_all(&m).unwrap();
        std::fs::write(m.join("config.json"), "{}").unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(
            r.models.iter().all(|m| m.name != "Stub"),
            "stub should be skipped"
        );
        assert!(r.is_healthy());
    }

    #[cfg(unix)]
    #[test]
    fn corrupt_model_weight_is_purged_on_repair() {
        let tmp = TempDir::new().unwrap();
        let m = tmp.path().join("models").join("Qwen3-Test");
        std::fs::create_dir_all(&m).unwrap();
        // A dangling weight symlink reads as corrupt under the cheap check.
        std::os::unix::fs::symlink(m.join("gone"), m.join("model.safetensors")).unwrap();

        let r = diagnose_in(tmp.path(), &opts(false, false));
        let mc = r.models.iter().find(|m| m.name == "Qwen3-Test").unwrap();
        assert!(matches!(mc.status, ModelStatus::Corrupt { purged: 0, .. }));

        let r = diagnose_in(tmp.path(), &opts(false, true));
        let mc = r.models.iter().find(|m| m.name == "Qwen3-Test").unwrap();
        match &mc.status {
            ModelStatus::Corrupt { purged, .. } => assert_eq!(*purged, 1),
            other => panic!("expected Corrupt, got {other:?}"),
        }
        assert!(std::fs::symlink_metadata(m.join("model.safetensors")).is_err());
    }

    /// Parslee-ai/car#2507: a model dir linked to the person's own storage is
    /// still repaired there — its own zero-length weight goes — but a link
    /// inside it resolving outside that folder loses only the link. A model
    /// linked into the hub and a real model dir are purged as before.
    #[cfg(unix)]
    #[test]
    fn repair_purges_a_linked_model_without_deleting_outside_its_target() {
        use std::os::unix::fs::symlink;
        let tmp = TempDir::new().unwrap();
        let models = tmp.path().join("models");
        let hub = tmp.path().join("hub");
        std::fs::create_dir_all(&models).unwrap();
        let weight = |dir: &Path| {
            std::fs::create_dir_all(dir).unwrap();
            let file = dir.join("model.safetensors");
            std::fs::write(&file, b"").unwrap();
            file
        };
        let external = weight(&tmp.path().join("external-drive/Out"));
        let unrelated = tmp.path().join("unrelated/notes.txt");
        std::fs::create_dir_all(unrelated.parent().unwrap()).unwrap();
        std::fs::write(&unrelated, b"").unwrap();
        symlink(&unrelated, external.with_file_name("b.safetensors")).unwrap();
        symlink(external.parent().unwrap(), models.join("Out")).unwrap();
        let in_hub = weight(&hub.join("models--x--in/snapshots/rev"));
        symlink(in_hub.parent().unwrap(), models.join("In")).unwrap();
        let real = weight(&models.join("Real"));

        let mut repairs = Vec::new();
        let checks = check_models(&models, &hub, &opts(false, true), &mut repairs);
        let purged = |name: &str| match &checks.iter().find(|c| c.name == name).unwrap().status {
            ModelStatus::Corrupt { purged, .. } => *purged,
            other => panic!("{name}: expected Corrupt, got {other:?}"),
        };
        assert_eq!(purged("Out"), 2, "its weight and the inner link go");
        assert!(!external.exists(), "a linked model dir is still repaired");
        assert!(
            unrelated.exists(),
            "a file outside the linked folder is not CAR's"
        );
        assert_eq!(purged("In"), 1);
        assert!(!in_hub.exists());
        assert_eq!(purged("Real"), 1);
        assert!(!real.exists());
    }

    /// The isolated seam judges "inside the hub" against the hub root it was
    /// given: a corrupt blob there is purged with its link (#2507 r2).
    #[cfg(unix)]
    #[test]
    fn isolated_diagnosis_purges_blobs_in_its_own_hub() {
        let tmp = TempDir::new().unwrap();
        let hub = tmp.path().join("hub");
        let blob = hub.join("models--x--y/blobs").join("a".repeat(64));
        std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
        std::fs::write(&blob, b"").unwrap();
        let model = tmp.path().join("models/Y");
        std::fs::create_dir_all(&model).unwrap();
        std::os::unix::fs::symlink(&blob, model.join("model.safetensors")).unwrap();

        let _ = diagnose_at_isolated(
            tmp.path(),
            &tmp.path().join("models"),
            &hub,
            &opts(false, true),
        );
        assert!(!blob.exists(), "the isolated hub's corrupt blob is purged");
        assert!(std::fs::symlink_metadata(model.join("model.safetensors")).is_err());
    }

    #[test]
    fn shared_huggingface_weights_count_as_installed() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        std::fs::create_dir(&models_dir).unwrap();
        let huggingface_hub = tmp.path().join("huggingface-hub");
        let snapshot = huggingface_hub
            .join("models--example--doctor-only")
            .join("snapshots")
            .join("revision");
        std::fs::create_dir_all(&snapshot).unwrap();
        std::fs::write(snapshot.join("config.json"), b"{}").unwrap();
        std::fs::write(snapshot.join("model.safetensors"), b"weights").unwrap();

        let schema: crate::schema::ModelSchema = serde_json::from_value(serde_json::json!({
            "id": "example/doctor-only:4bit",
            "name": "doctor-only",
            "provider": "example",
            "family": "doctor-test",
            "capabilities": ["generate"],
            "context_length": 4096,
            "source": {
                "type": "mlx",
                "hf_repo": "example/doctor-only",
                "hf_weight_file": null
            }
        }))
        .unwrap();
        let mut registry = crate::registry::UnifiedRegistry::new_empty(models_dir.clone());
        registry.register(schema);

        let report = diagnose_at_with_registry(
            tmp.path(),
            &models_dir,
            &opts(false, false),
            &registry,
            Some(&huggingface_hub),
        );
        assert!(
            report.models.is_empty(),
            "shared-cache weights do not create a managed model directory check"
        );
        assert_eq!(
            report.installed_models, 1,
            "registry physical readiness must count shared-cache-only weights"
        );
    }

    /// Positive control: with any of these names removed from its allowlist
    /// this fails naming it. `messages-inbound-watermark.json` is
    /// car-releases#86 and `onnxruntime` car-releases#90; the cross-crate
    /// guard that drives the real writers is
    /// `car-cli/tests/doctor_state_writers.rs`.
    #[test]
    fn current_version_state_entries_are_recognized() {
        let tmp = TempDir::new().unwrap();
        for name in [
            "model-resource-policy.json",
            "parslee-auth-authority.json",
            "messages-inbound-watermark.json",
            "catalog-status.json",
            "identity.json",
            "work-contexts.json",
            "coder.toml",
            "concierge-auto-since",
            "host-state.json",
        ] {
            std::fs::write(tmp.path().join(name), b"{}").unwrap();
        }
        for name in [
            "proposal-completed-index",
            "selfheal",
            "onnxruntime",
            "model-management",
            "lattice",
            "peer-certs",
            "work-contexts",
            "tools",
        ] {
            std::fs::create_dir(tmp.path().join(name)).unwrap();
        }

        let unrecognized = find_unrecognized(tmp.path());
        assert!(
            unrecognized.is_empty(),
            "current-version state must not be reported as older-install debris: {unrecognized:?}"
        );
    }

    #[test]
    fn repair_never_json_validates_or_moves_the_binary_peer_identity_key() {
        let tmp = TempDir::new().unwrap();
        let key_path = tmp.path().join("peer-identity.key");
        let key_bytes = b"0123456789abcdef0123456789abcdef";
        std::fs::write(&key_path, key_bytes).unwrap();

        let report = diagnose_repair_with_isolated_model_roots(tmp.path());

        assert_eq!(
            std::fs::read(&key_path).unwrap(),
            key_bytes,
            "repair must preserve the binary peer identity byte-for-byte"
        );
        assert!(
            !tmp.path().join("peer-identity.key.corrupt.bak").exists(),
            "the non-JSON identity key must never be classified as corrupt JSON"
        );
        assert!(
            report
                .state_files
                .iter()
                .all(|file| file.name != "peer-identity.key"),
            "the peer identity belongs to the non-JSON allowlist"
        );
        assert!(
            !report
                .unrecognized
                .contains(&"peer-identity.key".to_string()),
            "the live identity key must be recognized"
        );
    }

    /// Exercises the known-non-JSON branch: invalid UTF-8 must bypass
    /// `check_state_file` (whose read-to-string error branch reports Absent),
    /// remain recognized by `find_unrecognized`, and survive repair untouched.
    #[test]
    fn repair_preserves_a_non_utf8_peer_identity_key() {
        let tmp = TempDir::new().unwrap();
        let key_path = tmp.path().join("peer-identity.key");
        let key_bytes = [0xff, 0xfe, 0xfd, 0x00, 0x80, 0x81, 0x82, 0x83];
        std::fs::write(&key_path, key_bytes).unwrap();

        let report = diagnose_repair_with_isolated_model_roots(tmp.path());

        assert_eq!(
            std::fs::read(&key_path).unwrap(),
            key_bytes,
            "repair must preserve genuinely non-UTF-8 identity bytes"
        );
        assert!(
            !tmp.path().join("peer-identity.key.corrupt.bak").exists(),
            "repair must not create a corrupt-JSON backup for a binary key"
        );
        assert!(
            report
                .state_files
                .iter()
                .all(|file| file.name != "peer-identity.key"),
            "the binary key must bypass the JSON state-file checker"
        );
        assert!(
            !report
                .unrecognized
                .contains(&"peer-identity.key".to_string()),
            "the binary key must take the recognized non-JSON branch"
        );
    }

    /// Directories CAR itself creates must never be offered up as leftovers.
    ///
    /// The report's wording is "possibly from an older install … remove manually
    /// if you know they're stale", so a live directory listed there is advice to
    /// delete working state. `feedback-outbox` is the sharp case: its entries are
    /// reports the person wrote that have not been sent yet.
    ///
    /// Positive control: with any of these four removed from `KNOWN_DIRS` this
    /// fails, naming the one that regressed. Observed on a real `~/.car` before
    /// the fix — `car doctor` listed `.car-model-management`, `browser-profile`
    /// and `feedback-outbox` together (car#1822-adjacent; same shape as the
    /// `reason` directory noted in `KNOWN_DIRS`).
    #[test]
    fn directories_car_creates_are_never_reported_as_leftovers() {
        let tmp = TempDir::new().unwrap();
        let live = [
            "feedback-outbox",
            "browser-profile",
            "browser-profile-user",
            ".car-model-management",
        ];
        for dir in live {
            std::fs::create_dir_all(tmp.path().join(dir)).unwrap();
        }

        let report = diagnose_in(tmp.path(), &opts(false, true));

        for dir in live {
            assert!(
                !report.unrecognized.contains(&dir.to_string()),
                "{dir} is created by CAR and must not be reported as a leftover; \
                 unrecognized = {:?}",
                report.unrecognized
            );
            assert!(tmp.path().join(dir).exists(), "{dir} must survive --repair");
        }
    }

    /// A managed directory an interrupted pull left — links into a hub
    /// snapshot, no shards — and the hub it points into.
    #[cfg(unix)]
    struct InterruptedInstall {
        _tmp: TempDir,
        home: PathBuf,
        models: PathBuf,
        hub: PathBuf,
        snapshot: PathBuf,
        dir: PathBuf,
    }

    #[cfg(unix)]
    fn interrupted_install(name: &str) -> InterruptedInstall {
        let tmp = TempDir::new().unwrap();
        let home = tmp.path().join("car-home");
        let models = home.join("models");
        let hub = tmp.path().join("hub");
        let snapshot = hub.join("models--org--repo/snapshots/rev");
        std::fs::create_dir_all(&snapshot).unwrap();
        // The index names a shard that never arrived — the issue's exact shape.
        let index = serde_json::json!({
            "weight_map": {"model.embed": "model-00001-of-00002.safetensors"}
        });
        for (file, body) in [
            ("config.json", "{}".to_string()),
            ("tokenizer.json", "{}".to_string()),
            ("model.safetensors.index.json", index.to_string()),
        ] {
            std::fs::write(snapshot.join(file), body).unwrap();
        }
        let dir = models.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        for file in [
            "config.json",
            "tokenizer.json",
            "model.safetensors.index.json",
        ] {
            std::os::unix::fs::symlink(snapshot.join(file), dir.join(file)).unwrap();
        }
        InterruptedInstall {
            _tmp: tmp,
            home,
            models,
            hub,
            snapshot,
            dir,
        }
    }

    #[cfg(unix)]
    fn incomplete(report: &DoctorReport, name: &str) -> (String, bool, Option<String>) {
        let check = report
            .models
            .iter()
            .find(|c| c.name == name)
            .unwrap_or_else(|| panic!("{name} missing from {:?}", report.models));
        match &check.status {
            ModelStatus::Incomplete {
                detail,
                purged,
                superseded_by,
            } => (detail.clone(), *purged, superseded_by.clone()),
            other => panic!("{name}: expected Incomplete, got {other:?}"),
        }
    }

    /// car-releases#87: `--repair` clears an interrupted install, reports it,
    /// and leaves the hub content its links pointed at alone. Without repair
    /// the remedy names a command that works from this state.
    #[cfg(unix)]
    #[test]
    fn repair_clears_an_interrupted_install_and_never_the_hub() {
        let fx = interrupted_install("Qwen3.5-9B-MLX-vLLM");

        let diagnosed = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, false));
        let (detail, purged, _) = incomplete(&diagnosed, "Qwen3.5-9B-MLX-vLLM");
        assert!(!purged);
        assert!(
            detail.contains("`car doctor --repair`"),
            "the remedy must name the command that clears it: {detail}"
        );
        assert!(fx.dir.exists(), "diagnosis alone never deletes");

        let repaired = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, true));
        let (detail, purged, _) = incomplete(&repaired, "Qwen3.5-9B-MLX-vLLM");
        assert!(purged, "repair must clear it: {detail}");
        assert!(
            std::fs::symlink_metadata(&fx.dir).is_err(),
            "the managed directory is gone"
        );
        assert!(
            repaired
                .repairs
                .iter()
                .any(|r| r.contains("removed the interrupted install of 'Qwen3.5-9B-MLX-vLLM'")),
            "the purge is reported as a repair: {:?}",
            repaired.repairs
        );
        for file in [
            "config.json",
            "tokenizer.json",
            "model.safetensors.index.json",
        ] {
            assert!(
                fx.snapshot.join(file).exists(),
                "the shared hub's {file} must survive"
            );
        }

        let after = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, false));
        assert!(after.models.is_empty(), "nothing left to report");
    }

    /// Anything a pull does not write refuses the purge before anything goes.
    #[cfg(unix)]
    #[test]
    fn repair_refuses_a_directory_holding_what_a_pull_does_not_write() {
        let fx = interrupted_install("Mixed");
        std::fs::create_dir(fx.dir.join("notes")).unwrap();
        std::fs::write(fx.dir.join("notes/mine.txt"), b"keep").unwrap();

        let r = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, true));
        let (detail, purged, _) = incomplete(&r, "Mixed");
        assert!(!purged, "{detail}");
        assert!(fx.dir.join("notes/mine.txt").exists());
        assert!(
            std::fs::symlink_metadata(fx.dir.join("config.json")).is_ok(),
            "a refusal touches nothing, not even the links"
        );
        assert!(
            r.repairs
                .iter()
                .any(|x| x.contains("left the interrupted install of 'Mixed' in place")),
            "{:?}",
            r.repairs
        );
    }

    /// Parslee-ai/car#2507 applied to the new purge: a managed dir that is
    /// itself a link to the person's own storage is theirs, so it and its
    /// target stay; one linked into the hub is CAR's projection, so the link
    /// goes and the hub stays.
    #[cfg(unix)]
    #[test]
    fn repair_never_clears_through_a_link_outside_the_hub() {
        let fx = interrupted_install("InHub");
        // Rebuild InHub as a link into the hub snapshot.
        std::fs::remove_dir_all(&fx.dir).unwrap();
        let hub_snapshot_links = fx.hub.join("models--org--repo/snapshots/linked");
        std::fs::create_dir_all(&hub_snapshot_links).unwrap();
        std::os::unix::fs::symlink(
            fx.snapshot.join("config.json"),
            hub_snapshot_links.join("config.json"),
        )
        .unwrap();
        std::os::unix::fs::symlink(&hub_snapshot_links, &fx.dir).unwrap();

        // Elsewhere: the person's own folder of links, linked in.
        let theirs = fx.home.parent().unwrap().join("external/Theirs");
        std::fs::create_dir_all(&theirs).unwrap();
        std::os::unix::fs::symlink(fx.snapshot.join("config.json"), theirs.join("config.json"))
            .unwrap();
        let theirs_leaf = fx.models.join("Theirs");
        std::os::unix::fs::symlink(&theirs, &theirs_leaf).unwrap();

        let r = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, true));
        let (_, purged_in_hub, _) = incomplete(&r, "InHub");
        assert!(purged_in_hub);
        assert!(
            std::fs::symlink_metadata(&fx.dir).is_err(),
            "the hub link goes"
        );
        assert!(
            std::fs::symlink_metadata(hub_snapshot_links.join("config.json")).is_ok(),
            "what it pointed at in the hub stays"
        );
        let (detail, purged_theirs, _) = incomplete(&r, "Theirs");
        assert!(!purged_theirs, "{detail}");
        assert!(std::fs::symlink_metadata(&theirs_leaf).is_ok());
        assert!(std::fs::symlink_metadata(theirs.join("config.json")).is_ok());
    }

    /// A pull's staging directory looks exactly like an interrupted install
    /// for the whole of a live download. It is neither reported nor cleared.
    #[cfg(unix)]
    #[test]
    fn a_live_pulls_staging_directory_is_never_judged() {
        let fx = interrupted_install(".car-install-0123456789abcdef-00");
        let r = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, true));
        assert!(r.models.is_empty(), "{:?}", r.models);
        assert!(
            fx.dir.exists(),
            "a running pull's staging must survive --repair"
        );
    }

    #[cfg(unix)]
    fn mlx_row(id: &str, name: &str, repo: &str) -> crate::schema::ModelSchema {
        serde_json::from_value(serde_json::json!({
            "id": id,
            "name": name,
            "provider": "mlx",
            "family": "doctor-test",
            "capabilities": ["generate"],
            "context_length": 4096,
            "source": {"type": "mlx", "hf_repo": repo, "hf_weight_file": null}
        }))
        .unwrap()
    }

    /// car-releases#90: an incomplete install whose curated replacement
    /// (`car models upgrades`) is installed is reported as removable, not as
    /// something to re-pull, and the repair line says there is nothing to
    /// re-pull. A receipt-backed one is never cleared behind the store.
    #[cfg(unix)]
    #[test]
    fn a_superseded_incomplete_install_is_removable_not_re_pulled() {
        let fx = interrupted_install("Old-30B");
        // The one built-in rule: mlx/qwen3-30b-a3b:4bit -> vllm-mlx/qwen3.6-35b-a3b:4bit.
        let new_snapshot = fx.hub.join("models--org--new/snapshots/rev");
        std::fs::create_dir_all(&new_snapshot).unwrap();
        std::fs::write(new_snapshot.join("config.json"), b"{}").unwrap();
        std::fs::write(new_snapshot.join("model.safetensors"), b"weights").unwrap();
        let mut registry = crate::registry::UnifiedRegistry::new_empty(fx.models.clone());
        registry.register(mlx_row("mlx/qwen3-30b-a3b:4bit", "Old-30B", "org/repo"));
        registry.register(mlx_row(
            "vllm-mlx/qwen3.6-35b-a3b:4bit",
            "New-35B",
            "org/new",
        ));

        let diagnosed = diagnose_at_with_registry(
            &fx.home,
            &fx.models,
            &opts(false, false),
            &registry,
            Some(&fx.hub),
        );
        let (detail, _, superseded_by) = incomplete(&diagnosed, "Old-30B");
        assert_eq!(
            superseded_by.as_deref(),
            Some("vllm-mlx/qwen3.6-35b-a3b:4bit")
        );
        assert!(!detail.contains("car models pull"), "{detail}");
        assert!(detail.contains("supersedes"), "{detail}");

        let repaired = diagnose_at_with_registry(
            &fx.home,
            &fx.models,
            &opts(false, true),
            &registry,
            Some(&fx.hub),
        );
        assert!(
            repaired.repairs.iter().any(|r| r
                .contains("superseded by vllm-mlx/qwen3.6-35b-a3b:4bit")
                && r.contains("nothing to re-pull")),
            "{:?}",
            repaired.repairs
        );
        assert!(std::fs::symlink_metadata(&fx.dir).is_err());

        // Without its replacement installed it is worth re-pulling, by id.
        let fx = interrupted_install("Old-30B");
        let mut registry = crate::registry::UnifiedRegistry::new_empty(fx.models.clone());
        registry.register(mlx_row("mlx/qwen3-30b-a3b:4bit", "Old-30B", "org/repo"));
        registry.register(mlx_row(
            "vllm-mlx/qwen3.6-35b-a3b:4bit",
            "New-35B",
            "org/new",
        ));
        let r = diagnose_at_with_registry(
            &fx.home,
            &fx.models,
            &opts(false, false),
            &registry,
            Some(&fx.hub),
        );
        let (detail, _, superseded_by) = incomplete(&r, "Old-30B");
        assert_eq!(superseded_by, None);
        assert!(
            detail.contains("`car models pull mlx/qwen3-30b-a3b:4bit`"),
            "{detail}"
        );
    }

    /// An install CAR holds a receipt for belongs to `car models remove`.
    #[cfg(unix)]
    #[test]
    fn repair_never_clears_a_receipt_backed_install() {
        let fx = interrupted_install("Owned");
        let mut registry = crate::registry::UnifiedRegistry::new_empty(fx.models.clone());
        registry.register(mlx_row("mlx/owned:4bit", "Owned", "org/repo"));
        let receipts = fx.home.join("model-management/receipts");
        std::fs::create_dir_all(&receipts).unwrap();
        let receipt = receipts.join(crate::model_management::receipt_file_name_for_test(
            "mlx/owned:4bit",
        ));
        std::fs::write(&receipt, b"{}").unwrap();

        let r = diagnose_at_with_registry(
            &fx.home,
            &fx.models,
            &opts(false, true),
            &registry,
            Some(&fx.hub),
        );
        let (detail, purged, _) = incomplete(&r, "Owned");
        assert!(!purged);
        assert!(
            detail.contains("`car models remove mlx/owned:4bit`"),
            "{detail}"
        );
        assert!(fx.dir.exists());
    }

    /// Review of car-releases#90: a doctor pass clears an interrupted install
    /// only under the model's cross-process mutation lock, so a pull,
    /// adoption or removal of the same model running in another process is
    /// never raced. Held elsewhere, the directory stays and the repair line
    /// says why.
    #[cfg(unix)]
    #[test]
    fn repair_waits_out_a_pull_of_the_same_model_in_another_process() {
        let fx = interrupted_install("Busy");
        let mut registry = crate::registry::UnifiedRegistry::new_empty(fx.models.clone());
        registry.register(mlx_row("mlx/busy:4bit", "Busy", "org/repo"));
        let store =
            crate::model_management::ModelManagementStore::new(fx.home.clone(), fx.models.clone());
        let held = store.begin_mutation("mlx/busy:4bit").unwrap();

        let r = diagnose_at_with_registry(
            &fx.home,
            &fx.models,
            &opts(false, true),
            &registry,
            Some(&fx.hub),
        );
        let (detail, purged, _) = incomplete(&r, "Busy");
        assert!(!purged, "{detail}");
        assert!(
            std::fs::symlink_metadata(fx.dir.join("config.json")).is_ok(),
            "nothing is removed while another process holds the model"
        );
        assert!(
            r.repairs.iter().any(|x| x.contains("running right now")),
            "{:?}",
            r.repairs
        );

        drop(held);
        let r = diagnose_at_with_registry(
            &fx.home,
            &fx.models,
            &opts(false, true),
            &registry,
            Some(&fx.hub),
        );
        let (detail, purged, _) = incomplete(&r, "Busy");
        assert!(purged, "{detail}");
        assert!(
            detail.contains("if you still want it, `car models pull mlx/busy:4bit`"),
            "the re-pull is an option, not the next step: {detail}"
        );
    }

    /// Review of car-releases#90: the purge removes only regular files a pull
    /// writes. A small file of any other name beside a linked manifest — the
    /// older MLX `weights.npz` that the weight check does not count, or
    /// someone's notes — refuses the whole purge, and both survive.
    #[cfg(unix)]
    #[test]
    fn repair_keeps_small_files_a_pull_does_not_write() {
        for stray in ["weights.npz", "notes.txt", "pytorch_model.bin"] {
            let fx = interrupted_install("Stray");
            std::fs::write(fx.dir.join(stray), b"not a pull's").unwrap();
            let r = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, true));
            let (detail, purged, _) = incomplete(&r, "Stray");
            assert!(!purged, "{stray}: {detail}");
            assert!(fx.dir.join(stray).exists(), "{stray} survives");
            assert!(
                std::fs::symlink_metadata(fx.dir.join("config.json")).is_ok(),
                "{stray}: a refusal touches nothing"
            );
        }

        // What the copy fallback writes — tokenizer and metadata files, and its
        // own staging copy — is a pull's, and goes.
        let fx = interrupted_install("Copied");
        for name in [
            "generation_config.json",
            "vocab.json",
            ".tokenizer_config.json.car-install-42-0.tmp",
        ] {
            std::fs::write(fx.dir.join(name), b"{}").unwrap();
        }
        let r = diagnose_at_isolated(&fx.home, &fx.models, &fx.hub, &opts(false, true));
        let (detail, purged, _) = incomplete(&r, "Copied");
        assert!(purged, "{detail}");
        assert!(std::fs::symlink_metadata(&fx.dir).is_err());
    }

    /// A purge that stops partway must still leave a directory the next
    /// doctor, pull or forced remove recognizes: every regular file is planned
    /// before any link, and the links are what mark an interrupted install.
    #[cfg(unix)]
    #[test]
    fn a_purge_removes_the_links_that_mark_an_interrupted_install_last() {
        use crate::model_management::UnlinkKind;
        let fx = interrupted_install("Halfway");
        for name in ["generation_config.json", "vocab.json"] {
            std::fs::write(fx.dir.join(name), b"{}").unwrap();
        }
        let plan = purge_plan(&fx.dir).unwrap();
        let first_link = plan
            .iter()
            .position(|(_, kind)| *kind == UnlinkKind::Link)
            .expect("the manifests are links");
        assert!(
            plan[first_link..]
                .iter()
                .all(|(_, kind)| *kind == UnlinkKind::Link),
            "a regular file is planned after a link: {plan:?}"
        );
        assert_eq!(plan.len(), 5, "{plan:?}");
    }

    /// car-releases#87/#90 review: `--repair` reclaims a partial download only
    /// when it is provably abandoned and CAR's — a repo CAR fetches whole, no
    /// lock held, untouched for a day — through the concierge's own rule. A
    /// fresh partial in the same repo, and an old one in a repo CAR does not
    /// own, are reported and left alone.
    #[cfg(unix)]
    #[test]
    fn repair_reclaims_only_abandoned_partials_of_car_s_own_repos() {
        let (repo, _) = crate::retire::catalog_ownership()
            .into_iter()
            .find(|(_, owned)| *owned == crate::retire::Owned::Whole)
            .expect("the builtin catalog fetches at least one repo whole");
        let hf = TempDir::new().unwrap();
        let hub = hf.path().join("hub");
        let blobs_of = |repo: &str| {
            let dir = hub
                .join(format!("models--{}", repo.replace('/', "--")))
                .join("blobs");
            std::fs::create_dir_all(&dir).unwrap();
            dir
        };
        let stale = std::time::SystemTime::now()
            - std::time::Duration::from_secs(crate::retire::ABANDONED_PARTIAL_SECS + 60);
        let plant = |path: &Path, old: bool| {
            std::fs::write(path, vec![0u8; 1024]).unwrap();
            if old {
                std::fs::File::options()
                    .write(true)
                    .open(path)
                    .unwrap()
                    .set_modified(stale)
                    .unwrap();
            }
        };
        let ours = blobs_of(&repo);
        let abandoned = ours.join("old.sync.part");
        let running = ours.join("fresh.sync.part");
        let theirs = blobs_of("someone/else").join("old.sync.part");
        plant(&abandoned, true);
        plant(&running, false);
        plant(&theirs, true);

        let home = TempDir::new().unwrap();
        let diagnose = |repair| {
            diagnose_at_isolated(
                home.path(),
                &home.path().join("models"),
                &hub,
                &opts(false, repair),
            )
        };
        let reclaimable = |r: &DoctorReport, path: &Path| {
            r.leftovers
                .iter()
                .find(|l| Path::new(&l.path) == path)
                .map(|l| l.reclaimable)
        };

        let r = diagnose(false);
        assert_eq!(reclaimable(&r, &abandoned), Some(true), "{:?}", r.leftovers);
        assert_eq!(reclaimable(&r, &running), Some(false), "{:?}", r.leftovers);
        assert_eq!(reclaimable(&r, &theirs), Some(false), "{:?}", r.leftovers);
        assert!(abandoned.exists(), "diagnosis alone deletes nothing");

        let r = diagnose(true);
        assert!(!abandoned.exists(), "{:?}", r.repairs);
        assert!(
            running.exists(),
            "a partial written just now may be a live pull"
        );
        assert!(
            theirs.exists(),
            "a repo CAR does not own is not CAR's to clean"
        );
        assert!(
            r.repairs
                .iter()
                .any(|x| x.contains("removed 1 abandoned partial download(s)")),
            "{:?}",
            r.repairs
        );
        assert_eq!(r.leftovers.len(), 2, "{:?}", r.leftovers);
        assert!(r.leftovers.iter().all(|l| !l.reclaimable));
    }

    #[test]
    fn unrecognized_entries_are_reported_not_removed() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("mystery-leftover.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join("old_install_dir")).unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(r
            .unrecognized
            .contains(&"mystery-leftover.json".to_string()));
        assert!(r.unrecognized.contains(&"old_install_dir".to_string()));
        // Repair must NOT delete unrecognized entries.
        assert!(tmp.path().join("mystery-leftover.json").exists());
        assert!(tmp.path().join("old_install_dir").exists());
    }

    #[test]
    fn version_skew_detected() {
        let tmp = TempDir::new().unwrap();
        let stale = VersionStamp {
            car_version: "0.0.1-ancient".to_string(),
            state_schema_version: 1,
            previous_car_version: None,
            previous_state_schema_version: None,
        };
        std::fs::write(
            tmp.path().join("version.json"),
            serde_json::to_string(&stale).unwrap(),
        )
        .unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(r.version_skew);
        assert!(!r.is_healthy());

        // Repair refreshes the stamp to the current binary, clearing skew next run.
        let _ = diagnose_in(tmp.path(), &opts(false, true));
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(!r.version_skew, "stamp refreshed, skew cleared");
    }
}

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

    fn write(home: &Path, stamp: &VersionStamp) {
        std::fs::create_dir_all(home).unwrap();
        std::fs::write(
            home.join("version.json"),
            serde_json::to_string_pretty(stamp).unwrap(),
        )
        .unwrap();
    }

    fn stamp(version: &str, schema: u32) -> VersionStamp {
        VersionStamp {
            car_version: version.to_string(),
            state_schema_version: schema,
            previous_car_version: None,
            previous_state_schema_version: None,
        }
    }

    /// The car#881 bug, as a test. A daemon boot used to overwrite the stamp
    /// unconditionally, so the fact that an older CAR wrote this state was gone
    /// before `car doctor` — the only reader — could ever be run.
    #[test]
    fn stamping_after_an_upgrade_preserves_what_it_replaced() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("0.39.0", 1));

        let t = stamp_version(dir.path()).unwrap();
        assert!(t.upgraded(), "0.39.0 -> current is an upgrade");
        assert_eq!(
            t.current.previous_car_version.as_deref(),
            Some("0.39.0"),
            "the predecessor must survive the stamp that replaced it"
        );

        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert_eq!(
            report.carried_from_version.as_deref(),
            Some("0.39.0"),
            "doctor must still see it AFTER the daemon stamped"
        );
    }

    /// The subtler half. Rewriting `previous` on every boot would collapse it to
    /// the current version after one restart — the same erasure, one level down.
    #[test]
    fn rebooting_on_the_same_version_keeps_the_original_predecessor() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("0.39.0", 1));

        stamp_version(dir.path()).unwrap(); // the upgrade
        for _ in 0..5 {
            stamp_version(dir.path()).unwrap(); // ordinary reboots
        }

        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert_eq!(
            report.carried_from_version.as_deref(),
            Some("0.39.0"),
            "five reboots must not rewrite the predecessor to the current version"
        );
    }

    #[test]
    fn a_fresh_install_records_no_predecessor() {
        let dir = tempfile::tempdir().unwrap();
        let t = stamp_version(dir.path()).unwrap();
        assert!(t.previous.is_none());
        assert!(!t.upgraded());
        assert!(t.current.previous_car_version.is_none());
        assert!(!diagnose_in(dir.path(), &DoctorOptions::default()).schema_from_the_future);
    }

    /// A downgrade. STATE_SCHEMA_VERSION's contract says a reader older than the
    /// state should refuse rather than corrupt; nothing acted on it before.
    #[test]
    fn state_from_a_newer_schema_is_flagged() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("99.0.0", STATE_SCHEMA_VERSION + 7));

        let t = stamp_version(dir.path()).unwrap();
        assert!(
            t.schema_from_the_future(),
            "newer on-disk schema must be flagged"
        );

        // And it must be visible to doctor as unhealthy, not merely noted.
        write(dir.path(), &stamp("99.0.0", STATE_SCHEMA_VERSION + 7));
        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert!(report.schema_from_the_future);
        assert!(!report.is_healthy());
    }

    /// Carrying state across an upgrade is the NORMAL case. Treating it as a
    /// health problem would make every upgraded install permanently unhealthy,
    /// which is how a warning gets ignored.
    #[test]
    fn carrying_state_across_an_upgrade_is_not_unhealthy() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("0.39.0", STATE_SCHEMA_VERSION));
        stamp_version(dir.path()).unwrap();

        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert!(report.carried_from_version.is_some());
        assert!(report.is_healthy(), "an ordinary upgrade is not a defect");
    }

    /// An older stamp has no `previous_*` keys at all. It must deserialize, not
    /// blow up the boot path.
    #[test]
    fn a_pre_existing_stamp_without_the_new_fields_still_loads() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path()).unwrap();
        std::fs::write(
            dir.path().join("version.json"),
            r#"{"car_version":"0.39.0","state_schema_version":1}"#,
        )
        .unwrap();

        let t = stamp_version(dir.path()).unwrap();
        assert_eq!(
            t.previous.as_ref().map(|p| p.car_version.as_str()),
            Some("0.39.0")
        );
        assert_eq!(t.current.previous_car_version.as_deref(), Some("0.39.0"));
    }

    /// A corrupt stamp must not stop the daemon stamping — it is best-effort by
    /// contract, and refusing to boot over an unreadable version file would be a
    /// far worse failure than the one it guards.
    #[test]
    fn a_corrupt_stamp_is_treated_as_absent_and_replaced() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path()).unwrap();
        std::fs::write(dir.path().join("version.json"), "{ not json").unwrap();

        let t = stamp_version(dir.path()).unwrap();
        assert!(t.previous.is_none(), "unreadable == no usable predecessor");
        assert_eq!(t.current.car_version, VersionStamp::current().car_version);
    }
}

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

    /// A never-provisioned runtime is absent, not broken — a fresh install must
    /// not read as unhealthy.
    #[test]
    fn absent_runtimes_are_not_reported() {
        let dir = tempfile::tempdir().unwrap();
        assert!(check_runtimes(dir.path()).is_empty());
    }

    /// The failure this check exists for: the venv directory is fully populated
    /// but its interpreter symlink points at a Homebrew formula that is gone.
    // Unix-only because the *setup* needs a POSIX symlink, not because the
    // behaviour is. Same shape as `interrupted_pull_is_reported_not_skipped`.
    #[cfg(unix)]
    #[test]
    fn rotated_away_interpreter_is_reported_broken() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("visual-runtime").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::os::unix::fs::symlink(
            "/opt/homebrew/opt/python@0.0/bin/python0.0",
            bin.join("python"),
        )
        .unwrap();

        let checks = check_runtimes(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].name, "visual-runtime");
        assert!(checks[0].present);
        assert!(!checks[0].interpreter_ok);
        assert!(checks[0].is_broken());
    }

    /// A broken runtime must sink `is_healthy` — the whole point is that this
    /// stops being silent.
    #[test]
    fn broken_runtime_makes_report_unhealthy() {
        let mut report = DoctorReport {
            car_home: "/tmp/x".into(),
            binary_version: VersionStamp::current().car_version,
            on_disk_stamp: None,
            version_skew: false,
            carried_from_version: None,
            schema_from_the_future: false,
            state_files: Vec::new(),
            models: Vec::new(),
            installed_models: 0,
            leftovers: Vec::new(),
            revoked_copies: Vec::new(),
            catalog: Default::default(),
            runtimes: Vec::new(),
            unrecognized: Vec::new(),
            repairs: Vec::new(),
            daemon_tmpdir: None,
            daemon_single_principal: false,
            daemon_host_role_cause: None,
        };
        assert!(report.is_healthy());

        report.runtimes.push(RuntimeCheck {
            name: "speech-runtime".into(),
            root: "/tmp/x/speech-runtime".into(),
            present: true,
            interpreter_ok: false,
        });
        assert!(!report.is_healthy());
    }
}

/// car#3404: the daemon's startup host-role record, written by
/// [`record_daemon_auth_mode`] and read by the offline doctor. Temp dirs only;
/// the "running daemon" is this test process, the dead one a reaped child.
#[cfg(all(test, unix))]
mod daemon_auth_mode_tests {
    use super::*;

    fn diagnose_home(home: &Path) -> DoctorReport {
        let models = tempfile::tempdir().unwrap();
        let hub = tempfile::tempdir().unwrap();
        diagnose_at_isolated(home, models.path(), hub.path(), &DoctorOptions::default())
    }

    fn write_marker(home: &Path, pid: u32, single_principal: bool) {
        let path = daemon_auth_mode_marker_path(home);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let marker = DaemonAuthModeMarker {
            pid,
            booted_at_unix: 1_789_000_000,
            car_version: VersionStamp::current().car_version,
            single_principal,
            cause: None,
        };
        std::fs::write(path, serde_json::to_string(&marker).unwrap()).unwrap();
    }

    #[test]
    fn a_running_single_principal_daemon_is_reported_and_stays_healthy() {
        let home = tempfile::tempdir().unwrap();
        let recorded =
            record_daemon_auth_mode(home.path(), true, Some("--no-auth".into())).expect("record");
        assert_eq!(recorded.pid, std::process::id());

        let report = diagnose_home(home.path());
        assert!(report.daemon_single_principal, "{report:?}");
        assert_eq!(
            report.daemon_host_role_cause.as_deref(),
            Some("--no-auth"),
            "{report:?}"
        );
        assert!(report.is_healthy(), "informational, never a health failure");
    }

    #[test]
    fn a_host_token_daemon_a_gone_daemon_and_no_record_are_not_reported() {
        let home = tempfile::tempdir().unwrap();
        assert!(!diagnose_home(home.path()).daemon_single_principal);

        record_daemon_auth_mode(home.path(), false, Some("ignored".into())).expect("record");
        assert!(!running_daemon_is_single_principal(home.path()));

        let mut child = std::process::Command::new("true")
            .spawn()
            .expect("spawn `true`");
        let dead = child.id();
        child.wait().expect("reap `true`");
        write_marker(home.path(), dead, true);
        assert!(
            !running_daemon_is_single_principal(home.path()),
            "a record from a daemon that exited describes no running daemon"
        );

        std::fs::write(daemon_auth_mode_marker_path(home.path()), b"{not json").unwrap();
        assert!(!running_daemon_is_single_principal(home.path()));
    }
}

/// Parslee-ai/car#1494: the daemon's startup TMPDIR probe record, written by
/// [`record_daemon_tmpdir_probe`] and read by the offline doctor. Temp dirs and
/// injected paths only.
#[cfg(test)]
mod daemon_tmpdir_tests {
    use super::*;

    const NOT_A_DIRECTORY: &[u8] = b"a regular file where TMPDIR should be";

    fn marker(pid: u32, ok: bool) -> DaemonTmpdirMarker {
        let checked_path = "/private/tmp/PKInstallSandbox.test/tmp".to_string();
        DaemonTmpdirMarker {
            pid,
            booted_at_unix: 1_789_000_000,
            car_version: VersionStamp::current().car_version,
            checked_path: checked_path.clone(),
            checked_path_absolute: Some(checked_path),
            ok,
            error: (!ok)
                .then(|| "create failed: No such file or directory (os error 2)".to_string()),
            note: None,
        }
    }

    fn write_marker(home: &Path, marker: &DaemonTmpdirMarker) {
        let path = daemon_tmpdir_marker_path(home);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, serde_json::to_string_pretty(marker).unwrap()).unwrap();
    }

    /// Doctor against `home`, with the weights and Hugging Face roots isolated
    /// in temp dirs so nothing outside the test is read.
    fn diagnose_home(home: &Path) -> DoctorReport {
        let models = tempfile::tempdir().unwrap();
        let hub = tempfile::tempdir().unwrap();
        diagnose_at_isolated(home, models.path(), hub.path(), &DoctorOptions::default())
    }

    fn status_of(report: &DoctorReport) -> DaemonTmpdirStatus {
        report
            .daemon_tmpdir
            .clone()
            .expect("the record must be reported")
            .status
    }

    /// A pid that named a real process a moment ago and no longer does: a
    /// short-lived child, spawned and reaped.
    #[cfg(unix)]
    fn dead_pid() -> u32 {
        let mut child = std::process::Command::new("true")
            .spawn()
            .expect("spawn `true`");
        let pid = child.id();
        child.wait().expect("reap `true`");
        assert!(
            !unix_pid_alive(pid),
            "a reaped child's pid must read as gone"
        );
        pid
    }

    fn healthy_tmpdir(parent: &Path) -> PathBuf {
        let dir = parent.join("healthy-tmpdir");
        std::fs::create_dir(&dir).unwrap();
        dir
    }

    #[test]
    fn probing_a_file_tmpdir_records_a_failure() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        let tmpdir = tmp.path().join("tmpdir-is-a-file");
        std::fs::write(&tmpdir, NOT_A_DIRECTORY).unwrap();

        let recorded = record_daemon_tmpdir_probe(&home, &tmpdir)
            .expect("a failed probe is still a successful record");

        assert!(!recorded.ok, "{recorded:?}");
        assert_eq!(recorded.pid, std::process::id());
        assert_eq!(recorded.checked_path, tmpdir.display().to_string());
        let error = recorded.error.clone().expect("a failure names its error");
        assert!(error.starts_with("create failed"), "{error}");
        #[cfg(unix)]
        assert!(
            error.contains(&format!("os error {}", libc::ENOTDIR)),
            "a file where the directory should be is ENOTDIR: {error}"
        );
        assert_eq!(read_daemon_tmpdir_marker(&home), Some(Ok(recorded)));
        assert_eq!(std::fs::read(&tmpdir).unwrap(), NOT_A_DIRECTORY);
    }

    #[test]
    fn a_healthy_probe_replaces_a_prior_failure_and_leaves_nothing_behind() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        let broken = tmp.path().join("tmpdir-is-a-file");
        std::fs::write(&broken, NOT_A_DIRECTORY).unwrap();
        let healthy = healthy_tmpdir(tmp.path());

        assert!(!record_daemon_tmpdir_probe(&home, &broken).unwrap().ok);
        let recorded = record_daemon_tmpdir_probe(&home, &healthy).unwrap();

        assert!(recorded.ok, "{recorded:?}");
        assert_eq!(recorded.error, None);
        assert_eq!(recorded.checked_path_absolute.as_deref(), healthy.to_str());
        assert_eq!(read_daemon_tmpdir_marker(&home), Some(Ok(recorded)));
        #[cfg(any(unix, windows))]
        assert!(
            std::fs::read_dir(&healthy).unwrap().next().is_none(),
            "Unix unlinks the identity-checked probe and Windows deletes it on close"
        );
        #[cfg(all(not(unix), not(windows)))]
        assert_eq!(
            std::fs::read_dir(&healthy).unwrap().count(),
            1,
            "without portable file identity the tiny probe file is left safely behind"
        );
        let names: Vec<_> = std::fs::read_dir(home.join(DOCTOR_DIR))
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect();
        assert_eq!(
            names,
            vec![std::ffi::OsString::from(DAEMON_TMPDIR_MARKER_FILE)],
            "no temporary record may be left behind"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_tmpdir_is_followed_and_its_probe_file_is_removed() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        let target = healthy_tmpdir(tmp.path());
        let link = tmp.path().join("tmpdir-link");
        std::os::unix::fs::symlink(&target, &link).unwrap();

        let recorded = record_daemon_tmpdir_probe(&home, &link).unwrap();

        assert!(
            recorded.ok,
            "a directory symlink is valid TMPDIR: {recorded:?}"
        );
        assert_eq!(recorded.checked_path, link.display().to_string());
        assert!(
            std::fs::read_dir(&target).unwrap().next().is_none(),
            "the identity-checked probe file is removed from the resolved directory"
        );
    }

    #[cfg(unix)]
    #[test]
    fn cleanup_does_not_remove_a_different_file_at_the_probe_path() {
        let tmp = tempfile::tempdir().unwrap();
        let created_path = tmp.path().join("created");
        let probe_path = tmp.path().join("substitute");
        std::fs::write(&created_path, b"created").unwrap();
        std::fs::write(&probe_path, b"substitute").unwrap();
        let created = std::fs::metadata(&created_path).unwrap();

        let error = remove_probe_file(&probe_path, &created).unwrap_err();

        assert!(error.starts_with("remove skipped"), "{error}");
        assert_eq!(std::fs::read(&probe_path).unwrap(), b"substitute");
    }

    #[test]
    fn a_stat_failure_after_create_and_write_records_healthy_with_a_note() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        let tmpdir = healthy_tmpdir(tmp.path());
        let result = combine_probe_results(
            Err("stat failed: injected failure".to_string()),
            Ok(()),
            Err("cleanup skipped: identity could not be proven; file left".to_string()),
        );
        let recorded = record_daemon_tmpdir_probe_result(&home, &tmpdir, result).unwrap();

        assert!(
            recorded.ok,
            "create and write proved TMPDIR works: {recorded:?}"
        );
        assert_eq!(recorded.error, None);
        let note = recorded.note.as_deref().expect("stat failure is retained");
        assert!(note.contains("stat failed: injected failure"), "{note}");
        assert!(note.contains("identity could not be proven"), "{note}");
        assert!(note.contains("left"), "{note}");

        let report = diagnose_home(&home);
        assert!(!report.daemon_tmpdir.as_ref().unwrap().is_failing());
        assert!(
            report.is_healthy(),
            "a note must keep doctor at exit 0: {report:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_deletes_the_probe_file_when_its_handle_closes() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        let healthy = healthy_tmpdir(tmp.path());

        let recorded = record_daemon_tmpdir_probe(&home, &healthy).unwrap();

        assert!(recorded.ok, "{recorded:?}");
        assert!(
            std::fs::read_dir(&healthy).unwrap().next().is_none(),
            "FILE_FLAG_DELETE_ON_CLOSE must remove the probe file"
        );
    }

    #[test]
    fn the_record_does_not_trip_find_unrecognized() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        let healthy = healthy_tmpdir(tmp.path());

        record_daemon_tmpdir_probe(&home, &healthy).unwrap();

        assert!(daemon_tmpdir_marker_path(&home).is_file());
        assert!(KNOWN_DIRS.contains(&DOCTOR_DIR));
        assert!(
            find_unrecognized(&home).is_empty(),
            "{:?}",
            find_unrecognized(&home)
        );
        assert!(diagnose_home(&home).unrecognized.is_empty());
    }

    #[test]
    fn an_absent_record_is_not_an_error_and_adds_no_json_key() {
        let home = tempfile::tempdir().unwrap();
        let report = diagnose_home(home.path());
        assert!(report.daemon_tmpdir.is_none());
        assert!(report.is_healthy(), "{report:?}");
        let json = serde_json::to_value(&report).unwrap();
        assert!(
            json.get("daemon_tmpdir").is_none(),
            "additive: a report without a record serializes as before"
        );
    }

    #[cfg(unix)]
    #[test]
    fn doctor_reads_failure_healthy_stale_and_absent_records() {
        let home = tempfile::tempdir().unwrap();
        let live = std::process::id();

        let absent = diagnose_home(home.path());
        assert!(absent.daemon_tmpdir.is_none() && absent.is_healthy());

        let failed = marker(live, false);
        write_marker(home.path(), &failed);
        let report = diagnose_home(home.path());
        assert_eq!(
            status_of(&report),
            DaemonTmpdirStatus::Current { marker: failed }
        );
        assert!(!report.is_healthy(), "failure from the running daemon");

        let mut healthy = marker(live, true);
        healthy.checked_path = healthy_tmpdir(home.path()).display().to_string();
        healthy.checked_path_absolute = Some(healthy.checked_path.clone());
        write_marker(home.path(), &healthy);
        let report = diagnose_home(home.path());
        assert_eq!(
            status_of(&report),
            DaemonTmpdirStatus::Current { marker: healthy }
        );
        assert!(
            report.is_healthy(),
            "healthy record from the running daemon"
        );

        let stale = marker(dead_pid(), false);
        write_marker(home.path(), &stale);
        let report = diagnose_home(home.path());
        assert_eq!(
            status_of(&report),
            DaemonTmpdirStatus::Stale { marker: stale }
        );
        assert!(report.is_healthy(), "a stale failure is not failing");
    }

    #[cfg(unix)]
    #[test]
    fn a_running_daemons_failed_probe_is_unhealthy() {
        let home = tempfile::tempdir().unwrap();
        let recorded = marker(std::process::id(), false);
        write_marker(home.path(), &recorded);

        let report = diagnose_home(home.path());

        let check = report
            .daemon_tmpdir
            .clone()
            .expect("the record is reported");
        assert_eq!(
            check.marker_path,
            daemon_tmpdir_marker_path(home.path()).display().to_string()
        );
        assert_eq!(
            check.status,
            DaemonTmpdirStatus::Current { marker: recorded }
        );
        assert!(check.is_failing());
        assert!(!report.is_healthy(), "{report:?}");
    }

    #[cfg(unix)]
    #[test]
    fn a_record_from_a_daemon_that_is_gone_is_stale_not_failing() {
        let home = tempfile::tempdir().unwrap();
        let recorded = marker(dead_pid(), false);
        write_marker(home.path(), &recorded);

        let report = diagnose_home(home.path());

        let check = report
            .daemon_tmpdir
            .clone()
            .expect("the record is reported");
        assert_eq!(check.status, DaemonTmpdirStatus::Stale { marker: recorded });
        assert!(!check.is_failing());
        assert!(report.is_healthy(), "{report:?}");
    }

    #[cfg(unix)]
    #[test]
    fn a_current_ok_record_whose_checked_path_disappeared_is_failing() {
        let home = tempfile::tempdir().unwrap();
        let checked_path = healthy_tmpdir(home.path());
        let mut recorded = marker(std::process::id(), true);
        recorded.checked_path = checked_path.display().to_string();
        recorded.checked_path_absolute = Some(recorded.checked_path.clone());
        write_marker(home.path(), &recorded);
        std::fs::remove_dir(&checked_path).unwrap();

        let report = diagnose_home(home.path());

        assert_eq!(
            status_of(&report),
            DaemonTmpdirStatus::CurrentPathGone {
                marker: recorded.clone()
            }
        );
        assert!(report.daemon_tmpdir.as_ref().unwrap().is_failing());
        assert!(
            !report.is_healthy(),
            "the running daemon's vanished TMPDIR must produce exit 1"
        );
    }

    #[test]
    fn a_non_not_found_recheck_error_is_distinct_and_failing() {
        let recorded = marker(std::process::id(), true);
        let status = recheck_current_tmpdir_with(
            DaemonTmpdirStatus::Current {
                marker: recorded.clone(),
            },
            |_| {
                Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "injected permission denied",
                ))
            },
        );

        assert_eq!(
            status,
            DaemonTmpdirStatus::CurrentPathRecheckFailed {
                marker: recorded,
                error: "injected permission denied".to_string(),
            }
        );
        let check = DaemonTmpdirCheck {
            marker_path: "doctor/daemon-tmpdir.json".to_string(),
            status,
        };
        assert!(check.is_failing());
    }

    #[cfg(unix)]
    #[test]
    fn a_relative_probe_path_survives_doctor_running_from_a_different_cwd() {
        let runner_temp_root = std::env::temp_dir();
        let fixture_root = if runner_temp_root.to_str().is_some() {
            runner_temp_root.as_path()
        } else {
            Path::new(env!("CARGO_MANIFEST_DIR"))
        };
        assert!(
            fixture_root.to_str().is_some(),
            "the fixture root must be valid UTF-8"
        );
        let daemon_cwd = tempfile::Builder::new()
            .prefix("car-daemon-cwd-")
            .tempdir_in(fixture_root)
            .unwrap();
        let doctor_cwd = tempfile::Builder::new()
            .prefix("car-doctor-cwd-")
            .tempdir_in(fixture_root)
            .unwrap();
        assert!(daemon_cwd.path().to_str().is_some());
        assert!(doctor_cwd.path().to_str().is_some());

        let relative = Path::new("relative-tmpdir");
        let actual = daemon_cwd.path().join(relative);
        std::fs::create_dir(&actual).unwrap();
        assert!(
            matches!(
                std::fs::metadata(doctor_cwd.path().join(relative)),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound
            ),
            "the old display-path recheck would report this path as gone"
        );

        let (exact, note) =
            exact_absolute_tmpdir_path(relative, Ok(daemon_cwd.path().to_path_buf()));
        assert_eq!(note, None);
        assert_eq!(exact.as_deref(), actual.to_str());
        let mut recorded = marker(std::process::id(), true);
        recorded.checked_path = relative.display().to_string();
        recorded.checked_path_absolute = exact;

        let mut received_path = None;
        let status = recheck_current_tmpdir_with(
            DaemonTmpdirStatus::Current {
                marker: recorded.clone(),
            },
            |path| {
                received_path = Some(path.to_path_buf());
                std::fs::metadata(path).map(|_| ())
            },
        );

        assert_eq!(received_path.as_deref(), Some(actual.as_path()));
        assert!(received_path
            .as_ref()
            .is_some_and(|path| path.is_absolute()));
        assert_eq!(status, DaemonTmpdirStatus::Current { marker: recorded });
    }

    #[cfg(unix)]
    #[test]
    fn an_old_record_without_an_exact_path_skips_recheck_with_a_note() {
        let home = tempfile::tempdir().unwrap();
        let mut recorded = marker(std::process::id(), true);
        recorded.checked_path_absolute = None;
        write_marker(home.path(), &recorded);

        let report = diagnose_home(home.path());
        let DaemonTmpdirStatus::Current { marker } = status_of(&report) else {
            panic!("old record must remain current: {:?}", report.daemon_tmpdir);
        };

        assert!(marker
            .note
            .as_deref()
            .is_some_and(|note| note.contains("startup record has no exact absolute probe path")));
        assert!(
            report.is_healthy(),
            "skipping an unsafe guess is informational"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_non_utf8_probe_path_skips_future_rechecks_with_a_note() {
        use std::os::unix::ffi::OsStringExt;

        let path = PathBuf::from(std::ffi::OsString::from_vec(vec![
            b'/', b't', b'm', b'p', b'/', 0xff,
        ]));
        let (exact, note) = exact_absolute_tmpdir_path(&path, Ok(PathBuf::from("/ignored")));

        assert_eq!(exact, None);
        assert!(note
            .as_deref()
            .is_some_and(|note| note.contains("not valid UTF-8")));
    }

    #[test]
    fn an_ok_record_is_healthy() {
        let home = tempfile::tempdir().unwrap();
        let checked_path = healthy_tmpdir(home.path());
        let mut recorded = marker(std::process::id(), true);
        recorded.checked_path = checked_path.display().to_string();
        recorded.checked_path_absolute = Some(recorded.checked_path.clone());
        write_marker(home.path(), &recorded);

        let report = diagnose_home(home.path());

        #[cfg(any(unix, windows))]
        assert_eq!(
            status_of(&report),
            DaemonTmpdirStatus::Current { marker: recorded }
        );
        #[cfg(not(any(unix, windows)))]
        assert_eq!(
            status_of(&report),
            DaemonTmpdirStatus::Unverified { marker: recorded }
        );
        assert!(report.is_healthy(), "{report:?}");
    }

    /// The liveness check answers for this process, and answers the other way
    /// for a pid that cannot be running. Without the second half the first is
    /// satisfied by a function that returns `true` unconditionally.
    #[cfg(any(unix, windows))]
    #[test]
    fn the_liveness_check_separates_this_process_from_a_dead_one() {
        assert_eq!(daemon_writer_alive(std::process::id()), Some(true));
        // Pid 0 is the idle process on Windows and a process *group* to
        // `kill(2)`; neither is a daemon that recorded a probe.
        assert_eq!(daemon_writer_alive(0), Some(false));
    }

    /// Where there is no liveness check, the record is shown with its result
    /// and never folded into health as a failure.
    #[test]
    fn without_a_liveness_check_a_failed_record_is_unverified_not_failing() {
        let recorded = marker(std::process::id(), false);
        let status = classify_daemon_tmpdir_marker(recorded.clone(), None);
        assert_eq!(status, DaemonTmpdirStatus::Unverified { marker: recorded });
        let check = DaemonTmpdirCheck {
            marker_path: "doctor/daemon-tmpdir.json".to_string(),
            status,
        };
        assert!(!check.is_failing());
    }

    #[test]
    fn an_unreadable_record_is_reported_not_failing() {
        let home = tempfile::tempdir().unwrap();
        let path = daemon_tmpdir_marker_path(home.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "{ not json").unwrap();

        let report = diagnose_home(home.path());

        assert!(
            matches!(status_of(&report), DaemonTmpdirStatus::Unreadable { .. }),
            "{:?}",
            report.daemon_tmpdir
        );
        assert!(report.is_healthy(), "{report:?}");
    }

    #[test]
    fn a_record_serializes_additively_and_round_trips() {
        let home = tempfile::tempdir().unwrap();
        write_marker(home.path(), &marker(std::process::id(), true));

        let json = serde_json::to_value(diagnose_home(home.path())).unwrap();

        let record = json
            .get("daemon_tmpdir")
            .expect("the record serializes under `daemon_tmpdir`");
        assert!(
            record.get("status").is_some() && record.get("marker_path").is_some(),
            "{record}"
        );
        assert_eq!(record["marker"]["ok"], serde_json::Value::Bool(true));
        let back: DoctorReport = serde_json::from_value(json).unwrap();
        assert!(back.daemon_tmpdir.is_some());
    }

    #[cfg(unix)]
    #[test]
    fn the_record_is_never_written_through_a_symlinked_doctor_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        std::fs::create_dir(&home).unwrap();
        let elsewhere = tmp.path().join("elsewhere");
        std::fs::create_dir(&elsewhere).unwrap();
        std::os::unix::fs::symlink(&elsewhere, home.join(DOCTOR_DIR)).unwrap();
        let healthy = healthy_tmpdir(tmp.path());

        assert!(record_daemon_tmpdir_probe(&home, &healthy).is_err());
        assert!(
            std::fs::read_dir(&elsewhere).unwrap().next().is_none(),
            "nothing may land where the symlink points"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_at_the_record_path_is_replaced_not_followed() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("car-home");
        std::fs::create_dir_all(home.join(DOCTOR_DIR)).unwrap();
        let victim = tmp.path().join("victim");
        std::fs::write(&victim, b"victim").unwrap();
        std::os::unix::fs::symlink(&victim, daemon_tmpdir_marker_path(&home)).unwrap();
        let healthy = healthy_tmpdir(tmp.path());

        let recorded = record_daemon_tmpdir_probe(&home, &healthy).unwrap();

        assert_eq!(std::fs::read(&victim).unwrap(), b"victim");
        assert!(std::fs::symlink_metadata(daemon_tmpdir_marker_path(&home))
            .unwrap()
            .file_type()
            .is_file());
        assert_eq!(read_daemon_tmpdir_marker(&home), Some(Ok(recorded)));
    }
}