rto-graph 1.26.6

Provenance-tagged codebase knowledge graph store for Roteiro. Implementation detail of the roteiro CLI; no API stability guarantee.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
//! Local model **registry** and on-disk store (ADR-0003), shared by every model
//! tier.
//!
//! Holds a small in-binary registry of downloadable models with **per-platform
//! variants**, host-aware variant selection, the model-store layout
//! (`~/.roteiro/models/<name>/`), and SHA-256 verification. It only lists,
//! resolves, and verifies models — it touches neither an inference engine nor the
//! network. The actual loaders are feature-specific: the GGUF tiers (embedding /
//! generative / vision / audio) load via the llama.cpp core (`rto-llama`, feature
//! `inference-local-models`), while the OCR `.rten` set loads via `ocrs`/`rten`
//! (feature `image-ocr`); the consent-gated download lives in the `roteiro`
//! binary. This module is compiled whenever any model tier is enabled (feature
//! `models`), so even an OCR-only build can reuse the registry and `roteiro model
//! pull` without pulling the llama.cpp engine.

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

/// A host platform that a model may have a tuned variant for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    /// Apple Silicon (macOS / aarch64) — prefers Metal/MLX-oriented builds.
    MacosArm64,
    /// Everything else — the standard build (CPU by default).
    Standard,
}

impl Platform {
    /// The platform Roteiro is running on.
    #[must_use]
    pub fn host() -> Self {
        if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
            Self::MacosArm64
        } else {
            Self::Standard
        }
    }

    /// Stable token for this platform.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::MacosArm64 => "macos-arm64",
            Self::Standard => "standard",
        }
    }
}

/// One file that makes up a model variant, with its verification hash.
#[derive(Debug, Clone, Copy)]
pub struct ModelFile {
    /// Filename stored under the model directory (e.g. `model.safetensors`).
    pub name: &'static str,
    /// URL to fetch it from.
    pub url: &'static str,
    /// Lowercase hex SHA-256 the downloaded bytes must match.
    pub sha256: &'static str,
}

/// A platform-specific set of files for a model.
#[derive(Debug, Clone, Copy)]
pub struct ModelVariant {
    /// Which platform this variant targets.
    pub platform: Platform,
    /// The files to fetch (config, tokenizer, weights, …).
    pub files: &'static [ModelFile],
}

/// What a registry model is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModelKind {
    /// A text-embedding model (the inference layer, ADR-0003).
    Embedding,
    /// A generative instruct model (spec/blueprint drafting, ADR-0004 Tier 1).
    Generative,
    /// An OCR model set for image text extraction (ADR-0005 Tier A).
    Ocr,
    /// A vision-language model for image *understanding* (ADR-0005 Tier B).
    Vision,
    /// An audio-capable multimodal model for speech transcription (Stage 18;
    /// served through the same llama.cpp `mtmd` path as [`Self::Vision`], with an
    /// audio projector instead of a vision one).
    Audio,
}

impl ModelKind {
    /// Every kind, in registry-section order.
    ///
    /// Exists so [`crate::model_choice`] can derive which kinds a `[models]` key
    /// accepts by filtering this list through the capability table, rather than
    /// writing the accepted set down a second time where it could drift from it.
    pub const ALL: [Self; 5] = [
        Self::Embedding,
        Self::Generative,
        Self::Ocr,
        Self::Vision,
        Self::Audio,
    ];

    /// Stable token naming the model's *section* in the registry.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Embedding => "embedding",
            Self::Generative => "generative",
            Self::Ocr => "ocr",
            Self::Vision => "vision",
            Self::Audio => "audio",
        }
    }
}

/// The rough hardware a model is aimed at — an opinionated curation so `roteiro
/// model list` can recommend a pick per section for a machine's resources.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceTier {
    /// Runs comfortably on any laptop (low RAM/CPU).
    Low,
    /// Wants a moderate machine (~16 GB).
    Mid,
    /// Aimed at a workstation (e.g. a 64 GB Apple-silicon machine).
    High,
}

impl ResourceTier {
    /// Stable token for this tier.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Mid => "mid",
            Self::High => "high",
        }
    }
}

/// The specialisation of a generative model — a sub-label within the generative
/// section so `model list` can distinguish general drafting from coding and
/// reasoning models (Stage 20). Non-generative models are [`ModelRole::None`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModelRole {
    /// Not a generative model (embedding / OCR / vision).
    None,
    /// General instruction-following (chat, spec/blueprint drafting). Qwen3's
    /// thinking mode makes these reasoning-capable out of the box.
    Instruct,
    /// Code-specialised (completion, refactoring, code Q&A).
    Coding,
    /// Reasoning-specialised (long chain-of-thought before answering).
    Reasoning,
}

impl ModelRole {
    /// Stable token for this role (`instruct` | `coding` | `reasoning`), or `None`
    /// for a non-generative model.
    #[must_use]
    pub fn as_str(self) -> Option<&'static str> {
        match self {
            Self::None => None,
            Self::Instruct => Some("instruct"),
            Self::Coding => Some("coding"),
            Self::Reasoning => Some("reasoning"),
        }
    }
}

/// A model the user can pull and use.
#[derive(Debug, Clone, Copy)]
pub struct ModelSpec {
    /// Unique registry name (e.g. `all-minilm-l6-v2`).
    pub name: &'static str,
    /// What the model is for.
    pub kind: ModelKind,
    /// For generative models, the specialisation (instruct/coding/reasoning);
    /// [`ModelRole::None`] for non-generative models.
    pub role: ModelRole,
    /// The hardware tier this pick is curated for within its section.
    pub tier: ResourceTier,
    /// Embedding dimensionality (0 for generative models).
    pub dim: usize,
    /// SPDX licence of the model weights.
    pub licence: &'static str,
    /// One-line description.
    pub description: &'static str,
    /// Approximate download size, in mebibytes, for the consent prompt.
    pub size_mib: u32,
    /// Available per-platform variants (at least one `Standard`).
    pub variants: &'static [ModelVariant],
}

impl ModelSpec {
    /// The variant best matching the host: an exact platform match if present,
    /// otherwise the `Standard` variant.
    #[must_use]
    pub fn variant_for(&self, platform: Platform) -> Option<&ModelVariant> {
        self.variants
            .iter()
            .find(|v| v.platform == platform)
            .or_else(|| {
                self.variants
                    .iter()
                    .find(|v| v.platform == Platform::Standard)
            })
    }
}

