mx 0.1.121

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

use crate::knowledge::KnowledgeEntry;
use crate::types::{
    Agent, ApplicabilityType, Category, ContentType, EntryType, Project, Relationship,
    RelationshipType, Session, SessionType, SourceType,
};

// The with_db! macro must be defined BEFORE mod declarations so that
// submodules can use it (macro_rules! macros are visible to child modules
// when defined before the `mod` statement).

/// Macro to execute code with the appropriate database connection (embedded or network)
///
/// This macro handles the connection type dispatch, allowing the same query code
/// to work with both embedded (SurrealKV) and network (WebSocket) connections.
///
/// # Usage
/// ```rust,ignore
/// with_db!(self, db, {
///     db.query(&sql).bind(("key", value)).await?
/// })
/// ```
macro_rules! with_db {
    ($self:expr, $db:ident, $body:expr) => {
        match &$self.conn {
            SurrealConnection::Embedded($db) => $body,
            SurrealConnection::Network($db) => $body,
        }
    };
}

mod connection;
mod knowledge;
mod trait_impl;

// Re-export connection types that external code needs
pub use connection::SurrealConnection;

// Import normalize_datetime for use within this module
use connection::normalize_datetime;

/// Tag record for SurrealDB
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
}

/// SurrealDB Thing wrapper for typed record IDs
#[derive(Debug, Clone)]
pub(crate) struct RecordId(Thing);

impl RecordId {
    fn new(table: &str, id: &str) -> Self {
        Self(Thing::from((table, id)))
    }

    fn as_thing(&self) -> &Thing {
        &self.0
    }

    fn into_thing(self) -> Thing {
        self.0
    }

    fn to_record_id(&self) -> SurrealRecordId {
        SurrealRecordId::from((self.0.tb.as_str(), self.0.id.to_string().as_str()))
    }
}

/// SurrealDB-backed knowledge store
pub struct SurrealDatabase {
    conn: SurrealConnection,
}

/// Helper for SELECT-based existence checks on `relates_to` edges.
/// Used by both `delete_relationship_by_id_async` and `delete_relationship_async`.
#[derive(Debug, Deserialize)]
struct ExistsRow {
    id: String,
}

impl SurrealDatabase {
    // =========================================================================
    // BACKUP OPERATIONS (Issue #206)
    // =========================================================================

    /// Create a pre-mutation backup of entry content
    pub fn backup_content_internal(
        &self,
        entry: &KnowledgeEntry,
        operation: &str,
        agent: Option<&str>,
    ) -> Result<String> {
        Self::runtime().block_on(self.backup_content_async(entry, operation, agent))
    }

    async fn backup_content_async(
        &self,
        entry: &KnowledgeEntry,
        operation: &str,
        agent: Option<&str>,
    ) -> Result<String> {
        let entry_id = entry.id.clone();
        let content_hash = entry.content_hash.clone().unwrap_or_default();
        let backup_id = format!(
            "{}_{}",
            entry_id.replace("kn-", ""),
            Utc::now().format("%Y%m%dT%H%M%S%.3f")
        );

        let _response = with_db!(self, db, {
            db.query(
                "CREATE type::thing('memory_backup', $backup_id) SET
                    entry_id = $entry_id,
                    title = $title,
                    body = $body,
                    content_hash = $content_hash,
                    operation = $operation,
                    source_agent = $source_agent,
                    created_at = time::now()
                ",
            )
            .bind(("backup_id", backup_id.clone()))
            .bind(("entry_id", entry_id.clone()))
            .bind(("title", entry.title.clone()))
            .bind(("body", entry.body.clone()))
            .bind(("content_hash", content_hash))
            .bind(("operation", operation.to_string()))
            .bind(("source_agent", agent.map(|s| s.to_string())))
            .await
            .context("Failed to create memory backup")
        })?;

        // Purge old backups (keep 10 per entry) — non-fatal
        let _ = self.purge_backups_async(&entry_id, 10).await;

        Ok(backup_id)
    }

    /// List backups for an entry, newest first
    pub fn list_backups_internal(&self, entry_id: &str) -> Result<Vec<crate::types::MemoryBackup>> {
        Self::runtime().block_on(self.list_backups_async(entry_id))
    }

    async fn list_backups_async(&self, entry_id: &str) -> Result<Vec<crate::types::MemoryBackup>> {
        let mut response = with_db!(self, db, {
            db.query(
                "SELECT meta::id(id) AS id, entry_id, title, body, content_hash,
                        operation, source_agent, created_at
                 FROM memory_backup
                 WHERE entry_id = $entry_id
                 ORDER BY created_at DESC",
            )
            .bind(("entry_id", entry_id.to_string()))
            .await
            .context("Failed to list memory backups")
        })?;

        let backups: Vec<crate::types::MemoryBackup> = response.take(0)?;
        Ok(backups)
    }

    /// Get the most recent backup for an entry
    pub fn latest_backup_internal(
        &self,
        entry_id: &str,
    ) -> Result<Option<crate::types::MemoryBackup>> {
        Self::runtime().block_on(self.latest_backup_async(entry_id))
    }

    async fn latest_backup_async(
        &self,
        entry_id: &str,
    ) -> Result<Option<crate::types::MemoryBackup>> {
        let mut response = with_db!(self, db, {
            db.query(
                "SELECT meta::id(id) AS id, entry_id, title, body, content_hash,
                        operation, source_agent, created_at
                 FROM memory_backup
                 WHERE entry_id = $entry_id
                 ORDER BY created_at DESC
                 LIMIT 1",
            )
            .bind(("entry_id", entry_id.to_string()))
            .await
            .context("Failed to get latest backup")
        })?;

        let backups: Vec<crate::types::MemoryBackup> = response.take(0)?;
        Ok(backups.into_iter().next())
    }

    /// Purge old backups, keeping the most recent `keep` per entry
    pub fn purge_backups_internal(&self, entry_id: &str, keep: usize) -> Result<()> {
        Self::runtime().block_on(self.purge_backups_async(entry_id, keep))
    }

    async fn purge_backups_async(&self, entry_id: &str, keep: usize) -> Result<()> {
        // Delete backups older than the Nth newest
        let _response = with_db!(self, db, {
            db.query(
                "DELETE FROM memory_backup
                    WHERE entry_id = $entry_id
                    AND id NOT IN (
                        SELECT VALUE id FROM memory_backup
                        WHERE entry_id = $entry_id
                        ORDER BY created_at DESC
                        LIMIT $keep
                    )",
            )
            .bind(("entry_id", entry_id.to_string()))
            .bind(("keep", keep as i64))
            .await
            .context("Failed to purge old backups")
        })?;

        Ok(())
    }

    // =========================================================================
    // WAKE CASCADE - Three-layer resonance query for identity loading
    // =========================================================================

    /// Wake-up cascade: Load Q's identity through three layers of resonance
    pub fn wake_cascade(
        &self,
        ctx: &crate::store::AgentContext,
        limit: usize,
        min_resonance: Option<i32>,
        days: i64,
    ) -> Result<crate::store::WakeCascade> {
        Self::runtime().block_on(self.wake_cascade_async(ctx, limit, min_resonance, days))
    }

    async fn wake_cascade_async(
        &self,
        ctx: &crate::store::AgentContext,
        limit: usize,
        min_resonance: Option<i32>,
        days: i64,
    ) -> Result<crate::store::WakeCascade> {
        // If min_resonance is set, use simple query for all blooms >= threshold
        if let Some(threshold) = min_resonance {
            let blooms = self.query_blooms_by_resonance(ctx, threshold).await?;
            return Ok(crate::store::WakeCascade {
                core: blooms,
                recent: Vec::new(),
                bridges: Vec::new(),
            });
        }

        // Sequential filling: core first, then recent, then bridges
        // This ensures we get the most important blooms first

        // Layer 1: Core foundational/transformative blooms (resonance 8+)
        // Use full limit for core - we'll subtract what we get
        let core = self.query_core_blooms(ctx, limit).await?;
        let remaining = limit.saturating_sub(core.len());

        // Layer 2: Recent blooms (last N days)
        // Exclude IDs already in core, use remaining quota
        let core_ids: std::collections::HashSet<String> =
            core.iter().map(|e| e.id.clone()).collect();

        let all_recent = self.query_recent_blooms(ctx, remaining * 2, days).await?;
        let recent: Vec<_> = all_recent
            .into_iter()
            .filter(|e| !core_ids.contains(&e.id))
            .take(remaining)
            .collect();
        let remaining = remaining.saturating_sub(recent.len());

        // Layer 3: Bridge blooms (anchored to core/recent, resonance 5+)
        // Use final remaining quota
        let mut anchor_ids: Vec<String> = core
            .iter()
            .chain(recent.iter())
            .map(|e| e.id.clone())
            .collect();

        // Deduplicate anchor IDs
        anchor_ids.sort();
        anchor_ids.dedup();

        let bridges = if anchor_ids.is_empty() || remaining == 0 {
            Vec::new()
        } else {
            // Exclude IDs already in core/recent
            let mut existing_ids = core_ids;
            existing_ids.extend(recent.iter().map(|e| e.id.clone()));

            let all_bridges = self
                .query_bridge_blooms(ctx, remaining * 2, &anchor_ids)
                .await?;
            all_bridges
                .into_iter()
                .filter(|e| !existing_ids.contains(&e.id))
                .take(remaining)
                .collect()
        };

        Ok(crate::store::WakeCascade {
            core,
            recent,
            bridges,
        })
    }

    /// Query all blooms with resonance >= threshold (for --min-resonance flag)
    async fn query_blooms_by_resonance(
        &self,
        ctx: &crate::store::AgentContext,
        threshold: i32,
    ) -> Result<Vec<crate::knowledge::KnowledgeEntry>> {
        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        let sql = format!(
            "SELECT {}
            FROM knowledge
            WHERE resonance >= $threshold
            AND (resonance_type IS NONE OR resonance_type != 'ephemeral')
            {}
            ORDER BY resonance DESC",
            Self::knowledge_select_fields(),
            visibility_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db.query(&sql).bind(("threshold", threshold));
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to query blooms by resonance")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut entries = Vec::new();
        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// Layer 1: Query core blooms (resonance 8+, excludes ephemeral)
    async fn query_core_blooms(
        &self,
        ctx: &crate::store::AgentContext,
        limit: usize,
    ) -> Result<Vec<crate::knowledge::KnowledgeEntry>> {
        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        let sql = format!(
            "SELECT *,
                (wake_order IS NOT NULL) AS has_wake_order,
                wake_order ?? 999999 AS effective_wake_order
            FROM (
                SELECT {}
                FROM knowledge
                WHERE resonance >= 8
                AND (resonance_type IS NONE OR resonance_type != 'ephemeral')
                {}
            )
            ORDER BY
                has_wake_order DESC,
                effective_wake_order ASC,
                resonance DESC
            LIMIT $limit",
            Self::knowledge_select_fields(),
            visibility_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db.query(&sql).bind(("limit", limit as i64));
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to query core blooms")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut entries = Vec::new();
        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// Layer 2: Query recent blooms (last N days, sorted by resonance)
    async fn query_recent_blooms(
        &self,
        ctx: &crate::store::AgentContext,
        limit: usize,
        days: i64,
    ) -> Result<Vec<crate::knowledge::KnowledgeEntry>> {
        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        // Calculate cutoff date (N days ago)
        let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
        let cutoff_str = cutoff.to_rfc3339();

        let sql = format!(
            "SELECT *,
                (wake_order IS NOT NULL) AS has_wake_order,
                wake_order ?? 999999 AS effective_wake_order
            FROM (
                SELECT {}
                FROM knowledge
                WHERE last_activated > <datetime>$cutoff
                AND (resonance_type IS NONE OR resonance_type != 'ephemeral')
                {}
            )
            ORDER BY
                has_wake_order DESC,
                effective_wake_order ASC,
                resonance DESC
            LIMIT $limit",
            Self::knowledge_select_fields(),
            visibility_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db
                .query(&sql)
                .bind(("cutoff", cutoff_str))
                .bind(("limit", limit as i64));
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to query recent blooms")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut entries = Vec::new();
        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// Layer 3: Query bridge blooms (anchored to core/recent, resonance 5+)
    async fn query_bridge_blooms(
        &self,
        ctx: &crate::store::AgentContext,
        limit: usize,
        anchor_ids: &[String],
    ) -> Result<Vec<crate::knowledge::KnowledgeEntry>> {
        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        // Use array::intersect to check if anchors array has any overlap with anchor_ids
        // If intersection is non-empty, this bloom is anchored to a core/recent bloom
        let sql = format!(
            "SELECT *,
                (wake_order IS NOT NULL) AS has_wake_order,
                wake_order ?? 999999 AS effective_wake_order
            FROM (
                SELECT {}
                FROM knowledge
                WHERE array::len(array::intersect(anchors, $anchor_ids)) > 0
                AND resonance >= 5
                {}
            )
            ORDER BY
                has_wake_order DESC,
                effective_wake_order ASC,
                resonance DESC
            LIMIT $limit",
            Self::knowledge_select_fields(),
            visibility_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db
                .query(&sql)
                .bind(("anchor_ids", anchor_ids.to_vec()))
                .bind(("limit", limit as i64));
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to query bridge blooms")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut entries = Vec::new();
        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// Update activation counts for loaded blooms, resetting last_activated timestamp.
    /// Use this for intentional single-entry access (e.g. `show`, `fact-session`).
    pub fn update_activations(&self, ids: &[String]) -> Result<()> {
        Self::runtime().block_on(self.update_activations_async(ids))
    }

    async fn update_activations_async(&self, ids: &[String]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }

        // Strip "kn-" prefix from IDs if present
        let clean_ids: Vec<String> = ids
            .iter()
            .map(|id| id.strip_prefix("kn-").unwrap_or(id).to_string())
            .collect();

        // Build array of Thing references
        let things: Vec<Thing> = clean_ids
            .iter()
            .map(|id| Thing::from(("knowledge", id.as_str())))
            .collect();

        let mut response = with_db!(self, db, {
            db.query(
                "UPDATE knowledge SET
                activation_count += 1,
                last_activated = time::now()
                WHERE id IN $ids",
            )
            .bind(("ids", things))
            .await
            .context("Failed to update activations")
        })?;

        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!(
                "Failed to update activations: {:?}",
                errors
            ));
        }

        Ok(())
    }

    /// Update only the summary field of a knowledge entry.
    /// Respects visibility: agents can only update summaries on entries they can see.
    /// Returns Ok(false) for entries that don't exist OR that the agent can't see
    /// (to avoid leaking existence of private entries).
    pub fn update_summary(
        &self,
        id: &str,
        summary: &str,
        ctx: &crate::store::AgentContext,
    ) -> Result<bool> {
        Self::runtime().block_on(self.update_summary_async(id, summary, ctx))
    }

    async fn update_summary_async(
        &self,
        id: &str,
        summary: &str,
        ctx: &crate::store::AgentContext,
    ) -> Result<bool> {
        let id_part = id.strip_prefix("kn-").unwrap_or(id);

        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        // Check if the record exists AND is visible to the current agent.
        // If the entry exists but isn't visible, we return false (same as "not found")
        // to avoid leaking the existence of private entries.
        let check_sql = format!(
            "SELECT count() AS c FROM knowledge WHERE meta::id(id) = $id {} GROUP ALL",
            visibility_clause
        );

        let mut check_response = with_db!(self, db, {
            let mut query = db.query(&check_sql).bind(("id", id_part.to_string()));
            if let Some(ref agent) = current_agent {
                query = query.bind(("current_agent", agent.clone()));
            }
            query
                .await
                .context("Failed to check knowledge record existence for summary update")
        })?;

        let count_results: Vec<serde_json::Value> = check_response.take(0)?;
        let exists = count_results
            .first()
            .and_then(|v| v["c"].as_i64())
            .unwrap_or(0)
            > 0;

        if !exists {
            return Ok(false);
        }

        // Update with the same visibility filter to prevent TOCTOU race conditions.
        // Even though we checked above, re-applying the filter on the UPDATE ensures
        // no bypass is possible between check and update.
        let update_sql = format!(
            "UPDATE knowledge SET summary = $summary WHERE meta::id(id) = $id {}",
            visibility_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db
                .query(&update_sql)
                .bind(("id", id_part.to_string()))
                .bind(("summary", summary.to_string()));
            if let Some(ref agent) = current_agent {
                query = query.bind(("current_agent", agent.clone()));
            }
            query.await.context("Failed to update summary")
        })?;

        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!("Failed to update summary: {:?}", errors));
        }

        Ok(true)
    }

    /// Increment activation_count only — does NOT reset last_activated.
    /// Use this for passive bulk surfacing (wake cascade, for-session view) where
    /// the entries were not intentionally accessed and should continue decaying
    /// at their normal rate.
    pub fn increment_activation_count(&self, ids: &[String]) -> Result<()> {
        Self::runtime().block_on(self.increment_activation_count_async(ids))
    }

    async fn increment_activation_count_async(&self, ids: &[String]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }

        // Strip "kn-" prefix from IDs if present
        let clean_ids: Vec<String> = ids
            .iter()
            .map(|id| id.strip_prefix("kn-").unwrap_or(id).to_string())
            .collect();

        // Build array of Thing references
        let things: Vec<Thing> = clean_ids
            .iter()
            .map(|id| Thing::from(("knowledge", id.as_str())))
            .collect();

        let mut response = with_db!(self, db, {
            db.query(
                "UPDATE knowledge SET
                activation_count += 1
                WHERE id IN $ids",
            )
            .bind(("ids", things))
            .await
            .context("Failed to increment activation counts")
        })?;

        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!(
                "Failed to increment activation counts: {:?}",
                errors
            ));
        }

