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
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
//! Instinct: situation-triggered recall of discoveries and their methods.
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{BufRead, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
mod demo;
mod guide;
mod case_learning;
mod case_experiment;
mod codex_cell;
mod replay_lesson;
mod audit;
mod doctor;
mod codex_trust;
mod learn;
mod connect;
mod connect_mcp;
mod waits;
mod leftovers;
mod brief;
mod brief_action;
mod concepts;
mod unicode_words;
#[allow(dead_code)]
mod consolidation;
mod gates;
mod targets;
mod guard;
mod session;
mod continuation;
mod corrections;
mod outcomes;
mod meter;
mod speed;
mod speed_import;
mod eval;
mod mine;
mod scan;
#[allow(dead_code)]
mod last_turn;
mod starter;
mod rehearsal;
mod trust;
mod check;
mod tripwire;
mod fix;
use rehearsal::StandingInstruction;
#[allow(dead_code)]
mod eligibility;
#[allow(dead_code)]
mod helix_db;
#[allow(dead_code)]
mod journal;
#[allow(dead_code)]
mod recall_index;
// A browser has no filesystem: the verified index snapshot exists only in the native engine.
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
mod snapshot;
#[allow(dead_code)]
mod sync;
mod team;
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
mod serve_http;
#[cfg(not(target_arch = "wasm32"))]
mod serve;
use journal::append;

const DEFAULT_MODEL: &str = "nomic-embed-text";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
const IO_TIMEOUT: Duration = Duration::from_secs(60);
const MAX_RESPONSE: usize = 16 * 1024 * 1024;
const MAX_EMBED_BYTES: usize = 6000;

// ---------------------------------------------------------------- JSON

#[derive(Debug, Clone, PartialEq)]
enum Json {
    Null,
    Bool(bool),
    Num(f64),
    Str(String),
    Arr(Vec<Json>),
    Obj(Vec<(String, Json)>),
}

impl Json {
    fn get(&self, key: &str) -> Option<&Json> {
        match self {
            Json::Obj(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
            _ => None,
        }
    }
    fn as_str(&self) -> Option<&str> {
        match self {
            Json::Str(s) => Some(s),
            _ => None,
        }
    }
    fn as_f64(&self) -> Option<f64> {
        match self {
            Json::Num(n) => Some(*n),
            _ => None,
        }
    }
}

/// Escape `s` as the body of a JSON string (no surrounding quotes).
fn escape_json(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0c}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out
}

struct Parser<'a> {
    b: &'a [u8],
    i: usize,
}

impl<'a> Parser<'a> {
    fn ws(&mut self) {
        while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\n' | b'\r') {
            self.i += 1;
        }
    }
    fn eat(&mut self, c: u8) -> Result<(), String> {
        self.ws();
        if self.b.get(self.i) == Some(&c) {
            self.i += 1;
            Ok(())
        } else {
            Err(format!("expected '{}' at byte {}", c as char, self.i))
        }
    }
    fn lit(&mut self, word: &str, v: Json) -> Result<Json, String> {
        if self.b[self.i..].starts_with(word.as_bytes()) {
            self.i += word.len();
            Ok(v)
        } else {
            Err(format!("bad literal at byte {}", self.i))
        }
    }
    fn value(&mut self) -> Result<Json, String> {
        self.ws();
        match self.b.get(self.i) {
            None => Err("unexpected end of JSON".into()),
            Some(b'{') => {
                self.i += 1;
                let mut fields = Vec::new();
                self.ws();
                if self.b.get(self.i) == Some(&b'}') {
                    self.i += 1;
                    return Ok(Json::Obj(fields));
                }
                loop {
                    self.ws();
                    let k = self.string()?;
                    self.eat(b':')?;
                    fields.push((k, self.value()?));
                    self.ws();
                    match self.b.get(self.i) {
                        Some(b',') => self.i += 1,
                        Some(b'}') => {
                            self.i += 1;
                            return Ok(Json::Obj(fields));
                        }
                        _ => return Err(format!("expected ',' or '}}' at byte {}", self.i)),
                    }
                }
            }
            Some(b'[') => {
                self.i += 1;
                let mut items = Vec::new();
                self.ws();
                if self.b.get(self.i) == Some(&b']') {
                    self.i += 1;
                    return Ok(Json::Arr(items));
                }
                loop {
                    items.push(self.value()?);
                    self.ws();
                    match self.b.get(self.i) {
                        Some(b',') => self.i += 1,
                        Some(b']') => {
                            self.i += 1;
                            return Ok(Json::Arr(items));
                        }
                        _ => return Err(format!("expected ',' or ']' at byte {}", self.i)),
                    }
                }
            }
            Some(b'"') => Ok(Json::Str(self.string()?)),
            Some(b't') => self.lit("true", Json::Bool(true)),
            Some(b'f') => self.lit("false", Json::Bool(false)),
            Some(b'n') => self.lit("null", Json::Null),
            Some(_) => self.number(),
        }
    }
    fn number(&mut self) -> Result<Json, String> {
        let start = self.i;
        while self.i < self.b.len()
            && matches!(
                self.b[self.i],
                b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E'
            )
        {
            self.i += 1;
        }
        std::str::from_utf8(&self.b[start..self.i])
            .ok()
            .and_then(|t| t.parse::<f64>().ok())
            .map(Json::Num)
            .ok_or_else(|| format!("bad number at byte {start}"))
    }
    fn hex4(&mut self) -> Result<u32, String> {
        let h = self
            .b
            .get(self.i..self.i + 4)
            .ok_or("truncated \\u escape")?;
        let v = std::str::from_utf8(h)
            .ok()
            .and_then(|t| u32::from_str_radix(t, 16).ok())
            .ok_or("bad \\u escape")?;
        self.i += 4;
        Ok(v)
    }
    fn string(&mut self) -> Result<String, String> {
        if self.b.get(self.i) != Some(&b'"') {
            return Err(format!("expected string at byte {}", self.i));
        }
        self.i += 1;
        let mut out: Vec<u8> = Vec::new();
        loop {
            let c = *self.b.get(self.i).ok_or("unterminated string")?;
            self.i += 1;
            match c {
                b'"' => break,
                b'\\' => {
                    let e = *self.b.get(self.i).ok_or("unterminated escape")?;
                    self.i += 1;
                    let ch = match e {
                        b'"' => '"',
                        b'\\' => '\\',
                        b'/' => '/',
                        b'n' => '\n',
                        b'r' => '\r',
                        b't' => '\t',
                        b'b' => '\u{08}',
                        b'f' => '\u{0c}',
                        b'u' => {
                            let mut cp = self.hex4()?;
                            if (0xD800..0xDC00).contains(&cp)
                                && self.b[self.i..].starts_with(b"\\u")
                            {
                                self.i += 2;
                                let lo = self.hex4()?;
                                if !(0xDC00..0xE000).contains(&lo) {
                                    return Err("bad surrogate pair".into());
                                }
                                cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                            }
                            char::from_u32(cp).ok_or("invalid code point")?
                        }
                        _ => return Err(format!("bad escape '\\{}'", e as char)),
                    };
                    let mut buf = [0u8; 4];
                    out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
                }
                _ => out.push(c),
            }
        }
        String::from_utf8(out).map_err(|_| "invalid UTF-8 in string".to_string())
    }
}

fn parse_json(text: &str) -> Result<Json, String> {
    let mut p = Parser {
        b: text.as_bytes(),
        i: 0,
    };
    let v = p.value()?;
    p.ws();
    if p.i != p.b.len() {
        return Err(format!("trailing data at byte {}", p.i));
    }
    Ok(v)
}

fn json_floats(v: &Json) -> Option<Vec<f32>> {
    match v {
        Json::Arr(items) => items.iter().map(|n| n.as_f64().map(|f| f as f32)).collect(),
        _ => None,
    }
}

// ---------------------------------------------------------------- embeddings over raw HTTP

/// Decode an HTTP/1.1 chunked body.
fn dechunk(mut body: &[u8]) -> Result<Vec<u8>, String> {
    let mut out = Vec::new();
    loop {
        let nl = body
            .windows(2)
            .position(|w| w == b"\r\n")
            .ok_or("bad chunk framing")?;
        let size_txt = std::str::from_utf8(&body[..nl]).map_err(|_| "bad chunk size")?;
        let size = usize::from_str_radix(size_txt.split(';').next().unwrap_or("").trim(), 16)
            .map_err(|_| "bad chunk size")?;
        body = &body[nl + 2..];
        if size == 0 {
            return Ok(out);
        }
        if body.len() < size + 2 {
            return Err("truncated chunk".into());
        }
        out.extend_from_slice(&body[..size]);
        body = &body[size + 2..];
    }
}

/// POST `body` as JSON to `path` on `addr`; returns the response body on HTTP 200.
fn http_post_json(addr: &str, path: &str, body: &str) -> Result<String, String> {
    let sock = addr
        .to_socket_addrs()
        .map_err(|e| format!("cannot resolve {addr}: {e}"))?
        .next()
        .ok_or_else(|| format!("no address for {addr}"))?;
    let mut s = TcpStream::connect_timeout(&sock, CONNECT_TIMEOUT)
        .map_err(|e| format!("cannot connect to {addr}: {e}"))?;
    let _ = s.set_read_timeout(Some(IO_TIMEOUT));
    let _ = s.set_write_timeout(Some(IO_TIMEOUT));
    let req = format!(
        "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    s.write_all(req.as_bytes())
        .map_err(|e| format!("send to {addr} failed: {e}"))?;
    let mut raw = Vec::new();
    s.take(MAX_RESPONSE as u64)
        .read_to_end(&mut raw)
        .map_err(|e| format!("read from {addr} failed: {e}"))?;
    let split = raw
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .ok_or("malformed HTTP response")?;
    let head = String::from_utf8_lossy(&raw[..split]).to_string();
    let status = head.lines().next().unwrap_or("");
    let payload = &raw[split + 4..];
    let chunked = head.lines().any(|l| {
        let l = l.to_ascii_lowercase();
        l.starts_with("transfer-encoding:") && l.contains("chunked")
    });
    let bytes = if chunked {
        dechunk(payload)?
    } else {
        payload.to_vec()
    };
    let text = String::from_utf8(bytes).map_err(|_| "response is not UTF-8".to_string())?;
    if status.split_whitespace().nth(1) != Some("200") {
        return Err(format!(
            "{addr}{path} answered '{status}': {}",
            text.chars().take(200).collect::<String>()
        ));
    }
    Ok(text)
}

/// Pull the single vector out of `{"embeddings":[[f32,...]]}`.
fn parse_embedding(response: &str) -> Result<Vec<f32>, String> {
    let v = parse_json(response)?;
    if let Some(err) = v.get("error").and_then(Json::as_str) {
        return Err(format!("ollama error: {err}"));
    }
    let emb = match v.get("embeddings") {
        Some(Json::Arr(rows)) if rows.len() == 1 => json_floats(&rows[0]),
        _ => None,
    }
    .ok_or("response has no single numeric \"embeddings\" row")?;
    if emb.is_empty() || emb.iter().any(|f| !f.is_finite()) {
        return Err("embedding is empty or non-finite".into());
    }
    Ok(emb)
}

/// Cut `s` to at most `max` bytes without splitting a UTF-8 character.
fn truncate_utf8(s: &str, max: usize) -> &str {
    if s.len() <= max {
        return s;
    }
    let mut end = max;
    while !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Embed `text` under a nomic task prefix (`search_document: ` on add, `search_query: ` on recall).
/// Without the prefixes nomic similarities run ~0.15 low.
fn embed(prefix: &str, text: &str) -> Result<Vec<f32>, String> {
    let addr = std::env::var("INSTINCT_OLLAMA").map_err(|_| "optional embeddings disabled")?;
    let model = env_or("INSTINCT_EMBED_MODEL", DEFAULT_MODEL);
    let input = format!("{prefix}{}", truncate_utf8(text, MAX_EMBED_BYTES));
    let body = format!(
        "{{\"model\":\"{}\",\"input\":[\"{}\"]}}",
        escape_json(&model),
        escape_json(&input)
    );
    let resp = http_post_json(&addr, "/api/embed", &body)?;
    parse_embedding(&resp)
}

fn cosine(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }
    let (mut dot, mut na, mut nb) = (0.0f32, 0.0f32, 0.0f32);
    for (x, y) in a.iter().zip(b) {
        dot += x * y;
        na += x * x;
        nb += y * y;
    }
    let denom = na.sqrt() * nb.sqrt();
    if denom == 0.0 || !denom.is_finite() {
        return 0.0;
    }
    dot / denom
}

// ---------------------------------------------------------------- lexical (BM25) + fusion

const RRF_K: f32 = 60.0;

/// Lowercase alphanumeric/underscore words of >= 2 chars — keeps code identifiers (snake_case) whole.
fn tokens(s: &str) -> Vec<String> {
    unicode_words::tokens(s)
}

/// Okapi BM25 (k1=1.2, b=0.75) of `query` against each document.
fn bm25(query: &str, docs: &[String]) -> Vec<f32> {
    use std::borrow::Cow;
    use std::collections::HashMap;

    let mut terms = tokens(query);
    terms.sort();
    terms.dedup();
    if terms.is_empty() || docs.is_empty() {
        return vec![0.0; docs.len()];
    }
    let indices: HashMap<&str, usize> = terms
        .iter()
        .enumerate()
        .map(|(i, term)| (term.as_str(), i))
        .collect();
    let mut df = vec![0usize; terms.len()];
    let mut total_length = 0usize;
    let mut corpus = Vec::with_capacity(docs.len());
    // Only query terms can contribute to the score. Count them in one pass,
    // preserving document lengths and the original sorted-term summation order.
    for doc in docs {
        let mut length = 0usize;
        let mut counts = HashMap::new();
        let normalized = unicode_words::normalized(doc);
        for word in normalized.split(|c: char| !(c.is_alphanumeric() || c == '_')) {
            if word.chars().nth(1).is_none() {
                continue;
            }
            length += 1;
            let lower: Cow<'_, str> =
                if word.is_ascii() && !word.bytes().any(|b| b.is_ascii_uppercase()) {
                    Cow::Borrowed(word)
                } else {
                    Cow::Owned(word.to_lowercase())
                };
            if let Some(&index) = indices.get(lower.as_ref()) {
                *counts.entry(index).or_insert(0usize) += 1;
            }
        }
        let mut matched: Vec<_> = counts.into_iter().collect();
        matched.sort_unstable_by_key(|&(i, _)| i);
        for &(i, _) in &matched {
            df[i] += 1;
        }
        total_length += length;
        corpus.push((length, matched));
    }
    let n = docs.len() as f32;
    let avgdl = (total_length as f32 / n).max(1.0);
    let idf: Vec<_> = df
        .into_iter()
        .map(|d| {
            let d = d as f32;
            ((n - d + 0.5) / (d + 0.5) + 1.0).ln()
        })
        .collect();
    corpus
        .into_iter()
        .map(|(length, matched)| {
            matched
                .into_iter()
                .map(|(i, count)| {
                    let tf = count as f32;
                    idf[i] * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length as f32 / avgdl))
                })
                .sum()
        })
        .collect()
}

