kimetsu-brain 2.8.0

Project + user-scope memory, hybrid retrieval (lexical + cosine), ambient context, secret redaction at ingest for kimetsu.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
use std::borrow::Cow;
use std::str::FromStr;
use std::time::Duration;

use kimetsu_core::KimetsuResult;
use kimetsu_core::event::Event;
use kimetsu_core::ids::{EventId, RunId};
use rusqlite::{Connection, OptionalExtension, params};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;

use crate::redact;
use crate::schema;

/// Max attempts for a write transaction that loses the race to `SQLITE_BUSY`
/// after the 15s busy_timeout (rare; a fleet burst). The whole transaction is
/// retried from a clean state — safe because BUSY can only surface at `BEGIN`
/// (the IMMEDIATE write lock is held for the entire body once acquired).
const WRITE_TXN_MAX_ATTEMPTS: u32 = 5;

/// True when `err` is a SQLite busy/locked condition (downcastable through the
/// boxed `KimetsuResult` error, since `?` preserves the concrete type).
fn is_sqlite_busy(err: &(dyn std::error::Error + 'static)) -> bool {
    err.downcast_ref::<rusqlite::Error>()
        .and_then(|e| e.sqlite_error_code())
        .is_some_and(|code| {
            matches!(
                code,
                rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
            )
        })
}

/// Run `body` inside a single `BEGIN IMMEDIATE` transaction (concurrent-write
/// safe): the write lock is taken at `BEGIN`, so two processes writing the same
/// brain.db serialize cleanly and read-modify-write projections (use_count,
/// confidence) never interleave across writers. Retries the whole transaction on
/// `SQLITE_BUSY`/`LOCKED` (which can only occur at `BEGIN`). `&Connection` can't
/// use `transaction_with_behavior`, so the transaction is driven manually.
pub(crate) fn with_write_txn<F>(conn: &Connection, mut body: F) -> KimetsuResult<()>
where
    F: FnMut(&Connection) -> KimetsuResult<()>,
{
    let mut attempt = 0u32;
    loop {
        attempt += 1;
        // BEGIN IMMEDIATE — acquires the write lock now. BUSY surfaces here.
        if let Err(e) = conn.execute_batch("BEGIN IMMEDIATE") {
            let boxed: Box<dyn std::error::Error + Send + Sync> = e.into();
            if is_sqlite_busy(boxed.as_ref()) && attempt < WRITE_TXN_MAX_ATTEMPTS {
                std::thread::sleep(Duration::from_millis(20 * attempt as u64));
                continue;
            }
            return Err(boxed);
        }
        // Lock held — run the body, then COMMIT (or ROLLBACK on any error).
        match body(conn) {
            Ok(()) => match conn.execute_batch("COMMIT") {
                Ok(()) => return Ok(()),
                Err(e) => {
                    let _ = conn.execute_batch("ROLLBACK");
                    return Err(e.into());
                }
            },
            Err(e) => {
                let _ = conn.execute_batch("ROLLBACK");
                return Err(e);
            }
        }
    }
}

/// Event-schema durability seam. Normalizes an event written under an older
/// `EVENT_SCHEMA_VERSION` to the current payload shape *before projection*,
/// so a future version bump is a localized addition here rather than a
/// projector rewrite. Identity today (`EVENT_SCHEMA_VERSION == 1`: every
/// stored event is already current). When the event schema first changes,
/// add `(kind, schema_version)`-keyed transforms that return `Cow::Owned`
/// with the upgraded payload.
fn upcast_event(event: &Event) -> Cow<'_, Event> {
    // No historical versions to upcast yet.
    Cow::Borrowed(event)
}

pub fn rebuild(conn: &Connection, events: &[Event]) -> KimetsuResult<()> {
    with_write_txn(conn, |c| {
        // Trace import supplements the durable log. It must not replace claims
        // written directly to that log, nor leave an empty projection on error.
        for event in events {
            // Historical events cannot be applied to today's final state:
            // that could bind an old exposure to a newly corrected claim.
            insert_event(c, redact_memory_event(event).as_ref())?;
        }
        replay_locked(c).map(|_| ())
    })
}

/// Rebuild the projection from the durable events table (in place). Reads
/// every stored event, resets the derived tables, and re-projects — WITHOUT
/// re-inserting events (so no duplication). Returns the number of events
/// replayed.
pub fn rebuild_in_place(conn: &Connection) -> KimetsuResult<usize> {
    let mut count = 0;
    with_write_txn(conn, |c| {
        count = replay_locked(c)?;
        Ok(())
    })?;
    Ok(count)
}

/// Caller holds the SQLite writer lock across snapshot, reset and replay.
pub(crate) fn replay_locked(conn: &Connection) -> KimetsuResult<usize> {
    let events = read_events_ordered(conn)?;
    let existing = {
        let mut stmt = conn.prepare("SELECT memory_id FROM memories")?;
        stmt.query_map([], |r| r.get::<_, String>(0))?
            .collect::<Result<std::collections::BTreeSet<_>, _>>()?
    };
    reset_projection(conn)?;
    for event in &events {
        // Upgrade legacy missing bindings at their causal replay position,
        // preserving every explicitly supplied map (including empty maps).
        let bound = bind_injected_revisions(conn, event)?;
        if matches!(&bound, Cow::Owned(_)) {
            conn.execute(
                "UPDATE events SET payload_json=?2 WHERE event_id=?1",
                params![
                    event.event_id.to_string(),
                    serde_json::to_string(&bound.payload)?
                ],
            )?;
        }
        project_event(conn, bound.as_ref())?;
    }
    let mut stmt = conn.prepare("SELECT memory_id FROM memories")?;
    let restored = stmt
        .query_map([], |r| r.get::<_, String>(0))?
        .collect::<Result<std::collections::BTreeSet<_>, _>>()?;
    let missing = existing.difference(&restored).count();
    if missing > 0 {
        return Err(format!("rebuild refused: {missing} existing memories absent from replay; transaction rolled back. Back up the brain and recover missing events before rebuilding; legacy unlogged rows require migration.").into());
    }
    Ok(events.len())
}

/// Read all stored events from the durable `events` table, ordered by
/// (ts, rowid) so replay is deterministic AND causal.
///
/// `rowid` is the implicit, insertion-monotonic key, so within an equal `ts`
/// it preserves append order — the true causal order (e.g. a `memory.cited`
/// appended before the `memory.superseded` that reassigns it). The previous
/// `event_id` tiebreak was NOT causal: event ids are ULIDs whose ordering is
/// only random-tail-stable within the same millisecond, so equal-`ts` events
/// replayed in a platform-dependent order — non-deterministic rebuilds.
fn read_events_ordered(conn: &Connection) -> KimetsuResult<Vec<Event>> {
    // Order by HLC (Hybrid Logical Clock): a globally-deterministic, causal total
    // order. On a single brain this generalizes the old (ts, rowid) order; across
    // synced brains it makes the merged-log replay converge (same projection on
    // every brain regardless of import order). `rowid` is a stable final tiebreak.
    let mut stmt = conn.prepare(
        "
        SELECT event_id, run_id, ts, kind, schema_version, payload_json, origin, hlc
        FROM events
        ORDER BY hlc, rowid
        ",
    )?;
    let rows = stmt.query_map([], |row| {
        let event_id_str: String = row.get(0)?;
        let run_id_str: String = row.get(1)?;
        let ts_str: String = row.get(2)?;
        let kind: String = row.get(3)?;
        let schema_version: u32 = row.get(4)?;
        let payload_json: String = row.get(5)?;
        let origin: Option<String> = row.get(6)?;
        let hlc: Option<String> = row.get(7)?;
        Ok((
            event_id_str,
            run_id_str,
            ts_str,
            kind,
            schema_version,
            payload_json,
            origin,
            hlc,
        ))
    })?;

    let mut events = Vec::new();
    for row in rows {
        let (event_id_str, run_id_str, ts_str, kind, schema_version, payload_json, origin, hlc) =
            row?;
        let event_id = EventId(
            ulid::Ulid::from_str(&event_id_str)
                .map_err(|e| format!("invalid event_id {event_id_str:?}: {e}"))?,
        );
        let run_id = RunId(
            ulid::Ulid::from_str(&run_id_str)
                .map_err(|e| format!("invalid run_id {run_id_str:?}: {e}"))?,
        );
        let ts = OffsetDateTime::parse(&ts_str, &Rfc3339)
            .map_err(|e| format!("invalid ts {ts_str:?}: {e}"))?;
        let payload: serde_json::Value = serde_json::from_str(&payload_json)?;
        events.push(Event {
            event_id,
            run_id,
            ts,
            parent_event_id: None, // not stored; never read by the projector
            kind,
            schema_version,
            payload,
            origin, // preserved across rebuild (NULL for pre-v8 events)
            hlc,    // preserved across rebuild (backfilled for pre-v9 events)
        });
    }
    Ok(events)
}

pub fn apply_events(conn: &Connection, events: &[Event]) -> KimetsuResult<()> {
    apply_events_checked(conn, events, |_| Ok(()))
}

/// Validate a read-derived plan under the same write lock as its events.
pub(crate) fn apply_events_checked<F>(
    conn: &Connection,
    events: &[Event],
    mut validate: F,
) -> KimetsuResult<()>
where
    F: FnMut(&Connection) -> KimetsuResult<()>,
{
    with_write_txn(conn, |c| {
        validate(c)?;
        for event in events {
            apply_event(c, event)?;
        }
        Ok(())
    })
}

fn reset_projection(conn: &Connection) -> KimetsuResult<()> {
    // Wipe ONLY the derived/projected tables. The `events` table is the
    // durable log and MUST survive a rebuild (rebuild replays it).
    conn.execute_batch(
        "
        DELETE FROM runs;
        DELETE FROM sources;
        DELETE FROM memories;
        DELETE FROM memory_revisions;
        DELETE FROM memory_facts;
        DELETE FROM memory_proposals;
        DELETE FROM memories_fts;
        DELETE FROM memory_citations;
        DELETE FROM memory_conflicts;
        DELETE FROM sync_conflicts;
        DELETE FROM memory_edges;
        DELETE FROM memory_entities;
        DELETE FROM work_episodes;
        ",
    )?;
    Ok(())
}

pub(crate) fn apply_event(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let event = redact_memory_event(event);
    let event = bind_injected_revisions(conn, event.as_ref())?;
    let event = event.as_ref();
    // Persist the event after memory payload redaction so durable replay tables
    // never become a second secret store.
    insert_event(conn, event)?;
    // Project the now-stored event into the derived tables.
    project_event(conn, event)
}

/// Project a single event into the derived tables (the dispatch half of
/// `apply_event`, WITHOUT inserting into the events table). Used by both the
/// write path (after insert) and the in-place rebuild (events already stored).
fn project_event(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    // Project through the durability seam so older-schema events normalize
    // to the current shape before dispatch.
    let upcasted = upcast_event(event);
    let redacted = redact_memory_event(upcasted.as_ref());
    let event = redacted.as_ref();

    match event.kind.as_str() {
        "run.started" => apply_run_started(conn, event),
        "run.finished" | "run.failed" | "run.aborted" => apply_terminal_run(conn, event),
        "memory.accepted" => apply_memory_accepted(conn, event),
        "memory.proposed" => apply_memory_proposed(conn, event),
        "memory.rejected" => apply_memory_rejected(conn, event),
        "memory.invalidated" => apply_memory_invalidated(conn, event),
        "memory.restored" => apply_memory_restored(conn, event),
        "conflict.resolved" => crate::conflict::project_resolution(conn, event),
        // v0.5.1: per-turn memory citation. The model emits this
        // via the `cite_memory` tool when it consciously leveraged
        // a retrieved capsule. Best-effort — a missing or
        // malformed payload just no-ops.
        "memory.cited" => apply_memory_cited(conn, event),
        // Story 2.4: explicit regret (negative outcome) on a memory. Only
        // manual regrets mutate stats (see apply_retrieval_regret); auto
        // telemetry regrets are projected as no-ops.
        "retrieval.regret" => apply_retrieval_regret(conn, event),
        // Testing/benchmark affordance: backdate created_at / last_useful_at so
        // age-sensitive policies (forgetting) can be exercised.
        "memory.aged" => apply_memory_aged(conn, event),
        // Story 3.1: near-duplicate merge — stamp superseded_by on merged members,
        // remove their FTS rows, and drop them from the ANN index.
        "memory.superseded" => apply_memory_superseded(conn, event),
        // #2 knowledge graph: a typed relation edge between two memories, written
        // by `kimetsu brain graph build`. Projected into `memory_edges` so the
        // graph-lite / petgraph retrieval backends can traverse it. Rebuild-safe:
        // the edge is re-derived by replaying this event.
        "memory.edge" => apply_memory_edge(conn, event),
        // Flagship 1 / Story 1.4: temporal validity — stamp valid_from / valid_to.
        "memory.corrected" => apply_memory_corrected(conn, event),
        "memory.temporal" => apply_memory_temporal(conn, event),
        // Flagship 1 / Story 1.3: episodic work-resume.
        "work.episode" => crate::episode::project_work_episode(conn, event),
        _ => Ok(()),
    }
}

