instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
// generated by hxc 1.0.0-acgt-compiler from tests/check_feedback.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
#[cfg(unix)]
// hlx:4
mod fb {
    // hlx:5
    use std::io::Write;
    // hlx:6
    use std::path::{Path, PathBuf};
    // hlx:7
    use std::process::{Command, Stdio};
    // hlx:8
    use std::sync::atomic::{AtomicUsize, Ordering};
    // hlx:9
    use std::time::Duration;
    // hlx:10
    fn bin() -> &'static str {
        // hlx:11
        env!("CARGO_BIN_EXE_instinct")
        // hlx:12
    }
    // hlx:13
    // ---------------------------------------------------------------- minimal JSON reader for the outputs
    // hlx:14
    #[derive(Debug, Clone, PartialEq)]
    // hlx:15
    enum J {
        // hlx:16
        Null,
        // hlx:17
        Bool(bool),
        // hlx:18
        Num(String),
        // hlx:19
        Str(String),
        // hlx:20
        Arr(Vec<J>),
        // hlx:21
        Obj(Vec<(String, J)>),
        // hlx:22
    }
    // hlx:23
    impl J {
        // hlx:24
        fn get(&self, k: &str) -> Option<&J> {
            // hlx:25
            match self {
                // hlx:26
                J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
                // hlx:27
                _ => None,
                // hlx:28
            }
            // hlx:29
        }
        // hlx:30
        fn as_str(&self) -> Option<&str> {
            // hlx:31
            match self {
                // hlx:32
                J::Str(s) => Some(s),
                // hlx:33
                _ => None,
                // hlx:34
            }
            // hlx:35
        }
        // hlx:36
    }
    // hlx:37
    struct P<'a> {
        // hlx:38
        b: &'a [u8],
        // hlx:39
        i: usize,
        // hlx:40
    }
    // hlx:41
    impl<'a> P<'a> {
        // hlx:42
        fn ws(&mut self) {
            // hlx:43
            while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
                // hlx:44
                self.i += 1;
                // hlx:45
            }
            // hlx:46
        }
        // hlx:47
        fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
            // hlx:48
            if self.b[self.i..].starts_with(w.as_bytes()) {
                // hlx:49
                self.i += w.len();
                // hlx:50
                Ok(v)
            // hlx:51
            } else {
                // hlx:52
                Err(format!("bad literal at {}", self.i))
                // hlx:53
            }
            // hlx:54
        }
        // hlx:55
        fn hex4(&mut self) -> Result<u32, String> {
            // hlx:56
            let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
            // hlx:57
            let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
            // hlx:58
            self.i += 4;
            // hlx:59
            u32::from_str_radix(h, 16).map_err(|e| e.to_string())
            // hlx:60
        }
        // hlx:61
        fn string(&mut self) -> Result<String, String> {
            // hlx:62
            if self.b.get(self.i) != Some(&b'"') {
                // hlx:63
                return Err(format!("expected string at {}", self.i));
                // hlx:64
            }
            // hlx:65
            self.i += 1;
            // hlx:66
            let mut out: Vec<u8> = Vec::new();
            // hlx:67
            loop {
                // hlx:68
                let c = *self.b.get(self.i).ok_or("unterminated string")?;
                // hlx:69
                self.i += 1;
                // hlx:70
                match c {
                    // hlx:71
                    b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
                    // hlx:72
                    b'\\' => {
                        // hlx:73
                        let e = *self.b.get(self.i).ok_or("bad escape")?;
                        // hlx:74
                        self.i += 1;
                        // hlx:75
                        let ch = match e {
                            // hlx:76
                            b'"' => '"',
                            // hlx:77
                            b'\\' => '\\',
                            // hlx:78
                            b'/' => '/',
                            // hlx:79
                            b'b' => '\u{8}',
                            // hlx:80
                            b'f' => '\u{c}',
                            // hlx:81
                            b'n' => '\n',
                            // hlx:82
                            b'r' => '\r',
                            // hlx:83
                            b't' => '\t',
                            // hlx:84
                            b'u' => {
                                // hlx:85
                                let hi = self.hex4()?;
                                // hlx:86
                                if (0xD800..0xDC00).contains(&hi) {
                                    // hlx:87
                                    if self.b.get(self.i) != Some(&b'\\')
                                        || self.b.get(self.i + 1) != Some(&b'u')
                                    {
                                        // hlx:88
                                        return Err("lone surrogate".into());
                                        // hlx:89
                                    }
                                    // hlx:90
                                    self.i += 2;
                                    // hlx:91
                                    let lo = self.hex4()?;
                                    // hlx:92
                                    char::from_u32(
                                        0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)),
                                    )
                                    // hlx:93
                                    .ok_or("bad pair")?
                                // hlx:94
                                } else {
                                    // hlx:95
                                    char::from_u32(hi).ok_or("lone surrogate")?
                                    // hlx:96
                                }
                                // hlx:97
                            }
                            // hlx:98
                            _ => return Err("bad escape".into()),
                            // hlx:99
                        };
                        // hlx:100
                        let mut buf = [0u8; 4];
                        // hlx:101
                        out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
                        // hlx:102
                    }
                    // hlx:103
                    _ => out.push(c),
                    // hlx:104
                }
                // hlx:105
            }
            // hlx:106
        }
        // hlx:107
        fn val(&mut self) -> Result<J, String> {
            // hlx:108
            self.ws();
            // hlx:109
            match self.b.get(self.i).copied() {
                // hlx:110
                None => Err("eof".into()),
                // hlx:111
                Some(b'{') => {
                    // hlx:112
                    self.i += 1;
                    // hlx:113
                    let mut v = Vec::new();
                    // hlx:114
                    self.ws();
                    // hlx:115
                    if self.b.get(self.i) == Some(&b'}') {
                        // hlx:116
                        self.i += 1;
                        // hlx:117
                        return Ok(J::Obj(v));
                        // hlx:118
                    }
                    // hlx:119
                    loop {
                        // hlx:120
                        self.ws();
                        // hlx:121
                        let k = self.string()?;
                        // hlx:122
                        self.ws();
                        // hlx:123
                        if self.b.get(self.i) != Some(&b':') {
                            // hlx:124
                            return Err("expected colon".into());
                            // hlx:125
                        }
                        // hlx:126
                        self.i += 1;
                        // hlx:127
                        let x = self.val()?;
                        // hlx:128
                        v.push((k, x));
                        // hlx:129
                        self.ws();
                        // hlx:130
                        match self.b.get(self.i) {
                            // hlx:131
                            Some(b',') => self.i += 1,
                            // hlx:132
                            Some(b'}') => {
                                // hlx:133
                                self.i += 1;
                                // hlx:134
                                return Ok(J::Obj(v));
                                // hlx:135
                            }
                            // hlx:136
                            _ => return Err("bad object".into()),
                            // hlx:137
                        }
                        // hlx:138
                    }
                    // hlx:139
                }
                // hlx:140
                Some(b'[') => {
                    // hlx:141
                    self.i += 1;
                    // hlx:142
                    let mut v = Vec::new();
                    // hlx:143
                    self.ws();
                    // hlx:144
                    if self.b.get(self.i) == Some(&b']') {
                        // hlx:145
                        self.i += 1;
                        // hlx:146
                        return Ok(J::Arr(v));
                        // hlx:147
                    }
                    // hlx:148
                    loop {
                        // hlx:149
                        v.push(self.val()?);
                        // hlx:150
                        self.ws();
                        // hlx:151
                        match self.b.get(self.i) {
                            // hlx:152
                            Some(b',') => self.i += 1,
                            // hlx:153
                            Some(b']') => {
                                // hlx:154
                                self.i += 1;
                                // hlx:155
                                return Ok(J::Arr(v));
                                // hlx:156
                            }
                            // hlx:157
                            _ => return Err("bad array".into()),
                            // hlx:158
                        }
                        // hlx:159
                    }
                    // hlx:160
                }
                // hlx:161
                Some(b'"') => Ok(J::Str(self.string()?)),
                // hlx:162
                Some(b't') => self.lit("true", J::Bool(true)),
                // hlx:163
                Some(b'f') => self.lit("false", J::Bool(false)),
                // hlx:164
                Some(b'n') => self.lit("null", J::Null),
                // hlx:165
                Some(_) => {
                    // hlx:166
                    let st = self.i;
                    // hlx:167
                    while self.i < self.b.len()
                        && matches!(
                            self.b[self.i],
                            b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9'
                        )
                    {
                        // hlx:168
                        self.i += 1;
                        // hlx:169
                    }
                    // hlx:170
                    if st == self.i {
                        // hlx:171
                        return Err(format!("unexpected byte at {st}"));
                        // hlx:172
                    }
                    // hlx:173
                    Ok(J::Num(
                        String::from_utf8_lossy(&self.b[st..self.i]).into_owned(),
                    ))
                    // hlx:174
                } // hlx:175
            }
            // hlx:176
        }
        // hlx:177
    }
    // hlx:178
    fn parse_json(s: &str) -> Result<J, String> {
        // hlx:179
        let mut p = P {
            b: s.as_bytes(),
            i: 0,
        };
        // hlx:180
        let v = p.val()?;
        // hlx:181
        p.ws();
        // hlx:182
        if p.i != p.b.len() {
            // hlx:183
            return Err("trailing data".into());
            // hlx:184
        }
        // hlx:185
        Ok(v)
        // hlx:186
    }
    // hlx:187
    fn to_s(j: &J) -> String {
        // hlx:188
        match j {
            // hlx:189
            J::Null => "null".into(),
            // hlx:190
            J::Bool(b) => b.to_string(),
            // hlx:191
            J::Num(n) => n.clone(),
            // hlx:192
            J::Str(s) => format!("{s:?}"),
            // hlx:193
            J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
            // hlx:194
            J::Obj(v) => format!(
                "{{{}}}",
                v.iter()
                    .map(|(k, x)| format!("{k:?}:{}", to_s(x)))
                    .collect::<Vec<_>>()
                    .join(",")
            ),
            // hlx:195
        }
        // hlx:196
    }
    // hlx:197
    use std::os::unix::fs::PermissionsExt;
    // hlx:198
    // ---------------------------------------------------------------- isolated environment with a staging area
    // hlx:199
    struct Out {
        // hlx:200
        code: Option<i32>,
        // hlx:201
        out: Vec<u8>,
        // hlx:202
        err: Vec<u8>,
        // hlx:203
    }
    // hlx:204
    impl Out {
        // hlx:205
        fn text(&self) -> String {
            // hlx:206
            String::from_utf8_lossy(&self.out).into_owned()
            // hlx:207
        }
        // hlx:208
    }
    // hlx:209
    fn fnv(b: &[u8]) -> u64 {
        // hlx:210
        let mut h = 0xcbf29ce484222325u64;
        // hlx:211
        for x in b {
            // hlx:212
            h ^= *x as u64;
            // hlx:213
            h = h.wrapping_mul(0x100000001b3);
            // hlx:214
        }
        // hlx:215
        h
        // hlx:216
    }
    // hlx:217
    // never follows a symlink: links are recorded by their own target text, directories and files with their mode bits
    // hlx:218
    fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
        // hlx:219
        let mut ents: Vec<_> = match std::fs::read_dir(dir) {
            // hlx:220
            Ok(r) => r.filter_map(|e| e.ok()).collect(),
            // hlx:221
            Err(_) => return,
            // hlx:222
        };
        // hlx:223
        ents.sort_by_key(|e| e.file_name());
        // hlx:224
        for e in ents {
            // hlx:225
            let p = e.path();
            // hlx:226
            let rel = p.strip_prefix(base).unwrap().to_string_lossy().into_owned();
            // hlx:227
            let md = match std::fs::symlink_metadata(&p) {
                // hlx:228
                Ok(m) => m,
                // hlx:229
                Err(_) => continue,
                // hlx:230
            };
            // hlx:231
            let mode = md.permissions().mode();
            // hlx:232
            let ft = md.file_type();
            // hlx:233
            if ft.is_symlink() {
                // hlx:234
                acc.push(format!("l {rel} {:?}", std::fs::read_link(&p).ok()));
            // hlx:235
            } else if ft.is_dir() {
                // hlx:236
                acc.push(format!("d {rel} {mode:o}"));
                // hlx:237
                walk(base, &p, acc);
            // hlx:238
            } else if ft.is_file() {
                // hlx:239
                let b = std::fs::read(&p).unwrap_or_default();
                // hlx:240
                acc.push(format!("f {rel} {mode:o} {} {:x}", b.len(), fnv(&b)));
            // hlx:241
            } else {
                // hlx:242
                acc.push(format!("o {rel} {mode:o}"));
                // hlx:243
            }
            // hlx:244
        }
        // hlx:245
    }
    // hlx:246
    fn unlock(dir: &Path) {
        // hlx:247
        if let Ok(md) = std::fs::symlink_metadata(dir) {
            // hlx:248
            if md.file_type().is_dir() {
                // hlx:249
                let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755));
                // hlx:250
                if let Ok(r) = std::fs::read_dir(dir) {
                    // hlx:251
                    for e in r.filter_map(|e| e.ok()) {
                        // hlx:252
                        unlock(&e.path());
                        // hlx:253
                    }
                    // hlx:254
                }
                // hlx:255
            }
            // hlx:256
        }
        // hlx:257
    }
    // hlx:258
    struct Env {
        // hlx:259
        root: PathBuf,
        // hlx:260
    }
    // hlx:261
    impl Env {
        // hlx:262
        fn new(name: &str) -> Env {
            // hlx:263
            static N: AtomicUsize = AtomicUsize::new(0);
            // hlx:264
            #[cfg(target_os = "macos")]
            // hlx:265
            let base = PathBuf::from("/tmp"); // keep Unix socket names below SUN_LEN
                                              // hlx:266
            #[cfg(not(target_os = "macos"))]
            // hlx:267
            let base = std::env::temp_dir();
            // hlx:268
            let root = base.join(format!(
                // hlx:269
                "icfb-{}-{}-{name}",
                // hlx:270
                std::process::id(),
                // hlx:271
                N.fetch_add(1, Ordering::Relaxed) // hlx:272
            ));
            // hlx:273
            let _ = std::fs::remove_dir_all(&root);
            // hlx:274
            for d in [
                "home", "data", "local", "cfg", "state", "cache", "cwd", "in", "stage", "outside",
            ] {
                // hlx:275
                std::fs::create_dir_all(root.join(d)).unwrap();
                // hlx:276
            }
            // hlx:277
            std::fs::write(
                root.join("outside").join("OUTSIDE_TARGET_SECRET_731"),
                b"top secret",
            )
            .unwrap();
            // hlx:278
            std::fs::create_dir_all(root.join("outside").join("OUTSIDE_DIR_SECRET_731")).unwrap();
            // hlx:279
            std::fs::write(
                root.join("outside")
                    .join("OUTSIDE_DIR_SECRET_731")
                    .join("inner_731"),
                b"x",
            )
            .unwrap();
            // hlx:280
            std::fs::write(root.join("home").join("sentinel"), b"home sentinel").unwrap();
            // hlx:281
            Env { root }
            // hlx:282
        }
        // hlx:283
        // an empty observation root inside the staging area
        // hlx:284
        fn dir(&self, name: &str) -> PathBuf {
            // hlx:285
            let p = self.root.join("stage").join(name);
            // hlx:286
            std::fs::create_dir_all(&p).unwrap();
            // hlx:287
            p
            // hlx:288
        }
        // hlx:289
        fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
            // hlx:290
            let p = self.root.join("in").join(name);
            // hlx:291
            std::fs::write(&p, bytes).unwrap();
            // hlx:292
            p
            // hlx:293
        }
        // hlx:294
        fn snapshot(&self) -> Vec<String> {
            // hlx:295
            let mut acc = Vec::new();
            // hlx:296
            walk(&self.root, &self.root, &mut acc);
            // hlx:297
            acc
            // hlx:298
        }
        // hlx:299
        fn exec_raw(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)], snap: bool) -> Out {
            // hlx:300
            let before = if snap { self.snapshot() } else { Vec::new() };
            // hlx:301
            let mut c = Command::new(bin());
            // hlx:302
            c.args(args)
                // hlx:303
                .current_dir(self.root.join("cwd"))
                // hlx:304
                .env("HOME", self.root.join("home"))
                // hlx:305
                .env("XDG_DATA_HOME", self.root.join("data"))
                // hlx:306
                .env("XDG_CONFIG_HOME", self.root.join("cfg"))
                // hlx:307
                .env("XDG_STATE_HOME", self.root.join("state"))
                // hlx:308
                .env("XDG_CACHE_HOME", self.root.join("cache"))
                // hlx:309
                .env("LOCALAPPDATA", self.root.join("local"))
                // hlx:310
                .env("APPDATA", self.root.join("local"));
            // hlx:311
            for (k, _) in std::env::vars() {
                // hlx:312
                if k.starts_with("INSTINCT_") {
                    // hlx:313
                    c.env_remove(k);
                    // hlx:314
                }
                // hlx:315
            }
            // hlx:316
            for (k, v) in envs {
                // hlx:317
                c.env(k, v);
                // hlx:318
            }
            // hlx:319
            c.stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped());
            // hlx:320
            let mut child = c.spawn().unwrap();
            // hlx:321
            let mut si = child.stdin.take().unwrap();
            // hlx:322
            let data = stdin.to_vec();
            // hlx:323
            let w = std::thread::spawn(move || {
                // hlx:324
                let _ = si.write_all(&data);
                // hlx:325
            });
            // hlx:326
            let (tx, rx) = std::sync::mpsc::channel();
            // hlx:327
            std::thread::spawn(move || {
                // hlx:328
                let _ = tx.send(child.wait_with_output());
                // hlx:329
            });
            // hlx:330
            let o = rx
                .recv_timeout(Duration::from_secs(180))
                .expect("instinct check observe hung")
                .unwrap();
            // hlx:331
            let _ = w.join();
            // hlx:332
            if snap {
                // hlx:333
                let after = self.snapshot();
                // hlx:334
                assert_eq!(
                    before, after,
                    "observation changed the filesystem: {args:?}"
                );
                // hlx:335
            }
            // hlx:336
            Out {
                code: o.status.code(),
                out: o.stdout,
                err: o.stderr,
            }
            // hlx:337
        }
        // hlx:338
    }
    // hlx:339
    impl Drop for Env {
        // hlx:340
        fn drop(&mut self) {
            // hlx:341
            unlock(&self.root);
            // hlx:342
            let _ = std::fs::remove_dir_all(&self.root);
            // hlx:343
        }
        // hlx:344
    }
    // hlx:345
    // ---------------------------------------------------------------- fixtures built with std only
    // hlx:346
    fn put_file(root: &Path, rel: &str) {
        // hlx:347
        let p = root.join(rel);
        // hlx:348
        if let Some(parent) = p.parent() {
            // hlx:349
            std::fs::create_dir_all(parent).unwrap();
            // hlx:350
        }
        // hlx:351
        std::fs::write(p, b"contents").unwrap();
        // hlx:352
    }
    // hlx:353
    // ---------------------------------------------------------------- policy builder
    // hlx:354
    #[derive(Clone)]
    // hlx:355
    struct Pol {
        // hlx:356
        schema: String,
        // hlx:357
        assum: Option<String>,
        // hlx:358
        allowed: String,
        // hlx:359
        required: Option<String>,
        // hlx:360
        scope: Option<String>,
        // hlx:361
        limits: Option<String>,
        // hlx:362
        extra: String,
        // hlx:363
    }
    // hlx:364
    fn pol(allowed: &[&str]) -> Pol {
        // hlx:365
        Pol {
            // hlx:366
            schema: "\"instinct.artifact-policy/v1\"".into(),
            // hlx:367
            assum: Some("{\"trusted_quiescent_staging\":true}".into()),
            // hlx:368
            allowed: jl(allowed),
            // hlx:369
            required: None,
            // hlx:370
            scope: None,
            // hlx:371
            limits: None,
            // hlx:372
            extra: String::new(),
            // hlx:373
        }
        // hlx:374
    }
    // hlx:375
    // a JSON array of strings; items are already JSON-escaped text
    // hlx:376
    fn jl(items: &[&str]) -> String {
        // hlx:377
        format!(
            "[{}]",
            items
                .iter()
                .map(|s| format!("\"{s}\""))
                .collect::<Vec<_>>()
                .join(",")
        )
        // hlx:378
    }
    // hlx:379
    impl Pol {
        // hlx:380
        fn required(mut self, items: &[&str]) -> Pol {
            // hlx:381
            self.required = Some(jl(items));
            // hlx:382
            self
            // hlx:383
        }
        // hlx:384
        fn scope(mut self, s: &str) -> Pol {
            // hlx:385
            self.scope = Some(s.into());
            // hlx:386
            self
            // hlx:387
        }
        // hlx:388
        fn schema(mut self, s: &str) -> Pol {
            // hlx:389
            self.schema = s.into();
            // hlx:390
            self
            // hlx:391
        }
        // hlx:392
        fn extra(mut self, s: &str) -> Pol {
            // hlx:393
            self.extra.push_str(s);
            // hlx:394
            self
            // hlx:395
        }
        // hlx:396
        fn json(&self) -> String {
            // hlx:397
            let mut t = format!("{{\"schema\":{}", self.schema);
            // hlx:398
            if let Some(a) = &self.assum {
                // hlx:399
                t.push_str(&format!(",\"assumptions\":{a}"));
                // hlx:400
            }
            // hlx:401
            t.push_str(&format!(",\"allowed\":{}", self.allowed));
            // hlx:402
            if let Some(r) = &self.required {
                // hlx:403
                t.push_str(&format!(",\"required\":{r}"));
                // hlx:404
            }
            // hlx:405
            if let Some(s) = &self.scope {
                // hlx:406
                t.push_str(&format!(",\"scope\":{s}"));
                // hlx:407
            }
            // hlx:408
            if let Some(l) = &self.limits {
                // hlx:409
                t.push_str(&format!(",\"limits\":{l}"));
                // hlx:410
            }
            // hlx:411
            t.push_str(&self.extra);
            // hlx:412
            t.push('}');
            // hlx:413
            t
            // hlx:414
        }
        // hlx:415
    }
    // hlx:416
    // ---------------------------------------------------------------- small helpers
    // hlx:417
    fn trunc(s: &str) -> String {
        // hlx:418
        s.chars().take(500).collect()
        // hlx:419
    }
    // hlx:420
    fn obj(o: &Out) -> J {
        // hlx:421
        let t = o.text();
        // hlx:422
        parse_json(t.trim())
            .unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)))
        // hlx:423
    }
    // hlx:424
    fn sf<'a>(j: &'a J, k: &str) -> &'a str {
        // hlx:425
        j.get(k)
            .and_then(J::as_str)
            .unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
        // hlx:426
    }
    // hlx:427
    fn is_root() -> bool {
        // hlx:428
        let probe = std::env::temp_dir().join(format!("instinct-fb-probe-{}", std::process::id()));
        // hlx:429
        let _ = std::fs::remove_dir_all(&probe);
        // hlx:430
        std::fs::create_dir_all(&probe).unwrap();
        // hlx:431
        std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o000)).unwrap();
        // hlx:432
        let readable = std::fs::read_dir(&probe).is_ok();
        // hlx:433
        let _ = std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o755));
        // hlx:434
        let _ = std::fs::remove_dir_all(&probe);
        // hlx:435
        readable
        // hlx:436
    }
    // hlx:437
    fn has_hex64(s: &str) -> bool {
        // hlx:438
        let b = s.as_bytes();
        // hlx:439
        let mut run = 0;
        // hlx:440
        for &c in b {
            // hlx:441
            if matches!(c, b'0'..=b'9' | b'a'..=b'f') {
                // hlx:442
                run += 1;
                // hlx:443
                if run >= 64 {
                    // hlx:444
                    return true;
                    // hlx:445
                }
            // hlx:446
            } else {
                // hlx:447
                run = 0;
                // hlx:448
            }
            // hlx:449
        }
        // hlx:450
        false
        // hlx:451
    }
    // hlx:452
    const LEGACY_EVAL_KEYS: [&str; 16] = [
        // hlx:453
        "schema",
        "since",
        "generated",
        "lessons",
        "proven",
        "delivery_record",
        "paid_off",
        "misled",
        "to_quarantine",
        "delivered_never_judged",
        // hlx:454
        "never_fired",
        "near_duplicates",
        "savings",
        "next_actions",
        "applied_quarantine",
        "explore",
        // hlx:455
    ];
    // hlx:456
    fn key_list(j: &J) -> Vec<String> {
        // hlx:457
        match j {
            // hlx:458
            J::Obj(v) => v.iter().map(|(k, _)| k.clone()).collect(),
            // hlx:459
            _ => panic!("object"),
            // hlx:460
        }
        // hlx:461
    }
    // hlx:462
    // the same tree without lock files, which the contract allows to appear
    // hlx:463
    fn tree(env: &Env) -> Vec<String> {
        // hlx:464
        env.snapshot()
            .into_iter()
            .filter(|l| !l.to_lowercase().contains("lock"))
            .collect()
        // hlx:465
    }
    // hlx:466
    // ---------------------------------------------------------------- the fixture: a bank, a lesson, a staging root
    // hlx:467
    #[derive(Debug, Clone)]
    // hlx:468
    struct Sum {
        // hlx:469
        present: bool,
        // hlx:470
        total: u64,
        // hlx:471
        claimed: u64,
        // hlx:472
        verified: u64,
        // hlx:473
        downgraded: u64,
        // hlx:474
        invalid: u64,
        // hlx:475
    }
    // hlx:476
    struct Fx {
        // hlx:477
        env: Env,
        // hlx:478
        store: PathBuf,
        // hlx:479
        root: PathBuf,
        // hlx:480
        id: String,
        // hlx:481
        n: usize,
        // hlx:482
    }
    // hlx:483
    impl Fx {
        // hlx:484
        fn new(name: &str, native: bool) -> Fx {
            // hlx:485
            let env = Env::new(name);
            // hlx:486
            std::fs::create_dir_all(env.root.join("banks")).unwrap();
            // hlx:487
            let store =
                env.root
                    .join("banks")
                    .join(if native { "bank.hxdb" } else { "bank.jsonl" });
            // hlx:488
            let root = env.dir("staging");
            // hlx:489
            put_file(&root, "release.bin");
            // hlx:490
            let mut fx = Fx {
                env,
                store,
                root,
                id: String::new(),
                n: 0,
            };
            // hlx:491
            fx.id = fx.bank_lesson(&["--project", "release-lab"]);
            // hlx:492
            fx
            // hlx:493
        }
        // hlx:494
        fn st(&self) -> &str {
            // hlx:495
            self.store.to_str().unwrap()
            // hlx:496
        }
        // hlx:497
        fn envs(&self) -> Vec<(&'static str, &'static str)> {
            // hlx:498
            vec![("INSTINCT_PROJECT", "release-lab")]
            // hlx:499
        }
        // hlx:500
        fn cli(&self, args: &[&str]) -> Out {
            // hlx:501
            self.env.exec_raw(args, b"", &self.envs(), false)
            // hlx:502
        }
        // hlx:503
        fn cli_env(&self, args: &[&str], envs: &[(&str, &str)]) -> Out {
            // hlx:504
            self.env.exec_raw(args, b"", envs, false)
            // hlx:505
        }
        // hlx:506
        fn bank_lesson(&self, scope: &[&str]) -> String {
            // hlx:507
            let mut a = vec![
                "bank",
                "--store",
                self.st(),
                "--title",
                "Ship only release",
                "--when",
                "Packaging the release",
                "--found",
                "Stray files get shipped",
                "--how",
                "Check the inventory",
                "--evidence",
                "seen twice",
            ];
            // hlx:508
            a.extend_from_slice(scope);
            // hlx:509
            let o = self.cli_env(&a, &[]);
            // hlx:510
            assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
            // hlx:511
            let t = o.text();
            // hlx:512
            t.split_whitespace()
                .nth(1)
                .unwrap_or_else(|| panic!("{t}"))
                .to_string()
            // hlx:513
        }
        // hlx:514
        fn policy(&self, allowed: &[&str], required: &[&str]) -> String {
            // hlx:515
            pol(allowed)
                .required(required)
                .scope("{\"project\":\"release-lab\"}")
                .json()
            // hlx:516
        }
        // hlx:517
        fn std_policy(&self) -> String {
            // hlx:518
            self.policy(&["release.bin"], &["release.bin"])
            // hlx:519
        }
        // hlx:520
        fn attach_for(&mut self, id: &str, policy: &str) -> Out {
            // hlx:521
            self.n += 1;
            // hlx:522
            self.env.exec_raw(
                &[
                    "check",
                    "attach",
                    "--lesson",
                    id,
                    "--store",
                    self.st(),
                    "--input",
                    "-",
                ],
                policy.as_bytes(),
                &self.envs(),
                false,
            )
            // hlx:523
        }
        // hlx:524
        fn attach(&mut self, policy: &str) -> Out {
            // hlx:525
            let id = self.id.clone();
            // hlx:526
            self.attach_for(&id, policy)
            // hlx:527
        }
        // hlx:528
        fn attached(&mut self) {
            // hlx:529
            let p = self.std_policy();
            // hlx:530
            let o = self.attach(&p);
            // hlx:531
            assert_eq!(o.code, Some(0), "attach: {}", trunc(&o.text()));
            // hlx:532
        }
        // hlx:533
        fn hit_check_with(
            &self,
            id: &str,
            key: &str,
            note: &str,
            trusted: bool,
            root: &Path,
            envs: &[(&str, &str)],
        ) -> Out {
            // hlx:534
            let mut a = vec![
                "hit",
                id,
                "--check",
                "--root",
                root.to_str().unwrap(),
                "--outcome-id",
                key,
                "--store",
                self.st(),
                "--note",
                note,
            ];
            // hlx:535
            if trusted {
                // hlx:536
                a.push("--trusted-staging");
                // hlx:537
            }
            // hlx:538
            self.cli_env(&a, envs)
            // hlx:539
        }
        // hlx:540
        fn hit_check(&self, key: &str, note: &str) -> Out {
            // hlx:541
            self.hit_check_with(&self.id, key, note, true, &self.root, &self.envs())
            // hlx:542
        }
        // hlx:543
        fn events(&self) -> Vec<J> {
            // hlx:544
            let o = self.cli(&["export", "--store", self.st()]);
            // hlx:545
            assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
            // hlx:546
            o.text()
                .lines()
                .filter(|l| !l.trim().is_empty())
                .map(|l| parse_json(l).unwrap_or_else(|e| panic!("export line {e}: {l}")))
                .collect()
            // hlx:547
        }
        // hlx:548
        fn hits_of(&self, id: &str) -> Vec<J> {
            // hlx:549
            self.events()
                .into_iter()
                .filter(|e| {
                    e.get("kind").and_then(J::as_str) == Some("hit")
                        && e.get("id").and_then(J::as_str) == Some(id)
                })
                .collect()
            // hlx:550
        }
        // hlx:551
        fn hits(&self) -> Vec<J> {
            // hlx:552
            let id = self.id.clone();
            // hlx:553
            self.hits_of(&id)
            // hlx:554
        }
        // hlx:555
        fn misses(&self) -> usize {
            // hlx:556
            self.events()
                .iter()
                .filter(|e| e.get("kind").and_then(J::as_str) == Some("miss"))
                .count()
            // hlx:557
        }
        // hlx:558
        fn verified_events(&self) -> usize {
            // hlx:559
            self.events()
                .iter()
                .filter(|e| e.get("check_verification").is_some())
                .count()
            // hlx:560
        }
        // hlx:561
        fn eval_json(&self, since: &str) -> J {
            // hlx:562
            let o = self.cli(&["eval", "--json", "--since", since, "--store", self.st()]);
            // hlx:563
            assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
            // hlx:564
            obj(&o)
            // hlx:565
        }
        // hlx:566
        fn eval_text(&self) -> String {
            // hlx:567
            let o = self.cli(&["eval", "--since", "all", "--store", self.st()]);
            // hlx:568
            assert_eq!(o.code, Some(0));
            // hlx:569
            o.text()
            // hlx:570
        }
        // hlx:571
        // the documented summary (docs/check-verified-feedback.md): absent entirely when the bank has no verification marker
        // hlx:572
        fn summary(&self, since: &str) -> Sum {
            // hlx:573
            let j = self.eval_json(since);
            // hlx:574
            // Legacy savings.hits is all-time. Verification and paid_off are windowed.
            // hlx:575
            let total = match j.get("paid_off") {
                // hlx:576
                Some(J::Arr(rows)) => rows
                    .iter()
                    .map(|r| match r.get("hits") {
                        Some(J::Num(n)) => n.parse::<u64>().unwrap(),
                        other => panic!("paid_off hits: {other:?}"),
                    })
                    .sum(),
                // hlx:577
                other => panic!("paid_off: {other:?}"),
                // hlx:578
            };
            // hlx:579
            let num = |v: &J, k: &str| -> u64 {
                // hlx:580
                match v.get(k) {
                    // hlx:581
                    Some(J::Num(n)) => n.parse::<u64>().unwrap_or_else(|_| panic!("{k}: {n}")),
                    // hlx:582
                    other => panic!("verification.{k} must be a number, got {other:?}"),
                    // hlx:583
                }
                // hlx:584
            };
            // hlx:585
            let s = match j.get("verification") {
                // hlx:586
                None => {
                    // hlx:587
                    assert_eq!(
                        key_list(&j),
                        LEGACY_EVAL_KEYS.to_vec(),
                        "no marker, no new keys"
                    );
                    // hlx:588
                    Sum {
                        present: false,
                        total,
                        claimed: total,
                        verified: 0,
                        downgraded: 0,
                        invalid: 0,
                    }
                    // hlx:589
                }
                // hlx:590
                Some(v) => {
                    // hlx:591
                    assert_eq!(sf(v, "schema"), "instinct.verified-feedback-summary/v1");
                    // hlx:592
                    let s = Sum {
                        present: true,
                        total,
                        claimed: num(v, "claimed_hits"),
                        verified: num(v, "check_verified_hits"),
                        downgraded: num(v, "downgraded_hits"),
                        invalid: num(v, "invalid_records"),
                    };
                    // hlx:593
                    for k in LEGACY_EVAL_KEYS {
                        // hlx:594
                        assert!(
                            key_list(&j).contains(&k.to_string()),
                            "legacy key {k} stays"
                        );
                        // hlx:595
                    }
                    // hlx:596
                    s
                    // hlx:597
                } // hlx:598
            };
            // hlx:599
            assert_eq!(
                s.claimed + s.verified,
                s.total,
                "claimed_hits = total hits - check_verified_hits: {}",
                trunc(&to_s(&j))
            );
            // hlx:600
            assert!(
                s.verified <= s.total && s.downgraded <= s.claimed,
                "verified is a subset of hits and downgraded a subset of claimed: {}",
                trunc(&to_s(&j))
            );
            // hlx:601
            s
            // hlx:602
        }
        // hlx:603
        fn verified_count(&self, since: &str) -> u64 {
            // hlx:604
            self.summary(since).verified
            // hlx:605
        }
        // hlx:606
        fn append_event(&self, line: &str) {
            // hlx:607
            let mut t = std::fs::read_to_string(&self.store).unwrap();
            // hlx:608
            if !t.ends_with('\n') {
                // hlx:609
                t.push('\n');
                // hlx:610
            }
            // hlx:611
            t.push_str(line);
            // hlx:612
            t.push('\n');
            // hlx:613
            std::fs::write(&self.store, t).unwrap();
            // hlx:614
        }
        // hlx:615
        fn bank_titled(&self, title: &str, scope: &[&str]) -> String {
            // hlx:616
            let mut a = vec![
                "bank",
                "--store",
                self.st(),
                "--title",
                title,
                "--when",
                "Another packaging situation",
                "--found",
                "Other stray files",
                "--how",
                "Look at the folder list",
                "--evidence",
                "seen once",
            ];
            // hlx:617
            a.extend_from_slice(scope);
            // hlx:618
            let o = self.cli_env(&a, &[]);
            // hlx:619
            assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
            // hlx:620
            o.text().split_whitespace().nth(1).unwrap().to_string()
            // hlx:621
        }
        // hlx:622
        fn rewrite_store(&self, f: impl Fn(&str) -> String) {
            // hlx:623
            let t = std::fs::read_to_string(&self.store).unwrap();
            // hlx:624
            std::fs::write(&self.store, f(&t)).unwrap();
            // hlx:625
        }
        // hlx:626
    }
    // hlx:627
    // a hit that was not recorded: no hit event and no claim of success on stdout
    // hlx:628
    fn not_recorded(fx: &Fx, o: &Out, ctx: &str) {
        // hlx:629
        assert!(
            fx.hits().is_empty(),
            "{ctx}: a hit was recorded: {}",
            trunc(&o.text())
        );
        // hlx:630
        assert!(
            !(o.code == Some(0) && o.text().contains("hit recorded")),
            "{ctx}: claims a hit: {}",
            trunc(&o.text())
        );
        // hlx:631
    }
    // hlx:632
    // exactly one verified hit with the documented evidence, and no private content
    // hlx:633
    fn one_verified(fx: &Fx, key: &str, o: &Out) -> J {
        // hlx:634
        assert_eq!(
            o.code,
            Some(0),
            "expected a recorded verified hit: {} / {}",
            trunc(&o.text()),
            trunc(&String::from_utf8_lossy(&o.err))
        );
        // hlx:635
        let hits = fx.hits();
        // hlx:636
        assert_eq!(
            hits.len(),
            1,
            "exactly one hit: {}",
            trunc(&to_s(&J::Arr(hits.clone())))
        );
        // hlx:637
        let ev = &hits[0];
        // hlx:638
        for k in ["kind", "id", "ts", "note", "outcome_id"] {
            // hlx:639
            assert!(ev.get(k).is_some(), "the legacy hit fields stay: {k}");
            // hlx:640
        }
        // hlx:641
        assert_eq!(sf(ev, "outcome_id"), key);
        // hlx:642
        let cv = ev.get("check_verification").unwrap_or_else(|| {
            panic!(
                "a verified hit carries check_verification: {}",
                trunc(&to_s(ev))
            )
        });
        // hlx:643
        let t = to_s(cv);
        // hlx:644
        for needle in [
            "adapter_observed",
            "not_evaluated",
            "artifact-inventory/v1",
            key,
            fx.id.as_str(),
        ] {
            // hlx:645
            assert!(
                t.contains(needle),
                "check_verification must carry {needle}: {t}"
            );
            // hlx:646
        }
        // hlx:647
        assert!(
            has_hex64(&t),
            "check_verification must carry a SHA-256: {t}"
        );
        // hlx:648
        let line = to_s(ev);
        // hlx:649
        assert!(
            !line.contains(fx.root.to_str().unwrap()),
            "the root path must never be stored: {line}"
        );
        // hlx:650
        assert!(
            !o.text().contains(fx.root.to_str().unwrap()),
            "the root path must not be displayed"
        );
        // hlx:651
        ev.clone()
        // hlx:652
    }
    // hlx:653
    // ================================================================ 1. forged "it worked" with a hidden extra file
    // hlx:654
    #[test]
    // hlx:655
    fn a_forged_it_worked_with_a_hidden_extra_file_earns_no_hit_and_fixing_the_fixture_earns_exactly_one(
    ) {
        // hlx:656
        for native in [false, true] {
            // hlx:657
            let mut fx = Fx::new(
                if native {
                    "forged-native"
                } else {
                    "forged-jsonl"
                },
                native,
            );
            // hlx:658
            fx.attached();
            // hlx:659
            put_file(&fx.root, ".hidden-extra");
            // hlx:660
            let before = tree(&fx.env);
            // hlx:661
            let o = fx.hit_check("run-1", "it worked");
            // hlx:662
            not_recorded(&fx, &o, "hidden extra");
            // hlx:663
            assert_eq!(
                before,
                tree(&fx.env),
                "a failed check must leave the bank and sidecar unchanged"
            );
            // hlx:664
            assert_eq!(fx.verified_count("all"), 0);
            // hlx:665
            assert_eq!(fx.verified_events(), 0);
            // hlx:666
            // the failed attempt did not consume the outcome key; fix only the fixture
            // hlx:667
            std::fs::remove_file(fx.root.join(".hidden-extra")).unwrap();
            // hlx:668
            let o = fx.hit_check("run-1", "it worked");
            // hlx:669
            one_verified(&fx, "run-1", &o);
            // hlx:670
            assert_eq!(fx.verified_count("all"), 1);
            // hlx:671
            // retry: no extra hit, nothing changes
            // hlx:672
            let before = tree(&fx.env);
            // hlx:673
            let o = fx.hit_check("run-1", "it worked");
            // hlx:674
            assert_eq!(fx.hits().len(), 1, "a retry earns nothing");
            // hlx:675
            assert!(
                !(o.code == Some(0) && o.text().contains("hit recorded for"))
                    || o.text().contains("already"),
                "{}",
                trunc(&o.text())
            );
            // hlx:676
            assert_eq!(before, tree(&fx.env), "a retry changes nothing");
            // hlx:677
            assert_eq!(fx.verified_events(), 1, "one receipt event");
            // hlx:678
        }
        // hlx:679
    }
    // hlx:680
    #[test]
    // hlx:681
    fn a_missing_required_file_also_earns_no_hit() {
        // hlx:682
        let mut fx = Fx::new("required-missing", false);
        // hlx:683
        fx.attached();
        // hlx:684
        std::fs::remove_file(fx.root.join("release.bin")).unwrap();
        // hlx:685
        let o = fx.hit_check("k", "it worked");
        // hlx:686
        not_recorded(&fx, &o, "required file missing");
        // hlx:687
        put_file(&fx.root, "release.bin");
        // hlx:688
        let o = fx.hit_check("k", "it worked");
        // hlx:689
        one_verified(&fx, "k", &o);
        // hlx:690
    }
    // hlx:691
    // ================================================================ 2. claimed hits stay claimed
    // hlx:692
    #[test]
    // hlx:693
    fn a_claimed_hit_cannot_be_promoted_by_a_verified_retry() {
        // hlx:694
        let mut fx = Fx::new("claimed", false);
        // hlx:695
        fx.attached();
        // hlx:696
        let o = fx.cli(&[
            "hit",
            &fx.id.clone(),
            "--note",
            "claimed",
            "--outcome-id",
            "k",
            "--store",
            &fx.st().to_string(),
        ]);
        // hlx:697
        assert_eq!(o.code, Some(0));
        // hlx:698
        assert_eq!(fx.hits().len(), 1);
        // hlx:699
        assert!(fx.hits()[0].get("check_verification").is_none());
        // hlx:700
        let before = tree(&fx.env);
        // hlx:701
        let o = fx.hit_check("k", "now verified");
        // hlx:702
        assert_eq!(fx.hits().len(), 1, "no second credit: {}", trunc(&o.text()));
        // hlx:703
        assert!(
            fx.hits()[0].get("check_verification").is_none(),
            "a claimed hit stays claimed"
        );
        // hlx:704
        assert_eq!(fx.verified_events(), 0);
        // hlx:705
        assert_eq!(fx.verified_count("all"), 0);
        // hlx:706
        assert_eq!(before, tree(&fx.env), "nothing is mutated by the retry");
        // hlx:707
        // a different outcome is a different observation and may earn its own verified hit
        // hlx:708
        let o = fx.hit_check("k2", "verified");
        // hlx:709
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:710
        assert_eq!(fx.hits().len(), 2);
        // hlx:711
        assert_eq!(fx.verified_events(), 1);
        // hlx:712
        assert_eq!(fx.verified_count("all"), 1);
        // hlx:713
    }
    // hlx:714
    // ================================================================ 3. the gates: nothing earns a hit without every precondition
    // hlx:715
    #[test]
    // hlx:716
    fn every_missing_precondition_earns_no_hit() {
        // hlx:717
        let mut fx = Fx::new("gates", false);
        // hlx:718
        let id = fx.id.clone();
        // hlx:719
        // no attachment: --check never falls back to claimed feedback
        // hlx:720
        let o = fx.hit_check("k", "it worked");
        // hlx:721
        not_recorded(&fx, &o, "no attachment");
        // hlx:722
        assert_ne!(
            o.code,
            Some(0),
            "no attachment is an error: {}",
            trunc(&o.text())
        );
        // hlx:723
        fx.attached();
        // hlx:724
        let before = tree(&fx.env);
        // hlx:725
        // the caller's explicit acknowledgement is required on every verified hit
        // hlx:726
        let o = fx.hit_check_with(&id, "k", "it worked", false, &fx.root, &fx.envs());
        // hlx:727
        not_recorded(&fx, &o, "no --trusted-staging");
        // hlx:728
        assert_ne!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:729
        // the root is required and absolute
        // hlx:730
        let st = fx.st().to_string();
        // hlx:731
        for args in [
            // hlx:732
            vec![
                "hit",
                &id,
                "--check",
                "--trusted-staging",
                "--outcome-id",
                "k",
                "--store",
                &st,
            ],
            // hlx:733
            vec![
                "hit",
                &id,
                "--check",
                "--trusted-staging",
                "--root",
                "staging",
                "--outcome-id",
                "k",
                "--store",
                &st,
            ],
            // hlx:734
            vec![
                "hit",
                &id,
                "--check",
                "--trusted-staging",
                "--root",
                "",
                "--outcome-id",
                "k",
                "--store",
                &st,
            ],
            // hlx:735
            vec![
                "hit",
                &id,
                "--check",
                "--trusted-staging",
                "--root",
                "~/x",
                "--outcome-id",
                "k",
                "--store",
                &st,
            ],
            // hlx:736
        ] {
            // hlx:737
            let o = fx.cli(&args);
            // hlx:738
            not_recorded(&fx, &o, &format!("{args:?}"));
            // hlx:739
            assert_ne!(o.code, Some(0), "{args:?}");
            // hlx:740
        }
        // hlx:741
        // empty and whitespace observation keys are rejected
        // hlx:742
        for key in ["", " ", "   ", "\t", "\n"] {
            // hlx:743
            let o = fx.hit_check(key, "it worked");
            // hlx:744
            not_recorded(&fx, &o, &format!("key {key:?}"));
            // hlx:745
            assert_ne!(o.code, Some(0), "key {key:?}");
            // hlx:746
        }
        // hlx:747
        for flag in [
            "--trusted-staging=false",
            "--trusted-staging=0",
            "--check=false",
        ] {
            // hlx:748
            let mut args = vec![
                "hit",
                id.as_str(),
                "--check",
                "--root",
                fx.root.to_str().unwrap(),
                "--outcome-id",
                "false-grant",
                "--store",
                st.as_str(),
            ];
            // hlx:749
            args.push(flag);
            // hlx:750
            let out = fx.cli(&args);
            // hlx:751
            assert_ne!(
                out.code,
                Some(0),
                "false or repeated grant flag must be refused: {flag}"
            );
            // hlx:752
            assert!(fx.hits().is_empty());
            // hlx:753
        }
        // hlx:754
        // the miss path has no check mode
        // hlx:755
        let o = fx.cli(&[
            "miss",
            &id,
            "--check",
            "--root",
            fx.root.to_str().unwrap(),
            "--trusted-staging",
            "--outcome-id",
            "m",
            "--store",
            &st,
        ]);
        // hlx:756
        assert_ne!(
            o.code,
            Some(0),
            "miss --check is an error: {}",
            trunc(&o.text())
        );
        // hlx:757
        assert_eq!(fx.misses(), 0, "no miss was recorded either");
        // hlx:758
        assert!(fx.hits().is_empty());
        // hlx:759
        // an absent lesson
        // hlx:760
        let o = fx.hit_check_with("in-doesnotexist", "k", "n", true, &fx.root, &fx.envs());
        // hlx:761
        assert_ne!(o.code, Some(0));
        // hlx:762
        assert!(fx.hits_of("in-doesnotexist").is_empty());
        // hlx:763
        assert_eq!(before, tree(&fx.env), "none of these changed anything");
        // hlx:764
        // and the control: with everything in place the hit is earned
        // hlx:765
        let o = fx.hit_check("k", "fine");
        // hlx:766
        one_verified(&fx, "k", &o);
        // hlx:767
    }
    // hlx:768
    #[test]
    // hlx:769
    fn the_current_scope_cannot_be_overridden_by_the_attachment_or_the_request() {
        // hlx:770
        let mut fx = Fx::new("scope-gate", false);
        // hlx:771
        fx.attached();
        // hlx:772
        let id = fx.id.clone();
        // hlx:773
        // a different current project: the lesson is out of scope, whatever the attachment says
        // hlx:774
        let o = fx.hit_check_with(
            &id,
            "k",
            "it worked",
            true,
            &fx.root,
            &[("INSTINCT_PROJECT", "other-project")],
        );
        // hlx:775
        not_recorded(&fx, &o, "wrong current project");
        // hlx:776
        // Extra unrestricted dimensions are tested after the zero-credit negative cases below.
        // hlx:777
        let o = fx.hit_check_with(
            &id,
            "k",
            "it worked",
            true,
            &fx.root,
            &[("INSTINCT_PROJECT", "release-lab-2")],
        );
        // hlx:778
        not_recorded(&fx, &o, "near-miss project name");
        // hlx:779
        let o = fx.hit_check_with(
            &id,
            "k",
            "it worked",
            true,
            &fx.root,
            &[("INSTINCT_PROJECT", "Release-Lab")],
        );
        // hlx:780
        not_recorded(&fx, &o, "case-different project");
        // hlx:781
        // an attachment must equal the lesson's scope exactly: neither narrower, broader nor different
        // hlx:782
        let wide = pol(&["release.bin"])
            .required(&["release.bin"])
            .scope("{}")
            .json();
        // hlx:783
        let o = fx.attach(&wide);
        // hlx:784
        assert_ne!(
            o.code,
            Some(0),
            "an attachment must not broaden a project-scoped lesson: {}",
            trunc(&o.text())
        );
        // hlx:785
        let narrow = pol(&["release.bin"])
            .required(&["release.bin"])
            .scope("{\"project\":\"release-lab\",\"machine\":\"m1\"}")
            .json();
        // hlx:786
        assert_ne!(fx.attach(&narrow).code, Some(0), "or narrow it");
        // hlx:787
        let other = pol(&["release.bin"])
            .required(&["release.bin"])
            .scope("{\"project\":\"other\"}")
            .json();
        // hlx:788
        assert_ne!(fx.attach(&other).code, Some(0), "or change it");
        // hlx:789
        let extra = fx.hit_check_with(
            &id,
            "unrestricted-persona",
            "ok",
            true,
            &fx.root,
            &[
                ("INSTINCT_PROJECT", "release-lab"),
                ("INSTINCT_PERSONA", "someone"),
            ],
        );
        // hlx:790
        assert_eq!(
            extra.code,
            Some(0),
            "extra unrestricted scope must not block a valid hit"
        );
        // hlx:791
        // a lesson with two scope dimensions needs both
        // hlx:792
        let id2 = fx.bank_lesson(&["--project", "release-lab", "--persona", "p1"]);
        // hlx:793
        let one_dim = pol(&["release.bin"])
            .scope("{\"project\":\"release-lab\"}")
            .json();
        // hlx:794
        assert_ne!(fx.attach_for(&id2, &one_dim).code, Some(0));
        // hlx:795
        let two_dim = pol(&["release.bin"])
            .scope("{\"project\":\"release-lab\",\"persona\":\"p1\"}")
            .json();
        // hlx:796
        assert_eq!(fx.attach_for(&id2, &two_dim).code, Some(0));
        // hlx:797
        let o = fx.hit_check_with(
            &id2,
            "k",
            "n",
            true,
            &fx.root,
            &[
                ("INSTINCT_PROJECT", "release-lab"),
                ("INSTINCT_PERSONA", "p2"),
            ],
        );
        // hlx:798
        assert!(
            fx.hits_of(&id2).is_empty(),
            "wrong persona: {}",
            trunc(&o.text())
        );
        // hlx:799
        let o = fx.hit_check_with(
            &id2,
            "k",
            "n",
            true,
            &fx.root,
            &[
                ("INSTINCT_PROJECT", "release-lab"),
                ("INSTINCT_PERSONA", "p1"),
            ],
        );
        // hlx:800
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:801
        assert_eq!(fx.hits_of(&id2).len(), 1);
        // hlx:802
    }
    // hlx:803
    #[test]
    // hlx:804
    fn expired_quarantined_and_absent_lessons_earn_nothing_and_attachments_need_a_real_lesson() {
        // hlx:805
        // expired: a lesson whose validity ended
        // hlx:806
        let mut fx = Fx::new("expired", false);
        // hlx:807
        fx.attached();
        // hlx:808
        fx.rewrite_store(|t| t.replace("\"valid_until\":0", "\"valid_until\":1000"));
        // hlx:809
        let o = fx.hit_check("k", "it worked");
        // hlx:810
        not_recorded(&fx, &o, "expired lesson");
        // hlx:811
        // quarantined
        // hlx:812
        let mut fx = Fx::new("quarantined", true);
        // hlx:813
        fx.attached();
        // hlx:814
        let id = fx.id.clone();
        // hlx:815
        let o = fx.cli(&[
            "review",
            &id,
            "--state",
            "quarantined",
            "--reason",
            "misleading",
            "--source-ref",
            "test",
            "--store",
            &fx.st().to_string(),
        ]);
        // hlx:816
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:817
        let o = fx.hit_check("k", "it worked");
        // hlx:818
        not_recorded(&fx, &o, "quarantined lesson");
        // hlx:819
        // an attachment to an absent lesson is an error and stores nothing
        // hlx:820
        let before = tree(&fx.env);
        // hlx:821
        let p = fx.std_policy();
        // hlx:822
        let o = fx.attach_for("in-doesnotexist", &p);
        // hlx:823
        assert_ne!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:824
        assert_eq!(before, tree(&fx.env));
        // hlx:825
        let o = fx.hit_check_with("in-doesnotexist", "k", "n", true, &fx.root, &fx.envs());
        // hlx:826
        assert_ne!(o.code, Some(0));
        // hlx:827
    }
    // hlx:828
    // ================================================================ 4. observations that must not record
    // hlx:829
    fn assert_nothing_recorded(fx: &Fx, root: &Path, ctx: &str) {
        // hlx:830
        let before = tree(&fx.env);
        // hlx:831
        let o = fx.hit_check_with(&fx.id, "k-branch", "it worked", true, root, &fx.envs());
        // hlx:832
        not_recorded(fx, &o, ctx);
        // hlx:833
        assert_eq!(fx.verified_events(), 0, "{ctx}");
        // hlx:834
        assert_eq!(
            before,
            tree(&fx.env),
            "{ctx}: bank and sidecar must be unchanged"
        );
        // hlx:835
    }
    // hlx:836
    #[test]
    // hlx:837
    fn failed_abstained_missing_unreadable_symlinked_and_oversized_observations_record_nothing() {
        // hlx:838
        let mut fx = Fx::new("branches", false);
        // hlx:839
        fx.attached();
        // hlx:840
        let env = &fx.env;
        // hlx:841
        // missing root and a file as root
        // hlx:842
        assert_nothing_recorded(
            &fx,
            &env.root.join("stage").join("does-not-exist"),
            "missing root",
        );
        // hlx:843
        let file = env.put("not-a-dir", b"x");
        // hlx:844
        assert_nothing_recorded(&fx, &file, "root is a file");
        // hlx:845
        // an empty root abstains from nothing: the required file is simply absent
        // hlx:846
        let empty = env.dir("empty-root");
        // hlx:847
        assert_nothing_recorded(&fx, &empty, "empty root fails the required check");
        // hlx:848
        // symlink bypass variants
        // hlx:849
        let real = env.dir("REAL_TARGET_731");
        // hlx:850
        put_file(&real, "release.bin");
        // hlx:851
        let alias = env.root.join("stage").join("alias");
        // hlx:852
        std::os::unix::fs::symlink(&real, &alias).unwrap();
        // hlx:853
        assert_nothing_recorded(&fx, &alias, "root is a symlink to a clean tree");
        // hlx:854
        for spelling in ["alias/", "alias//", "alias/.", "alias/./"] {
            // hlx:855
            assert_nothing_recorded(
                &fx,
                &PathBuf::from(format!("{}/{spelling}", env.root.join("stage").display())),
                spelling,
            );
            // hlx:856
        }
        // hlx:857
        let parent_alias = env.root.join("stage").join("palias");
        // hlx:858
        std::os::unix::fs::symlink(env.root.join("stage"), &parent_alias).unwrap();
        // hlx:859
        assert_nothing_recorded(
            &fx,
            &parent_alias.join("REAL_TARGET_731"),
            "symlink in an ancestor of the root",
        );
        // hlx:860
        let inner = env.dir("inner-link");
        // hlx:861
        put_file(&inner, "release.bin");
        // hlx:862
        std::os::unix::fs::symlink(real.join("release.bin"), inner.join("link")).unwrap();
        // hlx:863
        assert_nothing_recorded(&fx, &inner, "symlink entry inside the tree");
        // hlx:864
        let sock_root = env.dir("sock-root");
        // hlx:865
        put_file(&sock_root, "release.bin");
        // hlx:866
        #[cfg(target_os = "linux")]
        // hlx:867
        let socket_dir = std::fs::File::open(&sock_root).unwrap();
        // hlx:868
        #[cfg(target_os = "linux")]
        // hlx:869
        let socket_path = {
            use std::os::fd::AsRawFd;
            PathBuf::from(format!("/proc/self/fd/{}/sock", socket_dir.as_raw_fd()))
        };
        // hlx:870
        #[cfg(not(target_os = "linux"))]
        // hlx:871
        let socket_path = sock_root.join("sock");
        // hlx:872
        let _l = std::os::unix::net::UnixListener::bind(socket_path).unwrap();
        // hlx:873
        assert_nothing_recorded(&fx, &sock_root, "unsupported entry kind");
        // hlx:874
        drop(_l);
        // hlx:875
        // unreadable nested directory
        // hlx:876
        if !is_root() {
            // hlx:877
            let locked = env.dir("locked-root");
            // hlx:878
            put_file(&locked, "release.bin");
            // hlx:879
            put_file(&locked, "sub/inner");
            // hlx:880
            std::fs::set_permissions(locked.join("sub"), std::fs::Permissions::from_mode(0o000))
                .unwrap();
            // hlx:881
            assert_nothing_recorded(&fx, &locked, "unreadable nested directory");
            // hlx:882
            std::fs::set_permissions(locked.join("sub"), std::fs::Permissions::from_mode(0o755))
                .unwrap();
            // hlx:883
        }
        // hlx:884
        // an observation whose exact result cannot fit the output budget
        // hlx:885
        let big = env.dir("big-root");
        // hlx:886
        put_file(&big, "release.bin");
        // hlx:887
        let names: Vec<String> = (0..400)
            .map(|i| format!("{i:03}{}", "n".repeat(252)))
            .collect();
        // hlx:888
        for n in &names {
            // hlx:889
            put_file(&big, n);
            // hlx:890
        }
        // hlx:891
        let mut allowed: Vec<&str> = vec!["release.bin"];
        // hlx:892
        allowed.extend(names.iter().map(|s| s.as_str()));
        // hlx:893
        let big_policy = pol(&allowed)
            .required(&["release.bin"])
            .scope("{\"project\":\"release-lab\"}")
            .json();
        // hlx:894
        let mut fx2 = Fx::new("branches-big", false);
        // hlx:895
        let o = fx2.attach(&big_policy);
        // hlx:896
        if o.code == Some(0) {
            // hlx:897
            assert_nothing_recorded(&fx2, &big, "output-limit observation");
            // hlx:898
        }
        // hlx:899
        // the control: the clean tree still earns exactly one verified hit afterwards
        // hlx:900
        let o = fx.hit_check("k-branch", "ok");
        // hlx:901
        one_verified(&fx, "k-branch", &o);
        // hlx:902
    }
    // hlx:903
    // ================================================================ 5. bindings
    // hlx:904
    #[test]
    // hlx:905
    fn changing_the_policy_or_the_lesson_invalidates_the_binding() {
        // hlx:906
        // changed policy: the outcome key cannot be reused for a second credit
        // hlx:907
        let mut fx = Fx::new("rebind-policy", false);
        // hlx:908
        fx.attached();
        // hlx:909
        let o = fx.hit_check("k", "first");
        // hlx:910
        one_verified(&fx, "k", &o);
        // hlx:911
        let p2 = fx.policy(&["release.bin", "extra-allowed"], &["release.bin"]);
        // hlx:912
        let o = fx.attach(&p2);
        // hlx:913
        assert_eq!(
            o.code,
            Some(0),
            "replacing a policy is an explicit new revision: {}",
            trunc(&o.text())
        );
        // hlx:914
        let before = tree(&fx.env);
        // hlx:915
        let o = fx.hit_check("k", "second");
        // hlx:916
        assert_eq!(fx.hits().len(), 1, "no second credit: {}", trunc(&o.text()));
        // hlx:917
        assert_eq!(before, tree(&fx.env));
        // hlx:918
        assert_eq!(fx.verified_count("all"), 1);
        // hlx:919
        // changed lesson content under a reused id (a trusted local edit of the bank file)
        // hlx:920
        let mut fx = Fx::new("rebind-lesson", false);
        // hlx:921
        fx.attached();
        // hlx:922
        fx.rewrite_store(|t| {
            t.replace(
                "\"how\":\"Check the inventory\"",
                "\"how\":\"Ship everything in the folder\"",
            )
        });
        // hlx:923
        let before = tree(&fx.env);
        // hlx:924
        let o = fx.hit_check("k", "it worked");
        // hlx:925
        not_recorded(&fx, &o, "lesson content changed after attachment");
        // hlx:926
        assert_eq!(before, tree(&fx.env));
        // hlx:927
        // a fresh attachment re-binds the new content
        // hlx:928
        fx.attached();
        // hlx:929
        let o = fx.hit_check("k", "it worked");
        // hlx:930
        one_verified(&fx, "k", &o);
        // hlx:931
    }
    // hlx:932
    #[test]
    // hlx:933
    fn attaching_is_idempotent_and_alters_neither_recall_nor_the_bank() {
        // hlx:934
        let mut fx = Fx::new("attach", false);
        // hlx:935
        let id = fx.id.clone();
        // hlx:936
        let st0 = fx.st().to_string();
        // hlx:937
        let recall_args = [
            "recall",
            "--q",
            "Packaging the release",
            "--k",
            "1",
            "--store",
            st0.as_str(),
        ];
        // hlx:938
        let recall_before = fx.cli(&recall_args).out;
        // hlx:939
        let bank_before = std::fs::read(&fx.store).unwrap();
        // hlx:940
        let p = fx.std_policy();
        // hlx:941
        let o = fx.attach(&p);
        // hlx:942
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:943
        assert_eq!(
            std::fs::read(&fx.store).unwrap(),
            bank_before,
            "attaching does not write the bank"
        );
        // hlx:944
        assert_eq!(
            fx.cli(&recall_args).out,
            recall_before,
            "attaching does not change recall"
        );
        // hlx:945
        assert!(
            fx.hits().is_empty(),
            "attaching earns no hit and runs no observation"
        );
        // hlx:946
        assert!(!o.text().contains(fx.root.to_str().unwrap()));
        // hlx:947
        // identical attachment again: success, no change
        // hlx:948
        let snap = tree(&fx.env);
        // hlx:949
        let o = fx.attach(&p);
        // hlx:950
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:951
        assert_eq!(
            snap,
            tree(&fx.env),
            "a duplicate identical attachment is idempotent"
        );
        // hlx:952
        // invalid policies are errors and store nothing
        // hlx:953
        let bad_policies: Vec<String> = vec![
            // hlx:954
            "{".into(),
            // hlx:955
            "{}".into(),
            // hlx:956
            pol(&["a"])
                .required(&["b"])
                .scope("{\"project\":\"release-lab\"}")
                .json(),
            // hlx:957
            pol(&["../a"]).scope("{\"project\":\"release-lab\"}").json(),
            // hlx:958
            pol(&["a"])
                .scope("{\"project\":\"release-lab\"}")
                .extra(",\"root\":\"/tmp\"")
                .json(),
            // hlx:959
            pol(&["a"])
                .scope("{\"project\":\"release-lab\"}")
                .schema("\"instinct.artifact-policy/v2\"")
                .json(),
            // hlx:960
        ];
        // hlx:961
        for b in &bad_policies {
            // hlx:962
            let o = fx.attach(b);
            // hlx:963
            assert_ne!(o.code, Some(0), "{}", trunc(b));
            // hlx:964
            assert_eq!(snap, tree(&fx.env), "{}", trunc(b));
            // hlx:965
        }
        // hlx:966
        // an explicit store is required for attach; the environment's store is not a substitute
        // hlx:967
        let f = fx.env.put("p.json", p.as_bytes());
        // hlx:968
        let snap = tree(&fx.env); // snapshot after harness creates the input file
                                  // hlx:969
        let o = fx.cli_env(
            &[
                "check",
                "attach",
                "--lesson",
                &id,
                "--input",
                f.to_str().unwrap(),
            ],
            &[("INSTINCT_STORE", fx.st())],
        );
        // hlx:970
        assert_ne!(o.code, Some(0), "attach without --store");
        // hlx:971
        assert_eq!(snap, tree(&fx.env));
        // hlx:972
        // argument mistakes
        // hlx:973
        let st = fx.st().to_string();
        // hlx:974
        let fs = f.to_str().unwrap().to_string();
        // hlx:975
        for args in [
            // hlx:976
            vec!["check", "attach"],
            // hlx:977
            vec!["check", "attach", "--lesson", &id, "--store", &st],
            // hlx:978
            vec!["check", "attach", "--store", &st, "--input", &fs],
            // hlx:979
            vec![
                "check", "attach", "--lesson", &id, "--lesson", &id, "--store", &st, "--input", &fs,
            ],
            // hlx:980
            vec![
                "check", "attach", "--lesson", &id, "--store", &st, "--input", &fs, "extra",
            ],
            // hlx:981
            vec![
                "check", "attach", "--lesson", &id, "--store", &st, "--input", &fs, "--root",
                "/tmp",
            ],
            // hlx:982
            vec![
                "check", "attach", "--lesson", &id, "--store", &st, "--input", &fs, "--bogus",
            ],
            // hlx:983
        ] {
            // hlx:984
            let o = fx.cli(&args);
            // hlx:985
            assert_ne!(o.code, Some(0), "{args:?}");
            // hlx:986
            assert_eq!(snap, tree(&fx.env), "{args:?}");
            // hlx:987
        }
        // hlx:988
    }
    // hlx:989
    // ================================================================ 6. the no-check path is unchanged
    // hlx:990
    #[test]
    // hlx:991
    fn feedback_without_check_is_byte_identical_with_or_without_attachments() {
        // hlx:992
        for attach in [false, true] {
            // hlx:993
            let mut fx = Fx::new(
                if attach {
                    "legacy-attached"
                } else {
                    "legacy-plain"
                },
                false,
            );
            // hlx:994
            if attach {
                // hlx:995
                fx.attached();
                // hlx:996
            }
            // hlx:997
            let id = fx.id.clone();
            // hlx:998
            let st = fx.st().to_string();
            // hlx:999
            let o = fx.cli(&[
                "hit",
                &id,
                "--note",
                "x",
                "--outcome-id",
                "k1",
                "--store",
                &st,
            ]);
            // hlx:1000
            assert_eq!(o.code, Some(0));
            // hlx:1001
            assert_eq!(o.text(), format!("hit recorded for {id}\n"));
            // hlx:1002
            let o = fx.cli(&[
                "hit",
                &id,
                "--note",
                "x",
                "--outcome-id",
                "k1",
                "--store",
                &st,
            ]);
            // hlx:1003
            assert_eq!(o.text(), format!("outcome already recorded for {id}\n"));
            // hlx:1004
            let o = fx.cli(&["miss", &id, "--note", "y", "--store", &st]);
            // hlx:1005
            assert_eq!(o.text(), format!("miss recorded for {id}\n"));
            // hlx:1006
            let o = fx.cli(&["hit", &id, "--note", "z", &"--store".to_string(), &st]);
            // hlx:1007
            assert_eq!(o.text(), format!("hit recorded for {id}\n"));
            // hlx:1008
            let events = fx.events();
            // hlx:1009
            let hit = events
                .iter()
                .find(|e| e.get("outcome_id").is_some())
                .unwrap();
            // hlx:1010
            assert_eq!(
                key_list(hit),
                vec!["kind", "id", "ts", "note", "outcome_id"],
                "the legacy hit event shape"
            );
            // hlx:1011
            let plain = events
                .iter()
                .filter(|e| e.get("kind").and_then(J::as_str) == Some("hit"))
                .last()
                .unwrap();
            // hlx:1012
            assert_eq!(key_list(plain), vec!["kind", "id", "ts", "note"]);
            // hlx:1013
            assert!(events.iter().all(|e| e.get("check_verification").is_none()));
            // hlx:1014
            // evaluation with no verified events: exactly the legacy keys and no verified wording
            // hlx:1015
            let j = fx.eval_json("all");
            // hlx:1016
            assert_eq!(
                key_list(&j),
                LEGACY_EVAL_KEYS.to_vec(),
                "no verified events, no new keys"
            );
            // hlx:1017
            assert!(
                !fx.eval_text().to_lowercase().contains("verified"),
                "{}",
                fx.eval_text()
            );
            // hlx:1018
        }
        // hlx:1019
        // two banks built the same way evaluate identically apart from the clock
        // hlx:1020
        let a = Fx::new("legacy-a", false);
        // hlx:1021
        let b = Fx::new("legacy-b", false);
        // hlx:1022
        let mut texts = Vec::new();
        // hlx:1023
        for fx in [&a, &b] {
            // hlx:1024
            let id = fx.id.clone();
            // hlx:1025
            fx.cli(&["hit", &id, "--note", "x", "--store", fx.st()]);
            // hlx:1026
            let t = fx.eval_text();
            // hlx:1027
            texts.push(t.replace(&id, "ID"));
            // hlx:1028
        }
        // hlx:1029
        assert_eq!(texts[0], texts[1]);
        // hlx:1030
    }
    // hlx:1031
    // ================================================================ 7. evaluation splits claimed and verified without double counting
    // hlx:1032
    #[test]
    // hlx:1033
    fn eval_separates_verified_from_claimed_counts_and_counts_each_hit_once() {
        // hlx:1034
        let mut fx = Fx::new("eval-split", false);
        // hlx:1035
        fx.attached();
        // hlx:1036
        let a = fx.id.clone();
        // hlx:1037
        let b = fx.bank_lesson(&["--project", "release-lab", "--persona", "claimed-only"]);
        // hlx:1038
        let st = fx.st().to_string();
        // hlx:1039
        let o = fx.cli(&[
            "hit",
            &b,
            "--note",
            "claimed",
            "--outcome-id",
            "kb",
            "--store",
            &st,
        ]);
        // hlx:1040
        assert_eq!(o.code, Some(0));
        // hlx:1041
        let before = fx.eval_json("all");
        // hlx:1042
        assert_eq!(
            key_list(&before),
            LEGACY_EVAL_KEYS.to_vec(),
            "only claimed hits so far"
        );
        // hlx:1043
        let o = fx.hit_check("ka", "verified");
        // hlx:1044
        one_verified(&fx, "ka", &o);
        // hlx:1045
        let j = fx.eval_json("all");
        // hlx:1046
        let keys = key_list(&j);
        // hlx:1047
        for k in LEGACY_EVAL_KEYS {
            // hlx:1048
            assert!(keys.contains(&k.to_string()), "legacy key {k} stays");
            // hlx:1049
        }
        // hlx:1050
        assert!(
            keys.contains(&"verification".to_string()),
            "a separate verified summary is appended: {keys:?}"
        );
        // hlx:1051
        let s = fx.summary("all");
        // hlx:1052
        assert!(s.present);
        // hlx:1053
        assert_eq!(
            (s.total, s.claimed, s.verified, s.downgraded, s.invalid),
            (2, 1, 1, 0, 0),
            "one verified, one claimed, each counted once: {}",
            trunc(&to_s(&j))
        );
        // hlx:1054
        // the totals still count each hit once: both lessons paid off exactly once
        // hlx:1055
        let paid = match j.get("paid_off") {
            // hlx:1056
            Some(J::Arr(v)) => v.clone(),
            // hlx:1057
            other => panic!("{other:?}"),
            // hlx:1058
        };
        // hlx:1059
        let hits_of = |id: &str| {
            paid.iter()
                .find(|e| sf(e, "id") == id)
                .map(|e| to_s(e.get("hits").unwrap()))
        };
        // hlx:1060
        assert_eq!(
            hits_of(&a).as_deref(),
            Some("1"),
            "the verified hit is one hit"
        );
        // hlx:1061
        assert_eq!(hits_of(&b).as_deref(), Some("1"));
        // hlx:1062
        assert!(
            fx.eval_text().to_lowercase().contains("verified"),
            "{}",
            fx.eval_text()
        );
        // hlx:1063
        // a retraction removes the credit
        // hlx:1064
        let o = fx.cli(&["retract", "hit", &a, "--store", &st]);
        // hlx:1065
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1066
        let s = fx.summary("all");
        // hlx:1067
        assert_eq!(
            (s.total, s.verified, s.downgraded),
            (1, 0, 0),
            "a retracted verified hit loses its credit and is not a downgrade: {s:?}"
        );
        // hlx:1068
        let j = fx.eval_json("all");
        // hlx:1069
        let paid = match j.get("paid_off") {
            // hlx:1070
            Some(J::Arr(v)) => v.clone(),
            // hlx:1071
            other => panic!("{other:?}"),
            // hlx:1072
        };
        // hlx:1073
        assert!(
            paid.iter().all(|e| sf(e, "id") != a),
            "the retracted hit no longer pays off"
        );
        // hlx:1074
    }
    // hlx:1075
    #[test]
    // hlx:1076
    fn eval_respects_the_time_window_for_verified_hits() {
        // hlx:1077
        let mut fx = Fx::new("eval-window", false);
        // hlx:1078
        fx.attached();
        // hlx:1079
        let o = fx.hit_check("k", "verified");
        // hlx:1080
        one_verified(&fx, "k", &o);
        // hlx:1081
        assert_eq!(fx.verified_count("all"), 1);
        // hlx:1082
        assert_eq!(fx.verified_count("7d"), 1);
        // hlx:1083
        // move the whole hit event 90 days into the past
        // hlx:1084
        let ts = to_s(fx.hits()[0].get("ts").unwrap());
        // hlx:1085
        let old: u64 = ts.parse::<u64>().unwrap() - 90 * 86_400;
        // hlx:1086
        fx.rewrite_store(|t| {
            t.replace(
                &format!("\"ts\":{ts},\"note\""),
                &format!("\"ts\":{old},\"note\""),
            )
        });
        // hlx:1087
        assert_eq!(
            fx.verified_count("all"),
            1,
            "still counted in the all-time window"
        );
        // hlx:1088
        assert_eq!(fx.verified_count("7d"), 0, "outside the 7 day window");
        // hlx:1089
        assert_eq!(fx.verified_count("30d"), 0);
        // hlx:1090
    }
    // hlx:1091
    #[test]
    // hlx:1092
    fn malformed_forged_or_misbound_verification_metadata_is_never_credited() {
        // hlx:1093
        let mut fx = Fx::new("eval-forged", false);
        // hlx:1094
        fx.attached();
        // hlx:1095
        let a = fx.id.clone();
        // hlx:1096
        let o = fx.hit_check("ka", "verified");
        // hlx:1097
        let ev = one_verified(&fx, "ka", &o);
        // hlx:1098
        let cv_text = to_s(ev.get("check_verification").unwrap());
        // hlx:1099
        assert_eq!(fx.verified_count("all"), 1);
        // hlx:1100
        let original = std::fs::read_to_string(&fx.store).unwrap();
        // hlx:1101
        // a claimed hit on another lesson, then graft metadata onto it
        // hlx:1102
        let b = fx.bank_lesson(&["--project", "release-lab", "--persona", "claimed-only"]);
        // hlx:1103
        let st = fx.st().to_string();
        // hlx:1104
        fx.cli(&[
            "hit",
            &b,
            "--note",
            "claimed",
            "--outcome-id",
            "kb",
            "--store",
            &st,
        ]);
        // hlx:1105
        let with_claimed = std::fs::read_to_string(&fx.store).unwrap();
        // hlx:1106
        assert_eq!(fx.verified_count("all"), 1);
        // hlx:1107
        let claimed_line = with_claimed
            .lines()
            .find(|l| l.contains("\"outcome_id\":\"kb\""))
            .unwrap()
            .to_string();
        // hlx:1108
        let graft = |extra: &str| {
            // hlx:1109
            let forged =
                claimed_line.replacen('}', &format!(",\"check_verification\":{extra}}}"), 1);
            // hlx:1110
            std::fs::write(&fx.store, with_claimed.replace(&claimed_line, &forged)).unwrap();
            // hlx:1111
            fx.summary("all")
            // hlx:1112
        };
        // hlx:1113
        let s = graft(&cv_text);
        // hlx:1114
        assert_eq!(
            (s.total, s.verified),
            (2, 1),
            "another lesson's verification grafted onto a claimed hit is not credited: {s:?}"
        );
        // hlx:1115
        for (what, extra) in [
// hlx:1116
("an empty object", "{}"),
// hlx:1117
("a plausible-looking stub", "{\"version\":1,\"authorization\":\"not_evaluated\",\"evidence_origin\":\"adapter_observed\"}"),
// hlx:1118
("a bare string", "\"verified\""),
// hlx:1119
] {
// hlx:1120
let s = graft(extra);
// hlx:1121
assert_eq!((s.total, s.verified), (2, 1), "{what} is not a receipt: {s:?}");
// hlx:1122
assert!(s.invalid >= 1, "{what} is structurally invalid metadata and is reported, not promoted: {s:?}");
// hlx:1123
}
        // hlx:1124
        for extra in ["true", "null"] {
            // hlx:1125
            let s = graft(extra);
            // hlx:1126
            assert_eq!((s.total, s.verified), (2, 1), "{extra}: {s:?}");
            // hlx:1127
        }
        // hlx:1128
        // the real receipt with a broken authority claim is not credited either, and is reported
        // hlx:1129
        if original.contains("\"authorization\":\"not_evaluated\"") {
            // hlx:1130
            std::fs::write(
                &fx.store,
                original.replace(
                    "\"authorization\":\"not_evaluated\"",
                    "\"authorization\":\"granted\"",
                ),
            )
            .unwrap();
            // hlx:1131
            let s = fx.summary("all");
            // hlx:1132
            assert_eq!(
                (s.total, s.verified, s.claimed),
                (1, 0, 1),
                "a receipt that grants authority is invalid: {s:?}"
            );
            // hlx:1133
            assert!(s.invalid + s.downgraded >= 1, "{s:?}");
            // hlx:1134
        }
        // hlx:1135
        if original.contains("\"evidence_origin\":\"adapter_observed\"") {
            // hlx:1136
            std::fs::write(
                &fx.store,
                original.replace(
                    "\"evidence_origin\":\"adapter_observed\"",
                    "\"evidence_origin\":\"caller_reported\"",
                ),
            )
            .unwrap();
            // hlx:1137
            let s = fx.summary("all");
            // hlx:1138
            assert_eq!(
                (s.total, s.verified),
                (1, 0),
                "a receipt that is not adapter-observed is not a verified hit: {s:?}"
            );
            // hlx:1139
        }
        // hlx:1140
        // whatever happened to the metadata, the hit itself still counts once as a claimed hit
        // hlx:1141
        let j = fx.eval_json("all");
        // hlx:1142
        let paid = match j.get("paid_off") {
            // hlx:1143
            Some(J::Arr(v)) => v.clone(),
            // hlx:1144
            other => panic!("{other:?}"),
            // hlx:1145
        };
        // hlx:1146
        assert!(
            paid.iter().any(|e| sf(e, "id") == a),
            "the event is still a hit"
        );
        // hlx:1147
    }
    // hlx:1148
    // ================================================================ 8. concurrency
    // hlx:1149
    #[test]
    // hlx:1150
    fn concurrent_verified_requests_with_one_key_earn_one_hit_and_one_receipt() {
        // hlx:1151
        for native in [false, true] {
            // hlx:1152
            let mut fx = Fx::new(if native { "conc-native" } else { "conc-jsonl" }, native);
            // hlx:1153
            fx.attached();
            // hlx:1154
            let args: Vec<String> = [
                "hit",
                &fx.id,
                "--check",
                "--root",
                fx.root.to_str().unwrap(),
                "--trusted-staging",
                "--outcome-id",
                "same-key",
                "--store",
                fx.st(),
                "--note",
                "race",
            ]
            // hlx:1155
            .iter()
            // hlx:1156
            .map(|s| s.to_string())
            // hlx:1157
            .collect();
            // hlx:1158
            let mut kids = Vec::new();
            // hlx:1159
            for _ in 0..6 {
                // hlx:1160
                let mut c = Command::new(bin());
                // hlx:1161
                c.args(&args)
                    // hlx:1162
                    .current_dir(fx.env.root.join("cwd"))
                    // hlx:1163
                    .env("HOME", fx.env.root.join("home"))
                    // hlx:1164
                    .env("XDG_DATA_HOME", fx.env.root.join("data"))
                    // hlx:1165
                    .env("INSTINCT_PROJECT", "release-lab")
                    // hlx:1166
                    .stdin(Stdio::null())
                    // hlx:1167
                    .stdout(Stdio::piped())
                    // hlx:1168
                    .stderr(Stdio::piped());
                // hlx:1169
                for (k, _) in std::env::vars() {
                    // hlx:1170
                    if k.starts_with("INSTINCT_") && k != "INSTINCT_PROJECT" {
                        // hlx:1171
                        c.env_remove(k);
                        // hlx:1172
                    }
                    // hlx:1173
                }
                // hlx:1174
                kids.push(c.spawn().unwrap());
                // hlx:1175
            }
            // hlx:1176
            let mut ok = 0;
            // hlx:1177
            for k in kids {
                // hlx:1178
                let o = k.wait_with_output().unwrap();
                // hlx:1179
                assert!(o.status.code().is_some(), "killed by a signal");
                // hlx:1180
                assert!(
                    !String::from_utf8_lossy(&o.stderr).contains("panicked"),
                    "{}",
                    String::from_utf8_lossy(&o.stderr)
                );
                // hlx:1181
                if o.status.code() == Some(0) {
                    // hlx:1182
                    ok += 1;
                    // hlx:1183
                }
                // hlx:1184
            }
            // hlx:1185
            assert!(ok >= 1, "at least one request succeeds");
            // hlx:1186
            assert_eq!(fx.hits().len(), 1, "one key, one hit (native={native})");
            // hlx:1187
            assert_eq!(fx.verified_events(), 1, "one receipt event");
            // hlx:1188
            assert_eq!(fx.verified_count("all"), 1);
            // hlx:1189
            let _ = fx.events();
            // hlx:1190
        }
        // hlx:1191
        // distinct keys are distinct outcomes: none is lost
        // hlx:1192
        let mut fx = Fx::new("conc-distinct", true);
        // hlx:1193
        fx.attached();
        // hlx:1194
        let mut kids = Vec::new();
        // hlx:1195
        for i in 0..3 {
            // hlx:1196
            let key = format!("key-{i}");
            // hlx:1197
            let mut c = Command::new(bin());
            // hlx:1198
            c.args([
                "hit",
                &fx.id,
                "--check",
                "--root",
                fx.root.to_str().unwrap(),
                "--trusted-staging",
                "--outcome-id",
                &key,
                "--store",
                fx.st(),
            ])
            // hlx:1199
            .current_dir(fx.env.root.join("cwd"))
            // hlx:1200
            .env("HOME", fx.env.root.join("home"))
            // hlx:1201
            .env("XDG_DATA_HOME", fx.env.root.join("data"))
            // hlx:1202
            .env("INSTINCT_PROJECT", "release-lab")
            // hlx:1203
            .stdin(Stdio::null())
            // hlx:1204
            .stdout(Stdio::piped())
            // hlx:1205
            .stderr(Stdio::piped());
            // hlx:1206
            kids.push(c.spawn().unwrap());
            // hlx:1207
        }
        // hlx:1208
        for k in kids {
            // hlx:1209
            let o = k.wait_with_output().unwrap();
            // hlx:1210
            assert_eq!(
                o.status.code(),
                Some(0),
                "{}",
                String::from_utf8_lossy(&o.stdout)
            );
            // hlx:1211
        }
        // hlx:1212
        assert_eq!(fx.hits().len(), 3);
        // hlx:1213
        assert_eq!(fx.verified_events(), 3);
        // hlx:1214
    }
    // hlx:1215
    // ================================================================ 9. formats, migration and old readers
    // hlx:1216
    #[test]
    // hlx:1217
    fn verified_hits_survive_migration_and_do_not_break_plain_commands() {
        // hlx:1218
        let mut fx = Fx::new("migrate", false);
        // hlx:1219
        fx.attached();
        // hlx:1220
        let o = fx.hit_check("k", "verified");
        // hlx:1221
        let ev = one_verified(&fx, "k", &o);
        // hlx:1222
        let cv = to_s(ev.get("check_verification").unwrap());
        // hlx:1223
        let new_store = fx.env.root.join("banks").join("migrated.hxdb");
        // hlx:1224
        let o = fx.cli(&[
            "migrate",
            "--store",
            fx.st(),
            "--to",
            new_store.to_str().unwrap(),
        ]);
        // hlx:1225
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1226
        let migrated = Fx {
            env: Env {
                root: fx.env.root.clone(),
            },
            store: new_store.clone(),
            root: fx.root.clone(),
            id: fx.id.clone(),
            n: 0,
        };
        // hlx:1227
        let hits = migrated.hits();
        // hlx:1228
        assert_eq!(hits.len(), 1, "counts preserved");
        // hlx:1229
        assert_eq!(
            to_s(hits[0].get("check_verification").unwrap()),
            cv,
            "the evidence binding is preserved"
        );
        // hlx:1230
        assert_eq!(migrated.verified_count("all"), 1);
        // hlx:1231
        std::mem::forget(migrated);
        // hlx:1232
        // plain commands keep working on a bank that holds verified events (an old reader would count a hit, never verify it)
        // hlx:1233
        let id = fx.id.clone();
        // hlx:1234
        let st = fx.st().to_string();
        // hlx:1235
        let recall = fx.cli(&[
            "recall",
            "--q",
            "Packaging the release",
            "--k",
            "1",
            "--store",
            &st,
        ]);
        // hlx:1236
        assert_eq!(recall.code, Some(0));
        // hlx:1237
        assert!(recall.text().contains("1 hit"), "{}", trunc(&recall.text()));
        // hlx:1238
        for args in [
            // hlx:1239
            vec!["stats", "--store", &st],
            // hlx:1240
            vec!["eval", "--store", &st],
            // hlx:1241
            vec!["instincts", "--store", &st],
            // hlx:1242
            vec!["export", "--store", &st],
            // hlx:1243
        ] {
            // hlx:1244
            let o = fx.cli(&args);
            // hlx:1245
            assert_eq!(o.code, Some(0), "{args:?}: {}", trunc(&o.text()));
            // hlx:1246
        }
        // hlx:1247
        let o = fx.cli(&["miss", &id, "--note", "later miss", "--store", &st]);
        // hlx:1248
        assert_eq!(o.code, Some(0));
        // hlx:1249
        let o = fx.cli(&["retract", "miss", &id, "--store", &st]);
        // hlx:1250
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1251
        assert_eq!(
            fx.verified_count("all"),
            1,
            "the verified hit is untouched by unrelated feedback"
        );
        // hlx:1252
    }
    // hlx:1253
    // ================================================================ 10. privacy
    // hlx:1254
    #[test]
    // hlx:1255
    fn nothing_private_leaks_into_events_outputs_or_the_sidecar() {
        // hlx:1256
        let mut fx = Fx::new("privacy", false);
        // hlx:1257
        let secret = "PRIVATE-SENTINEL_731.txt";
        // hlx:1258
        put_file(&fx.root, secret);
        // hlx:1259
        let p = fx.policy(&["release.bin", secret], &["release.bin"]);
        // hlx:1260
        let o = fx.attach(&p);
        // hlx:1261
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1262
        let o = fx.hit_check("k", "verified");
        // hlx:1263
        let ev = one_verified(&fx, "k", &o);
        // hlx:1264
        let root_s = fx.root.to_str().unwrap().to_string();
        // hlx:1265
        let line = to_s(&ev);
        // hlx:1266
        assert!(
            !line.contains(secret),
            "file names from the observation are not exported in the event: {line}"
        );
        // hlx:1267
        assert!(!o.text().contains(secret), "{}", o.text());
        // hlx:1268
        for text in [
            fx.eval_text(),
            to_s(&fx.eval_json("all")),
            fx.cli(&["recall", "--q", "Packaging the release", "--store", fx.st()])
                .text(),
        ] {
            // hlx:1269
            assert!(
                !text.contains(secret) && !text.contains(&root_s),
                "{}",
                trunc(&text)
            );
            // hlx:1270
        }
        // hlx:1271
        // no stored file anywhere (bank, sidecar, journals) holds the root path: it is never an executable grant
        // hlx:1272
        let mut found = Vec::new();
        // hlx:1273
        for e in std::fs::read_dir(fx.env.root.join("banks"))
            .unwrap()
            .filter_map(|e| e.ok())
        {
            // hlx:1274
            if let Ok(b) = std::fs::read(e.path()) {
                // hlx:1275
                if String::from_utf8_lossy(&b).contains(&root_s) {
                    // hlx:1276
                    found.push(e.path());
                    // hlx:1277
                }
                // hlx:1278
            }
            // hlx:1279
        }
        // hlx:1280
        assert!(found.is_empty(), "the root path was stored in {found:?}");
        // hlx:1281
        // the sidecar exists beside the bank and is private
        // hlx:1282
        let side: Vec<_> = std::fs::read_dir(fx.env.root.join("banks"))
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().contains("capabilities"))
            .collect();
        // hlx:1283
        assert!(
            !side.is_empty(),
            "the attachment sidecar `<bank>.capabilities.hxdb` must exist beside the bank"
        );
        // hlx:1284
        for e in side {
            // hlx:1285
            let mode = std::fs::metadata(e.path()).unwrap().permissions().mode() & 0o777;
            // hlx:1286
            assert_eq!(
                mode & 0o077,
                0,
                "{:?} must be private, mode {mode:o}",
                e.path()
            );
            // hlx:1287
        }
        // hlx:1288
    }
    // hlx:1289
    // ================================================================ 11. MCP
    // hlx:1290
    fn mcp(fx: &Fx, envs: &[(&str, &str)], requests: &[String]) -> Vec<String> {
        // hlx:1291
        let mut all: Vec<(&str, &str)> = vec![
            ("INSTINCT_STORE", fx.st()),
            ("INSTINCT_PROJECT", "release-lab"),
        ];
        // hlx:1292
        all.extend_from_slice(envs);
        // hlx:1293
        let input = requests.join("\n") + "\n";
        // hlx:1294
        let o = fx.env.exec_raw(&["mcp"], input.as_bytes(), &all, false);
        // hlx:1295
        o.text().lines().map(|l| l.to_string()).collect()
        // hlx:1296
    }
    // hlx:1297
    fn feedback(id: &str, extra: &str) -> String {
        // hlx:1298
        format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"instinct_feedback\",\"arguments\":{{\"id\":\"{id}\",\"paid_off\":true,\"note\":\"it worked\"{extra}}}}}}}")
        // hlx:1299
    }
    // hlx:1300
    fn is_error(line: &str) -> bool {
        // hlx:1301
        line.contains("\"isError\":true") || line.contains("\"error\"")
        // hlx:1302
    }
    // hlx:1303
    #[test]
    // hlx:1304
    fn mcp_verified_feedback_needs_an_explicit_server_grant_and_never_trusts_the_request() {
        // hlx:1305
        let mut fx = Fx::new("mcp", false);
        // hlx:1306
        fx.attached();
        // hlx:1307
        let id = fx.id.clone();
        // hlx:1308
        let root = fx.root.to_str().unwrap().to_string();
        // hlx:1309
        let chk = |key: &str, more: &str| {
            feedback(
                &id,
                &format!(",\"check\":true,\"outcome_id\":\"{key}\"{more}"),
            )
        };
        // hlx:1310
        // default denied: no server grant, whatever the request says
        // hlx:1311
        let before = tree(&fx.env);
        // hlx:1312
        let r = mcp(
            &fx,
            &[],
            &[
                chk("m1", ",\"trusted_staging\":true"),
                chk(
                    "m2",
                    &format!(",\"trusted_staging\":true,\"root\":\"{root}\""),
                ),
                chk(
                    "m3",
                    &format!(",\"trusted_staging\":true,\"check_root\":\"{root}\""),
                ),
            ],
        );
        // hlx:1313
        assert_eq!(r.len(), 3, "{r:?}");
        // hlx:1314
        assert!(
            r.iter().all(|l| is_error(l)),
            "no INSTINCT_CHECK_ROOT, no observation: {r:?}"
        );
        // hlx:1315
        assert!(fx.hits().is_empty());
        // hlx:1316
        assert_eq!(before, tree(&fx.env));
        // hlx:1317
        // a grant without the request's own acknowledgement
        // hlx:1318
        let grant = [("INSTINCT_CHECK_ROOT", root.as_str())];
        // hlx:1319
        let r = mcp(
            &fx,
            &grant,
            &[
                chk("m4", ""),
                chk("m5", ",\"trusted_staging\":false"),
                chk("m6", ",\"trusted_staging\":\"true\""),
                chk("m7", ",\"trusted_staging\":1"),
            ],
        );
        // hlx:1320
        assert!(r.iter().all(|l| is_error(l)), "{r:?}");
        // hlx:1321
        assert!(fx.hits().is_empty());
        // hlx:1322
        // a miss cannot be checked, and checked feedback cannot rest on the note alone
        // hlx:1323
        let r = mcp(&fx, &grant, &[format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"instinct_feedback\",\"arguments\":{{\"id\":\"{id}\",\"paid_off\":false,\"note\":\"n\",\"check\":true,\"outcome_id\":\"m8\",\"trusted_staging\":true}}}}}}")]);
        // hlx:1324
        assert!(is_error(&r[0]), "{r:?}");
        // hlx:1325
        assert!(fx.hits().is_empty() && fx.misses() == 0);
        // hlx:1326
        let r = mcp(
            &fx,
            &grant,
            &[
                chk("", ",\"trusted_staging\":true"),
                chk("   ", ",\"trusted_staging\":true"),
            ],
        );
        // hlx:1327
        assert!(r.iter().all(|l| is_error(l)), "{r:?}");
        // hlx:1328
        assert!(fx.hits().is_empty());
        // hlx:1329
        // the grant names one root; a different root in the request does not move it
        // hlx:1330
        let dirty = fx.env.dir("dirty-root");
        // hlx:1331
        put_file(&dirty, "release.bin");
        // hlx:1332
        put_file(&dirty, ".hidden-extra");
        // hlx:1333
        let dirty_s = dirty.to_str().unwrap().to_string();
        // hlx:1334
        let r = mcp(
            &fx,
            &[("INSTINCT_CHECK_ROOT", dirty_s.as_str())],
            &[
                chk(
                    "m9",
                    &format!(",\"trusted_staging\":true,\"root\":\"{root}\""),
                ),
                chk("m10", ",\"trusted_staging\":true"),
            ],
        );
        // hlx:1335
        assert!(
            fx.hits().is_empty(),
            "the clean root in the request must not replace the dirty grant: {r:?}"
        );
        // hlx:1336
        // the note 'it worked' never substitutes for the check
        // hlx:1337
        assert!(r.iter().all(|l| !l.contains("hit recorded")), "{r:?}");
        // hlx:1338
        // with the matching grant and acknowledgement the hit is earned once
        // hlx:1339
        let r = mcp(
            &fx,
            &grant,
            &[
                chk("m11", ",\"trusted_staging\":true"),
                chk("m11", ",\"trusted_staging\":true"),
            ],
        );
        // hlx:1340
        assert_eq!(r.len(), 2, "{r:?}");
        // hlx:1341
        assert!(!is_error(&r[0]), "{r:?}");
        // hlx:1342
        assert!(
            r.iter().all(|l| !l.contains(&root)),
            "the granted root path is not echoed: {r:?}"
        );
        // hlx:1343
        let hits = fx.hits();
        // hlx:1344
        assert_eq!(hits.len(), 1, "a retry with the same key earns nothing");
        // hlx:1345
        assert!(hits[0].get("check_verification").is_some());
        // hlx:1346
        assert_eq!(fx.verified_count("all"), 1);
        // hlx:1347
    }
    // hlx:1348
    #[test]
    // hlx:1349
    fn cli_and_mcp_verified_hits_have_the_same_evidence_shape_and_plain_feedback_is_unchanged() {
        // hlx:1350
        let mut fx = Fx::new("parity", false);
        // hlx:1351
        fx.attached();
        // hlx:1352
        let a = fx.id.clone();
        // hlx:1353
        let b = fx.bank_lesson(&["--project", "release-lab", "--persona", "second"]);
        // hlx:1354
        let p2 = pol(&["release.bin"])
            .required(&["release.bin"])
            .scope("{\"project\":\"release-lab\",\"persona\":\"second\"}")
            .json();
        // hlx:1355
        assert_eq!(fx.attach_for(&b, &p2).code, Some(0));
        // hlx:1356
        let o = fx.hit_check("kc", "cli");
        // hlx:1357
        let cli_ev = one_verified(&fx, "kc", &o);
        // hlx:1358
        let root = fx.root.to_str().unwrap().to_string();
        // hlx:1359
        let grant = [
            ("INSTINCT_CHECK_ROOT", root.as_str()),
            ("INSTINCT_PERSONA", "second"),
        ];
        // hlx:1360
        let r = mcp(
            &fx,
            &grant,
            &[feedback(
                &b,
                ",\"check\":true,\"outcome_id\":\"km\",\"trusted_staging\":true",
            )],
        );
        // hlx:1361
        assert!(!is_error(&r[0]), "{r:?}");
        // hlx:1362
        let mcp_hits = fx.hits_of(&b);
        // hlx:1363
        assert_eq!(mcp_hits.len(), 1);
        // hlx:1364
        let keys = |e: &J| match e.get("check_verification") {
            // hlx:1365
            Some(J::Obj(v)) => v.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
            // hlx:1366
            other => panic!("{other:?}"),
            // hlx:1367
        };
        // hlx:1368
        assert_eq!(
            keys(&cli_ev),
            keys(&mcp_hits[0]),
            "the CLI and MCP record the same evidence fields"
        );
        // hlx:1369
        assert_eq!(
            key_list(&cli_ev),
            key_list(&mcp_hits[0]),
            "and the same event shape"
        );
        // hlx:1370
        // plain MCP feedback (no check) is unchanged and records a claimed hit
        // hlx:1371
        let r = mcp(&fx, &[], &[feedback(&a, ",\"outcome_id\":\"plain\"")]);
        // hlx:1372
        assert!(!is_error(&r[0]), "{r:?}");
        // hlx:1373
        let plain: Vec<J> = fx
            .hits_of(&a)
            .into_iter()
            .filter(|e| e.get("outcome_id").and_then(J::as_str) == Some("plain"))
            .collect();
        // hlx:1374
        assert_eq!(plain.len(), 1);
        // hlx:1375
        assert!(plain[0].get("check_verification").is_none());
        // hlx:1376
        assert_eq!(
            key_list(&plain[0]),
            vec!["kind", "id", "ts", "note", "outcome_id"]
        );
        // hlx:1377
        // `check` absent or false is the ordinary path
        // hlx:1378
        let r = mcp(
            &fx,
            &[],
            &[feedback(&a, ",\"check\":false,\"outcome_id\":\"plain2\"")],
        );
        // hlx:1379
        assert!(!is_error(&r[0]), "{r:?}");
        // hlx:1380
        assert!(fx
            .hits_of(&a)
            .iter()
            .filter(|e| e.get("outcome_id").and_then(J::as_str) == Some("plain2"))
            .all(|e| e.get("check_verification").is_none()));
        // hlx:1381
    }
    // hlx:1382
    // ================================================================ 12. the consolidation fold (JSONL: supersede events are appended as public events)
    // hlx:1383
    fn supersede(fx: &Fx, member: &str, by: &str) {
        // hlx:1384
        fx.append_event(&format!(
            "{{\"kind\":\"supersede\",\"id\":\"{member}\",\"by\":\"{by}\"}}"
        ));
        // hlx:1385
    }
    // hlx:1386
    fn two_lessons(name: &str) -> (Fx, String, String) {
        // hlx:1387
        let mut fx = Fx::new(name, false);
        // hlx:1388
        let a = fx.id.clone();
        // hlx:1389
        let b = fx.bank_titled(
            "Second lesson about shipping",
            &["--project", "release-lab"],
        );
        // hlx:1390
        let p = fx.std_policy();
        // hlx:1391
        assert_eq!(fx.attach_for(&a, &p).code, Some(0));
        // hlx:1392
        assert_eq!(fx.attach_for(&b, &p).code, Some(0));
        // hlx:1393
        (fx, a, b)
        // hlx:1394
    }
    // hlx:1395
    fn earn(fx: &Fx, id: &str, key: &str) {
        // hlx:1396
        let o = fx.hit_check_with(id, key, "verified", true, &fx.root, &fx.envs());
        // hlx:1397
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1398
    }
    // hlx:1399
    #[test]
    // hlx:1400
    fn a_verified_credit_moved_by_supersede_to_another_lesson_is_downgraded_to_claimed() {
        // hlx:1401
        let (fx, a, b) = two_lessons("fold-transfer");
        // hlx:1402
        earn(&fx, &b, "kb");
        // hlx:1403
        let s = fx.summary("all");
        // hlx:1404
        assert!(s.present);
        // hlx:1405
        assert_eq!(
            (s.total, s.claimed, s.verified, s.downgraded, s.invalid),
            (1, 0, 1, 0, 0),
            "{s:?}"
        );
        // hlx:1406
        // B is folded into A: the credit survives consolidation, but a verification claim never moves between lessons
        // hlx:1407
        supersede(&fx, &b, &a);
        // hlx:1408
        let s = fx.summary("all");
        // hlx:1409
        assert_eq!(s.total, 1, "the credit survives consolidation once: {s:?}");
        // hlx:1410
        assert_eq!(
            s.verified, 0,
            "scopes matching is not a reason to transfer verification: {s:?}"
        );
        // hlx:1411
        assert_eq!(s.claimed, 1, "{s:?}");
        // hlx:1412
        assert_eq!(
            s.downgraded, 1,
            "the downgrade is reported separately: {s:?}"
        );
        // hlx:1413
        assert_eq!(s.invalid, 0, "a downgrade is not an invalid record: {s:?}");
        // hlx:1414
        assert!(
            fx.eval_text().to_lowercase().contains("verified"),
            "the text section matches the JSON summary"
        );
        // hlx:1415
        // the verified hit on the surviving lesson itself is still verified
        // hlx:1416
        earn(&fx, &a, "ka");
        // hlx:1417
        let s = fx.summary("all");
        // hlx:1418
        assert_eq!((s.total, s.verified, s.downgraded), (2, 1, 1), "{s:?}");
        // hlx:1419
        // undoing the consolidation restores the original binding
        // hlx:1420
        let o = fx.cli(&["unsupersede", &b, "--store", fx.st()]);
        // hlx:1421
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1422
        let s = fx.summary("all");
        // hlx:1423
        assert_eq!((s.total, s.verified, s.downgraded), (2, 2, 0), "{s:?}");
        // hlx:1424
    }
    // hlx:1425
    #[test]
    // hlx:1426
    fn mixed_claimed_and_verified_reports_of_one_consolidated_outcome_count_once_and_are_claimed() {
        // hlx:1427
        let (fx, a, b) = two_lessons("fold-mixed");
        // hlx:1428
        let st = fx.st().to_string();
        // hlx:1429
        // the same outcome key reported as a plain claim on A and as a verified check on B
        // hlx:1430
        let o = fx.cli(&[
            "hit",
            &a,
            "--note",
            "claimed",
            "--outcome-id",
            "same",
            "--store",
            &st,
        ]);
        // hlx:1431
        assert_eq!(o.code, Some(0));
        // hlx:1432
        earn(&fx, &b, "same");
        // hlx:1433
        let s = fx.summary("all");
        // hlx:1434
        assert_eq!(
            (s.total, s.verified),
            (2, 1),
            "before consolidation they are two lessons' outcomes: {s:?}"
        );
        // hlx:1435
        supersede(&fx, &b, &a);
        // hlx:1436
        let s = fx.summary("all");
        // hlx:1437
        assert_eq!(s.total, 1, "one consolidated outcome is one credit: {s:?}");
        // hlx:1438
        assert_eq!(
            s.verified, 0,
            "a mixed report is claimed unless every live contributing mark stays bound: {s:?}"
        );
        // hlx:1439
        assert_eq!(s.claimed, 1, "{s:?}");
        // hlx:1440
        // a second verified report of the same key on the survivor does not add a credit
        // hlx:1441
        let o = fx.hit_check_with(&a, "same", "again", true, &fx.root, &fx.envs());
        // hlx:1442
        let s = fx.summary("all");
        // hlx:1443
        assert_eq!(s.total, 1, "no second credit: {} {s:?}", trunc(&o.text()));
        // hlx:1444
    }
    // hlx:1445
    #[test]
    // hlx:1446
    fn a_changed_lesson_downgrades_its_verified_credit_and_reports_it() {
        // hlx:1447
        let mut fx = Fx::new("fold-content", false);
        // hlx:1448
        fx.attached();
        // hlx:1449
        let o = fx.hit_check("k", "verified");
        // hlx:1450
        one_verified(&fx, "k", &o);
        // hlx:1451
        let s = fx.summary("all");
        // hlx:1452
        assert_eq!((s.total, s.verified, s.downgraded), (1, 1, 0), "{s:?}");
        // hlx:1453
        fx.rewrite_store(|t| {
            t.replace(
                "\"how\":\"Check the inventory\"",
                "\"how\":\"Ship everything in the folder\"",
            )
        });
        // hlx:1454
        let s = fx.summary("all");
        // hlx:1455
        assert_eq!(s.total, 1, "the hit itself still counts: {s:?}");
        // hlx:1456
        assert_eq!(
            s.verified, 0,
            "the receipt no longer binds the current lesson content: {s:?}"
        );
        // hlx:1457
        assert_eq!(s.claimed, 1, "{s:?}");
        // hlx:1458
        assert_eq!(s.downgraded, 1, "{s:?}");
        // hlx:1459
        assert_eq!(s.invalid, 0, "{s:?}");
        // hlx:1460
        // the original receipt event is not rewritten by evaluation
        // hlx:1461
        assert!(fx.hits()[0].get("check_verification").is_some());
        // hlx:1462
    }
    // hlx:1463
    #[test]
    // hlx:1464
    fn retraction_removes_the_credit_without_a_second_vote_and_disputes_follow_the_existing_fold() {
        // hlx:1465
        let mut fx = Fx::new("fold-retract", false);
        // hlx:1466
        fx.attached();
        // hlx:1467
        let id = fx.id.clone();
        // hlx:1468
        let st = fx.st().to_string();
        // hlx:1469
        earn(&fx, &id, "k");
        // hlx:1470
        let o = fx.cli(&["retract", "hit", &id, "--store", &st]);
        // hlx:1471
        assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
        // hlx:1472
        let s = fx.summary("all");
        // hlx:1473
        assert_eq!(
            (s.total, s.verified, s.claimed, s.downgraded),
            (0, 0, 0, 0),
            "a retracted verified hit disappears entirely: {s:?}"
        );
        // hlx:1474
        assert_eq!(s.invalid, 0, "{s:?}");
        // hlx:1475
        // a conflicting verdict on a verified outcome never creates a second credit
        // hlx:1476
        let (fx2, a2, _b2) = two_lessons("fold-dispute");
        // hlx:1477
        earn(&fx2, &a2, "kd");
        // hlx:1478
        let st2 = fx2.st().to_string();
        // hlx:1479
        let o = fx2.cli(&[
            "miss",
            &a2,
            "--note",
            "disputed",
            "--outcome-id",
            "kd",
            "--store",
            &st2,
        ]);
        // hlx:1480
        let _ = o;
        // hlx:1481
        let s = fx2.summary("all");
        // hlx:1482
        assert!(s.total <= 1, "one outcome, at most one credit: {s:?}");
        // hlx:1483
        assert!(s.verified <= s.total);
        // hlx:1484
        // a plain claim with the same key afterwards does not upgrade, duplicate or change a verified credit
        // hlx:1485
        let (fx3, a3, _b3) = two_lessons("fold-retry");
        // hlx:1486
        earn(&fx3, &a3, "kr");
        // hlx:1487
        let st3 = fx3.st().to_string();
        // hlx:1488
        let o = fx3.cli(&[
            "hit",
            &a3,
            "--note",
            "claimed",
            "--outcome-id",
            "kr",
            "--store",
            &st3,
        ]);
        // hlx:1489
        assert_eq!(o.text(), format!("outcome already recorded for {a3}\n"));
        // hlx:1490
        let o = fx3.hit_check_with(&a3, "kr", "again", true, &fx3.root, &fx3.envs());
        // hlx:1491
        let _ = o;
        // hlx:1492
        let s = fx3.summary("all");
        // hlx:1493
        assert_eq!(
            (s.total, s.verified, s.claimed),
            (1, 1, 0),
            "retries change nothing: {s:?}"
        );
        // hlx:1494
        assert_eq!(fx3.hits_of(&a3).len(), 1);
        // hlx:1495
        assert_eq!(fx3.verified_events(), 1);
        // hlx:1496
    }
    // hlx:1497
    #[test]
    // hlx:1498
    fn the_window_uses_the_event_times_selected_by_consolidation() {
        // hlx:1499
        let mut fx = Fx::new("fold-window", false);
        // hlx:1500
        fx.attached();
        // hlx:1501
        let id = fx.id.clone();
        // hlx:1502
        earn(&fx, &id, "old");
        // hlx:1503
        earn(&fx, &id, "new");
        // hlx:1504
        let line = |key: &str| {
            fx.events()
                .into_iter()
                .find(|e| e.get("outcome_id").and_then(J::as_str) == Some(key))
                .map(|e| to_s(e.get("ts").unwrap()))
                .unwrap()
        };
        // hlx:1505
        let ts_old = line("old").parse::<u64>().unwrap();
        // hlx:1506
        let moved = ts_old - 90 * 86_400;
        // hlx:1507
        fx.rewrite_store(|t| {
// hlx:1508
t.lines()
// hlx:1509
.map(|l| if l.contains("\"outcome_id\":\"old\"") { l.replacen(&format!("\"ts\":{ts_old},"), &format!("\"ts\":{moved},"), 1) } else { l.to_string() })
// hlx:1510
.collect::<Vec<_>>()
// hlx:1511
.join("\n")
// hlx:1512
+ "\n"
// hlx:1513
});
        // hlx:1514
        let all = fx.summary("all");
        // hlx:1515
        assert_eq!((all.total, all.verified), (2, 2), "{all:?}");
        // hlx:1516
        for w in ["7d", "30d"] {
            // hlx:1517
            let s = fx.summary(w);
            // hlx:1518
            assert_eq!(
                (s.total, s.verified, s.claimed),
                (1, 1, 0),
                "{w}: only the recent verified hit is in the window: {s:?}"
            );
            // hlx:1519
        }
        // hlx:1520
        // a claimed-only bank has no verification section at all, in any window
        // hlx:1521
        let plain = Fx::new("fold-plain", false);
        // hlx:1522
        let pid = plain.id.clone();
        // hlx:1523
        plain.cli(&["hit", &pid, "--note", "c", "--store", plain.st()]);
        // hlx:1524
        for w in ["7d", "30d", "all"] {
            // hlx:1525
            let s = plain.summary(w);
            // hlx:1526
            assert!(!s.present, "{w}");
            // hlx:1527
            assert_eq!(s.total, 1);
            // hlx:1528
        }
        // hlx:1529
    }
    // hlx:1530
}