varve 0.27.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
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
//! 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 REAL `.crate`-shaped gzip tar: `<name>-<version>/Cargo.toml` plus a source
/// file, with `extra` appended to the manifest.
///
/// Every crate fixture here is one now. Opaque bytes used to be enough because
/// `export-cargo` never opened the tarball — it wrote `"deps":[]` for every
/// crate (varve#73), so a fixture that could not have deps was indistinguishable
/// from one whose deps were dropped. The index is READ from these bytes now, so
/// the fixture has to be able to tell the truth.
fn dot_crate(name: &str, version: &str, extra_manifest: &str) -> Vec<u8> {
    let manifest = format!(
        "[package]\nname = \"{name}\"\nversion = \"{version}\"\nedition = \"2021\"\n{extra_manifest}"
    );
    let mut b = tar::Builder::new(flate2::write::GzEncoder::new(
        Vec::new(),
        flate2::Compression::default(),
    ));
    for (path, body) in [
        (format!("{name}-{version}/Cargo.toml"), manifest),
        (
            format!("{name}-{version}/src/lib.rs"),
            "pub fn f() {}\n".to_string(),
        ),
    ] {
        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, &path, body.as_bytes()).unwrap();
    }
    b.into_inner().unwrap().finish().unwrap()
}

/// 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 REAL `.crate` whose Cargo.toml declares a dependency and a feature:
    // `export-cargo` reads both out of the tarball for the index entry
    // (REQ-CRATEIDX-001), so a blob with nothing in it would not exercise it.
    let crate_bytes = dot_crate(
        "demo-crate",
        "0.1.0",
        "[dependencies]\ncfg-if = \"1\"\n\n[features]\ndefault = [\"std\"]\nstd = []\n",
    );
    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.
    let line: serde_json::Value = serde_json::from_str(idx.trim()).expect("{idx}");
    assert!(
        line["cksum"].is_string() && line["vers"] == "0.1.0",
        "{idx}"
    );
    // …and the wiring carries the DEPS and FEATURES out of the tarball, not a
    // stub: the CLI is where varve#73 was observed.
    assert_eq!(line["deps"][0]["name"], "cfg-if", "{idx}");
    assert_eq!(
        line["features"]["default"],
        serde_json::json!(["std"]),
        "{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 = dot_crate("serde", "1.0.200", "");
    let new_bytes = dot_crate("serde", "1.0.210", "[features]\nderive = []\n");
    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 a_per_platform_payload_exports_the_hosts_bytes_not_another_platforms_digest() {
    // Found by building the REAL pulseengine layer: spar ships one .vsix per
    // platform, and a layer carrying them could be deposited and installed but
    // NOT exported — `export-vsix` failed with "on-disk bytes do not match the
    // signed digest".
    //
    // `install` platform-filters, laying down only the host's payload.
    // `payloads_of_layer` did not filter at all, so it walked every platform's
    // manifest entry, resolved each to the ONE on-disk file (the payload path
    // is name/version and carries no platform), and compared the host's bytes
    // against a foreign platform's signed digest. The mismatch was real; the
    // conclusion drawn from it was wrong.
    //
    // This is latent for every per-platform non-tool payload, not just vsix —
    // it stayed hidden because no layer had carried one until now.
    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("pp-root.key");
    std::fs::write(&sk_path, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("pp-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    let host = varve_core::host_platform();
    let other = if host == "x86_64-unknown-linux-gnu" {
        "aarch64-apple-darwin"
    } else {
        "x86_64-unknown-linux-gnu"
    };

    // One extension, one version, DIFFERENT bytes per platform — so exporting
    // the wrong platform's digest cannot accidentally agree.
    let mut spec_text =
        String::from("layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n");
    for plat in [host.as_str(), other] {
        let path = parent.join(format!("spar-aadl-{plat}.vsix"));
        std::fs::write(&path, format!("vsix-bytes-for-{plat}")).unwrap();
        spec_text.push_str(&format!(
            "\n[[tool]]\nname = \"spar-aadl\"\nversion = \"0.36.0\"\nkind = \"vsix\"\n\
             platform = \"{plat}\"\npath = \"{}\"\n",
            path.display()
        ));
    }
    let spec = parent.join("pp-spec.toml");
    std::fs::write(&spec, &spec_text).unwrap();

    let layout = parent.join("pp-layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-31T09:14:00Z", "--key"])
        .arg(&sk_path)
        .args(["--key-id", "test-1", "--out"])
        .arg(&layout)
        .assert()
        .success();
    install_pinned(&fx, &trust_root, "2026.07.0", &layout);

    let out = parent.join("pp-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-vsix", "--out"])
        .arg(&out)
        .assert()
        .success();
    // Exactly one file — the host's — carrying the host's bytes.
    let exported: Vec<_> = std::fs::read_dir(&out)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| n.ends_with(".vsix"))
        .collect();
    assert_eq!(exported.len(), 1, "one platform's vsix, got {exported:?}");
    let body = std::fs::read_to_string(out.join(&exported[0])).unwrap();
    assert_eq!(
        body,
        format!("vsix-bytes-for-{host}"),
        "the exported bytes are not the host's"
    );
}

// rivet: verifies REQ-VSIX-001
#[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, REQ-REPRO-001
#[test]
fn a_relative_out_is_resolved_not_embedded_verbatim() {
    // CORRECTED IN v0.27.0 (REQ-REPRO-001 clause 1). This test used to demand
    // an ABSOLUTE path in the generated config. The bug it was written for was
    // real — an independent review made absolute_export_dir return its argument
    // verbatim and the whole suite stayed GREEN, because every other export
    // test passes an absolute --out — but "absolute" was the wrong fix for it.
    // An absolute path makes the export unreproducible (varve#72: the same
    // layer exported twice differs) and breaks the moment the export is moved.
    //
    // Settled EMPIRICALLY against a real Cargo before changing anything (the
    // `cargo_offline` oracle now pins it): Cargo resolves a relative
    // `local-registry` against the directory that HOLDS `.cargo/`, never
    // against the invoking cwd. So a bare subdirectory name is correct, stays
    // correct when the export is copied, and is identical between two runs.
    //
    // What the original bug actually was — a relative --out embedded VERBATIM,
    // and so resolved against whatever cwd the build later ran in — is still
    // pinned here: the emitted string must not be the user's `./cargo-out`.
    // 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 = dot_crate("demo-crate", "0.1.0", "");
    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 out = workdir.join("cargo-out");
    let config = std::fs::read_to_string(out.join(".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}"));

    // NOT the user's argument, verbatim or prefixed — that was the real bug.
    assert!(
        path != "./cargo-out" && !path.starts_with("./") && !path.contains("/./"),
        "the user's --out must not be embedded verbatim: {registry_line}"
    );
    // A bare relative subdirectory: nothing machine-specific, so two exports of
    // one layer are byte-identical (REQ-REPRO-001 clause 1).
    assert!(
        !std::path::Path::new(path).is_absolute() && !path.contains('/'),
        "the config must carry a bare relative subdirectory: {registry_line}"
    );
    // …and it must NAME something, resolved the way Cargo resolves it: against
    // the directory holding `.cargo/`, which is the export root.
    assert!(
        out.join(path).join("index").is_dir(),
        "the config names {path}, which must be the registry inside {}",
        out.display()
    );
}

// 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")),
        );
}

/// Every file under `dir`, keyed by its path RELATIVE to `dir`. The comparison
/// unit for REQ-REPRO-001 clause 3: two exports of one layer to two
/// destinations must agree on this map exactly, including the export stamp.
fn tree(dir: &std::path::Path) -> std::collections::BTreeMap<std::path::PathBuf, Vec<u8>> {
    let mut out = std::collections::BTreeMap::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        for e in std::fs::read_dir(&d).unwrap() {
            let p = e.unwrap().path();
            if p.is_dir() {
                stack.push(p);
            } else {
                out.insert(
                    p.strip_prefix(dir).unwrap().to_path_buf(),
                    std::fs::read(&p).unwrap(),
                );
            }
        }
    }
    out
}

