dalo 1.11.1

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

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::{self, Read, Write};
use std::os::unix::fs::{PermissionsExt, symlink};
use std::path::{Component, Path, PathBuf};
use std::process;
#[cfg(test)]
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
use ureq::ResponseExt;
use ureq::http::Uri;
use ureq::http::header::{CONTENT_LENGTH, LOCATION};

use crate::error::{DaloError, DaloResult};
use crate::inventory::{InventoryWarning, InventoryWarningCode, SkillRecord, SourceInventory};
use crate::lockfile::LockedBinary;
use crate::plugin::{self, ToolAvailability};
use crate::source::{SourceConfig, SourceHeadCache, SourceKind, SourceProvenance};
use crate::store::{self, ApprovalRecord, StorePaths};
use crate::tool::make_directories_read_only;

/// Stable approval scope for exact release-binary contracts.
pub const APPROVAL_SCOPE: &str = "binary";

/// Largest release asset Dalo will download or accept as staged bytes.
const MAX_BINARY_BYTES: u64 = 256 * 1024 * 1024;

/// Global timeout for one download, including every redirect hop.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);

/// Redirects followed before a download is abandoned.
const MAX_REDIRECTS: u32 = 5;

/// Prefix of temporary download files, so `doctor` can find interrupted ones.
pub(crate) const DOWNLOAD_TEMPORARY_PREFIX: &str = ".binary-download-";

/// Age after which download debris is assumed abandoned. A younger file may
/// belong to a download that is still running, so cleanup leaves it alone.
const DOWNLOAD_DEBRIS_MIN_AGE: Duration = Duration::from_secs(60 * 60);

/// Test-only switch that lets the download policy accept plain-HTTP loopback
/// URLs, so unit tests can serve assets from a `127.0.0.1` fixture server.
///
/// It exists behind `cfg(test)`, so it is compiled out of the shipped binary
/// and is not part of the CLI surface, the same way `update.rs` overrides its
/// release endpoint for tests.
#[cfg(test)]
static TEST_ALLOW_INSECURE_LOOPBACK: Mutex<bool> = Mutex::new(false);

/// One validated release-binary declaration. Inventory never downloads it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryRecord {
    /// Binary ID, the key of the `binaries` frontmatter mapping.
    pub id: String,
    /// Skill-qualified identity, `<source>:<slot>#binary:<id>`.
    pub source_ref: String,
    /// Release source kind.
    pub source: BinarySource,
    /// GitHub repository, `<owner>/<name>`.
    pub repo: String,
    /// Release tag the assets are attached to.
    pub tag: String,
    /// Whether missing availability blocks the skill.
    pub availability: ToolAvailability,
    /// Declared asset for each platform, in platform order.
    pub assets: BTreeMap<BinaryPlatform, BinaryAsset>,
    /// Deterministic contract hash over the fields above; excludes provenance and derived URLs.
    pub contract_hash: String,
}

/// Supported release-binary sources. The enum is closed so each new kind is an explicit contract change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BinarySource {
    /// An asset attached to a GitHub release.
    #[serde(rename = "github-release")]
    GithubRelease,
}

impl BinarySource {
    /// Stable declaration label, identical to the serialized form.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::GithubRelease => "github-release",
        }
    }
}

/// Platforms a release binary may declare, serialized as `macos-arm64`, `macos-x64`, `linux-arm64`, or `linux-x64`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BinaryPlatform {
    /// Apple Silicon macOS.
    #[serde(rename = "macos-arm64")]
    MacosArm64,
    /// Intel macOS.
    #[serde(rename = "macos-x64")]
    MacosX64,
    /// ARM64 Linux.
    #[serde(rename = "linux-arm64")]
    LinuxArm64,
    /// x86-64 Linux.
    #[serde(rename = "linux-x64")]
    LinuxX64,
}

impl BinaryPlatform {
    /// Stable declaration label, identical to the serialized form.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MacosArm64 => "macos-arm64",
            Self::MacosX64 => "macos-x64",
            Self::LinuxArm64 => "linux-arm64",
            Self::LinuxX64 => "linux-x64",
        }
    }
}

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

/// One platform asset of a release binary, with its pinned digest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryAsset {
    /// Release asset file name.
    pub asset: String,
    /// Lowercase hexadecimal SHA-256 of the exact asset bytes.
    pub sha256: String,
    /// Derived download URL, `https://github.com/<repo>/releases/download/<tag>/<asset>`.
    pub url: String,
}

/// One declaration as authored, before identity and derived fields are added.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDeclaration {
    source: BinarySource,
    repo: String,
    tag: String,
    #[serde(default = "default_availability")]
    availability: ToolAvailability,
    assets: BTreeMap<BinaryPlatform, RawAsset>,
}

/// One platform asset as authored.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAsset {
    asset: String,
    sha256: String,
}

const fn default_availability() -> ToolAvailability {
    ToolAvailability::Required
}

/// Parse the `binaries` frontmatter value of one skill.
///
/// The value must be a mapping from binary ID to declaration, and an empty
/// mapping declares no binaries. Records are returned sorted by ID. The first
/// invalid declaration fails the whole value with a message that names its ID
/// and the rule it breaks. `skill_source_ref` is the owning skill's
/// `<source>:<slot>` reference, which prefixes every binary identity.
pub(crate) fn parse_declarations(
    skill_source_ref: &str,
    value: &yaml_serde::Value,
) -> Result<Vec<BinaryRecord>, String> {
    let yaml_serde::Value::Mapping(entries) = value else {
        return Err(
            "`binaries` must be a mapping from binary id to declaration; use `binaries: {}` for none"
                .to_owned(),
        );
    };
    let mut records = Vec::with_capacity(entries.len());
    for (key, declaration) in entries {
        let yaml_serde::Value::String(id) = key else {
            return Err("binary ids must be strings".to_owned());
        };
        if !plugin::is_plugin_name(id) {
            return Err(format!("binary `{id}`: the id must use lower kebab-case"));
        }
        let raw: RawDeclaration = yaml_serde::from_value(declaration.clone())
            .map_err(|error| format!("binary `{id}`: {error}"))?;
        records.push(build_record(skill_source_ref, id, raw)?);
    }
    records.sort_by(|left, right| left.id.cmp(&right.id));
    Ok(records)
}

fn build_record(
    skill_source_ref: &str,
    id: &str,
    raw: RawDeclaration,
) -> Result<BinaryRecord, String> {
    let rule = |message: String| format!("binary `{id}`: {message}");
    let RawDeclaration {
        source,
        repo,
        tag,
        availability,
        assets: raw_assets,
    } = raw;
    if !is_github_repo(&repo) {
        return Err(rule(
            "repo must be `<owner>/<name>` with 1-100 character segments that do not start with `.`"
                .to_owned(),
        ));
    }
    if !is_github_tag(&tag) {
        return Err(rule(
            "tag must be 1-128 characters from letters, digits, `.`, `_`, `/`, and `-`, must not start with `-`, `.`, or `/` or end with `/`, and must not contain `..` or `//`"
                .to_owned(),
        ));
    }
    if raw_assets.is_empty() {
        return Err(rule("assets must declare at least one platform".to_owned()));
    }
    let mut assets = BTreeMap::new();
    for (platform, asset) in raw_assets {
        if !is_binary_asset_name(&asset.asset) {
            return Err(rule(format!(
                "asset for {platform} must be 1-255 characters from letters, digits, `.`, `_`, and `-`, must not start with `.`, and must not contain `..`"
            )));
        }
        if !is_sha256_hex(&asset.sha256) {
            return Err(rule(format!(
                "asset for {platform} must pin a 64-character lower-case SHA-256 digest"
            )));
        }
        let url = format!(
            "https://github.com/{repo}/releases/download/{tag}/{}",
            asset.asset
        );
        assets.insert(
            platform,
            BinaryAsset {
                asset: asset.asset,
                sha256: asset.sha256,
                url,
            },
        );
    }
    let mut record = BinaryRecord {
        id: id.to_owned(),
        source_ref: format!("{skill_source_ref}#binary:{id}"),
        source,
        repo,
        tag,
        availability,
        assets,
        contract_hash: String::new(),
    };
    record.contract_hash = hash_binary_contract(&record);
    Ok(record)
}

/// `<owner>/<name>`: two segments of 1-100 characters, none starting with `.`.
/// The leading-dot rule also excludes `.` and `..`.
fn is_github_repo(value: &str) -> bool {
    let mut segments = value.split('/');
    let (Some(owner), Some(name), None) = (segments.next(), segments.next(), segments.next())
    else {
        return false;
    };
    [owner, name].into_iter().all(|segment| {
        (1..=100).contains(&segment.len())
            && !segment.starts_with('.')
            && segment
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
    })
}

/// A release tag may not start with `-`, `.`, or `/`, may not end with `/`,
/// and may contain neither `..` nor `//`, so a derived URL never gets an empty
/// path segment.
fn is_github_tag(value: &str) -> bool {
    (1..=128).contains(&value.len())
        && !value.starts_with(['-', '.', '/'])
        && !value.ends_with('/')
        && !value.contains("..")
        && !value.contains("//")
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'/' | b'-'))
}

fn is_binary_asset_name(value: &str) -> bool {
    (1..=255).contains(&value.len())
        && !value.starts_with('.')
        && !value.contains("..")
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
}

fn is_sha256_hex(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

fn hash_binary_contract(binary: &BinaryRecord) -> String {
    let mut hash = Sha256::new();
    hash.update(b"dalo-binary-contract-v1\0");
    plugin::hash_contract_value(&mut hash, &format!("id:{}", binary.id));
    plugin::hash_contract_value(&mut hash, &format!("source:{}", binary.source.as_str()));
    plugin::hash_contract_value(&mut hash, &format!("repo:{}", binary.repo));
    plugin::hash_contract_value(&mut hash, &format!("tag:{}", binary.tag));
    plugin::hash_contract_value(&mut hash, &format!("availability:{}", binary.availability));
    for (platform, asset) in &binary.assets {
        plugin::hash_contract_value(&mut hash, &format!("platform:{platform}"));
        plugin::hash_contract_value(&mut hash, &format!("asset:{}", asset.asset));
        plugin::hash_contract_value(&mut hash, &format!("sha256:{}", asset.sha256));
    }
    hash.finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// Complete read-only inventory and state report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BinaryListReport {
    /// Validated declarations in deterministic identity order.
    pub binaries: Vec<BinaryStatusReport>,
    /// Invalid `binaries` declarations found while scanning enabled sources.
    pub warnings: Vec<InventoryWarning>,
}

/// One declared binary joined with the host platform and local trust state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BinaryStatusReport {
    /// Validated declaration and contract hash.
    pub binary: BinaryRecord,
    /// Source-qualified ref of the skill that declares the binary.
    pub skill_source_ref: String,
    /// Directory of the declaring skill, retained only as provenance.
    pub skill_path: PathBuf,
    /// Source revision and origin provenance, excluded from approval identity.
    pub source_provenance: SourceProvenance,
    /// Exact approval value for this contract.
    pub approval_value: String,
    /// Platform of the running Dalo binary, or `None` when it is not a declarable platform.
    pub host_platform: Option<BinaryPlatform>,
    /// Current readiness state.
    pub state: BinaryState,
    /// Staged file for the host asset, when present.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub staged_path: Option<PathBuf>,
    /// Exposure link at `<store>/bin/<id>`, reported when it resolves to the staged file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exposed_path: Option<PathBuf>,
    /// Identity of the declaration that owns `bin/<id>`, reported only when this one is `blocked`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slot_owner: Option<String>,
    /// Actionable explanation.
    pub diagnostic: String,
}

