varve-core 0.44.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
//! The verified install pipeline (REQ-VERIFY-001, REQ-ROLLBACK-001).
//!
//! Order is the security argument, so it is fixed here and tested:
//!
//! 1. fetch manifest bytes (by pin digest if pinned, else by name)
//! 2. **verify the manifest signature** against the trust root
//! 3. parse strictly; cross-check layer name, channel, pinned digest
//! 4. anti-rollback check against the per-line high-water mark
//! 5. fetch each blob; **verify each digest** against the signed manifest
//! 6. lay down in the core
//! 7. only now advance the high-water mark
//!
//! Nothing a source returns reaches the core unverified, and a failed
//! install leaves both the core and the high-water marks untouched. The
//! kill-criterion (REQ-VERIFY-001): running the same bytes through two
//! different sources yields identical verdicts — a source that could
//! influence acceptance has joined the trusted base, and the design is broken.

use crate::layer::LayerId;
use crate::manifest::{LayerManifest, ManifestError};
use crate::pin::Pin;
use crate::rollback::{HighWaterMarks, RollbackError, RollbackVerdict};
use crate::source::{LayerRef, LayerSource, SourceError};
use crate::store::{Store, StoreError, manifest_digest};

/// Signature verification over fetched manifest bytes, against the
/// PulseEngine trust root. Returns the *authenticated payload* (the layer
/// manifest itself) — for DSSE-enveloped transport the fetched bytes and the
/// trusted bytes differ, and everything downstream must use only the latter.
/// Implementations carry the trust root; callers cannot relax it per-source —
/// the pipeline takes exactly one verifier for all sources.
pub trait ManifestVerifier {
    fn verify(&self, fetched_bytes: &[u8]) -> Result<Vec<u8>, VerifyError>;

    /// The root this verifier accepts, when it has one to name. A signed
    /// document OTHER than the layer (the line-status digest consent rests on,
    /// REQ-ROLLBACK-002) is verified against this same root and no other.
    /// `None` means "cannot say", which consumers must read as "cannot verify".
    fn root_public_key(&self) -> Option<&[u8]> {
        None
    }
}

#[derive(Debug, thiserror::Error)]
#[error("manifest signature verification failed: {0}")]
pub struct VerifyError(pub String);

/// A successful install.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallOutcome {
    pub digest: String,
    pub layer: LayerId,
    pub counter: u64,
    /// `Some(age_days)` when the accepted layer is older than the staleness
    /// threshold — surfaced, never fatal.
    pub staleness_days: Option<i64>,
    /// The greatest counter the realm's signed index asserts for this line
    /// (REQ-INDEXAUTH-001 clause 4). Reported, NOT enforced: the high-water
    /// mark records what this machine has accepted, and raising it to what
    /// merely EXISTS would refuse a deliberately-pinned older layer the moment
    /// a newer one is published — an availability failure wearing a security
    /// control's clothes, in the one tool whose purpose is frozen toolchains.
    pub index_high_water: Option<u64>,
    /// How many attestations travelled with the layer and were persisted into
    /// its root (REQ-ATTEST-002). Unverified at this point, by design — see
    /// `attestcarry::carry_from_source`; `varve verify` is what checks them.
    pub attestations_carried: usize,
    /// Why carriage was incomplete, when it was. REPORTED, never fatal: a
    /// mirror that dropped an attestation blob must not be able to make a
    /// correctly-signed layer uninstallable, but the loss must not be silent
    /// either — silence is the exact bandersnatch/Verdaccio failure this
    /// requirement exists to surface.
    pub attestation_note: Option<String>,
    /// Set when this install went ahead of the machine's anti-rollback
    /// high-water mark on the strength of a digest in the project's pin
    /// (REQ-ROLLBACK-002). Carries what the caller must say out loud.
    pub digest_consent: Option<DigestConsent>,
}

/// An install that was below the machine's mark and accepted anyway because the
/// pin names the layer by digest and the line's signed line-status supports it
/// (REQ-ROLLBACK-002).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DigestConsent {
    pub line: String,
    pub digest: String,
    pub presented: u64,
    pub high_water: u64,
}

impl DigestConsent {
    /// The one line the install prints: pinned digest, the machine's higher
    /// counter, and why that was not a refusal.
    pub fn note(&self) -> String {
        format!(
            "  note: installed past this machine's anti-rollback mark: the pin selects {} by \
             digest (counter {}), this machine has seen counter {} on line {}, and the line's \
             signed line-status reports it supported and not yanked. The mark is unchanged.",
            self.digest, self.presented, self.high_water, self.line
        )
    }
}

#[derive(Debug, thiserror::Error)]
pub enum InstallError {
    #[error(transparent)]
    Index(#[from] crate::lineindex::IndexError),
    #[error(transparent)]
    Source(#[from] SourceError),
    #[error(transparent)]
    Verify(#[from] VerifyError),
    #[error(transparent)]
    Manifest(#[from] ManifestError),
    #[error(
        "source returned manifest {got} where the pin demands {pinned} — refusing (the digest is the artifact)"
    )]
    DigestMismatch { pinned: String, got: String },
    #[error("manifest is for layer {got}, the pin names {pinned} — refusing")]
    LayerMismatch { pinned: String, got: String },
    #[error("manifest is on channel '{got}', the pin selects '{pinned}' — refusing")]
    ChannelMismatch { pinned: String, got: String },
    #[error(
        "rollback refused: layer presents counter {presented} but the {line} line's high-water mark is {high_water} — a stale, validly-signed layer cannot be passed off as current"
    )]
    Rollback {
        line: String,
        presented: u64,
        high_water: u64,
    },
    #[error(
        "rollback refused: layer presents counter {presented} but the {line} line's high-water \
         mark is {high_water}. The pin selects it by digest, which would be consent — but digest \
         consent needs a verifiable line-status that reports the layer supported and not \
         yanked, and {why}"
    )]
    RollbackConsentRefused {
        line: String,
        presented: u64,
        high_water: u64,
        why: String,
    },
    #[error(
        "layer on line {line} presents counter {presented}, below the floor of {floor} this \
         realm signs for the line — refusing.\n\n\
         This machine has never installed from {line}, so it has no history to compare against. \
         That is the one moment anti-rollback protects nobody, and the moment it is worth \
         attacking: a fresh checkout, a new CI runner, a new laptop are all first contacts. The \
         realm states a floor in its signed line-status so a consumer with no history still has \
         one.\n\n\
         Either the pin names a layer the realm has withdrawn from first-contact use, or \
         something served an old signed layer to a new machine. Both are worth knowing before \
         installing."
    )]
    BelowFloor {
        line: String,
        presented: u64,
        floor: u64,
    },
    #[error("blob {digest} fetched for tool '{tool}' does not match its signed digest — refusing")]
    BlobDigestMismatch { tool: String, digest: String },
    #[error("manifest entry {digest} is missing the eu.pulseengine.tool annotation")]
    UnnamedEntry { digest: String },
    #[error(
        "layer {layer} carries no entry for platform {platform} — refusing to install a \
         wrong-architecture toolchain; use --platform only if you know why"
    )]
    NoPlatformEntry { layer: String, platform: String },
    #[error(transparent)]
    Store(#[from] StoreError),
    #[error(transparent)]
    State(#[from] RollbackError),
}

/// Policy inputs the caller supplies; time is data, not something the
/// pipeline samples.
pub struct InstallPolicy<'a> {
    /// RFC 3339 "now" for the staleness verdict.
    pub now: &'a str,
    pub staleness_threshold_days: u32,
    /// Target platform (a triple) entries must match. Entries without a
    /// platform annotation are platform-independent (REQ-PLATFORM-001).
    pub platform: &'a str,
    /// The realm's line-index obligation (REQ-INDEXAUTH-001). `None` where the
    /// pin names no realm — there is then no root that could have signed an
    /// index, so there is nothing to check.
    pub index: Option<crate::lineindex::IndexPolicy<'a>>,
}

