car-inference 0.47.0

Local model inference for CAR — Candle backend with Qwen3 models
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
//! Unified model registry — local and remote models under one schema.
//!
//! Replaces the hardcoded `ModelRegistry` from `models.rs` with a schema-driven
//! registry that treats all models as first-class typed resources. Users can
//! register custom models (fine-tuned endpoints, private APIs) alongside the
//! built-in catalog.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use serde::{Deserialize, Serialize};
use tracing::{info, warn};

use crate::download::{DownloadEvent, ProgressSink};
use crate::schema::*;
use crate::InferenceError;

/// Filter for querying the registry.
#[derive(Debug, Clone, Default)]
pub struct ModelFilter {
    /// Required capabilities (model must have ALL of these).
    pub capabilities: Vec<ModelCapability>,
    /// Maximum on-disk / RAM size in MB.
    pub max_size_mb: Option<u64>,
    /// Maximum expected latency in ms (from declared envelope).
    pub max_latency_ms: Option<u64>,
    /// Maximum cost per 1M output tokens in USD.
    pub max_cost_per_mtok: Option<f64>,
    /// Required tags (model must have ALL of these).
    pub tags: Vec<String>,
    /// Filter by provider.
    pub provider: Option<String>,
    /// Only local models.
    pub local_only: bool,
    /// Only models that are currently available.
    pub available_only: bool,
}

/// A curated replacement for a local model that is installed but no longer
/// the preferred model in its line.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelUpgrade {
    pub from_id: String,
    pub from_name: String,
    pub to_id: String,
    pub to_name: String,
    pub reason: String,
    pub target_runtime: Option<String>,
    pub target_runtime_requirement: Option<String>,
    pub minimum_runtimes: Vec<ModelRuntimeRequirement>,
    pub target_available: bool,
    pub target_pullable: bool,
    pub remove_old_supported: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelRuntimeRequirement {
    pub name: String,
    pub minimum_version: String,
}

/// Unified registry of all known models.
#[derive(Clone)]
pub struct UnifiedRegistry {
    models_dir: PathBuf,
    /// All registered models, keyed by id.
    models: HashMap<String, ModelSchema>,
    /// IDs whose current rows came from the user-controlled `models.json`
    /// boundary or an explicit user registration.
    ///
    /// Tags cannot carry this provenance: a user can add `builtin`, while a
    /// valid signed catalog row does not have to. Keeping the boundary private
    /// prevents generic/builtin/catalog/discovery registration from being
    /// serialized back into user config and losing its trust tier on restart.
    user_config_ids: HashSet<String>,
    /// User-added model config file path (~/.car/models.json).
    user_config_path: PathBuf,
    /// Where to report downloads that nobody explicitly asked for.
    ///
    /// [`ensure_local`](Self::ensure_local) is the *implicit* acquisition path:
    /// it runs inside `generate`, when the router picks a model whose weights
    /// aren't on disk yet. It used to hard-code `ProgressSink::none()`, so a
    /// multi-gigabyte fetch triggered by a plain `car infer "hi"` produced no
    /// output on any surface — the command simply appeared to hang, and a
    /// user on a metered connection had no signal at all (Parslee-ai/car#620).
    ///
    /// Explicit pulls (`car models pull`) always passed a real sink and were
    /// never affected; this closes the gap for the path users actually hit
    /// first. Defaults to [`ProgressSink::none`], so an embedder that doesn't
    /// opt in behaves exactly as before.
    ambient_progress: ProgressSink,
}

#[derive(Debug, Clone, Deserialize)]
struct ModelUpgradeRule {
    from_ids: Vec<String>,
    to_id: String,
    reason: String,
    target_runtime: Option<String>,
    target_runtime_requirement: Option<String>,
    #[serde(default)]
    minimum_runtimes: Vec<ModelRuntimeRequirement>,
    #[serde(default = "default_remove_old_after_available")]
    remove_old_after_available: bool,
}

fn default_remove_old_after_available() -> bool {
    true
}

/// `resolved` is the per-refresh credential memo (car-releases#75). `None` means
/// "no memo, look it up" — correct for the single-model `register` path, where
/// there is nothing to deduplicate. `refresh_availability` passes `Some`, so a
/// catalog with dozens of rows over a dozen providers does a dozen keychain
/// reads instead of dozens.
fn proprietary_auth_available(
    model_id: &str,
    schema_provider: &str,
    source_provider: &str,
    auth: &ProprietaryAuth,
    parslee_oauth_available: bool,
    resolved: Option<&std::collections::HashMap<String, bool>>,
) -> bool {
    // Authentication is necessary but NOT sufficient for a PROXIED namespace.
    // The OAuth2Pkce arm below resolves to exactly "is a Parslee session signed
    // in", which is true regardless of what the gateway can actually serve —
    // so ten `parslee/openrouter/*` aliases advertised `available` while every
    // one of them 503'd with `openrouter_not_configured`, costing a benchmark
    // sweep that picked one on the strength of that claim (Parslee-ai/car#786).
    //
    // There is no discovery endpoint to consult instead (`parslee.capabilities`
    // enumerates product entitlements, not inference upstreams), so the gateway's
    // own answer to a real request is the only truthful signal there is. Once it
    // has told us, stop advertising — the catalog is then optimistic once and
    // self-correcting, rather than permanently wrong.
    //
    // Checked here rather than at the call sites so `register` and
    // `refresh_availability` cannot drift apart.
    if crate::openrouter::is_curated_managed_gateway_alias(model_id)
        && crate::openrouter::gateway_unconfigured()
    {
        return false;
    }
    match auth {
        ProprietaryAuth::ApiKeyEnv { env_var } | ProprietaryAuth::BearerTokenEnv { env_var } => {
            match resolved.and_then(|m| m.get(env_var).copied()) {
                Some(known) => known,
                None => car_secrets::resolve_env_or_keychain(env_var).is_some(),
            }
        }
        ProprietaryAuth::OAuth2Pkce { .. } => {
            schema_provider.eq_ignore_ascii_case("parslee")
                && source_provider.eq_ignore_ascii_case("parslee")
                && parslee_oauth_available
        }
    }
}

fn model_upgrade_rules() -> Vec<ModelUpgradeRule> {
    serde_json::from_str(include_str!("../assets/model-upgrades.json"))
        .expect("built-in model-upgrades.json should parse")
}

impl UnifiedRegistry {
    pub fn new(models_dir: PathBuf) -> Self {
        let catalog_public_key = std::env::var("CAR_CATALOG_PUBKEY").ok();
        Self::new_with_catalog_public_key(models_dir, catalog_public_key.as_deref())
    }

    fn new_with_catalog_public_key(models_dir: PathBuf, catalog_public_key: Option<&str>) -> Self {
        let user_config_path = models_dir
            .parent()
            .unwrap_or(&models_dir)
            .join("models.json");

        let mut registry = Self {
            models_dir,
            models: HashMap::new(),
            user_config_ids: HashSet::new(),
            user_config_path,
            ambient_progress: ProgressSink::none(),
        };
        registry.load_builtin_catalog();
        // Refreshable signed catalog (E1): a prior `refresh_catalog` stores the
        // exact authenticated body + signature envelope. Startup re-verifies
        // that envelope with the currently configured key before loading any
        // model on top of the built-ins.
        for schema in crate::catalog::load_cache(
            &crate::catalog::cache_path(&registry.models_dir),
            catalog_public_key,
        ) {
            registry.register_project_model(schema);
        }
        // Auto-discovered models (E2): Community-tier entries cached by a prior
        // discovery pass (provider /v1/models). Loaded on top of built-ins +
        // signed catalog, but never *overwriting* a curated/signed entry of the
        // same id — discovery only ever ADDS models the catalog doesn't have.
        for schema in
            crate::discovery::load_cache(&crate::discovery::cache_path(&registry.models_dir))
        {
            if !registry.models.contains_key(&schema.id) {
                registry.register(schema);
            }
        }
        registry.refresh_availability();
        // Load user config on top (silently ignore if missing)
        let _ = registry.load_user_config();
        // Surface models the user pulled/placed under ~/.car/models/ that no
        // catalog or user-config entry covers, so a locally-present model is
        // visible and routable instead of invisible (car-releases#62).
        registry.discover_on_disk_models();
        registry
    }

    /// Test-only: a registry with NO builtin catalog, signed cache, discovery
    /// cache, or user config — only the models a test explicitly `register`s.
    /// Routing unit tests that assert a synthetic model wins MUST use this:
    /// `new()` loads the real builtin frontier models, which become routable
    /// candidates the moment a test sets their `api_key_env` (e.g.
    /// `OPENAI_API_KEY`) — and once those models carry real benchmark scores
    /// (e.g. car-judged), they legitimately outrank the synthetic stand-ins and
    /// silently break the test's assumption. An empty registry keeps the test
    /// hermetic.
    #[cfg(test)]
    pub fn new_empty(models_dir: PathBuf) -> Self {
        let user_config_path = models_dir
            .parent()
            .unwrap_or(&models_dir)
            .join("models.json");
        Self {
            models_dir,
            models: HashMap::new(),
            user_config_ids: HashSet::new(),
            user_config_path,
            ambient_progress: ProgressSink::none(),
        }
    }