fn redact_memory_event(event: &Event) -> Cow<'_, Event> {
    if !matches!(
        event.kind.as_str(),
        "memory.accepted" | "memory.proposed" | "memory.cited" | "memory.corrected"
    ) {
        return Cow::Borrowed(event);
    }
    let (payload, changed) = redact_json_strings(&event.payload);
    if changed {
        Cow::Owned(Event {
            payload,
            ..event.clone()
        })
    } else {
        Cow::Borrowed(event)
    }
}

fn redact_json_strings(value: &serde_json::Value) -> (serde_json::Value, bool) {
    match value {
        serde_json::Value::String(text) => {
            let redaction = redact::redact_secrets(text);
            let changed = redaction.was_redacted();
            (serde_json::Value::String(redaction.text), changed)
        }
        serde_json::Value::Array(values) => {
            let mut changed = false;
            let values = values
                .iter()
                .map(|value| {
                    let (value, did_change) = redact_json_strings(value);
                    changed |= did_change;
                    value
                })
                .collect();
            (serde_json::Value::Array(values), changed)
        }
        serde_json::Value::Object(map) => {
            let mut changed = false;
            let map = map
                .iter()
                .map(|(key, value)| {
                    let (value, did_change) = redact_json_strings(value);
                    changed |= did_change;
                    (key.clone(), value)
                })
                .collect();
            (serde_json::Value::Object(map), changed)
        }
        other => (other.clone(), false),
    }
}

fn apply_memory_cited(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event
        .payload
        .get("memory_id")
        .and_then(|value| value.as_str())
    else {
        // No memory_id -> drop. Citations are best-effort metadata,
        // not load-bearing — silently skipping malformed payloads
        // keeps the run from breaking.
        return Ok(());
    };
    let current_revision = claim_revision_at(conn, memory_id, None)?;
    let explicit = event
        .payload
        .get("revision_event_id")
        .and_then(|v| v.as_str());
    let exposed =
        if let Some(exposure_id) = event.payload.get("exposure_id").and_then(|v| v.as_str()) {
            exact_claim_exposure(conn, exposure_id, &event.run_id.to_string(), memory_id)?
        } else {
            run_claim_revision(conn, &event.run_id.to_string(), memory_id)?
        };
    // A citation without a revision or exposure is ambiguous after a text
    // correction. Keep its durable event, but do not credit the new claim.
    let exposed = match exposed {
        ClaimExposure::Unbound => return Ok(()),
        ClaimExposure::Absent => None,
        ClaimExposure::Bound(revision) => Some(revision),
    };
    if explicit
        .zip(exposed.as_deref())
        .is_some_and(|(explicit, delivered)| explicit != delivered)
    {
        return Ok(());
    }
    let evidence_revision = explicit.map(str::to_owned).or(exposed);
    if evidence_revision
        .as_ref()
        .is_some_and(|r| r != &current_revision)
        || (evidence_revision.is_none() && !current_revision.starts_with("baseline:"))
    {
        return Ok(());
    }
    let turn = event
        .payload
        .get("turn")
        .and_then(|value| value.as_i64())
        .unwrap_or(0);
    let rationale = event
        .payload
        .get("rationale")
        .and_then(|value| value.as_str());
    let cited_at = ts_text(event)?;
    conn.execute(
        "
        INSERT OR REPLACE INTO memory_citations (
            run_id, memory_id, turn, cited_at, rationale
        )
        VALUES (?1, ?2, ?3, ?4, ?5)
        ",
        params![
            event.run_id.to_string(),
            memory_id,
            turn,
            cited_at,
            rationale,
        ],
    )?;

    // v2.5.2: persist which query this citation answered (feeds the
    // query_routes derived index built by `brain reinforce`). Column exists
    // from schema v10; skipped for events without a query.
    if let Some(query) = event.payload.get("query").and_then(|v| v.as_str()) {
        conn.execute(
            "UPDATE memory_citations SET query = ?4
             WHERE run_id = ?1 AND memory_id = ?2 AND turn = ?3",
            params![event.run_id.to_string(), memory_id, turn, query],
        )?;
    }

    // A citation records reliance only. Outcomes are credited separately.
    Ok(())
}

/// Story 2.4: a memory the model flagged as unhelpful/misleading. Mirrors the
/// `run.failed` cited delta. Only EXPLICIT manual regrets (`payload.source ==
/// "manual"`, set by `record_regret` / `brain regret`) mutate stats; the
/// auto-emitted regret telemetry (no `source`) stays a no-op so existing
/// behavior is unchanged.
fn apply_retrieval_regret(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let is_manual = event
        .payload
        .get("source")
        .and_then(|v| v.as_str())
        .map(|s| s == "manual")
        .unwrap_or(false);
    if !is_manual {
        return Ok(());
    }
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let ts = ts_text(event)?;
    apply_cited_outcome(conn, memory_id, -1.0, 0.0, &ts, false)?;
    Ok(())
}

/// Backdate a memory's `created_at` / `last_useful_at` from a `memory.aged`
/// event (absolute timestamps in the payload → rebuild-deterministic).
fn apply_memory_aged(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    if let Some(created) = event.payload.get("created_at").and_then(|v| v.as_str()) {
        conn.execute(
            "UPDATE memories SET created_at = ?2 WHERE memory_id = ?1",
            params![memory_id, created],
        )?;
    }
    if let Some(last_useful) = event.payload.get("last_useful_at").and_then(|v| v.as_str()) {
        conn.execute(
            "UPDATE memories SET last_useful_at = ?2 WHERE memory_id = ?1",
            params![memory_id, last_useful],
        )?;
    }
    Ok(())
}

/// Confidence calibration smoothing factor (Bayesian-ish nudge per outcome).
use crate::scoring::{CITED_DELTA, CONF_ALPHA, FAILURE_PENALTY_CITES_DIVISOR, PASSENGER_DELTA};

/// Apply a single cited-memory OUTCOME to one memory row, shared by the run
/// attribution path and the standalone cite/regret path: bump `use_count`,
/// add `usefulness_delta`, stamp `last_used_at` (and `last_useful_at` when
/// `bump_last_useful`), and nudge `confidence` toward `conf_target`
/// (`new = old + 0.05*(target-old)`, clamped to [0.1, 0.99]). Read-modify-write
/// on the deterministic event order → rebuild-safe.
fn apply_cited_outcome(
    conn: &Connection,
    memory_id: &str,
    usefulness_delta: f64,
    conf_target: f64,
    ts: &str,
    bump_last_useful: bool,
) -> KimetsuResult<()> {
    conn.execute(
        "UPDATE memories
         SET use_count = use_count + 1,
             usefulness_score = usefulness_score + ?2,
             last_used_at = ?3
         WHERE memory_id = ?1",
        params![memory_id, usefulness_delta, ts],
    )?;
    if bump_last_useful {
        conn.execute(
            "UPDATE memories SET last_useful_at = ?2 WHERE memory_id = ?1",
            params![memory_id, ts],
        )?;
    }
    let old_conf: f64 = conn
        .query_row(
            "SELECT confidence FROM memories WHERE memory_id = ?1",
            params![memory_id],
            |row| row.get::<_, f64>(0),
        )
        .unwrap_or(1.0);
    let new_conf = (old_conf + CONF_ALPHA * (conf_target - old_conf)).clamp(0.1, 0.99);
    conn.execute(
        "UPDATE memories SET confidence = ?2 WHERE memory_id = ?1",
        params![memory_id, new_conf],
    )?;
    Ok(())
}

