buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
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
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
// ===============================================================================
// BUILDLANG COMPILER - SCIENTIFIC-RUNTIME RECEIPT MODULE
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================
//
//! Scientific-runtime receipt (`buildlang-scientific-runtime-receipt/v0`).
//!
//! `buildc run <file> --emit-receipt <path>` compiles and runs a `.bld` program,
//! captures its numeric stdout as a measurement series, checks a stated
//! **invariant** over that series, and emits a sealed, re-checkable JSON receipt.
//!
//! Scope (read `docs/superpowers/specs/2026-07-01-scientific-runtime-receipt-design.md`):
//! the receipt records that the compiled program's observed output series
//! satisfies the stated invariant (or, for a negative fixture, violates it as
//! expected). Every receipt carries the label `NUMERICAL_RESULT` and a `scope`
//! list that names what it covers. The receipt holds one invariant over one
//! f64 series, sealed and re-derivable.

use std::path::Path;

use super::{source_digest_hex, CheckReceiptSourceDigest};

/// Schema id for the scientific-runtime receipt.
pub const SCIENTIFIC_RUNTIME_SCHEMA: &str = "buildlang-scientific-runtime-receipt/v1";

/// Schema id for version 0 receipts. Version 0 named its limits in a
/// `not_claimed` list and in negative labels. Verify still accepts version 0.
pub const SCIENTIFIC_RUNTIME_SCHEMA_V0: &str = "buildlang-scientific-runtime-receipt/v0";

/// True for a scientific-runtime schema that this verifier reads.
pub fn is_scientific_runtime_schema(schema: &str) -> bool {
    schema == SCIENTIFIC_RUNTIME_SCHEMA || schema == SCIENTIFIC_RUNTIME_SCHEMA_V0
}

/// The label on every receipt: the result is a numerical run checked against
/// an invariant.
pub const LABEL_NUMERICAL_RESULT: &str = "NUMERICAL_RESULT";

/// The label on a budgeted receipt: the result is the best one that the search
/// found within its budget.
pub const LABEL_BEST_FOUND_WITHIN_BUDGET: &str = "BEST_FOUND_WITHIN_BUDGET";

/// What every version 1 receipt covers. Verify requires
/// [`SCOPE_REQUIRED`].
pub const SCOPE_BASE: &[&str] = &[
    "source_and_build_digests",
    "observed_series_invariant",
    "rerun_agreement",
];

/// The scope entry that every version 1 receipt must carry.
pub const SCOPE_REQUIRED: &str = "observed_series_invariant";

/// The scope entry that pairs with a budget block.
pub const SCOPE_BUDGET: &str = "best_found_within_budget";

/// The scope entries that pair with an EXECUTED monte_carlo block: the
/// receipt re-checks the interval arithmetic and the sample denominator.
pub const MC_EXECUTED_SCOPE: &[&str] = &["interval_arithmetic", "sample_denominator"];

/// Version 0 name of [`LABEL_NUMERICAL_RESULT`].
pub const LABEL_NUMERICAL_RESULT_V0: &str = "NOT_A_NEW_PHYSICAL_LAW";

/// Version 0 name of [`LABEL_BEST_FOUND_WITHIN_BUDGET`].
pub const LABEL_BEST_FOUND_WITHIN_BUDGET_V0: &str = "NOT_PROVES_OPTIMALITY";

/// The vocabulary that one schema version uses for its labels and its
/// coverage list. Verify reads a receipt through the vocabulary of its own
/// version, so a version 0 receipt keeps verifying.
pub struct ReceiptVocabulary {
    /// The label that every receipt of this version carries.
    pub numerical_label: &'static str,
    /// The JSON name of the coverage list (`scope` or `not_claimed`).
    pub list_name: &'static str,
    /// The entry that every receipt of this version must carry.
    pub required_entry: &'static str,
    /// The failure class when the required entry is missing.
    pub missing_class: &'static str,
    /// The label and the list entry that pair with a budget block.
    pub budget_label: &'static str,
    pub budget_entry: &'static str,
    /// The list entries that pair with an EXECUTED monte_carlo block.
    pub mc_entries: &'static [&'static str],
}

/// The vocabulary for a schema id (version 1 for any id other than version 0).
pub fn receipt_vocabulary(schema: &str) -> ReceiptVocabulary {
    if schema == SCIENTIFIC_RUNTIME_SCHEMA_V0 {
        ReceiptVocabulary {
            numerical_label: LABEL_NUMERICAL_RESULT_V0,
            list_name: "not_claimed",
            required_entry: "physical_law",
            missing_class: "OVERCLAIM_BOUNDARY_MISSING",
            budget_label: LABEL_BEST_FOUND_WITHIN_BUDGET_V0,
            budget_entry: "optimality",
            mc_entries: MC_EXECUTED_NOT_CLAIMED,
        }
    } else {
        ReceiptVocabulary {
            numerical_label: LABEL_NUMERICAL_RESULT,
            list_name: "scope",
            required_entry: SCOPE_REQUIRED,
            missing_class: "SCOPE_MISSING",
            budget_label: LABEL_BEST_FOUND_WITHIN_BUDGET,
            budget_entry: SCOPE_BUDGET,
            mc_entries: MC_EXECUTED_SCOPE,
        }
    }
}

/// Default generated-program stdio mode for receipts sealed before the field
/// existed, and for new receipts that preserve native host behavior.
pub const SCIENTIFIC_STDIO_MODE_NATIVE: &str = "native";

/// Explicit byte-stable generated-program stdio mode for C-backend receipts.
pub const SCIENTIFIC_STDIO_MODE_PORTABLE_LF: &str = "portable-lf";

/// The invariant name emitted for the energy-monotone check.
pub const ENERGY_MONOTONE_INVARIANT: &str = "energy_monotone_nonincreasing";

/// The invariant name emitted for the conserved-quantity check: the measured
/// scalar (a conserved quantity such as total mass or a Hamiltonian) must stay
/// within tolerance of its initial value at every step.
pub const CONSERVATION_INVARIANT: &str = "conserved_quantity_constant";

/// Tolerance used by the monotone-non-increasing check. A step counts as an
/// increase only when `series[k+1] > series[k] + TOLERANCE`, so platform float
/// jitter at the ULP scale does not flip the verdict (design determinism rule).
pub const ENERGY_MONOTONE_TOLERANCE: f64 = 1e-12;

/// Tolerance used by the conserved-quantity check. Looser than the monotone
/// tolerance because a genuinely conserved discrete quantity still accumulates
/// floating-point roundoff over many steps, while a real leak (a non-conserving
/// scheme) drifts by an O(1) amount that this bound still catches decisively.
pub const CONSERVATION_TOLERANCE: f64 = 1e-9;

/// The invariant name emitted for the discrete maximum-principle check: the
/// measured scalar must never RISE above its initial value (a one-sided upper
/// bound). Distinct from monotone (which forbids any step-wise increase) and
/// from conservation (which forbids any deviation): a bounded quantity may
/// oscillate and decay freely, it just may never exceed where it started.
pub const BOUNDED_INVARIANT: &str = "bounded_by_initial_maximum";

/// Tolerance used by the maximum-principle check. Same scale as conservation:
/// a genuinely bounded quantity sits at or below its initial value to roundoff,
/// while a real overshoot (an unstable, energy-injecting scheme) exceeds it by
/// an O(1) amount this bound catches decisively.
pub const BOUNDED_TOLERANCE: f64 = 1e-9;

/// The invariant name emitted for the APPROXIMATE-conservation (bounded-drift)
/// check: the measured scalar must stay within a fixed error BUDGET of its
/// initial value, forever. It reuses conservation's two-sided evaluator but
/// with a looser, calibrated tolerance, so it accepts a quantity that is only
/// APPROXIMATELY conserved (a symplectic integrator's energy oscillates in an
/// O(dt^2) band and never drifts secularly) while still rejecting a scheme
/// whose energy drifts away (explicit Euler). Distinct from `conservation`
/// (roundoff-exact), `bounded` (one-sided, and too tight for a band that rises
/// slightly above the start), and `energy-monotone`.
pub const CONSERVED_BAND_INVARIANT: &str = "conserved_within_band";

/// Tolerance (error budget) for the bounded-drift check. Calibrated so a
/// well-resolved symplectic scheme passes and a drifting one fails: the
/// flagship leapfrog oscillator (dt = 0.1) holds its energy within a measured
/// ~1.25e-3 band forever, so `5e-3` clears it ~4x, while explicit Euler leaves
/// the band within two steps and grows without bound. Absolute, like every
/// family tolerance: a kernel must be resolved (and scaled) to fit the budget.
pub const CONSERVED_BAND_TOLERANCE: f64 = 5e-3;

/// The invariant name emitted for the NON-NEGATIVITY check: the measured scalar
/// must never drop below zero beyond tolerance. The lower-side companion to
/// `bounded` (which fences the upper side against the initial value); this
/// fences the lower side against an ABSOLUTE floor of zero, allowing arbitrarily
/// large positive values. It witnesses that a quantity that must stay
/// non-negative does: a diffusion concentration that never goes unphysically
/// negative, or a RESULT-BEARING slack (a proven upper bound minus an algorithm's
/// measured cost) that never goes negative, i.e. the algorithm never exceeds its
/// bound. Distinct from every other member (they reference the initial value,
/// the mean, or agreement; this is an absolute one-sided floor).
pub const NON_NEGATIVE_INVARIANT: &str = "non_negative";

/// Tolerance for the non-negativity check: a value counts as negative only when
/// it drops below `-tol`, so roundoff at a true zero does not trip it. A genuine
/// undershoot (an unphysical negative, or an algorithm exceeding its bound) is
/// an O(1) amount this bound catches decisively.
pub const NON_NEGATIVE_TOLERANCE: f64 = 1e-9;

/// The invariant name emitted for the discrete energy-identity check: the
/// measured scalar is a per-step energy-BALANCE residual that must stay within
/// tolerance of ZERO (an absolute bound, unlike conservation/bounded which
/// reference the initial value). This is the family's first QUANTITATIVE
/// invariant: it checks a computed numerical identity holds, not just a
/// monotonicity or bound pattern.
pub const ENERGY_IDENTITY_INVARIANT: &str = "energy_identity_residual";

/// Tolerance used by the energy-identity check. The exact discrete energy
/// balance holds to roundoff (measured max residual ~2e-14 for the reference
/// FTCS kernel), so `1e-9` clears it by ~5 orders (absorbing cross-platform
/// variation in a residual formed by cancelling O(1) quantities) while a real
/// dropped-term error leaves an O(r^2) residual ~1e-5 that this bound catches
/// by ~4 orders. Reference is 0, so every step (including step 0) is checked.
pub const ENERGY_IDENTITY_TOLERANCE: f64 = 1e-9;

/// The invariant name emitted for the cross-column RELATION check: each row of
/// a multi-column series must AGREE (all columns within tolerance of the row's
/// first column). This is the family's first invariant the VERIFIER computes
/// from raw captured columns rather than trusting a residual the kernel printed:
/// a kernel that emits two independent computations of a quantity cannot hide a
/// disagreement, because the check happens at verify, not in the program.
pub const RELATION_INVARIANT: &str = "relation_columns_agree";

/// Tolerance used by the relation check. Two faithful computations of the same
/// quantity agree to roundoff, while a genuine divergence (a dropped factor, a
/// wrong formula) differs by an O(1) amount this bound catches decisively.
pub const RELATION_TOLERANCE: f64 = 1e-9;

/// The invariant name emitted for the CROSS-BACKEND agreement check: each row
/// holds the same step's value computed by two backends (column 0 the C
/// anchor, column 1 the secondary lane), and every row must agree within the
/// cross-backend tolerance. The evaluator is the relation family's; only the
/// tolerance and the sealed provenance differ.
pub const CROSS_BACKEND_INVARIANT: &str = "cross_backend_columns_agree";

/// Tolerance for the cross-backend check. Looser than RELATION_TOLERANCE for
/// a measured reason: the C runtime prints %g (6 significant digits) while
/// the Rust lane prints shortest-roundtrip, so two IDENTICAL doubles can
/// print up to ~5e-7 apart on O(1) values (measured 2026-07-28 on the decay
/// recurrence). 1e-5 clears that display-rounding floor by ~20x, while a
/// genuine cross-backend divergence (a dropped term, a different formula, a
/// miscompiled kernel) is O(1) and caught decisively. Like every family
/// tolerance it is absolute: cross-backend kernels must emit O(1) values.
pub const CROSS_BACKEND_TOLERANCE: f64 = 1e-5;

/// Executed Monte Carlo estimator vocabulary, v1: the mean of Bernoulli
/// indicators. DECLARED blocks keep free text forever (the shipped corpus
/// uses `mean`); this vocabulary gates EXECUTED blocks only.
pub const MC_EXECUTED_ESTIMATOR_PROPORTION: &str = "proportion";

/// Executed interval method: normal approximation. Degenerate at a boundary
/// proportion (successes == 0 or successes == trials): refused at emit and
/// at verify, pointing at `wilson-95`.
pub const MC_INTERVAL_NORMAL_APPROX_95: &str = "normal-approx-95";

/// Executed interval method: Wilson score. Well-defined at the boundary
/// proportions, asymmetric by construction.
pub const MC_INTERVAL_WILSON_95: &str = "wilson-95";

/// NOT executable in v1 (needs an inverse incomplete beta with no in-tree
/// oracle). Named here only so refusal messages can point at it by
/// constant rather than a bare string; never accepted by
/// `compute_mc_executed`.
pub const MC_INTERVAL_CLOPPER_PEARSON_95: &str = "clopper-pearson-95";

/// z for a two-sided 95% normal/Wilson interval: the double nearest the
/// 0.975 standard-normal quantile. Shared by both executable methods.
pub const MC_INTERVAL_Z_95: f64 = 1.959963984540054;

/// Absolute float tolerance for the emit/verify interval recompute
/// (`estimate`, `interval_low`, `interval_high`, both stages). The
/// arithmetic runs on identical integer inputs through one fixed Rust
/// implementation at emit and verify, so agreement should be exact in
/// practice; this is headroom against a future compiler reassociating
/// verifier-side float ops, not load-bearing looseness. Values are O(1)
/// proportions, so absolute is safe.
pub const MC_RECOMPUTE_TOLERANCE: f64 = 1e-12;

/// Version 0 only: the three `not_claimed` entries that an EXECUTED
/// monte_carlo block added. Version 1 uses [`MC_EXECUTED_SCOPE`].
pub const MC_EXECUTED_NOT_CLAIMED: &[&str] = &[
    "sample_independence",
    "interval_coverage",
    "estimator_semantics",
];

/// Provenance reference to the Telos pass-0009 research probe (reference only;
/// never matched byte-wise, per the determinism decision in the design).
pub const RESEARCH_SOURCE_HASH: &str =
    "b3021c14b0e5dc8adeddadf0d22e2780dbf259c349caf5cbc2ba255b591fd7d5";

/// Version 0 only: the `not_claimed` list that every version 0 receipt
/// carried. Verify rejects a version 0 receipt whose list omits
/// "physical_law". Version 1 uses [`SCOPE_BASE`]. Kept as the record of the
/// version 0 list; the legacy tests build version 0 receipts from it.
#[cfg_attr(not(test), allow(dead_code))]
pub const NOT_CLAIMED_BOUNDARY: &[&str] = &[
    "numerical_correctness",
    "convergence",
    "pde_accuracy",
    "physical_law",
];

/// The versioned series-extraction policy: how raw stdout bytes become the
/// numeric series. Sealed in the receipt so a policy change is visible as a
/// different receipt, and byte-level drift stays distinguishable from
/// extraction-policy tolerance.
pub const SERIES_EXTRACTION_POLICY: &str =
    "whitespace-f64/v1: whitespace-split tokens parsed as finite f64; a non-finite token truncates the series and marks the run diverged; other tokens are skipped";

/// The criterion the verdict is measured against (the pass-0122 `oracle`
/// field). v0 supports one kind, `declared_invariant`: the named invariant IS
/// the criterion, declared rather than derived from an executed reference.
/// Future kinds (`reference_implementation`, `exact_proof`) get their own
/// status vocabulary when an oracle actually executes; the kind/status split
/// keeps "what the criterion is" separate from "how it was established".
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificOracle {
    /// `declared_invariant` (v0).
    pub kind: String,
    /// The criterion's name; for `declared_invariant` this MUST equal
    /// `invariant.name` (verify checks the binding).
    pub name: String,
    /// `DECLARED` (v0): the criterion was stated, not independently executed.
    pub status: String,
}

/// The pass-0122 `compiler_branch` contract: the toolchain that produced (and
/// re-produces) the run. Sealed at emit; verify re-probes the local toolchain
/// and treats a mismatch as environmental CONTEXT (a receipt may legitimately
/// re-verify under a different toolchain because the re-checked quantity is
/// the verdict, not bytes), and a missing toolchain as its own
/// `TOOL_UNAVAILABLE` verdict.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificToolchain {
    /// The resolved C compiler command (e.g. `cl.exe`, `gcc`).
    pub c_compiler: String,
    /// First line of the compiler's version banner (human triage).
    pub c_compiler_version: String,
    /// sha256 over the compiler's full version-probe output bytes.
    pub version_output_digest: ScientificDigest,
    /// The os/arch the emitting buildc binary was BUILT FOR (compile-time
    /// constants, e.g. `windows/x86_64`); equals the host in every supported
    /// configuration, but is not a runtime host probe.
    pub target: String,
    /// sha256 of the buildc binary that emitted the receipt.
    pub buildc_binary_digest: ScientificDigest,
    /// sha256 of the compiled program executable BEFORE it ran. REPORTED at
    /// verify (`executable_reproduced`), never required: C compiler output is
    /// not byte-stable across compiler versions, and requiring it would
    /// contradict the verdict-level determinism rule.
    pub program_executable_digest: ScientificDigest,
}

/// The master plan's "type/effect policy" receipt field, genuinely
/// witnessed: a digest over the canonical effect/capability facts the type
/// checker derived from source at emit, plus the observed capability union.
/// Verify RE-DERIVES both through the same check pipeline and fails with
/// `EFFECT_POLICY_DRIFT` on any disagreement, so the sealed policy facts can
/// neither be edited nor go stale against the source.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificEffectPolicy {
    /// sha256 over the canonical rendering of every function's declared
    /// effects and observed capabilities (sorted, so the digest is stable).
    pub facts_digest: ScientificDigest,
    /// Sorted union of capability names observed across the program.
    pub observed_capabilities: Vec<String>,
    /// Whether any function reads stdin. `Console` covers BOTH stdout writes
    /// (safe) and stdin reads (an external input that breaks the dataset and
    /// determinism absences), so the capability NAME alone cannot decide
    /// those fields; this flag disambiguates. Re-derived at verify, so a
    /// tampered flag is caught by `EFFECT_POLICY_DRIFT`.
    pub reads_stdin: bool,
}

/// A field whose VALUE is an honest statement about evidence: either a
/// witnessed absence (the effect system proves the thing cannot have
/// happened) or an explicit fence (buildc cannot witness it either way).
/// Used for `input_dataset` and `seed`.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificWitnessedField {
    /// `NONE_WITNESSED` (proven absent via capabilities),
    /// `POSSIBLE_UNWITNESSED` (capabilities permit it; buildc does not track
    /// which resources were touched), or `NOT_APPLICABLE` (the language
    /// cannot express it at all).
    pub status: String,
    /// The derivation grounds, human-readable and re-derivable.
    pub grounds: String,
}

/// The determinism statement DERIVED from the observed capability set: a
/// program whose capabilities exclude every nondeterminism source the
/// language exposes is deterministic modulo its sealed args.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificDeterminism {
    pub deterministic_modulo_args: bool,
    pub grounds: String,
}

/// The master plan's "numerical method" field: author-DECLARED (buildc
/// cannot derive scheme semantics from source and must not pretend to).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificNumericalMethod {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// `DECLARED` when a description was supplied, `UNDECLARED` otherwise;
    /// verify rejects an inconsistent pair (FIELD_CONTRACT_VIOLATION).
    pub status: String,
}

/// The Monte Carlo admission block: the estimator's facts, sealed, without
/// which an MC number is unpriceable. Author-DECLARED like
/// [`ScientificNumericalMethod`] (buildc cannot derive the sample count or
/// the interval method from source and does not pretend to), but with hard
/// contracts verify re-checks: the block declares completely or not at all
/// (emit refuses a partial declaration; the struct makes a partial block
/// unparseable), it rides only on a program that observes `Random` with a
/// sealed seed, and a zero sample count or a nameless estimator/interval is
/// refused as unpriceable. v0 claims REPRODUCIBILITY and declaration
/// discipline, never correctness of the interval: the receipt witnesses that
/// the estimator's denominator, id, and interval method were stated up
/// front, and that the run they describe re-derives exactly under the sealed
/// seed. The weaker the mode's promise, the more the receipt must carry.
///
/// No longer `Eq` (only `PartialEq`): the five EXECUTED fields below add
/// `f64`, which has no total order (`Eq` cannot be derived over it), the
/// same `ScientificBudget` precedent (its wall fields dropped `Eq` first).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificMonteCarlo {
    /// The estimator's id (e.g. `mean`), author-declared, non-empty.
    pub estimator: String,
    /// The declared sample count n (the denominator). Non-zero: an MC claim
    /// without its denominator is unpriceable.
    pub samples: u64,
    /// The declared interval method (e.g. `normal-approx-95`), non-empty: the
    /// claim is the interval, never the point, so a result whose interval
    /// method is undeclared is refused.
    pub interval_method: String,
    /// `DECLARED` | `EXECUTED`. DECLARED (v0): the facts were stated, not
    /// independently executed. EXECUTED: the verifier RE-DERIVES the interval
    /// from raw sufficient-statistic columns the kernel prints, at two
    /// stages (see `compute_mc_executed`).
    pub status: String,
    /// p_hat = successes_final / trials_final. Present IFF `status ==
    /// "EXECUTED"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub estimate: Option<f64>,
    /// Lower bound by the named method. Present IFF `status == "EXECUTED"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_low: Option<f64>,
    /// Upper bound by the named method. Present IFF `status == "EXECUTED"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_high: Option<f64>,
    /// trials_final; MUST equal `samples`, the witnessed denominator.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub n_effective: Option<u64>,
    /// successes_final.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub successes: Option<u64>,
}

/// The budgeted-search admission block: a heuristic result without its
/// budget ceiling hides whether it stopped at the limit, so the ceiling,
/// the consumption, and the exhausted flag seal together. Author-DECLARED
/// like [`ScientificMonteCarlo`], with shape contracts verify re-checks:
/// the ceiling is non-zero, consumption never exceeds it (a consumption
/// above its ceiling is incoherent), and `exhausted` is DERIVED
/// (`steps_consumed == steps_limit`), never hand-set. A budgeted receipt
/// also carries `BEST_FOUND_WITHIN_BUDGET` in `labels` and
/// `best_found_within_budget` in `scope`. Verify re-derives both: the result
/// is the best one that the search found within its budget.
///
/// No longer `Eq` (only `PartialEq`): the wall fields below add `f64`,
/// which has no total order (`Eq` cannot be derived over it), matching the
/// sibling `ScientificInvariant`'s `tolerance: f64`.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificBudget {
    /// The declared step ceiling. Non-zero.
    pub steps_limit: u64,
    /// The declared steps consumed. At most `steps_limit`.
    pub steps_consumed: u64,
    /// Whether the search ran to its ceiling: EXACTLY
    /// `steps_consumed == steps_limit`, re-derived at verify.
    pub exhausted: bool,
    /// `DECLARED` (v0): the facts were stated, not independently metered.
    pub status: String,
    /// The declared wall-clock ceiling in seconds (`--budget-wall-seconds`),
    /// present IFF the run declared one. A member of the budget block, not a
    /// freestanding knob: it requires the steps pair and a positive, finite
    /// value. Optional-with-default so receipts sealed before this field
    /// existed keep their exact bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wall_seconds_limit: Option<f64>,
    /// Whether the EMITTED run's sealed wall time exceeded the ceiling:
    /// EXACTLY `runtime_state.wall_seconds > wall_seconds_limit`, DERIVED
    /// from the two SEALED numbers at emit and re-derived at verify from the
    /// same sealed pair, never from verify's own re-measured time (a slower
    /// verify machine must not flip a receipt's coherence). Present IFF
    /// `wall_seconds_limit` is present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wall_exceeded: Option<bool>,
}

/// The cross-backend admission block: the secondary lane's witnessed facts.
/// Present IFF the invariant is the cross-backend member (a strict
/// biconditional verify re-checks). The secondary raw-stdout digest and
/// executable digest are sealed at emit and REPORTED at verify (exact bytes
/// are toolchain-dependent by design, exactly like the primary's); the
/// re-checked quantity is the verdict over the re-derived columns.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificCrossBackend {
    /// The secondary lane. v0: `rust` only (the validation lane); the GPU
    /// lane is a later value, not a different mechanism.
    pub secondary_target: String,
    /// First line of `rustc --version` at emit (human triage).
    pub secondary_toolchain_version: String,
    /// sha256 over the full version-probe output bytes.
    pub secondary_toolchain_digest: ScientificDigest,
    /// sha256 of the compiled secondary executable BEFORE it ran.
    pub secondary_executable_digest: ScientificDigest,
    /// sha256 over the secondary's exact raw stdout bytes at emit.
    pub secondary_raw_stdout_digest: ScientificDigest,
    /// The secondary's process exit code (sealed; re-checked at verify).
    pub secondary_exit_code: i32,
    /// `EXECUTED` (v0): unlike the declared blocks, this one witnesses a run
    /// that actually happened; verify re-executes it.
    pub status: String,
}

/// Derive the witnessed-absence fields from the observed capability union
/// (PURE, unit-tested): the typed-effect system doing receipt work.
///
/// FAIL CLOSED. Each capability is treated as a hazard for a claim UNLESS it
/// is provably incapable of undermining it. Two claims are derived:
///
/// * `input_dataset` (NONE_WITNESSED only if the program provably read no
///   external data): every capability that opens a data channel
///   (FileSystem, Network, Environment, Foreign, Gpu, and `Console` when it
///   reads stdin) is a hazard. `Process` (exit) and `Clock` are not: exiting
///   reads nothing, and the wall clock is a scalar nondeterminism source, not
///   a dataset channel.
/// * `determinism` (deterministic modulo sealed args only if nothing varies
///   between runs): every capability above PLUS `Clock` is a hazard;
///   `Process` alone is not.
///
/// `Console` is the one capability whose character depends on HOW it is used
/// (stdout writes are safe, stdin reads are not), which `reads_stdin`
/// disambiguates. `Random` is the other conditional one: it feeds no dataset
/// (the PRNG is arithmetic over a 64-bit state, not a data channel), and it
/// varies between runs ONLY when unseeded, which `sealed_seed` disambiguates.
/// Every capability not explicitly recognised as safe counts as a hazard for
/// BOTH claims, so a capability added to the type checker later cannot
/// silently widen a witnessed-absence claim.
///
/// The `seed` field is a trichotomy:
/// * no Random capability -> `NOT_APPLICABLE` (nothing draws; a sealed seed
///   would be a claim about a capability the program does not have);
/// * Random with a sealed seed -> `SEALED` (the receipt's `seed_value` field
///   carries the number; the same seed reproduces the stream);
/// * Random with NO seed -> `UNSEEDED`. Emit refuses to produce a receipt in
///   this state, so it only arises when verify re-derives the fields for a
///   receipt whose sealed claims disagree with its capabilities, where the
///   mismatch is exactly the point.
pub fn witnessed_fields_from_capabilities(
    observed_capabilities: &[String],
    reads_stdin: bool,
    sealed_seed: Option<u64>,
) -> (
    ScientificWitnessedField,
    ScientificWitnessedField,
    ScientificDeterminism,
) {
    let mut dataset_hazards: Vec<String> = Vec::new();
    let mut determinism_hazards: Vec<String> = Vec::new();
    let mut uses_random = false;
    for cap in observed_capabilities {
        let (feeds_dataset, varies) = match cap.as_str() {
            "Console" => (reads_stdin, reads_stdin),
            "Process" => (false, false),
            "Clock" => (false, true),
            "Random" => {
                uses_random = true;
                (false, sealed_seed.is_none())
            }
            // FileSystem, Network, Environment, Foreign, Gpu, and any
            // capability this build does not recognise: assume it can do both.
            _ => (true, true),
        };
        let label = if cap == "Console" && reads_stdin {
            "stdin".to_string()
        } else if cap == "Random" && sealed_seed.is_none() {
            "unseeded Random".to_string()
        } else {
            cap.clone()
        };
        if feeds_dataset {
            dataset_hazards.push(label.clone());
        }
        if varies {
            determinism_hazards.push(label);
        }
    }

    let input_dataset = if dataset_hazards.is_empty() {
        ScientificWitnessedField {
            status: "NONE_WITNESSED".to_string(),
            grounds: "no observed capability can feed an external dataset (no FileSystem, Network, stdin, Environment, Foreign, or GPU access), so the program provably consumed none".to_string(),
        }
    } else {
        ScientificWitnessedField {
            status: "POSSIBLE_UNWITNESSED".to_string(),
            grounds: format!(
                "observed capabilities include {}, which can feed an external dataset; buildc does not track which resources were touched",
                dataset_hazards.join(", ")
            ),
        }
    };

    let seed = match (uses_random, sealed_seed) {
        (false, _) => ScientificWitnessedField {
            status: "NOT_APPLICABLE".to_string(),
            grounds: "the program exercises no Random capability; there is no seed to record"
                .to_string(),
        },
        (true, Some(value)) => ScientificWitnessedField {
            status: "SEALED".to_string(),
            grounds: format!(
                "the Random capability draws from a PRNG seeded with the sealed seed {value}; re-running under the same seed reproduces the stream"
            ),
        },
        (true, None) => ScientificWitnessedField {
            status: "UNSEEDED".to_string(),
            grounds: "the Random capability draws with no sealed seed; emit refuses this state, so a receipt carrying it cannot have come from buildc".to_string(),
        },
    };

    let determinism = if determinism_hazards.is_empty() {
        let grounds = if uses_random {
            "no observed capability varies between runs given the sealed seed (no Clock, Environment, FileSystem, Network, stdin, Foreign, or GPU access; Random is seeded)".to_string()
        } else {
            "no observed capability varies between runs (no Clock, Environment, FileSystem, Network, stdin, Foreign, GPU, or unseeded Random access)".to_string()
        };
        ScientificDeterminism {
            deterministic_modulo_args: true,
            grounds,
        }
    } else {
        ScientificDeterminism {
            deterministic_modulo_args: false,
            grounds: format!(
                "observed capabilities include {}, which can vary between runs",
                determinism_hazards.join(", ")
            ),
        }
    };

    (input_dataset, seed, determinism)
}

/// An explicitly fenced receipt branch (the corpus's UNAVAILABLE_FENCED
/// discipline): the pass-0122 contract names `telemetry_branch` and
/// `lineage_branch`; buildc does not produce either, and says so in-band
/// rather than omitting the fields (absence of evidence is witnessed, not
/// implied).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificFencedBranch {
    /// `UNAVAILABLE_FENCED`.
    pub status: String,
}

impl ScientificFencedBranch {
    pub fn fenced() -> Self {
        ScientificFencedBranch {
            status: "UNAVAILABLE_FENCED".to_string(),
        }
    }
}

// `{algorithm:"sha256", hex}` digest shape. We re-declare a local, owned,
// serde-round-trippable copy so the receipt deserializes back cleanly; it is
// structurally compatible with `super::CheckReceiptSourceDigest` (which is
// serialize-only with a `&'static str` algorithm).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificDigest {
    pub algorithm: String,
    pub hex: String,
}

