varve-core 0.45.0

Layer manifests, resolution, the core store, and verification wiring for varve
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
//! 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 trust this verifier judges by, 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 trust and no other, each
    /// under the role its payload type belongs to (REQ-KEYROLES-001).
    /// `None` means "cannot say", which consumers must read as "cannot verify".
    fn trust(&self) -> Option<&crate::keyroles::RealmTrust> {
        None
    }
}

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

/// Why the omission check could not run against a MIRROR.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OmissionSkipped {
    /// The mirror carries no line index at all.
    NoIndex,
    /// The mirror carries an index but cannot enumerate the layers it serves
    /// (a directory or OCI layout), so the index has nothing to be compared
    /// with.
    CannotEnumerate,
}

/// 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>,
    /// The source was a MIRROR and carried no line index, so the omission
    /// check (a layer the signed index names but the source hides) could not
    /// run against it. Reported, never silent: the install proceeds only
    /// because this machine has local history bounding what a mirror says.
    pub omission_check_skipped: Option<OmissionSkipped>,
    /// 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(
        "first contact with line {line} needs the realm's primary: a mirror cannot prove it is \
         current, and this machine has no history (no high-water mark, no cached line-status) to \
         bound it"
    )]
    FirstContactNeedsPrimary { line: String },
    #[error(
        "first contact with line {line}'s index needs the realm's primary: this machine has no \
         cached line index for it, so nothing bounds what a mirror says is newest"
    )]
    IndexFirstContactNeedsPrimary { line: String },
    #[error(
        "an install by digest from a mirror must know the layer's line before the mirror is \
         contacted, and it cannot: {why}. Take it from the realm's primary"
    )]
    LineUnknownForMirror { 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 no high-water mark for {line} (it has never installed from it, or its \
         marks were reset), so it has no installed 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, served or cached by an earlier install, \
         so a consumer with no mark 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),
}

impl InstallError {
    /// May ANOTHER source of the same realm be asked after this failure?
    /// (REQ-MIRROR-002 clause 2.)
    ///
    /// Only when this source's BYTES are the problem: unavailable, not
    /// authentic, malformed, or substituted. A verified verdict about genuine
    /// bytes (rollback, floor, no platform entry) or a local failure is
    /// TERMINAL: asking a lagging mirror afterwards would hand the same
    /// machine a second chance against a lower bar, and failover itself would
    /// become the freeze/rollback attack.
    ///
    /// An exhaustive `match` with no `_` arm, so a new variant cannot be added
    /// without deciding which side of that line it is on.
    pub fn fails_over(&self) -> bool {
        match self {
            InstallError::Index(e) => e.fails_over(),
            InstallError::Source(_)
            | InstallError::Verify(_)
            | InstallError::Manifest(_)
            | InstallError::DigestMismatch { .. }
            | InstallError::LayerMismatch { .. }
            | InstallError::BlobDigestMismatch { .. } => true,
            InstallError::Rollback { .. }
            | InstallError::RollbackConsentRefused { .. }
            | InstallError::BelowFloor { .. }
            | InstallError::FirstContactNeedsPrimary { .. }
            | InstallError::IndexFirstContactNeedsPrimary { .. }
            | InstallError::LineUnknownForMirror { .. }
            | InstallError::ChannelMismatch { .. }
            | InstallError::NoPlatformEntry { .. }
            | InstallError::UnnamedEntry { .. }
            | InstallError::Store(_)
            | InstallError::State(_) => false,
        }
    }
}

/// 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> {
    install_by_digest_from(
        digest,
        source,
        verifier,
        store,
        marks,
        policy,
        DigestRole::Primary,
    )
}

/// Which source an install-by-digest is reading from. A digest names no line,
/// so a MIRROR carries the line the caller expects (from the include that
/// named the digest) and the first-contact refusal is decided on it BEFORE the
/// mirror is asked anything.
#[derive(Debug, Clone)]
pub enum DigestRole<'a> {
    /// The realm's primary (or its only source).
    Primary,
    /// A mirror. `expected_line` is the line of the layer the digest should
    /// turn out to be, if the caller knows it. `Err(why)` says why the line
    /// cannot be known before fetching (the include names no layer, or names
    /// one that is not a valid layer id); a mirror is then refused, because no
    /// history can be shown for an unknown line.
    Mirror {
        expected_line: Result<&'a crate::layer::Line, String>,
    },
}