// rivet: verifies REQ-REPRO-001
#[test]
fn every_export_adapter_is_byte_identical_between_two_runs() {
    // Clause 3, made permanent. varve#72 was found by exporting one layer twice
    // and diffing; the only difference was `.cargo/config.toml`, which embedded
    // an ABSOLUTE path. A new adapter is exactly where a stray timestamp or an
    // unordered map iteration will next appear, so every adapter is checked —
    // not the one that happened to be broken.
    //
    // The destinations differ in NAME as well as location, so an adapter that
    // leaked its `--out` anywhere into its output fails here.
    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();

    // One layer carrying every payload shape the adapters consume: a tool with
    // source provenance (export-bazel), two crates at two versions of one name
    // (export-cargo / -crates-vendor / -bazel-distdir), and two `.vsix`.
    let host = varve_core::host_platform();
    let tool_path = parent.join("rivet-bin");
    std::fs::write(&tool_path, b"rivet-binary-bytes").unwrap();
    let mut spec = 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()
    );
    for (name, version, extra) in [
        ("serde", "1.0.200", ""),
        ("serde", "1.0.210", "[features]\nderive = []\n"),
        ("cfg-if", "1.0.0", "[dependencies]\nserde = \"1.0\"\n"),
    ] {
        let p = parent.join(format!("{name}-{version}.crate"));
        std::fs::write(&p, dot_crate(name, version, extra)).unwrap();
        spec.push_str(&format!(
            "\n[[tool]]\nname = \"{name}\"\nversion = \"{version}\"\nkind = \"crate\"\npath = \"{}\"\n",
            p.display()
        ));
    }
    for (name, version) in [
        ("rust-lang.rust-analyzer", "0.3.2260"),
        ("vadimcn.vscode-lldb", "1.11.4"),
    ] {
        let p = parent.join(format!("{name}-{version}.vsix"));
        std::fs::write(&p, format!("{name}-{version}-zip").as_bytes()).unwrap();
        spec.push_str(&format!(
            "\n[[tool]]\nname = \"{name}\"\nversion = \"{version}\"\nkind = \"vsix\"\npath = \"{}\"\n",
            p.display()
        ));
    }
    let spec_path = parent.join("repro-spec.toml");
    std::fs::write(&spec_path, &spec).unwrap();
    let layout = parent.join("repro-layout");
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec_path)
        .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();

    for adapter in [
        "export-cargo",
        "export-crates-vendor",
        "export-bazel-distdir",
        "export-vsix",
        "export-bazel",
    ] {
        let first = parent.join(format!("{adapter}-alpha"));
        let second = parent.join(format!("{adapter}-a-much-longer-beta-name"));
        for out in [&first, &second] {
            varve(&fx)
                .env("VARVE_TRUST_ROOT", &trust_root)
                .args([adapter, "--layer", "2026.07.0", "--out"])
                .arg(out)
                .assert()
                .success();
        }
        let (a, b) = (tree(&first), tree(&second));
        assert_eq!(
            a.keys().collect::<Vec<_>>(),
            b.keys().collect::<Vec<_>>(),
            "{adapter} wrote a different set of files the second time"
        );
        for (path, bytes) in &a {
            assert_eq!(
                bytes,
                &b[path],
                "{adapter} is not reproducible: {} differs between two runs:\n--- first ---\n{}\n\
                 --- second ---\n{}",
                path.display(),
                String::from_utf8_lossy(bytes),
                String::from_utf8_lossy(&b[path]),
            );
        }
        assert!(
            !a.is_empty(),
            "{adapter} wrote nothing — a vacuous comparison"
        );
    }
}

/// Move the pin to `layer` and install that layer from `archive`. `install`
/// resolves the PIN, so a composition is installed one layer at a time — which
/// is what an extender does when they adopt an upstream realm's layer and then
/// pin their own on top.
fn install_pinned(
    fx: &Fixture,
    trust_root: &std::path::Path,
    layer: &str,
    archive: &std::path::Path,
) {
    std::fs::write(
        fx.project.join("varve.toml"),
        format!(
            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\n"
        ),
    )
    .unwrap();
    varve(fx)
        .env("VARVE_TRUST_ROOT", trust_root)
        .args(["install", "--from"])
        .arg(archive)
        .assert()
        .success();
}

/// A SIGNED layer holding `crate`-kind payloads, optionally composing other
/// layers by digest. Returns (archive directory, this layer's manifest digest).
///
/// `includes` is a slice, not an `Option`: a layer composing TWO others is the
/// shape that produces a diamond, and a helper that could only express one
/// include is why no test covered the diamond at the CLI boundary.
fn signed_crate_layer(
    fx: &Fixture,
    tag: &str,
    layer: &str,
    sk: &[u8],
    crates: &[(&str, &str, Vec<u8>)],
    includes: &[&str],
) -> (std::path::PathBuf, String) {
    let mut entries: Vec<String> = Vec::new();
    let mut blobs: Vec<(String, Vec<u8>)> = Vec::new();
    for (name, version, bytes) in crates {
        let d = varve_core::manifest_digest(bytes);
        entries.push(format!(
            r#"{{"mediaType":"application/octet-stream","digest":"{d}","size":{size},"annotations":{{"eu.pulseengine.varve.kind":"crate","eu.pulseengine.tool":"{name}","eu.pulseengine.tool.version":"{version}"}}}}"#,
            size = bytes.len()
        ));
        blobs.push((d, bytes.clone()));
    }
    for d in includes {
        // `digest` or `digest@realm`. An include that names a realm is
        // verified against THAT realm's root, not the includer's — the branch
        // that made composition worth having, and which no test could reach
        // while every fixture emitted realm-less includes.
        let (digest, realm) = match d.split_once('@') {
            Some((dg, r)) => (dg, Some(r)),
            None => (*d, None),
        };
        let realm_ann = realm
            .map(|r| format!(r#","eu.pulseengine.varve.include.realm":"{r}""#))
            .unwrap_or_default();
        entries.push(format!(
            r#"{{"mediaType":"application/vnd.oci.image.index.v1+json","digest":"{digest}","size":0,"annotations":{{"eu.pulseengine.varve.kind":"layer"{realm_ann}}}}}"#
        ));
    }
    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":"1","org.opencontainers.image.created":"2026-07-31T09:14:00Z"}},"manifests":[{}]}}"#,
        entries.join(",")
    );
    let digest = varve_core::manifest_digest(payload.as_bytes());
    let envelope = varve_core::sign_layer_manifest(payload.as_bytes(), sk, "test-root").unwrap();
    let archive = fx.project.parent().unwrap().join(format!("archive-{tag}"));
    let refs: Vec<(&str, &[u8])> = blobs
        .iter()
        .map(|(d, b)| (d.as_str(), b.as_slice()))
        .collect();
    varve_core::DirSource::at(&archive)
        .put(envelope.as_bytes(), &refs)
        .unwrap();
    (archive, digest)
}

// rivet: verifies REQ-COMPOSEEXPORT-001
#[test]
fn an_export_follows_the_composition() {
    // varve#79, reproduced at the boundary the user touches. An upstream layer
    // with a crate; a second layer `[[include]]`-ing it; before v0.27.0
    // `export-cargo` showed only the second layer's crate, with NO error — and
    // the build then failed with a missing-crate message pointing nowhere near
    // the cause. This is the topology varve is FOR.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("compose-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // Upstream: `cfg-if 1.0.0` and `serde 1.0.200`.
    let (up_archive, up_digest) = signed_crate_layer(
        &fx,
        "compose-up",
        "2026.08.0",
        &sk,
        &[
            ("cfg-if", "1.0.0", dot_crate("cfg-if", "1.0.0", "")),
            ("serde", "1.0.200", dot_crate("serde", "1.0.200", "")),
        ],
        &[],
    );
    // The pinned layer: its own crate, plus `serde` at a DIFFERENT version —
    // legal, and both must export (clause 2).
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "compose-root",
        "2026.07.0",
        &sk,
        &[
            (
                "rivet-core",
                "0.32.0",
                dot_crate("rivet-core", "0.32.0", ""),
            ),
            ("serde", "1.0.210", dot_crate("serde", "1.0.210", "")),
        ],
        &[&up_digest],
    );
    // `install` follows the pin, so the extender installs the upstream layer
    // under its own pin and then moves the pin to their own — the sequence a
    // consumer of two realms actually performs.
    install_pinned(&fx, &trust_root, "2026.08.0", &up_archive);
    install_pinned(&fx, &trust_root, "2026.07.0", &root_archive);

    let out = parent.join("composed-cargo");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-cargo", "--out"])
        .arg(&out)
        .assert()
        .success()
        // Clause 3: it SAYS it followed the composition, rather than producing
        // a quietly incomplete directory.
        .stdout(
            predicate::str::contains("following the composition")
                .and(predicate::str::contains("2026.08.0"))
                .and(predicate::str::contains("4 verified crate")),
        );

    // Every crate of BOTH layers is present — including two versions of one
    // name across the composition boundary.
    for (name, version) in [
        ("cfg-if", "1.0.0"),
        ("serde", "1.0.200"),
        ("serde", "1.0.210"),
        ("rivet-core", "0.32.0"),
    ] {
        assert!(
            out.join(format!("registry/{name}-{version}.crate"))
                .is_file(),
            "{name} {version} missing from the composed export"
        );
    }
    let idx = std::fs::read_to_string(out.join("registry/se/rd/serde"))
        .or_else(|_| std::fs::read_to_string(out.join("registry/index/se/rd/serde")))
        .unwrap();
    assert_eq!(
        idx.lines().filter(|l| !l.trim().is_empty()).count(),
        2,
        "the index must offer BOTH versions of serde: {idx}"
    );

    // …and the vendored adapter follows it too — one adapter fixed is not the
    // requirement.
    let vendor_out = parent.join("composed-vendor");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-crates-vendor", "--out"])
        .arg(&vendor_out)
        .assert()
        .success()
        .stdout(predicate::str::contains("4 verified crate"));
    assert!(vendor_out.join("vendor/cfg-if-1.0.0/Cargo.toml").is_file());
    assert!(
        vendor_out
            .join("vendor/rivet-core-0.32.0/Cargo.toml")
            .is_file()
    );
}

