aither-sandbox 0.28.0

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

use futures::{StreamExt, TryStreamExt, stream};
use futures_lite::io::AsyncReadExt;
use serde::{Deserialize, Serialize};
use url::Url;
use zenwave::Client;

use crate::tool_runtime::{
    DistributedTool, HostProgram, HostProgramPath, ImageTool, ImageTools, ManagedTool, PythonPin,
    PythonRuntime, ToolBinary, ToolBundle, ToolRuntimeError, ToolTarget, check_python, digest,
};

/// A kind of program a manifest artifact can provide.
trait Distributed: Copy + Send + Sync + Into<DistributedTool> {}

impl<P: Copy + Send + Sync + Into<DistributedTool>> Distributed for P {}

/// Largest xz decoder memory a trusted artifact may demand, in KiB.
const XZ_MEMORY_LIMIT_KIB: u32 = 256 * 1024;

/// Encoding of an artifact, with exactly one executable selected from archives.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "format", rename_all = "snake_case")]
pub enum ToolArtifactFormat {
    /// Uncompressed executable.
    Executable,
    /// Gzip-compressed tar archive.
    TarGzip {
        /// Regular-file member containing the executable.
        executable: PathBuf,
    },
    /// Xz-compressed tar archive.
    TarXz {
        /// Regular-file member containing the executable.
        executable: PathBuf,
    },
    /// Zip archive.
    Zip {
        /// Regular-file member containing the executable.
        executable: PathBuf,
    },
}

/// A remote artifact URL or a path relative to its packaged manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolArtifactLocation {
    /// A credential-free HTTPS URL or absolute local file URL.
    Download(Url),
    /// A portable artifact path beneath the manifest's installation directory.
    Bundled(PathBuf),
}

impl ToolArtifactLocation {
    const fn download_url(&self, tool: DistributedTool) -> Result<&Url, ToolRuntimeError> {
        match self {
            Self::Download(url) => Ok(url),
            Self::Bundled(_) => Err(ToolRuntimeError::ArtifactSource(tool)),
        }
    }
}

/// A version-pinned artifact from a trusted distribution manifest.
///
/// `P` is the kind of program it provides: a sandbox command
/// ([`ToolArtifact`]) or a host program ([`HostProgramArtifact`]).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PinnedArtifact<P> {
    /// Program provided by this artifact.
    pub tool: P,
    /// Semantic version of the program.
    pub version: String,
    /// Platform for which the executable was built.
    pub target: ToolTarget,
    /// Absolute local file URL or HTTPS distribution URL.
    pub url: ToolArtifactLocation,
    /// SHA-256 of the complete artifact, before extraction.
    pub sha256: String,
    /// Length in bytes of the complete artifact, before extraction.
    pub size: u64,
    /// Artifact encoding and executable member.
    pub encoding: ToolArtifactFormat,
}

/// A pinned artifact of a sandbox command.
pub type ToolArtifact = PinnedArtifact<ManagedTool>;

/// A pinned artifact of a host program.
///
/// Besides the archive digest it pins the digest of the executable inside, so
/// a prepared copy is verified without reading the archive.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostProgramArtifact {
    /// The pinned archive.
    #[serde(flatten)]
    pub artifact: PinnedArtifact<HostProgram>,
    /// SHA-256 of the extracted executable.
    pub executable_sha256: String,
}

/// Pinned artifact catalog used by every execution backend.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDistribution {
    artifacts: Vec<ToolArtifact>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    host_programs: Vec<HostProgramArtifact>,
    /// The interpreter the pinned `uv` installs, per platform that has one.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    python: Vec<PythonPin>,
    /// Credential for GitHub release downloads; supplied by the caller, never
    /// part of a manifest.
    #[serde(skip)]
    github_token: Option<GithubToken>,
}

/// A GitHub API token, kept out of `Debug` output.
#[derive(Clone)]
struct GithubToken(String);

impl fmt::Debug for GithubToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("GithubToken(..)")
    }
}

impl ToolDistribution {
    /// Downloads GitHub release artifacts through the authenticated REST API
    /// with `token` instead of anonymously, so anonymous-only rate limits and
    /// outages do not apply. Other URLs are fetched as before; the pinned size
    /// and digest checks are the same either way.
    #[must_use]
    pub fn with_github_token(mut self, token: impl Into<String>) -> Self {
        self.github_token = Some(GithubToken(token.into()));
        self
    }

    /// Loads a trusted, version-pinned manifest.
    ///
    /// # Errors
    /// Rejects malformed manifests or unsupported source protocols.
    pub fn from_json(json: &[u8]) -> Result<Self, ToolRuntimeError> {
        let distribution: Self = serde_json::from_slice(json)?;
        distribution.validate()?;
        Ok(distribution)
    }

    /// Loads a packaged manifest and resolves contained artifacts before validation.
    ///
    /// # Errors
    /// Rejects unreadable manifests, escaping paths and invalid artifact metadata.
    pub async fn from_path(path: &Path) -> Result<Self, ToolRuntimeError> {
        let path = async_fs::canonicalize(path).await?;
        let root = path.parent().ok_or(ToolRuntimeError::InvalidArchive)?;
        let mut distribution: Self = serde_json::from_slice(&async_fs::read(&path).await?)?;
        for artifact in &mut distribution.artifacts {
            resolve_bundled(artifact, root)?;
        }
        for artifact in &mut distribution.host_programs {
            resolve_bundled(&mut artifact.artifact, root)?;
        }
        distribution.validate()?;
        Ok(distribution)
    }

    fn validate(&self) -> Result<(), ToolRuntimeError> {
        for artifact in &self.artifacts {
            validate_artifact(artifact)?;
        }
        for artifact in &self.host_programs {
            validate_artifact(&artifact.artifact)?;
            hex::decode_to_slice(&artifact.executable_sha256, &mut [0; 32])?;
        }
        for pin in &self.python {
            pin.runtime()?;
        }
        Ok(())
    }

    /// The interpreter pinned for `target`: present exactly on the platforms
    /// that provide `uv`. A pin for a platform that does not is not selected.
    ///
    /// # Errors
    /// Rejects a missing or duplicate pin for a platform that needs one.
    fn select_python(
        &self,
        target: &ToolTarget,
    ) -> Result<Option<PythonRuntime>, ToolRuntimeError> {
        let mut pins = self
            .python
            .iter()
            .filter(|pin| &pin.target == target && target.provides_python());
        let runtime = pins.next().map(PythonPin::runtime).transpose()?;
        if pins.next().is_some() {
            return Err(ToolRuntimeError::DuplicatePython);
        }
        check_python(target, runtime.as_ref())?;
        Ok(runtime)
    }