pub(crate) fn insert_event(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let payload = serde_json::to_string(&event.payload)?;
    conn.execute(
        "
        INSERT OR IGNORE INTO events (
            event_id, run_id, ts, kind, schema_version, payload_json, origin, hlc
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
        ",
        params![
            event.event_id.to_string(),
            event.run_id.to_string(),
            ts_text(event)?,
            event.kind,
            event.schema_version,
            payload,
            event.origin,
            event.hlc,
        ],
    )?;
    Ok(())
}

fn apply_run_started(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let project_id = event
        .payload
        .get("project_id")
        .and_then(|value| value.as_str())
        .unwrap_or("unknown");
    let task = event
        .payload
        .get("task")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let model = event
        .payload
        .get("model")
        .and_then(|value| value.as_str())
        .map(str::to_string);

    conn.execute(
        "
        INSERT OR IGNORE INTO runs (
            run_id, project_id, task, started_at, model, total_cost_usd
        )
        VALUES (?1, ?2, ?3, ?4, ?5, 0)
        ",
        params![
            event.run_id.to_string(),
            project_id,
            task,
            ts_text(event)?,
            model
        ],
    )?;
    Ok(())
}

fn apply_terminal_run(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let total_cost = event
        .payload
        .get("total_cost_usd")
        .and_then(|value| value.as_f64())
        .unwrap_or(0.0);

    conn.execute(
        "
        UPDATE runs
        SET ended_at = ?2,
            terminal_kind = ?3,
            total_cost_usd = ?4
        WHERE run_id = ?1
        ",
        params![
            event.run_id.to_string(),
            ts_text(event)?,
            event.kind,
            total_cost
        ],
    )?;

    apply_memory_usefulness_for_run(conn, event)?;
    Ok(())
}

/// MP-4a + v0.5.1 outcome attribution: when a run terminates, walk every
/// `context.injected` event AND every `memory.cited` event the run emitted,
/// split the unique memory ids into "cited" vs "silent passenger", and
/// update each memory's `use_count` + `usefulness_score`.
///
/// Delta rules:
///   run.finished:
///     cited memory     -> +1.0 usefulness (matches MP-4a baseline)
///     silent passenger -> +0.1 usefulness (weaker signal — it was on
///                         screen but the model didn't reach for it)
///   run.failed (cat != "Gate"):
///     cited memory     -> -1.0 usefulness (the brain pushed wrong)
///     silent passenger -> -0.1 usefulness (was retrieved, didn't help)
///   run.failed (cat == "Gate"):
///     no update (graceful early-exit; the plan-create existence guard
///     doesn't reflect on the memory)
///   run.aborted:
///     no update (user-initiated stop)
///
/// Pre-v0.5.1 behavior: cited == silent (both got the full ±1). When no
/// `memory.cited` events exist (e.g. older runs, models that never call
/// `cite_memory`), every retrieved memory is treated as a silent
/// passenger — i.e. weak ±0.1 instead of strong ±1. This is intentional:
/// without citation evidence we shouldn't claim a memory "helped." The
/// blame command surfaces the discrepancy so operators can encourage
/// citation usage where the brain is under-rewarding good capsules.
fn apply_memory_usefulness_for_run(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let (strong, weak): (f64, f64) = match event.kind.as_str() {
        "run.finished" => (CITED_DELTA, PASSENGER_DELTA),
        "run.failed" => {
            let category = event
                .payload
                .get("category")
                .and_then(|value| value.as_str())
                .unwrap_or("");
            if category == "Gate" {
                return Ok(());
            }
            (-CITED_DELTA, -PASSENGER_DELTA)
        }
        _ => return Ok(()), // run.aborted, anything else: no update
    };

    let run_id = event.run_id.to_string();
    let retrieved = collect_injected_memory_ids(conn, &run_id)?;
    if retrieved.is_empty() {
        return Ok(());
    }
    let cited = collect_cited_memory_ids(conn, &run_id)?;
    let ts = ts_text(event)?;
    // v0.5.1: bump `last_useful_at` only on cited + run.finished.
    // Cited + run.failed doesn't count (the memory misled the
    // model). Silent passengers never bump regardless of outcome.
    let bump_last_useful = event.kind == "run.finished";

    // Flagship 2 / Story 2.4: confidence calibration target.
    // run.finished → target 1.0 (success), run.failed → target 0.0 (failure).
    // alpha = 0.05: conservative Bayesian-ish smoothing.
    let conf_target: Option<f64> = match event.kind.as_str() {
        "run.finished" => Some(1.0),
        "run.failed" => Some(0.0),
        _ => None,
    };

    for memory_id in &retrieved {
        let exposure = run_claim_revision(conn, &run_id, memory_id)?;
        if matches!(exposure, ClaimExposure::Unbound) {
            // An explicit delivery map is authoritative: missing/ambiguous IDs
            // have no safely attributable claim, including the baseline claim.
            continue;
        }
        if let ClaimExposure::Bound(exposed_revision) = exposure {
            if exposed_revision != claim_revision_at(conn, memory_id, None)? {
                // The run saw the old proposition. Its delayed outcome belongs
                // to that retained revision, even if correction removed the
                // old citation projection in the meantime.
                let was_cited: bool = conn.query_row(
                    "SELECT EXISTS(SELECT 1 FROM events WHERE run_id=?1 AND kind='memory.cited' AND json_extract(payload_json,'$.memory_id')=?2
                     AND (json_extract(payload_json,'$.revision_event_id') IS NULL OR json_extract(payload_json,'$.revision_event_id')=?3)
                     AND rowid <= (SELECT rowid FROM events WHERE event_id=?4))",
                    params![run_id,memory_id,exposed_revision,event.event_id.to_string()], |r| r.get(0))?;
                let delta = if was_cited { strong } else { weak };
                conn.execute("UPDATE memory_revisions SET use_count=use_count+1,usefulness_score=usefulness_score+?2,
                    confidence=CASE WHEN ?3 THEN MAX(0.1,MIN(0.99,confidence+?4*(?5-confidence))) ELSE confidence END
                    WHERE event_id=?1 AND memory_id=?6", params![exposed_revision,delta,was_cited,CONF_ALPHA,conf_target.unwrap_or(1.0),memory_id])?;
                continue;
            }
        }
        let is_cited = cited.contains(memory_id);
        let delta = if is_cited {
            if strong < 0.0 {
                // v2.5.1: citation-aware failure penalty. A memory cited in a
                // run that fails for unrelated reasons (flaky verification, an
                // environment hiccup categorized non-Gate) used to eat the flat
                // -1.0; two or three unlucky runs made a genuinely proven
                // memory a prune candidate. Scale the penalty down by the
                // memory's citation history: a long positive track record
                // absorbs occasional cited-failures, an unproven memory takes
                // proportionally more of the hit.
                //   effective = -1.0 / (1 + prior_citations / 3)
                // (0 priors -> -1.0, 3 -> -0.5, 9 -> -0.25). Successes are
                // never scaled; the Gate carve-out above still applies.
                let prior_cites: i64 = conn
                    .query_row(
                        "SELECT COUNT(*) FROM memory_citations
                         WHERE memory_id = ?1 AND run_id != ?2",
                        params![memory_id, run_id],
                        |row| row.get(0),
                    )
                    .unwrap_or(0);
                strong / (1.0 + prior_cites as f64 / FAILURE_PENALTY_CITES_DIVISOR)
            } else {
                strong
            }
        } else {
            weak
        };
        conn.execute(
            "
            UPDATE memories
            SET use_count = use_count + 1,
                usefulness_score = usefulness_score + ?2,
                last_used_at = ?3
            WHERE memory_id = ?1
            ",
            params![memory_id, delta, ts],
        )?;
        if is_cited && bump_last_useful {
            // v0.5.1: separate column for the decay reference. We
            // intentionally only touch it for confirmed successful
            // citations so the half-life curve in `usefulness_-
            // multiplier` reflects when the memory was last
            // PROVEN to help — not just when it was retrieved.
            conn.execute(
                "UPDATE memories SET last_useful_at = ?2 WHERE memory_id = ?1",
                params![memory_id, ts],
            )?;
        }
        // Flagship 2 / Story 2.4: update confidence only for cited memories.
        // Silent passengers do not get a confidence update — only explicitly
        // cited memories affect the calibration.
        if is_cited {
            if let Some(target) = conf_target {
                // Read current confidence, apply Bayesian-ish posterior, clamp.
                let old_conf: f64 = conn
                    .query_row(
                        "SELECT confidence FROM memories WHERE memory_id = ?1",
                        params![memory_id],
                        |row| row.get::<_, f64>(0),
                    )
                    .unwrap_or(1.0);
                let new_conf = (old_conf + CONF_ALPHA * (target - old_conf)).clamp(0.1, 0.99);
                conn.execute(
                    "UPDATE memories SET confidence = ?2 WHERE memory_id = ?1",
                    params![memory_id, new_conf],
                )?;
            }
        }
    }
    Ok(())
}

/// v0.5.1: walk this run's `memory_citations` rows and return the unique
/// memory ids that the model explicitly cited via the `cite_memory` tool.
/// Used by `apply_memory_usefulness_for_run` to give the strong delta
/// only to memories that actually contributed to the model's reasoning.
fn collect_cited_memory_ids(
    conn: &Connection,
    run_id: &str,
) -> KimetsuResult<std::collections::BTreeSet<String>> {
    let mut stmt = conn.prepare(
        "
        SELECT DISTINCT memory_id
        FROM memory_citations
        WHERE run_id = ?1
        ",
    )?;
    let rows = stmt.query_map(params![run_id], |row| row.get::<_, String>(0))?;
    let mut out = std::collections::BTreeSet::new();
    for row in rows {
        out.insert(row?);
    }
    Ok(out)
}

/// Walk this run's `context.injected` events and return the unique memory
/// ids that were surfaced into any stage's broker bundle. Per-run counting:
/// a memory injected into Localization AND PatchPlan in the same run counts
/// once.
fn collect_injected_memory_ids(conn: &Connection, run_id: &str) -> KimetsuResult<Vec<String>> {
    let mut stmt = conn.prepare(
        "
        SELECT payload_json
        FROM events
        WHERE run_id = ?1 AND kind = 'context.injected'
        ",
    )?;
    let rows = stmt.query_map(params![run_id], |row| row.get::<_, String>(0))?;

    let mut seen = std::collections::BTreeSet::new();
    for row in rows {
        let payload_json = row?;
        let payload: serde_json::Value = serde_json::from_str(&payload_json)?;
        if let Some(ids) = payload.get("memory_ids").and_then(|v| v.as_array()) {
            for id in ids {
                if let Some(id_str) = id.as_str()
                    && !id_str.is_empty()
                {
                    seen.insert(id_str.to_string());
                }
            }
        }
    }
    Ok(seen.into_iter().collect())
}

/// Validate applicability before projecting any part of the claim.
fn event_validity<'a>(
    conn: &Connection,
    event: &'a Event,
) -> KimetsuResult<(Option<&'a str>, Option<&'a str>)> {
    let endpoint = |name| -> KimetsuResult<Option<&'a str>> {
        match event.payload.get(name) {
            None | Some(serde_json::Value::Null) => Ok(None),
            Some(serde_json::Value::String(value)) => Ok(Some(value.as_str())),
            _ => Err(format!("{name} must be a timestamp string or null").into()),
        }
    };
    let from = endpoint("valid_from")?;
    let to = endpoint("valid_to")?;
    let (start, end): (Option<f64>, Option<f64>) = conn.query_row(
        "SELECT julianday(?1),julianday(?2)",
        params![from, to],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    if (from.is_some() && start.is_none())
        || (to.is_some() && end.is_none())
        || matches!((start,end), (Some(a),Some(b)) if a >= b)
    {
        return Err("invalid or empty temporal validity interval".into());
    }
    Ok((from, to))
}

