symbi-runtime 1.10.0

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

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::fs;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::RwLock;

use super::embedding::create_embedding_service_from_env;
use super::types::*;
use super::vector_db::{EmbeddingService, NoOpVectorDatabase, QdrantConfig};
use super::vector_db_factory::{create_vector_backend, resolve_vector_config, VectorBackendConfig};
use super::vector_db_trait::VectorDb;
use crate::integrations::policy_engine::{MockPolicyEngine, PolicyEngine};
use crate::secrets::{SecretStore, SecretsConfig};
use crate::types::AgentId;

/// Context Manager trait for agent memory and knowledge management
#[async_trait]
pub trait ContextManager: Send + Sync {
    /// Store agent context
    async fn store_context(
        &self,
        agent_id: AgentId,
        context: AgentContext,
    ) -> Result<ContextId, ContextError>;

    /// Retrieve agent context
    async fn retrieve_context(
        &self,
        agent_id: AgentId,
        session_id: Option<SessionId>,
    ) -> Result<Option<AgentContext>, ContextError>;

    /// Query context with semantic search
    async fn query_context(
        &self,
        agent_id: AgentId,
        query: ContextQuery,
    ) -> Result<Vec<ContextItem>, ContextError>;

    /// Update specific memory items
    async fn update_memory(
        &self,
        agent_id: AgentId,
        memory_updates: Vec<MemoryUpdate>,
    ) -> Result<(), ContextError>;

    /// Add knowledge to agent's knowledge base
    async fn add_knowledge(
        &self,
        agent_id: AgentId,
        knowledge: Knowledge,
    ) -> Result<KnowledgeId, ContextError>;

    /// Search knowledge base
    async fn search_knowledge(
        &self,
        agent_id: AgentId,
        query: &str,
        limit: usize,
    ) -> Result<Vec<KnowledgeItem>, ContextError>;

    /// Share knowledge between agents
    async fn share_knowledge(
        &self,
        from_agent: AgentId,
        to_agent: AgentId,
        knowledge_id: KnowledgeId,
        access_level: AccessLevel,
    ) -> Result<(), ContextError>;

    /// Get shared knowledge available to agent
    async fn get_shared_knowledge(
        &self,
        agent_id: AgentId,
    ) -> Result<Vec<SharedKnowledgeRef>, ContextError>;

    /// Archive old context based on retention policy
    async fn archive_context(
        &self,
        agent_id: AgentId,
        before: SystemTime,
    ) -> Result<u32, ContextError>;

    /// Get context statistics
    async fn get_context_stats(&self, agent_id: AgentId) -> Result<ContextStats, ContextError>;

    /// Shutdown the context manager gracefully
    async fn shutdown(&self) -> Result<(), ContextError>;
}

/// Standard implementation of ContextManager.
///
/// PERF: The contexts map uses a single RwLock. Under high concurrency
/// (many agents storing/retrieving simultaneously), consider migrating to
/// per-agent locking (HashMap<AgentId, Arc<RwLock<AgentContext>>>) or
/// dashmap to reduce contention.
pub struct StandardContextManager {
    /// In-memory storage for contexts (cache layer)
    contexts: Arc<RwLock<HashMap<AgentId, AgentContext>>>,
    /// Configuration for the context manager
    config: ContextManagerConfig,
    /// Shared knowledge store
    shared_knowledge: Arc<RwLock<HashMap<KnowledgeId, SharedKnowledgeItem>>>,
    /// Vector database for semantic search and knowledge storage
    vector_db: Arc<dyn VectorDb>,
    /// Embedding service for generating vector embeddings
    embedding_service: Arc<dyn EmbeddingService>,
    /// Persistent storage for contexts
    persistence: Arc<dyn ContextPersistence>,
    /// Secrets store for secure secret management
    secrets: Box<dyn SecretStore + Send + Sync>,
    /// Policy engine for access control and permissions
    #[allow(dead_code)]
    policy_engine: Arc<dyn PolicyEngine>,
    /// Shutdown flag to ensure idempotent shutdown
    shutdown_flag: Arc<RwLock<bool>>,
    /// Background task handles (for future retention scheduler)
    background_tasks: Arc<RwLock<Vec<tokio::task::JoinHandle<()>>>>,
}

/// Configuration for the Context Manager
#[derive(Debug, Clone)]
pub struct ContextManagerConfig {
    /// Maximum number of contexts to keep in memory
    pub max_contexts_in_memory: usize,
    /// Default retention policy for new contexts
    pub default_retention_policy: RetentionPolicy,
    /// Enable automatic archiving
    pub enable_auto_archiving: bool,
    /// Archiving check interval
    pub archiving_interval: std::time::Duration,
    /// Maximum memory items per agent
    pub max_memory_items_per_agent: usize,
    /// Maximum knowledge items per agent
    pub max_knowledge_items_per_agent: usize,
    /// Vector backend configuration (if set, used instead of qdrant_config)
    pub vector_backend: Option<VectorBackendConfig>,
    /// Qdrant vector database configuration (legacy, use vector_backend instead)
    pub qdrant_config: QdrantConfig,
    /// Enable vector database integration
    pub enable_vector_db: bool,
    /// File persistence configuration
    pub persistence_config: FilePersistenceConfig,
    /// Enable persistent storage
    pub enable_persistence: bool,
    /// Secrets configuration for secure secret management
    pub secrets_config: SecretsConfig,
}

impl Default for ContextManagerConfig {
    fn default() -> Self {
        use std::path::PathBuf;

        Self {
            max_contexts_in_memory: 1000,
            default_retention_policy: RetentionPolicy::default(),
            enable_auto_archiving: true,
            archiving_interval: std::time::Duration::from_secs(3600), // 1 hour
            max_memory_items_per_agent: 10000,
            max_knowledge_items_per_agent: 5000,
            vector_backend: None,
            qdrant_config: QdrantConfig::default(),
            enable_vector_db: false,
            persistence_config: FilePersistenceConfig::default(),
            enable_persistence: true,
            secrets_config: SecretsConfig::file_json(PathBuf::from("secrets.json")),
        }
    }
}

/// Configuration for importance calculation weights
#[derive(Debug, Clone)]
struct ImportanceWeights {
    /// Weight for base importance score
    pub base_importance: f32,
    /// Weight for access frequency factor
    pub access_frequency: f32,
    /// Weight for recency factor
    pub recency: f32,
    /// Weight for user feedback factor
    pub user_feedback: f32,
    /// Penalty for memories that have never been accessed
    pub no_access_penalty: f32,
}

impl Default for ImportanceWeights {
    fn default() -> Self {
        Self {
            base_importance: 0.3,
            access_frequency: 0.25,
            recency: 0.3,
            user_feedback: 0.15,
            no_access_penalty: 0.1,
        }
    }
}

/// Shared knowledge item with metadata
#[derive(Debug, Clone)]
struct SharedKnowledgeItem {
    knowledge: Knowledge,
    source_agent: AgentId,
    access_level: AccessLevel,
    created_at: SystemTime,
    access_count: u32,
}

/// Archived context structure for storing old items
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ArchivedContext {
    agent_id: AgentId,
    archived_at: SystemTime,
    archive_reason: String,
    memory: HierarchicalMemory,
    conversation_history: Vec<ConversationItem>,
    knowledge_base: KnowledgeBase,
    metadata: HashMap<String, String>,
}

impl ArchivedContext {
    fn new(agent_id: AgentId, before: SystemTime) -> Self {
        Self {
            agent_id,
            archived_at: SystemTime::now(),
            archive_reason: format!("Archiving items before {:?}", before),
            memory: HierarchicalMemory::default(),
            conversation_history: Vec::new(),
            knowledge_base: KnowledgeBase::default(),
            metadata: HashMap::new(),
        }
    }
}

/// File-based persistence implementation
pub struct FilePersistence {
    config: FilePersistenceConfig,
}

impl FilePersistence {
    /// Create a new FilePersistence instance
    pub fn new(config: FilePersistenceConfig) -> Self {
        Self { config }
    }

    /// Initialize storage directory
    pub async fn initialize(&self) -> Result<(), ContextError> {
        self.config
            .ensure_directories()
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to create storage directories: {}", e),
            })?;
        Ok(())
    }

    /// Get file path for agent context
    fn get_context_path(&self, agent_id: AgentId) -> PathBuf {
        let filename = if self.config.enable_compression {
            format!("{}.json.gz", agent_id)
        } else {
            format!("{}.json", agent_id)
        };
        self.config.agent_contexts_path().join(filename)
    }

    /// Serialize context to bytes
    async fn serialize_context(&self, context: &AgentContext) -> Result<Vec<u8>, ContextError> {
        let json_data =
            serde_json::to_vec_pretty(context).map_err(|e| ContextError::SerializationError {
                reason: format!("Failed to serialize context: {}", e),
            })?;

        if self.config.enable_compression {
            use flate2::write::GzEncoder;
            use flate2::Compression;
            use std::io::Write;

            let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
            encoder
                .write_all(&json_data)
                .map_err(|e| ContextError::SerializationError {
                    reason: format!("Failed to compress context: {}", e),
                })?;
            encoder
                .finish()
                .map_err(|e| ContextError::SerializationError {
                    reason: format!("Failed to finalize compression: {}", e),
                })
        } else {
            Ok(json_data)
        }
    }

    /// Deserialize context from bytes
    async fn deserialize_context(&self, data: Vec<u8>) -> Result<AgentContext, ContextError> {
        let json_data = if self.config.enable_compression {
            use flate2::read::GzDecoder;
            use std::io::Read;

            let mut decoder = GzDecoder::new(&data[..]);
            let mut decompressed = Vec::new();
            decoder.read_to_end(&mut decompressed).map_err(|e| {
                ContextError::SerializationError {
                    reason: format!("Failed to decompress context: {}", e),
                }
            })?;
            decompressed
        } else {
            data
        };

        serde_json::from_slice(&json_data).map_err(|e| ContextError::SerializationError {
            reason: format!("Failed to deserialize context: {}", e),
        })
    }

    /// Create backup of existing context file
    async fn create_backup(&self, agent_id: AgentId) -> Result<(), ContextError> {
        let context_path = self.get_context_path(agent_id);
        if !context_path.exists() {
            return Ok(());
        }

        let backup_path = context_path.with_extension(format!(
            "backup.{}.json",
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
        ));

        fs::copy(&context_path, &backup_path)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to create backup: {}", e),
            })?;

        // Clean up old backups
        self.cleanup_old_backups(agent_id).await?;
        Ok(())
    }

    /// Clean up old backup files
    async fn cleanup_old_backups(&self, agent_id: AgentId) -> Result<(), ContextError> {
        let mut backup_files = Vec::new();
        let mut dir = fs::read_dir(&self.config.agent_contexts_path())
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read storage directory: {}", e),
            })?;

        while let Some(entry) = dir
            .next_entry()
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read directory entry: {}", e),
            })?
        {
            let path = entry.path();
            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                if filename.starts_with(&format!("{}.backup.", agent_id)) {
                    if let Ok(metadata) = entry.metadata().await {
                        if let Ok(modified) = metadata.modified() {
                            backup_files.push((path, modified));
                        }
                    }
                }
            }
        }

        // Sort by modification time (newest first)
        backup_files.sort_by(|a, b| b.1.cmp(&a.1));

        // Remove excess backups
        for (path, _) in backup_files.into_iter().skip(self.config.backup_count) {
            if let Err(e) = fs::remove_file(&path).await {
                eprintln!(
                    "Warning: Failed to remove old backup {}: {}",
                    path.display(),
                    e
                );
            }
        }

        Ok(())
    }
}