/// Install a layer named only by the digest of its signed manifest — what an
/// `[[include]]` names (REQ-COMPOSEINSTALL-001).
///
/// A composition names the layers it needs by digest, and until v0.38.0 varve
/// declined to FETCH them: an operator installing a four-layer composition from
/// one registry had to create a pinned directory per layer and install each by
/// hand. The refusal bought nothing. A digest is fixed at signing, so whatever
/// arrives either hashes to it or is refused; declining to fetch bytes varve
/// can name exactly is friction wearing the clothes of caution.
///
/// What it does NOT do is pin: no varve.toml is written, because obtaining a
/// layer and choosing it are different acts, and a pin that appeared by itself
/// would be a decision nobody made.
///
/// Every check a direct install makes still runs — the realm's signed index,
/// anti-rollback, the platform filter — because this delegates to `install`
/// rather than reimplementing it. The cost is re-fetching one small manifest to
/// learn the layer id and channel the digest belongs to; the alternative was a
/// second copy of two hundred lines that decide whether bytes are acceptable,
/// and a second copy is how those two answers drift apart.
pub fn install_by_digest(
    digest: &str,
    source: &dyn LayerSource,
    verifier: &dyn ManifestVerifier,
    store: &Store,
    marks: &mut HighWaterMarks,
    policy: &InstallPolicy<'_>,
) -> Result<InstallOutcome, InstallError> {
    let fetched = source.fetch_manifest(&LayerRef::Digest(digest.to_string()))?;
    let bytes = verifier.verify(&fetched)?;
    let manifest = LayerManifest::parse(&bytes)?;
    let channel = match manifest.channel.as_str() {
        "qualified" => crate::pin::Channel::Qualified,
        "rolling" => crate::pin::Channel::Rolling,
        other => {
            return Err(InstallError::ChannelMismatch {
                pinned: "qualified|rolling".to_string(),
                got: other.to_string(),
            });
        }
    };
    let pin = Pin {
        realm: None,
        channel,
        layer: manifest.layer.clone(),
        digest: Some(digest.to_string()),
        tools: None,
        exports: Vec::new(),
    };
    // The digest here comes from a composing layer, not from a project's pin,
    // so it is NOT consent to go below the mark (REQ-ROLLBACK-002 speaks of
    // the project's pin): a layer's include list is the signer's choice, and
    // what this machine accepts is still the machine's.
    install_inner(&pin, source, verifier, store, marks, policy, false)
}

/// Install the layer a project's pin selects. A pin that names the layer by
/// digest is consent to go below the machine's high-water mark when the line's
/// signed line-status supports the layer (REQ-ROLLBACK-002).
pub fn install(
    pin: &Pin,
    source: &dyn LayerSource,
    verifier: &dyn ManifestVerifier,
    store: &Store,
    marks: &mut HighWaterMarks,
    policy: &InstallPolicy<'_>,
) -> Result<InstallOutcome, InstallError> {
    install_inner(pin, source, verifier, store, marks, policy, true)
}

fn install_inner(
    pin: &Pin,
    source: &dyn LayerSource,
    verifier: &dyn ManifestVerifier,
    store: &Store,
    marks: &mut HighWaterMarks,
    policy: &InstallPolicy<'_>,
    digest_is_consent: bool,
) -> Result<InstallOutcome, InstallError> {
    // 1. Fetch.
    let layer_ref = match &pin.digest {
        Some(digest) => LayerRef::Digest(digest.clone()),
        None => LayerRef::Name(pin.layer.clone()),
    };
    let fetched = source.fetch_manifest(&layer_ref)?;

    // 2. Signature first: nothing else is read from unverified bytes, and no
    // blob is fetched on the strength of an unverified manifest. Only the
    // authenticated payload the verifier returns is used from here on.
    let bytes = verifier.verify(&fetched)?;

    // 3. Strict parse + cross-checks against the pin.
    let manifest = LayerManifest::parse(&bytes)?;
    let digest = manifest_digest(&bytes);
    if let Some(pinned) = &pin.digest
        && &digest != pinned
    {
        return Err(InstallError::DigestMismatch {
            pinned: pinned.clone(),
            got: digest,
        });
    }
    if manifest.layer != pin.layer {
        return Err(InstallError::LayerMismatch {
            pinned: pin.layer.to_string(),
            got: manifest.layer.to_string(),
        });
    }
    let pinned_channel = match pin.channel {
        crate::pin::Channel::Qualified => "qualified",
        crate::pin::Channel::Rolling => "rolling",
    };
    if manifest.channel != pinned_channel {
        return Err(InstallError::ChannelMismatch {
            pinned: pinned_channel.to_string(),
            got: manifest.channel.clone(),
        });
    }

    // 3b. The realm's signed index (REQ-INDEXAUTH-001). Before anti-rollback,
    // because the index can RAISE the mark: a registry that hides the newest
    // layer must not lower the bar this install has to clear. Everything here
    // is verified against the realm's root — the source is the party being
    // constrained and is never asked whether its own listing is honest.
    let line = manifest.layer.line();
    let line_str = line.to_string();
    let index_cache = crate::lineindex::IndexCache::at_root(store.root());
    let mut index_high_water: Option<u64> = None;
    // The verified index and the bytes it came from, held until the install
    // lands: a refused install must not leave a raised index behind, for the
    // same reason it must not burn the high-water mark.
    let mut accepted_index: Option<(crate::lineindex::LineIndex, Vec<u8>)> = None;
    if let Some(index_policy) = &policy.index {
        let envelope = source.fetch_line_index(&line_str)?;
        let served = source.served_layers(&line_str)?;
        // Clause 2 needs something to compare AGAINST, and it is the cache
        // that supplies it. Passing `None` here left the whole
        // presented-older-than-held rule unreachable from the pipeline: it
        // could only ever fire in a test that called `check` itself.
        let cached = index_cache.load(&line_str)?;
        let verified = crate::lineindex::check(
            &line_str,
            envelope.as_deref(),
            served.as_deref(),
            cached.as_ref(),
            index_policy,
        )?;
        index_high_water = verified.as_ref().and_then(|i| i.high_water());
        if let (Some(doc), Some(bytes)) = (verified, envelope) {
            accepted_index = Some((doc, bytes));
        }
    }

    // REQ-FIRSTCONTACT-001: the realm's signed floor for this line, for a
    // consumer that has no mark of its own.
    //
    // Read from the line-status document, which is already DSSE-signed by the
    // realm root and already distributed beside the layer — a floor is worth
    // nothing if whoever serves the bytes can choose it. Verified here against
    // the same root the index policy carries; a document that does not verify,
    // or that covers another line, yields NO floor rather than a trusted zero.
    //
    // Best-effort, and the residual is worth stating plainly: a source that
    // simply omits the line-status removes the floor, exactly as it could
    // before this existed. That is not a regression, and it is not full
    // protection either — closing it needs the realm to REQUIRE a status the
    // way `signed-index` requires an index, which is a realm-policy change and
    // not this requirement.
    let mut first_contact_floor: Option<u64> = None;
    if marks.mark(line).is_none()
        && let Some(index_policy) = &policy.index
        && let Some(bytes) = source.fetch_line_status(&layer_ref)?
        && let Ok(doc) =
            crate::linestatus::LineStatus::verify_and_parse(&bytes, index_policy.root_public_key)
        && doc.line == line_str
    {
        first_contact_floor = doc.min_counter;
    }

    // 4. Anti-rollback, before any blob moves.
    let mut digest_consent: Option<DigestConsent> = None;
    match marks.check_with_floor(&manifest, first_contact_floor) {
        RollbackVerdict::Rollback {
            line,
            presented,
            high_water,
        } => match (&pin.digest, digest_is_consent) {
            // REQ-ROLLBACK-002: a digest in the project's pin is a decision a
            // reviewer saw; resolution by name is the replay REQ-ROLLBACK-001
            // exists for. The digest was already matched against the
            // verified manifest in step 3.
            (Some(pinned), true) => {
                match consent_why_not(
                    &manifest,
                    &layer_ref,
                    source,
                    store.root(),
                    verifier,
                    policy.now,
                ) {
                    None => {
                        digest_consent = Some(DigestConsent {
                            line,
                            digest: pinned.clone(),
                            presented,
                            high_water,
                        });
                    }
                    Some(why) => {
                        return Err(InstallError::RollbackConsentRefused {
                            line,
                            presented,
                            high_water,
                            why,
                        });
                    }
                }
            }
            _ => {
                return Err(InstallError::Rollback {
                    line,
                    presented,
                    high_water,
                });
            }
        },
        RollbackVerdict::BelowFloor {
            line,
            presented,
            floor,
        } => {
            return Err(InstallError::BelowFloor {
                line,
                presented,
                floor,
            });
        }
        RollbackVerdict::Accept => {}
    }

    // 5. Fetch blobs; each is accepted only if it matches its signed digest.
    // Platform filtering happens BEFORE any fetch: a foreign entry's blob
    // never even leaves the source (REQ-PLATFORM-001).
    // Name, version and dispatchability travel with the bytes: a payload that
    // is not dispatched by name is laid down under its version too, so two
    // versions of one crate cannot overwrite each other (REQ-STORE-002).
    struct Fetched {
        name: String,
        version: Option<String>,
        dispatchable: bool,
        /// What the payload builds for, when it says (REQ-SDKTARGET-001).
        /// Two cross-toolchains for one host differ ONLY here, so it has to
        /// survive the fetch or they collide on one path.
        target: Option<String>,
        bytes: Vec<u8>,
    }
    let mut tools: Vec<Fetched> = Vec::new();
    let mut matched = 0usize;
    // Entries that COULD match a platform — everything that is not a
    // composition edge. The fail-closed check below compares against this and
    // not against the manifest's whole entry list, because an `[[include]]`
    // carries no bytes and is never stamped for a platform: counting it would
    // make a layer that is ONLY a composition look like a layer whose every
    // payload was for the wrong architecture.
    let payload_entries = manifest
        .entries
        .iter()
        .filter(|e| e.kind() != Ok(crate::kind::PayloadKind::Layer))
        .count();
    for entry in &manifest.entries {
        if !crate::platform::entry_matches(
            entry
                .annotations
                .get(crate::platform::ANN_PLATFORM)
                .map(String::as_str),
            policy.platform,
        ) {
            continue;
        }
        // A composed layer is a REFERENCE, not a blob to lay down: its digest
        // names another layer's manifest, which has its own install. Skip it
        // here — install rejected it outright before, so a real composed layer
        // could not be installed at all (REQ-COMPOSE-001).
        if entry.kind() == Ok(crate::kind::PayloadKind::Layer) {
            continue;
        }
        matched += 1;
        let tool = entry
            .annotations
            .get("eu.pulseengine.tool")
            .ok_or_else(|| InstallError::UnnamedEntry {
                digest: entry.digest.clone(),
            })?
            .clone();
        let blob = source.fetch_blob(&entry.digest)?;
        if manifest_digest(&blob) != entry.digest {
            return Err(InstallError::BlobDigestMismatch {
                tool,
                digest: entry.digest.clone(),
            });
        }
        tools.push(Fetched {
            name: tool,
            version: crate::store::entry_version(entry).map(str::to_string),
            dispatchable: crate::store::entry_is_dispatchable(entry),
            target: crate::platform::entry_target(entry).map(str::to_string),
            bytes: blob,
        });
    }

    // A fully-stamped layer with nothing for this platform fails closed —
    // a wrong-architecture toolchain must not land looking installed.
    if matched == 0 && payload_entries > 0 {
        return Err(InstallError::NoPlatformEntry {
            layer: manifest.layer.to_string(),
            platform: policy.platform.to_string(),
        });
    }

    // 6. Lay down.
    let payloads: Vec<crate::store::Payload<'_>> = tools
        .iter()
        .map(|t| crate::store::Payload {
            name: t.name.as_str(),
            version: t.version.as_deref(),
            dispatchable: t.dispatchable,
            target: t.target.as_deref(),
            bytes: t.bytes.as_slice(),
        })
        .collect();
    let stored_digest = store.lay_down_payloads(&bytes, &payloads)?;
    debug_assert_eq!(stored_digest, digest);

    // Record WHICH platform these payloads were selected for, so `verify`
    // filters by the decision made here instead of re-deriving one from
    // whatever host it is run on later (varve#189).
    if let Some(entry) = store.get(&digest)? {
        crate::store::record_install_platform(&entry.root, policy.platform)?;
    }

    // Retain the signature envelope beside the payload, so `varve verify`
    // can repeat the install-time verdict offline, forever. (When transport
    // was already the bare payload — test doubles — there is nothing to keep.)
    if fetched != bytes
        && let Some(entry) = store.get(&digest)?
    {
        let path = entry.root.join(crate::reverify::ENVELOPE_FILE);
        std::fs::write(&path, &fetched).map_err(|source| StoreError::Io {
            path: path.display().to_string(),
            source,
        })?;
    }

    // 6b. Carry the layer's attestations into its root (REQ-ATTEST-002).
    // Registries publish this evidence and mirrors drop it: bandersnatch and
    // Verdaccio carry none, and every Bazel Central Registry attestation URL
    // points at github.com — so without this an air-gapped consumer receives
    // the bytes and none of the accountability, with no error saying so.
    // Persisting here is also what lets `archive` put it back on the wire.
    let mut attestations_carried = 0usize;
    let mut attestation_note = None;
    if let Some(entry) = store.get(&digest)? {
        match crate::attestcarry::carry_from_source(source, &layer_ref, &entry.root) {
            Ok(n) => attestations_carried = n,
            // Never fatal. The layer's own signature and digests decided the
            // install several steps ago; a third party's evidence being
            // missing, malformed, or unfetchable is evidence ABOUT the
            // evidence, and refusing here would hand a mirror the power to
            // make a perfectly-signed layer uninstallable.
            Err(e) => attestation_note = Some(e.to_string()),
        }
    }

    // 7. Only a fully landed layer advances the high-water mark — or the
    // cached index it was checked against (REQ-INDEXAUTH-001 clause 2).
    marks.advance(&manifest)?;
    if let Some((doc, bytes)) = &accepted_index {
        index_cache.update(&line_str, bytes, doc)?;
    }

    let staleness_days = crate::rollback::staleness_warning(
        &manifest.issued_at,
        policy.now,
        policy.staleness_threshold_days,
    );
    Ok(InstallOutcome {
        digest,
        layer: manifest.layer.clone(),
        counter: manifest.counter,
        staleness_days,
        index_high_water,
        attestations_carried,
        attestation_note,
        digest_consent,
    })
}