fn apply_memory_accepted(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event
        .payload
        .get("memory_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let (valid_from, valid_to) = event_validity(conn, event)?;
    let scope = event
        .payload
        .get("scope")
        .and_then(|value| value.as_str())
        .unwrap_or("global_user");
    let kind = event
        .payload
        .get("kind")
        .and_then(|value| value.as_str())
        .unwrap_or("fact");
    let text = event
        .payload
        .get("text")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let normalized_text = event
        .payload
        .get("normalized_text")
        .and_then(|value| value.as_str())
        .unwrap_or(text);
    let confidence = event
        .payload
        .get("confidence")
        .and_then(|value| value.as_f64())
        .unwrap_or(1.0);
    // Flagship 2 / Story 2.1: initial usefulness seed.
    // Pre-Flagship-2 events don't carry this field → default 0.0 (backward compat).
    let initial_usefulness = event
        .payload
        .get("initial_usefulness")
        .and_then(|value| value.as_f64())
        .unwrap_or(0.0) as f32;
    let provenance_snapshot = event
        .payload
        .get("provenance_snapshot")
        .cloned()
        .unwrap_or_else(
            || serde_json::json!({ "source": "event", "event_id": event.event_id.to_string() }),
        );

    conn.execute(
        "
        INSERT OR REPLACE INTO memories (
            memory_id, scope, kind, text, normalized_text, confidence,
            source_event_id, provenance_snapshot_json, created_at, use_count,
            usefulness_score, valid_from, valid_to
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 0, ?10, ?11, ?12)
        ",
        params![
            memory_id,
            scope,
            kind,
            text,
            normalized_text,
            confidence,
            event.event_id.to_string(),
            serde_json::to_string(&provenance_snapshot)?,
            ts_text(event)?,
            initial_usefulness,
            valid_from,
            valid_to
        ],
    )?;

    conn.execute(
        "DELETE FROM memories_fts WHERE memory_id = ?1",
        params![memory_id],
    )?;
    conn.execute(
        "INSERT INTO memories_fts (memory_id, text, kind, scope) VALUES (?1, ?2, ?3, ?4)",
        params![memory_id, text, kind, scope],
    )?;
    // v2.6: `memory_entities` is a projection of the text, exactly like the FTS
    // row above, so it is maintained here and rebuilt by `brain rebuild`.
    // Best-effort: an entity-index hiccup must not fail the write that carries
    // the user's actual memory.
    let _ = crate::graph::project_entities(conn, memory_id, text);
    if let Some(proposal_id) = event.payload.get("proposal_id").and_then(|v| v.as_str()) {
        conn.execute("UPDATE memory_proposals SET status='accepted', decided_at=?2, decided_by='cli' WHERE proposal_id=?1",
            params![proposal_id,ts_text(event)?])?;
    }
    crate::fact_store::refresh(conn, memory_id)?;
    Ok(())
}

fn apply_memory_proposed(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(proposal_id) = event
        .payload
        .get("proposal_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let (valid_from, valid_to) = event_validity(conn, event)?;
    let scope = event
        .payload
        .get("scope")
        .and_then(|value| value.as_str())
        .unwrap_or("run");
    let kind = event
        .payload
        .get("kind")
        .and_then(|value| value.as_str())
        .unwrap_or("fact");
    let text = event
        .payload
        .get("text")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let rationale = event
        .payload
        .get("rationale")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let confidence = event
        .payload
        .get("proposed_confidence")
        .and_then(|value| value.as_f64())
        .unwrap_or(0.5);
    let source_event_ids = event
        .payload
        .get("source_event_ids")
        .cloned()
        .unwrap_or_else(|| serde_json::json!([]));

    conn.execute(
        "
        INSERT OR REPLACE INTO memory_proposals (
            proposal_id, run_id, scope, kind, text, rationale,
            proposed_confidence, source_event_ids_json, status, valid_from, valid_to
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending', ?9, ?10)
        ",
        params![
            proposal_id,
            event.run_id.to_string(),
            scope,
            kind,
            text,
            rationale,
            confidence,
            serde_json::to_string(&source_event_ids)?,
            valid_from,
            valid_to
        ],
    )?;
    Ok(())
}

fn apply_memory_rejected(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(proposal_id) = event
        .payload
        .get("proposal_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let reason = event
        .payload
        .get("reason")
        .and_then(|value| value.as_str())
        .map(|s| s.to_string());

    conn.execute(
        "
        UPDATE memory_proposals
        SET status = 'rejected',
            decided_at = ?2,
            decided_by = 'cli',
            decided_reason = ?3
        WHERE proposal_id = ?1
        ",
        params![proposal_id, ts_text(event)?, reason],
    )?;
    Ok(())
}

/// MP-4d: human-invalidated memories are flagged so the broker excludes
/// them from retrieval and `kimetsu brain memory list` can render the
/// reason. The canonical trace still holds the original memory.accepted
/// event; invalidation is additive metadata, not a delete.
fn apply_memory_invalidated(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event
        .payload
        .get("memory_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let reason = event
        .payload
        .get("reason")
        .and_then(|value| value.as_str())
        .map(|s| s.to_string());
    if reason
        .as_deref()
        .is_some_and(|r| matches!(r, "forgotten" | "forgotten/archived" | "forgotten_archived"))
    {
        let active:bool=conn.query_row("SELECT EXISTS(SELECT 1 FROM memories WHERE memory_id=?1 AND invalidated_at IS NULL AND superseded_by IS NULL)",[memory_id],|r|r.get(0))?;
        if !active {
            return Ok(());
        }
    }
    conn.execute(
        "
        UPDATE memories
        SET invalidated_at = ?2,
            invalidated_reason = ?3
        WHERE memory_id = ?1
        ",
        params![memory_id, ts_text(event)?, reason],
    )?;
    conn.execute("DELETE FROM memories_fts WHERE memory_id=?1", [memory_id])?;
    #[cfg(feature = "embeddings")]
    crate::ann::on_invalidate(conn, memory_id);
    // v2.6: drop the entity rows too, so the graph stops routing traffic
    // through a memory retrieval already excludes.
    let _ = crate::graph::forget_entities(conn, memory_id);
    Ok(())
}

/// Restore only archived claims. Temporal expiry and supersession are preserved.
fn apply_memory_restored(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let changed = conn.execute(
        "UPDATE memories SET invalidated_at=NULL, invalidated_reason=NULL
      WHERE memory_id=?1 AND superseded_by IS NULL AND invalidated_at IS NOT NULL
      AND invalidated_reason IN ('forgotten','forgotten/archived','forgotten_archived')",
        [id],
    )?;
    if changed > 0 {
        conn.execute("DELETE FROM memories_fts WHERE memory_id=?1", [id])?;
        conn.execute("INSERT INTO memories_fts(memory_id,text,kind,scope) SELECT memory_id,text,kind,scope FROM memories WHERE memory_id=?1", [id])?;
    }
    Ok(())
}

/// Story 3.1: project a `memory.superseded` event.
///
/// Payload fields:
///   `memory_id`       — the member being superseded (merged into survivor)
///   `survivor_id`     — the memory that absorbs the cluster
///   `use_count_delta` — member's use_count contribution (optional, default 0)
///   `score_delta`     — member's usefulness_score contribution (optional, default 0)
///
/// Projection:
///   1. Stamp `superseded_by = survivor_id` on the member row.
///   2. Add member's use_count_delta / score_delta to the survivor row.
///   3. Reassign the member's citations to the survivor.
///   4. Delete the member's FTS row so it stops appearing in lexical retrieval.
///   5. Remove the member from the ANN index (embeddings feature only).
///
/// The member row is intentionally NOT invalidated — `blame` can still see
/// it and trace it to its survivor via `superseded_by`.
///
/// This is the single canonical projection path used by BOTH the live
/// consolidation path (via `apply_events`) and `rebuild_in_place` (replay),
/// so the two can never drift.
fn apply_memory_superseded(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let Some(survivor_id) = event.payload.get("survivor_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let use_count_delta = event
        .payload
        .get("use_count_delta")
        .and_then(|v| v.as_i64())
        .unwrap_or(0);
    let score_delta = event
        .payload
        .get("score_delta")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.0);

    // Slice B: detect a concurrent-supersede conflict. If this member is already
    // superseded by a DIFFERENT survivor, two edits (typically from different
    // brains' consolidations) disagree. HLC-order replay still picks a
    // deterministic winner (the supersede applied last in HLC order — see below),
    // so brains converge; we record the collision for human review. Replay-safe:
    // sync_conflicts is a projection cleared by reset_projection and the pair is
    // canonicalized + INSERT OR IGNORE, so it records once.
    let prior_survivor: Option<String> = conn
        .query_row(
            "SELECT superseded_by FROM memories WHERE memory_id = ?1",
            params![memory_id],
            |r| r.get::<_, Option<String>>(0),
        )
        .optional()?
        .flatten();
    if let Some(prev) = prior_survivor {
        if prev != survivor_id {
            let (a, b) = if prev.as_str() < survivor_id {
                (prev.as_str(), survivor_id)
            } else {
                (survivor_id, prev.as_str())
            };
            let detected_at = ts_text(event)?;
            conn.execute(
                "INSERT OR IGNORE INTO sync_conflicts
                     (member_id, survivor_a, survivor_b, detected_at)
                 VALUES (?1, ?2, ?3, ?4)",
                params![memory_id, a, b, detected_at],
            )?;
        }
    }

    // 1. Stamp superseded_by on the member (last supersede in HLC replay order
    //    wins → deterministic survivor on every brain).
    conn.execute(
        "UPDATE memories SET superseded_by = ?2 WHERE memory_id = ?1",
        params![memory_id, survivor_id],
    )?;

    // 2. Accumulate the member's stats onto the survivor.
    if use_count_delta != 0 || score_delta != 0.0 {
        conn.execute(
            "UPDATE memories
             SET use_count       = use_count       + ?2,
                 usefulness_score = usefulness_score + ?3
             WHERE memory_id = ?1",
            params![survivor_id, use_count_delta, score_delta],
        )?;
    }

    // 3. Reassign citations from member to survivor (shared helper).
    reassign_citations_projection(conn, memory_id, survivor_id)?;

    // 4. Remove from FTS index.
    conn.execute(
        "DELETE FROM memories_fts WHERE memory_id = ?1",
        params![memory_id],
    )?;

    // 5. Remove from ANN index (embeddings feature only).
    #[cfg(feature = "embeddings")]
    crate::ann::on_supersede(conn, memory_id);

    // 5b. v2.6: and from the entity index — the member is no longer a
    //     retrievable destination, so it should not anchor new edges either.
    let _ = crate::graph::forget_entities(conn, memory_id);

    // 6. S5.2: insert a `supersedes` edge from survivor → member into the
    //    typed-edge projection table so graph-lite traversal can follow it.
    let edge_ts = ts_text(event)?;
    insert_memory_edge(conn, survivor_id, memory_id, "supersedes", &edge_ts)?;

    Ok(())
}

/// Flagship 1 / Story 1.4: project a `memory.temporal` event.
///
/// Payload fields:
///   `memory_id`  — the memory whose validity window is being stamped.
///   `valid_from` — optional RFC 3339 lower bound (inclusive). NULL = "since creation".
///   `valid_to`   — optional RFC 3339 upper bound (exclusive). NULL = "never expires".
///                  When set to a past timestamp the memory is "expired" and the
///                  default retrieval path (`valid_to IS NULL OR valid_to > now`)
///                  will exclude it.
///
/// The update is additive: only the fields present in the payload are written.
/// A `memory.temporal` event with only `valid_to` leaves `valid_from` unchanged.
fn apply_memory_temporal(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let valid_from = event
        .payload
        .get("valid_from")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let valid_to = event
        .payload
        .get("valid_to")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Build a partial update: only stamp the fields that are present in the payload.
    // Both absent → no-op (caller sent an empty event — treat gracefully).
    match (valid_from, valid_to) {
        (Some(vf), Some(vt)) => {
            conn.execute(
                "UPDATE memories SET valid_from = ?2, valid_to = ?3 WHERE memory_id = ?1",
                params![memory_id, vf, vt],
            )?;
        }
        (Some(vf), None) => {
            conn.execute(
                "UPDATE memories SET valid_from = ?2 WHERE memory_id = ?1",
                params![memory_id, vf],
            )?;
        }
        (None, Some(vt)) => {
            conn.execute(
                "UPDATE memories SET valid_to = ?2 WHERE memory_id = ?1",
                params![memory_id, vt],
            )?;
        }
        (None, None) => {} // no-op
    }
    crate::fact_store::refresh(conn, memory_id)?;
    Ok(())
}

/// Flagship 1 / Story 1.4: programmatic API for stamping a memory's temporal
/// validity window.
///
/// Emits a `memory.temporal` event into the event log (so the action is
/// rebuild-safe and replay-correct) and applies it immediately by projecting
/// it into the `memories` table.
///
/// Used by the bench seeder (`brain_bench_single`) and will be used by
/// Flagship 1 Pass B (resolution) once it is implemented.
///
/// `valid_from` and `valid_to` are RFC 3339 / ISO-8601 strings. Pass `None`
/// to leave a bound unchanged.
pub fn mark_memory_temporal(
    conn: &Connection,
    memory_id: &str,
    valid_from: Option<&str>,
    valid_to: Option<&str>,
) -> KimetsuResult<()> {
    // Build a synthetic event to go through the standard projection path.
    // We use a throwaway RunId (zero ULID) since this is an out-of-band
    // operation (not part of a live agent run).
    use kimetsu_core::ids::RunId;
    let run_id = RunId::new();
    let mut payload = serde_json::json!({ "memory_id": memory_id });
    if let Some(vf) = valid_from {
        payload["valid_from"] = serde_json::Value::String(vf.to_string());
    }
    if let Some(vt) = valid_to {
        payload["valid_to"] = serde_json::Value::String(vt.to_string());
    }
    let event = kimetsu_core::event::Event::new(run_id, "memory.temporal", payload);
    // Use apply_event so the event is persisted AND projected in one step.
    apply_event(conn, &event)
}

/// #2 knowledge graph: project a `memory.edge` event into `memory_edges`.
///
/// Payload fields:
///   `src_id`    — source memory id.
///   `dst_id`    — destination memory id.
///   `edge_type` — relation kind (e.g. `"relates_to"`, `"refines"`).
///
/// A missing/malformed payload no-ops (best-effort, matching the other memory
/// projectors). The `OR IGNORE` insert makes replay idempotent.
fn apply_memory_edge(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(src_id) = event.payload.get("src_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let Some(dst_id) = event.payload.get("dst_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let Some(edge_type) = event.payload.get("edge_type").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    // Never self-loop.
    if src_id == dst_id {
        return Ok(());
    }
    let edge_ts = ts_text(event)?;
    insert_memory_edge(conn, src_id, dst_id, edge_type, &edge_ts)
}

/// #2 knowledge graph: programmatic API for writing a batch of typed relation
/// edges. Each `(src_id, dst_id, edge_type)` is emitted as a `memory.edge` event
/// (so the action is rebuild-safe — replay reconstructs the edges) and projected
/// into `memory_edges` in a single transaction via `apply_events`.
///
/// Self-loops (`src == dst`) are skipped. Returns the number of edges written.
/// Used by `kimetsu brain graph build`.
pub fn add_memory_edges(
    conn: &Connection,
    edges: &[(String, String, String)],
) -> KimetsuResult<usize> {
    use kimetsu_core::ids::RunId;
    let run_id = RunId::new();
    let mut events = Vec::with_capacity(edges.len());
    let mut written = 0usize;
    for (src_id, dst_id, edge_type) in edges {
        if src_id == dst_id {
            continue;
        }
        let payload = serde_json::json!({
            "src_id": src_id,
            "dst_id": dst_id,
            "edge_type": edge_type,
        });
        events.push(kimetsu_core::event::Event::new(
            run_id,
            "memory.edge",
            payload,
        ));
        written += 1;
    }
    apply_events(conn, &events)?;
    Ok(written)
}

/// S5.2: insert a typed edge into `memory_edges`.
///
/// This is the **single canonical path** for writing to `memory_edges`.
/// Call it from any projector that wants to populate an edge type.
///
/// Currently populated edge types:
///   * `"supersedes"` — populated here by `apply_memory_superseded`.
///
/// Reserved edge types (populated by Flagship 1 / Story 1.7):
///   * `"refines"`          — memory A refines / narrows memory B.
///   * `"dead_end_of"`      — task outcome closes a dead-end chain.
///   * `"decision_touches"` — decision memory touches a file path.
///   * `"lesson_from"`      — lesson memory derived from a source memory.
///
/// The INSERT is `OR IGNORE` so replaying the same event twice is safe.
pub(crate) fn insert_memory_edge(
    conn: &Connection,
    src_id: &str,
    dst_id: &str,
    edge_type: &str,
    created_at: &str,
) -> KimetsuResult<()> {
    conn.execute(
        "INSERT OR IGNORE INTO memory_edges (src_id, dst_id, edge_type, created_at)
         VALUES (?1, ?2, ?3, ?4)",
        params![src_id, dst_id, edge_type, created_at],
    )?;
    Ok(())
}

/// Shared citation-reassignment helper used by both the live consolidation
/// path and the replay path (`apply_memory_superseded`).  Keeping a single
/// implementation prevents the two paths from drifting.
///
/// Copies every `memory_citations` row from `from_id` to `to_id`
/// (INSERT OR IGNORE — skip conflicts), then deletes the originals.
pub(crate) fn reassign_citations_projection(
    conn: &Connection,
    from_id: &str,
    to_id: &str,
) -> KimetsuResult<()> {
    // Collect existing citations for `from_id`.
    let rows: Vec<(String, i64, String, Option<String>)> = {
        let mut stmt = conn.prepare(
            "SELECT run_id, turn, cited_at, rationale
             FROM memory_citations WHERE memory_id = ?1",
        )?;
        stmt.query_map(params![from_id], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, i64>(1)?,
                r.get::<_, String>(2)?,
                r.get::<_, Option<String>>(3)?,
            ))
        })?
        .collect::<Result<_, _>>()?
    };

    for (run_id, turn, cited_at, rationale) in &rows {
        conn.execute(
            "INSERT OR IGNORE INTO memory_citations
             (run_id, memory_id, turn, cited_at, rationale)
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![run_id, to_id, turn, cited_at, rationale],
        )?;
    }

    conn.execute(
        "DELETE FROM memory_citations WHERE memory_id = ?1",
        params![from_id],
    )?;

    Ok(())
}

pub fn ensure_schema(conn: &Connection) -> KimetsuResult<()> {
    schema::initialize(conn)
}

fn ts_text(event: &Event) -> KimetsuResult<String> {
    Ok(event.ts.format(&Rfc3339)?)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use kimetsu_core::event::Event;
    use kimetsu_core::ids::RunId;
    use rusqlite::{Connection, params};
    use serde_json::json;

    use super::{apply_events, rebuild_in_place, upcast_event};
    use crate::schema;

    fn make_conn() -> Connection {
        let conn = Connection::open_in_memory().expect("open_in_memory");
        schema::initialize(&conn).expect("schema::initialize");
        conn
    }

    #[test]
    fn rebuild_import_failure_preserves_existing_projection() {
        let conn = make_conn();
        let accepted = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({
                "memory_id":"kept", "text":"keep my evidence", "scope":"project", "kind":"fact"
            }),
        );
        apply_events(&conn, &[accepted]).unwrap();
        let malformed = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({
                "memory_id":"broken", "text":"bad validity", "scope":"project", "kind":"fact", "valid_from":"nonsense"
            }),
        );
        assert!(super::rebuild(&conn, &[malformed]).is_err());
        let text: String = conn
            .query_row(
                "SELECT text FROM memories WHERE memory_id='kept'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(text, "keep my evidence");
    }

    #[test]
    fn rebuild_import_keeps_durable_events_missing_from_trace() {
        let conn = make_conn();
        let accepted = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({
                "memory_id":"kept", "text":"durable but not in trace", "scope":"project", "kind":"fact"
            }),
        );
        apply_events(&conn, &[accepted]).unwrap();
        super::rebuild(&conn, &[]).unwrap();
        assert_eq!(
            conn.query_row(
                "SELECT count(*) FROM memories WHERE memory_id='kept'",
                [],
                |r| r.get::<_, i64>(0)
            )
            .unwrap(),
            1
        );
    }

    #[test]
    fn trace_import_binds_historical_exposure_before_later_correction() {
        let conn = make_conn();
        let accepted = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({
                "memory_id":"m", "text":"old claim", "scope":"project", "kind":"fact"
            }),
        );
        apply_events(&conn, std::slice::from_ref(&accepted)).unwrap();
        let original_revision = super::claim_revision_at(&conn, "m", None).unwrap();
        let exposure = Event::new(
            RunId::new(),
            "context.injected",
            json!({"memory_ids":["m"]}),
        );
        let corrected = Event::new(
            RunId::new(),
            "memory.corrected",
            json!({"memory_id":"m", "text":"new claim"}),
        );
        apply_events(&conn, &[corrected]).unwrap();
        super::rebuild(&conn, std::slice::from_ref(&exposure)).unwrap();
        for _ in 0..2 {
            let revision: String = conn.query_row("SELECT json_extract(payload_json,'$.memory_revisions.m') FROM events WHERE event_id=?1", [exposure.event_id.to_string()], |r|r.get(0)).unwrap();
            assert_eq!(revision, original_revision);
            rebuild_in_place(&conn).unwrap();
        }
    }

    #[test]
    fn trace_import_replays_missing_correction_before_later_invalidation() {
        let conn = make_conn();
        let accepted = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({
                "memory_id":"m", "text":"old claim", "scope":"project", "kind":"fact"
            }),
        );
        apply_events(&conn, &[accepted]).unwrap();
        let correction = Event::new(
            RunId::new(),
            "memory.corrected",
            json!({"memory_id":"m", "text":"historically corrected"}),
        );
        let invalidated = Event::new(
            RunId::new(),
            "memory.invalidated",
            json!({"memory_id":"m", "reason":"retired"}),
        );
        apply_events(&conn, &[invalidated]).unwrap();
        super::rebuild(&conn, &[correction]).unwrap();
        for _ in 0..2 {
            let row: (String, bool) = conn
                .query_row(
                    "SELECT text,invalidated_at IS NOT NULL FROM memories WHERE memory_id='m'",
                    [],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )
                .unwrap();
            assert_eq!(row, ("historically corrected".into(), true));
            rebuild_in_place(&conn).unwrap();
        }
    }

    #[test]
    fn rebuild_refuses_to_erase_unlogged_legacy_user_memory() {
        let conn = make_conn();
        conn.execute("INSERT INTO memories(memory_id,scope,kind,text,normalized_text,confidence,provenance_snapshot_json,created_at) VALUES ('legacy','global_user','fact','original','original',0.7,'{\"source\":\"user_brain\"}','2020-01-01T00:00:00Z')", []).unwrap();
        let error = rebuild_in_place(&conn).unwrap_err();
        assert!(error.to_string().contains("absent from replay"));
        assert_eq!(
            conn.query_row(
                "SELECT text FROM memories WHERE memory_id='legacy'",
                [],
                |r| r.get::<_, String>(0)
            )
            .unwrap(),
            "original"
        );
        assert!(super::rebuild(&conn, &[]).is_err());
    }

    #[test]
    fn rebuild_reads_events_after_acquiring_writer_lock() {
        use std::sync::atomic::{AtomicBool, Ordering};
        static WAITING: AtomicBool = AtomicBool::new(false);
        fn busy(_: i32) -> bool {
            WAITING.store(true, Ordering::SeqCst);
            std::thread::sleep(std::time::Duration::from_millis(1));
            true
        }
        WAITING.store(false, Ordering::SeqCst);
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("rebuild.db");
        let writer = Connection::open(&path).unwrap();
        schema::initialize(&writer).unwrap();
        writer.execute_batch("PRAGMA journal_mode=WAL").unwrap();
        let rebuilding = Connection::open(&path).unwrap();
        rebuilding.busy_handler(Some(busy)).unwrap();
        writer.execute_batch("BEGIN IMMEDIATE").unwrap();
        let event = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({
                "memory_id":"concurrent", "text":"committed while rebuild waits", "scope":"project", "kind":"fact"
            }),
        );
        super::apply_event(&writer, &event).unwrap();
        let worker =
            std::thread::spawn(move || rebuild_in_place(&rebuilding).map_err(|e| e.to_string()));
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !WAITING.load(Ordering::SeqCst) && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        let was_waiting = WAITING.load(Ordering::SeqCst);
        writer.execute_batch("COMMIT").unwrap();
        assert!(
            was_waiting,
            "rebuild did not reach the contested write lock"
        );
        assert_eq!(worker.join().unwrap().unwrap(), 1);
        assert_eq!(
            writer
                .query_row(
                    "SELECT count(*) FROM memories WHERE memory_id='concurrent'",
                    [],
                    |r| r.get::<_, i64>(0)
                )
                .unwrap(),
            1
        );
    }

    fn make_event(run_id: RunId, kind: &str, payload: serde_json::Value) -> Event {
        Event::new(run_id, kind, payload)
    }

    /// Legacy nil run identity used by manual regression fixtures.
    fn sentinel_run() -> RunId {
        RunId(ulid::Ulid::nil())
    }

    // ------------------------------------------------------------------
    // v2.6 #3: concurrent writers to ONE on-disk brain.db must not lose
    // updates. Independent Connections behave like independent processes for
    // SQLite locking, so this exercises the IMMEDIATE-transaction + busy-retry
    // write path under real contention.
    // ------------------------------------------------------------------
    #[test]
    fn concurrent_manual_regrets_lose_no_updates() {
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::sync::{Arc, Barrier};

        static CTR: AtomicU64 = AtomicU64::new(0);
        let n = CTR.fetch_add(1, Ordering::Relaxed);
        let db_path =
            std::env::temp_dir().join(format!("kimetsu-concurrency-{}-{n}.db", std::process::id()));
        let _ = std::fs::remove_file(&db_path);

        // Seed one accepted memory (use_count starts at 0).
        let mem_id = "mem-concurrency";
        {
            let conn = Connection::open(&db_path).expect("open seed");
            schema::initialize(&conn).expect("init seed");
            let accepted = Event::new(
                sentinel_run(),
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "hammer me",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            );
            apply_events(&conn, std::slice::from_ref(&accepted)).expect("seed accepted");
        }

        const THREADS: usize = 6;
        const CITES_PER_THREAD: usize = 25;
        let barrier = Arc::new(Barrier::new(THREADS));
        let path = Arc::new(db_path.clone());

        let mut handles = Vec::new();
        for _ in 0..THREADS {
            let b = Arc::clone(&barrier);
            let p = Arc::clone(&path);
            handles.push(std::thread::spawn(move || {
                // Each thread = its own connection (≈ its own process).
                let conn = Connection::open(&*p).expect("open writer");
                schema::initialize(&conn).expect("init writer");
                b.wait(); // maximize contention
                for _ in 0..CITES_PER_THREAD {
                    let cited = Event::new(
                        sentinel_run(),
                        "retrieval.regret",
                        json!({ "memory_id": mem_id, "source": "manual" }),
                    );
                    // Must not error under contention (busy-retry + IMMEDIATE).
                    apply_events(&conn, std::slice::from_ref(&cited))
                        .expect("concurrent explicit regret must succeed");
                }
            }));
        }
        for h in handles {
            h.join().expect("thread join");
        }

        let expected = (THREADS * CITES_PER_THREAD) as i64;

        let conn = Connection::open(&db_path).expect("open verify");
        schema::initialize(&conn).expect("init verify");

        // No lost increments: every concurrent explicit regret landed.
        let use_count: i64 = conn
            .query_row(
                "SELECT use_count FROM memories WHERE memory_id = ?1",
                params![mem_id],
                |r| r.get(0),
            )
            .expect("read use_count");
        assert_eq!(
            use_count, expected,
            "lost updates under concurrency: got {use_count}, expected {expected}"
        );

        // All events durably appended (1 accepted + N*M cited).
        let event_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .expect("count events");
        assert_eq!(event_count, expected + 1, "missing durable events");

        // Rebuild is deterministic: replay reproduces the same use_count.
        rebuild_in_place(&conn).expect("rebuild");
        let after: i64 = conn
            .query_row(
                "SELECT use_count FROM memories WHERE memory_id = ?1",
                params![mem_id],
                |r| r.get(0),
            )
            .expect("read use_count after rebuild");
        assert_eq!(after, expected, "rebuild changed the projected use_count");

        drop(conn);
        let _ = std::fs::remove_file(&db_path);
        // WAL sidecars.
        let _ = std::fs::remove_file(db_path.with_extension("db-wal"));
        let _ = std::fs::remove_file(db_path.with_extension("db-shm"));
    }

    #[test]
    fn event_carries_and_roundtrips_origin() {
        use super::{insert_event, read_events_ordered};

        let conn = make_conn();
        kimetsu_core::event::set_process_origin("test-machine/unit");

        let ev = Event::new(
            sentinel_run(),
            "memory.accepted",
            json!({
                "memory_id": "m-origin",
                "text": "with origin",
                "scope": "global_user",
                "kind": "fact"
            }),
        );
        // process_origin() is a OnceLock — first setter wins; assert the event
        // carries SOME origin and that it round-trips through the events table.
        let stamped = ev.origin.clone();
        insert_event(&conn, &ev).expect("insert");
        let read_back = read_events_ordered(&conn).expect("read");
        assert_eq!(read_back.len(), 1);
        assert_eq!(read_back[0].origin, stamped, "origin must round-trip");
    }

    // ------------------------------------------------------------------
    // A6-1. upcast_event is identity (Cow::Borrowed) at schema_version 1
    // ------------------------------------------------------------------
    #[test]
    fn upcast_is_identity_at_v1() {
        let run_id = RunId::new();
        let event = make_event(
            run_id,
            "run.started",
            json!({"project_id": "p1", "task": "t"}),
        );
        assert_eq!(
            event.schema_version, 1,
            "Event::new must stamp schema_version=1"
        );

        let cow = upcast_event(&event);
        // Must be a Borrowed reference, not an owned clone.
        assert!(
            matches!(cow, Cow::Borrowed(_)),
            "upcast_event must return Cow::Borrowed for current schema_version"
        );
        // The payload fields must be unchanged.
        let out = cow.as_ref();
        assert_eq!(out.kind, event.kind);
        assert_eq!(out.schema_version, event.schema_version);
        assert_eq!(out.payload, event.payload);
    }

    // ------------------------------------------------------------------
    // A6-2. Per-kind missing-field durability: every dispatched kind with
    // an empty payload replays without panic/error.
    // ------------------------------------------------------------------

    fn assert_empty_payload_ok(kind: &str) {
        let conn = make_conn();
        let run_id = RunId::new();
        let event = make_event(run_id, kind, json!({}));
        let result = apply_events(&conn, &[event]);
        assert!(
            result.is_ok(),
            "apply_events with empty payload for kind={kind:?} must return Ok(()), got: {result:?}"
        );
    }

    #[test]
    fn empty_payload_run_started() {
        assert_empty_payload_ok("run.started");
    }

    #[test]
    fn empty_payload_run_finished() {
        assert_empty_payload_ok("run.finished");
    }

    #[test]
    fn empty_payload_run_failed() {
        assert_empty_payload_ok("run.failed");
    }

    #[test]
    fn empty_payload_run_aborted() {
        assert_empty_payload_ok("run.aborted");
    }

    #[test]
    fn empty_payload_memory_accepted() {
        assert_empty_payload_ok("memory.accepted");
    }

    #[test]
    fn empty_payload_memory_proposed() {
        assert_empty_payload_ok("memory.proposed");
    }

    #[test]
    fn empty_payload_memory_rejected() {
        assert_empty_payload_ok("memory.rejected");
    }

    #[test]
    fn empty_payload_memory_invalidated() {
        assert_empty_payload_ok("memory.invalidated");
    }

    #[test]
    fn empty_payload_memory_cited() {
        assert_empty_payload_ok("memory.cited");
    }

    // F1: empty payload work.episode must not panic/error.
    #[test]
    fn empty_payload_work_episode() {
        assert_empty_payload_ok("work.episode");
    }

    // F1A: empty payload memory.temporal must not panic/error.
    #[test]
    fn empty_payload_memory_temporal() {
        assert_empty_payload_ok("memory.temporal");
    }

    // ------------------------------------------------------------------
    // A6-3. A well-formed run.started event still projects correctly
    // after routing through the upcast seam.
    // ------------------------------------------------------------------
    #[test]
    fn well_formed_run_started_projects_correctly() {
        let conn = make_conn();
        let run_id = RunId::new();
        let event = make_event(
            run_id,
            "run.started",
            json!({
                "project_id": "proj-abc",
                "task": "fix the bug",
                "model": "claude-sonnet-4-6"
            }),
        );
        apply_events(&conn, &[event])
            .expect("apply_events must succeed for well-formed run.started");

        let row: (String, String, String) = conn
            .query_row(
                "SELECT run_id, project_id, task FROM runs WHERE run_id = ?1",
                [run_id.to_string()],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
            )
            .expect("runs row must exist after apply_events");

        assert_eq!(row.0, run_id.to_string());
        assert_eq!(row.1, "proj-abc");
        assert_eq!(row.2, "fix the bug");
    }

    // ------------------------------------------------------------------
    // W1.1: reset_projection keeps the events table intact while wiping
    // all derived/projected tables.
    // ------------------------------------------------------------------
    #[test]
    fn reset_projection_keeps_events() {
        use super::reset_projection;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-reset-test";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "hello",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        // Preconditions: both events stored, memory projected.
        let event_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert!(event_count > 0, "events must be stored before reset");
        let mem_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .unwrap();
        assert_eq!(mem_count, 1, "memory must be projected before reset");

        reset_projection(&conn).expect("reset_projection");

        // Events MUST survive.
        let event_count_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            event_count_after, event_count,
            "reset_projection must NOT delete from events"
        );

        // All derived tables must be empty.
        let memories_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            memories_after, 0,
            "memories must be cleared by reset_projection"
        );

        let runs_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM runs", [], |r| r.get(0))
            .unwrap();
        assert_eq!(runs_after, 0, "runs must be cleared by reset_projection");

        let citations_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_citations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            citations_after, 0,
            "memory_citations must be cleared by reset_projection"
        );

        let conflicts_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_conflicts", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            conflicts_after, 0,
            "memory_conflicts must be cleared by reset_projection"
        );

        // work_episodes must also be cleared.
        let episodes_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM work_episodes", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            episodes_after, 0,
            "work_episodes must be cleared by reset_projection"
        );
    }

    // ------------------------------------------------------------------
    // W1.2a: rebuild_in_place round-trips without duplicating events.
    // ------------------------------------------------------------------
    #[test]
    fn rebuild_in_place_no_dup_events() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-dup-test";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "no dup",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            ),
            make_event(run_id, "run.finished", json!({"total_cost_usd": 0.01})),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let event_count_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(event_count_before, 3, "expected 3 events seeded");

        // Manually wipe derived tables to simulate a corrupted projection.
        conn.execute_batch("DELETE FROM memories; DELETE FROM memories_fts;")
            .unwrap();
        let mem_count_wiped: i64 = conn
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .unwrap();
        assert_eq!(mem_count_wiped, 0, "memories wiped before rebuild_in_place");

        let replayed = rebuild_in_place(&conn).expect("rebuild_in_place");

        // Correct replay count.
        assert_eq!(
            replayed, 3,
            "rebuild_in_place must return the number of events replayed"
        );

        // Memory is back.
        let mem_exists: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(
            mem_exists, 1,
            "memory must be re-projected after rebuild_in_place"
        );

        // NO duplicate events inserted.
        let event_count_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            event_count_after, event_count_before,
            "rebuild_in_place must NOT insert duplicate events"
        );
    }

    // ------------------------------------------------------------------
    // W1.2b: rebuild_in_place reconstructs memory_citations (proves
    // project_event runs the full dispatch including memory.cited).
    // ------------------------------------------------------------------
    #[test]
    fn rebuild_in_place_reconstructs_citations() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-cite-test";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "cite me",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            ),
            make_event(
                run_id,
                "memory.cited",
                json!({
                    "memory_id": mem_id,
                    "turn": 2,
                    "rationale": "relevant context"
                }),
            ),
            make_event(run_id, "run.finished", json!({"total_cost_usd": 0.0})),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let citations_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_citations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            citations_before, 1,
            "citation must exist after apply_events"
        );

        let replayed = rebuild_in_place(&conn).expect("rebuild_in_place");
        assert_eq!(replayed, 4, "expected 4 events replayed");

        let citations_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_citations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            citations_after, 1,
            "memory_citations must be repopulated by rebuild_in_place"
        );
    }

    #[test]
    fn add_memory_edges_writes_and_survives_rebuild() {
        use super::{add_memory_edges, rebuild_in_place};

        let conn = make_conn();
        let run_id = RunId::new();
        let m1 = "mem-edge-a";
        let m2 = "mem-edge-b";

        let events = vec![
            make_event(
                run_id,
                "memory.accepted",
                json!({"memory_id": m1, "text": "alpha", "scope": "global_user", "kind": "fact"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({"memory_id": m2, "text": "beta", "scope": "global_user", "kind": "fact"}),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        // Self-loop is skipped; a real edge is written.
        let written = add_memory_edges(
            &conn,
            &[
                (m1.to_string(), m1.to_string(), "relates_to".to_string()),
                (m1.to_string(), m2.to_string(), "relates_to".to_string()),
            ],
        )
        .expect("add_memory_edges");
        assert_eq!(
            written, 1,
            "self-loop must be skipped, one real edge written"
        );

        let edge_count = |c: &Connection| -> i64 {
            c.query_row(
                "SELECT COUNT(*) FROM memory_edges WHERE src_id=?1 AND dst_id=?2 AND edge_type='relates_to'",
                params![m1, m2],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(edge_count(&conn), 1, "edge present after write");

        // Rebuild from the durable log: the edge is re-derived (replayed event).
        let total_edges_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_edges", [], |r| r.get(0))
            .unwrap();
        rebuild_in_place(&conn).expect("rebuild_in_place");
        let total_edges_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_edges", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            total_edges_before, total_edges_after,
            "rebuild must reproduce exactly the same edge set"
        );
        assert_eq!(edge_count(&conn), 1, "edge survives rebuild_in_place");
    }

    // ------------------------------------------------------------------
    // W1.2c: Event reconstruction fidelity — after rebuild_in_place the
    // projected memory's text/scope/kind match the original.
    // ------------------------------------------------------------------
    #[test]
    fn memory_proposed_redacts_event_and_projection_payloads() {
        let conn = make_conn();
        let run_id = RunId::new();
        let secret = "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv0123456789AbCdEf";
        let event = make_event(
            run_id,
            "memory.proposed",
            json!({
                "proposal_id": "prop-redact",
                "scope": "project",
                "kind": "fact",
                "text": format!("lesson uses {secret}"),
                "rationale": format!("model repeated {secret}"),
                "proposed_confidence": 0.5,
                "source_event_ids": [],
            }),
        );
        apply_events(&conn, &[event]).expect("apply_events");

        let payload: String = conn
            .query_row(
                "SELECT payload_json FROM events WHERE kind = 'memory.proposed'",
                [],
                |r| r.get(0),
            )
            .expect("event payload");
        assert!(!payload.contains(secret), "event leaked secret: {payload}");
        assert!(payload.contains("[REDACTED:anthropic_oauth]"));

        let row: (String, String) = conn
            .query_row(
                "SELECT text, rationale FROM memory_proposals WHERE proposal_id = 'prop-redact'",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .expect("proposal row");
        assert!(!row.0.contains(secret), "proposal text leaked: {}", row.0);
        assert!(
            !row.1.contains(secret),
            "proposal rationale leaked: {}",
            row.1
        );
    }

    #[test]
    fn memory_cited_redacts_event_and_projection_rationale() {
        let conn = make_conn();
        let run_id = RunId::new();
        let secret = "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv0123456789AbCdEf";
        let event = make_event(
            run_id,
            "memory.cited",
            json!({
                "memory_id": "mem-redact",
                "turn": 1,
                "rationale": format!("used because output showed {secret}"),
            }),
        );
        apply_events(&conn, &[event]).expect("apply_events");

        let payload: String = conn
            .query_row(
                "SELECT payload_json FROM events WHERE kind = 'memory.cited'",
                [],
                |r| r.get(0),
            )
            .expect("event payload");
        assert!(!payload.contains(secret), "event leaked secret: {payload}");
        assert!(payload.contains("[REDACTED:anthropic_oauth]"));

        let rationale: String = conn
            .query_row(
                "SELECT rationale FROM memory_citations WHERE memory_id = 'mem-redact'",
                [],
                |r| r.get(0),
            )
            .expect("citation rationale");
        assert!(
            !rationale.contains(secret),
            "citation rationale leaked: {rationale}"
        );
        assert!(rationale.contains("[REDACTED:anthropic_oauth]"));
    }

    // ------------------------------------------------------------------
    // F1A: memory.temporal event stamps valid_from/valid_to and survives
    // rebuild_in_place (rebuild-safe).
    // ------------------------------------------------------------------
    #[test]
    fn memory_temporal_stamps_validity_and_survives_rebuild() {
        use super::{mark_memory_temporal, rebuild_in_place};

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-temporal-test";

        let events = vec![make_event(
            run_id,
            "memory.accepted",
            json!({
                "memory_id": mem_id,
                "text": "old fact that expired",
                "scope": "project",
                "kind": "fact",
                "confidence": 0.9
            }),
        )];
        apply_events(&conn, &events).expect("apply_events");

        // Stamp valid_to to a past timestamp (expired).
        mark_memory_temporal(
            &conn,
            mem_id,
            Some("2020-01-01T00:00:00Z"),
            Some("2025-01-01T00:00:00Z"),
        )
        .expect("mark_memory_temporal");

        // Verify both columns are set.
        let (vf, vt): (Option<String>, Option<String>) = conn
            .query_row(
                "SELECT valid_from, valid_to FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .expect("query valid_from/valid_to");
        assert_eq!(
            vf.as_deref(),
            Some("2020-01-01T00:00:00Z"),
            "valid_from must be set"
        );
        assert_eq!(
            vt.as_deref(),
            Some("2025-01-01T00:00:00Z"),
            "valid_to must be set"
        );

        // Rebuild in-place: temporal state must be restored from the event log.
        rebuild_in_place(&conn).expect("rebuild_in_place");

        let (vf2, vt2): (Option<String>, Option<String>) = conn
            .query_row(
                "SELECT valid_from, valid_to FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .expect("query valid_from/valid_to after rebuild");
        assert_eq!(
            vf2.as_deref(),
            Some("2020-01-01T00:00:00Z"),
            "valid_from must survive rebuild_in_place"
        );
        assert_eq!(
            vt2.as_deref(),
            Some("2025-01-01T00:00:00Z"),
            "valid_to must survive rebuild_in_place"
        );
    }

    #[test]
    fn rebuild_in_place_payload_fidelity() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-fidelity-test";
        let expected_text = "Rust edition 2024 requires explicit use of `use` for trait impls";
        let expected_scope = "project";
        let expected_kind = "guideline";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": expected_text,
                    "scope": expected_scope,
                    "kind": expected_kind,
                    "confidence": 0.9
                }),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        // Wipe derived tables to force a full rebuild.
        conn.execute_batch("DELETE FROM memories; DELETE FROM memories_fts; DELETE FROM runs;")
            .unwrap();

        rebuild_in_place(&conn).expect("rebuild_in_place");

        let row: (String, String, String) = conn
            .query_row(
                "SELECT text, scope, kind FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
            )
            .expect("memory must exist after rebuild_in_place");

        assert_eq!(row.0, expected_text, "text must round-trip through rebuild");
        assert_eq!(
            row.1, expected_scope,
            "scope must round-trip through rebuild"
        );
        assert_eq!(row.2, expected_kind, "kind must round-trip through rebuild");
    }

    // ------------------------------------------------------------------
    // Flagship 2 / Story 2.1: importance scoring at write time
    // ------------------------------------------------------------------

    /// Story 2.1: a memory.accepted event carrying `initial_usefulness` seeds
    /// the memory's usefulness_score (rebuild-safe), so a salient new memory
    /// outranks a freshly-added neutral one with score 0.
    #[test]
    fn initial_usefulness_seeds_score_and_survives_rebuild() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();

        let events = vec![
            // Salient: failure_pattern seeded at 0.3.
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": "salient",
                    "text": "rm -rf node_modules then reinstall fixes the EBUSY lock",
                    "scope": "project",
                    "kind": "failure_pattern",
                    "confidence": 1.0,
                    "initial_usefulness": 0.3
                }),
            ),
            // Neutral: no initial_usefulness field → default 0.0 (back-compat).
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": "neutral",
                    "text": "the readme mentions a port number",
                    "scope": "project",
                    "kind": "fact",
                    "confidence": 1.0
                }),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let read = |id: &str| -> f64 {
            conn.query_row(
                "SELECT usefulness_score FROM memories WHERE memory_id = ?1",
                [id],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert!(
            (read("salient") - 0.3).abs() < 1e-6,
            "salient memory must be seeded to 0.3"
        );
        assert!(
            read("neutral").abs() < 1e-6,
            "memory without initial_usefulness must default to 0.0"
        );
        assert!(
            read("salient") > read("neutral"),
            "salient new memory must outrank a neutral one from day one"
        );

        // Rebuild-safe: the seed is in the event payload, so it survives replay.
        conn.execute_batch("DELETE FROM memories; DELETE FROM memories_fts;")
            .unwrap();
        rebuild_in_place(&conn).expect("rebuild_in_place");
        assert!(
            (read("salient") - 0.3).abs() < 1e-6,
            "initial_usefulness seed must survive rebuild"
        );
    }

    // ------------------------------------------------------------------
    // Flagship 2 / Story 2.4: confidence calibration from outcomes
    // ------------------------------------------------------------------

    /// Run a full cycle that injects + cites `mem_id`, then terminates with
    /// `terminal_kind` ("run.finished" or "run.failed"). Returns the memory's
    /// confidence afterward.
    fn cite_and_terminate_confidence(terminal_kind: &str) -> (Connection, f64) {
        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "cal-mem";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "use lld linker on windows",
                    "scope": "project",
                    "kind": "convention",
                    "confidence": 0.7
                }),
            ),
            // Mark it as retrieved so usefulness/confidence attribution fires.
            make_event(
                run_id,
                "context.injected",
                json!({"stage": "loc", "memory_ids": [mem_id], "used_tokens": 100}),
            ),
            // Explicitly cited so it earns the strong (cited) confidence update.
            make_event(
                run_id,
                "memory.cited",
                json!({"memory_id": mem_id, "turn": 1}),
            ),
            make_event(run_id, terminal_kind, json!({"total_cost_usd": 0.0})),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let conf: f64 = conn
            .query_row(
                "SELECT confidence FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| r.get(0),
            )
            .unwrap();
        (conn, conf)
    }

    /// v2.5.1: the cited-in-failure penalty is scaled by citation history.
    /// A memory with a positive track record absorbs an unlucky failed run
    /// (flaky verification etc.); an unproven memory takes the full hit.
    #[test]
    fn failure_penalty_scales_with_prior_citations() {
        let conn = make_conn();

        // Two memories: "proven" accumulates 3 successful cited runs first.
        for (id, text) in [
            ("proven", "use lld on windows"),
            ("rookie", "try the new flag"),
        ] {
            apply_events(
                &conn,
                &[make_event(
                    RunId::new(),
                    "memory.accepted",
                    json!({"memory_id": id, "text": text, "scope": "project", "kind": "convention", "confidence": 0.7}),
                )],
            )
            .unwrap();
        }
        for _ in 0..3 {
            let run = RunId::new();
            apply_events(
                &conn,
                &[
                    make_event(run, "run.started", json!({"project_id": "p", "task": "t"})),
                    make_event(
                        run,
                        "context.injected",
                        json!({"stage": "loc", "memory_ids": ["proven"], "used_tokens": 50}),
                    ),
                    make_event(
                        run,
                        "memory.cited",
                        json!({"memory_id": "proven", "turn": 1}),
                    ),
                    make_event(run, "run.finished", json!({"outcome": "ok"})),
                ],
            )
            .unwrap();
        }

        let score = |id: &str| -> f64 {
            conn.query_row(
                "SELECT usefulness_score FROM memories WHERE memory_id = ?1",
                [id],
                |r| r.get(0),
            )
            .unwrap()
        };
        let proven_before = score("proven");
        let rookie_before = score("rookie");

        // One failing (non-Gate) run where BOTH are injected and cited.
        let fail_run = RunId::new();
        apply_events(
            &conn,
            &[
                make_event(
                    fail_run,
                    "run.started",
                    json!({"project_id": "p", "task": "t"}),
                ),
                make_event(
                    fail_run,
                    "context.injected",
                    json!({"stage": "loc", "memory_ids": ["proven", "rookie"], "used_tokens": 80}),
                ),
                make_event(
                    fail_run,
                    "memory.cited",
                    json!({"memory_id": "proven", "turn": 1}),
                ),
                make_event(
                    fail_run,
                    "memory.cited",
                    json!({"memory_id": "rookie", "turn": 1}),
                ),
                make_event(
                    fail_run,
                    "run.failed",
                    json!({"category": "Verification", "message": "flaky test"}),
                ),
            ],
        )
        .unwrap();

        let proven_drop = proven_before - score("proven");
        let rookie_drop = rookie_before - score("rookie");
        assert!(
            (rookie_drop - 1.0).abs() < 1e-6,
            "unproven memory takes the full -1.0, got -{rookie_drop}"
        );
        assert!(
            proven_drop < rookie_drop,
            "3 prior citations must shrink the penalty: proven -{proven_drop} vs rookie -{rookie_drop}"
        );
        // effective = 1.0 / (1 + 3/3) = 0.5
        assert!(
            (proven_drop - 0.5).abs() < 1e-6,
            "penalty with 3 priors must be -0.5, got -{proven_drop}"
        );
    }

    /// Story 2.4 (headline): a cited memory in a successful run ends with
    /// HIGHER confidence than one in a failed run, and the calibrated value
    /// is reproduced exactly after rebuild_in_place.
    #[test]
    fn confidence_calibration_rewards_success_and_survives_rebuild() {
        use super::rebuild_in_place;

        let (success_conn, success_conf) = cite_and_terminate_confidence("run.finished");
        let (_fail_conn, fail_conf) = cite_and_terminate_confidence("run.failed");

        // Started at 0.7. Success nudges toward 1.0; failure toward 0.0.
        assert!(
            success_conf > 0.7,
            "successful citation must raise confidence above 0.7, got {success_conf}"
        );
        assert!(
            fail_conf < 0.7,
            "failed citation must lower confidence below 0.7, got {fail_conf}"
        );
        assert!(
            success_conf > fail_conf,
            "cited-in-success must beat cited-in-failure: {success_conf} vs {fail_conf}"
        );

        // Rebuild-safe: the calibration is derived purely from replayed events.
        let mem_id = "cal-mem";
        success_conn
            .execute_batch("DELETE FROM memories; DELETE FROM memories_fts;")
            .unwrap();
        rebuild_in_place(&success_conn).expect("rebuild_in_place");
        let post: f64 = success_conn
            .query_row(
                "SELECT confidence FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| r.get(0),
            )
            .unwrap();
        assert!(
            (post - success_conf).abs() < 1e-9,
            "calibrated confidence must reproduce after rebuild: {post} vs {success_conf}"
        );
    }
}