/// The built-in registry of known embedding models.
///
/// Kept intentionally small; entries are curated so `pull` can suggest the right
/// per-platform artifact and verify its checksum. Larger/re-encoded variants
/// (e.g. Apple MLX builds) are added here as `MacosArm64` variants when they
/// exist — until then the host resolves to the `Standard` variant.
pub const REGISTRY: &[ModelSpec] = &[
    // Embedding models are **GGUF** (llama.cpp via rto-llama): they serve
    // `/v1/embeddings` and back `roteiro infer --model` through the shared engine
    // — no candle. The GGUF embeds its own tokenizer, so only `model.gguf` is
    // needed. `bge-small` is the low-tier default (below); bge-base/large are the
    // mid/high picks.
    ModelSpec {
        name: "bge-base-en-v1.5",
        kind: ModelKind::Embedding,
        role: ModelRole::None,
        tier: ResourceTier::Mid,
        dim: 768,
        licence: "MIT",
        description: "BAAI/bge-base-en-v1.5 (F16 GGUF) — stronger English embeddings (768-d)",
        size_mib: 209,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/CompendiumLabs/bge-base-en-v1.5-gguf/resolve/main/bge-base-en-v1.5-f16.gguf",
                sha256: "88360fdf8521af0ac08d43818bd272da679ab97c685d9b273c48efd01a4187c2",
            }],
        }],
    },
    ModelSpec {
        name: "bge-large-en-v1.5",
        kind: ModelKind::Embedding,
        role: ModelRole::None,
        tier: ResourceTier::High,
        dim: 1024,
        licence: "MIT",
        description: "BAAI/bge-large-en-v1.5 (F16 GGUF) — strongest English embeddings (1024-d)",
        size_mib: 639,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/CompendiumLabs/bge-large-en-v1.5-gguf/resolve/main/bge-large-en-v1.5-f16.gguf",
                sha256: "3379a0e9cea28fc6d7136df8ea7a88ef99ccce5963b9a6f7af9609997be762e3",
            }],
        }],
    },
    // The low-tier embedding default.
    ModelSpec {
        name: "bge-small-en-v1.5-gguf",
        kind: ModelKind::Embedding,
        role: ModelRole::None,
        tier: ResourceTier::Low,
        dim: 384,
        licence: "MIT",
        description: "BAAI/bge-small-en-v1.5 (F16 GGUF) — small English embeddings (384-d), served via llama.cpp",
        size_mib: 65,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/CompendiumLabs/bge-small-en-v1.5-gguf/resolve/main/bge-small-en-v1.5-f16.gguf",
                sha256: "f0b2fef971e8366438bfd2d9aefea1b0115919389448806d290237f638bae999",
            }],
        }],
    },
    // ADR-0004 Tier 1: Apache-2.0 Qwen3 instruct GGUFs for offline spec/blueprint
    // drafting, curated low/mid/high. GGUF-only — the embedded tokenizer serves
    // llama.cpp, so no separate `tokenizer.json` is needed. The low pick is the
    // `spec draft` default.
    ModelSpec {
        name: "qwen3-0.6b",
        kind: ModelKind::Generative,
        role: ModelRole::Instruct,
        tier: ResourceTier::Low,
        dim: 0,
        licence: "Apache-2.0",
        description: "Qwen3-0.6B (Q4_K_M GGUF) — tiny offline instruct model, the `spec draft` default",
        size_mib: 380,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/unsloth/Qwen3-0.6B-GGUF/resolve/main/Qwen3-0.6B-Q4_K_M.gguf",
                sha256: "ac2d97712095a558e31573f62f466a3f9d93990898b0ec79d7c974c1780d524a",
            }],
        }],
    },
    ModelSpec {
        name: "qwen3-8b",
        kind: ModelKind::Generative,
        role: ModelRole::Instruct,
        tier: ResourceTier::Mid,
        dim: 0,
        licence: "Apache-2.0",
        description: "Qwen3-8B (Q4_K_M GGUF) — stronger offline drafting on a ~16 GB machine",
        size_mib: 4795,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/Qwen/Qwen3-8B-GGUF/resolve/main/Qwen3-8B-Q4_K_M.gguf",
                sha256: "d98cdcbd03e17ce47681435b5150e34c1417f50b5c0019dd560e4882c5745785",
            }],
        }],
    },
    ModelSpec {
        name: "qwen3-32b",
        kind: ModelKind::Generative,
        role: ModelRole::Instruct,
        tier: ResourceTier::High,
        dim: 0,
        licence: "Apache-2.0",
        description: "Qwen3-32B (Q4_K_M GGUF) — best offline drafting, for a workstation",
        size_mib: 18845,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/Qwen/Qwen3-32B-GGUF/resolve/main/Qwen3-32B-Q4_K_M.gguf",
                sha256: "efd971561896866f0e910cce52761ca77b1b138090c7f15fe284676d57d1f689",
            }],
        }],
    },
    // The current strongest offline instruct pick for a workstation. Qwen3.8-27B
    // is a dense 27B declaring llama.cpp arch `qwen35`, which the pinned
    // `llama-cpp-2` 0.1.154 registers (`LLM_ARCH_QWEN35` in its vendored
    // `llama-arch.cpp`) — verified by loading this exact file with this repo's
    // own build and getting a `<tool_call>` for a graph tool, not merely a
    // successful load. A model Roteiro serves that cannot call
    // `search`/`explain`/`path`/`debt` is much less useful to it.
    //
    // **`ggml-org` rather than `unsloth` deliberately.** Unsloth bundles the
    // multi-token-prediction tensors inside the main GGUF, and on this build they
    // are allocated whether or not the head is used — roughly 0.3–0.5 GB resident
    // for something Roteiro never runs. `ggml-org` ships MTP as separate
    // `mtp-*.gguf` files, so *not* listing them here is the whole saving.
    //
    // **Q4_K_M rather than Q5_K_M deliberately.** Generation on Metal is
    // bandwidth-bound, so Q5 costs ~13–15% per token for the life of the model,
    // against a quality difference not observable at 27B.
    //
    // The repo also publishes `mmproj-*.gguf` (it is a vision-language model
    // upstream). Those are deliberately not listed: this entry is the *text*
    // generative tier, and a Vision-tier entry could add the projector later.
    ModelSpec {
        name: "qwen3.8-27b",
        kind: ModelKind::Generative,
        role: ModelRole::Instruct,
        tier: ResourceTier::High,
        dim: 0,
        licence: "Apache-2.0",
        description: "Qwen3.8-27B (Q4_K_M GGUF) — strongest offline instruct pick, tool-calling, for a workstation",
        size_mib: 18095,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/ggml-org/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_K_M.gguf",
                // Measured over the downloaded file: Hugging Face publishes no
                // SHA-256 for it, so this can come from nowhere else.
                sha256: "31629f53165ab6a7dad8c9847dcfd1fdf55829dac1e6e748f4a68581b0033d34",
            }],
        }],
    },
    // Stage 20: opt-in coding + reasoning generative models for local use and
    // serving (ADR-0006). GGUF-only (the embedded tokenizer serves llama.cpp — no
    // separate `tokenizer.json`); `role` distinguishes them from the general
    // Qwen3 instruct picks in `model list`. Off by default.
    ModelSpec {
        name: "qwen2.5-coder-3b",
        kind: ModelKind::Generative,
        role: ModelRole::Coding,
        tier: ResourceTier::Mid,
        dim: 0,
        licence: "Apache-2.0",
        description: "Qwen2.5-Coder-3B-Instruct (Q4_K_M GGUF) — code completion/Q&A, served via llama.cpp",
        size_mib: 1841,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/bartowski/Qwen2.5-Coder-3B-Instruct-GGUF/resolve/main/Qwen2.5-Coder-3B-Instruct-Q4_K_M.gguf",
                sha256: "3da3afe6cf5c674ac195803ea0dd6fee7e1c228c2105c1ce8c66890d1d4ab460",
            }],
        }],
    },
    ModelSpec {
        name: "qwen3-coder-30b-a3b",
        kind: ModelKind::Generative,
        role: ModelRole::Coding,
        tier: ResourceTier::High,
        dim: 0,
        licence: "Apache-2.0",
        description: "Qwen3-Coder-30B-A3B-Instruct (Q4_K_M GGUF) — 30B MoE coder (3B active), for a workstation",
        size_mib: 17697,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF/resolve/main/Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf",
                sha256: "fadc3e5f8d42bf7e894a785b05082e47daee4df26680389817e2093056f088ad",
            }],
        }],
    },
    ModelSpec {
        name: "deepseek-r1-distill-qwen-1.5b",
        kind: ModelKind::Generative,
        role: ModelRole::Reasoning,
        tier: ResourceTier::Low,
        dim: 0,
        licence: "MIT",
        description: "DeepSeek-R1-Distill-Qwen-1.5B (Q4_K_M GGUF) — small reasoning model, served via llama.cpp",
        size_mib: 1066,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[ModelFile {
                name: "model.gguf",
                url: "https://huggingface.co/bartowski/DeepSeek-R1-Distill-Qwen-1.5B-GGUF/resolve/main/DeepSeek-R1-Distill-Qwen-1.5B-Q4_K_M.gguf",
                sha256: "1741e5b2d062b07acf048bf0d2c514dadf2a48f94e2b4aa0cfe069af3838ee2f",
            }],
        }],
    },
    // ADR-0005 Tier A: the `ocrs` pure-Rust OCR model set (detection +
    // recognition, `.rten` format). Weights trace to open datasets (HierText,
    // CC-BY-SA-4.0); the `ocrs` engine crate is MIT/Apache-2.0. Checksums are
    // pinned so a model change invalidates cached image facts (see extract.rs).
    ModelSpec {
        name: "ocrs-text",
        kind: ModelKind::Ocr,
        role: ModelRole::None,
        tier: ResourceTier::Low,
        dim: 0,
        licence: "CC-BY-SA-4.0",
        description: "ocrs text detection + recognition (pure-Rust OCR for `image-ocr`)",
        size_mib: 12,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[
                ModelFile {
                    name: "text-detection.rten",
                    url: "https://ocrs-models.s3-accelerate.amazonaws.com/text-detection.rten",
                    sha256: "f15cfb56bd02c4bf478a20343986504a1f01e1665c2b3a0ad66340f054b1b5ca",
                },
                ModelFile {
                    name: "text-recognition.rten",
                    url: "https://ocrs-models.s3-accelerate.amazonaws.com/text-recognition.rten",
                    sha256: "e484866d4cce403175bd8d00b128feb08ab42e208de30e42cd9889d8f1735a6e",
                },
            ],
        }],
    },
    // Vision-language GGUF for the llama.cpp serving path (ADR-0006 multimodal
    // `/v1/chat/completions`). Ships a base `model.gguf` plus its multimodal
    // projector `mmproj.gguf`; served via llama.cpp `mtmd`. SmolVLM-500M is
    // llama.cpp's small reference multimodal model — image description *and*
    // reading text in an image (the OCR use case is just a prompt).
    ModelSpec {
        name: "smolvlm-500m-gguf",
        kind: ModelKind::Vision,
        role: ModelRole::None,
        tier: ResourceTier::Low,
        dim: 0,
        licence: "Apache-2.0",
        description: "SmolVLM-500M-Instruct (Q8_0 GGUF + mmproj) — small vision-language model served via llama.cpp",
        size_mib: 520,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[
                ModelFile {
                    name: "model.gguf",
                    url: "https://huggingface.co/ggml-org/SmolVLM-500M-Instruct-GGUF/resolve/main/SmolVLM-500M-Instruct-Q8_0.gguf",
                    sha256: "9d4612de6a42214499e301494a3ecc2be0abdd9de44e663bda63f1152fad1bf4",
                },
                ModelFile {
                    name: "mmproj.gguf",
                    url: "https://huggingface.co/ggml-org/SmolVLM-500M-Instruct-GGUF/resolve/main/mmproj-SmolVLM-500M-Instruct-Q8_0.gguf",
                    sha256: "d1eb8b6b23979205fdf63703ed10f788131a3f812c7b1f72e0119d5d81295150",
                },
            ],
        }],
    },
    // Stage 18: audio transcription via an audio-capable llama.cpp `mtmd` model —
    // the same multimodal path as vision, with an *audio* projector (a Whisper-
    // style encoder, `mmproj.gguf`) instead of a vision one. So `roteiro sync` can
    // transcribe spoken-word audio (wav/mp3/flac) into `meta.content`. Off by
    // default (feature `audio-transcribe`).
    //
    // Model choice: Voxtral-Mini-3B (Mistral, Apache-2.0) is a *transcription-
    // specialised* audio model, verified transcribing a speech clip verbatim over
    // this mtmd path (`rto-llama/tests/audio.rs`). It is the only curated audio
    // pick, and a mid-tier one — so the audio section has no low-tier floor
    // (see `every_section_has_a_low_tier_floor`). A smaller low-tier option (e.g.
    // Ultravox 1B) could be added later if it verifies at acceptable quality.
    ModelSpec {
        name: "voxtral-mini-3b",
        kind: ModelKind::Audio,
        role: ModelRole::None,
        tier: ResourceTier::Mid,
        dim: 0,
        licence: "Apache-2.0",
        description: "Voxtral-Mini-3B (Mistral, Q4_K_M GGUF + Q8_0 audio mmproj) — speech transcription via llama.cpp mtmd",
        size_mib: 3041,
        variants: &[ModelVariant {
            platform: Platform::Standard,
            files: &[
                ModelFile {
                    name: "model.gguf",
                    url: "https://huggingface.co/ggml-org/Voxtral-Mini-3B-2507-GGUF/resolve/main/Voxtral-Mini-3B-2507-Q4_K_M.gguf",
                    sha256: "4705be8ec22ca23d12632f4b4a3691faa95917d90a06d3cf3c3ec0e91958f1a8",
                },
                ModelFile {
                    name: "mmproj.gguf",
                    url: "https://huggingface.co/ggml-org/Voxtral-Mini-3B-2507-GGUF/resolve/main/mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf",
                    sha256: "4f24c4ef3ce929d02ed9d1cfb050ae9a7365f057c0ddec0d489580982ebe0d02",
                },
            ],
        }],
    },
];

