llmman 0.1.689

Run any agent on any model, models stored as OCI images
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
//! Local OCI Image Layout store.
//!
//! Implements a subset of the OCI Image Layout spec
//! (<https://github.com/opencontainers/image-spec/blob/main/image-layout.md>)
//! sufficient for llmman's local operations: build, list, rm, tag, inspect-local.
//!
//! Layout on disk:
//! ```text
//! <store-root>/
//!   oci-layout             {"imageLayoutVersion":"1.0.0"}
//!   manifests-v2/<host>/<repo>/<tag>.json
//!                          one small JSON OCI descriptor per reference,
//!                          pointing at the manifest blob under blobs/.
//!   manifests/<...>/<tag>  legacy per-reference paths, read as a fallback.
//!   blobs/
//!     sha256/
//!       <hex>              one file per blob — config, layers, and each
//!                          manifest's own raw JSON bytes
//! ```

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use anyhow::{anyhow, Context};
use serde::{Deserialize, Serialize};
use sha2::{Digest as Sha2Digest, Sha256};

/// Per-process counter used only to make `OciStore::write_ref`'s temp
/// file name unique across concurrent writers — see there.
static WRITE_REF_COUNTER: AtomicU64 = AtomicU64::new(0);

const MANIFESTS_V2_DIR: &str = "manifests-v2";

// ---------------------------------------------------------------------------
// Minimal OCI spec types (no external crate needed)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Descriptor {
    pub media_type: String,
    pub digest: String,
    pub size: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<std::collections::HashMap<String, String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
    pub schema_version: u32,
    pub media_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_type: Option<String>,
    pub config: Descriptor,
    pub layers: Vec<Descriptor>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<std::collections::HashMap<String, String>>,
}

/// `application/vnd.cncf.model.config.v1+json` — the CNCF Model Format Spec
/// (<https://github.com/modelpack/model-spec>) config document. The
/// deserializing counterpart of what `crate::hf::oci::build_cncf_manifest`
/// writes for HuggingFace/cloud-source pulls; this is the equivalent for
/// `llmman build`'s local-directory packaging path.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CncfConfigDescriptor {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CncfConfigConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CncfModelFs {
    #[serde(rename = "type")]
    pub fs_type: String,
    pub diff_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CncfModelConfig {
    pub descriptor: CncfConfigDescriptor,
    pub config: CncfConfigConfig,
    pub modelfs: CncfModelFs,
}

/// `find`'s "no such reference" error, distinct from a broken store so
/// callers (e.g. `/api/show`) can answer 404 for one and 500 for the other.
#[derive(Debug)]
pub struct NotFound(pub String);

impl std::fmt::Display for NotFound {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "image not found: {}", self.0)
    }
}

impl std::error::Error for NotFound {}

/// A pull the source answered with "no such model" (a registry's 404, a
/// Hugging Face repository that is not there), as opposed to one that failed
/// on the network, on credentials or part way through. The daemon answers it
/// with a 404 instead of a 500.
///
/// Transparent: it displays as the error it wraps and exposes that error's
/// source, so messages are unchanged. It takes the place of the wrapped
/// error's own chain entry, so wrap an error whose head is a message or a
/// context, not a typed error a caller downcasts to.
#[derive(Debug)]
pub struct SourceNotFound {
    cause: anyhow::Error,
}

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

impl std::error::Error for SourceNotFound {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.cause.source()
    }
}

/// `cause`, marked as the source's "no such model".
pub fn source_not_found(cause: anyhow::Error) -> anyhow::Error {
    anyhow::Error::new(SourceNotFound { cause })
}

/// Whether `err`, or anything it wraps, is a [`SourceNotFound`].
pub fn is_source_not_found(err: &anyhow::Error) -> bool {
    err.chain().any(|e| e.is::<SourceNotFound>())
}

/// Summary of a locally stored image shown by `list`.
#[derive(Debug)]
pub struct ImageSummary {
    pub reference: String,
    pub digest: String,
    #[allow(dead_code)]
    pub media_type: String,
    pub size: u64,
    pub modified_at: Option<std::time::SystemTime>,
}

// ---------------------------------------------------------------------------
// OciStore
// ---------------------------------------------------------------------------

pub struct OciStore {
    root: PathBuf,
}