fn apply_memory_corrected(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let id = event
        .payload
        .get("memory_id")
        .and_then(|v| v.as_str())
        .ok_or("correction requires memory_id")?;
    if conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM memory_revisions WHERE event_id=?1)",
        params![event.event_id.to_string()],
        |r| r.get::<_, bool>(0),
    )? {
        return Ok(());
    }
    let old: Option<(String, String, Option<String>)> = conn
        .query_row(
            "SELECT text, kind, invalidated_at FROM memories WHERE memory_id=?1",
            params![id],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
        )
        .optional()?;
    let (old_text, old_kind, invalidated) = old.ok_or_else(|| format!("memory not found: {id}"))?;
    if invalidated.is_some() {
        return Err(format!("memory {id} is already invalidated").into());
    }
    let text = event.payload.get("text").and_then(|v| v.as_str());
    let kind = event.payload.get("kind").and_then(|v| v.as_str());
    if text.is_none() && kind.is_none() {
        return Err("correction requires text or kind".into());
    }
    if text.is_some_and(|t| t.trim().is_empty()) {
        return Err("correction text cannot be empty".into());
    }
    if let Some(k) = kind {
        k.parse::<kimetsu_core::memory::MemoryKind>()?;
    }
    let now = ts_text(event)?;
    let effective = event
        .payload
        .get("effective_at")
        .and_then(|v| v.as_str())
        .unwrap_or(&now);
    OffsetDateTime::parse(effective, &Rfc3339)?;
    conn.execute("INSERT OR IGNORE INTO memory_revisions (memory_id,event_id,text,kind,known_at,effective_at,confidence,use_count,usefulness_score)
        SELECT memory_id, 'baseline:' || memory_id, text,kind,created_at,COALESCE(valid_from,'0001-01-01T00:00:00Z'),confidence,use_count,usefulness_score FROM memories WHERE memory_id=?1", params![id])?;
    // Freeze accumulated evidence on the retiring revision before resetting it.
    conn.execute(
        "UPDATE memory_revisions SET
        confidence=(SELECT confidence FROM memories WHERE memory_id=?1),
        use_count=(SELECT use_count FROM memories WHERE memory_id=?1),
        usefulness_score=(SELECT usefulness_score FROM memories WHERE memory_id=?1)
        WHERE revision_id=(SELECT MAX(revision_id) FROM memory_revisions WHERE memory_id=?1)",
        params![id],
    )?;
    let changed = text.is_some_and(|t| t != old_text);
    if changed {
        conn.execute("UPDATE memories SET confidence=1.0,use_count=0,usefulness_score=0,last_used_at=NULL,last_useful_at=NULL,embedding=NULL,embedding_model=NULL WHERE memory_id=?1", params![id])?;
        conn.execute(
            "DELETE FROM memory_citations WHERE memory_id=?1",
            params![id],
        )?;
        conn.execute("DELETE FROM query_routes WHERE memory_id=?1", params![id])?;
    }
    let text = text.unwrap_or(&old_text);
    let kind = kind.unwrap_or(&old_kind);
    conn.execute(
        "UPDATE memories SET text=?2,normalized_text=?3,kind=?4 WHERE memory_id=?1",
        params![
            id,
            text,
            kimetsu_core::memory::normalize_memory_text(text),
            kind
        ],
    )?;
    conn.execute("DELETE FROM memories_fts WHERE memory_id=?1", params![id])?;
    conn.execute("INSERT INTO memories_fts(memory_id,text,kind,scope) SELECT memory_id,text,kind,scope FROM memories WHERE memory_id=?1", params![id])?;
    crate::graph::project_entities(conn, id, text)?;
    conn.execute("INSERT INTO memory_revisions (memory_id,event_id,text,kind,known_at,effective_at,confidence,use_count,usefulness_score)
        SELECT memory_id,?2,text,kind,?3,?4,confidence,use_count,usefulness_score FROM memories WHERE memory_id=?1", params![id,event.event_id.to_string(),now,effective])?;
    crate::fact_store::refresh(conn, id)?;
    Ok(())
}

#[cfg(test)]
mod correction_regressions {
    use super::*;
    fn event(kind: &str, payload: serde_json::Value, at: &str) -> Event {
        let mut e = Event::new(RunId::new(), kind, payload);
        e.ts = OffsetDateTime::parse(at, &Rfc3339).unwrap();
        e
    }
    fn seed(c: &Connection) {
        schema::initialize(c).unwrap();
        apply_events(c, &[event("memory.accepted", serde_json::json!({"memory_id":"m", "scope":"project", "kind":"fact", "text":"original quokka"}), "2026-01-01T00:00:00Z")]).unwrap();
    }
    #[test]
    fn explicit_unbound_exposure_never_credits_a_claim() {
        for corrected in [false, true] {
            for bindings in [
                serde_json::json!({}),
                serde_json::json!({"other":"baseline:other"}),
            ] {
                let c = Connection::open_in_memory().unwrap();
                seed(&c);
                if corrected {
                    apply_events(
                        &c,
                        &[event(
                            "memory.corrected",
                            serde_json::json!({"memory_id":"m","text":"new claim"}),
                            "2026-01-02T00:00:00Z",
                        )],
                    )
                    .unwrap();
                }
                let run = RunId::new();
                let mut events = vec![
                    event(
                        "run.started",
                        serde_json::json!({"project_id":"p","task":"t"}),
                        "2026-01-03T00:00:00Z",
                    ),
                    event(
                        "context.injected",
                        serde_json::json!({"memory_ids":["m"],"memory_revisions":bindings}),
                        "2026-01-04T00:00:00Z",
                    ),
                    event(
                        "memory.cited",
                        serde_json::json!({"memory_id":"m","turn":1}),
                        "2026-01-05T00:00:00Z",
                    ),
                    event(
                        "run.finished",
                        serde_json::json!({"total_cost_usd":0}),
                        "2026-01-06T00:00:00Z",
                    ),
                ];
                for e in &mut events {
                    e.run_id = run;
                }
                apply_events(&c, &events).unwrap();
                for _ in 0..2 {
                    let current: (i64, f64) = c
                        .query_row(
                            "SELECT use_count,usefulness_score FROM memories WHERE memory_id='m'",
                            [],
                            |r| Ok((r.get(0)?, r.get(1)?)),
                        )
                        .unwrap();
                    assert_eq!(
                        current,
                        (0, 0.0),
                        "explicit unbound exposure must not fall back to current claim"
                    );
                    let citations: i64 = c
                        .query_row("SELECT count(*) FROM memory_citations", [], |r| r.get(0))
                        .unwrap();
                    assert_eq!(citations, 0);
                    let revision_uses: i64 = c
                        .query_row(
                            "SELECT COALESCE(SUM(use_count),0) FROM memory_revisions",
                            [],
                            |r| r.get(0),
                        )
                        .unwrap();
                    assert_eq!(revision_uses, 0);
                    rebuild_in_place(&c).unwrap();
                }
            }
        }
    }

    #[test]
    fn delayed_run_evidence_stays_on_the_retiring_claim() {
        let c = Connection::open_in_memory().unwrap();
        seed(&c);
        let run = RunId::new();
        let mut events = vec![
            event(
                "run.started",
                serde_json::json!({"project_id":"p","task":"t"}),
                "2026-01-02T00:00:00Z",
            ),
            event(
                "context.injected",
                serde_json::json!({"memory_ids":["m"]}),
                "2026-01-03T00:00:00Z",
            ),
            event(
                "memory.cited",
                serde_json::json!({"memory_id":"m","turn":1}),
                "2026-01-04T00:00:00Z",
            ),
            event(
                "memory.corrected",
                serde_json::json!({"memory_id":"m","text":"new claim"}),
                "2026-01-05T00:00:00Z",
            ),
            event(
                "memory.cited",
                serde_json::json!({"memory_id":"m","turn":2}),
                "2026-01-06T00:00:00Z",
            ),
            event(
                "run.finished",
                serde_json::json!({"total_cost_usd":0}),
                "2026-01-07T00:00:00Z",
            ),
        ];
        for e in &mut events {
            e.run_id = run;
            e.ts = OffsetDateTime::parse("2026-01-02T00:00:00Z", &Rfc3339).unwrap();
        }
        apply_events(&c, &events).unwrap();
        for _ in 0..2 {
            let current: (i64, f64) = c
                .query_row(
                    "SELECT use_count,usefulness_score FROM memories WHERE memory_id='m'",
                    [],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )
                .unwrap();
            assert_eq!(current, (0, 0.0));
            let retired:(i64,f64)=c.query_row("SELECT use_count,usefulness_score FROM memory_revisions WHERE event_id='baseline:m'",[],|r|Ok((r.get(0)?,r.get(1)?))).unwrap();
            assert_eq!(retired, (1, 1.0));
            rebuild_in_place(&c).unwrap();
        }
        // Pre-binding events also must not transfer evidence at equal times.
        c.execute("UPDATE events SET payload_json=json_remove(payload_json,'$.memory_revisions') WHERE kind='context.injected'",[]).unwrap();
        rebuild_in_place(&c).unwrap();
        assert_eq!(
            c.query_row(
                "SELECT use_count FROM memories WHERE memory_id='m'",
                [],
                |r| r.get::<_, i64>(0)
            )
            .unwrap(),
            0
        );
    }

    #[test]
    fn correction_validation_rolls_back_events_text_and_fts() {
        let c = Connection::open_in_memory().unwrap();
        seed(&c);
        let before: i64 = c
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        let bad = event(
            "memory.corrected",
            serde_json::json!({"memory_id":"m", "text":"changed narwhal", "kind":"invalid-kind"}),
            "2026-03-01T00:00:00Z",
        );
        assert!(apply_events(&c, &[bad]).is_err());
        assert_eq!(
            c.query_row("SELECT COUNT(*) FROM events", [], |r| r.get::<_, i64>(0))
                .unwrap(),
            before
        );
        assert_eq!(
            c.query_row("SELECT text FROM memories", [], |r| r.get::<_, String>(0))
                .unwrap(),
            "original quokka"
        );
        assert_eq!(
            c.query_row(
                "SELECT COUNT(*) FROM memories_fts WHERE memories_fts MATCH 'quokka'",
                [],
                |r| r.get::<_, i64>(0)
            )
            .unwrap(),
            1
        );
        // Force a failure after the text update: the entire projection must roll back.
        c.execute_batch("CREATE TRIGGER fail_correction BEFORE INSERT ON memory_revisions WHEN NEW.event_id NOT LIKE 'baseline:%' BEGIN SELECT RAISE(ABORT,'injected failure'); END;").unwrap();
        let valid = event(
            "memory.corrected",
            serde_json::json!({"memory_id":"m", "text":"changed narwhal"}),
            "2026-03-01T00:00:00Z",
        );
        assert!(apply_events(&c, &[valid]).is_err());
        assert_eq!(
            c.query_row("SELECT text FROM memories", [], |r| r.get::<_, String>(0))
                .unwrap(),
            "original quokka"
        );
        assert_eq!(
            c.query_row(
                "SELECT COUNT(*) FROM memories_fts WHERE memories_fts MATCH 'quokka'",
                [],
                |r| r.get::<_, i64>(0)
            )
            .unwrap(),
            1
        );
    }
    #[test]
    fn correction_history_separates_known_and_effective_time_and_replays() {
        let c = Connection::open_in_memory().unwrap();
        seed(&c);
        apply_events(&c, &[event("memory.corrected", serde_json::json!({"memory_id":"m", "text":"corrected narwhal", "effective_at":"2026-02-01T00:00:00Z"}), "2026-03-01T00:00:00Z")]).unwrap();
        for _ in 0..2 {
            assert_eq!(
                crate::bitemporal::memories_at(
                    &c,
                    "2026-02-15T00:00:00Z",
                    "2026-02-15T00:00:00Z",
                    0
                )
                .unwrap()[0]
                    .text,
                "original quokka"
            );
            assert_eq!(
                crate::bitemporal::memories_at(
                    &c,
                    "2026-02-15T00:00:00Z",
                    "2026-04-01T00:00:00Z",
                    0
                )
                .unwrap()[0]
                    .text,
                "corrected narwhal"
            );
            assert_eq!(
                crate::bitemporal::memories_at(
                    &c,
                    "2026-01-15T00:00:00Z",
                    "2026-04-01T00:00:00Z",
                    0
                )
                .unwrap()[0]
                    .text,
                "original quokka"
            );
            rebuild_in_place(&c).unwrap();
        }
        let (_, jsonl) = crate::sync::export_events(&c, 0, None, false).unwrap();
        let imported = Connection::open_in_memory().unwrap();
        schema::initialize(&imported).unwrap();
        crate::sync::import_events(&imported, &jsonl.unwrap(), false).unwrap();
        rebuild_in_place(&imported).unwrap();
        assert_eq!(
            imported
                .query_row("SELECT text FROM memories WHERE memory_id='m'", [], |r| {
                    r.get::<_, String>(0)
                })
                .unwrap(),
            "corrected narwhal"
        );
    }
    #[test]
    fn corpus_revision_observes_existing_embedding_updates_from_another_connection() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("brain.db");
        let reader = Connection::open(&db).unwrap();
        seed(&reader);
        let writer = Connection::open(&db).unwrap();
        let revision = || {
            reader
                .query_row("SELECT revision FROM corpus_revision", [], |r| {
                    r.get::<_, i64>(0)
                })
                .unwrap()
        };
        let before = revision();
        writer
            .execute(
                "UPDATE memories SET embedding=?1,embedding_model='stub' WHERE memory_id='m'",
                params![vec![0u8; 8]],
            )
            .unwrap();
        assert!(revision() > before);
        let before = revision();
        writer
            .execute(
                "UPDATE memories SET embedding=?1 WHERE memory_id='m'",
                params![vec![1u8; 8]],
            )
            .unwrap();
        assert!(revision() > before);
    }
}

