sui-eval 0.1.197

Clean-room Nix language evaluator — lazy tree-walker + bytecode VM with construction-guaranteed Lazy<T>
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
//! Content-addressed input fetcher for flake.lock resolved inputs.
//!
//! Fetches locked flake inputs (github tarballs, git repos, local paths,
//! remote tarballs) and caches them by `narHash` so repeated evaluations
//! hit the local filesystem instead of the network.

use std::io::Read as _;
use std::path::{Path, PathBuf};

use sui_compat::flake::LockedInput;
use sui_compat::flake_ref::FlakeRef;

// ── Error type ────────────────────────────────────────────────

/// Errors that can occur during input fetching.
///
/// # Why the HTTP failures are separate variants
///
/// Every network failure used to collapse into [`FetchError::Download`], a
/// single `String`. The status code was *known* — it was read as a `u16` and
/// immediately formatted into prose — so a rate-limit and a missing repository
/// arrived at the caller as the same shape, distinguishable only by matching
/// English text.
///
/// That cost real work, measured 2026-08-17: GitHub throttled a flake input's
/// archive on one host **while the API quota showed 4653/5000 remaining** (a
/// per-egress-IP limit on archive generation, unaffected by holding a valid
/// token), and two full rebuilds died before the cause was understood. The
/// remedy for a throttle is unlike the remedy for anything else here — another
/// egress can fetch the identical bytes, and `flake.lock`'s pinned `narHash`
/// makes "identical" *checkable* rather than merely hoped-for — so a consumer
/// has to be able to branch on it. A downstream tool
/// (`pleme-io/fleet`'s `warm-inputs`) was reduced to `contains("HTTP error
/// 429")` on this crate's own error text for exactly that reason.
///
/// So: no status is discarded, and [`FetchError::UnexpectedStatus`] exists so
/// that adding a *new* HTTP behaviour cannot silently fall back into a prose
/// bucket — an unclassified code still arrives as a number.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FetchError {
    #[error("unsupported input type: {0}")]
    UnsupportedType(String),
    #[error("missing required field: {0}")]
    MissingField(&'static str),
    /// A genuine transport failure — DNS, TLS, connect timeout, body read.
    /// **Not** a status: an HTTP response that arrived and said "no" is one of
    /// the four typed variants below.
    #[error("download failed: {0}")]
    Download(String),
    /// The upstream refused to serve content it has: HTTP 429, or a 403 whose
    /// body names a secondary rate limit. `retry_after` carries the server's
    /// own `Retry-After` in seconds when it sent one — the only authority on
    /// how long to wait, and previously thrown away unread.
    #[error("throttled by {url} (HTTP {status}){}", match retry_after {
        Some(s) => format!(", retry after {s}s"),
        None => String::new(),
    })]
    Throttled {
        url: String,
        status: u16,
        retry_after: Option<u64>,
    },
    /// 401 or 403 — our credential, not the content. Another egress does not
    /// help; the token does.
    #[error("not authorized for {url} (HTTP {status}) — check the access token")]
    Unauthorized { url: String, status: u16 },
    /// 404. For a private input this is frequently an *auth* failure wearing a
    /// not-found mask, which is why the message says so rather than asserting
    /// the content is absent.
    #[error("{url} not found (HTTP 404) — or present but invisible to this credential")]
    NotFound { url: String },
    /// Any other non-2xx. Carries the code so an unhandled status is still a
    /// number a caller can act on, never prose.
    #[error("{url} returned HTTP {status}")]
    UnexpectedStatus { url: String, status: u16 },
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("archive extraction failed: {0}")]
    Extract(String),
}

impl FetchError {
    /// The HTTP status, when this failure carried one.
    ///
    /// Exists so a caller branches on a number rather than re-deriving one from
    /// the `Display` text — which is the habit this enum was widened to end.
    #[must_use]
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Throttled { status, .. }
            | Self::Unauthorized { status, .. }
            | Self::UnexpectedStatus { status, .. } => Some(*status),
            Self::NotFound { .. } => Some(404),
            _ => None,
        }
    }

    /// Whether fetching the identical bytes from a different network egress
    /// could succeed.
    ///
    /// True **only** for a throttle. A 401/403/404 is about our credential or
    /// the content, so another host is refused identically — and answering
    /// `true` there would send an operator to build a second fetch path that
    /// cannot work.
    #[must_use]
    pub fn is_throttled(&self) -> bool {
        matches!(self, Self::Throttled { .. })
    }
}

// ── Typed archive report ──────────────────────────────────────

/// Which category a per-input failure fell into, as a stable machine-readable
/// tag.
///
/// This is the field a downstream tool branches on instead of matching prose.
/// The tags are wire-facing, so they are kebab-case and **must not be renamed**
/// once a consumer reads them — a renamed tag silently stops matching, which is
/// the same class of failure as the prose-matching it replaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FailureKind {
    /// The upstream refused to serve content it has. **The one recoverable
    /// kind**: a different network egress can fetch identical bytes.
    Throttled,
    /// Our credential is insufficient (401/403). Another egress is refused
    /// identically.
    Unauthorized,
    /// 404 — absent, or present but invisible to this credential.
    NotFound,
    /// A non-2xx nobody wrote an arm for; `status` carries the code.
    UnexpectedStatus,
    /// DNS / TLS / timeout — no response arrived at all.
    Transport,
    /// Not an HTTP failure: unsupported input type, missing field, IO,
    /// extraction.
    Local,
}

/// One input that could not be fetched, described well enough that a caller can
/// decide what to do without reading a sentence.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct InputFailure {
    /// The `flake.lock` node name, so the operator knows *which* input.
    pub input: String,
    pub kind: FailureKind,
    /// The HTTP status when there was one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
    /// The server's own `Retry-After` in seconds, when it sent one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after: Option<u64>,
    /// Whether a different network egress could plausibly succeed. Derived, not
    /// stored twice — a consumer should not have to re-derive policy from a tag.
    pub recoverable_elsewhere: bool,
    /// The human sentence, kept for a log. **Not** the machine surface: a
    /// consumer that parses this field has re-created the defect.
    pub message: String,
}

impl InputFailure {
    /// Classify a fetch failure for a named input.
    #[must_use]
    pub fn from_error(input: &str, err: &FetchError) -> Self {
        let kind = match err {
            FetchError::Throttled { .. } => FailureKind::Throttled,
            FetchError::Unauthorized { .. } => FailureKind::Unauthorized,
            FetchError::NotFound { .. } => FailureKind::NotFound,
            FetchError::UnexpectedStatus { .. } => FailureKind::UnexpectedStatus,
            FetchError::Download(_) => FailureKind::Transport,
            _ => FailureKind::Local,
        };
        Self {
            input: input.to_string(),
            kind,
            status: err.status(),
            retry_after: match err {
                FetchError::Throttled { retry_after, .. } => *retry_after,
                _ => None,
            },
            recoverable_elsewhere: err.is_throttled(),
            message: err.to_string(),
        }
    }
}

/// The outcome of walking every locked input.
///
/// `scanned` is carried deliberately: it is the **denominator**. A report of
/// zero failures means nothing without it — a walk that discovered no inputs
/// would otherwise be indistinguishable from a fleet that is fully warm, which
/// is the vacuous-success shape this codebase keeps paying for.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct ArchiveReport {
    pub scanned: usize,
    pub already_present: usize,
    pub fetched: usize,
    pub failures: Vec<InputFailure>,
}

impl ArchiveReport {
    /// Whether every scanned input is now available locally.
    ///
    /// **False when nothing was scanned**, by construction: "warm" is a claim
    /// about a non-empty set, and an empty walk has not earned it.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.scanned > 0 && self.failures.is_empty()
    }

    /// The failures a different egress could fix — what a recovery tool acts on.
    #[must_use]
    pub fn recoverable(&self) -> impl Iterator<Item = &InputFailure> {
        self.failures.iter().filter(|f| f.recoverable_elsewhere)
    }
}

// ── InputFetcher ──────────────────────────────────────────────

/// A content-addressed input fetcher that downloads and caches flake inputs.
///
/// Inputs are cached under `~/.cache/sui/inputs/` (or a custom directory)
/// keyed by their `narHash` from the lock file. Cache hits skip network
/// access entirely.
pub struct InputFetcher {
    cache_dir: PathBuf,
}

impl Default for InputFetcher {
    fn default() -> Self {
        Self::new()
    }
}

impl InputFetcher {
    /// Create a fetcher using the default cache directory (`~/.cache/sui/inputs/`).
    #[must_use]
    pub fn new() -> Self {
        let cache_dir = dirs_cache_dir().join("sui/inputs");
        Self { cache_dir }
    }

    /// Create a fetcher with a custom cache directory.
    #[must_use]
    pub fn with_cache_dir(cache_dir: PathBuf) -> Self {
        Self { cache_dir }
    }