/// Rank positions (0 = best) of the items with a positive score, best first.
fn ranking(scores: &[f32]) -> Vec<usize> {
    let mut idx: Vec<usize> = (0..scores.len()).filter(|&i| scores[i] > 0.0).collect();
    idx.sort_by(|&a, &b| {
        scores[b]
            .partial_cmp(&scores[a])
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    idx
}

// ---------------------------------------------------------------- store

#[derive(Clone)]
struct Discovery {
    id: String,
    ts: u64,
    title: String,
    when: String,
    found: String,
    how: String,
    evidence: String,
    reconsider: String,
    tags: String,
    embedding: Vec<f32>,
    hits: u32,
    misses: u32,
    outcomes: HashMap<String, Option<bool>>,
    standing: Option<StandingInstruction>,
    casebook: Option<case_learning::Casebook>,
    meta: eligibility::Meta,
}

fn apply_meta(m: &mut eligibility::Meta, v: &Json) {
    for (key, dest) in [
        ("source", &mut m.source),
        ("state", &mut m.state),
        ("evidence_status", &mut m.evidence_status),
        ("scope_project", &mut m.project),
        ("scope_persona", &mut m.persona),
        ("scope_harness", &mut m.harness),
        ("scope_version", &mut m.version),
        ("scope_machine", &mut m.machine),
    ] {
        if let Some(s) = v.get(key).and_then(Json::as_str) {
            *dest = s.to_string();
        }
    }
    if let Some(n) = v.get("valid_until").and_then(Json::as_f64) {
        m.valid_until = n as u64;
    }
}
fn meta_from(v: &Json) -> eligibility::Meta {
    let mut m = eligibility::Meta::default();
    apply_meta(&mut m, v);
    m
}

fn quiet_ids(_path: &PathBuf) -> HashSet<String> {
    let labels = std::env::var("INSTINCT_LABELS").ok();
    let mut counts = std::collections::HashMap::<String, (u32, u32)>::new();
    if let Some(text) = labels.and_then(|p| fs::read_to_string(p).ok()) {
        for line in text.lines() {
            if let Ok(v) = parse_json(line) {
                let id = v.get("id").and_then(Json::as_str).unwrap_or("");
                if id.is_empty() {
                    continue;
                }
                let e = counts.entry(id.to_string()).or_default();
                match v.get("verdict").and_then(Json::as_str).unwrap_or("") {
                    "helped" | "guarded" => e.0 += 1,
                    "irrelevant" | "misled" => e.1 += 1,
                    _ => {}
                }
            }
        }
    }
    counts
        .into_iter()
        .filter(|(_, (u, i))| eligibility::quiet(*u, *i))
        .map(|(id, _)| id)
        .collect()
}

impl Discovery {
    /// v2 2026-11-04 (lever-1, handover from cc-c9d58ab5): boost `when` 3× in the BM25 corpus.
    /// Recall @1 was 34.5 % because BM25 scored prose in `found`/`how` higher than the one field
    /// that actually describes the trigger context — `when`. Keep `found`+`how` so semantic phrase
    /// matches still land; triple `when` so prompt-text queries hit the right instinct more often.
    /// Embeddings computed on `d.text()` are cached per-entry; a `reembed` is needed to realign
    /// the semantic side (BM25 benefits immediately on next query).
    fn text(&self) -> String {
        format!(
            "{w} {w} {w} {t} {tg} {f} {h}",
            w = self.when,
            t = self.title,
            tg = self.tags,
            f = self.found,
            h = self.how
        )
    }
    /// 0.3.0-whenkey (2026-11-04): the BM25 side keys on the one-sentence `when` (ReasoningBank: the
    /// description IS the recall key). Field weights are env-tunable for benching — INSTINCT_W_WHEN
    /// (default 3) and INSTINCT_W_TITLE (default 1) — and `text()` above stays as the embedding input,
    /// so every stored vector remains aligned. With the defaults this equals `text()`.
    fn lex_text(&self) -> String {
        let (ww, wt, body) = lex_weights();
        let mut s = String::with_capacity(
            self.when.len() * ww + self.title.len() * wt + self.found.len() + self.how.len() + 16,
        );
        for _ in 0..ww {
            s.push_str(&self.when);
            s.push(' ');
        }
        for _ in 0..wt {
            s.push_str(&self.title);
            s.push(' ');
        }
        s.push_str(&self.tags);
        s.push(' ');
        if body == 1 {
            s.push_str(&self.found);
            s.push(' ');
            s.push_str(&self.how);
        }
        s
    }
    fn proven_in_use(&self) -> bool {
        self.hits >= 2 && self.strength() >= 0.6
    }

    /// Laplace-smoothed payoff rate: 0.5 for a fresh entry, -> 1.0 as recalls keep paying off.
    fn strength(&self) -> f32 {
        eligibility::strength(self.hits, self.misses)
    }
    fn to_line(&self) -> String {
        let emb: Vec<String> = self.embedding.iter().map(|f| f.to_string()).collect();
        // Older engines ignore the new record kind rather than using a machine-only
        // method on an unknown host. Portable discoveries keep their original kind.
        let kind = if self.meta.machine.is_empty() {
            "discovery"
        } else {
            "machine_discovery"
        };
        let base = format!(
            "{{\"kind\":\"{kind}\",\"id\":\"{}\",\"ts\":{},\"title\":\"{}\",\"when\":\"{}\",\"found\":\"{}\",\"how\":\"{}\",\"evidence\":\"{}\",\"tags\":\"{}\",\"reconsider\":\"{}\",\"embedding\":[{}]}}",
            escape_json(&self.id), self.ts, escape_json(&self.title), escape_json(&self.when), escape_json(&self.found),
            escape_json(&self.how), escape_json(&self.evidence), escape_json(&self.tags), escape_json(&self.reconsider), emb.join(",")
        );
        format!("{},\"source\":\"{}\",\"state\":\"{}\",\"evidence_status\":\"{}\",\"scope_project\":\"{}\",\"scope_persona\":\"{}\",\"scope_harness\":\"{}\",\"scope_version\":\"{}\",\"scope_machine\":\"{}\",\"valid_until\":{}}}",
            base.trim_end_matches('}'), escape_json(&self.meta.source), escape_json(&self.meta.state), escape_json(&self.meta.evidence_status),
            escape_json(&self.meta.project),escape_json(&self.meta.persona),escape_json(&self.meta.harness),escape_json(&self.meta.version),escape_json(&self.meta.machine),self.meta.valid_until)
    }
}

fn env_or(key: &str, default: &str) -> String {
    std::env::var(key)
        .ok()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| default.to_string())
}

/// Where the bank lives when nothing says otherwise: `$INSTINCT_STORE`, else `$XDG_DATA_HOME/instinct/bank.hxdb`,
/// else `~/.local/share/instinct/bank.hxdb` (Unix) or `%LOCALAPPDATA%\instinct\bank.hxdb` (Windows).
pub(crate) fn default_store() -> Result<PathBuf, String> {
    let set = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
    if let Some(p) = set("INSTINCT_STORE") {
        return Ok(p);
    }
    let base = if cfg!(windows) {
        set("LOCALAPPDATA")
    } else {
        set("XDG_DATA_HOME")
            .filter(|p| p.is_absolute())
            .or_else(|| set("HOME").map(|h| h.join(".local").join("share")))
    };
    base.map(|b| b.join("instinct").join("bank.hxdb"))
        .ok_or_else(|| "no home directory found; set INSTINCT_STORE to a bank file path".into())
}

fn store_path(a: &Args) -> Result<PathBuf, String> {
    match a.opt("store") {
        Some(p) => Ok(PathBuf::from(p)),
        None => default_store(),
    }
}

/// Create the default bank's folder (0700 on Unix). Explicit stores are the caller's to manage.
pub(crate) fn ensure_default_dir(path: &std::path::Path) -> Result<(), String> {
    let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty() && !d.exists()) else {
        return Ok(());
    };
    let mut b = std::fs::DirBuilder::new();
    b.recursive(true);
    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
    b.create(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
}

/// Set by the commands that run once and exit (`prompt`, `guard`, `recall`).
#[allow(dead_code)]
static ONE_SHOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// The three field weights that shape the lexical text (`when` repeats, title repeats, body on or off).
/// The index snapshot is keyed on them, so a bench that changes one never reads a stale token list.
fn lex_weights() -> (usize, usize, usize) {
    let ww = env_or("INSTINCT_W_WHEN", "3").parse::<usize>().unwrap_or(3).clamp(0, 12);
    let wt = env_or("INSTINCT_W_TITLE", "1").parse::<usize>().unwrap_or(1).clamp(0, 12);
    let body = env_or("INSTINCT_W_BODY", "1").parse::<usize>().unwrap_or(1).clamp(0, 1);
    (ww, wt, body)
}

/// A cold load that leaves a verified index snapshot behind for the next `prompt`, `guard` or `recall`.
fn load(path: &PathBuf) -> Result<Vec<Discovery>, String> {
    #[cfg(not(target_arch = "wasm32"))]
    let key = snapshot::key(path);
    let all = load_plain(path)?;
    #[cfg(not(target_arch = "wasm32"))]
    if let Some(key) = &key {
        snapshot::store(path, key, &all);
    }
    Ok(all)
}

/// Every lesson a read-only command shows: the user's bank, then the project bank's (`.instinct/lessons.jsonl`
/// above the cwd) when one exists. Each is folded on its own; an id in both stays the user's.
fn load_view(path: &PathBuf) -> Result<Vec<Discovery>, String> {
    let mut all = load(path)?;
    if let Some(shared) = team::find(path) {
        let have: HashSet<String> = all.iter().map(|d| d.id.clone()).collect();
        match team::load_indexed(&shared) {
            Ok(more) => all.extend(more.into_iter().filter(|d| !have.contains(&d.id))),
            Err(e) => eprintln!("instinct: project bank {} not used ({e})", shared.display()),
        }
    }
    Ok(all)
}

/// Fold the append-only event log: discovery lines create entries, hit/miss lines count against them.
/// This is the cold load without the snapshot write, for commands that append straight after reading.
fn load_plain(path: &PathBuf) -> Result<Vec<Discovery>, String> {
    fold_bank(path, |_, _, _| {})
}

fn fold_bank(path: &PathBuf, mut observe: impl FnMut(&str, u64, bool)) -> Result<Vec<Discovery>, String> {
    fold_bank_verified(path, |id, ts, hit, _| observe(id, ts, hit))
}

fn fold_bank_verified(path: &PathBuf, observe: impl FnMut(&str, u64, bool, u8)) -> Result<Vec<Discovery>, String> {
    let text = journal::read(path)?;
    fold_text(&text, &path.display().to_string(), observe)
}

/// The fold itself, over journal text. `label` names the source in a row error.
fn fold_text(text: &str, label: &str, observe: impl FnMut(&str, u64, bool, u8)) -> Result<Vec<Discovery>, String> {
    fold_text_for_bank(text, label, observe, None)
}

fn fold_text_for_bank(text: &str, label: &str, observe: impl FnMut(&str, u64, bool, u8), case_target: Option<&str>) -> Result<Vec<Discovery>, String> {
    let mut out: Vec<Discovery> = Vec::new();
    let mut superseded = HashMap::new();
    let mut retired = HashSet::new();
    let mut directly_banked = Vec::new();
    let personal = !is_team_bank(Path::new(label));
    let mut history: HashMap<usize, Vec<consolidation::Mark>> = HashMap::new();
    // id -> position in `out`: every event row resolves its discovery in O(1) instead of a linear scan
    // (0.2.2: the scans cost ~6M string compares per load at 5.4k rows; dedupe added another ~2M).
    let mut idx: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for (n, line) in text
        .lines()
        .enumerate()
        .filter(|(_, l)| !l.trim().is_empty())
    {
        let v = parse_json(line).map_err(|e| format!("{label}:{}: {e}", n + 1))?;
        let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("").to_string();
        match v.get("kind").and_then(Json::as_str) {
            // 0.2.1-dedupe (2026-11-03): a block of 12 discovery rows was written twice. With a plain push the
            // `embed` merge below (first match) only reached the first copy, so `reembed` re-embedded the
            // empty second copy on every heal tick (273 embed rows per id, heal stuck at 1973/1980).
            // First row wins; a later copy of the same id only donates its vector when the first has none.
            Some(kind @ ("discovery" | "machine_discovery")) => {
                if kind == "machine_discovery" && s("scope_machine").trim().is_empty() {
                    return Err(format!(
                        "machine discovery missing its machine at row {}",
                        n + 1
                    ));
                }
                let d = Discovery {
                    id: s("id"),
                    ts: v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64,
                    title: s("title"),
                    when: s("when"),
                    found: s("found"),
                    how: s("how"),
                    evidence: s("evidence"),
                    reconsider: s("reconsider"),
                    tags: s("tags"),
                    embedding: v.get("embedding").and_then(json_floats).unwrap_or_default(),
                    hits: 0,
                    misses: 0,
                    outcomes: HashMap::new(),
                    standing: None,
                    casebook: None,
                    meta: meta_from(&v),
                };
                if let Some(&i) = idx.get(&d.id) {
                    if out[i].embedding.is_empty() && !d.embedding.is_empty() {
                        out[i].embedding = d.embedding;
                    }
                } else {
                    directly_banked.push(d.meta.source == "banked");
                    idx.insert(d.id.clone(), out.len());
                    out.push(d);
                }
            }
            Some("casebook") if personal => {
                let id = s("id");
                if let Some(&i) = idx.get(&id) {
                    let d = &mut out[i];
                    // A peer may have observed this case before our quarantine or retirement.
                    // Keep the bound history, then gate the folded view on its final eligibility.
                    if directly_banked[i] && d.meta.source == "banked"
                        && v.get("binding").and_then(Json::as_str) == Some(&check::feedback::fingerprint(d))
                    {
                        let added = v.get("casebook").ok_or_else(|| "missing casebook".to_owned())
                            .and_then(case_learning::Casebook::parse)
                            .and_then(|add| match &d.casebook {
                                Some(current) => current.merge(&add),
                                None => Ok(add),
                            })
                            .map_err(|e| format!("{label}:{}: {e}", n + 1))?;
                        d.casebook = Some(added);
                    }
                }
            }
            Some(k @ ("hit" | "miss")) => {
                let id = s("id");
                if let Some(&i) = idx.get(&id) {
                    let hit = k == "hit";
                    let key = s("outcome_id");
                    if !key.is_empty() {
                        match out[i].outcomes.entry(key.clone()) {
                            std::collections::hash_map::Entry::Vacant(slot) => {
                                slot.insert(Some(hit));
                            }
                            std::collections::hash_map::Entry::Occupied(_) => continue,
                        }
                    }
                    history.entry(i).or_default().push(consolidation::Mark {
                        ts: v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64,
                        hit,
                        key,
                        withdrawn: false,
                        verification: check::feedback::provenance(&v, &out[i]),
                    });
                }
            }
            Some("review") => {
                if let Some(&i) = idx.get(&s("id")) {
                    let d = &mut out[i];
                    let previous = d.meta.clone();
                    apply_meta(&mut d.meta, &v);
                    if d.meta.state == "quarantined"
                        || d.meta.evidence_status == "contradicted"
                        || d.meta.source != "banked"
                        || scope_identity(&d.meta) != scope_identity(&previous)
                    {
                        d.standing = None;
                    }
                    if d.meta.source != previous.source || d.meta.valid_until != previous.valid_until
                        || scope_identity(&d.meta) != scope_identity(&previous)
                    {
                        d.casebook = None;
                    }
                }
            }
            Some("standing_instruction") => {
                if let Some(&i) = idx.get(&s("id")) {
                    let d = &mut out[i];
                    let text = s("instruction");
                    let reference = s("source_ref");
                    if d.meta.source == "banked"
                        && !d.meta.project.is_empty()
                        && d.meta.project == s("scope_project")
                        && d.meta.persona == s("scope_persona")
                        && d.meta.state != "quarantined"
                        && d.meta.evidence_status != "contradicted"
                    {
                        d.standing = match s("action").as_str() {
                            "clear" => None,
                            "set" if !text.trim().is_empty() && !reference.trim().is_empty() => {
                                Some(StandingInstruction { text, reference })
                            }
                            _ => {
                                return Err(format!(
                                    "invalid standing instruction at row {}",
                                    n + 1
                                ))
                            }
                        };
                    }
                }
            }
            // A near-duplicate merged into a canonical lesson (consolidate): its hits/misses move to `by`, it leaves recall.
            Some("supersede") => {
                if let Some(&i) = idx.get(&s("id")) {
                    out[i].standing = None;
                }
                consolidation::supersede(&mut superseded, s("id"), s("by"));
            }
            Some("unsupersede") => {
                let id = s("id");
                superseded.remove(&id);
            }
            // Curated out from its wiki page (lapis-instinct-pages `curation: retire`): history stays, it leaves recall.
            Some("retire") => {
                if let Some(&i) = idx.get(&s("id")) {
                    out[i].standing = None;
                }
                retired.insert(s("id"));
            }
            Some("unretire") => {
                let id = s("id");
                retired.remove(&id);
            }
            // Cancels one earlier hit/miss (wrong-argument marks); history stays append-only.
            Some("retract") => {
                if let Some(marks) = idx.get(&s("id")).and_then(|i| history.get_mut(i)) {
                    match s("of").as_str() {
                        "hit" => consolidation::retract(marks, true),
                        "miss" => consolidation::retract(marks, false),
                        _ => {}
                    }
                }
            }
            // A later embedding for an entry banked while Ollama was down (written by `reembed`).
            Some("embed") => {
                let id = s("id");
                if let (Some(&i), Some(e)) =
                    (idx.get(&id), v.get("embedding").and_then(json_floats))
                {
                    if !e.is_empty() {
                        out[i].embedding = e
                    }
                }
            }
            _ => {}
        }
    }
    if case_target.is_some_and(|id| retired.contains(id) || superseded.contains_key(id) || idx.get(id).is_some_and(|&i| !directly_banked[i])) {
        return Err("cases require an active directly banked personal lesson".into());
    }
    consolidation::finish(&mut out, &idx, &superseded, &retired, history, observe);
    for d in &mut out {
        if d.casebook.is_some() && !accepts_casebook(&d.meta, now_secs()) {
            d.casebook = None;
        }
    }
    Ok(out)
}

// wasm32-unknown-unknown has no clock (SystemTime::now traps): the browser host supplies it.
#[cfg(target_arch = "wasm32")]
fn now_secs() -> u64 {
    playground_api::clock()
}

#[cfg(not(target_arch = "wasm32"))]
fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Short stable id: FNV-1a over title+found, base36, prefixed "in-".
fn make_id(title: &str, found: &str) -> String {
    let mut h: u64 = 0xcbf29ce484222325;
    for b in title.bytes().chain([0u8]).chain(found.bytes()) {
        h ^= b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    let mut s = String::new();
    let mut x = h;
    for _ in 0..7 {
        s.push(b"0123456789abcdefghijklmnopqrstuvwxyz"[(x % 36) as usize] as char);
        x /= 36;
    }
    format!("in-{s}")
}

// ---------------------------------------------------------------- args

struct Args {
    pos: Vec<String>,
    kv: Vec<(String, String)>,
}

impl Args {
    fn parse(argv: &[String]) -> Args {
        let (mut pos, mut kv) = (Vec::new(), Vec::new());
        let mut i = 0;
        while i < argv.len() {
            if let Some(k) = argv[i].strip_prefix("--") {
                if let Some((key, value)) = k.split_once('=') {
                    kv.push((key.to_string(), value.to_string()));
                    i += 1;
                    continue;
                }
                // 0.3.0-whenkey: a `--switch` directly followed by another `--key` (or nothing) is a bare
                // switch and consumes no value — before this, `--fold --threshold 0.95` ate `--threshold`
                // and `--fold --apply` lost `--apply`. A value of "-" (stdin) is still a value.
                let next = argv.get(i + 1);
                if next.map_or(true, |n| n.starts_with("--")) {
                    kv.push((k.to_string(), String::new()));
                    i += 1;
                } else {
                    kv.push((k.to_string(), next.cloned().unwrap_or_default()));
                    i += 2;
                }
            } else {
                pos.push(argv[i].clone());
                i += 1;
            }
        }
        Args { pos, kv }
    }
    fn opt(&self, k: &str) -> Option<&str> {
        self.kv
            .iter()
            .rev()
            .find(|(key, _)| key == k)
            .map(|(_, v)| v.as_str())
    }
    fn text(&self, k: &str, stdin_used: &mut bool) -> Result<String, String> {
        match self.opt(k) {
            Some("-") if !*stdin_used => {
                *stdin_used = true;
                let mut s = String::new();
                std::io::stdin()
                    .read_to_string(&mut s)
                    .map_err(|e| format!("stdin: {e}"))?;
                Ok(s.trim().to_string())
            }
            Some(v) => Ok(v.to_string()),
            None => Ok(String::new()),
        }
    }
    fn num(&self, k: &str, default: usize) -> usize {
        self.opt(k).and_then(|v| v.parse().ok()).unwrap_or(default)
    }
    fn optional_json(&self, key: &str, stdin_used: &mut bool) -> Result<Option<Json>, String> {
        let Some(value) = self.opt(key) else { return Ok(None) };
        if self.kv.iter().filter(|(k, _)| k == key).count() != 1
            || (value == "-" && (*stdin_used || self.kv.iter().filter(|(_,v)|v=="-").count()!=1)) {
            return Err(format!("supply --{key} once, using stdin for at most one field"));
        }
        let raw = self.text(key, stdin_used)?;
        parse_json(&raw).map(Some).map_err(|e| format!("invalid --{key} JSON: {e}"))
    }
    /// A bare switch (`--apply`): present at all, whatever value the parser paired with it.
    fn flag(&self, k: &str) -> bool {
        self.kv.iter().any(|(key, _)| key == k)
    }
}

// ---------------------------------------------------------------- operations (shared by CLI and MCP)

struct BankIn {
    title: String,
    when: String,
    found: String,
    how: String,
    evidence: String,
    reconsider: String,
    tags: String,
    project: String,
    persona: String,
    applicability_harness: String,
    applicability_version: String,
    applicability_machine: Option<String>,
}

fn scope_identity(meta: &eligibility::Meta) -> [&str; 5] {
    [
        &meta.project,
        &meta.persona,
        &meta.harness,
        &meta.version,
        &meta.machine,
    ]
}

fn scoped_bank_id(title: &str, found: &str, meta: &eligibility::Meta) -> String {
    let scope = scope_identity(meta);
    if scope.iter().all(|s| s.is_empty()) {
        return make_id(title, found);
    }
    // JSON supplies unambiguous field boundaries. The original short ID remains
    // for unscoped legacy-compatible writes; scoped facts get a separate identity.
    let mut fields = vec![title, found, scope[0], scope[1], scope[2], scope[3]];
    // Preserve the ID of every portable discovery created before machine scoping.
    if !meta.machine.is_empty() {
        fields.push(&meta.machine);
    }
    let body = json_out(&Json::Arr(
        fields
            .into_iter()
            .map(|s| Json::Str(s.to_owned()))
            .collect(),
    ));
    let mut hash = 0xcbf29ce484222325u64;
    for b in body.bytes() {
        hash ^= b as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    }
    format!("in-s{hash:016x}")
}

fn bank_discovery(b: BankIn, context: &eligibility::Scope) -> Result<Discovery, String> {
    for (k, v, ex) in [
        ("title", &b.title, "Count delivered events"),
        (
            "when",
            &b.when,
            "Delivery and selection have separate timestamps",
        ),
        (
            "found",
            &b.found,
            "Only two selected items reached the recipient in time",
        ),
        (
            "how",
            &b.how,
            "Join event IDs and compare delivery with decision time",
        ),
        (
            "evidence",
            &b.evidence,
            "Five selected, two received before the decision",
        ),
    ] {
        if v.trim().is_empty() {
            return Err(format!(
                "--{k} is required (example: {ex}). A jackpot without its {k} is not reusable."
            ));
        }
    }
    if b.applicability_machine
        .as_ref()
        .is_some_and(|alias| alias.trim().is_empty() || alias.trim() != alias)
    {
        return Err("applicability-machine requires a nonempty alias without leading or trailing whitespace".into());
    }
    let meta = eligibility::Meta {
        source: "banked".into(),
        state: "candidate".into(),
        evidence_status: "unverified".into(),
        project: if b.project.is_empty() {
            context.project.clone()
        } else {
            b.project
        },
        persona: if b.persona.is_empty() {
            context.persona.clone()
        } else {
            b.persona
        },
        // Receipt origin and applicability are distinct. Never infer these from
        // INSTINCT_HARNESS / INSTINCT_HARNESS_VERSION or the current caller.
        harness: b.applicability_harness,
        version: b.applicability_version,
        machine: b.applicability_machine.unwrap_or_default(),
        valid_until: 0,
    };
    let id = scoped_bank_id(&b.title, &b.found, &meta);
    let tags = if b.tags.trim().is_empty() { title_tag(&b.title) } else { b.tags };
    Ok(Discovery {
        id,
        ts: now_secs(),
        title: b.title,
        when: b.when,
        found: b.found,
        how: b.how,
        evidence: b.evidence,
        reconsider: b.reconsider,
        tags,
        embedding: Vec::new(),
        hits: 0,
        misses: 0,
        outcomes: HashMap::new(),
        standing: None,
        casebook: None,
        meta,
    })
}

fn bank_scope_note(meta: &eligibility::Meta) -> String {
    let missing: Vec<_> = [
        ("project", &meta.project),
        ("persona", &meta.persona),
        ("applicability harness", &meta.harness),
        ("applicability version", &meta.version),
        ("applicability machine", &meta.machine),
    ]
    .iter()
    .filter(|(_, v)| v.is_empty())
    .map(|(k, _)| *k)
    .collect();
    format!(
        "new lesson, strength 0.50 until hits and misses come in{}",
        if missing.is_empty() {
            "; scoped to the project, persona, harness, version and machine you gave".into()
        } else if missing.len() == 5 {
            "; applies in every project (add --project to limit it)".into()
        } else {
            format!("; not limited by {} (optional)", missing.join(", "))
        }
    )
}

/// `bank --team`: the project bank above the cwd, which `instinct team init` creates.
fn team_bank_path(user: &PathBuf) -> Result<PathBuf, String> {
    if !team::enabled() {
        return Err("INSTINCT_TEAM=0 turns the project bank off".into());
    }
    let bank = team::find(user).ok_or("no project bank above this folder; run `instinct team init` in the repo first")?;
    team::ensure_ignore(&bank);
    team::WRITING_TEAM.store(true, std::sync::atomic::Ordering::Relaxed);
    Ok(bank)
}

fn op_bank(path: &PathBuf, b: BankIn) -> Result<String, String> {
    op_bank_as(path, b, "banked")
}

/// Same write with another origin. `instinct mine --apply` banks as "mined", which the engine recalls only after a hit.
fn op_bank_as(path: &PathBuf, b: BankIn, source: &str) -> Result<String, String> {
    op_bank_in(path, b, source, &eligibility::env_scope())
}

/// `instinct starter --apply` banks as "community" with an empty scope context, so the pack is portable.
/// A community lesson is not a candidate: it ships reviewed with public evidence, so it can be delivered at once.
fn op_bank_in(path: &PathBuf, b: BankIn, source: &str, context: &eligibility::Scope) -> Result<String, String> {
    bank_with_cases(path, b, source, None, context)
}

fn op_bank_cases(path: &PathBuf, b: BankIn, cases: Option<case_learning::Casebook>, context: &eligibility::Scope) -> Result<String, String> {
    bank_with_cases(path, b, "banked", cases, context)
}

fn is_team_bank(path: &Path) -> bool {
    path.file_name().is_some_and(|file| file == team::FILE)
        && path.parent().and_then(Path::file_name).is_some_and(|dir| dir == team::DIR)
}

fn accepts_casebook(meta: &eligibility::Meta, at: u64) -> bool {
    meta.source == "banked" && meta.state != "quarantined" && meta.evidence_status != "contradicted"
        && (meta.valid_until == 0 || at <= meta.valid_until)
}

fn case_event(d: &Discovery, cases: &case_learning::Casebook, ts: u64) -> String {
    json_out(&Json::Obj(vec![
        ("kind".into(), Json::Str("casebook".into())),
        ("id".into(), Json::Str(d.id.clone())),
        ("binding".into(), Json::Str(check::feedback::fingerprint(d))),
        ("ts".into(), Json::Num(ts as f64)),
        ("casebook".into(), cases.to_json()),
    ]))
}

fn bank_with_cases(path: &PathBuf, b: BankIn, source: &str, cases: Option<case_learning::Casebook>, context: &eligibility::Scope) -> Result<String, String> {
    let mut d0 = bank_discovery(b, context)?;
    d0.meta.source = source.into();
    if source == "community" {
        d0.meta.state = "community".into();
    }
    let id = d0.id.clone();
    let team_write = team::WRITING_TEAM.load(std::sync::atomic::Ordering::Relaxed);
    if cases.is_some() && (team_write || is_team_bank(path)) {
        return Err("casebooks require a personal bank; --team is unsupported".into());
    }
    let _lock = journal::identity_lock(path)?;
    let on_file = if cases.is_some() {
        fold_text_for_bank(&journal::read(path)?, &path.display().to_string(), |_, _, _, _| {}, Some(&id))?
    } else if team_write { team::load(path)? } else { load_plain(path)? };
    if let Some(existing) = on_file.iter().find(|d| d.id == id) {
        if scope_identity(&existing.meta) != scope_identity(&d0.meta) {
            return Err(
                "bank identity collision across applicability scopes; nothing written".into(),
            );
        }
        if let Some(add) = &cases {
            let ts = now_secs();
            if !accepts_casebook(&existing.meta, ts) {
                return Err("cases require an active directly banked personal lesson".into());
            }
            d0.meta.valid_until = existing.meta.valid_until;
            if check::feedback::fingerprint(existing) != check::feedback::fingerprint(&d0) {
                return Err("casebook lesson fields differ from the stored lesson; nothing written".into());
            }
            if let Some(held) = &existing.casebook {
                if held.merge(add)? == *held {
                    return Ok(format!("already banked: {id}; casebook already recorded"));
                }
            }
            append(path, &case_event(existing, add, ts))?;
            return Ok(format!("banked cases for {id}; lesson and feedback preserved"));
        }
        return Ok(format!(
            "already banked: {id}; existing source/status preserved; requested {}",
            bank_scope_note(&d0.meta)
        ));
    }
    let scope_note = bank_scope_note(&d0.meta);
    let embedding = if team_write { Vec::new() } else { embed("search_document: ", &d0.text()).unwrap_or_default() };
    // Embeddings are optional and off by default, so only mention them when they were asked for and failed.
    let note = if embedding.is_empty() && std::env::var_os("INSTINCT_OLLAMA").is_some() {
        " (embedding failed: word recall only for this entry)"
    } else {
        ""
    };
    d0.embedding = embedding;
    let discovery = d0.to_line();
    if let Some(add) = &cases {
        journal::append_many(path, &[&discovery, &case_event(&d0, add, d0.ts)])?;
    } else {
        append(path, &discovery)?;
    }
    Ok(format!("banked {id} ({scope_note}){note}"))
}

fn render(d: &Discovery) -> String {
    format!(
        "[{}] {}  (strength {:.2}, {} hit / {} miss)\n  WHEN: {}\n  FOUND: {}\n  HOW: {}\n  EVIDENCE: {}{}",
        d.id, d.title, d.strength(), d.hits, d.misses, d.when, d.found, d.how, d.evidence,
        [("RECONSIDER", &d.reconsider), ("MACHINE", &d.meta.machine), ("TAGS", &shown_tags(&d.tags))].into_iter().filter(|(_,v)| !v.is_empty()).map(|(k,v)| format!("\n  {k}: {v}")).collect::<String>()
    )
}

/// Tags as shown to an agent. The `cmd:` matchers that `instinct guard` uses are internal syntax, so they are
/// left out of the rendered lesson. Matching still uses the stored tags unchanged.
fn shown_tags(tags: &str) -> String {
    tags.split(';')
        .map(str::trim)
        .filter(|t| !t.is_empty() && !t.starts_with("cmd:"))
        .collect::<Vec<_>>()
        .join(";")
}

// ---------------------------------------------------------------- `when` vectors (0.3.0-whenkey)
//
// A second vector per lesson, computed on the one-sentence `when` alone, kept in a SIDECAR
// `<store>.when.bin` (binary ID/vector records), so the main store's format and every 0.2.2
// fixture rule stay byte-identical. Built by `reembed --when` (append-only, only missing ids).
// Recall fuses it as a third RRF list when the sidecar exists; INSTINCT_WHEN_VEC=0 switches it off,
// deleting the sidecar is the full rollback.

/// Sidecar is BINARY (`<store>.when.bin`), append-only records: u16 id_len · id bytes · u16 dim · dim × f32 LE.
/// A text sidecar cost ~1.4 s per recall at 2k rows (measured 2026-11-04) and would breach the deny path's
/// 2 s cap; the binary load is a byte walk (< 10 ms). Rollback = delete the file.
fn when_sidecar(path: &PathBuf) -> PathBuf {
    let mut s = path.as_os_str().to_owned();
    s.push(".when.bin");
    PathBuf::from(s)
}

/// id → `when` vector; later records for the same id win (append-only re-embeds).
fn load_when(path: &PathBuf) -> std::collections::HashMap<String, Vec<f32>> {
    let mut out = std::collections::HashMap::new();
    let Ok(buf) = fs::read(when_sidecar(path)) else {
        return out;
    };
    let mut p = 0usize;
    while p + 4 <= buf.len() {
        let il = u16::from_le_bytes([buf[p], buf[p + 1]]) as usize;
        p += 2;
        if p + il + 2 > buf.len() {
            break;
        }
        let id = String::from_utf8_lossy(&buf[p..p + il]).to_string();
        p += il;
        let dim = u16::from_le_bytes([buf[p], buf[p + 1]]) as usize;
        p += 2;
        if p + dim * 4 > buf.len() {
            break;
        }
        let mut v = Vec::with_capacity(dim);
        for i in 0..dim {
            let o = p + i * 4;
            v.push(f32::from_le_bytes([
                buf[o],
                buf[o + 1],
                buf[o + 2],
                buf[o + 3],
            ]));
        }
        p += dim * 4;
        if !v.is_empty() && v.iter().all(|x| x.is_finite()) {
            out.insert(id, v);
        }
    }
    out
}

fn append_when(path: &PathBuf, id: &str, v: &[f32]) -> Result<(), String> {
    let side = when_sidecar(path);
    let mut rec: Vec<u8> = Vec::with_capacity(4 + id.len() + v.len() * 4);
    rec.extend_from_slice(&(id.len() as u16).to_le_bytes());
    rec.extend_from_slice(id.as_bytes());
    rec.extend_from_slice(&(v.len() as u16).to_le_bytes());
    for x in v {
        rec.extend_from_slice(&x.to_le_bytes());
    }
    let mut f = journal::private_options()
        .create(true)
        .append(true)
        .open(&side)
        .map_err(|e| format!("cannot open {}: {e}", side.display()))?;
    f.write_all(&rec)
        .map_err(|e| format!("write {} failed: {e}", side.display()))
}

/// Embed `when` for every live entry lacking a when-vector; appends to the sidecar.
fn op_reembed_when(path: &PathBuf) -> Result<String, String> {
    let all = load(path)?;
    let have = load_when(path);
    let todo: Vec<&Discovery> = all
        .iter()
        .filter(|d| !have.contains_key(&d.id) && !d.when.trim().is_empty())
        .collect();
    let mut done = 0;
    for d in &todo {
        let e = embed("search_document: ", &d.when)
            .map_err(|e| format!("stopped after {done}/{} ({e})", todo.len()))?;
        append_when(path, &d.id, &e)?;
        done += 1;
    }
    Ok(format!(
        "when-embedded {done} of {} entries without a when-vector → {}",
        todo.len(),
        when_sidecar(path).display()
    ))
}

#[cfg_attr(not(test), allow(dead_code))]
fn op_recall(path: &PathBuf, q: &str, k: usize) -> Result<String, String> {
    op_recall_scoped(path, q, k, &eligibility::env_scope())
}
#[cfg_attr(not(test), allow(dead_code))]
fn op_recall_scoped(
    path: &PathBuf,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
) -> Result<String, String> {
    op_recall_data(path, q, k, scope).map(|(text, _)| text)
}
// Directly banked discoveries can be tried offline before their first payoff.
fn is_anchor_word(w: &str) -> bool {
    w.len() >= 4
        && !matches!(
            w,
            "with"
                | "when"
                | "that"
                | "this"
                | "from"
                | "what"
                | "which"
                | "have"
                | "does"
                | "need"
                | "using"
                | "into"
                | "were"
                | "there"
                | "their"
                | "they"
                | "before"
                | "after"
        )
}

fn anchors(text: &str) -> HashSet<String> {
    tokens(text)
        .into_iter()
        .filter_map(|w| {
            let folded = fold_word(&w);
            // A word in a synonym group counts through its canonical token, even a short one (ram, pod).
            concepts::canon(&folded).or_else(|| is_anchor_word(&w).then_some(folded))
        })
        .collect()
}

/// The trigger gate's view of a text: each anchor token with the number of distinct words that map to it.
/// A word outside the synonym groups is its own token with count 1. Words in one group ("test", "suite")
/// share the group's token, and the count keeps them as two words.
fn anchor_counts(text: &str) -> HashMap<String, usize> {
    let mut words: HashMap<String, HashSet<String>> = HashMap::new();
    for w in tokens(text) {
        let folded = fold_word(&w);
        let token = match concepts::canon(&folded) {
            Some(c) => c,
            None if is_anchor_word(&w) => folded.clone(),
            None => continue,
        };
        words.entry(token).or_default().insert(folded);
    }
    words.into_iter().map(|(k, v)| (k, v.len())).collect()
}

/// Keyword confidence for a delivery that rests on matched words alone (no embedding agreement). Two shared
/// generic words open the trigger gate but score low on BM25, and those were the wrong lessons delivered on
/// paraphrased questions; a lesson that really answers the question scores high. BM25 scores grow with the idf
/// of the matched words, which grows as ln(lessons), so the floors do too (80 lessons: 17 and 14).
/// A lesson is delivered when its score reaches `hi`, or reaches `lo` and is at least 1.5 times the best
/// other lesson's score (a clear winner). Otherwise the recall stays silent. Applies from 20 lessons up,
/// with the rare-word gate. `INSTINCT_MIN_LEX=0` turns it off; any other number replaces `hi` (`lo` is 0.8 of it).
fn lex_floors(lessons: usize) -> (f32, f32) {
    if !rare_gate_on(lessons) {
        return (0.0, 0.0);
    }
    match std::env::var("INSTINCT_MIN_LEX").ok().and_then(|v| v.parse::<f32>().ok()) {
        Some(v) => (v, v * 0.8),
        None => {
            let ln = (lessons as f32).ln();
            (3.9 * ln, 3.2 * ln)
        }
    }
}

/// True when a keyword-only delivery of lesson `i` is too weakly supported (see `lex_floors`).
fn weak_keyword_support(score: f32, top_two: (f32, f32), floors: (f32, f32)) -> bool {
    // `top_two` is the best and second best score in the bank, so the best other score is one lookup.
    let other = if score >= top_two.0 { top_two.1 } else { top_two.0 };
    score < floors.0 && !(score >= floors.1 && score >= 1.5 * other)
}

/// The best and second best score in `lex` (the second equals the best when two lessons tie).
fn top_two(lex: &[f32]) -> (f32, f32) {
    let (mut a, mut b) = (0.0_f32, 0.0_f32);
    for &s in lex {
        if s > a {
            b = a;
            a = s;
        } else if s > b {
            b = s;
        }
    }
    (a, b)
}

/// The rare-word gate applies from 20 lessons up, unless `INSTINCT_RARE=0`.
fn rare_gate_on(lessons: usize) -> bool {
    lessons >= 20 && env_or("INSTINCT_RARE", "1") != "0"
}

/// Anchors too common in the bank to count as the discriminating one: in more than 10% of the lessons'
/// trigger texts (when, title, tags). Empty when the gate is off (`INSTINCT_RARE=0`) or the bank has
/// fewer than 20 lessons, where a document frequency means nothing. The trigger gate then needs at least
/// one shared anchor outside this set, so two generic words ("page", "release") cannot open it alone.
fn common_anchors(all: &[Discovery]) -> HashSet<String> {
    if !rare_gate_on(all.len()) {
        return HashSet::new();
    }
    let mut df: HashMap<String, usize> = HashMap::new();
    for d in all {
        let mut seen = anchors(&d.when);
        seen.extend(anchors(&d.title));
        for t in d.tags.split(';') {
            seen.extend(anchors(t));
        }
        for a in seen {
            *df.entry(a).or_insert(0) += 1;
        }
    }
    df.into_iter().filter(|(_, c)| c * 10 > all.len()).map(|(a, _)| a).collect()
}

/// One tag phrase from a title's distinctive words (first four, in order, no repeats), used when a lesson is
/// banked without tags. Fewer than two distinctive words cannot satisfy the two-word trigger, so no tag.
fn title_tag(title: &str) -> String {
    let mut words: Vec<String> = Vec::new();
    // Tags are stored user-facing text: retain the legacy spelling and deduplication.
    let stored_fold = |w: &str| {
        let once = fold_once(w);
        if once.len() < w.len() && w.ends_with('s') { fold_once(&once) } else { once }
    };
    for w in title.split(|c: char| !(c.is_alphanumeric() || c == '_'))
        .filter(|w| w.chars().count() >= 2).map(str::to_lowercase) {
        if is_anchor_word(&w) && !words.iter().any(|x| stored_fold(x) == stored_fold(&w)) {
            words.push(w);
        }
    }
    words.truncate(4);
    if words.len() < 2 {
        return String::new();
    }
    words.join(" ")
}

/// Folds common English word forms onto one key, so "tests", "testing" and "tested" all match
/// "test", "running" matches "runs" and "updated" matches "update". Both sides of a trigger match go
/// through this, so the rule only has to be consistent, not linguistically exact. A plural folds a
/// second time so "warnings" and "warning" share a key. Latin accents are normalized first.
fn fold_word(w: &str) -> String {
    let normalized = unicode_words::normalized(w);
    let w = normalized.as_ref();
    let once = fold_once(w);
    if once.len() < w.len() && w.ends_with('s') {
        fold_once(&once)
    } else {
        once
    }
}

fn fold_once(w: &str) -> String {
    if !w.is_ascii() {
        return w.to_string();
    }
    let has_vowel = |s: &str| s.bytes().any(|b| b"aeiouy".contains(&b));
    let undouble = |s: &str| -> String {
        let b = s.as_bytes();
        let n = b.len();
        if n >= 3 && b[n - 1] == b[n - 2] && !b"aeiouylsz".contains(&b[n - 1]) {
            s[..n - 1].to_string()
        } else {
            s.to_string()
        }
    };
    let n = w.len();
    if n > 4 && w.ends_with("ies") {
        return format!("{}y", &w[..n - 3]);
    }
    if w.ends_with("sses") {
        return w[..n - 2].to_string();
    }
    if n > 5 && w.ends_with("ing") && has_vowel(&w[..n - 3]) {
        return undouble(&w[..n - 3]);
    }
    if n > 4 && w.ends_with("ed") && has_vowel(&w[..n - 2]) {
        return undouble(&w[..n - 2]);
    }
    if n > 4
        && w.ends_with("es")
        && ["x", "ch", "sh", "ss", "z"].iter().any(|t| w[..n - 2].ends_with(t))
    {
        return w[..n - 2].to_string();
    }
    if n > 3 && w.ends_with('s') && !w.ends_with("ss") && !w.ends_with("us") && !w.ends_with("is") {
        return w[..n - 1].to_string();
    }
    if n > 4 && w.ends_with('e') && !w.ends_with("ee") {
        return w[..n - 1].to_string();
    }
    w.to_string()
}

fn score_discoveries(query: &str, discoveries: &[Discovery]) -> Vec<f32> {
    bm25(query, &discoveries.iter().map(Discovery::lex_text).collect::<Vec<_>>())
}

/// The user's bank answers first; the project bank (`.instinct/lessons.jsonl` above the cwd) is a second layer,
/// ranked on its own index and appended after. A project bank that fails never stops the lookup.
fn recall_methods(
    path: &PathBuf,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
) -> Result<Vec<Discovery>, String> {
    let mut picked = recall_layer(path, q, k, scope, false)?;
    if let Some(shared) = team::find(path) {
        if let Ok(more) = recall_layer(&shared, q, k, scope, true) {
            let have: HashSet<String> = picked.iter().map(|d| d.id.clone()).collect();
            picked.extend(more.into_iter().filter(|d| !have.contains(&d.id)));
            picked.truncate(k);
        }
    }
    Ok(picked)
}

/// One bank, ranked: `shared` says it is a project bank (rows normalized for git merges before the fold).
fn recall_layer(
    path: &PathBuf,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
    shared: bool,
) -> Result<Vec<Discovery>, String> {
    // A verified snapshot of this exact bank answers without reading, verifying or tokenizing it again.
    #[cfg(not(target_arch = "wasm32"))]
    if let Some((all, pos, index)) = snapshot::key(path).and_then(|key| snapshot::open(path, &key, scope, now_secs())) {
        let picked = rank_methods_with(
            path,
            q,
            k,
            scope,
            &all,
            |action| snapshot::scores(&index, &pos, all.len(), action),
            || if rare_gate_on(all.len()) { snapshot::common_anchors(&index, &pos, all.len()) } else { HashSet::new() },
        );
        if ONE_SHOT.load(std::sync::atomic::Ordering::Relaxed) {
            std::mem::forget((all, index));
        }
        return picked;
    }
    let all = if shared { team::scoped(path, scope, now_secs()) } else { load_user_scoped(path, scope, now_secs())? };
    rank_methods(path, q, k, scope, &all, |action| score_discoveries(action, &all))
}

fn load_user_scoped(path: &PathBuf, scope: &eligibility::Scope, now: u64) -> Result<Vec<Discovery>, String> {
    Ok(load(path)?
        .into_iter()
        .filter(|d| eligibility::scope_check(&d.meta, scope, now).is_ok())
        .collect())
}

/// `load_scoped` for the guard's `cmd:` match: the project bank is read only when its file mentions a `cmd:` tag,
/// so a Bash guard call over thousands of shared lessons does not decode them just to find none.
fn load_scoped_for_cmd(path: &PathBuf, scope: &eligibility::Scope, now: u64) -> Result<Vec<Discovery>, String> {
    let mut all = load_user_scoped(path, scope, now)?;
    if let Some(shared) = team::find(path).filter(|t| team::mentions(t, "cmd:")) {
        let have: HashSet<String> = all.iter().map(|d| d.id.clone()).collect();
        all.extend(team::scoped(&shared, scope, now).into_iter().filter(|d| !have.contains(&d.id)));
    }
    Ok(all)
}

/// Every lesson that fits the scope: the user's bank, then the project bank's.
fn load_scoped(
    path: &PathBuf,
    scope: &eligibility::Scope,
    now: u64,
) -> Result<Vec<Discovery>, String> {
    let mut all = load_user_scoped(path, scope, now)?;
    if let Some(shared) = team::find(path) {
        let have: HashSet<String> = all.iter().map(|d| d.id.clone()).collect();
        all.extend(team::scoped(&shared, scope, now).into_iter().filter(|d| !have.contains(&d.id)));
    }
    Ok(all)
}

fn rank_methods(
    path: &PathBuf,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
    all: &[Discovery],
    lexical_scores: impl FnOnce(&str) -> Vec<f32>,
) -> Result<Vec<Discovery>, String> {
    rank_methods_with(path, q, k, scope, all, lexical_scores, || common_anchors(all))
}

/// `common` supplies the anchors too common to count (see `common_anchors`); a snapshot answers it from stored counts.
fn rank_methods_with(
    path: &PathBuf,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
    all: &[Discovery],
    lexical_scores: impl FnOnce(&str) -> Vec<f32>,
    common: impl FnOnce() -> HashSet<String>,
) -> Result<Vec<Discovery>, String> {
    meter::note_eligible(all);
    if all.is_empty() || q.trim().is_empty() {
        return Ok(Vec::new());
    }
    // A quoted passage being translated or counted is data. Rank on the request
    // around it, including for the resident index and the spelling fallback.
    let action_text = brief_action::action_text(q);
    let q = action_text.as_ref();
    let lex = lexical_scores(&concepts::expand(q));
    let mut fused = vec![0f32; all.len()];
    let mut similarities: Vec<Option<f32>> = vec![None; all.len()];
    let quiet = quiet_ids(path);
    let w_lex: f32 = env_or("INSTINCT_W_LEX", "1").parse().unwrap_or(1.0);
    for (r, &i) in ranking(&lex).iter().enumerate() {
        fused[i] += w_lex / (RRF_K + r as f32 + 1.0);
    }
    if let Ok(qe) = embed("search_query: ", q) {
        let mode = env_or("INSTINCT_VEC_MODE", "both");
        let whenv = if env_or("INSTINCT_WHEN_VEC", "1") == "0" || mode == "full" {
            std::collections::HashMap::new()
        } else {
            load_when(path)
        };
        for (i, d) in all.iter().enumerate() {
            if !d.embedding.is_empty() {
                similarities[i] = Some(cosine(&qe, &d.embedding));
            }
        }
        if mode != "when" || whenv.is_empty() {
            let sem: Vec<f32> = all
                .iter()
                .map(|d| {
                    let c = cosine(&qe, &d.embedding);
                    if c >= 0.5 {
                        c
                    } else {
                        0.0
                    }
                })
                .collect();
            for (r, &i) in ranking(&sem).iter().enumerate() {
                fused[i] += 1.0 / (RRF_K + r as f32 + 1.0);
            }
        }
        // Two guards keep the when-vector from diluting raw-command recall (measured 2026-11-04: as a free third
        // list it cost -4 @5 on 46 shell-command situations while gaining +2 @1):
        //  · INSTINCT_WHENVEC_GATE=1  — the when-vector only re-ranks items an existing signal already found
        //    (BM25 > 0 or full-vector cosine >= 0.5); it cannot introduce candidates of its own.
        //  · INSTINCT_WHENVEC_NLONLY=1 — skip it when the query reads as a shell command (>= 30 % of tokens
        //    carry / - $ | & ; = or start with a digit); situations are prose, deny-path queries are commands.
        let shellish = {
            let toks: Vec<&str> = q.split_whitespace().collect();
            let n = toks.len().max(1) as f32;
            let s = toks
                .iter()
                .filter(|t| {
                    t.contains('/')
                        || t.starts_with('-')
                        || t.contains('$')
                        || t.contains('|')
                        || t.contains('&')
                        || t.contains(';')
                        || t.contains('=')
                        || t.starts_with(|c: char| c.is_ascii_digit())
                })
                .count() as f32;
            s / n >= 0.30
        };
        let nl_only = env_or("INSTINCT_WHENVEC_NLONLY", "0") == "1";
        if !whenv.is_empty() && !(nl_only && shellish) {
            let w: f32 = env_or("INSTINCT_W_WHENVEC", "1").parse().unwrap_or(1.0);
            let gate = env_or("INSTINCT_WHENVEC_GATE", "0") == "1";
            let semw: Vec<f32> = all
                .iter()
                .enumerate()
                .map(|(i, d)| {
                    if gate && lex[i] <= 0.0 && cosine(&qe, &d.embedding) < 0.5 {
                        return 0.0;
                    }
                    whenv
                        .get(&d.id)
                        .map(|v| {
                            let c = cosine(&qe, v);
                            if c >= 0.5 {
                                c
                            } else {
                                0.0
                            }
                        })
                        .unwrap_or(0.0)
                })
                .collect();
            for (r, &i) in ranking(&semw).iter().enumerate() {
                fused[i] += w / (RRF_K + r as f32 + 1.0);
            }
        }
    }
    for (i, d) in all.iter().enumerate() {
        if fused[i] > 0.0 {
            fused[i] += 0.002 * d.strength();
        }
    }
    // Result fold (INSTINCT_FOLD = cosine threshold, default off): a near-duplicate of a lesson already in
    // the answer does not take a slot, so top-k carries k DIFFERENT lessons.
    let fold: f32 = env_or("INSTINCT_FOLD", "0").parse().unwrap_or(0.0);
    let mut picked: Vec<usize> = Vec::with_capacity(k.min(all.len()));
    let cues = anchor_counts(q);
    let common = common();
    // A BM25 score grows with the number of matched words, so a terse query is held to a proportionally lower
    // floor: full strength from 12 words up, a fifth of it at 2 words.
    let lex_floors = {
        let scale = (tokens(q).len() as f32 / 12.0).clamp(0.2, 1.0);
        let (hi, lo) = lex_floors(all.len());
        (hi * scale, lo * scale)
    };
    let lex_top = top_two(&lex);
    let brief = brief::Brief::parse(q);
    let roles = brief_action::TaskRoles::parse(q);
    let excluded = |d: &Discovery| {
        !roles.allows(&d.when, &d.how, &d.tags)
            || brief.excludes(&d.when, &d.how)
            || d.standing
                .as_ref()
                .is_some_and(|s| brief.excludes(&d.when, &s.text))
    };
    for i in ranking(&fused) {
        if picked.len() >= k {
            break;
        }
        let verdict = eligibility::eligible(
            &all[i].meta,
            scope,
            now_secs(),
            similarities[i],
            all[i].hits,
            quiet.contains(&all[i].id),
        );
        let trigger_matches = |trigger: &str| {
            // Count shared words, not shared tokens: "test suite" on both sides is two words even though
            // both map to one synonym token. A token contributes as many matches as the side with fewer
            // distinct words in it, so one synonym can never stand in for two different words.
            let mut shared = 0;
            let mut rare = common.is_empty();
            for (token, n) in anchor_counts(trigger) {
                if let Some(m) = cues.get(&token) {
                    shared += n.min(*m);
                    rare |= !common.contains(&token);
                }
            }
            shared >= 2 && rare
        };
        let strong_trigger =
            trigger_matches(&all[i].when)
                || trigger_matches(&all[i].title)
                || all[i].tags.split(';').any(trigger_matches);
        let offline_candidate = verdict == Err("candidate_match_unproven")
            && all[i].meta.source == "banked"
            && strong_trigger;
        if (verdict.is_err() && !offline_candidate)
            || eligibility::quiet(all[i].hits, all[i].misses)
            || (!strong_trigger && similarities[i].unwrap_or(0.0) < 0.74)
            || (similarities[i].unwrap_or(0.0) < 0.74 && weak_keyword_support(lex[i], lex_top, lex_floors))
            || excluded(&all[i])
        {
            continue;
        }
        if fold > 0.0
            && !all[i].embedding.is_empty()
            && picked.iter().any(|&j| {
                !all[j].embedding.is_empty() && cosine(&all[i].embedding, &all[j].embedding) >= fold
            })
        {
            continue;
        }
        picked.push(i);
    }
    if picked.is_empty() && k > 0 && cues.len() >= 2 {
        let query = tokens(q);
        let mut matches = Vec::new();
        for (i, d) in all.iter().enumerate() {
            if d.hits == 0
                || excluded(d)
                || quiet.contains(&d.id)
                || eligibility::quiet(d.hits, d.misses)
                || eligibility::scope_check(&d.meta, scope, now_secs()).is_err()
            {
                continue;
            }
            let score = std::iter::once(d.when.as_str())
                .chain(d.tags.split(';'))
                .map(|cue| helix_db::cue_similarity(&query, cue))
                .fold(0.0_f64, f64::max);
            if score > 0.0 {
                matches.push((i, score));
            }
        }
        matches.sort_by(|a, b| b.1.total_cmp(&a.1));
        if let Some(&(i, score)) = matches.first() {
            if score >= 0.62 && matches.get(1).is_none_or(|next| score - next.1 >= 0.08) {
                picked.push(i);
            }
        }
    }
    Ok(picked.into_iter().map(|i| all[i].clone()).collect())
}

// ---------------------------------------------------------------- lesson index (INSTINCT_INDEX=1)

const INDEX_HEADER: &str = "Instinct lessons: if one fits, run `instinct show ID` for the method";
/// The whole index block, header included, never exceeds this many bytes.
const INDEX_BUDGET: usize = 6 * 1024;

/// True for `instinct prompt --index` or `INSTINCT_INDEX=1`. Off by default.
fn index_wanted(a: &Args) -> bool {
    a.flag("index") || std::env::var("INSTINCT_INDEX").is_ok_and(|v| v.trim() == "1")
}

/// One line of text: control characters and the column separator become spaces, then cut to `max` bytes
/// at a character boundary with a trailing "...".
fn index_cell(text: &str, max: usize) -> String {
    let flat: String = text.chars().map(|c| if c.is_control() || c == '|' { ' ' } else { c }).collect();
    let flat = flat.split_whitespace().collect::<Vec<_>>().join(" ");
    if flat.len() <= max {
        return flat;
    }
    let mut end = max.saturating_sub(3);
    while !flat.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}...", flat[..end].trim_end())
}

/// The index block: a header line, then `ID | title | when` per lesson, strongest first (ties keep bank
/// order). Texts are cut as little as the budget allows: the first column widths that fit every lesson win;
/// if even the narrowest do not, the weakest lessons are left off. Empty when there is nothing to list.
fn render_index(all: &[Discovery], budget: usize) -> String {
    if all.is_empty() {
        return String::new();
    }
    let mut order: Vec<&Discovery> = all.iter().collect();
    order.sort_by(|a, b| b.strength().total_cmp(&a.strength()));
    let widths = [(60usize, 120usize), (48, 90), (40, 70), (36, 56), (32, 44), (28, 36), (24, 28)];
    let build = |(tw, ww): (usize, usize)| {
        let mut out = String::from(INDEX_HEADER);
        let mut all_fit = true;
        for d in &order {
            let line = format!("\n{} | {} | {}", d.id, index_cell(&d.title, tw), index_cell(&d.when, ww));
            if out.len() + line.len() > budget {
                all_fit = false;
                break;
            }
            out.push_str(&line);
        }
        (out, all_fit)
    };
    for w in widths {
        let (out, fit) = build(w);
        if fit {
            return out;
        }
    }
    build(widths[widths.len() - 1]).0
}

/// The index of the lessons recall may deliver in this scope: the user's bank plus the project (team) bank,
/// in scope, not quiet, and past the same eligibility gate recall applies. A lesson mined or distilled that no
/// hit has confirmed stays out until a match proves it, exactly as in recall; one you banked yourself is
/// listed, as recall lets it through on a strong trigger.
fn index_block(path: &PathBuf, scope: &eligibility::Scope) -> Result<String, String> {
    let quiet = quiet_ids(path);
    let now = now_secs();
    let mut all = load_scoped(path, scope, now)?;
    all.retain(|d| {
        if eligibility::quiet(d.hits, d.misses) {
            return false;
        }
        match eligibility::eligible(&d.meta, scope, now, None, d.hits, quiet.contains(&d.id)) {
            Ok(()) => true,
            Err("candidate_match_unproven") => d.meta.source == "banked",
            Err(_) => false,
        }
    });
    Ok(render_index(&all, INDEX_BUDGET))
}

/// `instinct show ID [ID...]`: the full lessons, rendered exactly as recall renders them.
fn op_show(path: &PathBuf, ids: &[String]) -> Result<String, String> {
    if ids.is_empty() {
        return Err("usage: show ID [ID...]".into());
    }
    // The user's bank and the project (team) bank, so every id the index lists can be shown.
    let all = load_view(path)?;
    let mut out = Vec::new();
    for raw in ids {
        let id = raw.trim().trim_matches(|c| c == '[' || c == ']');
        let d = all.iter().find(|d| d.id == id).ok_or_else(|| format!("no lesson {id}"))?;
        out.push(render_entry(d));
    }
    Ok(out.join("\n\n"))
}

/// Cline launches the hook in its active workspace. A single reported root also
/// identifies the workspace when the hook is invoked from another directory.
fn cline_workspace(event: &Json) -> Result<Option<&str>, ()> {
    match event.get("workspaceRoots") {
        None => Ok(None),
        Some(Json::Arr(roots)) if roots.is_empty() => Ok(None),
        Some(Json::Arr(roots)) => {
            let cwd = std::env::current_dir().ok();
            roots.iter().filter_map(Json::as_str).find(|root| {
                let path = Path::new(root);
                path.is_absolute() && (roots.len() == 1 || same_dir(path, cwd.as_deref()))
            }).map(Some).ok_or(())
        }
        _ => Err(()),
    }
}

/// getcwd returns the resolved path (macOS reports /private/var for /var), so compare resolved paths.
fn same_dir(root: &Path, cwd: Option<&Path>) -> bool {
    let Some(cwd) = cwd else { return false };
    root == cwd || matches!((root.canonicalize(), cwd.canonicalize()), (Ok(a), Ok(b)) if a == b)
}

fn cline_reply(text: &str) -> String {
    if text.is_empty() {
        r#"{"cancel":false}"#.into()
    } else {
        format!(r#"{{"cancel":false,"contextModification":"{}"}}"#, escape_json(text))
    }
}

/// The hook recall (k=1) with session memory: a lesson already delivered in this session is skipped, so the
/// same tokens never arrive twice. Without a session id it behaves exactly like a plain k=1 recall.
fn recall_once_per_session(
    path: &PathBuf,
    kind: &'static str,
    q: &str,
    scope: &eligibility::Scope,
    sid: Option<&str>,
) -> Result<(String, Vec<String>), String> {
    let previous = sid.map(|s| session::seen(path, s)).unwrap_or_default();
    let seen = previous.lesson_ids();
    let timer = meter::start(path, kind);
    let mut methods = recall_methods(path, q, 1 + seen.len().min(10), scope)?;
    methods.retain(|d| !seen.contains(&d.id));
    methods.truncate(1);
    // A correction is actionable on this turn. An unsettled verdict can still be requested later.
    let followup = match (kind, sid) {
        ("prompt", Some(s)) => session::correction_line(path, s, &previous, q, &scope.project)
            .or_else(|| session::followup(path, s, &previous)),
        _ => None,
    };
    if let Some(s) = sid {
        methods.retain(|d| session::claim_lesson(path, s, &d.id, session::Source::Prompt));
    }
    let mut text = String::new();
    let mut ids = Vec::new();
    if let Some(lesson) = methods.first() {
        ids.push(lesson.id.clone());
        text = match &lesson.standing {
            Some(instruction) => render_prompt_default(lesson, instruction),
            None => format!("{SELECT_FOR_TASK}\n{}", render_entry(lesson)),
        };
    }
    let text = match followup {
        Some(f) if text.trim().is_empty() => f,
        Some(f) => format!("{text}\n\n{f}"),
        None => text,
    };
    if let Some(t) = timer {
        t.finish(ids.len(), text.len());
    }
    Ok((text, ids))
}

/// Keep the user's continuing instruction separate from the evidence behind the original method.
fn render_prompt_default(lesson: &Discovery, instruction: &StandingInstruction) -> String {
    let mut text = format!(
        "Project default [{}] ({}): {}\nWhen: {}",
        lesson.id, instruction.reference, instruction.text, lesson.when
    );
    if !lesson.reconsider.is_empty() {
        text.push_str(&format!("\nReconsider: {}", lesson.reconsider));
    }
    text.push_str("\nOn a match, apply the default without asking again. The current request takes precedence.");
    if !lesson.how.is_empty() && lesson.how != instruction.text {
        text.push_str(&format!("\nPrior method ({}): {}", validity_text(lesson), lesson.how));
    }
    text
}

fn op_recall_data(
    path: &PathBuf,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
) -> Result<(String, Vec<String>), String> {
    Ok(render_recall(&recall_methods(path, q, k, scope)?))
}

/// Check the receiver's normal ranked selection without counting a delivery or recording feedback.
fn probe_recall(path: &PathBuf, args: &Args, query: &str) -> Result<String, String> {
    let mut keys = HashSet::new();
    for (key, value) in &args.kv {
        if !matches!(key.as_str(), "expect" | "q" | "k" | "store" | "project" | "persona" | "harness" | "harness-version" | "machine")
            || value.trim().is_empty() || !keys.insert(key)
        {
            return Err("probe requires known, nonempty options supplied once".into());
        }
    }
    let id = args.opt("expect").unwrap_or("");
    if !args.pos.is_empty() || id.trim().is_empty() || query.trim().is_empty() {
        return Err("probe needs --expect ID and a nonempty --q".into());
    }
    let k = args.opt("k").unwrap_or("5").parse::<usize>()
        .ok().filter(|n| *n > 0).ok_or("probe needs a positive --k")?;
    let selected = recall_methods(path, query, k, &eligibility::env_scope())?;
    match selected.iter().position(|lesson| lesson.id == id) {
        Some(i) => Ok(format!("matched {id} at rank {} of {}", i + 1, selected.len())),
        None if selected.is_empty() => Err("expected lesson absent: recall returned no lessons".into()),
        None => Err(format!("expected lesson absent: recall selected {} other lesson(s)", selected.len())),
    }
}

fn render_recall(methods: &[Discovery]) -> (String, Vec<String>) {
    let ids = methods.iter().map(|d| d.id.clone()).collect();
    let text = methods
        .iter()
        .map(render_entry)
        .collect::<Vec<_>>()
        .join("\n\n");
    (text, ids)
}

fn render_recall_with_facts(
    methods: &[Discovery],
    facts: Option<&Json>,
) -> Result<(String, Vec<String>), String> {
    let Some(facts) = facts else {
        return Ok(render_recall(methods));
    };
    case_learning::validate_facts(facts)?;
    let mut entries = Vec::with_capacity(methods.len());
    for d in methods {
        let mut entry = render_plain_entry(d);
        if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
            entry.push_str("\n  ");
            entry.push_str(&book.guidance(facts)?);
        }
        entries.push(entry);
    }
    Ok((
        entries.join("\n\n"),
        methods.iter().map(|d| d.id.clone()).collect(),
    ))
}

/// A new task may have different vocabulary and the same observed checks. Only
/// an unambiguous, eligible casebook in this exact project can fill an empty recall.
fn case_candidates(
    path: &PathBuf,
    q: &str,
    scope: &eligibility::Scope,
    facts: Option<&Json>,
    selected: Vec<Discovery>,
) -> Result<Vec<Discovery>, String> {
    let Some(facts) = facts else {
        return Ok(selected);
    };
    case_learning::validate_facts(facts)?;
    if !selected.is_empty()
        || q.trim().is_empty()
        || scope.project.is_empty()
        || !matches!(facts, Json::Obj(fields) if fields.len() >= 2)
    {
        return Ok(selected);
    }
    let quiet = quiet_ids(path);
    let mut matched = Vec::new();
    for d in load_user_scoped(path, scope, now_secs())? {
        if d.meta.project != scope.project
            || d.meta.source != "banked"
            || d.standing.is_some()
            || quiet.contains(&d.id)
            || eligibility::quiet(d.hits, d.misses)
        {
            continue;
        }
        let Some(book) = &d.casebook else { continue };
        let advice = book.advise(facts)?;
        if matches!(advice.get("ignored_keys"), Some(Json::Arr(v)) if v.is_empty())
            && matches!(advice.get("supporting_refs"), Some(Json::Arr(v)) if !v.is_empty())
        {
            if !matched.is_empty() {
                return Ok(Vec::new());
            }
            matched.push(d);
        }
    }
    Ok(matched)
}

/// Byte length of `render_entry(d)` without building it (the meter needs it for every eligible lesson on every
/// lookup). A test pins it to `render_entry(d).len()`.
fn render_len(d: &Discovery) -> usize {
    fn digits(n: u32) -> usize {
        n.checked_ilog10().map_or(1, |l| l as usize + 1)
    }
    let s = d.strength();
    if !(0.0..9.995).contains(&s) {
        return render_entry(d).len();
    }
    let mut n = "[".len() + d.id.len() + "] ".len() + d.title.len() + "  (strength ".len() + 4
        + ", ".len() + digits(d.hits) + " hit / ".len() + digits(d.misses) + " miss)".len()
        + "\n  WHEN: ".len() + d.when.len() + "\n  FOUND: ".len() + d.found.len()
        + "\n  HOW: ".len() + d.how.len() + "\n  EVIDENCE: ".len() + d.evidence.len();
    for (key, v) in [("RECONSIDER", &d.reconsider), ("MACHINE", &d.meta.machine), ("TAGS", &shown_tags(&d.tags))] {
        if !v.is_empty() {
            n += "\n  ".len() + key.len() + ": ".len() + v.len();
        }
    }
    n += "\n  VALIDITY: ".len();
    if d.hits >= 2 && s >= 0.6 {
        n += VALID_PROVEN_HEAD.len() + digits(d.hits) + " hits, ".len() + digits(d.misses)
            + VALID_PROVEN_TAIL.len();
    } else {
        n += if eligibility::unverified(&d.meta) { VALID_UNVERIFIED } else { VALID_VERIFIED }.len();
        if d.meta.state == "candidate" || d.meta.source == "mined" {
            n += VALID_CANDIDATE.len();
        }
    }
    if let Some(i) = &d.standing {
        n += "\n  STANDING INSTRUCTION (".len() + i.reference.len() + "): ".len() + i.text.len();
    } else if let Some(book) = &d.casebook {
        n += "\n  ".len() + book.first_guidance().len();
    }
    n
}

const VALID_UNVERIFIED: &str = "source claim not independently verified";
const VALID_VERIFIED: &str = "verified within recorded scope";
const VALID_CANDIDATE: &str = "; candidate, check original evidence";
const VALID_PROVEN_HEAD: &str = "proven in use (";
const VALID_PROVEN_TAIL: &str = " misses); act on it unless the reconsider condition applies";

fn render_entry(d: &Discovery) -> String {
    let mut entry = render_plain_entry(d);
    if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
        entry.push_str("\n  ");
        entry.push_str(&book.first_guidance());
    }
    entry
}

