varve 0.26.0

The PulseEngine toolchain layer manager — pinned, signed, dated toolchain bundles
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
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
//! CLI-level behavior: the fail-closed rules hold at the boundary users
//! actually touch, not only in the library.

use assert_cmd::Command;
use predicates::prelude::*;

const MANIFEST_JULY: &str = r#"{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
  "annotations": {
    "eu.pulseengine.varve.layer": "2026.07.0",
    "eu.pulseengine.varve.channel": "qualified"
  },
  "manifests": []
}"#;

const PIN_JULY: &str =
    "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\n";

struct Fixture {
    _tmp: tempfile::TempDir,
    root: std::path::PathBuf,
    project: std::path::PathBuf,
}

/// (tool name, tool bytes) pairs for one laid-down layer.
type LayerTools<'a> = &'a [(&'a str, &'a [u8])];

fn fixture(pin: Option<&str>, layers: &[(&str, LayerTools)]) -> Fixture {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("varve-root");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&project).unwrap();
    if let Some(pin) = pin {
        std::fs::write(project.join("varve.toml"), pin).unwrap();
    }
    let store = varve_core::Store::at(&root);
    for (manifest, tools) in layers {
        store.lay_down(manifest.as_bytes(), tools).unwrap();
    }
    Fixture {
        _tmp: tmp,
        root,
        project,
    }
}

fn varve(fx: &Fixture) -> Command {
    let mut cmd = Command::cargo_bin("varve").unwrap();
    cmd.env("PATH", "/usr/bin:/bin"); // hermetic — see the note on `varve()`
    cmd.env("VARVE_ROOT", &fx.root).current_dir(&fx.project);
    // A hermetic PATH. Without it these tests inherit the developer's, and
    // REQ-SHADOW-001 correctly reported a real conflict — a `cargo install`ed
    // `synth` in ~/.cargo/bin shadowing the fixture's pinned one — turning
    // three unrelated tests red on one machine and green on another. That is
    // the check doing its job; a suite whose result depends on what the person
    // running it happens to have installed is the defect.
    cmd.env("PATH", "/usr/bin:/bin");
    cmd
}

// rivet: verifies REQ-SHADOW-001
#[test]
fn verify_fails_when_path_runs_a_different_binary_than_the_pin() {
    // The reported bug (varve#66), end to end. Every individual answer was
    // correct and the composite was false: `which` printed the store path,
    // `verify` called the layer perfect — it WAS perfect — and the shell ran
    // something else. varve's headline claim in the README is `varve which
    // synth  # which binary runs here`.
    // A genuinely signed, installed layer — verify must have a trust root, and
    // the point of this test is that a PERFECT layer still fails the check.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    let tool = parent.join("synth-bin");
    std::fs::write(&tool, "#!/bin/sh\n").unwrap();
    let spec = parent.join("spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"1.0.0\"\npath = \"{}\"\n",
            tool.display()
        ),
    )
    .unwrap();
    let layout = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "k", "--out"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();

    let elsewhere = fx.project.parent().unwrap().join("elsewhere");
    std::fs::create_dir_all(&elsewhere).unwrap();
    let impostor = elsewhere.join("synth");
    std::fs::write(&impostor, "#!/bin/sh\necho WRONG\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&impostor, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    let shadowed_path = format!("{}:/usr/bin:/bin", elsewhere.display());

    // verify FAILS and says which binary actually wins, and how to fix it.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .env("PATH", &shadowed_path)
        .arg("verify")
        .assert()
        .failure()
        .stderr(predicate::str::contains("not what your PATH runs"))
        .stderr(predicate::str::contains("varve shim install"));

    // `which` keeps printing the dispatched path on STDOUT so scripts still
    // work, and warns on STDERR.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .env("PATH", &shadowed_path)
        .args(["which", "synth"])
        .assert()
        .success()
        .stdout(predicate::str::contains("/bin/synth"))
        .stderr(predicate::str::contains("on your PATH"));

    // With nothing shadowing it, verify passes — the check must not fire on a
    // machine that simply has not installed the shims yet.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .env("PATH", "/usr/bin:/bin")
        .arg("verify")
        .assert()
        .success();
}

// rivet: verifies REQ-PIN-001
#[test]
fn which_prints_the_resolved_binary_and_its_layer() {
    let fx = fixture(Some(PIN_JULY), &[(MANIFEST_JULY, &[("synth", b"s")])]);
    varve(&fx)
        .args(["which", "synth"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("bin/synth")
                .and(predicate::str::contains("2026.07.0"))
                .and(predicate::str::contains("sha256:")),
        );
}

// rivet: verifies REQ-PIN-001
#[test]
fn which_fails_closed_when_the_pinned_layer_is_not_installed() {
    let fx = fixture(Some(PIN_JULY), &[]);
    varve(&fx)
        .args(["which", "synth"])
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("2026.07.0").and(predicate::str::contains("varve install")),
        );
}

// rivet: verifies REQ-PIN-001
#[test]
fn which_fails_closed_when_no_pin_exists() {
    let fx = fixture(None, &[(MANIFEST_JULY, &[("synth", b"s")])]);
    varve(&fx)
        .args(["which", "synth"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("varve.toml"));
}

// rivet: verifies REQ-PIN-001
#[test]
fn which_fails_closed_when_the_tool_is_missing_from_the_layer() {
    let fx = fixture(Some(PIN_JULY), &[(MANIFEST_JULY, &[("rivet", b"r")])]);
    varve(&fx)
        .args(["which", "synth"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("synth"));
}

// rivet: verifies REQ-COEXIST-001
#[test]
fn list_shows_every_installed_layer() {
    let august = MANIFEST_JULY.replace("2026.07.0", "2026.08.0");
    let fx = fixture(
        Some(PIN_JULY),
        &[
            (MANIFEST_JULY, &[("synth", b"a")]),
            (august.as_str(), &[("synth", b"b")]),
        ],
    );
    varve(&fx).arg("list").assert().success().stdout(
        predicate::str::contains("2026.07.0")
            .and(predicate::str::contains("2026.08.0"))
            .and(predicate::str::contains("qualified")),
    );
}

/// Signed-layer fixture material for the install/verify tests.
struct SignedLayer {
    archive: std::path::PathBuf,
    trust_root: std::path::PathBuf,
    wrong_root: std::path::PathBuf,
    /// The hex-encoded SECRET half, for tests that must sign something else
    /// under the same root (attestation statements).
    secret_key: std::path::PathBuf,
}

fn signed_layer_fixture(fx: &Fixture, layer: &str, counter: u64) -> SignedLayer {
    let (sk, pk) = varve_core::generate_root_keypair();
    let (_, wrong_pk) = varve_core::generate_root_keypair();
    let tool_bytes = format!("{layer}-synth-binary").into_bytes();
    let blob_digest = varve_core::manifest_digest(&tool_bytes);
    let line = &layer[..layer.rfind('.').unwrap()];
    let payload = format!(
        r#"{{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
  "annotations": {{
    "eu.pulseengine.varve.layer": "{layer}",
    "eu.pulseengine.varve.line": "{line}",
    "eu.pulseengine.varve.channel": "qualified",
    "eu.pulseengine.varve.counter": "{counter}",
    "org.opencontainers.image.created": "2026-07-31T09:14:00Z"
  }},
  "manifests": [
    {{
      "mediaType": "application/vnd.oci.image.manifest.v1+json",
      "digest": "{blob_digest}",
      "size": 0,
      "annotations": {{ "eu.pulseengine.tool": "synth" }}
    }}
  ]
}}"#
    );
    let envelope = varve_core::sign_layer_manifest(payload.as_bytes(), &sk, "test-root").unwrap();
    let archive = fx
        .project
        .parent()
        .unwrap()
        .join(format!("archive-{layer}-{counter}"));
    let dir = varve_core::DirSource::at(&archive);
    dir.put(
        envelope.as_bytes(),
        &[(blob_digest.as_str(), tool_bytes.as_slice())],
    )
    .unwrap();
    let trust_root = fx
        .project
        .parent()
        .unwrap()
        .join(format!("root-{layer}-{counter}.pub"));
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    let wrong_root = fx
        .project
        .parent()
        .unwrap()
        .join(format!("wrong-{layer}-{counter}.pub"));
    std::fs::write(&wrong_root, hex::encode(&wrong_pk)).unwrap();
    let secret_key = fx
        .project
        .parent()
        .unwrap()
        .join(format!("secret-{layer}-{counter}.hex"));
    std::fs::write(&secret_key, hex::encode(&sk)).unwrap();
    SignedLayer {
        archive,
        trust_root,
        wrong_root,
        secret_key,
    }
}

/// A manifest whose entries are tools, plus optional composed layers.
fn manifest_with_includes(layer: &str, tools: &[&str], includes: &[&str]) -> String {
    let mut entries: Vec<String> = tools
        .iter()
        .map(|t| {
            format!(r#"{{"digest":"sha256:{t}","annotations":{{"eu.pulseengine.tool":"{t}"}}}}"#)
        })
        .collect();
    for d in includes {
        entries.push(format!(
            r#"{{"digest":"{d}","annotations":{{"eu.pulseengine.varve.kind":"layer","eu.pulseengine.varve.include.realm":"bytecodealliance"}}}}"#
        ));
    }
    format!(
        r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","artifactType":"application/vnd.pulseengine.varve.layer.v1+json","annotations":{{"eu.pulseengine.varve.layer":"{layer}","eu.pulseengine.varve.channel":"qualified"}},"manifests":[{}]}}"#,
        entries.join(",")
    )
}

// rivet: verifies REQ-KEYGEN-001, REQ-PRODUCER-001, REQ-STORE-001
#[test]
fn an_organisation_can_stand_up_its_own_realm() {
    // The path a ten-persona audit found CLOSED: four of five blocked personas
    // could not get from a signing key to the trust-root a realm demands.
    // keygen -> deposit under our own key -> our own realms file -> pin ->
    // install -> verify against OUR root.
    let fx = fixture(None, &[]);
    let dir = fx.project.clone();
    let key = dir.join("acme.key");
    let pubf = dir.join("acme.pub");
    varve(&fx)
        .args(["keygen", "--out"])
        .arg(&key)
        .arg("--pub")
        .arg(&pubf)
        .assert()
        .success()
        .stdout(predicate::str::contains("trust-root"));

    // pubkey re-prints the same value, bare, so it composes into a config.
    let printed = varve(&fx)
        .args(["pubkey"])
        .arg(&key)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let printed = String::from_utf8(printed).unwrap().trim().to_string();
    let from_file = std::fs::read_to_string(&pubf).unwrap().trim().to_string();
    assert_eq!(printed, from_file);
    assert_eq!(printed.len(), 64, "a trust-root is 64 hex characters");

    // Deposit a layer signed with our key.
    let tool = dir.join("acme-tool");
    std::fs::write(&tool, b"#!/bin/sh\necho acme\n").unwrap();
    let layout = dir.join("layout");
    varve(&fx)
        .args([
            "deposit",
            "--layer",
            "2026.08.0",
            "--channel",
            "qualified",
            "--counter",
            "1",
            "--issued-at",
            "2026-08-01T00:00:00Z",
            "--key",
        ])
        .arg(&key)
        .arg("--out")
        .arg(&layout)
        .arg("--tool")
        .arg(format!("acme-tool@1.0.0={}", tool.display()))
        .assert()
        .success();

    // Our own realm, pinned by our own project, verified against OUR root.
    std::fs::write(
        dir.join("varve-realms.toml"),
        format!(
            "[realm.acme]\nregistry = \"oci://example.invalid/acme\"\ntrust-root = \"{printed}\"\n"
        ),
    )
    .unwrap();
    std::fs::write(
        dir.join("varve.toml"),
        "manifest-version = 1\n[toolchain]\nrealm = \"acme\"\nchannel = \"qualified\"\nlayer = \"2026.08.0\"\n",
    )
    .unwrap();
    varve(&fx)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("verified"));
    varve(&fx).args(["which", "acme-tool"]).assert().success();

    // REQ-STORE-001: a layer `which` resolves must be a layer `list` can see.
    // `list` read only the top-level core, so after a realm install it printed
    // "no layers installed" with exit 0 — contradicted a second later by
    // verify, which, run and sbom. Three personas reported it.
    varve(&fx)
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("2026.08.0"));

    // …and an explicit --layer must find it too. This is the README's
    // headline example, and it failed on the realm path.
    varve(&fx)
        .args(["sbom", "--layer", "2026.08.0"])
        .assert()
        .success()
        .stdout(predicate::str::contains("CycloneDX"));
}

