car-inference 0.53.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
//! Model schema — declarative metadata for models, analogous to ToolSchema for tools.
//!
//! Every model (local GGUF, remote API, Ollama) is described by a `ModelSchema`
//! that declares identity, capabilities, constraints, cost, and source.
//! The router uses this schema for initial routing; observed outcomes refine it.

use serde::{Deserialize, Serialize};

/// What a model can do.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelCapability {
    /// Text completion / chat generation
    Generate,
    /// Vector embeddings
    Embed,
    /// Cross-encoder relevance scoring (query + document → relevance
    /// score). Qwen3-Reranker is the canonical local implementation.
    Rerank,
    /// Label assignment / classification
    Classify,
    /// Code generation, repair, refactoring
    Code,
    /// Chain-of-thought, planning, analysis
    Reasoning,
    /// Text condensation
    Summarize,
    /// Function/tool calling
    ToolUse,
    /// Multiple tool calls in a single response (parallel tool execution)
    MultiToolCall,
    /// Vision / image understanding
    Vision,
    /// Video understanding (multi-frame sampling + temporal tokens).
    /// Distinct from `Vision` so routing can prefer video-trained
    /// models when the caller attaches a video content block.
    VideoUnderstanding,
    /// Audio understanding (speech + non-speech audio as an input to
    /// a chat/reasoning model). Distinct from `SpeechToText` which is
    /// the transcription-only task. Gemma 4 E2B/E4B and Gemini do
    /// this; Qwen2.5-VL does not.
    AudioUnderstanding,
    /// Visual grounding — structured object-localization output
    /// (bounding boxes keyed to object labels) in addition to text.
    Grounding,
    /// Speech recognition / transcription
    SpeechToText,
    /// Speech synthesis / text-to-speech
    TextToSpeech,
    /// Image generation
    ImageGeneration,
    /// Video generation
    VideoGeneration,
}

/// How much the project vouches for a model. Gates automatic upgrades and
/// is surfaced in recommendation rationale. Closed enum — a new tier is a
/// deliberate FFI-visible change, never a silent string fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TrustTier {
    /// Vetted by the project — the built-in catalog and verified upgrades.
    /// Eligible for background auto-apply when the user opts in.
    #[default]
    Curated,
    /// User-registered or upstream-discovered, not project-vetted. Always
    /// notify-only; never auto-applied regardless of update policy.
    Community,
}

/// How to access the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ModelSource {
    /// Local GGUF file via Candle backend.
    Local {
        hf_repo: String,
        hf_filename: String,
        tokenizer_repo: String,
    },
    /// Remote API endpoint (OpenAI-compatible, Anthropic, etc.)
    RemoteApi {
        endpoint: String,
        /// Environment variable name containing the API key (never the key itself).
        /// The env var value may contain comma-separated keys for load balancing.
        api_key_env: String,
        /// Additional environment variable names for load balancing across multiple keys.
        /// Each env var may also contain comma-separated keys.
        #[serde(default)]
        api_key_envs: Vec<String>,
        #[serde(default)]
        api_version: Option<String>,
        protocol: ApiProtocol,
    },
    /// Ollama local server.
    Ollama {
        model_tag: String,
        #[serde(default = "default_ollama_host")]
        host: String,
    },
    /// Local MLX model via mlx-rs backend (Apple Silicon, safetensors format).
    /// Models from mlx-community on HuggingFace.
    Mlx {
        /// HuggingFace repo (e.g., "mlx-community/Qwen3-4B-4bit").
        hf_repo: String,
        /// Optional specific weight filename. If None, auto-discovers safetensors files.
        #[serde(default)]
        hf_weight_file: Option<String>,
    },
    /// Local whisper.cpp speech-to-text model — a ggml `.bin` from the
    /// `ggerganov/whisper.cpp` HF repo, run in-process via the shared
    /// `car-whisper` crate. Cross-platform (Windows/Linux/macOS): this is the
    /// on-device STT path where MLX isn't available. Cached at
    /// `~/.tokhn/whisper/ggml-<model>.bin`.
    WhisperCpp {
        /// whisper.cpp model id — the suffix of `ggml-<model>.bin`
        /// (e.g. `"large-v3-turbo-q5_0"`).
        model: String,
    },
    /// Windows OS text-to-speech via `Windows.Media.SpeechSynthesis` (WinRT),
    /// run in-process. The catalog-side analog of the `car-voice`
    /// `TtsProvider::WindowsSpeech` live path and the parity counterpart of
    /// Apple's OS synthesizer — free, on-device, no model download, no MLX.
    /// Windows-only; availability is `false` on every other target (like
    /// `AppleFoundationModels`).
    WindowsSpeech {},
    /// Local vLLM-MLX server (Apple Silicon, OpenAI-compatible API).
    /// Routes through RemoteBackend with OpenAI protocol handler.
    VllmMlx {
        /// Server endpoint (e.g., "http://localhost:8000").
        endpoint: String,
        /// The model name as known to vLLM-MLX (e.g., "mlx-community/Qwen3-4B-4bit").
        model_name: String,
    },
    /// CAR-owned supervised vLLM-MLX process backed by a managed HuggingFace
    /// artifact. Unlike `VllmMlx`, CAR downloads, admits, spawns, reaps, and
    /// accounts this allocation. Dispatch rewrites a clone to `VllmMlx` only
    /// after the child reports healthy.
    ManagedVllmMlx {
        hf_repo: String,
        #[serde(default)]
        hf_weight_file: Option<String>,
    },
    /// Apple's on-device system model via the FoundationModels framework
    /// (macOS 26+, Apple Silicon). Inference happens in-process through a
    /// Swift shim — there is no HTTP, no API key, and no model file: the
    /// OS owns the weights. Availability is checked at runtime via
    /// `@available(macOS 26.0, *)`; on older macOS or non-Apple-Silicon
    /// hosts the backend reports `UnsupportedMode` and the router falls
    /// through to the next candidate.
    AppleFoundationModels {
        /// Optional Apple use-case hint passed through to
        /// `LanguageModelSession`. Apple's framework tunes its prompt and
        /// safety scaffolding per use case (e.g. "general", "summarize").
        /// `None` uses the default.
        #[serde(default)]
        use_case: Option<String>,
    },
    /// Proprietary provider with custom auth and protocol.
    ///
    /// For vendor-specific APIs that aren't generic OpenAI-compatible endpoints.
    /// Parslee is the first proprietary provider — custom auth (OAuth2),
    /// custom response format, multi-provider routing built into the API.
    Proprietary {
        /// Provider identifier (e.g., "parslee").
        provider: String,
        /// Base URL for the API.
        endpoint: String,
        /// Auth configuration.
        auth: ProprietaryAuth,
        /// Custom protocol details.
        protocol: ProprietaryProtocol,
    },
    /// Inference is delegated to a host-registered runner. CAR does
    /// not own the wire format — the runner (typically a JS / Python
    /// host) translates the `GenerateRequest` to its provider's API,
    /// streams chunks back through the runner's event callback, and
    /// returns the final aggregated result.
    ///
    /// Closes Parslee-ai/car-releases#24. Use this when the host
    /// already has an SDK relationship with a provider (Anthropic,
    /// OpenAI, GitHub Models, Vercel AI SDK) and wants CAR to sit in
    /// the lifecycle / policy / replay path without learning every
    /// provider's wire format.
    ///
    /// Routing requires that a runner has been registered via
    /// [`crate::set_inference_runner`] (or its FFI equivalent —
    /// `registerInferenceRunner` on JS, `register_inference_runner`
    /// on Python, the `InferenceRunner` foreign trait on UniFFI,
    /// `inference.register_runner` on the WebSocket protocol).
    /// Without a runner, dispatch fails with `InferenceFailed`.
    Delegated {
        /// Opaque hint passed through to the runner — typically the
        /// provider id (`"anthropic"`, `"openai"`, `"vercel-ai-sdk"`)
        /// so a multi-provider runner can dispatch internally. CAR
        /// does not interpret this string.
        #[serde(default)]
        hint: Option<String>,
    },
}

/// Authentication method for proprietary providers.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProprietaryAuth {
    /// OAuth2 PKCE flow (e.g., Azure AD for Parslee).
    #[serde(rename = "oauth2_pkce", alias = "o_auth2_pkce")]
    OAuth2Pkce {
        authority: String,
        client_id: String,
        scopes: Vec<String>,
    },
    /// Static API key from environment variable.
    ApiKeyEnv { env_var: String },
    /// Bearer token from environment variable.
    BearerTokenEnv { env_var: String },
}

/// Protocol configuration for proprietary providers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProprietaryProtocol {
    /// Chat/completion endpoint path (appended to base URL).
    #[serde(default = "default_chat_path")]
    pub chat_path: String,
    /// Content type for requests.
    #[serde(default = "default_content_type")]
    pub content_type: String,
    /// Whether the API streams responses via SSE.
    #[serde(default)]
    pub streaming: bool,
    /// Custom headers to include in every request.
    #[serde(default)]
    pub extra_headers: std::collections::HashMap<String, String>,
}

impl Default for ProprietaryProtocol {
    fn default() -> Self {
        Self {
            chat_path: default_chat_path(),
            content_type: default_content_type(),
            streaming: false,
            extra_headers: std::collections::HashMap::new(),
        }
    }
}

fn default_chat_path() -> String {
    "/chat".to_string()
}

fn default_content_type() -> String {
    "application/json".to_string()
}

