varve-core 0.45.0

Layer manifests, resolution, the core store, and verification wiring for varve
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
//! `layer.toml` → assembler inputs (REQ-LAYERREPO-001).
//!
//! A realm's contents belong in the realm's own repository, not in varve's
//! workflow file: bumping `rivet` to v0.34.0 should be a one-line reviewed diff
//! in `pulseengine-layers`, not a commit to the tool that signs it. This module
//! is the adapter that makes that possible — it reads the manifest and produces
//! the environment `tools/build-deposit-spec.sh` already consumes.
//!
//! It lives HERE, next to the assembler it feeds, rather than in the layers
//! repository, because a realm running a *copy* of the assembler gets none of
//! the system testing varve does on it (REQ-PEL-ASSEMBLER-001). One writer, one
//! set of tests, every realm.
//!
//! ## Why this refuses so much
//!
//! The assembler's inputs are space-separated lists of colon-separated fields.
//! That encoding cannot represent a value containing a space or a colon, and
//! the shell will not complain — it will silently split one tool into two, or
//! truncate a version. A layer assembled from a mangled list is still signed,
//! still verifies, and carries the wrong bytes. So every field that lands in
//! the encoding is checked against the encoding's own alphabet BEFORE it gets
//! there, and anything the assembler cannot faithfully carry is an error rather
//! than a best-effort translation. This is the same reasoning that made
//! `UNVERIFIED_INGEST` line-separated instead of punctuation-separated.

use std::collections::BTreeSet;
use std::fmt;

/// The pinned varve release that builds this layer.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VarvePin {
    pub version: String,
}

/// Which realm this layer belongs to, and where it is published.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestRealm {
    pub name: String,
    pub channel: String,
    pub registry: String,
}

/// How a tool's release presents its binaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layout {
    /// One `.tar.gz` per target triple — the PulseEngine norm.
    Tarball,
    /// Bare per-platform binaries with no archive (sigil ships `wsc` this way).
    RawPerPlatform,
    /// A TREE: the archive itself is the payload (REQ-SDKDEPOSIT-001).
    ///
    /// The other two layouts mine one binary out of an archive and discard the
    /// rest. An SDK is the opposite shape — a compiler, its binutils, its
    /// headers and its sysroot are one thing, and taking a binary out of it
    /// destroys it. The archive is stored exactly as upstream published it;
    /// unpacking and relocating is `varve export-sdk`'s job, on the consumer's
    /// machine, per REQ-SDK-001 clause 3.
    Sdk,
    /// A Zephyr module TREE (REQ-ZMODEXPORT-001): the archive is the payload,
    /// as for `Sdk`, and for the same reason it cannot be mined for a binary.
    /// `varve export-zephyr-modules` lays it out on the consumer's machine.
    ZephyrModule,
}

impl Layout {
    fn parse(s: &str) -> Option<Layout> {
        match s {
            "tarball" => Some(Layout::Tarball),
            "raw-per-platform" => Some(Layout::RawPerPlatform),
            "sdk" => Some(Layout::Sdk),
            "zephyr-module" => Some(Layout::ZephyrModule),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestTool {
    pub name: String,
    pub version: String,
    /// `owner/repo`. Absent = `pulseengine/<name>`.
    #[serde(default)]
    pub repo: Option<String>,
    /// The executable's name, when it differs from the tool's (kiln ships
    /// `kilnd`). Absent = `<name>`.
    #[serde(default)]
    pub binary: Option<String>,
    /// Release asset name template; `%V` bare version, `%T` Rust target triple,
    /// `%U` short upstream platform tag. Absent = the assembler's default.
    #[serde(default)]
    pub asset: Option<String>,
    /// Absent = `tarball`.
    #[serde(default)]
    pub layout: Option<String>,
    /// The platforms this tool is carried for, when it is NOT every platform
    /// the layer declares. Absent = all of them, the ordinary case.
    ///
    /// This is for an upstream whose build for some platform cannot be carried
    /// as a varve payload at all, which is a different fact from not building
    /// it. `WebAssembly/binaryen` 133 is the measured case: its Linux binaries
    /// are statically linked and stand alone (18.7 MB), while its macOS
    /// binaries are 1.7 MB stubs needing a 15 MB `@rpath/libbinaryen.dylib`
    /// at `@loader_path/../lib`. A varve `tool` payload is ONE executable, so
    /// a macOS payload would pass install and verification and then fail at
    /// the first exec.
    ///
    /// An asset the release does not publish is already skipped, silently and
    /// correctly. That is the wrong mechanism here, because the macOS asset
    /// DOES exist: expressing this by naming a file that is not there would
    /// make a 404 enact a policy and leave the real reason recorded nowhere.
    #[serde(default)]
    pub platforms: Option<Vec<String>>,
    /// The opt-in, split into the part that EXPIRES and the parts that do not
    /// (REQ-PREPARED-001).
    ///
    /// `unverified-reason` below is one string carrying three different kinds
    /// of claim, and only one of them is about a particular release. Measured
    /// across the realms 2026-10-09: all 18 opt-ins follow the same three-part
    /// shape, in the same order.
    ///
    ///   * a MEASUREMENT — what was probed, when, what was found. True of ONE
    ///     release and false of the next.
    ///   * an ACCEPTANCE — why the operator carries it anyway. A standing
    ///     judgement about this upstream.
    ///   * an EXIT — what would remove the need. Also standing.
    ///
    /// Splitting them is what lets a scanner re-measure without touching the
    /// operator's judgement: it rewrites `measured` and never parses the rest.
    /// The alternative was a heuristic on free prose — replace everything up to
    /// the first full stop — which would mangle an unusually punctuated reason
    /// and then SIGN the result.
    #[serde(default)]
    pub unverified: Option<Unverified>,
    /// Why this tool is ingested with NO proof of origin (REQ-INGEST-001
    /// clause 3). Present only for a release that offers neither a
    /// cosign-signed sums file nor a build attestation.
    ///
    /// The reason is not paperwork: it is signed into the layer and shown by
    /// `varve inspect`, so every consumer reads the operator's words next to
    /// the bytes they were written about. "We could not verify this" must
    /// never be the silent path, which is why the field carries prose rather
    /// than a boolean.
    #[serde(rename = "unverified-reason", default)]
    pub unverified_reason: Option<String>,
    /// The RELEASE tag to fetch, when it differs from the payload's version
    /// (REQ-PAYLOADID-001).
    ///
    /// `version` is what the payload IS — the number it answers to, and the
    /// one signed into the layer. For almost every tool that is also its
    /// release tag, so `release` is absent and `version` serves both.
    ///
    /// A hub repository breaks that: `pulseengine/jess` tags `v0.7.2` and ships
    /// `with-device` at `0.2.2`. Without this field the manifest can say one or
    /// the other — sign a version the binary contradicts, or name a tag that
    /// does not exist — and the env encoding could already express it while
    /// layer.toml could not, so porting a realm to layer.toml LOST the payload.
    #[serde(rename = "release", default)]
    pub release: Option<String>,
    /// The asset carrying this release's UNSIGNED digest list, when it
    /// publishes one (REQ-UPSTREAMSUMS-001).
    ///
    /// Upstreams do not agree on a name — zephyrproject-rtos/sdk-ng calls it
    /// `sha256.sum` — so the realm states it rather than varve guessing.
    /// Guessing would be the worse failure: a file that is not the digest
    /// manifest, parsed as one, vouches for nothing while looking like it does.
    #[serde(rename = "upstream-sums", default)]
    pub upstream_sums: Option<String>,
    /// A path that must exist inside a `sdk` payload once unpacked
    /// (REQ-SDKDEPOSIT-001 clause 5).
    ///
    /// A tree payload cannot be architecture-checked the way a binary can — an
    /// SDK holds executables for several architectures and checking its first
    /// ELF proves nothing. What CAN be checked is shape, and the failure this
    /// catches is concrete: a 14 GB download that turns out to be an HTML
    /// error page hashes and signs perfectly well.
    #[serde(rename = "contains", default)]
    pub contains: Option<String>,
    /// The pip requirement files of a `zephyr-module` the operator accepts as
    /// a Python dependency (REQ-ZMODEXPORT-001 clause 5).
    ///
    /// varve distributes the blocks a project adds and needs no Python. A
    /// module whose `zephyr/module.yml` declares `package-managers: pip` adds
    /// a Python dependency to every build that uses it, so the deposit refuses
    /// it unless this names EXACTLY the declared files. It is signed into the
    /// layer and `varve inspect` shows it. Only a `layout = "zephyr-module"`
    /// entry may carry it.
    #[serde(rename = "allow-pip", default)]
    pub allow_pip: Option<Vec<String>>,
    /// Asset name for one target triple, when no template can derive it.
    ///
    /// Some upstreams ship a musl binary as their only Linux build —
    /// `wac-cli-x86_64-unknown-linux-musl` — and a static musl binary is the
    /// right payload for a gnu platform even though nothing in the platform
    /// name says so. Inventing a `%MUSL` placeholder would guess at a
    /// convention; naming the file is exact, and wrong-by-typo rather than
    /// wrong-by-inference.
    #[serde(rename = "asset-for", default)]
    pub asset_for: std::collections::BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestVsix {
    pub name: String,
    pub version: String,
    #[serde(default)]
    pub repo: Option<String>,
    /// Asset template; `%V` bare version, `%P` VS Code platform tag. A template
    /// with no `%P` is one portable package.
    pub asset: String,
}

/// What a `[[docs]]` payload IS, declared rather than inferred.
///
/// Never sniffed from the asset's extension. A wrong guess makes varve offer
/// to open a payload the wrong way, and extension-sniffing is the same class
/// of mistake as guessing an upstream's digest-manifest name — it looks like
/// it works until the one case where it does not. It is also the thing a
/// human filters on: "show me the PDF" is a question about this field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DocsFormat {
    /// A multi-file site rooted at `entry`. Needs a server for full fidelity:
    /// the traceability bundle's mermaid loader calls `fetch()`, which is
    /// CORS-blocked under `file://`, so diagrams degrade silently.
    Html,
    /// `cargo doc` output. Its own format rather than `html` because it is
    /// GENERATED, versions with the crate it documents, and answers a
    /// different question — "the API" is not "the handbook".
    Rustdoc,
    /// One file. Nothing to serve; there is only a path to hand over.
    Pdf,
    /// Source text, readable as-is.
    Markdown,
    /// ReqIF: an interchange file for a requirements tool, not for a reader.
    Reqif,
}

impl DocsFormat {
    /// Is this format a TREE of files, or a single one?
    ///
    /// It decides what `export-docs` produces and whether an `entry` can be
    /// checked at all — there is nothing inside a PDF to look for. The
    /// declared format decides it, never the asset's extension.
    pub fn is_tree(self) -> bool {
        matches!(self, DocsFormat::Html | DocsFormat::Rustdoc)
    }

    /// The file extension an exported single-file document is written under.
    ///
    /// `None` for a tree, which becomes a directory rather than a file.
    pub fn file_extension(self) -> Option<&'static str> {
        match self {
            DocsFormat::Pdf => Some("pdf"),
            DocsFormat::Markdown => Some("md"),
            DocsFormat::Reqif => Some("reqif"),
            DocsFormat::Html | DocsFormat::Rustdoc => None,
        }
    }

    /// The format a signed name denotes, or `None` for a name varve does not
    /// know.
    ///
    /// THE parser. `varve deposit` refuses an unknown format, and `export-docs`
    /// and `varve-serve` read one back; each used to carry its own list of
    /// names, so a format added to one would be signed by a deposit that the
    /// readers then refused, or the reverse.
    pub fn parse(raw: &str) -> Option<DocsFormat> {
        [
            DocsFormat::Html,
            DocsFormat::Rustdoc,
            DocsFormat::Pdf,
            DocsFormat::Markdown,
            DocsFormat::Reqif,
        ]
        .into_iter()
        .find(|f| f.as_str() == raw)
    }

    /// The word a human reads in `varve inspect` and filters on.
    pub fn as_str(self) -> &'static str {
        match self {
            DocsFormat::Html => "html",
            DocsFormat::Rustdoc => "rustdoc",
            DocsFormat::Pdf => "pdf",
            DocsFormat::Markdown => "markdown",
            DocsFormat::Reqif => "reqif",
        }
    }
}

/// Does `entry` name a real member of a docs payload?
///
/// Resolved against the payload ROOT, and the root is not always the archive
/// root: many upstreams wrap everything in a single top-level directory
/// (`thing-1.2.3/...`) while varve's own traceability bundle does not. So the
/// wrapper is detected — one top-level directory shared by every member — and
/// stripped before matching.
///
/// The match is then EXACT, deliberately. A tail match (`ends_with("/index.
/// html")`) looks equivalent and is not: the traceability bundle contains
/// `eu-ai-act/index.html` and `artifacts/index.html`, so a tail rule accepts a
/// payload whose declared root entry is missing entirely and reports success
/// while a reader's first link 404s.
pub fn docs_entry_present(members: &[String], entry: &str) -> bool {
    let norm: Vec<&str> = members
        .iter()
        .map(|m| m.trim_start_matches("./").trim_end_matches('/'))
        .filter(|m| !m.is_empty())
        .collect();

    // One top-level directory shared by everything = a wrapper, not content.
    let mut tops = norm
        .iter()
        .filter_map(|m| m.split('/').next())
        .collect::<std::collections::BTreeSet<_>>();
    let wrapper = if tops.len() == 1 {
        tops.pop_first().map(|t| format!("{t}/"))
    } else {
        None
    };

    let want = entry.trim_start_matches("./");
    norm.iter().any(|m| {
        let rel = match &wrapper {
            Some(w) => m.strip_prefix(w.as_str()).unwrap_or(m),
            None => m,
        };
        rel == want
    })
}

/// Why a docs payload's declared entry is not acceptable.
///
/// Returned rather than bailed so the DECISION is reachable by a `--lib` test.
/// The first version of this lived inline in the producer's staging loop, and
/// `cargo mutants` deleted the `!` from its `if !found` with nothing noticing:
/// the only thing exercising that branch was a system test, which the mutation
/// gate cannot run. A check whose logic only the systest reaches is a check
/// the gate cannot defend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocsEntryMissing {
    pub entry: String,
    /// A few member paths, for an error that helps rather than only refuses.
    pub saw: Vec<String>,
    pub members: usize,
}