// rivet: verifies REQ-PRODUCER-001
#[test]
fn deposit_refuses_a_key_that_would_sign_unverifiably() {
    // varve accepted 64 bytes of entropy and emitted a signed layer no trust
    // root on earth could verify, exit 0. The produce side now fails closed
    // like the consume side.
    let fx = fixture(None, &[]);
    let dir = fx.project.clone();
    let tool = dir.join("t");
    std::fs::write(&tool, b"x").unwrap();

    let entropy = dir.join("entropy.key");
    std::fs::write(&entropy, "ab".repeat(64)).unwrap();
    varve(&fx)
        .args([
            "deposit",
            "--layer",
            "2026.08.0",
            "--channel",
            "qualified",
            "--counter",
            "1",
            "--issued-at",
            "2026-08-01T00:00:00Z",
            "--key",
        ])
        .arg(&entropy)
        .arg("--out")
        .arg(dir.join("out1"))
        .arg("--tool")
        .arg(format!("t@1.0.0={}", tool.display()))
        .assert()
        .failure()
        .stderr(predicate::str::contains("NO trust root can verify"));

    // A 32-byte secret — what the old --key help text described — names both
    // lengths and the command that mints a real one.
    let short = dir.join("short.key");
    std::fs::write(&short, "ab".repeat(32)).unwrap();
    varve(&fx)
        .args([
            "deposit",
            "--layer",
            "2026.08.0",
            "--channel",
            "qualified",
            "--counter",
            "1",
            "--issued-at",
            "2026-08-01T00:00:00Z",
            "--key",
        ])
        .arg(&short)
        .arg("--out")
        .arg(dir.join("out2"))
        .arg("--tool")
        .arg(format!("t@1.0.0={}", tool.display()))
        .assert()
        .failure()
        .stderr(predicate::str::contains("128").and(predicate::str::contains("varve keygen")));
}

// rivet: verifies REQ-COMPOSE-001
#[test]
fn one_pin_resolves_tools_from_a_composed_layer() {
    // varve#52: relay needs the PulseEngine tools that CHECK its work and the
    // upstream tools that BUILD it. One pin, two layers, both resolvable.
    let fx = fixture(Some(PIN_JULY), &[]);
    let store = varve_core::Store::at(&fx.root);
    // The upstream layer, laid down first so we can learn its digest.
    let upstream = manifest_with_includes("2026.08.0", &["wasm-tools", "cargo-component"], &[]);
    let up_digest = store
        .lay_down(
            upstream.as_bytes(),
            &[("wasm-tools", b"w"), ("cargo-component", b"c")],
        )
        .unwrap();
    // The pinned layer composes it.
    let root = manifest_with_includes("2026.07.0", &["rivet"], &[&up_digest]);
    store.lay_down(root.as_bytes(), &[("rivet", b"r")]).unwrap();

    // The checking half still resolves…
    varve(&fx)
        .args(["which", "rivet"])
        .assert()
        .success()
        .stdout(predicate::str::contains("bin/rivet"));
    // …and now so does the PRODUCING half, through one pin.
    varve(&fx)
        .args(["which", "wasm-tools"])
        .assert()
        .success()
        .stdout(predicate::str::contains("bin/wasm-tools"));
    varve(&fx)
        .args(["which", "cargo-component"])
        .assert()
        .success();
}

// rivet: verifies REQ-COMPOSE-001
#[test]
fn verify_refuses_a_composition_whose_included_layer_is_unsigned() {
    // Clean-room review demonstrated this exactly: an included layer laid down
    // with NO signature envelope dispatched its tools and `varve verify` still
    // exited 0, because verify only checked the root layer. A composition is
    // only as trustworthy as every layer in it — the included layer's tools are
    // on PATH exactly like the root's.
    let fx = fixture(Some(PIN_JULY), &[]);
    let (sk, pk) = varve_core::generate_root_keypair();
    let store = varve_core::Store::at(&fx.root);

    // An UNSIGNED upstream layer, laid straight into the store.
    let upstream = manifest_with_includes("2026.08.0", &["wasm-tools"], &[]);
    let up = store
        .lay_down(upstream.as_bytes(), &[("wasm-tools", b"unsigned")])
        .unwrap();

    // A properly signed root layer that composes it.
    let tool_bytes: &[u8] = b"synth-binary";
    let blob = varve_core::manifest_digest(tool_bytes);
    let payload = format!(
        r#"{{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
  "annotations": {{
    "eu.pulseengine.varve.layer": "2026.07.0",
    "eu.pulseengine.varve.line": "2026.07",
    "eu.pulseengine.varve.channel": "qualified",
    "eu.pulseengine.varve.counter": "1",
    "org.opencontainers.image.created": "2026-07-31T09:14:00Z"
  }},
  "manifests": [
    {{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"{blob}","size":0,
      "annotations":{{"eu.pulseengine.tool":"synth"}}}},
    {{"mediaType":"application/vnd.oci.image.index.v1+json","digest":"{up}","size":0,
      "annotations":{{"eu.pulseengine.varve.kind":"layer"}}}}
  ]
}}"#
    );
    let envelope = varve_core::sign_layer_manifest(payload.as_bytes(), &sk, "test-root").unwrap();
    let archive = fx.project.parent().unwrap().join("composed-archive");
    varve_core::DirSource::at(&archive)
        .put(envelope.as_bytes(), &[(blob.as_str(), tool_bytes)])
        .unwrap();
    let root = fx.project.parent().unwrap().join("composed-root.pub");
    std::fs::write(&root, hex::encode(&pk)).unwrap();

    // Install must ACCEPT the composed layer (it used to reject the include).
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .args(["install", "--from"])
        .arg(&archive)
        .assert()
        .success();

    // …and verify must now REFUSE, because the included layer is unsigned.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("composed layer").or(predicate::str::contains("2026.08.0")),
        );
}

// rivet: verifies REQ-PRODUCE-002
#[test]
fn install_refuses_a_composition_whose_include_is_not_installed() {
    // An independent review changed the guard to `if false && !missing…` and
    // the whole suite stayed green: the test cited as this clause's evidence
    // contains no composition at all, and the one composition CLI test
    // exercises `which`, not `install`. Unguarded, install exits 0 on a
    // composition `verify` rejects, and `run` then executes a tool from an
    // unverified included layer.
    let fx = fixture(Some(PIN_JULY), &[]);
    let (sk, pk) = varve_core::generate_root_keypair();
    let tool_bytes = b"synth-bytes";
    let blob = varve_core::manifest_digest(tool_bytes);
    // An include that names a realm and a layer, and is NOT installed anywhere.
    let payload = format!(
        r#"{{
  "schemaVersion":2,
  "mediaType":"application/vnd.oci.image.index.v1+json",
  "artifactType":"application/vnd.pulseengine.varve.layer.v1+json",
  "annotations":{{"eu.pulseengine.varve.layer":"2026.07.0",
    "eu.pulseengine.varve.line":"2026.07",
    "eu.pulseengine.varve.channel":"qualified",
    "eu.pulseengine.varve.counter":"1",
    "org.opencontainers.image.created":"2026-07-31T09:14:00Z"}},
  "manifests":[
    {{"mediaType":"application/octet-stream","digest":"{blob}","size":{size},
      "annotations":{{"eu.pulseengine.tool":"synth"}}}},
    {{"mediaType":"application/vnd.oci.image.index.v1+json","digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","size":0,
      "annotations":{{"eu.pulseengine.varve.kind":"layer",
        "eu.pulseengine.varve.include.realm":"bytecodealliance",
        "eu.pulseengine.varve.include.layer":"2026.05.0"}}}}
  ]
}}"#,
        size = tool_bytes.len()
    );
    let envelope = varve_core::sign_layer_manifest(payload.as_bytes(), &sk, "test-root").unwrap();
    let archive = fx.project.parent().unwrap().join("missing-include-archive");
    varve_core::DirSource::at(&archive)
        .put(envelope.as_bytes(), &[(blob.as_str(), tool_bytes)])
        .unwrap();
    let root = fx.project.parent().unwrap().join("mi-root.pub");
    std::fs::write(&root, hex::encode(&pk)).unwrap();

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .args(["install", "--from"])
        .arg(&archive)
        .assert()
        .failure()
        // names the missing layer…
        .stderr(predicate::str::contains("2026.05.0"))
        // …and the realm it must come from, which is the whole point: the same
        // layer id under another realm is a different layer…
        .stderr(predicate::str::contains("bytecodealliance"))
        // …and how to get it. `varve install` alone takes no layer or digest,
        // so advice naming only that is a no-op loop.
        .stderr(predicate::str::contains("varve.toml"));
}

// rivet: verifies REQ-COMPOSE-001
#[test]
fn a_composed_layer_that_is_not_installed_names_itself() {
    // Transitive fetch is deliberately out of scope: the error must name the
    // missing layer and its corrective install, as a missing pin already does.
    let fx = fixture(Some(PIN_JULY), &[]);
    let store = varve_core::Store::at(&fx.root);
    let root = manifest_with_includes("2026.07.0", &["rivet"], &["sha256:notinstalled"]);
    store.lay_down(root.as_bytes(), &[("rivet", b"r")]).unwrap();
    varve(&fx)
        .args(["which", "rivet"])
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("not installed")
                .and(predicate::str::contains("varve install")),
        );
}

// rivet: verifies REQ-COMPOSE-001
#[test]
fn a_tool_in_two_composed_layers_refuses_to_resolve() {
    // varve does not pick a winner — the same rule as an ambiguous pin.
    let fx = fixture(Some(PIN_JULY), &[]);
    let store = varve_core::Store::at(&fx.root);
    let upstream = manifest_with_includes("2026.08.0", &["wasm-tools"], &[]);
    let up = store
        .lay_down(upstream.as_bytes(), &[("wasm-tools", b"u")])
        .unwrap();
    let root = manifest_with_includes("2026.07.0", &["wasm-tools"], &[&up]);
    store
        .lay_down(root.as_bytes(), &[("wasm-tools", b"r")])
        .unwrap();
    varve(&fx)
        .args(["which", "wasm-tools"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("more than one layer"));
}

// rivet: verifies REQ-LOCKPIN-001
#[test]
fn verify_lockfile_refuses_a_file_it_could_not_read() {
    // A ten-persona docs audit found this exiting 0 on a path that does not
    // exist, printing "pins no crates — nothing to check" for a file it had
    // never opened. This gate is sold as the CI check for REQ-LOCKPIN-001, so
    // a typo'd path would have been green forever. A gate that cannot fail is
    // not a gate — and varve had just shipped one.
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["verify", "--lockfile"])
        .arg(fx.project.join("no-such-file.lock"))
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot read lockfile"));
    // And a lockfile that exists but is malformed must also fail, even when
    // the layer pins no crates — the file was read, so it must parse.
    let bad = fx.project.join("Cargo.lock");
    std::fs::write(&bad, "not toml {{{").unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["verify", "--lockfile"])
        .arg(&bad)
        .assert()
        .failure();
}