impl From<&CheckReceiptSourceDigest> for ScientificDigest {
    fn from(value: &CheckReceiptSourceDigest) -> Self {
        ScientificDigest {
            algorithm: value.algorithm.to_string(),
            hex: value.hex.clone(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificBuildState {
    pub target: String,
    /// Generated-program stdio behavior. Missing means `native`, preserving
    /// the exact shape and hash of receipts sealed before this field existed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stdio_mode: Option<String>,
    pub compiler_status: String,
    pub flags: Vec<String>,
    /// The pass-0122 `compiler_branch` block (see [`ScientificToolchain`]).
    pub toolchain: ScientificToolchain,
}

// No longer `Eq` (only `PartialEq`): `wall_seconds` adds an `f64`, which has
// no total order (`Eq` cannot be derived over it).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificRuntimeState {
    pub os: String,
    pub exit_code: i32,
    /// Wall-clock duration of the witnessed run in seconds, measured with
    /// `std::time::Instant` around the primary program's `.output()` call
    /// and rounded to 3 decimal places. This is the receipt's first EXECUTED
    /// time fact (buildc genuinely observes it, unlike the declared step
    /// counts in `budget`). Sealed at emit; `receipt verify` re-measures its
    /// own re-run and REPORTS the fresh number beside this one, never
    /// requiring agreement (timing is environmental, exactly like raw
    /// stdout bytes). Optional-with-default so receipts sealed before this
    /// field existed keep their exact bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wall_seconds: Option<f64>,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScientificProblem {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificMeasurement {
    pub metric: String,
    pub observed_values: Vec<f64>,
    pub count: usize,
    /// How many columns each row of `observed_values` holds (row-major). `1`
    /// for the single-scalar-per-step invariants; `>= 2` for a relation
    /// invariant, whose verifier de-interleaves the flat series into columns
    /// and checks a relation ACROSS them. Sealed (a tamper is SEAL_MISMATCH);
    /// `count` remains the total token count, so a re-run's token-count drift
    /// is still caught independently of the column structure.
    ///
    /// REQUIRED (no serde default): the recomputed seal always covers this
    /// field, so a receipt sealed without it could never re-verify anyway. A
    /// default would only convert an honest `MALFORMED: missing column_count`
    /// into a misleading `SEAL_MISMATCH` (the same reasoning the `args` field
    /// records for rejecting a default on a sealed field).
    pub column_count: usize,
    /// sha256 over the EXACT raw stdout bytes captured at emit. The parse into
    /// `observed_values` is a lossy transform; sealing the raw payload keeps
    /// byte drift distinguishable from semantic drift. Verify recomputes this
    /// over the re-run's bytes and REPORTS whether it reproduced
    /// (`raw_stdout_reproduced`); a raw mismatch with a matching verdict is
    /// still faithful (exact bytes are platform-dependent by design).
    pub raw_stdout_digest: ScientificDigest,
    /// The versioned extraction policy that produced `observed_values` from
    /// the raw bytes (see [`SERIES_EXTRACTION_POLICY`]). Hard-checked at
    /// verify: a receipt extracted under a different policy cannot be
    /// faithfully re-checked by this build's parser.
    pub series_extraction_policy: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub units: Option<String>,
}

/// The observed outcome of the monotone-non-increasing check over a series.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct InvariantObserved {
    /// Number of steps `k` where `series[k+1] > series[k] + tolerance`.
    pub violation_count: usize,
    /// Zero-based index `k` of the first offending step, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_violation_step: Option<usize>,
    /// First series value (if the series is non-empty).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initial_value: Option<f64>,
    /// Last series value (if the series is non-empty).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub final_value: Option<f64>,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificInvariant {
    pub name: String,
    pub expectation: String,
    pub tolerance: f64,
    pub observed: InvariantObserved,
    /// `PASS` | `FAIL`.
    pub status: String,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificProvenance {
    pub research_source_hash: String,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificRuntimeReceipt {
    pub schema: String,
    pub compiler: String,
    pub compiler_version: String,
    pub language_version: String,
    pub source: String,
    pub source_digest: ScientificDigest,
    pub input_graph_digest: ScientificDigest,
    pub build_state: ScientificBuildState,
    pub runtime_state: ScientificRuntimeState,
    /// The program arguments the receipt was emitted with. `receipt verify`
    /// re-runs the program with EXACTLY these args, so an argv-parameterized
    /// kernel is faithfully re-derived instead of re-run argless. Sealed like
    /// every other field. REQUIRED: a receipt without this field is malformed
    /// (schema v0 shipped with it; a serde default here would be parse-leniency
    /// only, since the recomputed seal always covers the field and a receipt
    /// sealed without it could never verify anyway).
    pub args: Vec<String>,
    pub problem: ScientificProblem,
    /// The criterion the verdict is measured against (pass-0122 `oracle`).
    pub oracle: ScientificOracle,
    /// The witnessed type/effect policy facts (master plan field; verify
    /// re-derives them from source: EFFECT_POLICY_DRIFT on disagreement).
    pub effect_policy: ScientificEffectPolicy,
    /// Witnessed absence or explicit fence, derived from the capability
    /// facts (see `witnessed_fields_from_capabilities`).
    pub input_dataset: ScientificWitnessedField,
    pub seed: ScientificWitnessedField,
    /// The sealed RNG seed, present IFF the program observes the Random
    /// capability (the `seed` field's status is then `SEALED`). Verify re-runs
    /// the program under exactly this seed, so the stream (and therefore the
    /// verdict) is re-derived rather than trusted. Optional-with-default so
    /// receipts sealed before the Random capability existed still parse AND
    /// re-serialize to their original bytes (the field is skipped when absent,
    /// keeping their seals stable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed_value: Option<u64>,
    pub determinism: ScientificDeterminism,
    /// Author-declared numerical method (buildc cannot derive scheme
    /// semantics and does not pretend to).
    pub numerical_method: ScientificNumericalMethod,
    /// The Monte Carlo admission block, present IFF the run declared itself
    /// an MC estimate (all three `--mc-*` flags). Optional-with-default so
    /// receipts sealed before this block existed still parse AND re-serialize
    /// to their original bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub monte_carlo: Option<ScientificMonteCarlo>,
    /// The budgeted-search admission block, present IFF the run declared a
    /// budget (`--budget-steps` + `--budget-consumed`). Optional-with-default
    /// so receipts sealed before this block existed keep their exact bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<ScientificBudget>,
    /// The cross-backend admission block, present IFF the invariant is the
    /// cross-backend member (`--cross-backend <TARGET> --invariant
    /// cross-backend`). Optional-with-default so receipts sealed before this
    /// block existed keep their exact bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cross_backend: Option<ScientificCrossBackend>,
    pub measurement: ScientificMeasurement,
    pub invariant: ScientificInvariant,
    /// Explicitly fenced pass-0122 branches buildc does not produce: absence
    /// is witnessed in-band, never implied by omission.
    pub telemetry_branch: ScientificFencedBranch,
    pub lineage_branch: ScientificFencedBranch,
    pub negative_fixture: bool,
    /// Whether the run diverged (a non-finite value was observed and the series
    /// was truncated to its finite prefix). Load-bearing for verify: for a
    /// diverged run the finite-prefix LENGTH is the index of the first
    /// non-finite value, a function of the exact float trajectory, which the
    /// design declares non-reproducible across toolchains. Verify therefore
    /// gates the prefix-derived checks (count, violation_count) on this field
    /// and instead requires the re-run to reproduce the divergence itself.
    pub diverged: bool,
    /// Version 0 only: the limits list (see [`NOT_CLAIMED_BOUNDARY`]). It is
    /// skipped when empty, so a version 0 receipt re-serializes to its sealed
    /// bytes and a version 1 receipt never carries it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub not_claimed: Vec<String>,
    /// Version 1: what the receipt covers (see [`SCOPE_BASE`]). Skipped when
    /// empty, so a version 0 receipt keeps its sealed bytes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<String>,
    pub labels: Vec<String>,
    pub receipt_status: String,
    pub seal: ScientificDigest,
    pub provenance: ScientificProvenance,
}

/// Energy-monotone-non-increasing invariant over a measured series.
///
/// Counts steps `k` where `series[k + 1] > series[k] + tol`. Records the first
/// offending step (if any) and the initial/final values. The verdict is derived
/// separately in [`invariant_passes`]: PASS requires at least two points AND
/// zero increases. A single-point (or empty) series has nothing to compare, so
/// it cannot witness monotonicity and is not a PASS.
pub fn energy_monotone_nonincreasing(series: &[f64], tol: f64) -> InvariantObserved {
    let mut violation_count = 0usize;
    let mut first_violation_step = None;
    for k in 0..series.len().saturating_sub(1) {
        if series[k + 1] > series[k] + tol {
            violation_count += 1;
            if first_violation_step.is_none() {
                first_violation_step = Some(k);
            }
        }
    }
    InvariantObserved {
        violation_count,
        first_violation_step,
        initial_value: series.first().copied(),
        final_value: series.last().copied(),
    }
}

/// Conserved-quantity invariant over a measured series: the scalar must stay
/// within `tol` of its INITIAL value at every step. A "violation" is a step
/// whose value deviates from `series[0]` by more than `tol`.
///
/// The reference is the FIRST value, not the mean: the mean depends on the
/// whole series, so a re-run that reproduces a different-length prefix (the
/// diverged case) would shift the reference and could flip the verdict, whereas
/// `series[0]` is stable under prefixing. Step 0 always deviates by exactly 0,
/// so it is never a violation. Records the first offending step and the
/// initial/final values; the verdict is derived in [`invariant_passes`] (PASS
/// requires at least two points AND zero violations).
pub fn conserved_quantity_constant(series: &[f64], tol: f64) -> InvariantObserved {
    let reference = series.first().copied();
    let mut violation_count = 0usize;
    let mut first_violation_step = None;
    if let Some(ref0) = reference {
        for (k, &value) in series.iter().enumerate() {
            if (value - ref0).abs() > tol {
                violation_count += 1;
                if first_violation_step.is_none() {
                    first_violation_step = Some(k);
                }
            }
        }
    }
    InvariantObserved {
        violation_count,
        first_violation_step,
        initial_value: reference,
        final_value: series.last().copied(),
    }
}

/// Discrete maximum-principle invariant over a measured series: the scalar must
/// never rise above its INITIAL value by more than `tol` (a one-sided upper
/// bound). A "violation" is a step whose value exceeds `series[0] + tol`.
///
/// Like conservation the reference is the FIRST value (stable under prefixing,
/// so a truncated re-run prefix cannot shift it), but only the UPPER side is
/// fenced: the quantity may fall arbitrarily far. Step 0 exceeds its own
/// reference by exactly 0, so it is never a violation. This is the discrete
/// maximum principle a stable diffusion/oscillation obeys; an unstable
/// (energy-injecting) scheme overshoots and is caught. Records the first
/// offending step and the initial/final values; the verdict is derived in
/// [`invariant_passes`] (PASS requires at least two points AND zero violations).
pub fn bounded_by_initial_maximum(series: &[f64], tol: f64) -> InvariantObserved {
    let reference = series.first().copied();
    let mut violation_count = 0usize;
    let mut first_violation_step = None;
    if let Some(ref0) = reference {
        for (k, &value) in series.iter().enumerate() {
            if value > ref0 + tol {
                violation_count += 1;
                if first_violation_step.is_none() {
                    first_violation_step = Some(k);
                }
            }
        }
    }
    InvariantObserved {
        violation_count,
        first_violation_step,
        initial_value: reference,
        final_value: series.last().copied(),
    }
}

/// Discrete energy-identity invariant over a measured series: each value is a
/// per-step energy-BALANCE residual that must stay within `tol` of ZERO. A
/// "violation" is a step whose `abs(value) > tol`.
///
/// Unlike conservation and bounded, the reference is 0 (an absolute bound), so
/// EVERY step is checked, including step 0 (its residual is a real residual
/// too, not a self-reference). This is the family's quantitative member: the
/// series is not a physical trajectory but the residual of a computed identity,
/// which a faithful scheme keeps at roundoff and a broken one does not. Records
/// the first offending step and the initial/final values; the verdict is
/// derived in [`invariant_passes`] (PASS requires at least two points AND zero
/// violations).
pub fn energy_identity_residual(series: &[f64], tol: f64) -> InvariantObserved {
    let mut violation_count = 0usize;
    let mut first_violation_step = None;
    for (k, &value) in series.iter().enumerate() {
        if value.abs() > tol {
            violation_count += 1;
            if first_violation_step.is_none() {
                first_violation_step = Some(k);
            }
        }
    }
    InvariantObserved {
        violation_count,
        first_violation_step,
        initial_value: series.first().copied(),
        final_value: series.last().copied(),
    }
}

/// Non-negativity invariant over a measured series: no value may drop below zero
/// by more than `tol`. A "violation" is a step whose `value < -tol`.
///
/// The lower-side companion to `bounded`: `bounded` fences the UPPER side
/// against the initial value, this fences the LOWER side against an ABSOLUTE
/// floor of zero (arbitrarily large positive values are fine). It witnesses that
/// a quantity required to stay non-negative does so: a diffusion concentration
/// that never goes unphysically negative, or a result-bearing SLACK (a proven
/// bound minus an algorithm's measured cost) that never goes negative. Records
/// the first offending step and the initial/final values; the verdict is derived
/// in [`invariant_passes`] (PASS requires at least two points AND zero
/// violations).
pub fn non_negative(series: &[f64], tol: f64) -> InvariantObserved {
    let mut violation_count = 0usize;
    let mut first_violation_step = None;
    for (k, &value) in series.iter().enumerate() {
        if value < -tol {
            violation_count += 1;
            if first_violation_step.is_none() {
                first_violation_step = Some(k);
            }
        }
    }
    InvariantObserved {
        violation_count,
        first_violation_step,
        initial_value: series.first().copied(),
        final_value: series.last().copied(),
    }
}

/// The invariant PASSes iff the series has at least two points and no step
/// violated the invariant beyond tolerance. Uniform across the family: an
/// invariant's whole verdict is "enough points to witness it, and zero
/// violations".
pub fn invariant_passes(series_len: usize, observed: &InvariantObserved) -> bool {
    series_len >= 2 && observed.violation_count == 0
}

/// Every invariant this build implements and can re-check. The single source of
/// truth for the family: `is_known_invariant` and the verify-side "unsupported
/// invariant" diagnostic both read it, so adding an invariant here cannot leave
/// a hardcoded list stale (the failure mode the C1 review caught in the export
/// evidence). Each name here MUST have arms in `invariant_tolerance` and
/// `invariant_expectation`, and MUST be scored by `evaluate_measurement`: the
/// single-scalar invariants through its `evaluate_invariant` delegate, the
/// relation invariant through its own multi-column arm. Do NOT add the relation
/// name to `evaluate_invariant` (it lacks the `column_count` it needs).
pub const KNOWN_INVARIANTS: &[&str] = &[
    ENERGY_MONOTONE_INVARIANT,
    CONSERVATION_INVARIANT,
    BOUNDED_INVARIANT,
    ENERGY_IDENTITY_INVARIANT,
    RELATION_INVARIANT,
    CONSERVED_BAND_INVARIANT,
    NON_NEGATIVE_INVARIANT,
    CROSS_BACKEND_INVARIANT,
];

/// Whether `name` is an invariant this build implements (and can therefore
/// re-check). The oracle binding is pinned to this: a receipt naming an
/// invariant not in this set is `INVARIANT_UNSUPPORTED`.
pub fn is_known_invariant(name: &str) -> bool {
    KNOWN_INVARIANTS.contains(&name)
}

/// The column-count contract for an invariant: the `relation` invariant reads
/// ACROSS a row's columns and needs at least two; an EXECUTED monte_carlo
/// receipt requires exactly 3 columns (the invariant scalar plus the
/// witnessed successes/trials counters) paired with a single-scalar invariant
/// name, never with `relation`/`cross-backend` (their columns already mean
/// something else); every other single-scalar invariant requires exactly 1.
/// Emit enforces this before compiling; verify RE-CHECKS it
/// (FIELD_CONTRACT_VIOLATION) so a resealed receipt cannot present a column
/// structure the invariant's contract forbids, keeping the structural
/// contract symmetric across emit and verify like every other sealed field.
pub fn column_count_matches_invariant(name: &str, column_count: usize, mc_executed: bool) -> bool {
    if name == RELATION_INVARIANT {
        !mc_executed && column_count >= 2
    } else if name == CROSS_BACKEND_INVARIANT {
        // The cross-backend row is exactly two columns (the C anchor and the
        // secondary lane): unlike the open-ended relation family member, the
        // invariant itself defines the column structure, so no other count
        // is expressible. Never paired with an EXECUTED mc block: the
        // columns already mean something else, and cross-backend refuses
        // Random anyway, which mc requires.
        !mc_executed && column_count == 2
    } else if mc_executed {
        column_count == 3
    } else {
        column_count == 1
    }
}

/// The FIXED tolerance for a named invariant. Tolerance is a property of the
/// invariant, not an author-tunable knob: pinning it here (and re-checking the
/// sealed value against it at verify) stops a receipt from weakening its own
/// check by sealing a loose tolerance. Unknown names fall back to the strict
/// monotone tolerance (they are rejected upstream by `is_known_invariant`).
pub fn invariant_tolerance(name: &str) -> f64 {
    match name {
        CONSERVATION_INVARIANT => CONSERVATION_TOLERANCE,
        BOUNDED_INVARIANT => BOUNDED_TOLERANCE,
        ENERGY_IDENTITY_INVARIANT => ENERGY_IDENTITY_TOLERANCE,
        RELATION_INVARIANT => RELATION_TOLERANCE,
        CONSERVED_BAND_INVARIANT => CONSERVED_BAND_TOLERANCE,
        NON_NEGATIVE_INVARIANT => NON_NEGATIVE_TOLERANCE,
        CROSS_BACKEND_INVARIANT => CROSS_BACKEND_TOLERANCE,
        _ => ENERGY_MONOTONE_TOLERANCE,
    }
}

/// The human-readable expectation string sealed for a named invariant.
pub fn invariant_expectation(name: &str) -> &'static str {
    match name {
        CONSERVATION_INVARIANT => "no step deviates the conserved quantity beyond tolerance",
        BOUNDED_INVARIANT => "no step exceeds the initial value beyond tolerance",
        ENERGY_IDENTITY_INVARIANT => {
            "every step's energy-balance residual stays within tolerance of zero"
        }
        RELATION_INVARIANT => "every row's columns agree within tolerance",
        CONSERVED_BAND_INVARIANT => {
            "the quantity stays within the error budget of its initial value"
        }
        NON_NEGATIVE_INVARIANT => "no value drops below zero beyond tolerance",
        CROSS_BACKEND_INVARIANT => {
            "every row's two backend columns agree within the cross-backend tolerance"
        }
        _ => "no step increases energy beyond tolerance",
    }
}

/// Evaluate the named invariant over a series. The single dispatch point both
/// emit and verify go through, so the two can never disagree on what an
/// invariant means.
pub fn evaluate_invariant(name: &str, series: &[f64], tol: f64) -> InvariantObserved {
    match name {
        // conserved-band reuses conservation's two-sided evaluator; only its
        // (looser, calibrated) tolerance differs, which `invariant_tolerance`
        // supplies. The distinct claim is "approximately conserved within a
        // fixed error budget", not "conserved to roundoff".
        CONSERVATION_INVARIANT | CONSERVED_BAND_INVARIANT => {
            conserved_quantity_constant(series, tol)
        }
        BOUNDED_INVARIANT => bounded_by_initial_maximum(series, tol),
        ENERGY_IDENTITY_INVARIANT => energy_identity_residual(series, tol),
        NON_NEGATIVE_INVARIANT => non_negative(series, tol),
        _ => energy_monotone_nonincreasing(series, tol),
    }
}

/// Cross-column relation invariant over a MULTI-COLUMN series (row-major, with
/// `column_count` values per row): every row must AGREE, i.e. all its columns
/// lie within `tol` of the row's first column. A "violation" is a disagreeing
/// row. The verifier computes this from the raw columns, so a program that
/// prints two independent computations of a quantity cannot conceal a
/// divergence between them. Returns the observed result AND the ROW count (the
/// number of observations, which the verdict's "enough points" rule uses, not
/// the raw token count).
///
/// A `column_count` below 2, an empty series, or a series whose length is not a
/// multiple of `column_count` (ragged rows) yields zero complete rows, which
/// the verdict rule treats as "cannot witness the relation".
pub fn relation_columns_agree(
    series: &[f64],
    tol: f64,
    column_count: usize,
) -> (InvariantObserved, usize) {
    let ragged = column_count < 2 || series.is_empty() || series.len() % column_count != 0;
    let rows = if ragged {
        0
    } else {
        series.len() / column_count
    };
    let mut violation_count = 0usize;
    let mut first_violation_step = None;
    for k in 0..rows {
        let base = k * column_count;
        let col0 = series[base];
        let disagrees = (1..column_count).any(|c| (series[base + c] - col0).abs() > tol);
        if disagrees {
            violation_count += 1;
            if first_violation_step.is_none() {
                first_violation_step = Some(k);
            }
        }
    }
    (
        InvariantObserved {
            violation_count,
            first_violation_step,
            initial_value: series.first().copied(),
            final_value: series.last().copied(),
        },
        rows,
    )
}

/// The observed invariant result plus the EFFECTIVE observation count the
/// verdict's "at least two points" rule uses: `series.len()` for the
/// single-scalar invariants, but the ROW count for a relation invariant (each
/// row of `column_count` values is one observation).
pub struct MeasurementVerdict {
    pub observed: InvariantObserved,
    pub effective_len: usize,
}

/// The SINGLE evaluation dispatch both emit and verify go through, so the two
/// can never disagree on how a measurement is scored. Single-column invariants
/// ignore `column_count`; the relation invariant de-interleaves by it.
pub fn evaluate_measurement(
    name: &str,
    series: &[f64],
    tol: f64,
    column_count: usize,
) -> MeasurementVerdict {
    match name {
        // The cross-backend invariant reuses the relation family's evaluator
        // unchanged: only the tolerance (looser, for the C/Rust print-format
        // floor) and the sealed provenance (the `cross_backend` block)
        // differ. Do NOT add it to `evaluate_invariant` (it lacks the
        // `column_count` the relation arm needs), same reason as `relation`.
        RELATION_INVARIANT | CROSS_BACKEND_INVARIANT => {
            let (observed, rows) = relation_columns_agree(series, tol, column_count);
            MeasurementVerdict {
                observed,
                effective_len: rows,
            }
        }
        _ if column_count == 3 => {
            // An EXECUTED monte_carlo receipt: column 0 is the declared
            // single-scalar invariant, columns 1-2 are the witnessed
            // successes/trials counters `compute_mc_executed` checks
            // separately. De-interleave and evaluate the invariant over
            // column 0 only; rows are the effective observation count,
            // mirroring the relation arm above. Ragged (not a multiple of
            // 3) yields zero rows, same "cannot witness" treatment
            // `relation_columns_agree` gives a ragged relation series.
            let ragged = series.is_empty() || series.len() % 3 != 0;
            let col0: Vec<f64> = if ragged {
                Vec::new()
            } else {
                series.iter().step_by(3).copied().collect()
            };
            let rows = col0.len();
            MeasurementVerdict {
                observed: evaluate_invariant(name, &col0, tol),
                effective_len: rows,
            }
        }
        _ => MeasurementVerdict {
            observed: evaluate_invariant(name, series, tol),
            effective_len: series.len(),
        },
    }
}

/// The recomputed EXECUTED monte_carlo fields, owned by the caller to
/// compare against the sealed ones (emit: seal them; verify: compare).
#[derive(Clone, Debug, PartialEq)]
pub struct McExecutedComputed {
    pub estimate: f64,
    pub interval_low: f64,
    pub interval_high: f64,
    pub n_effective: u64,
    pub successes: u64,
}

/// Recompute the EXECUTED monte_carlo fields from a captured three-column
/// series (`<invariant_scalar> <successes> <trials>` per row), the
/// declared denominator, and the named interval method. PURE and
/// unit-tested; called from emit (fail closed before sealing), verify
/// Stage A (over the sealed series, before any re-run), and verify Stage B
/// (over the re-run series). Never trusts anything but the raw columns.
///
/// Coherence checks, in order (Decision 1, design doc): every successes/
/// trials value is integer-valued (`fract() == 0`) and below 2^53; trials
/// increments by exactly 1 across consecutive rows (the first row's
/// absolute value is free, the burn-in edge); successes is non-decreasing
/// with increments in {0, 1}; successes <= trials on every row; the final
/// row's trials equals `samples` (the witnessed-denominator equality).
/// `interval_method` must be one of the two executable methods
/// (`MC_INTERVAL_NORMAL_APPROX_95`, `MC_INTERVAL_WILSON_95`); any other
/// name (including `clopper-pearson-95`) is refused here, the single
/// source of truth for the executable vocabulary. `normal-approx-95` is
/// additionally refused at a boundary proportion (successes_final == 0 or
/// == trials_final): a zero-width interval there overclaims precision;
/// the message points at `wilson-95`.
pub fn compute_mc_executed(
    series: &[f64],
    column_count: usize,
    samples: u64,
    interval_method: &str,
) -> Result<McExecutedComputed, String> {
    const MAX_EXACT_INTEGER: f64 = 9007199254740992.0; // 2^53

    if column_count != 3 {
        return Err(format!(
            "column_count {column_count} is not 3: an EXECUTED monte_carlo receipt requires exactly three columns per row"
        ));
    }
    if series.is_empty() || series.len() % 3 != 0 {
        return Err(format!(
            "series length {} is not a positive multiple of 3: ragged rows cannot witness a Bernoulli count",
            series.len()
        ));
    }
    let rows = series.len() / 3;

    let mut prev_trials: Option<f64> = None;
    let mut prev_successes: Option<f64> = None;
    for k in 0..rows {
        let successes_k = series[k * 3 + 1];
        let trials_k = series[k * 3 + 2];
        for (label, value) in [("successes", successes_k), ("trials", trials_k)] {
            if value.fract() != 0.0 || !value.is_finite() || value.abs() >= MAX_EXACT_INTEGER {
                return Err(format!(
                    "row {k}: {label} = {value} is not an exact non-negative integer below 2^53"
                ));
            }
        }
        if let Some(prev) = prev_trials {
            if trials_k != prev + 1.0 {
                return Err(format!(
                    "row {k}: trials {trials_k} does not follow row {}'s trials {prev} by exactly 1",
                    k - 1
                ));
            }
        }
        if let Some(prev) = prev_successes {
            let delta = successes_k - prev;
            if delta != 0.0 && delta != 1.0 {
                return Err(format!(
                    "row {k}: successes {successes_k} does not follow row {}'s successes {prev} by 0 or 1",
                    k - 1
                ));
            }
        }
        if successes_k > trials_k {
            return Err(format!(
                "row {k}: successes {successes_k} exceeds trials {trials_k}"
            ));
        }
        prev_trials = Some(trials_k);
        prev_successes = Some(successes_k);
    }

    let trials_final = prev_trials.expect("rows > 0, checked above") as u64;
    let successes_final = prev_successes.expect("rows > 0, checked above") as u64;
    if trials_final != samples {
        return Err(format!(
            "witnessed final trials {trials_final} does not equal the declared samples {samples}: the denominator is not witnessed"
        ));
    }

    let n = trials_final as f64;
    let p_hat = successes_final as f64 / n;
    let z = MC_INTERVAL_Z_95;

    let (interval_low, interval_high) = match interval_method {
        MC_INTERVAL_NORMAL_APPROX_95 => {
            if successes_final == 0 || successes_final == trials_final {
                return Err(format!(
                    "normal-approx-95 is degenerate at the boundary proportion (successes = {successes_final} of {trials_final}); use wilson-95"
                ));
            }
            let half_width = z * (p_hat * (1.0 - p_hat) / n).sqrt();
            (p_hat - half_width, p_hat + half_width)
        }
        MC_INTERVAL_WILSON_95 => {
            let z2 = z * z;
            let denom = 1.0 + z2 / n;
            let center = (p_hat + z2 / (2.0 * n)) / denom;
            let margin = (z / denom) * (p_hat * (1.0 - p_hat) / n + z2 / (4.0 * n * n)).sqrt();
            (center - margin, center + margin)
        }
        other => {
            return Err(format!(
                "interval_method `{other}` is not in the EXECUTED executable vocabulary (v1: normal-approx-95, wilson-95); `{MC_INTERVAL_CLOPPER_PEARSON_95}` needs a verified inverse incomplete beta and is not executable"
            ));
        }
    };

    Ok(McExecutedComputed {
        estimate: p_hat,
        interval_low,
        interval_high,
        n_effective: trials_final,
        successes: successes_final,
    })
}

/// Inputs threaded from `cmd_run` into the receipt builder.
pub struct ScientificReceiptInputs<'a> {
    pub source_path: &'a Path,
    pub compiler_version: &'a str,
    pub language_version: String,
    pub source_digest: ScientificDigest,
    pub input_graph_digest: ScientificDigest,
    pub target: &'a str,
    /// Generated-program stdio behavior. `None` means native and is omitted
    /// from the sealed receipt for backward hash compatibility.
    pub stdio_mode: Option<&'a str>,
    pub os: &'a str,
    pub exit_code: i32,
    /// The witnessed run's wall-clock duration in seconds (measured by
    /// `compile_and_capture_run`). The real emit path always supplies
    /// `Some`; `None` is for test fixtures modeling a receipt sealed before
    /// this field existed.
    pub wall_seconds: Option<f64>,
    /// The pass-0122 `compiler_branch` facts probed at emit.
    pub toolchain: ScientificToolchain,
    /// The effect/capability facts derived by the check pipeline at emit.
    pub effect_policy: ScientificEffectPolicy,
    /// Author-declared numerical method description (from `--method`).
    pub method_description: Option<String>,
    /// sha256 over the exact raw stdout bytes the run produced.
    pub raw_stdout_digest: ScientificDigest,
    pub series: Vec<f64>,
    /// Whether the raw stdout produced at least one parseable numeric token.
    /// When false, the series is empty because nothing parsed -> UNVERIFIABLE.
    pub series_parsed: bool,
    /// Whether the program emitted a non-finite value (inf / NaN). A diverged
    /// run is UNVERIFIABLE: the invariant could not be honestly evaluated.
    pub diverged: bool,
    /// The program arguments the run was invoked with (recorded so verify can
    /// re-run identically).
    pub args: Vec<String>,
    /// The RNG seed the run was invoked with (`--seed N`). `cmd_run` has
    /// already enforced the pairing (a Random-using program requires a seed,
    /// a seed requires a Random-using program) before building the receipt.
    pub seed_value: Option<u64>,
    /// The Monte Carlo admission block (`--mc-estimator` / `--mc-samples` /
    /// `--mc-interval`). `cmd_run` has already enforced completeness and the
    /// Random pairing before building the receipt.
    pub monte_carlo: Option<ScientificMonteCarlo>,
    /// The budgeted-search admission block (`--budget-steps` /
    /// `--budget-consumed`). `cmd_run` has already enforced completeness and
    /// the coherence of consumption against the ceiling before building the
    /// receipt.
    pub budget: Option<ScientificBudget>,
    /// The cross-backend admission block (`--cross-backend <TARGET>`).
    /// `cmd_run` has already run the secondary lane, interleaved its series
    /// with the primary's, and enforced the pairing before building the
    /// receipt.
    pub cross_backend: Option<ScientificCrossBackend>,
    /// The invariant to check over the series (a name from the registry;
    /// `is_known_invariant`). Selects the evaluator, tolerance, expectation,
    /// and the sealed oracle/invariant binding.
    pub invariant_name: String,
    pub metric: String,
    pub units: Option<String>,
    /// How many columns each row of the captured series holds (row-major). `1`
    /// for the single-scalar invariants; `>= 2` for the relation invariant.
    pub column_count: usize,
    pub problem_label: Option<String>,
    pub negative_fixture: bool,
    pub flags: Vec<String>,
}

/// Build a sealed scientific-runtime receipt from a captured measurement series.
///
/// Status rule (design):
/// - invariant PASS                                  -> `PASS`
/// - invariant FAIL with `--negative-fixture`        -> `FAIL_EXPECTED`
/// - invariant FAIL without `--negative-fixture`     -> `FAIL_UNEXPECTED`
/// - empty / unparseable series                      -> `UNVERIFIABLE`
///
/// Labels always include `NUMERICAL_RESULT`; `NEGATIVE_FIXTURE` is added
/// when the run is a declared negative fixture.
pub fn build_scientific_runtime_receipt(
    inputs: ScientificReceiptInputs<'_>,
) -> ScientificRuntimeReceipt {
    let ScientificReceiptInputs {
        source_path,
        compiler_version,
        language_version,
        source_digest,
        input_graph_digest,
        target,
        stdio_mode,
        os,
        exit_code,
        wall_seconds,
        toolchain,
        effect_policy,
        method_description,
        raw_stdout_digest,
        series,
        series_parsed,
        diverged,
        args,
        seed_value,
        monte_carlo,
        budget,
        cross_backend,
        invariant_name,
        metric,
        units,
        column_count,
        problem_label,
        negative_fixture,
        flags,
    } = inputs;

    let tolerance = invariant_tolerance(&invariant_name);
    let verdict = evaluate_measurement(&invariant_name, &series, tolerance, column_count);
    let observed = verdict.observed;
    let has_series = series_parsed && !series.is_empty();
    // A diverged run (non-finite value observed) cannot witness the invariant,
    // even if its finite prefix looks monotone, so it never PASSes. The verdict
    // rule uses the effective observation count (rows for a relation invariant,
    // series length for the single-scalar ones).
    let passes = has_series && !diverged && invariant_passes(verdict.effective_len, &observed);

    // Invariant status is PASS/FAIL over the observed series. When there is no
    // series at all, or the run diverged, the invariant could not be evaluated,
    // so it is FAIL and the receipt_status is UNVERIFIABLE (below).
    let invariant_status = if passes { "PASS" } else { "FAIL" };

    let receipt_status = if !has_series || diverged {
        "UNVERIFIABLE"
    } else if passes {
        "PASS"
    } else if negative_fixture {
        "FAIL_EXPECTED"
    } else {
        "FAIL_UNEXPECTED"
    };

    let mut labels = vec![LABEL_NUMERICAL_RESULT.to_string()];
    if negative_fixture {
        labels.push("NEGATIVE_FIXTURE".to_string());
    }
    if diverged {
        // Records WHY an UNVERIFIABLE receipt is unverifiable: the program
        // produced a non-finite (inf/NaN) value, distinct from "no numeric
        // output at all".
        labels.push("NONFINITE_OBSERVED".to_string());
    }
    // A budgeted result carries a label and a scope entry that say it is the
    // best result the search found within its budget.
    let mut scope: Vec<String> = SCOPE_BASE.iter().map(|s| s.to_string()).collect();
    if budget.is_some() {
        labels.push(LABEL_BEST_FOUND_WITHIN_BUDGET.to_string());
        scope.push(SCOPE_BUDGET.to_string());
    }
    // An EXECUTED monte_carlo block adds the two checks it covers: the
    // interval arithmetic and the sample denominator.
    if let Some(mc) = &monte_carlo {
        if mc.status == "EXECUTED" {
            scope.extend(MC_EXECUTED_SCOPE.iter().map(|s| s.to_string()));
        }
    }

    // The typed-effect system doing receipt work: witnessed absences and the
    // determinism statement derive from the observed capability union.
    let (input_dataset, seed, determinism) = witnessed_fields_from_capabilities(
        &effect_policy.observed_capabilities,
        effect_policy.reads_stdin,
        seed_value,
    );

    let count = series.len();
    let mut receipt = ScientificRuntimeReceipt {
        schema: SCIENTIFIC_RUNTIME_SCHEMA.to_string(),
        compiler: "buildc".to_string(),
        compiler_version: compiler_version.to_string(),
        language_version,
        source: source_path.to_string_lossy().to_string(),
        source_digest,
        input_graph_digest,
        build_state: ScientificBuildState {
            target: target.to_string(),
            stdio_mode: stdio_mode
                .filter(|mode| *mode != SCIENTIFIC_STDIO_MODE_NATIVE)
                .map(str::to_string),
            compiler_status: "compiled_and_executed".to_string(),
            flags,
            toolchain,
        },
        runtime_state: ScientificRuntimeState {
            os: os.to_string(),
            exit_code,
            wall_seconds,
        },
        args,
        problem: ScientificProblem {
            label: problem_label,
        },
        oracle: ScientificOracle {
            kind: "declared_invariant".to_string(),
            name: invariant_name.clone(),
            status: "DECLARED".to_string(),
        },
        input_dataset,
        seed,
        seed_value,
        determinism,
        numerical_method: ScientificNumericalMethod {
            status: if method_description.is_some() {
                "DECLARED".to_string()
            } else {
                "UNDECLARED".to_string()
            },
            description: method_description,
        },
        monte_carlo,
        budget,
        cross_backend,
        effect_policy,
        measurement: ScientificMeasurement {
            metric,
            observed_values: series,
            count,
            column_count,
            raw_stdout_digest,
            series_extraction_policy: SERIES_EXTRACTION_POLICY.to_string(),
            units,
        },
        invariant: ScientificInvariant {
            name: invariant_name.clone(),
            expectation: invariant_expectation(&invariant_name).to_string(),
            tolerance,
            observed,
            status: invariant_status.to_string(),
        },
        telemetry_branch: ScientificFencedBranch::fenced(),
        lineage_branch: ScientificFencedBranch::fenced(),
        negative_fixture,
        diverged,
        not_claimed: Vec::new(),
        scope,
        labels,
        receipt_status: receipt_status.to_string(),
        // Placeholder; overwritten by `seal_receipt` below.
        seal: ScientificDigest {
            algorithm: "sha256".to_string(),
            hex: String::new(),
        },
        provenance: ScientificProvenance {
            research_source_hash: RESEARCH_SOURCE_HASH.to_string(),
        },
    };

    seal_receipt(&mut receipt);
    receipt
}

/// Compute and set the receipt seal.
///
/// The seal is `sha256` over the canonical JSON of the receipt with the `seal`
/// field's `hex` blanked (empty string) and `algorithm` fixed to `"sha256"`.
/// We serialize a clone of the receipt whose `seal.hex` is `""`, hash those
/// bytes with the existing [`source_digest_hex`], and store the result in
/// `seal.hex`. This is deterministic: `serde_json::to_vec` preserves struct
/// field order, and the only mutated field is the sealed one. Re-derivation
/// (T3 verify) blanks `seal.hex`, re-serializes, re-hashes, and compares.
pub fn seal_receipt(receipt: &mut ScientificRuntimeReceipt) {
    receipt.seal.algorithm = "sha256".to_string();
    receipt.seal.hex.clear();
    let canonical = serde_json::to_vec(receipt).expect("serialize scientific-runtime receipt");
    receipt.seal.hex = source_digest_hex(&canonical);
}

/// Re-derive the seal from a receipt read back from disk and compare against the
/// stored `seal.hex`. Used by `receipt verify` ([`verify_scientific_runtime_receipt`]).
/// Returns the recomputed hex.
pub fn recompute_seal_hex(receipt: &ScientificRuntimeReceipt) -> String {
    let mut probe = receipt.clone();
    probe.seal.algorithm = "sha256".to_string();
    probe.seal.hex.clear();
    let canonical = serde_json::to_vec(&probe).expect("serialize scientific-runtime receipt");
    source_digest_hex(&canonical)
}

/// A single tamper case for `receipt verify --self-test`: a mutated copy of a
/// valid receipt that the verifier MUST reject with a specific `failure_class`.
/// This extends the can-it-FAIL discipline from the kernels to the verifier
/// itself. A verifier whose failure taxonomy cannot actually distinguish these
/// tampers proves nothing when it reports one. Cases that keep the body
/// well-formed are re-sealed so they pass the integrity gate and reach the
/// specific field-contract check under test; the seal-mismatch case is
/// deliberately left unsealed so it trips the integrity gate itself.
#[derive(Clone, Debug)]
pub struct SelfTestCase {
    /// Human-readable description of what was tampered.
    pub label: String,
    /// The tampered receipt JSON to feed back to `receipt verify`.
    pub tampered: serde_json::Value,
    /// The `failure_class` the verifier must report for this tamper.
    pub expected_class: String,
    /// True if the case was re-sealed (so the tamper reaches a post-seal check),
    /// false if it is meant to trip the seal gate itself.
    #[cfg_attr(not(test), allow(dead_code))]
    pub resealed: bool,
}

/// Re-seal a mutated receipt JSON so its stored seal matches its (tampered)
/// body. Fails if the mutation left the body unparseable as a scientific-runtime
/// receipt.
fn reseal_json(value: &serde_json::Value) -> Result<serde_json::Value, String> {
    let mut receipt: ScientificRuntimeReceipt = serde_json::from_value(value.clone())
        .map_err(|e| format!("re-seal target is not a scientific-runtime receipt: {e}"))?;
    seal_receipt(&mut receipt);
    serde_json::to_value(&receipt).map_err(|e| format!("re-serialize after re-seal failed: {e}"))
}

/// Build the tamper table for `receipt verify --self-test`. Each case is a
/// distinct sealed-field tamper paired with the `failure_class` the verifier
/// must report, chosen so that a passing self-test exercises several separate
/// arms of the failure taxonomy (integrity gate, structural gate, and two
/// field-contract gates). The input must be a valid scientific-runtime receipt.
pub fn build_self_test_cases(
    receipt_json: &serde_json::Value,
) -> Result<Vec<SelfTestCase>, String> {
    // The pristine receipt must parse as a scientific-runtime receipt.
    let _: ScientificRuntimeReceipt = serde_json::from_value(receipt_json.clone())
        .map_err(|e| format!("self-test input is not a scientific-runtime receipt: {e}"))?;

    let mut cases = Vec::new();

    // 1. COMPILER_MISMATCH: a foreign compiler tag, rejected before the seal is
    //    even recomputed (the applicability gate).
    {
        let mut v = receipt_json.clone();
        v["compiler"] = serde_json::Value::String("gcc".to_string());
        cases.push(SelfTestCase {
            label: "compiler tag changed to a foreign compiler".to_string(),
            tampered: v,
            expected_class: "COMPILER_MISMATCH".to_string(),
            resealed: false,
        });
    }

    // 2. SEAL_MISMATCH: a witnessed value edited without re-sealing, so the
    //    integrity gate catches the unsealed edit.
    {
        let mut v = receipt_json.clone();
        let cur = v["invariant"]["observed"]["violation_count"]
            .as_i64()
            .unwrap_or(0);
        v["invariant"]["observed"]["violation_count"] = serde_json::Value::from(cur + 7);
        cases.push(SelfTestCase {
            label: "observed violation_count edited without re-sealing".to_string(),
            tampered: v,
            expected_class: "SEAL_MISMATCH".to_string(),
            resealed: false,
        });
    }

    // 3. MALFORMED: a required top-level field removed, so the body no longer
    //    deserializes into the receipt schema.
    {
        let mut v = receipt_json.clone();
        if let Some(obj) = v.as_object_mut() {
            obj.remove("args");
        }
        cases.push(SelfTestCase {
            label: "required `args` field removed".to_string(),
            tampered: v,
            expected_class: "MALFORMED".to_string(),
            resealed: false,
        });
    }

    // 4. FIELD_CONTRACT_VIOLATION: the sealed tolerance changed to a value the
    //    invariant forbids, then re-sealed so it passes the integrity gate and
    //    reaches the tolerance contract re-check.
    {
        let mut v = receipt_json.clone();
        let tol = v["invariant"]["tolerance"].as_f64().unwrap_or(1e-9);
        v["invariant"]["tolerance"] = serde_json::Value::from(tol * 10.0 + 1.0);
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "sealed tolerance loosened then re-sealed".to_string(),
            tampered: v,
            expected_class: "FIELD_CONTRACT_VIOLATION".to_string(),
            resealed: true,
        });
    }