/// Is a tree document's declared entry actually in it?
///
/// `Ok(())` when there is nothing to check — a single-file format has no
/// inside, and a payload that declares no entry has made no claim to break.
pub fn check_docs_entry(
    members: &[String],
    entry: Option<&str>,
    is_tree: bool,
) -> Result<(), DocsEntryMissing> {
    let Some(want) = entry else { return Ok(()) };
    if !is_tree {
        return Ok(());
    }
    if docs_entry_present(members, want) {
        return Ok(());
    }
    let mut saw: Vec<String> = members.iter().take(8).cloned().collect();
    saw.sort();
    Err(DocsEntryMissing {
        entry: want.to_string(),
        saw,
        members: members.len(),
    })
}

/// Documentation carried BY the layer, for the versions the layer pins
/// (REQ-LAYERDOCS-001).
///
/// Held, never dispatched — it is data, like a `vsix`. varve does not render
/// it; it carries it, verifies it, and says where it is.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestDocs {
    pub name: String,
    pub version: String,
    #[serde(default)]
    pub repo: Option<String>,
    /// What this payload IS. Declared; see [`DocsFormat`].
    pub format: DocsFormat,
    /// The file inside the payload a reader starts at.
    ///
    /// Declared rather than discovered. varve's own traceability bundle
    /// happens to have exactly one root `index.html`, and "whatever
    /// index.html we find" is a rule that breaks silently the day an upstream
    /// ships two — opening the wrong one is worse than refusing.
    ///
    /// Absent for a single-file format, where the asset IS the entry.
    #[serde(default)]
    pub entry: Option<String>,
    /// What a human sees when choosing. `name` is the handle a command takes;
    /// this is the sentence that tells someone which one they want.
    #[serde(default)]
    pub title: Option<String>,
    /// The payload this documents, by name — `documents = "varve-core"` on a
    /// crate's rustdoc (clause 2). Lets a reader ask for the documentation OF
    /// something. `varve deposit` refuses a name the layer does not carry.
    #[serde(default)]
    pub documents: Option<String>,
    /// Asset template; `%V` bare version, `%R` the release tag.
    pub asset: String,
    /// The release tag to fetch, when it differs from the payload's version.
    #[serde(rename = "release", default)]
    pub release: Option<String>,
}

/// A Rust crate carried BY the layer, as the `.crate` file a release publishes
/// (REQ-CRATEPAYLOAD-001).
///
/// Held, never dispatched: `varve run` on a `.crate` was never meaningful. The
/// consumer half already exists — `export-cargo`, `export-crates-vendor` and
/// `export-bazel-distdir` read `crate` payloads — and this is what lets a realm
/// declare one at all.
///
/// Ingested from a RELEASE ASSET, not from crates.io, so a crate is proven the
/// way every other payload of that release is. The bytes are the ones crates.io
/// serves: `cargo package` is reproducible, and varve's own release checks the
/// released `.crate` against the index `cksum` on every tag.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestCrate {
    /// The crate's name — what `Cargo.toml` depends on.
    pub name: String,
    /// The crate's own version, bare (`0.36.0`), as the registry index spells it.
    pub version: String,
    #[serde(default)]
    pub repo: Option<String>,
    /// Asset template; defaults to `<name>-%V.crate`, which is what
    /// `cargo package` writes.
    #[serde(default)]
    pub asset: Option<String>,
    /// The release tag to fetch, when it differs from the version — varve tags
    /// `v0.36.0` and publishes the crate as `0.36.0`.
    #[serde(rename = "release", default)]
    pub release: Option<String>,
}

/// Another realm's layer, composed into this one (REQ-COMPOSE-001).
///
/// One pin, two trust universes: this layer holds what the realm qualifies and
/// REFERENCES a layer it does not control, each keeping its own root, cadence
/// and qualification claim.
///
/// Until v0.37.0 this could only be said in a hand-written deposit spec, never
/// in a realm's manifest — so composition was implemented, tested and
/// documented, and no realm repository could produce a composed layer at all.
/// That is why the feature had no worked example: not an oversight in the
/// documentation, a gap in what the manifest could express.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestInclude {
    /// The digest of the included layer's SIGNED MANIFEST — not a tag, not a
    /// version. A composition names bytes, so it cannot drift after signing.
    pub digest: String,
    /// Whose trust root verifies the included layer.
    ///
    /// Optional in the format and required in practice: without it `verify`
    /// falls back to the PINNING project's root, so the layer installs cleanly
    /// and fails verification afterwards — and if the two realms happened to
    /// share a root it would silently widen trust instead. `check_manifest`
    /// refuses an include without one.
    #[serde(default)]
    pub realm: Option<String>,
    /// The included layer's id, used only in messages before it is fetched.
    #[serde(default)]
    pub layer: Option<String>,
}

/// The whole manifest. `deny_unknown_fields` throughout is load-bearing: a
/// mistyped `verison = "v0.34.0"` would otherwise leave the real `version`
/// missing or stale, and the layer would ship the wrong release under a good
/// signature.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LayerManifest {
    pub varve: VarvePin,
    pub realm: ManifestRealm,
    #[serde(default, rename = "tool")]
    pub tools: Vec<ManifestTool>,
    #[serde(default, rename = "vsix")]
    pub vsix: Vec<ManifestVsix>,
    #[serde(default, rename = "docs")]
    pub docs: Vec<ManifestDocs>,
    #[serde(default, rename = "crate")]
    pub crates: Vec<ManifestCrate>,
    #[serde(default, rename = "include")]
    pub includes: Vec<ManifestInclude>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LayerSpecError {
    /// The TOML did not parse, or carried a field the schema does not define.
    Parse(String),
    /// A value cannot survive the assembler's encoding.
    Unencodable {
        field: String,
        value: String,
        why: &'static str,
    },
    /// `layout = "..."` is not one the assembler implements.
    UnknownLayout { tool: String, layout: String },
    /// An `[[include]]` names no realm, or names a digest that is not one.
    BadInclude { digest: String, why: String },
    /// The assembler carries exactly one raw-per-platform tool, as
    /// `WSC_VERSION`. A second one has nowhere to go.
    ManyRawPerPlatform { first: String, second: String },
    /// The assembler's single raw-per-platform slot is not generic: it fetches
    /// `wsc` from `pulseengine/sigil`. Any other tool put in it becomes a
    /// request for the wrong tool from the wrong repository.
    RawPerPlatformNotWsc { tool: String, repo: String },
    /// The assembler hardcodes `pulseengine/` for extension repositories.
    VsixForeignOwner { name: String, repo: String },
    /// The assembler derives a tarball tool's identity from its REPOSITORY
    /// basename, so a manifest `name` that disagrees with it is discarded.
    RepoNameMismatch {
        name: String,
        repo: String,
        basename: String,
    },
    /// Two entries would land under one name.
    Duplicate { kind: &'static str, name: String },
    /// The env encoding has no field for this layout, so translating would
    /// silently change what the payload IS (REQ-SDKDEPOSIT-001).
    LayoutNotEncodable { tool: String, layout: String },
    /// The entry's fields are POSITIONAL, so a payload version cannot be
    /// carried past an absent binary or asset template.
    ReleaseNeedsBinaryAndAsset { tool: String },
    /// The encoding has no field for the upstream digest manifest, and losing
    /// it downgrades how the release is verified rather than how it is named.
    UpstreamSumsNotEncodable { tool: String, asset: String },
    /// The encoding has no field for a per-tool platform restriction, and
    /// losing it would carry the tool on a platform the realm deliberately
    /// excluded (REQ-TOOLPLAT-001).
    PlatformsNotEncodable {
        tool: String,
        platforms: Vec<String>,
    },
    /// Both opt-in forms on one entry. Which one counts would be a coin toss,
    /// and the loser is dropped silently out of a SIGNED layer.
    TwoOptInForms { tool: String },
    /// The encoding has one field for the whole reason, and flattening a split
    /// opt-in loses WHICH part is the measurement (REQ-PREPARED-001).
    SplitOptInNotEncodable { tool: String },
    /// An opt-in that states no reason.
    UnverifiedWithoutReason { tool: String },
    /// An opt-in whose reason is about a DIFFERENT release than the one
    /// pinned (REQ-INGEST-001). The commonest way to get here is a version
    /// bump that left the justification behind.
    ReasonIsAboutAnotherRelease {
        tool: String,
        pinned: String,
        reason: String,
    },
    /// Two tools from one repository disagree about why it is unverified.
    ConflictingReason {
        repo: String,
        first: String,
        second: String,
    },
    /// The manifest describes nothing to deposit.
    Empty,
}

impl fmt::Display for LayerSpecError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LayerSpecError::Parse(e) => write!(f, "layer.toml does not parse: {e}"),
            LayerSpecError::Unencodable { field, value, why } => write!(
                f,
                "{field} = {value:?} cannot be passed to the assembler: {why}. \
                 The assembler reads space-separated entries of colon-separated \
                 fields, so such a value would be split or truncated silently \
                 and the layer would carry the wrong bytes under a good signature."
            ),
            LayerSpecError::UnknownLayout { tool, layout } => write!(
                f,
                "tool {tool:?} declares layout = {layout:?}, which varve does not \
                 implement. Use \"tarball\" (one .tar.gz per target triple) or \
                 \"raw-per-platform\" (bare per-platform binaries)."
            ),
            LayerSpecError::BadInclude { digest, why } => {
                write!(f, "[[include]] {digest:?} cannot be used: {why}.")
            }
            LayerSpecError::ManyRawPerPlatform { first, second } => write!(
                f,
                "tools {first:?} and {second:?} both declare \
                 layout = \"raw-per-platform\", and the assembler carries only \
                 one (as WSC_VERSION). Depositing would silently drop one of \
                 them. Teach the assembler a general raw-per-platform list \
                 before adding the second."
            ),
            LayerSpecError::RawPerPlatformNotWsc { tool, repo } => write!(
                f,
                "tool {tool:?} from {repo:?} declares \
                 layout = \"raw-per-platform\", but the assembler's only slot \
                 for that layout is hardcoded to fetch `wsc` from \
                 `pulseengine/sigil` — it would emit WSC_VERSION and download \
                 the wrong tool, from the wrong repository, at this tool's \
                 version, and deposit it under the wrong name. Teach the \
                 assembler a general raw-per-platform list before carrying \
                 this."
            ),
            LayerSpecError::VsixForeignOwner { name, repo } => write!(
                f,
                "vsix {name:?} names repo {repo:?}, but the assembler resolves \
                 extension repositories as pulseengine/<name> and would fetch \
                 the wrong release. Either publish it under pulseengine, or \
                 teach the assembler an owner field for extensions."
            ),
            LayerSpecError::RepoNameMismatch {
                name,
                repo,
                basename,
            } => write!(
                f,
                "tool {name:?} names repo {repo:?}, but the assembler takes a \
                 tarball tool's identity from the repository basename — it \
                 would download, name the payload, and default the asset \
                 template as {basename:?}, and {name:?} would mean nothing. A \
                 consumer asking for {name:?} would then find no such tool in \
                 a layer that deposited and verified. Rename the entry to \
                 {basename:?}, or set `binary` if only the executable differs."
            ),
            LayerSpecError::UpstreamSumsNotEncodable { tool, asset } => write!(
                f,
                "tool {tool:?} declares upstream-sums {asset:?}, which the \
                 environment encoding cannot express. Dropping it would not \
                 lose a hint: it is the MECHANISM that vouches for the \
                 release, so the shell assembler would look for a cosign \
                 bundle and an attestation, find neither, and ingest the \
                 payload with no proof at all — while every other field \
                 survives the trip and the entry looks ordinary.\n\n\
                 Deposit this realm with `varve-producer deposit --manifest \
                 layer.toml`, which reads the mechanism directly."
            ),
            LayerSpecError::TwoOptInForms { tool } => write!(
                f,
                "tool {tool:?} carries BOTH `unverified-reason` and \
                 `[tool.unverified]`. Only one can reach the signed layer, and \
                 whichever lost would vanish silently from a document every \
                 consumer reads as the operator's own words. Keep one."
            ),
            LayerSpecError::SplitOptInNotEncodable { tool } => write!(
                f,
                "tool {tool:?} declares a split opt-in (`[tool.unverified]`), and \
                 the env encoding has ONE field for the whole reason.\n\
                 Flattening it would lose which part is the MEASUREMENT — and \
                 that boundary is the only thing standing between a scanner \
                 re-measuring a release and a scanner rewriting the operator's \
                 judgement. Deposit this realm with `varve-producer deposit \
                 --manifest layer.toml`, which reads the parts directly."
            ),
            LayerSpecError::PlatformsNotEncodable { tool, platforms } => write!(
                f,
                "tool {tool:?} is carried for {} only, and the env encoding \
                 has no field for that.\n\
                 Translating it away does not rename anything — it CARRIES THE \
                 TOOL ON PLATFORMS THE REALM EXCLUDED, and those are the \
                 platforms where the payload cannot work. binaryen's macOS \
                 build is the case this exists for: a 1.7 MB stub needing a \
                 dylib a single-executable payload cannot carry, so the layer \
                 would install, verify, and fail at the first exec.\n\
                 Deposit this realm with `varve-producer deposit --manifest \
                 layer.toml`, which reads the restriction directly.",
                platforms.join(", ")
            ),
            LayerSpecError::LayoutNotEncodable { tool, layout } => write!(
                f,
                "tool {tool:?} declares layout {layout:?}, which the environment \
                 encoding cannot express — it has fields for a repository, a \
                 version, a binary, an asset template and a payload version, \
                 and none for a LAYOUT. Translating would emit an ordinary \
                 tarball entry, and the shell assembler would mine the tree for \
                 a binary and destroy it, silently, because every other field \
                 survives the trip.\n\n\
                 Deposit this realm with `varve-producer deposit --manifest \
                 layer.toml`, which reads the layout directly. See `varve docs \
                 sdk`."
            ),
            LayerSpecError::ReleaseNeedsBinaryAndAsset { tool } => write!(
                f,
                "tool {tool:?} sets `release` separately from `version`, which \
                 the environment encoding carries in its FIFTH positional \
                 field — so `binary` and `asset` must be set too, because a \
                 positional field cannot be skipped. Set them explicitly, or \
                 drop `release` if the tag and the version are the same."
            ),
            LayerSpecError::Duplicate { kind, name } => {
                write!(f, "two {kind} entries are both named {name:?}")
            }
            LayerSpecError::UnverifiedWithoutReason { tool } => write!(
                f,
                "tool {tool:?} sets an empty `unverified-reason`. \"We could \
                 not verify this\" must never be the silent path: the reason \
                 is what travels with the bytes into the signed layer, where \
                 every consumer reads it. Say why this is acceptable and what \
                 removes the need, or do not carry the tool."
            ),
            LayerSpecError::ReasonIsAboutAnotherRelease {
                tool,
                pinned,
                reason,
            } => write!(
                f,
                "tool {tool:?} is pinned at {pinned} and its `unverified-reason` \
                 never mentions {pinned}: {reason:?}\n\nA reason for carrying \
                 unverified bytes is a MEASUREMENT of one release — who published \
                 it, what they did not sign, and when that was checked. It does \
                 not carry forward to the next release by itself, and the usual \
                 way to arrive here is a scanner bumping the version while the \
                 justification stayed behind. Re-check {pinned} upstream and say \
                 what you found; if it now publishes sums or provenance, drop \
                 the opt-in instead."
            ),
            LayerSpecError::ConflictingReason {
                repo,
                first,
                second,
            } => write!(
                f,
                "two tools from {repo:?} give different reasons for ingesting \
                 it unverified:\n  {first:?}\n  {second:?}\nThe opt-in is per \
                 RELEASE, not per tool, so one of these would be recorded and \
                 the other silently discarded. Give the repository one reason."
            ),
            LayerSpecError::Empty => write!(
                f,
                "layer.toml declares no [[tool]] and no [[vsix]]: there is \
                 nothing to deposit. A layer with no payloads is signed, \
                 published, and useless."
            ),
        }
    }
}

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