// rivet: verifies REQ-LOCKPIN-001
#[test]
fn verify_lockfile_fails_when_a_pinned_crate_disagrees() {
    // The first version of this test asserted .success() twice and never tested
    // a disagreement — a test whose NAME claimed the opposite of what it did
    // (found by clean-room review). It now exercises the failing path, against
    // a SIGNED layer, because the gate is trust-first and refuses to check
    // against a layer it cannot verify.
    let fx = fixture(Some(PIN_JULY), &[]);
    let (sk, pk) = varve_core::generate_root_keypair();
    let crate_bytes: &[u8] = b"fake-crate-tarball";
    let blob = varve_core::manifest_digest(crate_bytes);
    let payload = format!(
        r#"{{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
  "annotations": {{
    "eu.pulseengine.varve.layer": "2026.07.0",
    "eu.pulseengine.varve.line": "2026.07",
    "eu.pulseengine.varve.channel": "qualified",
    "eu.pulseengine.varve.counter": "1",
    "org.opencontainers.image.created": "2026-07-31T09:14:00Z"
  }},
  "manifests": [
    {{
      "mediaType": "application/vnd.oci.image.manifest.v1+json",
      "digest": "{blob}",
      "size": 0,
      "annotations": {{
        "eu.pulseengine.tool": "wit-bindgen-rt",
        "eu.pulseengine.tool.version": "0.58.0",
        "eu.pulseengine.varve.kind": "crate"
      }}
    }}
  ]
}}"#
    );
    let envelope = varve_core::sign_layer_manifest(payload.as_bytes(), &sk, "test-root").unwrap();
    let archive = fx.project.parent().unwrap().join("crate-archive");
    varve_core::DirSource::at(&archive)
        .put(envelope.as_bytes(), &[(blob.as_str(), crate_bytes)])
        .unwrap();
    let root = fx.project.parent().unwrap().join("crate-root.pub");
    std::fs::write(&root, hex::encode(&pk)).unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .args(["install", "--from"])
        .arg(&archive)
        .assert()
        .success();

    let lock = fx.project.join("Cargo.lock");
    // The consumer's actual drift: the layer pins 0.58.0, the project resolves 0.41.0.
    std::fs::write(
        &lock,
        "version = 4\n\n[[package]]\nname = \"wit-bindgen-rt\"\nversion = \"0.41.0\"\nchecksum = \"aaaa\"\n",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .args(["verify", "--lockfile"])
        .arg(&lock)
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("0.58.0")
                .and(predicate::str::contains("0.41.0"))
                .and(predicate::str::contains("disagree")),
        );

    // Agreement passes, and says what it actually checked.
    std::fs::write(
        &lock,
        "version = 4\n\n[[package]]\nname = \"wit-bindgen-rt\"\nversion = \"0.58.0\"\n",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .args(["verify", "--lockfile"])
        .arg(&lock)
        .assert()
        .success()
        .stdout(predicate::str::contains("agrees with layer"));

    // A malformed lockfile must FAIL, never silently pass.
    std::fs::write(&lock, "not toml {{{").unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root)
        .args(["verify", "--lockfile"])
        .arg(&lock)
        .assert()
        .failure();
}
// rivet: verifies REQ-ATTEST-001
#[test]
fn an_attestation_binds_to_its_layer_and_nothing_else() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();

    // An SBOM of the pinned layer, then a signed statement binding it.
    let sbom = fx.project.join("layer.cdx.json");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["sbom", "--out"])
        .arg(&sbom)
        .assert()
        .success();
    let stmt = fx.project.join("sbom.statement.dsse");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args([
            "sign-attestation",
            "--kind",
            "sbom",
            "--producer",
            "varve",
            "--file",
        ])
        .arg(&sbom)
        .arg("--key")
        .arg(&signed.secret_key)
        .arg("--key-id")
        .arg("test-root")
        .arg("--out")
        .arg(&stmt)
        .assert()
        .success();

    // It checks out against the pinned layer.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["check-attestation", "--statement"])
        .arg(&stmt)
        .arg("--file")
        .arg(&sbom)
        .assert()
        .success()
        .stdout(predicate::str::contains("attestation OK"));

    // Swap the bytes: the statement pins them, so this must be refused.
    let tampered = fx.project.join("tampered.cdx.json");
    std::fs::write(
        &tampered,
        b"{\"bomFormat\":\"CycloneDX\",\"components\":[]}",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["check-attestation", "--statement"])
        .arg(&stmt)
        .arg("--file")
        .arg(&tampered)
        .assert()
        .failure();

    // A statement signed by another root cannot vouch for anything here.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.wrong_root)
        .args(["check-attestation", "--statement"])
        .arg(&stmt)
        .arg("--file")
        .arg(&sbom)
        .assert()
        .failure();

    // An unknown kind is refused, not guessed.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["sign-attestation", "--kind", "vibes", "--file"])
        .arg(&sbom)
        .arg("--key")
        .arg(&signed.secret_key)
        .arg("--out")
        .arg(fx.project.join("nope.dsse"))
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown attestation kind"));
}

// rivet: verifies REQ-ATTEST-001
#[test]
fn check_attestation_refuses_a_tampered_layer() {
    // Clean-room review found check-attestation reporting "attestation OK" over
    // a store state `varve verify` rejects: it checked the statement signature
    // but never re-verified the LAYER, whose name and digest are local labels
    // until its retained envelope is re-checked. This is the command the
    // disconnected consumer runs; it must not be the trusting one.
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    let sbom = fx.project.join("l.cdx.json");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["sbom", "--out"])
        .arg(&sbom)
        .assert()
        .success();
    let stmt = fx.project.join("s.dsse");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["sign-attestation", "--kind", "sbom", "--file"])
        .arg(&sbom)
        .arg("--key")
        .arg(&signed.secret_key)
        .arg("--key-id")
        .arg("test-root")
        .arg("--out")
        .arg(&stmt)
        .assert()
        .success();
    // Now alter an installed tool binary — the layer no longer verifies.
    let core = fx.root.join("core");
    let entry = std::fs::read_dir(&core)
        .unwrap()
        .next()
        .unwrap()
        .unwrap()
        .path();
    std::fs::write(entry.join("bin/synth"), b"EVIL").unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .arg("verify")
        .assert()
        .failure();
    // check-attestation must reach the same verdict, not report OK.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["check-attestation", "--statement"])
        .arg(&stmt)
        .arg("--file")
        .arg(&sbom)
        .assert()
        .failure();
}

// rivet: verifies REQ-ATTEST-002
#[test]
fn an_attestation_travels_through_deposit_archive_and_an_offline_install() {
    // The carriage half, at the boundary a user actually touches. v0.22.0
    // shipped BINDING and a review found REQ-ATTEST-001 marked verified with
    // this half unimplemented: a statement that stays in the producer's CI is
    // not evidence anyone has. Registries publish this material and mirrors
    // drop it — bandersnatch and Verdaccio carry none, every BCR attestation
    // URL points at github.com — so an air-gapped consumer receives the bytes
    // and none of the accountability, with no error saying so.
    //
    // Three cores, sharing nothing but the pinned root: the producer's, the
    // consumer's, and the disconnected site's on the far side of `archive`.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap().to_path_buf();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("attcarry-root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("attcarry-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    let tool = parent.join("attcarry-synth");
    std::fs::write(&tool, "#!/bin/sh\n").unwrap();
    let spec = parent.join("attcarry-spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"1.0.0\"\npath = \"{}\"\n",
            tool.display()
        ),
    )
    .unwrap();

    // 1. CI deposits the layer as an oci-layout.
    let layout = parent.join("attcarry-layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "test-root", "--out"])
        .arg(&layout)
        .assert()
        .success();

    // 2. …installs it once to produce an SBOM transcribed from the signed
    // manifest, and signs a statement binding that SBOM to the layer, ATTACHING
    // both to the layout as referrer artifacts. This is the step that did not
    // exist: without it the statement is written to a file and reaches nobody.
    let producer_root = parent.join("producer-root");
    let sbom = parent.join("layer.cdx.json");
    let stmt = parent.join("sbom.statement.dsse");
    varve(&fx)
        .env("VARVE_ROOT", &producer_root)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_ROOT", &producer_root)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["sbom", "--out"])
        .arg(&sbom)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_ROOT", &producer_root)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args([
            "sign-attestation",
            "--kind",
            "sbom",
            "--producer",
            "acme-ci",
            "--file",
        ])
        .arg(&sbom)
        .arg("--key")
        .arg(&sk_path)
        .args(["--key-id", "test-root", "--out"])
        .arg(&stmt)
        .arg("--attach-to")
        .arg(&layout)
        .assert()
        .success()
        .stdout(predicate::str::contains("attached to layout"));

    // 3. A consumer installs from that layout into a core of its own: the
    // evidence travels with the layer, and `verify` says what it is and that
    // it still binds.
    let consumer_root = parent.join("consumer-root");
    varve(&fx)
        .env("VARVE_ROOT", &consumer_root)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success()
        .stdout(predicate::str::contains("carried 1 attestation(s)"));
    varve(&fx)
        .env("VARVE_ROOT", &consumer_root)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("carries 1 attestation(s)"))
        .stdout(predicate::str::contains(
            "sbom by acme-ci: binds to this layer",
        ));

    // 4. That consumer archives the layer for a disconnected site. The archive
    // must re-emit the attestation as referrer entries — this is the mirror
    // boundary, and dropping it here is exactly the bug.
    let air_gapped = parent.join("attcarry-archive");
    varve(&fx)
        .env("VARVE_ROOT", &consumer_root)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["archive", "2026.07.0"])
        .arg(&air_gapped)
        .assert()
        .success();

    // 5. The far side: a FRESH core, offline, nothing but the archive and the
    // pinned root. The evidence is there and still binds.
    let far_side = parent.join("far-side-root");
    varve(&fx)
        .env("VARVE_ROOT", &far_side)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&air_gapped)
        .assert()
        .success()
        .stdout(predicate::str::contains("carried 1 attestation(s)"));
    varve(&fx)
        .env("VARVE_ROOT", &far_side)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "sbom by acme-ci: binds to this layer",
        ));

    // 6. Reporting, not refusal — deliberately. Corrupt the carried statement
    // in the far-side core: `verify` must say the attestation no longer binds
    // and still PASS the layer, whose own signature and digests are untouched.
    // Failing here would make varve's verdict depend on a third party's
    // release cadence, in the one tool whose purpose is frozen toolchains.
    let store_dir = std::fs::read_dir(far_side.join("core"))
        .unwrap()
        .next()
        .unwrap()
        .unwrap()
        .path()
        .join("attestations");
    for e in std::fs::read_dir(&store_dir).unwrap() {
        let p = e.unwrap().path();
        if p.to_string_lossy().ends_with(".statement.json") {
            std::fs::write(&p, b"{\"payload\":\"bm90LWEtc3RhdGVtZW50\"}").unwrap();
        }
    }
    varve(&fx)
        .env("VARVE_ROOT", &far_side)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("verified: signature OK"))
        .stdout(predicate::str::contains("DOES NOT BIND"));
}

// rivet: verifies REQ-SBOM-001
#[test]
fn sbom_fails_closed_on_a_layer_it_cannot_verify() {
    // REQ-SBOM-001 says the command "shall fail closed". An SBOM for an
    // unverifiable layer is worse than none, because it looks authoritative.
    // Clean-room review noted this was asserted in prose but never tested.
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    let out = fx.project.join("sbom.cdx.json");

    // 1. No trust root at all: refuse.
    varve(&fx)
        .args(["sbom", "--out"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(predicate::str::contains("trust root"));
    assert!(!out.exists(), "nothing may be written without a trust root");

    // 2. The WRONG trust root: refuse.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.wrong_root)
        .args(["sbom", "--out"])
        .arg(&out)
        .assert()
        .failure();
    assert!(!out.exists(), "nothing may be written under the wrong root");

    // 3. The right root: a document, and it names the layer it describes.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["sbom", "--out"])
        .arg(&out)
        .assert()
        .success();
    let doc = std::fs::read_to_string(&out).unwrap();
    assert!(
        doc.contains("CycloneDX") && doc.contains("2026.07.0"),
        "{doc}"
    );

    // 4. An unknown format is refused before anything is verified or written.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["sbom", "--format", "spdx"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown SBOM format"));
}

// rivet: verifies REQ-EXPORT-SYNC-001
#[test]
fn verify_export_hard_fails_on_a_stale_stamp() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    // An export dir stamped from a DIFFERENT layer digest than the pin resolves.
    let export = fx.project.join("vendored");
    std::fs::create_dir_all(&export).unwrap();
    std::fs::write(
        export.join(".varve-export.json"),
        r#"{"layer":"2026.06.0","manifest_digest":"sha256:deadbeef","kind":"cargo"}"#,
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["verify", "--export"])
        .arg(&export)
        .assert()
        .failure()
        .stderr(predicate::str::contains("STALE").or(predicate::str::contains("stale")));
}

// rivet: verifies REQ-EXPORT-SYNC-001
#[test]
fn verify_export_passes_when_the_stamp_matches_the_pin() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    // Learn the installed layer's manifest digest from verify's own output.
    let out = varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .arg("verify")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    let digest = stdout
        .split_whitespace()
        .find(|w| w.starts_with("sha256:"))
        .expect("verify prints the layer digest");
    // A stamp naming exactly that digest is fresh — the gate passes.
    let export = fx.project.join("vendored");
    std::fs::create_dir_all(&export).unwrap();
    std::fs::write(
        export.join(".varve-export.json"),
        format!(r#"{{"layer":"2026.07.0","manifest_digest":"{digest}","kind":"cargo"}}"#),
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["verify", "--export"])
        .arg(&export)
        .assert()
        .success()
        .stdout(predicate::str::contains("fresh"));
}

// rivet: verifies REQ-EXPORT-SYNC-001
#[test]
fn verify_export_hard_fails_when_the_stamp_is_missing() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    // A directory with no stamp is not a verified export — that is a failure.
    let export = fx.project.join("hand-assembled");
    std::fs::create_dir_all(&export).unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["verify", "--export"])
        .arg(&export)
        .assert()
        .failure()
        .stderr(predicate::str::contains("no export stamp"));
}