    /// Return the cache directory path.
    #[must_use]
    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    /// Whether this input would be served from cache without any network access.
    ///
    /// Deliberately shares [`Self::cache_probe`] with [`Self::fetch`] rather
    /// than re-deriving the cache path: two independent notions of "cached"
    /// drift, and the drift is invisible — a reporter would announce "already
    /// present" for an entry the fetcher then re-downloads. Note it applies the
    /// same **non-empty** requirement, so a directory left behind by a fetch
    /// that died mid-extract counts as a miss here exactly as it does there.
    #[must_use]
    pub fn is_cached(&self, locked: &LockedInput) -> bool {
        self.cache_probe(locked).is_some()
    }

    /// Resolve a usable cache entry for `locked`, if one exists.
    ///
    /// `None` means "fetch is required", covering both no-entry and
    /// entry-exists-but-is-empty.
    fn cache_probe(&self, locked: &LockedInput) -> Option<PathBuf> {
        let nar_hash = locked.nar_hash.as_ref()?;
        let cached = self.cache_dir.join(sanitize_hash(nar_hash));
        if !cached.exists() {
            return None;
        }
        let resolved = find_single_subdir_or_self(&cached);
        is_non_empty_dir(&resolved).then_some(resolved)
    }

    /// Fetch a locked input and return the local filesystem path.
    ///
    /// Uses content-addressed caching by `narHash` — if the hash is present
    /// and a cached directory exists, returns immediately without network access.
    pub fn fetch(&self, locked: &LockedInput) -> Result<PathBuf, FetchError> {
        // Check cache first (keyed by narHash), through the SAME probe
        // `is_cached` uses so a reporter and the fetcher can never disagree
        // about whether network access is about to happen.
        if let Some(resolved) = self.cache_probe(locked) {
            return Ok(resolved);
        }
        // A present-but-empty entry is a miss (a previous fetch created the
        // directory then died before extracting). Clear it so the retry below
        // is not blocked by its own debris.
        if let Some(ref nar_hash) = locked.nar_hash {
            let cached = self.cache_dir.join(sanitize_hash(nar_hash));
            if cached.exists() {
                let _ = std::fs::remove_dir_all(&cached);
            }
        }

        match locked.source_type.as_str() {
            "github" => self.fetch_github(locked),
            "gitlab" => self.fetch_gitlab(locked),
            "sourcehut" => self.fetch_sourcehut(locked),
            "path" => Self::fetch_path(locked),
            "git" => self.fetch_git(locked),
            "tarball" | "file" => self.fetch_tarball(locked),
            other => Err(FetchError::UnsupportedType(other.to_string())),
        }
    }

    /// Construct the GitHub archive URL for a locked input.
    #[must_use]
    pub fn github_archive_url(owner: &str, repo: &str, rev: &str) -> String {
        format!("https://github.com/{owner}/{repo}/archive/{rev}.tar.gz")
    }

    /// GitLab archive URL.  Shape differs from GitHub — the file
    /// name embeds the repo + rev and lives under `/-/archive/{rev}/`.
    /// Honors `host` so self-hosted gitlab instances (e.g.
    /// `gitlab.gnome.org`, `git.example.com`) work; defaults to
    /// `gitlab.com` when host is None.
    #[must_use]
    pub fn gitlab_archive_url(host: Option<&str>, owner: &str, repo: &str, rev: &str) -> String {
        let host = host.unwrap_or("gitlab.com");
        format!(
            "https://{host}/{owner}/{repo}/-/archive/{rev}/{repo}-{rev}.tar.gz"
        )
    }

    /// Sourcehut archive URL. Owners carry the `~` prefix on the
    /// platform; the flake-ref parser stores them without the prefix,
    /// so we prepend here.
    #[must_use]
    pub fn sourcehut_archive_url(owner: &str, repo: &str, rev: &str) -> String {
        let owner_prefix = if owner.starts_with('~') {
            owner.to_string()
        } else {
            format!("~{owner}")
        };
        format!("https://git.sr.ht/{owner_prefix}/{repo}/archive/{rev}.tar.gz")
    }

    // ── Private fetch methods ─────────────────────────────

    fn fetch_github(&self, locked: &LockedInput) -> Result<PathBuf, FetchError> {
        let owner = locked.owner.as_deref().ok_or(FetchError::MissingField("owner"))?;
        let repo = locked.repo.as_deref().ok_or(FetchError::MissingField("repo"))?;
        let rev = locked.rev.as_deref().ok_or(FetchError::MissingField("rev"))?;

        let url = Self::github_archive_url(owner, repo, rev);
        // Was a hand-inlined copy of `fetch_archive`'s body — the only copy of
        // the three that lacked a cache guard, which is exactly how it came to
        // re-download on every invocation. Sharing the body is the fix for the
        // class; the guard below is the fix for the instance.
        self.fetch_archive(locked, &url, &format!("github-{owner}-{repo}-{rev}"), rev)
    }

    /// GitHub, GitLab and Sourcehut share one archive-fetch shape — download a
    /// tar.gz, extract, return the single top-level directory. Only the URL
    /// construction differs.
    ///
    /// ── ★ STAGE THEN RENAME; NEVER EXTRACT INTO THE FINAL PATH ────────────
    /// This used to `create_dir_all(dest)` and extract straight into it, which
    /// produced three distinct defects from one decision:
    ///
    /// 1. **A partial tree is a valid cache hit.** The hit predicate is "the
    ///    directory is non-empty", which goes true on the FIRST tar entry, so a
    ///    concurrent process could adopt a half-extracted tree and evaluate it
    ///    as if complete — a silently wrong eval, not an error.
    /// 2. **A re-extraction UNIONS.** `tar` runs with `overwrite: true`, so
    ///    extracting a second time over an existing tree leaves files that the
    ///    newer tree deleted. Content at a "content-addressed" path then
    ///    disagrees with the hash in its own name.
    /// 3. **A failing process deleted another process's good cache entry.**
    ///    Every error path called `remove_dir_all(&dest)` — on the FINAL path.
    ///    A transient network error during a redundant re-fetch would wipe a
    ///    complete tree that another eval was actively reading.
    ///
    /// Defect 2 is what poisoned `~/.cache/sui/nar-memo` and made `getFlake`
    /// return a store path CppNix disagrees with (measured 2026-08-17; see
    /// `sui-compat/src/source.rs`'s memo verifier, which is the read-side
    /// defence this is the write-side cause of).
    ///
    /// Staging beside the target rather than in `/tmp` keeps the rename on one
    /// filesystem, where it is atomic — the same reason `sui-castore`'s local
    /// storage stages beside its target.
    fn fetch_archive(
        &self,
        locked: &LockedInput,
        url: &str,
        cache_key: &str,
        rev: &str,
    ) -> Result<PathBuf, FetchError> {
        let dest = self.dest_dir(locked, cache_key);

        // ── The cache guard, and why it is conditional ────────────────────
        // A rev that is a 40/64-hex commit names one immutable tree, so a
        // complete directory at `dest` can be adopted with no network at all.
        // A rev that is a BRANCH NAME does not: `github:owner/repo/main` is a
        // legal ref (CppNix accepts it, so refusing it would be a parity
        // divergence, not a safety win) and the tree behind it moves. Guarding
        // unconditionally would freeze such an entry at whatever `main` was
        // the first time it was fetched, forever.
        //
        // So: immutable revs are cached, mutable ones are always re-fetched.
        // The old code re-fetched BOTH, which was wasteful for the first and
        // accidentally correct for the second.
        if is_immutable_rev(rev) && is_non_empty_dir(&dest) {
            return Ok(find_single_subdir_or_self(&dest));
        }

        let staging = staging_path(&dest);
        // A leftover staging dir means a previous process died mid-extract.
        // It is ours to clear: the name carries our pid.
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging)?;

        let bytes = match download_bytes(url) {
            Ok(b) => b,
            Err(e) => {
                let _ = std::fs::remove_dir_all(&staging);
                return Err(e);
            }
        };
        if let Err(e) = extract_tar_gz(&bytes, &staging) {
            let _ = std::fs::remove_dir_all(&staging);
            return Err(e);
        }