/// Why a digest-pinned layer below the mark may NOT be installed on the pin's
/// word alone; `None` when the line's signed line-status consents
/// (REQ-ROLLBACK-002).
///
/// The pin is not trusted by itself: the digest being in the file proves the
/// reviewer chose THIS layer, not that the line still stands behind it. That
/// is the line-status's word, and it has to verify against the realm's root —
/// fetched from the source when it carries one, else the copy cached by an
/// earlier install. A yank is never overridden, and neither is an expired
/// support window; no verifiable document means no consent.
fn consent_why_not(
    manifest: &LayerManifest,
    layer_ref: &LayerRef,
    source: &dyn LayerSource,
    store_root: &std::path::Path,
    verifier: &dyn ManifestVerifier,
    now: &str,
) -> Option<String> {
    let Some(root_pk) = verifier.root_public_key() else {
        return Some("there is no trust root to verify a line-status against".to_string());
    };
    let line = manifest.layer.line();
    let served = match crate::linestatus::current_line_status(
        source,
        layer_ref,
        line,
        root_pk,
        crate::linestatus::Published::BestEffort,
    ) {
        Ok(served) => served.map(|(_, doc)| doc),
        Err(e) => return Some(format!("the one served does not verify: {e}")),
    };
    // The registry is the party anti-rollback constrains, so what it serves
    // cannot outrank what this machine already holds: a validly-signed status
    // from BEFORE a yank, replayed, would otherwise re-enable the yanked
    // layer. The newer signed word decides, whichever side it came from.
    let cached = match crate::linestatus::StatusCache::at_root(store_root).load(line, root_pk) {
        Ok(cached) => cached,
        Err(e) => return Some(format!("the cached one does not verify: {e}")),
    };
    // One counter names one signed document, so which side wins a tie does
    // not matter; the greatest counter is the line's latest word.
    match [served, cached]
        .into_iter()
        .flatten()
        .max_by_key(|d| d.counter)
    {
        Some(newest) => consent_from_status(manifest, &newest, now),
        None => Some(format!(
            "none is available for line {line}: the source carries none and none was cached by \
             an earlier install"
        )),
    }
}

/// The same judgment from the line-status an earlier install cached, with no
/// source — what `varve verify` has, because it runs offline and must not
/// disagree with the install that put the layer there (REQ-ROLLBACK-002).
pub fn cached_consent_why_not(
    manifest: &LayerManifest,
    store_root: &std::path::Path,
    root_public_key: &[u8],
    now: &str,
) -> Option<String> {
    let line = manifest.layer.line();
    match crate::linestatus::StatusCache::at_root(store_root).load(line, root_public_key) {
        Ok(Some(doc)) => consent_from_status(manifest, &doc, now),
        Ok(None) => Some(format!(
            "none is available for line {line}: the source carries none and none was cached by \
             an earlier install"
        )),
        Err(e) => Some(format!("the cached one does not verify: {e}")),
    }
}