// rivet: verifies REQ-EXPORT-SYNC-001
#[test]
fn verify_export_hard_fails_on_a_malformed_stamp() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    // A stamp that is not valid JSON is not a verified export — a failure.
    let export = fx.project.join("corrupt");
    std::fs::create_dir_all(&export).unwrap();
    std::fs::write(export.join(".varve-export.json"), b"{not json").unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["verify", "--export"])
        .arg(&export)
        .assert()
        .failure()
        .stderr(predicate::str::contains("malformed"));
}

// rivet: verifies REQ-VERIFY-001
#[test]
fn install_verifies_lays_down_and_verify_repeats_the_verdict() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success()
        .stdout(predicate::str::contains("2026.07.0"));
    varve(&fx)
        .args(["which", "synth"])
        .assert()
        .success()
        .stdout(predicate::str::contains("bin/synth"));
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("verified"));
}

// rivet: verifies REQ-VERIFY-001
#[test]
fn install_refuses_a_layer_signed_by_the_wrong_root() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.wrong_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .failure()
        .stderr(predicate::str::contains("signature"));
    varve(&fx)
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("no layers"));
}

// rivet: verifies REQ-VERIFY-001
#[test]
fn install_without_a_trust_root_fails_closed() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .failure()
        .stderr(predicate::str::contains("trust root"));
}

// rivet: verifies REQ-VERIFY-001
#[test]
fn verify_detects_a_tampered_binary() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();
    // Corrupt the installed tool, then re-verify.
    let core = fx.root.join("core");
    let entry = std::fs::read_dir(&core)
        .unwrap()
        .next()
        .unwrap()
        .unwrap()
        .path();
    std::fs::write(entry.join("bin/synth"), b"EVIL").unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(predicate::str::contains("synth"));
}

// rivet: verifies REQ-ROLLBACK-001
#[test]
fn a_rolled_back_layer_is_refused_by_the_cli() {
    // Install the patched layer (counter 2) first…
    let fx = fixture(
        Some("manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.1\"\n"),
        &[],
    );
    let newer = signed_layer_fixture(&fx, "2026.07.1", 2);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &newer.trust_root)
        .args(["install", "--from"])
        .arg(&newer.archive)
        .assert()
        .success();
    // …then repoint the pin at the base layer (counter 1): refused as rollback.
    std::fs::write(fx.project.join("varve.toml"), PIN_JULY).unwrap();
    let older = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &older.trust_root)
        .args(["install", "--from"])
        .arg(&older.archive)
        .assert()
        .failure()
        .stderr(predicate::str::contains("rollback").or(predicate::str::contains("high-water")));
}

/// Deposit one layer of a line under a caller-supplied key, so several layers
/// share ONE trust root — `signed_layer_fixture` mints a fresh keypair per
/// call, and anti-rollback is a property of a line, which needs two layers a
/// single `verify` can check against a single root.
fn deposit_under(
    fx: &Fixture,
    key: &std::path::Path,
    layer: &str,
    counter: u64,
) -> std::path::PathBuf {
    let dir = fx.project.parent().unwrap();
    let tool = dir.join(format!("synth-{layer}"));
    std::fs::write(&tool, format!("#!/bin/sh\necho {layer}\n")).unwrap();
    let layout = dir.join(format!("layout-{layer}"));
    varve(fx)
        .args([
            "deposit",
            "--layer",
            layer,
            "--channel",
            "qualified",
            "--counter",
            &counter.to_string(),
            "--issued-at",
            "2026-08-01T00:00:00Z",
            "--key",
        ])
        .arg(key)
        .arg("--out")
        .arg(&layout)
        .arg("--tool")
        .arg(format!("synth@1.0.0={}", tool.display()))
        .assert()
        .success();
    layout
}

// rivet: verifies REQ-ROLLBACK-001, REQ-VERIFY-001
#[test]
fn verify_refuses_a_pin_that_resolves_below_the_lines_high_water_mark() {
    // varve#76. `verify` called itself "the install-time verdict, repeated
    // offline" and was not: the install-time verdict includes anti-rollback
    // and verify's did not. So a pin edited back to an already-installed
    // OLDER layer verified clean, exit 0 — and the docs tell people to run
    // `verify` in CI AS THE GATE, so the downgrade passed the gate. The layer
    // is genuinely signed and its digests genuinely match; every individual
    // answer was true and the composite was false.
    let fx = fixture(None, &[]);
    let dir = fx.project.parent().unwrap();
    let key = dir.join("root.key");
    let pubf = dir.join("root.pub");
    varve(&fx)
        .args(["keygen", "--out"])
        .arg(&key)
        .arg("--pub")
        .arg(&pubf)
        .assert()
        .success();

    let old = deposit_under(&fx, &key, "2026.08.0", 1);
    let new = deposit_under(&fx, &key, "2026.08.5", 5);
    let pin = |layer: &str| {
        std::fs::write(
            fx.project.join("varve.toml"),
            format!(
                "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\n"
            ),
        )
        .unwrap()
    };

    // Install the old one, then the new one: the line's high-water mark rises
    // to 5 while BOTH layers stay on disk, which is legitimate — a consumer
    // may keep an older layer around.
    pin("2026.08.0");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &pubf)
        .args(["install", "--from"])
        .arg(&old)
        .assert()
        .success();
    pin("2026.08.5");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &pubf)
        .args(["install", "--from"])
        .arg(&new)
        .assert()
        .success();

    // At the mark, verify passes — the check must not fire on a correct
    // setup, or it becomes a check people switch off.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &pubf)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("verified"));

    // Edit the pin back to the older, already-installed layer. Nothing about
    // the layer is wrong; what is wrong is that the pin now DISPATCHES it.
    pin("2026.08.0");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &pubf)
        .arg("verify")
        .assert()
        .failure()
        // Both counters, so the reader can see the gap and not just the
        // verdict — and the layer it resolved to, so they know which pin.
        .stderr(
            predicate::str::contains("2026.08.0")
                .and(predicate::str::contains("counter 1"))
                .and(predicate::str::contains("high-water mark is 5")),
        );

    // …and `install` refuses the same downgrade, which is the verdict verify
    // now repeats. The two commands must not disagree.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &pubf)
        .args(["install", "--from"])
        .arg(&old)
        .assert()
        .failure();
}

// rivet: verifies REQ-OFFLINE-001
#[test]
fn archive_then_offline_install_round_trips_with_verification_unchanged() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();

    // Export the installed layer as an oci-layout archive.
    let exported = fx.project.parent().unwrap().join("core-2026.07.0");
    varve(&fx)
        .args(["archive", "2026.07.0"])
        .arg(&exported)
        .assert()
        .success()
        .stdout(predicate::str::contains("oci-layout"));
    assert!(exported.join("oci-layout").is_file());
    assert!(exported.join("index.json").is_file());

    // A fresh machine (fresh VARVE_ROOT), no registry: install from the
    // archive with the same trust root, then re-verify offline.
    let fresh_root = fx.project.parent().unwrap().join("fresh-root");
    let mut cmd = Command::cargo_bin("varve").unwrap();
    cmd.env("PATH", "/usr/bin:/bin"); // hermetic — see the note on `varve()`
    cmd.env("VARVE_ROOT", &fresh_root)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .current_dir(&fx.project)
        .args(["install", "--from"])
        .arg(&exported)
        .assert()
        .success()
        .stdout(predicate::str::contains("2026.07.0"));
    let mut cmd = Command::cargo_bin("varve").unwrap();
    cmd.env("PATH", "/usr/bin:/bin"); // hermetic — see the note on `varve()`
    cmd.env("VARVE_ROOT", &fresh_root)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .current_dir(&fx.project)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("verified"));
}

// rivet: verifies REQ-OFFLINE-001
#[test]
fn archive_of_an_uninstalled_layer_fails_with_guidance() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let dest = fx.project.parent().unwrap().join("nowhere");
    varve(&fx)
        .args(["archive", "2026.07.0"])
        .arg(&dest)
        .assert()
        .failure()
        .stderr(predicate::str::contains("2026.07.0"));
}

/// Lay down a layer whose "tool" is a script that prints the provenance
/// environment and exits with a chosen code.
fn probe_layer(fx: &Fixture, layer: &str, exit: u8) -> String {
    let script = format!(
        "#!/bin/sh\necho \"layer=$VARVE_LAYER digest=$VARVE_LAYER_MANIFEST_DIGEST\"\nexit {exit}\n"
    );
    let manifest = MANIFEST_JULY.replace("2026.07.0", layer);
    let store = varve_core::Store::at(&fx.root);
    store
        .lay_down(manifest.as_bytes(), &[("probe", script.as_bytes())])
        .unwrap()
}

// rivet: partially-verifies REQ-PROV-001
#[test]
fn run_dispatches_with_the_layer_identity_in_the_environment() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let digest = probe_layer(&fx, "2026.07.0", 0);
    varve(&fx)
        .args(["run", "--", "probe"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("layer=2026.07.0")
                .and(predicate::str::contains(format!("digest={digest}"))),
        );
}

// rivet: partially-verifies REQ-PROV-001
#[test]
fn run_propagates_the_tool_exit_code() {
    let fx = fixture(Some(PIN_JULY), &[]);
    probe_layer(&fx, "2026.07.0", 7);
    let output = varve(&fx).args(["run", "--", "probe"]).output().unwrap();
    assert_eq!(
        output.status.code(),
        Some(7),
        "the tool's exit code is varve's"
    );
}

// rivet: verifies REQ-NOUPDATE-001
#[test]
fn run_with_an_explicit_layer_override_does_not_touch_the_pin() {
    let fx = fixture(Some(PIN_JULY), &[]);
    probe_layer(&fx, "2026.07.0", 0);
    probe_layer(&fx, "2026.09.0", 0);
    // One-off override runs the other layer…
    varve(&fx)
        .args(["run", "--varve", "2026.09.0", "--", "probe"])
        .assert()
        .success()
        .stdout(predicate::str::contains("layer=2026.09.0"));
    // …while the pin, and plain run, remain on July.
    varve(&fx)
        .args(["run", "--", "probe"])
        .assert()
        .success()
        .stdout(predicate::str::contains("layer=2026.07.0"));
    let pin = std::fs::read_to_string(fx.project.join("varve.toml")).unwrap();
    assert!(pin.contains("2026.07.0"), "the checked-in pin is untouched");
}