/// Look up a model spec by name.
#[must_use]
pub fn find(name: &str) -> Option<&'static ModelSpec> {
    REGISTRY.iter().find(|m| m.name == name)
}

/// Pure resolution of the model-store root, in precedence order: an explicit
/// `model_store` directory (config `[paths] model_store` or `ROTEIRO_MODEL_STORE`,
/// used verbatim), then `roteiro_home`'s `models` subdir (`ROTEIRO_HOME`), then
/// `~/.roteiro/models` under the given home. Factored out so it is testable
/// without mutating the process environment.
fn store_root_from(
    model_store: Option<PathBuf>,
    roteiro_home: Option<PathBuf>,
    home: Option<PathBuf>,
) -> PathBuf {
    // An explicit model-store dir (config `[paths] model_store`) wins verbatim.
    if let Some(dir) = model_store {
        return dir;
    }
    if let Some(dir) = roteiro_home {
        return dir.join("models");
    }
    home.unwrap_or_else(|| PathBuf::from("."))
        .join(".roteiro")
        .join("models")
}

/// A process-wide model-store override, set once from config `[paths]
/// model_store` (the env is `unsafe` to mutate under edition 2024, so a
/// `OnceLock` carries the config value instead).
static MODEL_STORE_OVERRIDE: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();

/// Set the model-store directory for this process (config `[paths] model_store`).
/// First call wins; later calls are ignored. Call once at startup, before any
/// model operation.
pub fn set_model_store(dir: PathBuf) {
    let _ = MODEL_STORE_OVERRIDE.set(dir);
}

/// Root of the user-level model store (`~/.roteiro/models`). Honours, in order,
/// the config override ([`set_model_store`]), `ROTEIRO_MODEL_STORE` (an explicit
/// store dir), and `ROTEIRO_HOME` (its `models` subdir).
#[must_use]
pub fn store_root() -> PathBuf {
    if let Some(dir) = MODEL_STORE_OVERRIDE.get() {
        return dir.clone();
    }
    store_root_from(
        std::env::var_os("ROTEIRO_MODEL_STORE").map(PathBuf::from),
        std::env::var_os("ROTEIRO_HOME").map(PathBuf::from),
        std::env::var_os("HOME")
            .or_else(|| std::env::var_os("USERPROFILE"))
            .map(PathBuf::from),
    )
}

/// Directory a given model is (or would be) stored in.
#[must_use]
pub fn model_dir(name: &str) -> PathBuf {
    store_root().join(name)
}

/// Whether every file of `variant` is already present in the model directory.
#[must_use]
pub fn is_installed(name: &str, variant: &ModelVariant) -> bool {
    let dir = model_dir(name);
    variant.files.iter().all(|f| dir.join(f.name).exists())
}

/// Total bytes a model currently occupies in the store — every file under its
/// directory, including any orphaned `.partial` from an abandoned pull.
///
/// 0 for a model that is not installed. This is what `roteiro model rm` would
/// reclaim and what `roteiro model list` reports beside an installed entry.
#[must_use]
pub fn installed_size(name: &str) -> u64 {
    dir_size(&model_dir(name))
}

/// Recursive byte total of `dir`, ignoring anything unreadable (a size report
/// must never be the thing that fails a command).
fn dir_size(dir: &Path) -> u64 {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    entries
        .flatten()
        .map(|e| match e.file_type() {
            Ok(t) if t.is_dir() => dir_size(&e.path()),
            Ok(_) => e.metadata().map_or(0, |m| m.len()),
            Err(_) => 0,
        })
        .sum()
}

/// What [`remove_model`] deleted.
#[derive(Debug, Clone)]
pub struct Removal {
    /// The directory that was removed.
    pub dir: PathBuf,
    /// Names of the files removed, sorted — including any `.partial` and its
    /// sidecar, so an abandoned pull is cleaned up with the model.
    pub files: Vec<String>,
    /// Bytes reclaimed.
    pub bytes: u64,
}

/// Delete a model's directory from the store, reporting what was freed.
///
/// The whole directory goes, not just the files the *current* registry entry
/// lists: a model's file set can change between releases, and leaving behind
/// bytes that `model list` no longer mentions is exactly the accumulation this
/// command exists to stop.
///
/// # Errors
/// Returns [`std::io::Error`] if the directory exists but cannot be removed.
/// Removing a model that is not installed is not an error here — callers decide
/// what an empty [`Removal`] means (`roteiro model rm` refuses).
pub fn remove_model(name: &str) -> std::io::Result<Removal> {
    let dir = model_dir(name);
    let mut files = Vec::new();
    let mut bytes = 0;
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            bytes += match entry.file_type() {
                Ok(t) if t.is_dir() => dir_size(&entry.path()),
                _ => entry.metadata().map_or(0, |m| m.len()),
            };
            files.push(entry.file_name().to_string_lossy().into_owned());
        }
    }
    files.sort();
    if dir.exists() {
        std::fs::remove_dir_all(&dir)?;
    }
    Ok(Removal { dir, files, bytes })
}

/// Lowercase hex SHA-256 of `bytes`.
#[must_use]
pub fn sha256_hex(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(bytes);
    let mut out = String::with_capacity(64);
    for byte in digest {
        use std::fmt::Write as _;
        let _ = write!(out, "{byte:02x}");
    }
    out
}

/// Verify `bytes` against an expected lowercase-hex SHA-256. An empty
/// `expected` means "no hash pinned" and always passes (registry entries whose
/// checksum has not yet been recorded).
#[must_use]
pub fn verify_sha256(bytes: &[u8], expected: &str) -> bool {
    expected.is_empty() || sha256_hex(bytes).eq_ignore_ascii_case(expected)
}

/// Path helper: ensure the model directory exists, returning it.
///
/// # Errors
/// Returns [`std::io::Error`] if the directory cannot be created.
pub fn ensure_model_dir(name: &str) -> std::io::Result<PathBuf> {
    let dir = model_dir(name);
    std::fs::create_dir_all(&dir)?;
    Ok(dir)
}

/// Errors from [`download_verified`] and [`download_resumable`].
#[derive(Debug, thiserror::Error)]
pub enum DownloadError {
    /// A read/write failure while streaming the download. For
    /// [`download_resumable`] the bytes already on disk are **kept** so the next
    /// attempt resumes from them.
    #[error("download io error: {0}")]
    Io(#[from] std::io::Error),
    /// The streamed bytes did not match the pinned checksum. The partial file is
    /// always discarded in this case: its contents are known-wrong, so resuming
    /// from it could only ever reproduce the same bad digest.
    #[error("checksum mismatch: expected {expected}, got {got} (partial discarded)")]
    Checksum {
        /// The pinned SHA-256.
        expected: String,
        /// The SHA-256 actually computed over the downloaded bytes.
        got: String,
    },
    /// The caller's range-opening callback failed to reach the server.
    #[error("transport error: {0}")]
    Transport(Box<dyn std::error::Error + Send + Sync>),
    /// The server's answer to a `Range` request could not be used: an
    /// unexpected status, or a `Content-Range` that is unparseable or starts
    /// somewhere other than where resumption asked it to.
    #[error("range request failed: {0}")]
    Range(String),
}

/// What a server did with a `Range` request, as handed back to
/// [`download_resumable`] by the caller's transport.
///
/// Distinguishing these two is the whole point: appending a `200` body (the
/// **entire** file) onto an existing prefix silently corrupts the result, and
/// the corruption only surfaces as a checksum failure after the *whole* file has
/// been transferred a second time.
#[derive(Debug)]
pub enum RangeReply<R> {
    /// The server honoured the request (`206 Partial Content`): `reader` yields
    /// the bytes **from the requested offset onwards**.
    Partial {
        /// Reader over the remaining bytes.
        reader: R,
        /// Total size of the complete resource, from `Content-Range`, if the
        /// server stated it (`*` ⇒ `None`).
        total: Option<u64>,
    },
    /// The server ignored the request, or none was made (`200 OK`): `reader`
    /// yields the resource **from byte zero**.
    Full {
        /// Reader over the whole resource.
        reader: R,
        /// Total size, from `Content-Length`, if the server stated it.
        total: Option<u64>,
        /// Why this is a whole-file body (status + `Accept-Ranges`), for the
        /// message shown when a resume has to be abandoned. See
        /// [`interpret_range_response`], which produces it.
        detail: String,
    },
}

/// Notable things that happen during a resumable download, reported to the
/// caller so it can tell the user. The library never prints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DownloadEvent {
    /// An existing partial could not be trusted and was deleted before starting
    /// over. `reason` says which check rejected it.
    DiscardedPartial {
        /// Bytes thrown away.
        bytes: u64,
        /// Why the partial was rejected.
        reason: String,
    },
    /// Picking up an existing partial: the transfer asks for `offset..`.
    Resuming {
        /// Byte offset the request resumes from.
        offset: u64,
        /// Total size, if known from the sidecar.
        total: Option<u64>,
    },
    /// The partial was already complete, so nothing was transferred — it only
    /// needed verifying and installing.
    AlreadyComplete {
        /// Size of the complete partial.
        bytes: u64,
    },
    /// The server would not honour the `Range` request, so the transfer
    /// restarted from zero rather than appending a whole-file body onto the
    /// existing prefix.
    RangeUnsupported {
        /// Bytes discarded by restarting.
        discarded: u64,
        /// What the server said (status / `Accept-Ranges`).
        detail: String,
    },
    /// The transfer failed part-way. The bytes are on disk and the next attempt
    /// will resume from them.
    KeptPartial {
        /// Bytes kept for the next attempt.
        bytes: u64,
    },
    /// The completed transfer failed verification, so the partial was discarded.
    PoisonedPartial {
        /// Bytes discarded.
        bytes: u64,
    },
}