/// What the assembler needs in its environment, derived from the manifest.
///
/// Rendered as `KEY=value` lines so a workflow can append them to `$GITHUB_ENV`
/// — no `eval`, no quoting round-trip, and nothing that would let a manifest
/// value execute.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssemblerEnv {
    pub layer_tools: String,
    pub wsc_version: Option<String>,
    pub vsix_packages: String,
    pub realm: String,
    pub channel: String,
    pub registry: String,
    pub varve_version: String,
    /// `owner/repo=reason` lines for releases ingested with no proof.
    pub unverified_ingest: Vec<(String, String)>,
}

impl AssemblerEnv {
    /// `KEY=value` lines, newline-terminated, in a stable order.
    pub fn render(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!("TARBALL_TOOLS={}\n", self.layer_tools));
        out.push_str(&format!(
            "WSC_VERSION={}\n",
            self.wsc_version.as_deref().unwrap_or("")
        ));
        out.push_str(&format!("VSIX_PACKAGES={}\n", self.vsix_packages));
        out.push_str(&format!("VARVE_REALM={}\n", self.realm));
        out.push_str(&format!("VARVE_CHANNEL={}\n", self.channel));
        out.push_str(&format!("VARVE_REGISTRY={}\n", self.registry));
        out.push_str(&format!("VARVE_VERSION={}\n", self.varve_version));
        // UNVERIFIED_INGEST is LINE-separated, because a reason is prose and
        // any punctuation separator can occur inside it — the assembler
        // documents that choice and the reason it made it. A `KEY=value` line
        // cannot carry newlines, so this uses $GITHUB_ENV's heredoc form.
        //
        // The delimiter is checked against the content rather than assumed: an
        // operator's reason that happened to contain the delimiter would end
        // the block early and inject whatever followed as further environment,
        // which is the shape of an actual injection rather than a typo.
        if !self.unverified_ingest.is_empty() {
            let body: String = self
                .unverified_ingest
                .iter()
                .map(|(repo, why)| format!("{repo}={why}\n"))
                .collect();
            let mut delim = String::from("VARVE_UNVERIFIED_EOF");
            while body.contains(&delim) {
                delim.push('_');
            }
            out.push_str(&format!("UNVERIFIED_INGEST<<{delim}\n{body}{delim}\n"));
        }
        out
    }
}

/// An opt-in with its measurement separated from the judgement around it.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Unverified {
    /// What was probed, when, and what was found. A scanner rewrites THIS and
    /// nothing else, and it is the part the release-naming rule checks.
    pub measured: String,
    /// Why the operator carries it anyway. Never rewritten.
    pub accepted: String,
    /// What would remove the need. Never rewritten.
    pub exit: String,
}

impl ManifestTool {
    /// The opt-in as one prose string, however it was written.
    ///
    /// Everything downstream — the signed layer, `varve inspect`, the ladder's
    /// recorded `proof-asserts` — consumed a single string before this split
    /// existed and still does. Joining here rather than at each reader keeps
    /// ONE answer to "what does this layer say about these bytes", which is the
    /// property the opt-in exists to carry.
    pub fn opt_in_reason(&self) -> Option<String> {
        if let Some(u) = &self.unverified {
            return Some(format!(
                "{} {} {}",
                u.measured.trim(),
                u.accepted.trim(),
                u.exit.trim()
            ));
        }
        self.unverified_reason.clone()
    }

    /// The part the release-naming rule applies to: the MEASUREMENT alone
    /// where the entry is split, and the whole string where it is not.
    pub fn opt_in_measurement(&self) -> Option<&str> {
        if let Some(u) = &self.unverified {
            return Some(u.measured.as_str());
        }
        self.unverified_reason.as_deref()
    }
}

pub fn parse_layer_manifest(text: &str) -> Result<LayerManifest, LayerSpecError> {
    let manifest: LayerManifest =
        toml::from_str(text).map_err(|e| LayerSpecError::Parse(e.to_string()))?;
    check_includes(&manifest.includes)?;
    check_unverified(&manifest.tools)?;
    Ok(manifest)
}

/// Every opt-in in the manifest states a current reason, for the release it
/// is about, and agrees with any other opt-in on the same release.
///
/// HERE, not in `assembler_env`, and that distinction is the whole point. The
/// real deposit path is `varve-producer deposit --manifest layer.toml`, which
/// reads this manifest directly — `deposit.yml` says so in as many words:
/// "there is no env-var adapter". A rule enforced only in the environment
/// encoding would therefore never run on the path that signs a layer. These
/// three refusals sat there until 2026-10-01 and were, for the deposit,
/// decorative.
///
/// Same reasoning as `check_includes` above: at the one place a manifest is
/// read, rather than at the deposit, where the error costs a published layer
/// id that cannot be reused.
fn check_unverified(tools: &[ManifestTool]) -> Result<(), LayerSpecError> {
    let mut seen: Vec<(String, String)> = Vec::new();
    for t in tools {
        // BOTH forms is not a preference to resolve: it is two different
        // answers to "what does this layer say about these bytes", one of
        // which would disappear.
        if t.unverified.is_some() && t.unverified_reason.is_some() {
            return Err(LayerSpecError::TwoOptInForms {
                tool: t.name.clone(),
            });
        }
        let Some(measured) = t.opt_in_measurement() else {
            continue;
        };
        // THE RELEASE-NAMING RULE APPLIES TO THE MEASUREMENT. Where the entry
        // is split, that is `measured` alone — an acceptance reading "the
        // component-model toolchain is unusable without wac" names no release
        // and must not be able to satisfy a check about one.
        let why = measured.trim();
        if why.is_empty() {
            return Err(LayerSpecError::UnverifiedWithoutReason {
                tool: t.name.clone(),
            });
        }
        // The reason must name the release it is about. A justification for
        // unverified bytes is a measurement of ONE release and does not carry
        // forward on its own — but a scanner that bumps `version` has no idea
        // the prose beside it just became false, and the stale excuse would
        // travel into the signed layer where every consumer reads it as
        // current.
        //
        // This is what lets a realm run its scanner unattended: a verified
        // payload bumps and deposits with nobody watching, while an unverified
        // one FAILS CLOSED at exactly the point a person's measurement is the
        // only thing standing behind the bytes. `release` or `version` is
        // accepted, because an entry whose payload version is its own number
        // may sensibly be justified by either, and both move with the tag.
        if !t
            .release
            .iter()
            .chain(std::iter::once(&t.version))
            .any(|v| why.contains(v.as_str()))
        {
            return Err(LayerSpecError::ReasonIsAboutAnotherRelease {
                tool: t.name.clone(),
                pinned: t.release.clone().unwrap_or_else(|| t.version.clone()),
                reason: why.to_string(),
            });
        }
        // The opt-in is per RELEASE, so it is keyed by repository; two tools
        // from one repo must agree about why it is unverified, or one reason
        // would be recorded and the other silently dropped.
        let full = match &t.repo {
            Some(r) => r.clone(),
            None => format!("pulseengine/{}", t.name),
        };
        // Compared on the WHOLE reason, not the measurement: two tools from
        // one release must agree about the acceptance and the exit too, or one
        // operator judgement would be recorded and the other dropped.
        let whole = t.opt_in_reason().unwrap_or_default();
        if let Some((_, prev)) = seen.iter().find(|(r, _)| *r == full) {
            if *prev != whole {
                return Err(LayerSpecError::ConflictingReason {
                    repo: full,
                    first: prev.clone(),
                    second: why.to_string(),
                });
            }
        } else {
            seen.push((full, whole));
        }
    }
    Ok(())
}