// rivet: verifies REQ-COMPOSEEXPORT-001
#[test]
fn an_export_verifies_a_composed_layer_against_its_own_realms_root() {
    // Clause 1b, which was dead code under test. Every composition-export
    // fixture emitted includes with NO `include.realm`, so `inc.realm` was
    // `None` in all of them and the cross-realm branch never ran. A clean-room
    // review confirmed it twice: swapping in the INCLUDER's verifier (trust
    // widening across realms) and deleting the branch outright both left the
    // whole suite green.
    //
    // Here the included layer is signed by a DIFFERENT key than the root
    // layer. Verifying it against the includer's root cannot succeed, so a
    // passing export is only possible if the realm's own root was used.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (up_sk, up_pk) = varve_core::generate_root_keypair();
    let (root_sk, root_pk) = varve_core::generate_root_keypair();
    assert_ne!(up_pk, root_pk, "the two realms must not share a root");

    // `upstream` is a realm of its own, with its own trust root.
    std::fs::write(
        parent.join("varve-realms.toml"),
        format!(
            "[realm.upstream]\nregistry = \"oci://example.invalid/upstream\"\ntrust-root = \"{}\"\n",
            hex::encode(&up_pk)
        ),
    )
    .unwrap();

    let (up_archive, up_digest) = signed_crate_layer(
        &fx,
        "xrealm-up",
        "2026.08.0",
        &up_sk,
        &[("serde", "1.0.200", dot_crate("serde", "1.0.200", ""))],
        &[],
    );
    // The include NAMES the realm, so the upstream root is the authority.
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "xrealm-root",
        "2026.07.0",
        &root_sk,
        &[(
            "rivet-core",
            "0.32.0",
            dot_crate("rivet-core", "0.32.0", ""),
        )],
        &[&format!("{up_digest}@upstream")],
    );

    let up_root = parent.join("xrealm-up.pub");
    std::fs::write(&up_root, hex::encode(&up_pk)).unwrap();
    let our_root = parent.join("xrealm-root.pub");
    std::fs::write(&our_root, hex::encode(&root_pk)).unwrap();
    install_pinned(&fx, &up_root, "2026.08.0", &up_archive);
    install_pinned(&fx, &our_root, "2026.07.0", &root_archive);

    let out = parent.join("xrealm-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &our_root)
        .args(["export-cargo", "--out"])
        .arg(&out)
        .assert()
        .success()
        .stdout(predicate::str::contains("following the composition"));
    // The composed realm's crate is present, so its layer really was verified
    // and followed rather than skipped.
    assert!(
        out.join("registry/serde-1.0.200.crate").is_file(),
        "the upstream realm's crate is missing from the composed export"
    );
}

// rivet: verifies REQ-COMPOSEEXPORT-001
#[test]
fn verify_lockfile_follows_the_composition_not_just_the_root() {
    // REQ-COMPOSEEXPORT-001 clause 1's extension: a lockfile checked against
    // only the ROOT layer silently asserts nothing about the crates the
    // INCLUDED layers pin — varve#79 wearing a different hat.
    //
    // This clause shipped in v0.27.0 with no test naming it. A clean-room
    // review replaced the composition walk with a root-only vec and the ENTIRE
    // workspace suite stayed green; the stub was then swept into a commit by an
    // unrelated `git add -A` and pushed, still green. A clause no test can
    // distinguish from its own absence is indistinguishable from unimplemented.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("lockcompose-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // The crate that will disagree lives ONLY in the included layer.
    let (up_archive, up_digest) = signed_crate_layer(
        &fx,
        "lockcompose-up",
        "2026.08.0",
        &sk,
        &[("serde", "1.0.200", dot_crate("serde", "1.0.200", ""))],
        &[],
    );
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "lockcompose-root",
        "2026.07.0",
        &sk,
        &[(
            "rivet-core",
            "0.32.0",
            dot_crate("rivet-core", "0.32.0", ""),
        )],
        &[&up_digest],
    );
    install_pinned(&fx, &trust_root, "2026.08.0", &up_archive);
    install_pinned(&fx, &trust_root, "2026.07.0", &root_archive);

    // The project resolves a DIFFERENT serde than the composed layer pins.
    // Root-only checking cannot see this: the root layer has no serde at all.
    let lock = fx.project.join("Cargo.lock");
    std::fs::write(
        &lock,
        "version = 4\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.99\"\nchecksum = \"aaaa\"\n",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["verify", "--lockfile"])
        .arg(&lock)
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("1.0.200")
                .and(predicate::str::contains("1.0.99"))
                .and(predicate::str::contains("disagree")),
        );

    // …and agreement with the COMPOSED layer's crate passes.
    std::fs::write(
        &lock,
        "version = 4\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.200\"\n",
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["verify", "--lockfile"])
        .arg(&lock)
        .assert()
        .success();
}