/// Stable claim identity: kind-only revisions do not start a new claim.
/// A -> B -> A does start a new claim, even though the text repeats.
pub(crate) fn claim_revision_at(
    conn: &Connection,
    memory_id: &str,
    known_at: Option<&str>,
) -> KimetsuResult<String> {
    let revision = conn
        .query_row(
            "SELECT event_id FROM (
        SELECT event_id, known_at, revision_id, text,
               LAG(text) OVER (ORDER BY revision_id) AS previous_text
        FROM memory_revisions WHERE memory_id=?1)
        WHERE (previous_text IS NULL OR text != previous_text)
          AND (?2 IS NULL OR julianday(known_at)<julianday(?2))
        ORDER BY revision_id DESC LIMIT 1",
            params![memory_id, known_at],
            |r| r.get::<_, String>(0),
        )
        .optional()?;
    Ok(revision.unwrap_or_else(|| format!("baseline:{memory_id}")))
}

/// Distinguish a legacy absent exposure from an explicitly unbound delivery.
enum ClaimExposure {
    Absent,
    Unbound,
    Bound(String),
}

fn exact_claim_exposure(
    conn: &Connection,
    exposure_id: &str,
    run_id: &str,
    memory_id: &str,
) -> KimetsuResult<ClaimExposure> {
    let payload:Option<String>=conn.query_row("SELECT payload_json FROM events e WHERE event_id=?1 AND run_id=?2 AND kind='context.injected' AND EXISTS(SELECT 1 FROM json_each(e.payload_json,'$.memory_ids') WHERE value=?3)",params![exposure_id,run_id,memory_id],|r|r.get(0)).optional()?;
    let Some(payload) = payload else {
        return Ok(ClaimExposure::Unbound);
    };
    let payload: serde_json::Value = serde_json::from_str(&payload)?;
    Ok(
        match payload["memory_revisions"][memory_id]
            .as_str()
            .filter(|r| !r.is_empty())
        {
            Some(r) => ClaimExposure::Bound(r.to_string()),
            None => ClaimExposure::Unbound,
        },
    )
}