fn render_plain_entry(d: &Discovery) -> String {
    let standing = d
        .standing
        .as_ref()
        .map(|instruction| {
            format!(
                "\n  STANDING INSTRUCTION ({}): {}",
                instruction.reference, instruction.text
            )
        })
        .unwrap_or_default();
    format!("{}\n  VALIDITY: {}{standing}", render(d), validity_text(d))
}

/// A lesson that already paid off twice (the `instinct instincts` bar) is an instinct: tell the agent to
/// act on it instead of re-checking the original evidence every time.
fn validity_text(d: &Discovery) -> String {
    if d.proven_in_use() {
        format!("{VALID_PROVEN_HEAD}{} hits, {}{VALID_PROVEN_TAIL}", d.hits, d.misses)
    } else {
        format!(
            "{}{}",
            if eligibility::unverified(&d.meta) { VALID_UNVERIFIED } else { VALID_VERIFIED },
            if d.meta.state == "candidate" || d.meta.source == "mined" { VALID_CANDIDATE } else { "" }
        )
    }
}

/// A synchronous adapter for any host's pre-decision step. No model call or feedback side effect.
fn decision_context(
    path: &PathBuf,
    situation: &str,
    scope: &eligibility::Scope,
    facts: Option<&Json>,
) -> Result<String, String> {
    if situation.trim().is_empty() {
        return Err("decide requires a situation via --q".into());
    }
    let timer = meter::start(path, "decide");
    let methods = case_candidates(path, situation, scope, facts, recall_methods(path, situation, 2, scope)?)?;
    let out = json_out(&decision_packet_with_facts(&methods, facts)?);
    if let Some(t) = timer {
        t.finish(methods.len(), out.len());
    }
    Ok(out)
}