    /// Register on-disk models under `models_dir` that nothing else already
    /// covers. Curated catalog entries already light up via the
    /// availability check (their `name` maps to `<models_dir>/<name>`), so
    /// this only fills the gap for *uncatalogued* local models — e.g. a
    /// model a user fetched by hand.
    ///
    /// Capability guessing from a bare directory is unreliable, and
    /// mis-tagging a speech/vision/video checkpoint as `Generate` would
    /// poison routing. So this is deliberately conservative: it only
    /// registers text LLMs it can positively identify by a recognized
    /// `model_type` in `config.json` (MLX) or by a GGUF weight file, infers
    /// embed/rerank from the directory name, and skips everything else.
    /// car-releases#62.
    fn discover_on_disk_models(&mut self) {
        let entries = match std::fs::read_dir(&self.models_dir) {
            Ok(e) => e,
            Err(_) => return,
        };
        // Names already registered (case-insensitive) — never shadow a
        // curated/user/discovered entry with an inferred one.
        let known: std::collections::HashSet<String> = self
            .models
            .values()
            .map(|m| m.name.to_ascii_lowercase())
            .collect();

        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let Some(name) = path
                .file_name()
                .and_then(|n| n.to_str())
                .map(str::to_string)
            else {
                continue;
            };
            if known.contains(&name.to_ascii_lowercase()) {
                continue;
            }

            let Some(schema) = synthesize_local_schema(&name, &path) else {
                continue;
            };
            tracing::info!(
                id = %schema.id,
                name = %name,
                "auto-discovered uncatalogued local model under models_dir (car-releases#62)"
            );
            self.register(schema);
        }
    }

    /// Register a model at a public runtime boundary.
    ///
    /// Callers cannot confer project curation: even a legacy schema whose
    /// omitted `trust_tier` deserializes as `Curated` is normalized to
    /// `Community` here. Project-owned builtins and signature-verified catalogs
    /// use the crate-private [`register_project_model`](Self::register_project_model)
    /// boundary instead.
    pub fn register(&mut self, mut schema: ModelSchema) {
        if crate::openrouter::is_curated_managed_gateway_alias(&schema.id) {
            warn!(id = %schema.id, "ignoring user registration for reserved Parslee-managed alias");
            return;
        }
        schema.mark_user_registered();
        self.register_preserving_trust(schema);
    }

    /// Register a model whose provenance was established by CAR itself.
    ///
    /// This trust-preserving path is intentionally crate-private. Production
    /// callers are limited to compiled builtins and signature-verified catalog
    /// rows; tests may use it to construct project-curated fixtures.
    pub(crate) fn register_project_model(&mut self, schema: ModelSchema) {
        self.register_preserving_trust(schema);
    }

    fn register_preserving_trust(&mut self, mut schema: ModelSchema) {
        // Check availability for local models
        if schema.is_mlx() {
            // MLX requires Apple Silicon Metal. On any other build target —
            // Intel Mac, Linux, Windows, or `car_skip_mlx` — the backend
            // is not compiled in and any execution attempt would fail at
            // dispatch with a "model not found" or backend-missing error.
            // Mirror the AppleFoundationModels cfg-gating below: the
            // registry must reflect that the model is *not* runnable here
            // so the adaptive router doesn't add it to fallback chains
            // (Parslee-ai/car#231 — §7.1, the "fresh Windows install has
            // no usable inference path" finding). Same shape as the
            // `refresh_availability` MLX branch.
            #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
            {
                schema.available = if schema.tags.contains(&"speech".to_string()) {
                    speech_mlx_available()
                } else if let ModelSource::Mlx { ref hf_repo, .. } = schema.source {
                    // Available if cached locally OR has an hf_repo —
                    // ensure_local() lazy-downloads on first use, so a
                    // declared hf_repo is "functionally available" the
                    // same way Ollama/RemoteApi entries are. Mirrors the
                    // refresh_availability() check below; see #164.
                    let mlx_dir = self.models_dir.join(&schema.name);
                    mlx_dir_has_weights(&mlx_dir) || !hf_repo.is_empty()
                } else {
                    let mlx_dir = self.models_dir.join(&schema.name);
                    mlx_dir_has_weights(&mlx_dir)
                };
            }
            #[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx))))]
            {
                schema.available = false;
            }
        } else if schema.is_vllm_mlx() {
            // vLLM-MLX: available if endpoint env var set or was manually marked available
            schema.available = std::env::var("VLLM_MLX_ENDPOINT").is_ok() || schema.available;
        } else if matches!(schema.source, ModelSource::WhisperCpp { .. }) {
            // whisper.cpp compiles on every platform and lazy-downloads its ggml
            // model on first use, so it's functionally available everywhere
            // (mirrors refresh_availability). Checked before the is_local() GGUF
            // branch below — whisper is_local() too but has no model.gguf.
            schema.available = true;
        } else if matches!(schema.source, ModelSource::WindowsSpeech {}) {
            // OS-provided WinRT synthesizer — available on Windows only.
            schema.available = cfg!(target_os = "windows");
        } else if schema.is_local() {
            let local_path = self.models_dir.join(&schema.name).join("model.gguf");
            schema.available = local_path.exists();
        } else if schema.is_remote() {
            // Remote models are available when their credential is present.
            // A credential counts whether it's in the env OR the OS keychain
            // (`resolve_env_or_keychain`) — matching the request path. Gating on
            // env-only marks a keychain-configured model unavailable, so the
            // router silently skips it (native-app users never set env vars).
            schema.available = match schema.source {
                ModelSource::RemoteApi {
                    protocol: crate::schema::ApiProtocol::OpenRouter,
                    ..
                } => crate::openrouter::credential_source().is_some(),
                ModelSource::RemoteApi {
                    ref api_key_env, ..
                } => car_secrets::resolve_env_or_keychain(api_key_env).is_some(),
                // Proprietary: available only when a credential resolves — keep
                // this in sync with `refresh_availability`.
                ModelSource::Proprietary {
                    ref provider,
                    ref auth,
                    ..
                } => proprietary_auth_available(
                    &schema.id,
                    &schema.provider,
                    provider,
                    auth,
                    car_auth::access_token_is_available(),
                    // Single model — nothing to deduplicate.
                    None,
                ),
                _ => schema.available,
            };
        }
        // Ready = usable without a download. For anything local that means
        // weights resolvable on disk *now*; `available` alone can't answer this,
        // since a declared `hf_repo` makes an MLX model "available" before a
        // byte is fetched (#164). Remote models never need a weights download.
        // Their live credential state belongs in `available`; coupling it to
        // `weights_ready` permanently excludes models registered before a key
        // is connected from `require_ready` routes.
        // See `ModelSchema::weights_ready` (Parslee-ai/car#638).
        // NOTE: `is_mlx()` must be tested before `is_local()` — `is_local()`
        // returns true for `ModelSource::Mlx` too, so the GGUF branch would
        // otherwise swallow every MLX model and look for a `model.gguf` that
        // never exists.
        schema.weights_ready = if schema.is_mlx() {
            mlx_dir_has_weights(&self.models_dir.join(&schema.name))
        } else if let ModelSource::WhisperCpp { model } = &schema.source {
            // whisper's ggml lives in ~/.tokhn/whisper/, not models_dir/model.gguf.
            car_whisper::model_cached(model)
        } else if matches!(schema.source, ModelSource::WindowsSpeech {}) {
            // OS-provided (WinRT) — no weights to download.
            true
        } else if schema.is_local() {
            self.models_dir
                .join(&schema.name)
                .join("model.gguf")
                .exists()
        } else {
            // Remote, vLLM-MLX, Apple FoundationModels, delegated: nothing
            // needs to be downloaded before an attempt.
            true
        };
        info!(
            id = %schema.id,
            name = %schema.name,
            available = schema.available,
            weights_ready = schema.weights_ready,
            "registered model"
        );
        self.models.insert(schema.id.clone(), schema);
    }

    /// Register a schema that crossed the user-controlled configuration
    /// boundary.
    ///
    /// This is deliberately separate from [`register`](Self::register):
    /// builtin, signed-catalog, and discovery rows must never become
    /// `models.json` rows merely because they share the same in-memory map.
    pub fn register_user_model(&mut self, mut schema: ModelSchema) {
        if crate::openrouter::is_curated_managed_gateway_alias(&schema.id) {
            warn!(id = %schema.id, "ignoring persisted user model for reserved Parslee-managed alias");
            return;
        }
        schema.mark_user_registered();
        let id = schema.id.clone();
        self.register_preserving_trust(schema);
        self.user_config_ids.insert(id);
    }

    /// Unregister a model by id. Returns the removed schema if found.
    pub fn unregister(&mut self, id: &str) -> Option<ModelSchema> {
        let removed = self.models.remove(id);
        if let Some(ref m) = removed {
            info!(id = %m.id, "unregistered model");
        }
        removed
    }

    /// Unregister an explicitly user-configured model.
    ///
    /// An untracked builtin, signed-catalog, or discovery row is not removable
    /// through this persistence boundary.
    pub fn unregister_user_model(&mut self, id: &str) -> Option<ModelSchema> {
        if !self.user_config_ids.remove(id) {
            return None;
        }
        self.unregister(id)
    }

    /// List all models.
    pub fn list(&self) -> Vec<&ModelSchema> {
        let mut models: Vec<&ModelSchema> = self.models.values().collect();
        models.sort_by(|a, b| a.id.cmp(&b.id));
        models
    }

    /// Query models matching a filter.
    pub fn query(&self, filter: &ModelFilter) -> Vec<&ModelSchema> {
        self.models
            .values()
            .filter(|m| {
                // Capability check: model must have ALL required capabilities
                if !filter.capabilities.iter().all(|c| m.has_capability(*c)) {
                    return false;
                }
                // Size check
                if let Some(max) = filter.max_size_mb {
                    if m.size_mb() > max && m.is_local() {
                        return false;
                    }
                }
                // Latency check (declared envelope)
                if let Some(max) = filter.max_latency_ms {
                    if let Some(p50) = m.performance.latency_p50_ms {
                        if p50 > max {
                            return false;
                        }
                    }
                }
                // Cost check
                if let Some(max) = filter.max_cost_per_mtok {
                    if let Some(cost) = m.cost.output_per_mtok {
                        if cost > max {
                            return false;
                        }
                    }
                }
                // Tag check
                if !filter.tags.iter().all(|t| m.tags.contains(t)) {
                    return false;
                }
                // Provider check
                if let Some(ref p) = filter.provider {
                    if &m.provider != p {
                        return false;
                    }
                }
                // Local only
                if filter.local_only && !m.is_local() {
                    return false;
                }
                // Available only
                if filter.available_only && !m.available_now() {
                    return false;
                }
                true
            })
            .collect()
    }

    /// Query models by a single capability.
    pub fn query_by_capability(&self, cap: ModelCapability) -> Vec<&ModelSchema> {
        self.query(&ModelFilter {
            capabilities: vec![cap],
            ..Default::default()
        })
    }

    /// Report installed local models with curated newer replacements.
    pub fn available_upgrades(&self) -> Vec<ModelUpgrade> {
        let mut upgrades = Vec::new();
        for rule in model_upgrade_rules() {
            let Some(from) = rule
                .from_ids
                .iter()
                .find_map(|id| self.models.get(id.as_str()))
                .filter(|schema| schema.available)
            else {
                continue;
            };
            let Some(to) = self.models.get(rule.to_id.as_str()) else {
                continue;
            };
            upgrades.push(ModelUpgrade {
                from_id: from.id.clone(),
                from_name: from.name.clone(),
                to_id: to.id.clone(),
                to_name: to.name.clone(),
                reason: rule.reason.clone(),
                target_runtime: rule.target_runtime.clone(),
                target_runtime_requirement: rule.target_runtime_requirement.clone(),
                minimum_runtimes: rule.minimum_runtimes.clone(),
                target_available: to.available,
                target_pullable: matches!(
                    to.source,
                    ModelSource::Local { .. } | ModelSource::Mlx { .. }
                ),
                remove_old_supported: matches!(
                    from.source,
                    ModelSource::Local { .. } | ModelSource::Mlx { .. }
                ) && rule.remove_old_after_available,
            });
        }
        upgrades.sort_by(|a, b| a.from_id.cmp(&b.from_id).then(a.to_id.cmp(&b.to_id)));
        upgrades.dedup_by(|a, b| a.from_id == b.from_id && a.to_id == b.to_id);
        upgrades
    }

    /// Get a specific model by id.
    pub fn get(&self, id: &str) -> Option<&ModelSchema> {
        self.models.get(id)
    }

    /// Return the currently registered schema without refreshing availability.
    ///
    /// Callers that need runtime credential/file state must explicitly use a
    /// refreshing snapshot; identity/provenance checks should use this exact
    /// stored row instead.
    pub fn registered_schema(&self, id: &str) -> Option<&ModelSchema> {
        self.get(id)
    }

    /// Iterate all registered model schemas (built-in + signed + discovered).
    pub fn all(&self) -> impl Iterator<Item = &ModelSchema> {
        self.models.values()
    }

    /// Find a model by name (case-insensitive). For backward compatibility
    /// with the old registry that used short names like "Qwen3-4B".
    pub fn find_by_name(&self, name: &str) -> Option<&ModelSchema> {
        #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
        if !name.to_ascii_lowercase().ends_with("-mlx") {
            if let Some(mlx_variant) = self
                .models
                .values()
                .find(|m| m.name.eq_ignore_ascii_case(&format!("{name}-MLX")))
            {
                return Some(mlx_variant);
            }
        }

        self.models
            .values()
            .find(|m| m.name.eq_ignore_ascii_case(name))
    }

    /// On Apple Silicon, resolve a GGUF/Candle model to its MLX equivalent.
    /// Returns the MLX model schema if one exists with the same family and
    /// matching capabilities; otherwise returns None.
    #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
    pub fn resolve_mlx_equivalent(&self, schema: &ModelSchema) -> Option<&ModelSchema> {
        // Already MLX — no redirect needed.
        if schema.is_mlx() || schema.is_vllm_mlx() {
            return None;
        }
        // Only redirect local GGUF models.
        if !matches!(schema.source, ModelSource::Local { .. }) {
            return None;
        }
        // Find the MLX twin: same family, SAME PARAMETER COUNT, and at least
        // the same primary capability. Family alone is too coarse — every
        // Qwen3 size shares family "qwen3", so a family-only `.find()` could
        // map an 8B GGUF to a 4B MLX model (whichever the HashMap yielded
        // first), silently swapping model size at execution and routing.
        // Keying on param_count makes the resolution deterministic and 1:1.
        let primary_cap = schema.capabilities.first()?;
        self.models.values().find(|m| {
            m.is_mlx()
                && m.family == schema.family
                && m.param_count == schema.param_count
                && m.capabilities.contains(primary_cap)
        })
    }

    /// Ensure a local model is downloaded, returning its local directory path.
    pub async fn ensure_local(&self, id: &str) -> Result<PathBuf, InferenceError> {
        // Report to the ambient sink rather than dropping the events on the
        // floor — see [`Self::ambient_progress`] (Parslee-ai/car#620). Still a
        // no-op sink unless an embedder opted in, so this is not a behaviour
        // change for anyone who hasn't.
        let sink = self.ambient_progress.clone();
        self.ensure_local_with_progress(id, &sink).await
    }

    /// Route implicit-download progress to `sink`.
    ///
    /// Applies to acquisitions nobody explicitly requested — the ones
    /// [`ensure_local`](Self::ensure_local) performs mid-`generate` when the
    /// router lands on a model that isn't on disk. Explicit pulls take their
    /// sink as an argument and ignore this.
    pub fn set_ambient_progress(&mut self, sink: ProgressSink) {
        self.ambient_progress = sink;
    }

    /// Like [`ensure_local`](Self::ensure_local) but drives a progress sink and
    /// enforces the acquisition lifecycle: a per-model lock (so this can't race
    /// a concurrent pull / remove / upgrade of the same model), a disk-space
    /// preflight, and `Started`/`Completed`/`Failed` events around the work.
    pub async fn ensure_local_with_progress(
        &self,
        id: &str,
        sink: &ProgressSink,
    ) -> Result<PathBuf, InferenceError> {
        self.acquire_and_ensure(id, sink, false).await
    }

    /// Force a complete re-acquisition: skip the "reuse what's already on disk"
    /// short-circuits so every expected file is re-checked and any missing one
    /// (e.g. a blob the self-heal path purged as provably corrupt) is
    /// re-downloaded. The per-file checks still skip intact files, so this
    /// re-fetches only what's actually gone — not the whole model.
    pub async fn redownload_local(&self, id: &str) -> Result<PathBuf, InferenceError> {
        self.acquire_and_ensure(id, &ProgressSink::none(), true)
            .await
    }

    async fn acquire_and_ensure(
        &self,
        id: &str,
        sink: &ProgressSink,
        force: bool,
    ) -> Result<PathBuf, InferenceError> {
        let schema = self
            .get(id)
            .or_else(|| self.find_by_name(id))
            .ok_or_else(|| InferenceError::ModelNotFound(id.to_string()))?;
        let model_name = schema.name.clone();
        let model_id = schema.id.clone();
        let needed_mb = schema.size_mb();
        let model_dir = self.models_dir.join(&schema.name);

        // Serialize acquisition of this model id against other pull/remove tasks.
        let _guard = crate::download::acquire_model_lock(&model_id).await;

        // Preflight: fail fast if there isn't room, before touching disk.
        if let Err(e) = crate::download::check_disk_space(&model_dir, needed_mb) {
            sink.emit(DownloadEvent::Failed { error: e.clone() });
            return Err(InferenceError::DownloadFailed(e));
        }

        sink.emit(DownloadEvent::Started {
            model: model_name.clone(),
            total_files: 0,
            total_mb: needed_mb,
        });
        let result = self.ensure_local_inner(id, sink, force).await;
        match &result {
            Ok(_) => sink.emit(DownloadEvent::Completed { model: model_name }),
            Err(e) => sink.emit(DownloadEvent::Failed {
                error: e.to_string(),
            }),
        }
        result
    }

    async fn ensure_local_inner(
        &self,
        id: &str,
        sink: &ProgressSink,
        force: bool,
    ) -> Result<PathBuf, InferenceError> {
        let schema = self
            .get(id)
            .or_else(|| self.find_by_name(id))
            .ok_or_else(|| InferenceError::ModelNotFound(id.to_string()))?;

        match &schema.source {
            ModelSource::Local {
                hf_repo,
                hf_filename,
                tokenizer_repo,
            } => {
                let model_dir = self.models_dir.join(&schema.name);
                let model_path = model_dir.join("model.gguf");
                let tokenizer_path = model_dir.join("tokenizer.json");

                if !force
                    && crate::download::cache_file_usable(&model_path)
                    && crate::download::cache_file_usable(&tokenizer_path)
                {
                    return Ok(model_dir);
                }

                std::fs::create_dir_all(&model_dir)?;

                if !crate::download::cache_file_usable(&model_path) {
                    info!(model = %schema.name, repo = %hf_repo, "downloading model weights");
                    sink.emit(DownloadEvent::FileStarted {
                        filename: "model weights".into(),
                        index: 1,
                        total_files: 2,
                        size_mb: schema.size_mb(),
                    });
                    download_file(hf_repo, hf_filename, &model_path).await?;
                    sink.emit(DownloadEvent::FileCompleted {
                        filename: "model weights".into(),
                    });
                }
                if !crate::download::cache_file_usable(&tokenizer_path) {
                    info!(model = %schema.name, repo = %tokenizer_repo, "downloading tokenizer");
                    sink.emit(DownloadEvent::FileStarted {
                        filename: "tokenizer".into(),
                        index: 2,
                        total_files: 2,
                        size_mb: 0,
                    });
                    download_file(tokenizer_repo, "tokenizer.json", &tokenizer_path).await?;
                    sink.emit(DownloadEvent::FileCompleted {
                        filename: "tokenizer".into(),
                    });
                }

                Ok(model_dir)
            }
            ModelSource::Mlx {
                hf_repo,
                hf_weight_file,
            } => {
                let model_dir = self.models_dir.join(&schema.name);
                let config_path = model_dir.join("config.json");

                // Diffusers-layout models (Flux image-gen, LTX video) keep their
                // weights in component subdirs (transformer/, vae/, text_encoder/,
                // tokenizer/) and ship NO root config.json / top-level weight
                // index. The standard MLX flow below hard-fetches config.json
                // (404 for these repos) and a weight index (absent), so they need
                // the whole-repo snapshot path. Detect by capability so DOWNLOAD,
                // REUSE, and (via mlx_dir_has_weights) LOAD all agree on the
                // layout — the recurring image-gen 404 was fixing only the load
                // path (recurse subdirs) while download + reuse still demanded a
                // config.json these repos don't have.
                let is_diffusers = schema.capabilities.iter().any(|c| {
                    matches!(
                        c,
                        ModelCapability::ImageGeneration | ModelCapability::VideoGeneration
                    )
                });

                // Reuse the managed dir ONLY if it actually holds weights — a
                // config-only stub (or dangling-symlink install) must fall
                // through to the download below, not no-op (car-releases#391).
                // `force` (self-heal re-pull) skips reuse so a purged shard is
                // actually re-fetched rather than masked by the surviving shards.
                // Standard MLX also gates on the root config.json; diffusers has
                // none, so recursive weights-present is its completeness signal.
                if !force
                    && mlx_dir_has_weights(&model_dir)
                    && (is_diffusers || config_path.exists())
                {
                    ensure_auxiliary_mlx_files(&schema.name, hf_repo, &model_dir).await?;
                    info!(model = %schema.name, path = %model_dir.display(), "using managed local MLX model");
                    return Ok(model_dir);
                }

                // Same guard for a cached HF snapshot: a partial/pruned snapshot
                // whose weights don't resolve isn't usable — re-download instead.
                if !force {
                    if let Some(snapshot_dir) =
                        latest_huggingface_repo_snapshot(hf_repo).filter(|d| mlx_dir_has_weights(d))
                    {
                        ensure_auxiliary_mlx_files(&schema.name, hf_repo, &snapshot_dir).await?;
                        info!(model = %schema.name, path = %snapshot_dir.display(), "using cached MLX snapshot");
                        return Ok(snapshot_dir);
                    }
                }

                std::fs::create_dir_all(&model_dir)?;

                info!(model = %schema.name, repo = %hf_repo, "downloading MLX model");

                // Diffusers-layout: mirror the whole repo (component subdirs
                // preserved). There is no root config.json or weight index to
                // drive the file-by-file flow below, and demanding one is the
                // 404 that broke image/video generation. Verify component weights
                // actually landed so a half-finished pull can't masquerade as
                // installed (the false-availability the caller relies on).
                if is_diffusers {
                    download_repo_snapshot(hf_repo, &model_dir, sink).await?;
                    ensure_auxiliary_mlx_files(&schema.name, hf_repo, &model_dir).await?;
                    if !mlx_dir_has_weights(&model_dir) {
                        return Err(InferenceError::DownloadFailed(format!(
                            "{hf_repo}: snapshot fetched but no component weights found"
                        )));
                    }
                    info!(model = %schema.name, path = %model_dir.display(), "downloaded diffusers model");
                    return Ok(model_dir);
                }

                // Download config, tokenizer, and weight files. total_files is
                // not known up front for MLX (single vs sharded), so events
                // carry total_files = 0 ("unknown") and the UI shows names.
                emit_file(sink, "config", 0, schema.size_mb());
                download_file(hf_repo, "config.json", &config_path).await?;
                download_tokenizer_assets(hf_repo, &model_dir, sink).await;
                let tok_config_path = model_dir.join("tokenizer_config.json");
                if !crate::download::cache_file_usable(&tok_config_path) {
                    let _ = download_file(hf_repo, "tokenizer_config.json", &tok_config_path).await;
                }

                // Download weight files
                if let Some(ref wf) = hf_weight_file {
                    let wf_path = model_dir.join(wf);
                    if !crate::download::cache_file_usable(&wf_path) {
                        emit_file(sink, "model weights", 0, schema.size_mb());
                        download_file(hf_repo, wf, &wf_path).await?;
                    }
                } else {
                    // Try single file first, then sharded
                    let single = model_dir.join("model.safetensors");
                    if !crate::download::cache_file_usable(&single) {
                        emit_file(sink, "model weights", 0, schema.size_mb());
                        match download_file(hf_repo, "model.safetensors", &single).await {
                            Ok(()) => {}
                            Err(_) => {
                                // Sharded: download index and then each shard
                                let index_path = model_dir.join("model.safetensors.index.json");
                                download_file(hf_repo, "model.safetensors.index.json", &index_path)
                                    .await?;

                                let index_json: serde_json::Value =
                                    serde_json::from_str(&std::fs::read_to_string(&index_path)?)
                                        .map_err(|e| {
                                            InferenceError::InferenceFailed(format!(
                                                "parse index: {e}"
                                            ))
                                        })?;

                                if let Some(weight_map) =
                                    index_json.get("weight_map").and_then(|m| m.as_object())
                                {
                                    let mut files: std::collections::HashSet<String> =
                                        std::collections::HashSet::new();
                                    for filename in weight_map.values() {
                                        if let Some(f) = filename.as_str() {
                                            files.insert(f.to_string());
                                        }
                                    }
                                    let shard_total = files.len() as u32;
                                    for (i, file) in files.iter().enumerate() {
                                        let dest = model_dir.join(file);
                                        if !crate::download::cache_file_usable(&dest) {
                                            info!(file = %file, "downloading weight shard");
                                            sink.emit(DownloadEvent::FileStarted {
                                                filename: format!("weights part {}", i + 1),
                                                index: (i + 1) as u32,
                                                total_files: shard_total,
                                                size_mb: 0,
                                            });
                                            download_file(hf_repo, file, &dest).await?;
                                            sink.emit(DownloadEvent::FileCompleted {
                                                filename: format!("weights part {}", i + 1),
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                ensure_auxiliary_mlx_files(&schema.name, hf_repo, &model_dir).await?;

                // Verify what we actually landed, exactly as the diffusers branch
                // above does (#808). Without this, a pull whose shard fetch was
                // interrupted returned `Ok(model_dir)` — indistinguishable from
                // success — and the model stayed broken until inference failed
                // with `load model-00001-of-00002.safetensors: Path must point to
                // a local file`, inside whatever job was running.
                //
                // A caller reaching for the two obvious mechanisms — check
                // availability, then pull — got "yes" and "ok" from both while
                // the model was unusable. Report the missing shards by name so
                // the failure is actionable at pull time.
                let missing = missing_weight_shards(&model_dir);
                if !missing.is_empty() {
                    return Err(InferenceError::DownloadFailed(format!(
                        "{}: pull finished but {} weight shard(s) are still missing: {}. \
                         The download was interrupted; re-run the pull to resume it.",
                        schema.name,
                        missing.len(),
                        missing.join(", ")
                    )));
                }
                if !mlx_dir_has_weights(&model_dir) {
                    return Err(InferenceError::DownloadFailed(format!(
                        "{}: pull finished but no usable weights are present under {}",
                        schema.name,
                        model_dir.display()
                    )));
                }
                Ok(model_dir)
            }
            _ => Err(InferenceError::InferenceFailed(format!(
                "model {} is not local",
                id
            ))),
        }
    }

    /// Remove a downloaded local model.
    pub fn remove_local(&mut self, id: &str) -> Result<(), InferenceError> {
        let schema = self
            .get(id)
            .or_else(|| self.find_by_name(id))
            .ok_or_else(|| InferenceError::ModelNotFound(id.to_string()))?;

        // Collect every directory to remove up front (clone out of the
        // borrowed schema so we can mutate `self.models` afterward).
        let name = schema.name.clone();
        let id = schema.id.clone();
        let mut targets: Vec<std::path::PathBuf> = vec![self.models_dir.join(&name)];
        match &schema.source {
            ModelSource::Mlx { hf_repo, .. } => {
                targets.push(huggingface_repo_dir(hf_repo));
            }
            ModelSource::Local {
                hf_repo,
                tokenizer_repo,
                ..
            } => {
                targets.push(huggingface_repo_dir(hf_repo));
                targets.push(huggingface_repo_dir(tokenizer_repo));
            }
            _ => {}
        }

        // Best-effort, all-or-most: a failure deleting one directory must not
        // abort the rest (which would leak the remaining caches) NOR skip the
        // availability flip below (which would leave the registry claiming a
        // model whose weights are already gone is still `available`). Record
        // the first error and keep going; the flag is always corrected.
        let mut first_err: Option<std::io::Error> = None;
        for dir in &targets {
            if dir.exists() {
                match std::fs::remove_dir_all(dir) {
                    Ok(()) => info!(model = %name, dir = %dir.display(), "removed model artifacts"),
                    Err(e) => {
                        tracing::warn!(model = %name, dir = %dir.display(), error = %e, "failed to remove model artifacts");
                        if first_err.is_none() {
                            first_err = Some(e);
                        }
                    }
                }
            }
        }

        // Update availability regardless of partial deletion failures.
        if let Some(m) = self.models.get_mut(&id) {
            m.available = false;
        }

        match first_err {
            Some(e) => Err(e.into()),
            None => Ok(()),
        }
    }

    /// Refresh availability flags for all models.
    ///
    /// Runtime-true vs catalog-says: this is what closes the gap
    /// `models.list_unified` callers rely on. If a model is listed
    /// as `available: true` here, an `infer` call against it should
    /// reach the backend, not bail with `UnsupportedMode { ...
    /// "mlx-vlm CLI not found on PATH" }` (the #137 trap).
    pub fn refresh_availability(&mut self) {
        // `models_dir` is consumed only inside the MLX and Local arms.
        // On non-MLX targets the MLX arm is a cfg-gated `available = false`
        // and never touches `models_dir`; the Local arm still needs it.
        let models_dir = self.models_dir.clone();
        // mlx-vlm CLI is the same probe call no matter which model
        // requires it; do it once per refresh, not per-model. On
        // non-MLX targets the variable is unused (the consuming arm
        // is cfg-gated out), so suppress the unused-variable warning.
        #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
        let mlx_vlm_cli_present = crate::backend::mlx_vlm_cli::is_available();
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx))))]
        #[allow(unused_variables)]
        let mlx_vlm_cli_present = false;
        // Parslee OAuth availability is authoritative V2 auth state, with the
        // bounded pre-V2 migration seam only when no V2 record exists. Capture
        // it once so every managed row in this routing snapshot sees the same
        // state without repeating a secret-store read per alias.
        let parslee_oauth_available = car_auth::access_token_is_available();
        // A learned "gateway has no OpenRouter upstream" is about the
        // environment behind THIS session. When the session is gone, so is the
        // evidence — otherwise a sign-in to a properly-configured org would
        // inherit the previous one's suppression (Parslee-ai/car#786).
        if !parslee_oauth_available {
            crate::openrouter::clear_gateway_unconfigured();
        }

        // Resolve each DISTINCT credential once, not once per model
        // (car-releases#75).
        //
        // Every `RemoteApi` and `Proprietary` row used to call
        // `resolve_env_or_keychain` inside the loop below, and on macOS that is
        // a keychain query — ~14 ms each. A stock catalog is ~72 models over
        // roughly a dozen providers, so a refresh spent ~1 s asking the keychain
        // the same handful of questions dozens of times. `routing_registry_
        // snapshot` runs a refresh per request AND `estimated_tokens` runs
        // another, so a single delegated call paid it twice: ~2 s before the
        // request reached the runner, which is the reported latency.
        //
        // Deduplicating changes no semantics. Within ONE refresh the same env
        // var must yield the same answer — reading it 30 times cannot be more
        // correct than reading it once. Credentials are still re-read on every
        // refresh, so the "pasted/OAuth key changes take effect without a
        // restart" property above is untouched.
        let mut credential_envs: std::collections::BTreeSet<String> = Default::default();
        let mut needs_openrouter = false;
        for m in self.models.values() {
            match &m.source {
                ModelSource::RemoteApi {
                    protocol: crate::schema::ApiProtocol::OpenRouter,
                    ..
                } => needs_openrouter = true,
                ModelSource::RemoteApi { api_key_env, .. } => {
                    credential_envs.insert(api_key_env.clone());
                }
                ModelSource::Proprietary { auth, .. } => match auth {
                    ProprietaryAuth::ApiKeyEnv { env_var }
                    | ProprietaryAuth::BearerTokenEnv { env_var } => {
                        credential_envs.insert(env_var.clone());
                    }
                    ProprietaryAuth::OAuth2Pkce { .. } => {}
                },
                _ => {}
            }
        }
        let credential_available: std::collections::HashMap<String, bool> = credential_envs
            .into_iter()
            .map(|env| {
                let ok = car_secrets::resolve_env_or_keychain(&env).is_some();
                (env, ok)
            })
            .collect();
        // Only probe OpenRouter when a row actually needs it — an unnecessary
        // probe is the same class of waste this block exists to remove.
        let openrouter_available =
            needs_openrouter && crate::openrouter::credential_source().is_some();

        for m in self.models.values_mut() {
            match &m.source {
                ModelSource::Mlx { hf_repo, .. } => {
                    // MLX requires Apple Silicon Metal. On any other
                    // build target — Intel Mac, Linux, Windows, or
                    // `car_skip_mlx` — the backend is not compiled in
                    // and the adaptive router must not select these
                    // models. Cfg-gate identical to the
                    // AppleFoundationModels branch below and the
                    // `register()` MLX branch above. Closes the §7.1
                    // arm of Parslee-ai/car#231.
                    #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
                    {
                        // Models tagged `requires-mlx-vlm` shell out to the
                        // mlx_vlm Python CLI for image inference (#115).
                        // If the CLI isn't on PATH, the runtime reaches it
                        // anyway and bails — the registry MUST reflect that
                        // by marking such entries unavailable until the
                        // user installs `uv tool install mlx-vlm`. #137.
                        let needs_mlx_vlm = m.tags.iter().any(|t| t == "requires-mlx-vlm");

                        m.available = if needs_mlx_vlm {
                            mlx_vlm_cli_present
                        } else if m.tags.contains(&"speech".to_string()) {
                            speech_mlx_available()
                        } else {
                            // Available if cached locally OR has an hf_repo —
                            // the native MLX path's ensure_local() lazy-
                            // downloads on first use, so a declared hf_repo
                            // is "functionally available" the same way
                            // Ollama and RemoteApi entries are ("should
                            // work in principle" not "physically cached").
                            // Closes #164: mlx/ltx-2.3:q4 reported
                            // unavailable even though `car video` would
                            // just download-and-run successfully.
                            let mlx_dir = models_dir.join(&m.name);
                            mlx_dir_has_weights(&mlx_dir) || !hf_repo.is_empty()
                        };
                    }
                    #[cfg(not(all(
                        target_os = "macos",
                        target_arch = "aarch64",
                        not(car_skip_mlx)
                    )))]
                    {
                        let _ = hf_repo; // unused on non-MLX targets
                        m.available = false;
                    }
                }
                ModelSource::Local { .. } => {
                    let local_path = models_dir.join(&m.name).join("model.gguf");
                    m.available = local_path.exists();
                }
                ModelSource::WhisperCpp { .. } => {
                    // whisper.cpp compiles on every platform and lazy-downloads
                    // its ggml model on first use (car-whisper), so it is
                    // functionally available everywhere — the cross-platform
                    // on-device STT the MLX speech models can't be off Apple.
                    m.available = true;
                }
                ModelSource::WindowsSpeech {} => {
                    // OS-provided WinRT synthesizer — available on Windows only
                    // (like AppleFoundationModels is Apple-only).
                    #[cfg(target_os = "windows")]
                    {
                        m.available = true;
                    }
                    #[cfg(not(target_os = "windows"))]
                    {
                        m.available = false;
                    }
                }
                ModelSource::RemoteApi {
                    protocol: crate::schema::ApiProtocol::OpenRouter,
                    ..
                } => {
                    m.available = openrouter_available;
                }
                ModelSource::RemoteApi { api_key_env, .. } => {
                    // env OR keychain — see `register`. Resolved once per
                    // refresh above, not once per model (car-releases#75).
                    m.available = credential_available
                        .get(api_key_env)
                        .copied()
                        .unwrap_or(false);
                }
                ModelSource::Ollama { .. } => {
                    // Assume available; health check is async and done lazily
                    m.available = true;
                }
                ModelSource::VllmMlx { .. } => {
                    // vLLM-MLX availability checked via health endpoint lazily
                    // Mark as available if VLLM_MLX_ENDPOINT env var is set or default endpoint assumed
                    m.available = std::env::var("VLLM_MLX_ENDPOINT").is_ok() || m.available;
                    // preserve manual registration
                }
                ModelSource::Proprietary { provider, auth, .. } => {
                    m.available = proprietary_auth_available(
                        &m.id,
                        &m.provider,
                        provider,
                        auth,
                        parslee_oauth_available,
                        Some(&credential_available),
                    );
                }
                ModelSource::AppleFoundationModels { .. } => {
                    // Apple Silicon macOS 26+ AND iOS 26+ both expose
                    // the FoundationModels framework. The shim's
                    // runtime probe handles per-device availability
                    // (Apple Intelligence may be off, the device may
                    // be pre-A17, etc.); cfg-gating here just hides
                    // the call on targets where the shim isn't built.
                    #[cfg(any(
                        all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)),
                        all(target_os = "ios", target_arch = "aarch64")
                    ))]
                    {
                        m.available = crate::backend::foundation_models::is_available();
                    }
                    #[cfg(not(any(
                        all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)),
                        all(target_os = "ios", target_arch = "aarch64")
                    )))]
                    {
                        m.available = false;
                    }
                }
                ModelSource::Delegated { .. } => {
                    // Availability tracks whether a runner is registered.
                    // Hosts call `registerInferenceRunner` (or its
                    // language equivalent) at startup; until then the
                    // model is unavailable.
                    m.available = crate::runner::current_inference_runner().is_some();
                }
            }
            m.weights_ready = if m.is_mlx() {
                mlx_dir_has_weights(&models_dir.join(&m.name))
            } else if let ModelSource::WhisperCpp { model } = &m.source {
                // whisper's ggml lives in ~/.tokhn/whisper/, not model.gguf.
                car_whisper::model_cached(model)
            } else if matches!(m.source, ModelSource::WindowsSpeech {}) {
                // OS-provided (WinRT) — no weights to download.
                true
            } else if m.is_local() {
                models_dir.join(&m.name).join("model.gguf").exists()
            } else {
                true
            };
        }
    }

    /// Persist only explicitly user-registered models to disk.
    pub fn save_user_config(&self) -> Result<(), InferenceError> {
        let mut user_models: Vec<ModelSchema> = self
            .user_config_ids
            .iter()
            .filter_map(|id| self.models.get(id))
            .cloned()
            .map(|mut model| {
                // `models.json` is a user-controlled trust boundary regardless
                // of how the in-memory row was originally registered.
                model.mark_user_registered();
                model
            })
            .collect();
        user_models.sort_by(|a, b| a.id.cmp(&b.id));

        let json = serde_json::to_string_pretty(&user_models)
            .map_err(|e| InferenceError::InferenceFailed(format!("serialize: {e}")))?;
        std::fs::write(&self.user_config_path, json)?;
        Ok(())
    }

    /// Load user-registered models from disk.
    pub fn load_user_config(&mut self) -> Result<(), InferenceError> {
        if !self.user_config_path.exists() {
            return Ok(());
        }

        let json = std::fs::read_to_string(&self.user_config_path)?;
        let models: Vec<ModelSchema> = serde_json::from_str(&json)
            .map_err(|e| InferenceError::InferenceFailed(format!("parse models.json: {e}")))?;

        for m in models {
            // Legacy rows omit `trust_tier` and serde must keep accepting that
            // shape, but a manual config can never confer project curation.
            self.register_user_model(m);
        }
        Ok(())
    }

    /// Get the models directory path.
    pub fn models_dir(&self) -> &Path {
        &self.models_dir
    }

    /// Whether invoking this model can start without CAR-managed model setup.
    ///
    /// `available` deliberately includes lazy-downloadable local models so
    /// normal CLI inference can pull on first use. Interactive host actions
    /// need the stricter answer: avoid starting a large download from a
    /// ready-to-use assistant button and point the user at Models setup
    /// instead.
    pub fn ready_without_download(&self, id: &str) -> Option<bool> {
        let schema = self.get(id).or_else(|| self.find_by_name(id))?;
        Some(match &schema.source {
            ModelSource::Local { .. } => {
                let model_dir = self.models_dir.join(&schema.name);
                crate::download::cache_file_usable(&model_dir.join("model.gguf"))
                    && crate::download::cache_file_usable(&model_dir.join("tokenizer.json"))
            }
            ModelSource::Mlx { hf_repo, .. } => {
                let managed_dir = self.models_dir.join(&schema.name);
                let managed_ready =
                    crate::download::cache_file_usable(&managed_dir.join("config.json"))
                        && crate::download::cache_file_usable(&managed_dir.join("tokenizer.json"))
                        && mlx_dir_has_weights(&managed_dir)
                        && mlx_auxiliary_ready_without_download(&schema.name, &managed_dir);
                let snapshot_ready = latest_huggingface_repo_snapshot(hf_repo)
                    .filter(|dir| {
                        crate::download::cache_file_usable(&dir.join("config.json"))
                            && crate::download::cache_file_usable(&dir.join("tokenizer.json"))
                            && mlx_dir_has_weights(dir)
                            && mlx_auxiliary_ready_without_download(&schema.name, dir)
                    })
                    .is_some();
                managed_ready || snapshot_ready
            }
            ModelSource::WindowsSpeech {} => true, // OS-provided; nothing to download
            ModelSource::WhisperCpp { model } => {
                // "ready without download" = the ggml file is physically cached
                // at ~/.tokhn/whisper/. (Availability is looser — whisper always
                // lazy-downloads — but this is the strict host-action answer.)
                car_whisper::model_cached(model)
            }
            ModelSource::RemoteApi { .. }
            | ModelSource::Ollama { .. }
            | ModelSource::VllmMlx { .. }
            | ModelSource::AppleFoundationModels { .. }
            | ModelSource::Proprietary { .. }
            | ModelSource::Delegated { .. } => true,
        })
    }

    /// Load the built-in Qwen3 catalog as ModelSchema objects.
    fn load_builtin_catalog(&mut self) {
        for schema in builtin_catalog() {
            self.register_project_model(schema);
        }
    }
}