#[async_trait]
impl ContextPersistence for FilePersistence {
    async fn save_context(
        &self,
        agent_id: AgentId,
        context: &AgentContext,
    ) -> Result<(), ContextError> {
        // Create backup of existing context
        self.create_backup(agent_id).await?;

        // Serialize context
        let data = self.serialize_context(context).await?;

        // Write to file
        let context_path = self.get_context_path(agent_id);
        let mut file =
            fs::File::create(&context_path)
                .await
                .map_err(|e| ContextError::StorageError {
                    reason: format!("Failed to create context file: {}", e),
                })?;

        file.write_all(&data)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to write context data: {}", e),
            })?;

        file.sync_all()
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to sync context file: {}", e),
            })?;

        Ok(())
    }

    async fn load_context(&self, agent_id: AgentId) -> Result<Option<AgentContext>, ContextError> {
        let context_path = self.get_context_path(agent_id);

        if !context_path.exists() {
            return Ok(None);
        }

        let mut file =
            fs::File::open(&context_path)
                .await
                .map_err(|e| ContextError::StorageError {
                    reason: format!("Failed to open context file: {}", e),
                })?;

        let mut data = Vec::new();
        file.read_to_end(&mut data)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read context file: {}", e),
            })?;

        let context = self.deserialize_context(data).await?;
        Ok(Some(context))
    }

    async fn delete_context(&self, agent_id: AgentId) -> Result<(), ContextError> {
        let context_path = self.get_context_path(agent_id);

        if context_path.exists() {
            fs::remove_file(&context_path)
                .await
                .map_err(|e| ContextError::StorageError {
                    reason: format!("Failed to delete context file: {}", e),
                })?;
        }

        Ok(())
    }

    async fn list_agent_contexts(&self) -> Result<Vec<AgentId>, ContextError> {
        let mut agent_ids = Vec::new();
        let mut dir = fs::read_dir(&self.config.agent_contexts_path())
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read storage directory: {}", e),
            })?;

        while let Some(entry) = dir
            .next_entry()
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read directory entry: {}", e),
            })?
        {
            let path = entry.path();
            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                if filename.ends_with(".json") || filename.ends_with(".json.gz") {
                    let agent_id_str = filename
                        .strip_suffix(".json.gz")
                        .or_else(|| filename.strip_suffix(".json"))
                        .unwrap_or(filename);

                    if let Ok(uuid) = uuid::Uuid::parse_str(agent_id_str) {
                        agent_ids.push(AgentId(uuid));
                    }
                }
            }
        }

        Ok(agent_ids)
    }

    async fn context_exists(&self, agent_id: AgentId) -> Result<bool, ContextError> {
        let context_path = self.get_context_path(agent_id);
        Ok(context_path.exists())
    }

    async fn get_storage_stats(&self) -> Result<StorageStats, ContextError> {
        let mut total_contexts = 0;
        let mut total_size_bytes = 0;

        let mut dir = fs::read_dir(&self.config.agent_contexts_path())
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read storage directory: {}", e),
            })?;

        while let Some(entry) = dir
            .next_entry()
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to read directory entry: {}", e),
            })?
        {
            let path = entry.path();
            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                if filename.ends_with(".json") || filename.ends_with(".json.gz") {
                    total_contexts += 1;
                    if let Ok(metadata) = entry.metadata().await {
                        total_size_bytes += metadata.len();
                    }
                }
            }
        }

        Ok(StorageStats {
            total_contexts,
            total_size_bytes,
            last_cleanup: SystemTime::now(),
            storage_path: self.config.agent_contexts_path(),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl StandardContextManager {
    /// Create a new StandardContextManager
    pub async fn new(config: ContextManagerConfig, agent_id: &str) -> Result<Self, ContextError> {
        let vector_db: Arc<dyn VectorDb> = if config.enable_vector_db {
            let db = if let Some(ref backend_config) = config.vector_backend {
                create_vector_backend(backend_config.clone())
                    .await
                    .unwrap_or_else(|e| {
                        tracing::warn!("Failed to create vector backend: {}, using NoOp", e);
                        Arc::new(NoOpVectorDatabase)
                    })
            } else {
                let resolved = resolve_vector_config();
                create_vector_backend(resolved).await.unwrap_or_else(|e| {
                    tracing::warn!("Failed to create vector backend: {}, using NoOp", e);
                    Arc::new(NoOpVectorDatabase)
                })
            };
            // Initialize the vector DB (creates table/collection if needed)
            if let Err(e) = db.initialize().await {
                tracing::warn!("Failed to initialize vector DB: {}, queries may fail", e);
            }
            db
        } else {
            Arc::new(NoOpVectorDatabase)
        };

        let embedding_service =
            create_embedding_service_from_env(config.qdrant_config.vector_dimension)?;

        let persistence: Arc<dyn ContextPersistence> = if config.enable_persistence {
            Arc::new(FilePersistence::new(config.persistence_config.clone()))
        } else {
            // Could use a no-op implementation for testing
            Arc::new(FilePersistence::new(config.persistence_config.clone()))
        };

        // Initialize secrets store
        let secrets = crate::secrets::new_secret_store(&config.secrets_config, agent_id)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to initialize secrets store: {}", e),
            })?;

        // Initialize policy engine
        let policy_engine: Arc<dyn PolicyEngine> = Arc::new(MockPolicyEngine::new());

        Ok(Self {
            contexts: Arc::new(RwLock::new(HashMap::new())),
            config,
            shared_knowledge: Arc::new(RwLock::new(HashMap::new())),
            vector_db,
            embedding_service,
            persistence,
            secrets,
            policy_engine,
            shutdown_flag: Arc::new(RwLock::new(false)),
            background_tasks: Arc::new(RwLock::new(Vec::new())),
        })
    }

    /// Get access to the secrets store
    pub fn secrets(&self) -> &(dyn SecretStore + Send + Sync) {
        self.secrets.as_ref()
    }

    /// Check token usage and run compaction if thresholds are crossed.
    ///
    /// Returns `Some(CompactionResult)` if compaction was performed, `None` if
    /// usage was below all thresholds.
    pub async fn check_and_compact(
        &self,
        agent_id: &AgentId,
        session_id: &SessionId,
        config: &super::compaction::CompactionConfig,
        counter: &dyn super::token_counter::TokenCounter,
    ) -> Result<Option<super::compaction::CompactionResult>, ContextError> {
        use super::compaction::{select_tier, truncate_items, CompactionTier};

        if !config.enabled {
            return Ok(None);
        }

        // Retrieve current context
        let context = match self.retrieve_context(*agent_id, Some(*session_id)).await? {
            Some(ctx) => ctx,
            None => return Ok(None),
        };

        // Count current token usage
        let current_tokens = counter.count_messages(&context.conversation_history);
        let limit = counter.model_context_limit();

        if limit == 0 {
            return Ok(None);
        }

        let usage_ratio = current_tokens as f32 / limit as f32;

        let tier = match select_tier(usage_ratio, config) {
            Some(t) => t,
            None => return Ok(None),
        };

        let start = std::time::Instant::now();

        match tier {
            CompactionTier::Truncate => {
                let (new_items, affected) = truncate_items(
                    &context.conversation_history,
                    config,
                    config.summarize_threshold,
                );

                if affected == 0 {
                    return Ok(None);
                }

                let tokens_after = counter.count_messages(&new_items);

                let mut updated = context.clone();
                updated.conversation_history = new_items;
                self.store_context(*agent_id, updated).await?;

                Ok(Some(super::compaction::CompactionResult {
                    tier_applied: CompactionTier::Truncate,
                    tokens_before: current_tokens,
                    tokens_after,
                    tokens_saved: current_tokens.saturating_sub(tokens_after),
                    items_affected: affected,
                    duration_ms: start.elapsed().as_millis() as u64,
                    summary_generated: None,
                }))
            }
            CompactionTier::Summarize => {
                // Summarize requires an LLM call — for now, fall back to truncate.
                // Full LLM integration deferred to heartbeat scheduler wiring.
                tracing::info!(
                    agent = %agent_id,
                    "compaction: Summarize tier selected but no LLM client in context manager, falling back to truncate"
                );
                let (new_items, affected) = truncate_items(
                    &context.conversation_history,
                    config,
                    config.summarize_threshold,
                );

                if affected == 0 {
                    return Ok(None);
                }

                let tokens_after = counter.count_messages(&new_items);
                let mut updated = context.clone();
                updated.conversation_history = new_items;
                self.store_context(*agent_id, updated).await?;

                Ok(Some(super::compaction::CompactionResult {
                    tier_applied: CompactionTier::Truncate, // Actually fell back
                    tokens_before: current_tokens,
                    tokens_after,
                    tokens_saved: current_tokens.saturating_sub(tokens_after),
                    items_affected: affected,
                    duration_ms: start.elapsed().as_millis() as u64,
                    summary_generated: None,
                }))
            }
            CompactionTier::CompressEpisodic | CompactionTier::ArchiveToMemory => {
                // Enterprise tiers — stub returns None in OSS
                Ok(None)
            }
        }
    }

    /// Initialize the context manager
    pub async fn initialize(&self) -> Result<(), ContextError> {
        // Initialize vector database connection and collection
        if self.config.enable_vector_db {
            self.vector_db.initialize().await?;
        }

        // Initialize persistence layer
        if self.config.enable_persistence {
            if let Some(file_persistence) =
                self.persistence.as_any().downcast_ref::<FilePersistence>()
            {
                file_persistence.initialize().await?;
            }

            // Load existing contexts from persistent storage
            self.load_existing_contexts().await?;
        }

        // Set up retention policy scheduler
        self.setup_retention_scheduler().await?;

        Ok(())
    }

    /// Load existing contexts from persistent storage
    async fn load_existing_contexts(&self) -> Result<(), ContextError> {
        let agent_ids = self.persistence.list_agent_contexts().await?;
        let mut contexts = self.contexts.write().await;

        for agent_id in agent_ids {
            if let Some(context) = self.persistence.load_context(agent_id).await? {
                contexts.insert(agent_id, context);
            }
        }

        Ok(())
    }

    /// Shutdown the context manager gracefully
    pub async fn shutdown(&self) -> Result<(), ContextError> {
        // Check if already shutdown (idempotent)
        {
            let shutdown_flag = self.shutdown_flag.read().await;
            if *shutdown_flag {
                tracing::info!("ContextManager already shutdown, skipping");
                return Ok(());
            }
        }

        tracing::info!("Starting ContextManager shutdown sequence");

        // Set shutdown flag to prevent new operations
        {
            let mut shutdown_flag = self.shutdown_flag.write().await;
            *shutdown_flag = true;
        }

        // 1. Stop all background tasks
        self.stop_background_tasks().await?;

        // 2. Save all contexts to persistent storage
        self.save_all_contexts().await?;

        // 3. Close vector database connections (if any cleanup is needed)
        // Note: Vector database connections are typically managed by the client
        // and don't require explicit cleanup, but we log the action
        tracing::info!("Vector database connections will be closed when client is dropped");

        // 4. Flush secrets store if needed
        // Note: Secrets store cleanup is typically handled by Drop trait
        tracing::info!("Secrets store cleanup handled by Drop trait");

        tracing::info!("ContextManager shutdown completed successfully");
        Ok(())
    }

    /// Stop all background tasks
    async fn stop_background_tasks(&self) -> Result<(), ContextError> {
        let mut tasks = self.background_tasks.write().await;

        if tasks.is_empty() {
            tracing::debug!("No background tasks to stop");
            return Ok(());
        }

        tracing::info!("Stopping {} background tasks", tasks.len());

        // Abort all background tasks
        for task in tasks.drain(..) {
            task.abort();

            // Wait for task to finish (with timeout to avoid hanging)
            match tokio::time::timeout(std::time::Duration::from_secs(5), task).await {
                Ok(result) => match result {
                    Ok(_) => tracing::debug!("Background task completed successfully"),
                    Err(e) if e.is_cancelled() => tracing::debug!("Background task was cancelled"),
                    Err(e) => tracing::warn!("Background task finished with error: {}", e),
                },
                Err(_) => tracing::warn!("Background task did not finish within timeout"),
            }
        }

        tracing::info!("All background tasks stopped");
        Ok(())
    }

    /// Save all in-memory contexts to persistent storage
    async fn save_all_contexts(&self) -> Result<(), ContextError> {
        if !self.config.enable_persistence {
            tracing::debug!("Persistence disabled, skipping context save");
            return Ok(());
        }

        let contexts = self.contexts.read().await;

        if contexts.is_empty() {
            tracing::debug!("No contexts to save");
            return Ok(());
        }

        tracing::info!("Saving {} contexts to persistent storage", contexts.len());

        let mut save_errors = Vec::new();

        for (agent_id, context) in contexts.iter() {
            match self.persistence.save_context(*agent_id, context).await {
                Ok(_) => tracing::debug!("Saved context for agent {}", agent_id),
                Err(e) => {
                    tracing::error!("Failed to save context for agent {}: {}", agent_id, e);
                    save_errors.push((*agent_id, e));
                }
            }
        }

        if !save_errors.is_empty() {
            let error_msg = format!(
                "Failed to save {} out of {} contexts during shutdown",
                save_errors.len(),
                contexts.len()
            );
            tracing::error!("{}", error_msg);

            // Return the first error, but log all of them
            if let Some((agent_id, error)) = save_errors.into_iter().next() {
                return Err(ContextError::StorageError {
                    reason: format!("Failed to save context for agent {}: {}", agent_id, error),
                });
            }
        }

        tracing::info!("All contexts saved successfully");
        Ok(())
    }

    /// Set up retention policy scheduler as a background task
    async fn setup_retention_scheduler(&self) -> Result<(), ContextError> {
        if !self.config.enable_auto_archiving {
            tracing::debug!("Auto-archiving disabled, skipping retention scheduler setup");
            return Ok(());
        }

        let contexts = self.contexts.clone();
        let persistence = self.persistence.clone();
        let config = self.config.clone();
        let shutdown_flag = self.shutdown_flag.clone();

        let task = tokio::spawn(async move {
            let mut interval = tokio::time::interval(config.archiving_interval);

            tracing::info!(
                "Retention policy scheduler started with interval {:?}",
                config.archiving_interval
            );

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // Check if we should shutdown
                        if *shutdown_flag.read().await {
                            tracing::info!("Retention scheduler shutting down");
                            break;
                        }

                        // Run retention check for all agents
                        Self::run_retention_check(&contexts, &persistence, &config).await;
                    }
                }
            }
        });

        self.add_background_task(task).await;
        tracing::info!("Retention policy scheduler initialized successfully");
        Ok(())
    }

    /// Run retention check across all agent contexts
    async fn run_retention_check(
        contexts: &Arc<RwLock<HashMap<AgentId, AgentContext>>>,
        persistence: &Arc<dyn ContextPersistence>,
        config: &ContextManagerConfig,
    ) {
        let current_time = SystemTime::now();

        // Collect agent IDs and stats first to avoid borrowing issues
        let agents_to_check: Vec<(AgentId, usize)> = {
            let context_guard = contexts.read().await;
            let agent_count = context_guard.len();

            if agent_count == 0 {
                tracing::debug!("No agent contexts to process for retention");
                return;
            }

            tracing::info!(
                "Starting retention check for {} agent contexts",
                agent_count
            );

            context_guard
                .iter()
                .map(|(agent_id, context)| {
                    let retention_stats = Self::calculate_retention_statistics_static(context);
                    (*agent_id, retention_stats.items_to_archive)
                })
                .collect()
        };

        let start_time = std::time::Instant::now();
        let total_agents = agents_to_check.len();

        // Process each agent that needs archiving
        for (agent_id, items_to_archive) in agents_to_check {
            if items_to_archive > 0 {
                tracing::debug!(
                    "Agent {} has {} items eligible for archiving",
                    agent_id,
                    items_to_archive
                );

                // Archive items for this agent
                let archive_result = Self::archive_agent_context_static(
                    agent_id,
                    current_time,
                    contexts,
                    persistence,
                    config,
                )
                .await;

                match archive_result {
                    Ok(archived_count) => {
                        tracing::info!(
                            "Successfully archived {} items for agent {}",
                            archived_count,
                            agent_id
                        );
                    }
                    Err(e) => {
                        tracing::error!("Failed to archive context for agent {}: {}", agent_id, e);
                    }
                }
            }
        }

        let elapsed = start_time.elapsed();
        tracing::info!(
            "Retention check completed for {} agents in {:?}",
            total_agents,
            elapsed
        );
    }

    /// Static version of calculate_retention_statistics for use in scheduler
    fn calculate_retention_statistics_static(context: &AgentContext) -> RetentionStatus {
        let now = SystemTime::now();
        let retention_policy = &context.retention_policy;

        let mut items_to_archive = 0;
        let items_to_delete = 0;

        // Calculate cutoff times based on retention policy
        let memory_cutoff = now
            .checked_sub(retention_policy.memory_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        let knowledge_cutoff = now
            .checked_sub(retention_policy.knowledge_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        let conversation_cutoff = now
            .checked_sub(retention_policy.session_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        // Count memory items eligible for archiving
        for item in &context.memory.short_term {
            if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                items_to_archive += 1;
            }
        }

        for item in &context.memory.long_term {
            if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                items_to_archive += 1;
            }
        }

        // Count conversation items eligible for archiving
        for item in &context.conversation_history {
            if item.timestamp < conversation_cutoff {
                items_to_archive += 1;
            }
        }

        // Count knowledge items eligible for archiving
        for fact in &context.knowledge_base.facts {
            if fact.created_at < knowledge_cutoff {
                items_to_archive += 1;
            }
        }

        // Calculate next cleanup time
        let next_cleanup = now + Duration::from_secs(86400); // 24 hours

        RetentionStatus {
            items_to_archive,
            items_to_delete,
            next_cleanup,
        }
    }

    /// Static version of archive_context for use in scheduler
    async fn archive_agent_context_static(
        agent_id: AgentId,
        before: SystemTime,
        contexts: &Arc<RwLock<HashMap<AgentId, AgentContext>>>,
        persistence: &Arc<dyn ContextPersistence>,
        config: &ContextManagerConfig,
    ) -> Result<u32, ContextError> {
        let mut total_archived = 0u32;
        let mut archived_context = ArchivedContext::new(agent_id, before);

        // Get mutable access to contexts
        let mut contexts_guard = contexts.write().await;
        if let Some(context) = contexts_guard.get_mut(&agent_id) {
            // Archive items based on retention policy
            let retention_policy = &context.retention_policy;

            // Calculate cutoff times
            let memory_cutoff = before
                .checked_sub(retention_policy.memory_retention)
                .unwrap_or(SystemTime::UNIX_EPOCH);

            let conversation_cutoff = before
                .checked_sub(retention_policy.session_retention)
                .unwrap_or(SystemTime::UNIX_EPOCH);

            let knowledge_cutoff = before
                .checked_sub(retention_policy.knowledge_retention)
                .unwrap_or(SystemTime::UNIX_EPOCH);

            // Archive short-term memory items
            let mut retained_short_term = Vec::new();
            for item in context.memory.short_term.drain(..) {
                if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                    archived_context.memory.short_term.push(item);
                    total_archived += 1;
                } else {
                    retained_short_term.push(item);
                }
            }
            context.memory.short_term = retained_short_term;

            // Archive long-term memory items
            let mut retained_long_term = Vec::new();
            for item in context.memory.long_term.drain(..) {
                if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                    archived_context.memory.long_term.push(item);
                    total_archived += 1;
                } else {
                    retained_long_term.push(item);
                }
            }
            context.memory.long_term = retained_long_term;

            // Archive conversation history
            let mut retained_conversations = Vec::new();
            for item in context.conversation_history.drain(..) {
                if item.timestamp < conversation_cutoff {
                    archived_context.conversation_history.push(item);
                    total_archived += 1;
                } else {
                    retained_conversations.push(item);
                }
            }
            context.conversation_history = retained_conversations;

            // Archive knowledge items
            let mut retained_facts = Vec::new();
            for fact in context.knowledge_base.facts.drain(..) {
                if fact.created_at < knowledge_cutoff {
                    archived_context.knowledge_base.facts.push(fact);
                    total_archived += 1;
                } else {
                    retained_facts.push(fact);
                }
            }
            context.knowledge_base.facts = retained_facts;

            // Update context metadata
            if total_archived > 0 {
                context.updated_at = SystemTime::now();
                context.metadata.insert(
                    "last_archived".to_string(),
                    SystemTime::now()
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs()
                        .to_string(),
                );
                context
                    .metadata
                    .insert("archived_count".to_string(), total_archived.to_string());

                // Save archived context to storage
                if config.enable_persistence {
                    Self::save_archived_context_static(
                        agent_id,
                        &archived_context,
                        persistence,
                        config,
                    )
                    .await?;
                    // Also save updated context
                    persistence.save_context(agent_id, context).await?;
                }
            }
        }

        Ok(total_archived)
    }

    /// Static version of save_archived_context for use in scheduler
    async fn save_archived_context_static(
        agent_id: AgentId,
        archived_context: &ArchivedContext,
        _persistence: &Arc<dyn ContextPersistence>,
        config: &ContextManagerConfig,
    ) -> Result<(), ContextError> {
        let archive_dir = config
            .persistence_config
            .agent_contexts_path()
            .join("archives")
            .join(agent_id.to_string());

        // Ensure archive directory exists
        tokio::fs::create_dir_all(&archive_dir)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to create archive directory: {}", e),
            })?;

        // Create archive filename with timestamp
        let timestamp = archived_context
            .archived_at
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let archive_filename = format!("archive_{}.json", timestamp);
        let archive_path = archive_dir.join(archive_filename);

        // Serialize archived context
        let archive_data = serde_json::to_vec_pretty(archived_context).map_err(|e| {
            ContextError::SerializationError {
                reason: format!("Failed to serialize archived context: {}", e),
            }
        })?;

        // Write to archive file
        tokio::fs::write(&archive_path, &archive_data)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to write archive file: {}", e),
            })?;

        tracing::debug!(
            "Saved archived context for agent {} to {}",
            agent_id,
            archive_path.display()
        );

        Ok(())
    }

    /// Add a background task to be tracked for shutdown
    pub async fn add_background_task(&self, task: tokio::task::JoinHandle<()>) {
        let mut tasks = self.background_tasks.write().await;
        tasks.push(task);
    }

    /// Check if the context manager is shutdown
    pub async fn is_shutdown(&self) -> bool {
        let shutdown_flag = self.shutdown_flag.read().await;
        *shutdown_flag
    }

    /// Create a new session for an agent
    pub async fn create_session(&self, agent_id: AgentId) -> Result<SessionId, ContextError> {
        let session_id = SessionId::new();

        // Create new context for the session
        let context = AgentContext {
            agent_id,
            session_id,
            memory: HierarchicalMemory::default(),
            knowledge_base: KnowledgeBase::default(),
            conversation_history: Vec::new(),
            metadata: HashMap::new(),
            created_at: SystemTime::now(),
            updated_at: SystemTime::now(),
            retention_policy: self.config.default_retention_policy.clone(),
        };

        ContextManager::store_context(self, agent_id, context).await?;
        Ok(session_id)
    }

    /// Validate access permissions for context operations
    async fn validate_access(
        &self,
        agent_id: AgentId,
        operation: &str,
    ) -> Result<(), ContextError> {
        // For now, we'll implement a simplified access check
        // In a full implementation, this would create the appropriate PolicyRequest
        // and call the policy engine with proper AgentAction and PolicyContext

        // Simple validation - deny dangerous operations by default
        let is_dangerous_operation = matches!(operation, "archive_context");

        if is_dangerous_operation {
            tracing::warn!(
                "Potentially dangerous operation {} denied for agent {} by default policy",
                operation,
                agent_id
            );
            Err(ContextError::AccessDenied {
                reason: format!("Operation {} requires explicit approval", operation),
            })
        } else {
            tracing::debug!("Policy engine allowed {} for agent {}", operation, agent_id);
            Ok(())
        }
    }

    /// Generate embeddings for content
    async fn generate_embeddings(&self, content: &str) -> Result<Vec<f32>, ContextError> {
        self.embedding_service.generate_embedding(content).await
    }

    /// Perform semantic search on memory items
    async fn semantic_search_memory(
        &self,
        agent_id: AgentId,
        query: &str,
        limit: usize,
    ) -> Result<Vec<ContextItem>, ContextError> {
        if self.config.enable_vector_db {
            // Generate embeddings for the query
            let query_embedding = self.generate_embeddings(query).await?;

            // Search the vector database with semantic similarity
            let threshold = 0.7; // Minimum similarity threshold
            self.vector_db
                .semantic_search(agent_id, query_embedding, limit, threshold)
                .await
        } else {
            // Fallback to simple keyword search
            let contexts = self.contexts.read().await;
            if let Some(context) = contexts.get(&agent_id) {
                let mut results = Vec::new();

                for memory_item in &context.memory.short_term {
                    if memory_item
                        .content
                        .to_lowercase()
                        .contains(&query.to_lowercase())
                    {
                        // Calculate relevance score based on importance and keyword match
                        let importance_score = self.calculate_importance(memory_item);
                        let relevance_score = (importance_score + 0.8) / 2.0; // Blend importance with match score

                        results.push(ContextItem {
                            id: memory_item.id,
                            content: memory_item.content.clone(),
                            item_type: ContextItemType::Memory(memory_item.memory_type.clone()),
                            relevance_score,
                            timestamp: memory_item.created_at,
                            metadata: memory_item.metadata.clone(),
                        });
                    }
                }

                results.truncate(limit);
                Ok(results)
            } else {
                Ok(Vec::new())
            }
        }
    }

    /// Calculate memory importance score using sophisticated multi-factor algorithm
    ///
    /// This algorithm considers:
    /// - Base importance: Initial importance score
    /// - Access frequency: How often the memory is accessed (logarithmic scaling)
    /// - Recency: How recently the memory was accessed or created
    /// - User feedback: Explicit or implicit feedback from user interactions
    /// - Memory type: Different types of memory have different base weightings
    /// - Age decay: Older memories naturally lose importance over time
    ///
    /// Returns a normalized score between 0.0 and 1.0
    fn calculate_importance(&self, memory_item: &MemoryItem) -> f32 {
        // Configurable weights for different factors
        let weights = ImportanceWeights::default();

        // 1. Base importance (0.0 - 1.0)
        let base_score = memory_item.importance.clamp(0.0, 1.0);

        // 2. Access frequency factor (logarithmic scaling to prevent dominance)
        let access_score = if memory_item.access_count == 0 {
            weights.no_access_penalty
        } else {
            let log_access = (memory_item.access_count as f32 + 1.0).ln();
            (log_access / 10.0).min(1.0) // Cap at ln(10) ≈ 2.3
        };

        // 3. Recency factor - considers both last access and creation time
        let recency_score = self.calculate_recency_factor(memory_item);

        // 4. User feedback factor from metadata
        let feedback_score = self.extract_user_feedback_score(memory_item);

        // 5. Memory type adjustment
        let type_multiplier = self.get_memory_type_multiplier(&memory_item.memory_type);

        // 6. Age decay factor
        let age_decay = self.calculate_age_decay(memory_item);

        // Combine all factors using weighted average
        let combined_score = (base_score * weights.base_importance
            + access_score * weights.access_frequency
            + recency_score * weights.recency
            + feedback_score * weights.user_feedback)
            * type_multiplier
            * age_decay;

        // Ensure the final score is within bounds [0.0, 1.0]
        combined_score.clamp(0.0, 1.0)
    }

    /// Calculate recency factor based on last access and creation time
    fn calculate_recency_factor(&self, memory_item: &MemoryItem) -> f32 {
        let now = SystemTime::now();

        // Use the more recent of last_accessed or created_at
        let most_recent = memory_item.last_accessed.max(memory_item.created_at);

        let time_since_access = now
            .duration_since(most_recent)
            .unwrap_or_else(|_| std::time::Duration::from_secs(0));

        let hours_since_access = time_since_access.as_secs() as f32 / 3600.0;

        // Exponential decay with configurable half-life
        let half_life_hours = 24.0; // 24 hours half-life
        let decay_factor = 2.0_f32.powf(-hours_since_access / half_life_hours);

        // Ensure minimum recency score to prevent complete obsolescence
        decay_factor.max(0.01)
    }

    /// Extract user feedback score from memory item metadata
    fn extract_user_feedback_score(&self, memory_item: &MemoryItem) -> f32 {
        let mut feedback_score = 0.5; // Neutral baseline

        // Check for explicit user ratings
        if let Some(rating_str) = memory_item.metadata.get("user_rating") {
            if let Ok(rating) = rating_str.parse::<f32>() {
                feedback_score = (rating / 5.0).clamp(0.0, 1.0); // Assume 1-5 rating scale
            }
        }

        // Check for implicit feedback indicators
        if let Some(helpful_str) = memory_item.metadata.get("helpful") {
            match helpful_str.to_lowercase().as_str() {
                "true" | "yes" | "1" => feedback_score = feedback_score.max(0.8),
                "false" | "no" | "0" => feedback_score = feedback_score.min(0.2),
                _ => {}
            }
        }

        // Check for correction indicators (negative feedback)
        if memory_item.metadata.contains_key("corrected")
            || memory_item.metadata.contains_key("incorrect")
        {
            feedback_score = feedback_score.min(0.3);
        }

        // Check for bookmark/favorite indicators (positive feedback)
        if memory_item.metadata.contains_key("bookmarked")
            || memory_item.metadata.contains_key("favorite")
        {
            feedback_score = feedback_score.max(0.9);
        }

        // Check for usage context that indicates importance
        if let Some(context) = memory_item.metadata.get("usage_context") {
            match context.to_lowercase().as_str() {
                "critical" | "important" => feedback_score = feedback_score.max(0.95),
                "routine" | "common" => feedback_score = feedback_score.max(0.7),
                "experimental" | "trial" => feedback_score = feedback_score.min(0.4),
                _ => {}
            }
        }

        feedback_score.clamp(0.0, 1.0)
    }

    /// Get multiplier based on memory type importance
    fn get_memory_type_multiplier(&self, memory_type: &MemoryType) -> f32 {
        match memory_type {
            MemoryType::Factual => 1.0,    // Base multiplier for facts
            MemoryType::Procedural => 1.2, // Procedures are often more important
            MemoryType::Episodic => 0.9,   // Episodes can vary in importance
            MemoryType::Semantic => 1.1,   // Concepts and relationships are valuable
            MemoryType::Working => 1.3,    // Current working memory is highly relevant
        }
    }

    /// Calculate age decay factor for long-term memory degradation
    fn calculate_age_decay(&self, memory_item: &MemoryItem) -> f32 {
        let now = SystemTime::now();
        let age = now
            .duration_since(memory_item.created_at)
            .unwrap_or_else(|_| std::time::Duration::from_secs(0));

        let days_old = age.as_secs() as f32 / 86400.0; // Convert to days

        // Different decay rates based on memory type
        let decay_rate = match memory_item.memory_type {
            MemoryType::Working => 0.1,      // Working memory decays quickly
            MemoryType::Factual => 0.01,     // Facts persist longer
            MemoryType::Procedural => 0.005, // Procedures are most persistent
            MemoryType::Episodic => 0.02,    // Episodes have moderate decay
            MemoryType::Semantic => 0.008,   // Semantic memory is quite persistent
        };

        // Exponential decay: importance = base * e^(-decay_rate * days)
        let decay_factor = (-decay_rate * days_old).exp();

        // Ensure minimum decay to prevent complete loss
        decay_factor.max(0.05)
    }

    /// Perform keyword search on memory items
    async fn keyword_search_memory(
        &self,
        agent_id: AgentId,
        query: &ContextQuery,
    ) -> Result<Vec<ContextItem>, ContextError> {
        let contexts = self.contexts.read().await;
        if let Some(context) = contexts.get(&agent_id) {
            let mut results = Vec::new();

            // Combine all search terms
            let search_terms: Vec<String> = query
                .search_terms
                .iter()
                .map(|term| term.to_lowercase())
                .collect();

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

            // Search through memory items
            for memory_item in context
                .memory
                .short_term
                .iter()
                .chain(context.memory.long_term.iter())
            {
                // Skip if memory type filter is specified and doesn't match
                if !query.memory_types.is_empty()
                    && !query.memory_types.contains(&memory_item.memory_type)
                {
                    continue;
                }

                let content_lower = memory_item.content.to_lowercase();
                let mut match_score = 0.0f32;
                let mut matched_terms = 0;

                // Calculate match score based on term presence
                for term in &search_terms {
                    if content_lower.contains(term) {
                        matched_terms += 1;
                        // Boost score for exact matches vs substring matches
                        if content_lower.split_whitespace().any(|word| word == term) {
                            match_score += 1.0;
                        } else {
                            match_score += 0.5;
                        }
                    }
                }

                if matched_terms > 0 {
                    // Calculate relevance score combining match score and importance
                    let importance_score = self.calculate_importance(memory_item);
                    let term_coverage = matched_terms as f32 / search_terms.len() as f32;
                    let relevance_score = (match_score * term_coverage + importance_score) / 2.0;

                    if relevance_score >= query.relevance_threshold {
                        results.push(ContextItem {
                            id: memory_item.id,
                            content: memory_item.content.clone(),
                            item_type: ContextItemType::Memory(memory_item.memory_type.clone()),
                            relevance_score,
                            timestamp: memory_item.created_at,
                            metadata: memory_item.metadata.clone(),
                        });
                    }
                }
            }

            // Search through episodic memory
            for episode in &context.memory.episodic_memory {
                let episode_content = format!("{} {}", episode.title, episode.description);
                let content_lower = episode_content.to_lowercase();
                let mut match_score = 0.0f32;
                let mut matched_terms = 0;

                for term in &search_terms {
                    if content_lower.contains(term) {
                        matched_terms += 1;
                        match_score += if content_lower.split_whitespace().any(|word| word == term)
                        {
                            1.0
                        } else {
                            0.5
                        };
                    }
                }

                if matched_terms > 0 {
                    let term_coverage = matched_terms as f32 / search_terms.len() as f32;
                    let relevance_score = (match_score * term_coverage + episode.importance) / 2.0;

                    if relevance_score >= query.relevance_threshold {
                        results.push(ContextItem {
                            id: episode.id,
                            content: episode_content,
                            item_type: ContextItemType::Episode,
                            relevance_score,
                            timestamp: episode.timestamp,
                            metadata: HashMap::new(),
                        });
                    }
                }
            }

            // Search through conversation history
            for conv_item in &context.conversation_history {
                let content_lower = conv_item.content.to_lowercase();
                let mut match_score = 0.0f32;
                let mut matched_terms = 0;

                for term in &search_terms {
                    if content_lower.contains(term) {
                        matched_terms += 1;
                        match_score += if content_lower.split_whitespace().any(|word| word == term)
                        {
                            1.0
                        } else {
                            0.5
                        };
                    }
                }

                if matched_terms > 0 {
                    let term_coverage = matched_terms as f32 / search_terms.len() as f32;
                    let relevance_score = match_score * term_coverage;

                    if relevance_score >= query.relevance_threshold {
                        results.push(ContextItem {
                            id: conv_item.id,
                            content: conv_item.content.clone(),
                            item_type: ContextItemType::Conversation,
                            relevance_score,
                            timestamp: conv_item.timestamp,
                            metadata: HashMap::new(),
                        });
                    }
                }
            }

            // Sort by relevance score (highest first) and limit results
            results.sort_by(|a, b| {
                b.relevance_score
                    .partial_cmp(&a.relevance_score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            results.truncate(query.max_results);

            Ok(results)
        } else {
            Ok(Vec::new())
        }
    }

    /// Perform temporal search on memory items within a time range
    async fn temporal_search_memory(
        &self,
        agent_id: AgentId,
        query: &ContextQuery,
    ) -> Result<Vec<ContextItem>, ContextError> {
        let time_range = match &query.time_range {
            Some(range) => range,
            None => return Ok(Vec::new()), // No time range specified
        };

        let contexts = self.contexts.read().await;
        if let Some(context) = contexts.get(&agent_id) {
            let mut results = Vec::new();

            // Search through memory items
            for memory_item in context
                .memory
                .short_term
                .iter()
                .chain(context.memory.long_term.iter())
            {
                // Skip if memory type filter is specified and doesn't match
                if !query.memory_types.is_empty()
                    && !query.memory_types.contains(&memory_item.memory_type)
                {
                    continue;
                }

                // Check if item falls within time range
                if memory_item.created_at >= time_range.start
                    && memory_item.created_at <= time_range.end
                {
                    // Optional keyword filtering within temporal results
                    let passes_keyword_filter = if query.search_terms.is_empty() {
                        true
                    } else {
                        let content_lower = memory_item.content.to_lowercase();
                        query
                            .search_terms
                            .iter()
                            .any(|term| content_lower.contains(&term.to_lowercase()))
                    };

                    if passes_keyword_filter {
                        let importance_score = self.calculate_importance(memory_item);
                        let recency_score = self.calculate_recency_factor(memory_item);
                        let relevance_score = (importance_score + recency_score) / 2.0;

                        if relevance_score >= query.relevance_threshold {
                            results.push(ContextItem {
                                id: memory_item.id,
                                content: memory_item.content.clone(),
                                item_type: ContextItemType::Memory(memory_item.memory_type.clone()),
                                relevance_score,
                                timestamp: memory_item.created_at,
                                metadata: memory_item.metadata.clone(),
                            });
                        }
                    }
                }
            }

            // Search through episodic memory
            for episode in &context.memory.episodic_memory {
                if episode.timestamp >= time_range.start && episode.timestamp <= time_range.end {
                    let passes_keyword_filter = if query.search_terms.is_empty() {
                        true
                    } else {
                        let episode_content = format!("{} {}", episode.title, episode.description);
                        let content_lower = episode_content.to_lowercase();
                        query
                            .search_terms
                            .iter()
                            .any(|term| content_lower.contains(&term.to_lowercase()))
                    };

                    if passes_keyword_filter && episode.importance >= query.relevance_threshold {
                        results.push(ContextItem {
                            id: episode.id,
                            content: format!("{} {}", episode.title, episode.description),
                            item_type: ContextItemType::Episode,
                            relevance_score: episode.importance,
                            timestamp: episode.timestamp,
                            metadata: HashMap::new(),
                        });
                    }
                }
            }

            // Search through conversation history
            for conv_item in &context.conversation_history {
                if conv_item.timestamp >= time_range.start && conv_item.timestamp <= time_range.end
                {
                    let passes_keyword_filter = if query.search_terms.is_empty() {
                        true
                    } else {
                        let content_lower = conv_item.content.to_lowercase();
                        query
                            .search_terms
                            .iter()
                            .any(|term| content_lower.contains(&term.to_lowercase()))
                    };

                    if passes_keyword_filter {
                        // Calculate relevance based on recency within the time range
                        let time_since_start = conv_item
                            .timestamp
                            .duration_since(time_range.start)
                            .unwrap_or_default()
                            .as_secs() as f32;
                        let range_duration = time_range
                            .end
                            .duration_since(time_range.start)
                            .unwrap_or_default()
                            .as_secs() as f32;

                        let temporal_score = if range_duration > 0.0 {
                            1.0 - (time_since_start / range_duration)
                        } else {
                            1.0
                        };

                        if temporal_score >= query.relevance_threshold {
                            results.push(ContextItem {
                                id: conv_item.id,
                                content: conv_item.content.clone(),
                                item_type: ContextItemType::Conversation,
                                relevance_score: temporal_score,
                                timestamp: conv_item.timestamp,
                                metadata: HashMap::new(),
                            });
                        }
                    }
                }
            }

            // Sort by timestamp (most recent first) and limit results
            results.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
            results.truncate(query.max_results);

            Ok(results)
        } else {
            Ok(Vec::new())
        }
    }

    /// Perform similarity search using vector embeddings
    async fn similarity_search_memory(
        &self,
        agent_id: AgentId,
        query: &ContextQuery,
    ) -> Result<Vec<ContextItem>, ContextError> {
        if self.config.enable_vector_db && !query.search_terms.is_empty() {
            // Use vector database for similarity search
            let search_term = query.search_terms.join(" ");
            let query_embedding = self.generate_embeddings(&search_term).await?;

            // Search the vector database with semantic similarity
            let threshold = query.relevance_threshold;
            self.vector_db
                .semantic_search(agent_id, query_embedding, query.max_results, threshold)
                .await
        } else {
            // Fallback to embedding-based similarity if available in memory
            let contexts = self.contexts.read().await;
            if let Some(context) = contexts.get(&agent_id) {
                if query.search_terms.is_empty() {
                    return Ok(Vec::new());
                }

                // Generate query embedding
                let search_term = query.search_terms.join(" ");
                let query_embedding = match self.generate_embeddings(&search_term).await {
                    Ok(embedding) => embedding,
                    Err(_) => return Ok(Vec::new()), // Fall back to empty results if embedding fails
                };

                let mut results = Vec::new();

                // Compare with memory item embeddings
                for memory_item in context
                    .memory
                    .short_term
                    .iter()
                    .chain(context.memory.long_term.iter())
                {
                    // Skip if memory type filter is specified and doesn't match
                    if !query.memory_types.is_empty()
                        && !query.memory_types.contains(&memory_item.memory_type)
                    {
                        continue;
                    }

                    if let Some(ref item_embedding) = memory_item.embedding {
                        // Calculate cosine similarity
                        let similarity = self.cosine_similarity(&query_embedding, item_embedding);

                        if similarity >= query.relevance_threshold {
                            let importance_score = self.calculate_importance(memory_item);
                            let relevance_score = (similarity + importance_score) / 2.0;

                            results.push(ContextItem {
                                id: memory_item.id,
                                content: memory_item.content.clone(),
                                item_type: ContextItemType::Memory(memory_item.memory_type.clone()),
                                relevance_score,
                                timestamp: memory_item.created_at,
                                metadata: memory_item.metadata.clone(),
                            });
                        }
                    }
                }

                // Sort by relevance score (highest first) and limit results
                results.sort_by(|a, b| {
                    b.relevance_score
                        .partial_cmp(&a.relevance_score)
                        .unwrap_or(std::cmp::Ordering::Equal)
                });
                results.truncate(query.max_results);

                Ok(results)
            } else {
                Ok(Vec::new())
            }
        }
    }

    /// Perform hybrid search combining keyword and similarity search
    async fn hybrid_search_memory(
        &self,
        agent_id: AgentId,
        query: &ContextQuery,
    ) -> Result<Vec<ContextItem>, ContextError> {
        // Perform both keyword and similarity searches
        let keyword_results = self.keyword_search_memory(agent_id, query).await?;
        let similarity_results = self.similarity_search_memory(agent_id, query).await?;

        // Combine and deduplicate results
        let mut combined_results: HashMap<ContextId, ContextItem> = HashMap::new();

        // Weight factors for combining scores (configurable)
        let keyword_weight = 0.4;
        let similarity_weight = 0.6;

        // Add keyword results
        for mut item in keyword_results {
            item.relevance_score *= keyword_weight;
            combined_results.insert(item.id, item);
        }

        // Add similarity results, combining scores for duplicates
        for mut item in similarity_results {
            item.relevance_score *= similarity_weight;

            if let Some(existing_item) = combined_results.get_mut(&item.id) {
                // Combine scores for items found in both searches
                existing_item.relevance_score += item.relevance_score;
                // Take the higher of the two relevance scores as the final score
                existing_item.relevance_score =
                    existing_item.relevance_score.max(item.relevance_score);
            } else {
                combined_results.insert(item.id, item);
            }
        }

        // Convert to vector and sort by combined relevance score
        let mut final_results: Vec<ContextItem> = combined_results.into_values().collect();
        final_results.sort_by(|a, b| {
            b.relevance_score
                .partial_cmp(&a.relevance_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Filter by threshold and limit results
        final_results.retain(|item| item.relevance_score >= query.relevance_threshold);
        final_results.truncate(query.max_results);

        Ok(final_results)
    }

    /// Calculate cosine similarity between two vectors
    fn cosine_similarity(&self, a: &[f32], b: &[f32]) -> f32 {
        if a.len() != b.len() {
            return 0.0;
        }

        let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
        let magnitude_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let magnitude_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();

        if magnitude_a == 0.0 || magnitude_b == 0.0 {
            0.0
        } else {
            dot_product / (magnitude_a * magnitude_b)
        }
    }

    /// Calculate knowledge relevance score for fallback search
    ///
    /// This method computes a meaningful relevance score based on:
    /// - Keyword match quality (exact vs partial matches)
    /// - Text coverage (how much of the query terms are found)
    /// - Knowledge confidence score
    /// - Content length factors
    ///
    /// Returns Some(score) if content matches query, None if no match
    fn calculate_knowledge_relevance(
        &self,
        content: &str,
        query: &str,
        confidence: f32,
    ) -> Option<f32> {
        let content_lower = content.to_lowercase();
        let query_lower = query.to_lowercase();
        let query_terms: Vec<&str> = query_lower.split_whitespace().collect();

        if query_terms.is_empty() {
            return None;
        }

        let mut total_match_score = 0.0f32;
        let mut matched_terms = 0;

        // Calculate match quality for each query term
        for term in &query_terms {
            if content_lower.contains(term) {
                matched_terms += 1;

                // Give higher score for exact word matches vs substring matches
                if content_lower.split_whitespace().any(|word| word == *term) {
                    total_match_score += 1.0; // Exact word match
                } else {
                    total_match_score += 0.6; // Substring match
                }

                // Bonus for terms appearing multiple times
                let occurrences = content_lower.matches(term).count();
                if occurrences > 1 {
                    total_match_score += (occurrences as f32 - 1.0) * 0.1;
                }
            }
        }

        // Return None if no matches found
        if matched_terms == 0 {
            return None;
        }

        // Calculate base relevance score
        let term_coverage = matched_terms as f32 / query_terms.len() as f32;
        let match_quality = total_match_score / query_terms.len() as f32;

        // Combine match quality, term coverage, and confidence
        let base_score = match_quality * 0.5 + term_coverage * 0.3 + confidence * 0.2;

        // Apply content length normalization
        let content_length_factor = if content.len() < 50 {
            1.0 // Short content gets full score
        } else if content.len() < 200 {
            0.95 // Medium content gets slight penalty
        } else {
            0.9 // Long content gets larger penalty for diluted relevance
        };

        // Apply position bonus if query terms appear early in content
        let position_bonus = if content_lower.starts_with(&query_lower) {
            0.1 // Exact prefix match
        } else if query_terms
            .iter()
            .any(|term| content_lower.starts_with(term))
        {
            0.05 // Partial prefix match
        } else {
            0.0
        };

        let final_score = (base_score + position_bonus) * content_length_factor;
        Some(final_score.clamp(0.0, 1.0))
    }

    /// Calculate trust score for shared knowledge based on usage patterns
    fn calculate_trust_score(&self, shared_item: &SharedKnowledgeItem) -> f32 {
        // Base trust score starts at 0.5
        let mut trust_score = 0.5;

        // Increase trust based on access count (more usage = more trusted)
        let access_factor = (shared_item.access_count as f32 + 1.0).ln() / 10.0;
        trust_score += access_factor;

        // Consider the type of knowledge (facts might be more trusted than patterns)
        let knowledge_factor = match &shared_item.knowledge {
            Knowledge::Fact(_) => 0.2,
            Knowledge::Procedure(_) => 0.1,
            Knowledge::Pattern(_) => 0.05,
        };
        trust_score += knowledge_factor;

        // Clamp between 0.0 and 1.0
        trust_score.clamp(0.0, 1.0)
    }

    /// Calculate accurate memory size in bytes for an agent context
    fn calculate_memory_size_bytes(&self, context: &AgentContext) -> usize {
        let mut total_size = 0;

        // Working memory size
        total_size += std::mem::size_of::<WorkingMemory>();
        for (key, value) in &context.memory.working_memory.variables {
            total_size += key.len();
            total_size += estimate_json_value_size(value);
        }
        for goal in &context.memory.working_memory.active_goals {
            total_size += goal.len();
        }
        if let Some(ref current_context) = context.memory.working_memory.current_context {
            total_size += current_context.len();
        }
        for focus in &context.memory.working_memory.attention_focus {
            total_size += focus.len();
        }

        // Short-term memory
        for item in &context.memory.short_term {
            total_size += estimate_memory_item_size(item);
        }

        // Long-term memory
        for item in &context.memory.long_term {
            total_size += estimate_memory_item_size(item);
        }

        // Episodic memory
        for episode in &context.memory.episodic_memory {
            total_size += estimate_episode_size(episode);
        }

        // Semantic memory
        for item in &context.memory.semantic_memory {
            total_size += estimate_semantic_memory_item_size(item);
        }

        // Knowledge base
        for fact in &context.knowledge_base.facts {
            total_size += estimate_knowledge_fact_size(fact);
        }
        for procedure in &context.knowledge_base.procedures {
            total_size += estimate_procedure_size(procedure);
        }
        for pattern in &context.knowledge_base.learned_patterns {
            total_size += estimate_pattern_size(pattern);
        }

        // Conversation history
        for item in &context.conversation_history {
            total_size += estimate_conversation_item_size(item);
        }

        // Metadata
        for (key, value) in &context.metadata {
            total_size += key.len() + value.len();
        }

        // Base struct overhead
        total_size += std::mem::size_of::<AgentContext>();

        total_size
    }

    /// Calculate retention statistics for archiving and deletion
    fn calculate_retention_statistics(&self, context: &AgentContext) -> RetentionStatus {
        let now = SystemTime::now();
        let retention_policy = &context.retention_policy;

        let mut items_to_archive = 0;
        let mut items_to_delete = 0;

        // Calculate cutoff times based on retention policy
        let memory_cutoff = now
            .checked_sub(retention_policy.memory_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        let knowledge_cutoff = now
            .checked_sub(retention_policy.knowledge_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        let conversation_cutoff = now
            .checked_sub(retention_policy.session_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        // Count memory items eligible for archiving
        for item in &context.memory.short_term {
            if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                items_to_archive += 1;
            }
        }

        for item in &context.memory.long_term {
            if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                items_to_archive += 1;
            }
        }

        for episode in &context.memory.episodic_memory {
            if episode.timestamp < memory_cutoff {
                items_to_archive += 1;
            }
        }

        // Semantic memory uses more conservative cutoff (2x memory retention)
        let semantic_cutoff = now
            .checked_sub(retention_policy.memory_retention * 2)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        for item in &context.memory.semantic_memory {
            if item.created_at < semantic_cutoff {
                items_to_archive += 1;
            }
        }

        // Count knowledge items eligible for archiving
        for fact in &context.knowledge_base.facts {
            if fact.created_at < knowledge_cutoff {
                items_to_archive += 1;
            }
        }

        // For procedures, use success rate as archiving criteria
        for procedure in &context.knowledge_base.procedures {
            if procedure.success_rate < 0.3 {
                items_to_archive += 1;
            }
        }

        // For patterns, use confidence and occurrence count
        for pattern in &context.knowledge_base.learned_patterns {
            if pattern.confidence < 0.4 || pattern.occurrences < 2 {
                items_to_archive += 1;
            }
        }

        // Count conversation items eligible for archiving
        for item in &context.conversation_history {
            if item.timestamp < conversation_cutoff {
                items_to_archive += 1;
            }
        }

        // Calculate items to delete (very old items that exceed 2x retention period)
        let delete_cutoff_memory = now
            .checked_sub(retention_policy.memory_retention * 2)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        let delete_cutoff_knowledge = now
            .checked_sub(retention_policy.knowledge_retention * 2)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        let delete_cutoff_conversation = now
            .checked_sub(retention_policy.session_retention * 2)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        // Count memory items eligible for deletion
        for item in &context.memory.short_term {
            if item.created_at < delete_cutoff_memory && item.last_accessed < delete_cutoff_memory {
                items_to_delete += 1;
            }
        }

        for item in &context.memory.long_term {
            if item.created_at < delete_cutoff_memory && item.last_accessed < delete_cutoff_memory {
                items_to_delete += 1;
            }
        }

        // Count knowledge items eligible for deletion
        for fact in &context.knowledge_base.facts {
            if fact.created_at < delete_cutoff_knowledge && !fact.verified {
                items_to_delete += 1;
            }
        }

        // Count conversation items eligible for deletion
        for item in &context.conversation_history {
            if item.timestamp < delete_cutoff_conversation {
                items_to_delete += 1;
            }
        }

        // Calculate next cleanup time (daily cleanup schedule)
        let next_cleanup = now + Duration::from_secs(86400); // 24 hours

        RetentionStatus {
            items_to_archive,
            items_to_delete,
            next_cleanup,
        }
    }

    /// Archive old memory items from context
    async fn archive_memory_items(
        &self,
        context: &mut AgentContext,
        before: SystemTime,
        archived_context: &mut ArchivedContext,
    ) -> Result<u32, ContextError> {
        let mut archived_count = 0u32;
        let retention_policy = &context.retention_policy;

        // Calculate cutoff times based on retention policy
        let memory_cutoff = before
            .checked_sub(retention_policy.memory_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        // Archive short-term memory items
        let mut retained_short_term = Vec::new();
        for item in context.memory.short_term.drain(..) {
            if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                archived_context.memory.short_term.push(item);
                archived_count += 1;
            } else {
                retained_short_term.push(item);
            }
        }
        context.memory.short_term = retained_short_term;

        // Archive long-term memory items (older than retention policy)
        let mut retained_long_term = Vec::new();
        for item in context.memory.long_term.drain(..) {
            if item.created_at < memory_cutoff || item.last_accessed < memory_cutoff {
                archived_context.memory.long_term.push(item);
                archived_count += 1;
            } else {
                retained_long_term.push(item);
            }
        }
        context.memory.long_term = retained_long_term;

        // Archive episodic memory
        let mut retained_episodes = Vec::new();
        for episode in context.memory.episodic_memory.drain(..) {
            if episode.timestamp < memory_cutoff {
                archived_context.memory.episodic_memory.push(episode);
                archived_count += 1;
            } else {
                retained_episodes.push(episode);
            }
        }
        context.memory.episodic_memory = retained_episodes;

        // Archive semantic memory (less aggressive - only archive very old items)
        let semantic_cutoff = before
            .checked_sub(retention_policy.memory_retention * 2)
            .unwrap_or(SystemTime::UNIX_EPOCH);
        let mut retained_semantic = Vec::new();
        for item in context.memory.semantic_memory.drain(..) {
            if item.created_at < semantic_cutoff {
                archived_context.memory.semantic_memory.push(item);
                archived_count += 1;
            } else {
                retained_semantic.push(item);
            }
        }
        context.memory.semantic_memory = retained_semantic;

        Ok(archived_count)
    }

    /// Archive old conversation history
    async fn archive_conversation_history(
        &self,
        context: &mut AgentContext,
        before: SystemTime,
        archived_context: &mut ArchivedContext,
    ) -> Result<u32, ContextError> {
        let mut archived_count = 0u32;
        let retention_policy = &context.retention_policy;

        // Calculate cutoff time for conversation history
        let conversation_cutoff = before
            .checked_sub(retention_policy.session_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        // Archive old conversation items
        let mut retained_conversations = Vec::new();
        for item in context.conversation_history.drain(..) {
            if item.timestamp < conversation_cutoff {
                archived_context.conversation_history.push(item);
                archived_count += 1;
            } else {
                retained_conversations.push(item);
            }
        }
        context.conversation_history = retained_conversations;

        Ok(archived_count)
    }

    /// Archive old knowledge base items
    async fn archive_knowledge_items(
        &self,
        context: &mut AgentContext,
        before: SystemTime,
        archived_context: &mut ArchivedContext,
    ) -> Result<u32, ContextError> {
        let mut archived_count = 0u32;
        let retention_policy = &context.retention_policy;

        // Calculate cutoff time for knowledge items
        let knowledge_cutoff = before
            .checked_sub(retention_policy.knowledge_retention)
            .unwrap_or(SystemTime::UNIX_EPOCH);

        // Archive old facts
        let mut retained_facts = Vec::new();
        for fact in context.knowledge_base.facts.drain(..) {
            if fact.created_at < knowledge_cutoff {
                archived_context.knowledge_base.facts.push(fact);
                archived_count += 1;
            } else {
                retained_facts.push(fact);
            }
        }
        context.knowledge_base.facts = retained_facts;

        // Archive old procedures (be more conservative)
        // Note: Procedures don't have created_at in current schema, so we use success_rate as proxy
        let mut retained_procedures = Vec::new();
        for procedure in context.knowledge_base.procedures.drain(..) {
            // Archive procedures with very low success rate
            if procedure.success_rate < 0.3 {
                archived_context.knowledge_base.procedures.push(procedure);
                archived_count += 1;
            } else {
                retained_procedures.push(procedure);
            }
        }
        context.knowledge_base.procedures = retained_procedures;

        // Archive old patterns (if confidence is low or very old)
        let mut retained_patterns = Vec::new();
        for pattern in context.knowledge_base.learned_patterns.drain(..) {
            if pattern.confidence < 0.4 || pattern.occurrences < 2 {
                archived_context
                    .knowledge_base
                    .learned_patterns
                    .push(pattern);
                archived_count += 1;
            } else {
                retained_patterns.push(pattern);
            }
        }
        context.knowledge_base.learned_patterns = retained_patterns;

        Ok(archived_count)
    }

    /// Save archived context to persistent storage
    async fn save_archived_context(
        &self,
        agent_id: AgentId,
        archived_context: &ArchivedContext,
    ) -> Result<(), ContextError> {
        if !self.config.enable_persistence {
            return Ok(());
        }

        // Get archive directory path
        let archive_dir = self.get_archive_directory_path(agent_id).await?;

        // Create archive filename with timestamp
        let timestamp = archived_context
            .archived_at
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let archive_filename = format!("archive_{}.json", timestamp);
        let archive_path = archive_dir.join(archive_filename);

        // Serialize archived context
        let archive_data = serde_json::to_vec_pretty(archived_context).map_err(|e| {
            ContextError::SerializationError {
                reason: format!("Failed to serialize archived context: {}", e),
            }
        })?;

        // Write to archive file with compression if enabled
        let final_data = if self.config.persistence_config.enable_compression {
            self.compress_data(&archive_data)?
        } else {
            archive_data
        };

        // Ensure atomic write operation
        let temp_path = archive_path.with_extension("tmp");
        fs::write(&temp_path, &final_data)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to write archive file: {}", e),
            })?;

        // Atomically move temp file to final location
        fs::rename(&temp_path, &archive_path)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to finalize archive file: {}", e),
            })?;

        tracing::info!(
            "Saved archived context for agent {} to {}",
            agent_id,
            archive_path.display()
        );

        Ok(())
    }

    /// Get archive directory path for an agent
    async fn get_archive_directory_path(&self, agent_id: AgentId) -> Result<PathBuf, ContextError> {
        let archive_dir = self
            .config
            .persistence_config
            .agent_contexts_path()
            .join("archives")
            .join(agent_id.to_string());

        // Ensure archive directory exists
        fs::create_dir_all(&archive_dir)
            .await
            .map_err(|e| ContextError::StorageError {
                reason: format!("Failed to create archive directory: {}", e),
            })?;

        Ok(archive_dir)
    }

    /// Compress data using gzip
    fn compress_data(&self, data: &[u8]) -> Result<Vec<u8>, ContextError> {
        use flate2::write::GzEncoder;
        use flate2::Compression;
        use std::io::Write;

        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder
            .write_all(data)
            .map_err(|e| ContextError::SerializationError {
                reason: format!("Failed to compress archive data: {}", e),
            })?;
        encoder
            .finish()
            .map_err(|e| ContextError::SerializationError {
                reason: format!("Failed to finalize compression: {}", e),
            })
    }

    /// Convert Knowledge to KnowledgeItem for vector storage
    fn knowledge_to_item(
        &self,
        knowledge: &Knowledge,
        knowledge_id: KnowledgeId,
    ) -> Result<KnowledgeItem, ContextError> {
        match knowledge {
            Knowledge::Fact(fact) => {
                Ok(KnowledgeItem {
                    id: knowledge_id,
                    content: format!("{} {} {}", fact.subject, fact.predicate, fact.object),
                    knowledge_type: KnowledgeType::Fact,
                    confidence: fact.confidence,
                    relevance_score: 1.0, // Initial relevance
                    source: fact.source.clone(),
                    created_at: fact.created_at,
                })
            }
            Knowledge::Procedure(procedure) => {
                Ok(KnowledgeItem {
                    id: knowledge_id,
                    content: format!("{}: {}", procedure.name, procedure.description),
                    knowledge_type: KnowledgeType::Procedure,
                    confidence: procedure.success_rate,
                    relevance_score: 1.0, // Initial relevance
                    source: KnowledgeSource::Learning,
                    created_at: SystemTime::now(),
                })
            }
            Knowledge::Pattern(pattern) => {
                Ok(KnowledgeItem {
                    id: knowledge_id,
                    content: format!("Pattern: {}", pattern.description),
                    knowledge_type: KnowledgeType::Pattern,
                    confidence: pattern.confidence,
                    relevance_score: 1.0, // Initial relevance
                    source: KnowledgeSource::Learning,
                    created_at: SystemTime::now(),
                })
            }
        }
    }
}

/// Estimate memory size of a JSON value in bytes
fn estimate_json_value_size(value: &Value) -> usize {
    match value {
        Value::Null => 4,
        Value::Bool(_) => 1,
        Value::Number(n) => std::mem::size_of::<f64>() + n.to_string().len(),
        Value::String(s) => s.len(),
        Value::Array(arr) => {
            arr.iter().map(estimate_json_value_size).sum::<usize>()
                + std::mem::size_of::<Vec<Value>>()
        }
        Value::Object(obj) => {
            obj.iter()
                .map(|(k, v)| k.len() + estimate_json_value_size(v))
                .sum::<usize>()
                + std::mem::size_of::<serde_json::Map<String, Value>>()
        }
    }
}

/// Estimate memory size of a MemoryItem in bytes
fn estimate_memory_item_size(item: &MemoryItem) -> usize {
    let mut size = std::mem::size_of::<MemoryItem>();
    size += item.content.len();

    // Estimate embedding size if present
    if let Some(ref embedding) = item.embedding {
        size += embedding.len() * std::mem::size_of::<f32>();
    }

    // Estimate metadata size
    for (key, value) in &item.metadata {
        size += key.len() + value.len();
    }

    size
}

/// Estimate memory size of an Episode in bytes
fn estimate_episode_size(episode: &Episode) -> usize {
    let mut size = std::mem::size_of::<Episode>();
    size += episode.title.len();
    size += episode.description.len();

    if let Some(ref outcome) = episode.outcome {
        size += outcome.len();
    }

    for event in &episode.events {
        size += event.action.len();
        size += event.result.len();
        for (key, value) in &event.context {
            size += key.len() + value.len();
        }
    }

    for lesson in &episode.lessons_learned {
        size += lesson.len();
    }

    size
}

/// Estimate memory size of a SemanticMemoryItem in bytes
fn estimate_semantic_memory_item_size(item: &SemanticMemoryItem) -> usize {
    let mut size = std::mem::size_of::<SemanticMemoryItem>();
    size += item.concept.len();

    for relationship in &item.relationships {
        size += relationship.target_concept.len();
        size += std::mem::size_of::<ConceptRelationship>();
    }

    for (key, value) in &item.properties {
        size += key.len() + estimate_json_value_size(value);
    }

    size
}

/// Estimate memory size of a KnowledgeFact in bytes
fn estimate_knowledge_fact_size(fact: &KnowledgeFact) -> usize {
    std::mem::size_of::<KnowledgeFact>()
        + fact.subject.len()
        + fact.predicate.len()
        + fact.object.len()
}

/// Estimate memory size of a Procedure in bytes
fn estimate_procedure_size(procedure: &Procedure) -> usize {
    let mut size = std::mem::size_of::<Procedure>();
    size += procedure.name.len();
    size += procedure.description.len();

    for step in &procedure.steps {
        size += step.action.len();
        size += step.expected_result.len();
        if let Some(ref error_handling) = step.error_handling {
            size += error_handling.len();
        }
    }

    for condition in &procedure.preconditions {
        size += condition.len();
    }

    for condition in &procedure.postconditions {
        size += condition.len();
    }

    size
}

/// Estimate memory size of a Pattern in bytes
fn estimate_pattern_size(pattern: &Pattern) -> usize {
    let mut size = std::mem::size_of::<Pattern>();
    size += pattern.name.len();
    size += pattern.description.len();

    for condition in &pattern.conditions {
        size += condition.len();
    }

    for outcome in &pattern.outcomes {
        size += outcome.len();
    }

    size
}

/// Estimate memory size of a ConversationItem in bytes
fn estimate_conversation_item_size(item: &ConversationItem) -> usize {
    let mut size = std::mem::size_of::<ConversationItem>();
    size += item.content.len();

    // Estimate size of ID vectors
    size += item.context_used.len() * std::mem::size_of::<ContextId>();
    size += item.knowledge_used.len() * std::mem::size_of::<KnowledgeId>();

    size
}

#[async_trait]
impl ContextManager for StandardContextManager {
    async fn store_context(
        &self,
        agent_id: AgentId,
        mut context: AgentContext,
    ) -> Result<ContextId, ContextError> {
        self.validate_access(agent_id, "store_context").await?;

        context.updated_at = SystemTime::now();
        let context_id = ContextId::new();

        // Store in persistent storage if enabled
        if self.config.enable_persistence {
            self.persistence.save_context(agent_id, &context).await?;
        }

        // Store in memory cache
        let mut contexts = self.contexts.write().await;
        contexts.insert(agent_id, context);

        Ok(context_id)
    }

    async fn retrieve_context(
        &self,
        agent_id: AgentId,
        session_id: Option<SessionId>,
    ) -> Result<Option<AgentContext>, ContextError> {
        self.validate_access(agent_id, "retrieve_context").await?;

        // First check memory cache
        {
            let contexts = self.contexts.read().await;
            if let Some(context) = contexts.get(&agent_id) {
                // If session_id is specified, check if it matches
                if let Some(sid) = session_id {
                    if context.session_id == sid {
                        return Ok(Some(context.clone()));
                    }
                } else {
                    return Ok(Some(context.clone()));
                }
            }
        }

        // If not in memory and persistence is enabled, try loading from storage
        if self.config.enable_persistence {
            if let Some(context) = self.persistence.load_context(agent_id).await? {
                // Check session_id if specified
                if let Some(sid) = session_id {
                    if context.session_id != sid {
                        return Ok(None);
                    }
                }

                // Cache the loaded context
                let mut contexts = self.contexts.write().await;
                contexts.insert(agent_id, context.clone());

                return Ok(Some(context));
            }
        }

        Ok(None)
    }

    async fn query_context(
        &self,
        agent_id: AgentId,
        query: ContextQuery,
    ) -> Result<Vec<ContextItem>, ContextError> {
        self.validate_access(agent_id, "query_context").await?;

        match query.query_type {
            QueryType::Semantic => {
                let search_term = query.search_terms.join(" ");
                self.semantic_search_memory(agent_id, &search_term, query.max_results)
                    .await
            }
            QueryType::Keyword => self.keyword_search_memory(agent_id, &query).await,
            QueryType::Temporal => self.temporal_search_memory(agent_id, &query).await,
            QueryType::Similarity => self.similarity_search_memory(agent_id, &query).await,
            QueryType::Hybrid => self.hybrid_search_memory(agent_id, &query).await,
        }
    }

    async fn update_memory(
        &self,
        agent_id: AgentId,
        memory_updates: Vec<MemoryUpdate>,
    ) -> Result<(), ContextError> {
        self.validate_access(agent_id, "update_memory").await?;

        let mut contexts = self.contexts.write().await;
        if let Some(context) = contexts.get_mut(&agent_id) {
            for update in memory_updates {
                match update.operation {
                    UpdateOperation::Add => {
                        match update.target {
                            MemoryTarget::ShortTerm(_) => {
                                // Parse data to create MemoryItem for short-term memory
                                if let Ok(memory_item_data) =
                                    serde_json::from_value::<serde_json::Map<String, Value>>(
                                        update.data,
                                    )
                                {
                                    let memory_item = MemoryItem {
                                        id: ContextId::new(),
                                        content: memory_item_data
                                            .get("content")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or("")
                                            .to_string(),
                                        memory_type: memory_item_data
                                            .get("memory_type")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or(MemoryType::Factual),
                                        importance: memory_item_data
                                            .get("importance")
                                            .and_then(|v| v.as_f64())
                                            .unwrap_or(0.5)
                                            as f32,
                                        access_count: 0,
                                        last_accessed: SystemTime::now(),
                                        created_at: SystemTime::now(),
                                        embedding: None,
                                        metadata: memory_item_data
                                            .get("metadata")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or_default(),
                                    };
                                    context.memory.short_term.push(memory_item);
                                }
                            }
                            MemoryTarget::LongTerm(_) => {
                                // Parse data to create MemoryItem for long-term memory
                                if let Ok(memory_item_data) =
                                    serde_json::from_value::<serde_json::Map<String, Value>>(
                                        update.data,
                                    )
                                {
                                    let memory_item = MemoryItem {
                                        id: ContextId::new(),
                                        content: memory_item_data
                                            .get("content")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or("")
                                            .to_string(),
                                        memory_type: memory_item_data
                                            .get("memory_type")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or(MemoryType::Factual),
                                        importance: memory_item_data
                                            .get("importance")
                                            .and_then(|v| v.as_f64())
                                            .unwrap_or(0.5)
                                            as f32,
                                        access_count: 0,
                                        last_accessed: SystemTime::now(),
                                        created_at: SystemTime::now(),
                                        embedding: None,
                                        metadata: memory_item_data
                                            .get("metadata")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or_default(),
                                    };
                                    context.memory.long_term.push(memory_item);
                                }
                            }
                            MemoryTarget::Working(key) => {
                                // Add to working memory variables
                                context
                                    .memory
                                    .working_memory
                                    .variables
                                    .insert(key, update.data);
                            }
                            MemoryTarget::Episodic(_) => {
                                // Parse data to create Episode for episodic memory
                                if let Ok(episode_data) =
                                    serde_json::from_value::<serde_json::Map<String, Value>>(
                                        update.data,
                                    )
                                {
                                    let episode = Episode {
                                        id: ContextId::new(),
                                        title: episode_data
                                            .get("title")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or("Untitled Episode")
                                            .to_string(),
                                        description: episode_data
                                            .get("description")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or("")
                                            .to_string(),
                                        events: episode_data
                                            .get("events")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or_default(),
                                        outcome: episode_data
                                            .get("outcome")
                                            .and_then(|v| v.as_str())
                                            .map(|s| s.to_string()),
                                        lessons_learned: episode_data
                                            .get("lessons_learned")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or_default(),
                                        timestamp: SystemTime::now(),
                                        importance: episode_data
                                            .get("importance")
                                            .and_then(|v| v.as_f64())
                                            .unwrap_or(0.5)
                                            as f32,
                                    };
                                    context.memory.episodic_memory.push(episode);
                                }
                            }
                            MemoryTarget::Semantic(_) => {
                                // Parse data to create SemanticMemoryItem for semantic memory
                                if let Ok(semantic_data) =
                                    serde_json::from_value::<serde_json::Map<String, Value>>(
                                        update.data,
                                    )
                                {
                                    let semantic_item = SemanticMemoryItem {
                                        id: ContextId::new(),
                                        concept: semantic_data
                                            .get("concept")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or("")
                                            .to_string(),
                                        relationships: semantic_data
                                            .get("relationships")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or_default(),
                                        properties: semantic_data
                                            .get("properties")
                                            .and_then(|v| serde_json::from_value(v.clone()).ok())
                                            .unwrap_or_default(),
                                        confidence: semantic_data
                                            .get("confidence")
                                            .and_then(|v| v.as_f64())
                                            .unwrap_or(0.5)
                                            as f32,
                                        created_at: SystemTime::now(),
                                        updated_at: SystemTime::now(),
                                    };
                                    context.memory.semantic_memory.push(semantic_item);
                                }
                            }
                        }
                    }
                    UpdateOperation::Update => {
                        match update.target {
                            MemoryTarget::ShortTerm(target_id) => {
                                // Update existing short-term memory item
                                if let Some(memory_item) = context
                                    .memory
                                    .short_term
                                    .iter_mut()
                                    .find(|item| item.id == target_id)
                                {
                                    if let Ok(update_data) =
                                        serde_json::from_value::<serde_json::Map<String, Value>>(
                                            update.data,
                                        )
                                    {
                                        if let Some(content) =
                                            update_data.get("content").and_then(|v| v.as_str())
                                        {
                                            memory_item.content = content.to_string();
                                        }
                                        if let Some(importance) =
                                            update_data.get("importance").and_then(|v| v.as_f64())
                                        {
                                            memory_item.importance = importance as f32;
                                        }
                                        if let Some(metadata) = update_data.get("metadata") {
                                            if let Ok(new_metadata) =
                                                serde_json::from_value(metadata.clone())
                                            {
                                                memory_item.metadata = new_metadata;
                                            }
                                        }
                                        memory_item.last_accessed = SystemTime::now();
                                        memory_item.access_count += 1;
                                    }
                                }
                            }
                            MemoryTarget::LongTerm(target_id) => {
                                // Update existing long-term memory item
                                if let Some(memory_item) = context
                                    .memory
                                    .long_term
                                    .iter_mut()
                                    .find(|item| item.id == target_id)
                                {
                                    if let Ok(update_data) =
                                        serde_json::from_value::<serde_json::Map<String, Value>>(
                                            update.data,
                                        )
                                    {
                                        if let Some(content) =
                                            update_data.get("content").and_then(|v| v.as_str())
                                        {
                                            memory_item.content = content.to_string();
                                        }
                                        if let Some(importance) =
                                            update_data.get("importance").and_then(|v| v.as_f64())
                                        {
                                            memory_item.importance = importance as f32;
                                        }
                                        if let Some(metadata) = update_data.get("metadata") {
                                            if let Ok(new_metadata) =
                                                serde_json::from_value(metadata.clone())
                                            {
                                                memory_item.metadata = new_metadata;
                                            }
                                        }
                                        memory_item.last_accessed = SystemTime::now();
                                        memory_item.access_count += 1;
                                    }
                                }
                            }
                            MemoryTarget::Working(key) => {
                                // Update working memory variable
                                context
                                    .memory
                                    .working_memory
                                    .variables
                                    .insert(key, update.data);
                            }
                            MemoryTarget::Episodic(target_id) => {
                                // Update existing episode
                                if let Some(episode) = context
                                    .memory
                                    .episodic_memory
                                    .iter_mut()
                                    .find(|ep| ep.id == target_id)
                                {
                                    if let Ok(update_data) =
                                        serde_json::from_value::<serde_json::Map<String, Value>>(
                                            update.data,
                                        )
                                    {
                                        if let Some(title) =
                                            update_data.get("title").and_then(|v| v.as_str())
                                        {
                                            episode.title = title.to_string();
                                        }
                                        if let Some(description) =
                                            update_data.get("description").and_then(|v| v.as_str())
                                        {
                                            episode.description = description.to_string();
                                        }
                                        if let Some(outcome) =
                                            update_data.get("outcome").and_then(|v| v.as_str())
                                        {
                                            episode.outcome = Some(outcome.to_string());
                                        }
                                        if let Some(importance) =
                                            update_data.get("importance").and_then(|v| v.as_f64())
                                        {
                                            episode.importance = importance as f32;
                                        }
                                        if let Some(lessons) = update_data.get("lessons_learned") {
                                            if let Ok(new_lessons) =
                                                serde_json::from_value(lessons.clone())
                                            {
                                                episode.lessons_learned = new_lessons;
                                            }
                                        }
                                    }
                                }
                            }
                            MemoryTarget::Semantic(target_id) => {
                                // Update existing semantic memory item
                                if let Some(semantic_item) = context
                                    .memory
                                    .semantic_memory
                                    .iter_mut()
                                    .find(|item| item.id == target_id)
                                {
                                    if let Ok(update_data) =
                                        serde_json::from_value::<serde_json::Map<String, Value>>(
                                            update.data,
                                        )
                                    {
                                        if let Some(concept) =
                                            update_data.get("concept").and_then(|v| v.as_str())
                                        {
                                            semantic_item.concept = concept.to_string();
                                        }
                                        if let Some(confidence) =
                                            update_data.get("confidence").and_then(|v| v.as_f64())
                                        {
                                            semantic_item.confidence = confidence as f32;
                                        }
                                        if let Some(relationships) =
                                            update_data.get("relationships")
                                        {
                                            if let Ok(new_relationships) =
                                                serde_json::from_value(relationships.clone())
                                            {
                                                semantic_item.relationships = new_relationships;
                                            }
                                        }
                                        if let Some(properties) = update_data.get("properties") {
                                            if let Ok(new_properties) =
                                                serde_json::from_value(properties.clone())
                                            {
                                                semantic_item.properties = new_properties;
                                            }
                                        }
                                        semantic_item.updated_at = SystemTime::now();
                                    }
                                }
                            }
                        }
                    }
                    UpdateOperation::Delete => {
                        match update.target {
                            MemoryTarget::ShortTerm(target_id) => {
                                // Remove from short-term memory
                                context
                                    .memory
                                    .short_term
                                    .retain(|item| item.id != target_id);
                            }
                            MemoryTarget::LongTerm(target_id) => {
                                // Remove from long-term memory
                                context.memory.long_term.retain(|item| item.id != target_id);
                            }
                            MemoryTarget::Working(key) => {
                                // Remove from working memory variables
                                context.memory.working_memory.variables.remove(&key);
                            }
                            MemoryTarget::Episodic(target_id) => {
                                // Remove from episodic memory
                                context
                                    .memory
                                    .episodic_memory
                                    .retain(|ep| ep.id != target_id);
                            }
                            MemoryTarget::Semantic(target_id) => {
                                // Remove from semantic memory
                                context
                                    .memory
                                    .semantic_memory
                                    .retain(|item| item.id != target_id);
                            }
                        }
                    }
                    UpdateOperation::Increment => {
                        match update.target {
                            MemoryTarget::ShortTerm(target_id) => {
                                // Increment numeric fields in short-term memory
                                if let Some(memory_item) = context
                                    .memory
                                    .short_term
                                    .iter_mut()
                                    .find(|item| item.id == target_id)
                                {
                                    if let Ok(increment_data) =
                                        serde_json::from_value::<serde_json::Map<String, Value>>(
                                            update.data,
                                        )
                                    {
                                        if let Some(importance_increment) = increment_data
                                            .get("importance")
                                            .and_then(|v| v.as_f64())
                                        {
                                            memory_item.importance = (memory_item.importance
                                                + importance_increment as f32)
                                                .clamp(0.0, 1.0);
                                        }
                                        if let Some(access_increment) = increment_data
                                            .get("access_count")
                                            .and_then(|v| v.as_u64())
                                        {
                                            memory_item.access_count = memory_item
                                                .access_count
                                                .saturating_add(access_increment as u32);
                                        }
                                        memory_item.last_accessed = SystemTime::now();
                                    }
                                }
                            }
                            MemoryTarget::LongTerm(target_id) => {
                                // Increment numeric fields in long-term memory
                                if let Some(memory_item) = context
                                    .memory
                                    .long_term
                                    .iter_mut()
                                    .find(|item| item.id == target_id)
                                {
                                    if let Ok(increment_data) =
                                        serde_json::from_value::<serde_json::Map<String, Value>>(
                                            update.data,
                                        )
                                    {
                                        if let Some(importance_increment) = increment_data
                                            .get("importance")
                                            .and_then(|v| v.as_f64())
                                        {
                                            memory_item.importance = (memory_item.importance
                                                + importance_increment as f32)
                                                .clamp(0.0, 1.0);
                                        }
                                        if let Some(access_increment) = increment_data
                                            .get("access_count")
                                            .and_then(|v| v.as_u64())
                                        {
                                            memory_item.access_count = memory_item
                                                .access_count
                                                .saturating_add(access_increment as u32);
                                        }
                                        memory_item.last_accessed = SystemTime::now();
                                    }
                                }
                            }
                            MemoryTarget::Working(key) => {
                                // Increment numeric value in working memory
                                if let Some(existing_value) =
                                    context.memory.working_memory.variables.get(&key)
                                {
                                    if let (Some(current), Some(increment)) =
                                        (existing_value.as_f64(), update.data.as_f64())
                                    {
                                        let new_value = current + increment;
                                        context.memory.working_memory.variables.insert(
                                            key,
                                            Value::Number(
                                                serde_json::Number::from_f64(new_value)
                                                    .unwrap_or_else(|| serde_json::Number::from(0)),
                                            ),
                                        );
                                    } else if let (Some(current), Some(increment)) =
                                        (existing_value.as_i64(), update.data.as_i64())
                                    {
                                        let new_value = current.saturating_add(increment);
                                        context.memory.working_memory.variables.insert(
                                            key,
                                            Value::Number(serde_json::Number::from(new_value)),
                                        );
                                    }
                                }
                            }
                            MemoryTarget::Episodic(target_id) => {
                                // Increment numeric fields in episodic memory
                                if let Some(episode) = context
                                    .memory
                                    .episodic_memory
                                    .iter_mut()
                                    .find(|ep| ep.id == target_id)
                                {
                                    if let Some(importance_increment) = update.data.as_f64() {
                                        episode.importance = (episode.importance
                                            + importance_increment as f32)
                                            .clamp(0.0, 1.0);
                                    }
                                }
                            }
                            MemoryTarget::Semantic(target_id) => {
                                // Increment numeric fields in semantic memory
                                if let Some(semantic_item) = context
                                    .memory
                                    .semantic_memory
                                    .iter_mut()
                                    .find(|item| item.id == target_id)
                                {
                                    if let Some(confidence_increment) = update.data.as_f64() {
                                        semantic_item.confidence = (semantic_item.confidence
                                            + confidence_increment as f32)
                                            .clamp(0.0, 1.0);
                                        semantic_item.updated_at = SystemTime::now();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Update context timestamp
            context.updated_at = SystemTime::now();

            // Persist changes to storage if enabled
            if self.config.enable_persistence {
                if let Err(e) = self.persistence.save_context(agent_id, context).await {
                    tracing::error!(
                        "Failed to persist memory updates for agent {}: {}",
                        agent_id,
                        e
                    );
                    return Err(e);
                }
            }
        } else {
            return Err(ContextError::NotFound {
                id: ContextId::new(),
            });
        }

        Ok(())
    }

    async fn add_knowledge(
        &self,
        agent_id: AgentId,
        knowledge: Knowledge,
    ) -> Result<KnowledgeId, ContextError> {
        self.validate_access(agent_id, "add_knowledge").await?;

        let knowledge_id = KnowledgeId::new();

        // Store in vector database if enabled
        if self.config.enable_vector_db {
            let knowledge_item = self.knowledge_to_item(&knowledge, knowledge_id)?;
            let embedding = self.generate_embeddings(&knowledge_item.content).await?;
            let _vector_id = self
                .vector_db
                .store_knowledge_item(&knowledge_item, embedding)
                .await?;
        }

        // Also store in local context for backward compatibility
        let mut contexts = self.contexts.write().await;
        if let Some(context) = contexts.get_mut(&agent_id) {
            match knowledge {
                Knowledge::Fact(fact) => {
                    context.knowledge_base.facts.push(fact);
                }
                Knowledge::Procedure(procedure) => {
                    context.knowledge_base.procedures.push(procedure);
                }
                Knowledge::Pattern(pattern) => {
                    context.knowledge_base.learned_patterns.push(pattern);
                }
            }
            context.updated_at = SystemTime::now();
        }

        Ok(knowledge_id)
    }

    async fn search_knowledge(
        &self,
        agent_id: AgentId,
        query: &str,
        limit: usize,
    ) -> Result<Vec<KnowledgeItem>, ContextError> {
        self.validate_access(agent_id, "search_knowledge").await?;

        if self.config.enable_vector_db {
            // Generate embeddings for the query
            let query_embedding = self.generate_embeddings(query).await?;

            // Search the vector database for knowledge items
            self.vector_db
                .search_knowledge_base(agent_id, query_embedding, limit)
                .await
        } else {
            // Fallback to simple keyword search
            let contexts = self.contexts.read().await;
            if let Some(context) = contexts.get(&agent_id) {
                let mut results = Vec::new();

                // Search facts
                for fact in &context.knowledge_base.facts {
                    let content = format!("{} {} {}", fact.subject, fact.predicate, fact.object);
                    if let Some(relevance_score) =
                        self.calculate_knowledge_relevance(&content, query, fact.confidence)
                    {
                        results.push(KnowledgeItem {
                            id: fact.id,
                            content,
                            knowledge_type: KnowledgeType::Fact,
                            confidence: fact.confidence,
                            relevance_score,
                            source: fact.source.clone(),
                            created_at: fact.created_at,
                        });
                    }
                }

                // Search procedures
                for procedure in &context.knowledge_base.procedures {
                    let searchable_content =
                        format!("{} {}", procedure.name, procedure.description);
                    if let Some(relevance_score) = self.calculate_knowledge_relevance(
                        &searchable_content,
                        query,
                        procedure.success_rate,
                    ) {
                        results.push(KnowledgeItem {
                            id: procedure.id,
                            content: format!("{}: {}", procedure.name, procedure.description),
                            knowledge_type: KnowledgeType::Procedure,
                            confidence: procedure.success_rate,
                            relevance_score,
                            source: KnowledgeSource::Learning,
                            created_at: SystemTime::now(), // Procedures don't store creation time in current schema
                        });
                    }
                }

                // Search patterns
                for pattern in &context.knowledge_base.learned_patterns {
                    let searchable_content = format!("{} {}", pattern.name, pattern.description);
                    if let Some(relevance_score) = self.calculate_knowledge_relevance(
                        &searchable_content,
                        query,
                        pattern.confidence,
                    ) {
                        results.push(KnowledgeItem {
                            id: pattern.id,
                            content: format!("Pattern: {}", pattern.description),
                            knowledge_type: KnowledgeType::Pattern,
                            confidence: pattern.confidence,
                            relevance_score,
                            source: KnowledgeSource::Learning,
                            created_at: SystemTime::now(), // Patterns don't store creation time in current schema
                        });
                    }
                }

                // Sort by relevance score (highest first) and limit results
                results.sort_by(|a, b| {
                    b.relevance_score
                        .partial_cmp(&a.relevance_score)
                        .unwrap_or(std::cmp::Ordering::Equal)
                });

                results.truncate(limit);
                Ok(results)
            } else {
                Ok(Vec::new())
            }
        }
    }

    async fn share_knowledge(
        &self,
        from_agent: AgentId,
        _to_agent: AgentId,
        knowledge_id: KnowledgeId,
        access_level: AccessLevel,
    ) -> Result<(), ContextError> {
        self.validate_access(from_agent, "share_knowledge").await?;

        // Find the knowledge item in the source agent's knowledge base
        let contexts = self.contexts.read().await;
        if let Some(from_context) = contexts.get(&from_agent) {
            // Find the knowledge item
            let knowledge = if let Some(fact) = from_context
                .knowledge_base
                .facts
                .iter()
                .find(|f| f.id == knowledge_id)
            {
                Some(Knowledge::Fact(fact.clone()))
            } else if let Some(procedure) = from_context
                .knowledge_base
                .procedures
                .iter()
                .find(|p| p.id == knowledge_id)
            {
                Some(Knowledge::Procedure(procedure.clone()))
            } else {
                from_context
                    .knowledge_base
                    .learned_patterns
                    .iter()
                    .find(|p| p.id == knowledge_id)
                    .map(|pattern| Knowledge::Pattern(pattern.clone()))
            };

            if let Some(knowledge) = knowledge {
                // Store in shared knowledge
                let shared_item = SharedKnowledgeItem {
                    knowledge,
                    source_agent: from_agent,
                    access_level,
                    created_at: SystemTime::now(),
                    access_count: 0,
                };

                let mut shared_knowledge = self.shared_knowledge.write().await;
                shared_knowledge.insert(knowledge_id, shared_item);

                Ok(())
            } else {
                Err(ContextError::KnowledgeNotFound { id: knowledge_id })
            }
        } else {
            Err(ContextError::NotFound {
                id: ContextId::new(),
            })
        }
    }

    async fn get_shared_knowledge(
        &self,
        agent_id: AgentId,
    ) -> Result<Vec<SharedKnowledgeRef>, ContextError> {
        self.validate_access(agent_id, "get_shared_knowledge")
            .await?;

        let shared_knowledge = self.shared_knowledge.read().await;
        let mut results = Vec::new();

        for (knowledge_id, shared_item) in shared_knowledge.iter() {
            // Check if agent has access to this knowledge
            match shared_item.access_level {
                AccessLevel::Public => {
                    // Calculate trust score based on access count and knowledge type
                    let trust_score = self.calculate_trust_score(shared_item);

                    tracing::debug!(
                        "Shared knowledge {} accessed {} times, trust score: {}",
                        knowledge_id,
                        shared_item.access_count,
                        trust_score
                    );

                    results.push(SharedKnowledgeRef {
                        knowledge_id: *knowledge_id,
                        source_agent: shared_item.source_agent,
                        shared_at: shared_item.created_at,
                        access_level: shared_item.access_level.clone(),
                        trust_score,
                    });
                }
                _ => {
                    // For other access levels, would check specific permissions
                }
            }
        }

        Ok(results)
    }

    async fn archive_context(
        &self,
        agent_id: AgentId,
        before: SystemTime,
    ) -> Result<u32, ContextError> {
        self.validate_access(agent_id, "archive_context").await?;

        let mut total_archived = 0u32;
        let mut archived_context = ArchivedContext::new(agent_id, before);

        // Get current context
        let mut contexts = self.contexts.write().await;
        if let Some(context) = contexts.get_mut(&agent_id) {
            // Archive old memory items
            total_archived += self
                .archive_memory_items(context, before, &mut archived_context)
                .await?;

            // Archive old conversation history
            total_archived += self
                .archive_conversation_history(context, before, &mut archived_context)
                .await?;

            // Archive old knowledge base items (based on retention policy)
            total_archived += self
                .archive_knowledge_items(context, before, &mut archived_context)
                .await?;

            // Persist archived data if we have items to archive
            if total_archived > 0 {
                self.save_archived_context(agent_id, &archived_context)
                    .await?;

                // Update context metadata
                context.updated_at = SystemTime::now();
                context.metadata.insert(
                    "last_archived".to_string(),
                    SystemTime::now()
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs()
                        .to_string(),
                );
                context
                    .metadata
                    .insert("archived_count".to_string(), total_archived.to_string());

                // Persist updated context
                if self.config.enable_persistence {
                    self.persistence.save_context(agent_id, context).await?;
                }
            }

            tracing::info!(
                "Archived {} items for agent {} before timestamp {:?}",
                total_archived,
                agent_id,
                before
            );
        } else {
            tracing::warn!("No context found for agent {} during archiving", agent_id);
        }

        Ok(total_archived)
    }

    async fn get_context_stats(&self, agent_id: AgentId) -> Result<ContextStats, ContextError> {
        self.validate_access(agent_id, "get_context_stats").await?;

        let contexts = self.contexts.read().await;
        if let Some(context) = contexts.get(&agent_id) {
            let total_memory_items = context.memory.short_term.len()
                + context.memory.long_term.len()
                + context.memory.episodic_memory.len()
                + context.memory.semantic_memory.len();

            let total_knowledge_items = context.knowledge_base.facts.len()
                + context.knowledge_base.procedures.len()
                + context.knowledge_base.learned_patterns.len();

            // Calculate accurate memory size in bytes
            let memory_size_bytes = self.calculate_memory_size_bytes(context);

            // Calculate retention statistics
            let retention_stats = self.calculate_retention_statistics(context);

            Ok(ContextStats {
                total_memory_items,
                total_knowledge_items,
                total_conversations: context.conversation_history.len(),
                total_episodes: context.memory.episodic_memory.len(),
                memory_size_bytes,
                last_activity: context.updated_at,
                retention_status: retention_stats,
            })
        } else {
            Err(ContextError::NotFound {
                id: ContextId::new(),
            })
        }
    }

    async fn shutdown(&self) -> Result<(), ContextError> {
        // Delegate to the concrete implementation's shutdown method
        StandardContextManager::shutdown(self).await
    }
}

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

    #[tokio::test]
    async fn check_and_compact_noop_when_below_threshold() {
        use super::super::compaction::CompactionConfig;
        use super::super::token_counter::HeuristicTokenCounter;

        let tmp = tempfile::tempdir().unwrap();
        let mut config = ContextManagerConfig::default();
        config.persistence_config.root_data_dir = tmp.path().to_path_buf();
        let agent_id = AgentId::new();
        let manager = StandardContextManager::new(config, &agent_id.to_string())
            .await
            .unwrap();
        manager.initialize().await.unwrap();
        let session_id = manager.create_session(agent_id).await.unwrap();

        let compaction_config = CompactionConfig::default();
        let counter = HeuristicTokenCounter::new(200_000);

        let result = manager
            .check_and_compact(&agent_id, &session_id, &compaction_config, &counter)
            .await
            .unwrap();

        assert!(
            result.is_none(),
            "should be no-op when context is nearly empty"
        );
    }
}