/// A composition must name WHOSE layer it composes, by a digest that is one.
///
/// Both refusals are here, at the one place a manifest is read, rather than at
/// the deposit: the deposit signs what it is given, and by then the error costs
/// a published layer id that cannot be reused.
///
/// The realm is the load-bearing field. Without it nothing writes an
/// `include.realm` annotation, so `verify` falls back to the PINNING project's
/// trust root: the layer installs cleanly and fails verification afterwards,
/// with nothing tampered — or, if the two realms happen to share a root,
/// verifies while silently widening trust, which is the thing realms exist to
/// prevent.
fn check_includes(includes: &[ManifestInclude]) -> Result<(), LayerSpecError> {
    for i in includes {
        let hex = i.digest.strip_prefix("sha256:").unwrap_or("");
        if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(LayerSpecError::BadInclude {
                digest: i.digest.clone(),
                why: "a composition names the included layer by the digest of its SIGNED \
                      MANIFEST — `sha256:` and 64 hex characters. A tag or a layer id would \
                      let the composition drift after signing, which is the one thing an \
                      include exists to prevent"
                    .to_string(),
            });
        }
        if i.realm.as_deref().unwrap_or("").trim().is_empty() {
            return Err(LayerSpecError::BadInclude {
                digest: i.digest.clone(),
                why: "no `realm`. Nothing then writes an include.realm annotation, so verify \
                      falls back to the PINNING project's trust root: the layer installs and \
                      fails verification afterwards with nothing tampered, or — if the two \
                      roots happen to match — verifies while widening trust across a realm \
                      boundary. Name the realm whose root verifies the included layer"
                    .to_string(),
            });
        }
    }
    Ok(())
}

/// Reject anything the assembler's encoding cannot carry intact.
///
/// `%` is allowed: it is the asset templates' own metacharacter. `:` and
/// whitespace are the encoding's separators, and an empty value would collapse
/// a field position.
fn encodable(field: &str, value: &str) -> Result<(), LayerSpecError> {
    let unencodable = |why| LayerSpecError::Unencodable {
        field: field.to_string(),
        value: value.to_string(),
        why,
    };
    if value.is_empty() {
        return Err(unencodable("it is empty"));
    }
    if value.contains(':') {
        return Err(unencodable("it contains ':', which separates fields"));
    }
    if value.chars().any(char::is_whitespace) {
        return Err(unencodable(
            "it contains whitespace, which separates entries",
        ));
    }
    Ok(())
}

/// `owner/repo` → (owner, repo), defaulting the owner to `pulseengine`.
fn split_repo(repo: &str, default_name: &str) -> (String, String) {
    match repo.split_once('/') {
        Some((owner, name)) => (owner.to_string(), name.to_string()),
        None => ("pulseengine".to_string(), default_name.to_string()),
    }
}

pub fn assembler_env(m: &LayerManifest) -> Result<AssemblerEnv, LayerSpecError> {
    if m.tools.is_empty() && m.vsix.is_empty() {
        return Err(LayerSpecError::Empty);
    }
    encodable("realm.name", &m.realm.name)?;
    encodable("realm.channel", &m.realm.channel)?;
    encodable("varve.version", &m.varve.version)?;

    let mut unverified: Vec<(String, String)> = Vec::new();
    let mut tarballs: Vec<String> = Vec::new();
    let mut wsc_version: Option<String> = None;
    let mut raw_owner: Option<String> = None;
    let mut seen_tools: BTreeSet<&str> = BTreeSet::new();

    for t in &m.tools {
        encodable("tool.name", &t.name)?;
        encodable("tool.version", &t.version)?;
        // Keyed on the name the payload is DEPOSITED under — what a consumer
        // resolves — rather than on the repository it came from
        // (REQ-PAYLOADID-001). Keying it on the repo meant one repository could
        // contribute at most one payload, which refused
        // zephyrproject-rtos/sdk-ng's 140 host×target toolchains outright and
        // would have refused any monorepo upstream.
        if !seen_tools.insert(t.name.as_str()) {
            return Err(LayerSpecError::Duplicate {
                kind: "tool",
                name: t.name.clone(),
            });
        }
        let layout = match t.layout.as_deref() {
            None => Layout::Tarball,
            Some(s) => Layout::parse(s).ok_or_else(|| LayerSpecError::UnknownLayout {
                tool: t.name.clone(),
                layout: s.to_string(),
            })?,
        };
        // A layout the encoding cannot carry must stop here, not arrive at the
        // shell as something else. `sdk` is the case: the tree IS the payload,
        // and a tarball entry would have a binary extracted from it.
        if layout == Layout::Sdk || layout == Layout::ZephyrModule {
            return Err(LayerSpecError::LayoutNotEncodable {
                tool: t.name.clone(),
                layout: t.layout.clone().unwrap_or_default(),
            });
        }
        // Same rule, and the reason is stronger: `upstream-sums` is not a name
        // but an ingestion MECHANISM (REQ-UPSTREAMSUMS-001). Translating it
        // away leaves an entry that assembles happily with less proof than the
        // realm asked for, which is the failure the ladder exists to prevent.
        if let Some(sums) = &t.upstream_sums {
            return Err(LayerSpecError::UpstreamSumsNotEncodable {
                tool: t.name.clone(),
                asset: sums.clone(),
            });
        }
        // Same rule again, and this one is not about naming at all: a
        // restriction the encoding drops means the tool is assembled for a
        // platform the realm deliberately excluded. For binaryen that is a
        // payload which passes every check and then cannot exec
        // (REQ-TOOLPLAT-001 clause 1).
        // Same rule as `platforms`, `sdk` and `upstream-sums`: a field the
        // encoding cannot carry stops at the boundary. Here what would be lost
        // is the BOUNDARY itself — which part of the reason is the measurement
        // — and that is the only thing keeping a scanner from rewriting the
        // operator's judgement (REQ-PREPARED-001).
        if t.unverified.is_some() {
            return Err(LayerSpecError::SplitOptInNotEncodable {
                tool: t.name.clone(),
            });
        }
        if let Some(only) = &t.platforms {
            return Err(LayerSpecError::PlatformsNotEncodable {
                tool: t.name.clone(),
                platforms: only.clone(),
            });
        }
        // Already VALIDATED at parse time (`check_unverified`); this only
        // collects what the assembler must pass on, deduplicated per repo.
        if let Some(why) = &t.opt_in_reason() {
            let why = why.trim();
            let full = match &t.repo {
                Some(r) => r.clone(),
                None => format!("pulseengine/{}", t.name),
            };
            if !unverified.iter().any(|(r, _)| *r == full) {
                unverified.push((full, why.to_string()));
            }
        }
        let (owner, repo_name) = match &t.repo {
            Some(r) => {
                encodable("tool.repo", r)?;
                split_repo(r, &t.name)
            }
            None => ("pulseengine".to_string(), t.name.clone()),
        };

        if layout == Layout::RawPerPlatform {
            if let Some(first) = &raw_owner {
                return Err(LayerSpecError::ManyRawPerPlatform {
                    first: first.clone(),
                    second: t.name.clone(),
                });
            }
            // The slot is not generic. `wsc` is what the assembler fetches,
            // from `pulseengine/sigil`; anything else silently becomes a
            // request for that tool at this tool's version.
            if t.name != "wsc" || owner != "pulseengine" || repo_name != "sigil" {
                return Err(LayerSpecError::RawPerPlatformNotWsc {
                    tool: t.name.clone(),
                    repo: format!("{owner}/{repo_name}"),
                });
            }
            raw_owner = Some(t.name.clone());
            wsc_version = Some(t.version.clone());
            continue;
        }

        // The assembler does `tool="${f_tool##*/}"` and then uses that name for
        // the payload, the extract directory and the default asset template. A
        // manifest whose `name` disagrees with the repository basename is
        // therefore not translated — it is DISCARDED, and the layer deposits a
        // payload under a name nobody asked for. `raw-per-platform` is exempt
        // because the assembler hardcodes that one pairing (`wsc` from
        // `pulseengine/sigil`) instead of deriving it.
        // The property this protects is real and survives: a payload deposited
        // under a name nobody asked for is a defect — a consumer looking for it
        // finds nothing in a layer that deposited and verified.
        //
        // But the CAUSE is the env encoding, not the manifest. The shell
        // assembler takes a tool's identity from its repository basename and
        // has no field for a deposited name, so it can only ever deposit under
        // the basename or under `binary`. That is the encoding's limit, and
        // pinning `name` to the repository to respect it made one repository
        // able to contribute exactly one payload.
        //
        // So the check moves to where the loss would actually happen — this
        // translation — and states what to do instead, rather than forbidding
        // a manifest the Rust assembler reads correctly.
        if repo_name != t.name && t.binary.is_none() {
            return Err(LayerSpecError::RepoNameMismatch {
                name: t.name.clone(),
                repo: t.repo.clone().unwrap_or_else(|| repo_name.clone()),
                basename: repo_name.clone(),
            });
        }

        // `[owner/]tool:version[:binary[:asset-template]]`. The owner prefix is
        // omitted when it is the default, so a manifest that names no repos
        // produces exactly the list the pre-migration workflow carried.
        // This USED to read `if owner == "pulseengine" { t.name }`, with a
        // comment explaining that `repo_name == t.name` held by the check
        // above, so testing it here would be a condition no input could vary —
        // and cargo-mutants had proved it dead by flipping it and killing
        // nothing.
        //
        // That was true, and it stopped being true the moment a payload's name
        // was allowed to differ from its repository (REQ-PAYLOADID-001). A
        // branch is only dead relative to an invariant, and removing the
        // invariant brings it back to life: with the shortcut left in,
        // `name = "with-device"` from `pulseengine/jess` emitted
        // `with-device:v0.7.2:…`, and the shell would have fetched
        // `pulseengine/with-device` — a repository that does not exist.
        //
        // So the bare form is now used only when the name really is the
        // repository, which is what made it safe in the first place.
        let head = if owner == "pulseengine" && repo_name == t.name {
            t.name.clone()
        } else {
            format!("{owner}/{repo_name}")
        };
        // The tag to FETCH; `version` is what the payload is. They differ for
        // a hub repo, and the entry carries both — the fifth positional field
        // is the payload's own version.
        let fetch_tag = t.release.as_deref().unwrap_or(&t.version);
        let mut entry = format!("{head}:{fetch_tag}");
        // A template cannot be given without a binary: they are positional.
        match (&t.binary, &t.asset) {
            (None, None) => {}
            (Some(b), None) => {
                encodable("tool.binary", b)?;
                entry.push(':');
                entry.push_str(b);
            }
            (b, Some(a)) => {
                encodable("tool.asset", a)?;
                let bin = b.clone().unwrap_or_else(|| t.name.clone());
                encodable("tool.binary", &bin)?;
                entry.push(':');
                entry.push_str(&bin);
                entry.push(':');
                entry.push_str(a);
            }
        }
        // The fifth positional field: the payload's OWN version, emitted only
        // when it differs from the tag. Omitted otherwise so every existing
        // entry translates to exactly the string it did before.
        if t.release.is_some() {
            // Positional, so the earlier optional fields must be present.
            if t.binary.is_none() || t.asset.is_none() {
                return Err(LayerSpecError::ReleaseNeedsBinaryAndAsset {
                    tool: t.name.clone(),
                });
            }
            entry.push(':');
            entry.push_str(t.version.trim_start_matches('v'));
        }
        tarballs.push(entry);
    }

    let mut vsix_entries: Vec<String> = Vec::new();
    let mut seen_vsix: BTreeSet<&str> = BTreeSet::new();
    for v in &m.vsix {
        encodable("vsix.name", &v.name)?;
        encodable("vsix.version", &v.version)?;
        encodable("vsix.asset", &v.asset)?;
        if !seen_vsix.insert(v.name.as_str()) {
            return Err(LayerSpecError::Duplicate {
                kind: "vsix",
                name: v.name.clone(),
            });
        }
        // The assembler builds `pulseengine/<repo_name>` itself, so a foreign
        // owner cannot be expressed — and quietly dropping the owner would
        // fetch a DIFFERENT repository's release of the same name.
        let repo_name = match &v.repo {
            Some(r) => {
                encodable("vsix.repo", r)?;
                let (owner, name) = split_repo(r, &v.name);
                if owner != "pulseengine" {
                    return Err(LayerSpecError::VsixForeignOwner {
                        name: v.name.clone(),
                        repo: r.clone(),
                    });
                }
                name
            }
            None => v.name.clone(),
        };
        vsix_entries.push(format!("{repo_name}:{}:{}:{}", v.version, v.name, v.asset));
    }

    Ok(AssemblerEnv {
        layer_tools: tarballs.join(" "),
        wsc_version,
        vsix_packages: vsix_entries.join(" "),
        realm: m.realm.name.clone(),
        channel: m.realm.channel.clone(),
        registry: m.realm.registry.clone(),
        varve_version: m.varve.version.clone(),
        unverified_ingest: unverified,
    })
}

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

    /// The manifest `pulseengine-layers` actually carries, trimmed to the
    /// shapes that differ from one another. Kept as one literal so the tests
    /// exercise a document that could really be committed, not a fragment.
    const REAL: &str = r#"