/// A run can deliver several revisions. Ambiguous mixed-claim runs never
/// transfer outcome credit onto whichever claim happens to be current.
fn run_claim_revision(
    conn: &Connection,
    run_id: &str,
    memory_id: &str,
) -> KimetsuResult<ClaimExposure> {
    let mut stmt=conn.prepare("SELECT ts,payload_json FROM events e WHERE run_id=?1 AND kind='context.injected' AND EXISTS(SELECT 1 FROM json_each(e.payload_json,'$.memory_ids') WHERE value=?2) ORDER BY julianday(ts),rowid")?;
    let rows = stmt
        .query_map(params![run_id, memory_id], |r| {
            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
        })?
        .collect::<Result<Vec<_>, _>>()?;
    let mut bound: Option<String> = None;
    for (at, payload) in rows {
        let payload: serde_json::Value = serde_json::from_str(&payload)?;
        let revision = if let Some(map) = payload.get("memory_revisions") {
            let Some(r) = map
                .get(memory_id)
                .and_then(|v| v.as_str())
                .filter(|r| !r.is_empty())
            else {
                return Ok(ClaimExposure::Unbound);
            };
            r.to_string()
        } else {
            claim_revision_at(conn, memory_id, Some(&at))?
        };
        if bound.as_ref().is_some_and(|r| r != &revision) {
            return Ok(ClaimExposure::Unbound);
        };
        bound = Some(revision);
    }
    Ok(bound
        .map(ClaimExposure::Bound)
        .unwrap_or(ClaimExposure::Absent))
}

/// Bind exposures while their event is first persisted, not when a delayed
/// outcome is projected. This also disambiguates equal-timestamp corrections.
fn bind_injected_revisions<'a>(
    conn: &Connection,
    event: &'a Event,
) -> KimetsuResult<Cow<'a, Event>> {
    if event.kind != "context.injected" || event.payload.get("memory_revisions").is_some() {
        return Ok(Cow::Borrowed(event));
    }
    let mut bound = event.clone();
    let mut revisions = serde_json::Map::new();
    if let Some(ids) = event.payload.get("memory_ids").and_then(|v| v.as_array()) {
        for id in ids.iter().filter_map(|v| v.as_str()) {
            revisions.insert(
                id.to_string(),
                serde_json::Value::String(claim_revision_at(conn, id, None)?),
            );
        }
    }
    bound.payload["memory_revisions"] = serde_json::Value::Object(revisions);
    Ok(Cow::Owned(bound))
}