/// Mutually exclusive release-binary readiness states.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BinaryState {
    /// The running host has no declared asset.
    PlatformUnsupported,
    /// No approval exists for this exact contract.
    PendingApproval,
    /// An approval exists for this identity, but the current contract hash differs.
    HashDrift,
    /// Verified bytes remain staged but the exact approval was revoked.
    Revoked,
    /// Approval exists, but the host asset has not been staged, or the verified bytes are not linked at `bin/<id>`.
    ApprovedNotStaged,
    /// The staged file no longer re-hashes to its pinned digest.
    AuditFailure,
    /// Exact approval, staged bytes that match the pinned digest, and the exposure link to them.
    Ready,
    /// Another declaration owns the exposure slot `bin/<id>`, so this one is never exposed.
    Blocked,
}

impl std::fmt::Display for BinaryState {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::PlatformUnsupported => "platform_unsupported",
            Self::PendingApproval => "pending_approval",
            Self::HashDrift => "hash_drift",
            Self::Revoked => "revoked",
            Self::ApprovedNotStaged => "approved_not_staged",
            Self::AuditFailure => "audit_failure",
            Self::Ready => "ready",
            Self::Blocked => "blocked",
        })
    }
}

/// Collect every valid binary declaration without downloading or executing it.
pub fn list(paths: &StorePaths) -> DaloResult<BinaryListReport> {
    let config = store::read_config(paths)?;
    let approvals = store::read_approvals(paths)?;
    let (inventories, _unscanned) = scan_enabled_sources(&config.sources);
    Ok(list_from_inventories(
        paths,
        &config.sources,
        &approvals.approvals,
        &inventories,
    ))
}

/// Scan the skills of every enabled source and name the enabled sources whose
/// scan failed. Skill discovery is read-only and never executes code.
fn scan_enabled_sources(sources: &[SourceConfig]) -> (Vec<SourceInventory>, Vec<String>) {
    let mut inventories = Vec::new();
    let mut unscanned = Vec::new();
    for source in sources.iter().filter(|source| source.enabled) {
        let scanned = crate::source::scoped_source_root(&source.path, source.subpath.as_deref())
            .and_then(|root| crate::inventory::scan_configured_source(source, &root));
        match scanned {
            Ok(inventory) => inventories.push(inventory),
            Err(_) => unscanned.push(source.id.clone()),
        }
    }
    (inventories, unscanned)
}

/// The declarations a cleanup pass sees, plus the sources that stop it from
/// proving which staged bytes are unreferenced.
pub(crate) struct BinarySnapshot {
    /// Listing built from every enabled source that scanned successfully.
    pub(crate) list: BinaryListReport,
    /// Disabled or unscannable sources. Cleanup does nothing while any exists,
    /// because their declarations cannot be seen and their bytes may still be wanted.
    pub(crate) incomplete_sources: Vec<String>,
}

/// Take a listing for cleanup and lock decisions from explicit configuration.
///
/// Callers pass the configuration and approvals they are about to commit, so a
/// source being removed is already absent from `sources`.
pub(crate) fn snapshot(
    paths: &StorePaths,
    sources: &[SourceConfig],
    approvals: &[ApprovalRecord],
) -> BinarySnapshot {
    let (inventories, mut incomplete_sources) = scan_enabled_sources(sources);
    incomplete_sources.extend(
        sources
            .iter()
            .filter(|source| !source.enabled)
            .map(|source| source.id.clone()),
    );
    incomplete_sources.sort();
    let list = list_from_inventories(paths, sources, approvals, &inventories);
    BinarySnapshot {
        list,
        incomplete_sources,
    }
}

/// Lock records for the binaries that are `ready` on this host, sorted by identity.
#[must_use]
pub(crate) fn lock_records(report: &BinaryListReport) -> Vec<LockedBinary> {
    let mut records = report
        .binaries
        .iter()
        .filter(|item| item.state == BinaryState::Ready)
        .filter_map(|item| {
            let platform = item.host_platform?;
            let asset = item.binary.assets.get(&platform)?;
            Some(LockedBinary {
                source_ref: item.binary.source_ref.clone(),
                contract_hash: item.binary.contract_hash.clone(),
                platform: platform.as_str().to_owned(),
                digest: asset.sha256.clone(),
                staged_path: item.staged_path.clone()?,
                exposed_path: item.exposed_path.clone()?,
            })
        })
        .collect::<Vec<_>>();
    records.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
    records
}

/// Join already-scanned skill inventories with local binary trust and staging state.
///
/// Two rules decide which declarations take part. A catalog skill that its
/// source does not select, directly or through a same-catalog `requires`, is an
/// offer rather than part of the resolution, so it is left out just as the
/// resolver leaves it out. Among the remaining declarations, the first by source
/// priority, then by source ID, then by skill ref owns the exposure slot
/// `bin/<id>`; every other declaration with the same ID is reported as `blocked`
/// and is never exposed.
#[must_use]
pub fn list_from_inventories(
    paths: &StorePaths,
    sources: &[SourceConfig],
    approvals: &[ApprovalRecord],
    inventories: &[SourceInventory],
) -> BinaryListReport {
    list_from_inventories_with_head_cache(
        paths,
        sources,
        approvals,
        inventories,
        &mut SourceHeadCache::default(),
    )
}

pub(crate) fn list_from_inventories_with_head_cache(
    paths: &StorePaths,
    sources: &[SourceConfig],
    approvals: &[ApprovalRecord],
    inventories: &[SourceInventory],
    head_cache: &mut SourceHeadCache,
) -> BinaryListReport {
    let source_lock = crate::catalog::read_source_lock(paths).ok();
    let host_platform = host_platform();
    let enabled_sources = sources
        .iter()
        .filter(|source| source.enabled)
        .map(|source| (source.id.as_str(), source))
        .collect::<BTreeMap<_, _>>();
    let selections = crate::resolver::expand_catalog_selections(&enabled_sources, inventories);
    let mut warnings = Vec::new();
    let mut declarations: Vec<(&SourceConfig, &SkillRecord, &BinaryRecord)> = Vec::new();
    for inventory in inventories {
        let Some(&source) = enabled_sources.get(inventory.source_id.as_str()) else {
            continue;
        };
        warnings.extend(
            inventory
                .warnings
                .iter()
                .filter(|warning| warning.code == InventoryWarningCode::InvalidBinaryDeclaration)
                .cloned(),
        );
        let selection = selections
            .get(source.id.as_str())
            .map_or(source.selection.as_slice(), Vec::as_slice);
        for skill in &inventory.skills {
            if source.kind == SourceKind::Catalog
                && !crate::catalog::skill_is_selected(skill, selection, &source.path)
            {
                continue;
            }
            for binary in &skill.binaries {
                declarations.push((source, skill, binary));
            }
        }
    }
    // Sorted so that the first declaration of each ID is its slot owner.
    declarations.sort_by(|left, right| {
        left.0
            .priority
            .cmp(&right.0.priority)
            .then_with(|| left.0.id.cmp(&right.0.id))
            .then_with(|| left.1.source_ref.cmp(&right.1.source_ref))
    });
    let mut owners: BTreeMap<&str, &str> = BTreeMap::new();
    for (_, _, binary) in &declarations {
        owners
            .entry(binary.id.as_str())
            .or_insert(binary.source_ref.as_str());
    }
    // Provenance can cost a Git lookup, so it is resolved once for each source
    // that actually declares a binary; doctor and status pay nothing otherwise.
    let mut provenance: BTreeMap<&str, SourceProvenance> = BTreeMap::new();
    let mut binaries = Vec::with_capacity(declarations.len());
    for (source, skill, binary) in declarations {
        let provenance = provenance
            .entry(source.id.as_str())
            .or_insert_with(|| {
                crate::source::source_provenance_with_head_cache(
                    source,
                    source_lock.as_ref(),
                    head_cache,
                )
            })
            .clone();
        let mut status = status_for(
            paths,
            binary.clone(),
            skill.source_ref.clone(),
            skill.path.clone(),
            provenance,
            approvals,
            host_platform,
        );
        let owner = owners[binary.id.as_str()];
        if owner != binary.source_ref {
            block_slot(&mut status, owner);
        }
        binaries.push(status);
    }
    binaries.sort_by(|left, right| left.binary.source_ref.cmp(&right.binary.source_ref));
    warnings.sort_by(|left, right| left.path.cmp(&right.path));
    BinaryListReport { binaries, warnings }
}

/// Mark a declaration whose exposure slot another declaration owns.
fn block_slot(report: &mut BinaryStatusReport, owner: &str) {
    report.state = BinaryState::Blocked;
    report.slot_owner = Some(owner.to_owned());
    report.exposed_path = None;
    report.diagnostic = format!(
        "exposure slot `bin/{}` belongs to `{owner}`; this declaration is blocked and is never exposed",
        report.binary.id
    );
}

/// Find one exact skill-qualified binary declaration.
pub fn show(paths: &StorePaths, value: &str) -> DaloResult<BinaryStatusReport> {
    validate_identity_shape(value)?;
    let report = list(paths)?;
    report
        .binaries
        .into_iter()
        .find(|candidate| candidate.binary.source_ref == value)
        .ok_or_else(|| DaloError::InvalidArgument {
            reason: format!(
                "unknown binary `{value}`; use `dalo binary list` and an exact `<source>:<skill>#binary:<id>` identity"
            ),
        })
}

/// Directory of immutable verified bytes for one pinned SHA-256 digest.
#[must_use]
pub fn staged_root(paths: &StorePaths, digest: &str) -> PathBuf {
    paths.binaries_dir.join(digest)
}

/// Platform of the running Dalo binary, when it is one of the declarable platforms.
#[must_use]
pub fn host_platform() -> Option<BinaryPlatform> {
    host_platform_for(std::env::consts::OS, std::env::consts::ARCH)
}