// rivet: verifies REQ-COMPOSE-001
#[test]
fn verify_walks_a_diamond_once_instead_of_calling_it_a_cycle() {
    // A diamond — two layers sharing a base — is the most ordinary composition
    // there is, and both `docs composition` and `docs layers` promise it is
    // "walked once and is perfectly legal". `compose::walk` was fixed for this
    // in v0.23.0; `verify_composition_inner` is an INDEPENDENT reimplementation
    // in the CLI that kept the bug, so `varve verify` exited 1 on a store that
    // `install`, `run`, `which` and every export handled correctly. Found by a
    // persona audit driving the real binary — no unit test could see it,
    // because the broken walker lives in the binary crate and the correct one
    // in the library.
    //
    // Shape: root composes MID and BASE; MID also composes BASE.
    //   root ─┬─> mid ──> base
    //         └─────────> base
    // BASE is reachable by two paths and is on NEITHER path twice.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("diamond-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    let (base_archive, base_digest) = signed_crate_layer(
        &fx,
        "diamond-base",
        "2026.08.0",
        &sk,
        &[("cfg-if", "1.0.0", dot_crate("cfg-if", "1.0.0", ""))],
        &[],
    );
    let (mid_archive, mid_digest) = signed_crate_layer(
        &fx,
        "diamond-mid",
        "2026.08.1",
        &sk,
        &[("serde", "1.0.200", dot_crate("serde", "1.0.200", ""))],
        &[&base_digest],
    );
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "diamond-root",
        "2026.07.0",
        &sk,
        &[(
            "rivet-core",
            "0.32.0",
            dot_crate("rivet-core", "0.32.0", ""),
        )],
        &[&mid_digest, &base_digest],
    );

    // `install` follows the pin, so each layer is installed under its own pin
    // before the pin moves to the root — the sequence a real consumer performs.
    install_pinned(&fx, &trust_root, "2026.08.0", &base_archive);
    install_pinned(&fx, &trust_root, "2026.08.1", &mid_archive);
    install_pinned(&fx, &trust_root, "2026.07.0", &root_archive);

    // The whole finding: this exited 1 with "composition cycle while verifying".
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("composes"));
}

// rivet: verifies REQ-COMPOSE-001
#[test]
fn verify_does_not_mistake_a_wide_composition_for_a_deep_one() {
    // The second defect of the same wrong data structure, and the reason the
    // fix is a path rather than a bigger set. `verify` guarded depth with
    // `path.len() > MAX_DEPTH` on an insert-only set, so the counter measured
    // every layer VISITED, not how deep the walk had gone. A root composing
    // MAX_DEPTH+2 sibling layers is one level deep and was refused as "more
    // than 8 layers deep".
    //
    // A cycle, by contrast, is deliberately NOT tested at this boundary: an
    // include is content-addressed, so a layer including itself would need its
    // own digest to depend on its own content, and a hand-edited layer.json is
    // refused earlier by the tamper check ("the core entry was modified after
    // install"). The cycle guard is retained as defence in depth against a
    // future non-content-addressed include, not because a test can reach it.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("wide-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    let width = varve_core::compose::MAX_DEPTH + 2;
    let mut archives = Vec::new();
    let mut digests = Vec::new();
    for i in 0..width {
        let (archive, digest) = signed_crate_layer(
            &fx,
            &format!("wide-{i}"),
            // Distinct layer ids so each installs under its own pin.
            &format!("2026.08.{i}"),
            &sk,
            &[(
                "cfg-if",
                &format!("1.0.{i}"),
                dot_crate("cfg-if", &format!("1.0.{i}"), ""),
            )],
            &[],
        );
        archives.push((format!("2026.08.{i}"), archive));
        digests.push(digest);
    }
    let refs: Vec<&str> = digests.iter().map(|d| d.as_str()).collect();
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "wide-root",
        "2026.07.0",
        &sk,
        &[(
            "rivet-core",
            "0.32.0",
            dot_crate("rivet-core", "0.32.0", ""),
        )],
        &refs,
    );

    for (layer, archive) in &archives {
        install_pinned(&fx, &trust_root, layer, archive);
    }
    install_pinned(&fx, &trust_root, "2026.07.0", &root_archive);

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .arg("verify")
        .assert()
        .success();
}

// rivet: verifies REQ-COMPOSEEXPORT-001
#[test]
fn an_export_refuses_a_composed_layer_it_cannot_vouch_for() {
    // Clause 1: each included layer is verified against ITS OWN realm's root,
    // and an export is not a way around that. Trust must not widen because a
    // layer was reached through an include rather than through the pin.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("badcompose-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    // An UNSIGNED upstream layer, laid straight into the store.
    let store = varve_core::Store::at(&fx.root);
    let up_manifest = manifest_with_includes("2026.08.0", &[], &[]);
    let up_digest = store.lay_down(up_manifest.as_bytes(), &[]).unwrap();

    let (root_archive, _) = signed_crate_layer(
        &fx,
        "badcompose-root",
        "2026.07.0",
        &sk,
        &[(
            "rivet-core",
            "0.32.0",
            dot_crate("rivet-core", "0.32.0", ""),
        )],
        &[&up_digest],
    );
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["install", "--from"])
        .arg(&root_archive)
        .assert()
        .success();

    let out = parent.join("badcompose-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-cargo", "--out"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(predicate::str::contains("2026.08.0"));
    assert!(
        !out.join("registry").exists(),
        "a refused export must not leave a directory that looks complete"
    );
}

// rivet: verifies REQ-COMPOSEEXPORT-001
#[test]
fn an_export_refuses_two_layers_that_disagree_about_one_crate() {
    // Clause 2's error case at the CLI. The same crate name at DIFFERENT
    // versions is legal and both export (proven above); the same name AND
    // version with DIFFERENT digests is two realms disagreeing about what those
    // bytes are, and varve does not pick a winner.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("clash-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    let (up_archive, up_digest) = signed_crate_layer(
        &fx,
        "clash-up",
        "2026.08.0",
        &sk,
        &[("cfg-if", "1.0.0", dot_crate("cfg-if", "1.0.0", ""))],
        &[],
    );
    // Same name, same version, DIFFERENT bytes.
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "clash-root",
        "2026.07.0",
        &sk,
        &[(
            "cfg-if",
            "1.0.0",
            dot_crate("cfg-if", "1.0.0", "[features]\nstd = []\n"),
        )],
        &[&up_digest],
    );
    install_pinned(&fx, &trust_root, "2026.08.0", &up_archive);
    install_pinned(&fx, &trust_root, "2026.07.0", &root_archive);

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-cargo", "--out"])
        .arg(parent.join("clash-out"))
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("cfg-if")
                .and(predicate::str::contains("1.0.0"))
                .and(predicate::str::contains("DIFFERENT bytes")),
        );
}