/// Build a `ModelSchema` for an uncatalogued local model directory, or
/// `None` if the directory isn't a recognized text-LLM checkpoint.
///
/// Recognizes two layouts: MLX (a `config.json` with a known causal-LM
/// `model_type` plus safetensors weights) and GGUF (a `*.gguf` weight
/// file). Capabilities are inferred conservatively from the directory
/// name — anything not positively identified as a text LLM is skipped so
/// speech/vision/image/video checkpoints are never mistaken for
/// generators. car-releases#62.
fn synthesize_local_schema(name: &str, dir: &Path) -> Option<ModelSchema> {
    let lower = name.to_ascii_lowercase();

    // Hard skip directory names that are unambiguously non-text models —
    // these would be catastrophic to route as `Generate`.
    const NON_TEXT_HINTS: &[&str] = &[
        "vad",
        "whisper",
        "parakeet",
        "kokoro",
        "tts",
        "stt",
        "flux",
        "ltx",
        "yume",
        "sd-",
        "stable-diffusion",
        "wan",
        "mochi",
        "sana",
        "diffusion",
    ];
    if NON_TEXT_HINTS.iter().any(|h| lower.contains(h)) {
        return None;
    }

    // Capabilities by name. Embedding / reranker checkpoints share the same
    // causal-LM architecture as generators, so the name is the only signal.
    let capabilities: Vec<ModelCapability> =
        if lower.contains("embedding") || lower.contains("embed") {
            vec![ModelCapability::Embed]
        } else if lower.contains("reranker") || lower.contains("rerank") {
            vec![ModelCapability::Rerank]
        } else {
            vec![
                ModelCapability::Generate,
                ModelCapability::Code,
                ModelCapability::Reasoning,
            ]
        };

    // Locate weights and (for MLX) validate the architecture.
    let config_path = dir.join("config.json");
    let has_safetensors =
        dir.join("model.safetensors").exists() || dir.join("model.safetensors.index.json").exists();

    let (source, context_length, quantization) = if config_path.exists() && has_safetensors {
        // MLX layout. Only accept a recognized causal-LM model_type.
        let cfg: serde_json::Value = std::fs::read_to_string(&config_path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())?;
        let model_type = cfg
            .get("model_type")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        const KNOWN_LLM_TYPES: &[&str] = &[
            "qwen",
            "qwen2",
            "qwen3",
            "qwen3_moe",
            "llama",
            "mistral",
            "mixtral",
            "gemma",
            "gemma2",
            "gemma3",
            "gemma4_unified",
            "gemma4_unified_text",
            "phi",
            "phi3",
            "phimoe",
            "starcoder2",
            "deepseek",
            "deepseek_v2",
            "internlm2",
            "cohere",
            "olmo",
        ];
        if !KNOWN_LLM_TYPES.iter().any(|t| model_type == *t) {
            return None;
        }
        let ctx = cfg
            .get("max_position_embeddings")
            .and_then(|v| v.as_u64())
            .unwrap_or(32_768) as usize;
        let quant = cfg
            .get("quantization")
            .and_then(|q| q.get("bits"))
            .and_then(|b| b.as_u64())
            .map(|bits| format!("{bits}-bit"));
        (
            serde_json::json!({ "type": "mlx", "hf_repo": "" }),
            ctx,
            quant,
        )
    } else {
        let gguf = std::fs::read_dir(dir).ok().and_then(|rd| {
            rd.flatten().map(|e| e.path()).find(|p| {
                p.extension()
                    .and_then(|x| x.to_str())
                    .is_some_and(|x| x.eq_ignore_ascii_case("gguf"))
            })
        })?;
        // GGUF layout (Candle). file name carried for the Local source.
        let filename = gguf
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("model.gguf")
            .to_string();
        (
            serde_json::json!({
                "type": "local",
                "hf_repo": "",
                "hf_filename": filename,
                "tokenizer_repo": "",
            }),
            4_096,
            None,
        )
    };

    let id = format!("local/{}", lower.replace(['/', ' '], "-"));
    serde_json::from_value(serde_json::json!({
        "id": id,
        "name": name,
        "provider": "local",
        "family": "local",
        "capabilities": capabilities,
        "context_length": context_length,
        "quantization": quantization,
        "source": source,
        "tags": ["auto-discovered"],
        "trust_tier": "community",
    }))
    .ok()
}