fn host_platform_for(os: &str, arch: &str) -> Option<BinaryPlatform> {
    match (os, arch) {
        ("macos", "aarch64") => Some(BinaryPlatform::MacosArm64),
        ("macos", "x86_64") => Some(BinaryPlatform::MacosX64),
        ("linux", "aarch64") => Some(BinaryPlatform::LinuxArm64),
        ("linux", "x86_64") => Some(BinaryPlatform::LinuxX64),
        _ => None,
    }
}

fn status_for(
    paths: &StorePaths,
    binary: BinaryRecord,
    skill_source_ref: String,
    skill_path: PathBuf,
    source_provenance: SourceProvenance,
    approvals: &[ApprovalRecord],
    host_platform: Option<BinaryPlatform>,
) -> BinaryStatusReport {
    let evaluation = evaluate(paths, &binary, approvals, host_platform);
    BinaryStatusReport {
        approval_value: approval_value(&binary),
        binary,
        skill_source_ref,
        skill_path,
        source_provenance,
        host_platform,
        state: evaluation.state,
        staged_path: evaluation.staged_path,
        exposed_path: evaluation.exposed_path,
        slot_owner: None,
        diagnostic: evaluation.diagnostic,
    }
}

struct Evaluation {
    state: BinaryState,
    staged_path: Option<PathBuf>,
    exposed_path: Option<PathBuf>,
    diagnostic: String,
}

/// Decide the readiness state from the declaration, approvals, staged bytes, and exposure link.
fn evaluate(
    paths: &StorePaths,
    binary: &BinaryRecord,
    approvals: &[ApprovalRecord],
    host_platform: Option<BinaryPlatform>,
) -> Evaluation {
    let exact_value = approval_value(binary);
    let exact_approval = approvals
        .iter()
        .any(|record| record.scope == APPROVAL_SCOPE && record.value == exact_value);
    let identity_prefix = format!("{}@sha256:", binary.source_ref);
    let prior_approval = approvals
        .iter()
        .any(|record| record.scope == APPROVAL_SCOPE && record.value.starts_with(&identity_prefix));
    let host_asset = host_platform.and_then(|platform| binary.assets.get(&platform));
    // A symlink or other non-regular entry counts as staged so that it is
    // reported as an audit failure instead of silently treated as absent.
    let staged_path = host_asset
        .map(|asset| staged_root(paths, &asset.sha256).join(&binary.id))
        .filter(|path| fs::symlink_metadata(path).is_ok());
    let staged = staged_path.is_some();
    let verified = match (host_asset, &staged_path) {
        (Some(asset), Some(path)) => staged_bytes_match(path, &asset.sha256),
        _ => false,
    };
    let exposure = paths.bin_dir.join(&binary.id);
    let linked = staged_path
        .as_deref()
        .is_some_and(|path| link_resolves_to(&exposure, path));
    let exposed_path = linked.then(|| exposure.clone());
    let (state, diagnostic) = if host_asset.is_none() {
        let diagnostic = match host_platform {
            Some(platform) => format!("no asset is declared for host platform `{platform}`"),
            None => "this host is not one of the platforms a binary can declare".to_owned(),
        };
        (BinaryState::PlatformUnsupported, diagnostic)
    } else if exact_approval && staged && verified && linked {
        (
            BinaryState::Ready,
            "exact binary contract approved, the staged bytes match the pinned digest, and the exposure link points at them"
                .to_owned(),
        )
    } else if exact_approval && staged && verified {
        (
            BinaryState::ApprovedNotStaged,
            format!(
                "verified bytes are staged but `{}` is not linked to them; rerun `dalo approve binary {}`",
                exposure.display(),
                binary.source_ref
            ),
        )
    } else if exact_approval && staged {
        (
            BinaryState::AuditFailure,
            "staged binary bytes do not match the pinned digest".to_owned(),
        )
    } else if exact_approval {
        (
            BinaryState::ApprovedNotStaged,
            "exact binary contract approved but the host asset is not staged".to_owned(),
        )
    } else if staged {
        (
            BinaryState::Revoked,
            "staged bytes exist but no exact binary approval remains".to_owned(),
        )
    } else if prior_approval {
        (
            BinaryState::HashDrift,
            "binary contract changed since its last approval and requires reapproval".to_owned(),
        )
    } else {
        (
            BinaryState::PendingApproval,
            format!(
                "exact binary contract has no approval; run `dalo approve binary {}`",
                binary.source_ref
            ),
        )
    };
    Evaluation {
        state,
        staged_path,
        exposed_path,
        diagnostic,
    }
}

/// Whether `link` is a symlink that resolves to `staged_path`.
fn link_resolves_to(link: &Path, staged_path: &Path) -> bool {
    fs::symlink_metadata(link).is_ok_and(|metadata| metadata.file_type().is_symlink())
        && matches!(
            (fs::canonicalize(link), fs::canonicalize(staged_path)),
            (Ok(linked), Ok(staged)) if linked == staged
        )
}

/// Re-hash one staged file by streaming it, refusing anything that is not a regular file.
fn staged_bytes_match(path: &Path, expected_sha256: &str) -> bool {
    fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_file())
        && fs::File::open(path)
            .and_then(|mut file| hash_reader(&mut file))
            .is_ok_and(|digest| digest == expected_sha256)
}

fn approval_value(binary: &BinaryRecord) -> String {
    format!("{}@sha256:{}", binary.source_ref, binary.contract_hash)
}

fn validate_identity_shape(value: &str) -> DaloResult<()> {
    let valid = value
        .split_once("#binary:")
        .is_some_and(|(skill, id)| skill.contains(':') && !id.is_empty());
    if valid {
        Ok(())
    } else {
        Err(DaloError::InvalidArgument {
            reason: format!(
                "invalid binary identity `{value}`: binary values must use `<source>:<skill>#binary:<id>`"
            ),
        })
    }
}

fn hex_digest(digest: impl AsRef<[u8]>) -> String {
    digest
        .as_ref()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// SHA-256 of everything `reader` yields, read in fixed-size chunks.
fn hash_reader(reader: &mut impl Read) -> io::Result<String> {
    let mut hasher = Sha256::new();
    let mut buffer = vec![0_u8; 64 * 1024];
    loop {
        match reader.read(&mut buffer) {
            Ok(0) => break,
            Ok(read) => hasher.update(&buffer[..read]),
            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
            Err(error) => return Err(error),
        }
    }
    Ok(hex_digest(hasher.finalize()))
}

/// Result of granting, planning, or revoking one exact release binary approval.
#[derive(Debug, Clone, Serialize)]
pub struct BinaryApprovalReport {
    /// Exact skill-qualified binary identity, `<source>:<skill>#binary:<id>`.
    pub binary: String,
    /// Exact content-bound approval value.
    pub approval_value: String,
    /// `planned` for a dry run, `granted`, `unchanged`, or `revoked`.
    pub action: String,
    /// Verified staged file for the host asset; for a dry run, where it would be staged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub staged_path: Option<PathBuf>,
    /// Exposure link at `<store>/bin/<id>`; for a dry run, where it would be created.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exposed_path: Option<PathBuf>,
    /// Whether mutation was suppressed.
    pub dry_run: bool,
    /// Staged directories, links, and debris removed by the cleanup that follows a revocation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub removed_paths: Vec<PathBuf>,
    /// Entries cleanup kept because removing them could not be proven safe.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cleanup_warnings: Vec<String>,
}

/// Status of every binary one skill declares, for `approve skill` output.
///
/// The statuses come from the full listing, so a declaration that loses its
/// exposure slot to another skill reads `blocked` here, as it does in `binary list`.
pub(crate) fn skill_binary_statuses(
    paths: &StorePaths,
    skill: &SkillRecord,
) -> DaloResult<Vec<BinaryStatusReport>> {
    Ok(list(paths)?
        .binaries
        .into_iter()
        .filter(|item| item.skill_source_ref == skill.source_ref)
        .collect())
}

/// Download, verify, stage, and expose the host asset, then grant the exact approval.
///
/// This is the only operation in this module that reaches the network. A dry
/// run reports the plan and touches nothing. A real run verifies the bytes
/// against the pinned digest before anything is renamed into place, so a
/// mismatch leaves neither a staged file nor an approval record.
pub fn approve(paths: &StorePaths, value: &str, dry_run: bool) -> DaloResult<BinaryApprovalReport> {
    let status = show(paths, value)?;
    if status.state == BinaryState::Blocked {
        return Err(DaloError::StateError {
            reason: format!(
                "binary `{}` cannot be approved: {}; nothing was downloaded",
                status.binary.source_ref, status.diagnostic
            ),
        });
    }
    let host_asset = status.host_platform.and_then(|platform| {
        status
            .binary
            .assets
            .get(&platform)
            .map(|asset| (platform, asset))
    });
    let Some((platform, asset)) = host_asset else {
        return Err(DaloError::StateError {
            reason: format!(
                "binary `{}` cannot be approved on this host: {}; nothing was downloaded",
                status.binary.source_ref, status.diagnostic
            ),
        });
    };
    let planned_staged = staged_root(paths, &asset.sha256).join(&status.binary.id);
    let planned_exposed = paths.bin_dir.join(&status.binary.id);
    let mut approvals = store::read_approvals(paths)?;
    let record = ApprovalRecord::granted(APPROVAL_SCOPE.to_owned(), status.approval_value.clone());
    let exists = approvals
        .approvals
        .iter()
        .any(|approval| approval.matches(&record));
    if dry_run {
        return Ok(BinaryApprovalReport {
            binary: status.binary.source_ref,
            approval_value: status.approval_value,
            action: "planned".to_owned(),
            staged_path: Some(planned_staged),
            exposed_path: Some(planned_exposed),
            dry_run,
            removed_paths: Vec::new(),
            cleanup_warnings: Vec::new(),
        });
    }
    let staged_path = fetch_and_stage(paths, &status.binary, platform)?;
    let exposed_path = expose(paths, &status.binary, &staged_path)?;
    if !exists {
        approvals.approvals.push(record);
        approvals.approvals.sort_by(|left, right| {
            left.scope
                .cmp(&right.scope)
                .then(left.value.cmp(&right.value))
        });
        store::write_approvals(paths, &approvals)?;
    }
    Ok(BinaryApprovalReport {
        binary: status.binary.source_ref,
        approval_value: status.approval_value,
        action: if exists { "unchanged" } else { "granted" }.to_owned(),
        staged_path: Some(staged_path),
        exposed_path: Some(exposed_path),
        dry_run,
        removed_paths: Vec::new(),
        cleanup_warnings: Vec::new(),
    })
}

/// Remove every approval for one exact binary identity.
///
/// A real run then removes the staged bytes and the exposure link that no
/// approved declaration still backs (see `garbage_collect`). Anything cleanup
/// keeps is reported as a warning rather than failing the revocation.
pub fn revoke(paths: &StorePaths, value: &str, dry_run: bool) -> DaloResult<BinaryApprovalReport> {
    validate_identity_shape(value)?;
    let mut approvals = store::read_approvals(paths)?;
    let prefix = format!("{value}@sha256:");
    let before = approvals.approvals.len();
    let mut removed = None;
    approvals.approvals.retain(|record| {
        let matches = record.scope == APPROVAL_SCOPE && record.value.starts_with(&prefix);
        if matches {
            removed = Some(record.value.clone());
        }
        !matches
    });
    let changed = before != approvals.approvals.len();
    if changed && !dry_run {
        store::write_approvals(paths, &approvals)?;
    }
    let cleanup = if dry_run {
        BinaryCleanupReport::default()
    } else {
        let config = store::read_config(paths)?;
        collect_unreferenced(
            paths,
            &snapshot(paths, &config.sources, &approvals.approvals),
        )
    };
    Ok(BinaryApprovalReport {
        binary: value.to_owned(),
        approval_value: removed.unwrap_or(prefix),
        action: if changed { "revoked" } else { "unchanged" }.to_owned(),
        staged_path: None,
        exposed_path: None,
        dry_run,
        removed_paths: cleanup.removed_paths,
        cleanup_warnings: cleanup.warnings,
    })
}

/// Paths one cleanup pass removed, and the entries it kept on purpose.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct BinaryCleanupReport {
    /// Staged directories, exposure links, and download debris that were deleted.
    pub removed_paths: Vec<PathBuf>,
    /// Entries kept because removing them could not be proven safe, and cleanup steps that failed.
    pub warnings: Vec<String>,
}