[varve]
version = "v0.28.0"

[realm]
name    = "pulseengine"
channel = "rolling"
registry = "oci://ghcr.io/pulseengine/layers"

[[tool]]
name    = "rivet"
version = "v0.34.0"

[[tool]]
name    = "kiln"
version = "v0.4.4"
binary  = "kilnd"

[[tool]]
name    = "wsc"
repo    = "pulseengine/sigil"
version = "v0.11.0"
layout  = "raw-per-platform"

[[vsix]]
name    = "rivet-sdlc"
repo    = "pulseengine/rivet"
version = "v0.34.0"
asset   = "rivet-sdlc-%V.vsix"

[[vsix]]
name    = "spar-aadl"
repo    = "pulseengine/spar"
version = "v0.40.0"
asset   = "spar-aadl-%P-%V.vsix"
"#;

    fn env_of(text: &str) -> AssemblerEnv {
        assembler_env(&parse_layer_manifest(text).expect("parses")).expect("converts")
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_plain_tool_becomes_name_and_version() {
        assert!(env_of(REAL).layer_tools.starts_with("rivet:v0.34.0 "));
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_differing_binary_name_is_carried_as_the_third_field() {
        assert!(env_of(REAL).layer_tools.contains("kiln:v0.4.4:kilnd"));
    }

    /// The one raw-per-platform tool leaves TARBALL_TOOLS entirely — putting it
    /// there would have the assembler look for a tarball that does not exist.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn the_raw_per_platform_tool_becomes_wsc_version_and_not_a_tarball() {
        let e = env_of(REAL);
        assert_eq!(e.wsc_version.as_deref(), Some("v0.11.0"));
        assert!(!e.layer_tools.contains("wsc"), "{}", e.layer_tools);
        assert!(!e.layer_tools.contains("sigil"), "{}", e.layer_tools);
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn vsix_entries_drop_the_default_owner_the_assembler_re_adds() {
        let e = env_of(REAL);
        assert_eq!(
            e.vsix_packages,
            "rivet:v0.34.0:rivet-sdlc:rivet-sdlc-%V.vsix \
             spar:v0.40.0:spar-aadl:spar-aadl-%P-%V.vsix"
        );
    }

    /// The manifest is the only place a version is written, so a typo there
    /// must not be able to leave the real key at its previous value.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_mistyped_key_is_refused_rather_than_ignored() {
        let text = REAL.replace("name    = \"rivet\"", "nmae    = \"rivet\"");
        let err = parse_layer_manifest(&text).unwrap_err();
        assert!(
            matches!(&err, LayerSpecError::Parse(m) if m.contains("nmae")),
            "{err}"
        );
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn an_unknown_layout_is_refused_and_names_the_two_that_work() {
        let text = REAL.replace("raw-per-platform", "zipfile");
        let err = assembler_env(&parse_layer_manifest(&text).unwrap()).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("zipfile") && msg.contains("raw-per-platform"),
            "{msg}"
        );
    }

    /// The assembler has exactly one slot. A second raw-per-platform tool would
    /// otherwise be dropped from a layer that still signs and publishes.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_second_raw_per_platform_tool_is_refused_rather_than_dropped() {
        let text = format!(
            "{REAL}\n[[tool]]\nname = \"other\"\nversion = \"v1.0.0\"\nlayout = \"raw-per-platform\"\n"
        );
        let err = assembler_env(&parse_layer_manifest(&text).unwrap()).unwrap_err();
        assert_eq!(
            err,
            LayerSpecError::ManyRawPerPlatform {
                first: "wsc".into(),
                second: "other".into()
            }
        );
    }

    /// Found by actually trying to assemble a bytecodealliance manifest: the
    /// assembler's one raw-per-platform slot fetches `wsc` from
    /// `pulseengine/sigil`, so putting any other tool in it emitted
    /// WSC_VERSION = that tool's version and would have downloaded wsc at
    /// v0.10.1 — wrong tool, wrong repo, wrong version, deposited under the
    /// wrong name, silently.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_raw_per_platform_tool_that_is_not_wsc_is_refused() {
        let text = format!(
            "{REAL}\n[[tool]]\nname = \"wac\"\nrepo = \"bytecodealliance/wac\"\n\
             version = \"v0.10.1\"\nlayout = \"raw-per-platform\"\n"
        );
        // The FIRST raw tool in REAL is wsc, so this trips the many-slot rule;
        // remove wsc to isolate the identity rule.
        let only = text.replace(
            "[[tool]]\nname    = \"wsc\"\nrepo    = \"pulseengine/sigil\"\nversion = \"v0.11.0\"\nlayout  = \"raw-per-platform\"\n",
            "",
        );
        assert!(!only.contains("wsc"), "the wsc block must be gone: {only}");
        let err = assembler_env(&parse_layer_manifest(&only).unwrap()).unwrap_err();
        assert_eq!(
            err,
            LayerSpecError::RawPerPlatformNotWsc {
                tool: "wac".into(),
                repo: "bytecodealliance/wac".into()
            },
            "{err}"
        );
        assert!(err.to_string().contains("wrong repository"), "{err}");
    }

    /// One wrong field is enough. The slot fetches `wsc` from
    /// `pulseengine/sigil`, so a tool that matches two of those three and
    /// misses the third still becomes a request for something else — and a
    /// test that only varies all three at once cannot tell the guard from a
    /// much weaker one. cargo-mutants proved that by narrowing it.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn the_wsc_slot_rejects_a_tool_that_differs_in_any_single_field() {
        let base = REAL.replace(
            "[[tool]]\nname    = \"wsc\"\nrepo    = \"pulseengine/sigil\"\nversion = \"v0.11.0\"\nlayout  = \"raw-per-platform\"\n",
            "",
        );
        for (name, repo, what) in [
            ("wsc", "acme/sigil", "a different OWNER"),
            ("wsc", "pulseengine/other", "a different REPOSITORY"),
            ("other", "pulseengine/sigil", "a different TOOL NAME"),
        ] {
            let text = format!(
                "{base}\n[[tool]]\nname = \"{name}\"\nrepo = \"{repo}\"\n\
                 version = \"v1.0.0\"\nlayout = \"raw-per-platform\"\n"
            );
            let err = assembler_env(&parse_layer_manifest(&text).unwrap()).expect_err(what);
            assert!(
                matches!(err, LayerSpecError::RawPerPlatformNotWsc { .. }),
                "{what} ({name} from {repo}) was not refused as a wsc-slot \
                 mismatch: {err:?}"
            );
        }
    }

    /// Dropping the owner would fetch pulseengine's release of the same name —
    /// a different repository's bytes, deposited under a good signature.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_foreign_owner_on_an_extension_is_refused() {
        let text = REAL.replace(
            "repo    = \"pulseengine/rivet\"",
            "repo    = \"acme/rivet\"",
        );
        let err = assembler_env(&parse_layer_manifest(&text).unwrap()).unwrap_err();
        assert_eq!(
            err,
            LayerSpecError::VsixForeignOwner {
                name: "rivet-sdlc".into(),
                repo: "acme/rivet".into()
            }
        );
    }

    /// The encoding's separators cannot appear in the data. Both of these would
    /// be split by the shell rather than reported.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_value_carrying_a_separator_is_refused() {
        for (bad, why) in [("v1.0 rc1", "whitespace"), ("v1.0:rc1", "':'")] {
            let text = REAL.replace("v0.34.0\"\n\n[[tool]]", &format!("{bad}\"\n\n[[tool]]"));
            let err = assembler_env(&parse_layer_manifest(&text).unwrap()).unwrap_err();
            let msg = err.to_string();
            assert!(msg.contains(why), "{bad}: {msg}");
        }
    }

    /// `tarball` is the default, but the docs say you may write it, so writing
    /// it must not be refused. cargo-mutants found this by deleting the match
    /// arm: every test used the default or `raw-per-platform`, so nothing
    /// noticed that spelling it out stopped working.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn an_explicit_tarball_layout_means_the_same_as_omitting_it() {
        let explicit = REAL.replace(
            "name    = \"rivet\"\nversion = \"v0.34.0\"",
            "name    = \"rivet\"\nversion = \"v0.34.0\"\nlayout  = \"tarball\"",
        );
        assert_ne!(explicit, REAL, "the fixture substitution must apply");
        assert_eq!(env_of(&explicit).layer_tools, env_of(REAL).layer_tools);
    }

    /// A foreign OWNER is fine — `bytecodealliance/wasm-tools` is the whole
    /// point of the second realm — as long as the basename still identifies
    /// the tool.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_foreign_owner_is_carried_as_a_qualified_repository() {
        let text = format!(
            "{REAL}\n[[tool]]\nname = \"wasm-tools\"\nrepo = \"bytecodealliance/wasm-tools\"\nversion = \"v1.257.1\"\n"
        );
        assert!(
            env_of(&text)
                .layer_tools
                .contains("bytecodealliance/wasm-tools:v1.257.1"),
            "{}",
            env_of(&text).layer_tools
        );
    }

    /// The assembler names the payload from the repository basename, so a
    /// disagreeing `name` is discarded rather than translated — the layer would
    /// deposit and verify while carrying a tool under a name nobody asked for.
    /// cargo-mutants found this too: no fixture had a tarball tool whose repo
    /// basename differed, because the only differing repo was exempt.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_tool_whose_repo_basename_disagrees_with_its_name_is_refused() {
        let text = format!(
            "{REAL}\n[[tool]]\nname = \"wsc2\"\nrepo = \"pulseengine/sigil\"\nversion = \"v0.11.0\"\n"
        );
        let err = assembler_env(&parse_layer_manifest(&text).unwrap()).unwrap_err();
        assert_eq!(
            err,
            LayerSpecError::RepoNameMismatch {
                name: "wsc2".into(),
                repo: "pulseengine/sigil".into(),
                basename: "sigil".into(),
            },
            "{err}"
        );
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn two_tools_of_one_name_are_refused() {
        let text = format!("{REAL}\n[[tool]]\nname = \"rivet\"\nversion = \"v0.1.0\"\n");
        let err = assembler_env(&parse_layer_manifest(&text).unwrap()).unwrap_err();
        assert_eq!(
            err,
            LayerSpecError::Duplicate {
                kind: "tool",
                name: "rivet".into()
            }
        );
    }

    /// A release offering neither mechanism can be carried only with a stated
    /// reason, and the reason is signed into the layer where every consumer
    /// reads it. It belongs in the manifest beside the tool it excuses, not in
    /// a workflow variable — split definitions are how versions drift (#106).
    // rivet: verifies REQ-LAYERADAPT-001
    // rivet: verifies REQ-INGEST-001
    #[test]
    fn an_unverified_reason_reaches_the_assembler_intact() {
        let text = format!(
            "{REAL}\n[[tool]]\nname = \"wac\"\nrepo = \"bytecodealliance/wac\"\n\
             version = \"v0.10.1\"\nunverified-reason = \"v0.10.1 publishes no sums, \
             no cosign bundle and no attestation; tracked upstream, re-check each cut\"\n"
        );
        let env = env_of(&text);
        assert_eq!(env.unverified_ingest.len(), 1);
        assert_eq!(env.unverified_ingest[0].0, "bytecodealliance/wac");
        assert!(env.unverified_ingest[0].1.contains("re-check each cut"));

        // Rendered in $GITHUB_ENV's heredoc form, because the value is
        // line-separated and a KEY=value line cannot carry newlines.
        let r = env.render();
        assert!(r.contains("UNVERIFIED_INGEST<<"), "{r}");
        assert!(
            r.contains("bytecodealliance/wac=v0.10.1 publishes no sums"),
            "{r}"
        );
    }

    /// A reason containing the delimiter would end the heredoc early and let
    /// whatever followed be read as further environment. That is an injection,
    /// not a typo, so the delimiter is chosen against the content.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_reason_containing_the_delimiter_cannot_close_the_block_early() {
        let text = format!(
            "{REAL}\n[[tool]]\nname = \"wac\"\nrepo = \"bytecodealliance/wac\"\n\
             version = \"v0.10.1\"\nunverified-reason = \"v0.10.1 VARVE_UNVERIFIED_EOF\\nPATH=/evil\"\n"
        );
        let r = env_of(&text).render();
        let opened = r
            .lines()
            .find(|l| l.starts_with("UNVERIFIED_INGEST<<"))
            .expect("heredoc opened");
        let delim = opened.trim_start_matches("UNVERIFIED_INGEST<<");
        // The delimiter must not appear inside the body it delimits.
        let body = r.split(&format!("<<{delim}\n")).nth(1).expect("body");
        let body = body.split(&format!("\n{delim}")).next().expect("closes");
        assert!(
            !body.contains(delim),
            "delimiter occurs inside its own body"
        );
        assert!(
            body.contains("PATH=/evil"),
            "the reason must survive verbatim"
        );
    }

    /// A scanner bumping the version must not carry the old justification
    /// with it.
    ///
    /// THE REAL CASE, 2026-10-01. `pulseengine-wasm` pins
    /// `bytecodealliance/wac` at v0.11.0 with the reason "wac v0.11.0
    /// publishes neither cosign-signed sums nor build provenance (measured
    /// 2026-09-18)". Upstream cut v0.12.0. Turning on that realm's 15-minute
    /// scanner would have rewritten `version` and left the prose untouched, so
    /// a signed layer would have carried v0.12.0 bytes beside a measurement of
    /// v0.11.0 — a false claim, signed, that every consumer reads as current.
    ///
    /// This is also what makes an unattended scanner safe to run: a verified
    /// payload bumps and deposits with nobody watching, and an unverified one
    /// stops here, at the one point where a person's measurement is the only
    /// thing standing behind the bytes.
    // rivet: verifies REQ-LAYERADAPT-001
    // rivet: verifies REQ-INGEST-001
    #[test]
    fn a_reason_measuring_another_release_is_refused() {
        let reason = "wac v0.11.0 publishes neither cosign-signed sums nor build \
                      provenance (measured 2026-09-18)";
        let bumped = format!(
            "{REAL}\n[[tool]]\nname = \"wac\"\nrepo = \"bytecodealliance/wac\"\n\
             version = \"v0.12.0\"\nunverified-reason = \"{reason}\"\n"
        );
        // At PARSE, not at `assembler_env`: the real deposit reads the
        // manifest directly and never builds an environment, so a refusal
        // that lived only in the encoding would not reach it.
        let err = parse_layer_manifest(&bumped).unwrap_err();
        assert_eq!(
            err,
            LayerSpecError::ReasonIsAboutAnotherRelease {
                tool: "wac".into(),
                pinned: "v0.12.0".into(),
                reason: reason.to_string(),
            },
            "{err}"
        );
        // The message has to say which release, or the operator has to diff
        // the manifest against the prose to find out what went stale.
        assert!(format!("{err}").contains("v0.12.0"), "{err}");

        // Re-measured, it assembles — the gate asks for a current statement,
        // not for the opt-in to be abandoned.
        let remeasured = bumped.replace("v0.11.0 publishes", "v0.12.0 publishes");
        parse_layer_manifest(&remeasured).expect("a current measurement parses");
        assert_eq!(env_of(&remeasured).unverified_ingest.len(), 1);
    }

    /// An entry whose payload version is its own number is justified by either
    /// number, because both move when the tag does and a reason may sensibly
    /// name whichever the measurer looked at.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_reason_may_name_the_release_or_the_version() {
        for names in ["r2026.1", "v9.9.9"] {
            let text = format!(
                "{REAL}\n[[tool]]\nname = \"wac\"\nrepo = \"bytecodealliance/wac\"\n\
                 version = \"v9.9.9\"\nrelease = \"r2026.1\"\nbinary = \"wac\"\n\
                 asset = \"wac-%T\"\nunverified-reason = \"{names}: nothing signed\"\n"
            );
            assert_eq!(
                env_of(&text).unverified_ingest.len(),
                1,
                "a reason naming {names} was refused"
            );
        }
    }

    /// "We could not verify this" must never be the silent path.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn an_empty_unverified_reason_is_refused() {
        for bad in ["\"\"", "\"   \""] {
            let text = format!(
                "{REAL}\n[[tool]]\nname = \"wac\"\nversion = \"v1\"\nunverified-reason = {bad}\n"
            );
            let err = parse_layer_manifest(&text).unwrap_err();
            assert_eq!(
                err,
                LayerSpecError::UnverifiedWithoutReason { tool: "wac".into() },
                "{bad}"
            );
        }
    }

    /// The opt-in is per RELEASE. Two tools from one repository giving
    /// different reasons would record one and drop the other.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn two_tools_from_one_repo_must_agree_on_the_reason() {
        // `wsc` already comes from pulseengine/sigil as a raw-per-platform
        // tool, which is exempt from the basename rule; a tarball tool named
        // `sigil` from the same repo is the reachable way two payloads share
        // one release. Two tarball tools cannot, by construction.
        let text = REAL.replace(
            "layout  = \"raw-per-platform\"",
            "layout  = \"raw-per-platform\"\nunverified-reason = \"v0.11.0 first\"",
        ) + "\n[[tool]]\nname = \"sigil\"\nrepo = \"pulseengine/sigil\"\nversion = \"v0.11.0\"\n\
             unverified-reason = \"v0.11.0 second\"\n";
        let err = parse_layer_manifest(&text).unwrap_err();
        assert!(
            matches!(err, LayerSpecError::ConflictingReason { .. }),
            "{err:?}"
        );
        // Agreeing is fine, and recorded once.
        let ok = text.replace("\"v0.11.0 second\"", "\"v0.11.0 first\"");
        assert_eq!(env_of(&ok).unverified_ingest.len(), 1);
    }

    /// A manifest with nothing unverified must not emit the variable at all —
    /// an empty opt-in list and an absent one are different statements.
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_manifest_with_nothing_unverified_emits_no_opt_in() {
        let r = env_of(REAL).render();
        assert!(!r.contains("UNVERIFIED_INGEST"), "{r}");
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_manifest_with_no_payloads_is_refused() {
        let text = "[varve]\nversion = \"v0.28.0\"\n\n[realm]\nname = \"p\"\nchannel = \"rolling\"\nregistry = \"oci://x\"\n";
        assert_eq!(
            assembler_env(&parse_layer_manifest(text).unwrap()).unwrap_err(),
            LayerSpecError::Empty
        );
    }

    /// VSIX_PACKAGES must be SET-but-empty rather than absent: the assembler
    /// distinguishes "this layer carries no extensions" from "someone forgot".
    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn a_layer_with_no_extensions_still_sets_the_variable() {
        let text = REAL
            .split("[[vsix]]")
            .next()
            .expect("has a tools section")
            .to_string();
        let rendered = env_of(&text).render();
        assert!(rendered.contains("\nVSIX_PACKAGES=\n"), "{rendered}");
    }

    // rivet: verifies REQ-LAYERADAPT-001
    #[test]
    fn render_emits_one_key_per_line_in_a_stable_order() {
        let rendered = env_of(REAL).render();
        let keys: Vec<&str> = rendered
            .lines()
            .map(|l| l.split('=').next().unwrap_or(""))
            .collect();
        assert_eq!(
            keys,
            [
                "TARBALL_TOOLS",
                "WSC_VERSION",
                "VSIX_PACKAGES",
                "VARVE_REALM",
                "VARVE_CHANNEL",
                "VARVE_REGISTRY",
                "VARVE_VERSION"
            ]
        );
    }

    /// A composition must say WHOSE layer it composes.
    // rivet: verifies REQ-COMPOSE-001
    #[test]
    fn an_include_without_a_realm_is_refused_where_it_is_written() {
        let text = format!(
            "{}\n[[include]]\ndigest = \"sha256:{}\"\n",
            REAL,
            "a".repeat(64)
        );
        let e = parse_layer_manifest(&text).expect_err("must refuse");
        let msg = e.to_string();
        assert!(matches!(e, LayerSpecError::BadInclude { .. }), "{e:?}");
        assert!(msg.contains("realm"), "{msg}");
        // The reason a reader needs is WHY, not that a field is absent.
        assert!(
            msg.contains("widening trust") || msg.contains("widening"),
            "{msg}"
        );
    }

    /// A tag or a layer id would let the composition drift after signing.
    // rivet: verifies REQ-COMPOSE-001
    #[test]
    fn an_include_must_name_a_manifest_digest_not_a_version() {
        for bad in ["2026.09.4", "v0.36.0", "sha256:abc", "sha256:", ""] {
            let text = format!("{REAL}\n[[include]]\ndigest = \"{bad}\"\nrealm = \"r\"\n");
            let e = parse_layer_manifest(&text)
                .expect_err(&format!("{bad:?} must be refused as a digest"));
            assert!(
                matches!(e, LayerSpecError::BadInclude { .. }),
                "{bad:?}: {e:?}"
            );
        }
    }

    /// The shape a realm actually writes.
    // rivet: verifies REQ-COMPOSE-001
    #[test]
    fn a_well_formed_include_parses_with_its_realm_and_layer() {
        let text = format!(
            "{}\n[[include]]\ndigest = \"sha256:{}\"\nrealm = \"pulseengine\"\nlayer = \"2026.09.4\"\n",
            REAL,
            "b".repeat(64)
        );
        let m = parse_layer_manifest(&text).expect("parses");
        assert_eq!(m.includes.len(), 1);
        assert_eq!(m.includes[0].realm.as_deref(), Some("pulseengine"));
        assert_eq!(m.includes[0].layer.as_deref(), Some("2026.09.4"));
    }
}

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

    fn env_of(text: &str) -> Result<AssemblerEnv, LayerSpecError> {
        assembler_env(&parse_layer_manifest(text).expect("parses"))
    }

    const HEAD: &str = "[varve]\nversion = \"v0.33.0\"\n[realm]\nname=\"pulseengine\"\n\
channel=\"rolling\"\nregistry=\"oci://x/y\"\n";

    /// The wall this removes. sdk-ng publishes 140 host×target toolchains and
    /// any monorepo upstream has the same shape; identity keyed on the
    /// repository allowed each repo exactly one payload.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn one_repository_can_contribute_more_than_one_payload() {
        let env = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"with-device\"\nrepo=\"pulseengine/jess\"\n\
binary=\"with-device\"\nversion=\"v0.7.2\"\nasset=\"with-device-0.2.2-%T.tar.gz\"\n\
\n[[tool]]\nname=\"bench-report\"\nrepo=\"pulseengine/jess\"\nbinary=\"bench-report\"\n\
version=\"v0.7.2\"\nasset=\"bench-report-0.1.0-%T.tar.gz\"\n"
        ))
        .expect("two payloads from one repository must be expressible");
        assert_eq!(env.layer_tools.split(' ').count(), 2, "{}", env.layer_tools);
    }

    /// The repository must survive translation. The old code shortened the
    /// entry to the bare NAME whenever the owner was the default — safe only
    /// while name == repo basename, which this requirement stops enforcing.
    /// With the shortcut left in, `with-device` from `pulseengine/jess` emitted
    /// `with-device:…` and the shell would fetch `pulseengine/with-device`.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn a_payload_named_differently_from_its_repo_still_names_its_repo() {
        let env = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"with-device\"\nrepo=\"pulseengine/jess\"\n\
binary=\"with-device\"\nversion=\"v0.7.2\"\nasset=\"w-%T.tar.gz\"\n"
        ))
        .expect("parses");
        assert!(
            env.layer_tools.starts_with("pulseengine/jess:"),
            "the repository was lost: {}",
            env.layer_tools
        );
    }

    /// A hub repository tags a release and ships a tool at a DIFFERENT
    /// version. `pulseengine/jess` tags v0.7.2 and ships with-device 0.2.2.
    /// Without `release`, the manifest could only sign a version the binary
    /// contradicts or name a tag that does not exist — and the env encoding
    /// could already express it, so porting a realm to layer.toml LOST the
    /// payload entirely. Found by the agent porting pulseengine-layers.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn a_hub_repos_tag_and_its_payloads_version_can_differ() {
        let env = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"with-device\"\nrepo=\"pulseengine/jess\"\n\
binary=\"with-device\"\nrelease=\"v0.7.2\"\nversion=\"0.2.2\"\n\
asset=\"with-device-%V-%T.tar.gz\"\n"
        ))
        .expect("a hub repo's payload must be expressible");
        assert_eq!(
            env.layer_tools, "pulseengine/jess:v0.7.2:with-device:with-device-%V-%T.tar.gz:0.2.2",
            "the tag is fetched, the payload version is recorded"
        );
    }

    /// The fifth field is POSITIONAL, so it cannot be carried past an absent
    /// binary or template — that would shift the template into the binary slot
    /// and fetch nonsense.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn a_payload_version_cannot_skip_the_positional_fields_before_it() {
        // `name` matches the basename here, so the name guard cannot fire and
        // this isolates the positional one.
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"jess\"\nrepo=\"pulseengine/jess\"\n\
release=\"v0.7.2\"\nversion=\"0.2.2\"\n"
        ))
        .expect_err("must refuse");
        assert!(
            matches!(e, LayerSpecError::ReleaseNeedsBinaryAndAsset { .. }),
            "{e:?}"
        );
        assert!(e.to_string().contains("positional"), "{e}");

        // EITHER one missing is enough, and this is the case that actually
        // corrupts: with `binary` set and `asset` absent, appending the payload
        // version would put it in the TEMPLATE slot, and the assembler would
        // look for an asset literally named "0.2.2".
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"jess\"\nrepo=\"pulseengine/jess\"\n\
binary=\"with-device\"\nrelease=\"v0.7.2\"\nversion=\"0.2.2\"\n"
        ))
        .expect_err("binary without asset must still refuse");
        assert!(
            matches!(e, LayerSpecError::ReleaseNeedsBinaryAndAsset { .. }),
            "{e:?}"
        );

        // ...and the mirror case.
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"jess\"\nrepo=\"pulseengine/jess\"\n\
asset=\"a-%T.tar.gz\"\nrelease=\"v0.7.2\"\nversion=\"0.2.2\"\n"
        ))
        .expect_err("asset without binary must still refuse");
        assert!(
            matches!(e, LayerSpecError::ReleaseNeedsBinaryAndAsset { .. }),
            "{e:?}"
        );
    }

    /// Clause 5. Every existing entry translates to exactly what it did before.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn an_ordinary_entry_is_unchanged() {
        let env = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"rivet\"\nversion=\"v0.35.0\"\n"
        ))
        .expect("parses");
        assert_eq!(env.layer_tools, "rivet:v0.35.0");
    }

    /// Clause 4. The property the old guard protected survives: a payload that
    /// would land under a name nobody asked for is still refused — a consumer
    /// looking for it finds nothing in a layer that deposited and verified.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn a_name_the_encoding_would_silently_discard_is_still_refused() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"zephyr-sdk\"\nrepo=\"zephyrproject-rtos/sdk-ng\"\n\