        publish(&staging, &dest, is_immutable_rev(rev))?;
        Ok(find_single_subdir_or_self(&dest))
    }

    fn fetch_gitlab(&self, locked: &LockedInput) -> Result<PathBuf, FetchError> {
        let owner = locked.owner.as_deref().ok_or(FetchError::MissingField("owner"))?;
        let repo = locked.repo.as_deref().ok_or(FetchError::MissingField("repo"))?;
        let rev = locked.rev.as_deref().ok_or(FetchError::MissingField("rev"))?;
        let host = locked.host.as_deref();
        let url = Self::gitlab_archive_url(host, owner, repo, rev);
        let host_tag = host.unwrap_or("gitlab.com").replace('.', "_");
        self.fetch_archive(locked, &url, &format!("gitlab-{host_tag}-{owner}-{repo}-{rev}"), rev)
    }

    fn fetch_sourcehut(&self, locked: &LockedInput) -> Result<PathBuf, FetchError> {
        let owner = locked.owner.as_deref().ok_or(FetchError::MissingField("owner"))?;
        let repo = locked.repo.as_deref().ok_or(FetchError::MissingField("repo"))?;
        let rev = locked.rev.as_deref().ok_or(FetchError::MissingField("rev"))?;
        let url = Self::sourcehut_archive_url(owner, repo, rev);
        let sanitized_owner = owner.trim_start_matches('~');
        self.fetch_archive(
            locked,
            &url,
            &format!("sourcehut-{sanitized_owner}-{repo}-{rev}"),
            rev,
        )
    }

    fn fetch_path(locked: &LockedInput) -> Result<PathBuf, FetchError> {
        let path = locked
            .path
            .as_deref()
            .ok_or(FetchError::MissingField("path"))?;
        Ok(PathBuf::from(path))
    }

    fn fetch_git(&self, locked: &LockedInput) -> Result<PathBuf, FetchError> {
        let url = locked.url.as_deref().ok_or(FetchError::MissingField("url"))?;
        let rev = locked.rev.as_deref().ok_or(FetchError::MissingField("rev"))?;

        let short_rev: String = rev.chars().take(12).collect();
        let dest = self.dest_dir(locked, &format!("git-{short_rev}"));

        // The cache key embeds the rev, so a full object id names one tree and
        // a present one is adoptable. Same conditional as the archive path.
        let immutable = is_immutable_rev(rev);
        if immutable && is_non_empty_dir(&dest) {
            return Ok(dest);
        }

        // Everything below builds the tree in a staging dir and publishes it
        // with one rename. This path was left out of the first stage-then-
        // rename pass, so until now a killed clone or a killed unpack left a
        // partial tree at the FINAL path that the non-empty predicate above
        // then accepted as a complete cache hit.
        let staging = staging_path(&dest);
        let _ = std::fs::remove_dir_all(&staging);

        // Try GitHub tarball first (avoids git CLI dependency in containers).
        // Most git-type inputs in flake.lock are GitHub repos that support
        // archive downloads via /archive/{rev}.tar.gz.
        if let Some(tarball_url) = github_tarball_from_git_url(url, rev) {
            std::fs::create_dir_all(&staging)?;
            match download_bytes(&tarball_url) {
                Ok(bytes) => {
                    if let Err(e) = extract_tar_gz(&bytes, &staging) {
                        let _ = std::fs::remove_dir_all(&staging);
                        return Err(e);
                    }
                    publish(&staging, &dest, immutable)?;
                    return Ok(find_single_subdir_or_self(&dest));
                }
                Err(e) => {
                    // Tarball fallback failed — try git CLI below.
                    let _ = std::fs::remove_dir_all(&staging);
                    tracing::debug!(url = %tarball_url, error = %e, "Tarball fallback failed, trying git CLI");
                }
            }
        }

        // Fall back to git CLI for non-GitHub repos or when tarball fails.
        let status = std::process::Command::new("git")
            .args(["clone", "--depth", "1", url])
            .arg(&staging)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map_err(|e| FetchError::Download(format!(
                "git clone failed (git not in PATH?): {e}"
            )))?;
        if !status.success() {
            let _ = std::fs::remove_dir_all(&staging);
            return Err(FetchError::Download(format!(
                "git clone failed for {url} (exit code: {})",
                status.code().unwrap_or(-1)
            )));
        }

        // Checkout the exact revision.
        //
        // NOTE, unverified and flagged rather than fixed here: the clone above
        // is `--depth 1` of the DEFAULT BRANCH, so an arbitrary `rev` is very
        // likely not among the objects it fetched, and this checkout would
        // fail for any non-HEAD rev. That belongs to whoever owns `git.rs`.
        if let Err(e) = crate::git::checkout_rev(&staging, rev) {
            let _ = std::fs::remove_dir_all(&staging);
            return Err(FetchError::Download(format!("git checkout {rev}: {e}")));
        }

        publish(&staging, &dest, immutable)?;
        Ok(dest)
    }

    fn fetch_tarball(&self, locked: &LockedInput) -> Result<PathBuf, FetchError> {
        let url = locked.url.as_deref().ok_or(FetchError::MissingField("url"))?;

        let hash_suffix = locked
            .nar_hash
            .as_deref()
            .map_or_else(|| url_to_safe_name(url), sanitize_hash);
        let dest = self.dest_dir(locked, &format!("tarball-{hash_suffix}"));

        // A tarball input is keyed on its narHash when it has one, which IS a
        // content address, so a present tree is adoptable. When it has none
        // the key is derived from the URL, which is mutable — same split as
        // `is_immutable_rev` on the archive path.
        let immutable = locked.nar_hash.is_some();
        if immutable && is_non_empty_dir(&dest) {
            return Ok(find_single_subdir_or_self(&dest));
        }

        // Stage then publish, exactly as `fetch_archive` does. This path was
        // left behind by the first pass at that fix, so until now a killed
        // `tarball:`/`file:` fetch could leave a partial tree that the
        // non-empty predicate then accepted as a cache hit.
        let staging = staging_path(&dest);
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging)?;

        let bytes = match download_bytes(url) {
            Ok(b) => b,
            Err(e) => {
                let _ = std::fs::remove_dir_all(&staging);
                return Err(e);
            }
        };
        if let Err(e) = extract_tar_gz(&bytes, &staging) {
            let _ = std::fs::remove_dir_all(&staging);
            return Err(e);
        }

        publish(&staging, &dest, immutable)?;
        Ok(find_single_subdir_or_self(&dest))
    }

    /// Compute the destination directory, preferring narHash-based names.
    fn dest_dir(&self, locked: &LockedInput, fallback: &str) -> PathBuf {
        if let Some(ref nar_hash) = locked.nar_hash {
            self.cache_dir.join(sanitize_hash(nar_hash))
        } else {
            self.cache_dir.join(fallback)
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────

/// Try to convert a git URL to a GitHub tarball URL.
///
/// `https://github.com/NixOS/nixpkgs.git` + rev → `https://github.com/NixOS/nixpkgs/archive/{rev}.tar.gz`
/// Returns `None` for non-GitHub URLs.
fn github_tarball_from_git_url(url: &str, rev: &str) -> Option<String> {
    let stripped = url
        .strip_prefix("https://github.com/")
        .or_else(|| url.strip_prefix("git+https://github.com/"))
        .or_else(|| url.strip_prefix("http://github.com/"))?;
    let stripped = stripped.strip_suffix(".git").unwrap_or(stripped);
    // Validate it looks like owner/repo (no extra path segments)
    let parts: Vec<&str> = stripped.split('/').collect();
    if parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() {
        Some(format!(
            "https://github.com/{}/{}/archive/{rev}.tar.gz",
            parts[0], parts[1]
        ))
    } else {
        None
    }
}

/// Turn a narHash like `sha256-AAAA...=` into a filesystem-safe name.
/// Turn a hash into a single safe path component.
///
/// ── ★ THE SUBSTITUTIONS ARE NOT A VALIDATION ──────────────────────────
/// `:`→`-`, `/`→`_`, drop `=` makes a hash *look* like a filename; it does not
/// make it *one*. `narHash` comes from a `flake.lock`, which is untrusted
/// input for any flake you did not write yourself, and three values survive
/// the transliteration as meaningful path components: `..`, `.` and `""`.
///
/// Because `/` is mapped away, a multi-level escape is impossible — the blast
/// radius is exactly ONE level, and it should not be rounded up to arbitrary
/// path deletion. One level is bad enough: `"narHash": ".."` makes the cache
/// destination `<cache>/inputs/..` = `~/.cache/sui`, so (a) `fetch` returns
/// `~/.cache/sui` AS the flake's source directory — a silently wrong eval with
/// no error — and (b) on a miss, publishing `remove_dir_all`s it, taking
/// `inputs/` and `nar-memo/` with it. That is the same memo whose poisoning
/// `sui-compat/src/source.rs` was hardened against today.
///
/// So the component is validated, not merely transliterated: anything that is
/// not a plain `[A-Za-z0-9._+-]` run, or that is `.`/`..`/empty, is replaced
/// by a fixed-width digest of the input. Fixed-width by construction beats a
/// denylist, which is what the transliteration was.
fn sanitize_hash(hash: &str) -> String {
    let mapped = hash.replace(':', "-").replace('/', "_").replace('=', "");
    let shaped = !mapped.is_empty()
        && mapped != "."
        && mapped != ".."
        && mapped
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'));
    if shaped {
        mapped
    } else {
        // Deterministic, collision-resistant, and structurally incapable of
        // being a traversal: hex has no `.` and no `/`.
        use sha2::Digest as _;
        let d = sha2::Sha256::digest(hash.as_bytes());
        let mut out = String::with_capacity(2 + 64);
        out.push_str("h-");
        for b in d {
            use std::fmt::Write as _;
            let _ = write!(out, "{b:02x}");
        }
        out
    }
}

/// Whether `rev` names one immutable tree — a full git object id.
///
/// 40 hex for sha1, 64 for the sha256 transition. Anything else (a branch, a
/// tag, a short rev) can move, so it must never be served from cache without a
/// network check. Lowercase only: git emits lowercase, and accepting mixed case
/// would let `ABC…` and `abc…` occupy two cache entries for one tree.
fn is_immutable_rev(rev: &str) -> bool {
    matches!(rev.len(), 40 | 64) && rev.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// A scratch path beside `dest`, on the same filesystem so the publish rename
/// is atomic.
///
/// ── ★ PID IS NOT ENOUGH; THE THREAD ID IS PART OF THE KEY ─────────────
/// An earlier version scoped this on the pid alone and claimed that "two
/// concurrent fetchers cannot share a staging dir". That is true across
/// processes and FALSE within one: two threads of the same process fetching
/// the same input compute the same staging path, and the second one's
/// `remove_dir_all(&staging)` fires while the first is mid-unpack — so the
/// first then publishes a TRUNCATED tree, reintroducing exactly the defect
/// the staging dance exists to prevent.
///
/// Latent today (there is no `rayon`/`par_iter` in the eval path), and it
/// detonates the moment anyone parallelizes input fetching, which is the
/// obvious next optimization on a lock file with N inputs. A claim that is
/// true only until someone does the obvious thing is not an invariant.
fn staging_path(dest: &Path) -> PathBuf {
    let name = dest
        .file_name()
        .map_or_else(|| "fetch".to_string(), |n| n.to_string_lossy().into_owned());
    // `ThreadId`'s Debug is the only stable accessor on stable Rust; it
    // renders as `ThreadId(N)`, so keep the digits and drop the rest.
    let tid = format!("{:?}", std::thread::current().id());
    let tid: String = tid.chars().filter(char::is_ascii_digit).collect();
    let tmp = [
        ".",
        &name,
        ".tmp-",
        &std::process::id().to_string(),
        "-",
        &tid,
    ]
    .concat();
    dest.parent()
        .map_or_else(|| PathBuf::from(&tmp), |p| p.join(&tmp))
}

/// Move `staging` onto `dest` without ever leaving `dest` observably absent
/// for longer than one rename syscall.
///
/// ── ★ WHY NOT `remove_dir_all(dest)` THEN RENAME ──────────────────────
/// That was the first version, and it is a regression dressed as a fix. For a
/// MUTABLE rev the guard above never short-circuits, so every invocation
/// deleted the published tree and re-created it — meaning a concurrent eval
/// reading that path got ENOENT for the whole duration of a recursive delete
/// of (measured on `pleme-io/nix`) 654 files. The staging dance had narrowed
/// the failure from "adopt a partial tree" to "have a complete tree yanked",
/// which is better and is still a bug.
///
/// Two cases, and neither deletes in place:
///
/// - **Immutable rev, tree already present.** Another process published the
///   same content-addressed tree. Theirs is by definition ours; adopt it and
///   drop our staging. No delete of `dest` at all.
/// - **Otherwise.** Rename the old tree ASIDE (one syscall), rename the new
///   one in, then delete the aside at leisure. `dest` is unresolvable only
///   between two renames rather than for the length of a tree walk.
fn publish(staging: &Path, dest: &Path, immutable: bool) -> Result<(), FetchError> {
    if immutable && is_non_empty_dir(dest) {
        let _ = std::fs::remove_dir_all(staging);
        return Ok(());
    }

    let aside = with_suffix(staging, ".old");
    let _ = std::fs::remove_dir_all(&aside);
    let moved_aside = dest.exists() && std::fs::rename(dest, &aside).is_ok();

    match std::fs::rename(staging, dest) {
        Ok(()) => {
            if moved_aside {
                let _ = std::fs::remove_dir_all(&aside);
            }
            Ok(())
        }
        Err(_) => {
            // Put the old tree back rather than leaving the cache emptier
            // than we found it.
            if moved_aside && !dest.exists() {
                let _ = std::fs::rename(&aside, dest);
            }
            let _ = std::fs::remove_dir_all(staging);
            let _ = std::fs::remove_dir_all(&aside);
            if is_non_empty_dir(dest) {
                // Lost the race; the winner left a good tree.
                Ok(())
            } else {
                Err(FetchError::Extract(
                    "could not publish the fetched tree and no other process left one".into(),
                ))
            }
        }
    }
}

/// `path` with `suffix` appended to its file name (not `with_extension`,
/// which truncates at the last dot and would mangle `repo-1.2.3`).
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
    let name = path
        .file_name()
        .map_or_else(|| "x".to_string(), |n| n.to_string_lossy().into_owned());
    path.parent().map_or_else(
        || PathBuf::from([&name, suffix].concat()),
        |p| p.join([&name, suffix].concat()),
    )
}

/// Return `true` when `dir` exists and has at least one child entry.
fn is_non_empty_dir(dir: &Path) -> bool {
    std::fs::read_dir(dir)
        .ok()
        .is_some_and(|mut rd| rd.next().is_some())
}

/// If the directory contains exactly one child directory (common for GitHub
/// tarballs which unpack as `repo-rev/`), return that child. Otherwise
/// return the directory itself.
fn find_single_subdir_or_self(dir: &Path) -> PathBuf {
    let entries: Vec<_> = std::fs::read_dir(dir)
        .ok()
        .into_iter()
        .flatten()
        .filter_map(|e| e.ok())
        .collect();
    if entries.len() == 1 && entries[0].path().is_dir() {
        entries[0].path()
    } else {
        dir.to_path_buf()
    }
}

/// Download a URL and return the raw bytes.
///
/// Uses `ureq` (synchronous, no tokio runtime) so this function is safe to
/// call from inside a running tokio context — no nested-runtime panic.
///
/// Body limit raised to 512 MiB to accommodate large inputs like nixpkgs tarballs.
fn download_bytes(url: &str) -> Result<Vec<u8>, FetchError> {
    // `http_status_as_error(false)` is load-bearing, not a preference.
    //
    // ureq 3 defaults it to TRUE, which turns every non-2xx into
    // `Err(Error::StatusCode(_))` *before* the response object exists. Two
    // consequences that both bit this function: the `!status().is_success()`
    // branch below was **unreachable for real HTTP failures** — dead code that
    // read as the status check — and `Retry-After` was unreachable too, because
    // the headers live on a response we never received.
    //
    // Turning it off means a 429 arrives as a response we can classify AND
    // read headers from, and the branch below becomes the live classifier it
    // always looked like. `call()` then errors only on genuine transport
    // failure, which is exactly what `FetchError::Download` should mean.
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .http_status_as_error(false)
        .build()
        .into();
    let mut req = agent.get(url);

    // Attach a host-appropriate auth token when one is available.
    // CppNix consults `~/.config/nix/nix.conf` `access-tokens =
    // github.com=<TOKEN>` etc.; we keep parity by reading the same
    // sources plus the common `GITHUB_TOKEN` env (gh CLI, nix-darwin
    // shell init).  Without this the operator's private flake
    // inputs (e.g. `arnes`) 404 unauthenticated.
    if let Some(token) = github_token_for_url(url) {
        req = req.header("Authorization", &format!("token {token}"));
    }

    let mut response = req
        .call()
        .map_err(|e| FetchError::Download(format!("{url}: {e}")))?;

    if !response.status().is_success() {
        return Err(classify_status(url, &response));
    }

    response
        .body_mut()
        .with_config()
        .limit(512 * 1024 * 1024)
        .read_to_vec()
        .map_err(|e| FetchError::Download(format!("{url}: {e}")))
}

/// Turn a non-2xx response into the typed variant that names what happened.
///
/// Pure apart from reading the response's status and headers, so it is unit
/// testable without a network — which matters because the interesting cases
/// (429 with and without `Retry-After`, a 403 that is really a secondary rate
/// limit) are precisely the ones nobody can reproduce on demand.
fn classify_status<B>(url: &str, response: &ureq::http::Response<B>) -> FetchError {
    let status = response.status().as_u16();
    let retry_after = retry_after_seconds(response.headers());

    // A secondary rate limit is spelled 403 by GitHub, and 403 otherwise means
    // "your credential is not enough". The header is what separates them: a
    // plain authorization failure carries no Retry-After. Reading a throttle as
    // a credential fault sends an operator to re-provision a token that is
    // fine — so when the server says "come back later", believe it over the code.
    let throttled = status == 429 || (status == 403 && retry_after.is_some());

    if throttled {
        FetchError::Throttled {
            url: url.to_string(),
            status,
            retry_after,
        }
    } else if status == 404 {
        FetchError::NotFound {
            url: url.to_string(),
        }
    } else if status == 401 || status == 403 {
        FetchError::Unauthorized {
            url: url.to_string(),
            status,
        }
    } else {
        FetchError::UnexpectedStatus {
            url: url.to_string(),
            status,
        }
    }
}

/// Read `Retry-After` as whole seconds.
///
/// RFC 9110 permits either a delta-seconds integer or an HTTP-date. Only the
/// integer form is honoured here, and an HTTP-date yields `None` rather than a
/// guess: a wrong wait derived from a misparsed date is worse than admitting we
/// were not told, because a caller that receives `None` falls back to its own
/// bounded policy while one that receives a wrong number obeys it.
fn retry_after_seconds(headers: &ureq::http::HeaderMap) -> Option<u64> {
    headers
        .get("retry-after")?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
}

/// Resolve a host-appropriate auth token for outgoing requests.
///
/// Sources, in order:
///   1. `GITHUB_TOKEN` env var (covers gh CLI exports + CI tokens).
///   2. `NIX_CONFIG` env var, parsed for `access-tokens` line.
///   3. `~/.config/nix/nix.conf` parsed for `access-tokens` line.
///   4. `~/.config/gh/hosts.yml` (`oauth_token:` field for github.com).
///
/// Returns `Some(token)` only for github.com URLs in this iteration —
/// gitlab / sr.ht / private git hosts can be added when needed.
fn github_token_for_url(url: &str) -> Option<String> {
    if !url.starts_with("https://github.com/")
        && !url.starts_with("https://api.github.com/")
    {
        return None;
    }
    if let Ok(t) = std::env::var("GITHUB_TOKEN") {
        if !t.is_empty() {
            return Some(t);
        }
    }
    if let Ok(cfg) = std::env::var("NIX_CONFIG") {
        if let Some(t) = parse_access_tokens(&cfg, "github.com") {
            return Some(t);
        }
    }
    if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
        let nix_conf = home.join(".config/nix/nix.conf");
        if let Ok(cfg) = std::fs::read_to_string(&nix_conf) {
            if let Some(t) = parse_access_tokens(&cfg, "github.com") {
                return Some(t);
            }
        }
        let gh_hosts = home.join(".config/gh/hosts.yml");
        if let Ok(yml) = std::fs::read_to_string(&gh_hosts) {
            if let Some(t) = parse_gh_hosts_token(&yml, "github.com") {
                return Some(t);
            }
        }
    }
    None
}

/// Parse a `~/.config/nix/nix.conf`-style `access-tokens = host=TOKEN ...`
/// line and return the token for `host` if present.
fn parse_access_tokens(cfg: &str, host: &str) -> Option<String> {
    for line in cfg.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("access-tokens") {
            let rest = rest.trim_start().trim_start_matches('=').trim();
            for pair in rest.split_whitespace() {
                if let Some((h, t)) = pair.split_once('=') {
                    if h == host {
                        return Some(t.to_string());
                    }
                }
            }
        }
    }
    None
}