#[allow(dead_code)] // callers are Apple-Silicon/MLX-gated; dead in car_skip_mlx builds
fn speech_mlx_available() -> bool {
    // On Apple Silicon, speech uses native MLX backends — no Python CLI needed.
    // Models are available if we're on the right platform (weights are downloaded on demand).
    #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
    {
        true
    }

    // On other platforms, check for the Python mlx-audio CLI.
    #[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx))))]
    {
        let runtime_root = speech_runtime_root();
        runtime_root
            .join("bin")
            .join("mlx_audio.stt.generate")
            .exists()
            || runtime_root
                .join("bin")
                .join("mlx_audio.tts.generate")
                .exists()
    }
}

#[allow(dead_code)] // general (no MLX deps); called from speech_mlx_available's non-MLX branch
fn speech_runtime_root() -> PathBuf {
    if let Ok(path) = std::env::var("CAR_SPEECH_RUNTIME_DIR") {
        if !path.trim().is_empty() {
            return PathBuf::from(path);
        }
    }
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".car")
        .join("speech-runtime")
}

/// Backward-compatible ModelInfo for listing (used by CLI and old callers).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
    pub id: String,
    pub name: String,
    pub provider: String,
    pub capabilities: Vec<ModelCapability>,
    pub param_count: String,
    pub size_mb: u64,
    pub context_length: usize,
    pub available: bool,
    pub is_local: bool,
    /// Per-model maximum OUTPUT tokens (registry-declared). `None` when the
    /// catalog entry omits it; callers fall back to a fraction of
    /// `context_length` via `ModelSchema::effective_max_output()`.
    #[serde(default)]
    pub max_output_tokens: Option<usize>,
    /// Public benchmark scores carried straight through from `ModelSchema`.
    /// The built-in catalog ships this empty; populating it is a curation
    /// step (see `BenchmarkScore` in the schema for shape and conventions).
    #[serde(default)]
    pub public_benchmarks: Vec<crate::schema::BenchmarkScore>,
    /// Declared per-token prices carried straight through from
    /// `ModelSchema::cost` — USD per 1M tokens for uncached input, output,
    /// cache reads and cache writes, plus any prompt-size pricing tiers the
    /// catalog declares.
    ///
    /// Every price component is `Option`: a local model that declares no
    /// prices reports them as `null`, which is deliberately **not** the same
    /// as a declared `0.0`. Consumers that price a request must distinguish
    /// "free" from "unpriced" — collapsing the two is how a caller ends up
    /// publishing a fabricated $0.00.
    ///
    /// `#[serde(default)]` so a newly built client can parse a catalog from
    /// an older daemon that predates this field: the row deserializes with an
    /// all-`None` cost rather than failing the whole response.
    #[serde(default)]
    pub cost: crate::schema::CostModel,
}

impl From<&ModelSchema> for ModelInfo {
    fn from(s: &ModelSchema) -> Self {
        ModelInfo {
            id: s.id.clone(),
            name: s.name.clone(),
            provider: s.provider.clone(),
            capabilities: s.capabilities.clone(),
            param_count: s.param_count.clone(),
            size_mb: s.size_mb(),
            context_length: s.context_length,
            available: s.available_now(),
            is_local: s.is_local(),
            max_output_tokens: s.max_output_tokens,
            public_benchmarks: s.public_benchmarks.clone(),
            // Prices only — the managed `parslee/…` aliases carry the same
            // `CostModel` as the personal row they front, and a `CostModel`
            // holds no identifiers, so publishing it discloses nothing about
            // the upstream model id.
            cost: s.cost.clone(),
        }
    }
}

/// Emit a lightweight `FileStarted` marker for an MLX auxiliary/weight file.
/// MLX pulls don't know `total_files` up front (single vs sharded), so these
/// carry `total_files = 0` ("unknown") and the UI shows the file name. The
/// sharded weight loop, which knows its count, pairs Started/Completed itself.
fn emit_file(sink: &ProgressSink, name: &str, index: u32, size_mb: u64) {
    sink.emit(DownloadEvent::FileStarted {
        filename: name.to_string(),
        index,
        total_files: 0,
        size_mb,
    });
}

/// Download a single file from a HuggingFace repo.
/// Mirror every file in a HuggingFace repo into `model_dir`, preserving its
/// subdirectory structure. For diffusers-layout models (Flux/LTX) whose weights
/// live in component subdirs (`transformer/`, `vae/`, `text_encoder/`, …) with
/// no root `config.json` or top-level weight index — the file-by-file MLX flow
/// can't enumerate them, so the whole snapshot is fetched. The repo file list
/// comes from the HF models API (version-independent, unlike hf-hub's `info()`);
/// metadata (`.gitattributes`, dotfiles, markdown) is skipped.
async fn download_repo_snapshot(
    repo: &str,
    model_dir: &Path,
    sink: &ProgressSink,
) -> Result<(), InferenceError> {
    #[derive(serde::Deserialize)]
    struct RepoInfo {
        siblings: Vec<Sibling>,
    }
    #[derive(serde::Deserialize)]
    struct Sibling {
        rfilename: String,
    }
    let url = format!("https://huggingface.co/api/models/{repo}");
    // Not `Client::new()`: that is `build().expect(..)`, which panics when the
    // OS trust store loads zero valid certificates — the failure the ladder in
    // `tls_client` exists to survive. huggingface.co is a public endpoint, so
    // the public-CA rung serves this call fully.
    let info: RepoInfo = crate::tls_client::model_download_client()
        .get(&url)
        .send()
        .await
        .map_err(|e| InferenceError::DownloadFailed(format!("list {repo}: {e}")))?
        .error_for_status()
        .map_err(|e| InferenceError::DownloadFailed(format!("list {repo}: {e}")))?
        .json()
        .await
        .map_err(|e| InferenceError::DownloadFailed(format!("parse {repo} file list: {e}")))?;

    let files: Vec<String> = info
        .siblings
        .into_iter()
        .map(|s| s.rfilename)
        .filter(|f| !f.starts_with('.') && !f.to_ascii_lowercase().ends_with(".md"))
        .collect();
    if files.is_empty() {
        return Err(InferenceError::DownloadFailed(format!(
            "{repo}: repo lists no downloadable files"
        )));
    }

    let total = files.len() as u32;
    for (i, fname) in files.iter().enumerate() {
        let dest = model_dir.join(fname);
        if crate::download::cache_file_usable(&dest) {
            continue;
        }
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)?;
        }
        sink.emit(DownloadEvent::FileStarted {
            filename: fname.clone(),
            index: (i + 1) as u32,
            total_files: total,
            size_mb: 0,
        });
        download_file(repo, fname, &dest).await?;
        sink.emit(DownloadEvent::FileCompleted {
            filename: fname.clone(),
        });
    }
    Ok(())
}