/// Run one cleanup pass over a snapshot, or explain why it must not run.
///
/// Cleanup is skipped while any enabled source is unscannable or any source is
/// disabled, because the declarations behind those sources cannot be seen. A
/// failure inside the pass becomes a warning, since the caller has already
/// committed the change that triggered it.
pub(crate) fn collect_unreferenced(
    paths: &StorePaths,
    snapshot: &BinarySnapshot,
) -> BinaryCleanupReport {
    if !snapshot.incomplete_sources.is_empty() {
        return BinaryCleanupReport {
            removed_paths: Vec::new(),
            warnings: vec![format!(
                "binary cleanup skipped: source(s) {} are disabled or could not be scanned, so their staged bytes cannot be proven unreferenced",
                snapshot.incomplete_sources.join(", ")
            )],
        };
    }
    garbage_collect(paths, &snapshot.list.binaries).unwrap_or_else(|error| BinaryCleanupReport {
        removed_paths: Vec::new(),
        warnings: vec![format!("binary cleanup failed: {error}")],
    })
}

/// Remove staged bytes, exposure links, and download debris that no approved
/// declaration in `live` still backs.
///
/// A digest directory `binaries/<sha256>/` is kept when an entry with an approval
/// record (`ready`, `approved_not_staged`, or `audit_failure`) pins that digest for
/// the host platform. Otherwise it is removed, provided it holds exactly one
/// regular file. An exposure link `bin/<id>` is removed when it is a symbolic link
/// into `binaries/` and either its target is gone or no approved entry owns `<id>`.
/// Download debris is removed once it is older than an hour. Anything else is left
/// in place and reported as a warning, and nothing is ever deleted through a
/// symbolic link.
pub(crate) fn garbage_collect(
    paths: &StorePaths,
    live: &[BinaryStatusReport],
) -> DaloResult<BinaryCleanupReport> {
    let backed = live
        .iter()
        .filter(|item| {
            matches!(
                item.state,
                BinaryState::Ready | BinaryState::ApprovedNotStaged | BinaryState::AuditFailure
            )
        })
        .collect::<Vec<_>>();
    let pinned = backed
        .iter()
        .filter_map(|item| {
            item.host_platform
                .and_then(|platform| item.binary.assets.get(&platform))
        })
        .map(|asset| asset.sha256.as_str())
        .collect::<BTreeSet<_>>();
    let owned = backed
        .iter()
        .map(|item| item.binary.id.as_str())
        .collect::<BTreeSet<_>>();
    let mut report = BinaryCleanupReport::default();
    collect_staged_store(paths, &pinned, &mut report)?;
    collect_exposure_links(paths, &owned, &mut report)?;
    report.removed_paths.sort();
    Ok(report)
}

/// Clean `binaries/`: unpinned digest directories and abandoned download debris.
fn collect_staged_store(
    paths: &StorePaths,
    pinned: &BTreeSet<&str>,
    report: &mut BinaryCleanupReport,
) -> DaloResult<()> {
    let root = &paths.binaries_dir;
    let metadata = match fs::symlink_metadata(root) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error.into()),
    };
    if !metadata.file_type().is_dir() {
        report.warnings.push(format!(
            "left `{}` in place: it is not a real directory",
            root.display()
        ));
        return Ok(());
    }
    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();
        let file_name = entry.file_name();
        // Names that are not UTF-8 cannot be Dalo's, so they are never touched.
        let Some(name) = file_name.to_str() else {
            continue;
        };
        if name.starts_with(DOWNLOAD_TEMPORARY_PREFIX) {
            remove_download_debris(&path, report);
        } else if is_sha256_hex(name) && !pinned.contains(name) {
            remove_staged_digest(&path, report);
        }
    }
    Ok(())
}

/// Remove one interrupted download once it is old enough to be abandoned.
fn remove_download_debris(path: &Path, report: &mut BinaryCleanupReport) {
    let Ok(metadata) = fs::symlink_metadata(path) else {
        return;
    };
    if !metadata.file_type().is_file() {
        report.warnings.push(format!(
            "left `{}` in place: download debris must be a regular file",
            path.display()
        ));
        return;
    }
    // A file with an unreadable or future timestamp is kept, not guessed at.
    let Ok(modified) = metadata.modified() else {
        return;
    };
    let abandoned = SystemTime::now()
        .duration_since(modified)
        .is_ok_and(|age| age > DOWNLOAD_DEBRIS_MIN_AGE);
    if !abandoned {
        return;
    }
    match fs::remove_file(path) {
        Ok(()) => report.removed_paths.push(path.to_path_buf()),
        Err(error) => report.warnings.push(format!(
            "could not remove download debris `{}`: {error}",
            path.display()
        )),
    }
}

/// Remove one staged digest directory that no approved declaration pins.
///
/// The directory must hold exactly one regular file, the verified binary Dalo
/// staged there. A symbolic link, or a directory with any other content, is kept.
fn remove_staged_digest(path: &Path, report: &mut BinaryCleanupReport) {
    let Ok(metadata) = fs::symlink_metadata(path) else {
        return;
    };
    if metadata.file_type().is_symlink() {
        report.warnings.push(format!(
            "left `{}` in place: it is a symbolic link, not a staged directory",
            path.display()
        ));
        return;
    }
    if !metadata.file_type().is_dir() {
        report.warnings.push(format!(
            "left `{}` in place: it is not a staged directory",
            path.display()
        ));
        return;
    }
    let entries = fs::read_dir(path).and_then(|entries| entries.collect::<io::Result<Vec<_>>>());
    let entries = match entries {
        Ok(entries) => entries,
        Err(error) => {
            report
                .warnings
                .push(format!("left `{}` in place: {error}", path.display()));
            return;
        }
    };
    let [entry] = entries.as_slice() else {
        report.warnings.push(format!(
            "left `{}` in place: it holds {} entries, expected one staged file",
            path.display(),
            entries.len()
        ));
        return;
    };
    let file = entry.path();
    if !fs::symlink_metadata(&file).is_ok_and(|metadata| metadata.file_type().is_file()) {
        report.warnings.push(format!(
            "left `{}` in place: its entry is not a regular file",
            path.display()
        ));
        return;
    }
    // The directory is read-only; making it writable is what lets its single file go.
    let outcome = fs::set_permissions(path, fs::Permissions::from_mode(0o755))
        .and_then(|()| fs::remove_file(&file))
        .and_then(|()| fs::remove_dir(path));
    match outcome {
        Ok(()) => report.removed_paths.push(path.to_path_buf()),
        Err(error) => report.warnings.push(format!(
            "could not remove staged binary `{}`: {error}",
            path.display()
        )),
    }
}

/// Clean `bin/`: links into `binaries/` whose target is gone or whose owner is not approved.
///
/// Anything else in `bin/`, including a real file a user placed there, is kept and
/// reported. Revocation and removal never delete a foreign entry.
fn collect_exposure_links(
    paths: &StorePaths,
    owned: &BTreeSet<&str>,
    report: &mut BinaryCleanupReport,
) -> DaloResult<()> {
    let entries = match fs::read_dir(&paths.bin_dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error.into()),
    };
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();
        let dalo_link = fs::symlink_metadata(&path)
            .is_ok_and(|metadata| metadata.file_type().is_symlink())
            && link_targets_binaries(&path, &paths.binaries_dir);
        if !dalo_link {
            report.warnings.push(format!(
                "left `{}` in place: it is not a symbolic link into `binaries/`",
                path.display()
            ));
            continue;
        }
        // `fs::metadata` follows the link, so a link whose target is gone reads as missing.
        let dangling = fs::metadata(&path).is_err();
        if dangling || !owned.contains(name.as_str()) {
            match fs::remove_file(&path) {
                Ok(()) => report.removed_paths.push(path),
                Err(error) => report.warnings.push(format!(
                    "could not remove exposure link `{}`: {error}",
                    path.display()
                )),
            }
        }
    }
    Ok(())
}

/// Stage the verified host asset of one binary, downloading it only when needed.
///
/// Bytes already staged under the pinned digest are reused without any network
/// access, which also lets two skills that pin the same bytes share them. Otherwise
/// the asset is streamed into a temporary file in the store and renamed into
/// `binaries/<sha256>/<id>` only once its digest matches; a mismatch deletes the
/// temporary file and stages nothing.
pub(crate) fn fetch_and_stage(
    paths: &StorePaths,
    binary: &BinaryRecord,
    platform: BinaryPlatform,
) -> DaloResult<PathBuf> {
    let asset = binary
        .assets
        .get(&platform)
        .ok_or_else(|| DaloError::InvalidArgument {
            reason: format!(
                "binary `{}` declares no asset for platform `{platform}`",
                binary.source_ref
            ),
        })?;
    let root = staged_root(paths, &asset.sha256);
    let destination = root.join(&binary.id);
    if staged_bytes_match(&destination, &asset.sha256) {
        return Ok(destination);
    }
    let temporary = download_verified(paths, binary, asset)?;
    // Another process may have staged the same digest while this one downloaded it.
    if staged_bytes_match(&destination, &asset.sha256) {
        return Ok(destination);
    }
    prepare_staging_directory(&root)?;
    fs::set_permissions(temporary.path(), fs::Permissions::from_mode(0o555))?;
    if let Err(error) = temporary.persist(&destination) {
        if staged_bytes_match(&destination, &asset.sha256) {
            return Ok(destination);
        }
        return Err(error.error.into());
    }
    make_directories_read_only(&root)?;
    Ok(destination)
}