fn default_ollama_host() -> String {
    "http://localhost:11434".to_string()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApiProtocol {
    OpenAiCompat,
    /// OpenRouter's OpenAI-compatible Chat Completions surface. Distinct so
    /// credential precedence and error translation stay provider-specific.
    OpenRouter,
    /// OpenAI Responses API (/v1/responses) — works with all OpenAI models including codex.
    OpenAiResponses,
    Anthropic,
    Google,
    /// Azure OpenAI — uses api-key header and deployment-based URLs.
    /// Endpoint format: {base}/openai/deployments/{model}/chat/completions?api-version={version}
    AzureOpenAi,
    /// Google Vertex AI — the enterprise Gemini surface. Same request/response
    /// shape as the AI-Studio `Google` protocol, but a project/location URL and
    /// OAuth Bearer auth (a GCP access token from `gcloud auth print-access-token`
    /// or a service account) instead of an `?key=` query param. Endpoint format:
    /// `{base}/publishers/google/models/{model}:generateContent`, where `base`
    /// is `https://{loc}-aiplatform.googleapis.com/v1/projects/{proj}/locations/{loc}`.
    VertexAi,
    /// AWS Bedrock — the **Converse** API (`bedrock-runtime`), a unified
    /// messages surface across Bedrock-hosted models (Claude, Llama, Mistral,
    /// Titan, …). Auth is **SigV4** request signing (not a bearer token), with
    /// credentials from the standard AWS env vars; the model's `endpoint` is the
    /// region (e.g. `us-east-1`) and `name` is the Bedrock model id. Non-stream
    /// only for now (Converse streaming uses a separate binary event-stream).
    Bedrock,
}

impl ApiProtocol {
    /// Prompt-cache economics for this provider, relative to its base input
    /// rate — used by the cost scoreboard to price cached tokens correctly.
    /// Anthropic uses explicit breakpoints (deep read discount + write
    /// premium); OpenAI/Azure cache automatically (~0.5× read, no write
    /// charge). Providers whose cache tokens CAR does not parse (Google/Vertex/
    /// Bedrock) report zero cache tokens, so their rates are inert.
    pub fn cache_rates(&self) -> crate::outcome::CacheRates {
        use crate::outcome::CacheRates;
        match self {
            ApiProtocol::Anthropic => CacheRates::ANTHROPIC,
            ApiProtocol::OpenAiCompat | ApiProtocol::OpenAiResponses | ApiProtocol::AzureOpenAi => {
                CacheRates::OPENAI
            }
            // OpenRouter rates differ per upstream model and are carried by
            // ModelSchema::cost. A blanket OpenAI-shaped discount is false.
            ApiProtocol::OpenRouter => CacheRates::NONE,
            ApiProtocol::Google | ApiProtocol::VertexAi | ApiProtocol::Bedrock => CacheRates::NONE,
        }
    }
}

/// The numeric format a checkpoint's weights are stored in.
///
/// Deliberately says nothing about *which engine* serves the file —
/// [`ModelSource`] already carries that, and keying this on the container
/// instead of the format produces falsehoods: whisper.cpp's `q5_0` ggml
/// checkpoints use the same round-to-nearest block format as llama.cpp's, and
/// a `Gguf*` variant would assert a GGUF text path that cannot load them.
///
/// What it does express is the axis neither the bit width nor the source can:
/// an MLX 4-bit affine checkpoint and a `Q4_K_M` are both "4-bit", were
/// produced by different algorithms, and do not have the same quality.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QuantScheme {
    /// Integer weights with a scale and bias shared across `group_size`
    /// elements (`4bit`, `6bit`). MLX's default and only affine format.
    AffineGroupInt,
    /// Block-scaled float — MX formats (`mxfp4`, `mxfp8`). A genuinely
    /// different loader path from [`QuantScheme::AffineGroupInt`] at the same
    /// nominal width; see the microscaling-mode rejection in `backend/mlx.rs`,
    /// which currently accepts exactly one of these.
    BlockScaledFloat,
    /// Mixed per-tensor bit allocation, optionally importance-weighted
    /// (`Q4_K_M`, `Q5_K_S`, `IQ4_XS`, `TQ1_0`).
    KQuantMixed,
    /// Uniform round-to-nearest blocks, no per-tensor mixing and no importance
    /// weighting (`Q8_0`, `q5_0`, `Q4_0_4_4`).
    RtnBlock,
    /// Full-precision weights (`bf16`, `f16`, `f32`). Distinct from `None` at
    /// the [`ModelSchema::quantization`] level: a positive claim that the
    /// checkpoint is unquantized, not an absence of information.
    Unquantized,
    /// A format this parser could not identify. The label is still preserved
    /// verbatim; only the classification is missing.
    #[default]
    Unknown,
}

/// Structured quantization descriptor.
///
/// This replaces a free-text string that mixed two vocabularies — MLX's
/// `4bit`/`6bit` and GGUF's `Q4_K_M`/`Q8_0` — under one field, so nothing could
/// tell a group-quantized integer checkpoint from a mixed k-quant one. It also
/// threw away what the ingest paths already had in hand: MLX `config.json`
/// declares `{bits, group_size, mode}` and only `bits` survived.
///
/// Deserializes from **either** the legacy bare string or the structured
/// object, so catalogs, user `models.json` files, and `models.register`
/// payloads written before this change keep loading unchanged. The object form
/// requires `label` and rejects unknown fields: a misspelled key is a producer
/// bug, and accepting it silently is how the field it replaced lost
/// information in the first place.
///
/// **Writes the bare label back whenever that is lossless**, and the object
/// only when it carries something parsing cannot recover — a `group_size`, or
/// a `scheme` that disambiguates a label the parser reads as `Unknown`. Two
/// reasons, both about blast radius rather than taste. This value is inside
/// `catalog_identity::row_digest`, so an unconditional shape change would move
/// the digest of every quantized row and hard-fail any client that pinned
/// `expected_catalog_revision`. And `registry::load_user_config` fails a
/// `models.json` **whole**, with its only production caller discarding the
/// error — so an older daemon meeting an object it cannot parse boots with
/// zero registered models and says nothing. Emitting the object only where it
/// adds information keeps both costs proportional to what actually changed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Quantization {
    /// Weight bit width. `None` when the label names none.
    pub bits: Option<u8>,
    /// Which quantization family this is.
    pub scheme: QuantScheme,
    /// Elements sharing one scale/zero point (MLX: 32, 64, 128). `None` when
    /// the scheme has no group concept, or the source declared none.
    pub group_size: Option<u32>,
    /// The label exactly as published. Never synthesized: it is what the user
    /// sees, what Hugging Face repos are named after, and the only thing that
    /// survives a scheme CAR does not recognize yet.
    pub label: String,
}

/// Widths affine group quantization actually uses. A `16bit` or `32bit`
/// label is full precision that happens to be spelled like a quant.
const AFFINE_GROUP_WIDTHS: std::ops::RangeInclusive<u8> = 2..=8;

impl Quantization {
    /// Best-effort structure from a published label.
    ///
    /// Never fails and never invents: an unrecognized label yields
    /// [`QuantScheme::Unknown`] with the label intact.
    pub fn parse(label: &str) -> Self {
        let label = label.trim();
        let lower = label.to_ascii_lowercase();
        let build = |bits: Option<u8>, scheme: QuantScheme| Self {
            bits,
            scheme,
            group_size: None,
            label: label.to_string(),
        };

        // Full precision. `fp8` is deliberately NOT here — an 8-bit float is a
        // quantized weight format, just not one this parser can attribute.
        match lower.as_str() {
            "bf16" | "f16" | "fp16" | "float16" | "half" => {
                return build(Some(16), QuantScheme::Unquantized)
            }
            "f32" | "fp32" | "float32" | "full" => {
                return build(Some(32), QuantScheme::Unquantized)
            }
            "none" => return build(None, QuantScheme::Unquantized),
            "f8" | "fp8" | "float8" => return build(Some(8), QuantScheme::Unknown),
            // Empty means nobody said, which is not a claim of full precision.
            "" => return build(None, QuantScheme::Unknown),
            _ => {}
        }

        // MLX block-scaled floats: `mxfp4`, `mxfp8`. A bare `mxfp` names no
        // width, so it identifies nothing.
        if let Some(rest) = lower.strip_prefix("mxfp") {
            return match leading_number(rest) {
                Some((bits, _)) => build(Some(bits), QuantScheme::BlockScaledFloat),
                None => build(None, QuantScheme::Unknown),
            };
        }

        // MLX affine group quant: `4bit`, `4-bit`, `6bit`.
        if let Some(width) = lower.strip_suffix("bit").map(|w| w.trim_end_matches('-')) {
            if let Some((bits, consumed)) = leading_number(width) {
                if consumed == width.len() && AFFINE_GROUP_WIDTHS.contains(&bits) {
                    return build(Some(bits), QuantScheme::AffineGroupInt);
                }
                // `16bit`/`32bit` are full precision spelled as a width.
                if consumed == width.len() && (bits == 16 || bits == 32) {
                    return build(Some(bits), QuantScheme::Unquantized);
                }
            }
        }

        // GGUF. `iq`/`tq` are k-quant families; a bare `q` needs its suffix
        // read to tell k-quant from legacy round-to-nearest.
        let gguf = lower
            .strip_prefix("iq")
            .or_else(|| lower.strip_prefix("tq"))
            .map(|rest| (rest, true))
            .or_else(|| lower.strip_prefix('q').map(|rest| (rest, false)));
        if let Some((rest, k_family)) = gguf {
            if let Some((bits, consumed)) = leading_number(rest) {
                if bits == 0 {
                    return build(None, QuantScheme::Unknown);
                }
                // Slice by digits consumed, not by the width's decimal length —
                // `q08_0` has a two-character prefix for a one-character number.
                let suffix = &rest[consumed..];
                let scheme = if k_family || suffix.contains("_k") {
                    QuantScheme::KQuantMixed
                } else if suffix.starts_with("_0") || suffix.starts_with("_1") {
                    // `starts_with`, not equality: the aarch64 repack quants
                    // are `Q4_0_4_4`, `Q4_0_4_8`, `Q4_0_8_8`.
                    QuantScheme::RtnBlock
                } else {
                    // A bare `Q4` names a width and no producer — llama.cpp
                    // has no such format, so this came from somewhere else.
                    QuantScheme::Unknown
                };
                return build(Some(bits), scheme);
            }
        }

        build(None, QuantScheme::Unknown)
    }

    /// Recover the quantization a GGUF file names in its own filename
    /// (`Qwen3-8B-Q4_K_M.gguf`, `ggml-large-v3-turbo-q5_0.gguf`).
    ///
    /// Scans the hyphen-separated segments from the right and takes the first
    /// that classifies, so a model whose *name* contains something quant-shaped
    /// does not outrank the real suffix. Returns `None` rather than guessing
    /// when nothing in the name is recognizable.
    pub fn from_gguf_filename(filename: &str) -> Option<Self> {
        let stem = filename
            .rsplit_once('.')
            .map(|(stem, _)| stem)
            .unwrap_or(filename);
        stem.rsplit('-')
            .map(Self::parse)
            .find(|q| q.scheme != QuantScheme::Unknown)
    }

    /// Descriptor for an MLX checkpoint, from the `quantization` block of its
    /// `config.json`. `mode` is MLX's own name for the format (`affine`,
    /// `mxfp4`, `mxfp8`); absent means affine, which is MLX's default.
    ///
    /// Returns `None` when the block carried nothing usable — declaring
    /// `AffineGroupInt` on the strength of an empty object would assert exactly the
    /// thing this type exists to establish.
    pub fn from_mlx_config(
        bits: Option<u8>,
        group_size: Option<u32>,
        mode: Option<&str>,
    ) -> Option<Self> {
        if bits.is_none() && group_size.is_none() && mode.is_none() {
            return None;
        }
        let normalized = mode.map(str::to_ascii_lowercase);
        let scheme = match normalized.as_deref() {
            Some(m) if m.starts_with("mxfp") => QuantScheme::BlockScaledFloat,
            Some("affine") | None => QuantScheme::AffineGroupInt,
            Some(_) => QuantScheme::Unknown,
        };
        let label = match (normalized.as_deref(), bits) {
            (Some(m), _) if m != "affine" => m.to_string(),
            (_, Some(b)) => format!("{b}bit"),
            // No width and no distinguishing mode: MLX said "affine" and
            // nothing else. Say that rather than inventing a width.
            (_, None) => "affine".to_string(),
        };
        Some(Self {
            bits,
            scheme,
            group_size,
            label,
        })
    }
}

/// Leading run of ASCII digits as a bit width, with the number of bytes it
/// occupied. The byte count is returned because it is not recoverable from the
/// value — `08` and `8` parse the same and slice differently.
fn leading_number(s: &str) -> Option<(u8, usize)> {
    let digits: String = s.chars().take_while(char::is_ascii_digit).collect();
    if digits.is_empty() {
        return None;
    }
    // Overflow (`Q256_K`) is a parse failure, not a silent truncation.
    digits.parse().ok().map(|n| (n, digits.len()))
}

impl std::fmt::Display for Quantization {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.label)
    }
}

impl Serialize for Quantization {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;

        // Round-tripping through `parse` is the exact test for "the label
        // carries everything": if it reproduces this value, the object form
        // would be a longer spelling of the same information.
        if Self::parse(&self.label) == *self {
            return serializer.serialize_str(&self.label);
        }