/// Parse `~/.config/gh/hosts.yml` and return the `oauth_token:` value
/// nested under the given host key.  We do this without a full YAML
/// parser to keep sui-eval's dep footprint small — the file is a
/// stable 5-line shape gh maintains.
fn parse_gh_hosts_token(yml: &str, host: &str) -> Option<String> {
    let mut in_host = false;
    for line in yml.lines() {
        let raw = line;
        let trimmed = raw.trim();
        if trimmed.starts_with(host) && trimmed.ends_with(':') {
            in_host = true;
            continue;
        }
        if !raw.starts_with(' ') && !raw.starts_with('\t') && !trimmed.is_empty() {
            in_host = false;
        }
        if in_host {
            if let Some(rest) = trimmed.strip_prefix("oauth_token:") {
                return Some(rest.trim().to_string());
            }
        }
    }
    None
}

/// Extract a `.tar.gz` archive into a destination directory.
fn extract_tar_gz(bytes: &[u8], dest: &Path) -> Result<(), FetchError> {
    let gz = flate2::read::GzDecoder::new(bytes);

    // Check if the gzip header is valid before attempting extraction.
    // An empty or non-gzip payload would fail inside tar::Archive.
    let mut buffered = std::io::BufReader::new(gz);
    let mut peek = [0u8; 1];
    // Try reading one byte to detect decompression errors early.
    match buffered.read(&mut peek) {
        Ok(0) => {
            return Err(FetchError::Extract("empty archive".into()));
        }
        Err(e) => {
            return Err(FetchError::Extract(format!("gzip decompression: {e}")));
        }
        Ok(_) => {
            // Put the byte back by chaining it in front of the reader.
            let cursor = std::io::Cursor::new(peek);
            let chain = cursor.chain(buffered);
            let mut archive = tar::Archive::new(chain);
            archive
                .unpack(dest)
                .map_err(|e| FetchError::Extract(format!("tar unpack: {e}")))?;
        }
    }

    Ok(())
}