        Ok(())
    }

    /// Query recent ephemeral facts with decay computation
    pub fn query_recent_facts(&self, days: i32) -> Result<Vec<KnowledgeEntry>> {
        Self::runtime().block_on(self.query_recent_facts_async(days))
    }

    async fn query_recent_facts_async(&self, days: i32) -> Result<Vec<KnowledgeEntry>> {
        // Query with computed effective_resonance for ordering and filtering.
        // Uses the shared decay formula from effective_resonance_expr().
        // This query only surfaces ephemeral entries (resonance_type = 'ephemeral');
        // foundational/transformative entries are excluded and never reach this path.
        let expr = Self::effective_resonance_expr();
        let sql = format!(
            "SELECT {},
                 ({expr}) AS effective_resonance
             FROM knowledge
             WHERE resonance_type = 'ephemeral'
             AND created_at > time::now() - duration::from::days($days)
             AND ({expr}) > 0.5
             ORDER BY effective_resonance DESC",
            Self::knowledge_select_fields(),
            expr = expr
        );

        let mut response = with_db!(self, db, {
            db.query(&sql)
                .bind(("days", days))
                .await
                .context("Failed to execute recent facts query")
        })?;

        let results: Vec<serde_json::Value> = response
            .take(0)
            .context("Failed to parse recent facts results")?;

        let mut entries = Vec::new();
        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// Query recent facts across ALL resonance types with decay computation.
    /// Foundational/transformative entries are exempt from decay (effective_resonance = resonance).
    pub fn query_recent_facts_all_types(&self, days: i32) -> Result<Vec<KnowledgeEntry>> {
        Self::runtime().block_on(self.query_recent_facts_all_types_async(days))
    }

    async fn query_recent_facts_all_types_async(&self, days: i32) -> Result<Vec<KnowledgeEntry>> {
        // Like query_recent_facts_async but without the resonance_type = 'ephemeral' filter.
        // Ephemeral entries are still decay-filtered (> 0.5). Foundational/transformative
        // entries are exempt from decay so they always surface here.
        let expr = Self::effective_resonance_expr();
        let sql = format!(
            "SELECT {},
                 ({expr}) AS effective_resonance
             FROM knowledge
             WHERE created_at > time::now() - duration::from::days($days)
             AND ({expr}) > 0.5
             ORDER BY effective_resonance DESC",
            Self::knowledge_select_fields(),
            expr = expr
        );

        let mut response = with_db!(self, db, {
            db.query(&sql)
                .bind(("days", days))
                .await
                .context("Failed to execute recent facts (all types) query")
        })?;

        let results: Vec<serde_json::Value> = response
            .take(0)
            .context("Failed to parse recent facts (all types) results")?;

        let mut entries = Vec::new();
        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// Reinforce a knowledge entry.
    /// Respects visibility: agents can only reinforce entries they can see.
    /// Returns Ok(None) for entries that don't exist OR that the agent can't see
    /// (to avoid leaking existence of private entries).
    pub fn reinforce(
        &self,
        id: &str,
        amount: i32,
        cap: Option<i32>,
        ctx: &crate::store::AgentContext,
    ) -> Result<Option<crate::store::ReinforcementResult>> {
        Self::runtime().block_on(self.reinforce_async(id, amount, cap, ctx))
    }

    async fn reinforce_async(
        &self,
        id: &str,
        amount: i32,
        cap: Option<i32>,
        ctx: &crate::store::AgentContext,
    ) -> Result<Option<crate::store::ReinforcementResult>> {
        // Normalize ID
        let normalized_id = if id.starts_with("kn-") {
            id.to_string()
        } else {
            format!("kn-{}", id)
        };

        let id_part = normalized_id.strip_prefix("kn-").unwrap_or(&normalized_id);

        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        // Check if the record exists AND is visible to the current agent.
        // If the entry exists but isn't visible, we return None (same as "not found")
        // to avoid leaking the existence of private entries.
        let select_sql = format!(
            "SELECT resonance, activation_count FROM knowledge WHERE meta::id(id) = $id {}",
            visibility_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db.query(&select_sql).bind(("id", id_part.to_string()));
            if let Some(ref agent) = current_agent {
                query = query.bind(("current_agent", agent.clone()));
            }
            query.await.context("Failed to select entry for reinforce")
        })?;

        let results: Vec<serde_json::Value> = response
            .take(0)
            .context("Failed to parse entry for reinforce")?;

        let current = match results.first() {
            Some(v) => v,
            None => return Ok(None),
        };

        let old_resonance = current
            .get("resonance")
            .and_then(|v| v.as_i64())
            .unwrap_or(0) as i32;

        let old_activation_count = current
            .get("activation_count")
            .and_then(|v| v.as_i64())
            .unwrap_or(0) as i32;

        // Calculate new resonance
        let mut new_resonance = old_resonance + amount;
        let capped = if let Some(cap_value) = cap {
            if new_resonance > cap_value {
                new_resonance = cap_value;
                true
            } else {
                false
            }
        } else {
            false
        };

        let new_activation_count = old_activation_count + 1;

        // Update with the same visibility filter to prevent TOCTOU race conditions.
        // Even though we checked above, re-applying the filter on the UPDATE ensures
        // no bypass is possible between check and update.
        let update_sql = format!(
            "UPDATE knowledge SET
            resonance = $new_resonance,
            last_activated = time::now(),
            activation_count = $new_count,
            updated_at = time::now()
            WHERE meta::id(id) = $id {}",
            visibility_clause
        );

        let mut update_response = with_db!(self, db, {
            let mut query = db
                .query(&update_sql)
                .bind(("id", id_part.to_string()))
                .bind(("new_resonance", new_resonance))
                .bind(("new_count", new_activation_count));
            if let Some(ref agent) = current_agent {
                query = query.bind(("current_agent", agent.clone()));
            }
            query.await.context("Failed to update entry for reinforce")
        })?;

        let errors = update_response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!("Failed to reinforce entry: {:?}", errors));
        }

        // Get current timestamp for response
        let now = Utc::now().to_rfc3339();

        Ok(Some(crate::store::ReinforcementResult {
            id: normalized_id,
            old_resonance,
            new_resonance,
            amount_added: amount,
            capped,
            last_activated: now,
            activation_count: new_activation_count,
        }))
    }

    // =========================================================================
    // LOOKUP OPERATIONS
    // =========================================================================

    /// List all categories
    pub fn list_categories(&self) -> Result<Vec<Category>> {
        Self::runtime().block_on(self.list_categories_async())
    }

    async fn list_categories_async(&self) -> Result<Vec<Category>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, <string>created_at AS created_at FROM category ORDER BY id")
                .await
                .context("Failed to list categories")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;

        let mut categories = Vec::new();
        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            categories.push(Category {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(categories)
    }

    /// List all projects
    pub fn list_projects(&self) -> Result<Vec<Project>> {
        Self::runtime().block_on(self.list_projects_async())
    }

    async fn list_projects_async(&self) -> Result<Vec<Project>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, name, path, repo_url, description, active, <string>created_at AS created_at, <string>updated_at AS updated_at FROM project ORDER BY name")
                .await
                .context("Failed to list projects")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut projects = Vec::new();

        for obj in results {
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            projects.push(Project {
                id,
                name: obj["name"].as_str().unwrap_or_default().to_string(),
                path: obj["path"].as_str().map(|s| s.to_string()),
                repo_url: obj["repo_url"].as_str().map(|s| s.to_string()),
                description: obj["description"].as_str().map(|s| s.to_string()),
                active: obj["active"].as_bool().unwrap_or(true),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
                updated_at: obj["updated_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(projects)
    }

    /// List all agents
    pub fn list_agents(&self) -> Result<Vec<Agent>> {
        Self::runtime().block_on(self.list_agents_async())
    }

    async fn list_agents_async(&self) -> Result<Vec<Agent>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, domain, <string>created_at AS created_at, <string>updated_at AS updated_at FROM agent ORDER BY id")
                .await
                .context("Failed to list agents")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut agents = Vec::new();

        for obj in results {
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            agents.push(Agent {
                id,
                description: obj["description"].as_str().map(|s| s.to_string()),
                domain: obj["domain"].as_str().map(|s| s.to_string()),
                created_at: obj["created_at"].as_str().map(|s| s.to_string()),
                updated_at: obj["updated_at"].as_str().map(|s| s.to_string()),
            });
        }

        Ok(agents)
    }

    /// List all tags
    pub fn list_tags(&self) -> Result<Vec<Tag>> {
        Self::runtime().block_on(self.list_tags_async())
    }

    async fn list_tags_async(&self) -> Result<Vec<Tag>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, name, <string>created_at AS created_at FROM tag ORDER BY name")
                .await
                .context("Failed to list tags")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut tags = Vec::new();

        for obj in results {
            tags.push(Tag {
                name: obj["name"].as_str().unwrap_or_default().to_string(),
                created_at: obj["created_at"].as_str().map(|s| s.to_string()),
            });
        }

        Ok(tags)
    }

    /// List all distinct tag names, optionally filtered by category
    pub fn list_all_tags(&self, category: Option<&str>) -> Result<Vec<String>> {
        Self::runtime().block_on(self.list_all_tags_async(category.map(|s| s.to_string())))
    }

    async fn list_all_tags_async(&self, category: Option<String>) -> Result<Vec<String>> {
        let mut tags = if let Some(cat) = category {
            // Traverse from tag side: find tags whose knowledge entries belong to the category.
            // Filtering via `WHERE in.category = ...` on a graph edge table does not work in
            // SurrealDB 2.x — the predicate matches nothing even though the field is present.
            // Reverse traversal through the tag record works correctly.
            let mut response = with_db!(self, db, {
                db.query(
                    "SELECT VALUE name FROM tag \
                     WHERE <-tagged_with<-knowledge.category CONTAINS type::thing('category', $cat)",
                )
                .bind(("cat", cat))
                .await
                .context("Failed to list tags by category")
            })?;
            let tags: Vec<String> = response.take(0).unwrap_or_default();
            tags
        } else {
            // Only return tags that are actually in use (have at least one incoming edge).
            // The previous query used `array::distinct(out.name)` on the edge table, but
            // `out.name` is a scalar string per row — array::distinct expects an array and errors.
            let mut response = with_db!(self, db, {
                db.query("SELECT VALUE name FROM tag WHERE <-tagged_with")
                    .await
                    .context("Failed to list all tags")
            })?;
            let tags: Vec<String> = response.take(0).unwrap_or_default();
            tags
        };

        tags.sort();
        Ok(tags)
    }

    /// List all applicability types
    pub fn list_applicability_types(&self) -> Result<Vec<ApplicabilityType>> {
        Self::runtime().block_on(self.list_applicability_types_async())
    }

    async fn list_applicability_types_async(&self) -> Result<Vec<ApplicabilityType>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, scope, <string>created_at AS created_at FROM applicability_type ORDER BY id")
                .await
                .context("Failed to list applicability types")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut types = Vec::new();

        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            types.push(ApplicabilityType {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                scope: obj["scope"].as_str().map(|s| s.to_string()),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(types)
    }

    /// Upsert a project (returns RecordId)
    pub fn upsert_project_internal(&self, project: &Project) -> Result<RecordId> {
        Self::runtime().block_on(self.upsert_project_async(project))
    }

    async fn upsert_project_async(&self, project: &Project) -> Result<RecordId> {
        let record_id = RecordId::new("project", &project.id);

        // Always include datetimes - use current time if not provided
        let now = Utc::now().to_rfc3339();
        let created_at = if project.created_at.is_empty() {
            now.clone()
        } else {
            project.created_at.clone()
        };
        let updated_at = if project.updated_at.is_empty() {
            now.clone()
        } else {
            project.updated_at.clone()
        };

        let mut response = with_db!(self, db, {
            db.query(
                "UPSERT type::thing('project', $id) SET
                name = $name,
                path = $path,
                repo_url = $repo_url,
                description = $description,
                active = $active,
                created_at = <datetime>$created_at,
                updated_at = <datetime>$updated_at
            ",
            )
            .bind(("id", project.id.clone()))
            .bind(("name", project.name.clone()))
            .bind(("path", project.path.clone()))
            .bind(("repo_url", project.repo_url.clone()))
            .bind(("description", project.description.clone()))
            .bind(("active", project.active))
            .bind(("created_at", normalize_datetime(&created_at)))
            .bind(("updated_at", normalize_datetime(&updated_at)))
            .await
            .context("Failed to upsert project")
        })?;

        // Check for errors in the response
        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!("SurrealDB returned errors: {:?}", errors));
        }

        Ok(record_id)
    }

    // =========================================================================
    // RELATIONSHIP OPERATIONS
    // =========================================================================

    /// Add a relationship between knowledge entries
    pub fn add_relationship(&self, from: &str, to: &str, rel_type: &str) -> Result<()> {
        Self::runtime().block_on(self.add_relationship_async(from, to, rel_type))
    }

    async fn add_relationship_async(&self, from: &str, to: &str, rel_type: &str) -> Result<()> {
        let from_id = from.strip_prefix("kn-").unwrap_or(from);
        let to_id = to.strip_prefix("kn-").unwrap_or(to);

        let from_thing = Thing::from(("knowledge", from_id));
        let to_thing = Thing::from(("knowledge", to_id));
        let rel_type_thing = Thing::from(("relationship_type", rel_type));

        with_db!(self, db, {
            db.query("RELATE $from->relates_to->$to SET relationship_type = $rel_type, created_at = time::now()")
                .bind(("from", from_thing))
                .bind(("to", to_thing))
                .bind(("rel_type", rel_type_thing))
                .await
                .context("Failed to create relationship")
        })?;

        Ok(())
    }

    /// List all relationships for a knowledge entry
    pub fn list_relationships(&self, entry_id: &str) -> Result<Vec<Relationship>> {
        Self::runtime().block_on(self.list_relationships_async(entry_id))
    }

    async fn list_relationships_async(&self, entry_id: &str) -> Result<Vec<Relationship>> {
        let id_part = entry_id.strip_prefix("kn-").unwrap_or(entry_id);
        let entry_thing = Thing::from(("knowledge", id_part));

        // Use meta::id() to extract plain string IDs from Thing record links.
        // Direct deserialization of Thing fields via serde_json::Value fails
        // because surrealdb::sql::Thing serializes as an untagged enum tuple
        // that serde_json cannot round-trip. meta::id() returns a plain string.
        #[derive(Debug, Deserialize)]
        struct RelRow {
            id: String,
            from_entry_id: String,
            to_entry_id: String,
            relationship_type: String,
            #[serde(default)]
            created_at: Option<String>,
        }

        let mut response = with_db!(self, db, {
            db.query(
                "SELECT meta::id(id) AS id,
                        meta::id(in) AS from_entry_id,
                        meta::id(out) AS to_entry_id,
                        meta::id(relationship_type) AS relationship_type,
                        <string>created_at AS created_at
                 FROM relates_to
                 WHERE in = $entry OR out = $entry
                 ORDER BY created_at DESC",
            )
            .bind(("entry", entry_thing))
            .await
            .context("Failed to query relationships")
        })?;

        let results: Vec<RelRow> = response.take(0)?;
        let relationships = results
            .into_iter()
            .map(|row| Relationship {
                id: row.id,
                from_entry_id: format!("kn-{}", row.from_entry_id),
                to_entry_id: format!("kn-{}", row.to_entry_id),
                relationship_type: row.relationship_type,
                created_at: row.created_at.unwrap_or_else(|| "unknown".to_string()),
            })
            .collect();

        Ok(relationships)
    }

    /// Delete a relationship by from/to/type triple
    pub fn delete_relationship(&self, from: &str, to: &str, rel_type: &str) -> Result<bool> {
        Self::runtime().block_on(self.delete_relationship_async(from, to, rel_type))
    }

    /// Delete a relationship edge by its record ID (e.g. "abc123" or the raw SurrealDB ID).
    pub fn delete_relationship_by_id(&self, id: &str) -> Result<bool> {
        Self::runtime().block_on(self.delete_relationship_by_id_async(id))
    }

    async fn delete_relationship_by_id_async(&self, id: &str) -> Result<bool> {
        // SurrealDB's RETURN BEFORE yields Thing-typed fields that serde_json cannot
        // round-trip. Instead: SELECT with meta::id() to check existence, then DELETE
        // without a RETURN clause (which is safe to take as Vec<Value> empty).
        //
        // NOTE: There is a TOCTOU window between the SELECT and DELETE — the edge
        // could be deleted by another caller between the two queries.  This is
        // acceptable for a single-user CLI tool where concurrent mutation is rare.
        let mut check = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id FROM relates_to WHERE meta::id(id) = $id LIMIT 1")
                .bind(("id", id.to_string()))
                .await
                .context("Failed to check relationship existence")
        })?;

        let exists: Vec<ExistsRow> = check.take(0)?;
        if exists.is_empty() {
            return Ok(false);
        }

        with_db!(self, db, {
            db.query("DELETE relates_to WHERE meta::id(id) = $id")
                .bind(("id", id.to_string()))
                .await
                .context("Failed to delete relationship by id")
        })?;

        Ok(true)
    }

    async fn delete_relationship_async(
        &self,
        from: &str,
        to: &str,
        rel_type: &str,
    ) -> Result<bool> {
        let from_id = from.strip_prefix("kn-").unwrap_or(from);
        let to_id = to.strip_prefix("kn-").unwrap_or(to);

        let from_thing = Thing::from(("knowledge", from_id));
        let to_thing = Thing::from(("knowledge", to_id));
        let rel_type_thing = Thing::from(("relationship_type", rel_type));

        // SurrealDB's RETURN BEFORE yields Thing-typed fields that serde_json cannot
        // round-trip. Check existence with meta::id() SELECT first, then DELETE without
        // a RETURN clause to avoid the deserialization error.
        let mut check = with_db!(self, db, {
            db.query(
                "SELECT meta::id(id) AS id FROM relates_to
                 WHERE in = $from AND out = $to AND relationship_type = $rel_type
                 LIMIT 1",
            )
            .bind(("from", from_thing.clone()))
            .bind(("to", to_thing.clone()))
            .bind(("rel_type", rel_type_thing.clone()))
            .await
            .context("Failed to check relationship existence")
        })?;

        let exists: Vec<ExistsRow> = check.take(0)?;
        if exists.is_empty() {
            return Ok(false);
        }

        with_db!(self, db, {
            db.query(
                "DELETE relates_to
                 WHERE in = $from AND out = $to AND relationship_type = $rel_type",
            )
            .bind(("from", from_thing))
            .bind(("to", to_thing))
            .bind(("rel_type", rel_type_thing))
            .await
            .context("Failed to delete relationship")
        })?;

        Ok(true)
    }

    /// Get facts extracted from a specific session
    pub fn get_facts_for_session(&self, session_id: &str) -> Result<Vec<String>> {
        Self::runtime().block_on(self.get_facts_for_session_async(session_id))
    }

    async fn get_facts_for_session_async(&self, session_id: &str) -> Result<Vec<String>> {
        let session_id_normalized = session_id.strip_prefix("kn-").unwrap_or(session_id);
        let session_thing = Thing::from(("knowledge", session_id_normalized));

        let mut response = with_db!(self, db, {
            db.query(
                "SELECT VALUE meta::id(in) FROM relates_to
                 WHERE out = $session_id AND relationship_type = relationship_type:extracted_from",
            )
            .bind(("session_id", session_thing))
            .await
            .context("Failed to query facts for session")
        })?;

        let fact_ids: Vec<String> = response.take(0).unwrap_or_default();
        let facts_with_prefix: Vec<String> = fact_ids
            .into_iter()
            .map(|id| format!("kn-{}", id))
            .collect();

        Ok(facts_with_prefix)
    }

    /// Get the session a fact was extracted from
    pub fn get_session_for_fact(&self, fact_id: &str) -> Result<Option<String>> {
        Self::runtime().block_on(self.get_session_for_fact_async(fact_id))
    }

    async fn get_session_for_fact_async(&self, fact_id: &str) -> Result<Option<String>> {
        let fact_id_normalized = fact_id.strip_prefix("kn-").unwrap_or(fact_id);
        let fact_thing = Thing::from(("knowledge", fact_id_normalized));

        let mut response = with_db!(self, db, {
            db.query(
                "SELECT VALUE meta::id(out) FROM relates_to
                 WHERE in = $fact AND relationship_type = relationship_type:extracted_from",
            )
            .bind(("fact", fact_thing))
            .await
            .context("Failed to query session for fact")
        })?;

        let session_ids: Vec<String> = response.take(0).unwrap_or_default();

        Ok(session_ids.first().map(|id| format!("kn-{}", id)))
    }

    // =========================================================================
    // TAG OPERATIONS (not exposed in public API, handled via knowledge entry)
    // =========================================================================

    /// Get tags for an entry
    pub fn get_tags_for_entry(&self, entry_id: &str) -> Result<Vec<String>> {
        Self::runtime().block_on(self.get_tags_for_entry_async(entry_id))
    }

    async fn get_tags_for_entry_async(&self, entry_id: &str) -> Result<Vec<String>> {
        let id_part = entry_id.strip_prefix("kn-").unwrap_or(entry_id);
        let entry_thing = Thing::from(("knowledge", id_part));

        let mut tags_response = with_db!(self, db, {
            db.query("SELECT VALUE out.name FROM tagged_with WHERE in = $knowledge")
                .bind(("knowledge", entry_thing))
                .await
                .context("Failed to query tags")
        })?;

        let tags: Vec<String> = tags_response.take(0).unwrap_or_default();
        Ok(tags)
    }

    /// Set tags for an entry - handled automatically by upsert_knowledge
    pub fn set_tags_for_entry(&self, _entry_id: &str, _tags: &[String]) -> Result<()> {
        // Tags are managed via upsert_knowledge, this is a no-op for compatibility
        Ok(())
    }

    /// Get applicability for an entry
    pub fn get_applicability_for_entry(&self, entry_id: &str) -> Result<Vec<String>> {
        Self::runtime().block_on(self.get_applicability_for_entry_async(entry_id))
    }

    async fn get_applicability_for_entry_async(&self, entry_id: &str) -> Result<Vec<String>> {
        let id_part = entry_id.strip_prefix("kn-").unwrap_or(entry_id);
        let entry_thing = Thing::from(("knowledge", id_part));

        let mut app_response = with_db!(self, db, {
            db.query("SELECT VALUE meta::id(out) FROM applies_to WHERE in = $knowledge")
                .bind(("knowledge", entry_thing))
                .await
                .context("Failed to query applicability")
        })?;

        let applicability_raw: Vec<Thing> = app_response.take(0).unwrap_or_default();
        let applicability: Vec<String> = applicability_raw
            .into_iter()
            .map(|t| t.id.to_string())
            .collect();

        Ok(applicability)
    }

    /// Set applicability for an entry - handled automatically by upsert_knowledge
    pub fn set_applicability_for_entry(&self, _entry_id: &str, _ids: &[String]) -> Result<()> {
        // Applicability is managed via upsert_knowledge, this is a no-op for compatibility
        Ok(())
    }

    /// Upsert applicability type
    pub fn upsert_applicability_type(&self, atype: &ApplicabilityType) -> Result<()> {
        Self::runtime().block_on(self.upsert_applicability_type_async(atype))
    }

    async fn upsert_applicability_type_async(&self, atype: &ApplicabilityType) -> Result<()> {
        // Always include datetimes - use current time if not provided
        let now = Utc::now().to_rfc3339();
        let created_at = if atype.created_at.is_empty() {
            now
        } else {
            atype.created_at.clone()
        };

        let mut response = with_db!(self, db, {
            db.query(
                "UPSERT type::thing('applicability_type', $id) SET
                description = $description,
                scope = $scope,
                created_at = <datetime>$created_at
            ",
            )
            .bind(("id", atype.id.clone()))
            .bind(("description", atype.description.clone()))
            .bind(("scope", atype.scope.clone()))
            .bind(("created_at", normalize_datetime(&created_at)))
            .await
            .context("Failed to upsert applicability type")
        })?;

        // Check for errors in the response
        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!("SurrealDB returned errors: {:?}", errors));
        }

        Ok(())
    }

    /// Get category by ID
    pub fn get_category(&self, id: &str) -> Result<Option<Category>> {
        Self::runtime().block_on(self.get_category_async(id))
    }

    async fn get_category_async(&self, id: &str) -> Result<Option<Category>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, <string>created_at AS created_at FROM category WHERE id = type::thing('category', $id)")
                .bind(("id", id.to_string()))
                .await
                .context("Failed to query category")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;

        if results.is_empty() {
            return Ok(None);
        }

        let obj = &results[0];
        let id_str = obj["id"].as_str().unwrap_or_default().to_string();

        Ok(Some(Category {
            id: id_str,
            description: obj["description"].as_str().unwrap_or_default().to_string(),
            created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
        }))
    }

    /// Upsert a category
    pub fn upsert_category(&self, category: &Category) -> Result<()> {
        Self::runtime().block_on(self.upsert_category_async(category))
    }

    async fn upsert_category_async(&self, category: &Category) -> Result<()> {
        // Always include datetime - use current time if not provided
        let now = Utc::now().to_rfc3339();
        let created_at = if category.created_at.is_empty() {
            now
        } else {
            category.created_at.clone()
        };

        let mut response = with_db!(self, db, {
            db.query(
                "UPSERT type::thing('category', $id) SET
                description = $description,
                created_at = <datetime>$created_at
            ",
            )
            .bind(("id", category.id.clone()))
            .bind(("description", category.description.clone()))
            .bind(("created_at", normalize_datetime(&created_at)))
            .await
            .context("Failed to upsert category")
        })?;

        // Check for errors in the response
        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!("SurrealDB returned errors: {:?}", errors));
        }

        Ok(())
    }

    /// Delete a category (only if no entries use it)
    pub fn delete_category(&self, id: &str) -> Result<bool> {
        Self::runtime().block_on(self.delete_category_async(id))
    }

    async fn delete_category_async(&self, id: &str) -> Result<bool> {
        let category_thing = Thing::from(("category", id));

        // Check if any knowledge entries use this category
        let mut count_response = with_db!(self, db, {
            db.query("SELECT count() AS c FROM knowledge WHERE category = $category GROUP ALL")
                .bind(("category", category_thing.clone()))
                .await
                .context("Failed to count knowledge entries for category")
        })?;

        let count_results: Vec<serde_json::Value> = count_response.take(0)?;
        let count = count_results
            .first()
            .and_then(|v| v["c"].as_i64())
            .unwrap_or(0);

        if count > 0 {
            return Err(anyhow::anyhow!(
                "Cannot remove category '{}': {} entries still use it",
                id,
                count
            ));
        }

        // Delete the category
        let record_id = RecordId::new("category", id);
        let result: Option<Value> = with_db!(self, db, {
            db.delete(record_id.to_record_id())
                .await
                .context("Failed to delete category")
        })?;

        Ok(result.is_some())
    }

    /// Get project by ID
    pub fn get_project(&self, id: &str) -> Result<Option<Project>> {
        Self::runtime().block_on(self.get_project_async(id))
    }

    async fn get_project_async(&self, id: &str) -> Result<Option<Project>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, name, path, repo_url, description, active, <string>created_at AS created_at, <string>updated_at AS updated_at FROM project WHERE id = type::thing('project', $id)")
                .bind(("id", id.to_string()))
                .await
                .context("Failed to query project")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;

        if results.is_empty() {
            return Ok(None);
        }

        let obj = &results[0];
        let id_str = obj["id"].as_str().unwrap_or_default().to_string();

        Ok(Some(Project {
            id: id_str,
            name: obj["name"].as_str().unwrap_or_default().to_string(),
            path: obj["path"].as_str().map(|s| s.to_string()),
            repo_url: obj["repo_url"].as_str().map(|s| s.to_string()),
            description: obj["description"].as_str().map(|s| s.to_string()),
            active: obj["active"].as_bool().unwrap_or(true),
            created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            updated_at: obj["updated_at"].as_str().unwrap_or_default().to_string(),
        }))
    }

    /// Get agent by ID
    pub fn get_agent(&self, id: &str) -> Result<Option<Agent>> {
        Self::runtime().block_on(self.get_agent_async(id))
    }

    async fn get_agent_async(&self, id: &str) -> Result<Option<Agent>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, domain, <string>created_at AS created_at, <string>updated_at AS updated_at FROM agent WHERE id = type::thing('agent', $id)")
                .bind(("id", id.to_string()))
                .await
                .context("Failed to query agent")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;

        if results.is_empty() {
            return Ok(None);
        }

        let obj = &results[0];
        let id_str = obj["id"].as_str().unwrap_or_default().to_string();

        Ok(Some(Agent {
            id: id_str,
            description: obj["description"].as_str().map(|s| s.to_string()),
            domain: obj["domain"].as_str().map(|s| s.to_string()),
            created_at: obj["created_at"].as_str().map(|s| s.to_string()),
            updated_at: obj["updated_at"].as_str().map(|s| s.to_string()),
        }))
    }

    /// Upsert agent
    pub fn upsert_agent(&self, agent: &Agent) -> Result<()> {
        Self::runtime().block_on(self.upsert_agent_async(agent))
    }

    async fn upsert_agent_async(&self, agent: &Agent) -> Result<()> {
        // Always include datetimes - use current time if not provided
        let now = Utc::now().to_rfc3339();
        let created_at = agent.created_at.clone().unwrap_or_else(|| now.clone());
        let updated_at = agent.updated_at.clone().unwrap_or_else(|| now.clone());

        let mut response = with_db!(self, db, {
            db.query(
                "UPSERT type::thing('agent', $id) SET
                description = $description,
                domain = $domain,
                created_at = <datetime>$created_at,
                updated_at = <datetime>$updated_at
            ",
            )
            .bind(("id", agent.id.clone()))
            .bind(("description", agent.description.clone()))
            .bind(("domain", agent.domain.clone()))
            .bind(("created_at", normalize_datetime(&created_at)))
            .bind(("updated_at", normalize_datetime(&updated_at)))
            .await
            .context("Failed to upsert agent")
        })?;

        // Check for errors in the response
        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!("SurrealDB returned errors: {:?}", errors));
        }

        Ok(())
    }

    /// Get tags for a project
    pub fn get_tags_for_project(&self, _project_id: &str) -> Result<Vec<String>> {
        // Not implemented in SurrealDB schema yet
        Ok(vec![])
    }

    /// Set tags for a project
    pub fn set_tags_for_project(&self, _project_id: &str, _tags: &[String]) -> Result<()> {
        // Not implemented in SurrealDB schema yet
        Ok(())
    }

    /// Get applicability for a project
    pub fn get_applicability_for_project(&self, _project_id: &str) -> Result<Vec<String>> {
        // Not implemented in SurrealDB schema yet
        Ok(vec![])
    }

    /// Set applicability for a project
    pub fn set_applicability_for_project(&self, _project_id: &str, _ids: &[String]) -> Result<()> {
        // Not implemented in SurrealDB schema yet
        Ok(())
    }

    // =========================================================================
    // CONTENT PATCH OPERATIONS
    // =========================================================================

    /// Edit content by finding and replacing text
    pub fn edit_content(
        &self,
        id: &str,
        ctx: &crate::store::AgentContext,
        old_text: &str,
        new_text: &str,
        replace_all: bool,
        nth: Option<usize>,
    ) -> Result<crate::store::EditResult> {
        // Fetch entry
        let entry = self
            .get_knowledge(id, ctx)?
            .ok_or_else(|| anyhow::anyhow!("Entry not found: {}", id))?;

        let body = entry
            .body
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Entry has no body content"))?;

        // Use shared content operation logic
        let result = crate::content_ops::edit_content(body, old_text, new_text, replace_all, nth)?;

        // Update the entry
        let mut updated = entry;
        let content_hash = KnowledgeEntry::compute_hash(&result.new_content);
        updated.body = Some(result.new_content.clone());
        updated.updated_at = Some(chrono::Utc::now().to_rfc3339());
        updated.content_hash = Some(content_hash);

        self.upsert_knowledge_internal(&updated)?;

        Ok(crate::store::EditResult {
            replacements: result.replacements,
            new_content: result.new_content,
        })
    }

    /// Append content to the end of an entry's body
    pub fn append_content(
        &self,
        id: &str,
        ctx: &crate::store::AgentContext,
        content: &str,
    ) -> Result<()> {
        let entry = self
            .get_knowledge(id, ctx)?
            .ok_or_else(|| anyhow::anyhow!("Entry not found: {}", id))?;

        // Use shared content operation logic
        let new_body = crate::content_ops::append_content(entry.body.as_deref(), content);

        let mut updated = entry;
        let content_hash = KnowledgeEntry::compute_hash(&new_body);
        updated.body = Some(new_body);
        updated.updated_at = Some(chrono::Utc::now().to_rfc3339());
        updated.content_hash = Some(content_hash);

        self.upsert_knowledge_internal(&updated)?;
        Ok(())
    }

    /// Prepend content to the start of an entry's body
    pub fn prepend_content(
        &self,
        id: &str,
        ctx: &crate::store::AgentContext,
        content: &str,
    ) -> Result<()> {
        let entry = self
            .get_knowledge(id, ctx)?
            .ok_or_else(|| anyhow::anyhow!("Entry not found: {}", id))?;

        // Use shared content operation logic
        let new_body = crate::content_ops::prepend_content(entry.body.as_deref(), content);

        let mut updated = entry;
        let content_hash = KnowledgeEntry::compute_hash(&new_body);
        updated.body = Some(new_body);
        updated.updated_at = Some(chrono::Utc::now().to_rfc3339());
        updated.content_hash = Some(content_hash);

        self.upsert_knowledge_internal(&updated)?;
        Ok(())
    }

    /// List tables - SurrealDB uses tables, return table names
    pub fn list_tables(&self) -> Result<Vec<String>> {
        Self::runtime().block_on(self.list_tables_async())
    }

    async fn list_tables_async(&self) -> Result<Vec<String>> {
        let mut response = with_db!(self, db, {
            db.query("INFO FOR DB")
                .await
                .context("Failed to query database info")
        })?;

        // SurrealDB INFO returns complex metadata - take as JSON directly
        let info: Option<serde_json::Value> = response.take(0)?;
        let mut tables = Vec::new();

        if let Some(info_json) = info
            && let Some(tables_obj) = info_json.get("tables").and_then(|v| v.as_object())
        {
            for table_name in tables_obj.keys() {
                tables.push(table_name.clone());
            }
            tables.sort();
        }

        Ok(tables)
    }

    /// Count total knowledge entries
    pub fn count(&self) -> Result<usize> {
        Self::runtime().block_on(self.count_async())
    }

    async fn count_async(&self) -> Result<usize> {
        let mut response = with_db!(self, db, {
            db.query("SELECT count() AS c FROM knowledge GROUP ALL")
                .await
                .context("Failed to count knowledge entries")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let count = results.first().and_then(|v| v["c"].as_i64()).unwrap_or(0) as usize;
        Ok(count)
    }

    /// Graph health vitality percentages.
    ///
    /// Returns a JSON object:
    ///   { "total": N, "embedded": N, "anchored": N, "stale_high_res": N,
    ///     "embedded_pct": N, "anchored_pct": N, "stale_high_res_pct": N }
    ///
    /// Counts:
    ///   embedded      — entries with a non-null embedding vector
    ///   anchored      — entries with at least one anchor relationship
    ///   stale_high_res — high-resonance entries (resonance >= 5) not activated
    ///                   in the last 30 days (potentially stale knowledge)
    pub fn graph_health(&self) -> Result<serde_json::Value> {
        Self::runtime().block_on(self.graph_health_async())
    }

    async fn graph_health_async(&self) -> Result<serde_json::Value> {
        let mut response = with_db!(self, db, {
            db.query(
                "SELECT
                    count() AS total,
                    math::sum(IF embedding IS NOT NONE THEN 1 ELSE 0 END) AS embedded,
                    math::sum(IF anchors IS NOT NONE AND array::len(anchors) > 0 THEN 1 ELSE 0 END) AS anchored,
                    math::sum(IF (last_activated IS NONE OR last_activated < time::now() - duration::from::days(30)) AND resonance >= 5 THEN 1 ELSE 0 END) AS stale_high_res
                FROM knowledge GROUP ALL",
            )
            .await
            .context("Failed to query graph health")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let row = results.into_iter().next().unwrap_or_default();

        let total = row["total"].as_i64().unwrap_or(0);
        let embedded = row["embedded"].as_i64().unwrap_or(0);
        let anchored = row["anchored"].as_i64().unwrap_or(0);
        let stale_high_res = row["stale_high_res"].as_i64().unwrap_or(0);

        let pct = |n: i64| -> i64 {
            if total == 0 {
                0
            } else {
                (n * 100 + total / 2) / total
            }
        };

        Ok(serde_json::json!({
            "total": total,
            "embedded": embedded,
            "anchored": anchored,
            "stale_high_res": stale_high_res,
            "embedded_pct": pct(embedded),
            "anchored_pct": pct(anchored),
            "stale_high_res_pct": pct(stale_high_res),
        }))
    }

    /// Per-week entry counts over the last 8 weeks (oldest to newest).
    ///
    /// Returns a JSON array of up to 8 integers.  Weeks with no entries are
    /// represented as 0.  The array is always exactly 8 elements, padded with
    /// leading zeros when fewer than 8 weeks of data exist.
    pub fn growth_sparkline(&self) -> Result<serde_json::Value> {
        Self::runtime().block_on(self.growth_sparkline_async())
    }

    async fn growth_sparkline_async(&self) -> Result<serde_json::Value> {
        // Aggregated GROUP BY approach.
        // Uses the same duration syntax as the working recent-facts queries.
        // GROUP BY on the projected alias.
        let results: Vec<serde_json::Value> = {
            let mut response = with_db!(self, db, {
                db.query(
                    "SELECT
                        (<int>time::unix(<datetime>created_at) / 604800) AS week_bucket,
                        count() AS cnt
                    FROM knowledge
                    WHERE created_at > time::now() - duration::from::days(56)
                    GROUP BY week_bucket
                    ORDER BY week_bucket",
                )
                .await
                .context("Failed to query growth sparkline")
            })?;
            response.take(0).unwrap_or_default()
        };

        // Build a sorted map from week_bucket -> count
        let mut bucket_map: std::collections::BTreeMap<i64, i64> =
            std::collections::BTreeMap::new();
        for row in &results {
            let bucket = row["week_bucket"].as_i64().unwrap_or(0);
            let cnt = row["cnt"].as_i64().unwrap_or(0);
            bucket_map.insert(bucket, cnt);
        }

        // Fill 8 contiguous buckets ending at current week.
        // Note: dividing unix seconds by 604800 yields epoch-relative weeks
        // whose boundaries fall on Thursday 00:00 UTC (since the Unix epoch
        // was a Thursday).  The alignment is arbitrary but consistent.
        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        let current_bucket = now_secs / 604800;

        let counts: Vec<i64> = (0i64..8)
            .map(|offset| {
                let bucket = current_bucket - (7 - offset);
                *bucket_map.get(&bucket).unwrap_or(&0)
            })
            .collect();

        Ok(serde_json::json!(counts))
    }

    /// Open threads: knowledge entries with category:thread that are not closed.
    ///
    /// Returns a JSON array sorted by decay-weighted score (resonance * 0.95^weeks_old),
    /// newest/highest-resonance first.  Each element contains the fields the dashboard
    /// thread widget needs: id, body, state, created_at, resonance, tags.
    ///
    /// Open = summary IS NONE OR summary.state IS NONE OR summary.state = "open"
    pub fn open_threads(&self) -> Result<serde_json::Value> {
        Self::runtime().block_on(self.open_threads_async())
    }

    async fn open_threads_async(&self) -> Result<serde_json::Value> {
        let mut response = with_db!(self, db, {
            db.query(
                "SELECT
                    meta::id(id) AS id,
                    body,
                    summary,
                    <string>created_at AS created_at,
                    resonance,
                    ->tagged_with->tag.name AS tags
                FROM knowledge
                WHERE category = category:thread
                  AND (summary IS NONE OR summary.state IS NONE OR summary.state = 'open')
                ORDER BY created_at DESC",
            )
            .await
            .context("Failed to query open threads")
        })?;

        let rows: Vec<serde_json::Value> = response.take(0).unwrap_or_default();

        // Parse state from summary JSON; build output with stable shape
        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as f64)
            .unwrap_or(0.0);

        let mut threads: Vec<serde_json::Value> = rows
            .into_iter()
            .filter_map(|row| {
                let id = row["id"].as_str().unwrap_or("").to_string();
                if id.is_empty() {
                    return None;
                }

                let summary_raw = &row["summary"];
                let state = if summary_raw.is_null()
                    || summary_raw.is_string() && summary_raw.as_str().unwrap_or("").is_empty()
                {
                    "open".to_string()
                } else {
                    let s: serde_json::Value = if let Some(s) = summary_raw.as_str() {
                        serde_json::from_str(s).unwrap_or(serde_json::Value::Null)
                    } else {
                        summary_raw.clone()
                    };
                    s.get("state")
                        .and_then(|v| v.as_str())
                        .unwrap_or("open")
                        .to_string()
                };

                // Defensive: the DB-side WHERE already filters to open threads, but
                // summary can be a raw JSON string that needs client-side parsing
                // (see the deserialisation dance above), so we re-check here in case
                // the parsed state diverges from what SurrealQL evaluated.
                if state != "open" {
                    return None;
                }

                let resonance = row["resonance"].as_i64().unwrap_or(0);
                let created_at = row["created_at"].as_str().unwrap_or("").to_string();
                let tags = row["tags"].clone();

                Some(serde_json::json!({
                    "id": format!("kn-{}", id),
                    "body": row["body"],
                    "state": state,
                    "created_at": created_at,
                    "resonance": resonance,
                    "tags": tags,
                    // Include decay score for client-side sort verification
                    "_score": Self::decay_score(resonance, &created_at, now_secs),
                }))
            })
            .collect();

        // Sort by decay-weighted score descending
        threads.sort_by(|a, b| {
            let sa = a["_score"].as_f64().unwrap_or(0.0);
            let sb = b["_score"].as_f64().unwrap_or(0.0);
            sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal)
        });

        // Strip the internal _score field before returning
        for t in &mut threads {
            if let Some(obj) = t.as_object_mut() {
                obj.remove("_score");
            }
        }

        Ok(serde_json::json!(threads))
    }

    /// Decay-weighted score: resonance * 0.95^weeks_old
    ///
    /// If `created_at` cannot be parsed, we treat the entry as maximally old
    /// (52 weeks) so it sinks to the bottom rather than floating to the top
    /// with zero decay.
    fn decay_score(resonance: i64, created_at: &str, now_secs: f64) -> f64 {
        let weeks = chrono::DateTime::parse_from_rfc3339(&created_at.replace('Z', "+00:00"))
            .map(|dt| {
                let created_secs = dt.timestamp() as f64;
                (now_secs - created_secs) / (7.0 * 86400.0)
            })
            .unwrap_or(52.0);

        resonance as f64 * 0.95_f64.powf(weeks)
    }

    /// List all knowledge entries
    pub fn list_all(&self, ctx: &crate::store::AgentContext) -> Result<Vec<KnowledgeEntry>> {
        Self::runtime().block_on(self.list_all_async(ctx))
    }

    async fn list_all_async(
        &self,
        ctx: &crate::store::AgentContext,
    ) -> Result<Vec<KnowledgeEntry>> {
        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);

        // Convert AND to WHERE for list_all (no WHERE clause exists yet)
        let where_clause = visibility_clause.replacen("AND", "WHERE", 1);

        // ORDER BY id instead of title to avoid SurrealDB query planner
        // selecting BM25 full-text index (knowledge_title_fts) for sort
        // resolution, which crashes with "No iterator has been found".
        // See: coryzibell/mx#191
        let sql = format!(
            "SELECT {}
            FROM knowledge
            {}
            ORDER BY id",
            Self::knowledge_select_fields(),
            where_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db.query(&sql);
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to query all knowledge entries")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut entries = Vec::new();

        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// List entries by category
    pub fn list_by_category(
        &self,
        category: &str,
        ctx: &crate::store::AgentContext,
        filter: &crate::store::KnowledgeFilter,
    ) -> Result<Vec<KnowledgeEntry>> {
        Self::runtime().block_on(self.list_by_category_async(category, ctx, filter))
    }

    /// Fast count of entries in a category with the same visibility / resonance
    /// filtering as list_by_category, but returning only the integer count —
    /// no row hydration, no tag/applicability follow-up queries. Used by
    /// `mx memory stats` so it doesn't round-trip thousands of times per call
    /// when the db is remote.
    pub fn count_by_category(
        &self,
        category: &str,
        ctx: &crate::store::AgentContext,
        filter: &crate::store::KnowledgeFilter,
    ) -> Result<usize> {
        Self::runtime().block_on(self.count_by_category_async(category, ctx, filter))
    }

    async fn count_by_category_async(
        &self,
        category: &str,
        ctx: &crate::store::AgentContext,
        filter: &crate::store::KnowledgeFilter,
    ) -> Result<usize> {
        let category_thing = Thing::from(("category", category));
        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);
        let resonance_clause = Self::build_resonance_filter(filter);

        // NOTE: `SELECT count() FROM knowledge WHERE ... GROUP ALL` returns
        // the wrong number in SurrealDB 2.6 when a WHERE clause is present
        // (observed on 2.6.1: bloom with visibility='public' reports 986
        // instead of 260 — off by ~3-4x, seemingly counting some join
        // product). Wrapping the filter in a subquery that projects id only
        // gives the correct count and still avoids row hydration.
        let sql = format!(
            "SELECT count() AS c FROM (
                SELECT id FROM knowledge
                WHERE category = $category {} {}
            ) GROUP ALL",
            visibility_clause, resonance_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db.query(&sql).bind(("category", category_thing));
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to count knowledge by category")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let count = results.first().and_then(|v| v["c"].as_i64()).unwrap_or(0) as usize;
        Ok(count)
    }

    async fn list_by_category_async(
        &self,
        category: &str,
        ctx: &crate::store::AgentContext,
        filter: &crate::store::KnowledgeFilter,
    ) -> Result<Vec<KnowledgeEntry>> {
        let category_thing = Thing::from(("category", category));

        let (visibility_clause, current_agent) = Self::build_visibility_filter(ctx);
        let resonance_clause = Self::build_resonance_filter(filter);

        // ORDER BY id instead of title — see comment in list_all_async
        let sql = format!(
            "SELECT {}
            FROM knowledge
            WHERE category = $category {} {}
            ORDER BY id",
            Self::knowledge_select_fields(),
            visibility_clause,
            resonance_clause
        );

        let mut response = with_db!(self, db, {
            let mut query = db.query(&sql).bind(("category", category_thing));
            if let Some(agent) = current_agent {
                query = query.bind(("current_agent", agent));
            }
            query.await.context("Failed to query knowledge by category")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut entries = Vec::new();

        for obj in results {
            entries.push(self.value_to_knowledge_entry(obj).await?);
        }

        Ok(entries)
    }

    /// List sessions
    pub fn list_sessions(&self, _project_id: Option<&str>) -> Result<Vec<Session>> {
        // Not fully implemented yet - return empty
        Ok(vec![])
    }

    /// Get session by ID
    pub fn get_session(&self, _id: &str) -> Result<Option<Session>> {
        // Not fully implemented yet
        Ok(None)
    }

    /// Upsert session
    pub fn upsert_session(&self, _session: &Session) -> Result<()> {
        // Not fully implemented yet
        Ok(())
    }

    /// List source types
    pub fn list_source_types(&self) -> Result<Vec<SourceType>> {
        Self::runtime().block_on(self.list_source_types_async())
    }

    async fn list_source_types_async(&self) -> Result<Vec<SourceType>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, <string>created_at AS created_at FROM source_type ORDER BY id")
                .await
                .context("Failed to list source types")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut types = Vec::new();

        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            types.push(SourceType {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(types)
    }

    /// List entry types
    pub fn list_entry_types(&self) -> Result<Vec<EntryType>> {
        Self::runtime().block_on(self.list_entry_types_async())
    }

    async fn list_entry_types_async(&self) -> Result<Vec<EntryType>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, <string>created_at AS created_at FROM entry_type ORDER BY id")
                .await
                .context("Failed to list entry types")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut types = Vec::new();

        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            types.push(EntryType {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(types)
    }

    /// List content types
    pub fn list_content_types(&self) -> Result<Vec<ContentType>> {
        Self::runtime().block_on(self.list_content_types_async())
    }

    async fn list_content_types_async(&self) -> Result<Vec<ContentType>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, file_extensions, <string>created_at AS created_at FROM content_type ORDER BY id")
                .await
                .context("Failed to list content types")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut types = Vec::new();

        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            // Parse array of file extensions
            let file_extensions = obj["file_extensions"].as_array().map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect()
            });

            types.push(ContentType {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                file_extensions,
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(types)
    }

    /// List session types
    pub fn list_session_types(&self) -> Result<Vec<SessionType>> {
        Self::runtime().block_on(self.list_session_types_async())
    }

    async fn list_session_types_async(&self) -> Result<Vec<SessionType>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, <string>created_at AS created_at FROM session_type ORDER BY id")
                .await
                .context("Failed to list session types")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut types = Vec::new();

        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            types.push(SessionType {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(types)
    }

    /// List relationship types
    pub fn list_relationship_types(&self) -> Result<Vec<RelationshipType>> {
        Self::runtime().block_on(self.list_relationship_types_async())
    }

    async fn list_relationship_types_async(&self) -> Result<Vec<RelationshipType>> {
        let mut response = with_db!(self, db, {
            db.query("SELECT meta::id(id) AS id, description, directional, <string>created_at AS created_at FROM relationship_type ORDER BY id")
                .await
                .context("Failed to list relationship types")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;
        let mut types = Vec::new();

        for obj in results {
            // Parse string from id field
            let id = obj["id"].as_str().unwrap_or_default().to_string();

            types.push(RelationshipType {
                id,
                description: obj["description"].as_str().unwrap_or_default().to_string(),
                directional: obj["directional"].as_bool().unwrap_or(false),
                created_at: obj["created_at"].as_str().unwrap_or_default().to_string(),
            });
        }

        Ok(types)
    }

    // =========================================================================
    // WAKE SESSION OPERATIONS
    // =========================================================================

    /// Create a wake session record, return the session_id
    pub fn create_wake_session(&self, session: &crate::wake_token::WakeSession) -> Result<String> {
        Self::runtime().block_on(self.create_wake_session_async(session))
    }

    async fn create_wake_session_async(
        &self,
        session: &crate::wake_token::WakeSession,
    ) -> Result<String> {
        // Serialize bloom_chunk_meta as a JSON array. The schema field is
        // `flexible array<object>` so SurrealDB will accept arbitrary shape.
        let bloom_chunk_meta_json = serde_json::to_value(&session.bloom_chunk_meta)?;
        let created_at = chrono::DateTime::from_timestamp(session.created_at, 0)
            .unwrap_or_else(chrono::Utc::now)
            .to_rfc3339();

        let mut response = with_db!(self, db, {
            db.query(
                "CREATE type::thing('wake_session', $session_id) SET
                    bloom_ids = $bloom_ids,
                    current_index = $current_index,
                    current_chunk_index = $current_chunk_index,
                    step = $step,
                    attempts_on_current = $attempts_on_current,
                    remembered_count = $remembered_count,
                    needed_help_count = $needed_help_count,
                    skipped_count = $skipped_count,
                    created_at = <datetime>$created_at,
                    bloom_chunk_meta = $bloom_chunk_meta
                ",
            )
            .bind(("session_id", session.session_id.clone()))
            .bind(("bloom_ids", session.bloom_ids.clone()))
            .bind(("current_index", session.current_index as i64))
            .bind(("current_chunk_index", session.current_chunk_index as i64))
            .bind(("step", session.step as i64))
            .bind(("attempts_on_current", session.attempts_on_current as i64))
            .bind(("remembered_count", session.remembered_count as i64))
            .bind(("needed_help_count", session.needed_help_count as i64))
            .bind(("skipped_count", session.skipped_count as i64))
            .bind(("created_at", normalize_datetime(&created_at)))
            .bind(("bloom_chunk_meta", bloom_chunk_meta_json))
            .await
            .context("Failed to create wake session")
        })?;

        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!(
                "SurrealDB error creating wake session: {:?}",
                errors
            ));
        }

        Ok(session.session_id.clone())
    }

    /// Get a wake session by ID
    pub fn get_wake_session(
        &self,
        session_id: &str,
    ) -> Result<Option<crate::wake_token::WakeSession>> {
        Self::runtime().block_on(self.get_wake_session_async(session_id))
    }

    async fn get_wake_session_async(
        &self,
        session_id: &str,
    ) -> Result<Option<crate::wake_token::WakeSession>> {
        let mut response = with_db!(self, db, {
            db.query(
                "SELECT
                    meta::id(id) AS session_id,
                    bloom_ids,
                    current_index,
                    current_chunk_index,
                    step,
                    attempts_on_current,
                    remembered_count,
                    needed_help_count,
                    skipped_count,
                    <int>time::unix(<datetime>created_at) AS created_at,
                    bloom_chunk_meta
                FROM type::thing('wake_session', $session_id)",
            )
            .bind(("session_id", session_id.to_string()))
            .await
            .context("Failed to get wake session")
        })?;

        let results: Vec<serde_json::Value> = response.take(0)?;

        if results.is_empty() {
            return Ok(None);
        }

        let obj = &results[0];

        let session_id_str = obj["session_id"].as_str().unwrap_or_default().to_string();
        let bloom_ids: Vec<String> = obj["bloom_ids"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .filter_map(|v| v.as_str().map(|s| s.to_string()))
            .collect();
        let current_index = obj["current_index"].as_u64().unwrap_or(0) as usize;
        // Diffi flagged the previous `as u64 as u16` pattern as a silent-wrap
        // footgun — reaching u16::MAX requires ~2000x default-threshold chunks
        // today but the cast hides the failure mode. `try_from` surfaces an
        // out-of-range stored value as a deserialization error instead of
        // quietly producing a wrong cursor value.
        let raw_chunk_idx = obj["current_chunk_index"].as_u64().unwrap_or(0);
        let current_chunk_index = u16::try_from(raw_chunk_idx).map_err(|_| {
            anyhow::anyhow!(
                "wake_session.current_chunk_index {} exceeds u16::MAX; \
                 session is corrupt or schema has drifted",
                raw_chunk_idx
            )
        })?;
        let step = obj["step"].as_u64().unwrap_or(0) as u32;
        let attempts_on_current = obj["attempts_on_current"].as_u64().unwrap_or(0) as u8;
        let remembered_count = obj["remembered_count"].as_u64().unwrap_or(0) as u32;
        let needed_help_count = obj["needed_help_count"].as_u64().unwrap_or(0) as u32;
        let skipped_count = obj["skipped_count"].as_u64().unwrap_or(0) as u32;
        let created_at = obj["created_at"]
            .as_i64()
            .unwrap_or_else(|| chrono::Utc::now().timestamp());

        // Deserialize bloom_chunk_meta via serde_json. Absent/empty → default
        // to one meta per bloom_id marking every bloom as phraseless (safe
        // fallback that keeps the session walkable via skips).
        let bloom_chunk_meta: Vec<crate::wake_token::BloomChunkMeta> =
            match obj.get("bloom_chunk_meta") {
                Some(v) if !v.is_null() => serde_json::from_value(v.clone()).unwrap_or_default(),
                _ => Vec::new(),
            };
        let bloom_chunk_meta = if bloom_chunk_meta.len() == bloom_ids.len() {
            bloom_chunk_meta
        } else {
            // Length mismatch — rebuild default metadata so the session can
            // at least walk (all phraseless, will drop through skip path).
            bloom_ids
                .iter()
                .map(|_| crate::wake_token::BloomChunkMeta {
                    authored_phrase_count: 0,
                    is_phraseless: true,
                    ..Default::default()
                })
                .collect()
        };

        Ok(Some(crate::wake_token::WakeSession {
            session_id: session_id_str,
            bloom_ids,
            current_index,
            current_chunk_index,
            step,
            attempts_on_current,
            remembered_count,
            needed_help_count,
            skipped_count,
            created_at,
            bloom_chunk_meta,
        }))
    }

    /// Update an existing wake session
    pub fn update_wake_session(&self, session: &crate::wake_token::WakeSession) -> Result<()> {
        Self::runtime().block_on(self.update_wake_session_async(session))
    }

    async fn update_wake_session_async(
        &self,
        session: &crate::wake_token::WakeSession,
    ) -> Result<()> {
        let bloom_chunk_meta_json = serde_json::to_value(&session.bloom_chunk_meta)?;

        let mut response = with_db!(self, db, {
            db.query(
                "UPDATE type::thing('wake_session', $session_id) SET
                    current_index = $current_index,
                    current_chunk_index = $current_chunk_index,
                    step = $step,
                    attempts_on_current = $attempts_on_current,
                    remembered_count = $remembered_count,
                    needed_help_count = $needed_help_count,
                    skipped_count = $skipped_count,
                    bloom_chunk_meta = $bloom_chunk_meta
                ",
            )
            .bind(("session_id", session.session_id.clone()))
            .bind(("current_index", session.current_index as i64))
            .bind(("current_chunk_index", session.current_chunk_index as i64))
            .bind(("step", session.step as i64))
            .bind(("attempts_on_current", session.attempts_on_current as i64))
            .bind(("remembered_count", session.remembered_count as i64))
            .bind(("needed_help_count", session.needed_help_count as i64))
            .bind(("skipped_count", session.skipped_count as i64))
            .bind(("bloom_chunk_meta", bloom_chunk_meta_json))
            .await
            .context("Failed to update wake session")
        })?;

        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!(
                "SurrealDB error updating wake session: {:?}",
                errors
            ));
        }

        Ok(())
    }

    /// Delete a wake session
    pub fn delete_wake_session(&self, session_id: &str) -> Result<()> {
        Self::runtime().block_on(self.delete_wake_session_async(session_id))
    }

    async fn delete_wake_session_async(&self, session_id: &str) -> Result<()> {
        let mut response = with_db!(self, db, {
            db.query("DELETE type::thing('wake_session', $session_id)")
                .bind(("session_id", session_id.to_string()))
                .await
                .context("Failed to delete wake session")
        })?;

        let errors = response.take_errors();
        if !errors.is_empty() {
            return Err(anyhow::anyhow!(
                "SurrealDB error deleting wake session: {:?}",
                errors
            ));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::KnowledgeStore;

    #[test]
    fn test_open_in_memory() {
        // Test that database opens without error
        let _db = SurrealDatabase::open_in_memory().unwrap();
    }

    #[test]
    fn test_schema_applies_without_error() {
        // Opening applies schema - if this succeeds, schema is valid
        let _db = SurrealDatabase::open_in_memory().unwrap();
    }

    #[test]
    fn test_open_with_path() {
        use tempfile::tempdir;

        let temp_dir = tempdir().unwrap();
        let db_path = temp_dir.path().join("test.surreal");

        // Open database at specific path
        let _db = SurrealDatabase::open(&db_path).unwrap();

        // Verify directory was created
        assert!(db_path.exists());
        assert!(db_path.is_dir());
    }

    #[test]
    fn test_upsert_applicability_type_with_datetime() {
        use crate::types::ApplicabilityType;

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create an applicability type with RFC3339 datetime
        let atype = ApplicabilityType {
            id: "test_type".to_string(),
            description: "Test applicability type".to_string(),
            scope: Some("test".to_string()),
            created_at: "2025-11-29T12:00:00Z".to_string(),
        };

        // Upsert should succeed without datetime parsing errors
        // This was previously failing with: "Found '2025-11-29T...' for field `created_at`, but expected a datetime"
        db.upsert_applicability_type(&atype).unwrap();
    }

    #[test]
    fn test_upsert_project_with_datetime() {
        use crate::types::Project;

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create a project with RFC3339 datetimes
        let project = Project {
            id: "test_project".to_string(),
            name: "Test Project".to_string(),
            path: Some("/test/path".to_string()),
            repo_url: None,
            description: Some("Test description".to_string()),
            active: true,
            created_at: "2025-11-29T12:00:00Z".to_string(),
            updated_at: "2025-11-29T12:30:00Z".to_string(),
        };

        // Upsert should succeed without datetime parsing errors
        // This was previously failing with: "Found '2025-11-29T...' for field `created_at`, but expected a datetime"
        db.upsert_project(&project).unwrap();
    }

    #[test]
    fn test_upsert_agent_with_datetime() {
        use crate::types::Agent;

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create an agent with RFC3339 datetimes
        let agent = Agent {
            id: "test_agent".to_string(),
            description: Some("Test agent".to_string()),
            domain: Some("testing".to_string()),
            created_at: Some("2025-11-29T12:00:00Z".to_string()),
            updated_at: Some("2025-11-29T12:30:00Z".to_string()),
        };

        // Upsert should succeed without datetime parsing errors
        // This was previously failing with: "Found '2025-11-29T...' for field `created_at`, but expected a datetime"
        db.upsert_agent(&agent).unwrap();
    }

    // =========================================================================
    // PR #118 EDGE CASE TESTS
    // =========================================================================
    // These tests cover edge cases identified during code review of the
    // memory/fact unification. They ensure robustness of:
    // - Decay formula computation
    // - ID normalization
    // - Thread duplicate detection
    // - Session linkage
    // =========================================================================

    fn make_test_entry(
        id: &str,
        resonance: i32,
        decay_rate: f64,
    ) -> crate::knowledge::KnowledgeEntry {
        use chrono::Utc;
        let now = Utc::now().to_rfc3339();

        crate::knowledge::KnowledgeEntry {
            id: id.to_string(),
            category_id: "test".to_string(),
            title: format!("Test Entry {}", id),
            body: Some("Test body".to_string()),
            summary: None,
            applicability: vec![],
            source_project_id: None,
            source_agent_id: None,
            file_path: None,
            tags: vec![],
            created_at: Some(now.clone()),
            updated_at: Some(now.clone()),
            content_hash: Some("test-hash".to_string()),
            source_type_id: Some("manual".to_string()),
            entry_type_id: Some("primary".to_string()),
            session_id: None,
            ephemeral: false,
            content_type_id: Some("text".to_string()),
            owner: None,
            visibility: "public".to_string(),
            resonance,
            resonance_type: Some("ephemeral".to_string()),
            last_activated: Some(now),
            activation_count: 0,
            decay_rate,
            anchors: vec![],
            wake_phrases: vec![],
            wake_order: None,
            wake_phrase: None,
            embedding: None,
            embedding_model: None,
            embedded_at: None,
            format: "markdown".to_string(),
            effective_resonance: None,
        }
    }

    #[test]
    fn test_id_normalization_double_prefix() {
        // Edge case: IDs that already have "kn-" prefix get doubled during processing
        // Example: "kn-123" -> strip_prefix -> "123" -> add prefix -> "kn-123"
        // But what if someone passes "kn-kn-123"?

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Insert with normal ID
        let entry = make_test_entry("kn-test123", 5, 0.5);
        db.upsert_knowledge(&entry).unwrap();

        // Try to retrieve with double prefix
        let ctx = crate::store::AgentContext::public_only();
        let result = db.get("kn-kn-test123", &ctx).unwrap();

        // Should NOT find it (this is expected behavior - double prefix is invalid)
        assert!(result.is_none(), "Double prefix should not match");

        // But normal retrieval should work
        let result = db.get("kn-test123", &ctx).unwrap();
        assert!(result.is_some(), "Normal prefix should match");
    }

    #[test]
    fn test_id_normalization_case_sensitivity() {
        // Edge case: Are IDs case-sensitive? "KN-123" vs "kn-123"

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Insert with lowercase
        let entry = make_test_entry("kn-test456", 5, 0.5);
        db.upsert_knowledge(&entry).unwrap();

        // Try to retrieve with uppercase
        let ctx = crate::store::AgentContext::public_only();
        let result = db.get("KN-test456", &ctx).unwrap();

        // SurrealDB IDs are case-sensitive, so this should NOT match
        assert!(
            result.is_none(),
            "Uppercase KN should not match lowercase kn"
        );
    }

    #[test]
    fn test_id_normalization_empty_suffix() {
        // Edge case: What happens with just "kn-" and no suffix?

        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Try to get an entry with empty suffix
        let result = db.get("kn-", &ctx);

        // Should handle gracefully (likely return None, not panic)
        assert!(result.is_ok(), "Empty suffix should not panic");
    }

    #[test]
    fn test_id_normalization_no_prefix() {
        // Edge case: What if someone passes just "123" without "kn-"?

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Insert with full ID
        let entry = make_test_entry("kn-test789", 5, 0.5);
        db.upsert_knowledge(&entry).unwrap();

        // Try to retrieve without prefix
        let ctx = crate::store::AgentContext::public_only();
        let result = db.get("test789", &ctx).unwrap();

        // This SHOULD work because strip_prefix returns the original if no prefix found
        // and that gets stored as-is in SurrealDB
        // Actually, the ID gets normalized during insert, so "test789" should find it
        assert!(result.is_some(), "ID without prefix should still match");
    }

    #[test]
    fn test_decay_formula_zero_days() {
        // Edge case: What happens when last_activated is NOW (0 days ago)?
        // Formula: resonance * 0.95^(days / 7)
        // If days = 0: resonance * 0.95^0 = resonance * 1 = resonance

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create entry with ephemeral type and recent activation
        let entry = make_test_entry("kn-fresh", 10, 0.5);
        db.upsert_knowledge(&entry).unwrap();

        // Query recent facts (should include entries from today)
        let facts = db.query_recent_facts(1).unwrap();

        // Should find the entry
        assert!(!facts.is_empty(), "Should find fresh facts");

        // The effective_resonance should be close to original resonance (no decay yet)
        // We can't directly check the computed value here, but it shouldn't crash
    }

    #[test]
    fn test_decay_formula_negative_days() {
        // Edge case: What if duration::days() returns negative?
        // This shouldn't happen with (now - last_activated), but let's test boundary

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Query with negative days parameter
        let result = db.query_recent_facts(-1);

        // Should handle gracefully (likely return empty or error)
        assert!(result.is_ok(), "Negative days should not panic");
    }

    #[test]
    fn test_decay_formula_extreme_resonance() {
        // Edge case: Resonance can be > 10 for "transcendent" blooms
        // Make sure formula doesn't overflow or break

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create entry with extreme resonance (like Ori at 13)
        let mut entry = make_test_entry("kn-transcendent", 13, 0.0);
        entry.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Query recent facts
        let result = db.query_recent_facts(30);

        // Should not crash or overflow
        assert!(
            result.is_ok(),
            "Extreme resonance should not break decay formula"
        );

        let facts = result.unwrap();
        assert!(!facts.is_empty(), "Should find transcendent fact");
    }

    #[test]
    fn test_decay_formula_max_int_resonance() {
        // Edge case: What if resonance is i32::MAX?

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create entry with maximum resonance
        let mut entry = make_test_entry("kn-maxres", i32::MAX, 0.0);
        entry.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Query recent facts
        let result = db.query_recent_facts(30);

        // Should handle without overflow
        assert!(result.is_ok(), "MAX resonance should not overflow");
    }

    // =========================================================================
    // TIERED DECAY & BLOOM EXEMPTION TESTS
    // =========================================================================

    #[test]
    fn test_tiered_decay_low_resonance_ephemeral() {
        // Ephemeral entries with resonance <= 3 use 0.90^(weeks) decay rate (10%/week).
        // At 0 days, effective_resonance == resonance. Entry should be returned.

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut entry = make_test_entry("kn-low-res", 2, 0.0);
        entry.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&entry).unwrap();

        let result = db.query_recent_facts(7).unwrap();
        assert!(
            !result.is_empty(),
            "Low-resonance ephemeral entry should be returned when freshly created"
        );
    }

    #[test]
    fn test_tiered_decay_mid_resonance_ephemeral() {
        // Ephemeral entries with resonance 4-5 use 0.95^(weeks) decay rate (5%/week).

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut entry = make_test_entry("kn-mid-res", 5, 0.0);
        entry.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&entry).unwrap();

        let result = db.query_recent_facts(7).unwrap();
        assert!(
            !result.is_empty(),
            "Mid-resonance ephemeral entry should be returned when freshly created"
        );
    }

    #[test]
    fn test_tiered_decay_high_resonance_ephemeral() {
        // Ephemeral entries with resonance >= 6 use 0.975^(weeks) decay rate (2.5%/week).

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut entry = make_test_entry("kn-high-res", 7, 0.0);
        entry.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&entry).unwrap();

        let result = db.query_recent_facts(7).unwrap();
        assert!(
            !result.is_empty(),
            "High-resonance ephemeral entry should be returned when freshly created"
        );
    }

    #[test]
    fn test_tiered_decay_ordering_over_time() {
        // Verify that tiered decay produces different effective_resonance values over time.
        // A low-resonance entry (3, 10%/week) should decay faster than a high-resonance
        // entry (7, 2.5%/week) when both have the same last_activated 30 days ago.
        //
        // After 30 days (~4.3 weeks):
        //   low  (res=3): 3 * 0.90^(30/7) ≈ 3 * 0.64 ≈ 1.9 — below 0.5? No. Well above.
        //   high (res=7): 7 * 0.975^(30/7) ≈ 7 * 0.87 ≈ 6.1
        // High should rank higher. Both should pass the > 0.5 filter.
        use chrono::Utc;

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Backdate last_activated by 30 days so decay has measurably occurred
        let thirty_days_ago = (Utc::now() - chrono::Duration::days(30)).to_rfc3339();

        let mut low = make_test_entry("kn-decay-low", 3, 0.0);
        low.resonance_type = Some("ephemeral".to_string());
        low.last_activated = Some(thirty_days_ago.clone());
        db.upsert_knowledge(&low).unwrap();

        let mut high = make_test_entry("kn-decay-high", 7, 0.0);
        high.resonance_type = Some("ephemeral".to_string());
        high.last_activated = Some(thirty_days_ago);
        db.upsert_knowledge(&high).unwrap();

        // Query over 60 days so both entries fall within the window
        let results = db.query_recent_facts(60).unwrap();

        // Both entries should survive the > 0.5 filter
        let low_found = results.iter().any(|e| e.id == "kn-decay-low");
        let high_found = results.iter().any(|e| e.id == "kn-decay-high");
        assert!(
            low_found,
            "Low-resonance entry should still pass > 0.5 filter after 30 days"
        );
        assert!(
            high_found,
            "High-resonance entry should pass > 0.5 filter after 30 days"
        );

        // Results are ordered by effective_resonance DESC — high-res should appear first
        let low_pos = results.iter().position(|e| e.id == "kn-decay-low").unwrap();
        let high_pos = results
            .iter()
            .position(|e| e.id == "kn-decay-high")
            .unwrap();
        assert!(
            high_pos < low_pos,
            "High-resonance entry (slower decay) should rank above low-resonance entry after 30 days"
        );
    }

    #[test]
    fn test_bloom_exemption_foundational() {
        // Foundational entries are exempt from decay: effective_resonance == resonance.
        // They should NOT appear in query_recent_facts (which filters resonance_type = 'ephemeral'),
        // but should be directly retrievable.

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut entry = make_test_entry("kn-foundational", 9, 0.0);
        entry.resonance_type = Some("foundational".to_string());
        db.upsert_knowledge(&entry).unwrap();

        // query_recent_facts only returns ephemeral — foundational should NOT appear here
        let ephemeral_results = db.query_recent_facts(30).unwrap();
        let found_in_ephemeral = ephemeral_results.iter().any(|e| e.id == "kn-foundational");
        assert!(
            !found_in_ephemeral,
            "Foundational entry should not appear in ephemeral fact query"
        );

        // Should still be accessible via direct get
        let ctx = crate::store::AgentContext::public_only();
        let direct = db.get("kn-foundational", &ctx).unwrap();
        assert!(
            direct.is_some(),
            "Foundational entry should be directly retrievable"
        );
    }

    #[test]
    fn test_bloom_exemption_transformative() {
        // Transformative entries are exempt from decay, same as foundational.

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut entry = make_test_entry("kn-transformative", 8, 0.0);
        entry.resonance_type = Some("transformative".to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Should NOT appear in ephemeral query
        let ephemeral_results = db.query_recent_facts(30).unwrap();
        let found_in_ephemeral = ephemeral_results
            .iter()
            .any(|e| e.id == "kn-transformative");
        assert!(
            !found_in_ephemeral,
            "Transformative entry should not appear in ephemeral fact query"
        );

        let ctx = crate::store::AgentContext::public_only();
        let direct = db.get("kn-transformative", &ctx).unwrap();
        assert!(
            direct.is_some(),
            "Transformative entry should be directly retrievable"
        );
    }

    #[test]
    fn test_increment_activation_count_no_timestamp_reset() {
        // increment_activation_count should bump activation_count but leave
        // last_activated unchanged.

        let db = SurrealDatabase::open_in_memory().unwrap();

        let entry = make_test_entry("kn-incr-test", 5, 0.0);
        db.upsert_knowledge(&entry).unwrap();

        let ctx = crate::store::AgentContext::public_only();

        // Record initial state
        let before = db.get("kn-incr-test", &ctx).unwrap().unwrap();
        let initial_count = before.activation_count;
        let initial_last_activated = before.last_activated.clone();

        // Increment count only
        db.increment_activation_count(&["kn-incr-test".to_string()])
            .unwrap();

        let after = db.get("kn-incr-test", &ctx).unwrap().unwrap();

        assert_eq!(
            after.activation_count,
            initial_count + 1,
            "activation_count should increment by 1"
        );

        assert_eq!(
            after.last_activated, initial_last_activated,
            "last_activated should not be reset by increment_activation_count"
        );
    }

    #[test]
    fn test_thread_duplicate_detection() {
        // Edge case: How does duplicate detection work with normalized content?
        // KnowledgeEntry::normalize_content() is used for fuzzy matching

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create two entries with similar content but different formatting
        let entry1 = make_test_entry("kn-thread1", 5, 0.5);
        let mut entry2 = make_test_entry("kn-thread2", 5, 0.5);
        entry2.body = Some("  TEST   BODY  ".to_string()); // Different whitespace

        db.upsert_knowledge(&entry1).unwrap();
        db.upsert_knowledge(&entry2).unwrap();

        // Both should be stored (deduplication happens at application level, not DB)
        let ctx = crate::store::AgentContext::public_only();
        assert!(db.get("kn-thread1", &ctx).unwrap().is_some());
        assert!(db.get("kn-thread2", &ctx).unwrap().is_some());
    }

    #[test]
    fn test_session_linkage_round_trip() {
        // Edge case: Can we link a fact to a session and retrieve it back?

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create a session entry
        let session = make_test_entry("kn-session123", 0, 0.0);
        db.upsert_knowledge(&session).unwrap();

        // Create a fact linked to that session
        let mut fact = make_test_entry("kn-fact456", 5, 0.5);
        fact.session_id = Some("kn-session123".to_string());
        db.upsert_knowledge(&fact).unwrap();

        // Create relationship
        db.add_relationship("kn-fact456", "kn-session123", "extracted_from")
            .unwrap();

        // Query facts for session
        let facts = db.get_facts_for_session("kn-session123").unwrap();

        // Should find the linked fact
        assert_eq!(facts.len(), 1, "Should find one fact for session");
        assert_eq!(
            facts[0], "kn-fact456",
            "Should return full fact ID with prefix"
        );

        // Reverse lookup: get session for fact
        let session_id = db.get_session_for_fact("kn-fact456").unwrap();
        assert!(session_id.is_some(), "Should find session for fact");
        assert_eq!(
            session_id.unwrap(),
            "kn-session123",
            "Should return full session ID with prefix"
        );
    }

    #[test]
    fn test_session_linkage_multiple_facts() {
        // Edge case: Multiple facts from same session

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create session
        let session = make_test_entry("kn-multisession", 0, 0.0);
        db.upsert_knowledge(&session).unwrap();

        // Create multiple facts
        for i in 1..=5 {
            let mut fact = make_test_entry(&format!("kn-fact{}", i), 5, 0.5);
            fact.session_id = Some("kn-multisession".to_string());
            db.upsert_knowledge(&fact).unwrap();
            db.add_relationship(
                &format!("kn-fact{}", i),
                "kn-multisession",
                "extracted_from",
            )
            .unwrap();
        }

        // Query facts for session
        let facts = db.get_facts_for_session("kn-multisession").unwrap();

        // Should find all 5 facts
        assert_eq!(facts.len(), 5, "Should find all 5 facts for session");
    }

    #[test]
    fn test_session_linkage_orphaned_fact() {
        // Edge case: Fact with session_id but no relationship

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create fact with session_id but don't create relationship
        let mut fact = make_test_entry("kn-orphan", 5, 0.5);
        fact.session_id = Some("kn-ghost".to_string());
        db.upsert_knowledge(&fact).unwrap();

        // Query for session that doesn't exist
        let facts = db.get_facts_for_session("kn-ghost").unwrap();

        // Should return empty (relationship is what matters, not just session_id field)
        assert_eq!(
            facts.len(),
            0,
            "Orphaned fact should not appear without relationship"
        );

        // Reverse lookup should also fail
        let session = db.get_session_for_fact("kn-orphan").unwrap();
        assert!(session.is_none(), "Orphaned fact should have no session");
    }

    #[test]
    fn test_normalize_content_edge_cases() {
        // Test the normalize_content function used for thread matching
        use crate::knowledge::KnowledgeEntry;

        // Empty string
        assert_eq!(KnowledgeEntry::normalize_content(""), "");

        // Only whitespace
        assert_eq!(KnowledgeEntry::normalize_content("   \n\t  "), "");

        // Unicode characters
        let unicode = "Hello 世界! Привет мир!";
        let normalized = KnowledgeEntry::normalize_content(unicode);
        assert!(normalized.contains("hello"), "Should lowercase ASCII");
        assert!(normalized.contains("世界"), "Should preserve unicode");

        // Multiple spaces and newlines
        let messy = "  hello\n\n  world\t\ttest  ";
        assert_eq!(KnowledgeEntry::normalize_content(messy), "hello world test");
    }

    #[test]
    fn test_wake_cascade_empty_anchors() {
        // Edge case: What if a bloom has empty anchors array?

        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create bloom with no anchors
        let mut entry = make_test_entry("kn-solo", 9, 0.0);
        entry.resonance_type = Some("foundational".to_string());
        entry.anchors = vec![];
        db.upsert_knowledge(&entry).unwrap();

        // Query wake cascade
        let cascade = db.wake_cascade(&ctx, 50, Some(7), 7).unwrap();

        // Should still include the entry in core (high resonance)
        assert!(!cascade.core.is_empty(), "Should find core bloom");
        // Bridges might be empty since no anchors
        // This is expected behavior
    }

    #[test]
    fn test_wake_cascade_circular_anchors() {
        // Edge case: What if bloom A anchors to B, and B anchors to A?

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create two blooms that reference each other
        let mut bloom_a = make_test_entry("kn-circular-a", 9, 0.0);
        bloom_a.resonance_type = Some("foundational".to_string());
        bloom_a.anchors = vec!["kn-circular-b".to_string()];

        let mut bloom_b = make_test_entry("kn-circular-b", 9, 0.0);
        bloom_b.resonance_type = Some("foundational".to_string());
        bloom_b.anchors = vec!["kn-circular-a".to_string()];

        db.upsert_knowledge(&bloom_a).unwrap();
        db.upsert_knowledge(&bloom_b).unwrap();

        // Query wake cascade
        let ctx = crate::store::AgentContext::public_only();
        let result = db.wake_cascade(&ctx, 50, Some(7), 7);

        // Should handle circular references without infinite loop
        assert!(
            result.is_ok(),
            "Circular anchors should not cause infinite loop"
        );
    }

    #[test]
    fn test_privacy_filtering_public_only() {
        // Edge case: Public-only context should not see private entries

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create public entry
        let public_entry = make_test_entry("kn-public", 5, 0.5);
        db.upsert_knowledge(&public_entry).unwrap();

        // Create private entry
        let mut private_entry = make_test_entry("kn-private", 5, 0.5);
        private_entry.visibility = "private".to_string();
        private_entry.owner = Some("test_agent".to_string());
        db.upsert_knowledge(&private_entry).unwrap();

        // Query with public-only context
        let ctx = crate::store::AgentContext::public_only();

        // Should see public
        assert!(
            db.get("kn-public", &ctx).unwrap().is_some(),
            "Should see public entry"
        );

        // Should NOT see private
        assert!(
            db.get("kn-private", &ctx).unwrap().is_none(),
            "Should not see private entry"
        );
    }

    #[test]
    fn test_privacy_filtering_agent_context() {
        // Edge case: Agent should see their own private entries

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Create private entry for test_agent
        let mut private_entry = make_test_entry("kn-my-private", 5, 0.5);
        private_entry.visibility = "private".to_string();
        private_entry.owner = Some("test_agent".to_string());
        db.upsert_knowledge(&private_entry).unwrap();

        // Create private entry for other_agent
        let mut other_entry = make_test_entry("kn-other-private", 5, 0.5);
        other_entry.visibility = "private".to_string();
        other_entry.owner = Some("other_agent".to_string());
        db.upsert_knowledge(&other_entry).unwrap();

        // Query as test_agent
        let ctx = crate::store::AgentContext::for_agent("test_agent");

        // Should see own private entry
        assert!(
            db.get("kn-my-private", &ctx).unwrap().is_some(),
            "Should see own private entry"
        );

        // Should NOT see other agent's private entry
        assert!(
            db.get("kn-other-private", &ctx).unwrap().is_none(),
            "Should not see other's private entry"
        );
    }

    // =========================================================================
    // CROSS-AGENT VISIBILITY BYPASS TESTS (PR #186 / PR #187)
    // =========================================================================
    // These tests prove that the visibility filter on delete and update_summary
    // prevents cross-agent operations on private entries. Agent-b must not be
    // able to delete or update_summary on agent-a's private entries.

    #[test]
    fn test_delete_cross_agent_visibility_blocked() {
        // PR #186: delete must respect visibility. Agent-b cannot delete
        // agent-a's private entry.
        let db = SurrealDatabase::open_in_memory().unwrap();

        // Agent-a creates a private entry
        let mut entry = make_test_entry("kn-private-del-target", 5, 0.0);
        entry.visibility = "private".to_string();
        entry.owner = Some("agent-a".to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Agent-b attempts to delete it
        let ctx_b = crate::store::AgentContext::for_agent("agent-b");
        let result = db.delete("kn-private-del-target", &ctx_b).unwrap();
        assert!(
            !result,
            "agent-b should not be able to delete agent-a's private entry"
        );

        // Verify entry still exists for agent-a
        let ctx_a = crate::store::AgentContext::for_agent("agent-a");
        let still_exists = db.get("kn-private-del-target", &ctx_a).unwrap();
        assert!(
            still_exists.is_some(),
            "Entry should still exist for agent-a after failed cross-agent delete"
        );
    }

    #[test]
    fn test_update_summary_cross_agent_visibility_blocked() {
        // This branch's fix: update_summary must respect visibility.
        // Agent-b cannot update the summary of agent-a's private entry.
        let db = SurrealDatabase::open_in_memory().unwrap();

        // Agent-a creates a private entry with a summary
        let mut entry = make_test_entry("kn-private-summary-target", 5, 0.0);
        entry.visibility = "private".to_string();
        entry.owner = Some("agent-a".to_string());
        entry.summary = Some(r#"{"state":"open"}"#.to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Agent-b attempts to update the summary
        let ctx_b = crate::store::AgentContext::for_agent("agent-b");
        let result = db
            .update_summary(
                "kn-private-summary-target",
                r#"{"state":"compromised"}"#,
                &ctx_b,
            )
            .unwrap();
        assert!(
            !result,
            "agent-b should not be able to update summary on agent-a's private entry"
        );

        // Verify the original summary is unchanged for agent-a
        let ctx_a = crate::store::AgentContext::for_agent("agent-a");
        let unchanged = db
            .get("kn-private-summary-target", &ctx_a)
            .unwrap()
            .unwrap();
        let summary: serde_json::Value =
            serde_json::from_str(unchanged.summary.as_deref().unwrap()).unwrap();
        assert_eq!(
            summary["state"], "open",
            "Summary should be unchanged after failed cross-agent update"
        );
    }
    #[test]
    fn test_reinforce_basic() {
        // Test basic reinforcement functionality
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create an entry with resonance 5
        let mut entry = make_test_entry("kn-test-reinforce", 5, 0.0);
        entry.activation_count = 10;
        db.upsert_knowledge(&entry).unwrap();

        // Reinforce by 2, with cap of 10
        let result = db
            .reinforce("kn-test-reinforce", 2, Some(10), &ctx)
            .unwrap()
            .expect("reinforce should return Some for visible entry");

        // Verify results
        assert_eq!(result.id, "kn-test-reinforce");
        assert_eq!(result.old_resonance, 5);
        assert_eq!(result.new_resonance, 7);
        assert_eq!(result.amount_added, 2);
        assert!(!result.capped);
        assert_eq!(result.activation_count, 11);

        // Verify the entry was actually updated
        let updated = db.get("kn-test-reinforce", &ctx).unwrap().unwrap();
        assert_eq!(updated.resonance, 7);
        assert_eq!(updated.activation_count, 11);
        assert!(updated.last_activated.is_some());
    }

    #[test]
    fn test_reinforce_with_cap() {
        // Test that cap is enforced
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create an entry with resonance 9
        let entry = make_test_entry("kn-test-cap", 9, 0.0);
        db.upsert_knowledge(&entry).unwrap();

        // Try to reinforce by 5, but cap at 10
        let result = db
            .reinforce("kn-test-cap", 5, Some(10), &ctx)
            .unwrap()
            .expect("reinforce should return Some for visible entry");

        // Should be capped at 10
        assert_eq!(result.old_resonance, 9);
        assert_eq!(result.new_resonance, 10);
        assert_eq!(result.amount_added, 5);
        assert!(result.capped);

        // Verify the entry was capped
        let updated = db.get("kn-test-cap", &ctx).unwrap().unwrap();
        assert_eq!(updated.resonance, 10);
    }

    #[test]
    fn test_reinforce_without_cap() {
        // Test reinforcement without a cap (for transcendent blooms)
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create an entry with resonance 9
        let entry = make_test_entry("kn-test-no-cap", 9, 0.0);
        db.upsert_knowledge(&entry).unwrap();

        // Reinforce by 5 with no cap
        let result = db
            .reinforce("kn-test-no-cap", 5, None, &ctx)
            .unwrap()
            .expect("reinforce should return Some for visible entry");

        // Should go above 10
        assert_eq!(result.old_resonance, 9);
        assert_eq!(result.new_resonance, 14);
        assert!(!result.capped);

        // Verify the entry was updated
        let updated = db.get("kn-test-no-cap", &ctx).unwrap().unwrap();
        assert_eq!(updated.resonance, 14);
    }

    #[test]
    fn test_reinforce_nonexistent() {
        // Test that reinforcing a nonexistent entry returns None
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        let result = db.reinforce("kn-nonexistent", 1, Some(10), &ctx).unwrap();
        assert!(
            result.is_none(),
            "reinforce should return None for nonexistent entry"
        );
    }

    #[test]
    fn test_reinforce_id_normalization() {
        // Test that ID normalization works
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create entry with full ID
        let entry = make_test_entry("kn-test-norm", 5, 0.0);
        db.upsert_knowledge(&entry).unwrap();

        // Reinforce with partial ID (no "kn-" prefix)
        let result = db
            .reinforce("test-norm", 2, Some(10), &ctx)
            .unwrap()
            .expect("reinforce should return Some for visible entry");

        // Should normalize correctly
        assert_eq!(result.id, "kn-test-norm");
        assert_eq!(result.new_resonance, 7);
    }

    #[test]
    fn test_reinforce_cross_agent_visibility_blocked() {
        // Fix #157: reinforce must respect visibility.
        // Agent-b cannot reinforce agent-a's private entry.
        let db = SurrealDatabase::open_in_memory().unwrap();

        // Agent-a creates a private entry with known resonance
        let mut entry = make_test_entry("kn-private-reinforce-target", 5, 0.0);
        entry.visibility = "private".to_string();
        entry.owner = Some("agent-a".to_string());
        entry.activation_count = 3;
        db.upsert_knowledge(&entry).unwrap();

        // Agent-b attempts to reinforce it
        let ctx_b = crate::store::AgentContext::for_agent("agent-b");
        let result = db
            .reinforce("kn-private-reinforce-target", 2, Some(10), &ctx_b)
            .unwrap();
        assert!(
            result.is_none(),
            "agent-b should not be able to reinforce agent-a's private entry"
        );

        // Verify the entry is unchanged for agent-a
        let ctx_a = crate::store::AgentContext::for_agent("agent-a");
        let unchanged = db
            .get("kn-private-reinforce-target", &ctx_a)
            .unwrap()
            .unwrap();
        assert_eq!(
            unchanged.resonance, 5,
            "Resonance should be unchanged after failed cross-agent reinforce"
        );
        assert_eq!(
            unchanged.activation_count, 3,
            "Activation count should be unchanged after failed cross-agent reinforce"
        );
    }

    #[test]
    fn test_reinforce_own_private_entry() {
        // Agent-a should be able to reinforce their own private entry
        let db = SurrealDatabase::open_in_memory().unwrap();

        // Agent-a creates a private entry
        let mut entry = make_test_entry("kn-private-reinforce-own", 5, 0.0);
        entry.visibility = "private".to_string();
        entry.owner = Some("agent-a".to_string());
        entry.activation_count = 3;
        db.upsert_knowledge(&entry).unwrap();

        // Agent-a reinforces their own entry
        let ctx_a = crate::store::AgentContext::for_agent("agent-a");
        let result = db
            .reinforce("kn-private-reinforce-own", 2, Some(10), &ctx_a)
            .unwrap()
            .expect("agent-a should be able to reinforce their own private entry");

        assert_eq!(result.old_resonance, 5);
        assert_eq!(result.new_resonance, 7);
        assert_eq!(result.activation_count, 4);

        // Verify it actually persisted
        let updated = db.get("kn-private-reinforce-own", &ctx_a).unwrap().unwrap();
        assert_eq!(updated.resonance, 7);
        assert_eq!(updated.activation_count, 4);
    }

    #[test]
    fn test_update_summary_persists() {
        // Regression: thread_closed handler modified summary in memory but
        // upsert_knowledge() silently failed on SCHEMAFULL tables. The new
        // update_summary() path must actually persist the change.
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create entry with initial summary (simulating an open thread)
        let mut entry = make_test_entry("kn-summary-test", 5, 0.0);
        entry.summary = Some(r#"{"state":"open","topic":"test thread"}"#.to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Update summary to closed state (mirrors thread_closed handler)
        let new_summary = r#"{"state":"closed","topic":"test thread"}"#;
        let result = db
            .update_summary("kn-summary-test", new_summary, &ctx)
            .unwrap();
        assert!(
            result,
            "update_summary should return true for visible entry"
        );

        // Read it back and verify the change persisted
        let updated = db.get("kn-summary-test", &ctx).unwrap().unwrap();
        let summary: serde_json::Value =
            serde_json::from_str(updated.summary.as_deref().unwrap()).unwrap();
        assert_eq!(summary["state"], "closed");
        assert_eq!(summary["topic"], "test thread");
    }

    #[test]
    fn test_update_summary_id_normalization() {
        // update_summary should accept IDs with or without "kn-" prefix,
        // consistent with get(), delete(), reinforce(), etc.
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        let mut entry = make_test_entry("kn-summary-norm", 5, 0.0);
        entry.summary = Some(r#"{"state":"open"}"#.to_string());
        db.upsert_knowledge(&entry).unwrap();

        // Update using raw ID (no prefix) - should still work
        let result = db
            .update_summary("summary-norm", r#"{"state":"closed"}"#, &ctx)
            .unwrap();
        assert!(result, "update_summary should return true with raw ID");

        let updated = db.get("kn-summary-norm", &ctx).unwrap().unwrap();
        let summary: serde_json::Value =
            serde_json::from_str(updated.summary.as_deref().unwrap()).unwrap();
        assert_eq!(summary["state"], "closed");

        // Update using prefixed ID - should also work
        let result2 = db
            .update_summary("kn-summary-norm", r#"{"state":"reopened"}"#, &ctx)
            .unwrap();
        assert!(
            result2,
            "update_summary should return true with prefixed ID"
        );

        let updated2 = db.get("kn-summary-norm", &ctx).unwrap().unwrap();
        let summary2: serde_json::Value =
            serde_json::from_str(updated2.summary.as_deref().unwrap()).unwrap();
        assert_eq!(summary2["state"], "reopened");
    }

    #[test]
    fn test_close_thread_with_no_summary() {
        // A thread entry with no summary (pre-convention) should accept a
        // closed-state summary written by the thread_closed handler.
        let db = SurrealDatabase::open_in_memory().unwrap();
        let ctx = crate::store::AgentContext::public_only();

        // Create a thread entry with no summary (pre-convention style)
        let mut entry = make_test_entry("kn-no-summary-thread", 5, 0.0);
        entry.summary = None;
        db.upsert_knowledge(&entry).unwrap();

        // The thread_closed handler writes the closed state via update_summary
        let closed_summary = r#"{"state":"closed","topic":"pre-convention thread"}"#;
        let result = db
            .update_summary("kn-no-summary-thread", closed_summary, &ctx)
            .unwrap();
        assert!(
            result,
            "update_summary should return true for entry with no prior summary"
        );

        // Verify the state persisted correctly
        let updated = db.get("kn-no-summary-thread", &ctx).unwrap().unwrap();
        let summary: serde_json::Value =
            serde_json::from_str(updated.summary.as_deref().unwrap()).unwrap();
        assert_eq!(summary["state"], "closed");
        assert_eq!(summary["topic"], "pre-convention thread");
    }

    #[test]
    fn test_get_summary_state_returns_none_for_no_summary() {
        // Confirms the get_summary_state() helper returns None for entries
        // with no summary — the condition that find_open_thread_by_content
        // treats as "potentially open" (pre-convention threads).
        let entry = make_test_entry("kn-state-none", 5, 0.0);
        // make_test_entry sets summary: None by default
        assert!(
            entry.summary.is_none(),
            "make_test_entry should produce summary: None"
        );
        assert_eq!(
            entry.get_summary_state(),
            None,
            "get_summary_state() must return None when summary is absent"
        );
    }

    #[test]
    fn test_query_recent_facts_all_types_includes_foundational() {
        // query_recent_facts_all_types should return foundational entries that would
        // be excluded from query_recent_facts (ephemeral-only).

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut foundational = make_test_entry("kn-all-types-foundational", 9, 0.0);
        foundational.resonance_type = Some("foundational".to_string());
        db.upsert_knowledge(&foundational).unwrap();

        let mut ephemeral = make_test_entry("kn-all-types-ephemeral", 5, 0.0);
        ephemeral.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&ephemeral).unwrap();

        // Baseline: ephemeral-only query should not include foundational
        let ephemeral_results = db.query_recent_facts(30).unwrap();
        assert!(
            !ephemeral_results
                .iter()
                .any(|e| e.id == "kn-all-types-foundational"),
            "Foundational entry should not appear in ephemeral-only query"
        );
        assert!(
            ephemeral_results
                .iter()
                .any(|e| e.id == "kn-all-types-ephemeral"),
            "Ephemeral entry should appear in ephemeral-only query"
        );

        // All-types query should include both
        let all_results = db.query_recent_facts_all_types(30).unwrap();
        assert!(
            all_results
                .iter()
                .any(|e| e.id == "kn-all-types-foundational"),
            "Foundational entry should appear in all-types query"
        );
        assert!(
            all_results.iter().any(|e| e.id == "kn-all-types-ephemeral"),
            "Ephemeral entry should appear in all-types query"
        );
    }

    #[test]
    fn test_query_recent_facts_all_types_includes_transformative() {
        // query_recent_facts_all_types should return transformative entries.

        let db = SurrealDatabase::open_in_memory().unwrap();

        let mut transformative = make_test_entry("kn-all-types-transformative", 8, 0.0);
        transformative.resonance_type = Some("transformative".to_string());
        db.upsert_knowledge(&transformative).unwrap();

        let all_results = db.query_recent_facts_all_types(30).unwrap();
        assert!(
            all_results
                .iter()
                .any(|e| e.id == "kn-all-types-transformative"),
            "Transformative entry should appear in all-types query"
        );
    }

    #[test]
    fn test_query_recent_facts_all_types_respects_decay_threshold() {
        // Entries with near-zero effective resonance (very old, low base) should
        // be excluded even from the all-types query (threshold > 0.5).

        let db = SurrealDatabase::open_in_memory().unwrap();

        // Resonance 1 with heavy decay (80 weeks ago equivalent = decay_rate abuse).
        // We simulate a very old entry by setting last_activated far in the past.
        // For this test we just confirm high-resonance entries are returned.
        let mut high = make_test_entry("kn-all-types-high", 8, 0.0);
        high.resonance_type = Some("ephemeral".to_string());
        db.upsert_knowledge(&high).unwrap();

        let results = db.query_recent_facts_all_types(30).unwrap();
        assert!(
            results.iter().any(|e| e.id == "kn-all-types-high"),
            "High-resonance ephemeral entry should appear in all-types query"
        );
    }

    // =========================================================================
    // list_all_tags TESTS (PR #147)
    // =========================================================================

    fn make_tagged_entry(
        id: &str,
        category: &str,
        tags: Vec<String>,
    ) -> crate::knowledge::KnowledgeEntry {
        let mut entry = make_test_entry(id, 5, 0.0);
        entry.category_id = category.to_string();
        entry.tags = tags;
        entry
    }

    #[test]
    fn test_list_all_tags_returns_distinct_tags() {
        let db = SurrealDatabase::open_in_memory().unwrap();

        let entry1 = make_tagged_entry(
            "kn-tag1",
            "pattern",
            vec!["rust".to_string(), "async".to_string()],
        );
        db.upsert_knowledge(&entry1).unwrap();

        let entry2 = make_tagged_entry(
            "kn-tag2",
            "technique",
            vec!["rust".to_string(), "error-handling".to_string()],
        );
        db.upsert_knowledge(&entry2).unwrap();

        let tags = db.list_all_tags(None).unwrap();
        assert_eq!(tags.len(), 3);
        assert_eq!(tags, vec!["async", "error-handling", "rust"]);
    }

    #[test]
    fn test_list_all_tags_with_category_filter() {
        let db = SurrealDatabase::open_in_memory().unwrap();

        let entry1 = make_tagged_entry(
            "kn-tag3",
            "pattern",
            vec!["rust".to_string(), "async".to_string()],
        );
        db.upsert_knowledge(&entry1).unwrap();

        let entry2 = make_tagged_entry(
            "kn-tag4",
            "technique",
            vec!["rust".to_string(), "error-handling".to_string()],
        );
        db.upsert_knowledge(&entry2).unwrap();

        let pattern_tags = db.list_all_tags(Some("pattern")).unwrap();
        assert_eq!(pattern_tags.len(), 2);
        assert_eq!(pattern_tags, vec!["async", "rust"]);

        let technique_tags = db.list_all_tags(Some("technique")).unwrap();
        assert_eq!(technique_tags.len(), 2);
        assert_eq!(technique_tags, vec!["error-handling", "rust"]);
    }

    #[test]
    fn test_list_all_tags_empty_database() {
        let db = SurrealDatabase::open_in_memory().unwrap();

        let tags = db.list_all_tags(None).unwrap();
        assert!(tags.is_empty());

        let tags = db.list_all_tags(Some("pattern")).unwrap();
        assert!(tags.is_empty());
    }
}