        let len = 2 + usize::from(self.bits.is_some()) + usize::from(self.group_size.is_some());
        let mut row = serializer.serialize_struct("Quantization", len)?;
        if let Some(bits) = self.bits {
            row.serialize_field("bits", &bits)?;
        }
        row.serialize_field("scheme", &self.scheme)?;
        if let Some(group_size) = self.group_size {
            row.serialize_field("group_size", &group_size)?;
        }
        row.serialize_field("label", &self.label)?;
        row.end()
    }
}

impl<'de> Deserialize<'de> for Quantization {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        /// The object form. `label` is required and unknown fields are
        /// rejected, so a typo'd or double-nested payload is an error rather
        /// than a row that silently claims `Unknown`.
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Structured {
            #[serde(default)]
            bits: Option<u8>,
            #[serde(default)]
            scheme: Option<QuantScheme>,
            #[serde(default)]
            group_size: Option<u32>,
            label: String,
        }

        struct QuantizationVisitor;

        impl<'de> serde::de::Visitor<'de> for QuantizationVisitor {
            type Value = Quantization;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a quantization label string, or an object with a `label` field")
            }

            fn visit_str<E: serde::de::Error>(self, label: &str) -> Result<Self::Value, E> {
                Ok(Quantization::parse(label))
            }

            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                map: M,
            ) -> Result<Self::Value, M::Error> {
                // Dispatched by hand rather than via `#[serde(untagged)]`,
                // which buffers the input and reports only "data did not match
                // any variant" — for a `models.json` holding dozens of models
                // that error names neither the field nor the row.
                let s = Structured::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
                // A row that omits `scheme` or `bits` recovers what its label
                // implies; an explicit value always wins.
                let inferred = Quantization::parse(&s.label);
                Ok(Quantization {
                    bits: s.bits.or(inferred.bits),
                    scheme: s.scheme.unwrap_or(inferred.scheme),
                    group_size: s.group_size,
                    label: s.label,
                })
            }
        }

        d.deserialize_any(QuantizationVisitor)
    }
}

/// Declared performance expectations. Overridden by observed data once available.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PerformanceEnvelope {
    /// Median latency in milliseconds (declared/estimated).
    #[serde(default)]
    pub latency_p50_ms: Option<u64>,
    /// 99th percentile latency in milliseconds.
    #[serde(default)]
    pub latency_p99_ms: Option<u64>,
    /// Tokens per second throughput.
    #[serde(default)]
    pub tokens_per_second: Option<f64>,
}

/// Cost model for routing optimization.
/// Generation parameters that a model may or may not support.
/// Models declare which params they accept. The inference layer
/// strips unsupported params before sending to the API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GenerateParam {
    Temperature,
    TopP,
    TopK,
    MaxTokens,
    StopSequences,
    FrequencyPenalty,
    PresencePenalty,
    Seed,
    ResponseFormat,
    /// Extended thinking / internal reasoning before responding.
    ExtendedThinking,
}

/// Standard parameter set for most models.
pub fn standard_params() -> Vec<GenerateParam> {
    vec![
        GenerateParam::Temperature,
        GenerateParam::TopP,
        GenerateParam::MaxTokens,
        GenerateParam::StopSequences,
        GenerateParam::FrequencyPenalty,
        GenerateParam::PresencePenalty,
        GenerateParam::Seed,
    ]
}

/// Parameter set for reasoning models (no temperature, no top_p).
pub fn reasoning_params() -> Vec<GenerateParam> {
    vec![GenerateParam::MaxTokens, GenerateParam::StopSequences]
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct TokenPrices {
    /// USD per 1M uncached input tokens.
    #[serde(default)]
    pub input_per_mtok: Option<f64>,
    /// USD per 1M output tokens.
    #[serde(default)]
    pub output_per_mtok: Option<f64>,
    /// USD per 1M cache-read input tokens.
    #[serde(default)]
    pub cache_read_input_per_mtok: Option<f64>,
    /// USD per 1M cache-write input tokens.
    #[serde(default)]
    pub cache_write_input_per_mtok: Option<f64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct TokenPricingTier {
    /// Inclusive prompt-token threshold at which this tier applies.
    pub min_prompt_tokens: usize,
    #[serde(flatten)]
    pub prices: TokenPrices,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CostModel {
    /// USD per 1M input tokens (remote models).
    #[serde(default)]
    pub input_per_mtok: Option<f64>,
    /// USD per 1M output tokens (remote models).
    #[serde(default)]
    pub output_per_mtok: Option<f64>,
    /// USD per 1M cache-read input tokens. Unlike protocol-wide cache
    /// multipliers, this is model-specific and comes from the provider's
    /// published catalog.
    #[serde(default)]
    pub cache_read_input_per_mtok: Option<f64>,
    /// USD per 1M cache-write input tokens, when the provider charges one.
    #[serde(default)]
    pub cache_write_input_per_mtok: Option<f64>,
    /// Prompt-size pricing overrides, sorted by increasing threshold.
    /// The highest threshold not greater than the prompt size wins.
    #[serde(default)]
    pub pricing_tiers: Vec<TokenPricingTier>,
    /// On-disk size in MB (local models).
    #[serde(default)]
    pub size_mb: Option<u64>,
    /// RAM required during inference in MB.
    #[serde(default)]
    pub ram_mb: Option<u64>,
}

impl CostModel {
    pub fn prices_for(&self, prompt_tokens: usize) -> TokenPrices {
        let mut prices = TokenPrices {
            input_per_mtok: self.input_per_mtok,
            output_per_mtok: self.output_per_mtok,
            cache_read_input_per_mtok: self.cache_read_input_per_mtok,
            cache_write_input_per_mtok: self.cache_write_input_per_mtok,
        };
        for tier in self
            .pricing_tiers
            .iter()
            .filter(|tier| tier.min_prompt_tokens <= prompt_tokens)
        {
            if tier.prices.input_per_mtok.is_some() {
                prices.input_per_mtok = tier.prices.input_per_mtok;
            }
            if tier.prices.output_per_mtok.is_some() {
                prices.output_per_mtok = tier.prices.output_per_mtok;
            }
            if tier.prices.cache_read_input_per_mtok.is_some() {
                prices.cache_read_input_per_mtok = tier.prices.cache_read_input_per_mtok;
            }
            if tier.prices.cache_write_input_per_mtok.is_some() {
                prices.cache_write_input_per_mtok = tier.prices.cache_write_input_per_mtok;
            }
        }
        prices
    }

    /// Estimated request cost from the provider's declared token prices.
    /// Unknown price components contribute zero; callers that need to
    /// distinguish unknown pricing should inspect `prices_for` first.
    ///
    /// **This is the routing-score input, not a display or billing figure.**
    /// The zero-fill is load-bearing here — `adaptive_router` normalizes the
    /// result into a 0..1 cost score, and it separately neutralizes models
    /// with no pricing at all, so changing the fill would change routing.
    /// For anything a human reads, use
    /// [`estimated_usd_bounded`](Self::estimated_usd_bounded), which refuses
    /// to bill an unrated bucket at zero and says which way it can be wrong.
    pub fn estimated_usd(
        &self,
        prompt_tokens: usize,
        output_tokens: usize,
        cache_read_tokens: usize,
        cache_write_tokens: usize,
    ) -> f64 {
        let prices = self.prices_for(prompt_tokens);
        let uncached_input = prompt_tokens
            .saturating_sub(cache_read_tokens)
            .saturating_sub(cache_write_tokens);
        (uncached_input as f64 * prices.input_per_mtok.unwrap_or(0.0)
            + output_tokens as f64 * prices.output_per_mtok.unwrap_or(0.0)
            + cache_read_tokens as f64 * prices.cache_read_input_per_mtok.unwrap_or(0.0)
            + cache_write_tokens as f64 * prices.cache_write_input_per_mtok.unwrap_or(0.0))
            / 1_000_000.0
    }

    /// Effective per-bucket rates under one resolved price sheet, in the
    /// bucket order `[uncached input, output, cache read, cache write]`, each
    /// paired with which way a *substituted* rate can be wrong:
    /// `(rate, may_overstate, may_understate)`.
    ///
    /// The two cache buckets substitute the uncached-input rate but are **not
    /// governed by one rule**, because the providers in this catalog do not
    /// price them the same way relative to input:
    ///
    /// | bucket | observed vs input, curated table |
    /// |---|---|
    /// | cache read | `0.10x`–`0.64x` — always a discount |
    /// | cache write | `0.1875x` (Google) … `1.25x` (Anthropic) — **both sides** |
    ///
    /// So substituting input for a missing **cache-read** rate can only be too
    /// high (`may_overstate`), while for a missing **cache-write** rate it can
    /// land either side and gets both flags, rendering `~` rather than a `≤`
    /// the figure cannot honour. Treating the two alike is how `claude-opus-4.8`
    /// — `input 5.0`, `cache_write 6.25` — would have worn a `≤$5.00` ceiling
    /// over a true cost of `$6.25`, or `$10.00` at OpenRouter's 1h-TTL rate.
    ///
    /// **Output** substitutes nothing and refuses instead: output runs
    /// `1.5x`–`8x` input across this same table, which is not a ballpark
    /// estimate in either direction, merely a wrong number wearing a marker.
    /// The line is whether a substitute is *within range and merely of unknown
    /// sign* (estimate, flag it) or *out of range entirely* (refuse) — see
    /// [`estimated_usd_bounded`](Self::estimated_usd_bounded).
    fn bucket_rates(prices: &TokenPrices) -> [(Option<f64>, bool, bool); 4] {
        // A cached READ is always discounted relative to uncached input — the
        // entire point of the cache — so the input rate is a true ceiling.
        let cache_read = match prices.cache_read_input_per_mtok {
            Some(rate) => (Some(rate), false, false),
            None => {
                let substituted = prices.input_per_mtok.is_some();
                (prices.input_per_mtok, substituted, false)
            }
        };
        // A cache WRITE may be a surcharge (Anthropic 1.25x, OpenRouter's 1h
        // TTL 2x) or a discount (Google 0.1875x). Unknown sign, so no bound.
        let cache_write = match prices.cache_write_input_per_mtok {
            Some(rate) => (Some(rate), false, false),
            None => {
                let substituted = prices.input_per_mtok.is_some();
                (prices.input_per_mtok, substituted, substituted)
            }
        };
        [
            (prices.input_per_mtok, false, false),
            (prices.output_per_mtok, false, false),
            cache_read,
            cache_write,
        ]
    }

    /// Cost estimate for a figure a person will read, carrying which way it
    /// can be wrong.
    ///
    /// Differs from [`estimated_usd`](Self::estimated_usd) in refusing to
    /// invent numbers. A token bucket the provider charges for but whose rate
    /// this catalog does not declare is **never billed at zero**, and a figure
    /// that might be wrong never presents itself as exact.
    ///
    /// `tier_prompt_tokens` selects the prompt-size pricing tier and is the
    /// parameter callers most often get wrong:
    ///
    /// - `Some(n)` — the prompt size of **one request**. Tiers resolve exactly.
    /// - `None` — the caller cannot say (a lifetime accumulator has summed
    ///   many requests and lost their boundaries). Base rates are used and the
    ///   result is flagged in whichever direction the model's own tiers run.
    ///
    /// Passing a *summed* token count as `Some` is the bug this signature
    /// exists to prevent: thirty 10K-token requests sum to 300K, which crosses
    /// a 272K threshold that no individual request came near, and every token
    /// ever sent gets priced at the high-context rate — roughly double, stated
    /// with total confidence.
    ///
    /// Two rejected alternatives, for the next person who wants tiers on an
    /// aggregate. **Pricing lifetime totals at the tier their sum lands in** is
    /// the bug above. **Pricing everything at the highest declared tier** does
    /// yield a true ceiling, but a useless one — it doubles the figure for a
    /// user whose prompts never approached the threshold, which is the same
    /// confident wrongness in the other direction. Resolving tiers properly
    /// needs per-request prompt sizes, which means [`crate::ModelProfile`]
    /// would have to accumulate per-tier token buckets at record time; that is
    /// a real feature with a persisted-schema change, not something to fake
    /// here from data that has already been summed away.
    ///
    /// Returns `None` when no defensible number exists — either the model
    /// declares no rate card at all, or a bucket carrying tokens has no rate
    /// and no usable substitute. Output deliberately has no input-rate
    /// fallback: it runs 1.5x–8x input across this catalog, far enough out of
    /// range that no marker could rescue the number. Which buckets substitute,
    /// and which way each substitution can be wrong, is decided in
    /// [`bucket_rates`](Self::bucket_rates) from observed provider pricing —
    /// notably cache *reads* and cache *writes* do not share a direction.
    /// `None` means unpriced, and a caller must render it as such, not as free.
    pub fn estimated_usd_bounded(
        &self,
        tier_prompt_tokens: Option<usize>,
        uncached_input_tokens: usize,
        output_tokens: usize,
        cache_read_tokens: usize,
        cache_write_tokens: usize,
    ) -> Option<ApproxCost> {
        // `prices_for(0)` is the base sheet: no tier threshold is <= 0 in a
        // catalog whose thresholds are positive, so nothing overrides.
        let prices = self.prices_for(tier_prompt_tokens.unwrap_or(0));
        if prices.input_per_mtok.is_none() && prices.output_per_mtok.is_none() {
            // No rate card. Not free — unknown.
            return None;
        }

        let tokens = [
            uncached_input_tokens,
            output_tokens,
            cache_read_tokens,
            cache_write_tokens,
        ];
        let rates = Self::bucket_rates(&prices);
        let mut usd = 0.0;
        let mut may_overstate = false;
        let mut may_understate = false;
        for (count, (rate, substitute_high, substitute_low)) in tokens.into_iter().zip(rates) {
            if count == 0 {
                continue;
            }
            // Charged, rate unknown, no usable substitute — admit we can't.
            let rate = rate?;
            // Direction comes from the bucket, not from one blanket rule: a
            // substituted cache-READ rate can only be high, a substituted
            // cache-WRITE rate can land either side.
            may_overstate |= substitute_high;
            may_understate |= substitute_low;
            usd += count as f64 * rate;
        }

        // Unresolvable tiers: say which way the base sheet can be wrong rather
        // than assuming tiers always cost more. Compare the rate each bucket
        // would actually pay at every declared threshold against the base.
        if tier_prompt_tokens.is_none() {
            for tier in &self.pricing_tiers {
                let at_tier = Self::bucket_rates(&self.prices_for(tier.min_prompt_tokens));
                for (count, ((base_rate, _, _), (tier_rate, _, _))) in
                    tokens.into_iter().zip(rates.iter().zip(at_tier))
                {
                    if count == 0 {
                        continue;
                    }
                    if let (Some(base), Some(tiered)) = (base_rate, tier_rate) {
                        may_understate |= tiered > *base;
                        may_overstate |= tiered < *base;
                    }
                }
            }
        }

        Some(ApproxCost {
            usd: usd / 1_000_000.0,
            may_overstate,
            may_understate,
        })
    }
}

/// A cost figure plus which way it can be wrong.
///
/// Presenting an estimate as an exact price is the same failure as billing an
/// unrated bucket at zero, one step later — so the direction travels with the
/// number instead of being re-derived (or forgotten) at each display site.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ApproxCost {
    /// USD.
    pub usd: f64,
    /// The true cost may be **lower** — a bucket was priced at a substitute
    /// rate that can only be too high (a cache read at the uncached-input
    /// rate), or a pricing tier is cheaper than the base sheet used.
    pub may_overstate: bool,
    /// The true cost may be **higher** — a pricing tier dearer than the base
    /// sheet could not be resolved from the tokens the caller had, or a cache
    /// *write* was priced at the uncached-input rate and the provider charges
    /// a surcharge for it (Anthropic 1.25x, OpenRouter's 1h TTL 2x).
    pub may_understate: bool,
}

impl ApproxCost {
    /// Every rate applied exactly; the figure is the price.
    pub fn is_exact(&self) -> bool {
        !self.may_overstate && !self.may_understate
    }

    /// Prefix for the figure: `≤` a ceiling, `≥` a floor, `~` neither bound
    /// holds, empty when exact. Rendering the number without this is the
    /// defect the type exists to prevent.
    pub fn marker(&self) -> &'static str {
        match (self.may_overstate, self.may_understate) {
            (false, false) => "",
            (true, false) => "",
            (false, true) => "",
            (true, true) => "~",
        }
    }
}

/// A score on a public benchmark from a published source (model card,
/// paper, leaderboard). The schema is deliberately permissive — no enum
/// of benchmark names — so the catalog can carry whichever benchmarks
/// the upstream provider chose to publish, and new ones can be added
/// without a code change. Scores are stored on a 0.0–1.0 scale (e.g.
/// 73.5% accuracy → 0.735) so they compare cleanly across benchmarks
/// and so `routing_ext::apply_benchmark_priors` can consume them
/// directly when wired in later.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkScore {
    /// Benchmark name as published (e.g., "MMLU-Pro", "GPQA-Diamond",
    /// "SWE-bench-Verified", "HumanEval", "MATH").
    pub name: String,
    /// Score on a 0.0–1.0 scale.
    pub score: f64,
    /// Evaluation harness or setup label (e.g., "5-shot", "0-shot CoT",
    /// "agentic", "pass@1"). Optional but strongly recommended — the
    /// same benchmark name can mean different things under different
    /// harnesses.
    #[serde(default)]
    pub harness: Option<String>,
    /// Where the score came from (model card URL, paper, leaderboard
    /// snapshot). Empty when the source is the upstream provider's
    /// announcement and a stable URL is not yet known.
    #[serde(default)]
    pub source_url: Option<String>,
    /// ISO 8601 date of the score snapshot (e.g., "2025-08-12"). Lets
    /// downstream code judge how stale a number is.
    #[serde(default)]
    pub measured_at: Option<String>,
}