// rivet: verifies REQ-PIN-001
#[test]
fn run_fails_closed_like_everything_else() {
    let fx = fixture(Some(PIN_JULY), &[]);
    varve(&fx)
        .args(["run", "--", "probe"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("varve install"));
}

// rivet: verifies REQ-DEPOSIT-001
#[test]
fn deposit_creates_a_layer_the_standard_pipeline_installs() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    // Root keypair on disk, as CI would hold it.
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    // A tool binary to deposit.
    let tool_path = parent.join("synth-bin");
    std::fs::write(&tool_path, b"deposited-synth").unwrap();
    let dest = parent.join("deposited");

    varve(&fx)
        .args(["deposit", "--layer", "2026.07.0", "--channel", "qualified"])
        .args(["--counter", "1", "--issued-at", "2026-08-07T00:00:00Z"])
        .args(["--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&dest)
        .args(["--tool"])
        .arg(format!("synth@0.45.0={}", tool_path.display()))
        .assert()
        .success()
        .stdout(predicate::str::contains("sha256:"));

    // The deposit installs through the very same pipeline.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&dest)
        .assert()
        .success()
        .stdout(predicate::str::contains("2026.07.0"));
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success();
}

// rivet: verifies REQ-STATUS-DIST-001
#[test]
fn an_attached_baseline_makes_status_work_after_an_offline_install() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    let tool_path = parent.join("synth-bin");
    std::fs::write(&tool_path, b"deposited-synth").unwrap();
    let dest = parent.join("deposited");

    varve(&fx)
        .args(["deposit", "--layer", "2026.07.0", "--channel", "qualified"])
        .args(["--counter", "1", "--issued-at", "2026-08-07T00:00:00Z"])
        .args(["--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&dest)
        .args(["--tool"])
        .arg(format!("synth@0.45.0={}", tool_path.display()))
        .assert()
        .success();

    // CI signs a baseline line-status with the SAME root and attaches it.
    let doc_path = parent.join("baseline.json");
    let env_path = parent.join("baseline.dsse.json");
    std::fs::write(&doc_path, status_doc_json("2026.07", 1)).unwrap();
    varve(&fx)
        .args(["sign-status", "--file"])
        .arg(&doc_path)
        .args(["--key"])
        .arg(&sk_path)
        .args(["--out"])
        .arg(&env_path)
        .assert()
        .success();
    varve(&fx)
        .args(["attach-status", "--layout"])
        .arg(&dest)
        .args(["--status"])
        .arg(&env_path)
        .assert()
        .success()
        .stdout(predicate::str::contains("attached baseline line-status #1"));

    // Install from the layout — the baseline is auto-cached, no --from-file.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&dest)
        .assert()
        .success()
        .stdout(predicate::str::contains("cached baseline line-status #1"));

    // `varve status` works OFFLINE with nothing but the install behind it.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("status")
        .assert()
        .success()
        .stdout(
            predicate::str::contains("YANKED").and(predicate::str::contains("1 known problem")),
        );
}

// rivet: verifies REQ-CRATE-001, REQ-KIND-001
#[test]
fn deposit_a_crate_kind_entry_and_export_a_cargo_registry() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // A stand-in .crate blob (export-cargo does not parse it; the offline
    // build oracle covers real crates). Its sha256 is the cksum Cargo checks.
    let crate_bytes = b"a-dot-crate-tarballs-bytes";
    let crate_path = parent.join("demo-crate.crate");
    std::fs::write(&crate_path, crate_bytes).unwrap();

    // Deposit it as a `crate`-kind entry via a spec file (only the spec path
    // carries kind).
    let spec = parent.join("deposit-spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"demo-crate\"\nversion = \"0.1.0\"\nkind = \"crate\"\n\
             path = \"{}\"\n",
            crate_path.display()
        ),
    )
    .unwrap();
    let dest = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-08-07T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&dest)
        .assert()
        .success();

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&dest)
        .assert()
        .success();

    // Export a Cargo registry from the verified layer.
    let out = parent.join("cargo-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-cargo", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .success()
        .stdout(predicate::str::contains("1 verified crate"));

    // The .crate is the verified bytes; the config redirects crates.io; the
    // index cksum is varve's signed digest.
    assert_eq!(
        std::fs::read(out.join("registry/demo-crate-0.1.0.crate")).unwrap(),
        crate_bytes
    );
    let config = std::fs::read_to_string(out.join(".cargo/config.toml")).unwrap();
    assert!(config.contains("replace-with = \"varve\""));
    let idx = std::fs::read_to_string(out.join("registry/index/de/mo/demo-crate")).unwrap();
    // A cksum is recorded (its correctness vs. real Cargo is proven by the
    // cargo_offline oracle); here we prove the CLI wiring end to end.
    assert!(
        idx.contains(r#""cksum":"#) && idx.contains(r#""vers":"0.1.0""#),
        "{idx}"
    );
}

// rivet: verifies REQ-STORE-002
#[test]
fn a_layer_holding_two_versions_of_one_crate_deposits_installs_verifies_and_exports_both() {
    // varve#69 end to end, at the boundary the user touches. `deposit` refused
    // the layer outright ("duplicate tool name 'serde'"), so a real dependency
    // graph — varve's own has 14 names at more than one version — could not be
    // expressed at all. And had only the deposit check been relaxed, the two
    // payloads would have landed on ONE path in the store: the wrong bytes
    // under the right name, with `verify` failing on the other entry.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // Two versions of ONE crate, plus a tool — the mixed layer, so the two
    // identity rules are exercised side by side.
    let old_bytes: &[u8] = b"serde-1.0.200-crate-tarball";
    let new_bytes: &[u8] = b"serde-1.0.210-crate-tarball";
    let old_path = parent.join("serde-1.0.200.crate");
    let new_path = parent.join("serde-1.0.210.crate");
    let tool_path = parent.join("synth-bin");
    std::fs::write(&old_path, old_bytes).unwrap();
    std::fs::write(&new_path, new_bytes).unwrap();
    std::fs::write(&tool_path, b"#!/bin/sh\n").unwrap();

    let spec = parent.join("spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"serde\"\nversion = \"1.0.200\"\nkind = \"crate\"\npath = \"{old}\"\n\n\
             [[tool]]\nname = \"serde\"\nversion = \"1.0.210\"\nkind = \"crate\"\npath = \"{new}\"\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"0.45.0\"\npath = \"{tool}\"\n",
            old = old_path.display(),
            new = new_path.display(),
            tool = tool_path.display(),
        ),
    )
    .unwrap();
    let layout = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&layout)
        .assert()
        .success();

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();

    // The layer verifies as a whole: three payloads, each against its own
    // signed digest.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success();

    // The exported registry OFFERS BOTH versions — a lockfile naming two
    // majors needs both present to build offline.
    let out = parent.join("cargo-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-cargo", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .success()
        .stdout(predicate::str::contains("2 verified crate"));
    assert_eq!(
        std::fs::read(out.join("registry/serde-1.0.200.crate")).unwrap(),
        old_bytes
    );
    assert_eq!(
        std::fs::read(out.join("registry/serde-1.0.210.crate")).unwrap(),
        new_bytes,
        "each version must export ITS OWN bytes"
    );
    let idx = std::fs::read_to_string(out.join("registry/index/se/rd/serde")).unwrap();
    let versions: Vec<String> = idx
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|l| {
            let v: serde_json::Value = serde_json::from_str(l).expect("Cargo-parseable index line");
            v["vers"].as_str().unwrap().to_string()
        })
        .collect();
    assert_eq!(versions.len(), 2, "index: {idx}");
    assert!(versions.contains(&"1.0.200".to_string()) && versions.contains(&"1.0.210".to_string()));

    // The lockfile gate agrees with a lockfile that resolves both — before
    // this, comparing every pinned entry against every locked package of the
    // same name reported 1.0.200-vs-1.0.210 as drift.
    let lock = fx.project.join("Cargo.lock");
    std::fs::write(
        &lock,
        "version = 4\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.200\"\n\n\
         [[package]]\nname = \"serde\"\nversion = \"1.0.210\"\n",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["verify", "--lockfile"])
        .arg(&lock)
        .assert()
        .success();

    // And the whole layer still crosses an air gap: archive it, install into a
    // fresh core from that archive alone, and verify there.
    let archive = parent.join("archive");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["archive", "2026.07.0"])
        .arg(&archive)
        .assert()
        .success();
    let far_side = parent.join("far-side");
    varve(&fx)
        .env("VARVE_ROOT", &far_side)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&archive)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_ROOT", &far_side)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success();
}

// rivet: verifies REQ-STORE-002
#[test]
fn two_versions_of_one_tool_are_still_refused_and_the_error_names_both() {
    // The other half of clause 1, at the boundary: dispatch is by name, so
    // `varve run synth` must have exactly one answer. Relaxing the rule for
    // everything would have made the shims ambiguous.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, _pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let bin = parent.join("synth-bin");
    std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
    let spec = parent.join("spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"0.45.0\"\npath = \"{p}\"\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"0.46.0\"\npath = \"{p}\"\n",
            p = bin.display(),
        ),
    )
    .unwrap();
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "k", "--out"])
        .arg(parent.join("layout"))
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("synth")
                .and(predicate::str::contains("0.45.0"))
                .and(predicate::str::contains("0.46.0")),
        );
}

// rivet: verifies REQ-VSIX-001, REQ-STORE-002
#[test]
fn vsix_extensions_deposit_install_verify_and_export_for_code() {
    // varve#68 end to end, at the boundary the user touches. Two extensions,
    // one of them at TWO versions (REQ-STORE-002's identity rule, inherited
    // rather than re-implemented), through deposit -> install -> verify ->
    // export-vsix, and out the other side as files `code --install-extension`
    // consumes directly.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // Stand-in .vsix zips — varve never looks inside one; the bytes are
    // anchored by the signed digest and the NAME comes from the manifest.
    let payloads: [(&str, &str, &[u8]); 3] = [
        ("rust-lang.rust-analyzer", "0.3.2260", b"ra-old-zip-bytes"),
        ("rust-lang.rust-analyzer", "0.3.2300", b"ra-new-zip-bytes"),
        ("vadimcn.vscode-lldb", "1.11.4", b"lldb-zip-bytes"),
    ];
    let mut spec_text =
        String::from("layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n");
    for (name, version, bytes) in payloads {
        let path = parent.join(format!("{name}-{version}.vsix"));
        std::fs::write(&path, bytes).unwrap();
        spec_text.push_str(&format!(
            "\n[[tool]]\nname = \"{name}\"\nversion = \"{version}\"\nkind = \"vsix\"\n\
             path = \"{}\"\n",
            path.display()
        ));
    }
    let spec = parent.join("vsix-spec.toml");
    std::fs::write(&spec, &spec_text).unwrap();

    let layout = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&layout)
        .assert()
        .success();

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();

    // Every entry verifies against its own signed digest — the digest check is
    // kind-agnostic (DD-003), so a `vsix` needed nothing new here (clause 1).
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success();

    // Clause 2 + clause 4 IN THE STORE: three distinct files, each holding its
    // own bytes, none of them executable.
    let store = varve_core::Store::at(&fx.root);
    let installed = store
        .list()
        .unwrap()
        .into_iter()
        .find(|l| l.layer.to_string() == "2026.07.0")
        .expect("the layer is installed");
    for (name, version, bytes) in payloads {
        let path = installed.root.join("payloads").join(name).join(version);
        assert_eq!(
            std::fs::read(&path).unwrap(),
            bytes,
            "{name}@{version} must be stored under its own path with its own bytes"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(
                mode & 0o111,
                0,
                "clause 2: a .vsix is an archive, not a program — {name}@{version} \
                 was laid down mode {mode:o}"
            );
        }
        // …and it is NOT dispatchable: nothing landed in bin/ under its name.
        assert!(
            !installed.root.join("bin").join(name).exists(),
            "an extension must never occupy a dispatch path"
        );
    }
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["which", "rust-lang.rust-analyzer"])
        .assert()
        .failure();

    // Clause 3: export for `code`.
    let out = parent.join("extensions");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-vsix", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .success()
        .stdout(
            predicate::str::contains("3 verified VS Code extension(s)")
                .and(predicate::str::contains("code --install-extension")),
        );

    for (name, version, bytes) in payloads {
        // The marketplace's own asset name: `code` dispatches on the .vsix
        // suffix, and a human tells two versions apart by this name alone.
        let file = out.join(format!("{name}-{version}.vsix"));
        assert_eq!(
            std::fs::read(&file).unwrap(),
            bytes,
            "{} must hold ITS OWN verified bytes",
            file.display()
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&file).unwrap().permissions().mode();
            assert_eq!(
                mode & 0o111,
                0,
                "clause 2 must survive the export too: {} is mode {mode:o}",
                file.display()
            );
        }
    }

    // Clause 3's second half: the stamp, so `verify --export` catches drift.
    let stamp: serde_json::Value =
        serde_json::from_slice(&std::fs::read(out.join(".varve-export.json")).unwrap()).unwrap();
    assert_eq!(stamp["kind"], "vsix");
    assert_eq!(stamp["layer"], "2026.07.0");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["verify", "--export"])
        .arg(&out)
        .assert()
        .success()
        .stdout(predicate::str::contains("fresh"));

    // And it goes STALE when the pin moves — the whole reason for the stamp.
    std::fs::write(
        out.join(".varve-export.json"),
        r#"{"layer":"2026.06.0","manifest_digest":"sha256:0000","kind":"vsix"}"#,
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["verify", "--export"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(predicate::str::contains("STALE"));
}

// rivet: verifies REQ-VSIX-001
#[test]
fn export_vsix_refuses_a_layer_with_no_extensions_rather_than_writing_an_empty_directory() {
    // An export directory that exists and is empty is worse than an error: a
    // consumer installs from it, gets nothing, and believes the pin carries no
    // extensions. Every other adapter fails closed here; so does this one.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    let bin = parent.join("synth-bin");
    std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
    let spec = parent.join("spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"0.45.0\"\npath = \"{}\"\n",
            bin.display()
        ),
    )
    .unwrap();
    let layout = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();

    let out = parent.join("extensions");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-vsix", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(predicate::str::contains("carries no `vsix` entries"));
    assert!(
        !out.join(".varve-export.json").exists(),
        "a refused export must not be stamped as one"
    );
}