// rivet: verifies REQ-COMPOSEEXPORT-001
#[test]
fn an_export_that_cannot_follow_the_composition_says_so() {
    // Clause 3. `install` refuses a composition whose include is missing, and
    // `resolve` refuses to dispatch one — but an export named with `--layer`
    // takes neither path, so a layer removed from the store AFTER install left
    // the export adapters free to write a directory that is quietly missing an
    // entire layer's crates. That is exactly varve#79's failure mode: no error,
    // and a build that fails later pointing nowhere near the cause.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let (sk, pk) = varve_core::generate_root_keypair();
    let trust_root = parent.join("gone-root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();

    let (up_archive, up_digest) = signed_crate_layer(
        &fx,
        "gone-up",
        "2026.08.0",
        &sk,
        &[("cfg-if", "1.0.0", dot_crate("cfg-if", "1.0.0", ""))],
        &[],
    );
    let (root_archive, _) = signed_crate_layer(
        &fx,
        "gone-root",
        "2026.07.0",
        &sk,
        &[(
            "rivet-core",
            "0.32.0",
            dot_crate("rivet-core", "0.32.0", ""),
        )],
        &[&up_digest],
    );
    install_pinned(&fx, &trust_root, "2026.08.0", &up_archive);
    install_pinned(&fx, &trust_root, "2026.07.0", &root_archive);

    // The composed layer disappears from the core after installation.
    let store = varve_core::Store::at(&fx.root);
    let up = store
        .list()
        .unwrap()
        .into_iter()
        .find(|l| l.layer.to_string() == "2026.08.0")
        .expect("the upstream layer is installed");
    std::fs::remove_dir_all(&up.root).unwrap();

    let out = parent.join("gone-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &trust_root)
        .args(["export-cargo", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .failure()
        // …naming what is missing and how to fix it, not exiting 0 with one
        // layer's crates.
        .stderr(
            predicate::str::contains("not installed")
                .and(predicate::str::contains("varve install"))
                .and(predicate::str::contains("silently omit")),
        );
    assert!(
        !out.join("registry").exists(),
        "an export that could not follow the composition must not leave a registry"
    );
}

// ───────────────────────────────────────────────────────────────────────────
// The library surface the SDK workstream left unwired: `export-sdk`, declared
// exports, the shadowing declaration, and `varve env`. Every test below drives
// the BINARY. A test that builds the policy itself cannot detect that the
// product never builds one — which is exactly how REQ-INDEXAUTH-001 shipped a
// `must` clause that no code path could reach.
// ───────────────────────────────────────────────────────────────────────────

/// The prefix an SDK must have been BUILT for so that `dest` fits inside its
/// relocation budget.
///
/// Not a constant: relocation can only ever SHORTEN a path (the interpreter
/// field is fixed-size), and a temporary directory is long. A hard-coded prefix
/// would make these tests pass or fail on the length of `$TMPDIR`, which is the
/// machine-dependent suite the hermetic PATH exists to prevent.
fn built_prefix_for(dest: &std::path::Path) -> String {
    let need = dest.to_str().expect("a utf-8 temp path").len();
    let mut s = String::from("/opt/poky/4.0.15/sysroots/x86_64-pokysdk-linux");
    while s.len() < need {
        s.push('p');
    }
    s
}

/// A synthetic Yocto SDK as the gzip tar a producer signs: a NUL-padded binary
/// field (the `relocate_sdk.py` half), a text `environment-setup-*` (the
/// `sed -i` half), an absolute symlink, and a `bin/synth` that will shadow the
/// pinned tool once the tree is on PATH.
fn sdk_tarball(built: &str) -> Vec<u8> {
    use std::io::Write;
    // A NUL-padded path field, the way an ELF PT_INTERP segment holds one.
    let field = |s: &str| {
        let mut v = s.as_bytes().to_vec();
        v.resize(s.len() + 8, 0);
        v
    };
    let mut binary = b"\x7fELF".to_vec();
    binary.extend_from_slice(&field(&format!(
        "{built}/sysroots/x86_64/lib/ld-linux.so.2"
    )));
    binary.extend_from_slice(b"\0\0trailer\0");
    // A REAL environment script: after relocation its PATH line points at the
    // export, which is what makes `eval "$(varve env)"` testable end to end.
    let env_setup = format!(
        "export SDKTARGETSYSROOT=\"{built}/sysroots/cortexa53\"\n\
         export PATH=\"{built}/bin:$PATH\"\n\
         export CC=\"aarch64-poky-linux-gcc --sysroot={built}/sysroots/cortexa53\"\n"
    );
    let synth = "#!/bin/sh\necho SDK-SYNTH\n";

    let mut tar_bytes = Vec::new();
    {
        let mut b = tar::Builder::new(&mut tar_bytes);
        let mut dir = tar::Header::new_gnu();
        dir.set_entry_type(tar::EntryType::Directory);
        dir.set_size(0);
        dir.set_mode(0o755);
        b.append_data(&mut dir, "sysroots/", std::io::empty())
            .unwrap();
        for (path, mode, bytes) in [
            (
                "sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc",
                0o755u32,
                binary.as_slice(),
            ),
            (
                "environment-setup-cortexa53-poky-linux",
                0o644,
                env_setup.as_bytes(),
            ),
            ("bin/synth", 0o755, synth.as_bytes()),
        ] {
            let mut h = tar::Header::new_gnu();
            h.set_size(bytes.len() as u64);
            h.set_mode(mode);
            b.append_data(&mut h, path, bytes).unwrap();
        }
        let mut link = tar::Header::new_gnu();
        link.set_entry_type(tar::EntryType::Symlink);
        link.set_size(0);
        link.set_mode(0o777);
        // `append_link`, not `set_link_name`: a real SDK's build prefix is
        // routinely past the 100-byte header field, and tar's GNU LongLink
        // record is how that is carried. A fixture that could only express a
        // short target would test a case the requirement is not about.
        b.append_link(
            &mut link,
            "bin/synth-latest",
            std::path::Path::new(&format!("{built}/bin/synth")),
        )
        .unwrap();
        b.finish().unwrap();
    }
    let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
    gz.write_all(&tar_bytes).unwrap();
    gz.finish().unwrap()
}

/// A signed root plus its key files, the two lines every one of these tests
/// starts with.
struct Root {
    key: std::path::PathBuf,
    trust_root: std::path::PathBuf,
}

fn root_at(parent: &std::path::Path) -> Root {
    let (sk, pk) = varve_core::generate_root_keypair();
    let key = parent.join("root.key");
    std::fs::write(&key, hex::encode(&sk)).unwrap();
    let trust_root = parent.join("root.pub");
    std::fs::write(&trust_root, hex::encode(&pk)).unwrap();
    Root { key, trust_root }
}

/// Deposit `spec_text` and install it — every test here needs a real, signed,
/// installed layer, because `export_target` verifies before it exports.
fn deposit_and_install(fx: &Fixture, root: &Root, spec_text: &str, tag: &str) {
    let parent = fx.project.parent().unwrap();
    let spec = parent.join(format!("{tag}-spec.toml"));
    std::fs::write(&spec, spec_text).unwrap();
    let layout = parent.join(format!("{tag}-layout"));
    varve(fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&root.key)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(&layout)
        .assert()
        .success();
    varve(fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["install", "--from"])
        .arg(&layout)
        .assert()
        .success();
}

// rivet: verifies REQ-SDK-001
#[cfg(unix)]
#[test]
fn export_sdk_lays_a_relocated_tree_down_through_the_cli() {
    // REQ-SDK-001 clause 3, at the boundary a user touches. The library could
    // relocate a tree since v0.27.0 and NOTHING could ask it to: there was no
    // subcommand, and no producer path for the signed prefix clause 4 requires.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);

    let out = parent.join("poky");
    std::fs::create_dir_all(&out).unwrap();
    let dest = out.canonicalize().unwrap();
    let built = built_prefix_for(&dest);
    let archive = parent.join("poky-sdk.tar.gz");
    let archive_bytes = sdk_tarball(&built);
    std::fs::write(&archive, &archive_bytes).unwrap();

    deposit_and_install(
        &fx,
        &root,
        &format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"poky-cortexa53\"\nversion = \"4.0.15\"\nkind = \"sdk\"\n\
             sdk-prefix = \"{built}\"\npath = \"{}\"\n",
            archive.display()
        ),
        "sdk",
    );

    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["export-sdk", "--layer", "2026.07.0", "--out"])
        .arg(&out)
        .assert()
        .success()
        .stdout(
            predicate::str::contains("exported sdk poky-cortexa53@4.0.15")
                .and(predicate::str::contains("field(s) patched in place")),
        );

    // The tree is HERE, relocated: no occurrence of the build prefix survives,
    // and the destination is what the binaries now name.
    let gcc = dest.join("sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc");
    let gcc_bytes = std::fs::read(&gcc).unwrap();
    assert!(
        !String::from_utf8_lossy(&gcc_bytes).contains(&built),
        "the interpreter field still names the build prefix"
    );
    assert!(String::from_utf8_lossy(&gcc_bytes).contains(dest.to_str().unwrap()));
    assert_eq!(
        gcc_bytes.len(),
        archive_len_preserving_probe(&built),
        "a binary field is patched IN PLACE — the file length must not move"
    );
    {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            std::fs::metadata(&gcc).unwrap().permissions().mode() & 0o111,
            0o111,
            "a compiler must survive the export executable"
        );
    }
    let env_script = std::fs::read_to_string(dest.join("environment-setup-cortexa53-poky-linux"))
        .expect("the sourceable script is part of the tree");
    assert!(env_script.contains(dest.to_str().unwrap()));
    assert!(!env_script.contains(&built));
    assert_eq!(
        std::fs::read_link(dest.join("bin/synth-latest")).unwrap(),
        dest.join("bin/synth"),
        "an SDK-internal absolute symlink is re-pointed into the export"
    );

    // Clause 2: the store still holds EXACTLY the bytes the producer signed —
    // nothing on the relocation path writes back into it — so `verify` (which
    // re-hashes that one file) still passes.
    let store = varve_core::Store::at(&fx.root);
    let installed = store
        .list()
        .unwrap()
        .into_iter()
        .find(|l| l.layer.to_string() == "2026.07.0")
        .unwrap();
    let held = installed.root.join("payloads/poky-cortexa53/4.0.15");
    assert_eq!(
        std::fs::read(&held).unwrap(),
        archive_bytes,
        "the store must keep the signed archive, not the relocated tree"
    );
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .success();

    // The stamp says `sdk` EXACTLY — a declaration in varve.toml is compared
    // against this string, and any other spelling reports the declared export
    // as never produced.
    let stamp: serde_json::Value =
        serde_json::from_slice(&std::fs::read(dest.join(".varve-export.json")).unwrap()).unwrap();
    assert_eq!(stamp["kind"], "sdk");
    assert_eq!(stamp["layer"], "2026.07.0");
}

/// The synthetic binary's length, recomputed from the same rule the fixture
/// builds it with — asserting a NUMBER here would be asserting the fixture.
fn archive_len_preserving_probe(built: &str) -> usize {
    // b"\x7fELF" + field(interp) + b"\0\0trailer\0"
    4 + (format!("{built}/sysroots/x86_64/lib/ld-linux.so.2").len() + 8) + 10
}

/// The same fixture, plus ONE symlink that is absolute, sits under the build
/// prefix, and climbs out of the export with `..`.
fn sdk_tarball_with_escaping_link(built: &str) -> Vec<u8> {
    use std::io::Write;
    let inner = sdk_tarball(built);
    let mut tar_bytes = Vec::new();
    {
        let mut b = tar::Builder::new(&mut tar_bytes);
        let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(inner.as_slice()));
        for entry in ar.entries().unwrap() {
            let entry = entry.unwrap();
            let mut h = entry.header().clone();
            let path = entry.path().unwrap().into_owned();
            if let Some(link) = entry.link_name().unwrap() {
                b.append_link(&mut h, &path, &link).unwrap();
            } else {
                let mut bytes = Vec::new();
                {
                    use std::io::Read;
                    let mut e = entry;
                    e.read_to_end(&mut bytes).unwrap();
                }
                h.set_size(bytes.len() as u64);
                b.append_data(&mut h, &path, bytes.as_slice()).unwrap();
            }
        }
        let mut link = tar::Header::new_gnu();
        link.set_entry_type(tar::EntryType::Symlink);
        link.set_size(0);
        link.set_mode(0o777);
        b.append_link(
            &mut link,
            "bin/escape-abs-dotdot",
            std::path::Path::new(&format!("{built}/../../../../../../../../tmp/varve-pwned")),
        )
        .unwrap();
        b.finish().unwrap();
    }
    let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
    gz.write_all(&tar_bytes).unwrap();
    gz.finish().unwrap()
}