/// Sidecar recorded next to a `.partial`, so a later run can tell whether the
/// bytes on disk are still a valid prefix of what it is now being asked to
/// fetch. Without it a partial is just anonymous bytes and must be discarded.
#[derive(serde::Serialize, serde::Deserialize)]
struct PartialMeta {
    /// Sidecar format version; an unrecognised value discards the partial.
    version: u32,
    /// The URL the partial was started against.
    url: String,
    /// The pinned SHA-256 it was started against (empty ⇒ unpinned).
    sha256: String,
    /// Total size of the complete resource, if the server stated it.
    total: Option<u64>,
}

/// Current [`PartialMeta::version`]. Bump when the sidecar's meaning changes so
/// older partials are discarded rather than misread.
const PARTIAL_META_VERSION: u32 = 1;

/// Path of the in-progress download for `dest` (`model.gguf` → `model.partial`).
#[must_use]
pub fn partial_path(dest: &Path) -> PathBuf {
    dest.with_extension("partial")
}

/// Path of the sidecar describing [`partial_path`]'s provenance.
#[must_use]
pub fn partial_meta_path(dest: &Path) -> PathBuf {
    dest.with_extension("partial.json")
}

/// Delete `dest`'s partial and its sidecar, returning the bytes reclaimed.
///
/// Used both internally and by `roteiro model rm`, which cleans up partials
/// orphaned by an abandoned pull.
///
/// # Errors
/// Returns [`std::io::Error`] if a file exists but cannot be removed.
pub fn discard_partial(dest: &Path) -> std::io::Result<u64> {
    let tmp = partial_path(dest);
    let freed = std::fs::metadata(&tmp).map_or(0, |m| m.len());
    remove_if_present(&tmp)?;
    remove_if_present(&partial_meta_path(dest))?;
    Ok(freed)
}

/// `remove_file`, treating "already gone" as success.
fn remove_if_present(path: &Path) -> std::io::Result<()> {
    match std::fs::remove_file(path) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        other => other,
    }
}

/// Interpret a server's answer to a range request into a [`RangeReply`] shape.
///
/// Pure, so the (fiddly) status/`Content-Range` reasoning is unit-testable
/// without a socket. `206` is authoritative for "the range was honoured";
/// `accept_ranges` is only advisory and is used to explain a `200`.
///
/// Returns the kind of body to expect and the total size if the server stated
/// it.
///
/// # Errors
/// Returns [`DownloadError::Range`] for a status other than `200`/`206`, a
/// `Content-Range` that cannot be parsed, or a `206` whose range starts
/// somewhere other than `requested_from`.
pub fn interpret_range_response(
    status: u16,
    accept_ranges: Option<&str>,
    content_range: Option<&str>,
    content_length: Option<u64>,
    requested_from: u64,
) -> Result<(RangeKind, Option<u64>), DownloadError> {
    match status {
        206 => {
            let raw = content_range
                .ok_or_else(|| DownloadError::Range("206 response without Content-Range".into()))?;
            let (start, total) = parse_content_range(raw)?;
            if start != requested_from {
                return Err(DownloadError::Range(format!(
                    "server resumed at byte {start} but {requested_from} was requested \
                     (Content-Range: {raw})"
                )));
            }
            Ok((RangeKind::Partial, total))
        }
        200 => {
            let detail = match accept_ranges {
                Some(v) => format!("200 OK, Accept-Ranges: {v}"),
                None => "200 OK, no Accept-Ranges header".to_owned(),
            };
            Ok((RangeKind::Full { detail }, content_length))
        }
        other => Err(DownloadError::Range(format!(
            "unexpected status {other} (expected 200 or 206)"
        ))),
    }
}

/// The two shapes [`interpret_range_response`] can conclude.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RangeKind {
    /// A `206`: the body starts at the requested offset.
    Partial,
    /// A `200`: the body is the whole resource, whatever was requested.
    Full {
        /// Human-readable note on why this is a whole-file body.
        detail: String,
    },
}

/// Parse `bytes <start>-<end>/<total>` into `(start, total)`; `total` is `None`
/// for the `*` (unknown-length) form.
fn parse_content_range(raw: &str) -> Result<(u64, Option<u64>), DownloadError> {
    let bad = || DownloadError::Range(format!("unparseable Content-Range: {raw}"));
    let rest = raw.trim().strip_prefix("bytes ").ok_or_else(bad)?;
    let (range, total) = rest.split_once('/').ok_or_else(bad)?;
    let (start, _end) = range.split_once('-').ok_or_else(bad)?;
    let start: u64 = start.trim().parse().map_err(|_| bad())?;
    let total = match total.trim() {
        "*" => None,
        n => Some(n.parse().map_err(|_| bad())?),
    };
    Ok((start, total))
}

/// Stream `reader` to `dest`, hashing the bytes **as they are written** (constant
/// memory — the file is never buffered whole), verify the result against
/// `expected_sha256` (empty ⇒ unpinned, verification skipped), and install
/// atomically (temp file + rename). This lets multi-gigabyte models download
/// without holding the whole file in memory.
///
/// On a checksum mismatch the partial file is removed and
/// [`DownloadError::Checksum`] is returned.
///
/// # Errors
/// Returns [`DownloadError::Io`] on a read/write failure, or
/// [`DownloadError::Checksum`] if the pinned hash does not match.
pub fn download_verified(
    mut reader: impl std::io::Read,
    dest: &Path,
    expected_sha256: &str,
) -> Result<(), DownloadError> {
    use sha2::{Digest, Sha256};

    /// Removes the partial file on drop unless disarmed — best-effort cleanup so
    /// *any* early return (network drop, disk full, fsync/rename failure, checksum
    /// mismatch) never leaves a stray `.partial` behind.
    struct PartialGuard<'a> {
        path: &'a Path,
        armed: bool,
    }
    impl Drop for PartialGuard<'_> {
        fn drop(&mut self) {
            if self.armed {
                std::fs::remove_file(self.path).ok();
            }
        }
    }

    let tmp = dest.with_extension("partial");
    let mut guard = PartialGuard {
        path: &tmp,
        armed: true,
    };

    let mut writer = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; 1 << 16]; // 64 KiB chunks
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
        std::io::Write::write_all(&mut writer, &buf[..n])?;
    }
    // `into_inner` flushes the buffer; fsync so the bytes are durable before the
    // rename makes them the installed file.
    writer
        .into_inner()
        .map_err(std::io::IntoInnerError::into_error)?
        .sync_all()?;

    if !expected_sha256.is_empty() {
        let mut got = String::with_capacity(64);
        for byte in hasher.finalize() {
            use std::fmt::Write as _;
            let _ = write!(got, "{byte:02x}");
        }
        if !got.eq_ignore_ascii_case(expected_sha256) {
            // `guard` removes the partial file on return.
            return Err(DownloadError::Checksum {
                expected: expected_sha256.to_owned(),
                got,
            });
        }
    }
    // Atomic install: remove any existing file first (Windows `rename` fails if
    // the destination exists), then rename the verified temp into place. If
    // either fails, `guard` cleans up the partial.
    if dest.exists() {
        std::fs::remove_file(dest)?;
    }
    std::fs::rename(&tmp, dest)?;
    guard.armed = false; // installed successfully — nothing to clean up
    Ok(())
}

/// A `Write` that forwards to `inner` and folds everything actually written into
/// `hasher` — so the digest is always over exactly the bytes that reached the
/// file, in constant memory.
struct HashingWriter<'a, W> {
    inner: W,
    hasher: &'a mut sha2::Sha256,
}

impl<W: std::io::Write> std::io::Write for HashingWriter<'_, W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        use sha2::Digest as _;
        // Hash only what the inner writer accepted, so a short write cannot
        // desynchronise the digest from the file.
        let n = self.inner.write(buf)?;
        self.hasher.update(&buf[..n]);
        Ok(n)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

/// Length of `path`, or 0 if it does not exist.
fn existing_len(path: &Path) -> u64 {
    std::fs::metadata(path).map_or(0, |m| m.len())
}

/// Fold the first `len` bytes of `path` into `hasher`.
///
/// A resume has to reconstruct the digest of the bytes already on disk, and
/// `sha2` cannot serialise a mid-stream hasher state — so the prefix is re-read.
/// That is a local disk read, which is orders of magnitude cheaper than
/// re-fetching the same prefix over the network, and it has the useful property
/// of hashing *what is actually there* rather than what a previous run believed
/// it wrote.
fn hash_prefix(path: &Path, len: u64, hasher: &mut sha2::Sha256) -> std::io::Result<()> {
    let mut src = std::io::Read::take(std::fs::File::open(path)?, len);
    let mut sink = HashingWriter {
        inner: std::io::sink(),
        hasher,
    };
    let read = std::io::copy(&mut src, &mut sink)?;
    if read != len {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            format!("partial download shrank while being re-hashed ({read} of {len} bytes)"),
        ));
    }
    Ok(())
}

/// Read the sidecar next to a partial, or `None` if it is absent or unreadable.
fn load_partial_meta(path: &Path) -> Option<PartialMeta> {
    let raw = std::fs::read(path).ok()?;
    serde_json::from_slice(&raw).ok()
}

/// Write the sidecar recording what the partial is being fetched against.
fn write_partial_meta(path: &Path, meta: &PartialMeta) -> std::io::Result<()> {
    let json = serde_json::to_vec(meta).map_err(std::io::Error::other)?;
    std::fs::write(path, json)
}

/// Verify the streamed digest and install the partial atomically.
///
/// On a mismatch the partial is **discarded**: unlike a dropped connection, bad
/// bytes are not a usable prefix of anything, so keeping them would only let a
/// later run resume into the same failure.
fn install_verified(
    dest: &Path,
    expected_sha256: &str,
    hasher: sha2::Sha256,
    on_event: &mut impl FnMut(DownloadEvent),
) -> Result<(), DownloadError> {
    use sha2::Digest as _;

    let tmp = partial_path(dest);
    if !expected_sha256.is_empty() {
        let mut got = String::with_capacity(64);
        for byte in hasher.finalize() {
            use std::fmt::Write as _;
            let _ = write!(got, "{byte:02x}");
        }
        if !got.eq_ignore_ascii_case(expected_sha256) {
            let bytes = existing_len(&tmp);
            discard_partial(dest)?;
            on_event(DownloadEvent::PoisonedPartial { bytes });
            return Err(DownloadError::Checksum {
                expected: expected_sha256.to_owned(),
                got,
            });
        }
    }
    // Atomic install: remove any existing file first (Windows `rename` fails if
    // the destination exists), then rename the verified temp into place.
    if dest.exists() {
        std::fs::remove_file(dest)?;
    }
    std::fs::rename(&tmp, dest)?;
    // The sidecar only describes an in-progress download; the installed file is
    // described by the registry.
    remove_if_present(&partial_meta_path(dest))?;
    Ok(())
}