impl OciStore {
    /// Open (or create) an OCI layout store at `root`.
    pub fn open(root: impl AsRef<Path>) -> anyhow::Result<Self> {
        let root = root.as_ref().to_path_buf();
        fs::create_dir_all(&root)?;
        fs::create_dir_all(root.join("blobs").join("sha256"))?;
        fs::create_dir_all(root.join(MANIFESTS_V2_DIR))?;

        // Write oci-layout marker if absent
        let marker = root.join("oci-layout");
        if !marker.exists() {
            fs::write(&marker, r#"{"imageLayoutVersion":"1.0.0"}"#)?;
        }

        Ok(Self { root })
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    // ------------------------------------------------------------------
    // Per-model manifest references
    // ------------------------------------------------------------------
    //
    // Each tagged/pulled/built model gets its own small JSON file (an OCI
    // `Descriptor`) recording which manifest blob it points to — see the
    // module doc comment. `ref_path` derives the file's path directly
    // from the reference, so the common lookup is an O(1) read, no index
    // to scan. `find`/`remove` fall back to a `list_refs` scan through
    // `matching_index` only for a reference spelled differently than it
    // was stored (see `ref_matches_precise`).

    /// The collision-resistant path for a reference's manifest pointer.
    fn ref_path(&self, reference: &str) -> PathBuf {
        manifest_ref_path(&self.root, reference)
    }

    fn legacy_ref_path(&self, reference: &str) -> PathBuf {
        legacy_manifest_ref_path(&self.root, reference)
    }

    fn read_ref_at(&self, path: &Path, reference: &str) -> anyhow::Result<Descriptor> {
        let data = fs::read(path).with_context(|| format!("read manifest ref {reference}"))?;
        serde_json::from_slice(&data).context("parse manifest ref")
    }

    fn read_ref_if_present(
        &self,
        path: &Path,
        reference: &str,
    ) -> anyhow::Result<Option<Descriptor>> {
        match self.read_ref_at(path, reference) {
            Ok(desc) => Ok(Some(desc)),
            Err(err)
                if err.chain().any(|cause| {
                    cause
                        .downcast_ref::<std::io::Error>()
                        .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
                }) =>
            {
                Ok(None)
            }
            Err(err) => Err(err),
        }
    }

    fn read_legacy_ref(&self, reference: &str) -> anyhow::Result<Option<Descriptor>> {
        let path = self.legacy_ref_path(reference);
        match fs::symlink_metadata(&path) {
            Ok(meta) if !meta.is_file() => return Ok(None),
            Ok(_) => {}
            Err(err) if missing_legacy_ref(&err) => return Ok(None),
            Err(err) => {
                return Err(err).with_context(|| format!("inspect manifest ref {reference}"))
            }
        }
        match self.read_ref_if_present(&path, reference) {
            Err(err) if err.chain().any(|cause| cause.is::<serde_json::Error>()) => Ok(None),
            result => result,
        }
    }

    fn write_ref(&self, reference: &str, desc: &Descriptor) -> anyhow::Result<()> {
        let path = self.ref_path(reference);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        // A uniquely-named temp file (pid + a per-process counter), not
        // a fixed one: two concurrent writers of the same reference must
        // not truncate/interleave each other's write. Appended as a
        // suffix, not via `with_extension` (which would eat whatever
        // follows the last '.' in a dotted tag, e.g. ".../0.8b" becoming
        // ".../0.tmp").
        let n = WRITE_REF_COUNTER.fetch_add(1, Ordering::Relaxed);
        let mut tmp = path.clone().into_os_string();
        tmp.push(format!(".{}.{n}.tmp", std::process::id()));
        let tmp = PathBuf::from(tmp);
        if let Err(e) = fs::write(&tmp, serde_json::to_string_pretty(desc)?) {
            let _ = fs::remove_file(&tmp);
            return Err(e.into());
        }
        if let Err(e) = fs::rename(&tmp, &path) {
            let _ = fs::remove_file(&tmp);
            return Err(e.into());
        }
        Ok(())
    }

    fn remove_ref(&self, reference: &str) -> anyhow::Result<bool> {
        let path = self.ref_path(reference);
        let legacy = self.legacy_ref_path(reference);
        // Explicit removal is the only operation allowed to delete an old
        // pointer; normal writes leave the legacy tree untouched. Otherwise
        // an old pointer would resurrect a model immediately after `rm`.
        // Read both candidates before deleting either one, so a filesystem
        // error on the legacy path cannot leave a partially removed ref.
        let remove_new = match self.read_ref_if_present(&path, reference) {
            Ok(desc) => desc
                .as_ref()
                .and_then(stored_ref_name)
                .is_some_and(|stored| same_ref_name(stored, reference)),
            // The current path names exactly one reference, so an
            // unparsable pointer there is its own: let `rm` clear it.
            Err(err) if err.chain().any(|cause| cause.is::<serde_json::Error>()) => true,
            Err(err) => return Err(err),
        };
        let remove_legacy = self
            .read_legacy_ref(reference)?
            .as_ref()
            .and_then(stored_ref_name)
            .is_some_and(|stored| same_ref_name(stored, reference));
        for candidate in [
            remove_new.then_some(&path),
            remove_legacy.then_some(&legacy),
        ]
        .into_iter()
        .flatten()
        {
            fs::remove_file(candidate)
                .with_context(|| format!("remove manifest ref {reference}"))?;
        }
        Ok(remove_new || remove_legacy)
    }

    /// Every stored manifest descriptor, read from current and legacy paths — each
    /// still carries its own reference name in its
    /// `org.opencontainers.image.ref.name` annotation. A single
    /// unreadable or unparsable entry is skipped rather than failing the
    /// whole walk.
    pub(crate) fn list_refs(&self) -> Vec<Descriptor> {
        let mut out = Vec::new();
        collect_refs(&self.root.join(MANIFESTS_V2_DIR), &mut out);
        collect_refs(&self.root.join("manifests"), &mut out);
        dedup_refs(&mut out);
        out
    }

    /// Like [`list_refs`], but aborts on the first unreadable subtree or
    /// unparsable pointer file instead of silently skipping it. Required by
    /// the destructive GC path ([`crate::storage::gc::referenced_digests`]):
    /// a reference dropped by the lossy `list_refs` would make that model's
    /// blobs look unreferenced and get swept, so GC must instead refuse to
    /// run at all when it can't enumerate every surviving reference. A
    /// missing pointer directory (a fresh store) is an empty list.
    pub(crate) fn list_refs_strict(&self) -> anyhow::Result<Vec<Descriptor>> {
        let mut out = Vec::new();
        collect_refs_strict(&self.root.join(MANIFESTS_V2_DIR), &mut out)?;
        collect_refs_strict(&self.root.join("manifests"), &mut out)?;
        Ok(out)
    }

    // ------------------------------------------------------------------
    // Blobs
    // ------------------------------------------------------------------

    pub(crate) fn blob_path(&self, digest: &str) -> anyhow::Result<PathBuf> {
        let (algo, hex) = split_digest(digest)?;
        Ok(self.root.join("blobs").join(algo).join(hex))
    }

    /// Write `data` as a blob.  Returns its `Descriptor`.
    pub fn write_blob(&self, media_type: &str, data: &[u8]) -> anyhow::Result<Descriptor> {
        let hex = hex::encode(Sha256::digest(data));
        let digest = format!("sha256:{}", hex);
        let path = self.root.join("blobs").join("sha256").join(&hex);
        if path.exists() {
            // Reused: refresh its age so a concurrent sweep's grace window
            // covers it until this build's tag lands.
            let _ = fs::OpenOptions::new()
                .write(true)
                .open(&path)
                .and_then(|f| f.set_modified(std::time::SystemTime::now()));
        } else {
            let tmp = path.with_extension("tmp");
            fs::write(&tmp, data)?;
            fs::rename(tmp, &path)?;
        }
        Ok(Descriptor {
            media_type: media_type.into(),
            digest,
            size: data.len() as u64,
            annotations: None,
        })
    }

    /// Write a large file as a blob, streaming to avoid buffering the whole file.
    ///
    /// Delegates to the layout-level writer the pull path uses: the file
    /// is copied and hashed in one pass into a uniquely named temp file,
    /// then renamed into place, and a blob that already exists has its
    /// age refreshed so a concurrent sweep's grace window covers it.
    pub fn write_blob_file(
        &self,
        media_type: &str,
        path: impl AsRef<Path>,
    ) -> anyhow::Result<Descriptor> {
        let desc =
            crate::hf::oci::write_blob_from_file(&self.root, media_type, path.as_ref(), false)?;
        Ok(Descriptor {
            media_type: desc.media_type,
            digest: desc.digest,
            size: u64::try_from(desc.size).context("blob size is negative")?,
            annotations: None,
        })
    }

    /// Read a blob's raw bytes.
    pub fn read_blob(&self, digest: &str) -> anyhow::Result<Vec<u8>> {
        fs::read(self.blob_path(digest)?).with_context(|| format!("read blob {}", digest))
    }

    // ------------------------------------------------------------------
    // Manifest helpers
    // ------------------------------------------------------------------

    pub fn write_manifest(&self, manifest: &Manifest) -> anyhow::Result<Descriptor> {
        let data = serde_json::to_vec(manifest)?;
        self.write_blob("application/vnd.oci.image.manifest.v1+json", &data)
    }

    pub fn read_manifest(&self, digest: &str) -> anyhow::Result<Manifest> {
        let data = self.read_blob(digest)?;
        serde_json::from_slice(&data).context("parse manifest")
    }

    // ------------------------------------------------------------------
    // Tag operations
    // ------------------------------------------------------------------

    /// Records that `reference` now points at `desc`, replacing any prior
    /// entry stored under that exact reference. The full `reference`
    /// string is stored in the annotation so `list` shows it verbatim —
    /// `manifest_ref_path` encodes the name into a portable readable tree;
    /// a tagless reference and its `:latest` spelling share a pointer.
    pub fn tag(&self, mut desc: Descriptor, reference: &str) -> anyhow::Result<()> {
        let mut ann = desc.annotations.take().unwrap_or_default();
        ann.insert(
            "org.opencontainers.image.ref.name".into(),
            reference.to_string(),
        );
        desc.annotations = Some(ann);
        self.write_ref(reference, &desc)
    }

    /// Find the descriptor stored for `reference` — see this type's own
    /// doc comment on the direct pointer path and its fallback
    /// (`matching_index` over every stored reference).
    pub fn find(&self, reference: &str) -> anyhow::Result<Descriptor> {
        let path = self.ref_path(reference);
        for current in [true, false] {
            // A corrupt current pointer is a broken store, not a typo. The
            // old lossy path may hold another name's pointer, a directory,
            // or junk: skip it, and never return it just because the
            // filename happens to match.
            let found = if current {
                self.read_ref_if_present(&path, reference)?
            } else {
                self.read_legacy_ref(reference)?
            };
            let Some(desc) = found else { continue };
            let same_name =
                stored_ref_name(&desc).is_some_and(|stored| same_ref_name(stored, reference));
            match split_ref_digest(reference).1 {
                Some(digest) if !desc.digest.eq_ignore_ascii_case(digest) => {}
                Some(_) | None if same_name => return Ok(desc),
                _ => {}
            }
        }
        let refs = self.list_refs();
        matching_index(&refs, reference)
            .map(|i| refs[i].clone())
            .ok_or_else(|| NotFound(reference.to_string()).into())
    }

    /// The real total size of an image: the sum of its layer sizes, not
    /// `desc.size` (a `Descriptor`'s own `size` field is the *manifest
    /// blob's* size — just a few hundred bytes of JSON — not the image's
    /// actual content size). Falls back to `desc.size` if the manifest
    /// can't be read, so callers still get *something* rather than an
    /// error over what's only ever used for display.
    pub fn total_size(&self, desc: &Descriptor) -> u64 {
        self.read_manifest(&desc.digest)
            .map(|manifest| manifest.layers.iter().map(|l| l.size).sum())
            .unwrap_or(desc.size)
    }

    // ------------------------------------------------------------------
    // List / Remove
    // ------------------------------------------------------------------

    pub fn list(&self) -> anyhow::Result<Vec<ImageSummary>> {
        let refs = self.list_refs();
        Ok(refs
            .into_iter()
            .map(|m| {
                let reference = m
                    .annotations
                    .as_ref()
                    .and_then(|a| a.get("org.opencontainers.image.ref.name"))
                    .cloned()
                    .unwrap_or_else(|| m.digest.clone());
                let modified_at = self
                    .blob_path(&m.digest)
                    .ok()
                    .and_then(|p| fs::metadata(p).ok())
                    .and_then(|meta| meta.modified().ok());
                let size = self.total_size(&m);
                ImageSummary {
                    reference,
                    digest: m.digest,
                    media_type: m.media_type,
                    size,
                    modified_at,
                }
            })
            .collect())
    }

    /// Remove the same single entry `find` would return for `reference`
    /// (see `find`'s own doc comment on its fast path and fallback), and
    /// say which: the stored reference that went, since for a digest
    /// that is a tag the caller did not spell. Two differences from
    /// `find`: the pointer at the reference's own path goes whatever
    /// digest it holds, since a pointer `find` passes over for holding
    /// other content is exactly what `rm` has to be able to take away;
    /// and a digest held by several tags is refused with the tags listed,
    /// the way `docker rmi` refuses an image several tags point at,
    /// unless the reference spells one of them (`m:v9@sha256:…`), rather
    /// than taking whichever the tree is walked to first. A bare
    /// `m@sha256:…` spells no tag here, even though `find` reads it as
    /// `:latest` for a lookup: a removal takes the explicit form. Does not
    /// GC blobs.
    pub fn remove(&self, reference: &str) -> anyhow::Result<String> {
        if self.remove_ref(reference)? {
            return Ok(reference.to_owned());
        }
        let refs = self.list_refs();
        let (base, digest) = split_ref_digest(reference);
        if digest.is_some() {
            // `default_tag` leaves a reference alone only when it already
            // carries a tag: that is the spelled one.
            let spelled = (default_tag(base) == base).then_some(base);
            let held_by: Vec<&str> = refs
                .iter()
                .filter(|m| ref_matches_precise(m, reference))
                .filter_map(stored_ref_name)
                .collect();
            if held_by.len() > 1
                && !held_by
                    .iter()
                    .any(|s| spelled.is_some_and(|t| default_tag(s) == t))
            {
                return Err(anyhow!(
                    "{reference} is held by more than one tag: {}; name the tag to remove",
                    held_by.join(", ")
                ));
            }
        }
        let Some(i) = matching_index(&refs, reference) else {
            return Err(anyhow!("image not found: {}", reference));
        };
        let Some(name) = stored_ref_name(&refs[i]) else {
            return Err(anyhow!("image not found: {}", reference));
        };
        anyhow::ensure!(self.remove_ref(name)?, "image not found: {reference}");
        Ok(name.to_owned())
    }

    // ------------------------------------------------------------------
    // Build helpers
    // ------------------------------------------------------------------

    /// Package all files in `src_dir` as a CNCF Model Format Spec
    /// (<https://github.com/modelpack/model-spec>) OCI artifact stored in
    /// this layout. Each file becomes one uncompressed tar layer, classified
    /// into the appropriate `application/vnd.cncf.model.*` media type by
    /// extension (mirroring [`crate::sources::classify_file`], the
    /// equivalent classifier used when pulling from HuggingFace/cloud
    /// sources), with `org.cncf.model.filepath` recording its path.
    /// With `raw`, each file is instead stored whole as a `*.v1.raw`
    /// layer classified by [`crate::sources::classify_file`], so the layer
    /// digest is the file's own SHA-256, as the pull path produces.
    /// Returns the manifest descriptor.
    pub fn build(
        &self,
        src_dir: impl AsRef<Path>,
        reference: &str,
        labels: &std::collections::HashMap<String, String>,
        raw: bool,
    ) -> anyhow::Result<Descriptor> {
        use walkdir::WalkDir;

        let src_dir = src_dir.as_ref();

        // Canonicalize the source directory so that symlinks, NTFS
        // junctions, and volume mount points all resolve to the real
        // path before any files are walked.  `dunce::canonicalize`
        // avoids the `\\?\` verbatim-path prefix on Windows that would
        // break `strip_prefix` below.
        let canonical_src = dunce::canonicalize(src_dir)
            .with_context(|| format!("canonicalize source dir {}", src_dir.display()))?;

        let mut layers: Vec<Descriptor> = Vec::new();
        let mut format: Option<&'static str> = None;

        // One layer per file (uncompressed tar, or the file itself with raw;
        // filename preserved via annotations)
        for entry in WalkDir::new(&canonical_src).follow_links(true) {
            let entry = entry?;

            // Canonicalize each entry to resolve nested symlinks and
            // detect any that escape the source root.
            let canonical_entry = dunce::canonicalize(entry.path())
                .with_context(|| format!("canonicalize {}", entry.path().display()))?;
            if !canonical_entry.starts_with(&canonical_src) {
                return Err(anyhow!(
                    "path {} resolves to {} which is outside source dir {}",
                    entry.path().display(),
                    canonical_entry.display(),
                    canonical_src.display()
                ));
            }

            if !entry.file_type().is_file() {
                continue;
            }

            let rel = entry
                .path()
                .strip_prefix(&canonical_src)
                .with_context(|| {
                    format!(
                        "strip prefix {:?} from entry {:?}",
                        canonical_src,
                        entry.path()
                    )
                })?
                .to_string_lossy()
                .replace('\\', "/");

            let (media_type, weight_type) = if raw {
                (
                    crate::sources::classify_file(&rel),
                    crate::hf::oci::MEDIA_TYPE_MODEL_WEIGHT_RAW,
                )
            } else {
                (classify_model_layer(&rel), WEIGHT_TAR_MEDIA_TYPE)
            };
            if media_type == weight_type {
                let lower = rel.to_lowercase();
                if lower.ends_with(".gguf") || lower.ends_with(".ggml") {
                    format = Some("gguf");
                } else if lower.ends_with(".safetensors") && format.is_none() {
                    format = Some("safetensors");
                }
            }

            let mut desc = if raw {
                self.write_blob_file(media_type, &canonical_entry)?
            } else {
                // Build a minimal tar with a single entry
                let tar_data = make_single_file_tar(&canonical_entry, &rel)?;
                self.write_blob(media_type, &tar_data)?
            };
            desc.annotations = Some({
                let mut m = std::collections::HashMap::new();
                m.insert("org.cncf.model.filepath".into(), rel.clone());
                m.insert("org.opencontainers.image.title".into(), rel);
                m
            });
            layers.push(desc);
        }

        if layers.is_empty() {
            return Err(anyhow!("no files found in {}", src_dir.display()));
        }

        // `application/vnd.cncf.model.config.v1+json` config. Every layer
        // above is uncompressed (a tar, or the file itself with `raw`), so
        // each layer's DiffID (hash of its uncompressed content) is simply
        // its own digest.
        let cncf_config = CncfModelConfig {
            descriptor: CncfConfigDescriptor {
                created_at: Some(chrono::Utc::now().to_rfc3339()),
            },
            config: CncfConfigConfig {
                format: format.map(str::to_string),
            },
            modelfs: CncfModelFs {
                fs_type: "layers".into(),
                diff_ids: layers.iter().map(|l| l.digest.clone()).collect(),
            },
        };
        let config_data = serde_json::to_vec(&cncf_config)?;
        let config_desc =
            self.write_blob("application/vnd.cncf.model.config.v1+json", &config_data)?;

        // `--label key=value` pairs have no dedicated slot in the model
        // config schema, so they're carried as manifest annotations instead.
        let manifest_annotations = if labels.is_empty() {
            None
        } else {
            Some(labels.clone())
        };

        // Manifest
        let manifest = Manifest {
            schema_version: 2,
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            artifact_type: Some("application/vnd.cncf.model.manifest.v1+json".into()),
            config: config_desc,
            layers,
            annotations: manifest_annotations,
        };
        let manifest_desc = self.write_manifest(&manifest)?;
        self.tag(manifest_desc.clone(), reference)?;
        Ok(manifest_desc)
    }
}

// ---------------------------------------------------------------------------
// CNCF Model Format Spec layer classification
// ---------------------------------------------------------------------------

const WEIGHT_TAR_MEDIA_TYPE: &str = "application/vnd.cncf.model.weight.v1.tar";
const WEIGHT_CONFIG_TAR_MEDIA_TYPE: &str = "application/vnd.cncf.model.weight.config.v1.tar";
const DOC_TAR_MEDIA_TYPE: &str = "application/vnd.cncf.model.doc.v1.tar";
const CODE_TAR_MEDIA_TYPE: &str = "application/vnd.cncf.model.code.v1.tar";

/// Maps a file's relative path to the appropriate CNCF model layer media
/// type by extension, mirroring [`crate::sources::classify_file`] (used for
/// HuggingFace/cloud-source pulls). Uses the `.tar` variants because
/// `build()` wraps each file in its own uncompressed tar archive, rather
/// than the `.raw` variants a pulled, un-archived blob gets.
fn classify_model_layer(rel_path: &str) -> &'static str {
    let lower = rel_path.to_lowercase();
    let base = Path::new(&lower)
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(lower.as_str());
    let ext = Path::new(base)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");

    match ext {
        "safetensors" | "bin" | "pt" | "pth" | "gguf" | "ggml" | "ot" | "engine" | "trt"
        | "onnx" => WEIGHT_TAR_MEDIA_TYPE,
        // "jinja": a standalone chat_template.jinja file.
        "json" | "yaml" | "yml" | "toml" | "ini" | "cfg" | "conf" | "model" | "tiktoken"
        | "vocab" | "merges" | "spm" | "jinja" => WEIGHT_CONFIG_TAR_MEDIA_TYPE,
        "txt" => {
            if base.contains("vocab") || base.contains("merges") {
                WEIGHT_CONFIG_TAR_MEDIA_TYPE
            } else {
                DOC_TAR_MEDIA_TYPE
            }
        }
        "py" | "sh" | "js" | "ts" => CODE_TAR_MEDIA_TYPE,
        "md" | "rst" | "pdf" => DOC_TAR_MEDIA_TYPE,
        _ => {
            // README, LICENSE, and anything unrecognized default to doc,
            // same as the Go classifier's fallback.
            DOC_TAR_MEDIA_TYPE
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// True if the descriptor's ref annotation matches `reference` precisely
/// — exact match, tag-only match (a bare `reference` against a stored
/// `"reg/repo:tag"`), tagless match (`reference` with an implicit
/// `:latest` appended), or, for a `reference` carrying `@<digest>`, a
/// digest match (the branch below says what that compares). The tag-only
/// branch is unambiguous only when `reference` is a bare tag that's
/// unique across stored tags — two different repos sharing the same tag
/// (e.g. both `:0.8b`) can still both match here. A digest match is
/// ambiguous across the tags of one repository in the same way, and
/// `matching_index` is what settles that.
fn ref_matches_precise(desc: &Descriptor, reference: &str) -> bool {
    let Some(stored) = stored_ref_name(desc) else {
        return false;
    };

    // `<name>[:tag]@<digest>` names content, not a tag: it matches the
    // stored model with that manifest digest under the same repository,
    // whatever tag it was stored under. Without this a digest reference
    // for a model already in the store was "not found", and the daemon
    // pulled the same bytes again under a second reference and started a
    // second server for them. The hex is compared without regard to case
    // because `shortnames::validate_reference` accepts either while the
    // store records lowercase, so an uppercase spelling matched nothing.
    // Unlike the tag branches below, this one has no tag-only fallback: a
    // bare `m@sha256:…` against a stored `docker.io/ai/m:v9` misses on the
    // repository. Latent today, since each caller resolves a reference
    // through `shortnames::resolve_ollama_api` before it gets here.
    if let (base, Some(digest)) = split_ref_digest(reference) {
        return desc.digest.eq_ignore_ascii_case(digest) && repo_name(stored) == repo_name(base);
    }

    if stored == reference || tag_from_ref(stored) == reference {
        return true;
    }
    // `default_tag` also guards non-taggable sources (URI schemes, absolute
    // paths), so this can't accidentally match one of those against some
    // unrelated stored `"...:latest"`.
    if stored == default_tag(reference) {
        return true;
    }
    false
}

/// Splits `<name>[:tag]@<digest>` into the part before `@` and the digest.
/// The `@` has to follow the last `/`, so a host or namespace component
/// cannot be mistaken for one; a reference without a digest comes back
/// whole. `shortnames::parse_registry_ref` splits at the first `@`
/// instead; the two agree on any reference it has accepted, since no
/// part before the model admits an `@`. This one is also applied to
/// stored names, which reach `ref_matches_precise` from the annotation
/// and not through that parser.
pub fn split_ref_digest(reference: &str) -> (&str, Option<&str>) {
    // The same guard as `default_tag`: an absolute path or a URI is
    // opaque to `shortnames::validate_reference`, so an `@` in its last
    // component is part of the name, not a digest, and splitting it
    // would let `s3://bucket/model@sha256:…` resolve to a stored
    // `s3://bucket/model` of that digest instead of importing the key.
    if reference.starts_with('/') || reference.contains("://") {
        return (reference, None);
    }
    let last_slash = reference.rfind('/').map_or(0, |i| i + 1);
    match reference[last_slash..].find('@') {
        Some(offset) => {
            let at = last_slash + offset;
            (&reference[..at], Some(&reference[at + 1..]))
        }
        None => (reference, None),
    }
}

/// The repository part of a reference: everything before a tag or digest,
/// so `docker.io/ai/m:v9`, `docker.io/ai/m` and `docker.io/ai/m@sha256:…`
/// all give `docker.io/ai/m`. The tag is cut by the rule
/// manifest references use, a `:` after the last `/`, so
/// a host port stays.
pub fn repo_name(reference: &str) -> &str {
    let (base, _) = split_ref_digest(reference);
    let last_slash = base.rfind('/').map_or(0, |i| i + 1);
    match base[last_slash..].find(':') {
        Some(offset) => &base[..last_slash + offset],
        None => base,
    }
}

/// The index of the entry in `manifests` that `find`/`remove` should
/// treat as matching `reference`, or `None`.
///
/// One manifest can sit under several tags, so a digest reference can
/// match more than one entry. The tag the reference spells (`:latest`
/// when it spells none) wins: `m:v9@<digest>` with `m:v9` and `m:latest`
/// both at that digest picks `m:v9`, and a stored name with no tag
/// counts as `:latest`, as it does everywhere else in this store.
/// Between tags it does not spell, the first in the order `list_refs`
/// walks the tree wins, which is readdir order and not sorted; `remove`
/// refuses that case rather than take one (see its doc comment), `find`
/// answers with it.
fn matching_index(manifests: &[Descriptor], reference: &str) -> Option<usize> {
    let (base, digest) = split_ref_digest(reference);
    if digest.is_some() {
        let spelled = default_tag(base);
        let own_tag = manifests.iter().position(|m| {
            ref_matches_precise(m, reference)
                && stored_ref_name(m).is_some_and(|stored| default_tag(stored) == spelled)
        });
        if own_tag.is_some() {
            return own_tag;
        }
    }
    manifests
        .iter()
        .position(|m| ref_matches_precise(m, reference))
}

fn stored_ref_name(desc: &Descriptor) -> Option<&str> {
    desc.annotations
        .as_ref()
        .and_then(|a| a.get("org.opencontainers.image.ref.name"))
        .map(|s| s.as_str())
}

fn dedup_refs(refs: &mut Vec<Descriptor>) {
    let mut seen = HashSet::new();
    refs.retain(|desc| {
        stored_ref_name(desc)
            .map(|name| seen.insert(default_tag(name)))
            .unwrap_or(true)
    });
}

fn same_ref_name(stored: &str, requested: &str) -> bool {
    default_tag(stored) == default_tag(requested)
}

pub(crate) fn manifest_ref_path(root: &Path, reference: &str) -> PathBuf {
    let key = default_tag(reference);
    let opaque = reference.starts_with('/') || reference.contains("://");
    let mut path = root.join(MANIFESTS_V2_DIR);
    if opaque {
        // `~` cannot be emitted by escape_ref_segment, so opaque names cannot
        // collide with a registry named "~" or with its ordinary repo tree.
        path.push("~");
    }
    let (name, tag) = if opaque {
        key.rsplit_once('/')
            .map_or(("", key.as_str()), |(name, tag)| (name, tag))
    } else {
        let pos = key
            .rfind(':')
            .expect("canonical registry reference has a tag");
        (&key[..pos], &key[pos + 1..])
    };
    if !name.is_empty() || opaque {
        for segment in name.split('/') {
            push_ref_segment(&mut path, segment, true);
        }
    }
    push_ref_segment(&mut path, tag, false);
    path
}

// Percent encoding can triple a long uppercase component. Keep each filesystem
// component below common 255-byte limits without losing any source bytes.
// `~` and `~~` are reserved markers: ordinary escaped names cannot emit them.
fn push_ref_segment(path: &mut PathBuf, segment: &str, directory: bool) {
    let encoded = escape_ref_segment(segment, directory);
    if encoded.len() <= 200 {
        path.push(if directory {
            encoded
        } else {
            format!("{encoded}.json")
        });
    } else {
        for chunk in encoded.as_bytes().chunks(180) {
            let chunk = std::str::from_utf8(chunk).expect("escaped ASCII");
            path.push(format!("~{}", escape_chunk_trailing_dot(chunk)));
        }
        path.push(if directory { "~~" } else { "~~.json" });
    }
}

fn escape_chunk_trailing_dot(chunk: &str) -> String {
    chunk
        .strip_suffix('.')
        .map_or_else(|| chunk.to_owned(), |rest| format!("{rest}%2E"))
}

/// Percent-escape unsafe bytes and uppercase letters so paths stay distinct
/// even on case-insensitive filesystems. A repo component may never end in
/// `.json`: pointer files do, preventing file-as-ancestor collisions.
fn escape_ref_segment(segment: &str, directory: bool) -> String {
    if segment.is_empty() {
        return "~".to_owned();
    }
    let reserved = matches!(
        segment
            .split('.')
            .next()
            .unwrap_or("")
            .to_ascii_lowercase()
            .as_str(),
        "con"
            | "prn"
            | "aux"
            | "nul"
            | "com1"
            | "com2"
            | "com3"
            | "com4"
            | "com5"
            | "com6"
            | "com7"
            | "com8"
            | "com9"
            | "lpt1"
            | "lpt2"
            | "lpt3"
            | "lpt4"
            | "lpt5"
            | "lpt6"
            | "lpt7"
            | "lpt8"
            | "lpt9"
    );
    let mut out = String::new();
    for (i, byte) in segment.bytes().enumerate() {
        let safe = byte.is_ascii_lowercase()
            || byte.is_ascii_digit()
            || matches!(byte, b'-' | b'_' | b'.');
        if safe && !(reserved && i == 0) && !(matches!(segment, "." | "..") && byte == b'.') {
            out.push(byte as char);
        } else {
            out.push_str(&format!("%{byte:02X}"));
        }
    }
    if directory && (out.ends_with(".json") || out.ends_with('.')) {
        let dot = out.rfind('.').expect("suffix contains a dot");
        out.replace_range(dot..=dot, "%2E");
    }
    out
}

pub(crate) fn legacy_manifest_ref_path(root: &Path, reference: &str) -> PathBuf {
    let mut path = root.join("manifests");
    for segment in legacy_ref_path_segments(reference) {
        path.push(segment);
    }
    path
}

pub(crate) fn missing_legacy_ref(err: &std::io::Error) -> bool {
    if matches!(
        err.kind(),
        std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
    ) {
        return true;
    }
    #[cfg(unix)]
    if err.raw_os_error() == Some(libc::ENAMETOOLONG) {
        return true;
    }
    #[cfg(windows)]
    if err.raw_os_error() == Some(206) {
        return true; // ERROR_FILENAME_EXCED_RANGE
    }
    false
}

fn legacy_ref_path_segments(reference: &str) -> Vec<String> {
    let tagged = default_tag(reference);
    let (name, tag): (&str, &str) = match tagged.rfind(':') {
        Some(pos) if pos > tagged.rfind('/').unwrap_or(0) => (&tagged[..pos], &tagged[pos + 1..]),
        _ => (tagged.as_str(), "latest"),
    };
    name.split('/')
        .filter(|s| !s.is_empty())
        .map(legacy_sanitize_ref_segment)
        .chain(std::iter::once(legacy_sanitize_ref_segment(tag)))
        .collect()
}

/// The pre-fix mapper, needed only to locate already-written pointers.
fn legacy_sanitize_ref_segment(s: &str) -> String {
    if s.is_empty() || s == "." || s == ".." {
        return "__".to_string();
    }
    s.replace([':', '\\'], "_")
}

/// Recursively collects every manifest-pointer file under `dir` into
/// `out` — see `OciStore::list_refs`.
fn collect_refs(dir: &Path, out: &mut Vec<Descriptor>) {
    let Ok(entries) = fs::read_dir(dir) else {
        return; // an unreadable subtree must not hide every other model
    };
    for entry in entries {
        let Ok(entry) = entry else { continue };
        let path = entry.path();
        let Ok(file_type) = entry.file_type() else {
            continue;
        };
        if file_type.is_dir() {
            collect_refs(&path, out);
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
            continue; // an in-progress or abandoned write — see write_ref
        }
        let Ok(data) = fs::read(&path) else { continue };
        if let Ok(desc) = serde_json::from_slice::<Descriptor>(&data) {
            out.push(desc);
        }
    }
}

/// Strict counterpart to [`collect_refs`] for the GC path: any error that
/// `collect_refs` would swallow (an unreadable directory, an unreadable or
/// unparsable pointer file) is propagated instead, so an incomplete
/// enumeration can never be mistaken for "these blobs are unreferenced". A
/// non-existent `dir` (a store with no `manifests/` yet) is treated as
/// empty — that's a genuinely empty reference set, not a read failure.
fn collect_refs_strict(dir: &Path, out: &mut Vec<Descriptor>) -> anyhow::Result<()> {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e).with_context(|| format!("read {}", dir.display())),
    };
    for entry in entries {
        let entry = entry.with_context(|| format!("read entry in {}", dir.display()))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .with_context(|| format!("stat {}", path.display()))?;
        if file_type.is_dir() {
            collect_refs_strict(&path, out)?;
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
            continue; // an in-progress or abandoned write — see write_ref
        }
        let data = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
        let desc = serde_json::from_slice::<Descriptor>(&data)
            .with_context(|| format!("parse manifest ref {}", path.display()))?;
        out.push(desc);
    }
    Ok(())
}

/// reference and its `:latest` spelling are one string wherever a
/// reference is used as a map/lock key. A no-op on anything that isn't a
/// taggable registry reference — a URI-scheme source (`s3://`, `ngc://`,
/// `ms://`, ...) or an absolute local path — since those never carry a
/// tag and appending one would corrupt them.
pub fn default_tag(reference: &str) -> String {
    if reference.starts_with('/') || reference.contains("://") {
        return reference.to_owned();
    }
    let after_slash = &reference[reference.rfind('/').unwrap_or(0)..];
    if after_slash.contains(':') {
        reference.to_owned()
    } else {
        format!("{reference}:latest")
    }
}

/// Splits `algo:hex` and accepts only the shape this store writes:
/// `sha256` and 64 ASCII hex digits. The hex becomes a path component
/// under `blobs/`, and digests arrive from manifests that are themselves
/// blobs, so anything else (`/dev/zero`, `..`) is refused here rather
/// than joined onto the store root.
pub(crate) fn split_digest(digest: &str) -> anyhow::Result<(&str, &str)> {
    match digest.split_once(':') {
        Some((algo @ "sha256", hex))
            if hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()) =>
        {
            Ok((algo, hex))
        }
        _ => Err(anyhow!("invalid digest: {}", digest)),
    }
}

pub fn tag_from_ref(reference: &str) -> &str {
    if let Some(pos) = reference.rfind(':') {
        if pos > reference.rfind('/').unwrap_or(0) {
            return &reference[pos + 1..];
        }
    }
    "latest"
}

/// Build an in-memory uncompressed tar archive containing a single file.
fn make_single_file_tar(path: &Path, name: &str) -> anyhow::Result<Vec<u8>> {
    let file_data = fs::read(path).with_context(|| format!("read {}", path.display()))?;
    let mut buf = Vec::new();
    {
        let mut archive = tar::Builder::new(&mut buf);
        let mut header = tar::Header::new_gnu();
        header.set_path(name)?;
        header.set_size(file_data.len() as u64);
        header.set_mode(0o644);
        header.set_cksum();
        archive.append(&header, file_data.as_slice())?;
        archive.finish()?;
    }
    Ok(buf)
}

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