/// A short retry can refer to the current job without naming it. Never carry context
/// through a new instruction, quoted text, or an ordinary acknowledgement.
fn short_retry(text: &str) -> bool {
    if text.len() > 96 {
        return false;
    }
    let lower = text.trim().trim_end_matches(['.', '!']).to_ascii_lowercase().replace('’', "'");
    let words = lower.trim().strip_prefix("no,").unwrap_or(&lower).trim();
    matches!(words, "still wrong" | "that's still wrong" | "that is still wrong"
        | "still incorrect" | "that's still incorrect" | "that is still incorrect")
}

/// Pick only when one applicability cue covers strictly more of the user's brief
/// than every competing cue. Refuse an incomplete candidate set.
fn retry_check(path: &PathBuf, task: &str, scope: &eligibility::Scope) -> Result<Option<Discovery>, String> {
    const LIMIT: usize = 8;
    if task.trim().is_empty() || task.len() > 2048 {
        return Ok(None);
    }
    let mut methods = recall_methods(path, task, LIMIT + 1, scope)?;
    if methods.len() > LIMIT {
        return Ok(None);
    }
    let query = anchors(brief_action::action_text(task).as_ref());
    let support: Vec<_> = methods.iter().map(|d| {
        let mut cue = anchors(&d.when);
        cue.retain(|a| query.contains(a));
        cue
    }).collect();
    let winner = support.iter().enumerate().position(|(i, cue)| {
        cue.len() >= 2 && support.iter().enumerate().all(|(j, other)| {
            i == j || (cue.len() > other.len() && cue.is_superset(other))
        })
    });
    Ok(winner.map(|i| methods.swap_remove(i)))
}

/// A short, opt-in preflight after a user correction. Keep the entire applicability boundary or abstain.
fn premortem(path: &PathBuf, situation: &str, previous_task: Option<&str>, scope: &eligibility::Scope) -> Result<String, String> {
    if situation.trim().is_empty() {
        return Err("premortem requires the user's correction".into());
    }
    let picked = if let Some(task) = previous_task.filter(|_| short_retry(situation)) {
        retry_check(path, task, scope)?
    } else if corrections::correction(situation) {
        recall_methods(path, situation, 1, scope)?.into_iter().next()
    } else {
        None
    };
    let Some(d) = picked else { return Ok(String::new()) };
    if !d.proven_in_use() || d.how.trim().is_empty() || d.found.trim().is_empty() {
        return Ok(String::new());
    }
    let mut fields = vec![
        ("id".into(), Json::Str(d.id.clone())),
        ("when".into(), Json::Str(d.when.clone())),
        ("previous_observation".into(), Json::Str(d.found.clone())),
        ("check".into(), Json::Str(d.how.clone())),
    ];
    if !d.reconsider.is_empty() {
        fields.push(("reconsider_if".into(), Json::Str(d.reconsider.clone())));
    }
    let packet = json_out(&Json::Obj(fields));
    Ok(if packet.len() <= 320 { packet } else { String::new() })
}

const SELECT_FOR_TASK: &str = "Select only the methods applicable to the current request. Use none if none apply.";
fn decision_packet(methods: &[Discovery]) -> Json {
    decision_packet_with_facts(methods, None).expect("empty facts are valid")
}

fn decision_packet_with_facts(methods: &[Discovery], facts: Option<&Json>) -> Result<Json,String> {
    let empty = Json::Obj(vec![]);
    let experiences = methods
        .iter()
        .map(|d| {
            let mut fields = vec![
                ("id".into(), Json::Str(d.id.clone())),
                ("when".into(), Json::Str(d.when.clone())),
                ("method".into(), Json::Str(d.how.clone())),
                (
                    "machine".into(),
                    if d.meta.machine.is_empty() {
                        Json::Null
                    } else {
                        Json::Str(d.meta.machine.clone())
                    },
                ),
                (
                    "standing_instruction".into(),
                    d.standing.as_ref().map_or(Json::Null, |v| {
                        Json::Obj(vec![
                            ("text".into(), Json::Str(v.text.clone())),
                            ("source_ref".into(), Json::Str(v.reference.clone())),
                        ])
                    }),
                ),
                ("observed".into(), Json::Str(d.found.clone())),
                ("evidence".into(), Json::Str(d.evidence.clone())),
                (
                    "reconsider_if".into(),
                    if d.reconsider.is_empty() {
                        Json::Null
                    } else {
                        Json::Str(d.reconsider.clone())
                    },
                ),
                ("hits".into(), Json::Num(d.hits.into())),
                ("misses".into(), Json::Num(d.misses.into())),
                // Same bar as `instinct instincts`: paid off twice, strength 0.6 or more. Hosts can act on it.
                ("proven".into(), Json::Bool(d.proven_in_use())),
                (
                    "evidence_status".into(),
                    Json::Str(
                        if eligibility::unverified(&d.meta) {
                            "unverified"
                        } else {
                            "verified_in_scope"
                        }
                        .into(),
                    ),
                ),
            ];
            if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
                fields.push(("case_advice".into(), book.advise(facts.unwrap_or(&empty))?));
            }
            Ok(Json::Obj(fields))
        })
        .collect::<Result<Vec<_>,String>>()?;
    Ok(Json::Obj(vec![
        ("version".into(), Json::Num(1.0)),
        ("selection_instruction".into(), Json::Str(SELECT_FOR_TASK.into())),
        ("experiences".into(), Json::Arr(experiences)),
    ]))
}

/// A checked hit is user-bank only: a team lesson keeps its evidence in the project bank, which has no check attachments.
fn refuse_team_check(path: &PathBuf, id: &str) -> Result<(), String> {
    if team::find(path).is_some_and(|t| team::has_lesson(&t, id)) {
        return Err("checked feedback does not support team lessons yet; nothing recorded (use plain `hit`)".into());
    }
    Ok(())
}

fn op_mark(
    path: &PathBuf,
    kind: &str,
    id: &str,
    note: &str,
    outcome_id: &str,
) -> Result<String, String> {
    // A lesson that lives in the project bank takes its evidence there, so the whole team counts it.
    let shared = team::find(path).filter(|t| team::has_lesson(t, id));
    let path = shared.as_ref().unwrap_or(path);
    let _lock = journal::identity_lock(path)?;
    let entry = match &shared {
        Some(t) => team::load(t),
        None => load_plain(path),
    }?
    .into_iter()
    .find(|d| d.id == id)
    .ok_or_else(|| format!("no discovery with id {id}"))?;
    let generated = if shared.is_some() && outcome_id.trim().is_empty() { team::event_key() } else { String::new() };
    let key = if generated.is_empty() { outcome_id.trim() } else { generated.as_str() };
    if let Some(&paid_off) = entry.outcomes.get(key) {
        if paid_off.is_none() {
            return Err("conflicting reports for this outcome; nothing recorded".into());
        }
        if paid_off != Some(kind == "hit") {
            return Err("outcome already recorded with a different verdict".into());
        }
        return Ok(format!("outcome already recorded for {id}"));
    }
    append(path, &feedback_event(kind, id, note, key, now_secs()))?;
    Ok(format!("{kind} recorded for {id}"))
}

fn feedback_event(kind: &str, id: &str, note: &str, key: &str, ts: u64) -> String {
    let mut fields = vec![
        ("kind".into(), Json::Str(kind.into())),
        ("id".into(), Json::Str(id.into())),
        ("ts".into(), Json::Num(ts as f64)),
        ("note".into(), Json::Str(note.into())),
    ];
    if !key.is_empty() {
        fields.push(("outcome_id".into(), Json::Str(key.into())));
    }
    json_out(&Json::Obj(fields))
}