/// Tokenizer filenames seen across the repos CAR pulls, in preference order.
///
/// There is no single convention, which is the whole point of this list:
///
/// | Layout | Files | Example |
/// |---|---|---|
/// | `tokenizers` library | `tokenizer.json` | most modern text MLX repos |
/// | GPT-2 BPE pair | `vocab.json`, `merges.txt` | `Qwen3-TTS-12Hz-1.7B-Base-5bit` |
/// | SentencePiece | `tokenizer.model`, `tokenizer.vocab`, `vocab.txt` | `parakeet-tdt-0.6b-v3` |
/// | none at all | — | `Kokoro-82M-*` (phoneme-based, needs no tokenizer) |
const TOKENIZER_FILENAMES: &[&str] = &[
    "tokenizer.json",
    "vocab.json",
    "merges.txt",
    "tokenizer.model",
    "tokenizer.vocab",
    "vocab.txt",
];

/// Fetch whatever tokenizer assets a repo actually has. **Never fails the pull
/// over their absence.**
///
/// This used to be a single `download_file(repo, "tokenizer.json", …).await?` —
/// an unconditional hard requirement that aborted the entire multi-gigabyte
/// acquisition when the file 404'd. That made every curated speech model
/// impossible to install, in either direction: both Kokoro TTS builds, the
/// Qwen3-TTS default, and the Parakeet STT default, so local speech did not work
/// at all on a clean machine (Parslee-ai/car#639).
///
/// Best-effort is the correct posture here, not a workaround. The downloader
/// cannot know what a given backend needs — and Kokoro settles it: it ships
/// **no** tokenizer files whatsoever, because a phoneme-based TTS has no use for
/// one. Any rule of the form "a tokenizer must be present" is therefore wrong
/// for some model CAR legitimately supports. A loader that genuinely needs a
/// tokenizer will fail at load with a precise, model-specific error, which beats
/// a blanket download-time abort that names a file the model was never going to
/// have. This also matches the treatment `tokenizer_config.json` already gets
/// on the very next line.
async fn download_tokenizer_assets(hf_repo: &str, model_dir: &Path, sink: &ProgressSink) {
    // Already satisfied by any recognized layout? Then don't re-probe the API.
    if TOKENIZER_FILENAMES
        .iter()
        .any(|f| crate::download::cache_file_usable(&model_dir.join(f)))
    {
        return;
    }
    emit_file(sink, "tokenizer", 0, 0);
    let mut fetched: Vec<&str> = Vec::new();
    for name in TOKENIZER_FILENAMES {
        let dest = model_dir.join(name);
        if crate::download::cache_file_usable(&dest) {
            continue;
        }
        if download_file(hf_repo, name, &dest).await.is_ok() {
            fetched.push(name);
        }
    }
    if fetched.is_empty() {
        // Not an error: see the doc comment — Kokoro has none by design.
        tracing::debug!(
            repo = %hf_repo,
            "no tokenizer assets in this repo; continuing (the backend may not need one)"
        );
    } else {
        tracing::debug!(repo = %hf_repo, files = ?fetched, "fetched tokenizer assets");
    }
}

async fn download_file(repo: &str, filename: &str, dest: &Path) -> Result<(), InferenceError> {
    let api = hf_hub::api::tokio::Api::new()
        .map_err(|e| InferenceError::DownloadFailed(e.to_string()))?;

    let repo = api.model(repo.to_string());
    let path = repo
        .get(filename)
        .await
        .map_err(|e| InferenceError::DownloadFailed(format!("{filename}: {e}")))?;

    if dest.exists() {
        return Ok(());
    }

    // Try symlink first, fall back to copy
    #[cfg(unix)]
    {
        if std::os::unix::fs::symlink(&path, dest).is_ok() {
            return Ok(());
        }
    }

    std::fs::copy(&path, dest)
        .map_err(|e| InferenceError::DownloadFailed(format!("copy to {}: {e}", dest.display())))?;
    Ok(())
}

async fn ensure_auxiliary_mlx_files(
    model_name: &str,
    hf_repo: &str,
    model_dir: &Path,
) -> Result<(), InferenceError> {
    if hf_repo == "mlx-community/Flux-1.lite-8B-MLX-Q4" || model_name == "Flux-1.lite-8B-MLX-Q4" {
        let t5_tokenizer_path = model_dir.join("tokenizer_2").join("tokenizer.json");
        if !t5_tokenizer_path.exists() {
            std::fs::create_dir_all(t5_tokenizer_path.parent().ok_or_else(|| {
                InferenceError::InferenceFailed("invalid tokenizer path".into())
            })?)?;
            info!(
                path = %t5_tokenizer_path.display(),
                "downloading missing Flux tokenizer_2/tokenizer.json from base model"
            );
            download_file(
                "Freepik/flux.1-lite-8B",
                "tokenizer_2/tokenizer.json",
                &t5_tokenizer_path,
            )
            .await?;
        }
    }
    Ok(())
}

fn mlx_auxiliary_ready_without_download(model_name: &str, model_dir: &Path) -> bool {
    if model_name == "Flux-1.lite-8B-MLX-Q4" {
        return crate::download::cache_file_usable(
            &model_dir.join("tokenizer_2").join("tokenizer.json"),
        );
    }
    true
}

/// Does a managed MLX model dir actually contain resolvable weights?
///
/// A dir holding only `config.json`/`tokenizer.json` stubs — or a dangling
/// `*.safetensors` symlink into a pruned HuggingFace cache — is NOT a complete
/// install. Treating it as installed makes `ensure_local`/`car models pull`
/// no-op and inference then fails at load with "no safetensors weights found"
/// (car-releases#391). We check for at least one `*.safetensors` whose target
/// resolves: `Path::exists()` follows symlinks, so a dangling link counts as
/// absent. This covers single-file (`model.safetensors`) and sharded
/// (`model-00001-of-0000N.safetensors`) layouts; the bare
/// `model.safetensors.index.json` (extension `.json`) correctly doesn't count.
///
/// **Sharded models are checked against their index, not by existence of any
/// one shard.** "At least one `*.safetensors` resolves" is the right question
/// for a single-file model and the wrong one for a sharded install: an
/// interrupted download that landed shard 2 of 2 satisfies it, so
/// `ensure_local` returns early without repairing, `car models pull` reports
/// success having done nothing, and the failure surfaces only at load —
/// `load model-00001-of-00002.safetensors: Path must point to a local file`
/// (Parslee-ai/car#808). The index enumerates every required shard, so when it
/// is present it is authoritative and cheap to consult.
pub(crate) fn mlx_dir_has_weights(dir: &Path) -> bool {
    // An index present at the top level means a sharded layout: require EVERY
    // shard it names. Absent (single-file, or a diffusers-layout model whose
    // components live in subdirs), fall back to the recursive any-weights walk.
    let index = dir.join("model.safetensors.index.json");
    if index.is_file() {
        if let Some(required) = sharded_weight_files(&index) {
            return !required.is_empty() && required.iter().all(|shard| dir.join(shard).exists());
        }
        // Unreadable/unparseable index: fall through rather than declaring the
        // model broken on a metadata problem we cannot interpret.
    }
    mlx_dir_has_weights_depth(dir, 0)
}

/// Weight shards the index requires but that are not present on disk (#808).
///
/// Empty means "nothing missing" — including for single-file and
/// diffusers-layout models, which have no top-level index to check against.
/// Callers should pair this with [`mlx_dir_has_weights`] rather than treating an
/// empty result as proof the model is complete.
///
/// Exists so a failed pull can say *which* shard is absent. The reported case
/// (#808) left a 6.7 GB model with one of two shards on disk for weeks, and the
/// only symptom was an inference-time `Path must point to a local file` naming
/// a shard the caller had no reason to know about.
pub(crate) fn missing_weight_shards(dir: &Path) -> Vec<String> {
    let index = dir.join("model.safetensors.index.json");
    if !index.is_file() {
        return Vec::new();
    }
    let Some(required) = sharded_weight_files(&index) else {
        // Unreadable index: not evidence of a missing shard. `mlx_dir_has_weights`
        // makes the same call, so the two cannot disagree about a broken index.
        return Vec::new();
    };
    required
        .into_iter()
        .filter(|shard| !dir.join(shard).exists())
        .collect()
}

/// Shard filenames an MLX/HF `model.safetensors.index.json` says are required.
///
/// `weight_map` maps every tensor name to the file holding it, so the distinct
/// values are exactly the shard set. Returns `None` when the index cannot be
/// read or has no `weight_map`, so callers can fall back rather than treat an
/// unreadable index as a missing model.
fn sharded_weight_files(index: &Path) -> Option<Vec<String>> {
    let raw = std::fs::read_to_string(index).ok()?;
    let parsed: serde_json::Value = serde_json::from_str(&raw).ok()?;
    let map = parsed.get("weight_map")?.as_object()?;
    let mut files: Vec<String> = map
        .values()
        .filter_map(|v| v.as_str().map(str::to_string))
        .collect();
    files.sort();
    files.dedup();
    Some(files)
}

/// Recurse into component subdirs to find weights, but bounded. Diffusers-layout
/// models (Flux image, LTX video, …) keep their component weights in subdirs
/// (`transformer/`, `vae/`, `text_encoder/`, …), not at the top level, so a flat
/// scan misjudges a fully-cached snapshot as weightless (the miss that sent the
/// image/video path into a re-download that 404s on the `config.json` these
/// repos don't ship). `load_all_tensors` reads those component safetensors
/// recursively. The walk is depth-capped and skips symlinked directories so a
/// symlink cycle in a cache dir can't stack-overflow us — the HF cache nests
/// real component dirs at most ~2 deep, with only leaf blob files symlinked
/// (those are files, resolved by `cache_file_usable`, not followed here).
fn mlx_dir_has_weights_depth(dir: &Path, depth: usize) -> bool {
    if depth > 4 {
        return false;
    }
    let Ok(rd) = std::fs::read_dir(dir) else {
        return false;
    };
    rd.flatten().any(|e| {
        let p = e.path();
        let is_symlink = std::fs::symlink_metadata(&p)
            .map(|m| m.file_type().is_symlink())
            .unwrap_or(true);
        if p.is_dir() {
            !is_symlink && mlx_dir_has_weights_depth(&p, depth + 1)
        } else {
            // `cache_file_usable` follows the symlink and requires non-empty, so
            // a dangling weight symlink (pruned blob) or a zero-length partial
            // write does not count as installed.
            p.extension().and_then(|x| x.to_str()) == Some("safetensors")
                && crate::download::cache_file_usable(&p)
        }
    })
}

#[allow(dead_code)] // conditionally compiled — used only on MLX-backend (macOS) snapshot-resolution paths
fn huggingface_repo_has_snapshot(repo_id: &str) -> bool {
    latest_huggingface_repo_snapshot(repo_id).is_some()
}

pub(crate) fn huggingface_cache_root() -> PathBuf {
    std::env::var("HF_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            std::env::var_os("HOME")
                .or_else(|| std::env::var_os("USERPROFILE"))
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".cache")
                .join("huggingface")
        })
        .join("hub")
}

fn huggingface_repo_dir(repo_id: &str) -> PathBuf {
    huggingface_cache_root().join(format!("models--{}", repo_id.replace('/', "--")))
}

fn resolve_huggingface_ref_snapshot(repo_dir: &Path, name: &str) -> Option<PathBuf> {
    let sha = std::fs::read_to_string(repo_dir.join("refs").join(name))
        .ok()?
        .trim()
        .to_string();
    if sha.is_empty() {
        return None;
    }

    let snapshot = repo_dir.join("snapshots").join(sha);
    if snapshot_looks_ready(&snapshot) {
        Some(snapshot)
    } else {
        None
    }
}

fn latest_huggingface_repo_snapshot(repo_id: &str) -> Option<PathBuf> {
    let repo_dir = huggingface_repo_dir(repo_id);
    if let Some(snapshot) = resolve_huggingface_ref_snapshot(&repo_dir, "main") {
        return Some(snapshot);
    }

    let snapshots = repo_dir.join("snapshots");
    let mut candidates: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(snapshots)
        .ok()?
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| p.is_dir() && snapshot_looks_ready(p))
        .map(|path| {
            let modified = path
                .metadata()
                .and_then(|metadata| metadata.modified())
                .unwrap_or(SystemTime::UNIX_EPOCH);
            (modified, path)
        })
        .collect();
    candidates.sort();
    candidates.pop().map(|(_, path)| path)
}

fn snapshot_looks_ready(path: &Path) -> bool {
    if path.join("config.json").exists() || path.join("model_index.json").exists() {
        return true;
    }
    snapshot_contains_ext(path, "safetensors")
}

fn snapshot_contains_ext(root: &Path, ext: &str) -> bool {
    let Ok(entries) = std::fs::read_dir(root) else {
        return false;
    };
    entries.filter_map(Result::ok).any(|entry| {
        let path = entry.path();
        if path.is_dir() {
            snapshot_contains_ext(&path, ext)
        } else {
            let ext_matches = path
                .extension()
                .and_then(|value| value.to_str())
                .map(|value| value.eq_ignore_ascii_case(ext))
                .unwrap_or(false);
            // A matching extension only counts when the file is actually usable
            // — a dangling symlink into a pruned blob or a zero-length partial
            // must not make a snapshot look ready.
            ext_matches && crate::download::cache_file_usable(&path)
        }
    })
}

/// Built-in catalog parsed from `builtin_catalog.json`.
///
/// Adding, removing, or editing a model is a JSON-only change — Rust
/// source stays put. The JSON is embedded at compile time via
/// `include_str!`, parsed once into a `LazyLock`, and cloned on each
/// call. A malformed JSON file fails the integration test
/// `builtin_catalog_json_parses` so the binary never ships unable
/// to load its own catalog.
const BUILTIN_CATALOG_JSON: &str = include_str!("builtin_catalog.json");

static BUILTIN_CATALOG: std::sync::LazyLock<Vec<ModelSchema>> = std::sync::LazyLock::new(|| {
    serde_json::from_str(BUILTIN_CATALOG_JSON)
        .expect("builtin_catalog.json failed to parse — fix the JSON, not this code")
});

pub(crate) fn builtin_catalog() -> Vec<ModelSchema> {
    let mut catalog = BUILTIN_CATALOG.clone();
    catalog.extend(crate::openrouter::builtin_schemas());
    catalog
}