// rivet: verifies REQ-PRODUCE-002
#[test]
fn a_relative_out_still_yields_an_absolute_path_in_the_generated_config() {
    // An independent review made absolute_export_dir return its argument
    // verbatim and the whole suite stayed GREEN: every export test passes an
    // ABSOLUTE --out, so the bug was unreachable from the suite that was cited
    // as its evidence. The generated .cargo/config.toml is meant to be COPIED
    // into a project and read from a different working directory, so a relative
    // path there is a build that fails while varve printed instructions saying
    // it would work. This test passes a RELATIVE --out, as a user does.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    let crate_bytes = b"fake-but-signed-crate-bytes".to_vec();
    let crate_path = parent.join("demo-crate-0.1.0.crate");
    std::fs::write(&crate_path, &crate_bytes).unwrap();
    let spec = parent.join("spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"demo-crate\"\nversion = \"0.1.0\"\nkind = \"crate\"\n\
             path = \"{}\"\n",
            crate_path.display()
        ),
    )
    .unwrap();
    let layout = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "k", "--out"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();

    // The user's own working directory, and a RELATIVE --out inside it.
    let workdir = parent.join("workdir");
    std::fs::create_dir_all(&workdir).unwrap();
    varve(&fx)
        .current_dir(&workdir)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args([
            "export-cargo",
            "--layer",
            "2026.07.0",
            "--out",
            "./cargo-out",
        ])
        .assert()
        .success();

    let config = std::fs::read_to_string(workdir.join("cargo-out/.cargo/config.toml")).unwrap();
    let registry_line = config
        .lines()
        .find(|l| l.contains("local-registry"))
        .unwrap_or_else(|| panic!("no local-registry in:\n{config}"));
    let path = registry_line
        .split('"')
        .nth(1)
        .unwrap_or_else(|| panic!("unquoted path: {registry_line}"));
    assert!(
        std::path::Path::new(path).is_absolute(),
        "a config meant to be copied into another directory must not carry a \
         relative path: {registry_line}"
    );
    assert!(
        !path.starts_with("./") && !path.contains("/./"),
        "the path must be resolved, not merely prefixed: {registry_line}"
    );
}

// rivet: verifies REQ-VENDOR-001
#[test]
fn deposit_a_crate_kind_entry_and_export_crates_vendor() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // A REAL .crate-shaped gzip tar (export-crates-vendor unpacks it).
    let crate_bytes = {
        let mut b = tar::Builder::new(flate2::write::GzEncoder::new(
            Vec::new(),
            flate2::Compression::default(),
        ));
        for (name, body) in [
            (
                "vend-0.1.0/Cargo.toml",
                "[package]\nname=\"vend\"\nversion=\"0.1.0\"\n",
            ),
            ("vend-0.1.0/src/lib.rs", "pub fn v() {}\n"),
        ] {
            let mut h = tar::Header::new_gnu();
            h.set_size(body.len() as u64);
            h.set_mode(0o644);
            h.set_cksum();
            b.append_data(&mut h, name, body.as_bytes()).unwrap();
        }
        b.into_inner().unwrap().finish().unwrap()
    };
    let crate_path = parent.join("vend.crate");
    std::fs::write(&crate_path, &crate_bytes).unwrap();

    let spec = parent.join("deposit-spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"vend\"\nversion = \"0.1.0\"\nkind = \"crate\"\npath = \"{}\"\n",
            crate_path.display()
        ),
    )
    .unwrap();
    let dest = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-08-07T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&dest)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&dest)
        .assert()
        .success();

    let out = parent.join("vendor-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-crates-vendor", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .success()
        .stdout(predicate::str::contains("vendored 1 verified crate"));

    // The crate is UNPACKED with its checksum; the config uses a directory source.
    assert!(out.join("vendor/vend-0.1.0/Cargo.toml").is_file());
    let checksum =
        std::fs::read_to_string(out.join("vendor/vend-0.1.0/.cargo-checksum.json")).unwrap();
    assert!(checksum.contains(r#""package":"#), "{checksum}");
    let config = std::fs::read_to_string(out.join(".cargo/config.toml")).unwrap();
    assert!(config.contains("replace-with = \"vendored-sources\""));
}

fn status_doc_json(line: &str, counter: u64) -> String {
    format!(
        r#"{{
  "line": "{line}",
  "counter": {counter},
  "issued-at": "2026-08-07T00:00:00Z",
  "support-until": "2028-07-31",
  "yanked": {{ "{line}.0": "CVE-2026-0001 in synth" }},
  "known-problems": [
    {{ "id": "KP-1", "title": "fusion regression", "severity": "medium",
       "affected": ["{line}.0"], "workaround": "disable mla fusion" }}
  ]
}}"#
    )
}

// rivet: verifies REQ-KP-001
#[test]
fn status_reports_yank_and_known_problems_from_attached_evidence() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &signed.trust_root)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .success();

    // CI signs a status document…
    let (sk_path, doc_path, env_path) = (
        parent.join("status-root.key"),
        parent.join("status.json"),
        parent.join("status.dsse.json"),
    );
    // …with the SAME root the layer was signed by: reuse the fixture's key
    // is not possible (it is internal), so re-sign layer + status with one
    // key here instead.
    let (sk, pk) = varve_core::generate_root_keypair();
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust = parent.join("one-root.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();
    std::fs::write(&doc_path, status_doc_json("2026.07", 1)).unwrap();
    varve(&fx)
        .args(["sign-status", "--file"])
        .arg(&doc_path)
        .args(["--key"])
        .arg(&sk_path)
        .args(["--out"])
        .arg(&env_path)
        .assert()
        .success();

    // status ingests the envelope, caches it, and reports for the pin.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["status", "--from-file"])
        .arg(&env_path)
        .assert()
        .success()
        .stdout(
            predicate::str::contains("YANKED")
                .and(predicate::str::contains("CVE-2026-0001"))
                .and(predicate::str::contains("1 known problem"))
                .and(predicate::str::contains("2028-07-31")),
        );

    // Cached: no --from-file needed on the second ask.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("YANKED"));
}

// rivet: verifies REQ-KP-001
#[test]
fn status_refuses_a_stale_document_and_keeps_the_newer_cache() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("k.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust = parent.join("k.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();

    let sign = |counter: u64, out: &std::path::Path| {
        let doc = parent.join(format!("doc-{counter}.json"));
        std::fs::write(&doc, status_doc_json("2026.07", counter)).unwrap();
        varve(&fx)
            .args(["sign-status", "--file"])
            .arg(&doc)
            .args(["--key"])
            .arg(&sk_path)
            .args(["--out"])
            .arg(out)
            .assert()
            .success();
    };
    let newer = parent.join("newer.dsse.json");
    sign(3, &newer);
    let older = parent.join("older.dsse.json");
    sign(2, &older);

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["status", "--from-file"])
        .arg(&newer)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["status", "--from-file"])
        .arg(&older)
        .assert()
        .failure()
        .stderr(predicate::str::contains("stale"));
}

// rivet: verifies REQ-SELF-001
#[test]
fn self_verify_accepts_a_signed_release_file_and_refuses_a_tampered_one() {
    let fx = fixture(None, &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust = parent.join("release-root.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();

    let archive = parent.join("varve-v9.9.9-x.tar.gz");
    std::fs::write(&archive, b"tarball-bytes").unwrap();
    let digest = varve_core::manifest_digest(b"tarball-bytes");
    let sums = format!(
        "{}  ./varve-v9.9.9-x.tar.gz\n",
        digest.strip_prefix("sha256:").unwrap()
    );
    let envelope = varve_core::sign_release_sums(sums.as_bytes(), &sk, "k").unwrap();
    let env_path = parent.join("SHA256SUMS.txt.dsse.json");
    std::fs::write(&env_path, envelope).unwrap();

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["self-verify", "--archive"])
        .arg(&archive)
        .args(["--envelope"])
        .arg(&env_path)
        .assert()
        .success()
        .stdout(predicate::str::contains("verified"));

    std::fs::write(&archive, b"tampered!").unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["self-verify", "--archive"])
        .arg(&archive)
        .args(["--envelope"])
        .arg(&env_path)
        .assert()
        .failure()
        .stderr(predicate::str::contains("does not match"));
}

// rivet: verifies REQ-SELF-001
#[test]
fn sign_sums_produces_an_envelope_self_verify_accepts() {
    let fx = fixture(None, &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("r.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust = parent.join("r.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();

    let archive = parent.join("varve-v9.9.9-y.tar.gz");
    std::fs::write(&archive, b"bytes").unwrap();
    let digest = varve_core::manifest_digest(b"bytes");
    let sums_path = parent.join("SHA256SUMS.txt");
    std::fs::write(
        &sums_path,
        format!(
            "{}  ./varve-v9.9.9-y.tar.gz\n",
            digest.strip_prefix("sha256:").unwrap()
        ),
    )
    .unwrap();
    let env_path = parent.join("SHA256SUMS.txt.dsse.json");

    varve(&fx)
        .args(["sign-sums", "--sums"])
        .arg(&sums_path)
        .args(["--key"])
        .arg(&sk_path)
        .args(["--out"])
        .arg(&env_path)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["self-verify", "--archive"])
        .arg(&archive)
        .args(["--envelope"])
        .arg(&env_path)
        .assert()
        .success();
}

// rivet: verifies REQ-SHIM-002
#[cfg(unix)]
#[test]
fn a_shim_passes_non_utf8_arguments_through_byte_for_byte() {
    // A shim must hand the tool the EXACT bytes the caller typed: unix
    // arguments are arbitrary byte strings, and a filename is a common one.
    // Rewriting them lossily would corrupt data silently — the opposite of
    // this tool's contract.
    use std::ffi::OsStr;
    use std::os::unix::ffi::OsStrExt;
    let fx = fixture(Some(PIN_JULY), &[]);
    let store = varve_core::Store::at(&fx.root);
    // A probe that writes its argument's raw bytes out for comparison.
    let probe = b"#!/bin/sh\nprintf '%s' \"$1\" > \"$VARVE_ARG_OUT\"\n";
    store
        .lay_down(MANIFEST_JULY.as_bytes(), &[("probe", probe.as_slice())])
        .unwrap();
    varve(&fx).args(["shim", "install"]).assert().success();

    let out_file = fx.project.join("arg.bin");
    let nasty = OsStr::from_bytes(b"bad\xff\xfename");
    let status = std::process::Command::new(fx.root.join("shims").join("probe"))
        .arg(nasty)
        .current_dir(&fx.project)
        .env("VARVE_ROOT", &fx.root)
        .env("VARVE_ARG_OUT", &out_file)
        .status()
        .unwrap();
    assert!(status.success(), "shim dispatch failed");
    let got = std::fs::read(&out_file).unwrap();
    assert_eq!(
        got.as_slice(),
        b"bad\xff\xfename",
        "the shim rewrote the argument instead of passing it through"
    );
}

// rivet: verifies REQ-SHIM-002
#[cfg(unix)]
#[test]
fn a_shim_is_varve_itself_not_a_shell_script() {
    // REQ-SHIM-002: no /bin/sh on the dispatch path, and no string handed to a
    // shell parser. The shim must BE the varve binary, reached by a link.
    let fx = fixture(Some(PIN_JULY), &[(MANIFEST_JULY, &[("synth", b"s")])]);
    varve(&fx).args(["shim", "install"]).assert().success();
    let shim = fx.root.join("shims").join("synth");
    let bytes = std::fs::read(&shim).unwrap();
    assert!(
        !bytes.starts_with(b"#!"),
        "the shim is still a script: {}",
        String::from_utf8_lossy(&bytes[..bytes.len().min(80)])
    );
    #[cfg(unix)]
    {
        let meta = std::fs::symlink_metadata(&shim).unwrap();
        assert!(
            meta.file_type().is_symlink(),
            "on unix a shim should be a symlink to varve, so it tracks self-update"
        );
        // …and it must point at a real varve binary.
        let target = std::fs::read_link(&shim).unwrap();
        assert!(
            target
                .file_name()
                .unwrap()
                .to_string_lossy()
                .contains("varve"),
            "shim points at {target:?}, not the varve binary"
        );
    }
}

// rivet: verifies REQ-SHIM-001, REQ-SHIM-002
#[cfg(unix)]
#[test]
fn shims_resolve_per_invocation_so_switching_projects_is_cd() {
    let fx = fixture(Some(PIN_JULY), &[]);
    // Two layers, each with a `probe` tool that names itself.
    let store = varve_core::Store::at(&fx.root);
    for (layer, marker) in [("2026.07.0", "i-am-july"), ("2026.09.0", "i-am-september")] {
        let manifest = MANIFEST_JULY.replace("2026.07.0", layer);
        let script = format!("#!/bin/sh\necho {marker} layer=$VARVE_LAYER\n");
        store
            .lay_down(manifest.as_bytes(), &[("probe", script.as_bytes())])
            .unwrap();
    }
    // Two projects pinning different layers.
    let parent = fx.project.parent().unwrap();
    let project_sep = parent.join("project-sep");
    std::fs::create_dir_all(&project_sep).unwrap();
    std::fs::write(
        project_sep.join("varve.toml"),
        PIN_JULY.replace("2026.07.0", "2026.09.0"),
    )
    .unwrap();

    // Install shims once, from the July project.
    varve(&fx)
        .args(["shim", "install"])
        .assert()
        .success()
        .stdout(predicate::str::contains("shims"));
    let shim = fx.root.join("shims").join("probe");
    assert!(shim.is_file(), "shim written at {}", shim.display());

    // The SAME shim binary, invoked from each project dir, runs that
    // project's layer — switching toolchains is cd.
    let run_shim = |dir: &std::path::Path| {
        let out = std::process::Command::new(&shim)
            .current_dir(dir)
            .env("VARVE_ROOT", &fx.root)
            .output()
            .unwrap();
        (
            out.status.success(),
            String::from_utf8_lossy(&out.stdout).to_string(),
        )
    };
    let (ok_july, out_july) = run_shim(&fx.project);
    assert!(ok_july, "july project shim run failed: {out_july}");
    assert!(
        out_july.contains("i-am-july") && out_july.contains("layer=2026.07.0"),
        "{out_july}"
    );
    let (ok_sep, out_sep) = run_shim(&project_sep);
    assert!(ok_sep, "september project shim run failed: {out_sep}");
    assert!(
        out_sep.contains("i-am-september") && out_sep.contains("layer=2026.09.0"),
        "{out_sep}"
    );

    // No pin, no fallback: from a pinless directory the shim fails closed.
    let bare = parent.join("no-pin-here");
    std::fs::create_dir_all(&bare).unwrap();
    let out = std::process::Command::new(&shim)
        .current_dir(&bare)
        .env("VARVE_ROOT", &fx.root)
        .output()
        .unwrap();
    assert!(!out.status.success(), "a pinless dir must not resolve");
    assert!(String::from_utf8_lossy(&out.stderr).contains("varve.toml"));
}

// rivet: verifies REQ-ENV-001
#[cfg(unix)]
#[test]
fn env_is_evaluable_and_idempotent() {
    let fx = fixture(None, &[]);
    let out = varve(&fx).arg("env").output().unwrap();
    assert!(out.status.success());
    let script = String::from_utf8(out.stdout).unwrap();
    let shims = fx.root.join("shims");
    assert!(script.contains(shims.to_str().unwrap()), "{script}");

    // Evaluating twice must not stack duplicate PATH entries.
    let shell = format!(
        "eval \"$VARVE_ENV\"; eval \"$VARVE_ENV\"; printf '%s' \"$PATH\" | tr ':' '\\n' | grep -cx '{}'",
        shims.display()
    );
    let out = std::process::Command::new("sh")
        .arg("-c")
        .arg(&shell)
        .env("VARVE_ENV", &script)
        .env("PATH", std::env::var("PATH").unwrap())
        .output()
        .unwrap();
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "1",
        "shim dir must appear exactly once after double eval"
    );
}