/// Decide where a download should start: the length of a partial that every
/// check confirms is still a prefix of `url`'s current contents, or 0.
///
/// Anything that cannot be *positively* confirmed is discarded, because a wrong
/// prefix is far more expensive than a re-download — it is only detected after
/// the whole file has been transferred again, and then only as an unexplained
/// checksum failure. Returns the resume offset and the total size the partial
/// was started against, if it was recorded.
fn plan_resume(
    dest: &Path,
    url: &str,
    expected_sha256: &str,
    on_event: &mut impl FnMut(DownloadEvent),
) -> Result<(u64, Option<u64>), DownloadError> {
    let on_disk = existing_len(&partial_path(dest));
    if on_disk == 0 {
        return Ok((0, None));
    }

    let mut known_total = None;
    let reject = match load_partial_meta(&partial_meta_path(dest)) {
        None => Some("no sidecar recording what it was started against".to_owned()),
        Some(m) if m.version != PARTIAL_META_VERSION => Some(format!(
            "its sidecar is format v{}, not v{PARTIAL_META_VERSION}",
            m.version
        )),
        Some(m) if m.url != url => Some("it was started against a different URL".to_owned()),
        Some(m) if m.sha256 != expected_sha256 => {
            Some("the pinned checksum changed since it was started".to_owned())
        }
        Some(m) => match m.total {
            Some(t) if on_disk > t => Some(format!(
                "it is larger ({on_disk} bytes) than the recorded total ({t} bytes)"
            )),
            total => {
                known_total = total;
                None
            }
        },
    };
    if let Some(reason) = reject {
        on_event(DownloadEvent::DiscardedPartial {
            bytes: on_disk,
            reason,
        });
        discard_partial(dest)?;
        return Ok((0, None));
    }
    Ok((on_disk, known_total))
}

/// Ask the transport for the bytes still needed and settle where they go.
///
/// `resume_from`, `known_total` and `hasher` are in/out: on return they describe
/// the transfer that is about to happen, so a rejected resume (`Range` ignored,
/// or a remote that changed size) leaves the caller with a consistent
/// start-from-zero state rather than a half-updated one. The `bool` says whether
/// the body appends to an existing prefix or replaces the file.
///
/// At most one retry: only the *server* can reveal that the resource is now a
/// different size from the one the partial was started against, so that check
/// costs a second request — but only ever one.
fn start_transfer<R, F, E>(
    dest: &Path,
    open: &mut F,
    on_event: &mut E,
    hasher: &mut sha2::Sha256,
    resume_from: &mut u64,
    known_total: &mut Option<u64>,
) -> Result<(R, bool), DownloadError>
where
    R: std::io::Read,
    F: FnMut(u64) -> Result<RangeReply<R>, DownloadError>,
    E: FnMut(DownloadEvent),
{
    use sha2::Digest as _;

    let tmp = partial_path(dest);
    loop {
        if *resume_from > 0 {
            hash_prefix(&tmp, *resume_from, hasher)?;
        }
        match open(*resume_from)? {
            RangeReply::Partial { reader, total } => {
                if let (Some(remote), Some(recorded)) = (total, *known_total)
                    && remote != recorded
                {
                    on_event(DownloadEvent::DiscardedPartial {
                        bytes: *resume_from,
                        reason: format!(
                            "the remote is now {remote} bytes but it was started against {recorded}"
                        ),
                    });
                    discard_partial(dest)?;
                    *resume_from = 0;
                    *known_total = None;
                    *hasher = sha2::Sha256::new();
                    continue;
                }
                *known_total = total.or(*known_total);
                on_event(DownloadEvent::Resuming {
                    offset: *resume_from,
                    total: *known_total,
                });
                return Ok((reader, true));
            }
            RangeReply::Full {
                reader,
                total,
                detail,
            } => {
                if *resume_from > 0 {
                    // Never append a whole-file body onto an existing prefix: it
                    // would corrupt the result and only surface as a checksum
                    // failure after the whole file had transferred again.
                    on_event(DownloadEvent::RangeUnsupported {
                        discarded: *resume_from,
                        detail,
                    });
                    *resume_from = 0;
                    *hasher = sha2::Sha256::new();
                }
                *known_total = total;
                return Ok((reader, false));
            }
        }
    }
}

/// Download `url` to `dest`, **resuming** an interrupted earlier attempt when it
/// is safe to do so, verifying the pinned SHA-256, and installing atomically.
///
/// `open` is the caller's transport: given a byte offset it issues the request
/// (a `Range: bytes=<offset>-` when the offset is non-zero) and reports what the
/// server did as a [`RangeReply`]. Keeping the transport out of this crate is
/// deliberate — `rto-graph` never touches the network — and it makes every
/// branch below testable against a local socket or an in-process stub.
///
/// `on_event` receives the [`DownloadEvent`]s worth telling a user about. The
/// library itself never prints.
///
/// # Failure modes
/// - **Transport failure** (the request never opens, the connection drops
///   mid-body, the disk fills while writing): the bytes on disk are **kept**
///   along with their sidecar, and [`DownloadEvent::KeptPartial`] is emitted.
///   The next call resumes from them. This is the whole point: a 19 GiB pull
///   that dies at 90% costs the last 10%, not the whole thing.
///
///   This holds for **every** failing return, not just the ones that happen
///   mid-stream: whenever this function returns an error and a non-empty partial
///   survives on disk, exactly one [`DownloadEvent::KeptPartial`] is emitted
///   naming its size. An operator can therefore always tell "a prefix survived,
///   the next pull will be shorter" from "nothing was kept" — which is the only
///   reason resumable downloads are worth having, and is most needed on the
///   failures that would otherwise return silently.
/// - **Checksum failure**: the partial is **discarded**
///   ([`DownloadEvent::PoisonedPartial`]) and [`DownloadError::Checksum`]
///   returned. Those bytes are known-wrong; resuming from them is meaningless.
/// - **Server without `Range` support** (a `200` where a `206` was asked for):
///   the existing prefix is dropped and the transfer restarts from zero, with
///   [`DownloadEvent::RangeUnsupported`] saying so. Appending a whole-file body
///   onto a prefix would corrupt the result and only surface as a checksum
///   failure after another full transfer.
/// - **Stale or mismatched partial** (different URL, different pinned digest,
///   different remote size, missing or unrecognised sidecar): discarded before
///   anything is transferred, with [`DownloadEvent::DiscardedPartial`] naming
///   the check that rejected it.
///
/// # Errors
/// Returns [`DownloadError::Io`] on a read/write failure,
/// [`DownloadError::Transport`] if `open` fails, [`DownloadError::Range`] if the
/// server's answer to a range request is unusable, or
/// [`DownloadError::Checksum`] if the pinned hash does not match.
pub fn download_resumable<R, F, E>(
    dest: &Path,
    url: &str,
    expected_sha256: &str,
    mut open: F,
    mut on_event: E,
) -> Result<(), DownloadError>
where
    R: std::io::Read,
    F: FnMut(u64) -> Result<RangeReply<R>, DownloadError>,
    E: FnMut(DownloadEvent),
{
    let result = download_attempt(dest, url, expected_sha256, &mut open, &mut on_event);
    if result.is_err() {
        // One uniform rule for every failing path, rather than an emission at
        // each `?` (which is how the early returns above the streaming loop —
        // `open` failing outright, the sidecar or the file refusing to be
        // written — came to return silently). Whatever went wrong, bytes still
        // on disk are a resumable prefix and the operator is told so, exactly
        // once. The paths that deliberately destroy the partial (poisoned
        // checksum, an over-long body) have already deleted it, so this reports
        // nothing for them — which is the distinction that matters.
        let kept = existing_len(&partial_path(dest));
        if kept > 0 {
            on_event(DownloadEvent::KeptPartial { bytes: kept });
        }
    }
    result
}