/// The full declarative schema for a model.
///
/// Analogous to `ToolSchema` — describes what a model is, what it can do,
/// and how to access it. The router uses this for constraint-based filtering
/// and cold-start scoring before observed performance data is available.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelSchema {
    /// Unique identifier: "provider/model-name:variant" (e.g., "qwen/qwen3-4b:q4_k_m").
    pub id: String,
    /// Human-readable display name.
    pub name: String,
    /// Provider (qwen, openai, anthropic, google, meta, ollama, custom).
    pub provider: String,
    /// Model family for grouping (qwen3, gpt-4, claude-4, llama-3).
    pub family: String,
    /// Semantic version or checkpoint label.
    #[serde(default)]
    pub version: String,
    /// What this model can do — ordered by primary capability first.
    pub capabilities: Vec<ModelCapability>,
    /// Context window in tokens.
    pub context_length: usize,
    /// Per-model maximum OUTPUT tokens the provider will return in one
    /// response. None = unknown; callers fall back to
    /// effective_max_output() which derives a fraction of context_length.
    #[serde(default)]
    pub max_output_tokens: Option<usize>,
    /// Parameter count as human-readable string (e.g., "4B", "30B (3B active)").
    #[serde(default)]
    pub param_count: String,
    /// How the weights are quantized, if at all. `None` for remote models and
    /// for local ones whose source declared nothing. See [`Quantization`] —
    /// this accepts the legacy bare-string form on the wire.
    #[serde(default)]
    pub quantization: Option<Quantization>,
    /// Declared performance envelope (initial estimate, overridden by observed data).
    #[serde(default)]
    pub performance: PerformanceEnvelope,
    /// Cost structure.
    #[serde(default)]
    pub cost: CostModel,
    /// How to access this model.
    pub source: ModelSource,
    /// Free-form tags for filtering (e.g., "fast", "multilingual", "moe").
    #[serde(default)]
    pub tags: Vec<String>,
    /// Supported generation parameters. The inference layer strips any parameter
    /// not in this set before sending to the API. Empty = all supported.
    #[serde(default)]
    pub supported_params: Vec<GenerateParam>,
    /// Public benchmark scores as published by the model provider or
    /// reproduced on a public leaderboard (MMLU-Pro, GPQA-Diamond,
    /// SWE-bench, HumanEval, etc.). The built-in catalog ships this
    /// empty — population is a curation step, not a code change. See
    /// `BenchmarkScore` for the field shape and the 0.0–1.0 scoring
    /// convention.
    #[serde(default)]
    pub public_benchmarks: Vec<BenchmarkScore>,
    /// How much the project vouches for this model. The built-in catalog is
    /// `Curated`. Deserialization retains the legacy `Curated` default, so
    /// every user-controlled ingestion boundary must call
    /// [`Self::mark_user_registered`] before persistence or registration.
    /// Gates auto-apply (task #8) and this is surfaced in recommendation
    /// rationale.
    #[serde(default)]
    pub trust_tier: TrustTier,
    /// Superseded models stay listed if installed but are excluded from
    /// fresh recommendations. `#[serde(default)]` → not deprecated.
    #[serde(default)]
    pub deprecated: bool,
    /// Whether this model is currently available (downloaded / reachable).
    /// Not serialized — computed at runtime.
    #[serde(skip)]
    pub available: bool,
    /// Whether this model can be used **right now, without a download**.
    ///
    /// Deliberately narrower than [`Self::available`], which for a local MLX
    /// model is true as soon as an `hf_repo` is declared — `ensure_local()`
    /// lazy-downloads on first use, so a declared repo is "functionally
    /// available" (see #164). That is the right default for open-ended work and
    /// wrong for work on a deadline: a step with a bounded budget that picks a
    /// model it must first fetch spends the whole budget downloading and fails.
    /// That is exactly how `car code`'s 120s contract derivation became
    /// unusable on a machine with no local weights (Parslee-ai/car#638).
    ///
    /// Callers express the requirement with [`crate::IntentHint::require_ready`];
    /// this is the per-candidate fact that hint filters on. Recomputed on every
    /// registration, so a cached schema can't carry a stale value.
    #[serde(skip)]
    pub weights_ready: bool,
}

impl ModelSchema {
    /// Mark a schema as user-controlled rather than project-vetted.
    ///
    /// This is intentionally separate from serde's legacy default: old built-in
    /// and test fixtures omit `trust_tier` and must continue to deserialize,
    /// while `models.json`, CLI imports, and daemon `models.register` must never
    /// inherit `Curated` merely because a caller omitted the field or supplied
    /// a forged value.
    pub fn mark_user_registered(&mut self) {
        self.trust_tier = TrustTier::Community;
    }

    /// Check if this model has a given capability.
    pub fn has_capability(&self, cap: ModelCapability) -> bool {
        self.capabilities.contains(&cap)
    }