// rivet: verifies REQ-ENV-001
#[cfg(unix)]
#[test]
fn shim_install_writes_a_sourceable_env_file() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let store = varve_core::Store::at(&fx.root);
    let script = "#!/bin/sh\necho from-the-layer\n";
    store
        .lay_down(MANIFEST_JULY.as_bytes(), &[("probe", script.as_bytes())])
        .unwrap();
    varve(&fx)
        .args(["shim", "install"])
        .assert()
        .success()
        .stdout(predicate::str::contains("env"));
    let env_file = fx.root.join("env");
    assert!(
        env_file.is_file(),
        "shim install must write {}",
        env_file.display()
    );

    // Sourcing the file makes the shim resolvable and runnable.
    let out = std::process::Command::new("sh")
        .arg("-c")
        .arg(format!(
            ". '{}' && cd '{}' && probe",
            env_file.display(),
            fx.project.display()
        ))
        .env("VARVE_ROOT", &fx.root)
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("from-the-layer"),
        "stdout: {} stderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
}

// rivet: verifies REQ-ENV-001
#[test]
fn completions_emit_per_shell_scripts() {
    let fx = fixture(None, &[]);
    varve(&fx)
        .args(["completions", "zsh"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#compdef varve"));
    varve(&fx)
        .args(["completions", "bash"])
        .assert()
        .success()
        .stdout(predicate::str::contains("complete"));
    varve(&fx)
        .args(["completions", "fish"])
        .assert()
        .success()
        .stdout(predicate::str::contains("complete -c varve"));
}

// rivet: verifies REQ-BAZEL-001
#[test]
fn spec_deposit_then_export_bazel_compiles_a_signature_anchored_registry() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust = parent.join("root.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();

    // Tool binary + a deposit spec carrying its source provenance.
    let host = varve_core::host_platform();
    let tool_path = parent.join("rivet-bin");
    std::fs::write(&tool_path, b"rivet-binary-bytes").unwrap();
    let spec_path = parent.join("deposit.toml");
    std::fs::write(
        &spec_path,
        format!(
            r#"layer = "2026.07.0"
channel = "qualified"
counter = 1

[[tool]]
name = "rivet"
version = "0.32.0"
platform = "{host}"
path = "{tool}"

[tool.source]
repo = "pulseengine/rivet"
release = "v0.32.0"
asset = "rivet-v0.32.0-{host}.tar.gz"
sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"#,
            tool = tool_path.display()
        ),
    )
    .unwrap();

    let dest = parent.join("spec-deposit");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec_path)
        .args(["--issued-at", "2026-08-07T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--out"])
        .arg(&dest)
        .assert()
        .success()
        .stdout(predicate::str::contains("2026.07.0"));

    // Install, then compile the Bazel registry from the verified layer.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["install", "--from"])
        .arg(&dest)
        .assert()
        .success();
    let out_dir = parent.join("bazel-registry");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["export-bazel", "--layer", "2026.07.0", "--out"])
        .arg(&out_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("rivet.json"));
    let json: serde_json::Value =
        serde_json::from_slice(&std::fs::read(out_dir.join("rivet.json")).unwrap()).unwrap();
    assert_eq!(json["github_repo"], "pulseengine/rivet");
    let key = varve_core::bazel::bazel_platform_key(&host).unwrap();
    assert_eq!(
        json["versions"]["0.32.0"]["platforms"][key]["sha256"],
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
    );
    assert!(
        json["_generated_by"]
            .as_str()
            .unwrap()
            .contains("Do not hand-edit")
    );
}

// rivet: verifies REQ-BAZEL-001
#[test]
fn export_bazel_refuses_without_a_trust_root() {
    let fx = fixture(Some(PIN_JULY), &[]);
    varve(&fx)
        .args(["export-bazel", "--layer", "2026.07.0", "--out"])
        .arg(fx.project.parent().unwrap().join("nowhere"))
        .assert()
        .failure()
        .stderr(predicate::str::contains("trust root"));
}

// rivet: verifies REQ-REALM-001
#[cfg(unix)]
#[test]
fn two_realms_same_layer_name_zero_cross_talk() {
    let fx = fixture(None, &[]);
    let parent = fx.project.parent().unwrap();

    // Two universes: same layer name and counter, different roots, and a
    // `probe` tool that names its universe.
    let mut realms_toml = String::new();
    let mut archives = std::collections::BTreeMap::new();
    for org in ["pulseengine", "acme"] {
        let (sk, pk) = varve_core::generate_root_keypair();
        let tool = format!("#!/bin/sh\necho universe={org} layer=$VARVE_LAYER\n");
        let digest = varve_core::manifest_digest(tool.as_bytes());
        let host = varve_core::host_platform();
        let payload = format!(
            r#"{{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "annotations": {{
    "eu.pulseengine.varve.layer": "2026.08.0",
    "eu.pulseengine.varve.line": "2026.08",
    "eu.pulseengine.varve.channel": "rolling",
    "eu.pulseengine.varve.counter": "5",
    "org.opencontainers.image.created": "2026-08-07T00:00:00Z"
  }},
  "manifests": [
    {{ "mediaType": "application/vnd.oci.image.manifest.v1+json",
       "digest": "{digest}", "size": 0,
       "annotations": {{ "eu.pulseengine.tool": "probe", "eu.pulseengine.platform": "{host}" }} }}
  ]
}}"#
        );
        let envelope = varve_core::sign_layer_manifest(payload.as_bytes(), &sk, "k").unwrap();
        let archive = parent.join(format!("archive-{org}"));
        varve_core::DirSource::at(&archive)
            .put(envelope.as_bytes(), &[(digest.as_str(), tool.as_bytes())])
            .unwrap();
        archives.insert(org.to_string(), archive);
        realms_toml.push_str(&format!(
            "[realm.{org}]\nregistry = \"oci://example.invalid/{org}\"\ntrust-root = \"{}\"\n\n",
            hex::encode(&pk)
        ));
    }
    std::fs::write(parent.join("varve-realms.toml"), realms_toml).unwrap();

    // Two projects pinning the SAME layer name in DIFFERENT realms.
    for org in ["pulseengine", "acme"] {
        let proj = parent.join(format!("proj-{org}"));
        std::fs::create_dir_all(&proj).unwrap();
        std::fs::write(
            proj.join("varve.toml"),
            format!(
                "manifest-version = 1\n[toolchain]\nrealm = \"{org}\"\nchannel = \"rolling\"\nlayer = \"2026.08.0\"\n"
            ),
        )
        .unwrap();
        // Install from each realm's archive; NO VARVE_TRUST_ROOT env — the
        // realm is authoritative and self-contained.
        let mut cmd = Command::cargo_bin("varve").unwrap();
        cmd.env("PATH", "/usr/bin:/bin"); // hermetic — see the note on `varve()`
        cmd.env("VARVE_ROOT", &fx.root)
            .env_remove("VARVE_TRUST_ROOT")
            .current_dir(&proj)
            .args(["install", "--from"])
            .arg(&archives[org])
            .assert()
            .success()
            .stdout(predicate::str::contains("2026.08.0"));
    }

    // One shim serves both universes: per-invocation resolution.
    let mut cmd = Command::cargo_bin("varve").unwrap();
    cmd.env("PATH", "/usr/bin:/bin"); // hermetic — see the note on `varve()`
    cmd.env("VARVE_ROOT", &fx.root)
        .current_dir(parent.join("proj-pulseengine"))
        .args(["shim", "install"])
        .assert()
        .success();
    let shim = fx.root.join("shims").join("probe");
    for (org, expect) in [
        ("pulseengine", "universe=pulseengine"),
        ("acme", "universe=acme"),
    ] {
        let out = std::process::Command::new(&shim)
            .current_dir(parent.join(format!("proj-{org}")))
            .env("VARVE_ROOT", &fx.root)
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            out.status.success() && stdout.contains(expect),
            "{org}: {stdout}"
        );
    }

    // Cross-acceptance impossible: acme's archive can NEVER install into the
    // pulseengine project (realm root refuses the signature).
    let mut cmd = Command::cargo_bin("varve").unwrap();
    cmd.env("PATH", "/usr/bin:/bin"); // hermetic — see the note on `varve()`
    cmd.env("VARVE_ROOT", &fx.root)
        .current_dir(parent.join("proj-pulseengine"))
        .args(["install", "--from"])
        .arg(&archives["acme"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("signature"));
}