    // 5. INVARIANT_UNSUPPORTED: an unknown invariant name, re-sealed, so the
    //    verifier rejects it at the invariant-registry gate.
    {
        let mut v = receipt_json.clone();
        v["invariant"]["name"] = serde_json::Value::String("not_a_real_invariant".to_string());
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "invariant name replaced with an unknown invariant".to_string(),
            tampered: v,
            expected_class: "INVARIANT_UNSUPPORTED".to_string(),
            resealed: true,
        });
    }

    // 6. FIELD_CONTRACT_VIOLATION (seed pairing): flip the sealed seed_value
    //    against what the program's capabilities can consume, then re-seal so
    //    the tamper reaches the capability-conditioned pairing check rather
    //    than the integrity gate. Both directions are inexpressible: a seed
    //    added to a program with no Random capability claims a knob nothing
    //    reads, and a seed removed from a Random-using program un-seals the
    //    one input that made its stream re-derivable.
    {
        let mut v = receipt_json.clone();
        if v.get("seed_value").is_none() {
            v["seed_value"] = serde_json::Value::from(7u64);
        } else if let Some(obj) = v.as_object_mut() {
            obj.remove("seed_value");
        }
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "sealed seed_value flipped against the program's capabilities".to_string(),
            tampered: v,
            expected_class: "FIELD_CONTRACT_VIOLATION".to_string(),
            resealed: true,
        });
    }

    // 7. FIELD_CONTRACT_VIOLATION (MC denominator): a monte_carlo block whose
    //    sample count is 0, re-sealed. If the receipt already carries a block,
    //    its denominator is zeroed; if not, a zero-denominator block is added.
    //    Either way the tamper reaches the admission contract (an MC claim
    //    without its denominator is unpriceable), never the integrity gate.
    {
        let mut v = receipt_json.clone();
        match v.get_mut("monte_carlo") {
            Some(mc) if !mc.is_null() => {
                mc["samples"] = serde_json::Value::from(0u64);
            }
            _ => {
                v["monte_carlo"] = serde_json::json!({
                    "estimator": "mean",
                    "samples": 0u64,
                    "interval_method": "normal-approx-95",
                    "status": "DECLARED",
                });
            }
        }
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "monte_carlo block with a zero sample denominator".to_string(),
            tampered: v,
            expected_class: "FIELD_CONTRACT_VIOLATION".to_string(),
            resealed: true,
        });
    }

    // 8. FIELD_CONTRACT_VIOLATION (budget consumption): a budget block whose
    //    steps_consumed exceeds steps_limit, re-sealed. If the receipt already
    //    carries a block, its consumption is bumped past the ceiling; if not,
    //    an incoherent block is added. Either way the tamper reaches the
    //    admission contract (a consumption above its ceiling is incoherent),
    //    never the integrity gate.
    {
        let mut v = receipt_json.clone();
        match v.get_mut("budget") {
            Some(budget) if !budget.is_null() => {
                let limit = budget["steps_limit"].as_u64().unwrap_or(10);
                budget["steps_consumed"] = serde_json::Value::from(limit + 1);
            }
            _ => {
                v["budget"] = serde_json::json!({
                    "steps_limit": 10u64,
                    "steps_consumed": 11u64,
                    "exhausted": false,
                    "status": "DECLARED",
                });
            }
        }
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "budget block with steps_consumed above steps_limit".to_string(),
            tampered: v,
            expected_class: "FIELD_CONTRACT_VIOLATION".to_string(),
            resealed: true,
        });
    }

    // 9. FIELD_CONTRACT_VIOLATION (cross-backend biconditional): swap the
    //    sealed invariant/block pairing. If the receipt carries a
    //    cross_backend block, remove it (keeping the invariant name); if not,
    //    add a syntactically valid block (target `rust`, `EXECUTED`, three
    //    64-hex digests of `a`, exit 0) while leaving the invariant name
    //    unchanged. Either way the tamper reaches the biconditional admission
    //    contract, never the integrity gate.
    {
        let mut v = receipt_json.clone();
        match v.get("cross_backend") {
            Some(cb) if !cb.is_null() => {
                if let Some(obj) = v.as_object_mut() {
                    obj.remove("cross_backend");
                }
            }
            _ => {
                v["cross_backend"] = serde_json::json!({
                    "secondary_target": "rust",
                    "secondary_toolchain_version": "rustc 0.0.0 (self-test)",
                    "secondary_toolchain_digest": {"algorithm": "sha256", "hex": "a".repeat(64)},
                    "secondary_executable_digest": {"algorithm": "sha256", "hex": "a".repeat(64)},
                    "secondary_raw_stdout_digest": {"algorithm": "sha256", "hex": "a".repeat(64)},
                    "secondary_exit_code": 0,
                    "status": "EXECUTED",
                });
            }
        }
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "cross_backend block swapped against the invariant/block biconditional"
                .to_string(),
            tampered: v,
            expected_class: "FIELD_CONTRACT_VIOLATION".to_string(),
            resealed: true,
        });
    }

    // 10. FIELD_CONTRACT_VIOLATION (MC executed interval does not recompute):
    //    nudge the sealed interval_high on an EXECUTED monte_carlo block (the
    //    receipt's own block if it already carries one -- e.g. a receipt
    //    emitted from mc_pi_rejection_executed.bld -- else a syntactically
    //    valid one is added, mirroring case 9's cross_backend fallback).
    //    Either way the tamper reaches Stage A's FIELD_CONTRACT_VIOLATION arm:
    //    whichever stage-A gate fires first (seed pairing, field presence, or
    //    the interval-mismatch check this case targets) on an arbitrary
    //    pristine input, the reported class is FIELD_CONTRACT_VIOLATION
    //    either way, the same robustness case 7's zero-denominator tamper
    //    already relies on.
    {
        let mut v = receipt_json.clone();
        match v.get_mut("monte_carlo") {
            Some(mc)
                if !mc.is_null()
                    && mc.get("status").and_then(|s| s.as_str()) == Some("EXECUTED") =>
            {
                let bumped = mc["interval_high"].as_f64().unwrap_or(0.5) + 0.25;
                mc["interval_high"] = serde_json::Value::from(bumped);
            }
            _ => {
                v["monte_carlo"] = serde_json::json!({
                    "estimator": "proportion",
                    "samples": 4u64,
                    "interval_method": "wilson-95",
                    "status": "EXECUTED",
                    "estimate": 0.5,
                    "interval_low": 0.15,
                    "interval_high": 0.85,
                    "n_effective": 4u64,
                    "successes": 2u64,
                });
            }
        }
        let v = reseal_json(&v)?;
        cases.push(SelfTestCase {
            label: "EXECUTED monte_carlo interval_high nudged against its Stage A recompute"
                .to_string(),
            tampered: v,
            expected_class: "FIELD_CONTRACT_VIOLATION".to_string(),
            resealed: true,
        });
    }

    Ok(cases)
}

/// Schema tag for a receipt chain manifest (see [`ReceiptChainManifest`]).
pub const RECEIPT_CHAIN_SCHEMA: &str = "buildlang-scientific-receipt-chain/v0";

/// One link in a receipt chain: a reference to a member receipt plus the exact
/// seal that receipt carried when the chain was built. Pinning the seal makes
/// substituting a different (even validly-sealed) receipt detectable.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ReceiptChainLink {
    /// Position in the chain (0-based). Bound into the chain seal, so a tampered
    /// index is caught as a chain seal mismatch.
    pub index: usize,
    /// Path to the member receipt file.
    pub receipt: String,
    /// The member receipt's sealed `source` field, for human reading.
    pub source: String,
    /// The member receipt's `seal.hex` at build time, pinned into the chain.
    pub receipt_seal: String,
}

/// A receipt chain manifest: an ordered bundle of scientific-runtime receipts
/// with a chain seal that binds their order and membership. It carries one
/// re-checkable provenance thread over a multi-stage computation without
/// changing the receipt schema itself. `receipt chain verify` re-checks the
/// chain seal, pins each member to its recorded seal, and re-verifies each
/// member receipt.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ReceiptChainManifest {
    pub schema: String,
    pub links: Vec<ReceiptChainLink>,
    pub chain_seal: ScientificDigest,
}

/// Compute the chain seal over the ORDERED list of member receipt seals.
/// Reordering, adding, or dropping a link changes this hash, so the chain is a
/// tamper-evident ordered bundle independent of each member's own seal.
pub fn receipt_chain_seal_hex(links: &[ReceiptChainLink]) -> String {
    // Bind BOTH the position index and the member seal, in order, so a tampered
    // index (not just a reordered or swapped member) is caught as a chain seal
    // mismatch. Index is therefore a witnessed field, not decorative.
    let ordered: Vec<(usize, &str)> = links
        .iter()
        .map(|l| (l.index, l.receipt_seal.as_str()))
        .collect();
    let canonical = serde_json::to_vec(&ordered).expect("serialize chain seal input");
    source_digest_hex(&canonical)
}

/// Build a chain manifest from `(receipt_path, source, seal_hex)` triples in
/// order. The chain seal is computed over the ordered member seals.
pub fn build_receipt_chain(members: &[(String, String, String)]) -> ReceiptChainManifest {
    let links: Vec<ReceiptChainLink> = members
        .iter()
        .enumerate()
        .map(|(index, (receipt, source, seal))| ReceiptChainLink {
            index,
            receipt: receipt.clone(),
            source: source.clone(),
            receipt_seal: seal.clone(),
        })
        .collect();
    let hex = receipt_chain_seal_hex(&links);
    ReceiptChainManifest {
        schema: RECEIPT_CHAIN_SCHEMA.to_string(),
        links,
        chain_seal: ScientificDigest {
            algorithm: "sha256".to_string(),
            hex,
        },
    }
}

/// Schema tag for a scientific-receipt corpus manifest (see
/// [`ScientificCorpusManifest`]).
pub const RECEIPT_CORPUS_SCHEMA: &str = "buildlang-scientific-receipt-corpus/v0";

fn default_corpus_columns() -> u32 {
    1
}

/// One member of a scientific-receipt corpus: an example kernel with the
/// invariant it is run under and the receipt status it is DECLARED to produce.
/// `receipt corpus` emits and verifies each member and asserts reality matches
/// this declaration, so a kernel that silently changes verdict fails the corpus.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificCorpusMember {
    /// Path to the kernel source, relative to the corpus run's working directory.
    pub source: String,
    /// The invariant name (kebab-case CLI form, e.g. `energy-monotone`).
    pub invariant: String,
    /// Columns to capture (default 1); >1 for cross-column invariants.
    #[serde(default = "default_corpus_columns")]
    pub columns: u32,
    /// Whether to emit under `--negative-fixture` (the member is expected to fail
    /// its invariant).
    #[serde(default)]
    pub negative_fixture: bool,
    /// The RNG seed to emit under (`--seed N`). Required for a member whose
    /// kernel observes the Random capability; emit refuses a seedless Random
    /// run, so a missing seed here fails the corpus loudly rather than
    /// producing an unseeded receipt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed: Option<u64>,
    /// The member's Monte Carlo declaration (`--mc-estimator` /
    /// `--mc-samples` / `--mc-interval`), passed through by the runner. The
    /// same all-or-nothing contract applies: a partial declaration is refused
    /// at emit, which fails the corpus loudly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mc_estimator: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mc_samples: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mc_interval: Option<String>,
    /// Whether to emit under `--mc-executed`, passed through by the runner.
    /// No `skip_serializing_if` (the `negative_fixture` precedent): this
    /// manifest is hand-authored input, never re-serialized from the
    /// struct, so byte-stability does not apply here the way it does to a
    /// sealed receipt.
    #[serde(default)]
    pub mc_executed: bool,
    /// The member's budgeted-search declaration (`--budget-steps` /
    /// `--budget-consumed`), passed through by the runner. The same
    /// all-or-nothing contract applies: a partial declaration is refused at
    /// emit, which fails the corpus loudly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget_steps: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget_consumed: Option<u64>,
    /// The member's cross-backend declaration (`--cross-backend <TARGET>`),
    /// passed through by the runner. v0: `rust` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cross_backend: Option<String>,
    /// The declared receipt status: `PASS`, `FAIL_EXPECTED`, or `FAIL_UNEXPECTED`.
    pub expected_status: String,
}

/// A scientific-receipt corpus manifest: the declared classification of every
/// example kernel. Unlike a receipt, this manifest is author-written input and
/// is not sealed; its members' expected statuses are the ground truth the
/// `receipt corpus` command checks reality against.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ScientificCorpusManifest {
    pub schema: String,
    pub members: Vec<ScientificCorpusMember>,
}

/// The outcome of parsing a program's numeric stdout into a measurement series.
#[derive(Clone, Debug, PartialEq)]
pub struct ParsedSeries {
    /// The finite f64 values, in order, up to (but not including) the first
    /// non-finite token. Always finite, so it round-trips through JSON cleanly
    /// (a non-finite f64 would serialize to `null` and break re-verification).
    pub series: Vec<f64>,
    /// Whether at least one numeric OR non-finite token was seen. False means
    /// the program emitted no parseable numbers -> UNVERIFIABLE upstream.
    pub any_parsed: bool,
    /// Whether the program emitted a non-finite value (inf / NaN, in any C
    /// runtime spelling). A numerical blow-up means the invariant could not be
    /// honestly evaluated, so the receipt is UNVERIFIABLE regardless of the
    /// finite prefix's shape (which would otherwise look monotone and PASS).
    pub diverged: bool,
}

/// Whether a token that Rust's f64 parser REJECTS is nonetheless a platform
/// C-runtime spelling of a non-finite value: Windows UCRT `nan(ind)`,
/// `-nan(ind)`, `nan(snan)`; legacy MSVCRT `1.#INF`, `-1.#IND`, `1.#QNAN`,
/// `1.#SNAN` (possibly with trailing padding digits under precision
/// formatting). The match is ANCHORED to those exact token shapes, not
/// substring containment: an ordinary stdout label like `step#info:` or
/// `cell#index=3` must NOT flag the run as diverged (substring matching on
/// `#inf`/`#ind` did exactly that). A word like `information` is also not
/// flagged. The Rust-parseable non-finite forms (`inf`, `nan`, `infinity`,
/// ...) are caught at the parse site, not here.
fn is_nonfinite_spelling(token: &str) -> bool {
    let t = token.trim_start_matches(['+', '-']).to_ascii_lowercase();
    t.starts_with("nan(")
        || t.starts_with("1.#inf")
        || t.starts_with("1.#ind")
        || t.starts_with("1.#qnan")
        || t.starts_with("1.#snan")
}

/// Parse whitespace/newline-separated f64 tokens from captured program stdout.
///
/// Accepts BOTH the plain-decimal (`0.530827`) and scientific (`1.59908e+28`,
/// `6.10352e-05`) forms the C `%g` backend emits, via `str::parse::<f64>`.
/// Non-numeric tokens (blank lines, labels) are skipped. A non-finite token
/// (inf / NaN, any spelling) signals a numerical blow-up: parsing STOPS at that
/// point (so `series` holds only the finite prefix and always serializes
/// cleanly) and `diverged` is set, which routes the receipt to UNVERIFIABLE
/// rather than sealing a diverged run as a false PASS.
pub fn parse_numeric_series(stdout: &str) -> ParsedSeries {
    let mut series = Vec::new();
    let mut any_parsed = false;
    let mut diverged = false;
    for token in stdout.split_whitespace() {
        match token.parse::<f64>() {
            Ok(value) if value.is_finite() => {
                series.push(value);
                any_parsed = true;
            }
            Ok(_) => {
                // Parsed as a non-finite float: `inf`, `-inf`, `nan`, `-nan`,
                // `infinity` (glibc / macOS `%g`). Divergence.
                any_parsed = true;
                diverged = true;
                break;
            }
            Err(_) => {
                // Not Rust-parseable. It may still be a platform C-runtime
                // non-finite spelling (UCRT `nan(ind)`, MSVCRT `1.#INF`), which
                // is a divergence signal; otherwise it's a label/blank -> skip.
                if is_nonfinite_spelling(token) {
                    any_parsed = true;
                    diverged = true;
                    break;
                }
            }
        }
    }
    ParsedSeries {
        series,
        any_parsed,
        diverged,
    }
}

/// The re-derived verdict triple used by `receipt verify` to compare against a
/// stored receipt. Deriving it from the SAME rules `build_scientific_runtime_receipt`
/// applies (via [`energy_monotone_nonincreasing`] / [`invariant_passes`]) is what
/// makes verify re-check the invariant instead of trusting the stored values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecomputedVerdict {
    /// `PASS` | `FAIL` over the re-run series.
    pub invariant_status: &'static str,
    /// Number of energy-increasing steps in the re-run series.
    pub violation_count: usize,
    /// `PASS` | `FAIL_EXPECTED` | `FAIL_UNEXPECTED` | `UNVERIFIABLE`.
    pub receipt_status: &'static str,
}

/// Recompute the invariant + receipt-status verdict from a freshly re-run
/// series, applying the exact same status rule as
/// [`build_scientific_runtime_receipt`]. `negative_fixture` is read back from the
/// stored receipt so the FAIL_EXPECTED / FAIL_UNEXPECTED distinction is
/// reproduced. This checks the VERDICT (monotonicity + increase count), not the
/// exact float values, so it is robust to platform float non-reproducibility.
pub fn recompute_verdict(
    invariant_name: &str,
    series: &[f64],
    series_parsed: bool,
    diverged: bool,
    negative_fixture: bool,
    column_count: usize,
) -> RecomputedVerdict {
    let verdict = evaluate_measurement(
        invariant_name,
        series,
        invariant_tolerance(invariant_name),
        column_count,
    );
    let observed = verdict.observed;
    let has_series = series_parsed && !series.is_empty();
    let passes = has_series && !diverged && invariant_passes(verdict.effective_len, &observed);

    let invariant_status = if passes { "PASS" } else { "FAIL" };
    let receipt_status = if !has_series || diverged {
        "UNVERIFIABLE"
    } else if passes {
        "PASS"
    } else if negative_fixture {
        "FAIL_EXPECTED"
    } else {
        "FAIL_UNEXPECTED"
    };

    RecomputedVerdict {
        invariant_status,
        violation_count: observed.violation_count,
        receipt_status,
    }
}

/// What the `rederive_digests` callback re-derives from the source through
/// the check pipeline: the two input digests plus the effect/capability
/// facts (the sealed effect_policy is compared against these, so the policy
/// block is genuinely re-derived, never trusted).
pub struct RederivedFacts {
    pub source_digest: ScientificDigest,
    pub input_graph_digest: ScientificDigest,
    pub effect_policy: ScientificEffectPolicy,
}

/// What a verify re-run observes from the SECONDARY (cross-backend) lane,
/// returned inside [`RerunObservation`] when the closure was called with
/// `Some(target)`. Mirrors the primary's shape (parsed series, exit code, the
/// two digests) since the secondary lane is re-checked the exact same way.
pub struct SecondaryObservation {
    /// The secondary re-run's parsed numeric stdout.
    pub parsed: ParsedSeries,
    /// The secondary re-run's process exit code (re-checked against the
    /// sealed `cross_backend.secondary_exit_code`; drift is
    /// `RERUN_EXIT_MISMATCH`, naming the secondary lane).
    pub exit_code: i32,
    /// sha256 of the secondary re-run's RAW stdout bytes (REPORTED as
    /// `secondary_raw_stdout_reproduced`; never a failure by itself).
    pub raw_stdout_digest: ScientificDigest,
    /// sha256 of the secondary's re-compiled executable (REPORTED as
    /// `secondary_executable_reproduced`; never a failure by itself).
    pub executable_digest: ScientificDigest,
    /// First line of the FRESHLY PROBED secondary (rustc) toolchain's
    /// version banner, from the same probe `rerun_scientific_receipt`
    /// already runs to invoke the compiler. Gives verify the secondary-lane
    /// visibility parity the primary C lane already has: without this, the
    /// probed rustc's identity was discarded after compiling, so a
    /// substituted `RUSTC` re-executed the secondary lane with zero
    /// visibility into whether it was the toolchain the receipt was sealed
    /// under.
    pub probed_toolchain_version: String,
    /// sha256 over the freshly probed rustc's full version-probe output
    /// bytes, compared against the sealed `cross_backend.secondary_toolchain_digest`
    /// to compute `secondary_toolchain_matched` (WARN on drift, exactly like
    /// the primary's `toolchain_matched`; cross-toolchain re-verification
    /// stays legitimate by design, the defect being fixed here is
    /// invisibility, not the ability to do it).
    pub probed_toolchain_digest: ScientificDigest,
}

/// What a verify re-run observes, returned by the `rerun_series` callback.
pub struct RerunObservation {
    /// The re-run's parsed numeric stdout.
    pub parsed: ParsedSeries,
    /// The re-run's process exit code (re-checked against the sealed
    /// `runtime_state.exit_code`; drift is `RERUN_EXIT_MISMATCH`).
    pub exit_code: i32,
    /// The secondary (cross-backend) lane's re-run observation, present IFF
    /// the `rerun_series` closure was called with `Some(target)` (i.e. the
    /// receipt carries a `cross_backend` block). `None` for every other
    /// receipt.
    pub secondary: Option<SecondaryObservation>,
    /// sha256 of the re-run's RAW stdout bytes (REPORTED as
    /// `raw_stdout_reproduced`; never a failure by itself).
    pub raw_stdout_digest: ScientificDigest,
    /// sha256 of the re-compiled program executable (REPORTED as
    /// `executable_reproduced`; never a failure by itself, since C compiler
    /// output is not byte-stable across compiler versions).
    pub executable_digest: ScientificDigest,
    /// Wall-clock duration of THIS re-run in seconds, measured the same way
    /// `compile_and_capture_run` measured the emitted run. Always present
    /// (verify always re-measures, regardless of whether the sealed receipt
    /// carries a `runtime_state.wall_seconds`); REPORTED beside the sealed
    /// value, never compared for pass/fail (timing is environmental).
    pub wall_seconds: f64,
}