// rivet: verifies REQ-SDK-001
#[test]
fn export_sdk_refuses_an_absolute_symlink_that_climbs_out_of_the_export() {
    // Clause 5 at the boundary that found it. A clean-room review reproduced
    // this end to end through the RELEASE binary: a symlink that is absolute,
    // starts with the SDK's own build prefix, and then climbs out with `..`
    // was re-pointed into the export and reported as "1 symlink(s)
    // re-pointed" — exit 0. The branch that re-points an SDK's internal
    // absolute links stripped the prefix without walking the remainder, while
    // the relative branch beside it had always walked its target.
    //
    // The library test for this lives in sdkexport.rs. It is repeated here
    // because "the invariant was verified in the library while nothing could
    // reach it" is a defect this very release shipped once already.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);
    // Long enough that the clause-4 fit check (destination must be no longer
    // than the build prefix) passes and clause 5 is what actually decides.
    let built = "/opt/poky/3.1/sysroots/x86_64-pokysdk-linux/usr/share/long-enough-prefix/padding";
    let archive = parent.join("escaping-sdk.tar.gz");
    std::fs::write(&archive, sdk_tarball_with_escaping_link(built)).unwrap();
    deposit_and_install(
        &fx,
        &root,
        &format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"poky\"\nversion = \"4.0\"\nkind = \"sdk\"\n\
             sdk-prefix = \"{built}\"\npath = \"{}\"\n",
            archive.display()
        ),
        "sdk",
    );
    let out = parent.join("escaping-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["export-sdk", "--out"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(predicate::str::contains("escape-abs-dotdot"));
    assert!(
        !out.join(".varve-export.json").exists(),
        "a refused export must not be stamped as one"
    );
}

// rivet: verifies REQ-SDK-001
#[test]
fn export_sdk_refuses_a_destination_the_sdk_cannot_reach_before_writing_anything() {
    // Clause 4 through the CLI: the refusal is EARLY (the archive is never
    // even opened) and names the budget, because "it failed" after relocating
    // thousands of files is not an answer anyone can act on.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);
    let archive = parent.join("poky-sdk.tar.gz");
    std::fs::write(&archive, sdk_tarball("/opt/tiny")).unwrap();
    deposit_and_install(
        &fx,
        &root,
        &format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"poky\"\nversion = \"4.0\"\nkind = \"sdk\"\n\
             sdk-prefix = \"/opt/tiny\"\npath = \"{}\"\n",
            archive.display()
        ),
        "sdk",
    );
    let out = parent.join("a-destination-far-longer-than-the-build-prefix");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["export-sdk", "--out"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("cannot relocate this sdk")
                .and(predicate::str::contains("/opt/tiny"))
                .and(predicate::str::contains("at most 9 characters")),
        );
    assert!(
        !out.join(".varve-export.json").exists(),
        "a refused export must not be stamped as one"
    );
    assert!(
        !out.join("bin").exists(),
        "the refusal must land before any byte of the tree"
    );
}