/// What a VERIFIED line-status says about one layer, as consent: a yank or a
/// lapsed support window refuses; silence on both consents.
fn consent_from_status(
    manifest: &LayerManifest,
    doc: &crate::linestatus::LineStatus,
    now: &str,
) -> Option<String> {
    let line = manifest.layer.line();
    if doc.line != line.to_string() {
        return Some(format!(
            "the line-status served covers line {}, not {line}",
            doc.line
        ));
    }
    if let Some(floor) = doc.min_counter
        && manifest.counter < floor
    {
        return Some(format!(
            "the line-status sets a floor of counter {floor} for line {line} and this layer \
             presents {}; consent does not override the line's own floor",
            manifest.counter
        ));
    }
    let report = doc.report_for(&manifest.layer);
    if let Some(reason) = report.yanked_reason {
        return Some(format!(
            "the line-status reports layer {} YANKED ({reason}); consent does not override a yank",
            manifest.layer
        ));
    }
    if let Some(until) = &report.support_until {
        match crate::support::standing(until, now) {
            Ok(standing) if standing.is_expired() => {
                return Some(format!(
                    "the line-status reports line {line} out of support since {until}; consent \
                     does not override that"
                ));
            }
            Ok(_) => {}
            Err(e) => return Some(format!("the line-status support window is unreadable: {e}")),
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::manifest::fixtures::manifest_with_tools;
    use crate::pin::Pin;
    use crate::rollback::HighWaterMarks;
    use crate::source::{DirSource, MemorySource};

    struct AcceptAll;
    impl ManifestVerifier for AcceptAll {
        fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
            Ok(fetched.to_vec())
        }
    }

    struct RejectAll;
    impl ManifestVerifier for RejectAll {
        fn verify(&self, _: &[u8]) -> Result<Vec<u8>, VerifyError> {
            Err(VerifyError("untrusted signature (test)".into()))
        }
    }

    fn pin(layer: &str) -> Pin {
        Pin::parse(
            &format!(
                "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\n"
            ),
            "varve.toml",
        )
        .unwrap()
    }

    fn policy() -> InstallPolicy<'static> {
        InstallPolicy {
            index: None,
            now: "2026-08-07T00:00:00Z",
            staleness_threshold_days: 90,
            platform: "test-platform",
        }
    }

    /// One layer's worth of test material: manifest bytes + blobs.
    fn july() -> (Vec<u8>, Vec<(String, Vec<u8>)>) {
        let synth = b"july-synth".to_vec();
        let rivet = b"july-rivet".to_vec();
        let blobs = vec![
            (manifest_digest(&synth), synth),
            (manifest_digest(&rivet), rivet),
        ];
        let bytes = manifest_with_tools(
            "2026.07.0",
            "qualified",
            1,
            "2026-07-31T09:14:00Z",
            &[("synth", &blobs[0].0), ("rivet", &blobs[1].0)],
        );
        (bytes, blobs)
    }

    fn memory_source(manifest: &[u8], blobs: &[(String, Vec<u8>)]) -> MemorySource {
        let mut source = MemorySource::new().with_manifest(manifest);
        for (digest, bytes) in blobs {
            source = source.with_blob(digest, bytes);
        }
        source
    }

    fn setup() -> (tempfile::TempDir, Store, HighWaterMarks) {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("varve-root");
        let store = Store::at(&root);
        let marks = HighWaterMarks::load(&root).unwrap();
        (tmp, store, marks)
    }

    // rivet: verifies REQ-VERIFY-001
    #[test]
    fn installs_a_verified_layer_end_to_end() {
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();
        let source = memory_source(&bytes, &blobs);
        let outcome = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap();
        assert_eq!(outcome.layer.to_string(), "2026.07.0");
        assert_eq!(outcome.digest, manifest_digest(&bytes));
        // The layer is resolvable afterwards — install feeds resolution.
        let entry = store.get(&outcome.digest).unwrap().unwrap();
        assert!(store.tool_path(&entry, "synth").is_some());
        assert!(store.tool_path(&entry, "rivet").is_some());
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn installing_two_versions_of_one_crate_lands_both_sets_of_bytes() {
        // Clause 2 through the function that actually runs it. `install`
        // collected (name, bytes) pairs and handed them to a store that wrote
        // `bin/<name>`, so the second serde's bytes landed under the first's
        // name: ONE file, the WRONG contents, and `verify` then failing on the
        // other entry with nothing explaining why.
        use crate::manifest::fixtures::manifest_with_payloads;
        let (_tmp, store, mut marks) = setup();
        let (a, b) = (
            b"serde-1.0.200-crate".to_vec(),
            b"serde-1.0.210-crate".to_vec(),
        );
        let (da, db) = (manifest_digest(&a), manifest_digest(&b));
        let bytes = manifest_with_payloads(
            "2026.07.0",
            "qualified",
            1,
            "2026-07-31T09:14:00Z",
            &[
                ("serde", "1.0.200", "crate", &da),
                ("serde", "1.0.210", "crate", &db),
            ],
        );
        let source = memory_source(&bytes, &[(da, a.clone()), (db, b.clone())]);
        let outcome = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .expect("two versions of one crate is the ordinary shape of a dependency graph");

        let entry = store.get(&outcome.digest).unwrap().unwrap();
        assert_eq!(
            std::fs::read(entry.root.join("payloads/serde/1.0.200")).unwrap(),
            a
        );
        assert_eq!(
            std::fs::read(entry.root.join("payloads/serde/1.0.210")).unwrap(),
            b,
            "the second version must not have overwritten the first"
        );
        // Nothing landed under the bare name, where one version would have won.
        assert!(!entry.root.join("bin/serde").exists());
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn a_signed_manifest_whose_entries_share_one_identity_is_refused_not_overwritten() {
        // `deposit` refuses this, but deposit is not the only producer varve
        // installs from: any realm root can sign a manifest, built by any
        // software. If two entries ever reach one path, install must fail
        // LOUDLY — writing one over the other would put the wrong bytes under
        // the right name and make `verify` fail on the innocent entry.
        use crate::manifest::fixtures::manifest_with_payloads;
        let (_tmp, store, mut marks) = setup();
        let (a, b) = (b"first-bytes".to_vec(), b"second-bytes".to_vec());
        let (da, db) = (manifest_digest(&a), manifest_digest(&b));
        let bytes = manifest_with_payloads(
            "2026.07.0",
            "qualified",
            1,
            "2026-07-31T09:14:00Z",
            &[
                ("serde", "1.0.200", "crate", &da),
                ("serde", "1.0.200", "crate", &db),
            ],
        );
        let source = memory_source(&bytes, &[(da, a), (db, b)]);
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .expect_err("one identity, two payloads: the store must refuse");
        assert!(
            matches!(err, InstallError::Store(StoreError::Collision { .. })),
            "got: {err}"
        );
        assert!(store.list().unwrap().is_empty(), "nothing may be laid down");
        assert_eq!(
            marks.mark(&"2026.07".parse().unwrap()),
            None,
            "a refused install must not burn the mark"
        );
    }

    // rivet: verifies REQ-VERIFY-001
    #[test]
    fn kill_criterion_two_sources_one_verdict() {
        // The same bytes through two different transports must produce
        // identical verdicts — accept AND reject cases.
        let (bytes, blobs) = july();
        let tmp = tempfile::tempdir().unwrap();
        let dir = DirSource::at(tmp.path().join("archive"));
        dir.put(
            &bytes,
            &blobs
                .iter()
                .map(|(d, b)| (d.as_str(), b.as_slice()))
                .collect::<Vec<_>>(),
        )
        .unwrap();
        let mem = memory_source(&bytes, &blobs);

        let run = |source: &dyn LayerSource, verifier: &dyn ManifestVerifier| {
            let (_t, store, mut marks) = setup();
            install(
                &pin("2026.07.0"),
                source,
                verifier,
                &store,
                &mut marks,
                &policy(),
            )
            .map_err(|e| e.to_string())
        };

        let accept_mem = run(&mem, &AcceptAll).unwrap();
        let accept_dir = run(&dir, &AcceptAll).unwrap();
        assert_eq!(accept_mem, accept_dir, "same bytes, same acceptance");

        let reject_mem = run(&mem, &RejectAll).unwrap_err();
        let reject_dir = run(&dir, &RejectAll).unwrap_err();
        assert_eq!(reject_mem, reject_dir, "same bytes, same rejection");
    }

    // rivet: verifies REQ-VERIFY-001
    #[test]
    fn an_unverified_manifest_fetches_no_blobs_and_installs_nothing() {
        struct CountingSource {
            inner: MemorySource,
            blob_fetches: std::cell::Cell<usize>,
        }
        impl LayerSource for CountingSource {
            fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
                self.inner.fetch_manifest(layer)
            }
            fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
                self.blob_fetches.set(self.blob_fetches.get() + 1);
                self.inner.fetch_blob(digest)
            }
        }
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();
        let source = CountingSource {
            inner: memory_source(&bytes, &blobs),
            blob_fetches: std::cell::Cell::new(0),
        };
        let err = install(
            &pin("2026.07.0"),
            &source,
            &RejectAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap_err();
        assert!(matches!(err, InstallError::Verify(_)), "got: {err}");
        assert_eq!(
            source.blob_fetches.get(),
            0,
            "no blob leaves the source before the signature verdict"
        );
        assert!(store.list().unwrap().is_empty(), "nothing laid down");
    }

    // rivet: verifies REQ-VERIFY-001
    #[test]
    fn a_source_that_alters_a_blob_is_caught_by_the_signed_digest() {
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();
        // Serve the right manifest but tamper with one blob.
        let mut source = MemorySource::new().with_manifest(&bytes);
        source = source.with_blob(&blobs[0].0, b"EVIL");
        source = source.with_blob(&blobs[1].0, &blobs[1].1);
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap_err();
        assert!(
            matches!(err, InstallError::BlobDigestMismatch { .. }),
            "got: {err}"
        );
        assert!(
            store.list().unwrap().is_empty(),
            "tampered layer must not land"
        );
    }

    // rivet: verifies REQ-VERIFY-001
    #[test]
    fn a_source_that_answers_a_digest_request_with_other_bytes_is_caught() {
        struct LyingSource(Vec<u8>);
        impl LayerSource for LyingSource {
            fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
                Ok(self.0.clone())
            }
            fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
                Err(SourceError::NotFound(digest.into()))
            }
        }
        let (_tmp, store, mut marks) = setup();
        // Pin a digest that is NOT the digest of what the source returns.
        let (bytes, _) = july();
        let other = manifest_with_tools("2026.07.0", "qualified", 1, "2026-07-31T09:14:00Z", &[]);
        let pinned = manifest_digest(&other);
        let hex = pinned.strip_prefix("sha256:").unwrap();
        let p = Pin::parse(
            &format!(
                "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ndigest = \"sha256:{hex}\"\n"
            ),
            "varve.toml",
        )
        .unwrap();
        let err = install(
            &p,
            &LyingSource(bytes),
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap_err();
        assert!(
            matches!(err, InstallError::DigestMismatch { .. }),
            "got: {err}"
        );
    }

    // rivet: verifies REQ-ROLLBACK-001
    #[test]
    fn a_rolled_back_layer_is_refused_at_install() {
        let (_tmp, store, mut marks) = setup();
        // The line's high-water mark is already at 5.
        let newer = manifest_with_tools("2026.07.2", "qualified", 5, "2026-08-01T00:00:00Z", &[]);
        marks
            .advance(&LayerManifest::parse(&newer).unwrap())
            .unwrap();
        let (bytes, blobs) = july(); // counter 1 < 5
        let source = memory_source(&bytes, &blobs);
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                InstallError::Rollback {
                    presented: 1,
                    high_water: 5,
                    ..
                }
            ),
            "got: {err}"
        );
        assert!(store.list().unwrap().is_empty());
    }

    // rivet: verifies REQ-ROLLBACK-001
    #[test]
    fn a_failed_install_does_not_advance_the_high_water_mark() {
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();
        // Source is missing one blob: install fails after the rollback check.
        let source = MemorySource::new()
            .with_manifest(&bytes)
            .with_blob(&blobs[0].0, &blobs[0].1);
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap_err();
        assert!(
            matches!(err, InstallError::Source(SourceError::NotFound(_))),
            "got: {err}"
        );
        let m = LayerManifest::parse(&bytes).unwrap();
        assert_eq!(
            marks.mark(m.layer.line()),
            None,
            "failed install must not burn the mark"
        );
    }

    // rivet: verifies REQ-ROLLBACK-001
    #[test]
    fn staleness_is_surfaced_on_an_accepted_layer() {
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july(); // issued 2026-07-31
        let source = memory_source(&bytes, &blobs);
        let policy = InstallPolicy {
            index: None,
            now: "2026-12-01T00:00:00Z",
            staleness_threshold_days: 90,
            platform: "test-platform",
        };
        let outcome = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .unwrap();
        assert_eq!(outcome.staleness_days, Some(123));
    }

    // rivet: verifies REQ-PLATFORM-001
    #[test]
    fn install_selects_only_entries_for_the_target_platform() {
        let (_tmp, store, mut marks) = setup();
        let here = b"here-tool".to_vec();
        let there = b"there-tool".to_vec();
        let (d_here, d_there) = (manifest_digest(&here), manifest_digest(&there));
        let bytes = crate::manifest::fixtures::manifest_with_platform_tools(
            "2026.07.0",
            "qualified",
            1,
            "2026-07-31T09:14:00Z",
            &[
                ("synth", &d_here, Some("test-platform")),
                ("synth", &d_there, Some("other-platform")),
            ],
        );
        // Only the matching blob is served — a correct install never asks
        // for the foreign one.
        let source = MemorySource::new()
            .with_manifest(&bytes)
            .with_blob(&d_here, &here);
        let policy = InstallPolicy {
            index: None,
            now: "2026-08-07T00:00:00Z",
            staleness_threshold_days: 90,
            platform: "test-platform",
        };
        let outcome = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .unwrap();
        let entry = store.get(&outcome.digest).unwrap().unwrap();
        assert_eq!(
            std::fs::read(store.tool_path(&entry, "synth").unwrap()).unwrap(),
            here,
            "the host-platform binary landed"
        );
    }

    // rivet: verifies REQ-PLATFORM-001
    #[test]
    fn a_layer_with_nothing_for_the_host_platform_fails_closed() {
        let (_tmp, store, mut marks) = setup();
        let there = b"there-tool".to_vec();
        let d_there = manifest_digest(&there);
        let bytes = crate::manifest::fixtures::manifest_with_platform_tools(
            "2026.07.0",
            "qualified",
            1,
            "2026-07-31T09:14:00Z",
            &[("synth", &d_there, Some("other-platform"))],
        );
        let source = MemorySource::new()
            .with_manifest(&bytes)
            .with_blob(&d_there, &there);
        let policy = InstallPolicy {
            index: None,
            now: "2026-08-07T00:00:00Z",
            staleness_threshold_days: 90,
            platform: "test-platform",
        };
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .unwrap_err();
        assert!(
            matches!(err, InstallError::NoPlatformEntry { .. }),
            "got: {err}"
        );
        assert!(store.list().unwrap().is_empty(), "no wrong-arch bytes land");
    }

    // rivet: verifies REQ-PLATFORM-001
    #[test]
    fn unstamped_legacy_entries_install_on_any_platform() {
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july(); // fixtures without platform annotations
        let source = memory_source(&bytes, &blobs);
        let policy = InstallPolicy {
            index: None,
            now: "2026-08-07T00:00:00Z",
            staleness_threshold_days: 90,
            platform: "any-platform-at-all",
        };
        assert!(
            install(
                &pin("2026.07.0"),
                &source,
                &AcceptAll,
                &store,
                &mut marks,
                &policy
            )
            .is_ok()
        );
    }

    // rivet: verifies REQ-PIN-001
    #[test]
    fn channel_and_layer_mismatches_are_refused() {
        let (_tmp, store, mut marks) = setup();
        // Manifest says rolling; pin says qualified.
        let synth = b"s".to_vec();
        let d = manifest_digest(&synth);
        let bytes = manifest_with_tools(
            "2026.07.0",
            "rolling",
            1,
            "2026-07-31T09:14:00Z",
            &[("synth", &d)],
        );
        let source = MemorySource::new()
            .with_manifest(&bytes)
            .with_blob(&d, &synth);
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap_err();
        assert!(
            matches!(err, InstallError::ChannelMismatch { .. }),
            "got: {err}"
        );
    }

    // rivet: verifies REQ-ATTEST-002
    #[test]
    fn install_carries_the_attestations_the_source_holds_into_the_installed_layer() {
        // The transport half. Binding shipped in v0.22.0 and reached nobody:
        // an attestation that stays in the producer's CI is not evidence a
        // consumer has. This asserts the evidence lands in the installed layer
        // root — the only place `archive` and `verify` can find it later.
        use crate::attest::{AttestationKind, sign, statement};
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();
        let layer_digest = manifest_digest(&bytes);
        let sbom = b"{\"bomFormat\":\"CycloneDX\"}";
        let st = statement(
            "2026.07.0",
            &layer_digest,
            AttestationKind::Sbom,
            sbom,
            "acme-ci",
        );
        let envelope = sign(&st, &sk, "root-1").unwrap();
        let source = memory_source(&bytes, &blobs).with_attestation(envelope.as_bytes(), sbom);

        let outcome = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .unwrap();
        assert_eq!(
            outcome.attestations_carried, 1,
            "install must report what travelled"
        );
        assert_eq!(outcome.attestation_note, None);

        // …and it is really on disk, verbatim, and still binds offline.
        let entry = store.get(&outcome.digest).unwrap().unwrap();
        let carried = crate::attestcarry::read_persisted(&entry.root, "2026.07.0").unwrap();
        assert_eq!(carried.len(), 1, "the evidence reached the installed layer");
        assert_eq!(
            carried[0].bytes, sbom,
            "the attested bytes are stored VERBATIM — varve transports another party's \
             judgement, it never restates it"
        );
        let reports = crate::attestcarry::report(&carried, &layer_digest, "2026.07.0", &pk);
        assert!(reports[0].binds, "reason: {:?}", reports[0].reason);
        assert_eq!(reports[0].producer, "acme-ci");
    }

    // rivet: verifies REQ-ATTEST-002
    #[test]
    fn a_source_that_loses_its_attestations_still_installs_but_says_so() {
        // Deliberate: REPORTING, not refusal. A mirror that drops the evidence
        // must not gain the power to make a correctly-signed layer
        // uninstallable — that would make varve's availability a function of
        // someone else's mirroring. But the loss must not be SILENT either:
        // silence is precisely the bandersnatch/Verdaccio failure this
        // requirement exists to surface.
        struct LosesAttestations(MemorySource);
        impl LayerSource for LosesAttestations {
            fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
                self.0.fetch_manifest(layer)
            }
            fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
                self.0.fetch_blob(digest)
            }
            fn fetch_attestations(
                &self,
                _layer: &LayerRef,
            ) -> Result<Vec<crate::attestcarry::CarriedAttestation>, SourceError> {
                Err(SourceError::Transport("the mirror dropped them".into()))
            }
        }
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();
        let outcome = install(
            &pin("2026.07.0"),
            &LosesAttestations(memory_source(&bytes, &blobs)),
            &AcceptAll,
            &store,
            &mut marks,
            &policy(),
        )
        .expect("a layer whose own signature and digests are good is still a good layer");
        assert_eq!(outcome.attestations_carried, 0);
        let note = outcome
            .attestation_note
            .expect("the loss must be reported, never swallowed");
        assert!(note.contains("dropped them"), "note: {note}");
    }

    /// REQ-FIRSTCONTACT-001 end to end, through install().
    ///
    /// A machine with no marks file — a fresh checkout, a new CI runner — used
    /// to accept ANY counter on a line it had never seen, because there was
    /// nothing to compare against. That is the one moment anti-rollback
    /// protects nobody, and it is the moment worth attacking.
    // rivet: verifies REQ-FIRSTCONTACT-001
    #[test]
    fn a_new_machine_refuses_a_layer_below_the_realms_signed_floor() {
        use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, mut marks) = setup();

        let (bytes, blobs) = july(); // 2026.07.0, counter 1
        let mut source = MemorySource::new().with_manifest(&bytes);
        for (d, b) in &blobs {
            source = source.with_blob(d, b);
        }
        let source = source
            .with_line_index(
                LineIndex {
                    line: "2026.07".into(),
                    counter: 1,
                    issued_at: "2026-08-07T00:00:00Z".into(),
                    layers: vec![IndexedLayer {
                        layer: "2026.07.0".into(),
                        digest: manifest_digest(&bytes),
                        channel: "qualified".into(),
                        counter: 1,
                    }],
                }
                .sign(&sk, "root-1")
                .unwrap()
                .as_bytes(),
            )
            // The realm signs a floor of 5 for this line; the layer is 1.
            .with_line_status(
                crate::linestatus::LineStatus {
                    line: "2026.07".into(),
                    counter: 1,
                    issued_at: "2026-08-07T00:00:00Z".into(),
                    min_counter: Some(5),
                    support_until: None,
                    yanked: Default::default(),
                    known_problems: Vec::new(),
                }
                .sign(&sk, "root-1")
                .unwrap()
                .as_bytes(),
            );

        let policy = InstallPolicy {
            index: Some(IndexPolicy {
                realm: "acme",
                root_public_key: &pk,
                required: true,
            }),
            ..policy()
        };
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .expect_err("a first contact below the signed floor must be refused");
        match &err {
            InstallError::BelowFloor {
                line,
                presented,
                floor,
            } => {
                assert_eq!(line, "2026.07");
                assert_eq!(*presented, 1);
                assert_eq!(*floor, 5);
            }
            other => panic!("expected BelowFloor, got {other:?}"),
        }
        // And the refusal explains why a NEW machine is the interesting case.
        assert!(err.to_string().contains("never installed"), "{err}");
    }

    /// The same layer, same realm, no stated floor: unchanged behaviour, so a
    /// realm that has not adopted this keeps installing exactly as before.
    // rivet: verifies REQ-FIRSTCONTACT-001
    #[test]
    fn a_line_whose_realm_states_no_floor_installs_as_it_always_did() {
        use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, mut marks) = setup();

        let (bytes, blobs) = july();
        let mut source = MemorySource::new().with_manifest(&bytes);
        for (d, b) in &blobs {
            source = source.with_blob(d, b);
        }
        let source = source
            .with_line_index(
                LineIndex {
                    line: "2026.07".into(),
                    counter: 1,
                    issued_at: "2026-08-07T00:00:00Z".into(),
                    layers: vec![IndexedLayer {
                        layer: "2026.07.0".into(),
                        digest: manifest_digest(&bytes),
                        channel: "qualified".into(),
                        counter: 1,
                    }],
                }
                .sign(&sk, "root-1")
                .unwrap()
                .as_bytes(),
            )
            .with_line_status(
                crate::linestatus::LineStatus {
                    line: "2026.07".into(),
                    counter: 1,
                    issued_at: "2026-08-07T00:00:00Z".into(),
                    min_counter: None,
                    support_until: None,
                    yanked: Default::default(),
                    known_problems: Vec::new(),
                }
                .sign(&sk, "root-1")
                .unwrap()
                .as_bytes(),
            );

        let policy = InstallPolicy {
            index: Some(IndexPolicy {
                realm: "acme",
                root_public_key: &pk,
                required: true,
            }),
            ..policy()
        };
        install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .expect("no stated floor must not change anything");
    }

    // rivet: verifies REQ-INDEXAUTH-001
    #[test]
    fn install_raises_the_mark_from_the_index_even_when_the_layer_is_hidden() {
        // Clause 4 end to end, through install() — the Uptane property. The
        // registry serves ONLY the old layer and its signature is perfect. The
        // realm's signed index says a newer one exists. Without this, the
        // registry's silence sets the bar, and the hidden layer's counter
        // never constrains anything.
        use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, mut marks) = setup();

        let (bytes, blobs) = july(); // 2026.07.0, counter 1
        let mut source = MemorySource::new().with_manifest(&bytes);
        for (d, b) in &blobs {
            source = source.with_blob(d, b);
        }
        let source = source.with_line_index(
            LineIndex {
                line: "2026.07".into(),
                counter: 1,
                issued_at: "2026-08-07T00:00:00Z".into(),
                layers: vec![
                    IndexedLayer {
                        layer: "2026.07.0".into(),
                        digest: manifest_digest(&bytes),
                        channel: "qualified".into(),
                        counter: 1,
                    },
                    // The layer the registry is not serving.
                    IndexedLayer {
                        layer: "2026.07.9".into(),
                        digest: "sha256:hidden".into(),
                        channel: "qualified".into(),
                        counter: 42,
                    },
                ],
            }
            .sign(&sk, "root-1")
            .unwrap()
            .as_bytes(),
        );

        let policy = InstallPolicy {
            index: Some(IndexPolicy {
                realm: "acme",
                root_public_key: &pk,
                required: true,
            }),
            ..policy()
        };
        let outcome = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .expect("a pinned layer must install even when the line has moved on");

        // The consumer LEARNS what the realm says the line contains, even
        // though the registry never offered it.
        assert_eq!(
            outcome.index_high_water,
            Some(42),
            "the realm's assertion must reach the consumer even when the source \
             withheld the layer it refers to"
        );
        // …and the pinned layer still installed. This assertion is the whole
        // correction: an earlier draft raised the ENFORCEMENT mark to 42, and
        // this very install then failed with `rollback refused: presented 1,
        // high_water 42` — a deliberately-pinned layer made uninstallable by
        // someone else publishing. varve exists to freeze toolchains; a
        // freshness control that unfreezes them is not a fix.
        assert_eq!(outcome.layer.to_string(), "2026.07.0");
        assert_eq!(
            marks.mark(&"2026.07".parse().unwrap()),
            Some(1),
            "the mark records what this machine ACCEPTED, not what exists"
        );
    }

    // rivet: verifies REQ-INDEXAUTH-001
    #[test]
    fn a_replayed_older_index_is_refused_on_the_next_install_not_only_in_theory() {
        // Clause 2 through the pipeline. `check` has always refused a
        // regression against a `cached` document — and install passed `None`
        // for `cached`, so the rule could not fire on any real machine: there
        // was nothing that REMEMBERED. This test installs twice, and the
        // second source replays a superseded index.
        use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = july();

        let signed_index = |counter: u64| {
            LineIndex {
                line: "2026.07".into(),
                counter,
                issued_at: "2026-08-07T00:00:00Z".into(),
                layers: vec![IndexedLayer {
                    layer: "2026.07.0".into(),
                    digest: manifest_digest(&bytes),
                    channel: "qualified".into(),
                    counter: 1,
                }],
            }
            .sign(&sk, "root-1")
            .unwrap()
        };
        // Counting the blob fetches is what makes this test able to tell WHERE
        // the refusal happened. Without it the test passed with `check` handed
        // `None` for the cached document, because the cache's own write-time
        // regression guard raised the identical error — after the layer had
        // been fetched, laid down, and the mark advanced. Same message, wholly
        // different behaviour, and the version that only compared messages
        // could not see the difference.
        struct CountingSource {
            inner: MemorySource,
            blob_fetches: std::cell::Cell<usize>,
        }
        impl LayerSource for CountingSource {
            fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
                self.inner.fetch_manifest(layer)
            }
            fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
                self.blob_fetches.set(self.blob_fetches.get() + 1);
                self.inner.fetch_blob(digest)
            }
            fn fetch_line_index(&self, line: &str) -> Result<Option<Vec<u8>>, SourceError> {
                self.inner.fetch_line_index(line)
            }
            fn served_layers(&self, line: &str) -> Result<Option<Vec<String>>, SourceError> {
                self.inner.served_layers(line)
            }
        }
        let source_with = |envelope: &str| {
            let mut s = MemorySource::new().with_manifest(&bytes);
            for (d, b) in &blobs {
                s = s.with_blob(d, b);
            }
            CountingSource {
                inner: s.with_line_index(envelope.as_bytes()),
                blob_fetches: std::cell::Cell::new(0),
            }
        };
        let policy = InstallPolicy {
            index: Some(IndexPolicy {
                realm: "acme",
                root_public_key: &pk,
                required: true,
            }),
            ..policy()
        };

        install(
            &pin("2026.07.0"),
            &source_with(&signed_index(9)),
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .expect("the first install accepts index #9");

        // A second source — a stale mirror, or an attacker who kept a copy of
        // a pre-yank index — offers #4. Everything about it verifies.
        let replay = source_with(&signed_index(4));
        let err = install(
            &pin("2026.07.0"),
            &replay,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .expect_err("a superseded index must not be replayable over the held one");
        assert_eq!(
            replay.blob_fetches.get(),
            0,
            "the index check runs BEFORE anything is fetched or laid down — a \
             refusal discovered only when the cache was written would already \
             have installed the layer and advanced the mark"
        );
        assert!(
            matches!(
                err,
                InstallError::Index(crate::lineindex::IndexError::Stale {
                    presented: 4,
                    cached: 9,
                    ..
                })
            ),
            "got: {err}"
        );
        assert!(
            err.to_string().contains('4') && err.to_string().contains('9'),
            "names both counters: {err}"
        );

        // …and the held document is still #9, so a third attempt at the same
        // replay fails the same way rather than sliding down.
        assert_eq!(
            crate::lineindex::IndexCache::at_root(store.root())
                .load("2026.07")
                .unwrap()
                .unwrap()
                .counter,
            9
        );
    }

    // rivet: verifies REQ-INDEXAUTH-001
    #[test]
    fn install_refuses_a_source_that_hides_an_indexed_layer() {
        // Clause 3 through install(). Every byte this source serves verifies;
        // the defect is what it withholds.
        use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, mut marks) = setup();

        let (bytes, blobs) = july();
        let mut source = MemorySource::new().with_manifest(&bytes);
        for (d, b) in &blobs {
            source = source.with_blob(d, b);
        }
        // It admits to serving only the old layer, while the realm's index
        // names another.
        let source = source.serving(&["2026.07.0"]).with_line_index(
            LineIndex {
                line: "2026.07".into(),
                counter: 1,
                issued_at: "2026-08-07T00:00:00Z".into(),
                layers: vec![IndexedLayer {
                    layer: "2026.07.5".into(),
                    digest: "sha256:withheld".into(),
                    channel: "qualified".into(),
                    counter: 5,
                }],
            }
            .sign(&sk, "root-1")
            .unwrap()
            .as_bytes(),
        );

        let policy = InstallPolicy {
            index: Some(IndexPolicy {
                realm: "acme",
                root_public_key: &pk,
                required: true,
            }),
            ..policy()
        };
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptAll,
            &store,
            &mut marks,
            &policy,
        )
        .expect_err("a source hiding an indexed layer must be refused");
        let msg = err.to_string();
        assert!(msg.contains("2026.07.5"), "names the hidden layer: {msg}");
        // Nothing was laid down on the strength of a dishonest listing.
        assert!(store.list().unwrap().is_empty(), "no install on a refusal");
    }

    // ---- REQ-ROLLBACK-002: a digest in the pin is consent --------------------

    /// Two layers of ONE line: 2026.07.0 (counter 1) and 2026.07.1 (counter 2),
    /// and a source that serves both.
    struct Consent {
        _tmp: tempfile::TempDir,
        store: Store,
        marks: HighWaterMarks,
        older: Vec<u8>,
        newer: Vec<u8>,
        source: MemorySource,
        sk: Vec<u8>,
        pk: Vec<u8>,
    }

    fn layer_of(name: &str, counter: u64, tag: &str) -> (Vec<u8>, Vec<(String, Vec<u8>)>) {
        let blob = format!("{tag}-tool").into_bytes();
        let blobs = vec![(manifest_digest(&blob), blob)];
        let bytes = manifest_with_tools(
            name,
            "qualified",
            counter,
            "2026-07-31T09:14:00Z",
            &[("synth", &blobs[0].0)],
        );
        (bytes, blobs)
    }

    fn consent_fixture() -> Consent {
        let (sk, pk) = crate::verify::generate_root_keypair();
        let (_tmp, store, marks) = setup();
        let (older, ob) = layer_of("2026.07.0", 1, "old");
        let (newer, nb) = layer_of("2026.07.1", 2, "new");
        let mut source = MemorySource::new()
            .with_manifest(&older)
            .with_manifest(&newer);
        for (d, b) in ob.iter().chain(nb.iter()) {
            source = source.with_blob(d, b);
        }
        Consent {
            _tmp,
            store,
            marks,
            older,
            newer,
            source,
            sk,
            pk,
        }
    }

    fn status_for(
        line: &str,
        support_until: Option<&str>,
        yanked: &[(&str, &str)],
        sk: &[u8],
    ) -> Vec<u8> {
        status_numbered(1, line, support_until, yanked, sk)
    }

    fn status_numbered(
        counter: u64,
        line: &str,
        support_until: Option<&str>,
        yanked: &[(&str, &str)],
        sk: &[u8],
    ) -> Vec<u8> {
        crate::linestatus::LineStatus {
            line: line.into(),
            counter,
            issued_at: "2026-08-01T00:00:00Z".into(),
            support_until: support_until.map(str::to_string),
            min_counter: None,
            yanked: yanked
                .iter()
                .map(|(l, r)| (l.to_string(), r.to_string()))
                .collect(),
            known_problems: Vec::new(),
        }
        .sign(sk, "root-1")
        .unwrap()
        .as_bytes()
        .to_vec()
    }

    fn digest_pin(layer: &str, digest: &str) -> Pin {
        Pin::parse(
            &format!(
                "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\ndigest = \"{digest}\"\n"
            ),
            "varve.toml",
        )
        .unwrap()
    }

    /// Accepts every manifest and names a root, as `PinnedKeyVerifier` does.
    struct AcceptWithRoot<'a>(&'a [u8]);
    impl ManifestVerifier for AcceptWithRoot<'_> {
        fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
            Ok(fetched.to_vec())
        }
        fn root_public_key(&self) -> Option<&[u8]> {
            Some(self.0)
        }
    }

    /// Install the NEWER layer by name, advancing the machine's mark to 2.
    fn see_the_newer(f: &mut Consent) {
        install(
            &pin("2026.07.1"),
            &f.source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .unwrap();
        assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_digest_pinned_older_layer_the_line_supports_installs_past_the_mark() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source =
            source.with_line_status(&status_for("2026.07", Some("2027-01-01"), &[], &f.sk));
        let digest = manifest_digest(&f.older);
        let outcome = install(
            &digest_pin("2026.07.0", &digest),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect("a digest-pinned, supported, unyanked layer installs past the mark");
        assert_eq!(outcome.counter, 1);
        let consent = outcome.digest_consent.expect("the install must say so");
        assert_eq!(consent.high_water, 2);
        assert_eq!(consent.presented, 1);
        assert_eq!(consent.digest, digest);
        let note = consent.note();
        for needle in [
            digest.as_str(),
            "counter 1",
            "counter 2",
            "2026.07",
            "supported",
            "not yanked",
        ] {
            assert!(note.contains(needle), "{needle} missing from: {note}");
        }
        // Clause 3: installing the older layer must NOT lower the mark.
        assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
        assert!(f.store.get(&digest).unwrap().is_some());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn an_install_at_or_above_the_mark_carries_no_consent_note() {
        let mut f = consent_fixture();
        let digest = manifest_digest(&f.newer);
        let outcome = install(
            &digest_pin("2026.07.1", &digest),
            &f.source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .unwrap();
        assert_eq!(outcome.digest_consent, None);
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn resolution_by_name_keeps_the_refusal_even_with_a_supporting_line_status() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
        let err = install(
            &pin("2026.07.0"),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a name is not consent");
        assert!(
            matches!(
                err,
                InstallError::Rollback {
                    presented: 1,
                    high_water: 2,
                    ..
                }
            ),
            "{err:?}"
        );
        assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_yank_is_not_overridden_by_a_digest() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for(
            "2026.07",
            None,
            &[("2026.07.0", "regression in synth")],
            &f.sk,
        ));
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a yanked layer stays refused");
        let msg = err.to_string();
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{msg}"
        );
        assert!(
            msg.contains("YANKED") && msg.contains("regression in synth"),
            "{msg}"
        );
        assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn an_expired_support_window_is_not_overridden_by_a_digest() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        // policy().now is 2026-08-07.
        let source =
            source.with_line_status(&status_for("2026.07", Some("2026-08-06"), &[], &f.sk));
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("an out-of-support layer stays refused");
        let msg = err.to_string();
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{msg}"
        );
        assert!(msg.contains("out of support"), "{msg}");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn the_last_supported_day_still_consents() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source =
            source.with_line_status(&status_for("2026.07", Some("2026-08-07"), &[], &f.sk));
        install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect("the horizon day is still supported");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn no_line_status_at_all_refuses_and_says_consent_needs_one() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &f.source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("the pin alone is not trusted");
        let msg = err.to_string();
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{msg}"
        );
        assert!(
            msg.contains("digest consent needs a verifiable line-status"),
            "{msg}"
        );
        assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_verifier_that_names_no_root_cannot_verify_a_status_so_it_is_refused() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptAll,
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("no root, no consent");
        assert!(err.to_string().contains("no trust root"), "{err}");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_status_signed_by_another_root_gives_no_consent() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let (other_sk, _) = crate::verify::generate_root_keypair();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for("2026.07", None, &[], &other_sk));
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a forged status must not consent");
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{err}"
        );
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_status_for_another_line_gives_no_consent() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for("2026.06", None, &[], &f.sk));
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a status of another line says nothing about this one");
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{err}"
        );
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_cached_line_status_consents_when_the_source_carries_none() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let envelope = status_for("2026.07", None, &[], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&envelope, &f.pk).unwrap();
        crate::linestatus::StatusCache::at_root(f.store.root())
            .update(&line, &envelope, &doc)
            .unwrap();
        let outcome = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &f.source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect("an offline machine that cached a verified status may consent");
        assert!(outcome.digest_consent.is_some());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_registry_replaying_an_older_status_cannot_undo_a_cached_yank() {
        // The attacker REQ-ROLLBACK-001 exists for controls the registry. A
        // yank issued at status #2 is cached here; the registry then serves
        // the validly-signed status #1 from before the yank. Consent must
        // follow the NEWER signed word, or a replay re-enables a yanked layer.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let yank = status_numbered(2, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&yank, &f.pk).unwrap();
        crate::linestatus::StatusCache::at_root(f.store.root())
            .update(&line, &yank, &doc)
            .unwrap();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_numbered(1, "2026.07", None, &[], &f.sk));
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("an older served status must not outrank the cached yank");
        assert!(err.to_string().contains("YANKED"), "{err}");
        assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_signed_floor_is_not_overridden_by_a_digest() {
        // The line-status's `min-counter` is the line's own statement that no
        // layer below it is acceptable. Consent is the line standing behind a
        // layer; a floor above it says the line does not.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let mut doc = crate::linestatus::LineStatus::verify_and_parse(
            &status_for("2026.07", None, &[], &f.sk),
            &f.pk,
        )
        .unwrap();
        doc.min_counter = Some(2);
        let envelope = doc.sign(&f.sk, "root-1").unwrap().as_bytes().to_vec();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&envelope);
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a counter below the signed floor stays refused");
        assert!(err.to_string().contains("floor"), "{err}");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_layer_exactly_at_the_signed_floor_still_consents() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let mut doc = crate::linestatus::LineStatus::verify_and_parse(
            &status_for("2026.07", None, &[], &f.sk),
            &f.pk,
        )
        .unwrap();
        doc.min_counter = Some(1); // the older layer presents counter 1
        let envelope = doc.sign(&f.sk, "root-1").unwrap().as_bytes().to_vec();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&envelope);
        let outcome = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect("a floor AT the layer's counter does not exclude it");
        assert!(outcome.digest_consent.is_some());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn verifys_offline_judgment_reads_the_cache_and_names_why() {
        // `varve verify` calls this with no source; it must agree with install.
        let f = consent_fixture();
        let older = LayerManifest::parse(&f.older).unwrap();
        let now = "2026-08-07T00:00:00Z";
        let none = cached_consent_why_not(&older, f.store.root(), &f.pk, now)
            .expect("nothing cached is not consent");
        assert!(
            none.contains("none is available for line 2026.07"),
            "{none}"
        );

        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let cache = crate::linestatus::StatusCache::at_root(f.store.root());
        let ok = status_numbered(1, "2026.07", None, &[], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&ok, &f.pk).unwrap();
        cache.update(&line, &ok, &doc).unwrap();
        assert_eq!(
            cached_consent_why_not(&older, f.store.root(), &f.pk, now),
            None
        );

        let yank = status_numbered(2, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&yank, &f.pk).unwrap();
        cache.update(&line, &yank, &doc).unwrap();
        let why = cached_consent_why_not(&older, f.store.root(), &f.pk, now)
            .expect("a cached yank refuses");
        assert!(why.contains("YANKED") && why.contains("bad"), "{why}");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_newer_served_status_outranks_an_older_cached_one() {
        // The other direction: a cached yank later LIFTED by a newer status
        // the registry serves. The newer word wins here too.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let yank = status_numbered(1, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&yank, &f.pk).unwrap();
        crate::linestatus::StatusCache::at_root(f.store.root())
            .update(&line, &yank, &doc)
            .unwrap();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_numbered(2, "2026.07", None, &[], &f.sk));
        let outcome = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect("a newer signed status that lifts the yank consents");
        assert!(outcome.digest_consent.is_some());
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_cached_status_that_yanks_the_layer_refuses_offline() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let envelope = status_for("2026.07", None, &[("2026.07.0", "bad")], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&envelope, &f.pk).unwrap();
        crate::linestatus::StatusCache::at_root(f.store.root())
            .update(&line, &envelope, &doc)
            .unwrap();
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &f.source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("the cached yank binds");
        assert!(err.to_string().contains("YANKED"), "{err}");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_pin_naming_one_layer_with_anothers_digest_is_refused_not_consented() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
        // Names 2026.07.0 but carries the digest of 2026.07.1.
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.newer)),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a digest that is not the named layer's is refused");
        assert!(matches!(err, InstallError::LayerMismatch { .. }), "{err}");
        // And a digest the source cannot match against its own bytes.
        let wrong = format!("sha256:{}", "ab".repeat(32));
        assert!(
            install(
                &digest_pin("2026.07.0", &wrong),
                &source,
                &AcceptWithRoot(&f.pk),
                &f.store,
                &mut f.marks,
                &policy(),
            )
            .is_err()
        );
        assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_digest_named_by_a_composition_is_not_consent() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
        let err = install_by_digest(
            &manifest_digest(&f.older),
            &source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("an include is a signer's choice, not this project's consent");
        assert!(matches!(err, InstallError::Rollback { .. }), "{err:?}");
    }

    // rivet: verifies REQ-ROLLBACK-002
    #[test]
    fn a_cached_status_filed_under_the_wrong_line_gives_no_consent() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        // Validly signed, but about line 2026.06 — cached under 2026.07.
        let envelope = status_for("2026.06", None, &[], &f.sk);
        let doc = crate::linestatus::LineStatus::verify_and_parse(&envelope, &f.pk).unwrap();
        crate::linestatus::StatusCache::at_root(f.store.root())
            .update(&line, &envelope, &doc)
            .unwrap();
        let err = install(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            &f.source,
            &AcceptWithRoot(&f.pk),
            &f.store,
            &mut f.marks,
            &policy(),
        )
        .expect_err("a status about another line says nothing about this one");
        assert!(err.to_string().contains("covers line 2026.06"), "{err}");
    }
}