/// Convert a URL into a filesystem-safe name (for fallback cache keys).
fn url_to_safe_name(url: &str) -> String {
    url.chars()
        .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
        .collect()
}

/// Platform-aware cache directory discovery.
fn dirs_cache_dir() -> PathBuf {
    // Try XDG_CACHE_HOME first, then platform default, then /tmp.
    // Absolute, not merely non-empty — see eval_cache.rs for the class.
    if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME")
        .map(PathBuf::from)
        .filter(|p| p.is_absolute())
    {
        return xdg;
    }
    if let Some(home) = std::env::var_os("HOME")
        .map(PathBuf::from)
        .filter(|p| p.is_absolute())
    {
        let default = home.join(".cache");
        if default.exists() || std::fs::create_dir_all(&default).is_ok() {
            return default;
        }
    }
    PathBuf::from("/tmp")
}

// ── Tests ─────────────────────────────────────────────────────

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

    fn throttled(retry: Option<u64>) -> FetchError {
        FetchError::Throttled { url: "u".into(), status: 429, retry_after: retry }
    }

    #[test]
    fn a_throttle_becomes_a_machine_readable_tag_with_the_servers_advice() {
        // The whole deliverable in one assertion: the fact a consumer used to
        // recover by matching "HTTP error 429" is now a tag plus a number.
        let f = InputFailure::from_error("nixpkgs", &throttled(Some(120)));
        assert_eq!(f.kind, FailureKind::Throttled);
        assert_eq!(f.status, Some(429));
        assert_eq!(f.retry_after, Some(120));
        assert!(f.recoverable_elsewhere);
        assert_eq!(f.input, "nixpkgs", "the report must name WHICH input");
    }

    #[test]
    fn each_error_maps_to_its_own_kind() {
        let cases: Vec<(FetchError, FailureKind)> = vec![
            (throttled(None), FailureKind::Throttled),
            (FetchError::Unauthorized { url: "u".into(), status: 403 }, FailureKind::Unauthorized),
            (FetchError::NotFound { url: "u".into() }, FailureKind::NotFound),
            (FetchError::UnexpectedStatus { url: "u".into(), status: 503 }, FailureKind::UnexpectedStatus),
            (FetchError::Download("dns".into()), FailureKind::Transport),
            (FetchError::UnsupportedType("hg".into()), FailureKind::Local),
            (FetchError::Extract("bad tar".into()), FailureKind::Local),
        ];
        for (err, want) in cases {
            let got = InputFailure::from_error("i", &err).kind;
            assert_eq!(got, want, "{err:?} classified as {got:?}");
        }
    }

    #[test]
    fn only_a_throttle_is_marked_recoverable_elsewhere() {
        for e in [
            FetchError::Unauthorized { url: "u".into(), status: 401 },
            FetchError::NotFound { url: "u".into() },
            FetchError::UnexpectedStatus { url: "u".into(), status: 500 },
            FetchError::Download("tls".into()),
        ] {
            assert!(
                !InputFailure::from_error("i", &e).recoverable_elsewhere,
                "{e:?} must not claim another egress would help"
            );
        }
    }

    #[test]
    fn an_empty_walk_is_NOT_complete() {
        // The vacuity guard, and the reason `scanned` is in the wire shape at
        // all: zero failures over zero inputs must never read as "warm". A
        // discovery bug that finds no inputs would otherwise report success.
        let empty = ArchiveReport { scanned: 0, already_present: 0, fetched: 0, failures: vec![] };
        assert!(!empty.is_complete(), "an empty walk has not earned 'complete'");

        let real = ArchiveReport { scanned: 3, already_present: 3, fetched: 0, failures: vec![] };
        assert!(real.is_complete());
    }

    #[test]
    fn recoverable_filters_to_exactly_the_throttles() {
        let r = ArchiveReport {
            scanned: 4,
            already_present: 1,
            fetched: 0,
            failures: vec![
                InputFailure::from_error("a", &throttled(Some(5))),
                InputFailure::from_error("b", &FetchError::NotFound { url: "u".into() }),
                InputFailure::from_error("c", &throttled(None)),
            ],
        };
        let names: Vec<&str> = r.recoverable().map(|f| f.input.as_str()).collect();
        assert_eq!(names, vec!["a", "c"]);
        assert!(!r.is_complete());
    }

    #[test]
    fn the_json_shape_is_the_contract_a_consumer_reads() {
        // Field names and tag spellings are wire-facing. Pinning them here means
        // a rename is a failing test rather than a consumer that silently stops
        // matching — the same failure mode as the prose-matching this replaces.
        let r = ArchiveReport {
            scanned: 2,
            already_present: 1,
            fetched: 0,
            failures: vec![InputFailure::from_error("nixpkgs", &throttled(Some(90)))],
        };
        let v: serde_json::Value = serde_json::to_value(&r).expect("serializes");
        assert_eq!(v["scanned"], 2);
        assert_eq!(v["already_present"], 1);
        assert_eq!(v["failures"][0]["kind"], "throttled", "kebab-case tag");
        assert_eq!(v["failures"][0]["status"], 429);
        assert_eq!(v["failures"][0]["retry_after"], 90);
        assert_eq!(v["failures"][0]["recoverable_elsewhere"], true);
        assert_eq!(v["failures"][0]["input"], "nixpkgs");

        // Absent optionals are OMITTED, not null — a consumer checking
        // presence must not have to also check for null.
        let r2 = ArchiveReport {
            scanned: 1,
            already_present: 0,
            fetched: 0,
            failures: vec![InputFailure::from_error("x", &FetchError::Download("dns".into()))],
        };
        let v2: serde_json::Value = serde_json::to_value(&r2).unwrap();
        assert!(v2["failures"][0].get("status").is_none());
        assert!(v2["failures"][0].get("retry_after").is_none());
        assert_eq!(v2["failures"][0]["kind"], "transport");
    }
}

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

    /// Build a response carrying only what the classifier reads.
    fn resp(status: u16, headers: &[(&str, &str)]) -> ureq::http::Response<()> {
        let mut b = ureq::http::Response::builder().status(status);
        for (k, v) in headers {
            b = b.header(*k, *v);
        }
        b.body(()).expect("a status + headers response always builds")
    }

    const URL: &str = "https://api.github.com/repos/o/r/tarball/deadbeef";

    #[test]
    fn a_429_is_throttled_and_keeps_the_servers_own_retry_after() {
        // The measured case. `Retry-After` is the only authority on how long to
        // wait, and it used to be discarded unread.
        let e = classify_status(URL, &resp(429, &[("retry-after", "120")]));
        assert!(matches!(
            e,
            FetchError::Throttled {
                status: 429,
                retry_after: Some(120),
                ..
            }
        ));
        assert!(e.is_throttled());
        assert_eq!(e.status(), Some(429));
    }

    #[test]
    fn a_429_without_a_header_is_still_throttled() {
        // GitHub's archive throttle frequently sends no Retry-After. Absence of
        // advice must not downgrade the classification.
        let e = classify_status(URL, &resp(429, &[]));
        assert!(matches!(e, FetchError::Throttled { retry_after: None, .. }));
        assert!(e.is_throttled());
    }

    #[test]
    fn a_403_with_retry_after_is_a_throttle_not_a_credential_fault() {
        // GitHub spells its secondary rate limit 403. Reading it as an auth
        // failure sends an operator to re-provision a token that is fine.
        let e = classify_status(URL, &resp(403, &[("retry-after", "60")]));
        assert!(
            e.is_throttled(),
            "a 403 that says 'come back later' is a throttle, got {e:?}"
        );
    }

    #[test]
    fn a_bare_403_is_a_credential_fault_and_NOT_recoverable_elsewhere() {
        // The other half of the pair: without the header, 403 means our
        // credential. Answering `is_throttled` here would send a caller to
        // build a second fetch path that is refused identically.
        let e = classify_status(URL, &resp(403, &[]));
        assert!(matches!(e, FetchError::Unauthorized { status: 403, .. }));
        assert!(!e.is_throttled());
    }

    #[test]
    fn a_404_says_it_may_be_an_invisible_private_input() {
        let e = classify_status(URL, &resp(404, &[]));
        assert!(matches!(e, FetchError::NotFound { .. }));
        assert_eq!(e.status(), Some(404));
        // For a private flake input a 404 is routinely an auth failure wearing
        // a not-found mask, so the message must not assert absence.
        let msg = e.to_string();
        assert!(msg.contains("invisible to this credential"), "got {msg}");
    }

    #[test]
    fn an_unhandled_status_arrives_as_a_NUMBER_never_as_prose() {
        // The anti-regression variant: a status nobody wrote an arm for must
        // still reach the caller as a u16, so widening HTTP behaviour cannot
        // silently re-create the single-String bucket this enum replaced.
        let e = classify_status(URL, &resp(503, &[]));
        assert!(matches!(e, FetchError::UnexpectedStatus { status: 503, .. }));
        assert_eq!(e.status(), Some(503));
        assert!(!e.is_throttled());
    }

    #[test]
    fn no_two_http_failures_render_the_same_bytes() {
        // ★★ kotae: a caller must be able to tell these apart. If any two
        // rendered identically, a consumer would be back to guessing — the
        // defect that made a downstream tool grep this crate's error text.
        //
        // The variants are constructed DIRECTLY at a deliberately CONSTANT
        // status, and that shape is the whole point. An earlier version of this
        // test classified four different statuses and compared the results — it
        // passes trivially, because the status number is interpolated into every
        // message, so the strings differ no matter how badly the *variants*
        // collide. Red-running proved it: NotFound's message was rewritten to be
        // byte-identical to UnexpectedStatus's and this test still went GREEN
        // while an unrelated test caught the break. A test that cannot fail for
        // the reason it names is worse than no test, because its green reads as
        // coverage of a property nobody is checking.
        let u = URL.to_string();
        let cases: Vec<(&str, FetchError)> = vec![
            ("Throttled(no advice)",  FetchError::Throttled { url: u.clone(), status: 404, retry_after: None }),
            ("Throttled(advice)",     FetchError::Throttled { url: u.clone(), status: 404, retry_after: Some(30) }),
            ("Unauthorized",          FetchError::Unauthorized { url: u.clone(), status: 404 }),
            ("NotFound",              FetchError::NotFound { url: u.clone() }),
            ("UnexpectedStatus",      FetchError::UnexpectedStatus { url: u.clone(), status: 404 }),
            ("Download",              FetchError::Download(format!("{u}: connection reset"))),
        ];

        for (i, (name_a, a)) in cases.iter().enumerate() {
            for (name_b, b) in cases.iter().skip(i + 1) {
                assert_ne!(
                    a.to_string(),
                    b.to_string(),
                    "{name_a} and {name_b} render identically at the same status \
                     — a caller cannot distinguish them"
                );
            }
        }
    }

    #[test]
    fn an_http_date_retry_after_yields_none_rather_than_a_guess() {
        // RFC 9110 allows an HTTP-date. We do not parse it, and `None` is the
        // honest answer: a caller given None uses its own bounded policy, while
        // a caller given a wrong number obeys it.
        let h = resp(429, &[("retry-after", "Wed, 21 Oct 2026 07:28:00 GMT")]);
        assert_eq!(retry_after_seconds(h.headers()), None);
        // ...and the classification is unaffected.
        assert!(classify_status(URL, &h).is_throttled());
    }

    #[test]
    fn a_junk_retry_after_does_not_panic_or_lie() {
        for v in ["", "  ", "abc", "-5", "12.5", "9999999999999999999999"] {
            let h = resp(429, &[("retry-after", v)]);
            assert_eq!(
                retry_after_seconds(h.headers()),
                None,
                "{v:?} must not parse"
            );
        }
        assert_eq!(retry_after_seconds(resp(429, &[("retry-after", " 30 ")]).headers()), Some(30));
    }

    #[test]
    fn a_transport_failure_is_not_given_a_status() {
        // `Download` is reserved for DNS/TLS/timeout — things with no response.
        // If it ever reported a status, the two categories would have merged
        // again.
        let e = FetchError::Download("dns failure".into());
        assert_eq!(e.status(), None);
        assert!(!e.is_throttled());
    }
}

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

    /// Helper: build a `LockedInput` with the given fields.
    fn make_locked(source_type: &str) -> LockedInput {
        LockedInput {
            source_type: source_type.to_string(),
            owner: None,
            repo: None,
            rev: None,
            nar_hash: None,
            last_modified: None,
            path: None,
            url: None,
            git_ref: None,
            dir: None,
            host: None,
            extra: BTreeMap::new(),
        }
    }

    // ── sanitize_hash ─────────────────────────────────────

    #[test]
    fn sanitize_hash_replaces_special_chars() {
        assert_eq!(
            sanitize_hash("sha256-AAAAAAAAAAAAAAAAAAAAAA="),
            "sha256-AAAAAAAAAAAAAAAAAAAAAA"
        );
        assert_eq!(sanitize_hash("sha256:abc/def="), "sha256-abc_def");
    }

    // ── sanitize_hash — a component, not a transliteration ──

    #[test]
    fn a_traversal_hash_cannot_become_a_path_component() {
        // `narHash` is lock-file input. `..` survives the substitutions and
        // would make the cache dest `<cache>/inputs/..` = `~/.cache/sui`,
        // which then gets returned AS the flake source and, on a miss,
        // remove_dir_all'd — taking `inputs/` and `nar-memo/` with it.
        for hostile in ["..", ".", "", "../..", "..\u{0}"] {
            let s = sanitize_hash(hostile);
            assert!(
                s != ".." && s != "." && !s.is_empty(),
                "{hostile:?} sanitized to {s:?}, still a meaningful component"
            );
            assert!(
                !s.contains('/') && !s.contains('\\'),
                "{hostile:?} sanitized to {s:?}, still a separator"
            );
        }
        // Deterministic — the same input must key the same directory.
        assert_eq!(sanitize_hash(".."), sanitize_hash(".."));
        // …and distinct inputs must not collide onto one entry.
        assert_ne!(sanitize_hash(".."), sanitize_hash("."));
    }

    #[test]
    fn a_well_formed_hash_is_untouched_by_the_guard() {
        // The guard must not change the key for ordinary input, or every
        // existing cache entry is orphaned on upgrade.
        assert_eq!(
            sanitize_hash("sha256-avzRM+ffKgikqMRcOhhYp3ifgwXMGbH0rEGEZPEGMYE="),
            "sha256-avzRM+ffKgikqMRcOhhYp3ifgwXMGbH0rEGEZPEGMYE"
        );
        assert_eq!(sanitize_hash("sha256:abc/def="), "sha256-abc_def");
    }

    // ── publish — never leave `dest` absent during a tree walk ──

    #[test]
    fn publishing_an_immutable_tree_adopts_the_winner_and_deletes_nothing() {
        let tmp = tempfile::tempdir().unwrap();
        let dest = tmp.path().join("github-o-r-deadbeef");
        let staging = staging_path(&dest);
        // A concurrent process already published.
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("theirs"), b"x").unwrap();
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("ours"), b"y").unwrap();

        publish(&staging, &dest, true).unwrap();

        assert!(
            dest.join("theirs").exists(),
            "an immutable tree is content-addressed: the winner's tree IS ours, \
             and deleting it to install an identical one is pure risk"
        );
        assert!(!staging.exists(), "our staging must be cleaned up");
    }

    #[test]
    fn publishing_a_mutable_tree_replaces_it_without_a_delete_in_place() {
        let tmp = tempfile::tempdir().unwrap();
        let dest = tmp.path().join("github-o-r-main");
        let staging = staging_path(&dest);
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("old"), b"x").unwrap();
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("new"), b"y").unwrap();

        publish(&staging, &dest, false).unwrap();

        assert!(dest.join("new").exists(), "the new tree must be published");
        assert!(!dest.join("old").exists(), "and must REPLACE, not union");
        assert!(!staging.exists());
        // The aside must not be left behind as cache litter.
        let leftovers: Vec<_> = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(Result::ok)
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.contains(".old"))
            .collect();
        assert!(leftovers.is_empty(), "aside dirs left behind: {leftovers:?}");
    }

    #[test]
    fn staging_is_scoped_by_thread_not_only_by_pid() {
        // An earlier version keyed on pid alone and CLAIMED two concurrent
        // fetchers could not collide. Two threads of one process share a pid,
        // so the second one's cleanup would delete the first one's half-built
        // tree and the first would then publish a truncated one.
        let dest = std::path::Path::new("/c/inputs/github-o-r-deadbeef");
        let here = staging_path(dest);
        let there = std::thread::spawn(move || staging_path(dest))
            .join()
            .unwrap();
        assert_ne!(
            here, there,
            "two threads must not share a staging directory"
        );
    }

    // ── is_immutable_rev — what may be served from cache ──

    #[test]
    fn only_a_full_object_id_is_treated_as_immutable() {
        // sha1 and the sha256 transition: one rev, one tree, forever.
        assert!(is_immutable_rev("7fd33221240a3ab97781a066c5efe0124979527f"));
        assert!(is_immutable_rev(&"a".repeat(64)));

        // ── ★ THE ONE THAT MATTERS ───────────────────────────────────────
        // `github:owner/repo/main` is a legal ref and CppNix accepts it, so
        // we must too — but the tree behind it MOVES. Caching it as if
        // immutable would freeze the entry at whatever `main` was the first
        // time it was fetched. There is a `github-pleme-io-nix-main`
        // directory in the live cache today, so this is not hypothetical.
        assert!(!is_immutable_rev("main"), "a branch name is not a commit");
        assert!(!is_immutable_rev("v1.2.3"), "a tag can be moved");
        assert!(!is_immutable_rev("7fd3322"), "a short rev is ambiguous");
        assert!(!is_immutable_rev(""), "an empty rev names nothing");

        // Length alone is not enough — 40 non-hex chars is not an object id.
        assert!(!is_immutable_rev(&"z".repeat(40)));
        // Uppercase is refused deliberately: git emits lowercase, and
        // accepting both would give one tree two cache entries.
        assert!(!is_immutable_rev(&"A".repeat(40)));
    }

    // ── staging_path — atomicity depends on it being a SIBLING ──

    #[test]
    fn staging_is_a_sibling_so_the_publish_rename_is_atomic() {
        let dest = std::path::Path::new("/cache/sui/inputs/sha256-abc/github-o-r-deadbeef");
        let staging = staging_path(dest);
        assert_eq!(
            staging.parent(),
            dest.parent(),
            "staging in /tmp would put the rename across filesystems, where it \
             is a copy — and a copy is not atomic, which is the whole point"
        );
        assert_ne!(staging, dest.to_path_buf());
        let name = staging.file_name().unwrap().to_string_lossy().into_owned();
        assert!(name.starts_with('.'), "hidden, so it is not mistaken for a tree");
        assert!(
            name.contains(&std::process::id().to_string()),
            "pid-scoped, so two concurrent fetchers cannot share a staging dir"
        );
        // A dotted directory name must not be truncated the way
        // `Path::with_extension` would truncate it.
        let dotted = std::path::Path::new("/c/github-o-r-1.2.3");
        assert!(
            staging_path(dotted)
                .file_name()
                .unwrap()
                .to_string_lossy()
                .contains("github-o-r-1.2.3"),
            "the full directory name must survive into the staging name"
        );
    }

    // ── find_single_subdir_or_self ────────────────────────

    #[test]
    fn find_single_subdir_returns_child_when_one_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let child = tmp.path().join("repo-abc123");
        std::fs::create_dir(&child).unwrap();
        std::fs::write(child.join("file.txt"), "hello").unwrap();

        let result = find_single_subdir_or_self(tmp.path());
        assert_eq!(result, child);
    }

    #[test]
    fn find_single_subdir_returns_self_when_multiple() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir(tmp.path().join("a")).unwrap();
        std::fs::create_dir(tmp.path().join("b")).unwrap();

        let result = find_single_subdir_or_self(tmp.path());
        assert_eq!(result, tmp.path());
    }

    #[test]
    fn find_single_subdir_returns_self_when_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let result = find_single_subdir_or_self(tmp.path());
        assert_eq!(result, tmp.path());
    }

    #[test]
    fn find_single_subdir_returns_self_when_child_is_file() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("file.txt"), "data").unwrap();
        let result = find_single_subdir_or_self(tmp.path());
        assert_eq!(result, tmp.path());
    }

    // ── url_to_safe_name ──────────────────────────────────

    #[test]
    fn url_to_safe_name_replaces_slashes_and_colons() {
        let name = url_to_safe_name("https://example.com/foo/bar.tar.gz");
        assert!(!name.contains('/'));
        assert!(!name.contains(':'));
        assert!(name.contains("example"));
    }

    // ── InputFetcher construction ─────────────────────────

    #[test]
    fn fetcher_with_custom_cache_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().to_path_buf());
        assert_eq!(fetcher.cache_dir(), tmp.path());
    }

    #[test]
    fn fetcher_default_cache_dir_exists() {
        let fetcher = InputFetcher::new();
        // The path should end with "sui/inputs".
        let path_str = fetcher.cache_dir().to_string_lossy();
        assert!(path_str.ends_with("sui/inputs"), "got: {path_str}");
    }

    // ── path-type fetch ───────────────────────────────────

    #[test]
    fn fetch_path_returns_filesystem_path() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));

        let mut locked = make_locked("path");
        locked.path = Some("/var/empty/dep".to_string());

        let result = fetcher.fetch(&locked).unwrap();
        assert_eq!(result, PathBuf::from("/var/empty/dep"));
    }

    #[test]
    fn fetch_path_missing_field_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let locked = make_locked("path");
        let result = fetcher.fetch(&locked);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("path"));
    }

    // ── unsupported type ──────────────────────────────────

    #[test]
    fn fetch_unsupported_type_returns_error() {
        // `mercurial` — parser doesn't produce this and fetcher
        // doesn't handle it. Remains unsupported for now. If a
        // future commit adds mercurial support, swap this to the
        // next truly-unsupported source_type to keep the test
        // meaningful.
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let locked = make_locked("mercurial");
        let result = fetcher.fetch(&locked);
        assert!(matches!(result, Err(FetchError::UnsupportedType(_))));
    }

    #[test]
    fn gitlab_archive_url_is_well_formed() {
        assert_eq!(
            InputFetcher::gitlab_archive_url(None, "group", "proj", "abc123"),
            "https://gitlab.com/group/proj/-/archive/abc123/proj-abc123.tar.gz"
        );
    }

    #[test]
    fn gitlab_archive_url_honors_custom_host() {
        assert_eq!(
            InputFetcher::gitlab_archive_url(Some("gitlab.gnome.org"), "GNOME", "gnome-shell", "abc"),
            "https://gitlab.gnome.org/GNOME/gnome-shell/-/archive/abc/gnome-shell-abc.tar.gz"
        );
    }

    #[test]
    fn sourcehut_archive_url_prepends_tilde() {
        // Sourcehut owner names on the platform carry a `~` prefix
        // (`~emersion`) but the flake-ref parser drops it. Fetcher
        // must reinstate so the URL is canonical.
        assert_eq!(
            InputFetcher::sourcehut_archive_url("emersion", "page", "HEAD"),
            "https://git.sr.ht/~emersion/page/archive/HEAD.tar.gz"
        );
        // If the caller already included `~`, don't double it.
        assert_eq!(
            InputFetcher::sourcehut_archive_url("~emersion", "page", "HEAD"),
            "https://git.sr.ht/~emersion/page/archive/HEAD.tar.gz"
        );
    }

    // ── cache hit ─────────────────────────────────────────

    #[test]
    fn cache_hit_returns_cached_path() {
        let tmp = tempfile::tempdir().unwrap();
        let cache_dir = tmp.path().join("cache");
        std::fs::create_dir_all(&cache_dir).unwrap();

        // Pre-populate cache.
        let hash = "sha256-TESTCACHEHIT";
        let cached_dir = cache_dir.join(sanitize_hash(hash));
        std::fs::create_dir_all(&cached_dir).unwrap();
        std::fs::write(cached_dir.join("flake.nix"), "{}").unwrap();

        let fetcher = InputFetcher::with_cache_dir(cache_dir);
        let mut locked = make_locked("github");
        locked.nar_hash = Some(hash.to_string());
        // Intentionally leave owner/repo/rev empty — cache hit should skip fetch.

        let result = fetcher.fetch(&locked).unwrap();
        // The cached directory has one file (not a subdir), so it returns itself.
        assert_eq!(result, cached_dir);
    }

    // ── github URL construction ───────────────────────────

    #[test]
    fn github_archive_url_format() {
        let url = InputFetcher::github_archive_url("nixos", "nixpkgs", "abc123");
        assert_eq!(
            url,
            "https://github.com/nixos/nixpkgs/archive/abc123.tar.gz"
        );
    }

    // ── github fetch missing fields ───────────────────────

    #[test]
    fn fetch_github_missing_owner_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let mut locked = make_locked("github");
        locked.repo = Some("nixpkgs".into());
        locked.rev = Some("abc123".into());
        let result = fetcher.fetch(&locked);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("owner"));
    }

    #[test]
    fn fetch_github_missing_rev_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let mut locked = make_locked("github");
        locked.owner = Some("nixos".into());
        locked.repo = Some("nixpkgs".into());
        let result = fetcher.fetch(&locked);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("rev"));
    }

    // ── git fetch missing fields ──────────────────────────

    #[test]
    fn fetch_git_missing_url_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let mut locked = make_locked("git");
        locked.rev = Some("abc123".into());
        let result = fetcher.fetch(&locked);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("url"));
    }

    #[test]
    fn fetch_git_missing_rev_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let mut locked = make_locked("git");
        locked.url = Some("https://example.com/repo.git".into());
        let result = fetcher.fetch(&locked);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("rev"));
    }

    // ── tarball fetch missing URL ─────────────────────────

    #[test]
    fn fetch_tarball_missing_url_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let fetcher = InputFetcher::with_cache_dir(tmp.path().join("cache"));
        let locked = make_locked("tarball");
        let result = fetcher.fetch(&locked);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("url"));
    }

    // ── extract_tar_gz ────────────────────────────────────

    #[test]
    fn extract_tar_gz_empty_archive_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let result = extract_tar_gz(&[], tmp.path());
        assert!(result.is_err());
    }

    #[test]
    fn extract_tar_gz_invalid_data_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let result = extract_tar_gz(b"not a gzip stream at all", tmp.path());
        assert!(result.is_err());
    }

    // ── dest_dir logic ────────────────────────────────────

    #[test]
    fn dest_dir_uses_nar_hash_when_present() {
        let fetcher = InputFetcher::with_cache_dir(PathBuf::from("/cache"));
        let mut locked = make_locked("github");
        locked.nar_hash = Some("sha256-ABC123=".to_string());
        let dest = fetcher.dest_dir(&locked, "fallback");
        assert!(dest.to_string_lossy().contains("sha256-ABC123"));
        assert!(!dest.to_string_lossy().contains("fallback"));
    }

    #[test]
    fn dest_dir_uses_fallback_when_no_hash() {
        let fetcher = InputFetcher::with_cache_dir(PathBuf::from("/cache"));
        let locked = make_locked("github");
        let dest = fetcher.dest_dir(&locked, "fallback-name");
        assert!(dest.to_string_lossy().contains("fallback-name"));
    }

    // ── is_non_empty_dir ─────────────────────────────────

    #[test]
    fn is_non_empty_dir_returns_true_for_non_empty() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("file.txt"), "data").unwrap();
        assert!(is_non_empty_dir(tmp.path()));
    }

    #[test]
    fn is_non_empty_dir_returns_false_for_empty() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(!is_non_empty_dir(tmp.path()));
    }

    #[test]
    fn is_non_empty_dir_returns_false_for_missing() {
        assert!(!is_non_empty_dir(Path::new("/nonexistent/path/12345")));
    }

    // ── empty cache invalidation ─────────────────────────

    #[test]
    fn empty_cache_dir_is_treated_as_miss() {
        let tmp = tempfile::tempdir().unwrap();
        let cache_dir = tmp.path().join("cache");
        std::fs::create_dir_all(&cache_dir).unwrap();

        // Pre-create an *empty* cache directory (simulates a failed fetch).
        let hash = "sha256-EMPTYTEST";
        let cached_dir = cache_dir.join(sanitize_hash(hash));
        std::fs::create_dir_all(&cached_dir).unwrap();
        // Verify the directory is empty.
        assert!(std::fs::read_dir(&cached_dir).unwrap().next().is_none());

        let fetcher = InputFetcher::with_cache_dir(cache_dir);
        let mut locked = make_locked("github");
        locked.nar_hash = Some(hash.to_string());
        // owner/repo/rev are missing, so the re-fetch will fail — but
        // the important thing is that the cache miss was detected (the
        // stale directory was removed) and the code attempted a fresh fetch.
        let result = fetcher.fetch(&locked);
        assert!(result.is_err(), "should not return stale empty cache");
        // The empty directory should have been cleaned up.
        assert!(!cached_dir.exists(), "stale cache dir should be removed");
    }

    // ── github_tarball_from_git_url ──────────────────────

    #[test]
    fn tarball_from_https_github() {
        let url = github_tarball_from_git_url(
            "https://github.com/NixOS/nixpkgs.git",
            "abc123",
        );
        assert_eq!(
            url.as_deref(),
            Some("https://github.com/NixOS/nixpkgs/archive/abc123.tar.gz")
        );
    }

    #[test]
    fn tarball_from_git_plus_https() {
        let url = github_tarball_from_git_url(
            "git+https://github.com/NixOS/nixpkgs",
            "def456",
        );
        assert_eq!(
            url.as_deref(),
            Some("https://github.com/NixOS/nixpkgs/archive/def456.tar.gz")
        );
    }

    #[test]
    fn tarball_from_non_github_returns_none() {
        assert!(github_tarball_from_git_url("https://gitlab.com/foo/bar.git", "abc").is_none());
        assert!(github_tarball_from_git_url("ssh://git@github.com/foo/bar", "abc").is_none());
    }

    #[test]
    fn tarball_from_malformed_path_returns_none() {
        assert!(github_tarball_from_git_url("https://github.com/", "abc").is_none());
        assert!(github_tarball_from_git_url("https://github.com/only-owner", "abc").is_none());
    }
}