// rivet: verifies REQ-RUNNER-001
#[cfg(unix)]
#[test]
fn portable_wasm_entries_dispatch_through_their_layer_runner() {
    let fx = fixture(None, &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust = parent.join("root.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();

    // A "runtime" that prints exactly how it was invoked, and a "wasm" blob.
    let runtime = parent.join("kilnd-double");
    std::fs::write(&runtime, "#!/bin/sh\necho invoked: \"$@\"\n").unwrap();
    let module = parent.join("scry.core.wasm");
    std::fs::write(&module, b"fake-wasm-bytes").unwrap();

    // Deposit: native runner + portable wasm entry carrying the contract.
    let host = varve_core::host_platform();
    let spec = parent.join("deposit.toml");
    std::fs::write(
        &spec,
        format!(
            r#"layer = "2026.09.0"
channel = "rolling"
counter = 1

[[tool]]
name = "kilnd"
version = "0.4.4"
platform = "{host}"
path = "{runtime}"

[[tool]]
name = "scry"
version = "3.2.4"
platform = "wasm32-wasip2"
path = "{module}"

[tool.runner]
tool = "kilnd"
args = ["--wasi", "--wasi-version", "preview2"]
arg-prefix = "--wasi-arg"
"#,
            runtime = runtime.display(),
            module = module.display()
        ),
    )
    .unwrap();
    let dest = parent.join("runner-deposit");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-08-08T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--out"])
        .arg(&dest)
        .assert()
        .success();

    // Install on THIS host: the wasm entry rides along (portable).
    std::fs::write(
        fx.project.join("varve.toml"),
        "manifest-version = 1\n[toolchain]\nchannel = \"rolling\"\nlayer = \"2026.09.0\"\n",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["install", "--from"])
        .arg(&dest)
        .assert()
        .success();

    // Dispatch: varve run -- scry --version x  →  the runner receives its
    // prefix args, then the module path, then per-arg-prefixed user args.
    varve(&fx)
        .args(["run", "--", "scry", "--version", "x"])
        .assert()
        .success()
        .stdout(
            predicate::str::is_match(
                r"invoked: --wasi --wasi-version preview2 .*bin/scry --wasi-arg --version --wasi-arg x",
            )
            .unwrap(),
        );
}

// rivet: verifies REQ-ONBOARD-001
#[test]
fn install_auto_caches_a_layout_carried_line_status_so_status_just_works() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust = parent.join("root.pub");
    std::fs::write(&trust, hex::encode(&pk)).unwrap();

    // Deposit a layer, then attach a signed line-status to its oci-layout.
    let sk_path = parent.join("root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let tool = parent.join("t");
    std::fs::write(&tool, b"toolbytes").unwrap();
    let spec = parent.join("d.toml");
    let host = varve_core::host_platform();
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n[[tool]]\nname = \"synth\"\nversion = \"1\"\nplatform = \"{host}\"\npath = \"{}\"\n",
            tool.display()
        ),
    )
    .unwrap();
    let layout = parent.join("layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-08-07T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--out"])
        .arg(&layout)
        .assert()
        .success();

    // Sign a line-status and attach it to the layout via the library.
    let status_json = r#"{"line":"2026.07","counter":1,"issued-at":"2026-08-07T00:00:00Z","support-until":"2028-07-31","yanked":{},"known-problems":[]}"#;
    let doc: varve_core::LineStatus = serde_json::from_str(status_json).unwrap();
    let envelope = doc
        .sign(
            &hex::decode(std::fs::read_to_string(&sk_path).unwrap().trim()).unwrap(),
            "k",
        )
        .unwrap();
    let line = "2026.07.0"
        .parse::<varve_core::LayerId>()
        .unwrap()
        .line()
        .clone();
    varve_core::attach_status_to_layout(&layout, &line, envelope.as_bytes()).unwrap();

    // Install — and then `varve status` works with NO --from-file (varve#34).
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust)
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("supported until 2028-07-31"));
}

// rivet: verifies REQ-ONBOARD-001
#[test]
fn the_trust_root_error_points_to_the_realm_path() {
    let fx = fixture(Some(PIN_JULY), &[]);
    let signed = signed_layer_fixture(&fx, "2026.07.0", 1);
    varve(&fx)
        .args(["install", "--from"])
        .arg(&signed.archive)
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("realm")
                .and(predicate::str::contains("rolling.pub"))
                .and(predicate::str::contains("Getting started")),
        );
}

// rivet: verifies REQ-COEXIST-001
#[test]
fn list_with_an_empty_core_succeeds_and_says_so() {
    let fx = fixture(None, &[]);
    varve(&fx)
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("no layers"));
}

// ──────────────── REQ-INDEXAUTH-001 through the shipped binary ────────────
//
// These drive the real `varve` executable, and that is the point. The whole
// requirement was implemented in varve-core, fully unit-tested, and reached
// nobody: the CLI's only `InstallPolicy` hardcoded `index: None`, so every
// clause was skipped at runtime while the suite stayed green. A test that
// constructs an `InstallPolicy` itself cannot detect that the product never
// constructs one — only a test that runs the binary can.

/// A project pinning its own realm, plus a deposited layout of one layer.
/// Returns (fixture, project dir, signing key, layout dir, payload digest).
fn realm_project(
    signed_index: bool,
) -> (
    Fixture,
    std::path::PathBuf,
    std::path::PathBuf,
    std::path::PathBuf,
    String,
) {
    let fx = fixture(None, &[]);
    let dir = fx.project.clone();
    let key = dir.join("root.key");
    let pubf = dir.join("root.pub");
    varve(&fx)
        .args(["keygen", "--out"])
        .arg(&key)
        .arg("--pub")
        .arg(&pubf)
        .assert()
        .success();
    let root = std::fs::read_to_string(&pubf).unwrap().trim().to_string();

    let tool = dir.join("acme-tool");
    std::fs::write(&tool, b"#!/bin/sh\necho acme\n").unwrap();
    let layout = dir.join("layout");
    varve(&fx)
        .args([
            "deposit",
            "--layer",
            "2026.08.0",
            "--channel",
            "qualified",
            "--counter",
            "3",
            "--issued-at",
            "2026-08-01T00:00:00Z",
            "--key",
        ])
        .arg(&key)
        .arg("--out")
        .arg(&layout)
        .arg("--tool")
        .arg(format!("acme-tool@1.0.0={}", tool.display()))
        .assert()
        .success();

    std::fs::write(
        dir.join("varve-realms.toml"),
        format!(
            "[realm.acme]\nregistry = \"oci://example.invalid/acme\"\n\
             trust-root = \"{root}\"\nsigned-index = {signed_index}\n"
        ),
    )
    .unwrap();
    std::fs::write(
        dir.join("varve.toml"),
        "manifest-version = 1\n[toolchain]\nrealm = \"acme\"\nchannel = \"qualified\"\nlayer = \"2026.08.0\"\n",
    )
    .unwrap();

    // The digest the deposited layer will install under — the entry in the
    // layout index that is not the signature.
    let index: serde_json::Value =
        serde_json::from_slice(&std::fs::read(layout.join("index.json")).unwrap()).unwrap();
    let payload_digest = index["manifests"]
        .as_array()
        .unwrap()
        .iter()
        .find(|e| e.get("artifactType").is_none())
        .and_then(|e| e["digest"].as_str())
        .expect("the layout names the layer manifest")
        .to_string();

    (fx, dir, key, layout, payload_digest)
}

// rivet: verifies REQ-INDEXAUTH-001
#[test]
fn the_binary_verifies_the_realms_index_and_reports_what_the_line_holds() {
    // Clauses 1, 4 and 5 end to end through the executable. The realm declares
    // `signed-index = true`; the source carries a signed index naming both the
    // pinned layer and a NEWER one it does not serve. The install must succeed
    // — the pin stays installable, which is the correction this release made —
    // and must SAY what the realm asserts, so the consumer learns about the
    // layer the source withheld instead of inferring it from silence.
    let (fx, dir, key, layout, payload_digest) = realm_project(true);

    let index_json = dir.join("index-2026.08.json");
    std::fs::write(
        &index_json,
        format!(
            r#"{{
  "line": "2026.08",
  "counter": 2,
  "issued-at": "2026-08-19T00:00:00Z",
  "layers": [
    {{ "layer": "2026.08.0", "digest": "{payload_digest}", "channel": "qualified", "counter": 3 }},
    {{ "layer": "2026.08.7", "digest": "sha256:notserved", "channel": "qualified", "counter": 9 }}
  ]
}}"#
        ),
    )
    .unwrap();
    let envelope = dir.join("index.dsse.json");
    varve(&fx)
        .args(["sign-index", "--file"])
        .arg(&index_json)
        .arg("--key")
        .arg(&key)
        .arg("--out")
        .arg(&envelope)
        .assert()
        .success()
        .stdout(predicate::str::contains("signed line-index #2"));
    varve(&fx)
        .args(["attach-index", "--layout"])
        .arg(&layout)
        .arg("--index")
        .arg(&envelope)
        .assert()
        .success();

    varve(&fx)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "installed layer 2026.08.0 (counter 3)",
        ))
        // Clause 4: REPORTED, naming the realm, the line, and both counters.
        .stdout(predicate::str::contains("realm 'acme'"))
        .stdout(predicate::str::contains("line 2026.08"))
        .stdout(predicate::str::contains("greatest counter 9"))
        .stdout(predicate::str::contains("accepted counter 3"));

    // …and the deliberately-pinned older layer really is installed and usable.
    // An earlier draft of clause 4 raised the ENFORCEMENT mark to 9 here and
    // this install failed with "rollback refused" — a frozen toolchain broken
    // by somebody else publishing.
    varve(&fx).arg("verify").assert().success();
    varve(&fx)
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("2026.08.0"));
}

// rivet: verifies REQ-INDEXAUTH-001
#[test]
fn the_binary_refuses_a_declaring_realm_whose_index_is_absent() {
    // Clause 5, the direction that makes the control a control. The realm says
    // it publishes an index; the source carries none. If this passed, an
    // attacker would disable the whole requirement by deleting one file — and
    // it DID pass, silently, for as long as the CLI hardcoded `index: None`.
    let (fx, _dir, _key, layout, _digest) = realm_project(true);
    varve(&fx)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .failure()
        .stderr(predicate::str::contains("acme"))
        .stderr(predicate::str::contains("will not fall back"));
    // Nothing was laid down on the strength of an unauthenticated listing.
    varve(&fx)
        .arg("list")
        .assert()
        .stdout(predicate::str::contains("2026.08.0").not());
}

// rivet: verifies REQ-INDEXAUTH-001
#[test]
fn a_realm_that_never_promised_an_index_installs_exactly_as_before() {
    // The other half of clause 5, and the reason the default is `false`:
    // failing closed by default would break every realm in existence at once.
    // The same layout, the same absent index, and no realm declaration.
    let (fx, _dir, _key, layout, _digest) = realm_project(false);
    varve(&fx)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success()
        .stdout(predicate::str::contains("installed layer 2026.08.0"))
        .stdout(predicate::str::contains("signed index").not());
    varve(&fx).arg("verify").assert().success();
}

// rivet: verifies REQ-OFFLINE-001
#[test]
fn archive_of_a_multi_platform_layer_says_what_it_carries_and_refuses_elsewhere() {
    // varve#80, at the boundary an operator actually touches. A tool name
    // repeats across triples while `install` lays down only the host's, so
    // `archive` used to write ONE host binary under every platform's digest and
    // exit 0 calling it the artifact of record. What matters here is that the
    // command SAYS which platform it carried and how much it left behind — an
    // operator carrying media to a mixed site must learn that before they
    // travel — and that a consumer on another platform is told so plainly.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let sk_path = parent.join("mp-root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("mp-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    for (file, bytes) in [("kilnd-a", b"kilnd-for-a"), ("kilnd-b", b"kilnd-for-b")] {
        std::fs::write(parent.join(file), bytes).unwrap();
    }
    let spec = parent.join("mp-spec.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"kilnd\"\nversion = \"1.0.0\"\n\
             platform = \"platform-a\"\npath = \"{a}\"\n\n\
             [[tool]]\nname = \"kilnd\"\nversion = \"1.0.0\"\n\
             platform = \"platform-b\"\npath = \"{b}\"\n",
            a = parent.join("kilnd-a").display(),
            b = parent.join("kilnd-b").display(),
        ),
    )
    .unwrap();
    let layout = parent.join("mp-layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "k", "--out"])
        .arg(&layout)
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .args(["--platform", "platform-a"])
        .assert()
        .success();

    // The archive names the platform it carries AND the entries it omits.
    let air_gapped = parent.join("mp-archive");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["archive", "2026.07.0"])
        .arg(&air_gapped)
        .args(["--platform", "platform-a"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("1 payload for platform-a")
                .and(predicate::str::contains("1 entry omitted"))
                .and(predicate::str::contains("platform-b (1)")),
        );

    // Every blob holds the bytes its digest names — CONTENT, not a count.
    for e in std::fs::read_dir(air_gapped.join("blobs/sha256")).unwrap() {
        let e = e.unwrap();
        let name = e.file_name().to_string_lossy().to_string();
        let bytes = std::fs::read(e.path()).unwrap();
        assert_eq!(
            varve_core::manifest_digest(&bytes),
            format!("sha256:{name}"),
            "blob {name} does not hold the bytes it is named for"
        );
    }

    // And the platform-b consumer is told what this archive is, not accused of
    // tampering — before varve#80 this was `does not match its signed digest`.
    varve(&fx)
        .env("VARVE_ROOT", parent.join("mp-far-root"))
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&air_gapped)
        .args(["--platform", "platform-b"])
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("carries no payload for platform-b")
                .and(predicate::str::contains("archived for platform-a")),
        );
}