    /// Live availability for credential-backed providers. The catalog field is
    /// a startup snapshot; Settings/OAuth changes must affect the next list and
    /// route without a daemon restart.
    pub fn available_now(&self) -> bool {
        match &self.source {
            ModelSource::RemoteApi {
                protocol: ApiProtocol::OpenRouter,
                ..
            } => self.available && crate::openrouter::credential_source().is_some(),
            _ => self.available,
        }
    }

    /// Prompt-cache economics for this model, derived from its remote
    /// protocol. Local / non-remote models have no remote prompt cache, so
    /// their cache rates are inert ([`CacheRates::NONE`]).
    pub fn cache_rates(&self) -> crate::outcome::CacheRates {
        match &self.source {
            ModelSource::RemoteApi {
                protocol: ApiProtocol::OpenRouter,
                ..
            } => {
                let input = self.cost.input_per_mtok.unwrap_or(0.0);
                if input > 0.0 {
                    crate::outcome::CacheRates {
                        read_mult: self.cost.cache_read_input_per_mtok.unwrap_or(0.0) / input,
                        write_mult: self.cost.cache_write_input_per_mtok.unwrap_or(0.0) / input,
                    }
                } else {
                    crate::outcome::CacheRates::NONE
                }
            }
            ModelSource::RemoteApi { protocol, .. } => protocol.cache_rates(),
            _ => crate::outcome::CacheRates::NONE,
        }
    }

    /// The organization whose model this is, when that can be honestly known.
    ///
    /// Answers one question — could two models be expected to fail the same
    /// way? — so it is deliberately conservative. `None` means UNKNOWABLE, not
    /// "none", and callers must treat it as "cannot tell" rather than folding
    /// it into a count of distinct vendors.
    ///
    /// NOT [`Self::provider`], which means four different things depending on
    /// which path built the schema:
    ///
    /// * curated remote rows — the real vendor (`openai`, `anthropic`);
    /// * OpenRouter and the Parslee gateway — the AGGREGATOR, so three vendors
    ///   behind one gateway all report `openrouter`/`parslee` and one vendor
    ///   reached two ways reports as two;
    /// * a HuggingFace-derived row — the repo ORG that uploaded it, so
    ///   `unsloth/Qwen3` and `mlx-community/Qwen3` are the same weights under
    ///   two "vendors";
    /// * a discovered local-server row — a guess from the model name.
    ///
    /// Only the first is a vendor, so only the first is reported. NOT `family`
    /// either — that is the model line, so `claude-4.6` and `claude-4.8` read as
    /// different and are both Anthropic.
    pub fn vendor(&self) -> Option<&str> {
        // The aggregator case: the curated table knows which upstream a gateway
        // alias resolves to, which is the only place that survives an id
        // carrying no trace of its vendor.
        if self.provider.eq_ignore_ascii_case("openrouter")
            || self.provider.eq_ignore_ascii_case("parslee")
        {
            return crate::openrouter::curated_vendor(&self.id);
        }
        // A local model is served by the operator's own machine. Whoever
        // uploaded the weights is not an organization that could fail
        // independently of the process running beside it.
        if self.is_local() {
            return None;
        }
        // Only a project-vetted row's `provider` was assigned deliberately. On a
        // community row it is the uploader or a guess, and claiming it here is
        // how two repacks of one checkpoint would pass as two vendors.
        if self.trust_tier != TrustTier::Curated {
            return None;
        }
        (!self.provider.is_empty()).then_some(self.provider.as_str())
    }

    /// Check if this model is local (runs on-device).
    pub fn is_local(&self) -> bool {
        matches!(
            self.source,
            ModelSource::Local { .. }
                | ModelSource::Mlx { .. }
                | ModelSource::WhisperCpp { .. }
                | ModelSource::WindowsSpeech { .. }
                | ModelSource::ManagedVllmMlx { .. }
                | ModelSource::AppleFoundationModels { .. }
        )
    }

    /// Whether this model has weights CAR fetches to disk before it can be
    /// used — i.e. whether "is it installed?" is a question with an answer.
    ///
    /// Three predicates in this area are easy to conflate, and conflating them
    /// is what Parslee-ai/car#894 was about:
    ///
    /// - [`is_local`](Self::is_local) — *owned on this machine*. True for
    ///   `WindowsSpeech` (the OS owns the voices), `AppleFoundationModels`
    ///   (the OS owns the weights), and CAR-managed sources. An external
    ///   `VllmMlx` endpoint is remote even when its URL happens to be loopback.
    /// - [`weights_ready`](Self::weights_ready) — *the weights are on disk
    ///   now*. Only meaningful when this predicate is true; for everything
    ///   else the registry sets it to `true` as a "nothing blocks an attempt"
    ///   sentinel, which reads as "installed" if taken literally.
    /// - `downloads_weights` (this one) — *there is something to install at
    ///   all*. Use it to decide whether an install/download status should be
    ///   reported, then use `weights_ready` for the status itself.
    ///
    /// Rendering `weights_ready` without this gate is what made
    /// `windows/speech-synthesis:os` claim `INSTALLED yes` while `car doctor`
    /// said `Models: none installed`, and made `apple/foundation:default` and
    /// the `vllm-mlx/*` rows claim `INSTALLED no` for models that install
    /// nothing.
    ///
    /// Written as an exhaustive `match` rather than `matches!` so that adding
    /// a `ModelSource` variant is a compile error here instead of a silently
    /// wrong answer in the CLI.
    pub fn downloads_weights(&self) -> bool {
        match self.source {
            // CAR fetches these to disk itself: a GGUF file, an MLX
            // safetensors repo, a whisper.cpp ggml `.bin`.
            ModelSource::Local { .. }
            | ModelSource::Mlx { .. }
            | ModelSource::WhisperCpp { .. }
            | ModelSource::ManagedVllmMlx { .. } => true,
            // The OS owns the voices / the weights — nothing to download.
            ModelSource::WindowsSpeech {} | ModelSource::AppleFoundationModels { .. } => false,
            // Someone else holds the weights: a local server (vLLM-MLX,
            // Ollama), a remote API, or a host-registered runner.
            ModelSource::VllmMlx { .. }
            | ModelSource::Ollama { .. }
            | ModelSource::RemoteApi { .. }
            | ModelSource::Proprietary { .. }
            | ModelSource::Delegated { .. } => false,
        }
    }

    /// Whether a CAR-downloadable artifact is physically present now.
    /// General runtime availability and OS/server-owned weights are not an
    /// installation claim.
    pub fn has_installed_weights(&self) -> bool {
        self.downloads_weights() && self.weights_ready
    }

    /// Whether CAR decodes this model **in its own process**, token by token,
    /// through the shared decode loop.
    ///
    /// Narrower than [`is_local`](Self::is_local) on purpose. `is_local` also
    /// covers CAR-managed vLLM-MLX and the speech backends. Those do not spend
    /// an output-token budget as this process's wall clock, so they must keep
    /// the remote treatment. Getting that distinction wrong takes the
    /// anti-truncation budget away from vLLM-MLX, which is the documented way
    /// to get structured tool calls out of a local model. (car#851)
    pub fn decodes_in_process(&self) -> bool {
        matches!(
            self.source,
            ModelSource::Local { .. } | ModelSource::Mlx { .. }
        )
    }

    /// Check if this model delegates inference to a host-registered
    /// runner (closes Parslee-ai/car-releases#24).
    pub fn is_delegated(&self) -> bool {
        matches!(self.source, ModelSource::Delegated { .. })
    }

    /// Check if this model uses the MLX backend.
    pub fn is_mlx(&self) -> bool {
        matches!(self.source, ModelSource::Mlx { .. })
    }

    /// Check if this model routes to Apple's on-device FoundationModels
    /// framework. True only for `ModelSource::AppleFoundationModels`;
    /// callers must still verify runtime availability before dispatch
    /// (the schema can describe the model on any host, but execution
    /// requires macOS 26+ on Apple Silicon).
    pub fn is_foundation_models(&self) -> bool {
        matches!(self.source, ModelSource::AppleFoundationModels { .. })
    }

    /// Check if this model uses vLLM-MLX backend.
    pub fn is_vllm_mlx(&self) -> bool {
        matches!(
            self.source,
            ModelSource::VllmMlx { .. } | ModelSource::ManagedVllmMlx { .. }
        )
    }

    /// Whether CAR, rather than an independently managed endpoint, owns the
    /// vLLM-MLX child process and its physical weight allocation. The existing
    /// HTTP `VllmMlx` contract remains external/server-owned. A supervised
    /// source must opt in explicitly and provide an already-installed local
    /// model path in `model_name`; it is then replaced with a loopback HTTP
    /// endpoint only after admission and a successful readiness ACK.
    pub fn is_car_managed_vllm_mlx(&self) -> bool {
        matches!(self.source, ModelSource::ManagedVllmMlx { .. })
    }

    /// Whether a CAR/OS-owned model can only run on Apple Silicon (Metal).
    /// External vLLM-MLX endpoints own their hardware and are not constrained
    /// by the client machine's accelerator.
    pub fn requires_apple_silicon(&self) -> bool {
        self.is_mlx() || self.is_car_managed_vllm_mlx() || self.is_foundation_models()
    }

    /// Check if this model is remote (requires API call).
    pub fn is_remote(&self) -> bool {
        matches!(
            self.source,
            ModelSource::RemoteApi { .. }
                | ModelSource::Proprietary { .. }
                | ModelSource::VllmMlx { .. }
        )
    }

    /// Collect all API key env var names for this model (primary + extras).
    /// Returns empty vec for non-remote models.
    pub fn all_api_key_envs(&self) -> Vec<String> {
        match &self.source {
            ModelSource::RemoteApi {
                api_key_env,
                api_key_envs,
                ..
            } => {
                let mut all = vec![api_key_env.clone()];
                all.extend(api_key_envs.iter().cloned());
                all
            }
            ModelSource::Proprietary {
                auth: ProprietaryAuth::ApiKeyEnv { env_var },
                ..
            }
            | ModelSource::Proprietary {
                auth: ProprietaryAuth::BearerTokenEnv { env_var },
                ..
            } => vec![env_var.clone()],
            _ => vec![],
        }
    }

    /// Get the size in MB (from cost model or 0 if unknown).
    pub fn size_mb(&self) -> u64 {
        self.cost.size_mb.unwrap_or(0)
    }

    /// Get the RAM requirement in MB (from cost model, falls back to size_mb).
    pub fn ram_mb(&self) -> u64 {
        self.cost.ram_mb.unwrap_or_else(|| self.size_mb())
    }

    /// Estimated cost per 1K output tokens in USD. Returns 0.0 for local models.
    pub fn cost_per_1k_output(&self) -> f64 {
        self.cost.output_per_mtok.map(|c| c / 1000.0).unwrap_or(0.0)
    }