/// One attempt at [`download_resumable`], with no responsibility for announcing a
/// surviving partial — its caller does that uniformly for every failure.
fn download_attempt<R, F, E>(
    dest: &Path,
    url: &str,
    expected_sha256: &str,
    open: &mut F,
    on_event: &mut E,
) -> Result<(), DownloadError>
where
    R: std::io::Read,
    F: FnMut(u64) -> Result<RangeReply<R>, DownloadError>,
    E: FnMut(DownloadEvent),
{
    use sha2::Digest as _;

    let tmp = partial_path(dest);
    let meta_path = partial_meta_path(dest);

    // 1. Decide whether the bytes already on disk are a usable prefix of what we
    //    are about to fetch.
    let (mut resume_from, mut known_total) = plan_resume(dest, url, expected_sha256, on_event)?;

    // 2. A partial that already covers the whole resource needs no transfer at
    //    all — just verification. (A previous run died between the last write
    //    and the rename.)
    if resume_from > 0 && known_total == Some(resume_from) {
        on_event(DownloadEvent::AlreadyComplete { bytes: resume_from });
        let mut hasher = sha2::Sha256::new();
        hash_prefix(&tmp, resume_from, &mut hasher)?;
        return install_verified(dest, expected_sha256, hasher, on_event);
    }

    // 3. Open the transfer, folding any prefix already on disk into the hash.
    let mut hasher = sha2::Sha256::new();
    let (mut reader, append) = start_transfer(
        dest,
        open,
        on_event,
        &mut hasher,
        &mut resume_from,
        &mut known_total,
    )?;

    // 4. Record what this partial is being fetched against *before* writing any
    //    bytes, so even a hard kill leaves a resumable pair.
    write_partial_meta(
        &meta_path,
        &PartialMeta {
            version: PARTIAL_META_VERSION,
            url: url.to_owned(),
            sha256: expected_sha256.to_owned(),
            total: known_total,
        },
    )?;

    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(false)
        .open(&tmp)?;
    if append {
        std::io::Seek::seek(&mut file, std::io::SeekFrom::Start(resume_from))?;
    } else {
        file.set_len(0)?;
    }

    // 5. Stream, hashing as it writes — a multi-gigabyte model never buffers in
    //    memory. A failure here keeps everything on disk for the next attempt.
    let mut sink = HashingWriter {
        inner: std::io::BufWriter::with_capacity(1 << 20, file),
        hasher: &mut hasher,
    };
    let streamed = std::io::copy(&mut reader, &mut sink).map(|_| ());
    // Flush and fsync unconditionally, so the file length on disk is exactly the
    // prefix a later resume will re-hash — even on the failure path.
    let durable = std::io::Write::flush(&mut sink).and_then(|()| sink.inner.get_ref().sync_all());
    drop(sink);

    if let Err(e) = streamed.and(durable) {
        return Err(DownloadError::Io(e));
    }

    // 6. A connection that dies mid-body closes *cleanly* from the reader's point
    //    of view, so `copy` returns `Ok` having transferred less than the whole
    //    file. Without this length check that would be diagnosed as a checksum
    //    failure — which discards the partial, and so would defeat resumption for
    //    the single most common failure mode there is.
    let on_disk = existing_len(&tmp);
    if let Some(total) = known_total {
        if on_disk < total {
            return Err(DownloadError::Io(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                format!("connection closed after {on_disk} of {total} bytes"),
            )));
        }
        if on_disk > total {
            // More bytes than the resource has: the response did not describe
            // what it sent, so nothing on disk can be trusted as a prefix.
            discard_partial(dest)?;
            on_event(DownloadEvent::PoisonedPartial { bytes: on_disk });
            return Err(DownloadError::Range(format!(
                "server sent {on_disk} bytes for a {total}-byte resource"
            )));
        }
    }

    // 7. Verify and install atomically.
    install_verified(dest, expected_sha256, hasher, on_event)
}

/// A local HTTP/1.1 server for the download tests — enough of the protocol to
/// answer `GET` with and without `Range`, and to cut a response short so the
/// resume path is exercised over a real socket instead of a stub.
///
/// Lives outside `mod tests` only because it is shared by the unit tests here
/// and kept beside the code it exercises; it is compiled only under `cfg(test)`.
#[cfg(test)]
mod testserver {
    use std::io::{Read as _, Write as _};
    use std::net::{SocketAddr, TcpListener, TcpStream};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};

    /// What the server should do with the next request.
    pub struct Behaviour {
        /// The resource being served.
        pub body: Vec<u8>,
        /// Whether to honour `Range` (a `206`) or ignore it (a `200`).
        pub ranges: bool,
        /// Write at most this many body bytes, then close — a dropped
        /// connection.
        pub limit: Option<usize>,
    }

    /// One served request: the offset it started at and how many bytes went out.
    pub type Hit = (u64, usize);

    pub struct TestServer {
        pub addr: SocketAddr,
        pub behaviour: Arc<Mutex<Behaviour>>,
        pub hits: Arc<Mutex<Vec<Hit>>>,
        stop: Arc<AtomicBool>,
    }

    impl TestServer {
        pub fn start(behaviour: Behaviour) -> Self {
            let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
            let addr = listener.local_addr().expect("addr");
            let behaviour = Arc::new(Mutex::new(behaviour));
            let hits = Arc::new(Mutex::new(Vec::new()));
            let stop = Arc::new(AtomicBool::new(false));
            {
                let (behaviour, hits, stop) = (behaviour.clone(), hits.clone(), stop.clone());
                std::thread::spawn(move || {
                    for sock in listener.incoming() {
                        if stop.load(Ordering::SeqCst) {
                            break;
                        }
                        if let Ok(sock) = sock {
                            handle(sock, &behaviour, &hits);
                        }
                    }
                });
            }
            Self {
                addr,
                behaviour,
                hits,
                stop,
            }
        }

        /// Requests served so far, oldest first.
        pub fn hits(&self) -> Vec<Hit> {
            self.hits.lock().expect("hits").clone()
        }

        /// Change what the next request gets.
        pub fn set_limit(&self, limit: Option<usize>) {
            self.behaviour.lock().expect("behaviour").limit = limit;
        }
    }

    impl Drop for TestServer {
        fn drop(&mut self) {
            // Unblock the accept loop so the thread exits with the test.
            self.stop.store(true, Ordering::SeqCst);
            let _ = TcpStream::connect(self.addr);
        }
    }

    /// Read the request head, then write the (possibly partial) response.
    fn handle(mut sock: TcpStream, behaviour: &Arc<Mutex<Behaviour>>, hits: &Arc<Mutex<Vec<Hit>>>) {
        let Some(head) = read_head(&mut sock) else {
            return;
        };
        // `Range: bytes=<from>-`
        let requested = head
            .lines()
            .find_map(|l| {
                l.to_ascii_lowercase()
                    .strip_prefix("range:")
                    .map(str::trim)
                    .map(str::to_owned)
            })
            .and_then(|v| v.strip_prefix("bytes=").map(str::to_owned))
            .and_then(|v| v.split('-').next().and_then(|n| n.parse::<u64>().ok()));

        let b = behaviour.lock().expect("behaviour");
        let total = b.body.len();
        let start = match requested {
            Some(from) if b.ranges => usize::try_from(from).expect("offset fits"),
            _ => 0,
        };
        let partial = b.ranges && requested.is_some();
        let remainder = &b.body[start.min(total)..];
        let serve = b.limit.unwrap_or(remainder.len()).min(remainder.len());

        let status_line = if partial {
            format!(
                "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {start}-{}/{total}\r\n",
                total.saturating_sub(1)
            )
        } else {
            "HTTP/1.1 200 OK\r\n".to_owned()
        };
        let accept = if b.ranges {
            "Accept-Ranges: bytes\r\n"
        } else {
            "Accept-Ranges: none\r\n"
        };
        // Content-Length always states the *full* remainder: when `limit` cuts the
        // body short the client sees exactly what a dropped connection looks like.
        let resp = format!(
            "{status_line}{accept}Content-Length: {}\r\nConnection: close\r\n\r\n",
            remainder.len()
        );
        let _ = sock.write_all(resp.as_bytes());
        let _ = sock.write_all(&remainder[..serve]);
        let _ = sock.flush();
        hits.lock()
            .expect("hits")
            .push((u64::try_from(start).unwrap_or(0), serve));
    }

    /// Read bytes until the end of the header block, and no further.
    fn read_head(sock: &mut TcpStream) -> Option<String> {
        let mut buf = Vec::new();
        let mut byte = [0u8; 1];
        while !buf.ends_with(b"\r\n\r\n") {
            match sock.read(&mut byte) {
                Ok(0) | Err(_) => return None,
                Ok(_) => buf.push(byte[0]),
            }
        }
        Some(String::from_utf8_lossy(&buf).into_owned())
    }
}

/// The test-side HTTP client: issues the request and interprets the answer with
/// the real [`interpret_range_response`], so the tests cover that reasoning too.
#[cfg(test)]
fn test_get_range(
    addr: std::net::SocketAddr,
    from: u64,
) -> Result<RangeReply<std::net::TcpStream>, DownloadError> {
    use std::io::{Read as _, Write as _};

    let transport = |e: std::io::Error| DownloadError::Transport(Box::new(e));
    let mut sock = std::net::TcpStream::connect(addr).map_err(transport)?;
    let range = if from > 0 {
        format!("Range: bytes={from}-\r\n")
    } else {
        String::new()
    };
    let req =
        format!("GET /model.bin HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n{range}\r\n");
    sock.write_all(req.as_bytes()).map_err(transport)?;

    // Byte-at-a-time so the socket is left positioned exactly at the body.
    let mut head = Vec::new();
    let mut byte = [0u8; 1];
    while !head.ends_with(b"\r\n\r\n") {
        match sock.read(&mut byte) {
            Ok(0) => return Err(DownloadError::Range("connection closed in headers".into())),
            Ok(_) => head.push(byte[0]),
            Err(e) => return Err(transport(e)),
        }
    }
    let head = String::from_utf8_lossy(&head).into_owned();
    let mut lines = head.lines();
    let status: u16 = lines
        .next()
        .and_then(|l| l.split_whitespace().nth(1).and_then(|s| s.parse().ok()))
        .ok_or_else(|| DownloadError::Range("no status line".into()))?;
    let (mut accept_ranges, mut content_range, mut content_length) = (None, None, None);
    for line in lines {
        let Some((k, v)) = line.split_once(':') else {
            continue;
        };
        let v = v.trim().to_owned();
        match k.trim().to_ascii_lowercase().as_str() {
            "accept-ranges" => accept_ranges = Some(v),
            "content-range" => content_range = Some(v),
            "content-length" => content_length = v.parse().ok(),
            _ => {}
        }
    }
    let (kind, total) = interpret_range_response(
        status,
        accept_ranges.as_deref(),
        content_range.as_deref(),
        content_length,
        from,
    )?;
    Ok(match kind {
        RangeKind::Partial => RangeReply::Partial {
            reader: sock,
            total,
        },
        RangeKind::Full { detail } => RangeReply::Full {
            reader: sock,
            total,
            detail,
        },
    })
}

#[cfg(test)]
mod tests {
    use super::testserver::{Behaviour, TestServer};
    use super::{
        DownloadError, DownloadEvent, ModelKind, Platform, REGISTRY, RangeKind, RangeReply,
        ResourceTier, download_resumable, download_verified, find, installed_size,
        interpret_range_response, partial_meta_path, partial_path, sha256_hex, store_root,
        test_get_range, verify_sha256,
    };
    use std::path::{Path, PathBuf};