version=\"v1.0.1\"\n"
        ))
        .expect_err("no binary means the shell deposits under the basename");
        assert!(
            matches!(e, LayerSpecError::RepoNameMismatch { .. }),
            "{e:?}"
        );
    }

    /// Two payloads that would land under ONE deposited name is still a
    /// collision — the check moved, it did not go away.
    // rivet: verifies REQ-PAYLOADID-001
    #[test]
    fn two_payloads_under_one_deposited_name_still_collide() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"dup\"\nrepo=\"pulseengine/a\"\nbinary=\"dup\"\n\
version=\"v1\"\nasset=\"a-%T.tar.gz\"\n\n[[tool]]\nname=\"dup\"\nrepo=\"pulseengine/b\"\n\
binary=\"dup\"\nversion=\"v2\"\nasset=\"b-%T.tar.gz\"\n"
        ))
        .expect_err("must refuse");
        assert!(matches!(e, LayerSpecError::Duplicate { .. }), "{e:?}");
    }

    /// Every `DocsFormat` helper, for every variant. These survived mutation
    /// as `true`, `None`, `Some("")` and `"xyzzy"` because nothing asserted
    /// them directly — they were only ever exercised through code that did not
    /// care which answer came back.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn every_format_states_what_it_is() {
        // is_tree decides whether there is an inside to look in at all.
        assert!(DocsFormat::Html.is_tree());
        assert!(DocsFormat::Rustdoc.is_tree());
        assert!(!DocsFormat::Pdf.is_tree());
        assert!(!DocsFormat::Markdown.is_tree());
        assert!(!DocsFormat::Reqif.is_tree());

        // A tree becomes a directory, so it names no extension; a single file
        // must name one, or the export has nothing to call it.
        assert_eq!(DocsFormat::Html.file_extension(), None);
        assert_eq!(DocsFormat::Rustdoc.file_extension(), None);
        assert_eq!(DocsFormat::Pdf.file_extension(), Some("pdf"));
        assert_eq!(DocsFormat::Markdown.file_extension(), Some("md"));
        assert_eq!(DocsFormat::Reqif.file_extension(), Some("reqif"));

        // The word a human filters on, and what the signed annotation holds.
        assert_eq!(DocsFormat::Html.as_str(), "html");
        assert_eq!(DocsFormat::Rustdoc.as_str(), "rustdoc");
        assert_eq!(DocsFormat::Pdf.as_str(), "pdf");
        assert_eq!(DocsFormat::Markdown.as_str(), "markdown");
        assert_eq!(DocsFormat::Reqif.as_str(), "reqif");

        // A tree never names an extension and a single file always does —
        // stated as the invariant, so a new variant cannot half-answer.
        for f in [
            DocsFormat::Html,
            DocsFormat::Rustdoc,
            DocsFormat::Pdf,
            DocsFormat::Markdown,
            DocsFormat::Reqif,
        ] {
            assert_eq!(
                f.is_tree(),
                f.file_extension().is_none(),
                "{} disagrees with itself about being a tree",
                f.as_str()
            );
            assert!(!f.as_str().is_empty());
        }
    }

    /// The staging check, as a decision rather than a branch inside an I/O
    /// loop. Both directions, because a mutant that inverts it must fail here.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_declared_entry_must_be_in_the_payload() {
        let has: Vec<String> = ["./index.html", "./sub/index.html"]
            .iter()
            .map(|s| s.to_string())
            .collect();

        assert_eq!(check_docs_entry(&has, Some("index.html"), true), Ok(()));

        let e = check_docs_entry(&has, Some("missing.html"), true)
            .expect_err("a declared entry that is absent must be refused");
        assert_eq!(e.entry, "missing.html");
        assert_eq!(e.members, 2);
        assert!(!e.saw.is_empty(), "the refusal must show what IS there");

        // Nothing claimed, nothing to break.
        assert_eq!(check_docs_entry(&has, None, true), Ok(()));
        // A single file has no inside, so an entry on one is not checked here.
        assert_eq!(check_docs_entry(&has, Some("whatever"), false), Ok(()));
        // A namesake one directory down does NOT satisfy a root entry —
        // but only where that directory is CONTENT. With two top-level
        // directories nothing is stripped, so neither `a/` nor `b/` can
        // stand in for the root.
        let two_tops: Vec<String> = ["a/index.html", "b/index.html"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert!(check_docs_entry(&two_tops, Some("index.html"), true).is_err());

        // With a SINGLE top-level directory the rule is the opposite, and
        // deliberately so: that is packaging, not content, and upstreams wrap
        // constantly. Asserted here so the two cases cannot be conflated.
        let wrapped: Vec<String> = vec!["book-1.0/index.html".to_string()];
        assert_eq!(check_docs_entry(&wrapped, Some("index.html"), true), Ok(()));
    }

    /// The exactness matters and a tail match would not give it. varve's own
    /// traceability bundle carries `eu-ai-act/index.html` and
    /// `artifacts/index.html`, so `ends_with("/index.html")` accepts a payload
    /// whose declared ROOT entry is missing — reporting success while the
    /// reader's first link 404s.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_subdirectory_namesake_does_not_satisfy_a_root_entry() {
        let members: Vec<String> = ["./", "./eu-ai-act/index.html", "./artifacts/index.html"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert!(
            !docs_entry_present(&members, "index.html"),
            "a namesake in a subdirectory is not the declared root entry"
        );
        assert!(docs_entry_present(&members, "eu-ai-act/index.html"));
    }

    /// The real bundle: many top-level entries, so no wrapper, and the root
    /// `index.html` is genuinely there.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn the_real_traceability_layout_resolves_its_root_entry() {
        let members: Vec<String> = [
            "./",
            "./_assets/styles.css",
            "./eu-ai-act/index.html",
            "./artifacts/REQ-ROLLBACK-001.html",
            "./index.html",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        assert!(docs_entry_present(&members, "index.html"));
    }

    /// Many upstreams wrap everything in one top-level directory. That is
    /// packaging, not content, so the declared entry is written relative to
    /// the payload rather than to the tarball.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_single_wrapper_directory_is_not_part_of_the_entry_path() {
        let members: Vec<String> = [
            "book-1.2.3/",
            "book-1.2.3/index.html",
            "book-1.2.3/ch1.html",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        assert!(docs_entry_present(&members, "index.html"));
    }

    /// ...but only when it really is a single wrapper. Two top-level
    /// directories are content, and stripping one would let any file in
    /// either satisfy the entry.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn two_top_level_directories_are_content_not_a_wrapper() {
        let members: Vec<String> = ["a/index.html", "b/index.html"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert!(!docs_entry_present(&members, "index.html"));
        assert!(docs_entry_present(&members, "a/index.html"));
    }

    /// A `[[docs]]` payload declares what it IS, so a reader can ask for the
    /// PDF and get a PDF. Sniffing the extension would be a guess that is
    /// wrong exactly once and silently.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_docs_payload_declares_its_format_and_its_entry_point() {
        let m = parse_layer_manifest(&format!(
            "{HEAD}\n[[docs]]\nname=\"traceability\"\nrepo=\"pulseengine/varve\"\n\
version=\"v0.35.0\"\nformat=\"html\"\nentry=\"index.html\"\n\
title=\"Requirements & traceability\"\n\
asset=\"varve-%V-traceability-html.tar.gz\"\n"
        ))
        .expect("parses");
        assert_eq!(m.docs.len(), 1);
        let d = &m.docs[0];
        assert_eq!(d.format, DocsFormat::Html);
        assert_eq!(d.entry.as_deref(), Some("index.html"));
        assert_eq!(d.title.as_deref(), Some("Requirements & traceability"));
    }

    /// `rustdoc` is not `html`. It is generated rather than authored, it
    /// versions with the crate it documents, and "show me the API" is a
    /// different request from "show me the handbook" — which only works if
    /// they are different values to filter on.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn rustdoc_is_its_own_format_not_merely_html() {
        let m = parse_layer_manifest(&format!(
            "{HEAD}\n[[docs]]\nname=\"varve-core-api\"\nrepo=\"pulseengine/varve\"\n\
version=\"v0.36.0\"\nformat=\"rustdoc\"\nentry=\"varve_core/index.html\"\n\
asset=\"varve-core-%V-rustdoc.tar.gz\"\n"
        ))
        .expect("parses");
        assert_eq!(m.docs[0].format, DocsFormat::Rustdoc);
        assert_ne!(m.docs[0].format, DocsFormat::Html);
    }

    /// A single-file format has no entry INSIDE it — the asset is the entry.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_single_file_format_needs_no_entry() {
        let m = parse_layer_manifest(&format!(
            "{HEAD}\n[[docs]]\nname=\"handbook\"\nrepo=\"pulseengine/docs\"\n\
version=\"v1.0.0\"\nformat=\"pdf\"\nasset=\"handbook-%V.pdf\"\n"
        ))
        .expect("parses");
        assert_eq!(m.docs[0].format, DocsFormat::Pdf);
        assert_eq!(m.docs[0].entry, None);
    }

    /// An unknown format is REFUSED, not defaulted to html. A realm that
    /// invents `format = "asciidoc"` must hear about it while it can still be
    /// fixed, rather than have varve carry it and offer the wrong opener.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn an_unknown_docs_format_is_refused() {
        let e = parse_layer_manifest(&format!(
            "{HEAD}\n[[docs]]\nname=\"x\"\nrepo=\"a/b\"\nversion=\"v1\"\n\
format=\"asciidoc\"\nasset=\"x-%V.adoc\"\n"
        ))
        .expect_err("must refuse");
        assert!(matches!(e, LayerSpecError::Parse(_)), "{e:?}");
        assert!(
            e.to_string().contains("asciidoc"),
            "the refusal must name the bad value: {e}"
        );
    }

    /// A layout the encoding cannot carry must stop at the boundary rather
    /// than arrive at the shell as something else.
    // rivet: verifies REQ-SDKDEPOSIT-001
    #[test]
    fn an_sdk_entry_refuses_to_translate_into_the_env_encoding() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"zephyr-sdk\"\nrepo=\"zephyrproject-rtos/sdk-ng\"\n\
binary=\"zephyr-sdk\"\nversion=\"v1.0.1\"\nlayout=\"sdk\"\n\
asset=\"toolchain_gnu_%U_arm-zephyr-eabi.tar.xz\"\n"
        ))
        .expect_err("must refuse");
        let msg = e.to_string();
        assert!(msg.contains("none for a LAYOUT"), "{msg}");
        assert!(msg.contains("varve-producer deposit"), "{msg}");
    }

    /// A `zephyr-module` is a tree like an sdk, and for the same reason it
    /// cannot be flattened into the env encoding: the shell assembler would
    /// mine the module for a binary. `allow-pip` is the other half of it
    /// (REQ-ZMODEXPORT-001 clause 5): a field the encoding cannot carry stops
    /// at the boundary.
    // rivet: verifies REQ-ZMODEXPORT-001
    #[test]
    fn a_zephyr_module_entry_refuses_to_translate_into_the_env_encoding() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"gale\"\nrepo=\"pulseengine/gale\"\n\
version=\"v0.1.0\"\nlayout=\"zephyr-module\"\nasset=\"gale-%V.tar.gz\"\n\
allow-pip=[\"scripts/requirements.txt\"]\n"
        ))
        .expect_err("must refuse");
        assert!(
            matches!(&e, LayerSpecError::LayoutNotEncodable { layout, .. } if layout == "zephyr-module"),
            "{e:?}"
        );
        // The sdk refusal still names `sdk`.
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"z\"\nrepo=\"o/z\"\nversion=\"v1\"\nlayout=\"sdk\"\nasset=\"z.tar.xz\"\n"
        ))
        .expect_err("must refuse");
        assert!(
            matches!(&e, LayerSpecError::LayoutNotEncodable { layout, .. } if layout == "sdk"),
            "{e:?}"
        );
    }

    /// `allow-pip` is a manifest field, read as a list of strings.
    // rivet: verifies REQ-ZMODEXPORT-001
    #[test]
    fn allow_pip_is_a_known_manifest_field() {
        let m = parse_layer_manifest(&format!(
            "{HEAD}\n[[tool]]\nname=\"gale\"\nrepo=\"pulseengine/gale\"\n\
version=\"v0.1.0\"\nlayout=\"zephyr-module\"\nasset=\"gale-%V.tar.gz\"\n\
allow-pip=[\"a.txt\", \"b/c.txt\"]\n"
        ))
        .expect("parses");
        assert_eq!(
            m.tools[0].allow_pip.as_deref(),
            Some(&["a.txt".to_string(), "b/c.txt".to_string()][..])
        );
        let none = parse_layer_manifest(&format!(
            "{HEAD}\n[[tool]]\nname=\"rivet\"\nrepo=\"pulseengine/rivet\"\nversion=\"v1\"\n"
        ))
        .unwrap();
        assert_eq!(none.tools[0].allow_pip, None);
    }

    /// A SPLIT OPT-IN joins into exactly the prose a consumer read before.
    ///
    /// The split exists so a scanner can re-measure without parsing the
    /// operator's judgement. It must not change what the layer SAYS: every
    /// consumer — `varve inspect`, the signed `proof-asserts` — read one
    /// string, and still does.
    // rivet: verifies REQ-PREPARED-001
    #[test]
    fn a_split_opt_in_reads_as_one_reason() {
        let m = parse_layer_manifest(&format!(
            "{HEAD}\n[[tool]]\nname=\"wac\"\nrepo=\"bytecodealliance/wac\"\n\
version=\"v0.12.0\"\n\
[tool.unverified]\n\
measured=\"wac v0.12.0 publishes no sums and no provenance (measured 2026-10-09).\"\n\
accepted=\"Accepted for rolling only; the toolchain is unusable without wac.\"\n\
exit=\"Removed by upstream adding attest-build-provenance.\"\n"
        ))
        .expect("a split opt-in parses");
        let t = &m.tools[0];
        assert_eq!(
            t.opt_in_reason().as_deref(),
            Some(
                "wac v0.12.0 publishes no sums and no provenance (measured 2026-10-09). \
                 Accepted for rolling only; the toolchain is unusable without wac. \
                 Removed by upstream adding attest-build-provenance."
            )
        );
        // And the measurement is reachable on its own, which is what a scanner
        // rewrites.
        assert!(t.opt_in_measurement().unwrap().contains("2026-10-09"));
        assert!(!t.opt_in_measurement().unwrap().contains("unusable"));
    }

    /// THE SUBTLE ONE. The release-naming rule applies to the MEASUREMENT,
    /// not to the whole reason.
    ///
    /// An acceptance clause may legitimately mention a version — "unusable
    /// without wac v0.12.0" — and if the rule looked at the joined text, that
    /// mention would satisfy a check about a release nothing was measured
    /// against. The stale measurement would then travel into the signed layer
    /// behind a rule that passed.
    // rivet: verifies REQ-PREPARED-001
    #[test]
    fn an_acceptance_naming_the_release_does_not_satisfy_the_measurement_rule() {
        let e = parse_layer_manifest(&format!(
            "{HEAD}\n[[tool]]\nname=\"wac\"\nrepo=\"bytecodealliance/wac\"\n\
version=\"v0.13.0\"\n\
[tool.unverified]\n\
measured=\"wac v0.12.0 publishes no sums and no provenance (measured 2026-10-02).\"\n\
accepted=\"Accepted for rolling only; v0.13.0 is unusable without it.\"\n\
exit=\"Removed by upstream adding attest-build-provenance.\"\n"
        ))
        .expect_err("the measurement is about v0.12.0 while the pin is v0.13.0");
        assert!(
            matches!(e, LayerSpecError::ReasonIsAboutAnotherRelease { .. }),
            "{e:?}"
        );
    }

    /// Both forms on one entry is refused, because one of them would vanish.
    // rivet: verifies REQ-PREPARED-001
    #[test]
    fn carrying_both_opt_in_forms_is_refused() {
        let e = parse_layer_manifest(&format!(
            "{HEAD}\n[[tool]]\nname=\"wac\"\nrepo=\"bytecodealliance/wac\"\n\
version=\"v0.12.0\"\n\
unverified-reason=\"wac v0.12.0 publishes nothing verifiable.\"\n\
[tool.unverified]\n\
measured=\"wac v0.12.0 publishes no sums (measured 2026-10-09).\"\n\
accepted=\"Accepted for rolling only.\"\n\
exit=\"Removed by upstream adding provenance.\"\n"
        ))
        .expect_err("two answers to one question");
        assert!(matches!(e, LayerSpecError::TwoOptInForms { .. }), "{e:?}");
    }

    /// The env encoding cannot carry the boundary, so it refuses rather than
    /// flattening it away.
    // rivet: verifies REQ-PREPARED-001
    #[test]
    fn a_split_opt_in_refuses_to_translate_into_the_env_encoding() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"wac\"\nrepo=\"bytecodealliance/wac\"\n\
version=\"v0.12.0\"\n\
[tool.unverified]\n\
measured=\"wac v0.12.0 publishes no sums (measured 2026-10-09).\"\n\
accepted=\"Accepted for rolling only.\"\n\
exit=\"Removed by upstream adding provenance.\"\n"
        ))
        .expect_err("the boundary is what would be lost");
        let msg = e.to_string();
        // The refusal must name WHAT is lost — the boundary — not merely that
        // something is unsupported. Case-insensitive because the message
        // emphasises the word in capitals.
        assert!(msg.to_lowercase().contains("measurement"), "{msg}");
        assert!(msg.contains("varve-producer deposit"), "{msg}");
    }

    /// A per-tool platform restriction stops at the env boundary too, and the
    /// stake here is not a name but a payload that cannot run.
    ///
    /// The sdk and upstream-sums cases established the rule: a field the
    /// encoding cannot carry must refuse rather than vanish. Dropping this one
    /// would assemble binaryen for macOS — a 1.7 MB stub needing a dylib a
    /// single-executable payload cannot carry — and that layer installs,
    /// verifies, and fails at the first exec, with every check that could have
    /// caught it passing.
    // rivet: verifies REQ-TOOLPLAT-001
    #[test]
    fn a_platform_restriction_refuses_to_translate_into_the_env_encoding() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"wasm-opt\"\nrepo=\"WebAssembly/binaryen\"\n\
version=\"133\"\nrelease=\"version_133\"\n\
platforms=[\"x86_64-unknown-linux-gnu\"]\n"
        ))
        .expect_err("must refuse rather than widen the platform set");
        let msg = e.to_string();
        assert!(
            msg.contains("x86_64-unknown-linux-gnu"),
            "the refusal must name the restriction it cannot carry: {msg}"
        );
        assert!(msg.contains("varve-producer deposit"), "{msg}");
    }

    /// `upstream-sums` names the mechanism that vouches for a release. The
    /// encoding has no field for it, and dropping it is not a lost hint: the
    /// shell assembler would look for a cosign bundle and an attestation,
    /// find neither, and ingest the payload with NO proof — the declared
    /// verification silently downgraded, with every other field surviving the
    /// trip so the entry looks perfectly ordinary.
    ///
    /// The sdk case above already established the rule: a field the encoding
    /// cannot carry stops at the boundary. This one was dropped instead.
    // rivet: verifies REQ-UPSTREAMSUMS-001
    #[test]
    fn an_upstream_sums_entry_refuses_rather_than_losing_the_mechanism() {
        let e = env_of(&format!(
            "{HEAD}\n[[tool]]\nname=\"wac\"\nrepo=\"bytecodealliance/wac\"\n\
binary=\"wac\"\nversion=\"v0.10.1\"\nasset=\"wac-%V-%T.tar.gz\"\n\
upstream-sums=\"sha256.sum\"\n"
        ))
        .expect_err("must refuse");
        let msg = e.to_string();
        assert!(msg.contains("upstream-sums"), "{msg}");
        assert!(msg.contains("varve-producer deposit"), "{msg}");
    }

    /// One vocabulary. `varve deposit` refuses a format, and both readers
    /// parse one, and all three used to carry their own list of names.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn every_docs_format_parses_back_from_the_name_it_is_signed_as() {
        let all = [
            DocsFormat::Html,
            DocsFormat::Rustdoc,
            DocsFormat::Pdf,
            DocsFormat::Markdown,
            DocsFormat::Reqif,
        ];
        for f in all {
            assert_eq!(DocsFormat::parse(f.as_str()), Some(f), "{f:?}");
        }
        assert_eq!(DocsFormat::parse("epub"), None);
        // layer.toml reads the same names through serde.
        #[derive(serde::Deserialize)]
        struct W {
            f: DocsFormat,
        }
        for f in all {
            let w: W = toml::from_str(&format!("f = \"{}\"", f.as_str())).expect("serde agrees");
            assert_eq!(w.f, f);
        }
        assert_eq!(
            DocsFormat::parse("HTML"),
            None,
            "the signed names are exact"
        );
    }
}