// rivet: verifies REQ-SDK-001
#[test]
fn an_sdk_without_the_signed_prefix_cannot_be_deposited_at_all() {
    // Clause 4's producing half. The budget is attributable or it is nothing:
    // an sdk with no signed prefix would install, verify, and be impossible to
    // export — discovered on the far side of an air gap, unfixable without a
    // re-deposit, because the annotation lives inside the signature.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);
    let archive = parent.join("poky-sdk.tar.gz");
    std::fs::write(&archive, sdk_tarball("/opt/poky")).unwrap();
    let spec = parent.join("no-prefix.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"poky\"\nversion = \"4.0\"\nkind = \"sdk\"\npath = \"{}\"\n",
            archive.display()
        ),
    )
    .unwrap();
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&root.key)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(parent.join("nope"))
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("declares no `sdk-prefix`")
                .and(predicate::str::contains("export-sdk")),
        );

    // …and the same field on a payload nobody relocates is refused rather than
    // signed, ignored, and believed.
    let bin = parent.join("synth-bin");
    std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
    let spec = parent.join("prefix-on-a-tool.toml");
    std::fs::write(
        &spec,
        format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"1.0\"\n\
             sdk-prefix = \"/opt/poky\"\npath = \"{}\"\n",
            bin.display()
        ),
    )
    .unwrap();
    varve(&fx)
        .args(["deposit", "--spec"])
        .arg(&spec)
        .args(["--issued-at", "2026-07-01T00:00:00Z", "--key"])
        .arg(&root.key)
        .args(["--key-id", "varve-root-1", "--out"])
        .arg(parent.join("nope2"))
        .assert()
        .failure()
        .stderr(predicate::str::contains("only a tree payload"));
}

/// A pin that declares exports, written into the project.
fn write_pin(fx: &Fixture, exports: &str) {
    std::fs::write(
        fx.project.join("varve.toml"),
        format!("{PIN_JULY}{exports}"),
    )
    .unwrap();
}

// rivet: verifies REQ-EXPORTDECL-001
#[test]
fn verify_checks_every_declared_export_without_being_told_to() {
    // Clause 3, through the binary. The library could classify a declared
    // export since v0.27.0 and `varve verify` never called it: the set of
    // checked exports still lived in whichever `--export` flags someone
    // remembered to type, which is the "only checks what it is told about"
    // failure the requirement exists to close.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);
    let vsix = parent.join("ext.vsix");
    std::fs::write(&vsix, b"zip-bytes").unwrap();
    deposit_and_install(
        &fx,
        &root,
        &format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"rust-lang.rust-analyzer\"\nversion = \"0.3.2300\"\n\
             kind = \"vsix\"\npath = \"{}\"\n",
            vsix.display()
        ),
        "decl",
    );

    // TWO declarations, neither generated. Both must be reported: a loop that
    // stops at the first fault checks one export and certifies the rest.
    write_pin(
        &fx,
        "\n[[export]]\nkind = \"vsix\"\nout = \"extensions\"\n\
         \n[[export]]\nkind = \"bazel-registry\"\nout = \"bazel/registries\"\n",
    );
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("2 declared export(s)")
                .and(predicate::str::contains("extensions"))
                .and(predicate::str::contains("bazel/registries"))
                .and(predicate::str::contains("MISSING"))
                // The command that FIXES it, spelled the way it really is:
                // `bazel-registry` is produced by `varve export-bazel`, so the
                // obvious format!("export-{kind}") would print a command that
                // does not exist in the one line whose job is to be run.
                .and(predicate::str::contains("varve export-bazel --out"))
                .and(predicate::str::contains("varve export-vsix --out")),
        );

    // Generate ONE of them: the other is still checked, so this is not a
    // "declared exports exist" check that any single directory satisfies.
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["export-vsix", "--out", "extensions"])
        .assert()
        .success();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("1 declared export(s)")
                .and(predicate::str::contains("bazel/registries")),
        );

    // With only the generated one declared, verify passes — and SAYS it looked,
    // because a silent pass is indistinguishable from a check that was skipped.
    write_pin(&fx, "\n[[export]]\nkind = \"vsix\"\nout = \"extensions\"\n");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("declared export").and(predicate::str::contains("fresh")));

    // The pin moves and the export does not.
    let stamp = fx.project.join("extensions/.varve-export.json");
    std::fs::write(
        &stamp,
        r#"{"layer":"2026.06.0","manifest_digest":"sha256:0000","kind":"vsix"}"#,
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(predicate::str::contains("STALE"));

    // A directory produced by a DIFFERENT adapter: freshness there says nothing
    // about the declared export, which was never produced at all.
    let current: serde_json::Value = {
        varve(&fx)
            .env("VARVE_TRUST_ROOT", &root.trust_root)
            .args(["export-vsix", "--out", "extensions"])
            .assert()
            .success();
        serde_json::from_slice(&std::fs::read(&stamp).unwrap()).unwrap()
    };
    std::fs::write(
        &stamp,
        serde_json::to_vec(&serde_json::json!({
            "layer": current["layer"],
            "manifest_digest": current["manifest_digest"],
            "kind": "cargo",
        }))
        .unwrap(),
    )
    .unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("DECLARED as a vsix export but stamped cargo")
                .and(predicate::str::contains("says nothing about it")),
        );

    // And a declared directory that is simply gone is a FAILURE, not a warning:
    // "I forgot to generate it" and "it is stale" are the same severity to
    // anyone relying on the export.
    std::fs::remove_dir_all(fx.project.join("extensions")).unwrap();
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .arg("verify")
        .assert()
        .failure()
        .stderr(predicate::str::contains("MISSING"));
}

// rivet: verifies REQ-EXPORTDECL-001, REQ-SHADOW-001
#[cfg(unix)]
#[test]
fn a_declared_sdk_environment_is_not_reported_as_a_hijack_by_verify() {
    // Clause 5 through the binary, in all three verdicts. Without the
    // declaration consulted here, a legitimately sourced SDK makes `verify`
    // cry wolf — and a check that fires on the setup the project deliberately
    // configured is the one people switch off, which is worse than not
    // checking at all.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);

    let out = fx.project.join("toolchains/poky");
    std::fs::create_dir_all(&out).unwrap();
    let dest = out.canonicalize().unwrap();
    let built = built_prefix_for(&dest);
    let archive = parent.join("poky-sdk.tar.gz");
    std::fs::write(&archive, sdk_tarball(&built)).unwrap();
    let synth_bin = parent.join("synth-bin");
    std::fs::write(&synth_bin, b"#!/bin/sh\necho PINNED\n").unwrap();

    deposit_and_install(
        &fx,
        &root,
        &format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"synth\"\nversion = \"1.0.0\"\npath = \"{}\"\n\n\
             [[tool]]\nname = \"poky\"\nversion = \"4.0.15\"\nkind = \"sdk\"\n\
             sdk-prefix = \"{built}\"\npath = \"{}\"\n",
            synth_bin.display(),
            archive.display()
        ),
        "shadow",
    );

    const DECL: &str = "\n[[export]]\nkind = \"sdk\"\nout = \"toolchains/poky\"\n\
                        \n[export.env]\nscript = \"environment-setup-cortexa53-poky-linux\"\n";
    write_pin(&fx, &format!("{DECL}path = \"before-shims\"\n"));
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["export-sdk", "--out", "toolchains/poky"])
        .assert()
        .success();

    // The SDK's own `synth` is what PATH runs — exactly the condition
    // REQ-SHADOW-001 detects, and exactly what `before-shims` declared.
    let sdk_path = format!("{}:/usr/bin:/bin", dest.join("bin").display());
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .env("PATH", &sdk_path)
        .arg("verify")
        .assert()
        .success()
        .stdout(
            predicate::str::contains("before-shims").and(predicate::str::contains("not a hijack")),
        );

    // The SAME PATH under an `after-shims` declaration is a real fault: the
    // project said varve's pinned tools win, and they do not.
    write_pin(&fx, &format!("{DECL}path = \"after-shims\"\n"));
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .env("PATH", &sdk_path)
        .arg("verify")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("varve.toml declares that export `after-shims`").and(
                predicate::str::contains("environment-setup-cortexa53-poky-linux"),
            ),
        );

    // …and a binary in no declared export at all is still the ordinary hijack,
    // with the ordinary fix — the declaration must not blunt the check it
    // exists to make usable.
    write_pin(&fx, &format!("{DECL}path = \"before-shims\"\n"));
    let elsewhere = parent.join("elsewhere");
    std::fs::create_dir_all(&elsewhere).unwrap();
    let impostor = elsewhere.join("synth");
    std::fs::write(&impostor, "#!/bin/sh\necho WRONG\n").unwrap();
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&impostor, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .env("PATH", format!("{}:/usr/bin:/bin", elsewhere.display()))
        .arg("verify")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("not what your PATH runs")
                .and(predicate::str::contains("varve shim install")),
        );
}