/// [`install_by_digest`] from a source that is, or is not, the realm's
/// PRIMARY. A non-primary source (a mirror, asked after the primary failed)
/// may not relax a protection: see [`install_from`].
pub fn install_by_digest_from(
    digest: &str,
    source: &dyn LayerSource,
    verifier: &dyn ManifestVerifier,
    store: &Store,
    marks: &mut HighWaterMarks,
    policy: &InstallPolicy<'_>,
    role: DigestRole<'_>,
) -> Result<InstallOutcome, InstallError> {
    // First contact is decided BEFORE a mirror is contacted: reading the
    // manifest here would otherwise be a fetch from a source that may not be
    // allowed to answer. The line comes from the caller (the include that
    // named this digest); `install_inner` re-checks it against the real
    // manifest's line afterwards.
    let source_is_primary = matches!(role, DigestRole::Primary);
    if let DigestRole::Mirror { expected_line } = &role {
        match expected_line {
            Err(why) => return Err(InstallError::LineUnknownForMirror { why: why.clone() }),
            Ok(line) if !has_local_history(line, store, verifier, marks) => {
                return Err(InstallError::FirstContactNeedsPrimary {
                    line: line.to_string(),
                });
            }
            Ok(_) => {}
        }
    }
    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,
        Via {
            digest_is_consent: false,
            source_is_primary,
        },
    )
}

/// 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_from(pin, source, verifier, store, marks, policy, true)
}

/// [`install`] from a source that is, or is not, the realm's PRIMARY.
///
/// Once the primary has failed in an attempt, a MIRROR's answer may not RELAX
/// a protection: absence or an older document on a mirror is "unknown", not
/// "none". So from a non-primary source (a) digest CONSENT to go below the
/// mark is refused, because it lifts a protection and the mirror may be
/// lagging a yank, and (b) a FIRST CONTACT (no local history for the line: no
/// high-water mark and no cached line-status) is refused outright with
/// [`InstallError::FirstContactNeedsPrimary`], before anything is fetched,
/// because a mirror cannot prove it is current and nothing bounds it. With
/// history a mirror answers, bounded by the marks and the cached status.
pub fn install_from(
    pin: &Pin,
    source: &dyn LayerSource,
    verifier: &dyn ManifestVerifier,
    store: &Store,
    marks: &mut HighWaterMarks,
    policy: &InstallPolicy<'_>,
    source_is_primary: bool,
) -> Result<InstallOutcome, InstallError> {
    install_inner(
        pin,
        source,
        verifier,
        store,
        marks,
        policy,
        Via {
            digest_is_consent: true,
            source_is_primary,
        },
    )
}

/// How an install reached its source: whether a digest in the pin is consent
/// to go below the mark, and whether the source is the realm's primary.
#[derive(Clone, Copy)]
struct Via {
    digest_is_consent: bool,
    source_is_primary: bool,
}

/// Whether this machine has ANY record of `line`: a high-water mark, or a
/// cached line-status that verifies against the realm's root.
fn has_local_history(
    line: &crate::layer::Line,
    store: &Store,
    verifier: &dyn ManifestVerifier,
    marks: &HighWaterMarks,
) -> bool {
    marks.mark(line).is_some()
        || verifier.trust().is_some_and(|trust| {
            matches!(
                crate::linestatus::StatusCache::at_root(store.root()).load(line, trust),
                Ok(Some(_))
            )
        })
}