    /// Packages hash-verified executables and a relocatable manifest for installation.
    ///
    /// # Errors
    /// Fails on invalid artifacts, tampered existing content or manifest write failure.
    pub async fn package_into(&self, directory: &Path) -> Result<PathBuf, ToolRuntimeError> {
        self.validate()?;
        async_fs::create_dir_all(directory.join("artifacts")).await?;
        let (artifacts, host_programs) = futures::future::try_join(
            package_artifacts(
                &self.artifacts,
                directory,
                ManagedTool::ALL.len(),
                self.github_token.as_ref(),
            ),
            package_artifacts(
                &self
                    .host_programs
                    .iter()
                    .map(|program| program.artifact.clone())
                    .collect::<Vec<_>>(),
                directory,
                HostProgram::ALL.len(),
                self.github_token.as_ref(),
            ),
        )
        .await?;
        // Packaged artifacts are the bare executable, whose digest the
        // manifest pinned; packaging must have found exactly that.
        let host_programs = host_programs
            .into_iter()
            .map(|artifact| {
                if !self.host_programs.iter().any(|pinned| {
                    pinned.artifact.tool == artifact.tool
                        && pinned.artifact.target == artifact.target
                        && pinned.executable_sha256 == artifact.sha256
                }) {
                    return Err(ToolRuntimeError::Integrity {
                        tool: artifact.tool.into(),
                    });
                }
                Ok(HostProgramArtifact {
                    executable_sha256: artifact.sha256.clone(),
                    artifact,
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        let manifest = directory.join("distribution.json");
        let content = serde_json::to_vec_pretty(&Self {
            artifacts,
            host_programs,
            python: self.python.clone(),
            github_token: None,
        })?;
        let destination = manifest.clone();
        let directory = directory.to_path_buf();
        blocking::unblock(move || {
            use std::io::Write;
            let mut stage = tempfile::NamedTempFile::new_in(directory)?;
            stage.write_all(&content)?;
            stage.persist(destination).map_err(|error| error.error)?;
            Ok::<(), ToolRuntimeError>(())
        })
        .await?;
        Ok(manifest)
    }

    /// The artifacts pinned for `target`, exactly one per tool the target
    /// requires; pins of other tools for it are not selected.
    ///
    /// # Errors
    /// Rejects missing or duplicate required tools for the target.
    fn select_artifacts(&self, target: &ToolTarget) -> Result<Vec<ToolArtifact>, ToolRuntimeError> {
        let required = target.required_tools();
        let selected = self
            .artifacts
            .iter()
            .filter(|artifact| &artifact.target == target && required.contains(&artifact.tool))
            .cloned()
            .collect::<Vec<_>>();
        for &tool in required {
            match selected
                .iter()
                .filter(|artifact| artifact.tool == tool)
                .count()
            {
                0 => return Err(ToolRuntimeError::MissingTool(tool)),
                1 => {}
                _ => return Err(ToolRuntimeError::DuplicateTool(tool)),
            }
        }
        Ok(selected)
    }

    /// The tools a container image must carry for `target`, pinned without bytes.
    ///
    /// Never touches the network or the filesystem: each entry carries the
    /// command, the version it must report and the digest of its pinned
    /// archive, which is all the container backend needs to verify the image.
    ///
    /// # Errors
    /// Rejects missing or duplicate tools for the target, or a manifest pin
    /// whose version or digest is malformed.
    pub fn image_tools(&self, target: &ToolTarget) -> Result<ImageTools, ToolRuntimeError> {
        let tools = self
            .select_artifacts(target)?
            .into_iter()
            .map(|artifact| {
                let mut archive_sha256 = [0; 32];
                hex::decode_to_slice(&artifact.sha256, &mut archive_sha256)?;
                Ok(ImageTool {
                    tool: artifact.tool,
                    version: artifact.version.parse()?,
                    archive_sha256,
                })
            })
            .collect::<Result<Vec<_>, ToolRuntimeError>>()?;
        Ok(ImageTools::new(
            target.clone(),
            tools,
            self.select_python(target)?,
        ))
    }

    /// Stages the executables an image build must place at
    /// [`ImageTools::container_directory`]: `<out>/<image cache key>/bin`,
    /// returning that `<out>/<key>` directory.
    ///
    /// The bundle is downloaded and digest-verified through [`Self::load`]:
    /// downloads are expected on the image-build machine, never on the host
    /// that runs the container.
    ///
    /// # Errors
    /// Rejects missing/duplicate tools, failed downloads, oversized artifacts,
    /// digest mismatch or failed writes.
    ///
    /// # Panics
    /// Panics if the staged directory lacks its required parent.
    pub async fn stage_image_tools(
        &self,
        target: &ToolTarget,
        artifact_cache: &Path,
        out: &Path,
    ) -> Result<PathBuf, ToolRuntimeError> {
        let key = self.image_tools(target)?.cache_key()?;
        let bundle = self.load(target, artifact_cache).await?;
        // The interpreter of an image for another platform is still installed
        // by a `uv` that runs here.
        let installer = if target.provides_python() && *target != ToolTarget::native()? {
            Some(self.load_native_installer(artifact_cache).await?)
        } else {
            None
        };
        let out = out.to_path_buf();
        blocking::unblock(move || {
            let prepared = bundle.prepare_local_sync(&out, &key, installer.as_deref())?;
            Ok(prepared
                .bin_dir()
                .parent()
                .expect("prepared binaries have a parent directory")
                .to_path_buf())
        })
        .await
    }

    /// Loads one complete target bundle concurrently, before shell execution.
    ///
    /// # Errors
    /// Rejects missing/duplicate tools, failed downloads, oversized artifacts,
    /// digest mismatch or unsafe/non-regular archive members.
    pub async fn load(
        &self,
        target: &ToolTarget,
        cache_root: &Path,
    ) -> Result<ToolBundle, ToolRuntimeError> {
        let selected = self.select_artifacts(target)?;
        async_fs::create_dir_all(cache_root).await?;
        let token = self.github_token.clone();
        let binaries = stream::iter(selected)
            .map(|artifact| {
                let cache_root = cache_root.to_path_buf();
                let token = token.clone();
                async move {
                    let bytes = load_artifact(&artifact, &cache_root, token.as_ref()).await?;
                    ToolBinary::verify(artifact.tool, &artifact.version, &digest(&bytes), bytes)
                }
            })
            .buffer_unordered(ManagedTool::ALL.len())
            .try_collect::<Vec<_>>()
            .await?;
        ToolBundle::new(target.clone(), binaries, self.select_python(target)?)
    }

    /// The bytes of the `uv` pinned for the machine running this build, which
    /// installs the interpreter of an image for another platform.
    async fn load_native_installer(
        &self,
        artifact_cache: &Path,
    ) -> Result<Vec<u8>, ToolRuntimeError> {
        let native = ToolTarget::native()?;
        let artifact = self
            .artifacts
            .iter()
            .find(|artifact| artifact.tool == ManagedTool::Uv && artifact.target == native)
            .ok_or(ToolRuntimeError::MissingTool(ManagedTool::Uv))?;
        async_fs::create_dir_all(artifact_cache).await?;
        load_artifact(artifact, artifact_cache, self.github_token.as_ref()).await
    }

    /// Prepares one host program for `target` and returns the path of its
    /// read-only executable, with the same pinning, download and
    /// verification as the sandbox commands. A target other than the host's
    /// yields a file the host does not run, such as one streamed to a server.
    ///
    /// Archives are cached under `<cache_root>/artifacts` and executables
    /// under `<cache_root>/bin/<executable sha256>/<command>`. When that
    /// executable already exists with the pinned digest, the archive is not
    /// read. The path has no way into a [`ToolBundle`], so the program never
    /// reaches a sandbox `PATH` or the command catalog.
    ///
    /// # Errors
    /// Fails with [`ToolRuntimeError::MissingHostProgram`] naming the program
    /// and target when the distribution has no artifact for it,
    /// [`ToolRuntimeError::Integrity`] when the extracted executable
    /// does not have the pinned digest, and on a failed download, archive
    /// digest mismatch, unsafe archive member or I/O failure.
    pub async fn prepare_host_program(
        &self,
        program: HostProgram,
        target: &ToolTarget,
        cache_root: &Path,
    ) -> Result<HostProgramPath, ToolRuntimeError> {
        let mut selected = self
            .host_programs
            .iter()
            .filter(|pinned| pinned.artifact.tool == program && &pinned.artifact.target == target);
        let (os, arch) = (target.os().to_owned(), target.arch().to_owned());
        let pinned = selected
            .next()
            .ok_or_else(|| ToolRuntimeError::MissingHostProgram {
                program,
                os: os.clone(),
                arch: arch.clone(),
            })?;
        if selected.next().is_some() {
            return Err(ToolRuntimeError::DuplicateHostProgram { program, os, arch });
        }
        let mut executable_sha256 = [0; 32];
        hex::decode_to_slice(&pinned.executable_sha256, &mut executable_sha256)?;
        let bin = cache_root.join("bin");
        let cached = {
            let (bin, target) = (bin.clone(), target.clone());
            blocking::unblock(move || {
                HostProgramPath::cached(&bin, program, &target, &executable_sha256)
            })
            .await?
        };
        if let Some(path) = cached {
            return Ok(path);
        }
        let artifacts = cache_root.join("artifacts");
        async_fs::create_dir_all(&artifacts).await?;
        let bytes = load_artifact(&pinned.artifact, &artifacts, self.github_token.as_ref()).await?;
        let target = target.clone();
        blocking::unblock(move || {
            if digest(&bytes) != executable_sha256 {
                return Err(ToolRuntimeError::Integrity {
                    tool: program.into(),
                });
            }
            HostProgramPath::write(&bin, program, &target, &executable_sha256, &bytes)
        })
        .await
    }
}

fn resolve_bundled<P: Distributed>(
    artifact: &mut PinnedArtifact<P>,
    root: &Path,
) -> Result<(), ToolRuntimeError> {
    if let ToolArtifactLocation::Bundled(relative) = &artifact.url {
        validate_member(relative)?;
        let url = Url::from_file_path(root.join(relative))
            .map_err(|()| ToolRuntimeError::ArtifactSource(artifact.tool.into()))?;
        artifact.url = ToolArtifactLocation::Download(url);
    }
    Ok(())
}

fn validate_artifact<P: Distributed>(artifact: &PinnedArtifact<P>) -> Result<(), ToolRuntimeError> {
    let tool = artifact.tool.into();
    let url = artifact.url.download_url(tool)?;
    match url.scheme() {
        "https" | "file" => {}
        _ => return Err(ToolRuntimeError::ArtifactSource(tool)),
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err(ToolRuntimeError::ArtifactSource(tool));
    }
    hex::decode_to_slice(&artifact.sha256, &mut [0; 32])?;
    let _ = semver::Version::parse(&artifact.version)?;
    Ok(())
}

/// Stores every artifact's verified executable beside a relocatable manifest.
async fn package_artifacts<P: Distributed>(
    artifacts: &[PinnedArtifact<P>],
    directory: &Path,
    concurrency: usize,
    token: Option<&GithubToken>,
) -> Result<Vec<PinnedArtifact<P>>, ToolRuntimeError> {
    stream::iter(artifacts.to_vec())
        .map(|mut artifact| {
            let directory = directory.to_path_buf();
            async move {
                let tool = artifact.tool.into();
                let bytes = load_artifact(&artifact, &directory.join("artifacts"), token).await?;
                let sha256 = digest(&bytes);
                let size = bytes.len() as u64;
                let name = hex::encode(sha256);
                let path = directory.join(&name);
                blocking::unblock(move || {
                    use std::io::Write;
                    if path.try_exists()? {
                        if digest(&std::fs::read(&path)?) != sha256 {
                            return Err(ToolRuntimeError::Integrity { tool });
                        }
                    } else {
                        let mut stage = tempfile::NamedTempFile::new_in(&directory)?;
                        stage.write_all(&bytes)?;
                        match stage.persist_noclobber(&path) {
                            Ok(_) => {}
                            Err(error)
                                if error.error.kind() == std::io::ErrorKind::AlreadyExists =>
                            {
                                if digest(&std::fs::read(&path)?) != sha256 {
                                    return Err(ToolRuntimeError::Integrity { tool });
                                }
                            }
                            Err(error) => return Err(error.error.into()),
                        }
                    }
                    Ok::<(), ToolRuntimeError>(())
                })
                .await?;
                artifact.url = ToolArtifactLocation::Bundled(name.clone().into());
                artifact.sha256 = name;
                artifact.size = size;
                artifact.encoding = ToolArtifactFormat::Executable;
                Ok::<_, ToolRuntimeError>(artifact)
            }
        })
        .buffer_unordered(concurrency)
        .try_collect::<Vec<_>>()
        .await
}

/// Fetches an artifact through the cache and returns its extracted executable.
async fn load_artifact<P: Distributed>(
    artifact: &PinnedArtifact<P>,
    cache_root: &Path,
    token: Option<&GithubToken>,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let tool = artifact.tool.into();
    let mut expected = [0; 32];
    hex::decode_to_slice(&artifact.sha256, &mut expected)?;
    let path = cache_root.join(hex::encode(expected));
    let encoded = match read_artifact_file(&path, tool, artifact.size).await {
        Ok(encoded) => encoded,
        Err(ToolRuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
            let encoded = download_artifact(tool, &artifact.url, artifact.size, token).await?;
            if digest(&encoded) != expected {
                return Err(ToolRuntimeError::Integrity { tool });
            }
            let destination = path.clone();
            let root = cache_root.to_path_buf();
            blocking::unblock(move || {
                use std::io::Write;
                let mut stage = tempfile::NamedTempFile::new_in(root)?;
                stage.write_all(&encoded)?;
                match stage.persist_noclobber(destination) {
                    Ok(_) => Ok::<(), ToolRuntimeError>(()),
                    Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
                    Err(error) => Err(error.error.into()),
                }
            })
            .await?;
            read_artifact_file(&path, tool, artifact.size).await?
        }
        Err(error) => return Err(error),
    };
    if digest(&encoded) != expected {
        return Err(ToolRuntimeError::Integrity { tool });
    }
    let encoding = artifact.encoding.clone();
    blocking::unblock(move || extract_executable(&encoding, &encoded)).await
}

/// Reads a file the manifest pins at `size` bytes, rejecting any other length
/// before the content is hashed.
async fn read_artifact_file(
    path: &Path,
    tool: DistributedTool,
    size: u64,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let file = async_fs::File::open(path).await?;
    let mut bytes = Vec::new();
    file.take(size.saturating_add(1))
        .read_to_end(&mut bytes)
        .await?;
    check_size(tool, size, &bytes)?;
    Ok(bytes)
}

/// Rejects `bytes` unless it is exactly the pinned `size`; a read bounded to
/// `size + 1` bytes that overran reports that longer length.
const fn check_size(
    tool: DistributedTool,
    size: u64,
    bytes: &[u8],
) -> Result<(), ToolRuntimeError> {
    let actual = bytes.len() as u64;
    if actual == size {
        Ok(())
    } else {
        Err(ToolRuntimeError::ArtifactSize {
            tool,
            expected: size,
            actual,
        })
    }
}

async fn download_artifact(
    tool: DistributedTool,
    location: &ToolArtifactLocation,
    size: u64,
    token: Option<&GithubToken>,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let url = location.download_url(tool)?;
    let encoded = match url.scheme() {
        "file" => {
            let path = url
                .to_file_path()
                .map_err(|()| ToolRuntimeError::ArtifactSource(tool))?;
            read_artifact_file(&path, tool, size).await?
        }
        "https" => {
            let source = match (token, GithubRelease::parse(url)) {
                (Some(token), Some(release)) => Source::GithubApi {
                    release,
                    api: Url::parse(GITHUB_API).expect("the GitHub API base is a valid URL"),
                    token,
                },
                _ => Source::Direct(url.as_str()),
            };
            download_with_retry(&source, size, DOWNLOAD_RETRY).await?
        }
        _ => return Err(ToolRuntimeError::ArtifactSource(tool)),
    };
    check_size(tool, size, &encoded)?;
    Ok(encoded)
}

/// Base of the GitHub REST API.
const GITHUB_API: &str = "https://api.github.com/";

/// Largest release metadata document read; a release lists its assets, and
/// anything past this is not one.
const RELEASE_METADATA_LIMIT: u64 = 8 * 1024 * 1024;

/// A `github.com/<owner>/<repo>/releases/download/<tag>/<asset>` URL, decoded.
#[derive(Debug, Clone, PartialEq, Eq)]
struct GithubRelease {
    owner: String,
    repo: String,
    tag: String,
    asset: String,
}

impl GithubRelease {
    /// The release asset a github.com download URL names; `None` for any
    /// other URL.
    fn parse(url: &Url) -> Option<Self> {
        if url.scheme() != "https" || url.host_str() != Some("github.com") {
            return None;
        }
        let segments = url
            .path_segments()?
            .map(|segment| {
                percent_encoding::percent_decode_str(segment)
                    .decode_utf8()
                    .ok()
                    .map(std::borrow::Cow::into_owned)
            })
            .collect::<Option<Vec<_>>>()?;
        let [owner, repo, releases, download, tag, asset] =
            <[String; 6]>::try_from(segments).ok()?;
        let named = [&owner, &repo, &tag, &asset]
            .iter()
            .all(|segment| !segment.is_empty());
        (named && releases == "releases" && download == "download").then_some(Self {
            owner,
            repo,
            tag,
            asset,
        })
    }

    /// `GET /repos/{owner}/{repo}/releases/tags/{tag}` under `api`.
    fn release_url(&self, api: &Url) -> Url {
        self.api_url(api, &["releases", "tags", &self.tag])
    }

    /// `GET /repos/{owner}/{repo}/releases/assets/{id}` under `api`.
    fn asset_url(&self, api: &Url, id: u64) -> Url {
        self.api_url(api, &["releases", "assets", &id.to_string()])
    }

    fn api_url(&self, api: &Url, tail: &[&str]) -> Url {
        let mut url = api.clone();
        url.path_segments_mut()
            .expect("the API base can be a base")
            .clear()
            .extend(["repos", &self.owner, &self.repo])
            .extend(tail);
        url
    }
}

/// The part of a GitHub release the asset lookup reads.
#[derive(Debug, Deserialize)]
struct ReleaseMetadata {
    assets: Vec<ReleaseAsset>,
}

#[derive(Debug, Deserialize)]
struct ReleaseAsset {
    id: u64,
    name: String,
}

impl ReleaseMetadata {
    fn asset_id(&self, name: &str) -> Option<u64> {
        self.assets
            .iter()
            .find(|asset| asset.name == name)
            .map(|asset| asset.id)
    }
}

/// Where a download attempt fetches the artifact from.
enum Source<'a> {
    /// A plain GET of the URL, with no credentials.
    Direct(&'a str),
    /// The release asset through the REST API at `api`, authenticated with
    /// `token`.
    GithubApi {
        release: GithubRelease,
        api: Url,
        token: &'a GithubToken,
    },
}

/// Retry schedule for transient artifact download failures.
#[derive(Clone, Copy, Debug)]
struct DownloadRetry {
    /// Total attempts, the first included.
    attempts: u32,
    /// Wait before the second attempt; each later wait doubles.
    initial_backoff: Duration,
    /// Deadline of a single attempt.
    attempt_timeout: Duration,
}

/// Four attempts with 1 s, 2 s and 4 s between them and 60 s per attempt: the
/// worst case is 4 * 60 s + 7 s = 247 s, and the common CI failure (a dropped
/// or timed-out connection setup) recovers within seconds.
const DOWNLOAD_RETRY: DownloadRetry = DownloadRetry {
    attempts: 4,
    initial_backoff: Duration::from_secs(1),
    attempt_timeout: Duration::from_secs(60),
};

/// Sent with API requests, which GitHub rejects without a `User-Agent`.
const USER_AGENT: &str = "aither-sandbox";

/// Reads at most `limit` bytes of a successful response.
async fn read_response(
    response: zenwave::Response,
    limit: u64,
) -> Result<Vec<u8>, ToolRuntimeError> {
    if !response.status().is_success() {
        return Err(ToolRuntimeError::DownloadStatus(response.status().as_u16()));
    }
    let mut bytes = Vec::new();
    response
        .into_body()
        .into_reader()
        .take(limit)
        .read_to_end(&mut bytes)
        .await?;
    Ok(bytes)
}

/// One authenticated API GET. The client follows redirects and drops
/// `Authorization` when one leaves the origin, so the signed storage URL a
/// asset download redirects to never sees the token.
async fn api_get(
    client: &mut zenwave::DefaultClient,
    url: &Url,
    accept: &str,
    token: &GithubToken,
) -> Result<zenwave::Response, ToolRuntimeError> {
    Ok(client
        .get(url.as_str())?
        .header("Accept", accept)?
        .header("User-Agent", USER_AGENT)?
        .bearer_auth(token.0.as_str())
        .await?)
}

/// Fetches the artifact once, bounded by the attempt deadline.
async fn download_once(
    source: &Source<'_>,
    size: u64,
    timeout: Duration,
) -> Result<Vec<u8>, ToolRuntimeError> {
    futures_lite::future::or(
        async {
            let mut client = zenwave::client();
            match source {
                Source::Direct(url) => {
                    let response = client.get(*url)?.await?;
                    read_response(response, size.saturating_add(1)).await
                }
                Source::GithubApi {
                    release,
                    api,
                    token,
                } => {
                    let response = api_get(
                        &mut client,
                        &release.release_url(api),
                        "application/vnd.github+json",
                        token,
                    )
                    .await?;
                    let metadata = read_response(response, RELEASE_METADATA_LIMIT).await?;
                    let metadata: ReleaseMetadata = serde_json::from_slice(&metadata)
                        .map_err(ToolRuntimeError::ReleaseMetadata)?;
                    let id = metadata.asset_id(&release.asset).ok_or_else(|| {
                        ToolRuntimeError::ReleaseAssetMissing(release.asset.clone())
                    })?;
                    let response = api_get(
                        &mut client,
                        &release.asset_url(api, id),
                        "application/octet-stream",
                        token,
                    )
                    .await?;
                    read_response(response, size.saturating_add(1)).await
                }
            }
        },
        async {
            async_io::Timer::after(timeout).await;
            Err(ToolRuntimeError::Download(zenwave::Error::Timeout))
        },
    )
    .await
}

/// Whether an HTTP status is worth another attempt: a server fault or throttling.
fn is_transient_status(status: u16) -> bool {
    status == 429 || (500..600).contains(&status)
}

/// Whether a failed download attempt may succeed when repeated. Only the
/// attempt's own failures reach this: connection setup, the deadline, a body
/// read cut off mid-transfer, and the HTTP status. A TLS, redirect, request or
/// proxy error is permanent.
fn is_transient(error: &ToolRuntimeError) -> bool {
    match error {
        ToolRuntimeError::DownloadStatus(status) => is_transient_status(*status),
        ToolRuntimeError::Io(_) => true,
        ToolRuntimeError::Download(error) => match error {
            zenwave::Error::Transport(_) | zenwave::Error::Timeout => true,
            zenwave::Error::Http { status, .. } => is_transient_status(status.as_u16()),
            _ => false,
        },
        _ => false,
    }
}

/// Downloads `url`, retrying transient failures with exponential backoff and
/// failing with the last error once the attempts are spent.
async fn download_with_retry(
    source: &Source<'_>,
    size: u64,
    retry: DownloadRetry,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let mut backoff = retry.initial_backoff;
    let mut attempt = 1;
    loop {
        match download_once(source, size, retry.attempt_timeout).await {
            Err(error) if attempt < retry.attempts && is_transient(&error) => {
                tracing::warn!(
                    %error,
                    attempt,
                    attempts = retry.attempts,
                    retry_in = ?backoff,
                    "tool artifact download failed; retrying"
                );
                async_io::Timer::after(backoff).await;
                backoff *= 2;
                attempt += 1;
            }
            result => return result,
        }
    }
}

/// Reads an archive member in full: the archive's pinned hash fixes its content.
fn read_executable(mut reader: impl Read) -> Result<Vec<u8>, ToolRuntimeError> {
    let mut bytes = Vec::new();
    reader.read_to_end(&mut bytes)?;
    Ok(bytes)
}

fn validate_member(path: &Path) -> Result<(), ToolRuntimeError> {
    if path.as_os_str().is_empty()
        || path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(ToolRuntimeError::InvalidArchive);
    }
    Ok(())
}

/// Reads the one regular member named `executable` from a decompressed tar stream.
fn select_tar_member(reader: impl Read, executable: &Path) -> Result<Vec<u8>, ToolRuntimeError> {
    let mut archive = tar::Archive::new(reader);
    let mut found = None;
    for entry in archive.entries()? {
        let entry = entry?;
        if entry.path()?.as_ref() != executable {
            continue;
        }
        if found.is_some() || !entry.header().entry_type().is_file() {
            return Err(ToolRuntimeError::InvalidArchive);
        }
        found = Some(read_executable(entry)?);
    }
    found.ok_or(ToolRuntimeError::InvalidArchive)
}

fn extract_executable(
    encoding: &ToolArtifactFormat,
    encoded: &[u8],
) -> Result<Vec<u8>, ToolRuntimeError> {
    match encoding {
        ToolArtifactFormat::Executable => Ok(encoded.to_vec()),
        ToolArtifactFormat::TarGzip { executable } => {
            validate_member(executable)?;
            select_tar_member(flate2::read::GzDecoder::new(encoded), executable)
        }
        ToolArtifactFormat::TarXz { executable } => {
            validate_member(executable)?;
            select_tar_member(
                lzma_rust2::XzReader::new_mem_limit(encoded, false, XZ_MEMORY_LIMIT_KIB),
                executable,
            )
        }
        ToolArtifactFormat::Zip { executable } => {
            validate_member(executable)?;
            let name = executable
                .to_str()
                .ok_or(ToolRuntimeError::InvalidArchive)?;
            let mut archive = zip::ZipArchive::new(Cursor::new(encoded))?;
            let mut found = None;
            for index in 0..archive.len() {
                let entry = archive.by_index(index)?;
                if entry.name()? != name {
                    continue;
                }
                if found.is_some() || !entry.is_file() || entry.is_symlink() {
                    return Err(ToolRuntimeError::InvalidArchive);
                }
                found = Some(read_executable(entry)?);
            }
            found.ok_or(ToolRuntimeError::InvalidArchive)
        }
    }
}

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

    pub use crate::tool_runtime::tests::{
        UnlockingTempDir, fixture_python_pin, native_tools, script_tool, unlocking_tempdir,
    };

    /// A distribution pinning one `script_tool` executable per command for
    /// `target`, each artifact located by `url` — file URLs for a fixture that
    /// `load` can read, unreachable URLs where nothing may be downloaded.
    ///
    /// The files are written under `dir`; keep `dir` alive while `load` runs.
    pub fn script_distribution(
        target: &ToolTarget,
        version: &str,
        dir: &Path,
        url: impl Fn(&Path) -> ToolArtifactLocation,
    ) -> ToolDistribution {
        let artifacts = target
            .required_tools()
            .iter()
            .map(|&tool| {
                let bytes = script_tool(tool, version);
                let path = dir.join(tool.command());
                std::fs::write(&path, &bytes).unwrap();
                ToolArtifact {
                    tool,
                    version: version.into(),
                    target: target.clone(),
                    url: url(&path),
                    sha256: hex::encode(digest(&bytes)),
                    size: bytes.len() as u64,
                    encoding: ToolArtifactFormat::Executable,
                }
            })
            .collect();
        ToolDistribution {
            artifacts,
            host_programs: Vec::new(),
            python: python_pins(target),
            github_token: None,
        }
    }

    /// The interpreter pins of `target`: one where it provides `python3`.
    pub fn python_pins(target: &ToolTarget) -> Vec<PythonPin> {
        target
            .provides_python()
            .then(|| fixture_python_pin(target))
            .into_iter()
            .collect()
    }

    /// File-backed artifacts for `script_distribution` fixtures that `load` reads.
    pub fn file_artifact(path: &Path) -> ToolArtifactLocation {
        ToolArtifactLocation::Download(Url::from_file_path(path).unwrap())
    }

    /// An artifact URL that can never be fetched, for fixtures that must
    /// prove nothing is downloaded.
    pub fn unreachable_artifact(_path: &Path) -> ToolArtifactLocation {
        ToolArtifactLocation::Download(Url::parse("http://127.0.0.1:9/tool").unwrap())
    }

    /// The repository's pinned third-party tools; `apply_patch`, `aither-sed` and `bash` are added by a release.
    fn pinned_distribution() -> ToolDistribution {
        ToolDistribution::from_json(include_bytes!("../../patch/third-party-tools.json")).unwrap()
    }

    /// Every tool aither builds is named in the release manifest by its
    /// `patch/built-tools.json` entry, so each name must be a `ManagedTool`.
    #[test]
    fn every_built_tool_is_a_managed_tool() {
        let list: serde_json::Value =
            serde_json::from_slice(include_bytes!("../../patch/built-tools.json")).unwrap();
        for entry in list["tools"].as_array().unwrap() {
            let name = entry["tool"].clone();
            serde_json::from_value::<ManagedTool>(name.clone())
                .unwrap_or_else(|error| panic!("{name} is not a managed tool: {error}"));
        }
    }

    #[test]
    fn pinned_tools_cover_the_required_set_of_every_platform() {
        let pinned = pinned_distribution();
        let mut targets = pinned
            .artifacts
            .iter()
            .map(|artifact| artifact.target.clone())
            .collect::<Vec<_>>();
        targets.sort_by_key(|target| (target.os().to_owned(), target.arch().to_owned()));
        targets.dedup();
        assert_eq!(targets.len(), 5);
        for target in targets {
            for &tool in target.required_tools() {
                let count = pinned
                    .artifacts
                    .iter()
                    .filter(|artifact| artifact.target == target && artifact.tool == tool)
                    .count();
                // A release supplies `apply_patch`, `aither-sed` and `bash`.
                let expected = usize::from(!matches!(
                    tool,
                    ManagedTool::ApplyPatch | ManagedTool::Sed | ManagedTool::Bash
                ));
                assert_eq!(
                    count,
                    expected,
                    "{tool:?} for {}/{}",
                    target.os(),
                    target.arch()
                );
            }
            let pinned_coreutils = pinned.artifacts.iter().any(|artifact| {
                artifact.target == target && artifact.tool == ManagedTool::Coreutils
            });
            assert_eq!(pinned_coreutils, target.os() != "windows");
        }
    }

    #[test]
    fn a_windows_target_selects_only_its_portable_pins() {
        let windows = ToolTarget::from_probe("Windows_NT", "x86_64").unwrap();
        let dir = tempfile::tempdir().unwrap();
        let mut distribution = script_distribution(&windows, "1.0.0", dir.path(), file_artifact);
        // A pin for a tool the platform does not provide is ignored, not required.
        distribution.artifacts.push(ToolArtifact {
            tool: ManagedTool::Coreutils,
            ..distribution.artifacts[0].clone()
        });
        let selected = distribution.select_artifacts(&windows).unwrap();
        assert_eq!(selected.len(), windows.required_tools().len());
        assert!(
            selected
                .iter()
                .all(|artifact| artifact.tool != ManagedTool::Coreutils)
        );
        distribution
            .artifacts
            .retain(|artifact| artifact.tool != ManagedTool::Jq);
        assert!(matches!(
            distribution.select_artifacts(&windows),
            Err(ToolRuntimeError::MissingTool(ManagedTool::Jq))
        ));
    }

    #[test]
    fn the_pinned_uv_and_python_cover_exactly_the_unix_targets() {
        let pinned = pinned_distribution();
        let unix = [
            ("macos", "aarch64"),
            ("linux", "aarch64"),
            ("linux", "x86_64"),
        ];
        for (os, arch) in unix {
            let target = ToolTarget::from_probe(os, arch).unwrap();
            let uv = pinned
                .artifacts
                .iter()
                .filter(|artifact| artifact.target == target && artifact.tool == ManagedTool::Uv)
                .collect::<Vec<_>>();
            assert_eq!(uv.len(), 1, "{os}/{arch}");
            assert_eq!(uv[0].version, "0.13.7");
            let ToolArtifactLocation::Download(url) = &uv[0].url else {
                panic!("pinned artifacts are downloads");
            };
            assert!(
                url.path()
                    .starts_with("/astral-sh/uv/releases/download/0.13.7/"),
                "{os}/{arch}"
            );
            let python = pinned.select_python(&target).unwrap().unwrap();
            assert_eq!(python.version(), &semver::Version::new(3, 13, 18));
            // The pinned request is what `uv python list` offers for the target.
            let request = python.request(&target).unwrap();
            assert!(request.starts_with("cpython-3.13.18-"), "{request}");
            assert!(
                request.ends_with(if os == "macos" { "-none" } else { "-gnu" }),
                "{request}"
            );
        }
        let digests = pinned
            .python
            .iter()
            .map(|pin| pin.interpreter_sha256.clone())
            .collect::<std::collections::HashSet<_>>();
        assert_eq!(digests.len(), pinned.python.len());
        assert_eq!(pinned.python.len(), unix.len());
        let windows = ToolTarget::from_probe("Windows_NT", "x86_64").unwrap();
        assert!(pinned.select_python(&windows).unwrap().is_none());
        assert!(
            !pinned
                .artifacts
                .iter()
                .any(|artifact| artifact.tool == ManagedTool::Uv && artifact.target == windows)
        );
    }

    #[test]
    fn a_missing_or_duplicate_python_pin_is_an_error_where_uv_is_provided() {
        let linux = ToolTarget::from_probe("Linux", "x86_64").unwrap();
        let dir = tempfile::tempdir().unwrap();
        let mut distribution = script_distribution(&linux, "1.0.0", dir.path(), file_artifact);
        distribution.select_python(&linux).unwrap().unwrap();
        distribution.python.push(distribution.python[0].clone());
        assert!(matches!(
            distribution.select_python(&linux),
            Err(ToolRuntimeError::DuplicatePython)
        ));
        distribution.python.clear();
        assert!(matches!(
            distribution.select_python(&linux),
            Err(ToolRuntimeError::MissingPython)
        ));
        // A pin for a platform without `uv` is not selected.
        let windows = ToolTarget::from_probe("Windows_NT", "x86_64").unwrap();
        distribution.python.push(fixture_python_pin(&windows));
        assert!(distribution.select_python(&windows).unwrap().is_none());
    }

    #[test]
    fn a_malformed_python_pin_is_rejected_when_the_manifest_loads() {
        let manifest = |version: &str, digest: &str| {
            format!(
                r#"{{"artifacts":[],"python":[{{"version":"{version}",
                "target":{{"os":"linux","arch":"x86_64"}},"interpreter_sha256":"{digest}"}}]}}"#
            )
        };
        ToolDistribution::from_json(manifest("3.13.18", &"0".repeat(64)).as_bytes()).unwrap();
        for (version, digest) in [
            ("3.13", "0".repeat(64)),
            ("three", "0".repeat(64)),
            ("3.13.18", "0".repeat(63)),
            ("3.13.18", "z".repeat(64)),
        ] {
            assert!(
                ToolDistribution::from_json(manifest(version, &digest).as_bytes()).is_err(),
                "{version} {digest}"
            );
        }
    }

    #[test]
    fn image_tools_carry_the_python_pin_and_catalog_entry() {
        let target = ToolTarget::native().unwrap();
        if !target.provides_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let distribution = script_distribution(&target, "1.0.0", dir.path(), file_artifact);
        let image = distribution.image_tools(&target).unwrap();
        assert_eq!(
            image
                .python
                .as_ref()
                .map(|python| python.version().to_string()),
            Some(crate::tool_runtime::tests::FIXTURE_PYTHON_VERSION.to_owned())
        );
        let mut without = distribution;
        without.python[0].version = "3.13.2".into();
        assert_ne!(
            without.image_tools(&target).unwrap().cache_key().unwrap(),
            image.cache_key().unwrap()
        );
    }

    #[tokio::test]
    async fn stage_image_tools_produces_the_directory_layout_the_image_verifies() {
        let files = tempfile::tempdir().unwrap();
        let out = unlocking_tempdir();
        let target = ToolTarget::native().unwrap();
        let distribution = script_distribution(&target, "1.0.0", files.path(), file_artifact);
        let staged = distribution
            .stage_image_tools(&target, &files.path().join("cache"), out.path())
            .await
            .unwrap();
        let image = distribution.image_tools(&target).unwrap();
        assert_eq!(
            staged,
            std::fs::canonicalize(out.path())
                .unwrap()
                .join(image.cache_key().unwrap())
        );
        for &tool in native_tools() {
            assert!(
                staged
                    .join("bin")
                    .join(tool.executable_name(&target))
                    .is_file()
            );
        }
    }

    #[tokio::test]
    async fn packaged_distribution_remains_valid_after_relocation() {
        let source = tempfile::tempdir().unwrap();
        let installation = tempfile::tempdir().unwrap();
        let relocated = tempfile::tempdir().unwrap();
        let bytes = b"verified artifact fixture";
        let binary = source.path().join("tool");
        async_fs::write(&binary, bytes).await.unwrap();
        let distribution = ToolDistribution {
            artifacts: native_tools()
                .iter()
                .map(|&tool| ToolArtifact {
                    tool,
                    version: "1.0.0".into(),
                    target: ToolTarget::native().unwrap(),
                    url: ToolArtifactLocation::Download(Url::from_file_path(&binary).unwrap()),
                    sha256: hex::encode(digest(bytes)),
                    size: bytes.len() as u64,
                    encoding: ToolArtifactFormat::Executable,
                })
                .collect(),
            host_programs: Vec::new(),
            python: python_pins(&ToolTarget::native().unwrap()),
            github_token: None,
        };
        let manifest = distribution
            .package_into(installation.path())
            .await
            .unwrap();
        async_fs::copy(&manifest, relocated.path().join("distribution.json"))
            .await
            .unwrap();
        let name = hex::encode(digest(bytes));
        async_fs::copy(
            installation.path().join(&name),
            relocated.path().join(&name),
        )
        .await
        .unwrap();
        let loaded = ToolDistribution::from_path(&relocated.path().join("distribution.json"))
            .await
            .unwrap();
        let bundle = loaded
            .load(&ToolTarget::native().unwrap(), &source.path().join("cache"))
            .await
            .unwrap();
        assert_eq!(
            bundle.catalog(),
            distribution
                .load(
                    &ToolTarget::native().unwrap(),
                    &source.path().join("original-cache")
                )
                .await
                .unwrap()
                .catalog()
        );
        async_fs::write(relocated.path().join(name), b"verified artifact fixtur3")
            .await
            .unwrap();
        assert!(matches!(
            loaded
                .load(
                    &ToolTarget::native().unwrap(),
                    &source.path().join("fresh-cache")
                )
                .await,
            Err(ToolRuntimeError::Integrity { .. })
        ));
    }

    #[tokio::test]
    async fn bundled_artifacts_cannot_escape_the_installation() {
        let root = tempfile::tempdir().unwrap();
        let distribution = ToolDistribution {
            artifacts: vec![ToolArtifact {
                tool: ManagedTool::ApplyPatch,
                version: "1.0.0".into(),
                target: ToolTarget::native().unwrap(),
                url: ToolArtifactLocation::Bundled("../outside".into()),
                sha256: "00".repeat(32),
                size: 1,
                encoding: ToolArtifactFormat::Executable,
            }],
            host_programs: Vec::new(),
            python: Vec::new(),
            github_token: None,
        };
        let path = root.path().join("distribution.json");
        async_fs::write(&path, serde_json::to_vec(&distribution).unwrap())
            .await
            .unwrap();
        assert!(matches!(
            ToolDistribution::from_path(&path).await,
            Err(ToolRuntimeError::InvalidArchive)
        ));
    }

    #[test]
    fn artifact_credentials_are_rejected_without_echoing_them() {
        let manifest = ToolDistribution {
            artifacts: vec![ToolArtifact {
                tool: ManagedTool::Ripgrep,
                version: "1.0.0".into(),
                target: ToolTarget::native().unwrap(),
                url: ToolArtifactLocation::Download(
                    Url::parse("https://user:secret@example.com/tool").unwrap(),
                ),
                sha256: "00".repeat(32),
                size: 1,
                encoding: ToolArtifactFormat::Executable,
            }],
            host_programs: Vec::new(),
            python: Vec::new(),
            github_token: None,
        };
        let error =
            ToolDistribution::from_json(&serde_json::to_vec(&manifest).unwrap()).unwrap_err();
        assert!(matches!(
            error,
            ToolRuntimeError::ArtifactSource(DistributedTool::Command(ManagedTool::Ripgrep))
        ));
        assert!(!error.to_string().contains("secret"));
    }

    #[test]
    fn rejects_path_traversal_before_archive_processing() {
        let encoding = ToolArtifactFormat::TarGzip {
            executable: "../rg".into(),
        };
        assert!(matches!(
            extract_executable(&encoding, b""),
            Err(ToolRuntimeError::InvalidArchive)
        ));
    }

    #[test]
    fn only_reads_the_regular_selected_member() {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(7);
        header.set_mode(0o755);
        header.set_cksum();
        tar.append_data(&mut header, "bin/rg", Cursor::new(b"content"))
            .unwrap();
        let contents = tar.into_inner().unwrap();
        let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        std::io::Write::write_all(&mut gzip, &contents).unwrap();
        let encoded = gzip.finish().unwrap();
        let encoding = ToolArtifactFormat::TarGzip {
            executable: "bin/rg".into(),
        };
        assert_eq!(extract_executable(&encoding, &encoded).unwrap(), b"content");
    }

    #[test]
    fn rejects_symlink_members() {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_size(0);
        header.set_mode(0o755);
        header.set_link_name("/etc/passwd").unwrap();
        header.set_cksum();
        tar.append_data(&mut header, "rg", Cursor::new(b""))
            .unwrap();
        let contents = tar.into_inner().unwrap();
        let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        std::io::Write::write_all(&mut gzip, &contents).unwrap();
        let encoded = gzip.finish().unwrap();
        let encoding = ToolArtifactFormat::TarGzip {
            executable: "rg".into(),
        };
        assert!(matches!(
            extract_executable(&encoding, &encoded),
            Err(ToolRuntimeError::InvalidArchive)
        ));
    }

    fn tar_xz(member: &str, content: &[u8]) -> Vec<u8> {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(content.len() as u64);
        header.set_mode(0o755);
        header.set_cksum();
        tar.append_data(&mut header, member, Cursor::new(content))
            .unwrap();
        let contents = tar.into_inner().unwrap();
        let mut xz =
            lzma_rust2::XzWriter::new(Vec::new(), lzma_rust2::XzOptions::with_preset(1)).unwrap();
        std::io::Write::write_all(&mut xz, &contents).unwrap();
        xz.finish().unwrap()
    }

    #[test]
    fn extracts_the_executable_from_a_tar_xz_artifact() {
        let encoded = tar_xz("repo-search-x/search", b"daemon");
        let encoding = ToolArtifactFormat::TarXz {
            executable: "repo-search-x/search".into(),
        };
        assert_eq!(extract_executable(&encoding, &encoded).unwrap(), b"daemon");
        let missing = ToolArtifactFormat::TarXz {
            executable: "other".into(),
        };
        assert!(matches!(
            extract_executable(&missing, &encoded),
            Err(ToolRuntimeError::InvalidArchive)
        ));
        assert!(extract_executable(&encoding, b"not xz").is_err());
    }

    /// A distribution of fixture sandbox commands plus a tar.xz `search` host program.
    struct HostFixture {
        directory: UnlockingTempDir,
        distribution: ToolDistribution,
        executable: &'static [u8],
        archive: PathBuf,
    }

    impl HostFixture {
        async fn new() -> Self {
            let directory = unlocking_tempdir();
            let target = ToolTarget::native().unwrap();
            let executable: &'static [u8] = b"host program fixture";
            let archive = directory.path().join("search.tar.xz");
            let encoded = tar_xz("repo-search/search", executable);
            async_fs::write(&archive, &encoded).await.unwrap();
            let fixture_tools =
                script_distribution(&target, "1.0.0", directory.path(), file_artifact);
            let distribution = ToolDistribution {
                artifacts: fixture_tools.artifacts,
                python: fixture_tools.python,
                host_programs: vec![HostProgramArtifact {
                    artifact: PinnedArtifact {
                        tool: HostProgram::RepoSearch,
                        version: "0.0.3".into(),
                        target,
                        url: ToolArtifactLocation::Download(Url::from_file_path(&archive).unwrap()),
                        sha256: hex::encode(digest(&encoded)),
                        size: encoded.len() as u64,
                        encoding: ToolArtifactFormat::TarXz {
                            executable: "repo-search/search".into(),
                        },
                    },
                    executable_sha256: hex::encode(digest(executable)),
                }],
                github_token: None,
            };
            Self {
                directory,
                distribution,
                executable,
                archive,
            }
        }
    }

    #[tokio::test]
    async fn host_program_is_returned_as_a_host_path_and_never_enters_sandbox_tools() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let host = fixture.directory.path().join("host");
        let prepared = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &host)
            .await
            .unwrap();
        assert_eq!(std::fs::read(prepared.path()).unwrap(), fixture.executable);
        assert_eq!(
            prepared.path().file_name().unwrap(),
            HostProgram::RepoSearch.executable_name(&target).as_str()
        );
        // Preparing again reuses the verified copy.
        assert_eq!(
            fixture
                .distribution
                .prepare_host_program(HostProgram::RepoSearch, &target, &host)
                .await
                .unwrap(),
            prepared
        );

        let bundle = fixture.distribution.load(&target, &cache).await.unwrap();
        let without_host_programs = ToolDistribution {
            host_programs: Vec::new(),
            ..fixture.distribution.clone()
        };
        let baseline = without_host_programs
            .load(&target, &fixture.directory.path().join("baseline-cache"))
            .await
            .unwrap();
        assert_eq!(bundle.catalog(), baseline.catalog());
        assert_eq!(
            bundle.catalog().render().unwrap(),
            baseline.catalog().render().unwrap()
        );
        let local = bundle
            .prepare_local(&fixture.directory.path().join("local"))
            .await
            .unwrap();
        let staged = fixture
            .distribution
            .stage_image_tools(&target, &cache, &fixture.directory.path().join("container"))
            .await
            .unwrap();
        let staged_bin = staged.join("bin");
        for bin_dir in [local.bin_dir().clone(), staged_bin.clone()] {
            let names = std::fs::read_dir(&bin_dir)
                .unwrap()
                .map(|entry| entry.unwrap().file_name())
                .collect::<Vec<_>>();
            assert!(!names.iter().any(|name| name == "search"));
            assert!(!prepared.path().starts_with(&bin_dir));
        }
        assert!(
            !local
                .prepend_path(None)
                .unwrap()
                .to_string_lossy()
                .contains(prepared.path().parent().unwrap().to_str().unwrap())
        );
        assert!(!staged_bin.join("search").exists());
        assert!(!prepared.path().starts_with(&staged));
    }

    #[tokio::test]
    async fn tampered_host_program_artifact_is_rejected() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let mut tampered = async_fs::read(&fixture.archive).await.unwrap();
        *tampered.last_mut().unwrap() ^= 1;
        async_fs::write(&fixture.archive, tampered).await.unwrap();
        assert!(matches!(
            fixture
                .distribution
                .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
                .await,
            Err(ToolRuntimeError::Integrity {
                tool: DistributedTool::Host(HostProgram::RepoSearch)
            })
        ));
    }

    #[tokio::test]
    async fn pinned_executable_digest_mismatch_is_rejected() {
        let mut fixture = HostFixture::new().await;
        let pin = hex::encode(digest(b"another executable"));
        fixture.distribution.host_programs[0].executable_sha256 = pin.clone();
        let cache = fixture.directory.path().join("cache");
        assert!(matches!(
            fixture
                .distribution
                .prepare_host_program(
                    HostProgram::RepoSearch,
                    &ToolTarget::native().unwrap(),
                    &cache
                )
                .await,
            Err(ToolRuntimeError::Integrity {
                tool: DistributedTool::Host(HostProgram::RepoSearch)
            })
        ));
        assert!(!cache.join("bin").join(pin).exists());
    }

    #[tokio::test]
    async fn prepared_host_program_does_not_touch_the_archive() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let first = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        async_fs::remove_file(&fixture.archive).await.unwrap();
        async_fs::remove_dir_all(cache.join("artifacts"))
            .await
            .unwrap();
        let second = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        assert_eq!(first, second);
    }

    #[tokio::test]
    async fn tampered_cached_host_program_is_replaced_from_the_archive() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let prepared = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        let mut permissions = std::fs::metadata(prepared.path()).unwrap().permissions();
        #[allow(clippy::permissions_set_readonly_false)]
        permissions.set_readonly(false);
        std::fs::set_permissions(prepared.path(), permissions).unwrap();
        std::fs::write(prepared.path(), b"tampered").unwrap();
        let repaired = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        assert_eq!(repaired, prepared);
        assert_eq!(std::fs::read(repaired.path()).unwrap(), fixture.executable);
    }

    #[test]
    fn manifest_rejects_a_missing_or_malformed_executable_digest() {
        let manifest = |entry: &str| {
            format!(
                r#"{{"artifacts":[],"host_programs":[{{"tool":"repo_search","version":"0.0.3",
                "target":{{"os":"linux","arch":"x86_64"}},"url":"https://example.com/search.tar.xz",
                "sha256":"{}","size":1,"encoding":{{"format":"executable"}}{entry}}}]}}"#,
                "0".repeat(64)
            )
        };
        assert!(ToolDistribution::from_json(manifest("").as_bytes()).is_err());
        for malformed in ["abc", &"g".repeat(64), &"0".repeat(63)] {
            let entry = format!(r#","executable_sha256":"{malformed}""#);
            assert!(ToolDistribution::from_json(manifest(&entry).as_bytes()).is_err());
        }
        let entry = format!(r#","executable_sha256":"{}""#, "0".repeat(64));
        ToolDistribution::from_json(manifest(&entry).as_bytes()).unwrap();
    }

    #[tokio::test]
    async fn host_program_without_an_artifact_for_the_target_names_both() {
        let fixture = HostFixture::new().await;
        let error = fixture
            .distribution
            .prepare_host_program(
                HostProgram::RepoSearch,
                &ToolTarget::from_probe("Windows_NT", "arm64").unwrap(),
                &fixture.directory.path().join("cache"),
            )
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            ToolRuntimeError::MissingHostProgram {
                program: HostProgram::RepoSearch,
                ..
            }
        ));
        assert_eq!(
            error.to_string(),
            "host program `search` has no artifact for windows/aarch64"
        );
    }

    #[test]
    fn third_party_manifest_pins_repo_search_for_its_published_targets() {
        let distribution =
            ToolDistribution::from_json(include_bytes!("../../patch/third-party-tools.json"))
                .unwrap();
        let mut targets = distribution
            .host_programs
            .iter()
            .filter(|pinned| pinned.artifact.tool == HostProgram::RepoSearch)
            .map(|pinned| {
                assert_eq!(pinned.executable_sha256.len(), 64);
                let artifact = &pinned.artifact;
                assert_eq!(artifact.tool, HostProgram::RepoSearch);
                assert_eq!(artifact.version, "0.0.3");
                assert!(matches!(
                    artifact.encoding,
                    ToolArtifactFormat::TarXz { .. }
                ));
                (artifact.target.os(), artifact.target.arch())
            })
            .collect::<Vec<_>>();
        targets.sort_unstable();
        assert_eq!(
            targets,
            [
                ("linux", "aarch64"),
                ("linux", "x86_64"),
                ("macos", "aarch64")
            ]
        );
    }

    #[tokio::test]
    async fn packaged_distribution_keeps_host_programs() {
        let fixture = HostFixture::new().await;
        let installation = tempfile::tempdir().unwrap();
        let manifest = fixture
            .distribution
            .package_into(installation.path())
            .await
            .unwrap();
        let packaged = ToolDistribution::from_path(&manifest).await.unwrap();
        let prepared = packaged
            .prepare_host_program(
                HostProgram::RepoSearch,
                &ToolTarget::native().unwrap(),
                &fixture.directory.path().join("host"),
            )
            .await
            .unwrap();
        assert_eq!(std::fs::read(prepared.path()).unwrap(), fixture.executable);
    }

    type Scripted = Vec<Option<(u16, &'static [u8])>>;

    /// Answers one scripted response per connection, in order (`None` drops the
    /// connection), and resolves to the number of connections served.
    async fn serve(responses: Scripted) -> (String, tokio::task::JoinHandle<usize>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}/artifact", listener.local_addr().unwrap());
        let handle = tokio::spawn(async move {
            let mut served = 0;
            for response in responses {
                let (mut socket, _) = listener.accept().await.unwrap();
                served += 1;
                let Some((status, body)) = response else {
                    drop(socket);
                    continue;
                };
                let mut request = [0; 4096];
                let _ = socket.read(&mut request).await.unwrap();
                let head = format!(
                    "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                socket.write_all(head.as_bytes()).await.unwrap();
                socket.write_all(body).await.unwrap();
                socket.shutdown().await.unwrap();
            }
            served
        });
        (url, handle)
    }

    /// One scripted reply: status, extra headers, body.
    type Reply = (u16, Vec<(&'static str, String)>, Vec<u8>);

    /// Answers one reply per connection, in order, and resolves to the head
    /// (request line and headers) of every request received.
    async fn serve_recorded(replies: Vec<Reply>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap().to_string();
        let handle = tokio::spawn(async move {
            let mut heads = Vec::new();
            for (status, headers, body) in replies {
                let (mut socket, _) = listener.accept().await.unwrap();
                let mut head = Vec::new();
                while !head.windows(4).any(|window| window == b"\r\n\r\n") {
                    let mut chunk = [0; 1024];
                    let read = socket.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "the client closed before finishing its request");
                    head.extend_from_slice(&chunk[..read]);
                }
                heads.push(String::from_utf8(head).unwrap().to_lowercase());
                let mut reply = format!(
                    "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n",
                    body.len()
                );
                for (name, value) in headers {
                    std::fmt::Write::write_fmt(&mut reply, format_args!("{name}: {value}\r\n"))
                        .unwrap();
                }
                reply.push_str("\r\n");
                socket.write_all(reply.as_bytes()).await.unwrap();
                socket.write_all(&body).await.unwrap();
                socket.shutdown().await.unwrap();
            }
            heads
        });
        (address, handle)
    }

    fn release(url: &str) -> Option<GithubRelease> {
        GithubRelease::parse(&Url::parse(url).unwrap())
    }

    #[test]
    fn only_github_release_download_urls_name_a_release_asset() {
        assert_eq!(
            release(
                "https://github.com/BurntSushi/ripgrep/releases/download/15.1.0/ripgrep-15.1.0-aarch64-apple-darwin.tar.gz"
            ),
            Some(GithubRelease {
                owner: "BurntSushi".into(),
                repo: "ripgrep".into(),
                tag: "15.1.0".into(),
                asset: "ripgrep-15.1.0-aarch64-apple-darwin.tar.gz".into(),
            })
        );
        assert_eq!(
            release("https://github.com/o/r/releases/download/v%2B1/a%20b.zip?x=1")
                .map(|r| (r.tag, r.asset)),
            Some(("v+1".into(), "a b.zip".into()))
        );
        for other in [
            "https://example.com/o/r/releases/download/v1/a.zip",
            "http://github.com/o/r/releases/download/v1/a.zip",
            "https://api.github.com/o/r/releases/download/v1/a.zip",
            "https://github.com/o/r/releases/latest/download/a.zip",
            "https://github.com/o/r/archive/v1.tar.gz",
            "https://github.com/o/r/releases/download/v1",
            "https://github.com/o/r/releases/download/v1/a/b.zip",
            "https://github.com/o/r/releases/download//a.zip",
        ] {
            assert_eq!(release(other), None, "{other}");
        }
    }

    #[test]
    fn api_urls_name_the_release_by_tag_and_the_asset_by_id() {
        let release = GithubRelease {
            owner: "o".into(),
            repo: "r".into(),
            tag: "rel/1 2".into(),
            asset: "a".into(),
        };
        let api = Url::parse(GITHUB_API).unwrap();
        assert_eq!(
            release.release_url(&api).as_str(),
            "https://api.github.com/repos/o/r/releases/tags/rel%2F1%202"
        );
        assert_eq!(
            release.asset_url(&api, 42).as_str(),
            "https://api.github.com/repos/o/r/releases/assets/42"
        );
    }

    #[test]
    fn the_token_never_appears_in_debug_output() {
        let distribution = pinned_distribution().with_github_token("ghs_secret");
        assert!(!format!("{distribution:?}").contains("ghs_secret"));
        assert!(
            !serde_json::to_string(&distribution)
                .unwrap()
                .contains("ghs_secret")
        );
    }

    #[tokio::test]
    async fn a_direct_download_sends_no_credentials() {
        let (address, server) = serve_recorded(vec![(200, vec![], b"payload".to_vec())]).await;
        let url = format!("http://{address}/artifact");
        let bytes = download_with_retry(&Source::Direct(&url), 7, FAST_RETRY)
            .await
            .unwrap();
        assert_eq!(bytes, b"payload");
        let heads = server.await.unwrap();
        assert!(heads[0].starts_with("get /artifact "), "{}", heads[0]);
        assert!(!heads[0].contains("authorization"), "{}", heads[0]);
    }

    fn api_source<'a>(address: &str, token: &'a GithubToken) -> Source<'a> {
        Source::GithubApi {
            release: GithubRelease {
                owner: "o".into(),
                repo: "r".into(),
                tag: "v1".into(),
                asset: "tool.tar.gz".into(),
            },
            api: Url::parse(&format!("http://{address}/")).unwrap(),
            token,
        }
    }

    #[tokio::test]
    async fn a_token_fetches_the_asset_through_the_api_and_keeps_it_from_the_redirect_host() {
        let (storage, storage_server) =
            serve_recorded(vec![(200, vec![], b"payload".to_vec())]).await;
        let metadata = br#"{"id":1,"assets":[{"id":7,"name":"other"},{"id":42,"name":"tool.tar.gz","size":7}]}"#;
        let (api, api_server) = serve_recorded(vec![
            (200, vec![], metadata.to_vec()),
            (
                302,
                vec![("Location", format!("http://{storage}/signed?sig=1"))],
                Vec::new(),
            ),
        ])
        .await;
        let token = GithubToken("ghs_secret".into());
        let bytes = download_with_retry(&api_source(&api, &token), 7, FAST_RETRY)
            .await
            .unwrap();
        assert_eq!(bytes, b"payload");

        let heads = api_server.await.unwrap();
        assert!(
            heads[0].starts_with("get /repos/o/r/releases/tags/v1 "),
            "{}",
            heads[0]
        );
        assert!(heads[0].contains("accept: application/vnd.github+json"));
        assert!(
            heads[1].starts_with("get /repos/o/r/releases/assets/42 "),
            "{}",
            heads[1]
        );
        assert!(heads[1].contains("accept: application/octet-stream"));
        for head in &heads {
            assert!(head.contains("authorization: bearer ghs_secret"), "{head}");
            assert!(head.contains("user-agent: aither-sandbox"), "{head}");
        }
        let heads = storage_server.await.unwrap();
        assert!(heads[0].starts_with("get /signed?sig=1 "), "{}", heads[0]);
        assert!(heads[0].contains("accept: application/octet-stream"));
        assert!(!heads[0].contains("authorization"), "{}", heads[0]);
        assert!(!heads[0].contains("ghs_secret"), "{}", heads[0]);
    }

    #[tokio::test]
    async fn a_release_without_the_pinned_asset_fails_without_a_second_request() {
        let (api, server) = serve_recorded(vec![(
            200,
            vec![],
            br#"{"assets":[{"id":7,"name":"other"}]}"#.to_vec(),
        )])
        .await;
        let token = GithubToken("t".into());
        let error = download_with_retry(&api_source(&api, &token), 7, FAST_RETRY)
            .await
            .unwrap_err();
        assert!(
            matches!(&error, ToolRuntimeError::ReleaseAssetMissing(name) if name == "tool.tar.gz"),
            "{error:?}"
        );
        assert_eq!(server.await.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn a_release_lookup_that_fails_with_a_server_fault_is_retried() {
        let (api, server) = serve_recorded(vec![
            (504, vec![], Vec::new()),
            (
                200,
                vec![],
                br#"{"assets":[{"id":42,"name":"tool.tar.gz"}]}"#.to_vec(),
            ),
            (200, vec![], b"payload".to_vec()),
        ])
        .await;
        let token = GithubToken("t".into());
        let bytes = download_with_retry(&api_source(&api, &token), 7, FAST_RETRY)
            .await
            .unwrap();
        assert_eq!(bytes, b"payload");
        assert_eq!(server.await.unwrap().len(), 3);
    }

    const FAST_RETRY: DownloadRetry = DownloadRetry {
        attempts: 4,
        initial_backoff: Duration::from_millis(5),
        attempt_timeout: Duration::from_secs(10),
    };

    #[tokio::test]
    async fn dropped_connections_and_server_faults_are_retried_until_the_bytes_arrive() {
        let (url, server) = serve(vec![
            None,
            Some((503, b"busy")),
            Some((429, b"")),
            Some((200, b"payload")),
        ])
        .await;
        let bytes = download_with_retry(&Source::Direct(&url), 7, FAST_RETRY)
            .await
            .unwrap();
        assert_eq!(bytes, b"payload");
        assert_eq!(server.await.unwrap(), 4);
    }

    #[tokio::test]
    async fn a_permanent_status_is_tried_exactly_once() {
        let (url, server) = serve(vec![Some((404, b"missing"))]).await;
        let error = download_with_retry(&Source::Direct(&url), 7, FAST_RETRY)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("404"), "{error}");
        assert!(!is_transient(&error));
        assert_eq!(server.await.unwrap(), 1);
    }

    #[tokio::test]
    async fn transient_failures_end_after_the_last_attempt_with_the_last_error() {
        let (url, server) = serve(vec![
            None,
            Some((503, b"")),
            Some((503, b"")),
            Some((502, b"")),
        ])
        .await;
        let error = download_with_retry(&Source::Direct(&url), 7, FAST_RETRY)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("502"), "{error}");
        assert_eq!(server.await.unwrap(), 4);
    }

    #[tokio::test]
    async fn a_download_longer_than_its_pinned_size_is_rejected_before_hashing() {
        let (url, server) = serve(vec![Some((200, b"payload and more"))]).await;
        let tool = DistributedTool::Command(ManagedTool::Ripgrep);
        // The body read stops one byte past the pin instead of buffering it all.
        let bytes = download_with_retry(&Source::Direct(&url), 7, FAST_RETRY)
            .await
            .unwrap();
        assert_eq!(bytes.len(), 8);
        let error = check_size(tool, 7, &bytes).unwrap_err();
        assert!(
            matches!(
                error,
                ToolRuntimeError::ArtifactSize {
                    tool: DistributedTool::Command(ManagedTool::Ripgrep),
                    expected: 7,
                    actual: 8,
                }
            ),
            "{error:?}"
        );
        assert_eq!(server.await.unwrap(), 1);
    }

    #[tokio::test]
    async fn a_cached_file_of_the_wrong_size_is_rejected_before_hashing() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("artifact");
        let tool = DistributedTool::Command(ManagedTool::Ripgrep);
        async_fs::write(&path, b"payload").await.unwrap();
        assert_eq!(
            read_artifact_file(&path, tool, 7).await.unwrap(),
            b"payload"
        );
        for pinned in [6, 8] {
            let error = read_artifact_file(&path, tool, pinned).await.unwrap_err();
            assert!(
                matches!(error, ToolRuntimeError::ArtifactSize { expected, .. } if expected == pinned),
                "{error:?}"
            );
        }
    }

    #[test]
    #[allow(
        clippy::manual_assert_eq,
        reason = "assert_eq! would print 64 MiB of bytes on failure"
    )]
    fn an_executable_over_64_mib_extracts_from_a_hash_verified_archive() {
        let executable = vec![7_u8; 64 * 1024 * 1024 + 1];
        let encoded = tar_xz("repo-search-x/search", &executable);
        let encoding = ToolArtifactFormat::TarXz {
            executable: "repo-search-x/search".into(),
        };
        let extracted = extract_executable(&encoding, &encoded).unwrap();
        assert!(extracted == executable);
    }

    /// The version of the `heel` library `Cargo.lock` resolves.
    fn locked_heel_version() -> String {
        let lock =
            std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../Cargo.lock"))
                .unwrap();
        let mut lines = lock.lines();
        while let Some(line) = lines.next() {
            if line == "name = \"heel\"" {
                let version = lines.next().expect("a locked package has a version");
                return version
                    .strip_prefix("version = \"")
                    .and_then(|version| version.strip_suffix('"'))
                    .expect("the version line is quoted")
                    .into();
            }
        }
        panic!("Cargo.lock locks no heel package");
    }

    /// The distribution's heel is the linked library's version on every
    /// platform it serves, so the sandbox it launches matches the library.
    #[test]
    fn tool_distribution_pins_heel_at_the_linked_version() {
        let version = locked_heel_version();
        let pinned = crate::test_heel::host_programs();
        let mut platforms = pinned
            .iter()
            .map(|program| {
                assert_eq!(program["version"], version.as_str(), "{program}");
                assert_eq!(program["sha256"], program["executable_sha256"], "{program}");
                let url = program["url"].as_str().unwrap();
                assert!(
                    url.starts_with(&format!(
                        "https://github.com/May-Agent/heel/releases/download/heel-v{version}/"
                    )),
                    "{url}"
                );
                format!("{}-{}", program["target"]["os"], program["target"]["arch"])
            })
            .collect::<Vec<_>>();
        platforms.sort();
        assert_eq!(
            platforms,
            [
                "\"linux\"-\"aarch64\"",
                "\"linux\"-\"x86_64\"",
                "\"macos\"-\"aarch64\"",
                "\"windows\"-\"aarch64\"",
                "\"windows\"-\"x86_64\"",
            ]
        );
    }

    /// The distribution resolves heel for this platform without any
    /// environment variable, and the binary it prepares runs as the linked
    /// library's version.
    #[tokio::test]
    async fn tool_distribution_resolves_heel_on_this_platform() {
        let cache = tempfile::tempdir().unwrap();
        let target = ToolTarget::native().unwrap();
        let heel = crate::test_heel::distribution()
            .prepare_host_program(HostProgram::Heel, &target, cache.path())
            .await
            .unwrap();
        assert_eq!(
            heel.path().file_name().unwrap(),
            HostProgram::Heel.executable_name(&target).as_str()
        );
        let verified = heel::HeelBinary::verify(heel.path()).unwrap();
        assert_eq!(verified.as_path(), heel.path());
    }
}