fn op_mark_case(
    path: &PathBuf, kind: &str, id: &str, note: &str, outcome_id: &str,
    observation: &Json, scope: &eligibility::Scope,
) -> Result<String, String> {
    if !matches!(kind, "hit" | "miss") || outcome_id.is_empty() || outcome_id.trim() != outcome_id {
        return Err("observed feedback requires hit or miss and a nonempty stable outcome id".into());
    }
    if is_team_bank(path) {
        return Err("observed feedback requires an active directly banked personal lesson".into());
    }
    let Json::Obj(fields) = observation else { return Err("observation must contain facts and action".into()) };
    if fields.len() != 2 {
        return Err("observation must contain exactly facts and action".into());
    }
    let facts = observation.get("facts").ok_or("observation requires facts")?;
    let action = observation.get("action").ok_or("observation requires the action that worked")?;
    let _lock = journal::identity_lock(path)?;
    let ts = now_secs();
    let all = fold_text_for_bank(&journal::read(path)?, &path.display().to_string(), |_, _, _, _| {}, Some(id))?;
    let d = all.iter().find(|d| d.id == id).ok_or("no active directly banked personal lesson with this id")?;
    eligibility::scope_check(&d.meta, scope, ts).map_err(|why| format!("lesson is outside the active scope: {why}"))?;
    let book = d.casebook.as_ref().ok_or("lesson has no active casebook")?;
    let vocabulary = book.to_json();
    let example = Json::Obj(vec![
        ("ref".into(), Json::Str(outcome_id.into())), ("facts".into(), facts.clone()), ("action".into(), action.clone()),
    ]);
    let add = case_learning::Casebook::parse(&Json::Obj(vec![
        ("checks".into(), vocabulary.get("checks").ok_or("casebook is missing checks")?.clone()),
        ("examples".into(), Json::Arr(vec![example])),
    ]))?;
    let changed = book.merge(&add)? != *book;
    let previous = d.outcomes.get(outcome_id);
    if previous.is_some_and(|verdict| *verdict != Some(kind == "hit")) {
        return Err("conflicting verdict for this outcome; nothing recorded".into());
    }
    let mut rows = Vec::new();
    if changed { rows.push(case_event(d, &add, ts)); }
    if previous.is_none() { rows.push(feedback_event(kind, id, note, outcome_id, ts)); }
    if rows.is_empty() { return Ok(format!("outcome and observation already recorded for {id}")); }
    journal::append_many(path, &rows.iter().map(String::as_str).collect::<Vec<_>>())?;
    Ok(format!("{kind} and observation recorded for {id}"))
}

fn op_review(
    path: &PathBuf,
    id: &str,
    state: &str,
    reason: &str,
    reference: &str,
) -> Result<String, String> {
    if !["quarantined", "candidate"].contains(&state)
        || reason.trim().is_empty()
        || reference.trim().is_empty()
    {
        return Err("review requires state quarantined|candidate, reason and source-ref; does not grant verified status".into());
    }
    let _lock = journal::identity_lock(path)?;
    if !load_plain(path)?.iter().any(|d| d.id == id) {
        return Err("unknown active lesson".into());
    }
    append(path,&format!("{{\"kind\":\"review\",\"id\":\"{}\",\"ts\":{},\"state\":\"{state}\",\"evidence_status\":\"unverified\",\"reason\":\"{}\",\"source_ref\":\"{}\"}}",escape_json(id),now_secs(),escape_json(reason),escape_json(reference)))?;
    Ok(format!("reviewed {id}: {state}; original preserved"))
}

/// `sync pull|push|status`: file-level bank sync, the diff and merge live in sync.hlx.
fn op_sync(path: &PathBuf, a: &Args) -> Result<String, String> {
    let other = |flag: &str| a.opt(flag).filter(|p| !p.starts_with("--")).map(PathBuf::from).ok_or(format!("usage: instinct sync pull --from PATH | push --to PATH | status --with PATH (missing --{flag})"));
    let done = |verb: &str, to: &Path, r: sync::Report| {
        let conflicts = if r.conflicts > 0 { format!("; {} outcome(s) kept local: the other side holds a different verdict for the same outcome id", r.conflicts) } else { String::new() };
        format!("{verb} {} event(s) into {} ({} already there, {} read){conflicts}", r.added, to.display(), r.had, r.source)
    };
    match a.pos.first().map(String::as_str) {
        Some("pull") => {
            let from = other("from")?;
            Ok(done("pulled", path, sync::pull(path, &from)?))
        }
        Some("push") => {
            let to = other("to")?;
            Ok(done("pushed", &to, sync::pull(&to, path)?))
        }
        Some("status") => {
            let with = other("with")?;
            let (lacking_here, lacking_there, conflicts) = sync::status(path, &with)?;
            Ok(format!("this bank lacks {lacking_here} event(s) from {w}; {w} lacks {lacking_there} from this bank; {conflicts} conflicting outcome(s)", w = with.display()))
        }
        _ => Err("usage: instinct sync pull --from PATH | push --to PATH | status --with PATH".into()),
    }
}

/// Instincts = discoveries that kept paying off: >= min_hits hits and strength >= 0.6. One reflex line each.
fn op_instincts(path: &PathBuf, min_hits: u32) -> Result<String, String> {
    let scope = eligibility::env_scope();
    let quiet = quiet_ids(path);
    let mut all: Vec<Discovery> = load_view(path)?
        .into_iter()
        .filter(|d| {
            eligibility::promoted(d.hits, d.misses, min_hits)
                && eligibility::eligible(
                    &d.meta,
                    &scope,
                    now_secs(),
                    None,
                    d.hits,
                    quiet.contains(&d.id),
                )
                .is_ok()
        })
        .collect();
    all.sort_by(|a, b| {
        b.strength()
            .partial_cmp(&a.strength())
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(b.hits.cmp(&a.hits))
    });
    Ok(all.iter().map(|d| format!("- WHEN {} → {} (how: {}) [{} · {} hits; historical source claim, verify applicability]", d.when, d.found, d.how, d.id, d.hits)).collect::<Vec<_>>().join("\n"))
}

/// Embed every entry that has no vector yet (banked while Ollama was down); appends one `embed` event per entry.
fn op_reembed(path: &PathBuf) -> Result<String, String> {
    let all = load(path)?;
    let todo: Vec<&Discovery> = all.iter().filter(|d| d.embedding.is_empty()).collect();
    let mut done = 0;
    for d in &todo {
        let e = embed("search_document: ", &d.text())
            .map_err(|e| format!("stopped after {done}/{} ({e})", todo.len()))?;
        let emb: Vec<String> = e.iter().map(|f| f.to_string()).collect();
        append(
            path,
            &format!(
                "{{\"kind\":\"embed\",\"id\":\"{}\",\"ts\":{},\"embedding\":[{}]}}",
                escape_json(&d.id),
                now_secs(),
                emb.join(",")
            ),
        )?;
        done += 1;
    }
    Ok(format!(
        "re-embedded {done} of {} entries without a vector",
        todo.len()
    ))
}

fn op_stats(path: &PathBuf, a: &Args) -> Result<String, String> {
    let all = load_view(path)?;
    let inst = all
        .iter()
        .filter(|d| eligibility::promoted(d.hits, d.misses, 2))
        .count();
    let emb = all.iter().filter(|d| !d.embedding.is_empty()).count();
    let hits: u32 = all.iter().map(|d| d.hits).sum();
    let misses: u32 = all.iter().map(|d| d.misses).sum();
    let line = format!(
        "store {} · {} discoveries ({} embedded) · {} instincts · {} hits / {} misses",
        path.display(),
        all.len(),
        emb,
        inst,
        hits,
        misses
    );
    let share = a.flag("share");
    let since = a
        .opt("since")
        .filter(|s| !s.starts_with("--"))
        .unwrap_or(if share { "7d" } else { "all" });
    let window = meter::parse_since(since)?;
    let totals = meter::read(path, window, now_secs());
    let bank = meter::Bank { hits, misses, proven: inst };
    Ok(if a.flag("json") {
        meter::json(&totals, &bank, since)
    } else if share {
        meter::share(&totals, &bank, since)
    } else {
        format!("{line}\n{}", meter::block(&totals, &bank, since))
    })
}

/// Re-serialise a parsed Json value.
fn json_out(v: &Json) -> String {
    match v {
        Json::Null => "null".into(),
        Json::Bool(b) => b.to_string(),
        Json::Num(n) => n.to_string(),
        Json::Str(s) => format!("\"{}\"", escape_json(s)),
        Json::Arr(a) => format!("[{}]", a.iter().map(json_out).collect::<Vec<_>>().join(",")),
        Json::Obj(f) => format!(
            "{{{}}}",
            f.iter()
                .map(|(k, v)| format!("\"{}\":{}", escape_json(k), json_out(v)))
                .collect::<Vec<_>>()
                .join(",")
        ),
    }
}

// ---------------------------------------------------------------- MCP (JSON-RPC 2.0 over newline-delimited stdio)

fn tool_schema() -> &'static str {
    r#"[{"name":"instinct_bank","description":"Call after a fix is verified (a command ran, a test passed, the error is gone) to save it as a lesson. Write `when` in the words a future question will use. Saved as an unverified candidate; evidence text does not make it verified. Set project for a project rule. Omit applicability_harness, applicability_version, applicability_machine and persona unless the rule actually depends on that exact dimension. Values like any or all are literal scope names, not wildcards.","inputSchema":{"type":"object","properties":{"title":{"type":"string"},"when":{"type":"string","description":"the situation/trigger where this applies"},"found":{"type":"string","description":"what was discovered (the fact/fix/lever)"},"how":{"type":"string","description":"the method that found it (probe, measurement, question asked)"},"evidence":{"type":"string","description":"the measured numbers or verification"},"reconsider":{"type":"string","description":"observed or explicitly stated change that would make this method unsuitable"},"tags":{"type":"string"},"project":{"type":"string","description":"exact project applicability; falls back only to explicit INSTINCT_PROJECT"},"persona":{"type":"string","description":"exact persona applicability; falls back only to explicit INSTINCT_PERSONA"},"applicability_harness":{"type":"string","description":"harness this lesson applies to, not the caller or receipt origin"},"applicability_version":{"type":"string","description":"exact applicable harness version, if known"},"applicability_machine":{"type":"string","description":"Restrict this lesson to a named machine only when its setup matters. Omit for portable methods."},"cases":{"type":"object","description":"Optional observed examples of one decision. Rebank the same lesson with new evidence references to extend it.","properties":{"checks":{"type":"array","minItems":1,"maxItems":16,"items":{"type":"object","properties":{"key":{"type":"string"},"question":{"type":"string"},"cost":{"type":"integer","minimum":1}},"required":["key","question","cost"],"additionalProperties":false}},"examples":{"type":"array","minItems":1,"maxItems":128,"items":{"type":"object","properties":{"ref":{"type":"string"},"facts":{"type":"object","additionalProperties":{"type":"boolean"}},"action":{"type":"string"}},"required":["ref","facts","action"],"additionalProperties":false}}},"required":["checks","examples"],"additionalProperties":false},"replay":{"type":"object","description":"A completed gnosis-1 check report. Bank its recomputed held-out result with optional scope fields."}},"oneOf":[{"required":["title","when","found","how","evidence"]},{"required":["replay"]}]}},
{"name":"instinct_default","description":"After banking a lesson, record the user's explicit continuing instruction for its project. Supply their exact instruction and its source reference. Use clear=true to withdraw it. One-time approvals are not continuing instructions.","inputSchema":{"type":"object","properties":{"id":{"type":"string"},"project":{"type":"string"},"persona":{"type":"string"},"instruction":{"type":"string"},"source_ref":{"type":"string"},"clear":{"type":"boolean"}},"required":["id","project"]}},
{"name":"instinct_recall","description":"Call before starting a task that failed or was corrected before, with the task, requested format and any exceptions in q. Select the returned methods that apply to this request. Use none if none apply. Apply selected methods marked proven in use. Check the evidence for other selections. Pass project, persona and harness when known; unspecified context does not match explicitly scoped lessons.","inputSchema":{"type":"object","properties":{"q":{"type":"string"},"k":{"type":"integer"},"project":{"type":"string"},"persona":{"type":"string"},"harness":{"type":"string"},"harness_version":{"type":"string"},"machine":{"type":"string","description":"Exact local alias for matching machine-specific lessons."},"session":{"type":"string"},"facts":{"type":"object","additionalProperties":{"type":"boolean"},"description":"Checks already observed on this task, keyed as given by a casebook on the initial recall. Omit unknown checks."}},"required":["q"]}},
{"name":"instinct_guide","description":"List decision workflows or run one on the current task. Use example for an isolated walkthrough. Read-only. Rehearse and transfer take changed, retry takes correction, verify and debrief take expected and optionally observed. Debrief can include method and exception; transfer can include test and prediction. Experiment chooses a feasible teaching case for a lesson with two observed actions or predicts conditionally under a two-check assumption.","inputSchema":{"type":"object","properties":{"mode":{"type":"string","enum":["list","run","prepare","investigate","review","start","options","challenge","explain","rehearse","transfer","verify","retry","handoff","debrief","experiment"]},"example":{"type":"string"},"steps":{"type":"string","description":"Comma-separated workflow names for run, in order."},"q":{"type":"string"},"changed":{"type":"string"},"expected":{"type":"string"},"observed":{"type":"string"},"correction":{"type":"string"},"method":{"type":"string"},"test":{"type":"string"},"prediction":{"type":"string"},"exception":{"type":"string"},"project":{"type":"string"},"persona":{"type":"string"},"harness":{"type":"string"},"harness_version":{"type":"string"},"machine":{"type":"string"},"id":{"type":"string","description":"The banked personal lesson to study in experiment mode."},"facts":{"type":"object","additionalProperties":{"type":"boolean"},"description":"Observed facts of a case to predict. Omit unknown checks."},"pool":{"type":"array","maxItems":512,"items":{"type":"object","additionalProperties":{"type":"boolean"}},"description":"Feasible teaching cases with all check values and no outcomes. An empty list disables suggestions."},"after_ref":{"type":"string","description":"Show how many explanations this observed reference alone rules out when all other evidence and action labels are held fixed."}},"additionalProperties":false},"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
{"name":"instinct_feedback","description":"Call after acting on a recalled lesson to record one outcome: paid_off true (hit) or false (miss), with a short note. Hits promote a lesson to proven in use.","inputSchema":{"type":"object","properties":{"id":{"type":"string"},"paid_off":{"type":"boolean"},"note":{"type":"string"},"outcome_id":{"type":"string","description":"Reuse the same key when retrying feedback for one observed outcome."},"check":{"type":"boolean","description":"Run the attached read-only check before recording a hit; requires a server root grant."},"trusted_staging":{"type":"boolean","description":"Explicitly acknowledge the granted tree is trusted and quiescent for this observation."},"case":{"type":"object","description":"Append a measured example to this lesson’s existing casebook. Supply the actual successful action, all its observed Boolean facts, matching scope and a stable outcome_id. On a miss use the verified correction.","properties":{"facts":{"type":"object","additionalProperties":{"type":"boolean"}},"action":{"type":"string"}},"required":["facts","action"],"additionalProperties":false},"project":{"type":"string","description":"Current task scope when teaching case feedback."},"persona":{"type":"string","description":"Current task scope when teaching case feedback."},"harness":{"type":"string","description":"Current task scope when teaching case feedback."},"harness_version":{"type":"string","description":"Current task scope when teaching case feedback."},"machine":{"type":"string","description":"Current task scope when teaching case feedback."}},"required":["id","paid_off"]}},
{"name":"instinct_list","description":"Call before a broad task, or to review what is proven: lists the lessons that repeatedly paid off, as WHEN -> DO reflex lines.","inputSchema":{"type":"object","properties":{}}}]"#
}

/// Sent in the MCP `initialize` result so an agent that only has the tools still knows the loop.
const MCP_INSTRUCTIONS: &str = "Instinct is a local memory of what worked. The loop: (1) Before a task that failed or was corrected before, call instinct_recall with the task, requested format and any exceptions. Select the methods that apply to the current request. Use none if none apply. Apply selected lessons marked proven in use. Check the evidence for other selections. (2) After you verify a fix (a command ran, a test passed, the error is gone), call instinct_bank. Write `when` in the words a future question will use, not a description of this session. (3) After acting on a recalled lesson, call instinct_feedback once with paid_off true or false and a short note.";

/// MCP prompts, shown as /mcp__instinct__NAME in Claude Code and /NAME in Gemini CLI: (name, description, text).
const PROMPTS: [(&str, &str, &str); 6] = [
    (
        "learn",
        "Bank the fix that just worked in this conversation as an Instinct lesson",
        "Bank the fix that just worked in this conversation as one Instinct lesson.\n\n1. Pick the single fix that was verified here (a command ran, a test passed, the error went away). If nothing was verified yet, say so and stop. Do not bank a guess.\n2. Write the lesson: title (short, names the problem); when (the words a future question would use when the problem shows up again: symptoms, error text, tool names); found (the cause, one sentence); how (the exact fix or command); evidence (what you observed that proves it worked); tags (1 to 3 lowercase words).\n3. Bank it with the instinct_bank tool.\n4. Read it back with instinct_recall using the `when` text and show the saved lesson: id, when, how. If the `when` does not find it, rewrite the `when` and bank again.",
    ),
    (
        "recall",
        "Show what Instinct already knows about a topic or the current task",
        "Call the instinct_recall tool with the topic below (k = 3). If no topic is given, use a one-line summary of the current task. Show each lesson with its id, WHEN, HOW and hit/miss counts as returned. If nothing fits, say 'Instinct has nothing for this yet' in one line and do not invent a lesson. Remember the id of the top lesson for /worked and /wrong.",
    ),
    (
        "worked",
        "Record that the lesson Instinct recalled last paid off",
        "Record one hit on the lesson Instinct recalled last in this conversation.\n\n1. Find the id of the most recent lesson Instinct returned here (an in-xxxxxxx id). If there is none, say so and stop. Do not guess an id.\n2. Write a one-sentence note: what the lesson said and how it helped.\n3. Call instinct_feedback with that id, paid_off true and the note.\n4. Show the id, the note and the new hit/miss counts (instinct_recall with the lesson's `when` prints them).",
    ),
    (
        "wrong",
        "Record that the lesson Instinct recalled last was wrong or did not help",
        "Record one miss on the lesson Instinct recalled last in this conversation.\n\n1. Find the id of the most recent lesson Instinct returned here (an in-xxxxxxx id). If there is none, say so and stop. Do not guess an id.\n2. Write a one-sentence note: what the lesson said and what was true instead.\n3. Call instinct_feedback with that id, paid_off false and the note.\n4. Show the id, the note and the new hit/miss counts (instinct_recall with the lesson's `when` prints them).",
    ),
    (
        "grade",
        "Grade this folder's agent memory files (CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules)",
        "Run `instinct audit` in the project folder (with no file it grades whichever of CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules and .github/copilot-instructions.md exist), then `instinct audit --share`. Show the grade and numbers as printed, then the share line on its own so it can be copied. Say in one sentence how many tokens the file adds to every prompt and how many one Instinct lookup adds instead, and give `instinct import FILE --apply` (with the real file name) as the way to turn its rules into lessons. If no file was found, say so and stop.",
    ),
    (
        "saved",
        "Show Instinct savings and the shareable one-line summary",
        "Run `instinct stats`, then `instinct stats --share`. Show both blocks as printed and add no numbers of your own. If the bank is empty, say Instinct has no lessons yet and that /learn banks the first one.",
    ),
];