    /// A marked error prints, and exposes its sources, as the original did.
    #[test]
    fn source_not_found_is_transparent() {
        use crate::hf::client::HttpStatusError;
        use anyhow::Context as _;

        let plain = || {
            Err::<(), _>(HttpStatusError::new(
                "GET https://huggingface.co/api/models/x/y",
                401,
                &reqwest::header::HeaderMap::new(),
            ))
            .context("HF model info")
            .unwrap_err()
        };
        let marked = source_not_found(plain());

        assert!(is_source_not_found(&marked));
        assert!(!is_source_not_found(&plain()));
        assert_eq!(marked.to_string(), plain().to_string());
        assert_eq!(format!("{marked:#}"), format!("{:#}", plain()));
        assert_eq!(
            marked.chain().count(),
            plain().chain().count(),
            "the marker takes the place of its cause's own link"
        );
        // A retry loop's downcast still reaches the inner error.
        assert!(crate::hf::client::is_permanent(&marked));

        // Further context on top does not hide it.
        let wrapped = marked.context("pull failed");
        assert!(is_source_not_found(&wrapped));
        assert_eq!(
            format!("{wrapped:#}"),
            "pull failed: HF model info: GET https://huggingface.co/api/models/x/y: HTTP 401"
        );
    }

    fn desc_with_ref(ref_name: &str) -> Descriptor {
        let mut ann = std::collections::HashMap::new();
        ann.insert(
            "org.opencontainers.image.ref.name".to_string(),
            ref_name.to_string(),
        );
        Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:deadbeef".into(),
            size: 123,
            annotations: Some(ann),
        }
    }

    /// The docker/containerd backend's own writer (go-shim/manifest_ref.go's
    /// writeManifestRef) always stores the full reference it was called with.
    #[test]
    fn ref_matches_precise_a_full_reference_stored_verbatim() {
        let d = desc_with_ref("docker.io/ai/qwen3.5:0.8b");
        assert!(ref_matches_precise(&d, "docker.io/ai/qwen3.5:0.8b"));
        assert!(!ref_matches_precise(&d, "docker.io/ai/qwen3.5:1.5b"));
        assert!(!ref_matches_precise(&d, "docker.io/ai/other:0.8b"));
    }

    /// Pins the digest branch of `ref_matches_precise` (see its own
    /// comment for why it exists): same digest and same repository match
    /// regardless of tag, and a different digest or repository does not.
    #[test]
    fn ref_matches_precise_resolves_a_digest_reference_by_content() {
        let mut d = desc_with_ref("docker.io/ai/m:v9");
        d.digest = "sha256:aaaa".into();
        assert!(ref_matches_precise(&d, "docker.io/ai/m@sha256:aaaa"));
        assert!(ref_matches_precise(&d, "docker.io/ai/m:latest@sha256:aaaa"));
        assert!(!ref_matches_precise(&d, "docker.io/ai/m@sha256:bbbb"));
        assert!(!ref_matches_precise(&d, "docker.io/ai/other@sha256:aaaa"));
        // A tag beside the digest does not narrow the match: the grammar
        // in docker/distribution's `reference.go` allows both, and there
        // the digest is what names content. `matching_index` is where the
        // tag counts, as a tie-breaker.
        assert!(ref_matches_precise(&d, "docker.io/ai/m:other@sha256:aaaa"));
        assert!(ref_matches_precise(&d, "docker.io/ai/m@sha256:AAAA"));
    }

    /// Two tags at one digest: the spelled tag is chosen, and without one
    /// the first entry is. See `matching_index`'s doc comment.
    #[test]
    fn matching_index_prefers_the_tag_a_digest_reference_spells() {
        let mut latest = desc_with_ref("docker.io/ai/m:latest");
        latest.digest = "sha256:aaaa".into();
        let mut v9 = desc_with_ref("docker.io/ai/m:v9");
        v9.digest = "sha256:aaaa".into();
        let manifests = [latest, v9];
        assert_eq!(
            matching_index(&manifests, "docker.io/ai/m:v9@sha256:aaaa"),
            Some(1)
        );
        assert_eq!(
            matching_index(&manifests, "docker.io/ai/m@sha256:aaaa"),
            Some(0)
        );
        assert_eq!(
            matching_index(&manifests, "docker.io/ai/m:v8@sha256:aaaa"),
            Some(0)
        );
        assert_eq!(
            matching_index(&manifests, "docker.io/ai/m@sha256:bbbb"),
            None
        );

        // A tagless stored name is `:latest` here too, ahead of `:v9`
        // whatever order the tree is walked in.
        let mut tagless = desc_with_ref("docker.io/ai/m");
        tagless.digest = "sha256:aaaa".into();
        let mut v9 = desc_with_ref("docker.io/ai/m:v9");
        v9.digest = "sha256:aaaa".into();
        assert_eq!(
            matching_index(&[v9, tagless], "docker.io/ai/m@sha256:aaaa"),
            Some(1)
        );
    }

    #[test]
    fn split_ref_digest_only_splits_after_the_last_slash() {
        assert_eq!(
            split_ref_digest("docker.io/ai/m@sha256:aa"),
            ("docker.io/ai/m", Some("sha256:aa"))
        );
        assert_eq!(
            split_ref_digest("docker.io/ai/m:v9@sha256:aa"),
            ("docker.io/ai/m:v9", Some("sha256:aa"))
        );
        assert_eq!(
            split_ref_digest("docker.io/ai/m:v9"),
            ("docker.io/ai/m:v9", None)
        );
        // Opaque sources keep their `@`, as `default_tag` keeps their `:`.
        assert_eq!(
            split_ref_digest("s3://bucket/model@sha256:aa"),
            ("s3://bucket/model@sha256:aa", None)
        );
        assert_eq!(
            split_ref_digest("/models/m@sha256:aa"),
            ("/models/m@sha256:aa", None)
        );
        assert_eq!(repo_name("docker.io/ai/m:v9@sha256:aa"), "docker.io/ai/m");
        assert_eq!(repo_name("localhost:5000/m"), "localhost:5000/m");
        assert_eq!(repo_name("localhost:5000/m:v1"), "localhost:5000/m");
    }

    /// A pointer at a digest-shaped path that holds another digest is not
    /// what a lookup by that digest gets; the content decides, and the
    /// pointer itself can still be removed by name.
    #[test]
    fn find_passes_over_a_digest_named_pointer_holding_other_content() {
        let dir = temp_store_dir("digest-pointer");
        let store = OciStore::open(&dir).unwrap();
        let mut lying = desc_with_ref("unused");
        lying.digest = "sha256:aaaa".into();
        store.tag(lying, "docker.io/ai/m@sha256:bbbb").unwrap();

        assert!(store.find("docker.io/ai/m@sha256:bbbb").is_err());
        assert_eq!(
            store.find("docker.io/ai/m@sha256:aaaa").unwrap().digest,
            "sha256:aaaa",
            "by content, the pointer is the entry for the digest it holds"
        );
        let mut real = desc_with_ref("unused");
        real.digest = "sha256:bbbb".into();
        store.tag(real, "docker.io/ai/m:v9").unwrap();
        assert_eq!(
            store
                .find("docker.io/ai/m@sha256:bbbb")
                .unwrap()
                .annotations
                .unwrap()["org.opencontainers.image.ref.name"],
            "docker.io/ai/m:v9"
        );
        store.remove("docker.io/ai/m@sha256:bbbb").unwrap();
        assert!(store.find("docker.io/ai/m@sha256:aaaa").is_err());
        assert!(store.find("docker.io/ai/m:v9").is_ok());

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

    /// A digest held by several tags: the removal is refused with every
    /// holder listed, a bare `m@sha256:…` included even with `:latest`
    /// among them, unless the reference spells one of the tags; then that
    /// one goes and is named. Nothing goes in readdir order.
    #[test]
    fn remove_by_digest_names_what_went_and_refuses_an_ambiguous_one() {
        let dir = temp_store_dir("digest-remove");
        let store = OciStore::open(&dir).unwrap();
        let desc = |digest: &str| {
            let mut d = desc_with_ref("unused");
            d.digest = digest.into();
            d
        };
        store.tag(desc("sha256:aaaa"), "docker.io/ai/m:v8").unwrap();
        store.tag(desc("sha256:aaaa"), "docker.io/ai/m:v9").unwrap();
        store
            .tag(desc("sha256:aaaa"), "docker.io/ai/m:latest")
            .unwrap();

        let err = store.remove("docker.io/ai/m@sha256:aaaa").unwrap_err();
        let msg = err.to_string();
        assert!(
            [
                "docker.io/ai/m:v8",
                "docker.io/ai/m:v9",
                "docker.io/ai/m:latest"
            ]
            .iter()
            .all(|t| msg.contains(t)),
            "{msg}"
        );
        assert!(store.find("docker.io/ai/m:latest").is_ok());

        assert_eq!(
            store.remove("docker.io/ai/m:latest@sha256:aaaa").unwrap(),
            "docker.io/ai/m:latest"
        );
        assert_eq!(
            store.remove("docker.io/ai/m:v9@sha256:aaaa").unwrap(),
            "docker.io/ai/m:v9"
        );
        assert_eq!(
            store.remove("docker.io/ai/m@sha256:aaaa").unwrap(),
            "docker.io/ai/m:v8",
            "one holder left is not ambiguous, and the name that went is reported"
        );
        assert!(store.remove("docker.io/ai/m@sha256:aaaa").is_err());

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

    /// Same branch through `find`: stored under a tag, looked up by digest.
    #[test]
    fn find_resolves_a_digest_reference_to_the_tagged_entry() {
        let dir = temp_store_dir("digest-find");
        let store = OciStore::open(&dir).unwrap();
        let mut d = desc_with_ref("unused");
        d.digest = "sha256:cafe".into();
        store.tag(d, "docker.io/ai/m:latest").unwrap();

        let found = store.find("docker.io/ai/m@sha256:cafe").unwrap();
        assert_eq!(
            found.annotations.unwrap()["org.opencontainers.image.ref.name"],
            "docker.io/ai/m:latest"
        );
        assert!(store.find("docker.io/ai/m@sha256:dead").is_err());

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

    #[test]
    fn ref_matches_precise_defaults_a_tagless_reference_to_latest() {
        let d = desc_with_ref("docker.io/ai/qwen3.5:latest");
        assert!(ref_matches_precise(&d, "docker.io/ai/qwen3.5"));
    }

    #[test]
    fn default_tag_appends_latest_only_when_no_tag_is_present() {
        assert_eq!(
            default_tag("docker.io/ai/gemma4"),
            "docker.io/ai/gemma4:latest"
        );
        assert_eq!(
            default_tag("docker.io/ai/gemma4:latest"),
            "docker.io/ai/gemma4:latest"
        );
        assert_eq!(
            default_tag("docker.io/ai/gemma4:e4b"),
            "docker.io/ai/gemma4:e4b"
        );
        // A colon before the last '/' (a port in a registry host) must not
        // be mistaken for a tag separator.
        assert_eq!(
            default_tag("localhost:5000/gemma4"),
            "localhost:5000/gemma4:latest"
        );
    }

    #[test]
    fn default_tag_leaves_non_registry_sources_untouched() {
        // These never carry a tag; appending one would corrupt them.
        assert_eq!(default_tag("ngc://org/model"), "ngc://org/model");
        assert_eq!(default_tag("s3://bucket/key"), "s3://bucket/key");
        assert_eq!(default_tag("gs://bucket/key"), "gs://bucket/key");
        assert_eq!(default_tag("ms://owner/repo"), "ms://owner/repo");
        assert_eq!(default_tag("/abs/path/model.gguf"), "/abs/path/model.gguf");
    }

    #[test]
    fn ref_matches_precise_returns_false_without_a_ref_name_annotation() {
        let d = Descriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:deadbeef".into(),
            size: 123,
            annotations: None,
        };
        assert!(!ref_matches_precise(&d, "docker.io/ai/qwen3.5:0.8b"));
    }

    /// An unrelated model stored under a bare "latest" tag must not
    /// hijack a precisely-matching tagless reference (which also
    /// defaults to "latest").
    #[test]
    fn matching_index_prefers_a_precise_match_over_an_unrelated_bare_latest() {
        let unrelated_bare_latest = desc_with_ref("latest");
        let inferact = desc_with_ref("hf.co/Inferact/Qwen3.8-27B-NVFP4:latest");
        let manifests = vec![unrelated_bare_latest, inferact.clone()];

        let i = matching_index(&manifests, "hf.co/Inferact/Qwen3.8-27B-NVFP4")
            .expect("must find a match");
        assert_eq!(manifests[i].digest, inferact.digest);

        let i = matching_index(&manifests, "hf.co/Inferact/Qwen3.8-27B-NVFP4:latest")
            .expect("must find a match");
        assert_eq!(manifests[i].digest, inferact.digest);
    }

    #[test]
    fn tag_from_ref_extracts_the_tag_after_the_last_slash() {
        assert_eq!(tag_from_ref("docker.io/ai/qwen3.5:0.8b"), "0.8b");
        assert_eq!(tag_from_ref("docker.io/ai/qwen3.5"), "latest");
        assert_eq!(tag_from_ref("0.8b"), "latest");
    }

    /// Ported from ollama's types/model/name_test.go
    /// ("host:port/namespace/model:tag" and the tagless default): a colon
    /// inside the host component must never be mistaken for a tag
    /// separator, and a reference without a tag defaults to "latest".
    #[test]
    fn tag_from_ref_ignores_a_port_in_the_host_component() {
        assert_eq!(tag_from_ref("example.com:5000/ns/model"), "latest");
        assert_eq!(tag_from_ref("example.com:5000/ns/model:tag"), "tag");
        assert_eq!(tag_from_ref("localhost:11434/library/mistral:7b"), "7b");
    }

    // ---------------------------------------------------------------
    // One-file-per-model storage (OciStore itself)
    // ---------------------------------------------------------------

    fn temp_store_dir(name: &str) -> std::path::PathBuf {
        std::env::temp_dir().join(format!(
            "llmman-oci-test-{name}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ))
    }

    #[test]
    fn rewriting_an_existing_blob_refreshes_its_age() {
        let dir = temp_store_dir("blob-reuse");
        let store = OciStore::open(&dir).unwrap();
        let desc = store
            .write_blob("application/octet-stream", b"layer")
            .unwrap();
        let path = store.blob_path(&desc.digest).unwrap();
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60);
        let touch = |t| {
            fs::OpenOptions::new()
                .write(true)
                .open(&path)
                .unwrap()
                .set_modified(t)
                .unwrap()
        };
        touch(old);

        store
            .write_blob("application/octet-stream", b"layer")
            .unwrap();

        let age = fs::metadata(&path)
            .unwrap()
            .modified()
            .unwrap()
            .elapsed()
            .unwrap();
        assert!(age < std::time::Duration::from_secs(60), "{age:?}");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn rewriting_an_existing_blob_file_refreshes_its_age() {
        let dir = temp_store_dir("blob-file-reuse");
        let store = OciStore::open(&dir).unwrap();
        let src = dir.join("layer.bin");
        fs::write(&src, b"layer file").unwrap();
        let first = store
            .write_blob_file("application/octet-stream", &src)
            .unwrap();
        assert_eq!(first.size, 10);
        assert_eq!(
            first.digest,
            format!("sha256:{}", hex::encode(Sha256::digest(b"layer file")))
        );
        let path = store.blob_path(&first.digest).unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"layer file");
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60);
        fs::OpenOptions::new()
            .write(true)
            .open(&path)
            .unwrap()
            .set_modified(old)
            .unwrap();

        let second = store
            .write_blob_file("application/octet-stream", &src)
            .unwrap();

        assert_eq!(second.digest, first.digest);
        assert_eq!(second.size, first.size);
        let age = fs::metadata(&path)
            .unwrap()
            .modified()
            .unwrap()
            .elapsed()
            .unwrap();
        assert!(age < std::time::Duration::from_secs(60), "{age:?}");
        let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap())
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .filter(|n| n.to_string_lossy().ends_with(".tmp"))
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn build_wraps_each_file_in_its_own_tar_layer() {
        let dir = temp_store_dir("build-tar");
        let store = OciStore::open(&dir).unwrap();
        let context = dir.join("context");
        fs::create_dir_all(context.join("sub")).unwrap();
        fs::write(
            context.join("sub").join("model.Q4.gguf"),
            b"GGUF\x03\0\0\0body",
        )
        .unwrap();
        let labels: std::collections::HashMap<String, String> =
            [("org.example.team".to_string(), "canary".to_string())].into();

        let desc = store
            .build(&context, "example.invalid/tar:v1", &labels, false)
            .unwrap();

        let manifest = store.read_manifest(&desc.digest).unwrap();
        assert_eq!(manifest.layers.len(), 1);
        let layer = &manifest.layers[0];
        assert_eq!(layer.media_type, WEIGHT_TAR_MEDIA_TYPE);
        assert!(layer.media_type.ends_with(".tar"), "{}", layer.media_type);
        let ann = layer.annotations.as_ref().unwrap();
        assert_eq!(ann["org.cncf.model.filepath"], "sub/model.Q4.gguf");
        assert_eq!(ann["org.opencontainers.image.title"], "sub/model.Q4.gguf");

        let blob = store.read_blob(&layer.digest).unwrap();
        let mut archive = tar::Archive::new(blob.as_slice());
        let mut entries = archive.entries().unwrap();
        let mut entry = entries.next().unwrap().unwrap();
        assert_eq!(
            entry.path().unwrap().to_string_lossy().replace('\\', "/"),
            "sub/model.Q4.gguf"
        );
        let mut body = Vec::new();
        std::io::Read::read_to_end(&mut entry, &mut body).unwrap();
        assert_eq!(body, b"GGUF\x03\0\0\0body");
        assert!(entries.next().is_none(), "more than one tar entry");

        let config: CncfModelConfig =
            serde_json::from_slice(&store.read_blob(&manifest.config.digest).unwrap()).unwrap();
        assert_eq!(config.modelfs.fs_type, "layers");
        let digests: Vec<String> = manifest.layers.iter().map(|l| l.digest.clone()).collect();
        assert_eq!(config.modelfs.diff_ids, digests);
        assert_eq!(config.config.format.as_deref(), Some("gguf"));
        assert_eq!(manifest.annotations.as_ref(), Some(&labels));
        assert_eq!(
            store.find("example.invalid/tar:v1").unwrap().digest,
            desc.digest
        );
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn ref_path_segments_mirrors_ollama_host_namespace_model_tag() {
        assert_eq!(
            legacy_ref_path_segments("docker.io/ai/qwen3.5:0.8b"),
            vec!["docker.io", "ai", "qwen3.5", "0.8b"]
        );
        assert_eq!(
            legacy_ref_path_segments("docker.io/ai/qwen3.5"),
            vec!["docker.io", "ai", "qwen3.5", "latest"]
        );
    }

    #[test]
    fn current_paths_are_portable_and_distinct() {
        let root = Path::new("store");
        let path = manifest_ref_path(root, "s3://bucket/key");
        assert_eq!(
            path,
            root.join(MANIFESTS_V2_DIR)
                .join("~")
                .join("s3%3A")
                .join("~")
                .join("bucket")
                .join("key.json")
        );
        assert_eq!(
            manifest_ref_path(root, "reg.example:5000/ns/model:t"),
            root.join(MANIFESTS_V2_DIR)
                .join("reg.example%3A5000/ns/model/t.json")
        );
        assert_ne!(path, manifest_ref_path(root, "../../etc/passwd"));
        assert_ne!(path, manifest_ref_path(root, "S3://bucket/key"));
        assert_ne!(path, manifest_ref_path(root, "s3://bucket/key:latest"));
        assert_ne!(
            manifest_ref_path(root, "reg.example/ns/model:Prod"),
            manifest_ref_path(root, "reg.example/ns/model:prod")
        );
        assert_ne!(
            manifest_ref_path(root, "reg.example/ns/model:t"),
            manifest_ref_path(root, "reg.example/ns/model/t.json:x")
        );
    }

    #[test]
    fn manifest_ref_paths_match_shared_golden_vectors() {
        #[derive(serde::Deserialize)]
        struct Vector {
            reference: String,
            path: String,
        }
        let vectors: Vec<Vector> =
            serde_json::from_str(include_str!("../../tests/fixtures/manifest-ref-paths.json"))
                .unwrap();
        for vector in vectors {
            assert_eq!(
                manifest_ref_path(Path::new("store"), &vector.reference),
                Path::new("store").join(vector.path),
                "{}",
                vector.reference
            );
        }
    }

    #[test]
    fn new_store_does_not_create_legacy_tree() {
        let dir = temp_store_dir("new-v2-only");
        let store = OciStore::open(&dir).unwrap();
        assert!(store.root().join(MANIFESTS_V2_DIR).is_dir());
        assert!(!store.root().join("manifests").exists());
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn long_escaped_tags_stay_within_component_limits() {
        let root = Path::new("store");
        let ref_name = format!("reg.example/ns/model:{}", "A".repeat(128));
        let path = manifest_ref_path(root, &ref_name);
        for part in path.components() {
            assert!(part.as_os_str().len() <= 255);
        }
        assert!(path.ends_with("~~.json"));
    }

    #[cfg(unix)]
    #[test]
    fn long_opaque_key_ignores_unrepresentable_legacy_pointer() {
        let dir = temp_store_dir("long-opaque-key");
        let store = OciStore::open(&dir).unwrap();
        let reference = format!("s3://bucket/{}", "a".repeat(256));
        fs::create_dir_all(
            store
                .legacy_ref_path(&reference)
                .parent()
                .unwrap()
                .parent()
                .unwrap(),
        )
        .unwrap();
        store.tag(desc_with_ref(&reference), &reference).unwrap();
        assert_eq!(store.find(&reference).unwrap().digest, "sha256:deadbeef");
        store.remove(&reference).unwrap();
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn opaque_reference_and_literal_latest_suffix_remain_distinct() {
        let dir = temp_store_dir("opaque-latest");
        let store = OciStore::open(&dir).unwrap();
        let first = "s3://bucket/key";
        let second = "s3://bucket/key:latest";
        let mut first_desc = desc_with_ref(first);
        first_desc.digest = "sha256:first".into();
        let mut second_desc = desc_with_ref(second);
        second_desc.digest = "sha256:second".into();
        store.tag(first_desc, first).unwrap();
        store.tag(second_desc, second).unwrap();
        assert_eq!(store.find(first).unwrap().digest, "sha256:first");
        assert_eq!(store.find(second).unwrap().digest, "sha256:second");
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn distinct_references_never_share_a_manifest_pointer() {
        let dir = temp_store_dir("distinct-refs");
        let store = OciStore::open(&dir).unwrap();
        let first = "reg.example:5000/ns/model:t";
        let second = "reg.example_5000/ns/model:t";
        assert!(crate::shortnames::validate_reference(first).is_ok());
        assert!(crate::shortnames::validate_reference(second).is_ok());
        assert_eq!(store.legacy_ref_path(first), store.legacy_ref_path(second));
        assert_ne!(store.ref_path(first), store.ref_path(second));
        assert_ne!(
            store.ref_path("docker.io/ai/model:Prod"),
            store.ref_path("docker.io/ai/model:prod")
        );

        let mut first_desc = desc_with_ref(first);
        first_desc.digest = "sha256:first".into();
        let mut second_desc = desc_with_ref(second);
        second_desc.digest = "sha256:second".into();
        store.tag(first_desc, first).unwrap();
        store.tag(second_desc, second).unwrap();
        assert_eq!(store.find(first).unwrap().digest, "sha256:first");
        assert_eq!(store.find(second).unwrap().digest, "sha256:second");
        store.remove(first).unwrap();
        assert!(store.find(first).is_err());
        assert_eq!(store.find(second).unwrap().digest, "sha256:second");
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn legacy_pointer_is_read_and_preserved_without_hiding_a_v2_reference() {
        let dir = temp_store_dir("legacy-collision");
        let store = OciStore::open(&dir).unwrap();
        let first = "reg.example:5000/ns/model:t";
        let second = "reg.example_5000/ns/model:t";
        let legacy = store.legacy_ref_path(first);
        fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        fs::write(&legacy, serde_json::to_vec(&desc_with_ref(first)).unwrap()).unwrap();
        assert_eq!(store.find(first).unwrap().digest, "sha256:deadbeef");

        let mut second_desc = desc_with_ref(second);
        second_desc.digest = "sha256:second".into();
        store.tag(second_desc, second).unwrap();
        assert!(
            legacy.exists(),
            "the other reference's old pointer must survive"
        );
        assert_eq!(store.find(first).unwrap().digest, "sha256:deadbeef");
        assert_eq!(store.find(second).unwrap().digest, "sha256:second");
        assert_eq!(store.list_refs().len(), 2);
        assert_eq!(store.list_refs_strict().unwrap().len(), 2);

        let mut updated = desc_with_ref(first);
        updated.digest = "sha256:updated".into();
        store.tag(updated, first).unwrap();
        assert!(legacy.exists(), "the old tree remains a read-only fallback");
        assert_eq!(store.find(first).unwrap().digest, "sha256:updated");
        assert_eq!(store.find(second).unwrap().digest, "sha256:second");
        assert_eq!(store.list_refs_strict().unwrap().len(), 3);
        store.remove(first).unwrap();
        assert!(store.find(first).is_err());
        assert!(!legacy.exists());
        assert_eq!(store.find(second).unwrap().digest, "sha256:second");
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn malformed_legacy_pointer_does_not_block_tag_or_remove() {
        let dir = temp_store_dir("malformed-legacy");
        let store = OciStore::open(&dir).unwrap();
        let reference = "docker.io/ai/model:latest";
        let legacy = store.legacy_ref_path(reference);
        fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        fs::write(&legacy, b"not JSON").unwrap();

        store.tag(desc_with_ref(reference), reference).unwrap();
        assert!(store.ref_path(reference).is_file());
        assert_eq!(fs::read(&legacy).unwrap(), b"not JSON");
        assert_eq!(store.remove(reference).unwrap(), reference);
        assert!(!store.ref_path(reference).exists());
        assert_eq!(fs::read(&legacy).unwrap(), b"not JSON");
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn legacy_directory_does_not_block_writing_or_removing() {
        let dir = temp_store_dir("legacy-directory");
        let store = OciStore::open(&dir).unwrap();
        let reference = "docker.io/ai/model:latest";
        let legacy = store.legacy_ref_path(reference);
        fs::create_dir_all(&legacy).unwrap();
        let nested = legacy.join("another-tag");
        fs::write(&nested, b"another model's pointer").unwrap();

        store.tag(desc_with_ref(reference), reference).unwrap();
        assert!(store.ref_path(reference).exists());
        assert_eq!(store.remove(reference).unwrap(), reference);
        assert!(!store.ref_path(reference).exists());
        assert!(legacy.is_dir());
        assert!(nested.exists());
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn legacy_ancestor_file_does_not_block_tag_or_remove() {
        let dir = temp_store_dir("legacy-ancestor-file");
        let store = OciStore::open(&dir).unwrap();
        let reference = "reg.example/ns/model/sub:t";
        let ancestor = store.legacy_ref_path("reg.example/ns/model:sub");
        fs::create_dir_all(ancestor.parent().unwrap()).unwrap();
        fs::write(&ancestor, b"another pointer").unwrap();

        store.tag(desc_with_ref(reference), reference).unwrap();
        assert!(store.ref_path(reference).is_file());
        assert_eq!(store.remove(reference).unwrap(), reference);
        assert!(!store.ref_path(reference).exists());
        assert_eq!(fs::read(&ancestor).unwrap(), b"another pointer");
        fs::remove_dir_all(dir).unwrap();
    }

    /// Core regression test for this change: two different references
    /// must resolve to two different files, so a torn write to one
    /// model's manifest file can never affect any other model's own file
    /// — unlike the old shared index.json, where every model's entry
    /// lived in the same file.
    #[test]
    fn tag_and_find_round_trip_one_file_per_model() {
        let dir = temp_store_dir("round-trip");
        let store = OciStore::open(&dir).unwrap();

        store
            .tag(desc_with_ref("unused"), "docker.io/ai/qwen3.5:0.8b")
            .unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/gemma4:latest")
            .unwrap();

        let a = store.ref_path("docker.io/ai/qwen3.5:0.8b");
        let b = store.ref_path("docker.io/ai/gemma4:latest");
        assert_ne!(a, b, "distinct references must live at distinct paths");
        assert!(a.is_file());
        assert!(b.is_file());

        let found = store.find("docker.io/ai/qwen3.5:0.8b").unwrap();
        assert_eq!(
            found.annotations.unwrap()["org.opencontainers.image.ref.name"],
            "docker.io/ai/qwen3.5:0.8b"
        );

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

    #[test]
    fn write_ref_is_atomic_and_leaves_no_tmp_file() {
        let dir = temp_store_dir("atomic");
        let store = OciStore::open(&dir).unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/gemma4:latest")
            .unwrap();

        let path = store.ref_path("docker.io/ai/gemma4:latest");
        assert!(path.is_file());
        let leftover_tmp = std::fs::read_dir(path.parent().unwrap())
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.path().extension().is_some_and(|ext| ext == "tmp"));
        assert!(
            !leftover_tmp,
            "no .tmp file should survive a successful write"
        );

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

    #[test]
    fn list_and_remove_work_across_many_models() {
        let dir = temp_store_dir("list-remove");
        let store = OciStore::open(&dir).unwrap();
        for i in 0..5 {
            store
                .tag(
                    desc_with_ref("unused"),
                    &format!("docker.io/ai/model-{i}:latest"),
                )
                .unwrap();
        }

        let images = store.list().unwrap();
        assert_eq!(images.len(), 5);

        store.remove("docker.io/ai/model-2:latest").unwrap();
        let images = store.list().unwrap();
        assert_eq!(images.len(), 4);
        assert!(!images
            .iter()
            .any(|i| i.reference == "docker.io/ai/model-2:latest"));

        assert!(store.remove("docker.io/ai/model-2:latest").is_err());

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

    /// Regression test: one unreadable directory under manifests/ must
    /// not hide every other model from `list`.
    #[test]
    #[cfg(unix)]
    fn list_skips_an_unreadable_subtree() {
        use std::os::unix::fs::PermissionsExt;

        let dir = temp_store_dir("unreadable-subtree");
        let store = OciStore::open(&dir).unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/ok:latest")
            .unwrap();

        let blocked = dir.join("manifests").join("unreadable");
        std::fs::create_dir_all(&blocked).unwrap();
        std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o0)).unwrap();

        let images = store.list().unwrap();
        assert_eq!(images.len(), 1);
        assert_eq!(images[0].reference, "docker.io/ai/ok:latest");

        std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Concurrent writers of *distinct* references must never lose an
    /// entry — the whole point of one file per model is that there's no
    /// shared read-modify-write cycle left for them to race on at all,
    /// unlike the old shared index.json (see this repo's git history).
    #[test]
    fn concurrent_tag_calls_across_distinct_refs_lose_nothing() {
        let dir = temp_store_dir("concurrent");
        let store = std::sync::Arc::new(OciStore::open(&dir).unwrap());

        let handles: Vec<_> = (0..25)
            .map(|i| {
                let store = store.clone();
                std::thread::spawn(move || {
                    store
                        .tag(
                            desc_with_ref("unused"),
                            &format!("docker.io/ai/model-{i}:latest"),
                        )
                        .unwrap();
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }

        let images = store.list().unwrap();
        assert_eq!(images.len(), 25);

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

    /// Regression test: two concurrent writers of the *same* reference
    /// must each produce a valid, parsable file — never a truncated or
    /// interleaved one from racing on a shared temp file name.
    #[test]
    fn concurrent_writes_to_the_same_ref_never_corrupt_it() {
        let dir = temp_store_dir("concurrent-same-ref");
        let store = std::sync::Arc::new(OciStore::open(&dir).unwrap());

        let handles: Vec<_> = (0..25)
            .map(|i| {
                let store = store.clone();
                std::thread::spawn(move || {
                    let mut desc = desc_with_ref("unused");
                    desc.digest = format!("sha256:{i:064x}");
                    store.tag(desc, "docker.io/ai/same:latest").unwrap();
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }

        // Whichever writer's rename won last, the result must be one
        // complete, valid entry — not a parse failure from interleaved
        // bytes.
        assert!(store.find("docker.io/ai/same:latest").is_ok());

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

    /// Regression test for a real bug: `Path::with_extension("tmp")`
    /// replaces whatever follows the last '.' in the file name — for a
    /// tag like "0.8b" that turns the temp path into ".../0.tmp",
    /// clobbering another tag's temp file (e.g. "0.5b" would collide on
    /// the same ".../0.tmp"). write_ref must append ".tmp" as a suffix
    /// instead.
    #[test]
    fn tag_with_a_dot_does_not_collide_with_a_different_tag() {
        let dir = temp_store_dir("dotted-tag");
        let store = OciStore::open(&dir).unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/x:0.8b")
            .unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/x:0.5b")
            .unwrap();

        let images = store.list().unwrap();
        assert_eq!(images.len(), 2, "distinct dotted tags must not collide");

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

    /// Regression test: an empty tag ("repo:") must not clobber the
    /// repo's own directory, or every subsequent tag of that repo would
    /// fail.
    #[test]
    fn tag_with_an_empty_tag_does_not_break_other_tags() {
        let dir = temp_store_dir("empty-tag");
        let store = OciStore::open(&dir).unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/x:")
            .unwrap();
        store
            .tag(desc_with_ref("unused"), "docker.io/ai/x:latest")
            .unwrap();

        assert!(store.find("docker.io/ai/x:latest").is_ok());

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

    /// A corrupt (present but unparsable) ref file must not look like a
    /// typo — `find` should surface the parse error, not "not found".
    #[test]
    fn find_distinguishes_a_corrupt_ref_from_a_missing_one() {
        let dir = temp_store_dir("corrupt-ref");
        let store = OciStore::open(&dir).unwrap();
        let path = store.ref_path("docker.io/ai/broken:latest");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, b"not json").unwrap();

        let err = store.find("docker.io/ai/broken:latest").unwrap_err();
        assert!(!err.to_string().contains("not found"), "got: {err}");

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

    /// `rm` is the way out of a corrupt pointer: the current path names
    /// exactly one reference, so an unparsable file there is its own.
    #[test]
    fn corrupt_current_pointer_can_be_removed() {
        let dir = temp_store_dir("corrupt-remove");
        let store = OciStore::open(&dir).unwrap();
        let reference = "docker.io/ai/broken:latest";
        let path = store.ref_path(reference);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, b"not json").unwrap();

        assert_eq!(store.remove(reference).unwrap(), reference);
        assert!(!path.exists());

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

    /// Another reference's old pointer can make this reference's legacy
    /// path a directory; that is absence, not a broken store.
    #[test]
    fn find_ignores_a_legacy_directory_of_another_reference() {
        let dir = temp_store_dir("find-legacy-dir");
        let store = OciStore::open(&dir).unwrap();
        let nested = "reg.example/ns/model/sub:t";
        let legacy = store.legacy_ref_path(nested);
        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        std::fs::write(&legacy, serde_json::to_vec(&desc_with_ref(nested)).unwrap()).unwrap();

        let err = store.find("reg.example/ns/model:sub").unwrap_err();
        assert!(err.downcast_ref::<NotFound>().is_some(), "got: {err}");

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