/// Turn a parsed flake reference into a directory on disk, fetching it first
/// if it is remote.
///
/// ── ★ ONE PLACE, BECAUSE THERE ARE THREE CALLERS ────────────────────────
/// `evaluate_flake` takes a `&Path`, so every entry point that accepts a
/// `--flake` argument has to answer "where is it?" — `sui-orchestrate`'s
/// `build_toplevel` and two sites in the `sui` CLI. Written per-caller, the
/// remote case would be right in whichever one was being fixed and missing in
/// the others, which is precisely how `github:` refs came to work in some
/// paths and not the one the fleet reconciler uses.
///
/// A local ref costs nothing here. A remote one is content-addressed and
/// cached by the same fetcher that pulls locked flake inputs, so re-resolving
/// the same rev does no network.
///
/// # Errors
///
/// Returns [`FetchError`] when a remote source cannot be fetched or
/// extracted.
pub fn resolve_flake_dir(flake_ref: &FlakeRef) -> Result<std::path::PathBuf, FetchError> {
    match flake_ref.local_dir() {
        Some(p) => Ok(p.to_path_buf()),
        None => {
            let locked = flake_ref
                .source
                .locked_input()
                .ok_or_else(|| FetchError::UnsupportedType("non-fetchable flake source".into()))?;
            InputFetcher::new().fetch(&locked)
        }
    }
}