/// Verify a `buildlang-scientific-runtime-receipt/v0` receipt by RE-DERIVING,
/// never trusting the stored values (mirrors `corpus verify`'s discipline):
///
/// 1. Deserialize the receipt and confirm its schema and compiler.
/// 2. Recompute the seal over the stored receipt body and confirm it matches
///    the stored `seal.hex` (integrity of the receipt itself). This runs
///    BEFORE any sealed field is interpreted, so an unsealed edit is reported
///    as tampering rather than as whichever field-level contradiction it
///    happens to trip first.
/// 3. Re-derive the source + input-graph digests and the effect/capability
///    policy from the file on disk (via the `rederive_digests` callback, which
///    runs the same check pipeline that produced the stored facts) and
///    compare. A source change fails here.
/// 4. Re-run the program WITH THE STORED ARGS (via `rerun_series`, the shared
///    compile+run+capture path) and re-parse its numeric stdout into a fresh
///    series. The observed-value COUNT is re-checked against the stored
///    `measurement.count` (a deterministic quantity); a mismatch fails.
/// 5. Recompute the invariant + receipt-status verdict from that fresh series
///    and compare the recomputed `invariant.status`, `violation_count`, and
///    `receipt_status` against the stored ones. Any disagreement is a failure.
///    Individual float VALUES are deliberately NOT re-compared: exact floats
///    need not reproduce across platforms, which is precisely why the verdict
///    (monotonicity + count), not the raw series, is the re-checked quantity.
///
/// A receipt that passes all five checks is FAITHFUL. The exit code additionally
/// reflects the invariant verdict: `Ok(())` for PASS and FAIL_EXPECTED (a
/// negative fixture reproducing its expected failure), and `Err(3)` for
/// FAIL_UNEXPECTED / UNVERIFIABLE. This keeps a bare `receipt verify r.json`
/// safe as a CI pass/fail gate (it does not exit 0 on a recorded invariant
/// violation), distinct from `Err(1)` which means the receipt did NOT reproduce.
///
/// The digest/re-run callbacks are supplied by `main.rs` (which owns `run_check`
/// and `compile_and_capture_run`); the verdict logic and comparisons live here.
///
/// `compiler_version` / `language_version` mismatches WARN (to stderr) rather
/// than hard-fail: a scientific receipt records a numerical verdict that a later
/// compiler build can still legitimately reproduce, so a version bump alone must
/// not be treated as tampering. (The check-receipt verifier pins versions
/// because it replays effect/capability facts that ARE version-sensitive; this
/// numerical receipt is not.)
///
/// `probed_toolchain` is the LOCAL C toolchain probed by the caller before
/// dispatch: `None` means no C compiler is available, which is its own
/// `TOOL_UNAVAILABLE` verdict (exit 4) rather than a generic re-run failure.
/// A present-but-different toolchain WARNs (the verdict is the re-checked
/// quantity, so cross-toolchain re-verification is legitimate) and marks any
/// subsequent drift failure as possibly environmental.
///
/// `rerun_series` is called with the receipt's recorded args and returns a
/// [`RerunObservation`]: the parsed series, the process exit code (re-checked
/// against the sealed `runtime_state.exit_code`; drift is
/// `RERUN_EXIT_MISMATCH`, not a tamper-flavored count drift), and the raw
/// stdout + executable digests (REPORTED as reproduced / not reproduced,
/// never failures by themselves). The fourth argument is the secondary
/// target named by the receipt's `cross_backend` block (`Some("rust")`), or
/// `None` for every receipt without one; the fifth is the sealed stdio mode,
/// defaulting missing old receipts to `native`. When a secondary target is
/// `Some`, the returned observation's `secondary` field must be filled.
///
/// Returns Ok(report) for every FAITHFUL receipt regardless of its recorded
/// verdict (PASS, FAIL_EXPECTED, FAIL_UNEXPECTED, UNVERIFIABLE alike); the
/// callers decide what a faithful-but-failed verdict means for THEM
/// (`verify` maps it to exit 3, the export bridge maps it to a DRIFT or
/// unmeasurable Crucible measurement). Err(1) = did not reproduce; Err(4) =
/// no toolchain.
#[allow(clippy::too_many_arguments)]
pub fn evaluate_scientific_runtime_receipt(
    receipt_json: &serde_json::Value,
    source_override: Option<&Path>,
    json: bool,
    current_compiler_version: &str,
    current_language_version: &str,
    probed_toolchain: Option<&ScientificToolchain>,
    rederive_digests: impl FnOnce(&Path) -> Result<RederivedFacts, i32>,
    rerun_series: impl FnOnce(
        &Path,
        &[String],
        Option<u64>,
        Option<&str>,
        &str,
    ) -> Result<RerunObservation, i32>,
) -> Result<ScientificVerifyReport, i32> {
    let receipt: ScientificRuntimeReceipt =
        serde_json::from_value(receipt_json.clone()).map_err(|err| {
            eprintln!("Error: scientific-runtime receipt is malformed: {}", err);
            verify_failure_class(json, "MALFORMED", 1)
        })?;

    if !is_scientific_runtime_schema(&receipt.schema) {
        eprintln!(
            "Error: unsupported scientific-runtime receipt schema `{}`",
            receipt.schema
        );
        return Err(verify_failure_class(json, "SCHEMA_UNSUPPORTED", 1));
    }
    if receipt.compiler != "buildc" {
        eprintln!(
            "Error: receipt compiler mismatch: expected buildc, got {}",
            receipt.compiler
        );
        return Err(verify_failure_class(json, "COMPILER_MISMATCH", 1));
    }

    // Integrity gate: recompute the seal over the stored receipt body BEFORE
    // interpreting any sealed field. Schema and compiler are the applicability
    // gate (they decide whether this verifier's seal is even comparable); once
    // past them, the very next question is whether the body was tampered with.
    // Checking the seal first means every field-level rejection below
    // (OVERCLAIM_BOUNDARY_MISSING, FIELD_CONTRACT_VIOLATION, ORACLE_*, ...)
    // reports a genuinely author-sealed invalid VALUE rather than misreporting
    // an unsealed edit as an internal contradiction.
    let recomputed_seal = recompute_seal_hex(&receipt);
    if !recomputed_seal.eq_ignore_ascii_case(&receipt.seal.hex) {
        eprintln!(
            "Error: seal mismatch: receipt sha256:{}, recomputed sha256:{}",
            receipt.seal.hex, recomputed_seal
        );
        return Err(verify_failure_class(json, "SEAL_MISMATCH", 1));
    }

    // Read the labels and the coverage list through the vocabulary of the
    // receipt's own schema version. Each version carries exactly one list.
    let vocab = receipt_vocabulary(&receipt.schema);
    let (entries, other) = if vocab.list_name == "scope" {
        (&receipt.scope, &receipt.not_claimed)
    } else {
        (&receipt.not_claimed, &receipt.scope)
    };
    if !other.is_empty() {
        eprintln!(
            "Error: a `{}` receipt carries only the `{}` list",
            receipt.schema, vocab.list_name
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    if !entries.iter().any(|c| c == vocab.required_entry) {
        eprintln!(
            "Error: the receipt's `{}` list must include `{}`, got {:?}",
            vocab.list_name, vocab.required_entry, entries
        );
        return Err(verify_failure_class(json, vocab.missing_class, 1));
    }
    if !receipt.labels.iter().any(|l| l == vocab.numerical_label) {
        eprintln!(
            "Error: the receipt's labels must include {}, got {:?}",
            vocab.numerical_label, receipt.labels
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }

    // The verifier's series-extraction policy must match the sealed one BY
    // VERSION TAG (the part before the first `:`): a receipt extracted under
    // a different policy family/version cannot be faithfully re-checked by
    // this build's parser, but a prose re-wording of the same versioned
    // policy must not read as tampering.
    let sealed_policy_tag = receipt
        .measurement
        .series_extraction_policy
        .split(':')
        .next()
        .unwrap_or("");
    let verifier_policy_tag = SERIES_EXTRACTION_POLICY.split(':').next().unwrap_or("");
    if sealed_policy_tag != verifier_policy_tag {
        eprintln!(
            "Error: series extraction policy mismatch: receipt `{}`, this verifier `{}`",
            receipt.measurement.series_extraction_policy, SERIES_EXTRACTION_POLICY
        );
        return Err(verify_failure_class(json, "EXTRACTION_POLICY_MISMATCH", 1));
    }

    let sealed_stdio_mode = receipt
        .build_state
        .stdio_mode
        .as_deref()
        .unwrap_or(SCIENTIFIC_STDIO_MODE_NATIVE);
    if !matches!(
        sealed_stdio_mode,
        SCIENTIFIC_STDIO_MODE_NATIVE | SCIENTIFIC_STDIO_MODE_PORTABLE_LF
    ) {
        eprintln!(
            "Error: build_state.stdio_mode `{sealed_stdio_mode}` is unsupported; supported: native, portable-lf"
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    if sealed_stdio_mode == SCIENTIFIC_STDIO_MODE_PORTABLE_LF && receipt.build_state.target != "c" {
        eprintln!(
            "Error: build_state.stdio_mode portable-lf is supported only by the C backend; receipt target `{}` does not use the C runtime",
            receipt.build_state.target
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }

    // Every sealed digest must be a real sha256 (64 hex chars): an empty or
    // malformed digest inside a sealed receipt would let "hash unavailable"
    // masquerade as witnessed provenance.
    for (field, digest) in [
        ("source_digest", &receipt.source_digest),
        ("input_graph_digest", &receipt.input_graph_digest),
        (
            "build_state.toolchain.version_output_digest",
            &receipt.build_state.toolchain.version_output_digest,
        ),
        (
            "build_state.toolchain.buildc_binary_digest",
            &receipt.build_state.toolchain.buildc_binary_digest,
        ),
        (
            "build_state.toolchain.program_executable_digest",
            &receipt.build_state.toolchain.program_executable_digest,
        ),
        (
            "measurement.raw_stdout_digest",
            &receipt.measurement.raw_stdout_digest,
        ),
    ] {
        if !digest_is_well_formed(digest) {
            eprintln!(
                "Error: malformed digest in `{}`: algorithm `{}`, hex `{}` (must be sha256 with 64 hex chars)",
                field, digest.algorithm, digest.hex
            );
            return Err(verify_failure_class(json, "DIGEST_MALFORMED", 1));
        }
    }

    // Oracle binding, pinned to the IMPLEMENTATION rather than to another
    // sealed field: this verifier implements exactly one invariant, so both
    // the invariant name and the oracle name must equal it. Comparing
    // oracle.name against invariant.name alone would be self-referential
    // (both are author-controlled sealed strings that a resealed receipt can
    // set to any equal pair).
    if receipt.oracle.kind != "declared_invariant" {
        eprintln!(
            "Error: unsupported oracle kind `{}` (this verifier re-checks `declared_invariant` only)",
            receipt.oracle.kind
        );
        return Err(verify_failure_class(json, "ORACLE_KIND_UNSUPPORTED", 1));
    }
    if receipt.oracle.status != "DECLARED" {
        eprintln!(
            "Error: unsupported oracle status `{}` for kind `declared_invariant` (a declared oracle cannot claim an executed status)",
            receipt.oracle.status
        );
        return Err(verify_failure_class(json, "ORACLE_STATUS_UNSUPPORTED", 1));
    }
    // The invariant is pinned to the IMPLEMENTATION SET, not to another sealed
    // field: `invariant.name` must be one this build actually re-checks, and
    // the oracle must bind to that same invariant. Validating `invariant.name`
    // against `is_known_invariant` (not against `oracle.name`) is what keeps
    // the binding non-self-referential: a resealed receipt may pick any known
    // invariant, but never one the verifier cannot execute.
    if !is_known_invariant(&receipt.invariant.name) {
        eprintln!(
            "Error: unsupported invariant `{}` (this verifier implements {})",
            receipt.invariant.name,
            KNOWN_INVARIANTS.join(", ")
        );
        return Err(verify_failure_class(json, "INVARIANT_UNSUPPORTED", 1));
    }
    if receipt.oracle.name != receipt.invariant.name {
        eprintln!(
            "Error: oracle binding mismatch: oracle names `{}`, invariant is `{}`",
            receipt.oracle.name, receipt.invariant.name
        );
        return Err(verify_failure_class(json, "ORACLE_BINDING_MISMATCH", 1));
    }
    // Tolerance is a FIXED property of the invariant, never an author knob: a
    // receipt that sealed a different tolerance is trying to redefine (usually
    // to weaken) its own check, so it is rejected rather than re-checked under
    // the loosened bound.
    let canonical_tolerance = invariant_tolerance(&receipt.invariant.name);
    if receipt.invariant.tolerance != canonical_tolerance {
        eprintln!(
            "Error: invariant tolerance mismatch: receipt {}, canonical {} for `{}`",
            receipt.invariant.tolerance, canonical_tolerance, receipt.invariant.name
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }

    // Re-check the column-count contract emit enforced (relation needs >= 2
    // columns, an EXECUTED monte_carlo receipt needs exactly 3, every other
    // single-scalar invariant needs exactly 1), so a resealed receipt cannot
    // present a column structure the invariant forbids. The field is inert
    // for the single-scalar invariants' verdict, but leaving the contract
    // unenforced at verify would let emit and verify disagree on what a
    // well-formed receipt is.
    let mc_executed_for_columns = receipt
        .monte_carlo
        .as_ref()
        .is_some_and(|mc| mc.status == "EXECUTED");
    if !column_count_matches_invariant(
        &receipt.invariant.name,
        receipt.measurement.column_count,
        mc_executed_for_columns,
    ) {
        eprintln!(
            "Error: column_count {} violates the contract for invariant `{}` (relation requires >= 2, an EXECUTED monte_carlo receipt requires exactly 3, every other single-scalar invariant requires exactly 1)",
            receipt.measurement.column_count, receipt.invariant.name
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }

    // The fenced branches are load-bearing honesty: v0 produces neither
    // telemetry nor lineage, so the only valid sealed value is the explicit
    // fence. A branch edited (and resealed) to claim availability must be
    // rejected, or the fence would be decorative.
    if receipt.telemetry_branch.status != "UNAVAILABLE_FENCED"
        || receipt.lineage_branch.status != "UNAVAILABLE_FENCED"
    {
        eprintln!(
            "Error: unexpected fence status: telemetry `{}`, lineage `{}` (v0 produces neither; the only valid value is UNAVAILABLE_FENCED)",
            receipt.telemetry_branch.status, receipt.lineage_branch.status
        );
        return Err(verify_failure_class(json, "FENCE_STATUS_UNEXPECTED", 1));
    }

    // Field contracts: the seed pairing is checked against the RE-DERIVED
    // capability facts in step (2a) below (whether a seed is expressible
    // depends on whether the program observes the Random capability, which
    // only the re-derivation can say); the numerical_method status must agree
    // with whether a description is present (a DECLARED method with no
    // description, or an UNDECLARED one with a description, is an
    // inconsistent claim).
    let method_consistent = match receipt.numerical_method.status.as_str() {
        "DECLARED" => receipt.numerical_method.description.is_some(),
        "UNDECLARED" => receipt.numerical_method.description.is_none(),
        _ => false,
    };
    if !method_consistent {
        eprintln!(
            "Error: numerical_method status `{}` is inconsistent with its description (present: {})",
            receipt.numerical_method.status,
            receipt.numerical_method.description.is_some()
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }

    // Version drift WARNs, does not fail (see the doc comment above).
    if receipt.compiler_version != current_compiler_version {
        eprintln!(
            "Warning: compiler version differs: receipt {}, current {} (re-checking the verdict anyway)",
            receipt.compiler_version, current_compiler_version
        );
    }
    if receipt.language_version != current_language_version {
        eprintln!(
            "Warning: language version differs: receipt {}, current {} (re-checking the verdict anyway)",
            receipt.language_version, current_language_version
        );
    }

    // Resolve the source path: an explicit --source override, else the embedded
    // `source` field.
    let source_path = match source_override {
        Some(path) => path.to_path_buf(),
        None => Path::new(&receipt.source).to_path_buf(),
    };

    // (2) Re-derive the source + input-graph digests and compare. A source-file
    // change since sealing shows up as a digest mismatch here.
    let rederived = rederive_digests(&source_path)
        .map_err(|code| verify_failure_class(json, "REDERIVATION_FAILED", code))?;
    let (source_digest, input_graph_digest) =
        (rederived.source_digest, rederived.input_graph_digest);
    if !digests_match(&source_digest, &receipt.source_digest) {
        eprintln!(
            "Error: source digest mismatch: receipt {}:{}, actual {}:{}",
            receipt.source_digest.algorithm,
            receipt.source_digest.hex,
            source_digest.algorithm,
            source_digest.hex
        );
        return Err(verify_failure_class(json, "SOURCE_DIGEST_MISMATCH", 1));
    }
    if !digests_match(&input_graph_digest, &receipt.input_graph_digest) {
        eprintln!(
            "Error: input graph digest mismatch: receipt {}:{}, actual {}:{}",
            receipt.input_graph_digest.algorithm,
            receipt.input_graph_digest.hex,
            input_graph_digest.algorithm,
            input_graph_digest.hex
        );
        return Err(verify_failure_class(json, "INPUT_GRAPH_DIGEST_MISMATCH", 1));
    }

    // (2a) The effect policy is RE-DERIVED, never trusted: the facts digest,
    // the capability union, and every capability-derived witnessed field must
    // agree with what the checker derives from the source right now.
    if !digests_match(
        &rederived.effect_policy.facts_digest,
        &receipt.effect_policy.facts_digest,
    ) || rederived.effect_policy.observed_capabilities
        != receipt.effect_policy.observed_capabilities
        || rederived.effect_policy.reads_stdin != receipt.effect_policy.reads_stdin
    {
        eprintln!(
            "Error: effect policy drift: receipt capabilities {:?} reads_stdin={} (facts sha256:{}), re-derived {:?} reads_stdin={} (facts sha256:{})",
            receipt.effect_policy.observed_capabilities,
            receipt.effect_policy.reads_stdin,
            receipt.effect_policy.facts_digest.hex,
            rederived.effect_policy.observed_capabilities,
            rederived.effect_policy.reads_stdin,
            rederived.effect_policy.facts_digest.hex
        );
        return Err(verify_failure_class(json, "EFFECT_POLICY_DRIFT", 1));
    }
    // The propose/dispose admission rule, enforced on the RE-DERIVED
    // capability union: a Model-observing program is inadmissible on the
    // accept path outright. Emit refuses to produce such a receipt; one
    // presented anyway (hand-built, or emitted by a tampered toolchain) is
    // refused with its own class rather than folded into a field contract.
    if rederived
        .effect_policy
        .observed_capabilities
        .iter()
        .any(|cap| cap == "Model")
    {
        eprintln!(
            "Error: the program uses the Model capability, so a scientific receipt cannot cover this run. Check the model output with a model-free oracled kernel."
        );
        return Err(verify_failure_class(json, "CAPABILITY_INADMISSIBLE", 1));
    }
    // The seed pairing, checked against the RE-DERIVED capabilities: a
    // Random-using program's receipt must seal the seed it ran under (emit
    // refuses to produce one otherwise), and a program with no Random
    // capability has no seed to seal, so a sealed value there is a claim
    // about a capability the program does not have.
    let rederived_uses_random = rederived
        .effect_policy
        .observed_capabilities
        .iter()
        .any(|cap| cap == "Random");
    if rederived_uses_random && receipt.seed_value.is_none() {
        eprintln!(
            "Error: the program observes the Random capability but the receipt seals no seed_value (a Random-using run requires `--seed N`, and the receipt must carry it)"
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    if !rederived_uses_random && receipt.seed_value.is_some() {
        eprintln!(
            "Error: the receipt seals seed_value {} but the program observes no Random capability (nothing draws from a seed)",
            receipt.seed_value.unwrap_or_default()
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    // The Monte Carlo admission contracts. The block is author-declared, but
    // its SHAPE is not negotiable: it rides only on a seeded Random program
    // (an MC claim over a stream that cannot re-derive is unpriceable), its
    // denominator is non-zero, its estimator and interval method are named,
    // and its status is one of the two things v0 can honestly say (DECLARED
    // or EXECUTED). Stage A (this block): re-derived over the SEALED series,
    // before any re-run, so a tampered-and-resealed interval is a pure data
    // contradiction. Stage B (after the re-run, below) re-derives the same
    // fields over the re-run series.
    if let Some(mc) = &receipt.monte_carlo {
        if !rederived_uses_random || receipt.seed_value.is_none() {
            eprintln!(
                "Error: the receipt carries a monte_carlo block but the program is not a seeded Random run (an MC estimate needs the Random capability and a sealed seed to re-derive)"
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if mc.samples == 0 {
            eprintln!(
                "Error: monte_carlo.samples is 0: an MC claim without its denominator is unpriceable"
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if mc.estimator.trim().is_empty() || mc.interval_method.trim().is_empty() {
            eprintln!(
                "Error: monte_carlo declares an empty estimator or interval_method: the claim is the interval, never the point, so both must be named"
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        let executed_fields_present = mc.estimate.is_some()
            || mc.interval_low.is_some()
            || mc.interval_high.is_some()
            || mc.n_effective.is_some()
            || mc.successes.is_some();
        match mc.status.as_str() {
            "DECLARED" => {
                if executed_fields_present {
                    eprintln!(
                        "Error: monte_carlo.status is DECLARED but an executed field is present: a DECLARED block never carries estimate/interval_low/interval_high/n_effective/successes"
                    );
                    return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
                }
            }
            "EXECUTED" => {
                let (
                    Some(estimate),
                    Some(interval_low),
                    Some(interval_high),
                    Some(n_effective),
                    Some(successes),
                ) = (
                    mc.estimate,
                    mc.interval_low,
                    mc.interval_high,
                    mc.n_effective,
                    mc.successes,
                )
                else {
                    eprintln!(
                        "Error: monte_carlo.status is EXECUTED but not all five executed fields (estimate, interval_low, interval_high, n_effective, successes) are present"
                    );
                    return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
                };
                if mc.estimator != MC_EXECUTED_ESTIMATOR_PROPORTION {
                    eprintln!(
                        "Error: EXECUTED monte_carlo estimator `{}` is not in the executable vocabulary (v1: proportion)",
                        mc.estimator
                    );
                    return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
                }
                let computed = compute_mc_executed(
                    &receipt.measurement.observed_values,
                    receipt.measurement.column_count,
                    mc.samples,
                    &mc.interval_method,
                )
                .map_err(|reason| {
                    eprintln!(
                        "Error: EXECUTED monte_carlo Stage A (sealed series, no re-run) recompute failed: {reason}"
                    );
                    verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1)
                })?;
                if computed.n_effective != n_effective || n_effective != mc.samples {
                    eprintln!(
                        "Error: sealed n_effective {n_effective} does not match the Stage A witnessed denominator {} (declared samples {})",
                        computed.n_effective, mc.samples
                    );
                    return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
                }
                if computed.successes != successes {
                    eprintln!(
                        "Error: sealed successes {successes} does not match the Stage A recompute {}",
                        computed.successes
                    );
                    return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
                }
                if (computed.estimate - estimate).abs() > MC_RECOMPUTE_TOLERANCE
                    || (computed.interval_low - interval_low).abs() > MC_RECOMPUTE_TOLERANCE
                    || (computed.interval_high - interval_high).abs() > MC_RECOMPUTE_TOLERANCE
                {
                    eprintln!(
                        "Error: sealed EXECUTED interval fields do not match the Stage A recompute over the sealed series (estimate {estimate} vs {}, low {interval_low} vs {}, high {interval_high} vs {})",
                        computed.estimate, computed.interval_low, computed.interval_high
                    );
                    return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
                }
            }
            other => {
                eprintln!(
                    "Error: monte_carlo.status `{other}` is not expressible (only DECLARED or EXECUTED)"
                );
                return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
            }
        }
    }
    // The budgeted-search admission contracts. Deterministic: unlike
    // monte_carlo, a budget block does NOT ride on Random or a seed. A
    // heuristic result without its budget ceiling hides whether it stopped
    // at the limit, so the ceiling is non-zero, consumption never exceeds
    // it, exhausted is DERIVED (never hand-set), and status is the one
    // thing v0 can honestly say (DECLARED).
    if let Some(budget) = &receipt.budget {
        if budget.steps_limit == 0 {
            eprintln!("Error: budget.steps_limit is 0: a zero ceiling is not a budget");
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if budget.steps_consumed > budget.steps_limit {
            eprintln!(
                "Error: budget.steps_consumed {} exceeds budget.steps_limit {}: a consumption above its ceiling is incoherent",
                budget.steps_consumed, budget.steps_limit
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if budget.exhausted != (budget.steps_consumed == budget.steps_limit) {
            eprintln!(
                "Error: budget.exhausted `{}` disagrees with steps_consumed == steps_limit ({} == {}): exhausted is DERIVED, never hand-set",
                budget.exhausted, budget.steps_consumed, budget.steps_limit
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if budget.status != "DECLARED" {
            eprintln!(
                "Error: budget.status `{}` is not expressible: v0 declares the facts, it does not execute them (the only valid status is DECLARED)",
                budget.status
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        // The declared wall ceiling, when present: a positive finite value,
        // riding only on a receipt that sealed a measured wall_seconds
        // (a ceiling needs a measurement to derive `wall_exceeded` against),
        // with `wall_exceeded` re-derived from the two SEALED numbers only
        // (never from this verify run's own re-measured time: a slower
        // verify machine must not flip a receipt's coherence).
        if let Some(limit) = budget.wall_seconds_limit {
            if limit <= 0.0 || !limit.is_finite() {
                eprintln!(
                    "Error: budget.wall_seconds_limit {} is not a positive, finite value",
                    limit
                );
                return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
            }
            let Some(sealed_wall) = receipt.runtime_state.wall_seconds else {
                eprintln!(
                    "Error: budget.wall_seconds_limit is declared but runtime_state.wall_seconds is not sealed: a wall ceiling needs a measured wall time to derive wall_exceeded against"
                );
                return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
            };
            let expected_exceeded = sealed_wall > limit;
            if budget.wall_exceeded != Some(expected_exceeded) {
                eprintln!(
                    "Error: budget.wall_exceeded {:?} disagrees with sealed wall_seconds {} > sealed wall_seconds_limit {} ({}): wall_exceeded is DERIVED from the two SEALED numbers, never hand-set",
                    budget.wall_exceeded, sealed_wall, limit, expected_exceeded
                );
                return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
            }
        } else if budget.wall_exceeded.is_some() {
            eprintln!(
                "Error: budget.wall_exceeded is present without budget.wall_seconds_limit: the flag cannot exist without the ceiling it is derived from"
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
    }
    // The cross-backend admission contract. The block and the invariant are
    // a STRICT BICONDITIONAL: a receipt witnessing backend agreement must
    // name the cross-backend invariant, and that invariant must carry the
    // block (there is nothing else it could mean). Unlike monte_carlo and
    // budget this block is EXECUTED, not DECLARED: v0 supports the `rust`
    // validation lane only, and the three witnessed digests must be
    // well-formed sha256 (reused from the top-level digest gate).
    let cross_backend_paired =
        receipt.cross_backend.is_some() == (receipt.invariant.name == CROSS_BACKEND_INVARIANT);
    if !cross_backend_paired {
        eprintln!(
            "Error: cross_backend block present={} but invariant is `{}`: the block and the invariant are a strict biconditional",
            receipt.cross_backend.is_some(),
            receipt.invariant.name
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    if let Some(cb) = &receipt.cross_backend {
        // The mirror of emit's own Random exclusion (main.rs: `--cross-backend`
        // refuses a Random-observing kernel before compiling, because the Rust
        // lane has no seeded PRNG builtin). Checked on the RE-DERIVED
        // capability union, exactly like the seed pairing and Model gates
        // above, so a hand-built (or tampered-toolchain) receipt cannot ride a
        // seeded Random kernel through to the re-run and get misclassified as
        // RERUN_FAILED when rustc later chokes on the undefined symbol. This
        // transitively excludes a monte_carlo block riding alongside
        // cross_backend too, since an MC block requires Random by the pairing
        // gate a few lines up.
        if rederived_uses_random {
            eprintln!(
                "Error: cross_backend block present but the re-derived capabilities include Random: the Rust lane has no seeded PRNG, so the two streams could not agree; emit refuses this combination and verify must too"
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if cb.secondary_target != "rust" {
            eprintln!(
                "Error: cross_backend.secondary_target `{}` is not supported (v0: rust only)",
                cb.secondary_target
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        if cb.status != "EXECUTED" {
            eprintln!(
                "Error: cross_backend.status `{}` is not expressible: this block witnesses a run that actually happened (the only valid status is EXECUTED)",
                cb.status
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
        for (field, digest) in [
            (
                "cross_backend.secondary_toolchain_digest",
                &cb.secondary_toolchain_digest,
            ),
            (
                "cross_backend.secondary_executable_digest",
                &cb.secondary_executable_digest,
            ),
            (
                "cross_backend.secondary_raw_stdout_digest",
                &cb.secondary_raw_stdout_digest,
            ),
        ] {
            if !digest_is_well_formed(digest) {
                eprintln!(
                    "Error: malformed digest in `{}`: algorithm `{}`, hex `{}` (must be sha256 with 64 hex chars)",
                    field, digest.algorithm, digest.hex
                );
                return Err(verify_failure_class(json, "DIGEST_MALFORMED", 1));
            }
        }
    }
    // The budget pairing, checked for every receipt: the budget label and the
    // budget list entry are present exactly when the budget block is present.
    let has_budget_label = receipt.labels.iter().any(|l| l == vocab.budget_label);
    if has_budget_label != receipt.budget.is_some() {
        eprintln!(
            "Error: the {} label is present={} and the budget block is present={}; they must match",
            vocab.budget_label,
            has_budget_label,
            receipt.budget.is_some()
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    let has_budget_entry = entries.iter().any(|c| c == vocab.budget_entry);
    if has_budget_entry != receipt.budget.is_some() {
        eprintln!(
            "Error: the `{}` entry `{}` is present={} and the budget block is present={}; they must match",
            vocab.list_name,
            vocab.budget_entry,
            has_budget_entry,
            receipt.budget.is_some()
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    // The monte_carlo entries are present (all of them) exactly when the
    // monte_carlo block is EXECUTED.
    let mc_executed = receipt
        .monte_carlo
        .as_ref()
        .is_some_and(|mc| mc.status == "EXECUTED");
    let has_all_mc_entries = vocab
        .mc_entries
        .iter()
        .all(|c| entries.iter().any(|x| x == c));
    let has_any_mc_entry = vocab
        .mc_entries
        .iter()
        .any(|c| entries.iter().any(|x| x == c));
    if mc_executed != has_all_mc_entries || (has_any_mc_entry && !has_all_mc_entries) {
        eprintln!(
            "Error: the `{}` monte_carlo entries {:?} are present={} and the monte_carlo block is EXECUTED={}; they must match",
            vocab.list_name, vocab.mc_entries, has_any_mc_entry, mc_executed
        );
        return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
    }
    // The label rule: a budgeted search reports the best result it found, so
    // the free text may not use the word `optimal`.
    if receipt.budget.is_some() {
        let problem_claims_optimal = receipt
            .problem
            .label
            .as_deref()
            .is_some_and(|s| s.to_lowercase().contains("optimal"));
        let method_claims_optimal = receipt
            .numerical_method
            .description
            .as_deref()
            .is_some_and(|s| s.to_lowercase().contains("optimal"));
        if problem_claims_optimal || method_claims_optimal {
            eprintln!(
                "Error: a budgeted search reports the best result it found within its budget, so the problem and method text cannot contain the word `optimal` in any case, including inside a word such as `suboptimal`. Rename the label and run again."
            );
            return Err(verify_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
        }
    }
    let (expected_input_dataset, expected_seed, expected_determinism) =
        witnessed_fields_from_capabilities(
            &rederived.effect_policy.observed_capabilities,
            rederived.effect_policy.reads_stdin,
            receipt.seed_value,
        );
    if receipt.input_dataset != expected_input_dataset
        || receipt.seed != expected_seed
        || receipt.determinism != expected_determinism
    {
        eprintln!(
            "Error: effect policy drift: the sealed input_dataset/seed/determinism fields do not re-derive from the observed capabilities"
        );
        return Err(verify_failure_class(json, "EFFECT_POLICY_DRIFT", 1));
    }

    // Toolchain preflight: no C compiler at all is its own verdict (exit 4),
    // distinct from both drift (1) and faithful-fail (3); a DIFFERENT
    // toolchain warns, and the verdict re-check proceeds (cross-toolchain
    // re-verification is legitimate by design).
    let toolchain_matched = match probed_toolchain {
        None => {
            eprintln!(
                "Error: no C compiler available to re-run the program (receipt was sealed under `{}`)",
                receipt.build_state.toolchain.c_compiler
            );
            return Err(verify_failure_class(json, "TOOL_UNAVAILABLE", 4));
        }
        Some(probed) => {
            let matched = probed.c_compiler == receipt.build_state.toolchain.c_compiler
                && probed.version_output_digest
                    == receipt.build_state.toolchain.version_output_digest
                && probed.target == receipt.build_state.toolchain.target;
            if !matched {
                eprintln!(
                    "Warning: toolchain differs: receipt `{}` ({}) on {}, local `{}` ({}) on {} (re-checking the verdict anyway; any drift below may be environmental)",
                    receipt.build_state.toolchain.c_compiler,
                    receipt.build_state.toolchain.c_compiler_version,
                    receipt.build_state.toolchain.target,
                    probed.c_compiler,
                    probed.c_compiler_version,
                    probed.target
                );
            }
            matched
        }
    };

    // (3) Re-run the program WITH THE STORED ARGS and re-parse its stdout, so an
    // argv-parameterized kernel is reproduced under the same conditions it was
    // emitted under. The fourth argument is the secondary lane named by a
    // sealed `cross_backend` block (`None` for every other receipt).
    let secondary_target = receipt
        .cross_backend
        .as_ref()
        .map(|cb| cb.secondary_target.as_str());
    let observation = rerun_series(
        &source_path,
        &receipt.args,
        receipt.seed_value,
        secondary_target,
        sealed_stdio_mode,
    )
    .map_err(|code| verify_failure_class(json, "RERUN_FAILED", code))?;
    // Wall-clock: REPORTED, never compared for pass/fail (timing is
    // environmental, exactly like raw stdout bytes). `wall_seconds_sealed`
    // is `None` for a receipt sealed before this field existed.
    let wall_seconds_sealed = receipt.runtime_state.wall_seconds;
    let wall_seconds_remeasured = observation.wall_seconds;
    let parsed = observation.parsed;

    // (3a) The process exit code is sealed and deterministic; a re-run that
    // exits differently (including a crash) is its own failure class, checked
    // BEFORE the series comparisons so a crashed re-run is not misreported as
    // a tamper-flavored count drift.
    if observation.exit_code != receipt.runtime_state.exit_code {
        eprintln!(
            "Error: exit code drift: receipt {}, re-run {}",
            receipt.runtime_state.exit_code, observation.exit_code
        );
        return Err(verify_failure_class(json, "RERUN_EXIT_MISMATCH", 1));
    }

    // Raw-byte and executable reproduction are REPORTED, never required:
    // exact stdout bytes and C compiler output are platform-dependent by
    // design (the verdict is the re-checked quantity). A match is the
    // strongest reproduction signal; a mismatch with a matching verdict is
    // still faithful.
    let raw_stdout_reproduced = digests_match(
        &observation.raw_stdout_digest,
        &receipt.measurement.raw_stdout_digest,
    );
    let executable_reproduced = digests_match(
        &observation.executable_digest,
        &receipt.build_state.toolchain.program_executable_digest,
    );

    // Cross-backend: require the secondary observation, re-check its exit
    // code, and rebuild the interleaved 2-column series from the two
    // re-parsed series the EXACT same way emit does, so verify re-derives
    // (never trusts) the backend agreement. `verdict_series` feeds every
    // check below in place of the primary-only `parsed.series`; for every
    // other receipt it IS `parsed.series`, so the rest of this function is
    // unchanged.
    let (
        verdict_series,
        secondary_raw_stdout_reproduced,
        secondary_executable_reproduced,
        secondary_toolchain_matched,
    ) = if let Some(cb) = &receipt.cross_backend {
        let secondary = observation.secondary.ok_or_else(|| {
                eprintln!(
                    "Error: cross-backend receipt requires a secondary (rust) re-run observation, but none was produced"
                );
                verify_failure_class(json, "RERUN_FAILED", 1)
            })?;

        // Secondary toolchain visibility parity with the primary's
        // `toolchain_matched` (WARN, never fail: cross-toolchain
        // re-verification stays legitimate by design). Unlike the
        // primary there is no "missing toolchain" branch to handle
        // here: `rerun_series` already mapped rustc absence to `Err(4)`
        // before this closure could return an observation at all.
        let secondary_toolchain_matched = digests_match(
            &secondary.probed_toolchain_digest,
            &cb.secondary_toolchain_digest,
        );
        if !secondary_toolchain_matched {
            eprintln!(
                    "Warning: secondary (rust) toolchain differs: receipt `{}`, local `{}` (re-checking the verdict anyway; any drift below may be environmental)",
                    cb.secondary_toolchain_version,
                    secondary.probed_toolchain_version
                );
        }

        if secondary.exit_code != cb.secondary_exit_code {
            eprintln!(
                "Error: secondary (rust) exit code drift: receipt {}, re-run {}",
                cb.secondary_exit_code, secondary.exit_code
            );
            return Err(verify_failure_class(json, "RERUN_EXIT_MISMATCH", 1));
        }
        if parsed.diverged
            || secondary.parsed.diverged
            || parsed.series.is_empty()
            || secondary.parsed.series.is_empty()
            || parsed.series.len() != secondary.parsed.series.len()
        {
            eprintln!(
                    "Error: cross-backend re-run series mismatch: primary (C) produced {} values (diverged={}), secondary (rust) produced {} values (diverged={})",
                    parsed.series.len(),
                    parsed.diverged,
                    secondary.parsed.series.len(),
                    secondary.parsed.diverged
                );
            return Err(verify_failure_class(json, "MEASUREMENT_COUNT_DRIFT", 1));
        }
        let mut interleaved = Vec::with_capacity(parsed.series.len() * 2);
        for (c, r) in parsed.series.iter().zip(secondary.parsed.series.iter()) {
            interleaved.push(*c);
            interleaved.push(*r);
        }
        let secondary_raw_stdout_reproduced = digests_match(
            &secondary.raw_stdout_digest,
            &cb.secondary_raw_stdout_digest,
        );
        let secondary_executable_reproduced = digests_match(
            &secondary.executable_digest,
            &cb.secondary_executable_digest,
        );
        (
            interleaved,
            secondary_raw_stdout_reproduced,
            secondary_executable_reproduced,
            secondary_toolchain_matched,
        )
    } else {
        // True-absent semantics: with no secondary lane there is nothing
        // to (not) reproduce, so all three flags default to true rather
        // than reading as a failure signal on an ordinary receipt.
        (parsed.series.clone(), true, true, true)
    };

    // For a DIVERGED run the finite-prefix length (and hence violation_count
    // over that prefix) is the step index of the first non-finite value: a
    // function of the exact float trajectory, which the design declares
    // non-reproducible across toolchains (a 1-ULP libm difference can shift
    // the divergence step). So when the receipt records divergence AND the
    // re-run also diverges, the prefix-derived checks are skipped and the
    // reproduced divergence itself is the faithfulness signal. A re-run that
    // does NOT diverge when the receipt says it did (or vice versa) falls
    // through to the strict checks and fails as non-reproduction.
    let both_diverged = receipt.diverged && parsed.diverged;

    // (3b) For non-diverged runs the observed-value count IS deterministic
    // (it is the number of values the program prints, independent of float
    // jitter), so a re-run with a different count means the stored measurement
    // was tampered with (or the program is non-deterministic in a way that
    // breaks re-derivation). Element values are NOT re-compared: exact floats
    // need not reproduce across platforms (see the doc comment), so the
    // verdict is the re-checked quantity, with count guarding series length.
    // `verdict_series` is the rebuilt interleaved series for a cross-backend
    // receipt, so this also catches a tampered `measurement.count` there.
    if !both_diverged && verdict_series.len() != receipt.measurement.count {
        eprintln!(
            "Error: measurement count drift: receipt {}, re-run {}",
            receipt.measurement.count,
            verdict_series.len()
        );
        return Err(verify_failure_class(json, "MEASUREMENT_COUNT_DRIFT", 1));
    }

    // Stage B: an EXECUTED monte_carlo block's sealed fields must ALSO
    // re-derive over the RE-RUN series (not just the sealed one, Stage A
    // above). Stage A alone would let a receipt stay internally coherent
    // while no longer describing the run it names; Stage B catches that.
    if let Some(mc) = &receipt.monte_carlo {
        if mc.status == "EXECUTED" {
            // Stage A already required all five fields present; unwrap is safe.
            let estimate = mc.estimate.expect("Stage A validated presence");
            let interval_low = mc.interval_low.expect("Stage A validated presence");
            let interval_high = mc.interval_high.expect("Stage A validated presence");
            let computed = compute_mc_executed(
                &verdict_series,
                receipt.measurement.column_count,
                mc.samples,
                &mc.interval_method,
            )
            .map_err(|reason| {
                eprintln!(
                    "Error: EXECUTED monte_carlo Stage B (re-run series) recompute failed: {reason}"
                );
                verify_failure_class(json, "MC_INTERVAL_DRIFT", 1)
            })?;
            if computed.n_effective != mc.samples
                || computed.successes != mc.successes.expect("Stage A validated presence")
                || (computed.estimate - estimate).abs() > MC_RECOMPUTE_TOLERANCE
                || (computed.interval_low - interval_low).abs() > MC_RECOMPUTE_TOLERANCE
                || (computed.interval_high - interval_high).abs() > MC_RECOMPUTE_TOLERANCE
            {
                eprintln!(
                    "Error: EXECUTED monte_carlo interval drift: sealed fields do not match the Stage B recompute over the re-run series"
                );
                return Err(verify_failure_class(json, "MC_INTERVAL_DRIFT", 1));
            }
        }
    }

    // (4) Recompute the verdict and compare against the stored one.
    let recomputed = recompute_verdict(
        &receipt.invariant.name,
        &verdict_series,
        parsed.any_parsed,
        parsed.diverged,
        receipt.negative_fixture,
        receipt.measurement.column_count,
    );
    let stored_increase = receipt.invariant.observed.violation_count;

    if recomputed.invariant_status != receipt.invariant.status {
        eprintln!(
            "Error: invariant status drift: receipt {}, re-run {}",
            receipt.invariant.status, recomputed.invariant_status
        );
        return Err(verify_failure_class(json, "INVARIANT_STATUS_DRIFT", 1));
    }
    // Prefix-derived like the count: skipped when both runs diverged (the
    // increase count over a platform-dependent finite prefix is itself
    // platform-dependent).
    if !both_diverged && recomputed.violation_count != stored_increase {
        eprintln!(
            "Error: violation_count drift: receipt {}, re-run {}",
            stored_increase, recomputed.violation_count
        );
        return Err(verify_failure_class(json, "VIOLATION_COUNT_DRIFT", 1));
    }
    if recomputed.receipt_status != receipt.receipt_status {
        eprintln!(
            "Error: receipt_status drift: receipt {}, re-run {}",
            receipt.receipt_status, recomputed.receipt_status
        );
        return Err(verify_failure_class(json, "RECEIPT_STATUS_DRIFT", 1));
    }

    // The receipt is FAITHFUL (seal, digests, count, and verdict all
    // re-check). Whether the recorded verdict is a PASS is a separate
    // question the report carries; the printing wrapper (and the export
    // bridge) decide what to do with it.
    Ok(ScientificVerifyReport {
        invariant_status: recomputed.invariant_status,
        invariant_name: receipt.invariant.name.clone(),
        violation_count: recomputed.violation_count,
        receipt_status: recomputed.receipt_status,
        invariant_held: matches!(recomputed.receipt_status, "PASS" | "FAIL_EXPECTED"),
        toolchain_matched,
        raw_stdout_reproduced,
        executable_reproduced,
        secondary_raw_stdout_reproduced,
        secondary_executable_reproduced,
        secondary_toolchain_matched,
        tolerance: receipt.invariant.tolerance,
        negative_fixture: receipt.negative_fixture,
        diverged: receipt.diverged,
        source: source_path.to_string_lossy().to_string(),
        source_digest_hex: receipt.source_digest.hex.clone(),
        raw_stdout_digest_hex: receipt.measurement.raw_stdout_digest.hex.clone(),
        stdio_mode: sealed_stdio_mode.to_string(),
        args: receipt.args.clone(),
        seal_hex: receipt.seal.hex.clone(),
        wall_seconds_sealed,
        wall_seconds_remeasured,
    })
}

/// Everything a FAITHFUL re-verification established, for consumers beyond
/// the human/`--json` printer: the export bridge derives Crucible
/// measurements from this report (never from stored receipt values alone).
/// Faithful does NOT mean the invariant held: `invariant_held` carries that.
pub struct ScientificVerifyReport {
    pub invariant_status: &'static str,
    /// The sealed invariant name (e.g. `conserved_quantity_constant`). Carried
    /// so the export bridge labels the witnessed Crucible measurement with the
    /// invariant the receipt ACTUALLY checked, never a hardcoded default.
    pub invariant_name: String,
    pub violation_count: usize,
    pub receipt_status: &'static str,
    pub invariant_held: bool,
    pub toolchain_matched: bool,
    pub raw_stdout_reproduced: bool,
    pub executable_reproduced: bool,
    /// REPORTED (never required) reproduction of the cross-backend secondary
    /// lane's raw stdout / executable digests. True-absent semantics: for a
    /// receipt with no `cross_backend` block both default to `true` (nothing
    /// to reproduce), so they never read as a failure signal on an ordinary
    /// receipt.
    pub secondary_raw_stdout_reproduced: bool,
    pub secondary_executable_reproduced: bool,
    /// Secondary-lane toolchain visibility parity with the primary's
    /// `toolchain_matched`: whether the FRESHLY PROBED rustc (the one that
    /// actually re-executed the secondary lane, honoring a `RUSTC` env
    /// override) matches the sealed `cross_backend.secondary_toolchain_digest`.
    /// A mismatch WARNS (never fails: cross-toolchain re-verification is
    /// legitimate by design) and this flag carries the result so a
    /// substituted rustc is at least visible rather than silently discarded.
    /// True-absent semantics like the two flags above: `true` when the
    /// receipt has no `cross_backend` block.
    pub secondary_toolchain_matched: bool,
    /// Canonical invariant tolerance carried for downstream callers. The current
    /// printers and Crucible export bridge use their own claim-scale tolerance, so
    /// this field is intentionally not read inside the crate today.
    #[allow(dead_code)]
    pub tolerance: f64,
    pub negative_fixture: bool,
    pub diverged: bool,
    pub source: String,
    pub source_digest_hex: String,
    pub raw_stdout_digest_hex: String,
    /// The sealed generated-program stdio mode. Missing old receipts report
    /// `native`.
    pub stdio_mode: String,
    pub args: Vec<String>,
    pub seal_hex: String,
    /// The sealed `runtime_state.wall_seconds`, `None` for a receipt sealed
    /// before this field existed. REPORTED beside the fresh remeasurement,
    /// never required to match (timing is environmental).
    pub wall_seconds_sealed: Option<f64>,
    /// This verification's own fresh wall-clock remeasurement, always
    /// present (verify always re-measures its re-run).
    pub wall_seconds_remeasured: f64,
}

/// Schema id for the Crucible-measurement export envelope (the Telos bridge).
pub const CRUCIBLE_MEASUREMENT_EXPORT_SCHEMA: &str = "buildlang-crucible-measurement-export/v0";

/// The versioned `method` string carried by exported measurements: names the
/// discipline (re-executed verification, never stored-value copying) so a
/// consumer can distinguish these rows from author-typed ones.
pub const CRUCIBLE_EXPORT_METHOD: &str = "buildc-receipt-verify/reexecuted-v1";

/// Map a FAITHFUL re-verification report into one Crucible measurement row
/// (the shape `crucible assess --measurements` ingests: claim_id,
/// claim_sha256, deviation, tolerance, method, measured_at, evidence,
/// recheck). PURE and total over reports, so the mapping rules are unit
/// tested without IO.
///
/// The honesty rules of the mapping:
/// - `deviation` is DERIVED from the fresh re-run (the report), never copied
///   from stored receipt values. UNVERIFIABLE receipts export deviation null
///   (Crucible reads unmeasurable as UNVERIFIABLE, fail-closed); everything
///   else exports the recomputed violation_count.
/// - `tolerance` is 0.5: violation_count is integral, so 0.5 cleanly separates
///   "no increases" (MATCH) from "any increase" (DRIFT). A FAIL_EXPECTED
///   receipt therefore exports a row that reads DRIFT against a
///   holds-everywhere claim; binding it to a claim whose falsification
///   expects the failure is the thesis side's job, and the receipt_status is
///   carried in evidence so that side can frame it.
/// - `recheck` seals everything an independent replayer needs to re-run
///   buildc and rebuild this row: the measurement is WITNESSED, not asserted
///   (a measurement without a recheck descriptor is exactly the
///   author-supplied pattern the provenance gate exists to catch).
pub fn crucible_measurement_from_report(
    report: &ScientificVerifyReport,
    claim_id: &str,
    claim_sha256: &str,
    claim_expects_failure: bool,
    receipt_path: &str,
    receipt_file_sha256: &str,
    measured_at: f64,
) -> serde_json::Value {
    // Deviation semantics, claim-relative when the binding declares an
    // expected failure (Crucible's verdict math is pure margin arithmetic;
    // there is no thesis-side escape hatch, so the expectation must be bound
    // HERE): a negative-fixture receipt that failed as predicted deviates 0
    // from its claim; one that unexpectedly PASSed deviates 1. Without the
    // expectation the deviation is the recomputed increase count, and an
    // UNVERIFIABLE receipt is unmeasurable (null; Crucible fails closed).
    let deviation = if report.receipt_status == "UNVERIFIABLE" {
        serde_json::Value::Null
    } else if claim_expects_failure {
        if report.receipt_status == "FAIL_EXPECTED" {
            serde_json::json!(0.0)
        } else {
            // The claim predicted failure; the run did not fail.
            serde_json::json!(1.0)
        }
    } else {
        serde_json::json!(report.violation_count as f64)
    };

    // For a DIVERGED receipt the increase count is prefix-derived and
    // platform-dependent (the verifier's own both_diverged rule skips it);
    // sealing a concrete expectation would make an independent replayer
    // wrongly conclude non-reproduction of a faithful receipt.
    let expected_violation_count = if report.diverged {
        serde_json::Value::Null
    } else {
        serde_json::json!(report.violation_count)
    };

    let mut evidence = vec![
        format!("receipt_seal:sha256:{}", report.seal_hex),
        format!("source:sha256:{}", report.source_digest_hex),
        // The digest sealed AT EMISSION, not the re-run's bytes (which are
        // platform-dependent); the reproduction object below says whether
        // the witnessing re-run reproduced it.
        format!("sealed_raw_stdout:sha256:{}", report.raw_stdout_digest_hex),
        format!("receipt_status:{}", report.receipt_status),
        format!("invariant:{}", report.invariant_name),
        format!("negative_fixture:{}", report.negative_fixture),
    ];
    if claim_expects_failure {
        evidence.push("claim_expectation:expects_failure".to_string());
    }
    if report.stdio_mode != SCIENTIFIC_STDIO_MODE_NATIVE {
        evidence.push(format!("stdio_mode:{}", report.stdio_mode));
    }

    serde_json::json!({
        "claim_id": claim_id,
        "claim_sha256": claim_sha256,
        "deviation": deviation,
        "tolerance": 0.5,
        "method": CRUCIBLE_EXPORT_METHOD,
        "measured_at": measured_at,
        "evidence": evidence,
        // What the witnessing re-run observed about reproduction. Kept OUT of
        // `evidence` deliberately: Crucible's recheck compares the evidence
        // list for stability, and these flags legitimately differ per replay
        // environment. A top-level key is outside the fixed measurement-seal
        // field list, so it stays visible to auditors without destabilizing
        // recheck.
        "reproduction": {
            "toolchain_matched": report.toolchain_matched,
            "raw_stdout_reproduced": report.raw_stdout_reproduced,
            "executable_reproduced": report.executable_reproduced,
        },
        "recheck": {
            "oracle": "buildc.receipt.verify",
            "receipt_path": receipt_path,
            "receipt_sha256": receipt_file_sha256,
            "source": report.source,
            "source_sha256": report.source_digest_hex,
            "args": report.args,
            "command": ["buildc", "receipt", "verify", receipt_path, "--json"],
            "diverged": report.diverged,
            "expected": {
                "receipt_status": report.receipt_status,
                "invariant_status": report.invariant_status,
                // Null for diverged receipts: reproduced divergence (same
                // receipt_status) is the faithfulness signal, mirroring the
                // verifier's both_diverged rule.
                "violation_count": expected_violation_count,
                // The exit code the sealed replay command must yield: 0 for
                // faithful PASS/FAIL_EXPECTED, 3 for faithful
                // FAIL_UNEXPECTED/UNVERIFIABLE.
                "exit_code": if report.invariant_held { 0 } else { 3 },
            },
        },
    })
}

/// The `receipt verify` entry point: evaluate, print (human or `--json`),
/// and map the report to the exit-code contract (Ok for faithful
/// PASS/FAIL_EXPECTED; Err(3) for faithful FAIL_UNEXPECTED/UNVERIFIABLE;
/// Err(1)/Err(4) propagate from evaluation).
#[allow(clippy::too_many_arguments)]
pub fn verify_scientific_runtime_receipt(
    receipt_json: &serde_json::Value,
    source_override: Option<&Path>,
    json: bool,
    current_compiler_version: &str,
    current_language_version: &str,
    probed_toolchain: Option<&ScientificToolchain>,
    rederive_digests: impl FnOnce(&Path) -> Result<RederivedFacts, i32>,
    rerun_series: impl FnOnce(
        &Path,
        &[String],
        Option<u64>,
        Option<&str>,
        &str,
    ) -> Result<RerunObservation, i32>,
) -> Result<(), i32> {
    let report = evaluate_scientific_runtime_receipt(
        receipt_json,
        source_override,
        json,
        current_compiler_version,
        current_language_version,
        probed_toolchain,
        rederive_digests,
        rerun_series,
    )?;

    if json {
        let mut out = serde_json::json!({
            "schema": SCIENTIFIC_RUNTIME_SCHEMA,
            "status": if report.invariant_held { "match" } else { "invariant_not_held" },
            "faithful": true,
            "invariant_held": report.invariant_held,
            "source": report.source,
            "invariant_status": report.invariant_status,
            "violation_count": report.violation_count,
            "receipt_status": report.receipt_status,
            "toolchain_matched": report.toolchain_matched,
            "raw_stdout_reproduced": report.raw_stdout_reproduced,
            "executable_reproduced": report.executable_reproduced,
            "secondary_raw_stdout_reproduced": report.secondary_raw_stdout_reproduced,
            "secondary_executable_reproduced": report.secondary_executable_reproduced,
            "seal": { "algorithm": "sha256", "hex": report.seal_hex },
        });
        // Secondary toolchain visibility parity (finding 1): unlike the two
        // reproduction flags above (always present, true-absent default),
        // this key is included only when the receipt actually carries a
        // `cross_backend` block, so a plain receipt's JSON report gains no
        // new key from this fix.
        if report.invariant_name == CROSS_BACKEND_INVARIANT {
            out["secondary_toolchain_matched"] =
                serde_json::Value::Bool(report.secondary_toolchain_matched);
        }
        // The wall-clock time fact: included only when the receipt sealed a
        // measurement, so a plain (pre-wall-metering) receipt's JSON report
        // gains no new key. Never a pass/fail signal, so there is no
        // "matched" boolean here, only the two numbers side by side.
        if let Some(sealed) = report.wall_seconds_sealed {
            out["wall_seconds"] = serde_json::json!({
                "sealed": sealed,
                "remeasured": report.wall_seconds_remeasured,
            });
        }
        if report.stdio_mode != SCIENTIFIC_STDIO_MODE_NATIVE {
            out["stdio_mode"] = serde_json::Value::String(report.stdio_mode.clone());
        }
        if !report.invariant_held {
            out["failure_class"] = serde_json::Value::String("INVARIANT_NOT_HELD".to_string());
        }
        let text = serde_json::to_string_pretty(&out).map_err(|err| {
            eprintln!(
                "Error serializing scientific-runtime verification report: {}",
                err
            );
            1
        })?;
        println!("{}", text);
    } else if report.invariant_held {
        // Appended only when the receipt sealed a wall_seconds measurement
        // (a plain pre-wall-metering receipt's MATCH line is unchanged).
        // Never a pass/fail signal: the two numbers are reported side by
        // side, with no "matched" verdict between them (timing is
        // environmental, exactly like raw stdout bytes).
        let wall_seconds_suffix = match report.wall_seconds_sealed {
            Some(sealed) => format!(
                ", wall_seconds={}~{}",
                sealed, report.wall_seconds_remeasured
            ),
            None => String::new(),
        };
        let stdio_mode_suffix = if report.stdio_mode == SCIENTIFIC_STDIO_MODE_NATIVE {
            String::new()
        } else {
            format!(", stdio_mode={}", report.stdio_mode)
        };
        if report.invariant_name == CROSS_BACKEND_INVARIANT {
            println!(
                "MATCH: scientific-runtime receipt re-runs and re-checks clean ({}, violation_count={}; toolchain_matched={}, raw_stdout_reproduced={}, executable_reproduced={}, secondary_toolchain_matched={}, secondary_raw_stdout_reproduced={}, secondary_executable_reproduced={}{}{})",
                report.receipt_status,
                report.violation_count,
                report.toolchain_matched,
                report.raw_stdout_reproduced,
                report.executable_reproduced,
                report.secondary_toolchain_matched,
                report.secondary_raw_stdout_reproduced,
                report.secondary_executable_reproduced,
                wall_seconds_suffix,
                stdio_mode_suffix
            );
        } else {
            println!(
                "MATCH: scientific-runtime receipt re-runs and re-checks clean ({}, violation_count={}; toolchain_matched={}, raw_stdout_reproduced={}, executable_reproduced={}{}{})",
                report.receipt_status,
                report.violation_count,
                report.toolchain_matched,
                report.raw_stdout_reproduced,
                report.executable_reproduced,
                wall_seconds_suffix,
                stdio_mode_suffix
            );
        }
    } else {
        eprintln!(
            "FAIL: scientific-runtime receipt faithfully reproduces, but the invariant did not hold ({}, violation_count={}). `receipt verify` exits nonzero so it is safe as a pass/fail gate.",
            report.receipt_status, report.violation_count
        );
    }

    if report.invariant_held {
        Ok(())
    } else {
        // The class line goes to stderr in both modes (the json report above
        // already carries the field; the human FAIL line is prose).
        eprintln!("failure_class: INVARIANT_NOT_HELD");
        Err(3)
    }
}

/// Two digests match iff their algorithm and (case-insensitive) hex agree AND
/// both carry a real hex value. Two EMPTY digests never match: an absent hash
/// must not report as the strongest reproduction signal (a vacuous
/// `reproduced=true` from two failed reads would fabricate provenance).
fn digests_match(actual: &ScientificDigest, expected: &ScientificDigest) -> bool {
    !actual.hex.is_empty()
        && actual.algorithm.eq_ignore_ascii_case(&expected.algorithm)
        && actual.hex.eq_ignore_ascii_case(&expected.hex)
}

/// A sealed digest field must be a real sha256: exactly 64 hex chars. A
/// receipt carrying an empty or malformed digest is rejected outright
/// (`DIGEST_MALFORMED`), so "digest unavailable" can never masquerade as a
/// witnessed hash inside a sealed receipt.
fn digest_is_well_formed(digest: &ScientificDigest) -> bool {
    digest.algorithm.eq_ignore_ascii_case("sha256")
        && digest.hex.len() == 64
        && digest.hex.chars().all(|ch| ch.is_ascii_hexdigit())
}

/// Report a stable machine-readable `failure_class` for a verify failure and
/// return the exit code to propagate. Emitted on stderr always (a line of the
/// form `failure_class: <CODE>`) and, in `--json` mode, as a JSON failure
/// report on stdout, so negative fixtures and CI consumers can pin
/// (failure_class, exit_code) pairs instead of accepting "anything failed".
///
/// The class vocabulary (stable within schema v1; v0 receipts use the same
/// classes plus `OVERCLAIM_BOUNDARY_MISSING`):
/// - `MALFORMED`, `SCHEMA_UNSUPPORTED`, `COMPILER_MISMATCH`: the receipt could
///   not be interpreted.
/// - `SCOPE_MISSING`: a v1 receipt's `scope` omits "observed_series_invariant".
/// - `OVERCLAIM_BOUNDARY_MISSING`: a v0 receipt's `not_claimed` omits
///   "physical_law".
/// - `EXTRACTION_POLICY_MISMATCH`: the sealed series-extraction policy's
///   version tag is not the one this verifier implements.
/// - `DIGEST_MALFORMED`: a sealed digest field is not a real sha256 (64 hex
///   chars), so "hash unavailable" cannot masquerade as witnessed provenance.
/// - `ORACLE_KIND_UNSUPPORTED`, `ORACLE_STATUS_UNSUPPORTED`,
///   `ORACLE_BINDING_MISMATCH`, `INVARIANT_UNSUPPORTED`: the oracle/invariant
///   block names a kind, status, or criterion this verifier does not
///   implement, or the oracle does not bind to the implemented invariant
///   (binding is pinned to the implementation, never to another sealed field).
/// - `FENCE_STATUS_UNEXPECTED`: a telemetry/lineage fence was edited to claim
///   availability v0 does not produce.
/// - `FIELD_CONTRACT_VIOLATION`: a sealed field claims something the program
///   cannot express (a seed_value when nothing draws from the Random
///   capability, or a Random-using program with no sealed seed) or is
///   internally inconsistent (a DECLARED method with no description).
/// - `EFFECT_POLICY_DRIFT`: the sealed effect/capability facts, or the
///   witnessed fields derived from them, do not re-derive from the source.
/// - `CAPABILITY_INADMISSIBLE`: a capability the receipt layer refuses
///   outright; today only `Model`. A model proposes; an oracled kernel checks.
/// - `TOOL_UNAVAILABLE` (exit 4): no C compiler is available for the re-run.
/// - `REDERIVATION_FAILED`, `RERUN_FAILED`: the source could not be re-checked
///   or re-run (missing file, toolchain failure), distinct from drift. Exit 4
///   is shared: `TOOL_UNAVAILABLE` for a missing primary (C) toolchain and
///   `RERUN_FAILED` for a missing secondary (rustc) toolchain both propagate
///   exit code 4. `failure_class`, not the exit code, is the machine key that
///   distinguishes which toolchain was unavailable.
/// - `SOURCE_DIGEST_MISMATCH`, `INPUT_GRAPH_DIGEST_MISMATCH`: the source
///   changed since sealing.
/// - `RERUN_EXIT_MISMATCH`: the re-run's process exit code differs from the
///   sealed `runtime_state.exit_code` (covers a crashing re-run).
/// - `MEASUREMENT_COUNT_DRIFT`, `INVARIANT_STATUS_DRIFT`,
///   `VIOLATION_COUNT_DRIFT`, `RECEIPT_STATUS_DRIFT`: the re-run disagrees with
///   the stored verdict facts.
/// - `MC_INTERVAL_DRIFT`: an EXECUTED monte_carlo receipt's sealed interval
///   fields do not match the Stage B recompute over the re-run series
///   (Stage A already passed over the sealed series; this catches a
///   receipt that stopped describing the run it names).
/// - `SEAL_MISMATCH`: the stored receipt body does not re-seal.
/// - `INVARIANT_NOT_HELD` (exit 3): the receipt is FAITHFUL but records
///   FAIL_UNEXPECTED / UNVERIFIABLE (emitted at the verdict tail, not here).
fn verify_failure_class(json: bool, failure_class: &str, exit_code: i32) -> i32 {
    eprintln!("failure_class: {failure_class}");
    if json {
        let report = serde_json::json!({
            "schema": SCIENTIFIC_RUNTIME_SCHEMA,
            "status": "failed",
            "failure_class": failure_class,
        });
        if let Ok(text) = serde_json::to_string_pretty(&report) {
            println!("{text}");
        }
    }
    exit_code
}

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

    fn hex_digest(fill: char) -> ScientificDigest {
        ScientificDigest {
            algorithm: "sha256".to_string(),
            hex: fill.to_string().repeat(64),
        }
    }

    /// The toolchain fixture sealed into test receipts; also what tests pass
    /// as the verify-time probe (matching by default).
    fn test_toolchain() -> ScientificToolchain {
        ScientificToolchain {
            c_compiler: "test-cc".to_string(),
            c_compiler_version: "test-cc 1.0".to_string(),
            version_output_digest: hex_digest('d'),
            target: "test-os/test-arch".to_string(),
            buildc_binary_digest: hex_digest('e'),
            program_executable_digest: hex_digest('f'),
        }
    }

    /// The effect-policy fixture sealed into test receipts; the rederive
    /// helper returns the same facts so faithful tests re-derive cleanly.
    fn test_effect_policy() -> ScientificEffectPolicy {
        ScientificEffectPolicy {
            facts_digest: hex_digest('7'),
            observed_capabilities: vec!["Console".to_string()],
            reads_stdin: false,
        }
    }

    fn rederive_facts(
        source_digest: ScientificDigest,
        input_graph_digest: ScientificDigest,
    ) -> RederivedFacts {
        RederivedFacts {
            source_digest,
            input_graph_digest,
            effect_policy: test_effect_policy(),
        }
    }

    fn base_inputs<'a>(
        path: &'a Path,
        series: Vec<f64>,
        parsed: bool,
        negative_fixture: bool,
    ) -> ScientificReceiptInputs<'a> {
        ScientificReceiptInputs {
            source_path: path,
            compiler_version: "0.0.0",
            language_version: "1.0.0".to_string(),
            source_digest: hex_digest('a'),
            input_graph_digest: hex_digest('b'),
            target: "c",
            stdio_mode: None,
            os: "test-os",
            exit_code: 0,
            wall_seconds: None,
            toolchain: test_toolchain(),
            effect_policy: test_effect_policy(),
            method_description: None,
            raw_stdout_digest: hex_digest('c'),
            series,
            series_parsed: parsed,
            diverged: false,
            args: Vec::new(),
            seed_value: None,
            monte_carlo: None,
            budget: None,
            cross_backend: None,
            invariant_name: ENERGY_MONOTONE_INVARIANT.to_string(),
            metric: "series".to_string(),
            units: None,
            column_count: 1,
            problem_label: None,
            negative_fixture,
            flags: Vec::new(),
        }
    }

    /// A `base_inputs` variant that seals a DIFFERENT invariant, for the
    /// conservation-family tests.
    fn base_inputs_for<'a>(
        invariant_name: &str,
        path: &'a Path,
        series: Vec<f64>,
        parsed: bool,
        negative_fixture: bool,
    ) -> ScientificReceiptInputs<'a> {
        ScientificReceiptInputs {
            invariant_name: invariant_name.to_string(),
            ..base_inputs(path, series, parsed, negative_fixture)
        }
    }

    #[test]
    fn monotone_series_has_zero_increases() {
        let series = [4.0, 3.0, 3.0, 2.5, 1.0];
        let observed = energy_monotone_nonincreasing(&series, ENERGY_MONOTONE_TOLERANCE);
        assert_eq!(observed.violation_count, 0);
        assert_eq!(observed.first_violation_step, None);
        assert_eq!(observed.initial_value, Some(4.0));
        assert_eq!(observed.final_value, Some(1.0));
        assert!(invariant_passes(series.len(), &observed));
    }

    #[test]
    fn one_bump_is_counted_with_first_violation_step() {
        // Increase happens at k = 2 (index 2 -> index 3: 2.0 -> 5.0).
        let series = [4.0, 3.0, 2.0, 5.0, 1.0];
        let observed = energy_monotone_nonincreasing(&series, ENERGY_MONOTONE_TOLERANCE);
        assert_eq!(observed.violation_count, 1);
        assert_eq!(observed.first_violation_step, Some(2));
        assert!(!invariant_passes(series.len(), &observed));
    }

    #[test]
    fn tolerance_absorbs_tiny_jitter_but_not_real_growth() {
        // A sub-tolerance wiggle up is NOT an increase.
        let jitter = [1.0, 1.0 + 5e-13, 1.0];
        let observed = energy_monotone_nonincreasing(&jitter, ENERGY_MONOTONE_TOLERANCE);
        assert_eq!(observed.violation_count, 0);

        // A supra-tolerance step up IS an increase.
        let growth = [1.0, 1.0 + 1e-9, 1.0 + 2e-9];
        let observed = energy_monotone_nonincreasing(&growth, ENERGY_MONOTONE_TOLERANCE);
        assert_eq!(observed.violation_count, 2);
        assert_eq!(observed.first_violation_step, Some(0));
    }

    #[test]
    fn single_point_series_does_not_pass() {
        let series = [1.0];
        let observed = energy_monotone_nonincreasing(&series, ENERGY_MONOTONE_TOLERANCE);
        assert_eq!(observed.violation_count, 0);
        // Zero increases but only one point: cannot witness monotonicity.
        assert!(!invariant_passes(series.len(), &observed));
    }

    #[test]
    fn empty_series_does_not_pass() {
        let observed = energy_monotone_nonincreasing(&[], ENERGY_MONOTONE_TOLERANCE);
        assert_eq!(observed.violation_count, 0);
        assert_eq!(observed.initial_value, None);
        assert_eq!(observed.final_value, None);
        assert!(!invariant_passes(0, &observed));
    }

    #[test]
    fn status_rule_pass_for_monotone_series() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        assert_eq!(receipt.receipt_status, "PASS");
        assert_eq!(receipt.invariant.status, "PASS");
        assert_eq!(receipt.invariant.observed.violation_count, 0);
        assert!(receipt.labels.contains(&LABEL_NUMERICAL_RESULT.to_string()));
        assert!(!receipt.labels.contains(&"NEGATIVE_FIXTURE".to_string()));
    }

    #[test]
    fn status_rule_fail_expected_when_negative_fixture() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![1.0, 2.0, 3.0], true, true));
        assert_eq!(receipt.receipt_status, "FAIL_EXPECTED");
        assert_eq!(receipt.invariant.status, "FAIL");
        assert_eq!(receipt.invariant.observed.violation_count, 2);
        assert_eq!(receipt.invariant.observed.first_violation_step, Some(0));
        assert!(receipt.labels.contains(&"NEGATIVE_FIXTURE".to_string()));
    }

    #[test]
    fn status_rule_fail_unexpected_without_negative_fixture() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![1.0, 2.0, 3.0], true, false));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        assert_eq!(receipt.invariant.status, "FAIL");
        assert!(!receipt.labels.contains(&"NEGATIVE_FIXTURE".to_string()));
    }

    #[test]
    fn status_rule_unverifiable_when_series_unparseable() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs(path, vec![], false, false));
        assert_eq!(receipt.receipt_status, "UNVERIFIABLE");
        assert_eq!(receipt.measurement.count, 0);
    }

    #[test]
    fn always_labels_numerical_result() {
        let path = Path::new("k.bld");
        for (series, parsed, neg) in [
            (vec![4.0, 3.0], true, false),
            (vec![1.0, 2.0], true, true),
            (vec![], false, false),
        ] {
            let receipt = build_scientific_runtime_receipt(base_inputs(path, series, parsed, neg));
            assert!(
                receipt.labels.contains(&LABEL_NUMERICAL_RESULT.to_string()),
                "every receipt must carry NUMERICAL_RESULT"
            );
        }
    }

    #[test]
    fn seal_is_64_hex_and_stable_and_reproducible() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        assert_eq!(receipt.seal.algorithm, "sha256");
        assert_eq!(receipt.seal.hex.len(), 64);
        assert!(receipt
            .seal
            .hex
            .chars()
            .all(|ch| ch.is_ascii_hexdigit() && !ch.is_ascii_uppercase()));

        // Re-deriving the seal from the sealed receipt reproduces the stored hex.
        assert_eq!(recompute_seal_hex(&receipt), receipt.seal.hex);
    }

    #[test]
    fn seal_detects_tampering() {
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let original = receipt.seal.hex.clone();
        // Tamper with a witnessed field; the recomputed seal must diverge.
        receipt.invariant.observed.violation_count = 99;
        assert_ne!(recompute_seal_hex(&receipt), original);
    }

    #[test]
    fn self_test_cases_cover_distinct_failure_classes_and_seal_states() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let json = serde_json::to_value(&receipt).expect("serialize receipt");
        let cases = build_self_test_cases(&json).expect("build self-test cases");

        // The table exercises five separate arms of the failure taxonomy (the
        // seed-pairing, MC-denominator, budget-consumption, and cross-backend
        // biconditional cases share FIELD_CONTRACT_VIOLATION with the
        // tolerance case but tamper different sealed fields through different
        // gates).
        let classes: Vec<&str> = cases.iter().map(|c| c.expected_class.as_str()).collect();
        assert_eq!(
            classes,
            vec![
                "COMPILER_MISMATCH",
                "SEAL_MISMATCH",
                "MALFORMED",
                "FIELD_CONTRACT_VIOLATION",
                "INVARIANT_UNSUPPORTED",
                "FIELD_CONTRACT_VIOLATION",
                "FIELD_CONTRACT_VIOLATION",
                "FIELD_CONTRACT_VIOLATION",
                "FIELD_CONTRACT_VIOLATION",
                "FIELD_CONTRACT_VIOLATION",
            ]
        );

        // A re-sealed case must carry a valid seal, so its tamper reaches the
        // intended post-seal contract check instead of tripping SEAL_MISMATCH.
        for case in cases.iter().filter(|c| c.resealed) {
            let r: ScientificRuntimeReceipt =
                serde_json::from_value(case.tampered.clone()).expect("resealed case parses");
            assert_eq!(
                recompute_seal_hex(&r),
                r.seal.hex,
                "re-sealed case `{}` must carry a valid seal",
                case.label
            );
        }

        // The seal-mismatch case must carry a STALE seal (that is its whole point).
        let seal_case = cases
            .iter()
            .find(|c| c.expected_class == "SEAL_MISMATCH")
            .expect("seal-mismatch case present");
        let r: ScientificRuntimeReceipt =
            serde_json::from_value(seal_case.tampered.clone()).expect("seal case parses");
        assert_ne!(
            recompute_seal_hex(&r),
            r.seal.hex,
            "the seal-mismatch case must carry a stale seal"
        );
    }

    #[test]
    fn receipt_chain_seal_binds_order_and_membership() {
        let mk = |i: usize, seal: &str| ReceiptChainLink {
            index: i,
            receipt: format!("r{i}.json"),
            source: format!("s{i}.bld"),
            receipt_seal: seal.to_string(),
        };
        let links = vec![mk(0, "aaa"), mk(1, "bbb"), mk(2, "ccc")];
        let seal = receipt_chain_seal_hex(&links);
        assert_eq!(seal.len(), 64);

        // Reordering the members changes the chain seal.
        let reordered = vec![mk(0, "bbb"), mk(1, "aaa"), mk(2, "ccc")];
        assert_ne!(receipt_chain_seal_hex(&reordered), seal);

        // Dropping a member changes the chain seal.
        let dropped = vec![mk(0, "aaa"), mk(1, "bbb")];
        assert_ne!(receipt_chain_seal_hex(&dropped), seal);

        // Tampering an index (same seals, wrong position) changes the chain seal:
        // index is bound, not decorative.
        let index_tampered = vec![mk(5, "aaa"), mk(1, "bbb"), mk(2, "ccc")];
        assert_ne!(receipt_chain_seal_hex(&index_tampered), seal);

        // The identical ordered membership reproduces the chain seal.
        let same = vec![mk(0, "aaa"), mk(1, "bbb"), mk(2, "ccc")];
        assert_eq!(receipt_chain_seal_hex(&same), seal);

        // build_receipt_chain stores a manifest whose seal matches the input order.
        let manifest = build_receipt_chain(&[
            ("r0.json".into(), "s0.bld".into(), "aaa".into()),
            ("r1.json".into(), "s1.bld".into(), "bbb".into()),
            ("r2.json".into(), "s2.bld".into(), "ccc".into()),
        ]);
        assert_eq!(manifest.schema, RECEIPT_CHAIN_SCHEMA);
        assert_eq!(manifest.chain_seal.hex, seal);
        assert_eq!(manifest.links[1].index, 1);
    }

    #[test]
    fn corpus_manifest_parses_with_column_and_fixture_defaults() {
        let json = r#"{
            "schema": "buildlang-scientific-receipt-corpus/v0",
            "members": [
                {"source": "examples/a.bld", "invariant": "conservation", "expected_status": "PASS"},
                {"source": "examples/b.bld", "invariant": "relation", "columns": 2,
                 "negative_fixture": true, "expected_status": "FAIL_EXPECTED"}
            ]
        }"#;
        let manifest: ScientificCorpusManifest = serde_json::from_str(json).expect("parse corpus");
        assert_eq!(manifest.schema, RECEIPT_CORPUS_SCHEMA);
        assert_eq!(manifest.members.len(), 2);
        // Defaults: the first member omits columns/negative_fixture.
        assert_eq!(manifest.members[0].columns, 1);
        assert!(!manifest.members[0].negative_fixture);
        assert_eq!(manifest.members[0].expected_status, "PASS");
        // The second member sets them explicitly.
        assert_eq!(manifest.members[1].columns, 2);
        assert!(manifest.members[1].negative_fixture);
        assert_eq!(manifest.members[1].expected_status, "FAIL_EXPECTED");
    }

    #[test]
    fn receipt_round_trips_as_json() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let json = serde_json::to_string(&receipt).expect("serialize");
        let back: ScientificRuntimeReceipt = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.schema, SCIENTIFIC_RUNTIME_SCHEMA);
        assert_eq!(back.receipt_status, "PASS");
        assert_eq!(back.seal.hex, receipt.seal.hex);
        // The seal read back re-verifies against its own body.
        assert_eq!(recompute_seal_hex(&back), back.seal.hex);
    }

    #[test]
    fn parse_series_accepts_plain_and_scientific() {
        let stdout = "0.530827\n0.530404\n1.59908e+28\n6.10352e-05\n";
        let parsed = parse_numeric_series(stdout);
        assert!(parsed.any_parsed);
        assert!(!parsed.diverged);
        assert_eq!(parsed.series.len(), 4);
        assert!((parsed.series[0] - 0.530827).abs() < 1e-9);
        assert!(parsed.series[2] > 1e28);
        assert!(parsed.series[3] > 0.0 && parsed.series[3] < 1e-3);
    }

    #[test]
    fn parse_series_reports_no_parse_for_non_numeric() {
        let parsed = parse_numeric_series("no numbers here\n");
        assert!(!parsed.any_parsed);
        assert!(!parsed.diverged);
        assert!(parsed.series.is_empty());
    }

    #[test]
    fn parse_series_flags_divergence_and_keeps_finite_prefix() {
        // Rust-parseable non-finite forms (glibc/macOS `%g`).
        for tail in ["inf", "-inf", "nan", "-nan", "infinity"] {
            let parsed = parse_numeric_series(&format!("4.0\n3.0\n{tail}\n{tail}\n"));
            assert!(parsed.diverged, "`{tail}` must signal divergence");
            assert!(parsed.any_parsed);
            // Only the finite prefix is kept, so it always serializes cleanly.
            assert_eq!(parsed.series, vec![4.0, 3.0], "tail={tail}");
            assert!(parsed.series.iter().all(|v| v.is_finite()));
        }
    }

    #[test]
    fn parse_series_flags_platform_nonfinite_spellings() {
        // Windows UCRT / legacy MSVCRT spellings Rust's f64 parser rejects.
        for tail in ["-nan(ind)", "nan(ind)", "1.#INF", "-1.#IND", "1.#QNAN"] {
            let parsed = parse_numeric_series(&format!("4.0\n3.0\n{tail}\n"));
            assert!(parsed.diverged, "`{tail}` must signal divergence");
            assert_eq!(parsed.series, vec![4.0, 3.0], "tail={tail}");
        }
    }

    #[test]
    fn parse_series_does_not_flag_ordinary_words() {
        // A label starting with `inf`/`nan` must not be mistaken for a blow-up.
        let parsed = parse_numeric_series("information: 4.0 nanometers 3.0\n");
        assert!(!parsed.diverged);
        assert_eq!(parsed.series, vec![4.0, 3.0]);
    }

    #[test]
    fn parse_series_does_not_flag_hash_labels() {
        // Ordinary labels containing `#inf`/`#ind` substrings must NOT flag
        // divergence: the MSVCRT match is anchored to the full token shapes
        // (`1.#INF` etc.), not substring containment. Regression for the
        // substring version, where `step#info:` diverged a healthy run.
        for label in ["step#info:", "cell#index=3", "grid#index", "x#snapshot"] {
            let parsed = parse_numeric_series(&format!("{label} 4.0\n3.0\n2.0\n"));
            assert!(!parsed.diverged, "`{label}` must not flag divergence");
            assert_eq!(parsed.series, vec![4.0, 3.0, 2.0], "label={label}");
        }
    }

    #[test]
    fn diverged_run_is_unverifiable_not_a_false_pass() {
        // A monotone-looking finite prefix followed by a blow-up is UNVERIFIABLE,
        // never PASS: the invariant could not be honestly evaluated.
        let path = Path::new("k.bld");
        let mut inputs = base_inputs(path, vec![4.0, 3.0], true, false);
        inputs.diverged = true;
        let receipt = build_scientific_runtime_receipt(inputs);
        assert_eq!(receipt.receipt_status, "UNVERIFIABLE");
        assert_eq!(receipt.invariant.status, "FAIL");
        assert!(receipt.diverged, "the diverged flag must be sealed in-band");
        assert!(receipt.labels.contains(&"NONFINITE_OBSERVED".to_string()));
        // The finite prefix is preserved and round-trips (no JSON `null`).
        let json = serde_json::to_string(&receipt).expect("serialize");
        assert!(
            !json.contains("null"),
            "observed_values must be finite: {json}"
        );
        let back: ScientificRuntimeReceipt = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.measurement.observed_values, vec![4.0, 3.0]);
        assert!(back.diverged);
    }

    // --- receipt verify (T3) verdict recomputation ---------------------------

    #[test]
    fn recompute_verdict_matches_builder_for_monotone_series() {
        // A monotone series recomputes PASS/PASS with zero increases, exactly
        // as `build_scientific_runtime_receipt` would have recorded it.
        let verdict = recompute_verdict(
            ENERGY_MONOTONE_INVARIANT,
            &[4.0, 3.0, 2.0],
            true,
            false,
            false,
            1,
        );
        assert_eq!(verdict.invariant_status, "PASS");
        assert_eq!(verdict.receipt_status, "PASS");
        assert_eq!(verdict.violation_count, 0);
    }

    #[test]
    fn recompute_verdict_distinguishes_expected_from_unexpected_failure() {
        // The negative-fixture flag (read back from the stored receipt) is what
        // separates FAIL_EXPECTED from FAIL_UNEXPECTED on a re-run.
        let expected = recompute_verdict(
            ENERGY_MONOTONE_INVARIANT,
            &[1.0, 2.0, 3.0],
            true,
            false,
            true,
            1,
        );
        assert_eq!(expected.invariant_status, "FAIL");
        assert_eq!(expected.receipt_status, "FAIL_EXPECTED");
        assert_eq!(expected.violation_count, 2);

        let unexpected = recompute_verdict(
            ENERGY_MONOTONE_INVARIANT,
            &[1.0, 2.0, 3.0],
            true,
            false,
            false,
            1,
        );
        assert_eq!(unexpected.receipt_status, "FAIL_UNEXPECTED");
    }

    #[test]
    fn recompute_verdict_is_unverifiable_when_nothing_parsed() {
        let verdict = recompute_verdict(ENERGY_MONOTONE_INVARIANT, &[], false, false, false, 1);
        assert_eq!(verdict.receipt_status, "UNVERIFIABLE");
        assert_eq!(verdict.invariant_status, "FAIL");
    }

    #[test]
    fn recompute_verdict_is_unverifiable_when_diverged() {
        // A monotone finite prefix that diverged is UNVERIFIABLE, not PASS, so a
        // re-run of a diverged program re-derives the same UNVERIFIABLE verdict.
        let verdict =
            recompute_verdict(ENERGY_MONOTONE_INVARIANT, &[4.0, 3.0], true, true, false, 1);
        assert_eq!(verdict.receipt_status, "UNVERIFIABLE");
        assert_eq!(verdict.invariant_status, "FAIL");
    }

    #[test]
    fn conservation_holds_for_a_constant_series() {
        let obs = conserved_quantity_constant(&[2.0, 2.0, 2.0, 2.0], CONSERVATION_TOLERANCE);
        assert_eq!(obs.violation_count, 0);
        assert!(invariant_passes(4, &obs));
        // Roundoff-scale jitter within tolerance is still conserved.
        let obs =
            conserved_quantity_constant(&[2.0, 2.0 + 1e-12, 2.0 - 1e-12], CONSERVATION_TOLERANCE);
        assert_eq!(obs.violation_count, 0);
    }

    #[test]
    fn conservation_flags_a_leak() {
        // A quantity that drifts from its initial value beyond tolerance: steps
        // 2 and 3 deviate from the reference 2.0.
        let obs = conserved_quantity_constant(&[2.0, 2.0, 1.5, 1.0], CONSERVATION_TOLERANCE);
        assert_eq!(obs.violation_count, 2);
        assert_eq!(obs.first_violation_step, Some(2));
        assert!(!invariant_passes(4, &obs));
        assert_eq!(obs.initial_value, Some(2.0));
        assert_eq!(obs.final_value, Some(1.0));
    }

    #[test]
    fn invariant_registry_dispatches_by_name() {
        assert!(is_known_invariant(ENERGY_MONOTONE_INVARIANT));
        assert!(is_known_invariant(CONSERVATION_INVARIANT));
        assert!(is_known_invariant(BOUNDED_INVARIANT));
        assert!(!is_known_invariant("no_such_invariant"));
        // Every name the family advertises must have a real tolerance and a
        // real evaluator arm (the KNOWN_INVARIANTS list is the single source of
        // truth; this guards against a name being advertised but unimplemented).
        for name in KNOWN_INVARIANTS {
            assert!(is_known_invariant(name));
            let _ = invariant_expectation(name);
            // Route through evaluate_measurement (the real dispatch) with a
            // 2-column series so the relation invariant exercises its own arm,
            // not evaluate_invariant's single-series fallback.
            let _ = evaluate_measurement(name, &[1.0, 1.0], invariant_tolerance(name), 2);
        }
        assert_eq!(
            invariant_tolerance(CONSERVATION_INVARIANT),
            CONSERVATION_TOLERANCE
        );
        assert_eq!(
            invariant_tolerance(ENERGY_MONOTONE_INVARIANT),
            ENERGY_MONOTONE_TOLERANCE
        );
        assert_eq!(invariant_tolerance(BOUNDED_INVARIANT), BOUNDED_TOLERANCE);

        // A monotone-DECREASING series distinguishes the two evaluators: it has
        // zero monotone violations (non-increasing) but DOES deviate from its
        // initial value, so conservation flags it. This proves the dispatcher
        // routes to genuinely different checks, not one aliased to the other.
        let decreasing = [3.0, 2.0, 1.0];
        let mono = evaluate_invariant(
            ENERGY_MONOTONE_INVARIANT,
            &decreasing,
            ENERGY_MONOTONE_TOLERANCE,
        );
        assert_eq!(mono.violation_count, 0);
        let cons = evaluate_invariant(CONSERVATION_INVARIANT, &decreasing, CONSERVATION_TOLERANCE);
        assert_eq!(cons.violation_count, 2);
    }

    #[test]
    fn verify_round_trips_a_conservation_receipt() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVATION_INVARIANT,
            path,
            vec![2.0, 2.0, 2.0],
            true,
            false,
        ));
        assert_eq!(receipt.invariant.name, CONSERVATION_INVARIANT);
        assert_eq!(receipt.oracle.name, CONSERVATION_INVARIANT);
        assert_eq!(receipt.invariant.tolerance, CONSERVATION_TOLERANCE);
        assert_eq!(receipt.receipt_status, "PASS");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![2.0, 2.0, 2.0])),
        );
        assert!(
            result.is_ok(),
            "a faithful conservation receipt must verify: {result:?}"
        );
    }

    #[test]
    fn verify_fails_a_faithful_conservation_leak() {
        // A conserved quantity that leaks (drifts past tolerance) faithfully
        // reproduces a FAIL_UNEXPECTED, so `receipt verify` exits 3 (not 0).
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVATION_INVARIANT,
            path,
            vec![2.0, 2.0, 1.0],
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![2.0, 2.0, 1.0])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful conservation leak must exit 3 (FAIL_UNEXPECTED)"
        );
    }

    #[test]
    fn verify_rejects_a_non_canonical_invariant_tolerance() {
        // Tolerance is fixed per invariant; a receipt that resealed a loosened
        // tolerance is rejected (FIELD_CONTRACT_VIOLATION), never re-checked
        // under the weaker bound.
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVATION_INVARIANT,
            path,
            vec![2.0, 2.0, 2.0],
            true,
            false,
        ));
        receipt.invariant.tolerance = 1e6;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![2.0, 2.0, 2.0])),
        );
        assert_eq!(result, Err(1), "a non-canonical tolerance must be rejected");
    }

    #[test]
    fn bounded_holds_for_a_capped_series() {
        // Every value sits at or below the initial 1.0, so the maximum
        // principle holds even though the series rises and falls (index 3
        // returns to exactly the reference, which is not an overshoot).
        let obs = bounded_by_initial_maximum(&[1.0, 0.5, 0.8, 1.0, 0.3], BOUNDED_TOLERANCE);
        assert_eq!(obs.violation_count, 0);
        assert!(invariant_passes(5, &obs));
        // Roundoff-scale rise above the reference is still within bound.
        let obs = bounded_by_initial_maximum(&[1.0, 1.0 + 1e-12], BOUNDED_TOLERANCE);
        assert_eq!(obs.violation_count, 0);
    }

    #[test]
    fn bounded_flags_an_overshoot() {
        // Values that exceed the initial 1.0 beyond tolerance: indices 1 and 3
        // overshoot; the quantity dipping in between does not matter.
        let obs = bounded_by_initial_maximum(&[1.0, 1.5, 0.5, 2.0], BOUNDED_TOLERANCE);
        assert_eq!(obs.violation_count, 2);
        assert_eq!(obs.first_violation_step, Some(1));
        assert!(!invariant_passes(4, &obs));
        assert_eq!(obs.initial_value, Some(1.0));
        assert_eq!(obs.final_value, Some(2.0));
    }

    #[test]
    fn bounded_is_distinct_from_the_other_invariants() {
        // A series that dips and returns to its initial value is the witness
        // that `bounded` is a genuinely separate check: it exceeds nothing
        // (bounded PASSes) yet it deviates (conservation flags it) and it rises
        // (monotone flags it). One series, three different verdicts.
        let dip_return = [1.0, 0.0, 1.0];
        let bounded = evaluate_invariant(BOUNDED_INVARIANT, &dip_return, BOUNDED_TOLERANCE);
        assert_eq!(bounded.violation_count, 0, "bounded accepts the capped dip");
        let cons = evaluate_invariant(CONSERVATION_INVARIANT, &dip_return, CONSERVATION_TOLERANCE);
        assert_eq!(cons.violation_count, 1, "conservation flags the deviation");
        let mono = evaluate_invariant(
            ENERGY_MONOTONE_INVARIANT,
            &dip_return,
            ENERGY_MONOTONE_TOLERANCE,
        );
        assert_eq!(
            mono.violation_count, 1,
            "monotone flags the rise back to 1.0"
        );
    }

    #[test]
    fn verify_round_trips_a_bounded_receipt() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            BOUNDED_INVARIANT,
            path,
            vec![1.0, 0.5, 1.0],
            true,
            false,
        ));
        assert_eq!(receipt.invariant.name, BOUNDED_INVARIANT);
        assert_eq!(receipt.oracle.name, BOUNDED_INVARIANT);
        assert_eq!(receipt.invariant.tolerance, BOUNDED_TOLERANCE);
        assert_eq!(receipt.receipt_status, "PASS");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 0.5, 1.0])),
        );
        assert!(
            result.is_ok(),
            "a faithful bounded receipt must verify: {result:?}"
        );
    }

    #[test]
    fn verify_fails_a_faithful_bounded_overshoot() {
        // A quantity that overshoots its initial value faithfully reproduces a
        // FAIL_UNEXPECTED, so `receipt verify` exits 3 (not 0).
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            BOUNDED_INVARIANT,
            path,
            vec![1.0, 2.0, 1.0],
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 2.0, 1.0])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful bounded overshoot must exit 3 (FAIL_UNEXPECTED)"
        );
    }

    #[test]
    fn verify_rejects_a_non_canonical_bounded_tolerance() {
        // Bounded's tolerance is pinned like every family member's: a resealed
        // loosened tolerance is rejected (FIELD_CONTRACT_VIOLATION).
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(base_inputs_for(
            BOUNDED_INVARIANT,
            path,
            vec![1.0, 0.5, 1.0],
            true,
            false,
        ));
        receipt.invariant.tolerance = 1e6;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 0.5, 1.0])),
        );
        assert_eq!(result, Err(1), "a non-canonical tolerance must be rejected");
    }

    #[test]
    fn energy_identity_holds_for_near_zero_residuals() {
        // Residuals at the roundoff scale are all within tolerance of zero.
        let obs = energy_identity_residual(&[1e-12, -5e-13, 2e-14, 0.0], ENERGY_IDENTITY_TOLERANCE);
        assert_eq!(obs.violation_count, 0);
        assert!(invariant_passes(4, &obs));
    }

    #[test]
    fn energy_identity_flags_a_large_residual() {
        // Residuals above tolerance (a broken balance) are violations, and the
        // reference is ZERO so step 0 is checked like any other.
        let obs = energy_identity_residual(&[1e-3, -1e-3, 0.0], ENERGY_IDENTITY_TOLERANCE);
        assert_eq!(obs.violation_count, 2);
        assert_eq!(obs.first_violation_step, Some(0));
        assert!(!invariant_passes(3, &obs));
    }

    #[test]
    fn energy_identity_references_zero_not_the_initial_value() {
        // The witness that energy-identity's reference is 0, not series[0]:
        // the SAME series [0.1, 0.0, 0.0] yields three different verdicts.
        // energy-identity flags step 0 (0.1 is far from 0); conservation
        // references 0.1 and flags the LATER steps (they deviate from 0.1);
        // bounded references 0.1 and PASSes (nothing exceeds it).
        let s = [0.1, 0.0, 0.0];
        let ei = evaluate_invariant(ENERGY_IDENTITY_INVARIANT, &s, ENERGY_IDENTITY_TOLERANCE);
        assert_eq!(ei.violation_count, 1);
        assert_eq!(ei.first_violation_step, Some(0));
        let cons = evaluate_invariant(CONSERVATION_INVARIANT, &s, CONSERVATION_TOLERANCE);
        assert_eq!(cons.violation_count, 2);
        assert_eq!(cons.first_violation_step, Some(1));
        let bounded = evaluate_invariant(BOUNDED_INVARIANT, &s, BOUNDED_TOLERANCE);
        assert_eq!(bounded.violation_count, 0);
    }

    #[test]
    fn verify_round_trips_an_energy_identity_receipt() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            ENERGY_IDENTITY_INVARIANT,
            path,
            vec![1e-12, -1e-13, 2e-14],
            true,
            false,
        ));
        assert_eq!(receipt.invariant.name, ENERGY_IDENTITY_INVARIANT);
        assert_eq!(receipt.oracle.name, ENERGY_IDENTITY_INVARIANT);
        assert_eq!(receipt.invariant.tolerance, ENERGY_IDENTITY_TOLERANCE);
        assert_eq!(receipt.receipt_status, "PASS");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1e-12, -1e-13, 2e-14])),
        );
        assert!(
            result.is_ok(),
            "a faithful energy-identity receipt must verify: {result:?}"
        );
    }

    #[test]
    fn verify_fails_a_faithful_energy_identity_breakage() {
        // A residual series that stays large (a dropped-term balance) faithfully
        // reproduces a FAIL_UNEXPECTED, so `receipt verify` exits 3.
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            ENERGY_IDENTITY_INVARIANT,
            path,
            vec![1e-3, 1e-3, 1e-3],
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1e-3, 1e-3, 1e-3])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful energy-identity breakage must exit 3 (FAIL_UNEXPECTED)"
        );
    }

    #[test]
    fn verify_rejects_a_non_canonical_energy_identity_tolerance() {
        // Energy-identity's tolerance is pinned like every family member's.
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(base_inputs_for(
            ENERGY_IDENTITY_INVARIANT,
            path,
            vec![1e-12, -1e-13, 2e-14],
            true,
            false,
        ));
        receipt.invariant.tolerance = 1e6;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1e-12, -1e-13, 2e-14])),
        );
        assert_eq!(result, Err(1), "a non-canonical tolerance must be rejected");
    }

    /// Inputs for a 2-column relation receipt.
    fn relation_inputs<'a>(
        path: &'a Path,
        series: Vec<f64>,
        parsed: bool,
        negative_fixture: bool,
    ) -> ScientificReceiptInputs<'a> {
        ScientificReceiptInputs {
            invariant_name: RELATION_INVARIANT.to_string(),
            column_count: 2,
            ..base_inputs(path, series, parsed, negative_fixture)
        }
    }

    #[test]
    fn relation_holds_when_every_row_agrees() {
        // 3 rows of (a, a): the columns agree, so no violations, and the
        // EFFECTIVE length is the ROW count (3), not the 6 raw tokens.
        let (obs, rows) =
            relation_columns_agree(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0], RELATION_TOLERANCE, 2);
        assert_eq!(obs.violation_count, 0);
        assert_eq!(rows, 3);
        assert!(invariant_passes(rows, &obs));
    }

    #[test]
    fn relation_flags_a_disagreeing_row() {
        // Row 1 is (2.0, 9.0): the columns disagree beyond tolerance.
        let (obs, rows) =
            relation_columns_agree(&[1.0, 1.0, 2.0, 9.0, 3.0, 3.0], RELATION_TOLERANCE, 2);
        assert_eq!(obs.violation_count, 1);
        assert_eq!(obs.first_violation_step, Some(1));
        assert_eq!(rows, 3);
        assert!(!invariant_passes(rows, &obs));
    }

    #[test]
    fn relation_reports_zero_rows_for_ragged_or_underwide_data() {
        // A flat length not divisible by column_count cannot form complete rows.
        let (_, rows) = relation_columns_agree(&[1.0, 1.0, 2.0], RELATION_TOLERANCE, 2);
        assert_eq!(rows, 0);
        // A column_count below 2 has nothing to compare across.
        let (_, rows) = relation_columns_agree(&[1.0, 2.0], RELATION_TOLERANCE, 1);
        assert_eq!(rows, 0);
    }

    #[test]
    fn evaluate_measurement_uses_row_count_for_relations_and_len_otherwise() {
        // The relation's effective length is rows (2), so a 4-token / 2-column
        // series is enough to witness (>= 2 rows). A single-scalar invariant on
        // the same 4 tokens uses the token count (4).
        let rel = evaluate_measurement(
            RELATION_INVARIANT,
            &[1.0, 1.0, 2.0, 2.0],
            RELATION_TOLERANCE,
            2,
        );
        assert_eq!(rel.effective_len, 2);
        assert_eq!(rel.observed.violation_count, 0);
        let mono = evaluate_measurement(
            ENERGY_MONOTONE_INVARIANT,
            &[4.0, 3.0, 2.0, 1.0],
            ENERGY_MONOTONE_TOLERANCE,
            1,
        );
        assert_eq!(mono.effective_len, 4);
    }

    #[test]
    fn evaluate_measurement_deinterleaves_column_zero_for_three_columns() {
        // Columns 1-2 would fail non_negative (negative values), but column 0
        // (the invariant scalar) is all non-negative, so the verdict must
        // read column 0 only, ignoring the witnessed counters beside it.
        let series = [
            1.0, -5.0, -5.0, // row 0: invariant 1.0, successes -5, trials -5
            2.0, -6.0, -6.0, // row 1
        ];
        let verdict =
            evaluate_measurement(NON_NEGATIVE_INVARIANT, &series, NON_NEGATIVE_TOLERANCE, 3);
        assert_eq!(verdict.effective_len, 2, "row count, not token count");
        assert_eq!(
            verdict.observed.violation_count, 0,
            "column 0 alone is non-negative; columns 1-2 must be ignored by the invariant check"
        );
    }

    #[test]
    fn evaluate_measurement_three_column_ragged_series_cannot_witness() {
        // A series length not a multiple of 3 cannot form complete rows,
        // mirroring the existing ragged-relation test.
        let verdict = evaluate_measurement(
            NON_NEGATIVE_INVARIANT,
            &[1.0, 2.0, 3.0, 4.0],
            NON_NEGATIVE_TOLERANCE,
            3,
        );
        assert_eq!(verdict.effective_len, 0);
    }

    #[test]
    fn column_count_matches_invariant_refuses_mc_executed_with_relation() {
        // An EXECUTED mc block can never pair with relation/cross-backend:
        // their columns already mean something else.
        assert!(!column_count_matches_invariant(RELATION_INVARIANT, 3, true));
        assert!(!column_count_matches_invariant(
            CROSS_BACKEND_INVARIANT,
            3,
            true
        ));
        assert!(column_count_matches_invariant(RELATION_INVARIANT, 3, false));
        assert!(column_count_matches_invariant(
            NON_NEGATIVE_INVARIANT,
            3,
            true
        ));
        assert!(!column_count_matches_invariant(
            NON_NEGATIVE_INVARIANT,
            3,
            false
        ));
    }

    #[test]
    fn compute_mc_executed_recovers_a_coherent_wilson_series() {
        // successes 1,1,2,2; trials 10,11,12,13 (each an increment of exactly
        // 1); the invariant scalar column is arbitrary (0.0 throughout).
        let series = [
            0.0, 1.0, 10.0, //
            0.0, 1.0, 11.0, //
            0.0, 2.0, 12.0, //
            0.0, 2.0, 13.0, //
        ];
        let result = compute_mc_executed(&series, 3, 13, MC_INTERVAL_WILSON_95);
        let computed = result.expect("a coherent series must compute");
        assert_eq!(computed.n_effective, 13);
        assert_eq!(computed.successes, 2);
        assert!((computed.estimate - 2.0 / 13.0).abs() < 1e-12);
        assert!(computed.interval_low < computed.estimate);
        assert!(computed.estimate < computed.interval_high);
    }

    #[test]
    fn compute_mc_executed_rejects_before_any_rerun_on_bad_trials_step() {
        // trials jumps by 2 between row 0 and row 1 (10 -> 12): a pure data
        // contradiction the function catches with no re-run machinery at all
        // (the function takes no compile/run inputs).
        let series = [0.0, 1.0, 10.0, 0.0, 1.0, 12.0];
        let err = compute_mc_executed(&series, 3, 12, MC_INTERVAL_WILSON_95)
            .expect_err("a trials step of 2 must be rejected");
        assert!(err.contains("row 1"), "error must name the row: {err}");
        assert!(err.contains("trials"), "error must name the field: {err}");
    }

    #[test]
    fn compute_mc_executed_rejects_successes_decrease() {
        let series = [0.0, 2.0, 10.0, 0.0, 1.0, 11.0];
        let err = compute_mc_executed(&series, 3, 11, MC_INTERVAL_WILSON_95)
            .expect_err("a successes decrease must be rejected");
        assert!(err.contains("row 1"), "error must name the row: {err}");
        assert!(
            err.contains("successes"),
            "error must name the field: {err}"
        );
    }

    #[test]
    fn compute_mc_executed_rejects_successes_exceeding_trials() {
        let series = [0.0, 5.0, 4.0];
        let err = compute_mc_executed(&series, 3, 4, MC_INTERVAL_WILSON_95)
            .expect_err("successes exceeding trials must be rejected");
        assert!(err.contains("exceeds"), "error must name the reason: {err}");
    }

    #[test]
    fn compute_mc_executed_rejects_non_integer_column() {
        let series = [0.0, 1.5, 10.0];
        let err = compute_mc_executed(&series, 3, 10, MC_INTERVAL_WILSON_95)
            .expect_err("a non-integer successes value must be rejected");
        assert!(
            err.contains("integer"),
            "error must name the integrality reason: {err}"
        );
    }

    #[test]
    fn compute_mc_executed_witnessed_denominator_must_equal_samples() {
        // A coherent series whose final trials is 2000, but samples declares
        // 1999: the denominator is not witnessed.
        let series = [0.0, 1000.0, 2000.0];
        let err = compute_mc_executed(&series, 3, 1999, MC_INTERVAL_WILSON_95)
            .expect_err("a witnessed/declared denominator mismatch must be rejected");
        assert!(
            err.contains("2000"),
            "error must name the witnessed trials: {err}"
        );
        assert!(
            err.contains("1999"),
            "error must name the declared samples: {err}"
        );
    }

    #[test]
    fn compute_mc_executed_rejects_ragged_series() {
        let series = [0.0, 1.0, 10.0, 0.0];
        let err = compute_mc_executed(&series, 3, 10, MC_INTERVAL_WILSON_95)
            .expect_err("a series length not a multiple of 3 must be rejected");
        assert!(err.contains("ragged"), "error must name the reason: {err}");
    }

    #[test]
    fn compute_mc_executed_normal_approx_degenerate_at_zero_successes() {
        let series = [0.0, 0.0, 10.0];
        let err = compute_mc_executed(&series, 3, 10, MC_INTERVAL_NORMAL_APPROX_95)
            .expect_err("zero successes must be rejected for normal-approx-95");
        assert!(
            err.contains("wilson-95"),
            "error must point at the alternative: {err}"
        );
    }

    #[test]
    fn compute_mc_executed_normal_approx_degenerate_at_all_successes() {
        let series = [0.0, 10.0, 10.0];
        let err = compute_mc_executed(&series, 3, 10, MC_INTERVAL_NORMAL_APPROX_95)
            .expect_err("all-successes must be rejected for normal-approx-95");
        assert!(
            err.contains("wilson-95"),
            "error must point at the alternative: {err}"
        );
    }

    #[test]
    fn compute_mc_executed_rejects_clopper_pearson() {
        let series = [0.0, 5.0, 10.0];
        let err = compute_mc_executed(&series, 3, 10, MC_INTERVAL_CLOPPER_PEARSON_95)
            .expect_err("clopper-pearson-95 is not executable in v1");
        assert!(
            err.contains("inverse incomplete beta"),
            "error must name the reason: {err}"
        );
    }

    #[test]
    fn compute_mc_executed_wilson_matches_hand_computed_value() {
        // successes = 3, trials = 10: p_hat = 0.3, z = 1.959963984540054.
        // Hand-computed (independent transcription of the Wilson formula):
        // z2 = 3.84145...; denom = 1 + z2/n; center = (p + z2/(2n)) / denom;
        // margin = (z/denom) * sqrt(p*(1-p)/n + z2/(4n^2)).
        let series = [0.0, 3.0, 10.0];
        let computed = compute_mc_executed(&series, 3, 10, MC_INTERVAL_WILSON_95)
            .expect("a coherent series must compute");
        let z = MC_INTERVAL_Z_95;
        let z2 = z * z;
        let n = 10.0f64;
        let p = 0.3f64;
        let denom = 1.0 + z2 / n;
        let center = (p + z2 / (2.0 * n)) / denom;
        let margin = (z / denom) * (p * (1.0 - p) / n + z2 / (4.0 * n * n)).sqrt();
        assert!((computed.interval_low - (center - margin)).abs() < 1e-9);
        assert!((computed.interval_high - (center + margin)).abs() < 1e-9);
        assert!((computed.estimate - 0.3).abs() < 1e-12);
    }

    #[test]
    fn verify_round_trips_a_relation_receipt() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(relation_inputs(
            path,
            vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0],
            true,
            false,
        ));
        assert_eq!(receipt.invariant.name, RELATION_INVARIANT);
        assert_eq!(receipt.oracle.name, RELATION_INVARIANT);
        assert_eq!(receipt.measurement.column_count, 2);
        assert_eq!(receipt.receipt_status, "PASS");
        assert_eq!(receipt.invariant.observed.violation_count, 0);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0])),
        );
        assert!(
            result.is_ok(),
            "a faithful relation receipt must verify: {result:?}"
        );
    }

    #[test]
    fn verify_fails_a_faithful_relation_disagreement() {
        // Row 1's columns disagree; the receipt faithfully reproduces a
        // FAIL_UNEXPECTED, so verify exits 3.
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(relation_inputs(
            path,
            vec![1.0, 1.0, 2.0, 9.0],
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.0, 2.0, 9.0])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful relation disagreement must exit 3 (FAIL_UNEXPECTED)"
        );
    }

    #[test]
    fn verify_rejects_a_non_canonical_relation_tolerance() {
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(relation_inputs(
            path,
            vec![1.0, 1.0, 2.0, 2.0],
            true,
            false,
        ));
        receipt.invariant.tolerance = 1e6;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.0, 2.0, 2.0])),
        );
        assert_eq!(result, Err(1), "a non-canonical tolerance must be rejected");
    }

    #[test]
    fn verify_rejects_a_receipt_missing_column_count() {
        // column_count is a REQUIRED sealed field (no serde default): a receipt
        // lacking it is MALFORMED at load, caught BEFORE any re-derivation or
        // re-run, rather than deserializing to a default and then misreporting
        // as SEAL_MISMATCH. (Regression for the C4 review finding.)
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let mut value = serde_json::to_value(&receipt).expect("to_value");
        value["measurement"]
            .as_object_mut()
            .expect("measurement object")
            .remove("column_count")
            .expect("column_count was present");
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| panic!("a malformed receipt must be rejected before re-derivation"),
            |_, _, _, _, _| panic!("a malformed receipt must be rejected before the re-run"),
        );
        assert_eq!(
            result,
            Err(1),
            "a receipt missing the required column_count must be rejected as malformed"
        );
    }

    #[test]
    fn conserved_band_holds_within_the_budget_and_flags_drift() {
        // Within the 5e-3 budget: no violations.
        let obs = evaluate_invariant(
            CONSERVED_BAND_INVARIANT,
            &[1.0, 1.002, 0.998, 1.001],
            CONSERVED_BAND_TOLERANCE,
        );
        assert_eq!(obs.violation_count, 0);
        // A drift past the budget is flagged (step 2 leaves the band).
        let obs = evaluate_invariant(
            CONSERVED_BAND_INVARIANT,
            &[1.0, 1.0, 1.1, 1.2],
            CONSERVED_BAND_TOLERANCE,
        );
        assert_eq!(obs.violation_count, 2);
        assert_eq!(obs.first_violation_step, Some(2));
    }

    #[test]
    fn conserved_band_is_distinct_from_conservation_and_bounded() {
        // A quantity oscillating in a small band around its initial value, both
        // above and below: conserved-band ACCEPTS it, while conservation
        // (roundoff-tight) and bounded (one-sided, no rise allowed) both reject
        // it. This is the symplectic-energy case in miniature.
        let band = [1.0, 1.002, 0.998];
        let cb = evaluate_invariant(CONSERVED_BAND_INVARIANT, &band, CONSERVED_BAND_TOLERANCE);
        assert_eq!(cb.violation_count, 0, "conserved-band accepts the band");
        let cons = evaluate_invariant(CONSERVATION_INVARIANT, &band, CONSERVATION_TOLERANCE);
        assert!(
            cons.violation_count > 0,
            "conservation rejects the deviation"
        );
        let bounded = evaluate_invariant(BOUNDED_INVARIANT, &band, BOUNDED_TOLERANCE);
        assert!(
            bounded.violation_count > 0,
            "bounded rejects the rise above s[0]"
        );
    }

    #[test]
    fn verify_round_trips_a_conserved_band_receipt() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVED_BAND_INVARIANT,
            path,
            vec![1.0, 1.002, 0.998],
            true,
            false,
        ));
        assert_eq!(receipt.invariant.name, CONSERVED_BAND_INVARIANT);
        assert_eq!(receipt.oracle.name, CONSERVED_BAND_INVARIANT);
        assert_eq!(receipt.invariant.tolerance, CONSERVED_BAND_TOLERANCE);
        assert_eq!(receipt.receipt_status, "PASS");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.002, 0.998])),
        );
        assert!(
            result.is_ok(),
            "a faithful conserved-band receipt must verify: {result:?}"
        );
    }

    #[test]
    fn verify_fails_a_faithful_conserved_band_drift() {
        // A quantity that drifts out of the budget faithfully reproduces a
        // FAIL_UNEXPECTED, so verify exits 3.
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVED_BAND_INVARIANT,
            path,
            vec![1.0, 1.0, 1.1],
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.0, 1.1])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful conserved-band drift must exit 3 (FAIL_UNEXPECTED)"
        );
    }

    #[test]
    fn verify_rejects_a_non_canonical_conserved_band_tolerance() {
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVED_BAND_INVARIANT,
            path,
            vec![1.0, 1.002, 0.998],
            true,
            false,
        ));
        receipt.invariant.tolerance = 1e6;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.002, 0.998])),
        );
        assert_eq!(result, Err(1), "a non-canonical tolerance must be rejected");
    }

    #[test]
    fn verify_rejects_a_column_count_that_violates_the_invariant_contract() {
        // Emit rejects a single-scalar invariant with column_count != 1; verify
        // RE-CHECKS the same contract, so a resealed conserved-band receipt with
        // column_count = 2 is rejected (FIELD_CONTRACT_VIOLATION) rather than
        // silently accepted. (Regression for the D1 review finding: the
        // structural column contract had no verify-side counterpart.)
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(base_inputs_for(
            CONSERVED_BAND_INVARIANT,
            path,
            vec![1.0, 1.002, 0.998],
            true,
            false,
        ));
        assert_eq!(receipt.measurement.column_count, 1);
        receipt.measurement.column_count = 2;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.002, 0.998])),
        );
        assert_eq!(
            result,
            Err(1),
            "a single-scalar invariant with column_count != 1 must be rejected"
        );

        // The mirror case: a relation receipt resealed to column_count 1 (below
        // the >= 2 contract) is also rejected.
        let mut relation = build_scientific_runtime_receipt(relation_inputs(
            path,
            vec![1.0, 1.0, 2.0, 2.0],
            true,
            false,
        ));
        relation.measurement.column_count = 1;
        seal_receipt(&mut relation);
        let value = serde_json::to_value(&relation).expect("to_value");
        let sd = relation.source_digest.clone();
        let gd = relation.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &relation.compiler_version,
            &relation.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 1.0, 2.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "a relation invariant with column_count < 2 must be rejected"
        );
    }

    #[test]
    fn non_negative_holds_and_flags_undershoot() {
        // Arbitrarily large positive values are fine; only a value below zero
        // (beyond roundoff) is a violation.
        let obs = non_negative(&[0.0, 5.0, 100.0, 0.5], NON_NEGATIVE_TOLERANCE);
        assert_eq!(obs.violation_count, 0);
        assert!(invariant_passes(4, &obs));
        // An undershoot below zero at step 2 is flagged.
        let obs = non_negative(&[1.0, 0.5, -0.3, 2.0], NON_NEGATIVE_TOLERANCE);
        assert_eq!(obs.violation_count, 1);
        assert_eq!(obs.first_violation_step, Some(2));
    }

    #[test]
    fn non_negative_is_distinct_from_the_family() {
        // A quantity that grows far above its start and returns to zero:
        // non-negative ACCEPTS it, while bounded (rose above s[0]), conservation
        // (deviated), and monotone (rose) all reject it. Only the absolute
        // lower floor accepts an unbounded-but-non-negative series.
        let grow = [1.0, 5.0, 100.0, 0.0];
        let nn = evaluate_invariant(NON_NEGATIVE_INVARIANT, &grow, NON_NEGATIVE_TOLERANCE);
        assert_eq!(nn.violation_count, 0, "non-negative accepts the growth");
        let bounded = evaluate_invariant(BOUNDED_INVARIANT, &grow, BOUNDED_TOLERANCE);
        assert!(
            bounded.violation_count > 0,
            "bounded rejects the rise above s[0]"
        );
        let cons = evaluate_invariant(CONSERVATION_INVARIANT, &grow, CONSERVATION_TOLERANCE);
        assert!(
            cons.violation_count > 0,
            "conservation rejects the deviation"
        );
        let mono = evaluate_invariant(ENERGY_MONOTONE_INVARIANT, &grow, ENERGY_MONOTONE_TOLERANCE);
        assert!(mono.violation_count > 0, "monotone rejects the rise");
    }

    #[test]
    fn verify_round_trips_a_non_negative_receipt() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            NON_NEGATIVE_INVARIANT,
            path,
            vec![0.0, 5.0, 100.0],
            true,
            false,
        ));
        assert_eq!(receipt.invariant.name, NON_NEGATIVE_INVARIANT);
        assert_eq!(receipt.oracle.name, NON_NEGATIVE_INVARIANT);
        assert_eq!(receipt.invariant.tolerance, NON_NEGATIVE_TOLERANCE);
        assert_eq!(receipt.receipt_status, "PASS");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![0.0, 5.0, 100.0])),
        );
        assert!(
            result.is_ok(),
            "a faithful non-negative receipt must verify: {result:?}"
        );
    }

    #[test]
    fn verify_fails_a_faithful_non_negative_undershoot() {
        // A series that dips below zero faithfully reproduces a FAIL_UNEXPECTED,
        // so verify exits 3.
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(base_inputs_for(
            NON_NEGATIVE_INVARIANT,
            path,
            vec![1.0, -0.5, 2.0],
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, -0.5, 2.0])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful non-negative undershoot must exit 3 (FAIL_UNEXPECTED)"
        );
    }

    #[test]
    fn verify_rejects_a_non_canonical_non_negative_tolerance() {
        let path = Path::new("k.bld");
        let mut receipt = build_scientific_runtime_receipt(base_inputs_for(
            NON_NEGATIVE_INVARIANT,
            path,
            vec![0.0, 5.0, 100.0],
            true,
            false,
        ));
        receipt.invariant.tolerance = 1e6;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, _, _| Ok(rerun(vec![0.0, 5.0, 100.0])),
        );
        assert_eq!(result, Err(1), "a non-canonical tolerance must be rejected");
    }

    /// Build a faithful re-run observation (finite series, exit 0, raw and
    /// executable digests matching the test receipt) for verify callbacks.
    fn rerun(series: Vec<f64>) -> RerunObservation {
        RerunObservation {
            parsed: ParsedSeries {
                any_parsed: !series.is_empty(),
                diverged: false,
                series,
            },
            exit_code: 0,
            secondary: None,
            raw_stdout_digest: hex_digest('c'),
            executable_digest: hex_digest('f'),
            wall_seconds: 0.123,
        }
    }

    #[test]
    fn native_stdio_mode_is_omitted_and_verified_as_legacy_default() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        assert!(
            value["build_state"].get("stdio_mode").is_none(),
            "native receipts must preserve the old missing-field shape: {value:#?}"
        );
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, stdio_mode| {
                assert_eq!(
                    stdio_mode, SCIENTIFIC_STDIO_MODE_NATIVE,
                    "missing sealed stdio_mode must verify as native"
                );
                Ok(rerun(vec![4.0, 3.0, 2.0]))
            },
        );

        assert_eq!(result, Ok(()));
    }

    #[test]
    fn portable_stdio_mode_is_sealed_and_passed_to_the_rerun() {
        let path = Path::new("k.bld");
        let receipt = build_scientific_runtime_receipt(ScientificReceiptInputs {
            stdio_mode: Some(SCIENTIFIC_STDIO_MODE_PORTABLE_LF),
            flags: vec!["stdio-mode=portable-lf".to_string()],
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        let value = serde_json::to_value(&receipt).expect("to_value");
        assert_eq!(value["build_state"]["stdio_mode"], "portable-lf");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, stdio_mode| {
                assert_eq!(
                    stdio_mode, SCIENTIFIC_STDIO_MODE_PORTABLE_LF,
                    "verify must compile the replay with the sealed stdio mode"
                );
                Ok(rerun(vec![4.0, 3.0, 2.0]))
            },
        );

        assert_eq!(result, Ok(()));
    }

    #[test]
    fn verify_matches_a_freshly_built_receipt() {
        // Round trip: build a receipt, serialize it, then verify it with
        // callbacks that reproduce the same digests and series. Verify passes.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert!(result.is_ok(), "a faithful re-run must verify");
    }

    #[test]
    fn verify_rejects_a_source_digest_mismatch() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let graph_digest = receipt.input_graph_digest.clone();

        // The re-derived source digest disagrees with the stored one.
        let wrong = ScientificDigest {
            algorithm: "sha256".to_string(),
            hex: "c".repeat(64),
        };
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(wrong.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(result, Err(1), "a source-digest mismatch must fail verify");
    }

    #[test]
    fn verify_rejects_a_verdict_drift() {
        // The stored receipt says PASS, but the re-run produces an increasing
        // series (FAIL). The verdict comparison must reject it.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 2.0, 3.0])),
        );
        assert_eq!(result, Err(1), "an invariant drift must fail verify");
    }

    #[test]
    fn verify_rejects_measurement_count_drift() {
        // The re-run reproduces a PASSing (monotone) series, but with a DIFFERENT
        // number of points than the stored receipt. The verdict alone would match
        // (PASS/PASS, 0 increases); the count re-check is what catches it.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        assert_eq!(receipt.measurement.count, 3);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            // Two points instead of three; still monotone (PASS), so only the
            // count check can reject this.
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0])),
        );
        assert_eq!(result, Err(1), "a measurement count drift must fail verify");
    }

    #[test]
    fn verify_fails_a_faithful_but_unexpected_failure() {
        // A receipt that faithfully reproduces but records FAIL_UNEXPECTED must
        // NOT exit 0: `receipt verify && deploy` must not deploy on it. Exit 3
        // distinguishes "faithful, invariant not held" from "did not reproduce".
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![1.0, 2.0, 3.0], true, false));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 2.0, 3.0])),
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful FAIL_UNEXPECTED receipt must fail verify with exit 3"
        );
    }

    #[test]
    fn verify_passes_a_faithful_negative_fixture() {
        // A negative fixture that reproduces its EXPECTED failure is a pass: the
        // receipt is FAIL_EXPECTED and verify returns Ok.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![1.0, 2.0, 3.0], true, true));
        assert_eq!(receipt.receipt_status, "FAIL_EXPECTED");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![1.0, 2.0, 3.0])),
        );
        assert!(
            result.is_ok(),
            "a faithful FAIL_EXPECTED receipt must verify"
        );
    }

    #[test]
    fn verify_fails_a_faithful_diverged_receipt() {
        // A diverged (UNVERIFIABLE) receipt whose re-run reproduces the same
        // divergence is faithful, but UNVERIFIABLE is not a pass -> Err(3).
        // The re-run's finite prefix is deliberately a DIFFERENT length than
        // the stored one: for a diverged run the prefix length is the index of
        // the first non-finite value, a platform-dependent quantity, so the
        // count / violation_count checks must be skipped when both runs
        // diverged (a 1-ULP libm difference can shift the divergence step and
        // must not misclassify an honest receipt as tampering, Err(1)).
        let path = Path::new("k.bld");
        let mut inputs = base_inputs(path, vec![4.0, 3.0], true, false);
        inputs.diverged = true;
        let receipt = build_scientific_runtime_receipt(inputs);
        assert_eq!(receipt.receipt_status, "UNVERIFIABLE");
        assert_eq!(receipt.measurement.count, 2);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| {
                let mut observation = rerun(vec![4.0, 3.0, 2.5]);
                // Three finite values instead of two: the divergence step
                // shifted by one on the re-run platform.
                observation.parsed.diverged = true;
                Ok(observation)
            },
        );
        assert_eq!(
            result,
            Err(3),
            "a faithful diverged receipt must exit 3 even when the platform-dependent prefix length shifts"
        );
    }

    #[test]
    fn verify_rejects_a_missing_scope_entry() {
        // A receipt whose scope omits "observed_series_invariant" is rejected
        // before any expensive work.
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.scope = vec!["rerun_agreement".to_string()];
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "a receipt without the observed_series_invariant scope entry must be rejected"
        );
    }

    #[test]
    fn verify_rejects_an_extraction_policy_mismatch() {
        // A receipt extracted under a different policy cannot be faithfully
        // re-checked by this build's parser.
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.measurement.series_extraction_policy = "whitespace-f64/v99".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "an unknown extraction policy must be rejected"
        );
    }

    #[test]
    fn verify_rejects_an_unbound_oracle() {
        // The declared oracle must bind to the invariant actually checked; an
        // unknown oracle kind cannot be re-checked by this verifier at all.
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.oracle.name = "some_other_criterion".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(result, Err(1), "an unbound oracle must be rejected");

        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.oracle.kind = "reference_implementation".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "an oracle kind this verifier cannot re-check must be rejected"
        );
    }

    #[test]
    fn empty_digests_never_match() {
        // Two absent hashes must not report as the strongest reproduction
        // signal: a vacuous reproduced=true would fabricate provenance.
        let empty = ScientificDigest {
            algorithm: "sha256".to_string(),
            hex: String::new(),
        };
        assert!(!digests_match(&empty, &empty));
        assert!(digests_match(&hex_digest('a'), &hex_digest('a')));
    }

    #[test]
    fn verify_rejects_a_malformed_digest() {
        // A sealed digest that is not a real sha256 (here: empty hex) is
        // rejected outright, so "hash unavailable" cannot masquerade as a
        // witnessed hash inside a sealed receipt.
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.build_state.toolchain.program_executable_digest.hex = String::new();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(result, Err(1), "an empty sealed digest must be rejected");
    }

    #[test]
    fn verify_rejects_a_self_consistent_but_unimplemented_oracle() {
        // The oracle binding is pinned to the IMPLEMENTATION: a receipt whose
        // oracle.name and invariant.name agree with EACH OTHER but name a
        // criterion this verifier does not implement must be rejected
        // (comparing the two sealed fields against each other alone is
        // self-referential and re-sealable to any equal pair).
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.oracle.name = "custom_criterion".to_string();
        receipt.invariant.name = "custom_criterion".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "a self-consistent but unimplemented oracle/invariant pair must be rejected"
        );

        // An oracle claiming an EXECUTED status on a declared kind is also
        // rejected: a declared criterion cannot claim execution provenance.
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.oracle.status = "EXECUTED".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "an executed status on a declared oracle must be rejected"
        );
    }

    #[test]
    fn verify_rejects_an_edited_fence() {
        // A fence edited (and resealed) to claim availability v0 does not
        // produce must be rejected, or the fence would be decorative.
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.telemetry_branch.status = "AVAILABLE".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "a fence claiming availability must be rejected"
        );
    }

    #[test]
    fn extraction_policy_matches_by_version_tag_not_prose() {
        // A prose re-wording of the SAME versioned policy must verify (the
        // tag is the contract; the description is display text)...
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.measurement.series_extraction_policy =
            "whitespace-f64/v1: same discipline, different wording".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert!(
            result.is_ok(),
            "same policy tag with different prose must verify: {result:?}"
        );
    }

    // --- Crucible export mapping (the Telos bridge) ---------------------------

    fn report_fixture(
        receipt_status: &'static str,
        violation_count: usize,
    ) -> ScientificVerifyReport {
        ScientificVerifyReport {
            invariant_status: if violation_count == 0 { "PASS" } else { "FAIL" },
            invariant_name: ENERGY_MONOTONE_INVARIANT.to_string(),
            violation_count,
            receipt_status,
            invariant_held: matches!(receipt_status, "PASS" | "FAIL_EXPECTED"),
            toolchain_matched: true,
            raw_stdout_reproduced: true,
            executable_reproduced: false,
            secondary_raw_stdout_reproduced: true,
            secondary_executable_reproduced: true,
            secondary_toolchain_matched: true,
            tolerance: ENERGY_MONOTONE_TOLERANCE,
            negative_fixture: receipt_status == "FAIL_EXPECTED",
            diverged: false,
            source: "k.bld".to_string(),
            source_digest_hex: "a".repeat(64),
            raw_stdout_digest_hex: "c".repeat(64),
            stdio_mode: SCIENTIFIC_STDIO_MODE_NATIVE.to_string(),
            args: vec!["--mode".to_string()],
            seal_hex: "e".repeat(64),
            wall_seconds_sealed: Some(1.234),
            wall_seconds_remeasured: 1.240,
        }
    }

    #[test]
    fn export_derives_deviation_from_the_rerun_and_seals_the_replay() {
        // A PASS report exports deviation 0.0 against tolerance 0.5 (MATCH in
        // Crucible's margin math), with a recheck descriptor carrying the
        // full replay command: witnessed, never asserted.
        let row = crucible_measurement_from_report(
            &report_fixture("PASS", 0),
            "claim-1",
            &"b".repeat(64),
            false,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert_eq!(row["deviation"], 0.0);
        assert_eq!(row["tolerance"], 0.5);
        assert_eq!(row["method"], CRUCIBLE_EXPORT_METHOD);
        assert_eq!(row["recheck"]["oracle"], "buildc.receipt.verify");
        assert_eq!(row["recheck"]["command"][0], "buildc");
        assert_eq!(row["recheck"]["expected"]["violation_count"], 0);
        assert!(row["evidence"]
            .as_array()
            .unwrap()
            .iter()
            .any(|e| e == "receipt_status:PASS"));
    }

    #[test]
    fn export_labels_the_invariant_the_receipt_actually_checked() {
        // The witnessed evidence must name the sealed invariant, not a
        // hardcoded default: a conservation receipt exported through the bridge
        // records `invariant:conserved_quantity_constant`, never the monotone
        // name. (Regression for the C1 review finding: the export string was
        // hardcoded to ENERGY_MONOTONE_INVARIANT and mislabeled every
        // non-monotone receipt.)
        let mut conservation = report_fixture("PASS", 0);
        conservation.invariant_name = CONSERVATION_INVARIANT.to_string();
        let row = crucible_measurement_from_report(
            &conservation,
            "claim-c",
            &"b".repeat(64),
            false,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        let evidence = row["evidence"].as_array().unwrap();
        assert!(
            evidence
                .iter()
                .any(|e| e == &format!("invariant:{}", CONSERVATION_INVARIANT)),
            "conservation export must name conserved_quantity_constant: {evidence:?}"
        );
        assert!(
            !evidence
                .iter()
                .any(|e| e == &format!("invariant:{}", ENERGY_MONOTONE_INVARIANT)),
            "conservation export must NOT carry the monotone name: {evidence:?}"
        );

        // The monotone default still labels itself correctly.
        let mono = crucible_measurement_from_report(
            &report_fixture("PASS", 0),
            "claim-m",
            &"b".repeat(64),
            false,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert!(mono["evidence"]
            .as_array()
            .unwrap()
            .iter()
            .any(|e| e == &format!("invariant:{}", ENERGY_MONOTONE_INVARIANT)));
    }

    #[test]
    fn export_maps_unverifiable_to_null_deviation() {
        // An UNVERIFIABLE receipt exports deviation null: Crucible reads an
        // unmeasurable deviation as UNVERIFIABLE, fail-closed. It must NOT
        // export 0.0 (that would read as a witnessed MATCH).
        let row = crucible_measurement_from_report(
            &report_fixture("UNVERIFIABLE", 0),
            "claim-1",
            &"b".repeat(64),
            false,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert!(row["deviation"].is_null());
    }

    #[test]
    fn export_reports_a_failing_receipt_honestly() {
        // FAIL_UNEXPECTED and FAIL_EXPECTED both export the REAL recomputed
        // increase count (which reads DRIFT against a holds-everywhere claim);
        // the receipt_status in evidence lets the thesis side frame an
        // expected failure. The exporter never launders a failure into 0.0.
        for status in ["FAIL_UNEXPECTED", "FAIL_EXPECTED"] {
            let row = crucible_measurement_from_report(
                &report_fixture(status, 199),
                "claim-1",
                &"b".repeat(64),
                false,
                "r.json",
                &"f".repeat(64),
                1000.0,
            );
            assert_eq!(row["deviation"], 199.0, "status={status}");
            assert!(row["evidence"]
                .as_array()
                .unwrap()
                .iter()
                .any(|e| e.as_str().unwrap() == format!("receipt_status:{status}")));
        }
    }

    #[test]
    fn export_expected_failure_binding_is_claim_relative() {
        // With --claim-expects-failure, deviation measures the claim's
        // PREDICTION: a fixture failing as predicted deviates 0 (MATCH in
        // Crucible's margin math); a fixture that unexpectedly PASSes
        // deviates 1 (DRIFT: the prediction was violated). The binding is
        // recorded in evidence.
        let row = crucible_measurement_from_report(
            &report_fixture("FAIL_EXPECTED", 199),
            "claim-1",
            &"b".repeat(64),
            true,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert_eq!(row["deviation"], 0.0);
        assert!(row["evidence"]
            .as_array()
            .unwrap()
            .iter()
            .any(|e| e == "claim_expectation:expects_failure"));

        let mut passed = report_fixture("PASS", 0);
        passed.negative_fixture = true;
        let row = crucible_measurement_from_report(
            &passed,
            "claim-1",
            &"b".repeat(64),
            true,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert_eq!(
            row["deviation"], 1.0,
            "a fixture that unexpectedly passes violates the failure-predicting claim"
        );
    }

    #[test]
    fn export_never_seals_a_platform_dependent_expectation_for_diverged_receipts() {
        // A diverged receipt's increase count is prefix-derived and
        // platform-dependent (the verifier's own both_diverged rule skips
        // comparing it); the recheck expectation must be null so an
        // independent replayer matches on receipt_status, not on a number
        // that legitimately differs across toolchains.
        let mut report = report_fixture("UNVERIFIABLE", 1957);
        report.diverged = true;
        let row = crucible_measurement_from_report(
            &report,
            "claim-1",
            &"b".repeat(64),
            false,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert!(row["recheck"]["expected"]["violation_count"].is_null());
        assert_eq!(row["recheck"]["diverged"], true);
        assert!(row["deviation"].is_null());
        assert_eq!(row["recheck"]["expected"]["exit_code"], 3);
    }

    #[test]
    fn export_carries_the_reproduction_flags_outside_evidence() {
        // The witnessing re-run's reproduction signals are visible to
        // auditors as a top-level object, deliberately NOT inside evidence
        // (Crucible's recheck compares evidence for stability, and these
        // flags legitimately differ per replay environment).
        let row = crucible_measurement_from_report(
            &report_fixture("PASS", 0),
            "claim-1",
            &"b".repeat(64),
            false,
            "r.json",
            &"f".repeat(64),
            1000.0,
        );
        assert_eq!(row["reproduction"]["toolchain_matched"], true);
        assert_eq!(row["reproduction"]["raw_stdout_reproduced"], true);
        assert_eq!(row["reproduction"]["executable_reproduced"], false);
        assert_eq!(row["recheck"]["expected"]["exit_code"], 0);
        // The sealed-time digest is labeled as such.
        assert!(row["evidence"]
            .as_array()
            .unwrap()
            .iter()
            .any(|e| e.as_str().unwrap().starts_with("sealed_raw_stdout:sha256:")));
    }

    #[test]
    fn witnessed_fields_derive_from_capabilities() {
        // Console writing stdout only (reads_stdin=false): no external dataset
        // POSSIBLE, deterministic modulo args - the effect system proving
        // absences. This is the pure-println flagship kernel; it MUST keep its
        // true absence claims.
        let (dataset, seed, determinism) =
            witnessed_fields_from_capabilities(&["Console".to_string()], false, None);
        assert_eq!(dataset.status, "NONE_WITNESSED");
        assert_eq!(seed.status, "NOT_APPLICABLE");
        assert!(determinism.deterministic_modulo_args);

        // Console READING stdin: stdin is an external input, so both absences
        // collapse (the Console NAME alone would have missed this).
        let (dataset, _, determinism) =
            witnessed_fields_from_capabilities(&["Console".to_string()], true, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(dataset.grounds.contains("stdin"));
        assert!(!determinism.deterministic_modulo_args);
        assert!(determinism.grounds.contains("stdin"));

        // FileSystem present: the dataset field fences honestly, and
        // determinism cannot be claimed.
        let caps = vec!["Console".to_string(), "FileSystem".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(dataset.grounds.contains("FileSystem"));
        assert!(!determinism.deterministic_modulo_args);

        // Clock alone breaks determinism but not the dataset absence (the wall
        // clock is a scalar nondeterminism source, not a data channel).
        let caps = vec!["Clock".to_string(), "Console".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "NONE_WITNESSED");
        assert!(!determinism.deterministic_modulo_args);
        assert!(determinism.grounds.contains("Clock"));

        // Foreign (extern C) can do arbitrary IO: hazard for BOTH claims.
        let caps = vec!["Console".to_string(), "Foreign".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(dataset.grounds.contains("Foreign"));
        assert!(!determinism.deterministic_modulo_args);

        // Gpu: hazard for BOTH claims.
        let caps = vec!["Console".to_string(), "Gpu".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(dataset.grounds.contains("Gpu"));
        assert!(!determinism.deterministic_modulo_args);

        // Environment (getenv / argv): hazard for BOTH claims.
        let caps = vec!["Console".to_string(), "Environment".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(!determinism.deterministic_modulo_args);

        // Process (exit) reads nothing and is deterministic: safe for BOTH.
        let caps = vec!["Console".to_string(), "Process".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "NONE_WITNESSED");
        assert!(determinism.deterministic_modulo_args);

        // An unrecognised capability is default-unsafe (fail closed): a
        // capability added to the checker later cannot silently widen either
        // absence claim.
        let caps = vec!["Console".to_string(), "Bluetooth".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(dataset.grounds.contains("Bluetooth"));
        assert!(!determinism.deterministic_modulo_args);
    }

    #[test]
    fn witnessed_fields_treat_model_as_a_hazard_for_both_claims() {
        // Model carries NO explicit arm in witnessed_fields_from_capabilities:
        // it falls through to the fail-closed default, exactly like any other
        // capability this function does not specifically recognise. This
        // pins that behaviour: if someone later adds an explicit Model arm
        // that weakens either claim (e.g. treating it as dataset-safe because
        // "it's just text"), this test goes red.
        let caps = vec!["Console".to_string(), "Model".to_string()];
        let (dataset, _, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "POSSIBLE_UNWITNESSED");
        assert!(dataset.grounds.contains("Model"));
        assert!(!determinism.deterministic_modulo_args);
        assert!(determinism.grounds.contains("Model"));
    }

    #[test]
    fn witnessed_fields_derive_the_seed_trichotomy() {
        let caps = vec!["Console".to_string(), "Random".to_string()];

        // Random with a sealed seed: no dataset hazard (the PRNG is arithmetic,
        // not a data channel), deterministic GIVEN the seed, and the seed field
        // is SEALED with the value named in its grounds.
        let (dataset, seed, determinism) =
            witnessed_fields_from_capabilities(&caps, false, Some(42));
        assert_eq!(dataset.status, "NONE_WITNESSED");
        assert_eq!(seed.status, "SEALED");
        assert!(seed.grounds.contains("42"));
        assert!(determinism.deterministic_modulo_args);
        assert!(determinism.grounds.contains("seeded"));

        // Random with NO seed: determinism collapses, and the seed field says
        // UNSEEDED (a state emit refuses; kept so the derivation is total and
        // a receipt claiming it can never re-derive as anything else).
        let (dataset, seed, determinism) = witnessed_fields_from_capabilities(&caps, false, None);
        assert_eq!(dataset.status, "NONE_WITNESSED");
        assert_eq!(seed.status, "UNSEEDED");
        assert!(!determinism.deterministic_modulo_args);
        assert!(determinism.grounds.contains("unseeded Random"));

        // No Random capability: NOT_APPLICABLE (a seed nothing draws from is
        // refused by the pairing gate upstream, not silently recorded here).
        let (_, seed, _) =
            witnessed_fields_from_capabilities(&["Console".to_string()], false, None);
        assert_eq!(seed.status, "NOT_APPLICABLE");
    }

    #[test]
    fn verify_enforces_the_seed_capability_pairing() {
        let random_policy = || ScientificEffectPolicy {
            facts_digest: hex_digest('9'),
            observed_capabilities: vec!["Console".to_string(), "Random".to_string()],
            reads_stdin: false,
        };
        let path = Path::new("k.bld");

        // A seeded Random receipt is faithful, and the re-run receives the
        // SEALED seed (the closure pins it, so a verifier that re-ran the
        // program seedless would fail this test at the assert, not by luck).
        let receipt = build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: random_policy(),
            seed_value: Some(42),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        assert_eq!(receipt.seed.status, "SEALED");
        assert_eq!(receipt.seed_value, Some(42));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| {
                Ok(RederivedFacts {
                    source_digest: src.clone(),
                    input_graph_digest: graph.clone(),
                    effect_policy: random_policy(),
                })
            },
            |_, _, seed, _, _| {
                assert_eq!(seed, Some(42), "the re-run must receive the sealed seed");
                Ok(rerun(vec![4.0, 3.0, 2.0]))
            },
        );
        assert_eq!(result, Ok(()), "a seeded Random receipt must verify");

        // A Random-using program whose receipt seals NO seed is refused at the
        // pairing gate, before any re-run.
        let unseeded = build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: random_policy(),
            seed_value: None,
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        let value = serde_json::to_value(&unseeded).expect("to_value");
        let src = unseeded.source_digest.clone();
        let graph = unseeded.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &unseeded.compiler_version,
            &unseeded.language_version,
            Some(&test_toolchain()),
            |_| {
                Ok(RederivedFacts {
                    source_digest: src.clone(),
                    input_graph_digest: graph.clone(),
                    effect_policy: random_policy(),
                })
            },
            |_, _, _, _, _| panic!("an unseeded Random receipt must be refused before the re-run"),
        );
        assert_eq!(
            result,
            Err(1),
            "a Random program with no sealed seed must fail"
        );

        // A sealed seed on a program with NO Random capability is a claim
        // about a knob nothing reads: refused at the same gate.
        let overclaimed = build_scientific_runtime_receipt(ScientificReceiptInputs {
            seed_value: Some(7),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        let value = serde_json::to_value(&overclaimed).expect("to_value");
        let src = overclaimed.source_digest.clone();
        let graph = overclaimed.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &overclaimed.compiler_version,
            &overclaimed.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src.clone(), graph.clone())),
            |_, _, _, _, _| panic!("a seed nothing consumes must be refused before the re-run"),
        );
        assert_eq!(
            result,
            Err(1),
            "a seed without a Random capability must fail"
        );

        // A CHANGED seed, properly re-sealed, passes the pairing gate (Random
        // is present, a seed is present) but the sealed `seed` grounds still
        // name the original value, so the witnessed-field re-derivation
        // refuses it: the seed cannot be quietly swapped for one whose stream
        // was never observed.
        let receipt = build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: random_policy(),
            seed_value: Some(42),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        let mut swapped = receipt.clone();
        swapped.seed_value = Some(43);
        seal_receipt(&mut swapped);
        let value = serde_json::to_value(&swapped).expect("to_value");
        let src = swapped.source_digest.clone();
        let graph = swapped.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &swapped.compiler_version,
            &swapped.language_version,
            Some(&test_toolchain()),
            |_| {
                Ok(RederivedFacts {
                    source_digest: src.clone(),
                    input_graph_digest: graph.clone(),
                    effect_policy: random_policy(),
                })
            },
            |_, _, _, _, _| panic!("a swapped seed must be refused before the re-run"),
        );
        assert_eq!(result, Err(1), "a re-sealed seed swap must fail");
    }

    #[test]
    fn verify_refuses_a_model_observing_receipt() {
        let model_policy = || ScientificEffectPolicy {
            facts_digest: hex_digest('9'),
            observed_capabilities: vec!["Console".to_string(), "Model".to_string()],
            reads_stdin: false,
        };
        let path = Path::new("k.bld");

        // A receipt whose RE-DERIVED capabilities include Model is refused
        // outright, before any re-run: models propose, oracles dispose. The
        // rerun closure panics if reached, so a verifier that let this
        // through to the re-run would fail this test at the panic, not by
        // luck.
        let receipt = build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: model_policy(),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| {
                Ok(RederivedFacts {
                    source_digest: src.clone(),
                    input_graph_digest: graph.clone(),
                    effect_policy: model_policy(),
                })
            },
            |_, _, _, _, _| panic!("a model-observing receipt must be refused before the re-run"),
        );
        assert_eq!(
            result,
            Err(1),
            "a receipt whose capabilities include Model must fail"
        );
    }

    #[test]
    fn verify_enforces_the_monte_carlo_admission_contracts() {
        fn random_policy() -> ScientificEffectPolicy {
            ScientificEffectPolicy {
                facts_digest: hex_digest('9'),
                observed_capabilities: vec!["Console".to_string(), "Random".to_string()],
                reads_stdin: false,
            }
        }
        fn mc() -> ScientificMonteCarlo {
            ScientificMonteCarlo {
                estimator: "mean".to_string(),
                samples: 2000,
                interval_method: "normal-approx-95".to_string(),
                status: "DECLARED".to_string(),
                estimate: None,
                interval_low: None,
                interval_high: None,
                n_effective: None,
                successes: None,
            }
        }
        fn run(
            receipt: &ScientificRuntimeReceipt,
            policy: ScientificEffectPolicy,
        ) -> Result<(), i32> {
            let value = serde_json::to_value(receipt).expect("to_value");
            let src = receipt.source_digest.clone();
            let graph = receipt.input_graph_digest.clone();
            verify_scientific_runtime_receipt(
                &value,
                None,
                true,
                &receipt.compiler_version,
                &receipt.language_version,
                Some(&test_toolchain()),
                move |_| {
                    Ok(RederivedFacts {
                        source_digest: src,
                        input_graph_digest: graph,
                        effect_policy: policy,
                    })
                },
                |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
            )
        }
        let path = Path::new("k.bld");
        let seeded_mc = |block: ScientificMonteCarlo| {
            build_scientific_runtime_receipt(ScientificReceiptInputs {
                effect_policy: random_policy(),
                seed_value: Some(42),
                monte_carlo: Some(block),
                ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
            })
        };

        // A complete, paired MC declaration verifies, and the block is sealed.
        let receipt = seeded_mc(mc());
        let value = serde_json::to_value(&receipt).unwrap();
        assert_eq!(value["monte_carlo"]["samples"], 2000);
        assert_eq!(value["monte_carlo"]["interval_method"], "normal-approx-95");
        assert_eq!(
            run(&receipt, random_policy()),
            Ok(()),
            "a complete MC declaration on a seeded Random run must verify"
        );
        // BACKWARD COMPATIBILITY PIN: a DECLARED block's serialized JSON
        // carries EXACTLY the four original keys, none of the five new
        // EXECUTED fields (`skip_serializing_if = "Option::is_none"`
        // working as intended). A receipt sealed before this slice, when
        // re-parsed and re-serialized today, produces this exact shape, so
        // its bytes and seal are unchanged.
        let mc_keys: std::collections::BTreeSet<&str> = value["monte_carlo"]
            .as_object()
            .expect("monte_carlo is an object")
            .keys()
            .map(|k| k.as_str())
            .collect();
        assert_eq!(
            mc_keys,
            ["estimator", "samples", "interval_method", "status"]
                .into_iter()
                .collect::<std::collections::BTreeSet<&str>>(),
            "a DECLARED monte_carlo block must serialize with exactly its original four keys"
        );

        // A zero denominator is unpriceable.
        let mut bad = mc();
        bad.samples = 0;
        assert_eq!(run(&seeded_mc(bad), random_policy()), Err(1));

        // An unnamed interval method is refused: the claim is the interval,
        // never the point.
        let mut bad = mc();
        bad.interval_method = " ".to_string();
        assert_eq!(run(&seeded_mc(bad), random_policy()), Err(1));

        // EXECUTED is now expressible, but this literal (via mc(), which
        // sets none of the five executed fields) must still fail: EXECUTED
        // with no executed fields present is FIELD_CONTRACT_VIOLATION (the
        // field-presence gate), not an unknown status.
        let mut bad = mc();
        bad.status = "EXECUTED".to_string();
        assert_eq!(run(&seeded_mc(bad), random_policy()), Err(1));

        // A THIRD status string is refused as unknown: the two-arm
        // vocabulary (DECLARED | EXECUTED) itself stays gated.
        let mut bad = mc();
        bad.status = "SIMULATED".to_string();
        assert_eq!(run(&seeded_mc(bad), random_policy()), Err(1));

        // An MC block on a program with no Random capability (and no seed) is
        // refused at the pairing gate.
        let unpaired = build_scientific_runtime_receipt(ScientificReceiptInputs {
            monte_carlo: Some(mc()),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        assert_eq!(run(&unpaired, test_effect_policy()), Err(1));

        // A receipt with no MC block serializes without the key, so receipts
        // sealed before the block existed keep their exact bytes and seals.
        let plain =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&plain).unwrap();
        assert!(value.get("monte_carlo").is_none());
    }

    /// The effect-policy fixture for the EXECUTED monte_carlo tests: Random
    /// paired with a sealed seed.
    fn mc_executed_random_policy() -> ScientificEffectPolicy {
        ScientificEffectPolicy {
            facts_digest: hex_digest('9'),
            observed_capabilities: vec!["Console".to_string(), "Random".to_string()],
            reads_stdin: false,
        }
    }

    /// A coherent 3-column EXECUTED monte_carlo receipt fixture: series is
    /// `<invariant scalar 0.0> <successes> <trials>` per row, successes
    /// 1,1,2,2 over trials 1,2,3,4 (samples = 4), wilson-95. The executed
    /// fields are computed by `compute_mc_executed` itself so the fixture is
    /// self-consistent by construction.
    fn coherent_executed_mc_receipt(path: &Path) -> ScientificRuntimeReceipt {
        let series = vec![
            0.0, 1.0, 1.0, //
            0.0, 1.0, 2.0, //
            0.0, 2.0, 3.0, //
            0.0, 2.0, 4.0, //
        ];
        let computed = compute_mc_executed(&series, 3, 4, MC_INTERVAL_WILSON_95)
            .expect("fixture series must be coherent");
        let mc = ScientificMonteCarlo {
            estimator: MC_EXECUTED_ESTIMATOR_PROPORTION.to_string(),
            samples: 4,
            interval_method: MC_INTERVAL_WILSON_95.to_string(),
            status: "EXECUTED".to_string(),
            estimate: Some(computed.estimate),
            interval_low: Some(computed.interval_low),
            interval_high: Some(computed.interval_high),
            n_effective: Some(computed.n_effective),
            successes: Some(computed.successes),
        };
        build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: mc_executed_random_policy(),
            seed_value: Some(42),
            monte_carlo: Some(mc),
            column_count: 3,
            ..base_inputs_for(NON_NEGATIVE_INVARIANT, path, series, true, false)
        })
    }

    /// An ALL-FAILURE variant (successes = 0 on every row) of the coherent
    /// EXECUTED fixture, under wilson-95 (which, unlike normal-approx-95,
    /// has no boundary refusal at successes = 0). This exists specifically
    /// to isolate the "all five executed fields present" gate from the
    /// Stage A recompute-mismatch gate: since `u64::default() == 0` equals
    /// the REAL successes value here, a missing `successes` field defaults
    /// to exactly the correct number, so ONLY the presence gate (not the
    /// recompute comparison) can catch it -- the field-presence-guard
    /// mutation test below relies on this.
    fn coherent_executed_mc_receipt_all_failures(path: &Path) -> ScientificRuntimeReceipt {
        let series = vec![
            0.0, 0.0, 1.0, //
            0.0, 0.0, 2.0, //
            0.0, 0.0, 3.0, //
            0.0, 0.0, 4.0, //
        ];
        let computed = compute_mc_executed(&series, 3, 4, MC_INTERVAL_WILSON_95)
            .expect("an all-failure series is coherent under wilson-95");
        assert_eq!(computed.successes, 0, "fixture precondition");
        let mc = ScientificMonteCarlo {
            estimator: MC_EXECUTED_ESTIMATOR_PROPORTION.to_string(),
            samples: 4,
            interval_method: MC_INTERVAL_WILSON_95.to_string(),
            status: "EXECUTED".to_string(),
            estimate: Some(computed.estimate),
            interval_low: Some(computed.interval_low),
            interval_high: Some(computed.interval_high),
            n_effective: Some(computed.n_effective),
            successes: Some(computed.successes),
        };
        build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: mc_executed_random_policy(),
            seed_value: Some(42),
            monte_carlo: Some(mc),
            column_count: 3,
            ..base_inputs_for(NON_NEGATIVE_INVARIANT, path, series, true, false)
        })
    }

    #[test]
    fn verify_round_trips_a_coherent_executed_monte_carlo_receipt() {
        // The positive control for every negative test below: a faithful
        // EXECUTED receipt must verify (both stages pass on an untampered,
        // faithfully re-run receipt).
        let path = Path::new("k.bld");
        let receipt = coherent_executed_mc_receipt(path);
        let value = serde_json::to_value(&receipt).expect("to_value");
        assert_eq!(value["monte_carlo"]["status"], "EXECUTED");
        assert_eq!(value["monte_carlo"]["n_effective"], 4);
        assert_eq!(value["monte_carlo"]["successes"], 2);
        assert!(receipt.scope.iter().any(|c| c == "interval_arithmetic"));
        assert!(receipt.scope.iter().any(|c| c == "sample_denominator"));
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let series = receipt.measurement.observed_values.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: src,
                    input_graph_digest: graph,
                    effect_policy: mc_executed_random_policy(),
                })
            },
            move |_, _, _, _, _| Ok(rerun(series)),
        );
        assert_eq!(result, Ok(()), "a faithful EXECUTED receipt must verify");
    }

    #[test]
    fn verify_stage_a_rejects_tampered_executed_interval_before_any_rerun() {
        // Tamper interval_high directly on the sealed JSON (bypassing
        // `seal_receipt`, so the seal would be stale) then re-seal via the
        // same `reseal_json` path the self-test uses. A rerun_series closure
        // that panics if called proves the rejection fires BEFORE any
        // re-run: this is the "Stage-A-rejects-before-rerun" property test.
        let path = Path::new("k.bld");
        let receipt = coherent_executed_mc_receipt(path);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let mut tampered = value.clone();
        let bumped = tampered["monte_carlo"]["interval_high"]
            .as_f64()
            .expect("interval_high must be present")
            + 0.25;
        tampered["monte_carlo"]["interval_high"] = serde_json::Value::from(bumped);
        let tampered = reseal_json(&tampered).expect("reseal must succeed");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &tampered,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: src,
                    input_graph_digest: graph,
                    effect_policy: mc_executed_random_policy(),
                })
            },
            |_, _, _, _, _| panic!("Stage A must reject a tampered interval before any re-run"),
        );
        assert_eq!(result, Err(1));
    }

    #[test]
    fn verify_stage_b_reports_mc_interval_drift_on_a_changed_rerun() {
        // The SEALED series is untampered (Stage A passes cleanly), but the
        // RE-RUN returns a DIFFERENT coherent series (one more successful
        // draw): a receipt that stayed internally coherent while no longer
        // describing the run it names. Only Stage B catches this.
        let path = Path::new("k.bld");
        let receipt = coherent_executed_mc_receipt(path);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let drifted_series = vec![
            0.0, 1.0, 1.0, //
            0.0, 2.0, 2.0, // one more success than the sealed series
            0.0, 3.0, 3.0, //
            0.0, 3.0, 4.0, //
        ];
        let report = evaluate_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: src,
                    input_graph_digest: graph,
                    effect_policy: mc_executed_random_policy(),
                })
            },
            move |_, _, _, _, _| Ok(rerun(drifted_series)),
        );
        assert!(report.is_err(), "a Stage B interval drift must fail verify");
    }

    #[test]
    fn verify_refuses_declared_block_carrying_an_executed_field() {
        let path = Path::new("k.bld");
        let mut mc = ScientificMonteCarlo {
            estimator: "mean".to_string(),
            samples: 2000,
            interval_method: "normal-approx-95".to_string(),
            status: "DECLARED".to_string(),
            estimate: None,
            interval_low: None,
            interval_high: None,
            n_effective: None,
            successes: None,
        };
        mc.estimate = Some(0.5); // an executed field on a DECLARED block
        let receipt = build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: mc_executed_random_policy(),
            seed_value: Some(42),
            monte_carlo: Some(mc),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: src,
                    input_graph_digest: graph,
                    effect_policy: mc_executed_random_policy(),
                })
            },
            |_, _, _, _, _| {
                panic!("a DECLARED-with-executed-field block must reject before any re-run")
            },
        );
        assert_eq!(result, Err(1));
    }

    #[test]
    fn verify_refuses_executed_block_missing_an_executed_field() {
        let path = Path::new("k.bld");
        // The all-failure fixture: real successes = 0 EQUALS
        // `u64::default()`, so a missing `successes` field would slip past
        // the Stage A recompute-mismatch comparison undetected -- ONLY the
        // "all five fields present" gate can catch it here, which is the
        // point (an ordinary nonzero fixture would be caught downstream
        // regardless of whether this specific gate runs, which would make
        // the test insensitive to this gate's removal).
        let receipt = coherent_executed_mc_receipt_all_failures(path);
        let mut value = serde_json::to_value(&receipt).expect("to_value");
        value["monte_carlo"]
            .as_object_mut()
            .unwrap()
            .remove("successes");
        let value = reseal_json(&value).expect("reseal must succeed");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: src,
                    input_graph_digest: graph,
                    effect_policy: mc_executed_random_policy(),
                })
            },
            |_, _, _, _, _| panic!("EXECUTED with a missing field must reject before any re-run"),
        );
        assert_eq!(result, Err(1));
    }

    #[test]
    fn verify_refuses_executed_estimator_outside_vocabulary() {
        let path = Path::new("k.bld");
        let receipt = coherent_executed_mc_receipt(path);
        let mut value = serde_json::to_value(&receipt).expect("to_value");
        value["monte_carlo"]["estimator"] = serde_json::Value::from("mean");
        let value = reseal_json(&value).expect("reseal must succeed");
        let src = receipt.source_digest.clone();
        let graph = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: src,
                    input_graph_digest: graph,
                    effect_policy: mc_executed_random_policy(),
                })
            },
            |_, _, _, _, _| panic!("an out-of-vocabulary estimator must reject before any re-run"),
        );
        assert_eq!(result, Err(1));
    }

    /// A receipt in the version 0 shape: schema v0, the `not_claimed` list and
    /// the version 0 labels, resealed.
    fn as_version_0(receipt: &ScientificRuntimeReceipt) -> serde_json::Value {
        let mut value = serde_json::to_value(receipt).expect("to_value");
        value["schema"] = serde_json::Value::from(SCIENTIFIC_RUNTIME_SCHEMA_V0);
        value.as_object_mut().unwrap().remove("scope");
        value["not_claimed"] = serde_json::json!(NOT_CLAIMED_BOUNDARY);
        let labels: Vec<String> = receipt
            .labels
            .iter()
            .map(|l| {
                if l == LABEL_NUMERICAL_RESULT {
                    LABEL_NUMERICAL_RESULT_V0.to_string()
                } else {
                    l.clone()
                }
            })
            .collect();
        value["labels"] = serde_json::json!(labels);
        reseal_json(&value).expect("reseal must succeed")
    }

    #[test]
    fn a_version_0_receipt_still_verifies() {
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let run = |value: &serde_json::Value| {
            let src = receipt.source_digest.clone();
            let graph = receipt.input_graph_digest.clone();
            verify_scientific_runtime_receipt(
                value,
                None,
                true,
                &receipt.compiler_version,
                &receipt.language_version,
                Some(&test_toolchain()),
                move |_| Ok(rederive_facts(src, graph)),
                |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
            )
        };
        let old = as_version_0(&receipt);
        assert_eq!(old["schema"], SCIENTIFIC_RUNTIME_SCHEMA_V0);
        assert!(old.get("scope").is_none());
        assert_eq!(run(&old), Ok(()), "a version 0 receipt must still verify");

        // A version 0 receipt without "physical_law" is still refused.
        let mut missing = old.clone();
        missing["not_claimed"] = serde_json::json!(["convergence"]);
        assert_eq!(run(&reseal_json(&missing).expect("reseal")), Err(1));

        // A version 0 receipt that also carries a scope list is refused.
        let mut both = old.clone();
        both["scope"] = serde_json::json!(SCOPE_BASE);
        assert_eq!(run(&reseal_json(&both).expect("reseal")), Err(1));

        // A version 1 receipt that carries a not_claimed list is refused.
        let mut mixed = serde_json::to_value(&receipt).expect("to_value");
        mixed["not_claimed"] = serde_json::json!(NOT_CLAIMED_BOUNDARY);
        assert_eq!(run(&reseal_json(&mixed).expect("reseal")), Err(1));
    }

    #[test]
    fn verify_mc_scope_pair_biconditional() {
        let path = Path::new("k.bld");

        fn check(receipt: &ScientificRuntimeReceipt, value: serde_json::Value) -> Result<(), i32> {
            let src = receipt.source_digest.clone();
            let graph = receipt.input_graph_digest.clone();
            verify_scientific_runtime_receipt(
                &value,
                None,
                true,
                &receipt.compiler_version,
                &receipt.language_version,
                Some(&test_toolchain()),
                move |_| {
                    Ok(RederivedFacts {
                        source_digest: src,
                        input_graph_digest: graph,
                        effect_policy: mc_executed_random_policy(),
                    })
                },
                |_, _, _, _, _| panic!("an mc scope pair mismatch must reject before any re-run"),
            )
        }

        // EXECUTED with the pair ABSENT is refused.
        let receipt = coherent_executed_mc_receipt(path);
        let mut value = serde_json::to_value(&receipt).expect("to_value");
        value["scope"] = serde_json::Value::Array(
            receipt
                .scope
                .iter()
                .filter(|c| !MC_EXECUTED_SCOPE.contains(&c.as_str()))
                .map(|c| serde_json::Value::from(c.clone()))
                .collect(),
        );
        let value = reseal_json(&value).expect("reseal must succeed");
        assert_eq!(check(&receipt, value), Err(1));

        // DECLARED with the pair PRESENT is refused.
        let plain =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let mut value = serde_json::to_value(&plain).expect("to_value");
        let mut scope: Vec<serde_json::Value> = value["scope"].as_array().unwrap().to_vec();
        for c in MC_EXECUTED_SCOPE {
            scope.push(serde_json::Value::from(*c));
        }
        value["scope"] = serde_json::Value::Array(scope);
        let value = reseal_json(&value).expect("reseal must succeed");
        assert_eq!(check(&plain, value), Err(1));

        // EXECUTED with only one of the two present is refused.
        let receipt = coherent_executed_mc_receipt(path);
        let mut value = serde_json::to_value(&receipt).expect("to_value");
        value["scope"] = serde_json::Value::Array(
            receipt
                .scope
                .iter()
                .filter(|c| c.as_str() != "interval_arithmetic")
                .map(|c| serde_json::Value::from(c.clone()))
                .collect(),
        );
        let value = reseal_json(&value).expect("reseal must succeed");
        assert_eq!(check(&receipt, value), Err(1));
    }

    #[test]
    fn verify_enforces_the_budget_admission_contracts() {
        fn budget() -> ScientificBudget {
            ScientificBudget {
                steps_limit: 500,
                steps_consumed: 437,
                exhausted: false,
                status: "DECLARED".to_string(),
                wall_seconds_limit: None,
                wall_exceeded: None,
            }
        }
        fn run(
            receipt: &ScientificRuntimeReceipt,
            policy: ScientificEffectPolicy,
        ) -> Result<(), i32> {
            let value = serde_json::to_value(receipt).expect("to_value");
            let src = receipt.source_digest.clone();
            let graph = receipt.input_graph_digest.clone();
            verify_scientific_runtime_receipt(
                &value,
                None,
                true,
                &receipt.compiler_version,
                &receipt.language_version,
                Some(&test_toolchain()),
                move |_| {
                    Ok(RederivedFacts {
                        source_digest: src,
                        input_graph_digest: graph,
                        effect_policy: policy,
                    })
                },
                |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
            )
        }
        let path = Path::new("k.bld");
        let budgeted = |block: ScientificBudget| {
            build_scientific_runtime_receipt(ScientificReceiptInputs {
                budget: Some(block),
                ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
            })
        };

        // A complete, coherent budget declaration verifies, and the block is
        // sealed alongside the boundary rule (label + not_claimed entry).
        let receipt = budgeted(budget());
        let value = serde_json::to_value(&receipt).unwrap();
        assert_eq!(value["budget"]["steps_limit"], 500);
        assert_eq!(value["budget"]["steps_consumed"], 437);
        assert_eq!(value["budget"]["exhausted"], false);
        assert!(receipt
            .labels
            .contains(&LABEL_BEST_FOUND_WITHIN_BUDGET.to_string()));
        assert!(receipt.scope.contains(&SCOPE_BUDGET.to_string()));
        assert_eq!(
            run(&receipt, test_effect_policy()),
            Ok(()),
            "a complete, coherent budget declaration must verify"
        );

        // A zero ceiling is not a budget.
        let mut bad = budget();
        bad.steps_limit = 0;
        assert_eq!(run(&budgeted(bad), test_effect_policy()), Err(1));

        // Consumption above the ceiling is incoherent.
        let mut bad = budget();
        bad.steps_consumed = bad.steps_limit + 1;
        assert_eq!(run(&budgeted(bad), test_effect_policy()), Err(1));

        // exhausted is DERIVED, never hand-set: consumed < limit with
        // exhausted hand-set true is refused.
        let mut bad = budget();
        bad.exhausted = true;
        assert_eq!(run(&budgeted(bad), test_effect_policy()), Err(1));

        // A status v0 cannot honestly say is refused.
        let mut bad = budget();
        bad.status = "METERED".to_string();
        assert_eq!(run(&budgeted(bad), test_effect_policy()), Err(1));

        // The claim-language rule: free text may not contradict
        // NOT_PROVES_OPTIMALITY.
        let claims_optimal = build_scientific_runtime_receipt(ScientificReceiptInputs {
            budget: Some(budget()),
            problem_label: Some("greedy-change-optimal".to_string()),
            ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
        });
        assert_eq!(run(&claims_optimal, test_effect_policy()), Err(1));

        // The label-pairing rule, both directions (the covering tests for
        // this rule, so its mutation check can go red): a budgeted receipt
        // whose NOT_PROVES_OPTIMALITY label is stripped after building is
        // refused.
        let mut stripped = receipt.clone();
        stripped
            .labels
            .retain(|l| l != LABEL_BEST_FOUND_WITHIN_BUDGET);
        seal_receipt(&mut stripped);
        assert_eq!(run(&stripped, test_effect_policy()), Err(1));

        // Symmetrically, a budgetless receipt with the label pushed and
        // re-sealed is refused.
        let mut faked =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        faked
            .labels
            .push(LABEL_BEST_FOUND_WITHIN_BUDGET.to_string());
        seal_receipt(&mut faked);
        assert_eq!(run(&faked, test_effect_policy()), Err(1));

        // A budgetless receipt's JSON has no budget key and no
        // NOT_PROVES_OPTIMALITY label.
        let plain =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&plain).unwrap();
        assert!(value.get("budget").is_none());
        assert!(!plain
            .labels
            .contains(&LABEL_BEST_FOUND_WITHIN_BUDGET.to_string()));
    }

    #[test]
    fn verify_enforces_the_wall_metering_contracts() {
        fn budget_with_wall(limit: Option<f64>, exceeded: Option<bool>) -> ScientificBudget {
            ScientificBudget {
                steps_limit: 500,
                steps_consumed: 437,
                exhausted: false,
                status: "DECLARED".to_string(),
                wall_seconds_limit: limit,
                wall_exceeded: exceeded,
            }
        }
        fn run(
            receipt: &ScientificRuntimeReceipt,
            policy: ScientificEffectPolicy,
        ) -> Result<(), i32> {
            let value = serde_json::to_value(receipt).expect("to_value");
            let src = receipt.source_digest.clone();
            let graph = receipt.input_graph_digest.clone();
            verify_scientific_runtime_receipt(
                &value,
                None,
                true,
                &receipt.compiler_version,
                &receipt.language_version,
                Some(&test_toolchain()),
                move |_| {
                    Ok(RederivedFacts {
                        source_digest: src,
                        input_graph_digest: graph,
                        effect_policy: policy,
                    })
                },
                |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
            )
        }
        let path = Path::new("k.bld");
        let metered = |block: ScientificBudget, wall_seconds: Option<f64>| {
            build_scientific_runtime_receipt(ScientificReceiptInputs {
                budget: Some(block),
                wall_seconds,
                ..base_inputs(path, vec![4.0, 3.0, 2.0], true, false)
            })
        };

        // A complete, coherent wall declaration verifies: sealed
        // wall_seconds 12.5, limit 300.0, correctly-derived exceeded=false.
        let receipt = metered(budget_with_wall(Some(300.0), Some(false)), Some(12.5));
        let value = serde_json::to_value(&receipt).unwrap();
        assert_eq!(value["runtime_state"]["wall_seconds"], 12.5);
        assert_eq!(value["budget"]["wall_seconds_limit"], 300.0);
        assert_eq!(value["budget"]["wall_exceeded"], false);
        assert_eq!(
            run(&receipt, test_effect_policy()),
            Ok(()),
            "a coherent wall ceiling declaration must verify"
        );

        // The exceeded flag disagreeing with the sealed numbers is refused:
        // sealed wall_seconds 12.5 is NOT > limit 300.0, so a sealed
        // exceeded=true is incoherent.
        let bad_exceeded = metered(budget_with_wall(Some(300.0), Some(true)), Some(12.5));
        assert_eq!(run(&bad_exceeded, test_effect_policy()), Err(1));

        // wall_exceeded present without wall_seconds_limit is refused: the
        // flag cannot exist without the ceiling it is derived from.
        let bad_flag_only = metered(budget_with_wall(None, Some(false)), Some(12.5));
        assert_eq!(run(&bad_flag_only, test_effect_policy()), Err(1));

        // wall_seconds_limit present without a sealed
        // runtime_state.wall_seconds is refused: a ceiling needs a measured
        // wall time to derive wall_exceeded against.
        let bad_no_measurement = metered(budget_with_wall(Some(300.0), Some(false)), None);
        assert_eq!(run(&bad_no_measurement, test_effect_policy()), Err(1));

        // The zeroed-steps + wall-fields interaction (plan Task 2, line 26):
        // a budget block with a zeroed steps_limit but otherwise-coherent
        // wall fields present must still be refused, and refused by the
        // PRE-EXISTING steps gate, not by any wall-specific one. This pins
        // the gate ORDER at scientific_runtime.rs:2357 (the steps_limit == 0
        // check) running before the wall gate at ~2372, so a future reorder
        // of these checks can't silently let a zeroed-steps budget slip
        // through just because its wall fields happen to be coherent.
        let mut zeroed_steps = budget_with_wall(Some(300.0), Some(false));
        zeroed_steps.steps_limit = 0;
        zeroed_steps.steps_consumed = 0;
        zeroed_steps.exhausted = true;
        let bad_zeroed_steps = metered(zeroed_steps, Some(12.5));
        assert_eq!(
            run(&bad_zeroed_steps, test_effect_policy()),
            Err(1),
            "a zeroed steps_limit with coherent wall fields present must still be refused by the pre-existing steps gates"
        );

        // A receipt with NO new fields (no runtime_state.wall_seconds, no
        // wall fields in budget) round-trips with no new keys in its JSON,
        // AND still verifies: the backward-compat pin. This is the shape a
        // receipt sealed before wall metering existed would have.
        let plain = metered(budget_with_wall(None, None), None);
        let value = serde_json::to_value(&plain).unwrap();
        assert!(value["runtime_state"].get("wall_seconds").is_none());
        assert!(value["budget"].get("wall_seconds_limit").is_none());
        assert!(value["budget"].get("wall_exceeded").is_none());
        assert_eq!(
            run(&plain, test_effect_policy()),
            Ok(()),
            "a pre-wall-metering-shaped receipt (no wall fields at all) must still verify"
        );
    }

    /// A fixture cross-backend block: target `rust`, `EXECUTED`, three
    /// well-formed digests, exit 0.
    fn cross_backend_block() -> ScientificCrossBackend {
        ScientificCrossBackend {
            secondary_target: "rust".to_string(),
            secondary_toolchain_version: "rustc 1.0.0 (test)".to_string(),
            secondary_toolchain_digest: hex_digest('1'),
            secondary_executable_digest: hex_digest('2'),
            secondary_raw_stdout_digest: hex_digest('3'),
            secondary_exit_code: 0,
            status: "EXECUTED".to_string(),
        }
    }

    /// Inputs for a 2-column cross-backend receipt, modeled on `relation_inputs`.
    fn cross_backend_inputs<'a>(
        path: &'a Path,
        series: Vec<f64>,
        parsed: bool,
        negative_fixture: bool,
    ) -> ScientificReceiptInputs<'a> {
        ScientificReceiptInputs {
            invariant_name: CROSS_BACKEND_INVARIANT.to_string(),
            column_count: 2,
            cross_backend: Some(cross_backend_block()),
            ..base_inputs(path, series, parsed, negative_fixture)
        }
    }

    #[test]
    fn cross_backend_receipt_round_trips_and_pins_the_secondary_target() {
        // Interleaved [c0, r0, c1, r1]: two rows, each backend agreeing well
        // within the cross-backend tolerance (1e-5).
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.0000005, 0.5, 0.5000001];
        let receipt =
            build_scientific_runtime_receipt(cross_backend_inputs(path, series, true, false));
        assert_eq!(receipt.invariant.name, CROSS_BACKEND_INVARIANT);
        assert_eq!(receipt.oracle.name, CROSS_BACKEND_INVARIANT);
        assert_eq!(receipt.measurement.column_count, 2);
        assert_eq!(receipt.measurement.count, 4);
        assert_eq!(receipt.receipt_status, "PASS");
        assert_eq!(receipt.invariant.observed.violation_count, 0);
        assert!(receipt.cross_backend.is_some());

        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        // The re-run returns the PRIMARY-only and SECONDARY-only series
        // separately, exactly like `cmd_run`'s two backends; the evaluator
        // rebuilds the interleaved series itself.
        let primary_rerun = vec![1.0, 0.5];
        let secondary_rerun = vec![1.0000005, 0.5000001];
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, target, _| {
                assert_eq!(
                    target,
                    Some("rust"),
                    "the rerun closure must receive the secondary target from the sealed block"
                );
                let mut observation = rerun(primary_rerun.clone());
                observation.secondary = Some(SecondaryObservation {
                    parsed: ParsedSeries {
                        series: secondary_rerun.clone(),
                        any_parsed: true,
                        diverged: false,
                    },
                    exit_code: 0,
                    raw_stdout_digest: hex_digest('3'),
                    executable_digest: hex_digest('2'),
                    // Matches cross_backend_block()'s sealed toolchain facts:
                    // a faithful round trip probes the SAME rustc it was
                    // sealed under.
                    probed_toolchain_version: "rustc 1.0.0 (test)".to_string(),
                    probed_toolchain_digest: hex_digest('1'),
                });
                Ok(observation)
            },
        );
        assert!(
            result.is_ok(),
            "a faithful cross-backend receipt must verify: {result:?}"
        );
    }

    #[test]
    fn cross_backend_evaluator_fails_a_genuine_divergence() {
        // Row 0 disagrees: 1.0 vs 1.1 is far outside the cross-backend
        // tolerance (1e-5). This is the family's can-it-fail evidence at the
        // evaluator level: a genuine cross-backend divergence FAILs.
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.1, 0.5, 0.5];
        let receipt = build_scientific_runtime_receipt(cross_backend_inputs(
            path,
            series.clone(),
            true,
            false,
        ));
        assert_eq!(receipt.receipt_status, "FAIL_UNEXPECTED");
        assert_eq!(receipt.invariant.status, "FAIL");
        assert_eq!(receipt.invariant.observed.violation_count, 1);
        assert_eq!(receipt.invariant.observed.first_violation_step, Some(0));

        // The negative-fixture variant of the exact same divergent series is
        // FAIL_EXPECTED, not FAIL_UNEXPECTED.
        let negative =
            build_scientific_runtime_receipt(cross_backend_inputs(path, series, true, true));
        assert_eq!(negative.receipt_status, "FAIL_EXPECTED");
    }

    #[test]
    fn verify_enforces_the_cross_backend_admission_contracts() {
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.0000005, 0.5, 0.5000001];
        let receipt =
            build_scientific_runtime_receipt(cross_backend_inputs(path, series, true, false));

        fn run(receipt: &ScientificRuntimeReceipt) -> Result<(), i32> {
            let value = serde_json::to_value(receipt).expect("to_value");
            let sd = receipt.source_digest.clone();
            let gd = receipt.input_graph_digest.clone();
            verify_scientific_runtime_receipt(
                &value,
                None,
                true,
                &receipt.compiler_version,
                &receipt.language_version,
                Some(&test_toolchain()),
                move |_| Ok(rederive_facts(sd.clone(), gd.clone())),
                |_, _, _, _, _| {
                    panic!("a biconditional or shape violation must be refused before any re-run")
                },
            )
        }

        // A cross_backend block attached to a receipt whose invariant is NOT
        // cross-backend: refused (block without the invariant).
        let mut block_without_invariant =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        block_without_invariant.cross_backend = Some(cross_backend_block());
        seal_receipt(&mut block_without_invariant);
        assert_eq!(
            run(&block_without_invariant),
            Err(1),
            "a cross_backend block without the cross-backend invariant must be refused"
        );

        // The cross-backend invariant with NO block: refused (invariant
        // without the block).
        let mut invariant_without_block = receipt.clone();
        invariant_without_block.cross_backend = None;
        seal_receipt(&mut invariant_without_block);
        assert_eq!(
            run(&invariant_without_block),
            Err(1),
            "the cross-backend invariant without its block must be refused"
        );

        // An unsupported secondary target is refused.
        let mut wrong_target = receipt.clone();
        wrong_target
            .cross_backend
            .as_mut()
            .unwrap()
            .secondary_target = "vulkan".to_string();
        seal_receipt(&mut wrong_target);
        assert_eq!(
            run(&wrong_target),
            Err(1),
            "an unsupported secondary_target must be refused"
        );

        // A non-EXECUTED status is refused (this block witnesses a run that
        // actually happened; it is not author-DECLARED like monte_carlo/budget).
        let mut wrong_status = receipt.clone();
        wrong_status.cross_backend.as_mut().unwrap().status = "DECLARED".to_string();
        seal_receipt(&mut wrong_status);
        assert_eq!(
            run(&wrong_status),
            Err(1),
            "a non-EXECUTED cross_backend.status must be refused"
        );
    }

    #[test]
    fn verify_refuses_a_cross_backend_receipt_over_a_random_kernel() {
        // I-1 from the final-stack review: emit refuses `--cross-backend` on a
        // Random-observing kernel (main.rs) because the Rust lane has no
        // seeded PRNG builtin, so the two streams could not agree. Verify had
        // no mirror -- a hand-built, correctly re-sealed receipt pairing
        // cross_backend with a seeded Random effect policy passed every other
        // field-contract gate and was only caught deep in the re-run, when
        // rustc failed on the undefined `build_random_f64` symbol
        // (misclassified RERUN_FAILED instead of FIELD_CONTRACT_VIOLATION).
        // This test builds exactly that receipt through the real builder --
        // a Random-including effect policy, a sealed seed, AND a cross_backend
        // block -- and asserts it is refused before any re-run is attempted.
        fn random_policy() -> ScientificEffectPolicy {
            ScientificEffectPolicy {
                facts_digest: hex_digest('9'),
                observed_capabilities: vec!["Console".to_string(), "Random".to_string()],
                reads_stdin: false,
            }
        }
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.0000005, 0.5, 0.5000001];
        let receipt = build_scientific_runtime_receipt(ScientificReceiptInputs {
            effect_policy: random_policy(),
            seed_value: Some(42),
            ..cross_backend_inputs(path, series, true, false)
        });
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            move |_| {
                Ok(RederivedFacts {
                    source_digest: sd,
                    input_graph_digest: gd,
                    effect_policy: random_policy(),
                })
            },
            |_, _, _, _, _| panic!("must be refused before the re-run"),
        );
        assert_eq!(
            result,
            Err(1),
            "a cross_backend receipt over a re-derived Random kernel must be refused"
        );
    }

    #[test]
    fn verify_passes_none_as_the_secondary_target_when_no_cross_backend_block() {
        // A receipt with no cross_backend block still verifies, and the
        // rerun closure must be handed `None` as the fourth argument.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        assert!(receipt.cross_backend.is_none());
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, target, _| {
                assert_eq!(
                    target, None,
                    "a receipt without a cross_backend block must pass None as the secondary target"
                );
                Ok(rerun(vec![4.0, 3.0, 2.0]))
            },
        );
        assert!(
            result.is_ok(),
            "a plain receipt must still verify: {result:?}"
        );
    }

    #[test]
    fn verify_rejects_a_cross_backend_length_mismatch() {
        // The primary and secondary re-run series must agree in length
        // BEFORE the interleaved verdict series is rebuilt: this is the
        // covering assertion for the length-mismatch interleave refusal
        // (mutation check 6b). The primary re-run stays at the SEALED
        // length (2), and the secondary re-run carries one EXTRA value (3):
        // a naive `.zip()`-truncate (dropping the length guard) would
        // silently produce an interleaved series whose length coincidentally
        // still matches the sealed `measurement.count` (4), so the generic
        // downstream count-drift check alone would NOT catch this mutation;
        // only the dedicated length-mismatch guard does, which is exactly
        // what makes this the discriminating test for it.
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.0000005, 0.5, 0.5000001];
        let receipt =
            build_scientific_runtime_receipt(cross_backend_inputs(path, series, true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, target, _| {
                assert_eq!(target, Some("rust"));
                let mut observation = rerun(vec![1.0, 0.5]);
                observation.secondary = Some(SecondaryObservation {
                    // Three values instead of two: the primary and
                    // secondary re-run series lengths disagree.
                    parsed: ParsedSeries {
                        series: vec![1.0000005, 0.5000001, 0.7],
                        any_parsed: true,
                        diverged: false,
                    },
                    exit_code: 0,
                    raw_stdout_digest: hex_digest('3'),
                    executable_digest: hex_digest('2'),
                    probed_toolchain_version: "rustc 1.0.0 (test)".to_string(),
                    probed_toolchain_digest: hex_digest('1'),
                });
                Ok(observation)
            },
        );
        assert_eq!(
            result,
            Err(1),
            "a primary/secondary re-run length mismatch must be refused"
        );
    }

    #[test]
    fn verify_reports_secondary_toolchain_matched_when_probe_agrees_with_the_seal() {
        // Finding 1 (secondary toolchain visibility parity): the freshly
        // probed secondary (rust) toolchain facts, threaded through
        // SecondaryObservation, are compared against the sealed
        // cross_backend.secondary_toolchain_digest. A matching probe (the
        // common case: the same rustc that sealed the receipt re-executes it
        // at verify) reports secondary_toolchain_matched=true, and verify
        // still Oks (this flag never fails verify by itself, mirroring the
        // primary's toolchain_matched).
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.0000005, 0.5, 0.5000001];
        let receipt =
            build_scientific_runtime_receipt(cross_backend_inputs(path, series, true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let report = evaluate_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, target, _| {
                assert_eq!(target, Some("rust"));
                let mut observation = rerun(vec![1.0, 0.5]);
                observation.secondary = Some(SecondaryObservation {
                    parsed: ParsedSeries {
                        series: vec![1.0000005, 0.5000001],
                        any_parsed: true,
                        diverged: false,
                    },
                    exit_code: 0,
                    raw_stdout_digest: hex_digest('3'),
                    executable_digest: hex_digest('2'),
                    // Matches cross_backend_block()'s sealed
                    // secondary_toolchain_digest exactly.
                    probed_toolchain_version: "rustc 1.0.0 (test)".to_string(),
                    probed_toolchain_digest: hex_digest('1'),
                });
                Ok(observation)
            },
        )
        .expect("a faithful cross-backend receipt with a matching secondary toolchain must verify");
        assert!(
            report.secondary_toolchain_matched,
            "a probed rustc matching the sealed digest must report secondary_toolchain_matched=true"
        );
    }

    #[test]
    fn verify_warns_but_still_matches_on_a_mismatched_secondary_toolchain() {
        // The mirror case: the probed rustc's version-output digest
        // DISAGREES with the sealed cross_backend.secondary_toolchain_digest
        // (e.g. a substituted RUSTC pointed at a different or fabricating
        // binary, or a legitimate different-toolchain re-verification
        // environment). By design this WARNS -- the evaluator's
        // `if !secondary_toolchain_matched { eprintln!(...) }` fires, naming
        // both the sealed and the local version line; not captured by this
        // test, which asserts the machine-readable signal instead -- and
        // does NOT fail verify (cross-toolchain re-verification stays
        // legitimate by design, exactly like the primary C lane's
        // toolchain_matched). The mismatch is instead surfaced through
        // secondary_toolchain_matched=false on the returned report, closing
        // the visibility gap the review flagged: before this fix, a
        // substituted rustc's identity was silently discarded after
        // compiling, with zero warning and zero visibility.
        let path = Path::new("k.bld");
        let series = vec![1.0, 1.0000005, 0.5, 0.5000001];
        let receipt =
            build_scientific_runtime_receipt(cross_backend_inputs(path, series, true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let sd = receipt.source_digest.clone();
        let gd = receipt.input_graph_digest.clone();
        let report = evaluate_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(sd.clone(), gd.clone())),
            |_, _, _, target, _| {
                assert_eq!(target, Some("rust"));
                let mut observation = rerun(vec![1.0, 0.5]);
                observation.secondary = Some(SecondaryObservation {
                    parsed: ParsedSeries {
                        series: vec![1.0000005, 0.5000001],
                        any_parsed: true,
                        diverged: false,
                    },
                    exit_code: 0,
                    raw_stdout_digest: hex_digest('3'),
                    executable_digest: hex_digest('2'),
                    // DISAGREES with cross_backend_block()'s sealed digest
                    // (hex_digest('1')): simulates a substituted rustc.
                    probed_toolchain_version: "rustc 9.9.9 (substituted)".to_string(),
                    probed_toolchain_digest: hex_digest('9'),
                });
                Ok(observation)
            },
        )
        .expect(
            "a mismatched secondary toolchain must WARN, not fail: cross-toolchain \
             re-verification stays legitimate by design",
        );
        assert!(
            !report.secondary_toolchain_matched,
            "a probed rustc differing from the sealed digest must report secondary_toolchain_matched=false"
        );
    }

    #[test]
    fn verify_rejects_effect_policy_drift() {
        // The sealed capability union disagrees with what the checker
        // re-derives from source: EFFECT_POLICY_DRIFT, exit 1. This is the
        // "type/effect policy" field being genuinely re-derived.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| {
                let mut facts = rederive_facts(src_digest.clone(), graph_digest.clone());
                // The re-derivation now observes an extra capability.
                facts
                    .effect_policy
                    .observed_capabilities
                    .push("FileSystem".to_string());
                facts.effect_policy.facts_digest = hex_digest('8');
                Ok(facts)
            },
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(result, Err(1), "effect-policy drift must fail verify");
    }

    #[test]
    fn verify_rejects_witnessed_fields_that_do_not_rederive() {
        // The sealed input_dataset claims NONE_WITNESSED but was edited (and
        // resealed) while the capabilities say otherwise... here simulated by
        // editing the sealed determinism flag: the fields must re-derive from
        // the re-derived capabilities, not merely be internally consistent.
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.determinism.deterministic_modulo_args = false;
        receipt.determinism.grounds = "edited".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "witnessed fields that do not re-derive must fail verify"
        );
    }

    #[test]
    fn verify_rejects_field_contract_violations() {
        // A seed status other than NOT_APPLICABLE claims a capability the
        // language does not have (no RNG builtin in v0).
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.seed.status = "RECORDED".to_string();
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "an inexpressible seed status must be rejected"
        );

        // A DECLARED method with no description is internally inconsistent.
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.numerical_method.status = "DECLARED".to_string();
        receipt.numerical_method.description = None;
        seal_receipt(&mut receipt);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "an inconsistent numerical_method must be rejected"
        );
    }

    #[test]
    fn verify_checks_the_seal_before_interpreting_fields() {
        // The C5 ordering contract: an UNSEALED edit to a field is caught by
        // the integrity gate (SEAL_MISMATCH) rather than by whichever
        // field-level contradiction it happens to trip first. Here the seed
        // status is edited to an inexpressible value WITHOUT resealing: the
        // receipt no longer re-seals, so it is rejected as tampering, not as a
        // FIELD_CONTRACT_VIOLATION. (The validly-sealed contradiction is the
        // separate `verify_rejects_field_contract_violations` case, which
        // reseals and therefore reaches the field-contract check - proving
        // that check stays reachable after the seal gate.)
        let path = Path::new("k.bld");
        let mut receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        receipt.seed.status = "RECORDED".to_string();
        // Deliberately do NOT reseal.
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| panic!("an unsealed receipt must be rejected before any re-run"),
        );
        assert_eq!(result, Err(1), "an unsealed field edit must be rejected");
    }

    #[test]
    fn verify_fails_with_exit_4_when_no_toolchain_is_available() {
        // No C compiler is its own verdict (TOOL_UNAVAILABLE, exit 4),
        // distinct from drift (1) and faithful-fail (3), checked BEFORE any
        // re-run attempt.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            None,
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| panic!("the re-run must never be attempted without a toolchain"),
        );
        assert_eq!(result, Err(4), "a missing toolchain must exit 4");
    }

    #[test]
    fn verify_warns_but_proceeds_on_a_different_toolchain() {
        // Cross-toolchain re-verification is legitimate by design: a
        // different-but-present toolchain WARNs and the verdict re-check
        // proceeds to a faithful pass.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let mut other = test_toolchain();
        other.c_compiler = "other-cc".to_string();
        other.version_output_digest = hex_digest('9');
        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&other),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0, 2.0])),
        );
        assert!(
            result.is_ok(),
            "a different toolchain must warn, not fail: {result:?}"
        );
    }

    #[test]
    fn verify_rejects_an_exit_code_drift() {
        // The sealed exit code is deterministic; a re-run exiting differently
        // (including a crash) is non-reproduction with its own class, checked
        // before any series comparison.
        let path = Path::new("k.bld");
        let receipt =
            build_scientific_runtime_receipt(base_inputs(path, vec![4.0, 3.0, 2.0], true, false));
        assert_eq!(receipt.runtime_state.exit_code, 0);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            // Same series, but the process exited 9 instead of the sealed 0.
            |_, _, _, _, _| {
                let mut observation = rerun(vec![4.0, 3.0, 2.0]);
                observation.exit_code = 9;
                Ok(observation)
            },
        );
        assert_eq!(result, Err(1), "an exit-code drift must fail verify");
    }

    #[test]
    fn verify_rejects_a_receipt_whose_divergence_does_not_reproduce() {
        // The receipt records divergence, but the re-run completes finite:
        // the recorded blow-up did NOT reproduce, which is genuine
        // non-reproduction -> Err(1), not the faithful-UNVERIFIABLE Err(3).
        let path = Path::new("k.bld");
        let mut inputs = base_inputs(path, vec![4.0, 3.0], true, false);
        inputs.diverged = true;
        let receipt = build_scientific_runtime_receipt(inputs);
        assert_eq!(receipt.receipt_status, "UNVERIFIABLE");
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            // Finite, monotone re-run: no divergence reproduced.
            |_, _, _, _, _| Ok(rerun(vec![4.0, 3.0])),
        );
        assert_eq!(
            result,
            Err(1),
            "a recorded divergence that does not reproduce is non-reproduction"
        );
    }

    #[test]
    fn verify_reruns_with_the_recorded_args() {
        // The re-run must receive the receipt's stored args, so an argv-dependent
        // kernel is reproduced under the same conditions it was emitted with.
        let path = Path::new("k.bld");
        let mut inputs = base_inputs(path, vec![4.0, 3.0, 2.0], true, false);
        inputs.args = vec!["--mode".to_string(), "stable".to_string()];
        let receipt = build_scientific_runtime_receipt(inputs);
        let value = serde_json::to_value(&receipt).expect("to_value");
        let src_digest = receipt.source_digest.clone();
        let graph_digest = receipt.input_graph_digest.clone();

        let result = verify_scientific_runtime_receipt(
            &value,
            None,
            true,
            &receipt.compiler_version,
            &receipt.language_version,
            Some(&test_toolchain()),
            |_| Ok(rederive_facts(src_digest.clone(), graph_digest.clone())),
            |_, args, _, _, _| {
                assert_eq!(
                    args,
                    ["--mode".to_string(), "stable".to_string()],
                    "verify must re-run with the receipt's recorded args"
                );
                Ok(rerun(vec![4.0, 3.0, 2.0]))
            },
        );
        assert!(result.is_ok(), "recorded-args re-run must verify");
    }
}