fn install_inner(
    pin: &Pin,
    source: &dyn LayerSource,
    verifier: &dyn ManifestVerifier,
    store: &Store,
    marks: &mut HighWaterMarks,
    policy: &InstallPolicy<'_>,
    via: Via,
) -> Result<InstallOutcome, InstallError> {
    let Via {
        digest_is_consent,
        source_is_primary,
    } = via;
    // 0. FIRST CONTACT is answered only by the realm's primary. With no local
    // history for the line (no high-water mark and no cached line-status) a
    // mirror's answer is bounded by nothing: a lagging mirror can serve a
    // genuine but OLD layer with a genuine but OLD status (no raised floor, a
    // pre-demotion channel, no omission check), and this machine has nothing to
    // notice that it is old. Asked before anything is fetched from it.
    //
    // WITH history a mirror's answer is accepted, bounded by the marks and the
    // cached status below as for any source. The residual is the documented
    // one: a machine that has installed before can be served a state no older
    // than it last recorded — including a pre-demotion manifest whose channel
    // still matches — but not a state older than that.
    if !source_is_primary && !has_local_history(pin.layer.line(), store, verifier, marks) {
        return Err(InstallError::FirstContactNeedsPrimary {
            line: pin.layer.line().to_string(),
        });
    }
    // 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;
    let mut omission_check_skipped: Option<OmissionSkipped> = 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)?;
        // A mirror with no index leaves the omission check unable to run: that
        // is UNKNOWN, not "nothing hidden", and it is reported (D4).
        let served = source.served_layers(&line_str)?;
        // ... and so is a mirror whose index cannot be compared with a listing
        // (it cannot enumerate what it serves): the check cannot run either.
        if !source_is_primary {
            omission_check_skipped = if envelope.is_none() {
                Some(OmissionSkipped::NoIndex)
            } else if served.is_none() {
                Some(OmissionSkipped::CannotEnumerate)
            } else {
                None
            };
        }
        // 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.
    //
    // With NO mark the floor is the one stated by the HIGHER-counter verified
    // status among the one this machine already CACHED and the one the source
    // serves. A source can therefore only raise the bar: an older status (a
    // lower or absent `min_counter`), no status, or an unverifiable one leaves
    // the recorded floor in force. That is what bounds a mirror's answer by
    // what this machine has already recorded, primary or not.
    let mut first_contact_floor: Option<u64> = None;
    if marks.mark(line).is_none()
        && let Some(index_policy) = &policy.index
    {
        let cached = crate::linestatus::StatusCache::at_root(store.root())
            .load(line, index_policy.trust)
            .ok()
            .flatten()
            .filter(|doc| doc.line == line_str);
        let served = source
            .fetch_line_status(&layer_ref)?
            .and_then(|bytes| {
                crate::linestatus::LineStatus::verify_and_parse(&bytes, index_policy.trust).ok()
            })
            .filter(|doc| doc.line == line_str);
        first_contact_floor = [cached, served]
            .into_iter()
            .flatten()
            .max_by_key(|doc| doc.counter)
            .and_then(|doc| 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(_), true) if !source_is_primary => {
                // Consent LIFTS the mark. A mirror asked after the primary
                // failed may be lagging a yank, so it cannot grant it.
                return Err(InstallError::RollbackConsentRefused {
                    line,
                    presented,
                    high_water,
                    why: "digest consent is only taken from the realm's primary source, and this \
                          one is a mirror (a mirror may be lagging a yank the primary has made)"
                        .to_string(),
                });
            }
            (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,
        omission_check_skipped,
        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.
///
/// EVERY refusal here is terminal for failover (`InstallError::fails_over`),
/// including "this source carries no line-status". Consent LIFTS a protection
/// (the machine's own rollback mark), so it must not be obtainable by asking
/// another source: a lagging mirror's older line-status, from before a yank,
/// could grant consent the primary would have refused. The cost is chosen:
/// a digest-pinned rollback install is unavailable while the primary's status
/// cannot be had.
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(trust) = verifier.trust() 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,
        trust,
        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, trust) {
        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,
    trust: &crate::keyroles::RealmTrust,
    now: &str,
) -> Option<String> {
    let line = manifest.layer.line();
    match crate::linestatus::StatusCache::at_root(store_root).load(line, trust) {
        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 failover_class_tests {
    use super::*;

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn verdicts_about_genuine_bytes_and_local_failures_never_fail_over() {
        let terminal = [
            InstallError::Rollback {
                line: "l".into(),
                presented: 1,
                high_water: 2,
            },
            // A realm-signed verdict about the requested layer (a demotion),
            // not a fault of the source that served it.
            InstallError::ChannelMismatch {
                pinned: "a".into(),
                got: "b".into(),
            },
            InstallError::FirstContactNeedsPrimary { line: "l".into() },
            InstallError::IndexFirstContactNeedsPrimary { line: "l".into() },
            InstallError::LineUnknownForMirror { why: "w".into() },
            InstallError::RollbackConsentRefused {
                line: "l".into(),
                presented: 1,
                high_water: 2,
                why: "w".into(),
            },
            InstallError::BelowFloor {
                line: "l".into(),
                presented: 1,
                floor: 2,
            },
            InstallError::NoPlatformEntry {
                layer: "l".into(),
                platform: "p".into(),
            },
            InstallError::UnnamedEntry { digest: "d".into() },
            InstallError::State(RollbackError::Io {
                path: "p".into(),
                source: std::io::Error::other("x"),
            }),
        ];
        for e in &terminal {
            assert!(!e.fails_over(), "{e} must be terminal");
        }
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn unavailable_unauthentic_or_substituted_bytes_fail_over() {
        let over = [
            InstallError::Source(SourceError::Transport("down".into())),
            InstallError::Source(SourceError::NotFound("x".into())),
            InstallError::DigestMismatch {
                pinned: "a".into(),
                got: "b".into(),
            },
            InstallError::LayerMismatch {
                pinned: "a".into(),
                got: "b".into(),
            },
            InstallError::BlobDigestMismatch {
                tool: "t".into(),
                digest: "d".into(),
            },
            InstallError::Manifest(ManifestError::Json("x".into())),
            InstallError::Index(crate::lineindex::IndexError::Payload("x".into())),
        ];
        for e in &over {
            assert!(e.fails_over(), "{e} must fail over");
        }
        let stale = InstallError::Index(crate::lineindex::IndexError::Stale {
            line: "l".into(),
            presented: 1,
            cached: 2,
        });
        assert!(
            stale.fails_over(),
            "a later source is judged against the same local cache, so it can never pass below it"
        );
    }
}

#[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",
            &crate::keyroles::test_support::rt(&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",
                trust: crate::keyroles::test_support::leak_rt(&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",
                trust: crate::keyroles::test_support::leak_rt(&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",
                trust: crate::keyroles::test_support::leak_rt(&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",
                trust: crate::keyroles::test_support::leak_rt(&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",
                trust: crate::keyroles::test_support::leak_rt(&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(crate::keyroles::RealmTrust);
    impl ManifestVerifier for AcceptWithRoot {
        fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
            Ok(fetched.to_vec())
        }
        fn trust(&self) -> Option<&crate::keyroles::RealmTrust> {
            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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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-MIRROR-002
    #[test]
    fn every_refusal_of_digest_consent_is_terminal_so_no_mirror_can_grant_it() {
        // Consent LIFTS a protection (the machine's own rollback mark), so it
        // must not be obtainable by asking another source: a lagging mirror's
        // older line-status, from before a yank, could grant what the primary
        // would refuse. Availability is the price, and it is chosen.
        let refusal = |f: &mut Consent, source: MemorySource, v: &dyn ManifestVerifier| {
            install(
                &digest_pin("2026.07.0", &manifest_digest(&f.older)),
                &source,
                v,
                &f.store,
                &mut f.marks,
                &policy(),
            )
            .expect_err("refused")
        };
        // No status carried by this source.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let pk = f.pk.clone();
        let err = refusal(
            &mut f,
            source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
        );
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{err}"
        );
        assert!(
            !err.fails_over(),
            "an absent status must not send us elsewhere: {err}"
        );

        // A status that does not verify.
        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())
            .with_line_status(&status_for("2026.07", None, &[], &other_sk));
        let pk = f.pk.clone();
        let err = refusal(
            &mut f,
            source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
        );
        assert!(
            !err.fails_over(),
            "an unverifiable status must not send us elsewhere: {err}"
        );

        // A verified yank, a verified lapsed window, and no trust root.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new()).with_line_status(
            &status_for("2026.07", None, &[("2026.07.0", "regression")], &f.sk),
        );
        let pk = f.pk.clone();
        let err = refusal(
            &mut f,
            source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
        );
        assert!(!err.fails_over(), "a verified yank is terminal: {err}");

        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new())
            .with_line_status(&status_for("2026.07", Some("2026-08-06"), &[], &f.sk));
        let pk = f.pk.clone();
        let err = refusal(
            &mut f,
            source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
        );
        assert!(!err.fails_over(), "a verified expiry is terminal: {err}");

        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new())
            .with_line_status(&status_for("2026.07", None, &[], &f.sk));
        let err = refusal(&mut f, source, &AcceptAll);
        assert!(!err.fails_over(), "no root is local: {err}");
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_mirror_is_never_asked_to_consent_even_when_its_status_would() {
        // The status SUPPORTS the layer, so from the primary this installs
        // (see `a_cached_line_status_consents...` and `the_last_supported_day`).
        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 pin = digest_pin("2026.07.0", &manifest_digest(&f.older));
        let ok = install_from(
            &pin,
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
            &f.store,
            &mut f.marks,
            &policy(),
            true,
        );
        assert!(ok.is_ok(), "the primary may grant consent: {ok:?}");

        // The same pin, same status, from a MIRROR: refused, and terminal.
        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_from(
            &pin,
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
            &f.store,
            &mut f.marks,
            &policy(),
            false,
        )
        .expect_err("a mirror cannot grant consent");
        assert!(
            matches!(err, InstallError::RollbackConsentRefused { .. }),
            "{err}"
        );
        assert!(
            err.to_string()
                .contains("only taken from the realm's primary"),
            "{err}"
        );
        assert!(!err.fails_over());
        assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
    }

    fn first_contact(
        f: &mut Consent,
        source: &MemorySource,
        primary: bool,
    ) -> Result<InstallOutcome, InstallError> {
        first_contact_from(f, source, primary)
    }

    fn first_contact_from(
        f: &mut Consent,
        source: &dyn LayerSource,
        primary: bool,
    ) -> Result<InstallOutcome, InstallError> {
        let pk = f.pk.clone();
        let policy = InstallPolicy {
            index: Some(crate::lineindex::IndexPolicy {
                realm: "acme",
                trust: crate::keyroles::test_support::leak_rt(&pk),
                required: false,
            }),
            ..policy()
        };
        install_from(
            &digest_pin("2026.07.0", &manifest_digest(&f.older)),
            source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy,
            primary,
        )
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_first_contact_is_refused_to_a_mirror_whatever_status_it_carries() {
        // No mark and no cached status for the line: nothing bounds a mirror.
        // Not even a genuine status that VERIFIES helps: an old one states no
        // raised floor, and the machine cannot tell it is old.
        for status in [
            None,
            Some(("2026.07", false)), // genuine, same line, states no floor
            Some(("2026.07", true)),  // forged
            Some(("2026.06", false)), // another line
        ] {
            let mut f = consent_fixture();
            let (other_sk, _) = crate::verify::generate_root_keypair();
            let mut source = std::mem::replace(&mut f.source, MemorySource::new());
            if let Some((line, forged)) = status {
                let sk = if forged { &other_sk } else { &f.sk };
                source = source.with_line_status(&status_for(line, None, &[], sk));
            }
            let err = first_contact(&mut f, &source, false)
                .expect_err("a mirror must not answer a first contact");
            assert!(
                matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
                "{err}"
            );
            assert!(
                err.to_string()
                    .contains("first contact with line 2026.07 needs the realm's primary"),
                "{err}"
            );
            assert!(!err.fails_over(), "no other mirror can do better");
            assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
        }
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_mirror_is_asked_nothing_before_a_first_contact_is_refused() {
        // The refusal comes before any fetch: a source that panics if touched.
        struct Untouched;
        impl LayerSource for Untouched {
            fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
                panic!("a mirror was asked about a first contact");
            }
            fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, SourceError> {
                panic!("a mirror was asked about a first contact");
            }
        }
        let mut f = consent_fixture();
        let err = first_contact_from(&mut f, &Untouched, false).expect_err("refused");
        assert!(matches!(err, InstallError::FirstContactNeedsPrimary { .. }));
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn the_primary_answers_a_first_contact_and_history_of_either_kind_admits_a_mirror() {
        // The primary may omit the status (a stated, pre-existing residual).
        let mut f = consent_fixture();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        first_contact(&mut f, &source, true).expect("the primary answers a first contact");

        // History as a high-water MARK admits a mirror.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let newer = digest_pin("2026.07.1", &manifest_digest(&f.newer));
        let pk = f.pk.clone();
        let policy = InstallPolicy {
            index: Some(crate::lineindex::IndexPolicy {
                realm: "acme",
                trust: crate::keyroles::test_support::leak_rt(&pk),
                required: false,
            }),
            ..policy()
        };
        let outcome = install_from(
            &newer,
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy,
            false,
        )
        .expect("a mark is history");
        assert_eq!(
            outcome.omission_check_skipped,
            Some(OmissionSkipped::NoIndex),
            "a mirror with no index could not run the omission check"
        );

        // History as a cached LINE-STATUS alone (no mark) also admits one.
        let mut f = consent_fixture();
        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,
            &crate::keyroles::test_support::rt(&f.pk),
        )
        .unwrap();
        crate::linestatus::StatusCache::at_root(f.store.root())
            .update(&line, &envelope, &doc)
            .unwrap();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        first_contact(&mut f, &source, false).expect("a cached status is history");
    }

    /// A status document with a stated `min_counter`, signed by `sk`.
    fn status_with_floor(counter: u64, min_counter: Option<u64>, sk: &[u8]) -> Vec<u8> {
        crate::linestatus::LineStatus {
            line: "2026.07".into(),
            counter,
            issued_at: "2026-08-01T00:00:00Z".into(),
            support_until: None,
            min_counter,
            yanked: Default::default(),
            known_problems: Vec::new(),
        }
        .sign(sk, "root-1")
        .unwrap()
        .into_bytes()
    }

    /// No MARK for the line, but a verified status #3 cached with a raised
    /// floor of 5. Installing layer counter 4 from `source` as the primary or a
    /// mirror: the outcome.
    fn install_four_against_a_cached_floor(
        source_status: Option<Vec<u8>>,
        cached: Vec<u8>,
        pk: &[u8],
        primary: bool,
    ) -> Result<InstallOutcome, InstallError> {
        let (_tmp, store, mut marks) = setup();
        let (bytes, blobs) = layer_of("2026.07.2", 4, "four");
        let mut source = MemorySource::new().with_manifest(&bytes);
        for (d, b) in &blobs {
            source = source.with_blob(d, b);
        }
        if let Some(status) = &source_status {
            source = source.with_line_status(status);
        }
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let doc = crate::linestatus::LineStatus::verify_and_parse(
            &cached,
            &crate::keyroles::test_support::rt(pk),
        )
        .unwrap();
        crate::linestatus::StatusCache::at_root(store.root())
            .update(&line, &cached, &doc)
            .unwrap();
        let policy = InstallPolicy {
            index: Some(crate::lineindex::IndexPolicy {
                realm: "acme",
                trust: crate::keyroles::test_support::leak_rt(pk),
                required: false,
            }),
            ..policy()
        };
        install_from(
            &pin("2026.07.2"),
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(pk)),
            &store,
            &mut marks,
            &policy,
            primary,
        )
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_floor_this_machine_already_recorded_is_not_lowered_by_what_a_source_serves() {
        let (sk, pk) = crate::verify::generate_root_keypair();
        let cached = || status_with_floor(3, Some(5), &sk);
        for primary in [false, true] {
            // The source serves an OLDER status that states no floor.
            let err = install_four_against_a_cached_floor(
                Some(status_with_floor(1, None, &sk)),
                cached(),
                &pk,
                primary,
            )
            .expect_err("counter 4 is below the recorded floor of 5");
            assert!(
                matches!(err, InstallError::BelowFloor { floor: 5, .. }),
                "primary={primary}: {err}"
            );
            // The source serves no status at all.
            let err = install_four_against_a_cached_floor(None, cached(), &pk, primary)
                .expect_err("silence does not lower a recorded floor");
            assert!(
                matches!(err, InstallError::BelowFloor { floor: 5, .. }),
                "primary={primary}: {err}"
            );
            // The source serves a status that does not verify.
            let (other_sk, _) = crate::verify::generate_root_keypair();
            let err = install_four_against_a_cached_floor(
                Some(status_with_floor(9, None, &other_sk)),
                cached(),
                &pk,
                primary,
            )
            .expect_err("a forged status does not lower it either");
            assert!(matches!(err, InstallError::BelowFloor { .. }), "{err}");
        }
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn the_newer_verified_status_decides_the_floor_whichever_side_holds_it() {
        let (sk, pk) = crate::verify::generate_root_keypair();
        // The source serves a NEWER status (#4) with a higher floor: it binds.
        let err = install_four_against_a_cached_floor(
            Some(status_with_floor(4, Some(7), &sk)),
            status_with_floor(3, Some(2), &sk),
            &pk,
            false,
        )
        .expect_err("the newer status raised the floor to 7");
        assert!(
            matches!(err, InstallError::BelowFloor { floor: 7, .. }),
            "{err}"
        );
        // A newer status that LOWERS the floor is the realm's later word, and
        // the cached one is outranked by it (counter 4 clears a floor of 2).
        install_four_against_a_cached_floor(
            Some(status_with_floor(4, Some(2), &sk)),
            status_with_floor(3, Some(5), &sk),
            &pk,
            false,
        )
        .expect("the newer word lowered the floor");
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_mirror_that_carries_an_index_but_cannot_enumerate_leaves_the_omission_check_unrun() {
        // History as a MARK, so a mirror may answer.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let pk = f.pk.clone();
        let index = crate::lineindex::LineIndex {
            line: "2026.07".into(),
            counter: 1,
            issued_at: "2026-08-07T00:00:00Z".into(),
            layers: vec![crate::lineindex::IndexedLayer {
                layer: "2026.07.1".into(),
                digest: manifest_digest(&f.newer),
                channel: "qualified".into(),
                counter: 2,
            }],
        }
        .sign(&f.sk, "root-1")
        .unwrap();
        // The source carries the index but, like a directory or OCI layout,
        // cannot ENUMERATE what it serves (`served_layers` is None).
        let source =
            std::mem::replace(&mut f.source, MemorySource::new()).with_line_index(index.as_bytes());
        let policy = InstallPolicy {
            index: Some(crate::lineindex::IndexPolicy {
                realm: "acme",
                trust: crate::keyroles::test_support::leak_rt(&pk),
                required: false,
            }),
            ..policy()
        };
        let newer = digest_pin("2026.07.1", &manifest_digest(&f.newer));
        let outcome = install_from(
            &newer,
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy,
            false,
        )
        .expect("history lets a mirror answer");
        assert_eq!(
            outcome.omission_check_skipped,
            Some(OmissionSkipped::CannotEnumerate),
            "an index it cannot compare with a listing is a check that could not run"
        );
        // The same source as the PRIMARY reports nothing skipped.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let source =
            std::mem::replace(&mut f.source, MemorySource::new()).with_line_index(index.as_bytes());
        let outcome = install_from(
            &newer,
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy,
            true,
        )
        .unwrap();
        assert_eq!(outcome.omission_check_skipped, None);
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_digest_install_refuses_a_mirror_before_contacting_it_when_there_is_no_history() {
        struct Untouched;
        impl LayerSource for Untouched {
            fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
                panic!("a mirror was contacted for a first contact");
            }
            fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, SourceError> {
                panic!("a mirror was contacted for a first contact");
            }
        }
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let mut f = consent_fixture();
        let pk = f.pk.clone();
        let err = install_by_digest_from(
            &manifest_digest(&f.older),
            &Untouched,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy(),
            DigestRole::Mirror {
                expected_line: Ok(&line),
            },
        )
        .expect_err("no history, no mirror");
        assert!(
            matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
            "{err}"
        );
        assert!(!err.fails_over());
        // An include whose line CANNOT be known: refused in words that say so,
        // not as a missing history. Absent and unparseable read differently.
        for why in [
            "the include names no layer",
            "the include's layer name \"x\" is not a valid layer id",
        ] {
            let mut f = consent_fixture();
            let err = install_by_digest_from(
                &manifest_digest(&f.older),
                &Untouched,
                &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
                &f.store,
                &mut f.marks,
                &policy(),
                DigestRole::Mirror {
                    expected_line: Err(why.to_string()),
                },
            )
            .unwrap_err();
            assert!(
                matches!(&err, InstallError::LineUnknownForMirror { why: w } if w == why),
                "{err}"
            );
            assert!(err.to_string().contains(why), "{err}");
            assert!(!err.to_string().contains("no history"), "{err}");
            assert!(!err.fails_over());
        }
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_digest_install_from_a_mirror_proceeds_when_the_expected_line_has_history() {
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let pk = f.pk.clone();
        let line: crate::layer::Line = "2026.07".parse().unwrap();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        install_by_digest_from(
            &manifest_digest(&f.newer),
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy(),
            DigestRole::Mirror {
                expected_line: Ok(&line),
            },
        )
        .expect("history for the line admits a mirror");
        // History for ANOTHER line does not.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let other: crate::layer::Line = "2026.06".parse().unwrap();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let err = install_by_digest_from(
            &manifest_digest(&f.newer),
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy(),
            DigestRole::Mirror {
                expected_line: Ok(&other),
            },
        )
        .unwrap_err();
        assert!(
            matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
            "{err}"
        );
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn an_include_that_names_one_line_but_digests_another_is_refused_terminally() {
        // The include NAMES a layer of line 2026.07 (which this machine has
        // history for) but the DIGEST is a layer of line 2026.06 (which it does
        // not). The early check passes on the named line; install_inner then
        // checks the REAL manifest's line and refuses.
        let mut f = consent_fixture();
        see_the_newer(&mut f);
        let (other_layer, other_blobs) = layer_of("2026.06.0", 1, "elsewhere");
        let mut source =
            std::mem::replace(&mut f.source, MemorySource::new()).with_manifest(&other_layer);
        for (d, b) in &other_blobs {
            source = source.with_blob(d, b);
        }
        let named: crate::layer::Line = "2026.07".parse().unwrap();
        let pk = f.pk.clone();
        let err = install_by_digest_from(
            &manifest_digest(&other_layer),
            &source,
            &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
            &f.store,
            &mut f.marks,
            &policy(),
            DigestRole::Mirror {
                expected_line: Ok(&named),
            },
        )
        .expect_err("a mislabelled include");
        assert!(
            matches!(&err, InstallError::FirstContactNeedsPrimary { line } if line == "2026.06"),
            "{err}"
        );
        assert!(!err.fails_over());
        assert!(
            f.store
                .get(&manifest_digest(&other_layer))
                .unwrap()
                .is_none(),
            "nothing may be installed"
        );
    }

    // rivet: verifies REQ-MIRROR-002
    #[test]
    fn a_primary_install_never_reports_a_skipped_omission_check() {
        let mut f = consent_fixture();
        let source = std::mem::replace(&mut f.source, MemorySource::new());
        let outcome = first_contact(&mut f, &source, true).unwrap();
        assert_eq!(outcome.omission_check_skipped, 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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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),
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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),
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(),
            &crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&f.pk),
        )
        .unwrap();
        cache.update(&line, &ok, &doc).unwrap();
        assert_eq!(
            cached_consent_why_not(
                &older,
                f.store.root(),
                &crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&f.pk),
        )
        .unwrap();
        cache.update(&line, &yank, &doc).unwrap();
        let why = cached_consent_why_not(
            &older,
            f.store.root(),
            &crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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,
            &crate::keyroles::test_support::rt(&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(crate::keyroles::test_support::rt(&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}");
    }
}