/// Make `root` a writable directory so a verified file can be renamed into it.
///
/// A symlink or other non-directory at this path is refused rather than followed,
/// so permissions are never changed outside the store.
fn prepare_staging_directory(root: &Path) -> DaloResult<()> {
    match fs::symlink_metadata(root) {
        Ok(metadata) if metadata.file_type().is_dir() => {
            fs::set_permissions(root, fs::Permissions::from_mode(0o755))?;
            Ok(())
        }
        Ok(_) => Err(DaloError::StateError {
            reason: format!(
                "content-addressed binary path `{}` is not a directory",
                root.display()
            ),
        }),
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            fs::create_dir(root)?;
            Ok(())
        }
        Err(error) => Err(error.into()),
    }
}

/// Download the host asset into a temporary file in the store and verify its digest.
///
/// The temporary file is returned only when its digest matches the pin. Every
/// other outcome, including a policy refusal, a size refusal, or a digest
/// mismatch, drops it, which deletes it.
fn download_verified(
    paths: &StorePaths,
    binary: &BinaryRecord,
    asset: &BinaryAsset,
) -> DaloResult<NamedTempFile> {
    let mut response = request_asset(asset, &binary.source_ref)?;
    let declared = response
        .headers()
        .get(CONTENT_LENGTH)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse::<u64>().ok());
    if let Some(length) = declared.filter(|length| *length > MAX_BINARY_BYTES) {
        return Err(DaloError::StateError {
            reason: format!(
                "binary `{}` declares {length} bytes, above the 256 MiB limit; refusing to download it",
                binary.source_ref
            ),
        });
    }
    fs::create_dir_all(&paths.binaries_dir)?;
    let mut temporary = tempfile::Builder::new()
        .prefix(DOWNLOAD_TEMPORARY_PREFIX)
        .tempfile_in(&paths.binaries_dir)?;
    // One byte past the limit, so an oversized body reaches the explicit check in
    // `stream_and_hash` instead of surfacing as a reader error.
    let mut reader = response
        .body_mut()
        .with_config()
        .limit(MAX_BINARY_BYTES + 1)
        .reader();
    let downloaded = stream_and_hash(
        &mut reader,
        temporary.as_file_mut(),
        MAX_BINARY_BYTES,
        &binary.source_ref,
    )?;
    if downloaded != asset.sha256 {
        return Err(DaloError::StateError {
            reason: format!(
                "binary verification failed for `{}`: expected sha256:{}, downloaded sha256:{downloaded}",
                binary.source_ref, asset.sha256
            ),
        });
    }
    temporary.as_file().sync_all()?;
    Ok(temporary)
}

/// Copy `reader` into `writer` while hashing it, refusing more than `limit` bytes.
fn stream_and_hash(
    reader: &mut impl Read,
    writer: &mut impl Write,
    limit: u64,
    identity: &str,
) -> DaloResult<String> {
    let mut hasher = Sha256::new();
    let mut total = 0_u64;
    let mut buffer = vec![0_u8; 64 * 1024];
    loop {
        let read = match reader.read(&mut buffer) {
            Ok(0) => break,
            Ok(read) => read,
            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
            Err(error) => {
                return Err(DaloError::Io(io::Error::other(format!(
                    "could not download the asset for `{identity}`: {error}"
                ))));
            }
        };
        total += read as u64;
        if total > limit {
            return Err(DaloError::StateError {
                reason: format!(
                    "binary `{identity}` is larger than {limit} bytes; refusing to stage it"
                ),
            });
        }
        hasher.update(&buffer[..read]);
        writer.write_all(&buffer[..read])?;
    }
    Ok(hex_digest(hasher.finalize()))
}

/// Send the asset request, following at most [`MAX_REDIRECTS`] redirects.
///
/// Each target is checked before Dalo connects to it, so a redirect outside
/// GitHub is refused without a request reaching that host. No credentials are
/// ever attached. The final response URI is checked again before its body is read.
fn request_asset(
    asset: &BinaryAsset,
    identity: &str,
) -> DaloResult<ureq::http::Response<ureq::Body>> {
    let agent = download_agent();
    let mut url = asset.url.clone();
    let mut redirects = 0_u32;
    loop {
        let uri: Uri = url.parse().map_err(|_| DaloError::StateError {
            reason: format!("binary `{identity}` has an invalid download URL"),
        })?;
        check_download_uri(&uri, identity)?;
        let response = agent
            .get(url.as_str())
            .header("Accept", "application/octet-stream")
            .call()
            .map_err(|error| {
                DaloError::Io(io::Error::other(format!(
                    "could not download the asset for `{identity}`: {error}"
                )))
            })?;
        let status = response.status();
        if matches!(status.as_u16(), 301 | 302 | 303 | 307 | 308) {
            if redirects == MAX_REDIRECTS {
                return Err(DaloError::StateError {
                    reason: format!(
                        "binary download for `{identity}` followed more than {MAX_REDIRECTS} redirects"
                    ),
                });
            }
            redirects += 1;
            let location = response
                .headers()
                .get(LOCATION)
                .and_then(|value| value.to_str().ok())
                .and_then(|value| resolve_location(&uri, value))
                .ok_or_else(|| DaloError::StateError {
                    reason: format!(
                        "binary download for `{identity}` redirected without a usable Location header"
                    ),
                })?;
            url = location;
            continue;
        }
        if !status.is_success() {
            return Err(DaloError::StateError {
                reason: format!(
                    "binary download for `{identity}` returned HTTP status {}",
                    status.as_u16()
                ),
            });
        }
        check_download_uri(response.get_uri(), identity)?;
        return Ok(response);
    }
}

/// Resolve a redirect `Location` header against the URI of the request that received it.
///
/// An absolute location is returned unchanged. A root-relative one (`/path`) keeps
/// the request's scheme and authority. Any other location is relative to the
/// directory of the request path, up to and including its last `/`. The authority
/// never changes, so a relative location cannot move the request to another host;
/// the download policy still checks the result. Returns `None` when the result is
/// not a valid URI.
fn resolve_location(current: &Uri, location: &str) -> Option<String> {
    if location
        .parse::<Uri>()
        .is_ok_and(|uri| uri.scheme().is_some())
    {
        return Some(location.to_owned());
    }
    let scheme = current.scheme_str()?;
    let authority = current.authority()?.as_str();
    let path = if location.starts_with('/') {
        location.to_owned()
    } else {
        let base = current.path();
        let directory = match base.rfind('/') {
            Some(index) => &base[..=index],
            None => "/",
        };
        format!("{directory}{location}")
    };
    let resolved = format!("{scheme}://{authority}{path}");
    resolved.parse::<Uri>().ok().map(|_| resolved)
}

/// Refuse any download target that is not HTTPS on GitHub or its release CDN.
fn check_download_uri(uri: &Uri, identity: &str) -> DaloResult<()> {
    if loopback_http_allowed(uri) {
        return Ok(());
    }
    if uri.scheme_str() != Some("https") {
        return Err(DaloError::StateError {
            reason: format!("binary download for `{identity}` must use https; refusing `{uri}`"),
        });
    }
    let host = uri.host().unwrap_or_default().to_ascii_lowercase();
    if host == "github.com" || host.ends_with(".githubusercontent.com") {
        return Ok(());
    }
    Err(DaloError::StateError {
        reason: format!(
            "binary download for `{identity}` may only come from github.com or *.githubusercontent.com; refusing `{host}`"
        ),
    })
}

/// Whether a test may fetch a plain-HTTP loopback URL.
#[cfg(test)]
fn loopback_http_allowed(uri: &Uri) -> bool {
    uri.scheme_str() == Some("http")
        && uri.host() == Some("127.0.0.1")
        && *TEST_ALLOW_INSECURE_LOOPBACK
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
}

/// Production builds never accept a plain-HTTP download target.
#[cfg(not(test))]
fn loopback_http_allowed(_uri: &Uri) -> bool {
    false
}

/// HTTP agent for one download: a global timeout, no automatic redirects, and
/// Dalo's own user agent. Proxies follow `ureq`'s standard environment handling.
fn download_agent() -> ureq::Agent {
    ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(DOWNLOAD_TIMEOUT))
            .max_redirects(0)
            .max_redirects_will_error(false)
            .user_agent(concat!("dalo/", env!("CARGO_PKG_VERSION")))
            .build(),
    )
}

/// Expose one verified binary at `<store>/bin/<id>` as a relative symlink.
///
/// A link that already resolves to `staged_path` is left alone. A symlink into
/// `binaries/` for another digest, or a dangling one, is replaced atomically through
/// a temporary link. Anything else at that path (a real file, a directory, or a
/// foreign symlink) is refused and never removed.
pub(crate) fn expose(
    paths: &StorePaths,
    binary: &BinaryRecord,
    staged_path: &Path,
) -> DaloResult<PathBuf> {
    fs::create_dir_all(&paths.bin_dir)?;
    let link = paths.bin_dir.join(&binary.id);
    if link_resolves_to(&link, staged_path) {
        return Ok(link);
    }
    let staged_relative =
        staged_path
            .strip_prefix(&paths.root)
            .map_err(|_| DaloError::StateError {
                reason: format!(
                    "staged binary `{}` is outside the store",
                    staged_path.display()
                ),
            })?;
    let target = Path::new("..").join(staged_relative);
    match fs::symlink_metadata(&link) {
        Ok(metadata)
            if metadata.file_type().is_symlink()
                && link_targets_binaries(&link, &paths.binaries_dir) => {}
        Ok(_) => {
            return Err(DaloError::StateError {
                reason: format!(
                    "`{}` already exists and is not a Dalo link to a verified binary; refusing to replace it",
                    link.display()
                ),
            });
        }
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(error.into()),
    }
    replace_link(&link, &target, &binary.id)?;
    Ok(link)
}

/// Atomically point `link` at `target` by renaming a temporary symlink over it.
fn replace_link(link: &Path, target: &Path, id: &str) -> DaloResult<()> {
    let temporary = link.with_file_name(format!("{id}.tmp-{}", process::id()));
    if fs::symlink_metadata(&temporary).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
        fs::remove_file(&temporary)?;
    }
    symlink(target, &temporary)?;
    if let Err(error) = fs::rename(&temporary, link) {
        let _ = fs::remove_file(&temporary);
        return Err(error.into());
    }
    Ok(())
}

/// Whether the symlink at `link` lexically targets a path inside `binaries_dir`.
fn link_targets_binaries(link: &Path, binaries_dir: &Path) -> bool {
    let Ok(target) = fs::read_link(link) else {
        return false;
    };
    let resolved = if target.is_absolute() {
        target
    } else {
        link.parent().unwrap_or(Path::new("")).join(target)
    };
    lexical_normalize(&resolved).starts_with(lexical_normalize(binaries_dir))
}

