instinct-cli 0.3.6

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
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
// generated by hxc 1.0.0-acgt-compiler from tests/check_receipt.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:3
use std::io::Write;
// hlx:4
use std::path::{Path, PathBuf};
// hlx:5
use std::process::{Command, Stdio};
// hlx:6
use std::sync::atomic::{AtomicUsize, Ordering};
// hlx:7
use std::time::Duration;
// hlx:8
fn bin() -> &'static str {
    // hlx:9
    env!("CARGO_BIN_EXE_instinct")
    // hlx:10
}
// hlx:11
// ---------------------------------------------------------------- minimal JSON reader for the outputs
// hlx:12
#[derive(Debug, Clone, PartialEq)]
// hlx:13
enum J {
    // hlx:14
    Null,
    // hlx:15
    Bool(bool),
    // hlx:16
    Num(String),
    // hlx:17
    Str(String),
    // hlx:18
    Arr(Vec<J>),
    // hlx:19
    Obj(Vec<(String, J)>),
    // hlx:20
}
// hlx:21
impl J {
    // hlx:22
    fn get(&self, k: &str) -> Option<&J> {
        // hlx:23
        match self {
            // hlx:24
            J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
            // hlx:25
            _ => None,
            // hlx:26
        }
        // hlx:27
    }
    // hlx:28
    fn as_str(&self) -> Option<&str> {
        // hlx:29
        match self {
            // hlx:30
            J::Str(s) => Some(s),
            // hlx:31
            _ => None,
            // hlx:32
        }
        // hlx:33
    }
    // hlx:34
}
// hlx:35
struct P<'a> {
    // hlx:36
    b: &'a [u8],
    // hlx:37
    i: usize,
    // hlx:38
}
// hlx:39
impl<'a> P<'a> {
    // hlx:40
    fn ws(&mut self) {
        // hlx:41
        while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
            // hlx:42
            self.i += 1;
            // hlx:43
        }
        // hlx:44
    }
    // hlx:45
    fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
        // hlx:46
        if self.b[self.i..].starts_with(w.as_bytes()) {
            // hlx:47
            self.i += w.len();
            // hlx:48
            Ok(v)
        // hlx:49
        } else {
            // hlx:50
            Err(format!("bad literal at {}", self.i))
            // hlx:51
        }
        // hlx:52
    }
    // hlx:53
    fn hex4(&mut self) -> Result<u32, String> {
        // hlx:54
        let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
        // hlx:55
        let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
        // hlx:56
        self.i += 4;
        // hlx:57
        u32::from_str_radix(h, 16).map_err(|e| e.to_string())
        // hlx:58
    }
    // hlx:59
    fn string(&mut self) -> Result<String, String> {
        // hlx:60
        if self.b.get(self.i) != Some(&b'"') {
            // hlx:61
            return Err(format!("expected string at {}", self.i));
            // hlx:62
        }
        // hlx:63
        self.i += 1;
        // hlx:64
        let mut out: Vec<u8> = Vec::new();
        // hlx:65
        loop {
            // hlx:66
            let c = *self.b.get(self.i).ok_or("unterminated string")?;
            // hlx:67
            self.i += 1;
            // hlx:68
            match c {
                // hlx:69
                b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
                // hlx:70
                b'\\' => {
                    // hlx:71
                    let e = *self.b.get(self.i).ok_or("bad escape")?;
                    // hlx:72
                    self.i += 1;
                    // hlx:73
                    let ch = match e {
                        // hlx:74
                        b'"' => '"',
                        // hlx:75
                        b'\\' => '\\',
                        // hlx:76
                        b'/' => '/',
                        // hlx:77
                        b'b' => '\u{8}',
                        // hlx:78
                        b'f' => '\u{c}',
                        // hlx:79
                        b'n' => '\n',
                        // hlx:80
                        b'r' => '\r',
                        // hlx:81
                        b't' => '\t',
                        // hlx:82
                        b'u' => {
                            // hlx:83
                            let hi = self.hex4()?;
                            // hlx:84
                            if (0xD800..0xDC00).contains(&hi) {
                                // hlx:85
                                if self.b.get(self.i) != Some(&b'\\')
                                    || self.b.get(self.i + 1) != Some(&b'u')
                                {
                                    // hlx:86
                                    return Err("lone surrogate".into());
                                    // hlx:87
                                }
                                // hlx:88
                                self.i += 2;
                                // hlx:89
                                let lo = self.hex4()?;
                                // hlx:90
                                char::from_u32(
                                    0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)),
                                )
                                // hlx:91
                                .ok_or("bad pair")?
                            // hlx:92
                            } else {
                                // hlx:93
                                char::from_u32(hi).ok_or("lone surrogate")?
                                // hlx:94
                            }
                            // hlx:95
                        }
                        // hlx:96
                        _ => return Err("bad escape".into()),
                        // hlx:97
                    };
                    // hlx:98
                    let mut buf = [0u8; 4];
                    // hlx:99
                    out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
                    // hlx:100
                }
                // hlx:101
                _ => out.push(c),
                // hlx:102
            }
            // hlx:103
        }
        // hlx:104
    }
    // hlx:105
    fn val(&mut self) -> Result<J, String> {
        // hlx:106
        self.ws();
        // hlx:107
        match self.b.get(self.i).copied() {
            // hlx:108
            None => Err("eof".into()),
            // hlx:109
            Some(b'{') => {
                // hlx:110
                self.i += 1;
                // hlx:111
                let mut v = Vec::new();
                // hlx:112
                self.ws();
                // hlx:113
                if self.b.get(self.i) == Some(&b'}') {
                    // hlx:114
                    self.i += 1;
                    // hlx:115
                    return Ok(J::Obj(v));
                    // hlx:116
                }
                // hlx:117
                loop {
                    // hlx:118
                    self.ws();
                    // hlx:119
                    let k = self.string()?;
                    // hlx:120
                    self.ws();
                    // hlx:121
                    if self.b.get(self.i) != Some(&b':') {
                        // hlx:122
                        return Err("expected colon".into());
                        // hlx:123
                    }
                    // hlx:124
                    self.i += 1;
                    // hlx:125
                    let x = self.val()?;
                    // hlx:126
                    v.push((k, x));
                    // hlx:127
                    self.ws();
                    // hlx:128
                    match self.b.get(self.i) {
                        // hlx:129
                        Some(b',') => self.i += 1,
                        // hlx:130
                        Some(b'}') => {
                            // hlx:131
                            self.i += 1;
                            // hlx:132
                            return Ok(J::Obj(v));
                            // hlx:133
                        }
                        // hlx:134
                        _ => return Err("bad object".into()),
                        // hlx:135
                    }
                    // hlx:136
                }
                // hlx:137
            }
            // hlx:138
            Some(b'[') => {
                // hlx:139
                self.i += 1;
                // hlx:140
                let mut v = Vec::new();
                // hlx:141
                self.ws();
                // hlx:142
                if self.b.get(self.i) == Some(&b']') {
                    // hlx:143
                    self.i += 1;
                    // hlx:144
                    return Ok(J::Arr(v));
                    // hlx:145
                }
                // hlx:146
                loop {
                    // hlx:147
                    v.push(self.val()?);
                    // hlx:148
                    self.ws();
                    // hlx:149
                    match self.b.get(self.i) {
                        // hlx:150
                        Some(b',') => self.i += 1,
                        // hlx:151
                        Some(b']') => {
                            // hlx:152
                            self.i += 1;
                            // hlx:153
                            return Ok(J::Arr(v));
                            // hlx:154
                        }
                        // hlx:155
                        _ => return Err("bad array".into()),
                        // hlx:156
                    }
                    // hlx:157
                }
                // hlx:158
            }
            // hlx:159
            Some(b'"') => Ok(J::Str(self.string()?)),
            // hlx:160
            Some(b't') => self.lit("true", J::Bool(true)),
            // hlx:161
            Some(b'f') => self.lit("false", J::Bool(false)),
            // hlx:162
            Some(b'n') => self.lit("null", J::Null),
            // hlx:163
            Some(_) => {
                // hlx:164
                let st = self.i;
                // hlx:165
                while self.i < self.b.len()
                    && matches!(
                        self.b[self.i],
                        b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9'
                    )
                {
                    // hlx:166
                    self.i += 1;
                    // hlx:167
                }
                // hlx:168
                if st == self.i {
                    // hlx:169
                    return Err(format!("unexpected byte at {st}"));
                    // hlx:170
                }
                // hlx:171
                Ok(J::Num(
                    String::from_utf8_lossy(&self.b[st..self.i]).into_owned(),
                ))
                // hlx:172
            } // hlx:173
        }
        // hlx:174
    }
    // hlx:175
}
// hlx:176
fn parse_json(s: &str) -> Result<J, String> {
    // hlx:177
    let mut p = P {
        b: s.as_bytes(),
        i: 0,
    };
    // hlx:178
    let v = p.val()?;
    // hlx:179
    p.ws();
    // hlx:180
    if p.i != p.b.len() {
        // hlx:181
        return Err("trailing data".into());
        // hlx:182
    }
    // hlx:183
    Ok(v)
    // hlx:184
}
// hlx:185
fn to_s(j: &J) -> String {
    // hlx:186
    match j {
        // hlx:187
        J::Null => "null".into(),
        // hlx:188
        J::Bool(b) => b.to_string(),
        // hlx:189
        J::Num(n) => n.clone(),
        // hlx:190
        J::Str(s) => format!("{s:?}"),
        // hlx:191
        J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
        // hlx:192
        J::Obj(v) => format!(
            "{{{}}}",
            v.iter()
                .map(|(k, x)| format!("{k:?}:{}", to_s(x)))
                .collect::<Vec<_>>()
                .join(",")
        ),
        // hlx:193
    }
    // hlx:194
}
// hlx:195
// ---------------------------------------------------------------- isolated environment and process runner
// hlx:196
struct Out {
    // hlx:197
    code: Option<i32>,
    // hlx:198
    out: Vec<u8>,
    // hlx:199
    err: Vec<u8>,
    // hlx:200
}
// hlx:201
impl Out {
    // hlx:202
    fn text(&self) -> String {
        // hlx:203
        String::from_utf8_lossy(&self.out).into_owned()
        // hlx:204
    }
    // hlx:205
}
// hlx:206
fn fnv(b: &[u8]) -> u64 {
    // hlx:207
    let mut h = 0xcbf29ce484222325u64;
    // hlx:208
    for x in b {
        // hlx:209
        h ^= *x as u64;
        // hlx:210
        h = h.wrapping_mul(0x100000001b3);
        // hlx:211
    }
    // hlx:212
    h
    // hlx:213
}
// hlx:214
fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
    // hlx:215
    let mut ents: Vec<_> = match std::fs::read_dir(dir) {
        // hlx:216
        Ok(r) => r.filter_map(|e| e.ok()).collect(),
        // hlx:217
        Err(_) => return,
        // hlx:218
    };
    // hlx:219
    ents.sort_by_key(|e| e.file_name());
    // hlx:220
    for e in ents {
        // hlx:221
        let p = e.path();
        // hlx:222
        let rel = p.strip_prefix(base).unwrap().display().to_string();
        // hlx:223
        let md = match std::fs::symlink_metadata(&p) {
            // hlx:224
            Ok(m) => m,
            // hlx:225
            Err(_) => continue,
            // hlx:226
        };
        // hlx:227
        if md.is_dir() {
            // hlx:228
            acc.push(format!("d {rel}"));
            // hlx:229
            walk(base, &p, acc);
        // hlx:230
        } else {
            // hlx:231
            let b = std::fs::read(&p).unwrap_or_default();
            // hlx:232
            acc.push(format!("f {rel} {} {:x}", b.len(), fnv(&b)));
            // hlx:233
        }
        // hlx:234
    }
    // hlx:235
}
// hlx:236
struct Env {
    // hlx:237
    root: PathBuf,
    // hlx:238
}
// hlx:239
impl Env {
    // hlx:240
    fn new(name: &str) -> Env {
        // hlx:241
        static N: AtomicUsize = AtomicUsize::new(0);
        // hlx:242
        let root = std::env::temp_dir().join(format!(
            // hlx:243
            "instinct-check-contract-{}-{}-{name}",
            // hlx:244
            std::process::id(),
            // hlx:245
            N.fetch_add(1, Ordering::Relaxed) // hlx:246
        ));
        // hlx:247
        let _ = std::fs::remove_dir_all(&root);
        // hlx:248
        for d in [
            "home", "data", "local", "cfg", "state", "cache", "cwd", "in",
        ] {
            // hlx:249
            std::fs::create_dir_all(root.join(d)).unwrap();
            // hlx:250
        }
        // hlx:251
        Env { root }
        // hlx:252
    }
    // hlx:253
    fn bank(&self) -> PathBuf {
        // hlx:254
        let base = if cfg!(windows) { "local" } else { "data" };
        // hlx:255
        self.root.join(base).join("instinct").join("bank.hxdb")
        // hlx:256
    }
    // hlx:257
    fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
        // hlx:258
        let p = self.root.join("in").join(name);
        // hlx:259
        std::fs::write(&p, bytes).unwrap();
        // hlx:260
        p
        // hlx:261
    }
    // hlx:262
    fn snapshot(&self) -> Vec<String> {
        // hlx:263
        let mut acc = Vec::new();
        // hlx:264
        walk(&self.root, &self.root, &mut acc);
        // hlx:265
        acc
        // hlx:266
    }
    // hlx:267
    fn exec_env(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)]) -> Out {
        // hlx:268
        let before = self.snapshot();
        // hlx:269
        let mut c = Command::new(bin());
        // hlx:270
        c.args(args)
            // hlx:271
            .current_dir(self.root.join("cwd"))
            // hlx:272
            .env("HOME", self.root.join("home"))
            // hlx:273
            .env("XDG_DATA_HOME", self.root.join("data"))
            // hlx:274
            .env("XDG_CONFIG_HOME", self.root.join("cfg"))
            // hlx:275
            .env("XDG_STATE_HOME", self.root.join("state"))
            // hlx:276
            .env("XDG_CACHE_HOME", self.root.join("cache"))
            // hlx:277
            .env("LOCALAPPDATA", self.root.join("local"))
            // hlx:278
            .env("APPDATA", self.root.join("local"));
        // hlx:279
        for (k, _) in std::env::vars() {
            // hlx:280
            if k.starts_with("INSTINCT_") {
                // hlx:281
                c.env_remove(k);
                // hlx:282
            }
            // hlx:283
        }
        // hlx:284
        for (k, v) in envs {
            // hlx:285
            c.env(k, v);
            // hlx:286
        }
        // hlx:287
        c.stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        // hlx:288
        let mut child = c.spawn().unwrap();
        // hlx:289
        let mut si = child.stdin.take().unwrap();
        // hlx:290
        let data = stdin.to_vec();
        // hlx:291
        let w = std::thread::spawn(move || {
            // hlx:292
            let _ = si.write_all(&data);
            // hlx:293
        });
        // hlx:294
        let (tx, rx) = std::sync::mpsc::channel();
        // hlx:295
        std::thread::spawn(move || {
            // hlx:296
            let _ = tx.send(child.wait_with_output());
            // hlx:297
        });
        // hlx:298
        let o = rx
            .recv_timeout(Duration::from_secs(180))
            .expect("instinct check hung")
            .unwrap();
        // hlx:299
        let _ = w.join();
        // hlx:300
        let after = self.snapshot();
        // hlx:301
        assert_eq!(before, after, "command changed the filesystem: {args:?}");
        // hlx:302
        if std::env::var_os("CHECK_CONTRACT_COUNT").is_some() {
            // hlx:303
            eprintln!("check_contract_exec");
            // hlx:304
        }
        // hlx:305
        Out {
            code: o.status.code(),
            out: o.stdout,
            err: o.stderr,
        }
        // hlx:306
    }
    // hlx:307
    fn exec(&self, args: &[&str], stdin: &[u8]) -> Out {
        // hlx:308
        self.exec_env(args, stdin, &[])
        // hlx:309
    }
    // hlx:310
    fn run(&self, sub: &str, doc: &str) -> Out {
        // hlx:311
        self.exec(&["check", sub, "--input", "-"], doc.as_bytes())
        // hlx:312
    }
    // hlx:313
    fn run_bytes(&self, sub: &str, doc: &[u8]) -> Out {
        // hlx:314
        self.exec(&["check", sub, "--input", "-"], doc)
        // hlx:315
    }
    // hlx:316
}
// hlx:317
impl Drop for Env {
    // hlx:318
    fn drop(&mut self) {
        // hlx:319
        let _ = std::fs::remove_dir_all(&self.root);
        // hlx:320
    }
    // hlx:321
}
// hlx:322
// ---------------------------------------------------------------- output assertions
// hlx:323
fn trunc(s: &str) -> String {
    // hlx:324
    s.chars().take(400).collect()
    // hlx:325
}
// hlx:326
fn obj(o: &Out) -> J {
    // hlx:327
    let t = o.text();
    // hlx:328
    let j = parse_json(t.trim())
        .unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)));
    // hlx:329
    assert!(
        matches!(j, J::Obj(_)),
        "stdout must be one JSON object: {}",
        trunc(&t)
    );
    // hlx:330
    j
    // hlx:331
}
// hlx:332
fn sf<'a>(j: &'a J, k: &str) -> &'a str {
    // hlx:333
    j.get(k)
        .and_then(J::as_str)
        .unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
    // hlx:334
}
// hlx:335
fn names(j: &J) -> Vec<String> {
    // hlx:336
    match j {
        // hlx:337
        J::Arr(v) => v
            .iter()
            .map(|x| x.as_str().expect("array of strings").to_string())
            .collect(),
        // hlx:338
        other => panic!("expected an array, got {}", to_s(other)),
        // hlx:339
    }
    // hlx:340
}
// hlx:341
fn result(o: &Out) -> J {
    // hlx:342
    assert_eq!(o.code, Some(0), "expected exit 0: {}", trunc(&o.text()));
    // hlx:343
    let j = obj(o);
    // hlx:344
    assert_eq!(
        sf(&j, "schema"),
        "instinct.check-result/v1",
        "{}",
        trunc(&o.text())
    );
    // hlx:345
    assert!(
        ["pass", "fail", "abstain"].contains(&sf(&j, "verdict")),
        "{}",
        trunc(&o.text())
    );
    // hlx:346
    assert_eq!(sf(&j, "authorization"), "not_evaluated");
    // hlx:347
    assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
    // hlx:348
    assert!(!sf(&j, "reason").is_empty());
    // hlx:349
    assert!(!sf(&j, "check_id").is_empty());
    // hlx:350
    match j.get("revision") {
        // hlx:351
        Some(J::Num(n)) => assert!(n.parse::<u32>().is_ok(), "revision must be an integer: {n}"),
        // hlx:352
        other => panic!("revision must be a number: {other:?}"),
        // hlx:353
    }
    // hlx:354
    match j.get("steps") {
        // hlx:355
        Some(J::Num(n)) => assert!(
            n.parse::<u64>().is_ok(),
            "steps must be a non-negative integer: {n}"
        ),
        // hlx:356
        other => panic!("steps must be a number: {other:?}"),
        // hlx:357
    }
    // hlx:358
    match j.get("witness") {
        // hlx:359
        Some(J::Null) | Some(J::Str(_)) => {}
        // hlx:360
        other => panic!("witness must be string or null: {other:?}"),
        // hlx:361
    }
    // hlx:362
    let m = names(j.get("missing").expect("missing field"));
    // hlx:363
    let mut sorted = m.clone();
    // hlx:364
    sorted.sort();
    // hlx:365
    sorted.dedup();
    // hlx:366
    assert_eq!(m, sorted, "missing must be sorted and unique");
    // hlx:367
    assert!(
        matches!(j.get("scope"), Some(J::Obj(_))),
        "scope must be an object"
    );
    // hlx:368
    let verdict = sf(&j, "verdict");
    // hlx:369
    if verdict == "pass" || verdict == "abstain" {
        // hlx:370
        assert_eq!(
            j.get("witness"),
            Some(&J::Null),
            "only a failed check has a witness: {}",
            trunc(&o.text())
        );
        // hlx:371
    }
    // hlx:372
    j
    // hlx:373
}
// hlx:374
fn err(o: &Out, ctx: &str) {
    // hlx:375
    assert_eq!(
        o.code,
        Some(2),
        "{ctx}: expected exit 2, stdout={}",
        trunc(&o.text())
    );
    // hlx:376
    let j = obj(o);
    // hlx:377
    assert_eq!(
        sf(&j, "schema"),
        "instinct.check-error/v1",
        "{ctx}: {}",
        trunc(&o.text())
    );
    // hlx:378
    assert_eq!(sf(&j, "verdict"), "error", "{ctx}");
    // hlx:379
    assert!(!sf(&j, "reason").is_empty(), "{ctx}");
    // hlx:380
    assert_eq!(sf(&j, "authorization"), "not_evaluated", "{ctx}");
    // hlx:381
    assert!(
        o.out.len() <= 65_537,
        "{ctx}: error output must be bounded, got {} bytes",
        o.out.len()
    );
    // hlx:382
}
// hlx:383
#[derive(Clone)]
// hlx:384
struct D {
    // hlx:385
    schema: String,
    // hlx:386
    id: String,
    // hlx:387
    rev: String,
    // hlx:388
    inputs: String,
    // hlx:389
    claim: String,
    // hlx:390
    req: Option<String>,
    // hlx:391
    dscope: Option<String>,
    // hlx:392
    facts: Option<String>,
    // hlx:393
    conds: Option<String>,
    // hlx:394
    scope: Option<String>,
    // hlx:395
}
// hlx:396
fn d(inputs: &str, claim: &str) -> D {
    // hlx:397
    D {
        // hlx:398
        schema: "\"instinct.check/v1\"".into(),
        // hlx:399
        id: "\"t1\"".into(),
        // hlx:400
        rev: "1".into(),
        // hlx:401
        inputs: inputs.into(),
        // hlx:402
        claim: claim.into(),
        // hlx:403
        req: None,
        // hlx:404
        dscope: None,
        // hlx:405
        facts: None,
        // hlx:406
        conds: None,
        // hlx:407
        scope: None,
        // hlx:408
    }
    // hlx:409
}
// hlx:410
impl D {
    // hlx:411
    fn facts(mut self, s: &str) -> D {
        // hlx:412
        self.facts = Some(s.into());
        // hlx:413
        self
        // hlx:414
    }
    // hlx:415
    fn conds(mut self, s: &str) -> D {
        // hlx:416
        self.conds = Some(s.into());
        // hlx:417
        self
        // hlx:418
    }
    // hlx:419
    fn scope(mut self, s: &str) -> D {
        // hlx:420
        self.scope = Some(s.into());
        // hlx:421
        self
        // hlx:422
    }
    // hlx:423
    fn dscope(mut self, s: &str) -> D {
        // hlx:424
        self.dscope = Some(s.into());
        // hlx:425
        self
        // hlx:426
    }
    // hlx:427
    fn req(mut self, s: &str) -> D {
        // hlx:428
        self.req = Some(s.into());
        // hlx:429
        self
        // hlx:430
    }
    // hlx:431
    fn id(mut self, s: &str) -> D {
        // hlx:432
        self.id = s.into();
        // hlx:433
        self
        // hlx:434
    }
    // hlx:435
    fn rev(mut self, s: &str) -> D {
        // hlx:436
        self.rev = s.into();
        // hlx:437
        self
        // hlx:438
    }
    // hlx:439
    fn json(&self) -> String {
        // hlx:440
        let mut c = format!(
            // hlx:441
            "{{\"schema\":{},\"id\":{},\"revision\":{},\"inputs\":{},\"claim\":{}",
            // hlx:442
            self.schema,
            self.id,
            self.rev,
            self.inputs,
            self.claim // hlx:443
        );
        // hlx:444
        if let Some(r) = &self.req {
            // hlx:445
            c.push_str(&format!(",\"required_conditions\":{r}"));
            // hlx:446
        }
        // hlx:447
        if let Some(s) = &self.dscope {
            // hlx:448
            c.push_str(&format!(",\"scope\":{s}"));
            // hlx:449
        }
        // hlx:450
        c.push('}');
        // hlx:451
        let mut t = format!("{{\"check\":{c}");
        // hlx:452
        if let Some(f) = &self.facts {
            // hlx:453
            t.push_str(&format!(",\"facts\":{f}"));
            // hlx:454
        }
        // hlx:455
        if let Some(f) = &self.conds {
            // hlx:456
            t.push_str(&format!(",\"conditions\":{f}"));
            // hlx:457
        }
        // hlx:458
        if let Some(f) = &self.scope {
            // hlx:459
            t.push_str(&format!(",\"scope\":{f}"));
            // hlx:460
        }
        // hlx:461
        t.push('}');
        // hlx:462
        t
        // hlx:463
    }
    // hlx:464
}
// hlx:465
fn fact(n: &str) -> String {
    // hlx:466
    format!("{{\"fact\":\"{n}\"}}")
    // hlx:467
}
// hlx:468
fn op2(op: &str, l: &str, r: &str) -> String {
    // hlx:469
    format!(
        "{{\"op\":\"{op}\",\"left\":{},\"right\":{}}}",
        fact(l),
        fact(r)
    )
    // hlx:470
}
// hlx:471
fn all_of(a: &[String]) -> String {
    // hlx:472
    format!("{{\"op\":\"all\",\"args\":[{}]}}", a.join(","))
    // hlx:473
}
// hlx:474
fn any_of(a: &[String]) -> String {
    // hlx:475
    format!("{{\"op\":\"any\",\"args\":[{}]}}", a.join(","))
    // hlx:476
}
// hlx:477
fn not_of(a: &str) -> String {
    // hlx:478
    format!("{{\"op\":\"not\",\"arg\":{a}}}")
    // hlx:479
}
// hlx:480
// the example from the contract, on one line
// hlx:481
const BASE: &str = "{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"artifact-membership\",\"revision\":1,\"inputs\":{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"},\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}},\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"],\"scope\":{\"project\":\"release-lab\"}},\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"allowed\":[\"release.bin\"]},\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}";
// hlx:482
const SET_IN: &str = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"}";
// hlx:483
fn mutate(from: &str, to: &str) -> String {
    // hlx:484
    assert_eq!(
        BASE.matches(from).count(),
        1,
        "mutation anchor must be unique: {from}"
    );
    // hlx:485
    BASE.replacen(from, to, 1)
    // hlx:486
}
// hlx:487
fn set_doc(op: &str, l: &str, r: &str) -> String {
    // hlx:488
    d(SET_IN, &op2(op, "actual", "allowed"))
        .facts(&format!("{{\"actual\":{l},\"allowed\":{r}}}"))
        .json()
    // hlx:489
}
// hlx:490
fn many(n: usize, prefix: &str) -> String {
    // hlx:491
    format!(
        "[{}]",
        (0..n)
            .map(|i| format!("\"{prefix}{i:05}\""))
            .collect::<Vec<_>>()
            .join(",")
    )
    // hlx:492
}
// hlx:493
// ================================================================ independent oracle (from docs/check-receipt-wire.md)
// hlx:494
fn sha256(data: &[u8]) -> [u8; 32] {
    // hlx:495
    const K: [u32; 64] = [
        // hlx:496
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, // hlx:497
        0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
        0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, // hlx:498
        0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3,
        0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, // hlx:499
        0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, // hlx:500
        0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c,
        0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, // hlx:501
        0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb,
        0xbef9a3f7, 0xc67178f2,
        // hlx:502
    ];
    // hlx:503
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
        0x5be0cd19,
    ];
    // hlx:504
    let mut msg = data.to_vec();
    // hlx:505
    let bits = (data.len() as u64).wrapping_mul(8);
    // hlx:506
    msg.push(0x80);
    // hlx:507
    while msg.len() % 64 != 56 {
        // hlx:508
        msg.push(0);
        // hlx:509
    }
    // hlx:510
    msg.extend_from_slice(&bits.to_be_bytes());
    // hlx:511
    for chunk in msg.chunks(64) {
        // hlx:512
        let mut w = [0u32; 64];
        // hlx:513
        for i in 0..16 {
            // hlx:514
            w[i] = u32::from_be_bytes([
                chunk[4 * i],
                chunk[4 * i + 1],
                chunk[4 * i + 2],
                chunk[4 * i + 3],
            ]);
            // hlx:515
        }
        // hlx:516
        for i in 16..64 {
            // hlx:517
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            // hlx:518
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            // hlx:519
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
            // hlx:520
        }
        // hlx:521
        let mut v = h;
        // hlx:522
        for i in 0..64 {
            // hlx:523
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            // hlx:524
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            // hlx:525
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            // hlx:526
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            // hlx:527
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            // hlx:528
            let t2 = s0.wrapping_add(maj);
            // hlx:529
            v[7] = v[6];
            // hlx:530
            v[6] = v[5];
            // hlx:531
            v[5] = v[4];
            // hlx:532
            v[4] = v[3].wrapping_add(t1);
            // hlx:533
            v[3] = v[2];
            // hlx:534
            v[2] = v[1];
            // hlx:535
            v[1] = v[0];
            // hlx:536
            v[0] = t1.wrapping_add(t2);
            // hlx:537
        }
        // hlx:538
        for i in 0..8 {
            // hlx:539
            h[i] = h[i].wrapping_add(v[i]);
            // hlx:540
        }
        // hlx:541
    }
    // hlx:542
    let mut out = [0u8; 32];
    // hlx:543
    for i in 0..8 {
        // hlx:544
        out[4 * i..4 * i + 4].copy_from_slice(&h[i].to_be_bytes());
        // hlx:545
    }
    // hlx:546
    out
    // hlx:547
}
// hlx:548
fn hex(b: &[u8]) -> String {
    // hlx:549
    b.iter().map(|x| format!("{x:02x}")).collect()
    // hlx:550
}
// hlx:551
fn is_hex64(s: &str) -> bool {
    // hlx:552
    s.len() == 64 && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
    // hlx:553
}
// hlx:554
fn put_len(out: &mut Vec<u8>, n: usize) {
    // hlx:555
    out.extend_from_slice(&(n as u64).to_be_bytes());
    // hlx:556
}
// hlx:557
// typed, length-framed binary encoding: Null 0, Bool 1+byte, Number 2+len+literal, String 3+len+bytes,
// hlx:558
// Array 4+count+elements, Object 5+count+(key as String, value) with keys in Unicode scalar order
// hlx:559
fn enc(j: &J, out: &mut Vec<u8>) {
    // hlx:560
    match j {
        // hlx:561
        J::Null => out.push(0),
        // hlx:562
        J::Bool(b) => {
            // hlx:563
            out.push(1);
            // hlx:564
            out.push(*b as u8);
            // hlx:565
        }
        // hlx:566
        J::Num(n) => {
            // hlx:567
            out.push(2);
            // hlx:568
            put_len(out, n.len());
            // hlx:569
            out.extend_from_slice(n.as_bytes());
            // hlx:570
        }
        // hlx:571
        J::Str(s) => {
            // hlx:572
            out.push(3);
            // hlx:573
            put_len(out, s.len());
            // hlx:574
            out.extend_from_slice(s.as_bytes());
            // hlx:575
        }
        // hlx:576
        J::Arr(v) => {
            // hlx:577
            out.push(4);
            // hlx:578
            put_len(out, v.len());
            // hlx:579
            for x in v {
                // hlx:580
                enc(x, out);
                // hlx:581
            }
            // hlx:582
        }
        // hlx:583
        J::Obj(v) => {
            // hlx:584
            let mut kv = v.clone();
            // hlx:585
            kv.sort_by(|a, b| a.0.cmp(&b.0));
            // hlx:586
            out.push(5);
            // hlx:587
            put_len(out, kv.len());
            // hlx:588
            for (k, x) in kv {
                // hlx:589
                enc(&J::Str(k), out);
                // hlx:590
                enc(&x, out);
                // hlx:591
            }
            // hlx:592
        } // hlx:593
    }
    // hlx:594
}
// hlx:595
fn digest(prefix: &str, j: &J) -> String {
    // hlx:596
    let mut pre = prefix.as_bytes().to_vec();
    // hlx:597
    pre.push(0);
    // hlx:598
    enc(j, &mut pre);
    // hlx:599
    hex(&sha256(&pre))
    // hlx:600
}
// hlx:601
fn strs(j: &J) -> Vec<String> {
    // hlx:602
    match j {
        // hlx:603
        J::Arr(v) => v
            .iter()
            .map(|x| x.as_str().expect("string").to_string())
            .collect(),
        // hlx:604
        other => panic!("{}", to_s(other)),
        // hlx:605
    }
    // hlx:606
}
// hlx:607
// the canonical request: defaults materialized, set facts and required_conditions sorted, everything else as written
// hlx:608
fn canon_request(req: &J) -> J {
    // hlx:609
    let check = req.get("check").expect("check");
    // hlx:610
    let types: Vec<(String, String)> = match check.get("inputs") {
        // hlx:611
        Some(J::Obj(v)) => v
            .iter()
            .map(|(k, t)| (k.clone(), t.as_str().unwrap().to_string()))
            .collect(),
        // hlx:612
        _ => panic!("inputs"),
        // hlx:613
    };
    // hlx:614
    let facts = match req.get("facts") {
        // hlx:615
        Some(J::Obj(v)) => J::Obj(
            // hlx:616
            v.iter()
                // hlx:617
                .map(|(k, x)| {
                    // hlx:618
                    let is_set = types.iter().any(|(n, t)| n == k && t == "set<string>");
                    // hlx:619
                    if is_set {
                        // hlx:620
                        let mut m = strs(x);
                        // hlx:621
                        m.sort();
                        // hlx:622
                        (k.clone(), J::Arr(m.into_iter().map(J::Str).collect()))
                    // hlx:623
                    } else {
                        // hlx:624
                        (k.clone(), x.clone())
                        // hlx:625
                    }
                    // hlx:626
                })
                // hlx:627
                .collect(),
            // hlx:628
        ),
        // hlx:629
        _ => J::Obj(vec![]),
        // hlx:630
    };
    // hlx:631
    let obj_or_empty = |k: &str| req.get(k).cloned().unwrap_or(J::Obj(vec![]));
    // hlx:632
    let mut cv: Vec<(String, J)> = match check {
        // hlx:633
        J::Obj(v) => v
            .iter()
            .filter(|(k, _)| k != "required_conditions" && k != "scope")
            .cloned()
            .collect(),
        // hlx:634
        _ => panic!("check"),
        // hlx:635
    };
    // hlx:636
    let mut rc = check
        .get("required_conditions")
        .map(strs)
        .unwrap_or_default();
    // hlx:637
    rc.sort();
    // hlx:638
    cv.push((
        "required_conditions".into(),
        J::Arr(rc.into_iter().map(J::Str).collect()),
    ));
    // hlx:639
    cv.push((
        "scope".into(),
        check.get("scope").cloned().unwrap_or(J::Obj(vec![])),
    ));
    // hlx:640
    J::Obj(vec![
        // hlx:641
        ("check".into(), J::Obj(cv)),
        // hlx:642
        ("facts".into(), facts),
        // hlx:643
        ("conditions".into(), obj_or_empty("conditions")),
        // hlx:644
        ("scope".into(), obj_or_empty("scope")),
        // hlx:645
    ])
    // hlx:646
}
// hlx:647
fn oracle_input(req_text: &str) -> String {
    // hlx:648
    digest(
        "instinct.check-input/v1",
        &canon_request(&parse_json(req_text).expect("request json")),
    )
    // hlx:649
}
// hlx:650
// the result core is the kernel `run` result without `steps`
// hlx:651
fn oracle_result(run_out: &J) -> String {
    // hlx:652
    match run_out {
        // hlx:653
        J::Obj(v) => digest(
            "instinct.check-result-core/v1",
            &J::Obj(v.iter().filter(|(k, _)| k != "steps").cloned().collect()),
        ),
        // hlx:654
        _ => panic!("result"),
        // hlx:655
    }
    // hlx:656
}
// hlx:657
fn esc_str(s: &str, ascii: bool) -> String {
    // hlx:658
    let mut o = String::from("\"");
    // hlx:659
    for c in s.chars() {
        // hlx:660
        match c {
            // hlx:661
            '"' => o.push_str("\\\""),
            // hlx:662
            '\\' => o.push_str("\\\\"),
            // hlx:663
            '\n' => o.push_str("\\n"),
            // hlx:664
            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
            // hlx:665
            c if ascii && (c as u32) > 0x7e => {
                // hlx:666
                let mut b = [0u16; 2];
                // hlx:667
                for u in c.encode_utf16(&mut b) {
                    // hlx:668
                    o.push_str(&format!("\\u{:04x}", u));
                    // hlx:669
                }
                // hlx:670
            }
            // hlx:671
            c => o.push(c),
            // hlx:672
        }
        // hlx:673
    }
    // hlx:674
    o.push('"');
    // hlx:675
    o
    // hlx:676
}
// hlx:677
fn ser(j: &J, ws: bool, ascii: bool) -> String {
    // hlx:678
    let (sep, colon) = if ws { (",\n  ", " : ") } else { (",", ":") };
    // hlx:679
    match j {
        // hlx:680
        J::Null => "null".into(),
        // hlx:681
        J::Bool(b) => b.to_string(),
        // hlx:682
        J::Num(n) => n.clone(),
        // hlx:683
        J::Str(s) => esc_str(s, ascii),
        // hlx:684
        J::Arr(v) => format!(
            "[{}]",
            v.iter()
                .map(|x| ser(x, ws, ascii))
                .collect::<Vec<_>>()
                .join(sep)
        ),
        // hlx:685
        J::Obj(v) => format!(
            "{{{}}}",
            v.iter()
                .map(|(k, x)| format!("{}{colon}{}", esc_str(k, ascii), ser(x, ws, ascii)))
                .collect::<Vec<_>>()
                .join(sep)
        ),
        // hlx:686
    }
    // hlx:687
}
// hlx:688
fn reorder<T>(mut v: Vec<T>, mode: usize) -> Vec<T> {
    // hlx:689
    match mode {
        // hlx:690
        0 => v.reverse(),
        // hlx:691
        1 => {
            // hlx:692
            if !v.is_empty() {
                // hlx:693
                v.rotate_left(1)
                // hlx:694
            }
            // hlx:695
        }
        // hlx:696
        _ => {
            // hlx:697
            let n = v.len();
            // hlx:698
            if n > 2 {
                // hlx:699
                v.swap(0, n - 1);
                // hlx:700
                v.swap(1, n / 2);
                // hlx:701
            }
            // hlx:702
        } // hlx:703
    }
    // hlx:704
    v
    // hlx:705
}
// hlx:706
// reorder every object's keys and every set-like array (but never the ordered `args` of all/any)
// hlx:707
fn permute(j: &J, mode: usize) -> J {
    // hlx:708
    match j {
        // hlx:709
        J::Obj(v) => J::Obj(
            // hlx:710
            reorder(v.clone(), mode)
                // hlx:711
                .into_iter()
                // hlx:712
                .map(|(k, x)| {
                    // hlx:713
                    let nx = match (&k[..], &x) {
                        // hlx:714
                        ("args", J::Arr(items)) => {
                            J::Arr(items.iter().map(|i| permute(i, mode)).collect())
                        }
                        // hlx:715
                        (_, J::Arr(items)) => J::Arr(reorder(items.clone(), mode)),
                        // hlx:716
                        _ => permute(&x, mode),
                        // hlx:717
                    };
                    // hlx:718
                    (k, nx)
                    // hlx:719
                })
                // hlx:720
                .collect(),
            // hlx:721
        ),
        // hlx:722
        other => other.clone(),
        // hlx:723
    }
    // hlx:724
}
// hlx:725
// ================================================================ CLI helpers
// hlx:726
const MEANING: &str = "matches_recomputed_supplied_facts_not_world_truth";
// hlx:727
fn keys_of(j: &J) -> Vec<String> {
    // hlx:728
    match j {
        // hlx:729
        J::Obj(v) => {
            // hlx:730
            let mut k: Vec<String> = v.iter().map(|(k, _)| k.clone()).collect();
            // hlx:731
            k.sort();
            // hlx:732
            k
            // hlx:733
        }
        // hlx:734
        _ => panic!("object"),
        // hlx:735
    }
    // hlx:736
}
// hlx:737
fn rcpt(o: &Out) -> J {
    // hlx:738
    assert_eq!(o.code, Some(0), "receipt: {}", trunc(&o.text()));
    // hlx:739
    assert!(o.out.len() <= 65_537, "{} bytes", o.out.len());
    // hlx:740
    let j = obj(o);
    // hlx:741
    let mut want = vec![
        "authorization",
        "check_id",
        "evidence_origin",
        "input_sha256",
        "result_sha256",
        "revision",
        "schema",
        "verdict",
        "verifier",
    ];
    // hlx:742
    want.sort();
    // hlx:743
    assert_eq!(
        keys_of(&j),
        want,
        "a receipt has exactly these keys: {}",
        trunc(&o.text())
    );
    // hlx:744
    assert_eq!(sf(&j, "schema"), "instinct.check-receipt/v1");
    // hlx:745
    assert_eq!(sf(&j, "verifier"), "instinct.check-kernel/v1");
    // hlx:746
    assert_eq!(sf(&j, "authorization"), "not_evaluated");
    // hlx:747
    assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
    // hlx:748
    assert!(
        is_hex64(sf(&j, "input_sha256")) && is_hex64(sf(&j, "result_sha256")),
        "{}",
        trunc(&o.text())
    );
    // hlx:749
    assert!(["pass", "fail", "abstain"].contains(&sf(&j, "verdict")));
    // hlx:750
    assert!(!sf(&j, "check_id").is_empty());
    // hlx:751
    assert!(matches!(j.get("revision"), Some(J::Num(n)) if n.parse::<u32>().is_ok()));
    // hlx:752
    let t = o.text();
    // hlx:753
    for bad in [
        "safe_to_release",
        "signature",
        "authenticated",
        "adapter_observed",
        "\"witness\"",
        "\"scope\"",
        "\"facts\"",
    ] {
        // hlx:754
        assert!(
            !t.contains(bad),
            "a receipt must not contain {bad}: {}",
            trunc(&t)
        );
        // hlx:755
    }
    // hlx:756
    j
    // hlx:757
}
// hlx:758
fn replay_doc(req: &str, receipt: &str) -> String {
    // hlx:759
    format!("{{\"request\":{req},\"receipt\":{receipt}}}")
    // hlx:760
}
// hlx:761
fn consistent(o: &Out, verdict: &str, input: &str, result: &str) {
    // hlx:762
    assert_eq!(o.code, Some(0), "replay: {}", trunc(&o.text()));
    // hlx:763
    assert!(o.out.len() <= 65_537);
    // hlx:764
    let j = obj(o);
    // hlx:765
    let mut want = vec![
        "authorization",
        "evidence_origin",
        "input_sha256",
        "meaning",
        "result_sha256",
        "schema",
        "status",
        "verdict",
    ];
    // hlx:766
    want.sort();
    // hlx:767
    assert_eq!(keys_of(&j), want, "{}", trunc(&o.text()));
    // hlx:768
    assert_eq!(sf(&j, "schema"), "instinct.check-replay/v1");
    // hlx:769
    assert_eq!(sf(&j, "status"), "consistent", "{}", trunc(&o.text()));
    // hlx:770
    assert_eq!(sf(&j, "verdict"), verdict);
    // hlx:771
    assert_eq!(sf(&j, "input_sha256"), input);
    // hlx:772
    assert_eq!(sf(&j, "result_sha256"), result);
    // hlx:773
    assert_eq!(sf(&j, "authorization"), "not_evaluated");
    // hlx:774
    assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
    // hlx:775
    assert_eq!(sf(&j, "meaning"), MEANING);
    // hlx:776
}
// hlx:777
fn mismatch(o: &Out, forbidden: &[&str], ctx: &str) {
    // hlx:778
    assert_eq!(o.code, Some(0), "{ctx}: {}", trunc(&o.text()));
    // hlx:779
    assert!(o.out.len() <= 65_537);
    // hlx:780
    let j = obj(o);
    // hlx:781
    assert_eq!(sf(&j, "schema"), "instinct.check-replay/v1", "{ctx}");
    // hlx:782
    assert_eq!(sf(&j, "status"), "mismatch", "{ctx}: {}", trunc(&o.text()));
    // hlx:783
    assert_eq!(sf(&j, "verdict"), "abstain", "{ctx}");
    // hlx:784
    assert_eq!(sf(&j, "reason"), "receipt_mismatch", "{ctx}");
    // hlx:785
    assert_eq!(sf(&j, "authorization"), "not_evaluated");
    // hlx:786
    assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
    // hlx:787
    assert_eq!(sf(&j, "meaning"), MEANING);
    // hlx:788
    let t = o.text();
    // hlx:789
    for f in forbidden {
        // hlx:790
        assert!(
            !t.contains(f),
            "{ctx}: a mismatch must not echo {f}: {}",
            trunc(&t)
        );
        // hlx:791
    }
    // hlx:792
}
// hlx:793
struct Made {
    // hlx:794
    receipt: J,
    // hlx:795
    input: String,
    // hlx:796
    result: String,
    // hlx:797
    verdict: String,
    // hlx:798
}
// hlx:799
// receipt for a request, checked against the independent oracle
// hlx:800
fn make(env: &Env, req: &str) -> Made {
    // hlx:801
    let o = env.run("receipt", req);
    // hlx:802
    let r = rcpt(&o);
    // hlx:803
    let run = result(&env.run("run", req));
    // hlx:804
    let input = oracle_input(req);
    // hlx:805
    let res = oracle_result(&run);
    // hlx:806
    assert_eq!(
        sf(&r, "input_sha256"),
        input,
        "input digest must equal the independent oracle for {}",
        trunc(req)
    );
    // hlx:807
    assert_eq!(
        sf(&r, "result_sha256"),
        res,
        "result digest must equal the independent oracle for {}",
        trunc(req)
    );
    // hlx:808
    assert_eq!(sf(&r, "verdict"), sf(&run, "verdict"));
    // hlx:809
    assert_eq!(sf(&r, "check_id"), sf(&run, "check_id"));
    // hlx:810
    assert_eq!(r.get("revision"), run.get("revision"));
    // hlx:811
    Made {
        receipt: r.clone(),
        input,
        result: res,
        verdict: sf(&r, "verdict").to_string(),
    }
    // hlx:812
}
// hlx:813
// a request exercising every type, nested ordered logic, big sets and several conditions
// hlx:814
fn rich() -> String {
    // hlx:815
    let ins = "{\"z\":\"string\",\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"n\":\"int\",\"m\":\"int\",\"b\":\"bool\",\"c\":\"bool\"}";
    // hlx:816
    let claim = all_of(&[
        // hlx:817
        op2("subset", "actual", "allowed"),
        // hlx:818
        op2("contains", "allowed", "z"),
        // hlx:819
        any_of(&[op2("lt", "n", "m"), op2("eq", "b", "c")]),
        // hlx:820
        not_of(&op2("disjoint", "actual", "allowed")),
        // hlx:821
    ]);
    // hlx:822
    d(ins, &claim)
// hlx:823
.id("\"rich-check_1.x\"")
// hlx:824
.rev("7")
// hlx:825
.req("[\"c3\",\"c1\",\"c2\"]")
// hlx:826
.dscope("{\"project\":\"p\",\"persona\":\"q\"}")
// hlx:827
.facts("{\"z\":\"\\u00e9\",\"actual\":[\"d\",\"b\",\"a\",\"\\u00e9\",\"c\"],\"allowed\":[\"e\",\"a\",\"b\",\"d\",\"c\",\"\\u00e9\"],\"n\":\"9007199254740993\",\"m\":\"9007199254740995\",\"b\":true,\"c\":false}")
// hlx:828
.conds("{\"c2\":true,\"c1\":true,\"c3\":true}")
// hlx:829
.scope("{\"project\":\"p\",\"persona\":\"q\",\"machine\":\"m1\"}")
// hlx:830
.json()
    // hlx:831
}
// hlx:832
fn corpus() -> Vec<(&'static str, String)> {
    // hlx:833
    let heavy_sets = {
        // hlx:834
        let n = 4900;
        // hlx:835
        let left = many(n, "m");
        // hlx:836
        let mut rev: Vec<String> = (0..n).map(|i| format!("\"m{i:05}\"")).collect();
        // hlx:837
        rev.reverse();
        // hlx:838
        let sub = op2("subset", "actual", "allowed");
        // hlx:839
        d(
            SET_IN,
            &all_of(&(0..30).map(|_| sub.clone()).collect::<Vec<_>>()),
        )
        // hlx:840
        .facts(&format!(
            "{{\"actual\":{left},\"allowed\":[{}]}}",
            rev.join(",")
        ))
        // hlx:841
        .json()
        // hlx:842
    };
    // hlx:843
    vec![
// hlx:844
("contract example (fail)", BASE.to_string()),
// hlx:845
("pass", mutate("\"allowed\":[\"release.bin\"]", "\"allowed\":[\"scratch.env\",\"release.bin\"]")),
// hlx:846
("abstain: facts omitted", d(SET_IN, &op2("subset", "actual", "allowed")).json()),
// hlx:847
("abstain: one fact missing", d(SET_IN, &op2("subset", "actual", "allowed")).facts("{\"actual\":[\"a\"]}").json()),
// hlx:848
("abstain: condition false", mutate("\"complete-inventory\":true", "\"complete-inventory\":false")),
// hlx:849
("abstain: condition missing", mutate("\"complete-inventory\":true,", "")),
// hlx:850
("abstain: scope mismatch", mutate("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"other\"}}")),
// hlx:851
("abstain: fuel exhaustion", heavy_sets),
// hlx:852
("rich", rich()),
// hlx:853
("ints", d("{\"a\":\"int\",\"b\":\"int\"}", &op2("lt", "a", "b")).facts("{\"a\":\"170141183460469231731687303715884105726\",\"b\":\"170141183460469231731687303715884105727\"}").json()),
// hlx:854
("long exact witness", set_doc("subset", &format!("[\"{}\"]", "w".repeat(5000)), "[]")),
// hlx:855
("unicode set", set_doc("subset", "[\"e\\u0301\",\"\\u00e9\",\"\\ud83d\\ude00\"]", "[\"\\u00e9\"]")),
// hlx:856
("empty sets", set_doc("subset", "[]", "[]")),
// hlx:857
("scope 20k", d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}").scope(&format!("{{\"project\":\"{}\"}}", "p".repeat(20_000))).json()),
// hlx:858
]
    // hlx:859
}
// hlx:860
// ================================================================ the oracle itself
// hlx:861
#[test]
// hlx:862
fn the_independent_sha256_oracle_matches_the_standard_vectors() {
    // hlx:863
    assert_eq!(
        hex(&sha256(b"")),
        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    );
    // hlx:864
    assert_eq!(
        hex(&sha256(b"abc")),
        "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
    );
    // hlx:865
    assert_eq!(
        // hlx:866
        hex(&sha256(
            b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
        )),
        // hlx:867
        "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" // hlx:868
    );
    // hlx:869
    assert_eq!(
        hex(&sha256(&vec![b'a'; 1_000_000])),
        "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
    );
    // hlx:870
    // the framing is exactly as documented: tag, big-endian u64 length, bytes
    // hlx:871
    let mut v = Vec::new();
    // hlx:872
    enc(&J::Str("ab".into()), &mut v);
    // hlx:873
    assert_eq!(v, [3, 0, 0, 0, 0, 0, 0, 0, 2, b'a', b'b']);
    // hlx:874
    let mut v = Vec::new();
    // hlx:875
    enc(
        &J::Obj(vec![
            ("b".into(), J::Bool(true)),
            ("a".into(), J::Num("1".into())),
        ]),
        &mut v,
    );
    // hlx:876
    assert_eq!(
        v,
        [
            5, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 1, b'a', 2, 0, 0, 0, 0, 0, 0, 0, 1,
            b'1', 3, 0, 0, 0, 0, 0, 0, 0, 1, b'b', 1, 1
        ]
    );
    // hlx:877
}
// hlx:878
// ================================================================ receipts
// hlx:879
#[test]
// hlx:880
fn a_receipt_has_exactly_the_documented_keys_and_digests_that_match_the_independent_oracle() {
    // hlx:881
    let env = Env::new("receipt");
    // hlx:882
    for (name, req) in corpus() {
        // hlx:883
        let m = make(&env, &req);
        // hlx:884
        assert!(is_hex64(&m.input) && is_hex64(&m.result), "{name}");
        // hlx:885
        assert_ne!(m.input, m.result, "{name}");
        // hlx:886
    }
    // hlx:887
    let m = make(&env, BASE);
    // hlx:888
    assert_eq!(sf(&m.receipt, "check_id"), "artifact-membership");
    // hlx:889
    assert_eq!(m.receipt.get("revision"), Some(&J::Num("1".into())));
    // hlx:890
    assert_eq!(m.verdict, "fail");
    // hlx:891
}
// hlx:892
#[test]
// hlx:893
fn receipts_are_deterministic_and_identical_from_file_stdin_and_other_machines() {
    // hlx:894
    let a = Env::new("det-a");
    // hlx:895
    let b = Env::new("det-b");
    // hlx:896
    for (name, req) in corpus() {
        // hlx:897
        let x = a.run("receipt", &req);
        // hlx:898
        assert_eq!(x.out, a.run("receipt", &req).out, "{name}");
        // hlx:899
        assert_eq!(x.out, b.run("receipt", &req).out, "{name}");
        // hlx:900
        let f = a.put("req.json", req.as_bytes());
        // hlx:901
        let y = a.exec(&["check", "receipt", "--input", f.to_str().unwrap()], b"");
        // hlx:902
        assert_eq!(x.out, y.out, "{name}: file == stdin");
        // hlx:903
    }
    // hlx:904
}
// hlx:905
#[test]
// hlx:906
fn missing_evidence_gives_an_abstain_receipt_never_a_pass() {
    // hlx:907
    let env = Env::new("abstain");
    // hlx:908
    for (name, req) in corpus() {
        // hlx:909
        if !name.starts_with("abstain") {
            // hlx:910
            continue;
            // hlx:911
        }
        // hlx:912
        let m = make(&env, &req);
        // hlx:913
        assert_eq!(m.verdict, "abstain", "{name}");
        // hlx:914
        let o = env.run("replay", &replay_doc(&req, &ser(&m.receipt, false, false)));
        // hlx:915
        consistent(&o, "abstain", &m.input, &m.result);
        // hlx:916
    }
    // hlx:917
}
// hlx:918
#[test]
// hlx:919
fn malformed_requests_and_output_limit_errors_are_structured_errors_not_receipts() {
    // hlx:920
    let env = Env::new("receipt-errors");
    // hlx:921
    let huge = "w".repeat(100_000);
    // hlx:922
    let bad: Vec<String> = vec![
        // hlx:923
        "".into(),
        // hlx:924
        "{".into(),
        // hlx:925
        "[]".into(),
        // hlx:926
        "{}".into(),
        // hlx:927
        mutate("\"op\":\"subset\"", "\"op\":\"nope\""),
        // hlx:928
        mutate("\"revision\":1", "\"revision\":0"),
        // hlx:929
        mutate("\"revision\":1", "\"revision\":1.0"),
        // hlx:930
        mutate("\"id\":\"artifact-membership\"", "\"id\":\"0bad\""),
        // hlx:931
        mutate(
            "\"actual\":[\"release.bin\",\"scratch.env\"]",
            "\"actual\":[\"a\",\"a\"]",
        ),
        // hlx:932
        mutate(
            "\"actual\":[\"release.bin\",\"scratch.env\"]",
            "\"actual\":\"a\"",
        ),
        // hlx:933
        mutate("\"facts\":{", "\"facts\":{\"ghost\":true,"),
        // hlx:934
        mutate("\"facts\":{", "\"facts\":{\"actual\":[],"),
        // hlx:935
        mutate(
            "\"id\":\"artifact-membership\"",
            "\"id\":\"artifact-membership\",\"\\u0069d\":\"x\"",
        ),
        // hlx:936
        mutate(
            "\"complete-inventory\":true",
            "\"complete-inventory\":\"true\"",
        ),
        // hlx:937
        mutate(
            "\"project\":\"release-lab\"}},\"facts\"",
            "\"env\":\"x\"}},\"facts\"",
        ),
        // hlx:938
        format!("{BASE} x"),
        // hlx:939
        set_doc("subset", "[\"\\ud800\"]", "[]"),
        // hlx:940
        // an output-limit error: the exact witness cannot fit
        // hlx:941
        set_doc("subset", &format!("[\"{huge}\"]"), "[]"),
        // hlx:942
        d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
            .facts("{\"a\":true}")
            .scope(&format!("{{\"project\":\"{}\"}}", "p".repeat(90_000)))
            .json(),
        // hlx:943
    ];
    // hlx:944
    for doc in &bad {
        // hlx:945
        let r = env.run("receipt", doc);
        // hlx:946
        err(&r, &format!("receipt {}", trunc(doc)));
        // hlx:947
        let run = env.run("run", doc);
        // hlx:948
        assert_eq!(
            run.code,
            Some(2),
            "the kernel agrees that this request is an error: {}",
            trunc(doc)
        );
        // hlx:949
        let o = env.run(
            "replay",
            &replay_doc(doc, &ser(&make(&env, BASE).receipt, false, false)),
        );
        // hlx:950
        err(&o, &format!("replay {}", trunc(doc)));
        // hlx:951
    }
    // hlx:952
    let mut padded = BASE.as_bytes().to_vec();
    // hlx:953
    padded.resize(1_048_576, b' ');
    // hlx:954
    assert_eq!(
        env.run_bytes("receipt", &padded).code,
        Some(0),
        "exactly 1 MiB is accepted"
    );
    // hlx:955
    padded.push(b' ');
    // hlx:956
    err(&env.run_bytes("receipt", &padded), "1 MiB + 1");
    // hlx:957
    let mut bytes = BASE.as_bytes().to_vec();
    // hlx:958
    bytes.splice(10..10, [0xffu8]);
    // hlx:959
    err(&env.run_bytes("receipt", &bytes), "invalid UTF-8");
    // hlx:960
}
// hlx:961
// ================================================================ canonical identity
// hlx:962
#[test]
// hlx:963
fn key_order_set_order_whitespace_and_escapes_do_not_change_the_identity() {
    // hlx:964
    let env = Env::new("equiv");
    // hlx:965
    for (name, req) in [("contract", BASE.to_string()), ("rich", rich())] {
        // hlx:966
        let base = make(&env, &req);
        // hlx:967
        let tree = parse_json(&req).unwrap();
        // hlx:968
        let mut variants: Vec<(String, String)> = Vec::new();
        // hlx:969
        for mode in 0..3 {
            // hlx:970
            for (ws, ascii) in [(false, false), (true, false), (false, true), (true, true)] {
                // hlx:971
                variants.push((
                    format!("{name} mode {mode} ws={ws} ascii={ascii}"),
                    ser(&permute(&tree, mode), ws, ascii),
                ));
                // hlx:972
            }
            // hlx:973
        }
        // hlx:974
        for (label, v) in variants {
            // hlx:975
            let m = make(&env, &v);
            // hlx:976
            assert_eq!(m.input, base.input, "{label}: input identity");
            // hlx:977
            assert_eq!(
                m.result, base.result,
                "{label}: result identity (steps are telemetry, not identity)"
            );
            // hlx:978
            assert_eq!(
                ser(&m.receipt, false, false),
                ser(&base.receipt, false, false),
                "{label}"
            );
            // hlx:979
            // a receipt made from the original replays against the permuted request and vice versa
            // hlx:980
            consistent(
                &env.run("replay", &replay_doc(&v, &ser(&base.receipt, false, false))),
                &base.verdict,
                &base.input,
                &base.result,
            );
            // hlx:981
            consistent(
                &env.run("replay", &replay_doc(&req, &ser(&m.receipt, true, true))),
                &base.verdict,
                &base.input,
                &base.result,
            );
            // hlx:982
        }
        // hlx:983
    }
    // hlx:984
}
// hlx:985
#[test]
// hlx:986
fn omitted_defaults_equal_their_explicit_empty_forms() {
    // hlx:987
    let env = Env::new("defaults");
    // hlx:988
    let ins = "{\"a\":\"bool\",\"x\":\"set<string>\"}";
    // hlx:989
    let claim = op2("eq", "a", "a");
    // hlx:990
    let omitted = d(ins, &claim).json();
    // hlx:991
    let explicit = d(ins, &claim)
        .req("[]")
        .dscope("{}")
        .facts("{}")
        .conds("{}")
        .scope("{}")
        .json();
    // hlx:992
    let a = make(&env, &omitted);
    // hlx:993
    let b = make(&env, &explicit);
    // hlx:994
    assert_eq!((a.input.clone(), a.result.clone()), (b.input, b.result));
    // hlx:995
    assert_eq!(a.verdict, "abstain");
    // hlx:996
    // each default individually
    // hlx:997
    for variant in [
        // hlx:998
        d(ins, &claim).req("[]").json(),
        // hlx:999
        d(ins, &claim).dscope("{}").json(),
        // hlx:1000
        d(ins, &claim).facts("{}").json(),
        // hlx:1001
        d(ins, &claim).conds("{}").json(),
        // hlx:1002
        d(ins, &claim).scope("{}").json(),
        // hlx:1003
    ] {
        // hlx:1004
        let m = make(&env, &variant);
        // hlx:1005
        assert_eq!(m.input, a.input, "{}", trunc(&variant));
        // hlx:1006
    }
    // hlx:1007
    // but an empty set is a supplied fact, not a missing one, and a false condition is not a missing one
    // hlx:1008
    let supplied = d(ins, &claim).facts("{\"x\":[]}").json();
    // hlx:1009
    assert_ne!(make(&env, &supplied).input, a.input);
    // hlx:1010
    let c_missing = d(ins, &claim).req("[\"c\"]").json();
    // hlx:1011
    let c_false = d(ins, &claim).req("[\"c\"]").conds("{\"c\":false}").json();
    // hlx:1012
    let c_true = d(ins, &claim).req("[\"c\"]").conds("{\"c\":true}").json();
    // hlx:1013
    let ids = [
        make(&env, &c_missing).input,
        make(&env, &c_false).input,
        make(&env, &c_true).input,
    ];
    // hlx:1014
    assert!(
        ids[0] != ids[1] && ids[1] != ids[2] && ids[0] != ids[2],
        "missing, false and true conditions are three identities"
    );
    // hlx:1015
}
// hlx:1016
#[test]
// hlx:1017
fn every_semantic_change_alters_the_input_identity_even_when_the_verdict_stays_the_same() {
    // hlx:1018
    let env = Env::new("identity");
    // hlx:1019
    let allowed_a = "\"allowed\":[\"release.bin\"]},\"conditions\"";
    // hlx:1020
    let actual_a = "\"actual\":[\"release.bin\",\"scratch.env\"]";
    // hlx:1021
    let cond_a = "\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true}";
    // hlx:1022
    let req_a = "\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"]";
    // hlx:1023
    let claim_a = "\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}";
    // hlx:1024
    let scope_def = "\"scope\":{\"project\":\"release-lab\"}},\"facts\"";
    // hlx:1025
    let scope_req = "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}";
    // hlx:1026
    let variants: Vec<(&str, String)> = vec![
// hlx:1027
("base", BASE.to_string()),
// hlx:1028
("revision 2", mutate("\"revision\":1", "\"revision\":2")),
// hlx:1029
("revision 3", mutate("\"revision\":1", "\"revision\":3")),
// hlx:1030
("check id", mutate("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership2\"")),
// hlx:1031
("fact value, same verdict and witness", mutate(allowed_a, "\"allowed\":[\"release.bin\",\"zzz\"]},\"conditions\"")),
// hlx:1032
("fact value, other witness", mutate(actual_a, "\"actual\":[\"aaa\",\"release.bin\",\"scratch.env\"]")),
// hlx:1033
("fact missing", mutate(allowed_a, "},\"conditions\"").replace(",},\"conditions\"", "},\"conditions\"")),
// hlx:1034
("fact case", mutate(allowed_a, "\"allowed\":[\"Release.bin\"]},\"conditions\"")),
// hlx:1035
("fact trailing space", mutate(allowed_a, "\"allowed\":[\"release.bin \"]},\"conditions\"")),
// hlx:1036
("fact composed unicode", mutate(allowed_a, "\"allowed\":[\"release.bin\",\"\\u00e9\"]},\"conditions\"")),
// hlx:1037
("fact decomposed unicode", mutate(allowed_a, "\"allowed\":[\"release.bin\",\"e\\u0301\"]},\"conditions\"")),
// hlx:1038
("request scope extra dimension", mutate(scope_req, "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"persona\":\"p\"}}")),
// hlx:1039
("request and definition scope extra", mutate(scope_req, "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"persona\":\"p\"}}").replace(scope_def, "\"scope\":{\"project\":\"release-lab\",\"persona\":\"p\"}},\"facts\"")),
// hlx:1040
("scope value (both sides)", BASE.replace("release-lab", "release-lab-2")),
// hlx:1041
("scope value case", BASE.replace("release-lab", "Release-Lab")),
// hlx:1042
("condition false", mutate("\"complete-inventory\":true", "\"complete-inventory\":false")),
// hlx:1043
("condition missing", mutate("\"complete-inventory\":true,", "")),
// hlx:1044
("extra required condition", mutate(req_a, "\"required_conditions\":[\"complete-inventory\",\"explicit-policy\",\"third\"]").replace(cond_a, "\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true,\"third\":true}")),
// hlx:1045
("fewer required conditions", mutate(req_a, "\"required_conditions\":[\"complete-inventory\"]").replace(cond_a, "\"conditions\":{\"complete-inventory\":true}")),
// hlx:1046
("claim operands swapped", mutate(claim_a, "\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"allowed\"},\"right\":{\"fact\":\"actual\"}}")),
// hlx:1047
("claim operator", mutate(claim_a, "\"claim\":{\"op\":\"disjoint\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}")),
// hlx:1048
("claim wrapped in not(not())", mutate(claim_a, "\"claim\":{\"op\":\"not\",\"arg\":{\"op\":\"not\",\"arg\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}}}")),
// hlx:1049
];
    // hlx:1050
    let mut seen: Vec<(String, &str)> = Vec::new();
    // hlx:1051
    let mut made: Vec<Made> = Vec::new();
    // hlx:1052
    for (name, req) in &variants {
        // hlx:1053
        let m = make(&env, req);
        // hlx:1054
        if let Some((_, other)) = seen.iter().find(|(d, _)| *d == m.input) {
            // hlx:1055
            panic!("{name} has the same input identity as {other}");
            // hlx:1056
        }
        // hlx:1057
        seen.push((m.input.clone(), name));
        // hlx:1058
        made.push(m);
        // hlx:1059
    }
    // hlx:1060
    // a receipt never replays as consistent against any other variant
    // hlx:1061
    let base = &made[0];
    // hlx:1062
    for ((name, req), _m) in variants.iter().zip(made.iter()).skip(1) {
        // hlx:1063
        let o = env.run(
            "replay",
            &replay_doc(req, &ser(&base.receipt, false, false)),
        );
        // hlx:1064
        mismatch(&o, &[&base.input, &base.result], name);
        // hlx:1065
    }
    // hlx:1066
    // the same verdict and witness with different facts: equal result identity, different input identity
    // hlx:1067
    let same = &made[4];
    // hlx:1068
    assert_eq!(same.verdict, base.verdict);
    // hlx:1069
    assert_eq!(
        same.result, base.result,
        "result identity excludes steps and raw facts"
    );
    // hlx:1070
    assert_ne!(same.input, base.input);
    // hlx:1071
    // changes that alter the decision alter the result identity
    // hlx:1072
    for i in [1usize, 2, 3, 5, 6, 11, 14, 15, 16, 19, 20] {
        // hlx:1073
        assert_ne!(made[i].result, base.result, "{}", variants[i].0);
        // hlx:1074
    }
    // hlx:1075
}
// hlx:1076
#[test]
// hlx:1077
fn ordered_logic_is_part_of_the_identity() {
    // hlx:1078
    let env = Env::new("ordered");
    // hlx:1079
    let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
    // hlx:1080
    let t = op2("eq", "one", "one");
    // hlx:1081
    let f = op2("eq", "one", "zero");
    // hlx:1082
    let facts = "{\"one\":true,\"zero\":false}";
    // hlx:1083
    let mk = |claim: String| make(&env, &d(ins, &claim).facts(facts).json());
    // hlx:1084
    let tf = mk(all_of(&[t.clone(), f.clone()]));
    // hlx:1085
    let ft = mk(all_of(&[f.clone(), t.clone()]));
    // hlx:1086
    let tf_any = mk(any_of(&[t.clone(), f.clone()]));
    // hlx:1087
    let ft_any = mk(any_of(&[f.clone(), t.clone()]));
    // hlx:1088
    assert_eq!(tf.verdict, ft.verdict, "same verdict");
    // hlx:1089
    assert_ne!(
        tf.input, ft.input,
        "all[T,F] and all[F,T] are different definitions"
    );
    // hlx:1090
    assert_ne!(tf_any.input, ft_any.input);
    // hlx:1091
    assert_ne!(tf.input, tf_any.input);
    // hlx:1092
    // but permuting keys inside the same ordered logic keeps the identity
    // hlx:1093
    let doc = d(ins, &all_of(&[t.clone(), f.clone()])).facts(facts).json();
    // hlx:1094
    let v = ser(&permute(&parse_json(&doc).unwrap(), 0), false, false);
    // hlx:1095
    assert_eq!(make(&env, &v).input, tf.input);
    // hlx:1096
    // the order of args survives permutation of everything else
    // hlx:1097
    let v1 = ser(
        &permute(
            &parse_json(&d(ins, &all_of(&[f.clone(), t.clone()])).facts(facts).json()).unwrap(),
            1,
        ),
        false,
        false,
    );
    // hlx:1098
    assert_eq!(make(&env, &v1).input, ft.input);
    // hlx:1099
}
// hlx:1100
#[test]
// hlx:1101
fn unicode_values_are_exact_and_no_extra_normalization_happens() {
    // hlx:1102
    let env = Env::new("unicode-id");
    // hlx:1103
    let mk = |s: &str| {
        make(
            &env,
            &d("{\"s\":\"string\"}", &op2("eq", "s", "s"))
                .facts(&format!("{{\"s\":\"{s}\"}}"))
                .json(),
        )
        .input
    };
    // hlx:1104
    let composed = mk("\\u00e9");
    // hlx:1105
    assert_eq!(
        composed,
        mk("\u{e9}"),
        "an escape and the raw character are the same scalar"
    );
    // hlx:1106
    assert_ne!(
        composed,
        mk("e\\u0301"),
        "composed and decomposed are different"
    );
    // hlx:1107
    assert_ne!(mk("a"), mk("A"));
    // hlx:1108
    assert_ne!(mk("a"), mk("a "));
    // hlx:1109
    assert_ne!(mk("a b"), mk("a  b"));
    // hlx:1110
    assert_ne!(mk("a\\nb"), mk("a b"));
    // hlx:1111
    assert_ne!(mk("a/b"), mk("a\\\\b"));
    // hlx:1112
    assert_ne!(mk("a/b"), mk("a//b"));
    // hlx:1113
    assert_eq!(mk("a\\/b"), mk("a/b"));
    // hlx:1114
    assert_eq!(mk("\\ud83d\\ude00"), mk("\u{1F600}"));
    // hlx:1115
    assert_ne!(mk(""), mk(" "));
    // hlx:1116
    // set members sort in Unicode scalar order whatever their spelling or position
    // hlx:1117
    let mkset = |items: &str| make(&env, &set_doc("subset", items, "[]")).input;
    // hlx:1118
    let one = mkset("[\"\\u00e9\",\"z\",\"\\ud83d\\ude00\",\"A\",\"a\"]");
    // hlx:1119
    assert_eq!(one, mkset("[\"a\",\"A\",\"\u{1F600}\",\"z\",\"\u{e9}\"]"));
    // hlx:1120
    assert_eq!(
        one,
        mkset("[\"\\ud83d\\ude00\",\"\\u00e9\",\"a\",\"z\",\"A\"]")
    );
    // hlx:1121
    assert_ne!(one, mkset("[\"\\u00e9\",\"z\",\"\\ud83d\\ude00\",\"A\"]"));
    // hlx:1122
    // int identities are the exact canonical strings
    // hlx:1123
    let mki = |a: &str| {
        make(
            &env,
            &d("{\"n\":\"int\"}", &op2("eq", "n", "n"))
                .facts(&format!("{{\"n\":\"{a}\"}}"))
                .json(),
        )
        .input
    };
    // hlx:1124
    assert_ne!(mki("9007199254740992"), mki("9007199254740993"));
    // hlx:1125
    assert_ne!(mki("1"), mki("-1"));
    // hlx:1126
    assert_ne!(mki("0"), mki("1"));
    // hlx:1127
}
// hlx:1128
// ================================================================ replay
// hlx:1129
#[test]
// hlx:1130
fn replay_of_a_matching_receipt_is_consistent_and_says_what_it_does_not_prove() {
    // hlx:1131
    let env = Env::new("replay-ok");
    // hlx:1132
    for (name, req) in corpus() {
        // hlx:1133
        let m = make(&env, &req);
        // hlx:1134
        let doc = replay_doc(&req, &ser(&m.receipt, false, false));
        // hlx:1135
        let o = env.run("replay", &doc);
        // hlx:1136
        consistent(&o, &m.verdict, &m.input, &m.result);
        // hlx:1137
        let t = o.text();
        // hlx:1138
        for bad in [
            "safe_to_release",
            "signature",
            "authenticated",
            "adapter_observed",
            "\"witness\"",
            "\"facts\"",
        ] {
            // hlx:1139
            assert!(!t.contains(bad), "{name}: {bad}");
            // hlx:1140
        }
        // hlx:1141
        // a receipt written by the independent oracle (not by the CLI) is consistent too
        // hlx:1142
        let forged = format!(
// hlx:1143
"{{\"schema\":\"instinct.check-receipt/v1\",\"verifier\":\"instinct.check-kernel/v1\",\"check_id\":{},\"revision\":{},\"input_sha256\":\"{}\",\"result_sha256\":\"{}\",\"verdict\":\"{}\",\"authorization\":\"not_evaluated\",\"evidence_origin\":\"caller_reported\"}}",
// hlx:1144
esc_str(sf(&m.receipt, "check_id"), false),
// hlx:1145
to_s(m.receipt.get("revision").unwrap()),
// hlx:1146
m.input,
// hlx:1147
m.result,
// hlx:1148
m.verdict
// hlx:1149
);
        // hlx:1150
        consistent(
            &env.run("replay", &replay_doc(&req, &forged)),
            &m.verdict,
            &m.input,
            &m.result,
        );
        // hlx:1151
        // spelling of the envelope and of the receipt does not matter
        // hlx:1152
        let pretty = format!(
            "{{\n \"receipt\" : {},\n \"request\" : {}\n}}",
            ser(&m.receipt, true, true),
            ser(&parse_json(&req).unwrap(), true, true)
        );
        // hlx:1153
        consistent(&env.run("replay", &pretty), &m.verdict, &m.input, &m.result);
        // hlx:1154
        let f = env.put("replay.json", doc.as_bytes());
        // hlx:1155
        let via_file = env.exec(&["check", "replay", "--input", f.to_str().unwrap()], b"");
        // hlx:1156
        assert_eq!(via_file.out, o.out, "{name}: file == stdin");
        // hlx:1157
        assert_eq!(env.run("replay", &doc).out, o.out, "{name}: deterministic");
        // hlx:1158
    }
    // hlx:1159
    // a receipt for changed facts that was recomputed is legitimately consistent: replay is not authentication
    // hlx:1160
    let changed = mutate(
        "\"allowed\":[\"release.bin\"]",
        "\"allowed\":[\"release.bin\",\"scratch.env\"]",
    );
    // hlx:1161
    let m = make(&env, &changed);
    // hlx:1162
    consistent(
        &env.run(
            "replay",
            &replay_doc(&changed, &ser(&m.receipt, false, false)),
        ),
        "pass",
        &m.input,
        &m.result,
    );
    // hlx:1163
}
// hlx:1164
#[test]
// hlx:1165
fn any_one_byte_digest_mutation_forgery_or_changed_request_is_a_mismatch_never_consistent() {
    // hlx:1166
    let env = Env::new("replay-bad");
    // hlx:1167
    let m = make(&env, BASE);
    // hlx:1168
    let r = &m.receipt;
    // hlx:1169
    let set = |k: &str, v: J| -> String {
        // hlx:1170
        let mut o = match r {
            // hlx:1171
            J::Obj(kv) => kv.clone(),
            // hlx:1172
            _ => unreachable!(),
            // hlx:1173
        };
        // hlx:1174
        for e in o.iter_mut() {
            // hlx:1175
            if e.0 == k {
                // hlx:1176
                e.1 = v.clone();
                // hlx:1177
            }
            // hlx:1178
        }
        // hlx:1179
        ser(&J::Obj(o), false, false)
        // hlx:1180
    };
    // hlx:1181
    let forbid: Vec<&str> = vec![];
    // hlx:1182
    // flip each hex digit of each digest
    // hlx:1183
    for k in ["input_sha256", "result_sha256"] {
        // hlx:1184
        let orig = sf(r, k).to_string();
        // hlx:1185
        for i in 0..64 {
            // hlx:1186
            let mut b = orig.clone().into_bytes();
            // hlx:1187
            b[i] = if b[i] == b'0' { b'1' } else { b'0' };
            // hlx:1188
            let mutated = String::from_utf8(b).unwrap();
            // hlx:1189
            let o = env.run(
                "replay",
                &replay_doc(BASE, &set(k, J::Str(mutated.clone()))),
            );
            // hlx:1190
            mismatch(&o, &[&mutated, &orig], &format!("{k}[{i}]"));
            // hlx:1191
        }
        // hlx:1192
    }
    // hlx:1193
    // forged fields on an otherwise valid receipt
    // hlx:1194
    let forged: Vec<(&str, String)> = vec![
        // hlx:1195
        ("verdict pass", set("verdict", J::Str("pass".into()))),
        // hlx:1196
        ("verdict abstain", set("verdict", J::Str("abstain".into()))),
        // hlx:1197
        ("check_id", set("check_id", J::Str("other-check".into()))),
        // hlx:1198
        ("revision 2", set("revision", J::Num("2".into()))),
        // hlx:1199
        (
            "revision 2147483647",
            set("revision", J::Num("2147483647".into())),
        ),
        // hlx:1200
        (
            "input digest zeros",
            set("input_sha256", J::Str("0".repeat(64))),
        ),
        // hlx:1201
        (
            "result digest ffs",
            set("result_sha256", J::Str("f".repeat(64))),
        ),
        // hlx:1202
        ("digests swapped", {
            // hlx:1203
            let mut o = match r {
                // hlx:1204
                J::Obj(kv) => kv.clone(),
                // hlx:1205
                _ => unreachable!(),
                // hlx:1206
            };
            // hlx:1207
            let (a, b) = (
                sf(r, "input_sha256").to_string(),
                sf(r, "result_sha256").to_string(),
            );
            // hlx:1208
            for e in o.iter_mut() {
                // hlx:1209
                if e.0 == "input_sha256" {
                    // hlx:1210
                    e.1 = J::Str(b.clone());
                    // hlx:1211
                }
                // hlx:1212
                if e.0 == "result_sha256" {
                    // hlx:1213
                    e.1 = J::Str(a.clone());
                    // hlx:1214
                }
                // hlx:1215
            }
            // hlx:1216
            ser(&J::Obj(o), false, false)
            // hlx:1217
        }),
        // hlx:1218
    ];
    // hlx:1219
    for (name, rc) in &forged {
        // hlx:1220
        mismatch(
            &env.run("replay", &replay_doc(BASE, rc)),
            &["other-check", &m.input, &m.result],
            name,
        );
        // hlx:1221
    }
    // hlx:1222
    // a receipt for one request replayed against another
    // hlx:1223
    let other = mutate(
        "\"allowed\":[\"release.bin\"]",
        "\"allowed\":[\"release.bin\",\"zzz\"]",
    );
    // hlx:1224
    mismatch(
        &env.run("replay", &replay_doc(&other, &ser(r, false, false))),
        &[&m.input, &m.result],
        "different facts, same verdict",
    );
    // hlx:1225
    let other_rev = mutate("\"revision\":1", "\"revision\":2");
    // hlx:1226
    mismatch(
        &env.run("replay", &replay_doc(&other_rev, &ser(r, false, false))),
        &[&m.input, &m.result],
        "different revision",
    );
    // hlx:1227
    // a receipt for a different check whose digests and verdict are right but whose id differs
    // hlx:1228
    let renamed = mutate("\"id\":\"artifact-membership\"", "\"id\":\"renamed\"");
    // hlx:1229
    mismatch(
        &env.run("replay", &replay_doc(&renamed, &ser(r, false, false))),
        &["renamed", &m.input],
        "different id",
    );
    // hlx:1230
    let _ = forbid;
    // hlx:1231
}
// hlx:1232
#[test]
// hlx:1233
fn malformed_receipts_and_envelopes_are_errors_not_mismatches() {
    // hlx:1234
    let env = Env::new("replay-malformed");
    // hlx:1235
    let m = make(&env, BASE);
    // hlx:1236
    let r = ser(&m.receipt, false, false);
    // hlx:1237
    let kv = match &m.receipt {
        // hlx:1238
        J::Obj(kv) => kv.clone(),
        // hlx:1239
        _ => unreachable!(),
        // hlx:1240
    };
    // hlx:1241
    let with = |k: &str, v: Option<J>| -> String {
        // hlx:1242
        let mut o: Vec<(String, J)> = kv.iter().filter(|(n, _)| n != k).cloned().collect();
        // hlx:1243
        if let Some(v) = v {
            // hlx:1244
            o.push((k.to_string(), v));
            // hlx:1245
        }
        // hlx:1246
        ser(&J::Obj(o), false, false)
        // hlx:1247
    };
    // hlx:1248
    let mut bad: Vec<(String, String)> = Vec::new();
    // hlx:1249
    for (k, _) in &kv {
        // hlx:1250
        bad.push((format!("missing {k}"), with(k, None)));
        // hlx:1251
        bad.push((format!("{k} null"), with(k, Some(J::Null))));
        // hlx:1252
        bad.push((format!("{k} array"), with(k, Some(J::Arr(vec![])))));
        // hlx:1253
        bad.push((format!("{k} object"), with(k, Some(J::Obj(vec![])))));
        // hlx:1254
        bad.push((format!("{k} bool"), with(k, Some(J::Bool(true)))));
        // hlx:1255
    }
    // hlx:1256
    for (name, k, v) in [
        // hlx:1257
        (
            "schema v2",
            "schema",
            J::Str("instinct.check-receipt/v2".into()),
        ),
        // hlx:1258
        (
            "schema other",
            "schema",
            J::Str("instinct.check-result/v1".into()),
        ),
        // hlx:1259
        ("schema empty", "schema", J::Str("".into())),
        // hlx:1260
        (
            "schema case",
            "schema",
            J::Str("Instinct.check-receipt/v1".into()),
        ),
        // hlx:1261
        (
            "verifier v2",
            "verifier",
            J::Str("instinct.check-kernel/v2".into()),
        ),
        // hlx:1262
        ("verifier other", "verifier", J::Str("someone-else".into())),
        // hlx:1263
        ("verifier empty", "verifier", J::Str("".into())),
        // hlx:1264
        (
            "authorization granted",
            "authorization",
            J::Str("granted".into()),
        ),
        // hlx:1265
        (
            "authorization allowed",
            "authorization",
            J::Str("allowed".into()),
        ),
        // hlx:1266
        ("authorization empty", "authorization", J::Str("".into())),
        // hlx:1267
        (
            "origin adapter_observed",
            "evidence_origin",
            J::Str("adapter_observed".into()),
        ),
        // hlx:1268
        (
            "origin observed",
            "evidence_origin",
            J::Str("observed".into()),
        ),
        // hlx:1269
        (
            "origin world",
            "evidence_origin",
            J::Str("world_verified".into()),
        ),
        // hlx:1270
        ("verdict error", "verdict", J::Str("error".into())),
        // hlx:1271
        ("verdict PASS", "verdict", J::Str("PASS".into())),
        // hlx:1272
        ("verdict empty", "verdict", J::Str("".into())),
        // hlx:1273
        ("verdict true", "verdict", J::Bool(true)),
        // hlx:1274
        ("id number", "check_id", J::Num("7".into())),
        // hlx:1275
        ("revision string", "revision", J::Str("1".into())),
        // hlx:1276
        ("revision zero", "revision", J::Num("0".into())),
        // hlx:1277
        ("revision negative", "revision", J::Num("-1".into())),
        // hlx:1278
        ("revision too big", "revision", J::Num("2147483648".into())),
        // hlx:1279
        ("revision float", "revision", J::Num("1.0".into())),
        // hlx:1280
        ("revision exponent", "revision", J::Num("1e0".into())),
        // hlx:1281
        ("revision leading zero", "revision", J::Num("01".into())),
        // hlx:1282
        ("input digest short", "input_sha256", J::Str("a".repeat(63))),
        // hlx:1283
        ("input digest long", "input_sha256", J::Str("a".repeat(65))),
        // hlx:1284
        ("input digest empty", "input_sha256", J::Str("".into())),
        // hlx:1285
        (
            "input digest uppercase",
            "input_sha256",
            J::Str(sf(&m.receipt, "input_sha256").to_uppercase()),
        ),
        // hlx:1286
        (
            "input digest non-hex",
            "input_sha256",
            J::Str("g".repeat(64)),
        ),
        // hlx:1287
        (
            "input digest with prefix",
            "input_sha256",
            J::Str(format!("sha256:{}", &sf(&m.receipt, "input_sha256")[..57])),
        ),
        // hlx:1288
        (
            "input digest padded",
            "input_sha256",
            J::Str(format!(" {}", &sf(&m.receipt, "input_sha256")[..63])),
        ),
        // hlx:1289
        (
            "result digest short",
            "result_sha256",
            J::Str("a".repeat(63)),
        ),
        // hlx:1290
        (
            "result digest uppercase",
            "result_sha256",
            J::Str(sf(&m.receipt, "result_sha256").to_uppercase()),
        ),
        // hlx:1291
        (
            "result digest non-hex",
            "result_sha256",
            J::Str("z".repeat(64)),
        ),
        // hlx:1292
        ("result digest number", "result_sha256", J::Num("0".into())),
        // hlx:1293
    ] {
        // hlx:1294
        bad.push((name.to_string(), with(k, Some(v))));
        // hlx:1295
    }
    // hlx:1296
    bad.push(("unknown key".into(), r.replacen('{', "{\"extra\":1,", 1)));
    // hlx:1297
    bad.push((
        "signature key".into(),
        r.replacen('{', "{\"signature\":\"abc\",", 1),
    ));
    // hlx:1298
    bad.push((
        "witness key".into(),
        r.replacen('{', "{\"witness\":\"x\",", 1),
    ));
    // hlx:1299
    bad.push(("scope key".into(), r.replacen('{', "{\"scope\":{},", 1)));
    // hlx:1300
    bad.push((
        "duplicate schema".into(),
        r.replacen('{', "{\"schema\":\"instinct.check-receipt/v1\",", 1),
    ));
    // hlx:1301
    bad.push((
        "duplicate escaped".into(),
        r.replacen('{', "{\"sch\\u0065ma\":\"instinct.check-receipt/v1\",", 1),
    ));
    // hlx:1302
    bad.push((
        "duplicate digest".into(),
        r.replacen(
            '{',
            &format!("{{\"input_sha256\":\"{}\",", sf(&m.receipt, "input_sha256")),
            1,
        ),
    ));
    // hlx:1303
    bad.push((
        "duplicate escaped id".into(),
        r.replacen('{', "{\"check\\u005fid\":\"artifact-membership\",", 1),
    ));
    // hlx:1304
    bad.push(("not an object: array".into(), "[]".into()));
    // hlx:1305
    bad.push(("not an object: string".into(), "\"receipt\"".into()));
    // hlx:1306
    bad.push(("not an object: null".into(), "null".into()));
    // hlx:1307
    bad.push(("empty object".into(), "{}".into()));
    // hlx:1308
    bad.push(("truncated".into(), r[..r.len() - 1].to_string()));
    // hlx:1309
    bad.push(("trailing garbage".into(), format!("{r} x")));
    // hlx:1310
    for (name, rc) in &bad {
        // hlx:1311
        let o = env.run("replay", &replay_doc(BASE, rc));
        // hlx:1312
        err(&o, name);
        // hlx:1313
        assert!(
            !o.text().contains("\"consistent\"") && !o.text().contains("\"mismatch\""),
            "{name}"
        );
        // hlx:1314
    }
    // hlx:1315
    // envelope shape
    // hlx:1316
    let envelope_bad: Vec<(&str, String)> = vec![
        // hlx:1317
        ("missing receipt", format!("{{\"request\":{BASE}}}")),
        // hlx:1318
        ("missing request", format!("{{\"receipt\":{r}}}")),
        // hlx:1319
        (
            "extra key",
            format!("{{\"request\":{BASE},\"receipt\":{r},\"extra\":1}}"),
        ),
        // hlx:1320
        (
            "extra key root",
            format!("{{\"request\":{BASE},\"receipt\":{r},\"root\":\"/tmp\"}}"),
        ),
        // hlx:1321
        (
            "duplicate request",
            format!("{{\"request\":{BASE},\"request\":{BASE},\"receipt\":{r}}}"),
        ),
        // hlx:1322
        (
            "duplicate receipt",
            format!("{{\"request\":{BASE},\"receipt\":{r},\"receipt\":{r}}}"),
        ),
        // hlx:1323
        (
            "duplicate escaped",
            format!("{{\"request\":{BASE},\"receipt\":{r},\"rec\\u0065ipt\":{r}}}"),
        ),
        // hlx:1324
        (
            "request null",
            format!("{{\"request\":null,\"receipt\":{r}}}"),
        ),
        // hlx:1325
        (
            "receipt null",
            format!("{{\"request\":{BASE},\"receipt\":null}}"),
        ),
        // hlx:1326
        (
            "request string",
            format!("{{\"request\":\"x\",\"receipt\":{r}}}"),
        ),
        // hlx:1327
        (
            "receipt string",
            format!("{{\"request\":{BASE},\"receipt\":\"x\"}}"),
        ),
        // hlx:1328
        ("array envelope", format!("[{BASE},{r}]")),
        // hlx:1329
        ("bare request", BASE.to_string()),
        // hlx:1330
        ("bare receipt", r.clone()),
        // hlx:1331
        ("empty", String::new()),
        // hlx:1332
        (
            "invalid request inside",
            replay_doc(&mutate("\"op\":\"subset\"", "\"op\":\"nope\""), &r),
        ),
        // hlx:1333
        (
            "duplicate key inside request",
            replay_doc(
                &mutate(
                    "\"id\":\"artifact-membership\"",
                    "\"id\":\"artifact-membership\",\"id\":\"x\"",
                ),
                &r,
            ),
        ),
        // hlx:1334
    ];
    // hlx:1335
    for (name, doc) in &envelope_bad {
        // hlx:1336
        err(&env.run("replay", doc), name);
        // hlx:1337
    }
    // hlx:1338
    // REVISION NOTE (docs/check-receipt-clarifications.md): the replay envelope alone may carry 1 MiB + 4096 bytes.
    // hlx:1339
    // The original expectation "1 MiB + 1 is an error" applied to the envelope; it now applies at 1 MiB + 4096 + 1.
    // hlx:1340
    let mut padded = replay_doc(BASE, &r).into_bytes();
    // hlx:1341
    padded.resize(1_048_576, b' ');
    // hlx:1342
    consistent(
        &env.run_bytes("replay", &padded),
        "fail",
        &m.input,
        &m.result,
    );
    // hlx:1343
    padded.resize(1_048_576 + 4096, b' ');
    // hlx:1344
    consistent(
        &env.run_bytes("replay", &padded),
        "fail",
        &m.input,
        &m.result,
    );
    // hlx:1345
    padded.push(b' ');
    // hlx:1346
    err(
        &env.run_bytes("replay", &padded),
        "envelope over 1 MiB + 4096",
    );
    // hlx:1347
}
// hlx:1348
// ================================================================ privacy, authority and isolation
// hlx:1349
#[test]
// hlx:1350
fn receipts_and_replays_never_echo_facts_witnesses_scope_or_paths() {
    // hlx:1351
    let env = Env::new("privacy");
    // hlx:1352
    let s = "SECRET_SENTINEL_731";
    // hlx:1353
    let ins = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"note\":\"string\"}";
    // hlx:1354
    let req = d(ins, &op2("subset", "actual", "allowed"))
// hlx:1355
.id("\"public-check-id\"")
// hlx:1356
.dscope(&format!("{{\"project\":\"{s}-proj\"}}"))
// hlx:1357
.facts(&format!("{{\"actual\":[\"{s}-member\",\"/home/user/{s}/path\"],\"allowed\":[],\"note\":\"{s}-note\"}}"))
// hlx:1358
.scope(&format!("{{\"project\":\"{s}-proj\",\"persona\":\"{s}-persona\"}}"))
// hlx:1359
.json();
    // hlx:1360
    let m = make(&env, &req);
    // hlx:1361
    assert_eq!(m.verdict, "fail");
    // hlx:1362
    let run = env.run("run", &req).text();
    // hlx:1363
    assert!(
        run.contains(s),
        "the kernel result itself carries the witness; the receipt must not"
    );
    // hlx:1364
    let rc_text = env.run("receipt", &req).text();
    // hlx:1365
    assert!(
        !rc_text.contains(s) && !rc_text.contains("/home/user"),
        "{rc_text}"
    );
    // hlx:1366
    assert!(
        rc_text.contains("public-check-id"),
        "the public check id is the one allowed identifier"
    );
    // hlx:1367
    let good = replay_doc(&req, &ser(&m.receipt, false, false));
    // hlx:1368
    assert!(!env.run("replay", &good).text().contains(s));
    // hlx:1369
    let other = req.replace(&format!("{s}-note"), "changed");
    // hlx:1370
    let o = env.run(
        "replay",
        &replay_doc(&other, &ser(&m.receipt, false, false)),
    );
    // hlx:1371
    mismatch(&o, &[s, "/home/user", &m.input, &m.result], "changed note");
    // hlx:1372
    // errors do not echo the request either
    // hlx:1373
    let broken = req.replace("\"allowed\":[]", &format!("\"allowed\":\"{s}\""));
    // hlx:1374
    for sub in ["receipt", "replay"] {
        // hlx:1375
        let doc = if sub == "receipt" {
            broken.clone()
        } else {
            replay_doc(&broken, &ser(&m.receipt, false, false))
        };
        // hlx:1376
        let o = env.run(sub, &doc);
        // hlx:1377
        err(&o, sub);
        // hlx:1378
        assert!(!o.text().contains(s), "{sub}: {}", trunc(&o.text()));
        // hlx:1379
    }
    // hlx:1380
}
// hlx:1381
#[test]
// hlx:1382
fn authority_and_origin_are_fixed_and_the_environment_never_changes_a_receipt() {
    // hlx:1383
    let env = Env::new("authority");
    // hlx:1384
    for (name, req) in corpus() {
        // hlx:1385
        let m = make(&env, &req);
        // hlx:1386
        assert_eq!(sf(&m.receipt, "authorization"), "not_evaluated", "{name}");
        // hlx:1387
        assert_eq!(
            sf(&m.receipt, "evidence_origin"),
            "caller_reported",
            "{name}"
        );
        // hlx:1388
    }
    // hlx:1389
    let doc = d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
        .facts("{\"a\":true}")
        .dscope("{\"project\":\"release-lab\"}")
        .json();
    // hlx:1390
    let plain = env.run("receipt", &doc);
    // hlx:1391
    let envs = [
        ("INSTINCT_PROJECT", "release-lab"),
        ("INSTINCT_PERSONA", "p"),
        ("INSTINCT_HARNESS", "h"),
        ("INSTINCT_MACHINE", "m"),
        ("PWD", "/"),
    ];
    // hlx:1392
    let with = env.exec_env(&["check", "receipt", "--input", "-"], doc.as_bytes(), &envs);
    // hlx:1393
    assert_eq!(plain.out, with.out, "no ambient scope");
    // hlx:1394
    assert_eq!(
        sf(&rcpt(&plain), "verdict"),
        "abstain",
        "the definition requires a project that was not supplied"
    );
    // hlx:1395
    let r = rcpt(&with);
    // hlx:1396
    assert_eq!(sf(&r, "verdict"), "abstain");
    // hlx:1397
    // the kernel's own run output still says caller_reported
    // hlx:1398
    assert_eq!(
        sf(&result(&env.run("run", &doc)), "evidence_origin"),
        "caller_reported"
    );
    // hlx:1399
}
// hlx:1400
#[test]
// hlx:1401
fn receipt_and_replay_write_nothing_and_leave_a_bank_alone() {
    // hlx:1402
    let env = Env::new("nowrites");
    // hlx:1403
    std::fs::create_dir_all(env.bank().parent().unwrap()).unwrap();
    // hlx:1404
    std::fs::write(env.bank(), b"\xff\xfenot a bank").unwrap();
    // hlx:1405
    let m = make(&env, BASE);
    // hlx:1406
    let r = ser(&m.receipt, false, false);
    // hlx:1407
    for doc in [BASE.to_string(), "{".to_string()] {
        // hlx:1408
        let _ = env.run("receipt", &doc);
        // hlx:1409
    }
    // hlx:1410
    for doc in [
        replay_doc(BASE, &r),
        replay_doc(BASE, "{}"),
        "{".to_string(),
    ] {
        // hlx:1411
        let _ = env.run("replay", &doc);
        // hlx:1412
    }
    // hlx:1413
    assert_eq!(std::fs::read(env.bank()).unwrap(), b"\xff\xfenot a bank");
    // hlx:1414
    // INSTINCT_STORE pointing nowhere does not matter and nothing is created
    // hlx:1415
    let missing = env.root.join("elsewhere").join("bank.hxdb");
    // hlx:1416
    let o = env.exec_env(
        &["check", "receipt", "--input", "-"],
        BASE.as_bytes(),
        &[("INSTINCT_STORE", missing.to_str().unwrap())],
    );
    // hlx:1417
    assert_eq!(o.code, Some(0));
    // hlx:1418
    assert!(!missing.exists() && !missing.parent().unwrap().exists());
    // hlx:1419
    // the exec wrapper snapshots the whole tree around every call: no temp, sidecar, ledger or journal file appeared
    // hlx:1420
}
// hlx:1421
// ================================================================ CLI shape
// hlx:1422
#[test]
// hlx:1423
fn receipt_and_replay_argument_mistakes_are_errors_and_help_is_side_effect_free() {
    // hlx:1424
    let env = Env::new("cli");
    // hlx:1425
    let f = env.put("req.json", BASE.as_bytes());
    // hlx:1426
    let f = f.to_str().unwrap();
    // hlx:1427
    for sub in ["receipt", "replay"] {
        // hlx:1428
        let rows: Vec<Vec<&str>> = vec![
            // hlx:1429
            vec!["check", sub],
            // hlx:1430
            vec!["check", sub, "--input"],
            // hlx:1431
            vec!["check", sub, "--input", f, "--input", f],
            // hlx:1432
            vec!["check", sub, "--input", "-", "--input", f],
            // hlx:1433
            vec!["check", sub, "--input", f, "extra"],
            // hlx:1434
            vec!["check", sub, f],
            // hlx:1435
            vec!["check", sub, "--bogus"],
            // hlx:1436
            vec!["check", sub, "--input", f, "--bogus"],
            // hlx:1437
            vec!["check", sub, "--root", f, "--input", f],
            // hlx:1438
            vec!["check", sub, "--Input", f],
            // hlx:1439
            vec!["check", sub, "-i", f],
            // hlx:1440
            vec!["check", sub, "--input", f, "--help"],
            // hlx:1441
        ];
        // hlx:1442
        for row in rows {
            // hlx:1443
            let o = env.exec(&row, BASE.as_bytes());
            // hlx:1444
            err(&o, &format!("{row:?}"));
            // hlx:1445
        }
        // hlx:1446
        let o = env.exec(&["check", sub, "--help"], BASE.as_bytes());
        // hlx:1447
        assert_eq!(o.code, Some(0), "check {sub} --help: {}", trunc(&o.text()));
        // hlx:1448
        let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
        // hlx:1449
        assert!(all.contains("--input"), "{sub}: {}", trunc(&all));
        // hlx:1450
        assert!(
            !o.text().contains("check-receipt")
                && !o.text().contains("check-replay")
                && !o.text().contains("check-error"),
            "help is not a result"
        );
        // hlx:1451
    }
    // hlx:1452
    // the legacy commands keep their behavior
    // hlx:1453
    assert_eq!(env.run("run", BASE).code, Some(0));
    // hlx:1454
    assert_eq!(env.run("validate", BASE).code, Some(0));
    // hlx:1455
    assert_eq!(env.run("explain", BASE).code, Some(0));
    // hlx:1456
    err(
        &env.exec(&["check", "run", "--input", f, "--input", f], b""),
        "legacy duplicate",
    );
    // hlx:1457
}
// hlx:1458
// ================================================================ round-trip boundaries (docs/check-receipt-clarifications.md)
// hlx:1459
fn nested_all(k: usize) -> String {
    // hlx:1460
    let mut c = op2("eq", "a", "a");
    // hlx:1461
    for _ in 0..k {
        // hlx:1462
        c = all_of(&[c]);
        // hlx:1463
    }
    // hlx:1464
    d("{\"a\":\"bool\"}", &c).facts("{\"a\":true}").json()
    // hlx:1465
}
// hlx:1466
// a compact request of exactly `total` bytes: one big set fact, a short string fact and a cheap claim
// hlx:1467
fn exact_size_request(total: usize) -> String {
    // hlx:1468
    let n = 9000usize;
    // hlx:1469
    let ins = "{\"actual\":\"set<string>\",\"z\":\"string\"}";
    // hlx:1470
    let claim = op2("contains", "actual", "z");
    // hlx:1471
    let mk = |members: &str| {
        format!("{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"big\",\"revision\":1,\"inputs\":{ins},\"claim\":{claim}}},\"facts\":{{\"actual\":[{members}],\"z\":\"m00001\"}}}}")
    };
    // hlx:1472
    let base = mk("").len();
    // hlx:1473
    let per = (total - base - (n - 1)) / n - 2;
    // hlx:1474
    let member = |i: usize, len: usize| format!("\"m{i:05}{}\"", "x".repeat(len - 6));
    // hlx:1475
    let mut parts: Vec<String> = (0..n).map(|i| member(i, per)).collect();
    // hlx:1476
    let used = mk(&parts.join(",")).len();
    // hlx:1477
    let extra = total - used;
    // hlx:1478
    parts[n - 1] = member(n - 1, per + extra);
    // hlx:1479
    let doc = mk(&parts.join(","));
    // hlx:1480
    assert_eq!(doc.len(), total, "fixture builder");
    // hlx:1481
    doc
    // hlx:1482
}
// hlx:1483
#[test]
// hlx:1484
fn a_valid_request_at_the_nesting_limit_round_trips_through_receipt_and_replay() {
    // hlx:1485
    let env = Env::new("roundtrip-depth");
    // hlx:1486
    // the request nesting limit is 64: 30 nested `all` is the deepest valid shape (the 29-level control is shallower)
    // hlx:1487
    for k in [0usize, 1, 10, 28, 29, 30] {
        // hlx:1488
        let req = nested_all(k);
        // hlx:1489
        let m = make(&env, &req);
        // hlx:1490
        assert_eq!(m.verdict, "pass", "k={k}");
        // hlx:1491
        let o = env.run("replay", &replay_doc(&req, &ser(&m.receipt, false, false)));
        // hlx:1492
        consistent(&o, "pass", &m.input, &m.result);
        // hlx:1493
        // spelled with whitespace and escapes too (whitespace does not count toward nesting)
        // hlx:1494
        let pretty = ser(&parse_json(&req).unwrap(), true, true);
        // hlx:1495
        consistent(
            &env.run("replay", &replay_doc(&pretty, &ser(&m.receipt, true, true))),
            "pass",
            &m.input,
            &m.result,
        );
        // hlx:1496
    }
    // hlx:1497
    // one level deeper is not a valid request, so there is no receipt and replay cannot succeed either
    // hlx:1498
    let valid_receipt = ser(&make(&env, &nested_all(30)).receipt, false, false);
    // hlx:1499
    for k in [31usize, 32, 40] {
        // hlx:1500
        let req = nested_all(k);
        // hlx:1501
        err(&env.run("receipt", &req), &format!("receipt k={k}"));
        // hlx:1502
        err(&env.run("run", &req), &format!("run k={k}"));
        // hlx:1503
        err(
            &env.run("replay", &replay_doc(&req, &valid_receipt)),
            &format!("replay k={k}"),
        );
        // hlx:1504
    }
    // hlx:1505
    // other operators at the same depth
    // hlx:1506
    let mut c = op2("eq", "a", "a");
    // hlx:1507
    for i in 0..30 {
        // hlx:1508
        c = if i % 2 == 0 {
            any_of(&[c])
        } else {
            all_of(&[c])
        };
        // hlx:1509
    }
    // hlx:1510
    let req = d("{\"a\":\"bool\"}", &c).facts("{\"a\":true}").json();
    // hlx:1511
    let m = make(&env, &req);
    // hlx:1512
    consistent(
        &env.run("replay", &replay_doc(&req, &ser(&m.receipt, false, false))),
        "pass",
        &m.input,
        &m.result,
    );
    // hlx:1513
}
// hlx:1514
#[test]
// hlx:1515
fn a_request_of_exactly_one_mebibyte_round_trips_and_one_byte_more_is_still_rejected() {
    // hlx:1516
    let env = Env::new("roundtrip-size");
    // hlx:1517
    let limit = 1_048_576usize;
    // hlx:1518
    let req = exact_size_request(limit);
    // hlx:1519
    assert_eq!(req.len(), limit);
    // hlx:1520
    let m = make(&env, &req);
    // hlx:1521
    let rc = ser(&m.receipt, false, false);
    // hlx:1522
    let doc = replay_doc(&req, &rc);
    // hlx:1523
    assert!(
        doc.len() > limit && doc.len() <= limit + 4096,
        "the envelope overhead is the receipt plus the wrapper: {}",
        doc.len() - limit
    );
    // hlx:1524
    let o = env.run("replay", &doc);
    // hlx:1525
    consistent(&o, &m.verdict, &m.input, &m.result);
    // hlx:1526
    // the same through files
    // hlx:1527
    let f = env.put("replay.json", doc.as_bytes());
    // hlx:1528
    assert_eq!(
        env.exec(&["check", "replay", "--input", f.to_str().unwrap()], b"")
            .out,
        o.out
    );
    // hlx:1529
    let rf = env.put("request.json", req.as_bytes());
    // hlx:1530
    assert_eq!(
        env.exec(&["check", "receipt", "--input", rf.to_str().unwrap()], b"")
            .code,
        Some(0)
    );
    // hlx:1531
    // inner request beyond 1 MiB errors on receipt and inside the larger envelope
    // hlx:1532
    let over = exact_size_request(limit + 1);
    // hlx:1533
    assert_eq!(over.len(), limit + 1);
    // hlx:1534
    err(&env.run("receipt", &over), "receipt over 1 MiB");
    // hlx:1535
    err(&env.run("run", &over), "run over 1 MiB");
    // hlx:1536
    let doc_over = replay_doc(&over, &rc);
    // hlx:1537
    assert!(
        doc_over.len() <= limit + 4096,
        "the envelope itself is within its own cap"
    );
    // hlx:1538
    err(
        &env.run("replay", &doc_over),
        "inner request over 1 MiB inside a legal envelope",
    );
    // hlx:1539
    err(
        &env.run("replay", &replay_doc(&exact_size_request(limit + 64), &rc)),
        "inner request over 1 MiB by 64 bytes",
    );
    // hlx:1540
    // a legal request plus a legal receipt whose outer whitespace exceeds the envelope cap
    // hlx:1541
    let mut padded = doc.into_bytes();
    // hlx:1542
    padded.resize(limit + 4096, b' ');
    // hlx:1543
    assert_eq!(
        env.run_bytes("replay", &padded).code,
        Some(0),
        "exactly at the envelope cap"
    );
    // hlx:1544
    padded.push(b' ');
    // hlx:1545
    err(
        &env.run_bytes("replay", &padded),
        "envelope one byte over its cap",
    );
    // hlx:1546
}
// hlx:1547
#[test]
// hlx:1548
fn only_replay_gets_the_envelope_allowance_and_other_modes_keep_the_ordinary_cap() {
    // hlx:1549
    let env = Env::new("cap-scope");
    // hlx:1550
    let limit = 1_048_576usize;
    // hlx:1551
    for extra in [1usize, 100, 4096] {
        // hlx:1552
        let mut padded = BASE.as_bytes().to_vec();
        // hlx:1553
        padded.resize(limit + extra, b' ');
        // hlx:1554
        for sub in ["receipt", "run", "validate", "explain"] {
            // hlx:1555
            err(&env.run_bytes(sub, &padded), &format!("{sub} +{extra}"));
            // hlx:1556
        }
        // hlx:1557
    }
    // hlx:1558
    let mut padded = BASE.as_bytes().to_vec();
    // hlx:1559
    padded.resize(limit, b' ');
    // hlx:1560
    for sub in ["receipt", "run", "validate", "explain"] {
        // hlx:1561
        assert_eq!(
            env.run_bytes(sub, &padded).code,
            Some(0),
            "{sub} at exactly 1 MiB"
        );
        // hlx:1562
    }
    // hlx:1563
}
// hlx:1564
#[test]
// hlx:1565
fn envelope_depth_allows_one_extra_level_and_no_more_and_deep_input_is_bounded() {
    // hlx:1566
    let env = Env::new("env-depth");
    // hlx:1567
    let m = make(&env, &nested_all(30));
    // hlx:1568
    let rc = ser(&m.receipt, false, false);
    // hlx:1569
    // request depth 64 + envelope = 65: accepted (also covered above); the receipt object adds no depth beyond 2
    // hlx:1570
    consistent(
        &env.run("replay", &replay_doc(&nested_all(30), &rc)),
        "pass",
        &m.input,
        &m.result,
    );
    // hlx:1571
    // anything deeper than 65 in total is an error, whatever sits in the deep position, and never a crash
    // hlx:1572
    let head = format!("{{\"request\":{},\"receipt\":{rc},\"x\":", nested_all(30));
    // hlx:1573
    for n in [1usize, 2, 64, 65, 66, 1000, 100_000] {
        // hlx:1574
        for (open, close) in [("[", "]"), ("{\"k\":", "}")] {
            // hlx:1575
            let doc = format!("{head}{}0{}}}", open.repeat(n), close.repeat(n));
            // hlx:1576
            if doc.len() > 1_048_576 + 4096 {
                // hlx:1577
                continue;
                // hlx:1578
            }
            // hlx:1579
            let o = env.run("replay", &doc);
            // hlx:1580
            assert!(
                o.code.is_some(),
                "a signal killed the process at nesting {n}"
            );
            // hlx:1581
            err(&o, &format!("extra key nested {n}"));
            // hlx:1582
        }
        // hlx:1583
    }
    // hlx:1584
    // a receipt stuffed with arbitrary payload cannot use the allowance: its exact schema is enforced
    // hlx:1585
    let mut stuffed = rc.clone();
    // hlx:1586
    stuffed.pop();
    // hlx:1587
    stuffed.push_str(&format!(",\"pad\":\"{}\"}}", "x".repeat(4000)));
    // hlx:1588
    err(
        &env.run("replay", &replay_doc(&nested_all(30), &stuffed)),
        "receipt with a padding field",
    );
    // hlx:1589
    let long_id = "a".repeat(3000);
    // hlx:1590
    let mut long = m.receipt.clone();
    // hlx:1591
    if let J::Obj(kv) = &mut long {
        // hlx:1592
        for e in kv.iter_mut() {
            // hlx:1593
            if e.0 == "check_id" {
                // hlx:1594
                e.1 = J::Str(long_id.clone());
                // hlx:1595
            }
            // hlx:1596
        }
        // hlx:1597
    }
    // hlx:1598
    let o = env.run(
        "replay",
        &replay_doc(&nested_all(30), &ser(&long, false, false)),
    );
    // hlx:1599
    assert!(
        o.code == Some(2) || o.code == Some(0),
        "{}",
        trunc(&o.text())
    );
    // hlx:1600
    if o.code == Some(0) {
        // hlx:1601
        mismatch(&o, &[&long_id], "long id");
    // hlx:1602
    } else {
        // hlx:1603
        err(&o, "long id");
        // hlx:1604
    }
    // hlx:1605
    // 29 levels still replays the ordinary way
    // hlx:1606
    let m29 = make(&env, &nested_all(29));
    // hlx:1607
    consistent(
        &env.run(
            "replay",
            &replay_doc(&nested_all(29), &ser(&m29.receipt, false, false)),
        ),
        "pass",
        &m29.input,
        &m29.result,
    );
    // hlx:1608
}