    /// A fresh scratch directory per test.
    fn scratch(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("roteiro-dl-{tag}-{}", std::process::id()));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).expect("mkdir");
        dir
    }

    /// Widen a length for comparison against a byte count.
    fn u(n: usize) -> u64 {
        u64::try_from(n).expect("length fits u64")
    }

    /// A deterministic, incompressible-enough payload big enough to be cut in
    /// half meaningfully.
    fn payload(len: usize) -> Vec<u8> {
        (0..len)
            .map(|i| u8::try_from(i % 251).unwrap_or(0))
            .collect()
    }

    /// Run one `download_resumable` attempt against `server`, collecting events.
    fn attempt(
        server: &TestServer,
        dest: &Path,
        sha: &str,
    ) -> (Result<(), DownloadError>, Vec<DownloadEvent>) {
        let addr = server.addr;
        let mut events = Vec::new();
        let url = format!("http://{addr}/model.bin");
        let result = download_resumable(
            dest,
            &url,
            sha,
            |from| test_get_range(addr, from),
            |e| events.push(e),
        );
        (result, events)
    }

    #[test]
    fn resumable_clean_download() {
        let dir = scratch("clean");
        let dest = dir.join("model.bin");
        let body = payload(50_000);
        let sha = sha256_hex(&body);
        let server = TestServer::start(Behaviour {
            body: body.clone(),
            ranges: true,
            limit: None,
        });

        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("clean download");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        // Nothing left behind.
        assert!(!partial_path(&dest).exists());
        assert!(!partial_meta_path(&dest).exists());
        // One request, whole file, from byte zero.
        assert_eq!(server.hits(), vec![(0, 50_000)]);
        assert!(events.is_empty(), "unexpected events: {events:?}");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resumable_interrupted_then_resumed_transfers_only_the_remainder() {
        const CUT: usize = 20_000;
        let dir = scratch("resume");
        let dest = dir.join("model.bin");
        let body = payload(50_000);
        let sha = sha256_hex(&body);
        let server = TestServer::start(Behaviour {
            body: body.clone(),
            ranges: true,
            limit: Some(CUT),
        });

        // First attempt: the connection dies after CUT bytes.
        let (result, events) = attempt(&server, &dest, &sha);
        let err = result.expect_err("interrupted");
        assert!(
            matches!(err, DownloadError::Io(_)),
            "a dropped connection must be an I/O failure, not a checksum one: {err:?}"
        );
        assert_eq!(events, vec![DownloadEvent::KeptPartial { bytes: u(CUT) }]);
        // The partial and its sidecar survive, holding exactly the prefix.
        assert_eq!(
            std::fs::metadata(partial_path(&dest))
                .expect("partial kept")
                .len(),
            u(CUT)
        );
        assert!(partial_meta_path(&dest).exists());
        assert!(!dest.exists());

        // Second attempt against a healthy server.
        server.set_limit(None);
        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("resumed");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        assert_eq!(
            events,
            vec![DownloadEvent::Resuming {
                offset: u(CUT),
                total: Some(50_000),
            }]
        );

        // The point of the exercise: the second request asked for, and received,
        // only the remaining bytes.
        assert_eq!(
            server.hits(),
            vec![(0, CUT), (u(CUT), 50_000 - CUT)],
            "the resumed attempt must transfer only the remainder"
        );
        assert!(!partial_path(&dest).exists());
        assert!(!partial_meta_path(&dest).exists());

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resumable_server_without_range_support_restarts_and_says_so() {
        const CUT: usize = 15_000;
        let dir = scratch("norange");
        let dest = dir.join("model.bin");
        let body = payload(40_000);
        let sha = sha256_hex(&body);
        // `ranges: false` → every response is a 200 with `Accept-Ranges: none`.
        let server = TestServer::start(Behaviour {
            body: body.clone(),
            ranges: false,
            limit: Some(CUT),
        });

        let (result, _) = attempt(&server, &dest, &sha);
        assert!(matches!(result, Err(DownloadError::Io(_))));
        assert_eq!(
            std::fs::metadata(partial_path(&dest)).expect("kept").len(),
            u(CUT)
        );

        // Second attempt: the server ignores Range, so the prefix must be thrown
        // away and the transfer restarted — never appended to.
        server.set_limit(None);
        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("restarted");
        assert_eq!(
            std::fs::read(&dest).expect("installed"),
            body,
            "restarting must not append a whole-file body onto the stale prefix"
        );
        match events.as_slice() {
            [DownloadEvent::RangeUnsupported { discarded, detail }] => {
                assert_eq!(*discarded, u(CUT));
                assert!(
                    detail.contains("200") && detail.to_ascii_lowercase().contains("accept-ranges"),
                    "the message must explain why: {detail}"
                );
            }
            other => panic!("expected a single RangeUnsupported event, got {other:?}"),
        }
        // Second request started at zero and carried the whole file.
        assert_eq!(server.hits(), vec![(0, CUT), (0, 40_000)]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resumable_stale_partial_is_discarded() {
        let dir = scratch("stale");
        let body = payload(30_000);
        let sha = sha256_hex(&body);
        let server = TestServer::start(Behaviour {
            body: body.clone(),
            ranges: true,
            limit: None,
        });

        // (a) A partial with no sidecar at all — anonymous bytes.
        let dest = dir.join("nometa.bin");
        std::fs::write(partial_path(&dest), b"anonymous bytes").expect("write");
        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("re-downloaded");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        assert!(
            matches!(
                events.first(),
                Some(DownloadEvent::DiscardedPartial { bytes: 15, reason }) if reason.contains("sidecar")
            ),
            "{events:?}"
        );

        // (b) A partial whose sidecar records a different pinned checksum.
        let dest = dir.join("othersha.bin");
        std::fs::write(partial_path(&dest), &body[..1000]).expect("write");
        std::fs::write(
            partial_meta_path(&dest),
            format!(
                r#"{{"version":1,"url":"http://{}/model.bin","sha256":"{}","total":30000}}"#,
                server.addr,
                "0".repeat(64)
            ),
        )
        .expect("write meta");
        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("re-downloaded");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        assert!(
            matches!(
                events.first(),
                Some(DownloadEvent::DiscardedPartial { reason, .. }) if reason.contains("checksum")
            ),
            "{events:?}"
        );

        // (c) A partial whose sidecar records a different URL.
        let dest = dir.join("otherurl.bin");
        std::fs::write(partial_path(&dest), &body[..2000]).expect("write");
        std::fs::write(
            partial_meta_path(&dest),
            format!(
                r#"{{"version":1,"url":"http://elsewhere.invalid/model.bin","sha256":"{sha}","total":30000}}"#
            ),
        )
        .expect("write meta");
        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("re-downloaded");
        assert!(
            matches!(
                events.first(),
                Some(DownloadEvent::DiscardedPartial { reason, .. }) if reason.contains("URL")
            ),
            "{events:?}"
        );

        // (d) A partial started against a *different remote size* — only the
        //     server can reveal this, so it is caught on the response.
        let dest = dir.join("othersize.bin");
        std::fs::write(partial_path(&dest), &body[..3000]).expect("write");
        std::fs::write(
            partial_meta_path(&dest),
            format!(
                r#"{{"version":1,"url":"http://{}/model.bin","sha256":"{sha}","total":999999}}"#,
                server.addr
            ),
        )
        .expect("write meta");
        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("re-downloaded");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        assert!(
            matches!(
                events.first(),
                Some(DownloadEvent::DiscardedPartial { reason, .. }) if reason.contains("30000")
            ),
            "{events:?}"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_transport_that_never_opens_still_reports_the_partial_it_kept() {
        let dir = scratch("openfail");
        let dest = dir.join("model.bin");
        let body = payload(30_000);
        let sha = sha256_hex(&body);
        let dead = "http://example.invalid/model.bin";

        // A previous attempt left a valid, resumable prefix.
        std::fs::write(partial_path(&dest), &body[..9_000]).expect("write");
        std::fs::write(
            partial_meta_path(&dest),
            format!(r#"{{"version":1,"url":"{dead}","sha256":"{sha}","total":30000}}"#),
        )
        .expect("write meta");

        // This attempt cannot even reach the server — it fails *before* a single
        // byte moves, which is the path that used to return silently.
        let mut events = Vec::new();
        let result = download_resumable(
            &dest,
            dead,
            &sha,
            |_from| -> Result<RangeReply<std::io::Empty>, DownloadError> {
                Err(DownloadError::Transport("connection refused".into()))
            },
            |e| events.push(e),
        );
        let err = result.expect_err("transport failure");
        assert!(matches!(err, DownloadError::Transport(_)), "{err:?}");

        // The operator must be able to tell "9 KB survived, the next pull is
        // shorter" from "nothing was kept". That distinction is the whole reason
        // resumable downloads are worth having, and this is when it is needed.
        assert_eq!(events, vec![DownloadEvent::KeptPartial { bytes: 9_000 }]);
        assert_eq!(
            std::fs::metadata(partial_path(&dest)).expect("kept").len(),
            9_000,
            "the prefix itself must survive, not merely be announced"
        );
        assert!(partial_meta_path(&dest).exists(), "sidecar survives too");

        // And it really is resumable: a working transport picks up from 9,000.
        let server = TestServer::start(Behaviour {
            body: body.clone(),
            ranges: true,
            limit: None,
        });
        let live = format!("http://{}/model.bin", server.addr);
        std::fs::write(
            partial_meta_path(&dest),
            format!(r#"{{"version":1,"url":"{live}","sha256":"{sha}","total":30000}}"#),
        )
        .expect("rewrite meta");
        let (result, _) = attempt(&server, &dest, &sha);
        result.expect("resumed");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        assert_eq!(server.hits(), vec![(9_000, 21_000)], "only the remainder");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resumable_checksum_failure_discards_the_partial() {
        let dir = scratch("poison");
        let dest = dir.join("model.bin");
        let body = payload(25_000);
        let server = TestServer::start(Behaviour {
            body,
            ranges: true,
            limit: None,
        });

        // Pin a hash the body cannot match: the transfer completes, then fails.
        let (result, events) = attempt(&server, &dest, &"a".repeat(64));
        let err = result.expect_err("checksum mismatch");
        assert!(matches!(err, DownloadError::Checksum { .. }), "{err:?}");
        assert_eq!(
            events,
            vec![DownloadEvent::PoisonedPartial { bytes: 25_000 }]
        );
        // Unlike a dropped connection, poisoned bytes are *not* kept: resuming
        // from them could only reproduce the same bad digest.
        assert!(!partial_path(&dest).exists());
        assert!(!partial_meta_path(&dest).exists());
        assert!(!dest.exists());

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resumable_complete_partial_only_needs_verifying() {
        let dir = scratch("complete");
        let dest = dir.join("model.bin");
        let body = payload(12_345);
        let sha = sha256_hex(&body);
        let server = TestServer::start(Behaviour {
            body: body.clone(),
            ranges: true,
            limit: None,
        });

        // A previous run wrote every byte but died before the rename.
        std::fs::write(partial_path(&dest), &body).expect("write");
        std::fs::write(
            partial_meta_path(&dest),
            format!(
                r#"{{"version":1,"url":"http://{}/model.bin","sha256":"{sha}","total":12345}}"#,
                server.addr
            ),
        )
        .expect("write meta");

        let (result, events) = attempt(&server, &dest, &sha);
        result.expect("installed from the complete partial");
        assert_eq!(std::fs::read(&dest).expect("installed"), body);
        assert_eq!(
            events,
            vec![DownloadEvent::AlreadyComplete { bytes: 12_345 }]
        );
        // Nothing was fetched at all.
        assert!(server.hits().is_empty(), "no request should have been made");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn range_response_interpretation() {
        // A 206 that starts where we asked.
        let (kind, total) =
            interpret_range_response(206, Some("bytes"), Some("bytes 100-499/500"), None, 100)
                .expect("206");
        assert_eq!(kind, RangeKind::Partial);
        assert_eq!(total, Some(500));

        // A 206 with an unknown total (`*`).
        let (_, total) =
            interpret_range_response(206, None, Some("bytes 10-19/*"), None, 10).expect("206 *");
        assert_eq!(total, None);

        // A 206 that resumes somewhere else is a hard error — appending it would
        // silently corrupt the file.
        let err = interpret_range_response(206, None, Some("bytes 0-499/500"), None, 100)
            .expect_err("wrong offset");
        assert!(matches!(err, DownloadError::Range(_)), "{err:?}");

        // A 206 without a Content-Range at all.
        assert!(matches!(
            interpret_range_response(206, None, None, None, 5),
            Err(DownloadError::Range(_))
        ));

        // Unparseable Content-Range.
        assert!(matches!(
            interpret_range_response(206, None, Some("chunks 1-2/3"), None, 1),
            Err(DownloadError::Range(_))
        ));

        // A 200 is a whole-file body, and the detail explains why.
        let (kind, total) =
            interpret_range_response(200, Some("none"), None, Some(500), 100).expect("200");
        match kind {
            RangeKind::Full { detail } => assert!(detail.contains("none"), "{detail}"),
            RangeKind::Partial => panic!("expected Full, got Partial"),
        }
        assert_eq!(total, Some(500));

        // A 200 with no Accept-Ranges header says so.
        let (kind, _) = interpret_range_response(200, None, None, None, 0).expect("200");
        match kind {
            RangeKind::Full { detail } => assert!(detail.contains("no Accept-Ranges"), "{detail}"),
            RangeKind::Partial => panic!("expected Full, got Partial"),
        }

        // Anything else is refused rather than guessed at.
        assert!(matches!(
            interpret_range_response(416, None, None, None, 10),
            Err(DownloadError::Range(_))
        ));
    }

    #[test]
    fn installed_size_and_removal() {
        use super::{model_dir, remove_model, set_model_store};

        // Point the store at a scratch dir for this process. `set_model_store` is
        // first-call-wins, so tolerate another test having set it already.
        // Must still end in `models`: `store_root_resolution` asserts that, and
        // the override is process-wide across the parallel test run.
        let dir = scratch("store");
        set_model_store(dir.join("models"));
        let root = super::store_root();

        let name = "size-probe";
        assert_eq!(installed_size(name), 0, "absent model occupies nothing");

        let mdir = root.join(name);
        std::fs::create_dir_all(&mdir).expect("mkdir");
        std::fs::write(mdir.join("model.gguf"), vec![7u8; 4096]).expect("write");
        std::fs::write(mdir.join("model.partial"), vec![7u8; 1024]).expect("write");
        std::fs::write(mdir.join("model.partial.json"), b"{}").expect("write");
        assert_eq!(model_dir(name), mdir);
        assert_eq!(installed_size(name), 4096 + 1024 + 2);

        let removed = remove_model(name).expect("removed");
        assert_eq!(removed.bytes, 4096 + 1024 + 2);
        assert_eq!(
            removed.files,
            vec!["model.gguf", "model.partial", "model.partial.json"],
            "an orphaned partial is cleaned up with the model"
        );
        assert!(!mdir.exists());

        // Removing again is not an error; it simply frees nothing.
        let again = remove_model(name).expect("idempotent");
        assert_eq!(again.bytes, 0);
        assert!(again.files.is_empty());

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn download_verified_streams_and_checks() {
        // A reader that yields `.0` bytes then errors — to exercise the mid-stream
        // I/O-failure cleanup path.
        struct FailReader(usize);
        impl std::io::Read for FailReader {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                if self.0 == 0 {
                    return Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "boom"));
                }
                let n = buf.len().min(self.0);
                buf[..n].fill(b'x');
                self.0 -= n;
                Ok(n)
            }
        }

        let dir = std::env::temp_dir().join(format!("roteiro-dl-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let payload = b"the streamed model bytes";
        let sha = sha256_hex(payload);

        // Correct hash → file installed with exactly the streamed bytes.
        let good = dir.join("good.bin");
        download_verified(&payload[..], &good, &sha).expect("verified");
        assert_eq!(std::fs::read(&good).expect("read"), payload);

        // Wrong hash → error, and no partial file left behind.
        let bad = dir.join("bad.bin");
        let err = download_verified(&payload[..], &bad, &"0".repeat(64)).unwrap_err();
        assert!(matches!(err, DownloadError::Checksum { .. }));
        assert!(!bad.exists());
        assert!(!bad.with_extension("partial").exists());

        // A read error mid-stream → error, and the partial file is cleaned up.
        let dropped = dir.join("dropped.bin");
        let err = download_verified(FailReader(100), &dropped, "").unwrap_err();
        assert!(matches!(err, DownloadError::Io(_)));
        assert!(!dropped.exists());
        assert!(!dropped.with_extension("partial").exists());

        // Empty (unpinned) hash → installed without verification.
        let unpinned = dir.join("unpinned.bin");
        download_verified(&payload[..], &unpinned, "").expect("unpinned");
        assert!(unpinned.exists());

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn registry_entries_are_well_formed() {
        assert!(!REGISTRY.is_empty());
        for spec in REGISTRY {
            assert!(!spec.name.is_empty());
            // Embedding models carry a dimension; generative models do not.
            assert_eq!(
                spec.dim > 0,
                spec.kind == ModelKind::Embedding,
                "{}",
                spec.name
            );
            assert!(!spec.variants.is_empty());
            // Every model must have a Standard variant so any host resolves.
            assert!(
                spec.variants
                    .iter()
                    .any(|v| v.platform == Platform::Standard),
                "{} needs a Standard variant",
                spec.name,
            );
            let v = spec.variant_for(Platform::host()).expect("host variant");
            assert!(!v.files.is_empty());
            assert!(!spec.tier.as_str().is_empty());
        }
    }

    #[test]
    fn every_section_has_a_low_tier_floor() {
        // The curated matrix must offer a runs-anywhere pick for each section, so
        // `roteiro model list` always has a low-resource recommendation — except
        // Audio: the only curated audio model (Voxtral, transcription-quality) is
        // mid-tier and no low-tier audio pick is offered yet, so the audio section
        // deliberately has no low-tier floor. See the audio registry entry.
        for kind in [
            ModelKind::Embedding,
            ModelKind::Generative,
            ModelKind::Ocr,
            ModelKind::Vision,
        ] {
            assert!(
                REGISTRY
                    .iter()
                    .any(|s| s.kind == kind && s.tier == ResourceTier::Low),
                "section {} needs a Low-tier entry",
                kind.as_str(),
            );
        }
    }

    #[test]
    fn variant_selection_falls_back_to_standard() {
        let spec = find("bge-base-en-v1.5").expect("registered");
        // It only ships a Standard variant, so both hosts resolve to it.
        let mac = spec.variant_for(Platform::MacosArm64).expect("mac");
        let std = spec.variant_for(Platform::Standard).expect("std");
        assert_eq!(mac.platform, Platform::Standard);
        assert_eq!(std.platform, Platform::Standard);
    }

    #[test]
    fn platform_host_is_stable() {
        let p = Platform::host();
        assert!(matches!(p, Platform::MacosArm64 | Platform::Standard));
        assert!(!p.as_str().is_empty());
    }

    #[test]
    fn store_root_resolution() {
        use super::store_root_from;
        use std::path::PathBuf;
        // An explicit model-store dir wins verbatim (config `[paths] model_store`).
        assert_eq!(
            store_root_from(
                Some(PathBuf::from("/data/models")),
                Some(PathBuf::from("/opt/rt")),
                Some(PathBuf::from("/home/u"))
            ),
            Path::new("/data/models"),
        );
        // Else ROTEIRO_HOME's `models` subdir.
        assert_eq!(
            store_root_from(
                None,
                Some(PathBuf::from("/opt/rt")),
                Some(PathBuf::from("/home/u"))
            ),
            Path::new("/opt/rt/models"),
        );
        // Else falls back to <home>/.roteiro/models.
        assert_eq!(
            store_root_from(None, None, Some(PathBuf::from("/home/u"))),
            Path::new("/home/u/.roteiro/models"),
        );
        // The live resolver returns a `models`-suffixed path.
        assert!(store_root().ends_with("models"));
    }

    #[test]
    fn sha256_and_verify() {
        // Known vector: SHA-256("abc").
        let want = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
        assert_eq!(sha256_hex(b"abc"), want);
        assert!(verify_sha256(b"abc", want));
        assert!(verify_sha256(b"abc", &want.to_uppercase()));
        assert!(!verify_sha256(b"abc", "00"));
        // Empty expected = unpinned, always passes.
        assert!(verify_sha256(b"anything", ""));
    }
}