/// Resolve `.` and `..` without touching the filesystem.
fn lexical_normalize(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                normalized.pop();
            }
            Component::CurDir => {}
            other => normalized.push(other.as_os_str()),
        }
    }
    normalized
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{TcpListener, TcpStream};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::thread;
    use tempfile::TempDir;

    const SKILL_REF: &str = "team:page-engine";
    const DIGEST: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    /// The `binaries` mapping of one valid declaration.
    const MAPPING: &str = "impeccino:
  source: github-release
  repo: sebastian-software/impeccino
  tag: engine-v0.2.0
  availability: required
  assets:
    macos-arm64:
      asset: impeccino-darwin-arm64
      sha256: \"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"
    linux-x64:
      asset: impeccino-linux-x64
      sha256: \"fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210\"
";

    fn parse(text: &str) -> Result<Vec<BinaryRecord>, String> {
        let value: yaml_serde::Value = yaml_serde::from_str(text).expect("test YAML should parse");
        parse_declarations(SKILL_REF, &value)
    }

    /// A whole `SKILL.md` frontmatter with the given description and digest.
    fn frontmatter(description: &str, digest: &str) -> String {
        format!(
            "name: page-engine
description: {description}
binaries:
  impeccino:
    source: github-release
    repo: sebastian-software/impeccino
    tag: engine-v0.2.0
    availability: required
    assets:
      macos-arm64:
        asset: impeccino-darwin-arm64
        sha256: \"{digest}\"
      linux-x64:
        asset: impeccino-linux-x64
        sha256: \"fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210\"
"
        )
    }

    /// The binary records declared by one frontmatter document.
    fn declared(document: &str) -> Vec<BinaryRecord> {
        let mapping: yaml_serde::Mapping =
            yaml_serde::from_str(document).expect("frontmatter should parse");
        let value = mapping.get("binaries").expect("binaries key should exist");
        parse_declarations(SKILL_REF, value).expect("declaration should be valid")
    }

    #[test]
    fn valid_declaration_derives_identity_urls_and_a_pinned_contract_hash() {
        let records = parse(MAPPING).expect("declaration should be valid");
        assert_eq!(records.len(), 1);
        let binary = &records[0];
        assert_eq!(binary.id, "impeccino");
        assert_eq!(binary.source_ref, "team:page-engine#binary:impeccino");
        assert_eq!(binary.source, BinarySource::GithubRelease);
        assert_eq!(binary.availability, ToolAvailability::Required);
        assert_eq!(
            binary.assets.keys().copied().collect::<Vec<_>>(),
            [BinaryPlatform::MacosArm64, BinaryPlatform::LinuxX64]
        );
        assert_eq!(
            binary.assets[&BinaryPlatform::MacosArm64].url,
            "https://github.com/sebastian-software/impeccino/releases/download/engine-v0.2.0/impeccino-darwin-arm64"
        );
        assert_eq!(
            binary.contract_hash,
            "d651c9b99dadd5d94b9dd94e39b3d8c8d72efbc900d4b81641afd9b2e89db4c1"
        );
    }

    #[test]
    fn changing_one_asset_digest_changes_the_contract_hash() {
        let first = declared(&frontmatter("Audit pages", DIGEST))[0]
            .contract_hash
            .clone();
        let second = declared(&frontmatter(
            "Audit pages",
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        ))[0]
            .contract_hash
            .clone();
        assert_eq!(first.len(), 64);
        assert_ne!(first, second);
    }

    #[test]
    fn a_description_only_change_keeps_the_contract_hash() {
        let before = declared(&frontmatter("Audit pages", DIGEST));
        let after = declared(&frontmatter("Audit rendered pages with the engine", DIGEST));
        assert_eq!(before[0].contract_hash, after[0].contract_hash);
    }

    #[test]
    fn records_are_sorted_by_id_and_availability_defaults_to_required() {
        let text = format!(
            "zeta:\n  source: github-release\n  repo: a/zeta\n  tag: v1\n  assets:\n    linux-x64:\n      asset: zeta\n      sha256: \"{DIGEST}\"\n{MAPPING}"
        );
        let records = parse(&text).expect("both declarations should be valid");
        let ids = records
            .iter()
            .map(|record| record.id.as_str())
            .collect::<Vec<_>>();
        assert_eq!(ids, ["impeccino", "zeta"]);
        assert_eq!(records[1].availability, ToolAvailability::Required);
    }

    #[test]
    fn empty_mapping_declares_no_binaries() {
        assert_eq!(parse("{}"), Ok(Vec::new()));
    }

    #[test]
    fn rejects_each_declaration_rule_with_the_binary_id_in_the_message() {
        let cases: Vec<(&str, String)> = vec![
            ("bad id key", MAPPING.replace("impeccino:", "Impeccino:")),
            (
                "unknown source",
                MAPPING.replace("github-release", "http-download"),
            ),
            (
                "single-segment repo",
                MAPPING.replace("sebastian-software/impeccino", "sebastian-software"),
            ),
            (
                "dot-dot repo segment",
                MAPPING.replace("sebastian-software/impeccino", "sebastian-software/.."),
            ),
            (
                "tag starting with a dash",
                MAPPING.replace("engine-v0.2.0", "-engine"),
            ),
            (
                "tag with a leading slash",
                MAPPING.replace("engine-v0.2.0", "/v1"),
            ),
            (
                "tag with a trailing slash",
                MAPPING.replace("engine-v0.2.0", "v1/"),
            ),
            (
                "tag of a single slash",
                MAPPING.replace("engine-v0.2.0", "/"),
            ),
            (
                "unknown availability",
                MAPPING.replace("availability: required", "availability: always"),
            ),
            (
                "empty assets",
                MAPPING
                    .split("  assets:")
                    .next()
                    .expect("prefix")
                    .to_owned()
                    + "  assets: {}\n",
            ),
            (
                "unknown platform key",
                MAPPING.replace("macos-arm64", "windows-x64"),
            ),
            (
                "path-shaped asset name",
                MAPPING.replace("impeccino-linux-x64", "../impeccino"),
            ),
            (
                "63-character digest",
                MAPPING.replace(DIGEST, &DIGEST[..63]),
            ),
            (
                "unknown field",
                MAPPING.replace(
                    "  availability: required\n",
                    "  availability: required\n  expires: 1\n",
                ),
            ),
            (
                "unknown asset field",
                MAPPING.replace(
                    "asset: impeccino-linux-x64\n",
                    "asset: impeccino-linux-x64\n      expires: 1\n",
                ),
            ),
        ];
        for (label, text) in cases {
            let error = parse(&text).expect_err(label);
            assert!(error.starts_with("binary `"), "{label}: {error}");
        }
    }

    #[test]
    fn rejects_a_binaries_value_that_is_not_a_mapping() {
        for text in ["impeccino", "- impeccino", "~"] {
            assert!(parse(text).is_err(), "{text:?} must not be accepted");
        }
    }

    #[test]
    fn duplicate_binary_ids_are_a_yaml_error_before_validation() {
        let text = format!("impeccino:\n  tag: a\n{MAPPING}");
        assert!(yaml_serde::from_str::<yaml_serde::Value>(&text).is_err());
    }

    #[test]
    fn tag_rules_reject_empty_path_segments_at_both_ends() {
        for tag in ["/v1", "v1/", "/", "a//b", "a..b", "-x", ".x"] {
            assert!(!is_github_tag(tag), "{tag}");
        }
        for tag in ["engine-v0.2.0", "release/v1", "_x"] {
            assert!(is_github_tag(tag), "{tag}");
        }
    }

    #[test]
    fn host_platform_maps_only_the_declarable_os_and_architecture_pairs() {
        assert_eq!(
            host_platform_for("macos", "aarch64"),
            Some(BinaryPlatform::MacosArm64)
        );
        assert_eq!(
            host_platform_for("macos", "x86_64"),
            Some(BinaryPlatform::MacosX64)
        );
        assert_eq!(
            host_platform_for("linux", "aarch64"),
            Some(BinaryPlatform::LinuxArm64)
        );
        assert_eq!(
            host_platform_for("linux", "x86_64"),
            Some(BinaryPlatform::LinuxX64)
        );
        assert_eq!(host_platform_for("windows", "x86_64"), None);
        assert_eq!(host_platform_for("linux", "riscv64"), None);
    }

    #[test]
    fn identity_shape_requires_the_binary_namespace() {
        assert!(validate_identity_shape("team:page-engine#binary:impeccino").is_ok());
        for value in [
            "team:page-engine#tool:impeccino",
            "page-engine#binary:impeccino",
            "team:page-engine#binary:",
        ] {
            assert!(validate_identity_shape(value).is_err(), "{value}");
        }
    }

    const CONTRACT: &str = "1111111111111111111111111111111111111111111111111111111111111111";

    fn declaration(platform: BinaryPlatform, sha256: &str) -> BinaryRecord {
        BinaryRecord {
            id: "impeccino".to_owned(),
            source_ref: "team:page-engine#binary:impeccino".to_owned(),
            source: BinarySource::GithubRelease,
            repo: "sebastian-software/impeccino".to_owned(),
            tag: "engine-v0.2.0".to_owned(),
            availability: ToolAvailability::Required,
            assets: BTreeMap::from([(
                platform,
                BinaryAsset {
                    asset: "impeccino-bin".to_owned(),
                    sha256: sha256.to_owned(),
                    url: "https://github.com/sebastian-software/impeccino/releases/download/engine-v0.2.0/impeccino-bin".to_owned(),
                },
            )]),
            contract_hash: CONTRACT.to_owned(),
        }
    }

    fn exact_approval() -> ApprovalRecord {
        ApprovalRecord {
            scope: APPROVAL_SCOPE.to_owned(),
            value: format!("team:page-engine#binary:impeccino@sha256:{CONTRACT}"),
            granted_at_unix: None,
        }
    }

    fn stage(paths: &StorePaths, digest: &str, bytes: &[u8]) {
        let directory = staged_root(paths, digest);
        fs::create_dir_all(&directory).unwrap();
        fs::write(directory.join("impeccino"), bytes).unwrap();
    }

    #[test]
    fn undeclared_host_is_platform_unsupported_with_or_without_a_host() {
        let temp = TempDir::new().unwrap();
        let paths = StorePaths::new(temp.path().join("store"));
        let record = declaration(BinaryPlatform::LinuxX64, &"aa".repeat(32));

        let mismatched = evaluate(
            &paths,
            &record,
            &[exact_approval()],
            Some(BinaryPlatform::MacosArm64),
        );
        assert_eq!(mismatched.state, BinaryState::PlatformUnsupported);
        let unknown = evaluate(&paths, &record, &[], None);
        assert_eq!(unknown.state, BinaryState::PlatformUnsupported);
        assert!(unknown.staged_path.is_none());
    }

    #[test]
    fn undecided_contract_is_pending_and_a_changed_contract_drifts() {
        let temp = TempDir::new().unwrap();
        let paths = StorePaths::new(temp.path().join("store"));
        let record = declaration(BinaryPlatform::LinuxX64, &"aa".repeat(32));

        assert_eq!(
            evaluate(&paths, &record, &[], Some(BinaryPlatform::LinuxX64)).state,
            BinaryState::PendingApproval
        );
        let prior = ApprovalRecord {
            scope: APPROVAL_SCOPE.to_owned(),
            value: format!(
                "team:page-engine#binary:impeccino@sha256:{}",
                "00".repeat(32)
            ),
            granted_at_unix: None,
        };
        assert_eq!(
            evaluate(&paths, &record, &[prior], Some(BinaryPlatform::LinuxX64)).state,
            BinaryState::HashDrift
        );
    }

    #[test]
    fn approval_and_staged_bytes_decide_between_ready_audit_and_revocation() {
        let temp = TempDir::new().unwrap();
        let paths = StorePaths::new(temp.path().join("store"));
        let bytes = b"verified release bytes";
        let digest = sha256_hex(bytes);
        let record = declaration(BinaryPlatform::LinuxX64, &digest);
        let host = Some(BinaryPlatform::LinuxX64);
        let approvals = [exact_approval()];

        assert_eq!(
            evaluate(&paths, &record, &approvals, host).state,
            BinaryState::ApprovedNotStaged
        );

        stage(&paths, &digest, b"tampered");
        assert_eq!(
            evaluate(&paths, &record, &approvals, host).state,
            BinaryState::AuditFailure
        );
        assert_eq!(
            evaluate(&paths, &record, &[], host).state,
            BinaryState::Revoked
        );

        stage(&paths, &digest, bytes);
        let unlinked = evaluate(&paths, &record, &approvals, host);
        assert_eq!(unlinked.state, BinaryState::ApprovedNotStaged);
        assert!(unlinked.exposed_path.is_none());
        assert!(
            unlinked
                .diagnostic
                .contains("is not linked to them; rerun `dalo approve binary team:page-engine#binary:impeccino`"),
            "{}",
            unlinked.diagnostic
        );

        let staged = staged_root(&paths, &digest).join("impeccino");
        expose(&paths, &record, &staged).unwrap();
        let ready = evaluate(&paths, &record, &approvals, host);
        assert_eq!(ready.state, BinaryState::Ready);
        assert_eq!(ready.staged_path, Some(staged));
        assert_eq!(ready.exposed_path, Some(paths.bin_dir.join("impeccino")));
    }

    /// Serializes the tests that toggle the loopback download override.
    static LOOPBACK_POLICY: Mutex<()> = Mutex::new(());

    /// Run `body` with plain-HTTP loopback downloads allowed or refused.
    fn with_loopback_policy<T>(allowed: bool, body: impl FnOnce() -> T) -> T {
        let _serial = LOOPBACK_POLICY
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        *TEST_ALLOW_INSECURE_LOOPBACK
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = allowed;
        let result = body();
        *TEST_ALLOW_INSECURE_LOOPBACK
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = false;
        result
    }

    fn sha256_hex(bytes: &[u8]) -> String {
        hex_digest(Sha256::digest(bytes))
    }

    /// A plain-HTTP fixture on `127.0.0.1` that answers each accepted connection
    /// with the next canned response, repeating the last one, and counts connections.
    struct Loopback {
        port: u16,
        accepted: Arc<AtomicUsize>,
    }

    impl Loopback {
        /// Start serving the responses that `responses` builds for this port.
        fn serve(responses: impl FnOnce(u16) -> Vec<Vec<u8>>) -> Self {
            let listener = TcpListener::bind(("127.0.0.1", 0)).expect("loopback port should bind");
            let port = listener.local_addr().expect("local address").port();
            let responses = responses(port);
            let accepted = Arc::new(AtomicUsize::new(0));
            let counter = Arc::clone(&accepted);
            thread::spawn(move || {
                for stream in listener.incoming() {
                    let Ok(mut stream) = stream else { continue };
                    let index = counter.fetch_add(1, Ordering::SeqCst);
                    read_request_head(&mut stream);
                    let response = &responses[index.min(responses.len() - 1)];
                    let _ = stream.write_all(response);
                }
            });
            Self { port, accepted }
        }

        fn url(&self, path: &str) -> String {
            format!("http://127.0.0.1:{}{path}", self.port)
        }

        fn connections(&self) -> usize {
            self.accepted.load(Ordering::SeqCst)
        }
    }

    fn read_request_head(stream: &mut TcpStream) {
        let mut seen = Vec::new();
        let mut chunk = [0_u8; 1024];
        while !seen.windows(4).any(|window| window == b"\r\n\r\n") && seen.len() < 16 * 1024 {
            match stream.read(&mut chunk) {
                Ok(0) | Err(_) => break,
                Ok(read) => seen.extend_from_slice(&chunk[..read]),
            }
        }
    }

    /// One complete `Connection: close` HTTP/1.1 response.
    fn response(status: &str, headers: &[(&str, String)], body: &[u8]) -> Vec<u8> {
        let mut head = format!("HTTP/1.1 {status}\r\nConnection: close\r\n");
        for (name, value) in headers {
            head.push_str(&format!("{name}: {value}\r\n"));
        }
        head.push_str("\r\n");
        let mut bytes = head.into_bytes();
        bytes.extend_from_slice(body);
        bytes
    }

    fn ok_with(body: &[u8]) -> Vec<u8> {
        response(
            "200 OK",
            &[("Content-Length", body.len().to_string())],
            body,
        )
    }

    /// A store whose read-only staging is made writable again on drop, so the
    /// temporary directory can be removed.
    struct TestStore {
        _temp: TempDir,
        paths: StorePaths,
    }

    impl TestStore {
        fn new() -> Self {
            let temp = TempDir::new().unwrap();
            let paths = StorePaths::new(temp.path().join("store"));
            fs::create_dir_all(&paths.root).unwrap();
            Self { _temp: temp, paths }
        }

        fn leftover_entries(&self) -> usize {
            fs::read_dir(&self.paths.binaries_dir).map_or(0, Iterator::count)
        }
    }

    impl Drop for TestStore {
        fn drop(&mut self) {
            if let Ok(entries) = fs::read_dir(&self.paths.binaries_dir) {
                for entry in entries.flatten() {
                    let _ = fs::set_permissions(entry.path(), fs::Permissions::from_mode(0o755));
                }
            }
            let _ =
                fs::set_permissions(&self.paths.binaries_dir, fs::Permissions::from_mode(0o755));
        }
    }

    fn mode(path: &Path) -> u32 {
        fs::metadata(path).unwrap().permissions().mode() & 0o777
    }

    /// A linux-x64 declaration whose asset URL points at a test server.
    fn downloadable(url: &str, sha256: &str) -> BinaryRecord {
        let mut record = declaration(BinaryPlatform::LinuxX64, sha256);
        record
            .assets
            .get_mut(&BinaryPlatform::LinuxX64)
            .expect("linux-x64 asset")
            .url = url.to_owned();
        record
    }

    fn fetch(store: &TestStore, record: &BinaryRecord) -> DaloResult<PathBuf> {
        fetch_and_stage(&store.paths, record, BinaryPlatform::LinuxX64)
    }

    #[test]
    fn fetch_should_stage_a_matching_asset_read_only_at_its_digest_path() {
        let bytes = b"verified release bytes";
        let digest = sha256_hex(bytes);
        let server = Loopback::serve(|_| vec![ok_with(bytes)]);
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let staged = with_loopback_policy(true, || fetch(&store, &record)).unwrap();

        assert_eq!(staged, staged_root(&store.paths, &digest).join("impeccino"));
        assert_eq!(fs::read(&staged).unwrap(), bytes);
        assert_eq!(mode(&staged), 0o555);
        assert_eq!(mode(&staged_root(&store.paths, &digest)), 0o555);
        assert_eq!(server.connections(), 1);
        assert_eq!(store.leftover_entries(), 1, "only the digest directory");
    }

    #[test]
    fn a_second_fetch_reuses_the_staged_bytes_without_any_request() {
        let bytes = b"verified release bytes";
        let digest = sha256_hex(bytes);
        let server = Loopback::serve(|_| vec![ok_with(bytes)]);
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let first = with_loopback_policy(true, || fetch(&store, &record)).unwrap();
        let second = with_loopback_policy(true, || fetch(&store, &record)).unwrap();

        assert_eq!(first, second);
        assert_eq!(server.connections(), 1);
    }

    #[test]
    fn a_tampered_download_fails_verification_and_leaves_nothing_behind() {
        let digest = sha256_hex(b"the pinned release bytes");
        let server = Loopback::serve(|_| vec![ok_with(b"tampered bytes")]);
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let error = with_loopback_policy(true, || fetch(&store, &record)).unwrap_err();

        let message = error.to_string();
        assert!(message.contains("binary verification failed"), "{message}");
        assert!(
            message.contains(&format!("expected sha256:{digest}")),
            "{message}"
        );
        assert!(!staged_root(&store.paths, &digest).exists());
        assert_eq!(
            store.leftover_entries(),
            0,
            "no temporary download may remain"
        );
    }

    #[test]
    fn a_content_length_above_the_limit_is_refused_before_the_body_is_read() {
        let digest = sha256_hex(b"unused");
        let oversized = (MAX_BINARY_BYTES + 1).to_string();
        let server = Loopback::serve(|_| {
            vec![response(
                "200 OK",
                &[("Content-Length", oversized.clone())],
                b"",
            )]
        });
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let error = with_loopback_policy(true, || fetch(&store, &record)).unwrap_err();

        assert!(
            error.to_string().contains("above the 256 MiB limit"),
            "{error}"
        );
        assert_eq!(store.leftover_entries(), 0);
    }

    #[test]
    fn a_body_past_the_size_limit_is_refused_while_streaming() {
        let mut input: &[u8] = b"0123456789";
        let mut sink = Vec::new();

        let error =
            stream_and_hash(&mut input, &mut sink, 4, "team:page-engine#binary:x").unwrap_err();

        assert!(error.to_string().contains("larger than 4 bytes"), "{error}");
        let mut input: &[u8] = b"0123456789";
        let digest = stream_and_hash(&mut input, &mut Vec::new(), 10, "x").unwrap();
        assert_eq!(digest, sha256_hex(b"0123456789"));
    }

    #[test]
    fn a_redirect_is_followed_only_to_an_allowed_target() {
        let bytes = b"verified release bytes";
        let digest = sha256_hex(bytes);
        let server = Loopback::serve(|port| {
            vec![
                response(
                    "302 Found",
                    &[("Location", format!("http://127.0.0.1:{port}/final"))],
                    b"",
                ),
                ok_with(bytes),
            ]
        });
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let staged = with_loopback_policy(true, || fetch(&store, &record)).unwrap();

        assert_eq!(fs::read(staged).unwrap(), bytes);
        assert_eq!(server.connections(), 2);
    }

    #[test]
    fn a_redirect_outside_github_is_refused_before_it_is_contacted() {
        let digest = sha256_hex(b"unused");
        let server = Loopback::serve(|_| {
            vec![response(
                "302 Found",
                &[("Location", "http://example.invalid/impeccino".to_owned())],
                b"",
            )]
        });
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let error = with_loopback_policy(true, || fetch(&store, &record)).unwrap_err();

        assert!(error.to_string().contains("example.invalid"), "{error}");
        assert_eq!(
            server.connections(),
            1,
            "the redirect target is never requested"
        );
        assert_eq!(store.leftover_entries(), 0);
    }

    #[test]
    fn a_plain_http_loopback_asset_is_refused_without_the_test_override() {
        let digest = sha256_hex(b"unused");
        let server = Loopback::serve(|_| vec![ok_with(b"unused")]);
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let error = with_loopback_policy(false, || fetch(&store, &record)).unwrap_err();

        assert!(error.to_string().contains("must use https"), "{error}");
        assert_eq!(server.connections(), 0);
    }

    #[test]
    fn download_policy_accepts_only_https_github_hosts() {
        let accepted = [
            "https://github.com/sebastian-software/impeccino/releases/download/v1/a",
            "https://objects.githubusercontent.com/a",
            "https://release-assets.githubusercontent.com/a",
        ];
        let refused = [
            "http://github.com/a",
            "https://api.github.com/a",
            "https://github.com.evil.example/a",
            "https://evil.githubusercontent.com.example/a",
            "https://evil.example/github.com",
            "https://user@evil.example/github.com",
        ];
        for url in accepted {
            let uri: Uri = url.parse().unwrap();
            assert!(check_download_uri(&uri, "x").is_ok(), "{url}");
        }
        for url in refused {
            let uri: Uri = url.parse().unwrap();
            assert!(check_download_uri(&uri, "x").is_err(), "{url}");
        }
    }

    #[test]
    fn a_root_relative_redirect_resolves_against_the_request_url() {
        let bytes = b"verified release bytes";
        let digest = sha256_hex(bytes);
        let server = Loopback::serve(|_| {
            vec![
                response(
                    "302 Found",
                    &[("Location", "/final/impeccino-linux-x64".to_owned())],
                    b"",
                ),
                ok_with(bytes),
            ]
        });
        let store = TestStore::new();
        let record = downloadable(&server.url("/impeccino-linux-x64"), &digest);

        let staged = with_loopback_policy(true, || fetch(&store, &record)).unwrap();

        assert_eq!(fs::read(staged).unwrap(), bytes);
        assert_eq!(server.connections(), 2);
    }

    #[test]
    fn resolve_location_keeps_absolute_locations_and_resolves_relative_ones() {
        let current: Uri = "https://github.com/owner/repo/releases/download/v1/asset.bin"
            .parse()
            .unwrap();

        assert_eq!(
            resolve_location(&current, "https://objects.githubusercontent.com/blob/x"),
            Some("https://objects.githubusercontent.com/blob/x".to_owned())
        );
        assert_eq!(
            resolve_location(&current, "/owner/repo/releases/download/v2/asset.bin"),
            Some("https://github.com/owner/repo/releases/download/v2/asset.bin".to_owned())
        );
        assert_eq!(
            resolve_location(&current, "other.bin"),
            Some("https://github.com/owner/repo/releases/download/v1/other.bin".to_owned())
        );
    }

    #[test]
    fn resolve_location_never_changes_the_authority_of_a_relative_location() {
        let current: Uri = "https://github.com/owner/repo/releases/download/v1/asset.bin"
            .parse()
            .unwrap();

        let scheme_relative = resolve_location(&current, "//evil.example/asset.bin")
            .expect("a path-shaped location should resolve");
        let uri: Uri = scheme_relative.parse().unwrap();
        assert_eq!(uri.host(), Some("github.com"));
        assert_eq!(
            resolve_location(&current, "https://bad host/asset.bin"),
            None
        );
    }

    #[test]
    fn expose_links_a_staged_binary_with_a_relative_target_and_is_idempotent() {
        let store = TestStore::new();
        let bytes = b"verified release bytes";
        let digest = sha256_hex(bytes);
        stage(&store.paths, &digest, bytes);
        let staged = staged_root(&store.paths, &digest).join("impeccino");
        let record = declaration(BinaryPlatform::LinuxX64, &digest);

        let link = expose(&store.paths, &record, &staged).unwrap();
        assert_eq!(link, store.paths.bin_dir.join("impeccino"));
        assert_eq!(
            fs::read_link(&link).unwrap(),
            PathBuf::from(format!("../binaries/{digest}/impeccino"))
        );
        expose(&store.paths, &record, &staged).unwrap();
        assert_eq!(fs::read(&link).unwrap(), bytes);
    }

    #[test]
    fn expose_replaces_a_stale_link_into_the_binaries_directory() {
        let store = TestStore::new();
        let old_digest = sha256_hex(b"old release bytes");
        let new_bytes = b"new release bytes";
        let new_digest = sha256_hex(new_bytes);
        stage(&store.paths, &old_digest, b"old release bytes");
        stage(&store.paths, &new_digest, new_bytes);
        let old_record = declaration(BinaryPlatform::LinuxX64, &old_digest);
        let new_record = declaration(BinaryPlatform::LinuxX64, &new_digest);
        expose(
            &store.paths,
            &old_record,
            &staged_root(&store.paths, &old_digest).join("impeccino"),
        )
        .unwrap();

        let link = expose(
            &store.paths,
            &new_record,
            &staged_root(&store.paths, &new_digest).join("impeccino"),
        )
        .unwrap();

        assert_eq!(
            fs::read_link(&link).unwrap(),
            PathBuf::from(format!("../binaries/{new_digest}/impeccino"))
        );
        assert_eq!(fs::read(&link).unwrap(), new_bytes);
        let leftovers = fs::read_dir(&store.paths.bin_dir).unwrap().count();
        assert_eq!(leftovers, 1, "the temporary link must not remain");
    }

    #[test]
    fn expose_refuses_a_real_file_or_a_foreign_link_and_never_removes_it() {
        let store = TestStore::new();
        let digest = sha256_hex(b"release bytes");
        stage(&store.paths, &digest, b"release bytes");
        let staged = staged_root(&store.paths, &digest).join("impeccino");
        let record = declaration(BinaryPlatform::LinuxX64, &digest);
        fs::create_dir_all(&store.paths.bin_dir).unwrap();
        let link = store.paths.bin_dir.join("impeccino");

        fs::write(&link, "user content").unwrap();
        let error = expose(&store.paths, &record, &staged).unwrap_err();
        assert!(
            error.to_string().contains("refusing to replace it"),
            "{error}"
        );
        assert_eq!(fs::read_to_string(&link).unwrap(), "user content");

        fs::remove_file(&link).unwrap();
        let foreign = store.paths.root.parent().unwrap().join("foreign-tool");
        symlink(&foreign, &link).unwrap();
        let error = expose(&store.paths, &record, &staged).unwrap_err();
        assert!(
            error.to_string().contains("refusing to replace it"),
            "{error}"
        );
        assert_eq!(fs::read_link(&link).unwrap(), foreign);
    }

    #[test]
    fn garbage_collect_removes_only_unpinned_single_file_digests_and_refuses_anything_else() {
        let store = TestStore::new();
        let unpinned_digest = sha256_hex(b"unpinned bytes");
        stage(&store.paths, &unpinned_digest, b"unpinned bytes");
        let unpinned = staged_root(&store.paths, &unpinned_digest);

        // A symbolic link named like a digest is never followed, even into a directory outside the store.
        let outside = store.paths.root.parent().unwrap().join("outside");
        fs::create_dir_all(&outside).unwrap();
        fs::write(outside.join("keep"), "outside").unwrap();
        let linked_digest = sha256_hex(b"linked");
        symlink(&outside, store.paths.binaries_dir.join(&linked_digest)).unwrap();

        // A digest directory with two entries is not one staged binary.
        let crowded_digest = sha256_hex(b"crowded");
        stage(&store.paths, &crowded_digest, b"crowded");
        let crowded = staged_root(&store.paths, &crowded_digest);
        fs::write(crowded.join("other"), "other").unwrap();

        // Dalo's link to the unpinned digest dangles once that digest is gone; a real file is not Dalo's.
        fs::create_dir_all(&store.paths.bin_dir).unwrap();
        symlink(
            unpinned.join("impeccino"),
            store.paths.bin_dir.join("impeccino"),
        )
        .unwrap();
        fs::write(store.paths.bin_dir.join("user-tool"), "user").unwrap();

        let report = garbage_collect(&store.paths, &[]).unwrap();

        assert!(!unpinned.exists());
        assert!(report.removed_paths.contains(&unpinned), "{report:?}");
        assert!(
            report
                .removed_paths
                .contains(&store.paths.bin_dir.join("impeccino")),
            "{report:?}"
        );
        assert_eq!(report.removed_paths.len(), 2, "{report:?}");
        assert_eq!(fs::read_to_string(outside.join("keep")).unwrap(), "outside");
        assert!(fs::symlink_metadata(store.paths.binaries_dir.join(&linked_digest)).is_ok());
        assert!(crowded.join("impeccino").is_file());
        assert!(crowded.join("other").is_file());
        assert!(store.paths.bin_dir.join("user-tool").is_file());
        for expected in [
            "is a symbolic link, not a staged directory",
            "holds 2 entries",
            "is not a symbolic link into `binaries/`",
        ] {
            assert!(
                report
                    .warnings
                    .iter()
                    .any(|warning| warning.contains(expected)),
                "missing `{expected}` in {:?}",
                report.warnings
            );
        }
    }

    #[test]
    fn cleanup_does_nothing_while_a_source_is_disabled_or_unscanned() {
        let store = TestStore::new();
        let digest = sha256_hex(b"kept bytes");
        stage(&store.paths, &digest, b"kept bytes");
        let snapshot = BinarySnapshot {
            list: BinaryListReport {
                binaries: Vec::new(),
                warnings: Vec::new(),
            },
            incomplete_sources: vec!["team".to_owned()],
        };

        let report = collect_unreferenced(&store.paths, &snapshot);

        assert!(report.removed_paths.is_empty(), "{report:?}");
        assert!(report.warnings[0].contains("binary cleanup skipped"));
        assert!(
            staged_root(&store.paths, &digest)
                .join("impeccino")
                .is_file()
        );
    }
}