    /// The per-turn output-token ceiling to use when the caller didn't
    /// specify one. Prefers the registry-declared `max_output_tokens`;
    /// otherwise derives a quarter of the context window, clamped to a
    /// sane [4096, 32768] band so a 1M-context model doesn't request a
    /// 250K-token response the API rejects and a tiny 8K model doesn't
    /// get an absurdly small ceiling. (Registry value first, computed
    /// fallback second — mirrors a provider lookup with a derived default.)
    pub fn effective_max_output(&self) -> usize {
        self.max_output_tokens
            .unwrap_or_else(|| (self.context_length / 4).clamp(4096, 32_768))
    }
}

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

    fn sample_local() -> ModelSchema {
        ModelSchema {
            id: "qwen/qwen3-4b:q4_k_m".into(),
            name: "Qwen3-4B".into(),
            provider: "qwen".into(),
            family: "qwen3".into(),
            version: "1.0".into(),
            capabilities: vec![ModelCapability::Generate, ModelCapability::Code],
            context_length: 32768,
            max_output_tokens: None,
            param_count: "4B".into(),
            quantization: Some(Quantization::parse("Q4_K_M")),
            performance: PerformanceEnvelope {
                tokens_per_second: Some(45.0),
                ..Default::default()
            },
            cost: CostModel {
                size_mb: Some(2500),
                ram_mb: Some(2500),
                ..Default::default()
            },
            source: ModelSource::Local {
                hf_repo: "Qwen/Qwen3-4B-GGUF".into(),
                hf_filename: "Qwen3-4B-Q4_K_M.gguf".into(),
                tokenizer_repo: "Qwen/Qwen3-4B".into(),
            },
            tags: vec!["code".into(), "fast".into()],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: TrustTier::Curated,
            deprecated: false,
            available: false,
            weights_ready: false,
        }
    }

    fn sample_remote() -> ModelSchema {
        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,
                ModelCapability::Vision,
            ],
            context_length: 200000,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: PerformanceEnvelope {
                latency_p50_ms: Some(2000),
                latency_p99_ms: Some(8000),
                tokens_per_second: Some(80.0),
            },
            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!["reasoning".into(), "tool_use".into()],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: TrustTier::Curated,
            deprecated: false,
            available: false,
            weights_ready: false,
        }
    }

    #[test]
    fn capabilities() {
        let m = sample_local();
        assert!(m.has_capability(ModelCapability::Code));
        assert!(!m.has_capability(ModelCapability::Vision));
    }

    #[test]
    fn local_vs_remote() {
        assert!(sample_local().is_local());
        assert!(!sample_local().is_remote());
        assert!(sample_remote().is_remote());
        assert!(!sample_remote().is_local());
    }

    #[test]
    fn vllm_ownership_drives_local_remote_and_apple_predicates() {
        let external = ModelSchema {
            source: ModelSource::VllmMlx {
                endpoint: "https://gpu-owner.example/v1".into(),
                model_name: "owner/runtime-model".into(),
            },
            ..sample_local()
        };
        assert!(!external.is_local());
        assert!(external.is_remote());
        assert!(!external.requires_apple_silicon());

        let managed = ModelSchema {
            source: ModelSource::ManagedVllmMlx {
                hf_repo: "mlx-community/Qwen3-4B-4bit".into(),
                hf_weight_file: None,
            },
            ..sample_local()
        };
        assert!(managed.is_local());
        assert!(!managed.is_remote());
        assert!(managed.requires_apple_silicon());
    }

    #[test]
    fn cost() {
        let local = sample_local();
        assert_eq!(local.cost_per_1k_output(), 0.0);

        let remote = sample_remote();
        assert!(remote.cost_per_1k_output() > 0.0);
    }

    #[test]
    fn serde_roundtrip() {
        let local = sample_local();
        let json = serde_json::to_string(&local).unwrap();
        let parsed: ModelSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.id, local.id);
        assert_eq!(parsed.capabilities, local.capabilities);

        let remote = sample_remote();
        let json = serde_json::to_string(&remote).unwrap();
        let parsed: ModelSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.id, remote.id);
        // available is skip-serialized, defaults to false
        assert!(!parsed.available);
    }

    #[test]
    fn managed_vllm_source_is_versioned_without_reinterpreting_legacy_vllm_json() {
        let legacy: ModelSource = serde_json::from_str(
            r#"{"type":"vllm_mlx","endpoint":"http://localhost:8000","model_name":"legacy"}"#,
        )
        .unwrap();
        assert!(matches!(
            legacy,
            ModelSource::VllmMlx {
                endpoint,
                model_name
            } if endpoint == "http://localhost:8000" && model_name == "legacy"
        ));

        let managed = ModelSource::ManagedVllmMlx {
            hf_repo: "mlx-community/Qwen3-4B-4bit".into(),
            hf_weight_file: Some("model.safetensors".into()),
        };
        let encoded = serde_json::to_string(&managed).unwrap();
        assert!(encoded.contains(r#""type":"managed_vllm_mlx""#));
        assert!(matches!(
            serde_json::from_str::<ModelSource>(&encoded).unwrap(),
            ModelSource::ManagedVllmMlx { .. }
        ));
    }

    #[test]
    fn vendor_refuses_to_claim_a_repackager_or_a_guess() {
        // A HuggingFace-derived row's `provider` is the repo ORG that uploaded
        // it, so `unsloth/Qwen3` and `mlx-community/Qwen3` — one checkpoint,
        // two repacks — would otherwise read as two independent vendors. That
        // is a false independence claim produced silently, which is the exact
        // failure a vendor check exists to prevent.
        let mut m = sample_remote();
        m.provider = "mlx-community".into();
        m.trust_tier = TrustTier::Community;
        assert_eq!(m.vendor(), None);

        // A project-vetted remote row IS authoritative.
        m.provider = "openai".into();
        m.trust_tier = TrustTier::Curated;
        assert_eq!(m.vendor(), Some("openai"));

        // A local model is served by the operator's own machine; whoever
        // uploaded the weights is not an independently-failing organization.
        assert_eq!(sample_local().vendor(), None);
    }

    #[test]
    fn trust_tier_and_deprecated_default_when_absent() {
        // Pre-existing ~/.car/models.json configs omit the new fields.
        // They must deserialize to Curated / not-deprecated, not error.
        let json = serde_json::to_string(&sample_local()).unwrap();
        let stripped = json
            .replace(",\"trust_tier\":\"curated\"", "")
            .replace(",\"deprecated\":false", "");
        let parsed: ModelSchema = serde_json::from_str(&stripped).unwrap();
        assert_eq!(parsed.trust_tier, TrustTier::Curated);
        assert!(!parsed.deprecated);
    }

    #[test]
    fn trust_tier_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&TrustTier::Community).unwrap(),
            "\"community\""
        );
        assert_eq!(TrustTier::default(), TrustTier::Curated);
    }

    #[test]
    fn requires_apple_silicon_only_for_metal_backends() {
        // GGUF/Candle local and remote models run anywhere CAR builds for.
        assert!(!sample_local().requires_apple_silicon());
        assert!(!sample_remote().requires_apple_silicon());

        let mlx = ModelSchema {
            source: ModelSource::Mlx {
                hf_repo: "mlx-community/Qwen3-4B-4bit".into(),
                hf_weight_file: None,
            },
            ..sample_local()
        };
        assert!(mlx.requires_apple_silicon());

        // Only CAR-managed vLLM-MLX and Apple FoundationModels are Metal-bound.
        // A raw endpoint is external and its owner's hardware is opaque to CAR.
        let managed_vllm = ModelSchema {
            source: ModelSource::ManagedVllmMlx {
                hf_repo: "mlx-community/Qwen3-4B-4bit".into(),
                hf_weight_file: None,
            },
            ..sample_local()
        };
        assert!(managed_vllm.requires_apple_silicon());

        let external_vllm = ModelSchema {
            source: ModelSource::VllmMlx {
                endpoint: "https://gpu-owner.example/v1".into(),
                model_name: "mlx-community/Qwen3-4B-4bit".into(),
            },
            ..sample_local()
        };
        assert!(!external_vllm.requires_apple_silicon());

        let foundation = ModelSchema {
            source: ModelSource::AppleFoundationModels { use_case: None },
            ..sample_local()
        };
        assert!(foundation.requires_apple_silicon());
    }

    fn priced(
        input: Option<f64>,
        output: Option<f64>,
        cache_read: Option<f64>,
        cache_write: Option<f64>,
    ) -> CostModel {
        CostModel {
            input_per_mtok: input,
            output_per_mtok: output,
            cache_read_input_per_mtok: cache_read,
            cache_write_input_per_mtok: cache_write,
            ..Default::default()
        }
    }

    #[test]
    fn an_undeclared_cache_rate_is_bounded_by_the_input_rate_not_billed_at_zero() {
        // The real shape this exists for: qwen3.5-plus declares input and
        // output but no cache-read rate. 1M cache-read tokens must not be free.
        let cost = priced(Some(0.26), Some(1.56), None, None);
        let bounded = cost
            .estimated_usd_bounded(Some(1_000_000), 0, 0, 1_000_000, 0)
            .expect("a model with input+output rates is priceable");
        assert!(bounded.may_overstate, "substituted rate can only be high");
        assert!(!bounded.may_understate);
        assert_eq!(bounded.marker(), "");
        assert!(
            (bounded.usd - 0.26).abs() < 1e-9,
            "cache reads fall back to the $0.26/MTok input rate, got {}",
            bounded.usd
        );

        // The routing-score path still zero-fills, deliberately and untouched.
        assert_eq!(cost.estimated_usd(1_000_000, 0, 1_000_000, 0), 0.0);
    }

    #[test]
    fn an_undeclared_cache_write_rate_claims_no_bound_it_cannot_keep() {
        // The shipped `claude-opus-4.8` shape with its cache-write rate
        // omitted. Anthropic's cache write is a 1.25x SURCHARGE (6.25 against
        // 5.0 input), and OpenRouter's 1h-TTL rate is 2x — so pricing the
        // bucket at the input rate is a FLOOR, and the `≤` a blanket
        // "cache is always cheaper" rule would have produced is a false
        // ceiling over a true cost of $6.25, or $10.00 at the 1h rate.
        let cost = priced(Some(5.0), Some(25.0), Some(0.5), None);
        let bounded = cost
            .estimated_usd_bounded(Some(1_000_000), 0, 0, 0, 1_000_000)
            .expect("input and output rates are published");
        assert!((bounded.usd - 5.0).abs() < 1e-9, "got {}", bounded.usd);
        assert!(
            bounded.may_understate,
            "a cache-write surcharge can exceed the input rate"
        );
        assert_ne!(bounded.marker(), "", "must not claim a ceiling it fails");
        assert_eq!(bounded.marker(), "~", "sign is unknown, so neither bound");
        // Both real cache-write rates this shape could carry sit ABOVE the
        // substituted figure — which is exactly why `≤` would have been a
        // false ceiling. Assert the tighter of the two; it implies the looser,
        // and spelling out both comparisons is a `redundant_comparisons` lint.
        let at_anthropics_1_25x: f64 = 1_000_000.0 * 6.25 / 1e6;
        let at_openrouters_1h_2x: f64 = 1_000_000.0 * 10.0 / 1e6;
        assert!(bounded.usd < at_anthropics_1_25x.min(at_openrouters_1h_2x));

        // Declaring the rate makes it exact — the flag tracks substitution,
        // not the mere presence of cache-write tokens.
        let declared = priced(Some(5.0), Some(25.0), Some(0.5), Some(6.25))
            .estimated_usd_bounded(Some(1_000_000), 0, 0, 0, 1_000_000)
            .unwrap();
        assert!(declared.is_exact());
        assert!((declared.usd - 6.25).abs() < 1e-9);

        // The same omission on the cache READ side DOES keep its ceiling —
        // the two directions are not shared. Note the rate must be missing for
        // a substitution to happen at all.
        let read = priced(Some(5.0), Some(25.0), None, Some(6.25))
            .estimated_usd_bounded(Some(1_000_000), 0, 0, 1_000_000, 0)
            .unwrap();
        assert_eq!(read.marker(), "");
        assert!((read.usd - 5.0).abs() < 1e-9);
        // A real cache-read rate is a discount, so the ceiling holds.
        assert!(read.usd > 1_000_000.0 * 0.5 / 1e6);
    }

    #[test]
    fn a_declared_cache_rate_is_exact_and_never_flagged() {
        let cost = priced(Some(5.0), Some(25.0), Some(0.5), Some(6.25));
        let bounded = cost
            .estimated_usd_bounded(Some(1_600_000), 1_000_000, 200_000, 500_000, 100_000)
            .expect("fully rated");
        assert!(bounded.is_exact(), "nothing was substituted or unresolved");
        assert_eq!(bounded.marker(), "");
        // 1M uncached x 5 + 200k x 25 + 500k x 0.5 + 100k x 6.25, per MTok.
        assert!((bounded.usd - 10.875).abs() < 1e-9, "got {}", bounded.usd);
        // Identical to the router's figure when every rate is published.
        assert!(
            (bounded.usd - cost.estimated_usd(1_600_000, 200_000, 500_000, 100_000)).abs() < 1e-9
        );
    }

    #[test]
    fn an_unbounded_bucket_refuses_rather_than_understating() {
        // Output has no safe substitute — it is normally the dearer side, so
        // pricing it at the input rate would UNDER-state. Refuse instead.
        let cost = priced(Some(1.0), None, None, None);
        assert_eq!(
            cost.estimated_usd_bounded(Some(1_000), 1_000, 1_000, 0, 0),
            None
        );
        // With no output tokens the same model is priceable and exact.
        let bounded = cost
            .estimated_usd_bounded(Some(1_000), 1_000, 0, 0, 0)
            .unwrap();
        assert!(bounded.is_exact());
    }

    #[test]
    fn no_rate_card_is_unpriced_rather_than_free() {
        let cost = CostModel::default();
        assert_eq!(
            cost.estimated_usd_bounded(Some(1_000), 1_000, 1_000, 0, 0),
            None
        );
        // And a zero-usage priced model is genuinely free, not unpriced.
        let free = priced(Some(0.0), Some(0.0), None, None)
            .estimated_usd_bounded(Some(0), 0, 0, 0, 0)
            .expect("a declared zero rate card is priced");
        assert_eq!(free.usd, 0.0);
        assert!(free.is_exact());
    }

    fn tiered() -> CostModel {
        CostModel {
            input_per_mtok: Some(2.5),
            output_per_mtok: Some(15.0),
            cache_read_input_per_mtok: Some(0.25),
            pricing_tiers: vec![TokenPricingTier {
                min_prompt_tokens: 272_000,
                prices: TokenPrices {
                    input_per_mtok: Some(5.0),
                    output_per_mtok: Some(22.5),
                    cache_read_input_per_mtok: Some(0.5),
                    cache_write_input_per_mtok: None,
                },
            }],
            ..Default::default()
        }
    }

    #[test]
    fn a_known_prompt_size_resolves_the_tier_exactly() {
        let cost = tiered();
        let below = cost
            .estimated_usd_bounded(Some(271_999), 271_999, 0, 0, 0)
            .unwrap();
        assert!(below.is_exact());
        assert!((below.usd - 271_999.0 * 2.5 / 1e6).abs() < 1e-9);

        let above = cost
            .estimated_usd_bounded(Some(272_000), 272_000, 0, 0, 0)
            .unwrap();
        assert!(above.is_exact());
        assert!((above.usd - 272_000.0 * 5.0 / 1e6).abs() < 1e-9);
    }

    #[test]
    fn a_lifetime_aggregate_uses_base_rates_and_admits_it_may_be_low() {
        // Thirty 10K-token requests. Their SUM crosses the 272K threshold that
        // no single request came near — the double-charging bug. `None` says
        // "boundaries lost", so base rates apply and the figure is marked.
        let cost = tiered();
        let aggregate = cost.estimated_usd_bounded(None, 300_000, 0, 0, 0).unwrap();
        assert!(
            (aggregate.usd - 300_000.0 * 2.5 / 1e6).abs() < 1e-9,
            "must use the $2.50 base rate, got {}",
            aggregate.usd
        );
        assert!(aggregate.may_understate, "a dearer tier may apply");
        assert!(!aggregate.may_overstate);
        assert_eq!(aggregate.marker(), "");

        // What the bug looked like: summed tokens passed as a real prompt size
        // price at the high-context rate — exactly double, and unmarked.
        let bug = cost
            .estimated_usd_bounded(Some(300_000), 300_000, 0, 0, 0)
            .unwrap();
        assert!((bug.usd - 2.0 * aggregate.usd).abs() < 1e-9);
        assert!(bug.is_exact(), "and it would have claimed to be exact");
    }

    #[test]
    fn a_cheaper_tier_flags_the_aggregate_as_possibly_high_instead() {
        // Direction is derived from the tiers, not assumed. A volume DISCOUNT
        // makes the base-rate figure too high, not too low.
        let cost = CostModel {
            input_per_mtok: Some(2.0),
            output_per_mtok: Some(10.0),
            pricing_tiers: vec![TokenPricingTier {
                min_prompt_tokens: 100_000,
                prices: TokenPrices {
                    input_per_mtok: Some(1.0),
                    ..Default::default()
                },
            }],
            ..Default::default()
        };
        let aggregate = cost.estimated_usd_bounded(None, 500_000, 0, 0, 0).unwrap();
        assert!(aggregate.may_overstate);
        assert!(!aggregate.may_understate);
        assert_eq!(aggregate.marker(), "");
    }

    #[test]
    fn both_directions_at_once_claims_neither_bound() {
        // Unrated cache bucket (can be high) plus an unresolved dearer tier
        // (can be low). Neither bound survives, so the figure is just an
        // estimate and must not wear a `≤` it cannot honour.
        let cost = CostModel {
            input_per_mtok: Some(2.0),
            output_per_mtok: Some(10.0),
            pricing_tiers: vec![TokenPricingTier {
                min_prompt_tokens: 100_000,
                prices: TokenPrices {
                    input_per_mtok: Some(4.0),
                    ..Default::default()
                },
            }],
            ..Default::default()
        };
        let aggregate = cost.estimated_usd_bounded(None, 0, 0, 500_000, 0).unwrap();
        assert!(aggregate.may_overstate && aggregate.may_understate);
        assert_eq!(aggregate.marker(), "~");
    }

    /// Parslee-ai/car#894 (follow-up): "runs here" and "has weights to fetch"
    /// are different questions, and `is_local` answers only the first. Three
    /// `is_local` sources download nothing — the CLI must not offer an
    /// install status for them.
    #[test]
    fn downloads_weights_is_true_only_for_sources_car_fetches() {
        let mut schema = sample_local();

        // CAR downloads these itself.
        schema.source = ModelSource::Local {
            hf_repo: "Qwen/Qwen3-4B-GGUF".into(),
            hf_filename: "Qwen3-4B-Q4_K_M.gguf".into(),
            tokenizer_repo: "Qwen/Qwen3-4B".into(),
        };
        assert!(schema.downloads_weights(), "GGUF weights are downloaded");

        schema.source = ModelSource::Mlx {
            hf_repo: "mlx-community/Qwen3-4B-4bit".into(),
            hf_weight_file: None,
        };
        assert!(schema.downloads_weights(), "MLX weights are downloaded");

        schema.source = ModelSource::WhisperCpp {
            model: "large-v3-turbo-q5_0".into(),
        };
        assert!(
            schema.downloads_weights(),
            "the whisper.cpp ggml bin is downloaded"
        );

        // The OS owns these — there is nothing to install. `WindowsSpeech` is
        // the row that rendered `INSTALLED yes` against `car doctor`'s
        // `Models: none installed`.
        schema.source = ModelSource::WindowsSpeech {};
        assert!(
            !schema.downloads_weights(),
            "WinRT speech synthesis has no weights to download"
        );

        schema.source = ModelSource::AppleFoundationModels { use_case: None };
        assert!(
            !schema.downloads_weights(),
            "Apple FoundationModels weights belong to the OS"
        );

        // Someone else holds the weights.
        schema.source = ModelSource::VllmMlx {
            endpoint: "http://localhost:8000".into(),
            model_name: "mlx-community/Qwen3-4B-4bit".into(),
        };
        assert!(
            !schema.downloads_weights(),
            "the vLLM-MLX server owns its own weights"
        );

        schema.source = ModelSource::ManagedVllmMlx {
            hf_repo: "mlx-community/Qwen3-4B-4bit".into(),
            hf_weight_file: None,
        };
        assert!(
            schema.downloads_weights(),
            "the explicitly managed vLLM-MLX contract is CAR-owned"
        );

        schema.source = ModelSource::Ollama {
            model_tag: "qwen3:4b".into(),
            host: default_ollama_host(),
        };
        assert!(!schema.downloads_weights(), "Ollama owns its own weights");

        schema.source = sample_remote().source;
        assert!(
            !schema.downloads_weights(),
            "a remote API has no weights on this machine"
        );

        schema.source = ModelSource::Delegated { hint: None };
        assert!(
            !schema.downloads_weights(),
            "a host-registered runner owns its own weights"
        );
    }

    /// `is_local` is the predicate the CLI used to reach for. These OS-owned
    /// sources are where the two answers diverge, which is why a
    /// separate predicate exists rather than a reuse of `is_local`.
    #[test]
    fn downloads_weights_differs_from_is_local_on_os_owned_sources() {
        let mut schema = sample_local();
        for source in [
            ModelSource::WindowsSpeech {},
            ModelSource::AppleFoundationModels { use_case: None },
        ] {
            schema.source = source;
            assert!(
                schema.is_local(),
                "this source runs on-device: {:?}",
                schema.source
            );
            assert!(
                !schema.downloads_weights(),
                "…but CAR downloads nothing for it: {:?}",
                schema.source
            );
        }
    }
}

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

    /// Every distinct label the built-in catalog ships, the hyphenated form
    /// `registry.rs` writes into auto-discovered entries, and the formats that
    /// review found misclassified.
    #[test]
    fn classifies_known_labels() {
        let cases: &[(&str, Option<u8>, QuantScheme)] = &[
            ("4bit", Some(4), QuantScheme::AffineGroupInt),
            ("6bit", Some(6), QuantScheme::AffineGroupInt),
            ("3bit", Some(3), QuantScheme::AffineGroupInt),
            ("5bit", Some(5), QuantScheme::AffineGroupInt),
            // registry.rs emits the hyphen; users already have it on disk.
            ("4-bit", Some(4), QuantScheme::AffineGroupInt),
            ("mxfp8", Some(8), QuantScheme::BlockScaledFloat),
            ("mxfp4", Some(4), QuantScheme::BlockScaledFloat),
            ("Q4_K_M", Some(4), QuantScheme::KQuantMixed),
            ("Q5_K_S", Some(5), QuantScheme::KQuantMixed),
            ("IQ4_XS", Some(4), QuantScheme::KQuantMixed),
            ("TQ1_0", Some(1), QuantScheme::KQuantMixed),
            ("Q8_0", Some(8), QuantScheme::RtnBlock),
            ("q5_0", Some(5), QuantScheme::RtnBlock),
            // aarch64 repack quants: the suffix is a prefix match, not equality.
            ("Q4_0_4_4", Some(4), QuantScheme::RtnBlock),
            ("Q4_0_8_8", Some(4), QuantScheme::RtnBlock),
            // A zero-padded width must slice by digits consumed, not by the
            // decimal length of the parsed number.
            ("q08_0", Some(8), QuantScheme::RtnBlock),
            ("bf16", Some(16), QuantScheme::Unquantized),
            ("F16", Some(16), QuantScheme::Unquantized),
            ("f32", Some(32), QuantScheme::Unquantized),
            // Spelled like a quant, but affine group quant has no such width.
            ("16bit", Some(16), QuantScheme::Unquantized),
            ("32bit", Some(32), QuantScheme::Unquantized),
            // An 8-bit float IS quantized — just not attributable from this
            // label alone. Calling it full precision was the bug.
            ("fp8", Some(8), QuantScheme::Unknown),
            // Names a width and no producer.
            ("Q4", Some(4), QuantScheme::Unknown),
        ];
        for (label, bits, scheme) in cases {
            let q = Quantization::parse(label);
            assert_eq!(q.bits, *bits, "bits for {label}");
            assert_eq!(q.scheme, *scheme, "scheme for {label}");
            assert_eq!(q.label, *label, "label must survive verbatim");
        }
    }

    /// Labels that identify nothing must say so rather than guess.
    #[test]
    fn refuses_to_guess() {
        for label in [
            "",                 // nobody said; not a claim of full precision
            "mxfp",             // MX family, no width
            "Q256_K",           // width overflows u8
            "q0_0",             // a zero-bit quantization is not a thing
            "awq-marlin-w4a16", // real format, unknown to this parser
        ] {
            let q = Quantization::parse(label);
            assert_eq!(q.scheme, QuantScheme::Unknown, "scheme for {label:?}");
            assert_eq!(q.bits, None, "bits for {label:?}");
            assert_eq!(q.label, label, "label for {label:?}");
        }
    }

    /// The distinction the free-text field could not express: same width,
    /// different algorithm, different loader.
    #[test]
    fn same_width_different_scheme() {
        let affine = Quantization::parse("4bit");
        let kquant = Quantization::parse("Q4_K_M");
        let mx = Quantization::parse("mxfp4");
        assert_eq!(affine.bits, kquant.bits);
        assert_eq!(affine.bits, mx.bits);
        assert_ne!(affine.scheme, kquant.scheme);
        assert_ne!(affine.scheme, mx.scheme);
        // And within GGUF, k-quant is not round-to-nearest.
        assert_ne!(
            Quantization::parse("Q5_K_S").scheme,
            Quantization::parse("q5_0").scheme
        );
    }

    /// The scheme names a numeric format, never a container or an engine.
    /// whisper.cpp ships `q5_0` ggml checkpoints that no GGUF text path can
    /// load; a container-named variant would assert otherwise.
    #[test]
    fn scheme_does_not_imply_an_engine() {
        let whisper = Quantization::parse("q5_0");
        let llama = Quantization::parse("Q5_0");
        assert_eq!(whisper.scheme, llama.scheme);
        assert_eq!(whisper.scheme, QuantScheme::RtnBlock);
    }

    #[test]
    fn mlx_config_block_survives_ingest() {
        let q = Quantization::from_mlx_config(Some(8), Some(32), Some("mxfp8")).unwrap();
        assert_eq!(q.bits, Some(8));
        assert_eq!(q.group_size, Some(32));
        assert_eq!(q.scheme, QuantScheme::BlockScaledFloat);

        // Absent `mode` means affine — MLX's default, not unknown.
        let affine = Quantization::from_mlx_config(Some(4), Some(64), None).unwrap();
        assert_eq!(affine.scheme, QuantScheme::AffineGroupInt);
        assert_eq!(affine.group_size, Some(64));
        assert_eq!(affine.label, "4bit");
    }

    /// An empty or absent block must not become a claim of affine group quant.
    /// The field it replaced returned nothing here, and asserting a scheme is
    /// exactly the error a router acting on `scheme` would inherit.
    #[test]
    fn empty_mlx_block_asserts_nothing() {
        assert!(Quantization::from_mlx_config(None, None, None).is_none());
    }

    #[test]
    fn deserializes_legacy_bare_string() {
        let q: Quantization = serde_json::from_str(r#""Q4_K_M""#).unwrap();
        assert_eq!(q.scheme, QuantScheme::KQuantMixed);
        assert_eq!(q.bits, Some(4));
        assert_eq!(q.label, "Q4_K_M");
    }

    #[test]
    fn deserializes_structured_object() {
        let q: Quantization = serde_json::from_str(
            r#"{"bits":4,"scheme":"affine_group_int","group_size":64,"label":"4bit"}"#,
        )
        .unwrap();
        assert_eq!(q.group_size, Some(64));
        assert_eq!(q.scheme, QuantScheme::AffineGroupInt);
    }

    /// A partial object recovers from its label rather than defaulting to
    /// Unknown — the same reason the bare string is still accepted.
    #[test]
    fn partial_object_recovers_from_label() {
        let q: Quantization = serde_json::from_str(r#"{"label":"Q8_0"}"#).unwrap();
        assert_eq!(q.scheme, QuantScheme::RtnBlock);
        assert_eq!(q.bits, Some(8));
    }

    /// A malformed object must be an error, not a row that silently claims
    /// `Unknown`. Under `#[serde(untagged)]` every one of these deserialized
    /// successfully into a fabricated descriptor.
    #[test]
    fn malformed_objects_are_rejected() {
        for bad in [
            r#"{"btis":4,"scehme":"k_quant_mixed","labl":"Q4_K_M"}"#, // typos
            r#"{"quantization":{"bits":4}}"#,                         // double-nested
            r#"{}"#,                                                  // nothing at all
            r#"{"group_size":64}"#,                                   // no label
            r#"{"bits":4,"scheme":"k_quant_mixed"}"#,                 // no label
        ] {
            let parsed: Result<Quantization, _> = serde_json::from_str(bad);
            assert!(parsed.is_err(), "should have rejected {bad}");
        }
    }

    /// The error must name what was wrong. `#[serde(untagged)]` reported only
    /// "data did not match any variant", for a `models.json` that fails whole.
    #[test]
    fn rejection_names_the_offending_field() {
        let err = serde_json::from_str::<Quantization>(
            r#"{"bits":4,"scheme":"affine_grp_int","label":"4bit"}"#,
        )
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("affine_grp_int") || err.contains("scheme"),
            "unhelpful error: {err}"
        );
    }

    #[test]
    fn round_trips_through_the_object_form() {
        for label in ["Q4_K_M", "4bit", "mxfp8", "bf16", "weird-vendor-format"] {
            let q = Quantization::parse(label);
            let round: Quantization =
                serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
            assert_eq!(q, round, "round trip for {label}");
        }
    }

    /// The label alone is the wire form whenever it is lossless. This is what
    /// keeps `row_digest` stable for rows that gained no new information.
    #[test]
    fn serializes_as_a_bare_label_when_lossless() {
        for label in [
            "Q4_K_M",
            "4bit",
            "mxfp8",
            "bf16",
            "q5_0",
            "weird-vendor-format",
        ] {
            let json = serde_json::to_string(&Quantization::parse(label)).unwrap();
            assert_eq!(json, format!("\"{label}\""), "should stay a bare string");
        }
    }

    /// ...and the object form appears exactly where the label would lose
    /// something: a group size, or a scheme the label cannot express.
    #[test]
    fn serializes_as_an_object_only_when_it_adds_information() {
        let with_group = Quantization::from_mlx_config(Some(4), Some(64), None).unwrap();
        let json = serde_json::to_value(&with_group).unwrap();
        assert_eq!(json["group_size"], 64, "group_size must survive the write");
        assert_eq!(json["label"], "4bit");

        // A bare `Q4` parses as Unknown, so an explicit scheme is real
        // information and has to be written out.
        let disambiguated = Quantization {
            bits: Some(4),
            scheme: QuantScheme::AffineGroupInt,
            group_size: None,
            label: "Q4".into(),
        };
        let json = serde_json::to_value(&disambiguated).unwrap();
        assert_eq!(json["scheme"], "affine_group_int");
        assert!(json.get("group_size").is_none(), "no null padding");
    }

    /// Both write forms must read back identically, or the minimal-write rule
    /// would trade a digest change for silent data loss.
    #[test]
    fn every_write_form_round_trips() {
        let cases = [
            Quantization::parse("Q4_K_M"),
            Quantization::parse("bf16"),
            Quantization::parse("unattributable-format"),
            Quantization::from_mlx_config(Some(8), Some(32), Some("mxfp8")).unwrap(),
            Quantization::from_mlx_config(Some(4), Some(64), None).unwrap(),
            Quantization {
                bits: Some(4),
                scheme: QuantScheme::AffineGroupInt,
                group_size: None,
                label: "Q4".into(),
            },
        ];
        for q in cases {
            let round: Quantization =
                serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
            assert_eq!(q, round, "round trip for {q:?}");
        }
    }

    /// The digest guard. `catalog_identity::row_digest` is a SHA-256 over the
    /// serialized schema and clients pin it through
    /// `expected_catalog_revision`, so a row whose quantization gained no new
    /// information must re-serialize to the byte-identical JSON it was read
    /// from. Only rows that genuinely changed may move.
    #[test]
    fn catalog_quantizations_reserialize_unchanged() {
        let raw: Vec<serde_json::Value> =
            serde_json::from_str(include_str!("builtin_catalog.json")).unwrap();
        let parsed: Vec<ModelSchema> =
            serde_json::from_str(include_str!("builtin_catalog.json")).unwrap();
        let mut moved = Vec::new();
        for (raw_row, model) in raw.iter().zip(&parsed) {
            let before = raw_row
                .get("quantization")
                .cloned()
                .unwrap_or(serde_json::Value::Null);
            let after = serde_json::to_value(&model.quantization).unwrap();
            if before != after {
                moved.push(format!("{}: {before} -> {after}", model.id));
            }
        }
        assert!(
            moved.is_empty(),
            "these rows would change catalog digest: {moved:#?}"
        );
    }

    /// Every quantization the built-in catalog ships must classify. An entry
    /// may carry an explicit `scheme` only where its label is genuinely
    /// ambiguous — the guard is that an explicit scheme never *contradicts* a
    /// label the parser can already read, which is how catalog data stops
    /// being a place to make a failing test pass.
    #[test]
    fn builtin_catalog_quantizations_are_coherent() {
        let catalog: Vec<ModelSchema> =
            serde_json::from_str(include_str!("builtin_catalog.json")).unwrap();
        let mut problems = Vec::new();
        for model in &catalog {
            let Some(q) = &model.quantization else {
                continue;
            };
            if q.scheme == QuantScheme::Unknown {
                problems.push(format!("{}: unclassified label {:?}", model.id, q.label));
                continue;
            }
            let from_label = Quantization::parse(&q.label).scheme;
            if from_label != QuantScheme::Unknown && from_label != q.scheme {
                problems.push(format!(
                    "{}: label {:?} parses as {:?} but the row claims {:?}",
                    model.id, q.label, from_label, q.scheme
                ));
            }
        }
        assert!(
            problems.is_empty(),
            "incoherent catalog rows: {problems:#?}"
        );
    }
}