fn recall_receipt(picked: &[String], args: Option<&Json>) -> Option<Json> {
    let ids: Vec<Json> = picked.iter().map(|id| Json::Str(id.clone())).collect();
    if ids.is_empty() {
        return None;
    }
    let arg = |k: &str| {
        args.and_then(|v| v.get(k))
            .and_then(Json::as_str)
            .unwrap_or("")
            .to_string()
    };
    let mut session = arg("session");
    if session.is_empty() {
        session = env_or("INSTINCT_SESSION", "unknown-session");
    }
    let mut harness = arg("harness");
    if harness.is_empty() {
        harness = env_or("INSTINCT_HARNESS", "unknown");
    }
    let ns = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    Some(Json::Obj(vec![
        ("schema_version".into(), Json::Num(1.0)),
        (
            "event_id".into(),
            Json::Str(format!("recall-{}-{ns}", std::process::id())),
        ),
        ("ts".into(), Json::Num(now_secs() as f64)),
        ("session".into(), Json::Str(session)),
        ("harness".into(), Json::Str(harness)),
        ("ids".into(), Json::Arr(ids)),
        ("channel".into(), Json::Str("mcp-recall".into())),
        (
            "delivery_boundary".into(),
            Json::Str("MCP stdout flushed; model use unproven".into()),
        ),
    ]))
}
fn receipt_stage(mut meta: Json, stage: &str, text: &str) -> Result<(), String> {
    // Opt in per installation. Separate stores do not write into another harness's telemetry.
    let root = match std::env::var("INSTINCT_TELEMETRY_DIR") {
        Ok(s) if !s.is_empty() => PathBuf::from(s),
        _ => return Ok(()),
    };
    // Fixed paths, no PATH lookup: GNU coreutils on Linux, /sbin on recent macOS, shasum on older macOS.
    let mut child = [
        ("/usr/bin/sha256sum", &[][..]),
        ("/sbin/sha256sum", &[][..]),
        ("/usr/bin/shasum", &["-a", "256"][..]),
    ]
    .iter()
    .find_map(|(exe, args)| {
        std::process::Command::new(exe)
            .args(*args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .ok()
    })
    .ok_or("no sha256 tool at /usr/bin/sha256sum, /sbin/sha256sum or /usr/bin/shasum")?;
    child
        .stdin
        .take()
        .ok_or("hash stdin")?
        .write_all(text.as_bytes())
        .map_err(|e| e.to_string())?;
    let out = child.wait_with_output().map_err(|e| e.to_string())?;
    let hash = String::from_utf8_lossy(&out.stdout)
        .split_whitespace()
        .next()
        .unwrap_or("")
        .to_string();
    if !out.status.success() || hash.len() != 64 {
        return Err("receipt hashing failed".into());
    }
    if let Json::Obj(ref mut fields) = meta {
        fields.push(("stage".into(), Json::Str(stage.into())));
        fields.push(("excerpt_sha256".into(), Json::Str(hash)));
    }
    append(
        &root.join(if stage == "selected" {
            "instinct-injections.jsonl"
        } else {
            "instinct-deliveries.jsonl"
        }),
        &json_out(&meta),
    )
}

fn bank_payload(
    path: &PathBuf,
    payload: &Json,
    scope: &eligibility::Scope,
) -> Result<String, String> {
    let mut derived;
    let payload = if let Some(report) = payload.get("replay") {
        derived = replay_lesson::from_gnosis(report)?;
        let Json::Obj(fields) = payload else {
            return Err("bank requires an object".into());
        };
        let Json::Obj(lesson) = &mut derived else {
            return Err("expected a replay lesson".into());
        };
        let mut keys = HashSet::new();
        for (key, value) in fields {
            if !keys.insert(key) {
                return Err(format!("duplicate bank field {key}"));
            }
            match key.as_str() {
                "replay" => {}
                "project"
                | "persona"
                | "applicability_harness"
                | "applicability_version"
                | "applicability_machine"
                    if value.as_str().is_some() =>
                {
                    lesson.push((key.clone(), value.clone()));
                }
                _ => return Err(format!("unexpected field alongside replay: {key}")),
            }
        }
        &derived
    } else {
        payload
    };
    let text = |key| {
        payload
            .get(key)
            .and_then(Json::as_str)
            .unwrap_or("")
            .to_owned()
    };
    let lesson = BankIn {
        title: text("title"),
        when: text("when"),
        found: text("found"),
        how: text("how"),
        evidence: text("evidence"),
        reconsider: text("reconsider"),
        tags: text("tags"),
        project: text("project"),
        persona: text("persona"),
        applicability_harness: text("applicability_harness"),
        applicability_version: text("applicability_version"),
        applicability_machine: payload
            .get("applicability_machine")
            .map(|_| text("applicability_machine")),
    };
    let cases = payload
        .get("cases")
        .map(case_learning::Casebook::parse)
        .transpose()?;
    op_bank_cases(path, lesson, cases, scope)
}

/// Scope belongs to the importing caller. A shared file describes the method and its evidence.
fn bank_from(path: &PathBuf, args: &Args, source: &str) -> Result<String, String> {
    let mut keys = HashSet::new();
    if !args.pos.is_empty()
        || args.kv.iter().any(|(key, _)| {
            !matches!(key.as_str(), "from" | "store" | "project" | "persona") || !keys.insert(key)
        })
    {
        return Err("use bank --from SOURCE with optional --project, --persona and --store".into());
    }
    let raw = match source {
        "builtin:zip-handoff" => {
            include_str!("../skills/instinct/references/zip-handoff.json").to_owned()
        }
        "builtin:verify-handoff" => {
            include_str!("../skills/instinct/references/verify-handoff.json").to_owned()
        }
        "-" => {
            let mut raw = String::new();
            std::io::stdin()
                .read_to_string(&mut raw)
                .map_err(|e| format!("read lesson from stdin: {e}"))?;
            raw
        }
        file => fs::read_to_string(file).map_err(|e| format!("read lesson file {file}: {e}"))?,
    };
    let payload = parse_json(&raw)?;
    if payload.get("protocol").and_then(Json::as_str) == Some("gnosis-1") {
        let lesson = replay_lesson::from_gnosis(&payload)?;
        return bank_payload(path, &lesson, &eligibility::env_scope());
    }
    let Json::Obj(fields) = &payload else {
        return Err("lesson file must be a JSON object".into());
    };
    let mut seen = HashSet::new();
    for (key, value) in fields {
        if !seen.insert(key)
            || !matches!(
                key.as_str(),
                "title" | "when" | "found" | "how" | "evidence" | "reconsider" | "tags" | "cases"
            )
            || (key != "cases" && value.as_str().is_none())
        {
            return Err(format!("invalid or repeated lesson field {key}"));
        }
    }
    bank_payload(path, &payload, &eligibility::env_scope())
}

fn mcp_call(
    cache: &mut Option<recall_index::Index>,
    path: &PathBuf,
    name: &str,
    args: Option<&Json>,
) -> Result<(String, Vec<String>), String> {
    let s = |k: &str| {
        args.and_then(|a| a.get(k))
            .and_then(Json::as_str)
            .unwrap_or("")
            .to_string()
    };
    let request_scope = || {
            let mut scope = eligibility::env_scope();
            for (key, dest) in [
                ("project", &mut scope.project),
                ("persona", &mut scope.persona),
                ("harness", &mut scope.harness),
                ("harness_version", &mut scope.version),
                ("machine", &mut scope.machine),
            ] {
                let v = s(key);
                if !v.is_empty() {
                    *dest = v;
                }
            }
            scope
        };
    let out = match name {
        "instinct_bank" => bank_payload(path, args.ok_or("bank needs lesson fields")?, &request_scope()),
        "instinct_default" => {
            let mut kv = vec![("project".into(), s("project"))];
            for (key, option) in [("instruction", "instruction"), ("source_ref", "source-ref")] {
                if let Some(value) = args.and_then(|a| a.get(key)) {
                    kv.push((option.into(), value.as_str().ok_or("expected text in default instruction and source_ref")?.into()));
                }
            }
            match args.and_then(|a| a.get("clear")) {
                Some(Json::Bool(true)) => kv.push(("clear".into(), String::new())),
                None | Some(Json::Bool(false)) => {}
                _ => return Err("clear requires a boolean".into()),
            }
            rehearsal::set_default(path, &Args { pos: vec![s("id")], kv }, &request_scope())
        }
        "instinct_guide" => {
            let empty = Json::Obj(vec![]);
            guide::run(|| Ok(path.clone()), args.unwrap_or(&empty), &request_scope()).map(|v| json_out(&v))
        }
        "instinct_recall" => {
            let k = args
                .and_then(|a| a.get("k"))
                .and_then(Json::as_f64)
                .unwrap_or(5.0) as usize;
            let scope = request_scope();
            let timer = meter::start(path, "mcp");
            return recall_index::recall(cache, path, &s("q"), k.clamp(1, 20), &scope).and_then(
                |methods| {
                    let facts = args.and_then(|a| a.get("facts"));
                    let methods = case_candidates(path, &s("q"), &scope, facts, methods)?;
                    let (r, ids) = render_recall_with_facts(&methods, facts)?;
                    if let Some(t) = timer {
                        t.finish(ids.len(), r.len());
                    }
                    Ok((
                        if r.is_empty() {
                            "(nothing banked matches)".into()
                        } else {
                            r
                        },
                        ids,
                    ))
                },
            );
        }
        "instinct_feedback" => {
            // A missing or misspelled flag used to record a silent "miss" (2026-10-20: `paid: true` became a miss, and old
            // misses carry notes that read like wins). Now: accept the obvious spellings, refuse anything else.
            let flag = ["paid_off", "paid", "helped", "hit"]
                .iter()
                .find_map(|k| args.and_then(|a| a.get(k)));
            let paid = match flag {
                Some(Json::Bool(b)) => *b,
                _ => return Err("instinct_feedback needs paid_off: true (helped) or false (misled); nothing recorded".into()),
            };
            if let Some(observation) = args.and_then(|a| a.get("case")) {
                if args.is_some_and(|a| ["check","trusted_staging","root"].iter().any(|k| a.get(k).is_some())) {
                    return Err("case feedback uses the observed example and cannot be combined with checked-feedback options".into());
                }
                return op_mark_case(path, if paid {"hit"} else {"miss"}, &s("id"), &s("note"),
                    &s("outcome_id"), observation, &request_scope()).map(|r| (r, vec![]));
            }
            if let Some(flag) = args.and_then(|a| a.get("check")) {
                if !matches!(flag, Json::Bool(_)) { return Err("check must be boolean".into()); }
                if flag == &Json::Bool(true) {
                    if !paid { return Err("checked feedback requires paid_off true".into()); }
                    if args.is_some_and(|a| a.get("root").is_some()) { return Err("request cannot override server root grant".into()); }
                    let root = std::env::var("INSTINCT_CHECK_ROOT").unwrap_or_default();
                    let trusted = args.and_then(|a| a.get("trusted_staging")) == Some(&Json::Bool(true));
                    refuse_team_check(path, &s("id"))?;
                    return check::feedback::hit(path, &s("id"), &s("note"), &s("outcome_id"), &root, trusted).map(|r| (r, vec![]));
                }
            }
            op_mark(
                path,
                if paid { "hit" } else { "miss" },
                &s("id"),
                &s("note"),
                &s("outcome_id"),
            )
        }
        "instinct_list" => op_instincts(path, 2).map(|r| {
            if r.is_empty() {
                "(no instincts yet — discoveries become instincts after 2+ hits)".into()
            } else {
                r
            }
        }),
        _ => Err(format!("unknown tool {name}")),
    };
    out.map(|text| (text, Vec::new()))
}

/// Tools that change the bank. `instinct serve` refuses them (and hides them) unless started with --allow-write.
const WRITE_TOOLS: [&str; 3] = ["instinct_bank", "instinct_feedback", "instinct_default"];

/// One JSON-RPC line in, at most one reply line out. The stdio loop and `instinct serve` both call this, so the
/// tools are identical on both transports. `allow_write` is always true on stdio. The second value is the recall
/// delivery receipt the caller stages after it has sent the reply.
fn mcp_message(
    cache: &mut Option<recall_index::Index>,
    path: &PathBuf,
    line: &str,
    allow_write: bool,
) -> Option<(String, Option<(Json, String)>)> {
    let msg = parse_json(line).ok()?;
    let id = msg.get("id")?; // notifications get no reply
    {
        let id_txt = match id {
            Json::Num(n) => format!("{}", *n as i64),
            Json::Str(s) => format!("\"{}\"", escape_json(s)),
            _ => "null".into(),
        };
        let method = msg.get("method").and_then(Json::as_str).unwrap_or("");
        let mut delivery: Option<(Json, String)> = None;
        let result = match method {
            "initialize" => {
                let pv = msg
                    .get("params")
                    .and_then(|p| p.get("protocolVersion"))
                    .and_then(Json::as_str)
                    .unwrap_or("2024-11-05");
                format!("{{\"protocolVersion\":\"{}\",\"capabilities\":{{\"tools\":{{}},\"prompts\":{{}}}},\"serverInfo\":{{\"name\":\"instinct\",\"version\":\"{}\"}},\"instructions\":\"{}\"}}", escape_json(pv), env!("CARGO_PKG_VERSION"), escape_json(MCP_INSTRUCTIONS))
            }
            "prompts/list" => {
                let items: Vec<String> = PROMPTS
                    .iter()
                    .map(|(name, desc, _)| {
                        format!(
                            "{{\"name\":\"{name}\",\"description\":\"{}\",\"arguments\":[{{\"name\":\"text\",\"description\":\"optional detail\",\"required\":false}}]}}",
                            escape_json(desc)
                        )
                    })
                    .collect();
                format!("{{\"prompts\":[{}]}}", items.join(","))
            }
            "prompts/get" => {
                let p = msg.get("params");
                let name = p.and_then(|p| p.get("name")).and_then(Json::as_str).unwrap_or("");
                let text = p
                    .and_then(|p| p.get("arguments"))
                    .and_then(|a| a.get("text"))
                    .and_then(Json::as_str)
                    .unwrap_or("")
                    .trim();
                let Some((_, desc, body)) = PROMPTS.iter().find(|(n, _, _)| *n == name) else {
                    return Some((format!("{{\"jsonrpc\":\"2.0\",\"id\":{id_txt},\"error\":{{\"code\":-32602,\"message\":\"unknown prompt {}\"}}}}", escape_json(name)), None));
                };
                let extra = if text.is_empty() { String::new() } else { format!("\n\nFrom the user: {text}") };
                format!(
                    "{{\"description\":\"{}\",\"messages\":[{{\"role\":\"user\",\"content\":{{\"type\":\"text\",\"text\":\"{}\"}}}}]}}",
                    escape_json(desc),
                    escape_json(&format!("{body}{extra}"))
                )
            }
            "tools/list" => {
                let existing = tool_schema().replace('\n', "");
                let all = format!("{{\"tools\":{},{}]}}", existing.trim_end_matches(']'), check::mcp::SCHEMA);
                if allow_write {
                    all
                } else {
                    // Read-only: list only the tools that cannot change the bank.
                    let Ok(Json::Obj(mut fields)) = parse_json(&all) else { return None };
                    for (_, v) in fields.iter_mut() {
                        if let Json::Arr(tools) = v {
                            tools.retain(|t| !t.get("name").and_then(Json::as_str).is_some_and(|n| WRITE_TOOLS.contains(&n)));
                        }
                    }
                    json_out(&Json::Obj(fields))
                }
            },
            "tools/call" => {
                let p = msg.get("params");
                let name = p
                    .and_then(|p| p.get("name"))
                    .and_then(Json::as_str)
                    .unwrap_or("");
                let (text, picked, err) =
                    match if !allow_write && WRITE_TOOLS.contains(&name) {
                        Err(format!("{name} changes the bank and this server is read-only; restart `instinct serve` with --allow-write"))
                    } else if name == "instinct_check" {
                        check::mcp::call_wire(line)
                    } else {
                        mcp_call(cache, path, name, p.and_then(|p| p.get("arguments")))
                    } {
                        Ok((t, ids)) => (t, ids, false),
                        Err(e) => (e, Vec::new(), true),
                    };
                if name == "instinct_recall" && !err {
                    if let Some(meta) = recall_receipt(&picked, p.and_then(|p| p.get("arguments")))
                    {
                        if let Err(e) = receipt_stage(meta.clone(), "selected", &text) {
                            eprintln!("instinct telemetry: {e}");
                        }
                        delivery = Some((meta, text.clone()));
                    }
                }
                format!(
                    "{{\"content\":[{{\"type\":\"text\",\"text\":\"{}\"}}],\"isError\":{err}}}",
                    escape_json(&text)
                )
            }
            "ping" => "{}".into(),
            _ => {
                return Some((format!("{{\"jsonrpc\":\"2.0\",\"id\":{id_txt},\"error\":{{\"code\":-32601,\"message\":\"method not found\"}}}}"), None));
            }
        };
        Some((format!("{{\"jsonrpc\":\"2.0\",\"id\":{id_txt},\"result\":{result}}}"), delivery))
    }
}

fn mcp(path: &PathBuf) -> Result<(), String> {
    let mut cache = None;
    let stdin = std::io::stdin();
    let mut out = std::io::stdout();
    for line in stdin.lock().lines() {
        let line = line.map_err(|e| format!("stdin: {e}"))?;
        if line.trim().is_empty() {
            continue;
        }
        let Some((reply, delivery)) = mcp_message(&mut cache, path, &line, true) else { continue };
        writeln!(out, "{reply}").map_err(|e| format!("stdout: {e}"))?;
        out.flush().map_err(|e| format!("stdout flush: {e}"))?;
        if let Some((meta, text)) = delivery {
            if let Err(e) = receipt_stage(meta, "delivered", &text) {
                eprintln!("instinct telemetry: {e}");
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------- main

const USAGE: &str = "instinct: a local memory of what worked, for any AI agent

usage: instinct COMMAND [options]

deterministic checks
  check validate|run|explain --input FILE|-
                           evaluate a bounded predicate over supplied facts; no bank or action access
                           pass is not authorization; missing evidence abstains
  check observe --root ABS --input FILE|-
                           read-only staging inventory under an explicit caller trust assumption
  check attach --lesson ID --store BANK --input FILE|-
                           attach a read-only artifact policy; no hit is recorded
  hit ID --check --root ABS --trusted-staging --outcome-id KEY
                           record a hit only after the attached observed check passes

everyday
  bank --title T --when W --found F --how H --evidence E [--tags a,b] [--cases JSON|-]
  bank --from FILE|-|builtin:verify-handoff|builtin:zip-handoff [--project NAME]
                           save a lesson; write WHEN in the words a future question will use
  recall --q QUESTION [--k 5] [--facts JSON|-]
                           the lessons that fit (a lesson marked proven has paid off in use)
  probe --expect ID --q QUESTION [--k 5]
                           check the receiving scope; exit 0 only if the expected lesson is selected
  show ID [ID...]          the full lesson(s), as recall prints them
  hit ID [--note N] [--outcome-id KEY] [--case JSON|-]
                           a recalled lesson paid off; reuse KEY on a retry so one outcome counts once
  miss ID [--note N] [--outcome-id KEY] [--case JSON|-]
                           it did not
  instincts [--min-hits 2] the lessons that proved themselves
  stats [--since 7d|30d|all] [--json|--share]
  eval [--since 7d|30d|all] [--json] [--apply-quarantine] [--store PATH]
                           what the bank did for you: paid off, misled, never judged, never fired,
                           near-duplicates, savings, next three actions; reads only
  connect codex [--trust] | connect claude [--user]
                           wire the hooks: Codex hooks.json (--trust: trust only those), or the Claude Code
                           plugins at project scope (--user: every project)
  connect cursor|vscode|gemini|windsurf [--user] [--dry-run]
                           add the instinct MCP server to that harness's config (merges, backs up, idempotent)
  codex-trust [--check]                      trust the instinct hooks in Codex CLI (Codex skips untrusted hooks silently)
  doctor [--json] [--online] [--store PATH] [--fix]
  doctor --waits [--min-age MIN] [--fix]
  doctor --leftovers [--fix] [--min-age MIN] [--quiet]
                           stale waits, orphaned agent processes (headless browsers, sleep, tail -f /dev/null,
                           test binaries) and merged idle worktrees; --fix stops/removes only those
                           find wait loops (until/while + sleep, tail --pid, pgrep) whose result is in or that
                           match themselves; --fix stops them (your user only; Linux)
                           is Instinct wired up here: the bank, when each hook last ran, and each agent's
                           config (Claude Code, Codex, Gemini CLI, Cursor), with the next command for each;
                           --fix runs the repairs that only touch Instinct's own bank or hooks (starter
                           tripwires, connect claude/codex), is a no-op when nothing is needed, and only prints
                           anything that is another program's file (an older instinct earlier on PATH)
                           gap; reads only, never writes, exit 0
  audit [FILE...] [--share] [--json] [--k N]
                           grade memory files by tokens per prompt (A <= 400 ... F above 5000);
                           no FILE: every CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules and
                           .github/copilot-instructions.md in this folder
  mine [PATHS...] [--since 7d] [--project P] [--limit 10] [--apply] [--json]
                           find lesson candidates in past Claude Code and Codex sessions;
                           a dry run unless --apply. Mining finds candidates; you decide what to bank
  learn [PATHS...] [--days 30] [--project P] [--limit 10] [--apply] [--json]
                           propose tripwires (and fixes) from commands that failed and were retried
                           in a corrected form in your own transcripts; replay-scored; a dry run unless --apply
  scan [--days 30] [--json] [--share]
                           what your agent got wrong in the last 30 days and what Instinct would have caught;
                           reads your Claude Code and Codex transcripts, read-only, no bank needed
  starter [--apply] [--json] [--store PATH]
  fix --dry-run COMMAND
                           the community tripwire pack: lessons for classic agent disasters (rm -rf on
                           an unset variable, force pushes, DROP TABLE ...); a dry run unless --apply
  team init                share lessons through this repo: creates .instinct/ with a union-merge rule;
                           `bank --team` writes there, hits and misses on those lessons follow;
                           INSTINCT_TEAM=0 turns the project bank off
  sync pull --from PATH    append the events this bank lacks from another bank file (hxdb or jsonl);
                           a corrupt source stops the pull before any write; pulling twice adds nothing
  sync push --to PATH      the same, in the other direction
  sync status --with PATH  how many events each side lacks; read-only
  demo [SITUATION]         a short tour in a temporary bank
  skill [--guide]          print the agent skill

hooks and agents
  mcp                      MCP server on stdio
  serve [--port N] [--host H] [--allow-write] | serve --init-key
                           MCP over HTTP on 127.0.0.1 only (prototype); first run `serve --init-key`, see docs/serve.md
  prompt [--project P] [--format cline|text]
                           UserPromptSubmit hook: one fitting lesson per prompt
  guard [--project P] [--format text|json]
                           pre-tool hook: warns when a saved lesson fits the command
  timing                   PostToolUse hook: records how long each kind of Bash command takes (the class only,
                           never the command); INSTINCT_TIMING=0 turns it off
  speed [--json] [--limit N] | speed --import [--days 30]
                           where the time goes: slowest command classes, p50/p95, a faster route for each
  settle [--format claude|codex|text]
                           Stop hook: asks once per session for a hit or miss on a lesson it used
  track                    PostToolUse and PostToolUseFailure hook: records failed Bash commands (INSTINCT_RETRY=1)
  stop                     Stop hook: sends a done claim back once after a correction when nothing ran
                           since the last change (INSTINCT_DONE_GATE=1)
  outcomes [TRANSCRIPTS...] [--since 7d] [--apply] [--json]
                           what happened after each delivered lesson, read from the Claude Code or
                           Codex transcript: helped, misled, unused or unclear, with the evidence;
                           --apply records hits and misses (idempotent). INSTINCT_EXPLORE=0.1
                           withholds that share of deliveries so they can be compared

maintenance
  import FILE... [--project P] [--apply]
  export | migrate --to NEW.hxdb | reembed [--when]
  retract hit|miss ID | unsupersede ID | review ID --state quarantined --reason WHY --source-ref REF
  default ID --project P (--instruction TEXT --source-ref REF | --clear)
  guidebook                print the self-contained HTML field guide
  guide experiment --id ID [--pool JSON|-] [--facts JSON|-] [--after-ref REF]    choose a teaching case or inspect a conditional prediction
  guide [MODE]             explore ten decision workflows. Try guide list or guide challenge --example website
  dream --q USUAL --changed EXCEPTION | decide --q SITUATION [--facts JSON|-]
  bank scope options: --project P --persona P --applicability-harness H --applicability-version V
                      --applicability-machine M --reconsider R

store: $INSTINCT_STORE, else $XDG_DATA_HOME/instinct/bank.hxdb, else ~/.local/share/instinct/bank.hxdb
       (%LOCALAPPDATA%\\instinct\\bank.hxdb on Windows); --store PATH overrides for one call";

/// The lines of USAGE that describe `cmd`: every entry (two-space indent) whose first word is `cmd`, with its
/// continuation lines. None when USAGE has no such entry.
fn usage_for(cmd: &str) -> Option<String> {
    let mut out = String::new();
    let mut inside = false;
    for line in USAGE.lines() {
        let entry = line.starts_with("  ") && !line.starts_with("   ");
        if entry {
            inside = line.trim_start().split_whitespace().next() == Some(cmd);
        }
        if inside {
            out.push_str(line);
            out.push('\n');
        }
    }
    (!out.is_empty()).then(|| format!("usage: instinct {cmd} ...\n{}", out.trim_end()))
}

fn run(argv: &[String]) -> Result<(), String> {
    let cmd = argv.first().map(String::as_str).unwrap_or("");
    if matches!(cmd, "" | "--help" | "-h" | "help") {
        println!("{USAGE}");
        return Ok(());
    }
    if matches!(cmd, "--version" | "-V") {
        println!("instinct {}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }
    // `instinct doctor|codex-trust|connect --help` print that command's own usage (they used to fail or say nothing useful).
    if matches!(argv.get(1).map(String::as_str), Some("--help" | "-h")) && matches!(cmd, "doctor" | "codex-trust" | "connect") {
        if let Some(u) = usage_for(cmd) {
            println!("{u}");
            return Ok(());
        }
    }
    if cmd == "continue-tasks" {
        return continuation::cli(&argv[1..]);
    }
    if cmd == "skill" {
        let content = match &argv[1..] {
            [] => include_str!("../skills/instinct/SKILL.md"),
            [arg] if arg == "--guide" => {
                include_str!("../skills/instinct/references/architecture.md")
            }
            _ => return Err("usage: instinct skill [--guide]".into()),
        };
        print!("{content}");
        return Ok(());
    }
    if cmd == "guidebook" {
        if argv.len() != 1 {
            return Err("usage: instinct guidebook > instinct-guidebook.html".into());
        }
        println!("{}", guide::book()?);
        return Ok(());
    }
    if cmd == "demo" {
        if argv.len() > 2 {
            return Err("usage: instinct demo [quoted situation]".into());
        }
        return demo::run(argv.get(1).map(String::as_str));
    }
    if cmd == "learn" {
        return learn::run(&argv[1..]);
    }
    if cmd == "connect" {
        return connect::run(&argv[1..]);
    }
    if cmd == "codex-trust" {
        return codex_trust::run(&argv[1..]);
    }
    if cmd == "doctor" {
        return doctor::run(&argv[1..]);
    }
    if cmd == "audit" {
        return audit::run_audit(&argv[1..]);
    }
    if cmd == "import" {
        return audit::run_import(&argv[1..]);
    }
    if cmd == "team" {
        return match argv.get(1).map(String::as_str) {
            Some("init") if argv.len() == 2 => {
                let here = std::env::current_dir().map_err(|e| format!("no working folder: {e}"))?;
                println!("{}", team::init(&here)?);
                Ok(())
            }
            _ => Err("usage: instinct team init".into()),
        };
    }
    if cmd == "fix" {
        return fix::run(&argv[1..]);
    }
    if cmd == "starter" {
        return starter::run(&argv[1..]);
    }
    if cmd == "scan" {
        return scan::run(&argv[1..]);
    }
    if cmd == "gates-trace" {
        gates::trace(&argv[1..]);
        return Ok(());
    }
    if cmd == "mine" {
        return mine::run(&argv[1..]);
    }
    const STORE_CMDS: &[&str] = &[
        "migrate", "export", "bank", "default", "dream", "decide", "guide", "prompt", "recall", "probe", "show", "review", "hit", "miss",
        "instincts", "stats", "eval", "reembed", "unsupersede", "retract", "mcp", "serve", "guard", "settle", "track", "stop", "outcomes", "timing", "speed", "sync",
    ];
    if !STORE_CMDS.contains(&cmd) {
        return Err(format!("unknown command {cmd}\n\n{USAGE}"));
    }
    // These run once and exit: the lessons read for the lookup are not worth freeing one by one.
    if matches!(cmd, "prompt" | "guard" | "recall" | "show" | "timing") {
        ONE_SHOT.store(true, std::sync::atomic::Ordering::Relaxed);
    }
    if cmd != "guard" && matches!(argv.get(1).map(String::as_str), Some("--help" | "-h")) {
        println!("{USAGE}");
        return Ok(());
    }
    let a = Args::parse(argv.get(1..).unwrap_or(&[]));
    if cmd == "guard" {
        guard::run(&a);
        return Ok(());
    }
    if cmd == "track" {
        gates::track(&a);
        return Ok(());
    }
    if cmd == "stop" {
        gates::stop(&a);
        return Ok(());
    }
    if cmd == "timing" {
        speed::run_post(&a);
        return Ok(());
    }
    if cmd == "speed" {
        speed::run(&a);
        return Ok(());
    }
    if cmd == "settle" {
        session::settle(&a);
        return Ok(());
    }
    for (key, env) in [
        ("project", "INSTINCT_PROJECT"),
        ("persona", "INSTINCT_PERSONA"),
        ("harness", "INSTINCT_HARNESS"),
        ("harness-version", "INSTINCT_HARNESS_VERSION"),
        ("machine", "INSTINCT_MACHINE"),
    ] {
        if let Some(v) = a.opt(key) {
            std::env::set_var(env, v);
        }
    }
    let mut stdin_used = false;
    if cmd == "guide" {
        if a.pos.len() > 1 {
            return Err("supply one guide mode. Use guide list".into());
        }
        if a.pos.first().is_some_and(|mode| mode == "experiment") {
            let mut seen = HashSet::new();
            for (key, value) in &a.kv {
                let allowed = matches!(key.as_str(), "id" | "facts" | "pool" | "after-ref" | "json"
                    | "store" | "project" | "persona" | "machine" | "harness" | "harness-version");
                if !allowed || !seen.insert(key) || (key == "json") != value.is_empty() {
                    return Err(format!("invalid or repeated guide experiment option --{key}"));
                }
            }
        }
        let mut fields = vec![("mode".into(), Json::Str(a.pos.first().cloned().unwrap_or_default()))];
        for key in ["q", "example", "steps", "changed", "expected", "observed", "correction", "method", "test", "prediction", "exception", "id"] {
            if a.flag(key) {
                if a.opt(key) == Some("-") && stdin_used {
                    return Err("only one guide input can come from stdin".into());
                }
                fields.push((key.into(), Json::Str(a.text(key, &mut stdin_used)?)));
            }
        }
        if a.flag("after-ref") {
            fields.push(("after_ref".into(), Json::Str(a.text("after-ref", &mut stdin_used)?)));
        }
        for key in ["facts", "pool"] {
            if let Some(value) = a.optional_json(key, &mut stdin_used)? {
                fields.push((key.into(), value));
            }
        }
        let result = guide::run(|| store_path(&a), &Json::Obj(fields), &eligibility::env_scope())?;
        println!("{}", if a.flag("json") {json_out(&result)} else {guide::display(&result)});
        return Ok(());
    }
    // The store is resolved only now, for commands that read or write it.
    let path = store_path(&a)?;
    if a.opt("store").is_none() && std::env::var_os("INSTINCT_STORE").map_or(true, |v| v.is_empty()) {
        ensure_default_dir(&path)?;
    }
    let out = match cmd {
        "migrate" => {
            if !path.is_file() {
                return Err("source bank does not exist".into());
            }
            let dest = PathBuf::from(a.opt("to").ok_or("supply --to NEW.hxdb")?);
            let snapshot = journal::read(&path)?;
            let count = helix_db::import(&dest, &snapshot)?;
            format!("migrated {count} events to {}", dest.display())
        }
        "export" => {
            if !path.is_file() {
                return Err("source bank does not exist".into());
            }
            let snapshot = journal::read(&path)?;
            for line in snapshot.lines().filter(|s| !s.trim().is_empty()) {
                parse_json(line)?;
            }
            print!("{snapshot}");
            return Ok(());
        }
        "bank" if a.opt("from").is_some() => bank_from(&path, &a, a.opt("from").unwrap())?,
        "bank" => {
            if a.flag("cases") && a.flag("team") {
                return Err("bank case evidence in a personal bank with the project's scope".into());
            }
            let cases = a.optional_json("cases", &mut stdin_used)?.as_ref().map(case_learning::Casebook::parse).transpose()?;
            let bank = if a.flag("team") { team_bank_path(&path)? } else { path.clone() };
            let lesson = BankIn {
                title: a.text("title", &mut stdin_used)?,
                when: a.text("when", &mut stdin_used)?,
                found: a.text("found", &mut stdin_used)?,
                how: a.text("how", &mut stdin_used)?,
                evidence: a.text("evidence", &mut stdin_used)?,
                reconsider: a.text("reconsider", &mut stdin_used)?,
                tags: a.text("tags", &mut stdin_used)?,
                project: a.text("project", &mut stdin_used)?,
                persona: a.text("persona", &mut stdin_used)?,
                applicability_harness: a.text("applicability-harness", &mut stdin_used)?,
                applicability_version: a.text("applicability-version", &mut stdin_used)?,
                applicability_machine: a.opt("applicability-machine").map(str::to_owned),
            };
            op_bank_cases(&bank, lesson, cases, &eligibility::env_scope())?
        }
        "default" => rehearsal::set_default(&path, &a, &eligibility::env_scope())?,
        "dream" => rehearsal::dream(
            &path,
            &a.text("q", &mut stdin_used)?,
            &a.text("changed", &mut stdin_used)?,
            &eligibility::env_scope(),
        )?,
        "decide" => decision_context(
            &path,
            &a.text("q", &mut stdin_used)?,
            &eligibility::env_scope(),
            a.optional_json("facts", &mut stdin_used)?.as_ref(),
        )?,
        "prompt" => {
            let mut input = String::new();
            std::io::stdin()
                .read_to_string(&mut input)
                .map_err(|e| e.to_string())?;
            let event = parse_json(&input)?;
            let format = a.opt("format");
            let cline = format == Some("cline") || event.get("userPromptSubmit").is_some();
            let cline_json = cline && format != Some("text");
            let (query, cwd, sid) = if cline {
                let query = event.get("userPromptSubmit").and_then(|p| p.get("prompt")).and_then(Json::as_str);
                let is_submit = event.get("hookName").is_none_or(|name| name.as_str() == Some("UserPromptSubmit"));
                let (Some(query), Ok(root), true) = (query.filter(|q| !q.trim().is_empty()), cline_workspace(&event), is_submit) else {
                    if cline_json {
                        println!("{}", cline_reply(""));
                    }
                    return Ok(());
                };
                if root.is_none() {
                    // Without a workspace, the launcher's cwd cannot identify a team bank.
                    std::env::set_var("INSTINCT_TEAM", "0");
                }
                let task = event.get("taskId").and_then(Json::as_str).and_then(session::clean);
                (query, root, task.and_then(|id| session::clean(&format!("cline:{id}"))))
            } else {
                let query = event.get("prompt").and_then(Json::as_str).unwrap_or("");
                let cwd = event.get("cwd").and_then(Json::as_str);
                let sid = event.get("session_id").and_then(Json::as_str).and_then(session::clean);
                (query, cwd, sid)
            };
            team::set_cwd(cwd);
            let mut scope = eligibility::prompt_scope(a.opt("project"), cwd);
            if cline {
                scope.harness = "cline".into();
                scope.version = event.get("clineVersion").and_then(Json::as_str).unwrap_or("").into();
            }
            // First run: a bank that does not exist yet gets the starter tripwires before this call is answered.
            let explicit = a.opt("store").is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
            let seeded = starter::seed_first_run(&path, explicit);
            let mut text = recall_once_per_session(&path, "prompt", query, &scope, sid.as_deref())?.0;
            // Opt-in lesson index: the first prompt of a session also carries the compact list.
            if index_wanted(&a) {
                if let Some(s) = sid.as_deref() {
                    if session::claim_index(&path, s) {
                        let block = index_block(&path, &scope)?;
                        if !block.is_empty() {
                            text = if text.trim().is_empty() { block } else { format!("{block}\n\n{text}") };
                        }
                    }
                }
            }
            if cline_json {
                println!("{}", cline_reply(&text));
                return Ok(());
            }
            match seeded {
                None => text,
                Some(n) => {
                    // The seeding call only: Claude Code JSON carries the notice for the user as `systemMessage`
                    // and the lesson as context; `--format text` prints the notice as one plain line first.
                    let notice = starter::first_run_notice(n);
                    if a.opt("format") == Some("text") {
                        if text.trim().is_empty() { notice } else { format!("{notice}\n{text}") }
                    } else if text.trim().is_empty() {
                        format!("{{\"systemMessage\":\"{}\"}}", escape_json(&notice))
                    } else {
                        format!(
                            "{{\"systemMessage\":\"{}\",\"hookSpecificOutput\":{{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"{}\"}}}}",
                            escape_json(&notice),
                            escape_json(&text)
                        )
                    }
                }
            }
        }
        "outcomes" => outcomes::run(&path, &a)?,
        "sync" => op_sync(&path, &a)?,
        "show" => op_show(&path, &a.pos)?,
        "probe" => probe_recall(&path, &a, &a.text("q", &mut stdin_used)?)?,
        "recall" => meter::recall_text(&path, "recall", &a.text("q", &mut stdin_used)?, a.num("k", 5), &eligibility::env_scope(), a.optional_json("facts", &mut stdin_used)?.as_ref())?,
        "review" => op_review(
            &path,
            a.pos.first().ok_or("review ID required")?,
            a.opt("state").unwrap_or(""),
            a.opt("reason").unwrap_or(""),
            a.opt("source-ref").unwrap_or(""),
        )?,
        "hit" | "miss" if a.flag("case") => {
            if a.pos.len()!=1 || ["check","trusted-staging","root","team"].iter().any(|k| a.flag(k)) {
                return Err("case feedback needs one personal lesson ID and a directly observed outcome".into());
            }
            let observation = a.optional_json("case", &mut stdin_used)?.ok_or("missing --case JSON")?;
            op_mark_case(&path,cmd,&a.pos[0],a.opt("note").unwrap_or(""),a.opt("outcome-id").unwrap_or(""),
                &observation,&eligibility::env_scope())?
        },
        "hit" | "miss" if a.flag("check") => {
            if cmd != "hit" { return Err("miss --check is not supported; nothing recorded".into()); }
            let mut seen = HashSet::new();
            for (key, value) in &a.kv {
                if !["check", "trusted-staging", "root", "outcome-id", "note", "store", "project", "persona", "harness", "harness-version", "machine"].contains(&key.as_str()) || !seen.insert(key) {
                    return Err("unknown or repeated checked-feedback option; nothing recorded".into());
                }
                if matches!(key.as_str(), "check" | "trusted-staging") && !value.is_empty() {
                    return Err("--check and --trusted-staging are bare flags, not boolean values; nothing recorded".into());
                }
            }
            if a.pos.len() != 1 { return Err("checked feedback requires exactly one lesson ID".into()); }
            refuse_team_check(&path, a.pos.first().ok_or("hit ID required")?)?;
            check::feedback::hit(&path, a.pos.first().ok_or("hit ID required")?, a.opt("note").unwrap_or(""), a.opt("outcome-id").unwrap_or(""), a.opt("root").unwrap_or(""), a.flag("trusted-staging"))?
        },
        "hit" | "miss" => op_mark(
            &path,
            cmd,
            a.pos.first().ok_or("usage: hit|miss ID [--note N] [--outcome-id KEY]")?,
            a.opt("note").unwrap_or(""),
            a.opt("outcome-id").unwrap_or(""),
        )?,
        "instincts" => op_instincts(&path, a.num("min-hits", 2) as u32)?,
        "stats" => op_stats(&path, &a)?,
        "eval" => eval::run(&path, &a)?,
        "reembed" => {
            if a.flag("when") {
                op_reembed_when(&path)?
            } else {
                op_reembed(&path)?
            }
        }
        "unsupersede" => {
            let id = a.pos.first().ok_or("usage: unsupersede ID [--note N]")?;
            append(
                &path,
                &format!(
                    "{{\"kind\":\"unsupersede\",\"id\":\"{}\",\"ts\":{},\"note\":\"{}\"}}",
                    escape_json(id),
                    now_secs(),
                    escape_json(a.opt("note").unwrap_or(""))
                ),
            )?;
            format!("unsuperseded {id} (back in recall)")
        }
        "retract" => {
            let of = a.pos.first().map(String::as_str).unwrap_or("");
            let id = a
                .pos
                .get(1)
                .ok_or("usage: retract hit|miss ID [--note N]")?;
            if of != "hit" && of != "miss" {
                return Err("usage: retract hit|miss ID [--note N]".into());
            }
            append(&path, &format!("{{\"kind\":\"retract\",\"of\":\"{of}\",\"id\":\"{}\",\"ts\":{},\"note\":\"{}\"}}", escape_json(id), now_secs(), escape_json(a.opt("note").unwrap_or(""))))?;
            format!("retracted one {of} on {id}")
        }
        "mcp" => return mcp(&path),
        #[cfg(not(target_arch = "wasm32"))]
        "serve" => return serve::run(&a, &path),
        _ => return Err(USAGE.into()),
    };
    if !out.is_empty() {
        println!("{out}");
    }
    Ok(())
}

fn main() {
    let argv: Vec<String> = std::env::args().skip(1).collect();
    // Check operations are opt-in; attach is an explicit bank-sidecar mutation.
    if argv.first().map(String::as_str) == Some("check") {
        process::exit(check::cli(&argv[1..]));
    }
    if let Err(e) = run(&argv) {
        eprintln!("instinct: {e}");
        // `prompt` runs as a UserPromptSubmit hook. Claude Code reads exit 2 as "block and erase the
        // prompt", so a missing store, a bad payload or a damaged bank must never cost the user their
        // message: drain the payload and exit 0, leaving the note above on stderr.
        if argv.first().map(String::as_str) == Some("prompt") {
            let _ = std::io::copy(&mut std::io::stdin().take(1 << 20), &mut std::io::sink());
            if Args::parse(&argv[1..]).opt("format") == Some("cline") {
                println!("{}", cline_reply(""));
            }
            process::exit(0);
        }
        process::exit(2);
    }
}

/// Browser playground surface: the real banking, BM25 + RRF ranking, eligibility and quiet rules over an
/// in-memory bank. Compiled only for wasm32, so native builds do not contain it. One JSON request in,
/// one JSON reply out; `playground/` wraps `handle` in raw `extern "C"` exports.
#[cfg(target_arch = "wasm32")]
pub mod playground_api {
    use super::*;
    use std::cell::RefCell;
    use std::sync::atomic::{AtomicU64, Ordering};

    static CLOCK: AtomicU64 = AtomicU64::new(0);
    thread_local! { static BANK: RefCell<Vec<Discovery>> = const { RefCell::new(Vec::new()) }; }

    pub fn clock() -> u64 {
        CLOCK.load(Ordering::Relaxed)
    }

    fn view(d: &Discovery) -> Json {
        let s = |t: &str| Json::Str(t.to_string());
        Json::Obj(vec![
            ("id".into(), s(&d.id)),
            ("title".into(), s(&d.title)),
            ("when".into(), s(&d.when)),
            ("found".into(), s(&d.found)),
            ("how".into(), s(&d.how)),
            ("evidence".into(), s(&d.evidence)),
            ("reconsider".into(), s(&d.reconsider)),
            // Byte length of the full lesson an agent receives from `instinct recall`.
            ("rendered".into(), Json::Num(render_entry(d).len() as f64)),
            ("hits".into(), Json::Num(d.hits.into())),
            ("misses".into(), Json::Num(d.misses.into())),
            ("strength".into(), Json::Num(d.strength().into())),
            (
                "quiet".into(),
                Json::Bool(eligibility::quiet(d.hits, d.misses)),
            ),
        ])
    }

    fn run(req: &Json) -> Result<Json, String> {
        let f = |k: &str| req.get(k).and_then(Json::as_str).unwrap_or("").to_string();
        let scope = eligibility::Scope::default();
        match f("op").as_str() {
            "clock" => {
                CLOCK.store(req.get("now").and_then(Json::as_f64).unwrap_or(0.0) as u64, Ordering::Relaxed);
                Ok(Json::Null)
            }
            "reset" => {
                BANK.with(|b| b.borrow_mut().clear());
                Ok(Json::Null)
            }
            "bank" => {
                let d = bank_discovery(
                    BankIn {
                        title: f("title"),
                        when: f("when"),
                        found: f("found"),
                        how: f("how"),
                        evidence: f("evidence"),
                        reconsider: f("reconsider"),
                        tags: f("tags"),
                        project: String::new(),
                        persona: String::new(),
                        applicability_harness: String::new(),
                        applicability_version: String::new(),
                        applicability_machine: None,
                    },
                    &scope,
                )?;
                let note = bank_scope_note(&d.meta);
                let id = d.id.clone();
                let fresh = BANK.with(|b| {
                    let mut b = b.borrow_mut();
                    if b.iter().any(|x| x.id == id) {
                        false
                    } else {
                        b.push(d);
                        true
                    }
                });
                Ok(Json::Obj(vec![
                    ("id".into(), Json::Str(id)),
                    ("new".into(), Json::Bool(fresh)),
                    ("note".into(), Json::Str(note)),
                ]))
            }
            "recall" => {
                let q = f("q");
                let k = req.get("k").and_then(Json::as_f64).unwrap_or(1.0) as usize;
                let now = now_secs();
                let all: Vec<Discovery> = BANK.with(|b| {
                    b.borrow()
                        .iter()
                        .filter(|d| eligibility::scope_check(&d.meta, &scope, now).is_ok())
                        .cloned()
                        .collect()
                });
                let picked = rank_methods(&PathBuf::new(), &q, k, &scope, &all, |action| {
                    score_discoveries(action, &all)
                })?;
                Ok(Json::Arr(picked.iter().map(view).collect()))
            }
            kind @ ("hit" | "miss") => {
                let id = f("id");
                BANK.with(|b| {
                    let mut b = b.borrow_mut();
                    let d = b
                        .iter_mut()
                        .find(|d| d.id == id)
                        .ok_or_else(|| format!("no discovery with id {id}"))?;
                    if kind == "hit" {
                        d.hits += 1;
                    } else {
                        d.misses += 1;
                    }
                    Ok(view(d))
                })
            }
            "list" => Ok(BANK.with(|b| Json::Arr(b.borrow().iter().map(view).collect()))),
            other => Err(format!("unknown op {other:?}")),
        }
    }

    /// `request` is one JSON object with an `op`; the reply is `{"ok":...}` or `{"error":"..."}`.
    pub fn handle(request: &str) -> String {
        let out = parse_json(request).and_then(|req| run(&req));
        json_out(&match out {
            Ok(v) => Json::Obj(vec![("ok".into(), v)]),
            Err(e) => Json::Obj(vec![("error".into(), Json::Str(e))]),
        })
    }
}

#[cfg(test)]
mod fold_tests {
    use super::*;

    #[test]
    fn word_forms_share_a_key() {
        for (a, b) in [
            ("tests", "test"),
            ("testing", "test"),
            ("tested", "test"),
            ("running", "runs"),
            ("failing", "fails"),
            ("failed", "fail"),
            ("queries", "query"),
            ("fixes", "fix"),
            ("passes", "pass"),
            ("stopped", "stop"),
            ("warnings", "warning"),
            ("settings", "setting"),
            ("updated", "update"),
            ("updates", "updating"),
            ("cached", "cache"),
            ("merging", "merge"),
            ("writing", "write"),
            ("issues", "issue"),
        ] {
            assert_eq!(fold_word(a), fold_word(b), "{a} vs {b}");
        }
    }

    #[test]
    fn short_words_stay_and_latin_accents_normalize() {
        for w in ["status", "class", "bonus", "analysis", "string", "проект", "日本語"] {
            assert_eq!(fold_word(w), w, "{w}");
        }
        assert_eq!(fold_word("zażółć"), "zazolc");
    }

    #[test]
    fn inflected_question_reaches_the_when_line() {
        let when = anchors("Running the test suite in this repo");
        let cues = anchors("how do I run the tests in this repo?");
        assert!(when.intersection(&cues).count() >= 2, "{when:?} vs {cues:?}");
    }
}

#[cfg(test)]
mod keyword_support_tests {
    use super::*;

    #[test]
    fn floors_follow_bank_size_and_small_banks_are_exempt() {
        assert_eq!(lex_floors(10), (0.0, 0.0));
        let (hi80, lo80) = lex_floors(80);
        assert!((16.5..17.5).contains(&hi80) && (13.5..14.5).contains(&lo80));
        assert!(lex_floors(2000).0 > hi80);
    }

    #[test]
    fn weak_scores_are_silent_unless_a_clear_winner() {
        let floors = (17.0, 14.0);
        let weak = |lex: &[f32], i: usize, f| weak_keyword_support(lex[i], top_two(lex), f);
        assert!(!weak(&[20.0, 19.0], 0, floors)); // strong
        assert!(weak(&[10.0, 0.0], 0, floors)); // below both floors
        assert!(weak(&[15.0, 14.0], 0, floors)); // middle score, no clear winner
        assert!(weak(&[14.0, 15.0], 0, floors)); // not even the best
        assert!(!weak(&[15.0, 9.0], 0, floors)); // middle score, 1.5x the next
        assert!(!weak(&[3.0], 0, (0.0, 0.0))); // floors off
        assert_eq!(top_two(&[5.0, 5.0, 2.0]), (5.0, 5.0));
    }
}

#[cfg(test)]
mod reliable_tests {
    use super::*;
    fn bank_input() -> BankIn {
        BankIn {
            title: "fixture discovery".into(),
            when: "fixture condition".into(),
            found: "fixture result".into(),
            how: "fixture measurement".into(),
            reconsider: String::new(),
            evidence: "verified! (caller text, not a verification grant)".into(),
            tags: String::new(),
            project: String::new(),
            persona: String::new(),
            applicability_harness: String::new(),
            applicability_version: String::new(),
            applicability_machine: None,
        }
    }
    fn fixture() -> PathBuf {
        let p = std::env::temp_dir().join(format!(
            "instinct-bank-test-{}-{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir_all(&p).unwrap();
        p.join("bank.jsonl")
    }

    fn observed_case(reference: &str, value: bool, action: &str) -> case_learning::Casebook {
        let text = format!(r#"{{"checks":[{{"key":"ready","question":"Is it ready?","cost":1}}],"examples":[{{"ref":"{reference}","facts":{{"ready":{value}}},"action":"{action}"}}]}}"#);
        case_learning::Casebook::parse(&parse_json(&text).unwrap()).unwrap()
    }

    #[test]
    fn casebook_sync_keeps_counterexamples_and_rejects_conflicts_before_writing() {
        let root = fixture();
        let scope = eligibility::Scope::default();
        let left = root.with_extension("hxdb");
        let right = root.with_file_name("other.jsonl");
        let conflict = root.with_file_name("conflict.jsonl");
        let a = observed_case("positive", true, "use");
        let b = observed_case("counter", false, "wait");
        let changed = observed_case("positive", true, "wait");
        for (path, cases) in [(&left, &a), (&right, &b), (&conflict, &changed)] {
            op_bank_cases(path, bank_input(), Some(cases.clone()), &scope).unwrap();
        }
        sync::pull(&left, &right).unwrap();
        sync::pull(&right, &left).unwrap();
        let merged = a.merge(&b).unwrap();
        for path in [&left, &right] {
            let d = load(path).unwrap().pop().unwrap();
            assert_eq!(d.casebook.as_ref(), Some(&merged));
            assert_eq!((d.hits, d.misses), (0, 0));
            assert_eq!(d.meta.source, "banked");
            assert_eq!(d.meta.evidence_status, "unverified");
            let key = snapshot::key(path).unwrap();
            let (cached, _, _) = snapshot::open(path, &key, &scope, now_secs()).unwrap();
            assert_eq!(cached[0].casebook.as_ref(), Some(&merged));
            let held = fs::read(path).unwrap();
            op_bank_cases(path, bank_input(), Some(a.clone()), &scope).unwrap();
            assert!(op_bank_cases(path, bank_input(), Some(changed.clone()), &scope).is_err());
            assert!(sync::pull(path, &conflict).is_err());
            assert_eq!(fs::read(path).unwrap(), held);
        }
        assert_eq!(sync::status(&left, &right).unwrap(), (0, 0, 0));
        fs::remove_dir_all(root.parent().unwrap()).unwrap();
    }

    #[test]
    fn casebook_feedback_validates_both_rows_and_retries_partial_outcomes() {
        let path = fixture();
        let scope = eligibility::Scope { project: "handoff".into(), ..Default::default() };
        let seed = observed_case("starter", true, "use");
        op_bank_cases(&path, bank_input(), Some(seed), &scope).unwrap();
        let id = load_plain(&path).unwrap().pop().unwrap().id;
        let observation = parse_json(r#"{"facts":{"ready":false},"action":"inspect"}"#).unwrap();
        let mark = |kind, key, obs: &Json| op_mark_case(&path, kind, &id, "", key, obs, &scope);
        assert!(op_mark_case(&path, "miss", &id, "", "wrong-scope", &observation, &Default::default()).is_err());
        mark("miss", "actual", &observation).unwrap();
        let held = fs::read(&path).unwrap();
        mark("miss", "actual", &observation).unwrap();
        assert!(mark("hit", "actual", &observation).is_err());
        assert!(mark("miss", "actual", &parse_json(r#"{"facts":{"ready":true},"action":"inspect"}"#).unwrap()).is_err());
        assert!(mark("hit", "missing-fact", &parse_json(r#"{"facts":{},"action":"inspect"}"#).unwrap()).is_err());
        assert_eq!(fs::read(&path).unwrap(), held);

        op_mark(&path, "hit", &id, "", "mark-only").unwrap();
        mark("hit", "mark-only", &observation).unwrap();
        op_bank_cases(&path, bank_input(), Some(observed_case("case-only", false, "inspect")), &scope).unwrap();
        mark("hit", "case-only", &observation).unwrap();
        let d = load_plain(&path).unwrap().pop().unwrap();
        assert_eq!((d.hits, d.misses), (2, 1));
        let book = d.casebook.as_ref().unwrap();
        for key in ["case-only", "mark-only", "actual"] {
            assert_eq!(book.merge(&observed_case(key, false, "inspect")).unwrap(), *book);
        }
        let peer = path.with_extension("hxdb");
        sync::pull(&peer, &path).unwrap();
        let held = fs::read(&peer).unwrap();
        op_mark_case(&peer, "miss", &id, "", "actual", &observation, &scope).unwrap();
        assert_eq!(fs::read(&peer).unwrap(), held);
        let imported = load_plain(&peer).unwrap().pop().unwrap();
        assert_eq!((imported.hits, imported.misses, imported.casebook), (2, 1, d.casebook));
        let opposite = path.with_file_name("opposite.jsonl");
        op_bank_in(&opposite, bank_input(), "banked", &scope).unwrap();
        op_mark(&opposite, "hit", &id, "", "actual").unwrap();
        let held = fs::read(&opposite).unwrap();
        assert!(sync::pull(&opposite, &path).is_err());
        assert_eq!(fs::read(&opposite).unwrap(), held);
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn casebook_concurrent_writers_preserve_scope_fields_and_inactive_history() {
        let path = fixture();
        let scope = eligibility::Scope::default();
        let a = observed_case("one", true, "use");
        let b = observed_case("two", false, "wait");
        let barrier = std::sync::Barrier::new(2);
        std::thread::scope(|s| {
            for add in [&a, &b] {
                s.spawn(|| {
                    barrier.wait();
                    op_bank_cases(&path, bank_input(), Some(add.clone()), &scope).unwrap();
                });
            }
        });
        let d = load_plain(&path).unwrap().pop().unwrap();
        assert_eq!(d.casebook.as_ref(), Some(&a.merge(&b).unwrap()));
        assert_eq!(journal::read(&path).unwrap().lines().count(), 3);
        let other_scope = eligibility::Scope { persona: "second".into(), ..scope.clone() };
        op_bank_cases(&path, bank_input(), Some(b.clone()), &other_scope).unwrap();
        let mut other = load_plain(&path).unwrap();
        assert_eq!(other.len(), 2);
        assert_eq!(other.pop().unwrap().casebook, Some(b.clone()));
        let mut altered = bank_input();
        altered.how = "unrelated method".into();
        assert!(op_bank_cases(&path, altered, Some(a.clone()), &scope).is_err());
        for (kind, undo) in [("retire", "unretire"), ("supersede", "unsupersede")] {
            append(&path, &format!(r#"{{"kind":"{kind}","id":"{}"}}"#, d.id)).unwrap();
            assert!(op_bank_cases(&path, bank_input(), Some(a.clone()), &scope).is_err());
            append(&path, &format!(r#"{{"kind":"{undo}","id":"{}"}}"#, d.id)).unwrap();
        }
        op_review(&path, &d.id, "quarantined", "under review", "ref").unwrap();
        assert!(op_bank_cases(&path, bank_input(), Some(a.clone()), &scope).is_err());
        let peer = path.with_file_name("peer.jsonl");
        let c = observed_case("from-peer", false, "inspect");
        op_bank_cases(&peer, bank_input(), Some(c.clone()), &scope).unwrap();
        sync::pull(&path, &peer).unwrap();
        assert!(load_plain(&path).unwrap()[0].casebook.is_none());
        op_review(&path, &d.id, "candidate", "review ended", "ref").unwrap();
        assert_eq!(load_plain(&path).unwrap()[0].casebook, Some(d.casebook.unwrap().merge(&c).unwrap()));
        let mined = path.with_file_name("mined.jsonl");
        op_bank_in(&mined, bank_input(), "mined", &scope).unwrap();
        assert!(op_bank_cases(&mined, bank_input(), Some(a.clone()), &scope).is_err());
        let shared = path.parent().unwrap().join(team::DIR).join(team::FILE);
        assert!(op_bank_cases(&shared, bank_input(), Some(a), &scope).is_err());
        assert!(sync::pull(&shared, &path).is_err());
        assert!(!shared.exists());
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }
    #[test]
    fn consolidated_counts_match_reverse_reachability_on_every_four_lesson_graph() {
        // Four possible targets or no edge for each member: 5^4 graphs, including cycles.
        const N: usize = 4;
        let p = fixture();
        let mut rows = Vec::new();
        let mut expected = HashMap::new();
        for graph in 0..(N + 1).pow(N as u32) {
            let id = |i| format!("g{graph}-{i}");
            let edges: [usize; N] = std::array::from_fn(|i| graph / (N + 1).pow(i as u32) % (N + 1));
            for (i, &target) in edges.iter().enumerate() {
                let member = id(i);
                rows.push(format!(r#"{{"kind":"discovery","id":"{member}"}}"#));
                rows.push(format!(r#"{{"kind":"hit","id":"{member}"}}"#));
                let (verdict, key) = match i {
                    0 | 1 => ("hit", "shared"),
                    2 => ("miss", "other"),
                    _ => ("hit", "other"),
                };
                rows.push(format!(r#"{{"kind":"{verdict}","id":"{member}","outcome_id":"{key}"}}"#));
                if target != N {
                    rows.push(format!(r#"{{"kind":"supersede","id":"{member}","by":"{}"}}"#, id(target)));
                }
            }

            // Independent oracle: expand a set backwards from each visible root.
            for root in (0..N).filter(|i| edges[*i] == N) {
                let mut family = HashSet::from([root]);
                for _ in 0..N {
                    for (member, to) in edges.iter().enumerate() {
                        if family.contains(to) {
                            family.insert(member);
                        }
                    }
                }
                let shared = family.contains(&0) || family.contains(&1);
                let yes = family.contains(&3);
                let no = family.contains(&2);
                let hits = family.len() as u32 + u32::from(shared) + u32::from(yes && !no);
                expected.insert(id(root), (hits, u32::from(no && !yes)));
            }
        }
        fs::write(&p, rows.join("\n")).unwrap();
        let actual: HashMap<_, _> = load_plain(&p).unwrap().into_iter()
            .map(|entry| (entry.id, (entry.hits, entry.misses))).collect();
        fs::remove_dir_all(p.parent().unwrap()).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn render_len_matches_the_rendered_bytes() {
        let p = fixture();
        let mut with_everything = bank_input();
        with_everything.title = "čas \"quoted\" ünïcode".into();
        with_everything.tags = "a,b".into();
        with_everything.reconsider = "if it changes".into();
        with_everything.applicability_machine = Some("box-1".into());
        with_everything.when = "fixture condition two".into();
        op_bank(&p, bank_input()).unwrap();
        op_bank(&p, with_everything).unwrap();
        let all = load(&p).unwrap();
        for d in &all {
            op_mark(&p, "hit", &d.id, "", "").unwrap();
        }
        op_mark(&p, "miss", &all[0].id, "", "").unwrap();
        for _ in 0..11 {
            op_mark(&p, "hit", &all[1].id, "", "").unwrap();
        }
        let all = load(&p).unwrap();
        assert_eq!(all.len(), 2);
        for d in &all {
            assert_eq!(render_len(d), render_entry(d).len(), "{}", render_entry(d));
        }
        assert!(all.iter().any(|d| d.hits >= 10), "two-digit hit counts covered");
        assert!(
            all.iter().any(|d| render_entry(d).contains("proven in use"))
                && all.iter().any(|d| !render_entry(d).contains("proven in use")),
            "both the proven and the unproven validity line are covered"
        );
    }
    #[test]
    fn lexical_score_preserves_lengths_case_and_repeated_terms() {
        let documents = vec!["Čas CLOCK clock".into(), "čas other".into(), "a".into()];
        let scores = bm25("CLOCK čas clock", &documents);
        let weight = |df: f32| ((3.0 - df + 0.5) / (df + 0.5) + 1.0).ln();
        let term = |df: f32, tf: f32, len: f32| {
            weight(df) * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * len / (5.0 / 3.0)))
        };
        assert_eq!(
            scores,
            vec![
                term(1.0, 2.0, 3.0) + term(2.0, 1.0, 3.0),
                term(2.0, 1.0, 2.0),
                0.0
            ]
        );
        assert_eq!(bm25("", &documents), vec![0.0; 3]);
    }

    #[test]
    fn decision_context_transfers_a_method_with_its_boundary() {
        let path = fixture();
        let mut entry = bank_input();
        entry.when = "command acknowledgement delay".into();
        entry.how = "Compare command and acknowledgement timestamps".into();
        entry.reconsider = "If clocks differ, measure the offset first".into();
        let d = bank_discovery(entry, &eligibility::Scope::default()).unwrap();
        append(&path, &d.to_line()).unwrap();
        let mut private = bank_input();
        private.when = d.when.clone();
        private.project = "other-project".into();
        let restricted = bank_discovery(private, &eligibility::Scope::default()).unwrap();
        append(&path, &restricted.to_line()).unwrap();
        let scope = eligibility::Scope::default();
        let query = "New controller has an acknowledgement delay";
        for hits in 0..=1 {
            let data = parse_json(&decision_context(&path, query, &scope, None).unwrap()).unwrap();
            let Some(Json::Arr(methods)) = data.get("experiences") else {
                panic!("missing experiences")
            };
            assert_eq!(methods.len(), 1);
            assert_eq!(
                methods[0].get("method").and_then(Json::as_str),
                Some(d.how.as_str())
            );
            assert_eq!(
                methods[0].get("reconsider_if").and_then(Json::as_str),
                Some(d.reconsider.as_str())
            );
            assert_eq!(
                methods[0].get("hits").and_then(Json::as_f64),
                Some(hits as f64)
            );
            if hits == 0 {
                op_mark(
                    &path,
                    "hit",
                    &d.id,
                    "Independent timing check succeeded",
                    "",
                )
                .unwrap();
            }
        }
        let empty = decision_context(&path, "colour palette", &scope, None).unwrap();
        assert!(
            matches!(parse_json(&empty).unwrap().get("experiences"),Some(Json::Arr(a)) if a.is_empty())
        );
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn offline_experience_lifecycle() {
        let path = fixture();
        let mut entry = bank_input();
        entry.when = "signal comparison uses a proxy whose score may disagree with independent task outcomes".into();
        entry.found = "Similarity can reward responses that never accomplished the task".into();
        entry.how = "Compare each proxy score against an independent completion check".into();
        entry.evidence =
            "Synthetic sample: two high-similarity failures and one low-similarity success".into();
        let d = bank_discovery(entry, &eligibility::Scope::default()).unwrap();
        append(&path, &d.to_line()).unwrap();
        let query = "Which proxy score tracks completion of a translation task?";
        let read = || op_recall_scoped(&path, query, 1, &eligibility::Scope::default()).unwrap();
        assert!(read().contains(&d.how));
        assert!(op_recall(&path, "prepare dinner", 1).unwrap().is_empty());
        assert!(op_instincts(&path, 2).unwrap().is_empty());
        for case in [
            "translation: independent check passed",
            "retrieval: independent check passed",
        ] {
            op_mark(&path, "hit", &d.id, case, "").unwrap();
        }
        assert!(op_instincts(&path, 2).unwrap().contains(&d.id));
        op_review(
            &path,
            &d.id,
            "quarantined",
            "Changed applicability",
            "fixture:v2",
        )
        .unwrap();
        assert!(read().is_empty());
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn scope_and_quarantine_survive_roundtrip_and_append() {
        let p = fixture();
        let original="{\"kind\":\"discovery\",\"id\":\"in-fixture\",\"title\":\"test\",\"scope_persona\":\"koscak\",\"source\":\"mined\",\"state\":\"candidate\"}\n";
        fs::write(&p, original).unwrap();
        let d = load(&p).unwrap().remove(0);
        let v = parse_json(&d.to_line()).unwrap();
        assert_eq!(
            v.get("scope_persona").and_then(Json::as_str),
            Some("koscak")
        );
        op_review(
            &p,
            "in-fixture",
            "quarantined",
            "contradictory source",
            "fixture:1",
        )
        .unwrap();
        assert!(fs::read_to_string(&p).unwrap().starts_with(original));
        let d = load(&p).unwrap().remove(0);
        assert_eq!(
            eligibility::scope_check(&d.meta, &eligibility::Scope::default(), 1),
            Err("quarantined")
        );
    }
    #[test]
    fn receipt_has_exact_ids_and_unknown_session_is_explicit() {
        let r = recall_receipt(&["in-one".into(), "in-two".into()], None).unwrap();
        assert!(matches!(r.get("ids"),Some(Json::Arr(v)) if v.len()==2));
        assert!(!r.get("event_id").and_then(Json::as_str).unwrap().is_empty());
        assert!(recall_receipt(&[], None).is_none());
    }
    #[test]
    fn review_never_grants_verified_status() {
        let p = fixture();
        assert!(op_review(&p, "x", "validated", "because", "ref").is_err());
        assert!(!p.exists());
    }
    #[test]
    fn scope_missing_cannot_match_explicit_requirement() {
        let m = meta_from(
            &parse_json("{\"scope_project\":\"/project/a\",\"scope_harness\":\"codex\"}").unwrap(),
        );
        assert_eq!(
            eligibility::scope_check(&m, &eligibility::Scope::default(), 1),
            Err("project")
        );
    }
    #[test]
    fn bank_creation_persists_explicit_scope_without_verification_escalation() {
        let mut b = bank_input();
        b.project = "/project/a".into();
        b.persona = "persona-a".into();
        b.applicability_harness = "codex".into();
        b.applicability_version = "version-a".into();
        let d = bank_discovery(b, &eligibility::Scope::default()).unwrap();
        let p = fixture();
        append(&p, &d.to_line()).unwrap();
        let stored = load(&p).unwrap().remove(0);
        assert_eq!(
            scope_identity(&stored.meta),
            ["/project/a", "persona-a", "codex", "version-a", ""]
        );
        assert_eq!(stored.meta.source, "banked");
        assert_eq!(stored.meta.state, "candidate");
        assert_eq!(stored.meta.evidence_status, "unverified");
        assert!(eligibility::unverified(&stored.meta));
        assert_eq!(
            eligibility::scope_check(&stored.meta, &eligibility::Scope::default(), 1),
            Err("project")
        );
    }
    #[test]
    fn bank_creation_does_not_infer_applicability_from_receipt_origin() {
        let origin = eligibility::Scope {
            project: "/explicit/project".into(),
            persona: "explicit-persona".into(),
            harness: "claude".into(),
            version: "origin-version".into(),
            machine: "workstation".into(),
        };
        let d = bank_discovery(bank_input(), &origin).unwrap();
        assert_eq!(
            scope_identity(&d.meta),
            ["/explicit/project", "explicit-persona", "", "", ""]
        );
        assert!(bank_scope_note(&d.meta).contains("applicability harness, applicability version"));
        let d = bank_discovery(bank_input(), &eligibility::Scope::default()).unwrap();
        assert_eq!(d.id, make_id(&d.title, &d.found));
        // Nothing scoped: the note says the lesson applies everywhere rather than listing five field names.
        assert!(bank_scope_note(&d.meta).contains("applies in every project"));
        assert_eq!(
            eligibility::eligible(&d.meta, &eligibility::Scope::default(), 1, None, 0, false),
            Err("candidate_match_unproven")
        );
    }
    #[test]
    fn bank_creation_keeps_each_scope_identity_distinct() {
        let mut ids = std::collections::HashSet::new();
        let p = fixture();
        for scope in [
            ["p1", "a", "codex", "v1"],
            ["p2", "a", "codex", "v1"],
            ["p1", "b", "codex", "v1"],
            ["p1", "a", "claude", "v1"],
            ["p1", "a", "codex", "v2"],
        ] {
            let mut b = bank_input();
            b.project = scope[0].into();
            b.persona = scope[1].into();
            b.applicability_harness = scope[2].into();
            b.applicability_version = scope[3].into();
            let d = bank_discovery(b, &eligibility::Scope::default()).unwrap();
            assert!(ids.insert(d.id.clone()));
            append(&p, &d.to_line()).unwrap();
        }
        let all = load(&p).unwrap();
        assert_eq!(all.len(), 5);
        let scope = eligibility::Scope {
            project: "p1".into(),
            persona: "a".into(),
            harness: "codex".into(),
            version: "v1".into(),
            machine: String::new(),
        };
        assert_eq!(
            all.iter()
                .filter(|d| eligibility::eligible(&d.meta, &scope, 1, Some(0.99), 0, false).is_ok())
                .count(),
            1
        );
        assert_eq!(
            all.iter()
                .filter(|d| eligibility::eligible(
                    &d.meta,
                    &eligibility::Scope::default(),
                    1,
                    Some(0.99),
                    0,
                    false
                )
                .is_ok())
                .count(),
            0
        );
    }
}

/// `journal::append` output is pinned to the bytes the 0.3.6 code wrote (captured from origin/main before `append_many`
/// existed), and a batch is byte-identical to the same events appended one at a time. Files written by the batch path
/// therefore read the same under any older binary.
#[cfg(test)]
mod append_bytes_tests {
    use super::*;
    const EVENTS: [&str; 3] = [
        "{\"kind\":\"discovery\",\"id\":\"a1\",\"title\":\"tab\\tq\\\"uote\"}",
        "{\"kind\":\"hit\",\"id\":\"a1\",\"note\":\"caf\u{e9} \u{1f600} back\\\\slash\"}",
        "{\"kind\":\"miss\",\"id\":\"a1\"}",
    ];
    const JSONL: &str = "{\"kind\":\"discovery\",\"id\":\"a1\",\"title\":\"tab\\tq\\\"uote\"}\n{\"kind\":\"hit\",\"id\":\"a1\",\"note\":\"café 😀 back\\\\slash\"}\n{\"kind\":\"miss\",\"id\":\"a1\"}\n";
    const HXDB: &str = "event:0000000000000000\tV\t4a6948f46fe1cd09:{\"kind\":\"discovery\",\"id\":\"a1\",\"title\":\"tab\\\\tq\\\\\"uote\"}\nevent:0000000000000062\tV\t91d327060c95fec2:{\"kind\":\"hit\",\"id\":\"a1\",\"note\":\"café 😀 back\\\\\\\\slash\"}\nevent:00000000000000c7\tV\t3f9c8f27de351bc6:{\"kind\":\"miss\",\"id\":\"a1\"}\n";

    #[test]
    fn single_appends_are_byte_identical_to_the_previous_release_and_a_batch_matches_them() {
        let d = std::env::temp_dir().join(format!("append-bytes-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        for (name, golden) in [("one.jsonl", JSONL), ("one.hxdb", HXDB)] {
            let one = d.join(name);
            for l in EVENTS {
                journal::append(&one, l).unwrap();
            }
            assert_eq!(std::fs::read_to_string(&one).unwrap(), golden, "{name}: single appends");
            let many = d.join(format!("many-{name}"));
            journal::append_many(&many, &EVENTS).unwrap();
            assert_eq!(std::fs::read_to_string(&many).unwrap(), golden, "{name}: one batch");
            let tail = d.join(format!("tail-{name}"));
            journal::append(&tail, EVENTS[0]).unwrap();
            journal::append_many(&tail, &EVENTS[1..]).unwrap();
            assert_eq!(std::fs::read_to_string(&tail).unwrap(), golden, "{name}: single then batch");
            let before = std::fs::read_to_string(&many).unwrap();
            journal::append_many(&many, &[]).unwrap();
            assert_eq!(std::fs::read_to_string(&many).unwrap(), before, "{name}: empty batch");
            let none = d.join(format!("none-{name}"));
            journal::append_many(&none, &[]).unwrap();
            assert!(!none.exists(), "{name}: empty batch creates nothing");
            assert_eq!(journal::read(&many).unwrap(), journal::read(&one).unwrap());
        }
        std::fs::remove_dir_all(&d).ok();
    }
}