#[cfg(test)]
mod tests {
    /// A sharded install missing one shard is NOT installed.
    ///
    /// The interrupted-download shape from car#808: shard 2 of 2 landed, shard
    /// 1 did not. The old any-weights check said "installed", so `ensure_local`
    /// returned early without repairing, `pull_model` reported success having
    /// done nothing, and the failure surfaced only at load. Synthetic dir — no
    /// real weights needed, which is what makes it runnable in CI.
    #[test]
    fn a_sharded_model_missing_one_shard_is_not_installed() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        std::fs::write(
            dir.join("model.safetensors.index.json"),
            r#"{"weight_map":{"a":"model-00001-of-00002.safetensors",
                              "b":"model-00002-of-00002.safetensors"}}"#,
        )
        .unwrap();
        // Only shard 2 present — exactly the reported state.
        std::fs::write(dir.join("model-00002-of-00002.safetensors"), b"x").unwrap();
        assert!(
            !mlx_dir_has_weights(dir),
            "a missing shard must read as not-installed, or pull silently no-ops"
        );

        // Completing the set flips it.
        std::fs::write(dir.join("model-00001-of-00002.safetensors"), b"x").unwrap();
        assert!(
            mlx_dir_has_weights(dir),
            "a complete shard set must read as installed"
        );
    }

    /// A failed pull must be able to NAME the shard it is missing (car#808).
    ///
    /// The reported symptom was an inference-time
    /// `load model-00001-of-00002.safetensors: Path must point to a local file`
    /// — a filename the caller had no way to anticipate, surfacing inside a
    /// benchmarking run rather than at pull time. `missing_weight_shards` is
    /// what lets the pull itself say which shard is absent.
    #[test]
    fn missing_shards_are_reported_by_name() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        std::fs::write(
            dir.join("model.safetensors.index.json"),
            r#"{"weight_map":{"a":"model-00001-of-00002.safetensors",
                              "b":"model-00002-of-00002.safetensors"}}"#,
        )
        .unwrap();
        std::fs::write(dir.join("model-00002-of-00002.safetensors"), b"x").unwrap();

        assert_eq!(
            missing_weight_shards(dir),
            vec!["model-00001-of-00002.safetensors".to_string()],
            "the absent shard must be named, not just counted"
        );

        std::fs::write(dir.join("model-00001-of-00002.safetensors"), b"x").unwrap();
        assert!(
            missing_weight_shards(dir).is_empty(),
            "a complete shard set must report nothing missing"
        );
    }

    /// No index (single-file or diffusers layout) means there is no shard list
    /// to check against — report nothing missing rather than inventing a
    /// failure. `mlx_dir_has_weights` remains the completeness signal there.
    #[test]
    fn missing_shards_is_empty_without_an_index() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("model.safetensors"), b"x").unwrap();
        assert!(missing_weight_shards(tmp.path()).is_empty());

        // An unreadable index is a metadata problem, not proof of a missing
        // shard — same call `mlx_dir_has_weights` makes, so they cannot disagree.
        let bad = tempfile::tempdir().unwrap();
        std::fs::write(bad.path().join("model.safetensors.index.json"), b"not json").unwrap();
        assert!(missing_weight_shards(bad.path()).is_empty());
    }

    /// A single-file model has no index; the any-weights walk still governs.
    #[test]
    fn a_single_file_model_still_counts_without_an_index() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("model.safetensors"), b"x").unwrap();
        assert!(mlx_dir_has_weights(tmp.path()));
    }

    /// An unreadable index must not condemn the model — fall back rather than
    /// report a complete install as broken on a metadata problem.
    #[test]
    fn an_unparseable_index_falls_back_instead_of_failing_closed() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("model.safetensors.index.json"),
            b"{not-json",
        )
        .unwrap();
        std::fs::write(tmp.path().join("model.safetensors"), b"x").unwrap();
        assert!(
            mlx_dir_has_weights(tmp.path()),
            "an unreadable index should fall back to the weights walk"
        );
    }

    use super::*;
    use tempfile::TempDir;

    #[test]
    fn mlx_dir_has_weights_detects_completeness() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path();

        // A config-only stub is NOT complete (car-releases#391).
        std::fs::write(dir.join("config.json"), "{}").unwrap();
        std::fs::write(dir.join("tokenizer.json"), "{}").unwrap();
        assert!(
            !mlx_dir_has_weights(dir),
            "config-only stub must not count as installed"
        );

        // The bare sharded index without shards is still incomplete.
        std::fs::write(dir.join("model.safetensors.index.json"), "{}").unwrap();
        assert!(!mlx_dir_has_weights(dir), "index.json alone is not weights");

        // A real single-file weight makes it complete.
        std::fs::write(dir.join("model.safetensors"), b"\x00\x01\x02").unwrap();
        assert!(mlx_dir_has_weights(dir));
    }

    #[test]
    fn mlx_dir_has_weights_handles_sharded_and_dangling_symlinks() {
        let sharded = TempDir::new().unwrap();
        std::fs::write(sharded.path().join("config.json"), "{}").unwrap();
        std::fs::write(
            sharded.path().join("model-00001-of-00002.safetensors"),
            b"\x00",
        )
        .unwrap();
        assert!(mlx_dir_has_weights(sharded.path()), "sharded shard counts");

        // A DANGLING *.safetensors symlink (into a pruned HF cache) must NOT
        // count — Path::exists() follows the link and returns false.
        #[cfg(unix)]
        {
            let dangling = TempDir::new().unwrap();
            std::fs::write(dangling.path().join("config.json"), "{}").unwrap();
            std::os::unix::fs::symlink(
                dangling.path().join("does-not-exist"),
                dangling.path().join("model.safetensors"),
            )
            .unwrap();
            assert!(
                !mlx_dir_has_weights(dangling.path()),
                "dangling weight symlink must count as absent"
            );
        }
    }

    fn test_registry() -> (UnifiedRegistry, TempDir) {
        let tmp = TempDir::new().unwrap();
        let reg = UnifiedRegistry::new(tmp.path().join("models"));
        (reg, tmp)
    }

    fn test_generate_schema(id: &str, name: &str, source: ModelSource) -> ModelSchema {
        ModelSchema {
            id: id.into(),
            name: name.into(),
            provider: "local".into(),
            family: "qwen3".into(),
            version: "test".into(),
            capabilities: vec![ModelCapability::Generate],
            context_length: 4096,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: PerformanceEnvelope::default(),
            cost: CostModel::default(),
            source,
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: false,
            weights_ready: false,
        }
    }

    /// `refresh_availability` must probe each DISTINCT credential once, not
    /// once per model (car-releases#75).
    ///
    /// A credential probe is a keychain query on macOS — ~14 ms. The stock
    /// catalog is ~72 models over roughly a dozen providers, so probing
    /// per-model cost ~1 s per refresh; a snapshot runs per request, and
    /// `estimated_tokens` ran a second one, so a delegated call waited ~2 s
    /// before it ever reached the host's runner.
    ///
    /// Asserted by COUNTING probes rather than by timing: a latency assertion
    /// would be flaky on a loaded CI runner, and the invariant that actually
    /// matters is "O(providers), not O(models)".
    /// Parslee-ai/car#786 — the catalog must stop advertising a managed
    /// namespace once the gateway has said it has no upstream for it.
    ///
    /// This is the reported symptom directly: `car models list` showed all ten
    /// `parslee/openrouter/*` aliases as `avail=yes` while every one of them
    /// 503'd, because availability for those rows resolves to "is a Parslee
    /// session signed in" and nothing more. A harness picked one on the
    /// strength of that claim and lost a full benchmark sweep to it.
    ///
    /// Asserted through the real `curated_schemas()` rows rather than a
    /// fixture, because the bug lives in how THOSE rows derive availability.
    #[test]
    fn a_gateway_that_reports_no_upstream_stops_being_advertised() {
        let _guard = crate::openrouter::test_environment_scope();
        crate::openrouter::clear_gateway_unconfigured();

        let managed: Vec<ModelSchema> = crate::openrouter::curated_schemas()
            .into_iter()
            .filter(|s| crate::openrouter::is_curated_managed_gateway_alias(&s.id))
            .collect();
        assert!(
            !managed.is_empty(),
            "precondition: the curated catalog must still carry managed aliases"
        );

        let availability_of = |schema: &ModelSchema| match &schema.source {
            ModelSource::Proprietary { provider, auth, .. } => proprietary_auth_available(
                &schema.id,
                &schema.provider,
                provider,
                auth,
                // Signed in — the state in which the bug reported `yes`.
                true,
                None,
            ),
            other => panic!("managed aliases must be Proprietary, got {other:?}"),
        };

        assert!(
            managed.iter().all(availability_of),
            "precondition: an authenticated session advertises these today"
        );

        crate::openrouter::note_gateway_unconfigured();
        assert!(
            managed.iter().all(|s| !availability_of(s)),
            "after the gateway says it has no OpenRouter upstream, every alias in \
             the namespace must report unavailable — that claim is what cost the \
             benchmark sweep in #786"
        );

        // Self-correcting: forgetting the observation restores the optimistic
        // claim, so an environment that later gains OpenRouter is not
        // permanently written off.
        crate::openrouter::clear_gateway_unconfigured();
        assert!(
            managed.iter().all(availability_of),
            "the suppression must be recoverable, not a one-way latch"
        );
    }

    #[test]
    fn refresh_availability_probes_each_credential_once_not_per_model() {
        let tmp = TempDir::new().unwrap();
        let mut registry = UnifiedRegistry::new_empty(tmp.path().join("models"));
        for i in 0..25 {
            let mut schema = test_generate_schema(
                &format!("openrouter/model-{i}"),
                &format!("model-{i}"),
                ModelSource::RemoteApi {
                    protocol: crate::schema::ApiProtocol::OpenRouter,
                    endpoint: "https://openrouter.ai/api/v1".into(),
                    api_key_env: "OPENROUTER_API_KEY".into(),
                    api_key_envs: vec![],
                    api_version: None,
                },
            );
            schema.provider = "openrouter".into();
            registry.register(schema);
        }

        crate::openrouter::reset_credential_source_call_count();
        registry.refresh_availability();
        let calls = crate::openrouter::credential_source_call_count();

        assert_eq!(
            calls, 1,
            "refresh_availability probed the OpenRouter credential {calls} times for 25 models; \
             it must resolve each distinct credential once per refresh, not once per model"
        );
    }

    #[test]
    fn user_config_load_and_save_force_community_trust() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let config_path = tmp.path().join("models.json");
        let schema = test_generate_schema(
            "user/test-model",
            "user-test-model",
            ModelSource::RemoteApi {
                endpoint: "https://attacker.invalid/v1/chat/completions".into(),
                api_key_env: "CAR_USER_MODEL_TEST_KEY".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: crate::schema::ApiProtocol::OpenAiCompat,
            },
        );
        let mut omitted_tier = serde_json::to_value(schema.clone()).unwrap();
        omitted_tier.as_object_mut().unwrap().remove("trust_tier");
        std::fs::write(
            &config_path,
            serde_json::to_vec_pretty(&vec![omitted_tier]).unwrap(),
        )
        .unwrap();

        let mut loaded = UnifiedRegistry::new_empty(models_dir.clone());
        loaded.load_user_config().unwrap();
        assert_eq!(
            loaded.get("user/test-model").unwrap().trust_tier,
            crate::schema::TrustTier::Community
        );

        let mut persisted = UnifiedRegistry::new_empty(models_dir);
        persisted.register_user_model(schema);
        persisted.save_user_config().unwrap();
        let saved: Vec<ModelSchema> =
            serde_json::from_slice(&std::fs::read(config_path).unwrap()).unwrap();
        assert_eq!(saved.len(), 1);
        assert_eq!(saved[0].trust_tier, crate::schema::TrustTier::Community);
    }

    #[test]
    fn persisted_user_model_cannot_shadow_managed_openrouter_alias() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let config_path = tmp.path().join("models.json");
        let mut shadow = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .unwrap();
        shadow.provider = "attacker".into();
        std::fs::write(
            &config_path,
            serde_json::to_vec_pretty(&vec![shadow]).unwrap(),
        )
        .unwrap();

        let registry = UnifiedRegistry::new(models_dir);
        let actual = registry
            .get("parslee/openrouter/frontier-general")
            .expect("compiled managed alias must remain present");
        assert_eq!(actual.provider, "parslee");
        assert_eq!(
            crate::openrouter::canonical_managed_gateway_selector(actual),
            Some("parslee/openrouter/frontier-general")
        );
    }

    #[test]
    fn user_config_persistence_excludes_signed_rows_and_keeps_builtin_tagged_user_rows() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let config_path = tmp.path().join("models.json");

        let signed = test_generate_schema(
            "signed/catalog-only",
            "signed-catalog-only",
            ModelSource::RemoteApi {
                endpoint: "https://catalog.example/v1".into(),
                api_key_env: "SIGNED_CATALOG_TEST_KEY".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: crate::schema::ApiProtocol::OpenAiCompat,
            },
        );
        assert!(!signed.tags.iter().any(|tag| tag == "builtin"));
        let (verified, public_key) = crate::catalog::signed_test_catalog(
            crate::catalog::CatalogDoc {
                version: 81,
                models: vec![signed],
            },
            81,
        );
        crate::catalog::save_verified(&crate::catalog::cache_path(&models_dir), &verified).unwrap();

        let mut registry = UnifiedRegistry::new_with_catalog_public_key(
            models_dir.clone(),
            Some(public_key.as_str()),
        );
        let mut user = test_generate_schema(
            "user/builtin-tagged",
            "user-builtin-tagged",
            ModelSource::RemoteApi {
                endpoint: "https://user.example/v1".into(),
                api_key_env: "USER_MODEL_TEST_KEY".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: crate::schema::ApiProtocol::OpenAiCompat,
            },
        );
        user.tags.push("builtin".into());
        registry.register_user_model(user);
        registry.save_user_config().unwrap();

        let saved: Vec<ModelSchema> =
            serde_json::from_slice(&std::fs::read(&config_path).unwrap()).unwrap();
        assert_eq!(
            saved
                .iter()
                .map(|model| model.id.as_str())
                .collect::<Vec<_>>(),
            vec!["user/builtin-tagged"],
            "models.json must contain only explicitly user-registered rows"
        );
        assert_eq!(saved[0].trust_tier, crate::schema::TrustTier::Community);

        let restarted =
            UnifiedRegistry::new_with_catalog_public_key(models_dir, Some(public_key.as_str()));
        assert_eq!(
            restarted.get("signed/catalog-only").unwrap().trust_tier,
            crate::schema::TrustTier::Curated,
            "user persistence must not demote an unrelated signed catalog row"
        );
        assert_eq!(
            restarted.get("user/builtin-tagged").unwrap().trust_tier,
            crate::schema::TrustTier::Community
        );
    }

    #[test]
    fn empty_user_config_save_clears_stale_rows() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let config_path = tmp.path().join("models.json");
        let stale = test_generate_schema(
            "user/stale",
            "stale",
            ModelSource::RemoteApi {
                endpoint: "https://stale.example/v1".into(),
                api_key_env: "STALE_USER_MODEL_TEST_KEY".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: crate::schema::ApiProtocol::OpenAiCompat,
            },
        );
        std::fs::write(
            &config_path,
            serde_json::to_vec_pretty(&vec![stale]).unwrap(),
        )
        .unwrap();

        UnifiedRegistry::new_empty(models_dir)
            .save_user_config()
            .unwrap();

        let saved: Vec<ModelSchema> =
            serde_json::from_slice(&std::fs::read(config_path).unwrap()).unwrap();
        assert!(
            saved.is_empty(),
            "saving an empty user set must overwrite stale models.json rows"
        );
    }

    #[test]
    fn unregister_then_save_removes_the_user_row_from_disk() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let config_path = tmp.path().join("models.json");
        let mut registry = UnifiedRegistry::new_empty(models_dir);
        registry.register_project_model(test_generate_schema(
            "signed/not-user-removable",
            "not-user-removable",
            ModelSource::RemoteApi {
                endpoint: "https://catalog.example/v1".into(),
                api_key_env: "SIGNED_CATALOG_TEST_KEY".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: crate::schema::ApiProtocol::OpenAiCompat,
            },
        ));
        assert!(
            registry
                .unregister_user_model("signed/not-user-removable")
                .is_none(),
            "the user boundary cannot unregister an untracked catalog row"
        );
        assert!(registry.get("signed/not-user-removable").is_some());
        registry.register_user_model(test_generate_schema(
            "user/removable",
            "removable",
            ModelSource::RemoteApi {
                endpoint: "https://user.example/v1".into(),
                api_key_env: "REMOVABLE_USER_MODEL_TEST_KEY".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: crate::schema::ApiProtocol::OpenAiCompat,
            },
        ));
        registry.save_user_config().unwrap();
        assert!(registry.unregister_user_model("user/removable").is_some());
        registry.save_user_config().unwrap();

        let saved: Vec<ModelSchema> =
            serde_json::from_slice(&std::fs::read(config_path).unwrap()).unwrap();
        assert!(saved.is_empty());
    }

    #[test]
    fn ready_without_download_is_strict_for_local_model_files() {
        let tmp = TempDir::new().unwrap();
        let models = tmp.path().join("models");
        let mut reg = UnifiedRegistry::new_empty(models.clone());
        reg.register(test_generate_schema(
            "local/test",
            "TestLocal",
            ModelSource::Local {
                hf_repo: "example/repo".into(),
                hf_filename: "model.gguf".into(),
                tokenizer_repo: "example/repo".into(),
            },
        ));

        assert_eq!(reg.ready_without_download("local/test"), Some(false));

        let dir = models.join("TestLocal");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("model.gguf"), b"weights").unwrap();
        assert_eq!(
            reg.ready_without_download("local/test"),
            Some(false),
            "tokenizer is required too"
        );
        std::fs::write(dir.join("tokenizer.json"), "{}").unwrap();
        assert_eq!(reg.ready_without_download("local/test"), Some(true));
    }

    #[test]
    fn ready_without_download_rejects_mlx_config_only_stub() {
        let tmp = TempDir::new().unwrap();
        let models = tmp.path().join("models");
        let mut reg = UnifiedRegistry::new_empty(models.clone());
        reg.register(test_generate_schema(
            "mlx/test",
            "TestMlx",
            ModelSource::Mlx {
                hf_repo: "example/repo".into(),
                hf_weight_file: None,
            },
        ));

        let dir = models.join("TestMlx");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("config.json"), "{}").unwrap();
        std::fs::write(dir.join("tokenizer.json"), "{}").unwrap();
        assert_eq!(
            reg.ready_without_download("mlx/test"),
            Some(false),
            "config/tokenizer stubs must not start assistant inference"
        );

        std::fs::write(dir.join("model.safetensors"), b"weights").unwrap();
        assert_eq!(reg.ready_without_download("mlx/test"), Some(true));
    }

    fn write_mlx_dir(root: &Path, name: &str, model_type: &str) {
        let dir = root.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("config.json"),
            serde_json::json!({
                "model_type": model_type,
                "max_position_embeddings": 40_960,
                "quantization": { "bits": 8, "group_size": 32, "mode": "mxfp8" },
            })
            .to_string(),
        )
        .unwrap();
        std::fs::write(dir.join("model.safetensors"), b"weights").unwrap();
    }

    #[test]
    fn synthesize_local_schema_classifies_by_name_and_arch() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();

        write_mlx_dir(root, "MyCustom-Qwen3-7B", "qwen3");
        let gen = synthesize_local_schema("MyCustom-Qwen3-7B", &root.join("MyCustom-Qwen3-7B"))
            .expect("text LLM should be recognized");
        assert_eq!(
            gen.capabilities,
            vec![
                ModelCapability::Generate,
                ModelCapability::Code,
                ModelCapability::Reasoning
            ]
        );
        assert_eq!(gen.context_length, 40_960);
        assert_eq!(gen.provider, "local");
        assert!(matches!(gen.source, ModelSource::Mlx { .. }));

        write_mlx_dir(root, "Some-Embedding-0.6B", "qwen3");
        let emb = synthesize_local_schema("Some-Embedding-0.6B", &root.join("Some-Embedding-0.6B"))
            .expect("embedding model recognized");
        assert_eq!(emb.capabilities, vec![ModelCapability::Embed]);

        // Unknown architecture: refuse rather than guess.
        write_mlx_dir(root, "Mystery-Net", "some_unknown_arch");
        assert!(synthesize_local_schema("Mystery-Net", &root.join("Mystery-Net")).is_none());

        // Speech/vision/etc. names are skipped even with a valid LLM config.
        write_mlx_dir(root, "silero-vad-v6-mlx", "qwen3");
        assert!(
            synthesize_local_schema("silero-vad-v6-mlx", &root.join("silero-vad-v6-mlx")).is_none()
        );

        // A bare directory with no weights is not a model.
        std::fs::create_dir_all(root.join("empty")).unwrap();
        assert!(synthesize_local_schema("empty", &root.join("empty")).is_none());
    }

    #[test]
    fn discovery_registers_uncatalogued_local_model() {
        let tmp = TempDir::new().unwrap();
        let models = tmp.path().join("models");
        std::fs::create_dir_all(&models).unwrap();
        write_mlx_dir(&models, "Totally-Custom-Llama-3B", "llama");

        let reg = UnifiedRegistry::new(models);
        let found = reg
            .list()
            .into_iter()
            .find(|m| m.name == "Totally-Custom-Llama-3B");
        assert!(
            found.is_some(),
            "uncatalogued on-disk model should be registered"
        );
        assert!(found.unwrap().tags.iter().any(|t| t == "auto-discovered"));
    }

    #[test]
    fn refreshed_catalog_entry_replaces_builtin() {
        // A refreshed (signature-verified, cached) catalog entry whose id
        // matches a built-in must REPLACE it, so a catalog refresh can fix
        // a bad built-in — not just add new models.
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");

        let builtin = builtin_catalog();
        let mut overriding = builtin.first().expect("a built-in model").clone();
        let target_id = overriding.id.clone();
        overriding.name = "REPLACED-BY-CATALOG".into();

        let (verified, public_key) = crate::catalog::signed_test_catalog(
            crate::catalog::CatalogDoc {
                version: 1,
                models: vec![overriding],
            },
            51,
        );
        crate::catalog::save_verified(&crate::catalog::cache_path(&models_dir), &verified).unwrap();

        // new() merges the verified cache on top of the built-ins.
        let reg =
            UnifiedRegistry::new_with_catalog_public_key(models_dir, Some(public_key.as_str()));
        assert_eq!(
            reg.get(&target_id).map(|m| m.name.as_str()),
            Some("REPLACED-BY-CATALOG"),
            "cache entry should replace the built-in of the same id"
        );
    }

    #[test]
    fn legacy_unsigned_catalog_cache_cannot_replace_builtin() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let builtin = builtin_catalog();
        let original = builtin.first().expect("a built-in model");
        let mut forged = original.clone();
        forged.name = "FORGED-UNSIGNED-CATALOG".into();
        let path = crate::catalog::cache_path(&models_dir);
        std::fs::write(
            &path,
            serde_json::to_vec_pretty(&crate::catalog::CatalogDoc {
                version: u64::MAX,
                models: vec![forged],
            })
            .unwrap(),
        )
        .unwrap();

        let reg = UnifiedRegistry::new(models_dir);
        assert_eq!(
            reg.get(&original.id).map(|model| model.name.as_str()),
            Some(original.name.as_str()),
            "legacy unsigned cache JSON must fail closed and preserve the built-in"
        );
    }

    #[test]
    fn tampered_signed_managed_row_preserves_builtin() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let original = builtin_catalog()
            .into_iter()
            .find(|model| model.id == "parslee/openrouter/frontier-general")
            .expect("managed frontier alias");
        let mut forged = original.clone();
        forged.name = "SIGNED-THEN-TAMPERED-MANAGED".into();
        let (verified, public_key) = crate::catalog::signed_test_catalog(
            crate::catalog::CatalogDoc {
                version: 9,
                models: vec![forged],
            },
            52,
        );
        let path = crate::catalog::cache_path(&models_dir);
        crate::catalog::save_verified(&path, &verified).unwrap();
        let cache = std::fs::read_to_string(&path)
            .unwrap()
            .replace("SIGNED-THEN-TAMPERED-MANAGED", "ATTACKER-MUTATION");
        std::fs::write(&path, cache).unwrap();

        let reg =
            UnifiedRegistry::new_with_catalog_public_key(models_dir, Some(public_key.as_str()));
        assert_eq!(
            reg.get(&original.id).map(|model| model.name.as_str()),
            Some(original.name.as_str()),
            "a tampered same-id managed row must fail verification and preserve the builtin"
        );
    }

    #[test]
    fn validly_signed_managed_id_with_wrong_name_is_not_a_trusted_gateway_alias() {
        let tmp = TempDir::new().unwrap();
        let models_dir = tmp.path().join("models");
        let mut wrong_selector = builtin_catalog()
            .into_iter()
            .find(|model| model.id == "parslee/openrouter/frontier-general")
            .expect("managed frontier alias");
        wrong_selector.name = "attacker-controlled-upstream-selector".into();
        let (verified, public_key) = crate::catalog::signed_test_catalog(
            crate::catalog::CatalogDoc {
                version: 82,
                models: vec![wrong_selector],
            },
            82,
        );
        crate::catalog::save_verified(&crate::catalog::cache_path(&models_dir), &verified).unwrap();

        let registry =
            UnifiedRegistry::new_with_catalog_public_key(models_dir, Some(public_key.as_str()));
        let loaded = registry
            .get("parslee/openrouter/frontier-general")
            .expect("validly signed row replaces the builtin");
        assert_eq!(loaded.trust_tier, crate::schema::TrustTier::Curated);
        assert_eq!(loaded.name, "attacker-controlled-upstream-selector");
        assert!(
            !crate::openrouter::is_managed_gateway_schema(loaded),
            "signature trust does not allow a signed row to change the managed selector"
        );
    }

    #[test]
    fn builtin_catalog_loads() {
        let (reg, _tmp) = test_registry();
        let all = reg.list();
        assert_eq!(all.len(), builtin_catalog().len());
    }

    /// #137: a model tagged `requires-mlx-vlm` must report
    /// `available: true` if and only if `mlx_vlm_cli::is_available()`
    /// returns true. Without this, registry consumers (FFI
    /// `listModelsUnified`, the tray Models submenu, agent routing)
    /// see a model as available, the user picks it, and inference
    /// bails with `mlx-vlm CLI not found on PATH`.
    ///
    /// The probe is environmental — runs the same check on the host
    /// the test executes on. CI usually doesn't have `mlx_vlm`
    /// installed → expected unavailable; a dev box with it installed
    /// → expected available. Either way, the registry tracks the
    /// runtime probe.
    #[test]
    fn mlx_vlm_models_reflect_runtime_availability() {
        let (reg, _tmp) = test_registry();
        let mlx_vlm_models: Vec<&ModelSchema> = reg
            .list()
            .into_iter()
            .filter(|m| m.tags.iter().any(|t| t == "requires-mlx-vlm"))
            .collect();
        assert!(
            !mlx_vlm_models.is_empty(),
            "catalog should contain at least one model tagged \
             `requires-mlx-vlm` — otherwise this regression has \
             nothing to guard"
        );

        #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
        let expected = crate::backend::mlx_vlm_cli::is_available();
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx))))]
        let expected = false;

        for m in mlx_vlm_models {
            assert_eq!(
                m.available, expected,
                "model {} `available` field should reflect \
                 mlx_vlm CLI presence (expected {expected}, got {})",
                m.id, m.available
            );
        }
    }

    /// F1 (Parslee-ai/car#231 §7.1): MLX models must report
    /// `available: false` on any non-Apple-Silicon-with-MLX build target.
    /// Without this, the Windows / Linux / Intel-Mac router happily
    /// adds MLX entries to fallback chains and inference fails at
    /// dispatch with "model not found", producing a 7-deep cascade
    /// of useless errors on a fresh install.
    ///
    /// The test runs on every platform. On macOS arm64 (default-features),
    /// at least one MLX model with an `hf_repo` should report available;
    /// on Linux / Windows / Intel-Mac / `car_skip_mlx`, every plain MLX
    /// model must report unavailable.
    #[test]
    fn mlx_models_unavailable_on_non_mlx_targets() {
        let (reg, _tmp) = test_registry();
        let mlx_models: Vec<&ModelSchema> = reg
            .list()
            .into_iter()
            .filter(|m| {
                m.is_mlx()
                    // Exclude `requires-mlx-vlm` and `speech` — those have
                    // their own availability logic (mlx_vlm CLI probe,
                    // speech_mlx_available). The plain MLX models are
                    // what §7.1 surfaced as broken on Windows.
                    && !m.tags.iter().any(|t| t == "requires-mlx-vlm")
                    && !m.tags.contains(&"speech".to_string())
            })
            .collect();
        assert!(
            !mlx_models.is_empty(),
            "catalog should contain at least one plain MLX model — \
             otherwise this F1 regression guard has nothing to guard"
        );

        #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
        {
            // On a real MLX target, models with an `hf_repo` should be
            // marked available (the `ensure_local()` lazy-download path).
            // At least one must qualify.
            let any_available = mlx_models.iter().any(|m| m.available);
            assert!(
                any_available,
                "on macOS arm64 with MLX enabled, at least one plain MLX \
                 model with hf_repo should be available — none were"
            );
        }
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx))))]
        {
            // On every other target, MLX models cannot execute, so the
            // registry must mark them all unavailable.
            for m in &mlx_models {
                assert!(
                    !m.available,
                    "MLX model {} is marked available on a non-MLX target — \
                     the adaptive router will add it to fallback chains \
                     and dispatch will fail (Parslee-ai/car#231 §7.1)",
                    m.id
                );
            }
        }
    }

    /// Embedded JSON must parse cleanly — if it doesn't, the runtime
    /// would panic on first registry load. Catch it in CI instead.
    #[test]
    fn builtin_catalog_json_parses() {
        let catalog: Vec<ModelSchema> = serde_json::from_str(BUILTIN_CATALOG_JSON)
            .expect("builtin_catalog.json must be valid ModelSchema array");
        assert!(
            !catalog.is_empty(),
            "embedded catalog has no entries — that's almost certainly wrong"
        );

        let mut seen = std::collections::HashSet::new();
        for entry in &catalog {
            assert!(
                seen.insert(entry.id.clone()),
                "duplicate id in builtin_catalog.json: {}",
                entry.id
            );
        }
    }

    /// In-process Qwen3 models advertise tool capability because the local
    /// generate path now renders Qwen3's `<tools>` chat format and parses
    /// `<tool_call>` blocks back out (`tasks::generate::render_chat_prompt` /
    /// `parse_tool_calls`). This pins the catalog so the capability claim and
    /// the implementation stay in lockstep — if the in-process tool path is
    /// ever removed, this test should fail until the claim is dropped too.
    #[test]
    fn in_process_qwen3_models_declare_tool_use() {
        use crate::schema::ModelSource;
        let catalog: Vec<ModelSchema> = serde_json::from_str(BUILTIN_CATALOG_JSON).unwrap();
        // The mid/large Qwen3 sizes are reliable tool-callers; the 0.6b/1.7b
        // tiers legitimately don't advertise tool_use.
        let tool_sizes = ["qwen3-4b", "qwen3-8b", "qwen3-30b-a3b"];
        let mut checked = 0;
        for entry in &catalog {
            let in_process = matches!(
                entry.source,
                ModelSource::Mlx { .. } | ModelSource::Local { .. }
            );
            if !in_process || !tool_sizes.iter().any(|s| entry.id.contains(s)) {
                continue;
            }
            assert!(
                entry.capabilities.contains(&ModelCapability::ToolUse),
                "in-process Qwen3 model {} should advertise ToolUse — the local \
                 generate path renders/parses tool calls",
                entry.id
            );
            checked += 1;
        }
        assert_eq!(
            checked, 6,
            "expected 6 in-process tool-capable Qwen3 entries (3 mlx + 3 gguf)"
        );
    }

    #[test]
    fn public_benchmarks_round_trip_through_model_info() {
        use crate::schema::BenchmarkScore;
        let (mut reg, _tmp) = test_registry();
        let mut schema = reg
            .find_by_name("Qwen3-4B")
            .expect("catalog has Qwen3-4B")
            .clone();
        schema.id = "test/qwen3-4b-with-bench".into();
        schema.public_benchmarks = vec![
            BenchmarkScore {
                name: "MMLU-Pro".into(),
                score: 0.482,
                harness: Some("5-shot CoT".into()),
                source_url: Some("https://example.invalid/qwen3-4b-card".into()),
                measured_at: Some("2025-08-12".into()),
            },
            BenchmarkScore {
                name: "HumanEval".into(),
                score: 0.713,
                harness: Some("pass@1".into()),
                source_url: None,
                measured_at: None,
            },
        ];
        reg.register(schema);

        let stored = reg
            .get("test/qwen3-4b-with-bench")
            .expect("registered model is retrievable");
        let info = ModelInfo::from(stored);
        assert_eq!(info.public_benchmarks.len(), 2);

        // The serialized JSON shape is what the WS / FFI clients consume.
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("\"public_benchmarks\""));
        assert!(json.contains("\"MMLU-Pro\""));
        assert!(json.contains("\"5-shot CoT\""));

        // Round-trip back through serde to confirm deserialization works.
        let decoded: ModelInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.public_benchmarks.len(), 2);
        assert_eq!(decoded.public_benchmarks[0].name, "MMLU-Pro");
        assert_eq!(decoded.public_benchmarks[1].name, "HumanEval");
    }

    #[test]
    fn public_benchmarks_default_to_empty_when_absent_in_json() {
        // Older user-config JSON written before this field existed must
        // still deserialize cleanly into the new ModelSchema shape.
        let legacy_json = r#"{
            "id": "legacy/test:1",
            "name": "Legacy Test",
            "provider": "test",
            "family": "test",
            "version": "",
            "capabilities": ["generate"],
            "context_length": 4096,
            "param_count": "1B",
            "quantization": null,
            "performance": {},
            "cost": {},
            "source": { "type": "ollama", "model_tag": "legacy:1" },
            "tags": [],
            "supported_params": []
        }"#;
        let schema: ModelSchema = serde_json::from_str(legacy_json).unwrap();
        assert!(schema.public_benchmarks.is_empty());
    }

    #[test]
    fn find_by_name() {
        let (reg, _tmp) = test_registry();
        let m = reg.find_by_name("Qwen3-4B").unwrap();
        #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
        assert_eq!(m.id, "mlx/qwen3-4b:4bit");
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx))))]
        assert_eq!(m.id, "qwen/qwen3-4b:q4_k_m");
        assert!(m.has_capability(ModelCapability::Code));
    }

    #[test]
    fn query_by_capability() {
        let (reg, _tmp) = test_registry();
        let embed_models = reg.query_by_capability(ModelCapability::Embed);
        assert_eq!(embed_models.len(), 2);
        assert!(embed_models
            .iter()
            .any(|model| model.name == "Qwen3-Embedding-0.6B"));
        assert!(embed_models
            .iter()
            .any(|model| model.name == "Qwen3-Embedding-0.6B-MLX"));
    }

    #[test]
    fn query_with_filter() {
        let (reg, _tmp) = test_registry();
        let code_small = reg.query(&ModelFilter {
            capabilities: vec![ModelCapability::Code],
            max_size_mb: Some(3000),
            local_only: true,
            ..Default::default()
        });
        // Qwen3-1.7B, Qwen3-1.7B-MLX, Qwen3-4B, and Qwen3-4B-MLX fit and have Code capability.
        assert_eq!(code_small.len(), 4);
    }

    #[test]
    fn register_remote() {
        let (mut reg, _tmp) = test_registry();
        let initial_len = reg.list().len();
        let initial_reasoning_len = reg
            .query(&ModelFilter {
                capabilities: vec![ModelCapability::Reasoning, ModelCapability::ToolUse],
                ..Default::default()
            })
            .len();
        let remote = ModelSchema {
            id: "anthropic/claude-sonnet-4-6:latest".into(),
            name: "Claude Sonnet 4.6".into(),
            provider: "anthropic".into(),
            family: "claude-4".into(),
            version: "latest".into(),
            capabilities: vec![
                ModelCapability::Generate,
                ModelCapability::Code,
                ModelCapability::Reasoning,
                ModelCapability::ToolUse,
            ],
            context_length: 200000,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: PerformanceEnvelope {
                latency_p50_ms: Some(2000),
                ..Default::default()
            },
            cost: CostModel {
                input_per_mtok: Some(3.0),
                output_per_mtok: Some(15.0),
                ..Default::default()
            },
            source: ModelSource::RemoteApi {
                endpoint: "https://api.anthropic.com/v1/messages".into(),
                api_key_env: "ANTHROPIC_API_KEY".into(),
                api_key_envs: vec![],
                api_version: Some("2023-06-01".into()),
                protocol: ApiProtocol::Anthropic,
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: false,
            weights_ready: false,
        };

        reg.register(remote);
        // Same ID as builtin claude-sonnet-4-6 — replaces, count stays same
        assert_eq!(reg.list().len(), initial_len);

        let reasoning = reg.query(&ModelFilter {
            capabilities: vec![ModelCapability::Reasoning, ModelCapability::ToolUse],
            ..Default::default()
        });
        // Replacing an existing remote slot should not change the reasoning/tool-use lineup size.
        assert_eq!(reasoning.len(), initial_reasoning_len);
    }

    #[test]
    fn unregister() {
        let (mut reg, _tmp) = test_registry();
        let initial_len = reg.list().len();
        let removed = reg.unregister("qwen/qwen3-0.6b:q8_0");
        assert!(removed.is_some());
        assert_eq!(reg.list().len(), initial_len - 1);
    }

    #[test]
    fn speech_models_are_curated() {
        let (reg, _tmp) = test_registry();
        let stt = reg.query_by_capability(ModelCapability::SpeechToText);
        let tts = reg.query_by_capability(ModelCapability::TextToSpeech);
        // Parakeet-TDT-MLX + Whisper-large-v3-turbo (cross-platform) + scribe_v1.
        assert_eq!(stt.len(), 3);
        // Kokoro-6bit/bf16 + Windows-Speech (OS, Windows-only) + Qwen3-TTS + eleven.
        assert_eq!(tts.len(), 5);
        // whisper.cpp STT is a first-class catalog citizen — the cross-platform
        // local STT that runs where MLX (Apple-only) can't.
        let whisper = stt
            .iter()
            .find(|m| m.name == "Whisper-large-v3-turbo-q5_0")
            .expect("whisper STT model should be curated");
        assert!(whisper.is_local());
        assert!(matches!(
            whisper.source,
            crate::schema::ModelSource::WhisperCpp { .. }
        ));
    }

    #[test]
    fn qwen_8b_variants_keep_tool_use_consistent() {
        // The GGUF and MLX twins of Qwen3-8B must agree on tool capability, and
        // both advertise it: the in-process generate path renders Qwen3's
        // <tools> chat format and parses <tool_call> blocks back out (see
        // tasks::generate::render_chat_prompt / parse_tool_calls).
        let (reg, _tmp) = test_registry();
        for name in ["Qwen3-8B", "Qwen3-8B-MLX"] {
            let model = reg.find_by_name(name).expect("model should exist");
            assert!(model.has_capability(ModelCapability::ToolUse));
            assert!(model.has_capability(ModelCapability::MultiToolCall));
        }
    }

    #[test]
    fn mac_name_resolution_prefers_mlx_siblings() {
        // Only used inside the aarch64-macos cfg below; non-mac targets
        // keep the test as a smoke compile.
        #[allow(unused_variables)]
        let (reg, _tmp) = test_registry();
        #[cfg(all(target_os = "macos", target_arch = "aarch64", not(car_skip_mlx)))]
        {
            assert_eq!(
                reg.find_by_name("Qwen3-0.6B").unwrap().id,
                "mlx/qwen3-0.6b:6bit"
            );
            assert_eq!(
                reg.find_by_name("Qwen3-1.7B").unwrap().id,
                "mlx/qwen3-1.7b:3bit"
            );
            assert_eq!(
                reg.find_by_name("Qwen3-Embedding-0.6B").unwrap().id,
                "mlx/qwen3-embedding-0.6b:mxfp8"
            );
        }
    }

    #[test]
    fn remote_multimodal_models_are_curated_as_vision_capable() {
        let (reg, _tmp) = test_registry();
        for name in [
            "claude-opus-4-7",
            "claude-opus-4-6",
            "claude-sonnet-4-6",
            "claude-haiku-4-5",
            "gpt-5.4",
            "gpt-5.4-mini",
            "o3",
            "o4-mini",
            "gpt-4.1-mini",
            "gemini-2.5-pro",
            "gemini-2.5-flash",
        ] {
            let model = reg.find_by_name(name).expect("model should exist");
            assert!(
                model.has_capability(ModelCapability::Vision),
                "{name} should be curated as vision-capable"
            );
        }
    }

    #[test]
    fn qwen25vl_entries_are_replaced_by_qwen3vl_in_builtin_catalog() {
        let (reg, _tmp) = test_registry();

        let stale_ids = [
            // Native MLX text tower can't tokenize images — never advertise.
            "mlx/qwen2.5-vl-3b:4bit",
            "mlx/qwen2.5-vl-7b:4bit",
            // Qwen2.5-VL is superseded by Qwen3-VL; drop the mlx-vlm CLI
            // catalog entries so callers route to the upgraded family.
            "mlx-vlm/qwen2.5-vl-3b:4bit",
            "mlx-vlm/qwen2.5-vl-7b:4bit",
            // Same supersession applies to the vLLM-MLX route.
            "vllm-mlx/qwen2.5-vl-3b:4bit",
        ];
        for id in stale_ids {
            assert!(
                reg.get(id).is_none(),
                "{id} is superseded by Qwen3-VL; the catalog must not advertise it"
            );
        }

        let vision_ids: Vec<&str> = reg
            .query_by_capability(ModelCapability::Vision)
            .into_iter()
            .map(|model| model.id.as_str())
            .collect();
        for stale in stale_ids {
            assert!(
                !vision_ids.contains(&stale),
                "{stale} must not be reachable through the Vision capability index"
            );
        }
        assert!(
            vision_ids.contains(&"mlx-vlm/qwen3-vl-2b:bf16"),
            "Qwen3-VL is the supported local VL family and must route as Vision"
        );
    }

    #[test]
    fn gemini_models_are_curated_for_multimodal_tool_use() {
        let (reg, _tmp) = test_registry();
        for name in ["gemini-2.5-pro", "gemini-2.5-flash"] {
            let model = reg.find_by_name(name).expect("model should exist");
            assert!(model.has_capability(ModelCapability::Vision));
            assert!(model.has_capability(ModelCapability::ToolUse));
            assert!(model.has_capability(ModelCapability::MultiToolCall));
        }
    }

    #[test]
    fn model_info_publishes_declared_prices_and_keeps_unpriced_distinct_from_free() {
        let (reg, _tmp) = test_registry();

        // A priced remote row publishes every declared rate plus its tiers.
        let opus = reg
            .list()
            .into_iter()
            .find(|m| m.id == "openrouter/anthropic/claude-opus-4.8")
            .map(ModelInfo::from)
            .expect("curated opus-4.8 row is present on first boot");
        assert_eq!(opus.cost.input_per_mtok, Some(5.0));
        assert_eq!(opus.cost.output_per_mtok, Some(25.0));
        assert_eq!(opus.cost.cache_read_input_per_mtok, Some(0.5));
        assert_eq!(opus.cost.cache_write_input_per_mtok, Some(6.25));

        // Tiered pricing survives the projection where a model declares it.
        let gpt = reg
            .list()
            .into_iter()
            .find(|m| m.id == "openrouter/openai/gpt-5.4")
            .map(ModelInfo::from)
            .expect("curated gpt-5.4 row");
        assert_eq!(gpt.cost.pricing_tiers.len(), 1);
        assert_eq!(gpt.cost.prices_for(272_000).input_per_mtok, Some(5.0));

        // A local model that declares no prices reports them ABSENT. `null`
        // and `0.0` are different facts and must stay different on the wire.
        let local = reg
            .list()
            .into_iter()
            .find(|m| m.is_local() && m.cost.input_per_mtok.is_none())
            .map(ModelInfo::from)
            .expect("the built-in catalog ships unpriced local models");
        let json = serde_json::to_value(&local).unwrap();
        assert!(json["cost"]["input_per_mtok"].is_null());
        assert!(json["cost"]["output_per_mtok"].is_null());
        assert_ne!(json["cost"]["input_per_mtok"], serde_json::json!(0.0));
    }

    #[test]
    fn a_hand_registered_copy_of_a_curated_id_does_not_double_the_row() {
        let (mut reg, _tmp) = test_registry();
        let id = "openrouter/anthropic/claude-opus-4.8";
        assert_eq!(reg.list().iter().filter(|m| m.id == id).count(), 1);

        // The runtime registry is keyed by id, so a user registration of the
        // same id replaces the curated row rather than appending a duplicate.
        let mut copy = reg
            .list()
            .into_iter()
            .find(|m| m.id == id)
            .cloned()
            .expect("curated row");
        copy.name = "hand-registered".into();
        reg.register_user_model(copy);
        assert_eq!(reg.list().iter().filter(|m| m.id == id).count(), 1);
    }

    /// Scoped to `ModelInfo` — the `models.list_unified` projection — on
    /// purpose. `models.search` wraps this same struct but adds `family`,
    /// which for a managed alias names the upstream model family and is
    /// matched against by queries. That is pre-existing (`frontier-deep`
    /// already carries `claude-4.6`) and out of scope here; this test locks
    /// the surface the guarantee actually holds on rather than implying a
    /// registry-wide one it does not.
    #[test]
    fn managed_alias_publishes_prices_without_disclosing_the_upstream_id_in_the_catalog_view() {
        let (reg, _tmp) = test_registry();
        let alias = reg
            .list()
            .into_iter()
            .find(|m| m.id == "parslee/openrouter/frontier-deep-next")
            .map(ModelInfo::from)
            .expect("managed alias for the new curated row");

        assert_eq!(alias.cost.input_per_mtok, Some(5.0));
        assert_eq!(alias.cost.output_per_mtok, Some(25.0));
        assert_eq!(alias.cost.cache_read_input_per_mtok, Some(0.5));
        assert_eq!(alias.cost.cache_write_input_per_mtok, Some(6.25));

        let wire = serde_json::to_string(&alias).unwrap();
        assert!(!wire.contains("claude-opus-4.8"));
        assert!(!wire.contains("anthropic/"));
    }

    #[test]
    fn model_info_from_an_older_daemon_without_cost_still_parses() {
        // A newly built client must not fail to read a catalog produced before
        // `cost` existed; the row deserializes with an all-absent cost.
        let legacy = serde_json::json!({
            "id": "legacy/model",
            "name": "legacy",
            "provider": "legacy",
            "capabilities": ["generate"],
            "param_count": "",
            "size_mb": 0,
            "context_length": 8192,
            "available": true,
            "is_local": false
        });
        let info: ModelInfo = serde_json::from_value(legacy).expect("older catalog row parses");
        assert!(info.cost.input_per_mtok.is_none());
        assert!(info.cost.output_per_mtok.is_none());
        assert!(info.cost.pricing_tiers.is_empty());
        assert!(info.max_output_tokens.is_none());
    }

    #[test]
    fn visual_generation_models_are_curated() {
        let (reg, _tmp) = test_registry();
        assert_eq!(
            reg.query_by_capability(ModelCapability::ImageGeneration)
                .len(),
            1
        );
        assert_eq!(
            reg.query_by_capability(ModelCapability::VideoGeneration)
                .len(),
            1
        );
    }
}