// rivet: verifies REQ-EXPORTDECL-001
#[cfg(unix)]
#[test]
fn env_enters_every_declared_environment_in_the_order_that_inverts_the_file() {
    // Clause 4 through the binary. `env_lines` computed the inverted order in
    // the library and `varve env` printed the shim fragment alone, so a project
    // that declared its SDK still had to source it by hand — in whichever order
    // it guessed.
    let fx = fixture(Some(PIN_JULY), &[]);
    // Two sourced exports, one on each side of the shims, so the assertion is
    // about ORDER and not merely about presence.
    write_pin(
        &fx,
        "\n[[export]]\nkind = \"sdk\"\nout = \"sdk-after\"\n\
         \n[export.env]\nscript = \"env-after.sh\"\npath = \"after-shims\"\n\
         \n[[export]]\nkind = \"sdk\"\nout = \"sdk-before\"\n\
         \n[export.env]\nscript = \"env-before.sh\"\npath = \"before-shims\"\n",
    );
    for (dir, marker) in [("sdk-after", "AFTER"), ("sdk-before", "BEFORE")] {
        let d = fx.project.join(dir);
        std::fs::create_dir_all(d.join("bin")).unwrap();
        std::fs::write(
            d.join(format!("env-{}.sh", marker.to_lowercase())),
            format!("export PATH=\"{}/bin:$PATH\"\n", d.display()),
        )
        .unwrap();
    }

    let out = varve(&fx).arg("env").output().unwrap();
    assert!(out.status.success());
    let script = String::from_utf8(out.stdout).unwrap();
    let at = |needle: &str| {
        script
            .find(needle)
            .unwrap_or_else(|| panic!("`varve env` never mentions {needle}:\n{script}"))
    };
    let shims = fx.root.join("shims");
    assert!(
        at("env-after.sh") < at(shims.to_str().unwrap()),
        "an `after-shims` export must be sourced FIRST, so the shims land ahead \
         of it on PATH:\n{script}"
    );
    assert!(
        at(shims.to_str().unwrap()) < at("env-before.sh"),
        "a `before-shims` export must be sourced LAST, so its own bin wins:\n{script}"
    );

    // …and the emitted script actually produces that PATH when a shell runs it,
    // which is the only claim that matters. Asserting the text alone would
    // verify the formatter.
    let probe = std::process::Command::new("sh")
        .arg("-c")
        .arg("eval \"$VARVE_ENV\"; printf '%s' \"$PATH\"")
        .env("VARVE_ENV", &script)
        .env("PATH", "/usr/bin:/bin")
        .current_dir(&fx.project)
        .output()
        .unwrap();
    let path = String::from_utf8_lossy(&probe.stdout);
    let entries: Vec<&str> = path.split(':').collect();
    let idx = |needle: &str| {
        entries
            .iter()
            .position(|e| e.contains(needle))
            .unwrap_or_else(|| panic!("{needle} is not on the resulting PATH: {path}"))
    };
    assert!(
        idx("sdk-before/bin") < idx("shims"),
        "sourcing PREPENDS, so `before-shims` must end up ahead of the shims: {path}"
    );
    assert!(
        idx("shims") < idx("sdk-after/bin"),
        "…and `after-shims` behind them: {path}"
    );

    // fish cannot source a producer's POSIX-sh environment script, so it fails
    // rather than handing back an environment missing what varve.toml declares.
    varve(&fx)
        .args(["env", "--shell", "fish"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("fish cannot source it"));

    // A pin that EXISTS and does not parse is an error, not a fallback: half an
    // environment, exit 0, is how a declared SDK goes missing without anyone
    // noticing. (Outside a project there is no pin at all, and the shims stay
    // the whole answer — `env_is_evaluable_and_idempotent` covers that.)
    std::fs::write(fx.project.join("varve.toml"), "manifest-version = 1\n").unwrap();
    varve(&fx)
        .arg("env")
        .assert()
        .failure()
        .stderr(predicate::str::contains("varve.toml"));
}

// rivet: verifies REQ-PIN-001
#[test]
fn a_schema_mistake_in_the_pin_is_reported_once_not_twice() {
    // varve#7 fixed this for the `Layer` variant and left its siblings alone:
    // every variant that both interpolates `{source}` into its Display AND
    // declares `#[source]` prints its cause twice, glued by a stray `: `. That
    // is eleven lines of output for a one-line problem, on the errors a
    // newcomer hits first — a missing field in varve.toml. Found by a persona
    // audit, which ranked it the highest friction-removed-per-line-changed
    // fix in the tool.
    let fx = fixture(Some(PIN_JULY), &[]);
    std::fs::write(fx.project.join("varve.toml"), "[toolchain]\n").unwrap();
    let out = varve(&fx).arg("which").arg("rivet").assert().failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert_eq!(
        stderr.matches("missing field").count(),
        1,
        "the parse error is printed once, not once per formatter layer:\n{stderr}"
    );
    // …and no orphaned separator left behind by the removed interpolation.
    assert!(
        !stderr.contains("\n: "),
        "stray `: ` gluing a doubled cause:\n{stderr}"
    );
}

// rivet: verifies REQ-SDK-001
#[test]
fn export_sdk_refuses_a_hostile_archive_member_at_the_cli_boundary() {
    // Clause 5 where it now actually runs. The tree's invariants were verified
    // in the library while nothing could reach them; a signed blob is
    // ATTRIBUTABLE, not benign, and this is the boundary a user types.
    let fx = fixture(Some(PIN_JULY), &[]);
    let parent = fx.project.parent().unwrap();
    let root = root_at(parent);

    let mut tar_bytes = Vec::new();
    {
        let mut b = tar::Builder::new(&mut tar_bytes);
        let mut h = tar::Header::new_gnu();
        let payload = b"PWNED";
        h.set_size(payload.len() as u64);
        h.set_mode(0o644);
        // Written into the header DIRECTLY: `set_path` refuses `..` itself, and
        // an archive built by other software is under no obligation to have
        // used it. The refusal has to be varve's.
        {
            let gnu = h.as_gnu_mut().unwrap();
            let name = b"../../escaped";
            gnu.name[..name.len()].copy_from_slice(name);
        }
        h.set_cksum();
        b.append(&h, &payload[..]).unwrap();
        b.finish().unwrap();
    }
    let archive = parent.join("hostile.tar");
    std::fs::write(&archive, &tar_bytes).unwrap();
    deposit_and_install(
        &fx,
        &root,
        &format!(
            "layer = \"2026.07.0\"\nchannel = \"qualified\"\ncounter = 1\n\n\
             [[tool]]\nname = \"hostile\"\nversion = \"1.0\"\nkind = \"sdk\"\n\
             sdk-prefix = \"/opt/poky-with-a-prefix-long-enough-for-any-temporary-directory-so-the-fit-check-is-not-what-refuses-this\"\n\
             path = \"{}\"\n",
            archive.display()
        ),
        "hostile",
    );

    let out = parent.join("hostile-out");
    varve(&fx)
        .env("VARVE_TRUST_ROOT", &root.trust_root)
        .args(["export-sdk", "--out"])
        .arg(&out)
        .assert()
        .failure()
        .stderr(predicate::str::contains("not a usable path"));
    assert!(
        !parent.join("escaped").exists() && !out.join("escaped").exists(),
        "a refused tree must leave nothing behind, inside the export or out of it"
    );
}