minimemory 3.0.0

Embedded vector database library for Rust - like SQLite for vectors
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
//! # Memory Traits - Domain-Agnostic Memory System
//!
//! Este modulo define los traits core que permiten crear sistemas de memoria
//! para cualquier dominio: desarrollo de software, chatbots, ventas, soporte, etc.
//!
//! ## Arquitectura
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                    NIVEL 4: UNIVERSAL                       │
//! │  Conocimiento siempre aplicable en cualquier contexto       │
//! ├─────────────────────────────────────────────────────────────┤
//! │                    NIVEL 3: DOMINIO                         │
//! │  Conocimiento especifico de un area (web, soporte, etc.)    │
//! ├─────────────────────────────────────────────────────────────┤
//! │                    NIVEL 2: CONTEXTO                        │
//! │  Conocimiento de un contexto especifico (lenguaje, tono)    │
//! ├─────────────────────────────────────────────────────────────┤
//! │                    NIVEL 1: INSTANCIA                       │
//! │  Conocimiento de una instancia particular (proyecto, user)  │
//! └─────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Ejemplo: Agente de Software
//!
//! ```rust,ignore
//! use minimemory::memory_traits::*;
//! use minimemory::memory_traits::presets::SoftwareDevelopment;
//!
//! let memory = GenericMemory::<SoftwareDevelopment>::new(384)?;
//! memory.set_instance("my-project", "rust", "WebBackend");
//! memory.learn("auth", embedding, "JWT implementation", "success")?;
//! ```
//!
//! ## Ejemplo: Chatbot de Telegram
//!
//! ```rust,ignore
//! use minimemory::memory_traits::*;
//! use minimemory::memory_traits::presets::Conversational;
//!
//! let memory = GenericMemory::<Conversational>::new(384)?;
//! memory.set_instance("@user123", "casual", "Support");
//! memory.learn("greeting", embedding, "User prefers informal tone", "positive")?;
//! ```

use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::error::Result;
use crate::types::{Metadata, VectorId};
use crate::Config;
use crate::Filter;
use crate::VectorDB;

// ============================================================================
// Core Traits
// ============================================================================

/// Clasificador de dominios.
///
/// Determina a que dominio pertenece un contenido dado.
pub trait DomainClassifier: Send + Sync + Default {
    /// Nombre del tipo de dominio (para metadata).
    fn domain_type_name(&self) -> &'static str;

    /// Lista de dominios disponibles.
    fn available_domains(&self) -> Vec<&'static str>;

    /// Clasifica contenido en un dominio.
    fn classify(&self, content: &str) -> String;

    /// Determina si dos dominios estan relacionados.
    fn related(&self, domain1: &str, domain2: &str) -> bool;

    /// Score de relacion entre dominios (0.0 - 1.0).
    fn relatedness_score(&self, domain1: &str, domain2: &str) -> f32 {
        if domain1 == domain2 {
            1.0
        } else if self.related(domain1, domain2) {
            0.7
        } else {
            0.3
        }
    }
}

/// Extractor de conceptos abstractos.
///
/// Identifica patrones y principios transferibles del contenido.
pub trait ConceptExtractor: Send + Sync + Default {
    /// Extrae conceptos abstractos del contenido.
    fn extract(&self, description: &str, content: &str) -> Vec<String>;

    /// Determina si un concepto es universal (aplica a cualquier contexto).
    fn is_universal(&self, concept: &str) -> bool;

    /// Lista de conceptos universales predefinidos.
    fn universal_concepts(&self) -> Vec<&'static str>;
}

/// Evaluador de compatibilidad de contexto.
///
/// Determina que tan compatible es el conocimiento entre contextos.
pub trait ContextMatcher: Send + Sync + Default {
    /// Nombre del tipo de contexto (para metadata).
    fn context_type_name(&self) -> &'static str;

    /// Lista de contextos disponibles.
    fn available_contexts(&self) -> Vec<&'static str>;

    /// Score de compatibilidad entre contextos (0.0 - 1.0).
    fn compatibility(&self, context1: &str, context2: &str) -> f32;

    /// Agrupa contextos en familias relacionadas.
    fn context_family(&self, context: &str) -> Option<&'static str>;
}

/// Configuracion de un preset de dominio.
///
/// Combina los cuatro traits en una configuracion cohesiva.
pub trait DomainPreset: Send + Sync + 'static {
    type Domain: DomainClassifier;
    type Concepts: ConceptExtractor;
    type Context: ContextMatcher;
    type Priority: PriorityCalculator;

    /// Nombre del preset.
    fn name() -> &'static str;

    /// Descripcion del preset.
    fn description() -> &'static str;

    /// Configuracion de decay por defecto para este dominio.
    fn default_decay() -> DecayConfig {
        DecayConfig::default()
    }

    /// Pesos de prioridad por defecto para este dominio.
    fn default_weights() -> PriorityWeights {
        PriorityWeights::default()
    }

    /// Crea instancias de los componentes.
    fn create() -> (Self::Domain, Self::Concepts, Self::Context, Self::Priority) {
        (
            Self::Domain::default(),
            Self::Concepts::default(),
            Self::Context::default(),
            Self::Priority::default(),
        )
    }
}

// ============================================================================
// Transfer Level (Generico)
// ============================================================================

/// Nivel de transferibilidad del conocimiento.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(u8)]
#[derive(Default)]
pub enum TransferLevel {
    /// Solo aplica a esta instancia especifica.
    #[default]
    Instance = 1,
    /// Aplica al mismo contexto (lenguaje, tono, etc.).
    Context = 2,
    /// Aplica al mismo dominio (web, soporte, etc.).
    Domain = 3,
    /// Conocimiento universal, siempre aplicable.
    Universal = 4,
}

impl TransferLevel {
    /// Convierte a string para metadata.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Instance => "instance",
            Self::Context => "context",
            Self::Domain => "domain",
            Self::Universal => "universal",
        }
    }

    /// Crea desde string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "instance" | "project" | "specific" => Some(Self::Instance),
            "context" | "stack" | "language" => Some(Self::Context),
            "domain" | "area" => Some(Self::Domain),
            "universal" | "global" | "always" => Some(Self::Universal),
            _ => None,
        }
    }

    /// Score de transferibilidad (0.25 - 1.0).
    pub fn transfer_score(&self) -> f32 {
        match self {
            Self::Instance => 0.25,
            Self::Context => 0.5,
            Self::Domain => 0.75,
            Self::Universal => 1.0,
        }
    }

    /// Determina si este nivel es transferible al nivel objetivo.
    pub fn transfers_to(&self, target: TransferLevel) -> bool {
        *self >= target
    }
}

// ============================================================================
// Priority System (Hibrido)
// ============================================================================

/// Nivel de prioridad base (manual).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(u8)]
#[derive(Default)]
pub enum Priority {
    /// Prioridad minima, puede ser olvidado.
    Low = 1,
    /// Prioridad normal, comportamiento por defecto.
    #[default]
    Normal = 2,
    /// Prioridad alta, preferido en recall.
    High = 3,
    /// Prioridad critica, siempre incluido.
    Critical = 4,
}

impl Priority {
    /// Convierte a string para metadata.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Normal => "normal",
            Self::High => "high",
            Self::Critical => "critical",
        }
    }

    /// Crea desde string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "low" | "minor" | "trivial" => Some(Self::Low),
            "normal" | "medium" | "default" => Some(Self::Normal),
            "high" | "important" | "major" => Some(Self::High),
            "critical" | "urgent" | "essential" | "security" => Some(Self::Critical),
            _ => None,
        }
    }

    /// Score base de prioridad (0.25 - 1.0).
    pub fn base_score(&self) -> f32 {
        match self {
            Self::Low => 0.25,
            Self::Normal => 0.5,
            Self::High => 0.75,
            Self::Critical => 1.0,
        }
    }
}

/// Estadisticas de uso de una memoria.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UsageStats {
    /// Numero de veces que ha sido accedida.
    pub access_count: u32,
    /// Timestamp del ultimo acceso.
    pub last_accessed: i64,
    /// Timestamp de creacion.
    pub created_at: i64,
    /// Veces que fue util (feedback positivo).
    pub useful_count: u32,
}

impl UsageStats {
    /// Crea nuevas estadisticas con timestamp actual.
    pub fn new() -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        Self {
            access_count: 0,
            last_accessed: now,
            created_at: now,
            useful_count: 0,
        }
    }

    /// Registra un acceso.
    pub fn record_access(&mut self) {
        self.access_count += 1;
        self.last_accessed = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
    }

    /// Registra que fue util.
    pub fn record_useful(&mut self) {
        self.useful_count += 1;
    }

    /// Calcula score por frecuencia de uso (0.0 - 1.0).
    /// Usa logaritmo para evitar que memorias muy usadas dominen.
    pub fn frequency_score(&self) -> f32 {
        if self.access_count == 0 {
            0.0
        } else {
            // log2(access + 1) / 10, capped at 1.0
            ((self.access_count as f32 + 1.0).log2() / 10.0).min(1.0)
        }
    }

    /// Calcula score de utilidad (0.0 - 1.0).
    pub fn usefulness_score(&self) -> f32 {
        if self.access_count == 0 {
            0.5 // Neutral si nunca fue accedida
        } else {
            self.useful_count as f32 / self.access_count as f32
        }
    }

    /// Edad en segundos.
    pub fn age_seconds(&self) -> i64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        now - self.created_at
    }

    /// Segundos desde ultimo acceso.
    pub fn staleness_seconds(&self) -> i64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        now - self.last_accessed
    }

    /// Guarda los campos de UsageStats en metadata para persistencia.
    pub fn save_to_metadata(&self, meta: &mut Metadata) {
        meta.insert("_access_count", self.access_count as i64);
        meta.insert("_last_accessed", self.last_accessed);
        meta.insert("_created_at", self.created_at);
        meta.insert("_useful_count", self.useful_count as i64);
    }

    /// Restaura UsageStats desde metadata. Retorna Default si faltan campos.
    pub fn load_from_metadata(meta: &Metadata) -> Self {
        let access_count = meta
            .get("_access_count")
            .and_then(|v| v.as_i64())
            .unwrap_or(0) as u32;
        let last_accessed = meta
            .get("_last_accessed")
            .and_then(|v| v.as_i64())
            .unwrap_or(0);
        let created_at = meta
            .get("_created_at")
            .and_then(|v| v.as_i64())
            .unwrap_or(0);
        let useful_count = meta
            .get("_useful_count")
            .and_then(|v| v.as_i64())
            .unwrap_or(0) as u32;

        Self {
            access_count,
            last_accessed,
            created_at,
            useful_count,
        }
    }
}

/// Configuracion de decay temporal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DecayConfig {
    /// Activar decay temporal.
    pub enabled: bool,
    /// Vida media en segundos (tiempo para perder 50% de prioridad).
    pub half_life_seconds: i64,
    /// Piso minimo de decay (nunca baja de este valor).
    pub min_decay: f32,
    /// Excepciones: niveles que no decaen.
    pub immune_priorities: Vec<Priority>,
}

impl Default for DecayConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            half_life_seconds: 30 * 24 * 60 * 60, // 30 dias
            min_decay: 0.1,
            immune_priorities: vec![Priority::Critical],
        }
    }
}

impl DecayConfig {
    /// Sin decay (todo persiste igual).
    pub fn no_decay() -> Self {
        Self {
            enabled: false,
            ..Default::default()
        }
    }

    /// Decay rapido (1 semana).
    pub fn fast() -> Self {
        Self {
            enabled: true,
            half_life_seconds: 7 * 24 * 60 * 60,
            min_decay: 0.2,
            immune_priorities: vec![Priority::Critical, Priority::High],
        }
    }

    /// Decay lento (90 dias).
    pub fn slow() -> Self {
        Self {
            enabled: true,
            half_life_seconds: 90 * 24 * 60 * 60,
            min_decay: 0.05,
            immune_priorities: vec![Priority::Critical],
        }
    }

    /// Calcula factor de decay basado en edad.
    pub fn calculate_decay(&self, age_seconds: i64, priority: Priority) -> f32 {
        if !self.enabled || self.immune_priorities.contains(&priority) {
            return 1.0;
        }

        // Exponential decay: 0.5^(age / half_life)
        let decay = 0.5_f32.powf(age_seconds as f32 / self.half_life_seconds as f32);
        decay.max(self.min_decay)
    }
}

/// Calculador de prioridad automatica basado en contenido.
pub trait PriorityCalculator: Send + Sync + Default {
    /// Calcula prioridad automatica basada en contenido.
    fn calculate(&self, description: &str, content: &str, outcome: &str) -> Priority;

    /// Keywords que indican prioridad critica.
    fn critical_keywords(&self) -> Vec<&'static str>;

    /// Keywords que indican prioridad alta.
    fn high_keywords(&self) -> Vec<&'static str>;

    /// Keywords que indican prioridad baja.
    fn low_keywords(&self) -> Vec<&'static str>;
}

/// Pesos para combinar factores de prioridad.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriorityWeights {
    /// Peso de prioridad manual/automatica.
    pub base_priority: f32,
    /// Peso de frecuencia de uso.
    pub frequency: f32,
    /// Peso de utilidad (feedback).
    pub usefulness: f32,
    /// Peso de recencia (inverso de staleness).
    pub recency: f32,
}

impl Default for PriorityWeights {
    fn default() -> Self {
        Self {
            base_priority: 0.4,
            frequency: 0.2,
            usefulness: 0.25,
            recency: 0.15,
        }
    }
}

impl PriorityWeights {
    /// Prioriza la prioridad manual.
    pub fn manual_focused() -> Self {
        Self {
            base_priority: 0.6,
            frequency: 0.15,
            usefulness: 0.15,
            recency: 0.1,
        }
    }

    /// Prioriza el uso frecuente.
    pub fn usage_focused() -> Self {
        Self {
            base_priority: 0.2,
            frequency: 0.4,
            usefulness: 0.25,
            recency: 0.15,
        }
    }

    /// Prioriza la recencia.
    pub fn recency_focused() -> Self {
        Self {
            base_priority: 0.25,
            frequency: 0.15,
            usefulness: 0.2,
            recency: 0.4,
        }
    }

    /// Calcula score combinado de prioridad.
    pub fn calculate_score(&self, base: f32, frequency: f32, usefulness: f32, recency: f32) -> f32 {
        (self.base_priority * base
            + self.frequency * frequency
            + self.usefulness * usefulness
            + self.recency * recency)
            .clamp(0.0, 1.0)
    }
}

/// Score de recencia basado en staleness.
pub fn recency_score(staleness_seconds: i64) -> f32 {
    // Score exponencial: 1.0 si es reciente, decae con el tiempo
    // 1 hora -> 0.95, 1 dia -> 0.75, 1 semana -> 0.5, 1 mes -> 0.25
    let hours = staleness_seconds as f32 / 3600.0;
    (-hours / 168.0).exp() // 168 horas = 1 semana como punto medio
}

// ============================================================================
// Instance Context (Generico)
// ============================================================================

/// Contexto de la instancia actual.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct InstanceContext {
    /// Identificador de la instancia (proyecto, usuario, sesion).
    pub instance_id: String,
    /// Contexto actual (lenguaje, tono, tipo).
    pub context: String,
    /// Dominio actual.
    pub domain: String,
    /// Metadata adicional especifica del dominio.
    pub extra: HashMap<String, String>,
}

impl InstanceContext {
    /// Crea un nuevo contexto de instancia.
    pub fn new(instance_id: impl Into<String>) -> Self {
        Self {
            instance_id: instance_id.into(),
            ..Default::default()
        }
    }

    /// Establece el contexto.
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context = context.into();
        self
    }

    /// Establece el dominio.
    pub fn with_domain(mut self, domain: impl Into<String>) -> Self {
        self.domain = domain.into();
        self
    }

    /// Agrega metadata extra.
    pub fn with_extra(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.insert(key.into(), value.into());
        self
    }

    /// Creates an InstanceContext from a ProjectContext.
    pub fn from_project_context(ctx: &ProjectContext) -> Self {
        let mut ic = Self::new(&ctx.name)
            .with_context(&ctx.language)
            .with_domain(ctx.domain.as_str());

        for (i, fw) in ctx.frameworks.iter().enumerate() {
            ic.extra
                .insert(format!("framework_{}", i), fw.clone());
        }
        for (i, pat) in ctx.patterns.iter().enumerate() {
            ic.extra
                .insert(format!("pattern_{}", i), pat.clone());
        }
        for (i, tag) in ctx.tags.iter().enumerate() {
            ic.extra.insert(format!("tag_{}", i), tag.clone());
        }

        ic
    }
}

// ============================================================================
// Knowledge Domain
// ============================================================================

/// Dominio del conocimiento.
///
/// Categoriza el tipo de aplicacion o sistema.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum KnowledgeDomain {
    /// APIs, servicios web, microservicios
    WebBackend,
    /// Interfaces de usuario web (React, Vue, etc.)
    WebFrontend,
    /// Aplicaciones de linea de comandos
    CLI,
    /// Analisis de datos, ML, visualizacion
    DataScience,
    /// Programacion de sistemas, bajo nivel
    Systems,
    /// Apps moviles (iOS, Android, Flutter)
    Mobile,
    /// DevOps, CI/CD, infraestructura
    DevOps,
    /// Seguridad, criptografia, pentesting
    Security,
    /// Bases de datos, almacenamiento
    Database,
    /// Juegos y graficos
    GameDev,
    /// IoT y sistemas embebidos
    Embedded,
    /// Conocimiento general que aplica a todo
    General,
}

impl KnowledgeDomain {
    pub fn as_str(&self) -> &'static str {
        match self {
            KnowledgeDomain::WebBackend => "web_backend",
            KnowledgeDomain::WebFrontend => "web_frontend",
            KnowledgeDomain::CLI => "cli",
            KnowledgeDomain::DataScience => "data_science",
            KnowledgeDomain::Systems => "systems",
            KnowledgeDomain::Mobile => "mobile",
            KnowledgeDomain::DevOps => "devops",
            KnowledgeDomain::Security => "security",
            KnowledgeDomain::Database => "database",
            KnowledgeDomain::GameDev => "gamedev",
            KnowledgeDomain::Embedded => "embedded",
            KnowledgeDomain::General => "general",
        }
    }

    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "web_backend" | "webbackend" | "backend" => KnowledgeDomain::WebBackend,
            "web_frontend" | "webfrontend" | "frontend" => KnowledgeDomain::WebFrontend,
            "cli" | "command_line" => KnowledgeDomain::CLI,
            "data_science" | "datascience" | "data" | "ml" => KnowledgeDomain::DataScience,
            "systems" | "system" => KnowledgeDomain::Systems,
            "mobile" | "ios" | "android" => KnowledgeDomain::Mobile,
            "devops" | "ops" | "infra" => KnowledgeDomain::DevOps,
            "security" | "sec" => KnowledgeDomain::Security,
            "database" | "db" => KnowledgeDomain::Database,
            "gamedev" | "game" | "games" => KnowledgeDomain::GameDev,
            "embedded" | "iot" => KnowledgeDomain::Embedded,
            _ => KnowledgeDomain::General,
        }
    }

    /// Dominios relacionados que pueden compartir conocimiento.
    pub fn related_domains(&self) -> Vec<KnowledgeDomain> {
        match self {
            KnowledgeDomain::WebBackend => vec![
                KnowledgeDomain::Database,
                KnowledgeDomain::Security,
                KnowledgeDomain::DevOps,
            ],
            KnowledgeDomain::WebFrontend => {
                vec![KnowledgeDomain::Mobile, KnowledgeDomain::WebBackend]
            }
            KnowledgeDomain::CLI => vec![KnowledgeDomain::Systems, KnowledgeDomain::DevOps],
            KnowledgeDomain::DataScience => {
                vec![KnowledgeDomain::Database, KnowledgeDomain::Systems]
            }
            KnowledgeDomain::Systems => {
                vec![KnowledgeDomain::Embedded, KnowledgeDomain::Security]
            }
            KnowledgeDomain::Mobile => vec![KnowledgeDomain::WebFrontend],
            KnowledgeDomain::DevOps => {
                vec![KnowledgeDomain::Security, KnowledgeDomain::Systems]
            }
            KnowledgeDomain::Security => {
                vec![KnowledgeDomain::WebBackend, KnowledgeDomain::Systems]
            }
            KnowledgeDomain::Database => {
                vec![KnowledgeDomain::WebBackend, KnowledgeDomain::DataScience]
            }
            KnowledgeDomain::GameDev => {
                vec![KnowledgeDomain::Systems, KnowledgeDomain::WebFrontend]
            }
            KnowledgeDomain::Embedded => vec![KnowledgeDomain::Systems],
            KnowledgeDomain::General => vec![],
        }
    }
}

// ============================================================================
// Project Context
// ============================================================================

/// Contexto del proyecto actual.
///
/// Define las caracteristicas del proyecto para calcular transferibilidad.
/// Use `InstanceContext::from_project_context()` to convert to an InstanceContext.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectContext {
    /// Nombre del proyecto
    pub name: String,
    /// Lenguaje principal (e.g., "rust", "python", "typescript")
    pub language: String,
    /// Dominio de la aplicacion
    pub domain: KnowledgeDomain,
    /// Frameworks y librerias principales
    pub frameworks: Vec<String>,
    /// Patrones arquitectonicos usados (REST, GraphQL, event-driven, etc.)
    pub patterns: Vec<String>,
    /// Tags adicionales para matching
    pub tags: Vec<String>,
}

impl ProjectContext {
    pub fn new(
        name: impl Into<String>,
        language: impl Into<String>,
        domain: KnowledgeDomain,
    ) -> Self {
        Self {
            name: name.into(),
            language: language.into(),
            domain,
            frameworks: Vec::new(),
            patterns: Vec::new(),
            tags: Vec::new(),
        }
    }

    pub fn with_frameworks(mut self, frameworks: Vec<String>) -> Self {
        self.frameworks = frameworks;
        self
    }

    pub fn with_patterns(mut self, patterns: Vec<String>) -> Self {
        self.patterns = patterns;
        self
    }

    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }
}

// ============================================================================
// Language Compatibility
// ============================================================================

/// Calcula compatibilidad entre lenguajes de programacion.
pub struct LanguageCompatibility;

impl LanguageCompatibility {
    /// Grupos de lenguajes similares
    const LANGUAGE_GROUPS: &'static [&'static [&'static str]] = &[
        &["typescript", "javascript", "js", "ts"],
        &["python", "ruby", "perl"],
        &["rust", "go", "c", "cpp", "c++", "zig"],
        &["java", "kotlin", "scala", "groovy"],
        &["csharp", "c#", "fsharp", "f#"],
        &["swift", "objective-c", "objc"],
        &["haskell", "ocaml", "elm", "purescript"],
        &["clojure", "lisp", "scheme", "racket"],
        &["php", "hack"],
        &["elixir", "erlang"],
    ];

    /// Calcula compatibilidad entre dos lenguajes (0.0 - 1.0)
    pub fn compatibility(lang_a: &str, lang_b: &str) -> f32 {
        let a = lang_a.to_lowercase();
        let b = lang_b.to_lowercase();

        if a == b {
            return 1.0;
        }

        for group in Self::LANGUAGE_GROUPS {
            let a_in = group.contains(&a.as_str());
            let b_in = group.contains(&b.as_str());
            if a_in && b_in {
                return 0.7;
            }
        }

        0.2
    }

    /// Describe la adaptacion necesaria entre lenguajes
    pub fn adaptation_description(from: &str, to: &str) -> Option<String> {
        let from_lower = from.to_lowercase();
        let to_lower = to.to_lowercase();

        if from_lower == to_lower {
            return None;
        }

        let desc = match (from_lower.as_str(), to_lower.as_str()) {
            ("python", "rust") => {
                "Cambiar a tipado estatico, usar Result para errores, ownership"
            }
            ("javascript", "typescript") => "Anadir tipos, interfaces",
            ("typescript", "javascript") => "Remover tipos",
            ("java", "kotlin") => "Simplificar sintaxis, usar null-safety",
            ("python", "javascript") | ("javascript", "python") => {
                "Adaptar sintaxis y async model"
            }
            ("rust", "go") => "Simplificar ownership, usar goroutines",
            ("go", "rust") => "Anadir ownership, Result types, macros",
            _ => return Some(format!("Adaptar sintaxis de {} a {}", from, to)),
        };

        Some(desc.to_string())
    }
}

// ============================================================================
// Memory Recall (Generico)
// ============================================================================

/// Resultado de recall con informacion de transferibilidad y prioridad.
#[derive(Debug, Clone)]
pub struct GenericRecall {
    /// ID del recuerdo.
    pub id: VectorId,
    /// Score de relevancia semantica (0.0 - 1.0).
    pub relevance: f32,
    /// Nivel de transferibilidad.
    pub transfer_level: TransferLevel,
    /// Prioridad base del recuerdo.
    pub priority: Priority,
    /// Score de prioridad hibrido (incluye uso, recencia, decay).
    pub priority_score: f32,
    /// Score combinado final.
    pub combined_score: f32,
    /// Conceptos abstractos asociados.
    pub concepts: Vec<String>,
    /// Estadisticas de uso.
    pub usage: UsageStats,
    /// Metadata del recuerdo.
    pub metadata: Metadata,
}

// ============================================================================
// Generic Memory System
// ============================================================================

/// Sistema de memoria generico basado en traits.
pub struct GenericMemory<P: DomainPreset> {
    /// Base de datos vectorial.
    db: VectorDB,
    /// Clasificador de dominios.
    domain_classifier: P::Domain,
    /// Extractor de conceptos.
    concept_extractor: P::Concepts,
    /// Evaluador de contexto.
    context_matcher: P::Context,
    /// Calculador de prioridad.
    priority_calculator: P::Priority,
    /// Contexto actual.
    current_context: RwLock<Option<InstanceContext>>,
    /// Estadisticas de uso por ID.
    usage_stats: RwLock<HashMap<String, UsageStats>>,
    /// Configuracion de decay.
    decay_config: DecayConfig,
    /// Pesos de prioridad.
    priority_weights: PriorityWeights,
    /// Peso de relevancia vs transferibilidad vs prioridad.
    relevance_weight: f32,
    /// Peso de transferibilidad.
    transfer_weight: f32,
    /// Peso de prioridad.
    priority_weight: f32,
    /// Umbral minimo de transferibilidad.
    transfer_threshold: f32,
}

impl<P: DomainPreset> GenericMemory<P> {
    /// Crea una nueva memoria generica.
    pub fn new(dimensions: usize) -> Result<Self> {
        let config = Config::new(dimensions);
        let db = VectorDB::with_fulltext(config, vec!["content".into(), "description".into()])?;
        let (domain_classifier, concept_extractor, context_matcher, priority_calculator) =
            P::create();

        Ok(Self {
            db,
            domain_classifier,
            concept_extractor,
            context_matcher,
            priority_calculator,
            current_context: RwLock::new(None),
            usage_stats: RwLock::new(HashMap::new()),
            decay_config: P::default_decay(),
            priority_weights: P::default_weights(),
            relevance_weight: 0.4,
            transfer_weight: 0.3,
            priority_weight: 0.3,
            transfer_threshold: 0.3,
        })
    }

    /// Crea con configuracion personalizada.
    pub fn with_config(config: Config) -> Result<Self> {
        let db = VectorDB::with_fulltext(config, vec!["content".into(), "description".into()])?;
        let (domain_classifier, concept_extractor, context_matcher, priority_calculator) =
            P::create();

        Ok(Self {
            db,
            domain_classifier,
            concept_extractor,
            context_matcher,
            priority_calculator,
            current_context: RwLock::new(None),
            usage_stats: RwLock::new(HashMap::new()),
            decay_config: P::default_decay(),
            priority_weights: P::default_weights(),
            relevance_weight: 0.4,
            transfer_weight: 0.3,
            priority_weight: 0.3,
            transfer_threshold: 0.3,
        })
    }

    /// Crea desde un VectorDB existente.
    ///
    /// Util para wrapping: permite que un sistema externo (como AgentMemory)
    /// construya su propio VectorDB con configuracion personalizada y luego
    /// lo envuelva en GenericMemory para heredar prioridad, decay y usage stats.
    pub fn with_db(db: VectorDB) -> Self {
        let (domain_classifier, concept_extractor, context_matcher, priority_calculator) =
            P::create();

        Self {
            db,
            domain_classifier,
            concept_extractor,
            context_matcher,
            priority_calculator,
            current_context: RwLock::new(None),
            usage_stats: RwLock::new(HashMap::new()),
            decay_config: P::default_decay(),
            priority_weights: P::default_weights(),
            relevance_weight: 0.4,
            transfer_weight: 0.3,
            priority_weight: 0.3,
            transfer_threshold: 0.3,
        }
    }

    /// Acceso a la base de datos vectorial subyacente.
    pub fn db(&self) -> &VectorDB {
        &self.db
    }

    /// Establece la configuracion de decay.
    pub fn set_decay_config(&mut self, config: DecayConfig) {
        self.decay_config = config;
    }

    /// Establece los pesos de prioridad.
    pub fn set_priority_weights(&mut self, weights: PriorityWeights) {
        self.priority_weights = weights;
    }

    /// Establece los pesos del score final.
    /// Los tres pesos deben sumar 1.0.
    pub fn set_score_weights(&mut self, relevance: f32, transfer: f32, priority: f32) {
        let total = relevance + transfer + priority;
        self.relevance_weight = relevance / total;
        self.transfer_weight = transfer / total;
        self.priority_weight = priority / total;
    }

    /// Establece el umbral de transferibilidad.
    pub fn set_transfer_threshold(&mut self, threshold: f32) {
        self.transfer_threshold = threshold.clamp(0.0, 1.0);
    }

    /// Establece el contexto actual de la instancia.
    pub fn set_context(&self, context: InstanceContext) {
        *self.current_context.write() = Some(context);
    }

    /// Atajo para establecer contexto con parametros comunes.
    pub fn set_instance(
        &self,
        instance_id: impl Into<String>,
        context: impl Into<String>,
        domain: impl Into<String>,
    ) {
        self.set_context(
            InstanceContext::new(instance_id)
                .with_context(context)
                .with_domain(domain),
        );
    }

    /// Establece el contexto desde un ProjectContext.
    ///
    /// Converts the ProjectContext into an InstanceContext and sets it.
    pub fn set_project_context(&self, ctx: &ProjectContext) {
        self.set_context(InstanceContext::from_project_context(ctx));
    }

    /// Obtiene el contexto actual.
    pub fn current_context(&self) -> Option<InstanceContext> {
        self.current_context.read().clone()
    }

    /// Aprende nuevo conocimiento con prioridad automatica.
    pub fn learn(
        &self,
        id: &str,
        embedding: &[f32],
        content: &str,
        description: &str,
        outcome: &str,
    ) -> Result<VectorId> {
        // Calcular prioridad automatica
        let priority = self
            .priority_calculator
            .calculate(description, content, outcome);
        self.learn_with_priority(id, embedding, content, description, outcome, priority)
    }

    /// Aprende nuevo conocimiento con prioridad manual.
    pub fn learn_with_priority(
        &self,
        id: &str,
        embedding: &[f32],
        content: &str,
        description: &str,
        outcome: &str,
        priority: Priority,
    ) -> Result<VectorId> {
        let ctx = self.current_context.read().clone();

        // Extraer conceptos
        let concepts = self.concept_extractor.extract(description, content);

        // Inferir nivel de transferencia
        let transfer_level = self.infer_transfer_level(&concepts, content);

        // Crear estadisticas de uso
        let usage = UsageStats::new();
        self.usage_stats.write().insert(id.to_string(), usage.clone());

        // Construir metadata
        let mut meta = Metadata::new();
        meta.insert("content", content);
        meta.insert("description", description);
        meta.insert("outcome", outcome);
        meta.insert("transfer_level", transfer_level.as_str());
        meta.insert("priority", priority.as_str());
        meta.insert("concepts", concepts.join(","));
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        meta.insert("timestamp", timestamp);

        if let Some(ref ctx) = ctx {
            meta.insert("instance_id", ctx.instance_id.as_str());
            meta.insert("context", ctx.context.as_str());
            meta.insert("domain", ctx.domain.as_str());

            for (k, v) in &ctx.extra {
                meta.insert(k.as_str(), v.as_str());
            }
        }

        // Clasificar dominio automaticamente si no esta establecido
        if ctx.as_ref().is_none_or(|c| c.domain.is_empty()) {
            let domain = self.domain_classifier.classify(content);
            meta.insert("domain", domain.as_str());
        }

        // Persistir UsageStats en metadata
        usage.save_to_metadata(&mut meta);

        self.db.insert(id, embedding, Some(meta))?;
        Ok(id.to_string())
    }

    /// Aprende con metadata pre-construida y prioridad automatica.
    ///
    /// A diferencia de `learn()`, acepta metadata ya poblada con campos
    /// especificos del dominio. Enriquece la metadata con campos del sistema
    /// (priority, transfer_level, concepts, usage stats, timestamp, context).
    ///
    /// # Arguments
    /// * `id` - ID del documento
    /// * `embedding` - Vector de embedding
    /// * `meta` - Metadata pre-construida con campos del dominio
    /// * `content_for_analysis` - Texto para analisis de conceptos y dominio
    pub fn learn_raw(
        &self,
        id: &str,
        embedding: &[f32],
        meta: Metadata,
        content_for_analysis: &str,
    ) -> Result<VectorId> {
        let description = meta
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let outcome = meta.get("outcome").and_then(|v| v.as_str()).unwrap_or("");
        let priority = self
            .priority_calculator
            .calculate(description, content_for_analysis, outcome);
        self.learn_raw_with_priority(id, embedding, meta, content_for_analysis, priority)
    }

    /// Aprende con metadata pre-construida y prioridad manual.
    ///
    /// Igual que `learn_raw()` pero con prioridad explicita.
    pub fn learn_raw_with_priority(
        &self,
        id: &str,
        embedding: &[f32],
        mut meta: Metadata,
        content_for_analysis: &str,
        priority: Priority,
    ) -> Result<VectorId> {
        let ctx = self.current_context.read().clone();

        // Extraer conceptos
        let description = meta
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let concepts = self
            .concept_extractor
            .extract(description, content_for_analysis);

        // Inferir nivel de transferencia
        let transfer_level = self.infer_transfer_level(&concepts, content_for_analysis);

        // Crear estadisticas de uso
        let usage = UsageStats::new();
        self.usage_stats
            .write()
            .insert(id.to_string(), usage.clone());

        // Agregar campos del sistema (solo si no estan ya presentes)
        if meta.get("transfer_level").is_none() {
            meta.insert("transfer_level", transfer_level.as_str());
        }
        if meta.get("priority").is_none() {
            meta.insert("priority", priority.as_str());
        }
        if meta.get("concepts").is_none() {
            meta.insert("concepts", concepts.join(","));
        }
        if meta.get("timestamp").is_none() {
            let timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs() as i64;
            meta.insert("timestamp", timestamp);
        }

        // Agregar contexto de instancia
        if let Some(ref ctx) = ctx {
            if meta.get("instance_id").is_none() && !ctx.instance_id.is_empty() {
                meta.insert("instance_id", ctx.instance_id.as_str());
            }
            if meta.get("context").is_none() && !ctx.context.is_empty() {
                meta.insert("context", ctx.context.as_str());
            }
            if meta.get("domain").is_none() && !ctx.domain.is_empty() {
                meta.insert("domain", ctx.domain.as_str());
            }
        }

        // Clasificar dominio automaticamente si no esta establecido
        let has_domain = meta
            .get("domain")
            .and_then(|v| v.as_str())
            .is_some_and(|s| !s.is_empty());
        if !has_domain {
            let domain = self.domain_classifier.classify(content_for_analysis);
            meta.insert("domain", domain.as_str());
        }

        // Persistir UsageStats en metadata
        usage.save_to_metadata(&mut meta);

        self.db.insert(id, embedding, Some(meta))?;
        Ok(id.to_string())
    }

    /// Registra feedback positivo (la memoria fue util).
    pub fn mark_useful(&self, id: &str) {
        let mut stats_map = self.usage_stats.write();
        let stats = if let Some(s) = stats_map.get_mut(id) {
            s.record_useful();
            s.clone()
        } else {
            // Load from metadata if not in cache
            if let Ok(Some((_, Some(meta)))) = self.db.get(id) {
                let mut s = UsageStats::load_from_metadata(&meta);
                s.record_useful();
                stats_map.insert(id.to_string(), s.clone());
                s
            } else {
                return;
            }
        };
        drop(stats_map);

        // Persist updated stats to metadata
        if let Ok(Some((vec_opt, meta_opt))) = self.db.get(id) {
            if let (Some(vec), Some(mut meta)) = (vec_opt, meta_opt) {
                stats.save_to_metadata(&mut meta);
                let _ = self.db.update(id, &vec, Some(meta));
            }
        }
    }

    /// Actualiza la prioridad de una memoria existente.
    pub fn update_priority(&self, id: &str, priority: Priority) -> Result<()> {
        // Get current vector and update metadata
        if let Some((vec_opt, meta_opt)) = self.db.get(id)? {
            if let (Some(vec), Some(mut meta)) = (vec_opt, meta_opt) {
                meta.insert("priority", priority.as_str());
                self.db.update(id, &vec, Some(meta))?;
            }
        }
        Ok(())
    }

    /// Inferir nivel de transferencia basado en conceptos y contenido.
    fn infer_transfer_level(&self, concepts: &[String], content: &str) -> TransferLevel {
        // Si tiene conceptos universales, es universal
        let universal_count = concepts
            .iter()
            .filter(|c| self.concept_extractor.is_universal(c))
            .count();

        if universal_count >= 2 {
            return TransferLevel::Universal;
        }

        // Analizar contenido para determinar especificidad
        let content_lower = content.to_lowercase();

        // Patrones que indican conocimiento especifico de instancia
        let instance_patterns = [
            "this project",
            "este proyecto",
            "specific to",
            "only here",
            "custom",
            "our",
            "nuestra",
        ];

        if instance_patterns.iter().any(|p| content_lower.contains(p)) {
            return TransferLevel::Instance;
        }

        // Por defecto, nivel de contexto
        if universal_count >= 1 {
            TransferLevel::Domain
        } else {
            TransferLevel::Context
        }
    }

    /// Recall con filtrado por transferibilidad y prioridad hibrida.
    pub fn recall(&self, query_embedding: &[f32], k: usize) -> Result<Vec<GenericRecall>> {
        let ctx = self.current_context.read().clone();

        // Buscar en la base de datos
        let results = self.db.search(query_embedding, k * 3)?;

        let mut recalls: Vec<GenericRecall> = results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                let id = r.id.clone();

                // Obtener nivel de transferencia
                let transfer_level = meta
                    .get("transfer_level")
                    .and_then(|v| v.as_str())
                    .and_then(TransferLevel::from_str)
                    .unwrap_or(TransferLevel::Instance);

                // Calcular score de transferibilidad
                let transfer_score = self.calculate_transfer_score(&ctx, &meta, transfer_level);

                if transfer_score < self.transfer_threshold {
                    return None;
                }

                // Obtener prioridad base
                let priority = meta
                    .get("priority")
                    .and_then(|v| v.as_str())
                    .and_then(Priority::from_str)
                    .unwrap_or(Priority::Normal);

                // Cargar estadisticas de uso desde metadata (persistentes)
                let usage = {
                    let cached = self.usage_stats.read().get(&id).cloned();
                    cached.unwrap_or_else(|| UsageStats::load_from_metadata(&meta))
                };

                // Calcular score de prioridad hibrido
                let priority_score = self.calculate_priority_score(&usage, priority);

                // Score combinado final: relevancia + transferibilidad + prioridad
                let relevance = 1.0 - r.distance; // Convertir distancia a similitud
                let combined_score = relevance * self.relevance_weight
                    + transfer_score * self.transfer_weight
                    + priority_score * self.priority_weight;

                // Extraer conceptos
                let concepts = meta
                    .get("concepts")
                    .and_then(|v| v.as_str())
                    .map(|s: &str| s.split(',').map(String::from).collect())
                    .unwrap_or_default();

                Some(GenericRecall {
                    id,
                    relevance,
                    transfer_level,
                    priority,
                    priority_score,
                    combined_score,
                    concepts,
                    usage,
                    metadata: meta,
                })
            })
            .collect();

        // Registrar acceso para todas las memorias retornadas y persistir en metadata
        {
            let mut stats = self.usage_stats.write();
            for recall in &recalls {
                let entry = stats
                    .entry(recall.id.clone())
                    .or_insert_with(|| UsageStats::load_from_metadata(&recall.metadata));
                entry.record_access();

                // Persistir stats actualizados en metadata via db.update
                if let Ok(Some((vec_opt, meta_opt))) = self.db.get(&recall.id) {
                    if let (Some(vec), Some(mut meta)) = (vec_opt, meta_opt) {
                        entry.save_to_metadata(&mut meta);
                        let _ = self.db.update(&recall.id, &vec, Some(meta));
                    }
                }
            }
        }

        // Ordenar por score combinado
        recalls.sort_by(|a, b| b.combined_score.partial_cmp(&a.combined_score).unwrap());
        recalls.truncate(k);

        Ok(recalls)
    }

    /// Calcula el score de prioridad hibrido.
    fn calculate_priority_score(&self, usage: &UsageStats, priority: Priority) -> f32 {
        // Score base de prioridad
        let base = priority.base_score();

        // Score de frecuencia
        let frequency = usage.frequency_score();

        // Score de utilidad
        let usefulness = usage.usefulness_score();

        // Score de recencia
        let recency = recency_score(usage.staleness_seconds());

        // Combinar con pesos
        let raw_score = self
            .priority_weights
            .calculate_score(base, frequency, usefulness, recency);

        // Aplicar decay temporal
        let age = usage.age_seconds();
        let decay = self.decay_config.calculate_decay(age, priority);

        raw_score * decay
    }

    /// Calcula el score de transferibilidad para un recuerdo.
    fn calculate_transfer_score(
        &self,
        current_ctx: &Option<InstanceContext>,
        meta: &Metadata,
        level: TransferLevel,
    ) -> f32 {
        // Universal siempre tiene score maximo
        if level == TransferLevel::Universal {
            return 1.0;
        }

        let Some(ctx) = current_ctx else {
            return level.transfer_score();
        };

        // Obtener valores del recuerdo
        let stored_instance = meta
            .get("instance_id")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let stored_context = meta.get("context").and_then(|v| v.as_str()).unwrap_or("");
        let stored_domain = meta.get("domain").and_then(|v| v.as_str()).unwrap_or("");

        // Calcular compatibilidad
        let instance_match = if ctx.instance_id == stored_instance {
            1.0
        } else {
            0.0
        };
        // Use LanguageCompatibility for richer language matching (handles language families),
        // falling back to the context_matcher for non-language contexts
        let context_compat = if !ctx.context.is_empty() && !stored_context.is_empty() {
            // Take the better score between LanguageCompatibility and the preset matcher
            let lang_compat = LanguageCompatibility::compatibility(&ctx.context, stored_context);
            let matcher_compat = self.context_matcher.compatibility(&ctx.context, stored_context);
            lang_compat.max(matcher_compat)
        } else {
            self.context_matcher
                .compatibility(&ctx.context, stored_context)
        };
        // Use KnowledgeDomain relationship awareness for richer domain matching
        let domain_compat = if !ctx.domain.is_empty() && !stored_domain.is_empty() {
            let current_kd = KnowledgeDomain::from_str(&ctx.domain);
            let stored_kd = KnowledgeDomain::from_str(stored_domain);
            if current_kd == stored_kd {
                1.0
            } else if current_kd.related_domains().contains(&stored_kd) {
                0.7
            } else {
                self.domain_classifier
                    .relatedness_score(&ctx.domain, stored_domain)
            }
        } else {
            self.domain_classifier
                .relatedness_score(&ctx.domain, stored_domain)
        };

        // Ponderar segun nivel
        match level {
            TransferLevel::Instance => {
                instance_match * 0.6 + context_compat * 0.2 + domain_compat * 0.2
            }
            TransferLevel::Context => context_compat * 0.5 + domain_compat * 0.3 + 0.2,
            TransferLevel::Domain => domain_compat * 0.6 + 0.4,
            TransferLevel::Universal => 1.0,
        }
    }

    /// Helper para crear GenericRecall con todos los campos.
    fn make_recall(&self, id: String, distance: f32, meta: Metadata) -> GenericRecall {
        let transfer_level = meta
            .get("transfer_level")
            .and_then(|v| v.as_str())
            .and_then(TransferLevel::from_str)
            .unwrap_or(TransferLevel::Instance);

        let priority = meta
            .get("priority")
            .and_then(|v| v.as_str())
            .and_then(Priority::from_str)
            .unwrap_or(Priority::Normal);

        let usage = self
            .usage_stats
            .read()
            .get(&id)
            .cloned()
            .unwrap_or_default();
        let priority_score = self.calculate_priority_score(&usage, priority);
        let relevance = 1.0 - distance;

        let concepts = meta
            .get("concepts")
            .and_then(|v| v.as_str())
            .map(|s: &str| s.split(',').map(String::from).collect())
            .unwrap_or_default();

        GenericRecall {
            id,
            relevance,
            transfer_level,
            priority,
            priority_score,
            combined_score: relevance, // Simple score for filtered queries
            concepts,
            usage,
            metadata: meta,
        }
    }

    /// Recall solo de conocimiento universal.
    pub fn recall_universal(
        &self,
        query_embedding: &[f32],
        k: usize,
    ) -> Result<Vec<GenericRecall>> {
        let results = self.db.search_with_filter(
            query_embedding,
            k,
            Filter::eq("transfer_level", "universal"),
        )?;

        Ok(results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                Some(self.make_recall(r.id, r.distance, meta))
            })
            .collect())
    }

    /// Recall en el mismo dominio.
    pub fn recall_same_domain(
        &self,
        query_embedding: &[f32],
        k: usize,
    ) -> Result<Vec<GenericRecall>> {
        let ctx = self.current_context.read().clone();
        let domain = ctx.map(|c| c.domain).unwrap_or_default();

        if domain.is_empty() {
            return self.recall(query_embedding, k);
        }

        let results = self.db.search_with_filter(
            query_embedding,
            k,
            Filter::eq("domain", domain.as_str()),
        )?;

        Ok(results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                Some(self.make_recall(r.id, r.distance, meta))
            })
            .collect())
    }

    /// Recall en el mismo contexto.
    pub fn recall_same_context(
        &self,
        query_embedding: &[f32],
        k: usize,
    ) -> Result<Vec<GenericRecall>> {
        let ctx = self.current_context.read().clone();
        let context = ctx.map(|c| c.context).unwrap_or_default();

        if context.is_empty() {
            return self.recall(query_embedding, k);
        }

        let results = self.db.search_with_filter(
            query_embedding,
            k,
            Filter::eq("context", context.as_str()),
        )?;

        Ok(results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                Some(self.make_recall(r.id, r.distance, meta))
            })
            .collect())
    }

    /// Recall solo de prioridad critica.
    pub fn recall_critical(&self, query_embedding: &[f32], k: usize) -> Result<Vec<GenericRecall>> {
        let results =
            self.db
                .search_with_filter(query_embedding, k, Filter::eq("priority", "critical"))?;

        Ok(results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                Some(self.make_recall(r.id, r.distance, meta))
            })
            .collect())
    }

    /// Recall de prioridad alta o critica.
    pub fn recall_high_priority(
        &self,
        query_embedding: &[f32],
        k: usize,
    ) -> Result<Vec<GenericRecall>> {
        let results = self.db.search_with_filter(
            query_embedding,
            k * 2,
            Filter::any(vec![
                Filter::eq("priority", "critical"),
                Filter::eq("priority", "high"),
            ]),
        )?;

        let mut recalls: Vec<GenericRecall> = results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                Some(self.make_recall(r.id, r.distance, meta))
            })
            .collect();

        // Sort by priority score
        recalls.sort_by(|a, b| b.priority_score.partial_cmp(&a.priority_score).unwrap());
        recalls.truncate(k);
        Ok(recalls)
    }

    /// Busqueda por keywords.
    pub fn recall_by_keywords(&self, keywords: &str, k: usize) -> Result<Vec<GenericRecall>> {
        let results = self.db.keyword_search(keywords, k)?;

        Ok(results
            .into_iter()
            .filter_map(|r| {
                let meta = r.metadata?;
                let transfer_level = meta
                    .get("transfer_level")
                    .and_then(|v| v.as_str())
                    .and_then(TransferLevel::from_str)
                    .unwrap_or(TransferLevel::Instance);
                let priority = meta
                    .get("priority")
                    .and_then(|v| v.as_str())
                    .and_then(Priority::from_str)
                    .unwrap_or(Priority::Normal);
                let id = r.id.clone();
                let usage = self
                    .usage_stats
                    .read()
                    .get(&id)
                    .cloned()
                    .unwrap_or_default();
                let priority_score = self.calculate_priority_score(&usage, priority);

                let concepts = meta
                    .get("concepts")
                    .and_then(|v| v.as_str())
                    .map(|s: &str| s.split(',').map(String::from).collect())
                    .unwrap_or_default();

                Some(GenericRecall {
                    id,
                    relevance: r.score,
                    transfer_level,
                    priority,
                    priority_score,
                    combined_score: r.score,
                    concepts,
                    usage,
                    metadata: meta,
                })
            })
            .collect())
    }

    /// Estadisticas de la memoria.
    pub fn stats(&self) -> MemoryStats {
        let usage_stats = self.usage_stats.read();
        let total_accesses: u32 = usage_stats.values().map(|u| u.access_count).sum();
        let avg_usefulness = if usage_stats.is_empty() {
            0.0
        } else {
            usage_stats
                .values()
                .map(|u| u.usefulness_score())
                .sum::<f32>()
                / usage_stats.len() as f32
        };

        MemoryStats {
            total_memories: self.db.len(),
            preset_name: P::name().to_string(),
            has_context: self.current_context.read().is_some(),
            total_accesses,
            avg_usefulness,
        }
    }
}

/// Estadisticas de la memoria.
#[derive(Debug, Clone)]
pub struct MemoryStats {
    pub total_memories: usize,
    pub preset_name: String,
    pub has_context: bool,
    pub total_accesses: u32,
    pub avg_usefulness: f32,
}

// ============================================================================
// Presets Module
// ============================================================================

pub mod presets {
    //! Presets predefinidos para diferentes dominios.

    use super::*;

    // ------------------------------------------------------------------------
    // Software Development Preset
    // ------------------------------------------------------------------------

    /// Clasificador de dominios para desarrollo de software.
    #[derive(Debug, Default)]
    pub struct SoftwareDomainClassifier;

    impl DomainClassifier for SoftwareDomainClassifier {
        fn domain_type_name(&self) -> &'static str {
            "software_domain"
        }

        fn available_domains(&self) -> Vec<&'static str> {
            vec![
                "web_backend",
                "web_frontend",
                "cli",
                "data_science",
                "systems",
                "mobile",
                "devops",
                "security",
                "database",
                "gamedev",
                "embedded",
                "general",
            ]
        }

        fn classify(&self, content: &str) -> String {
            let lower = content.to_lowercase();

            if lower.contains("api") || lower.contains("endpoint") || lower.contains("rest") {
                "web_backend".into()
            } else if lower.contains("react") || lower.contains("vue") || lower.contains("css") {
                "web_frontend".into()
            } else if lower.contains("cli")
                || lower.contains("terminal")
                || lower.contains("command")
            {
                "cli".into()
            } else if lower.contains("pandas") || lower.contains("numpy") || lower.contains("ml") {
                "data_science".into()
            } else if lower.contains("docker")
                || lower.contains("kubernetes")
                || lower.contains("ci/cd")
            {
                "devops".into()
            } else if lower.contains("auth")
                || lower.contains("security")
                || lower.contains("encrypt")
            {
                "security".into()
            } else if lower.contains("sql") || lower.contains("database") || lower.contains("query")
            {
                "database".into()
            } else if lower.contains("android") || lower.contains("ios") || lower.contains("mobile")
            {
                "mobile".into()
            } else if lower.contains("kernel")
                || lower.contains("memory")
                || lower.contains("syscall")
            {
                "systems".into()
            } else if lower.contains("game") || lower.contains("render") || lower.contains("sprite")
            {
                "gamedev".into()
            } else if lower.contains("embedded")
                || lower.contains("mcu")
                || lower.contains("firmware")
            {
                "embedded".into()
            } else {
                "general".into()
            }
        }

        fn related(&self, domain1: &str, domain2: &str) -> bool {
            let web = ["web_backend", "web_frontend"];
            let low_level = ["systems", "embedded"];
            let data = ["data_science", "database"];

            (web.contains(&domain1) && web.contains(&domain2))
                || (low_level.contains(&domain1) && low_level.contains(&domain2))
                || (data.contains(&domain1) && data.contains(&domain2))
        }
    }

    /// Extractor de conceptos para desarrollo de software.
    #[derive(Debug, Default)]
    pub struct SoftwareConceptExtractor;

    impl ConceptExtractor for SoftwareConceptExtractor {
        fn extract(&self, description: &str, content: &str) -> Vec<String> {
            let text = format!("{} {}", description, content).to_lowercase();
            let mut concepts = Vec::new();

            let patterns = [
                (
                    "error handling",
                    &["error", "exception", "try", "catch", "result"][..],
                ),
                ("validation", &["valid", "check", "verify", "sanitize"]),
                ("caching", &["cache", "memoize", "ttl"]),
                ("async", &["async", "await", "future", "promise"]),
                ("testing", &["test", "mock", "assert", "spec"]),
                ("logging", &["log", "trace", "debug", "info"]),
                ("authentication", &["auth", "login", "jwt", "token"]),
                ("pagination", &["page", "limit", "offset", "cursor"]),
                ("rate limiting", &["rate", "throttle", "limit"]),
                ("middleware", &["middleware", "interceptor", "filter"]),
            ];

            for (concept, keywords) in patterns {
                if keywords.iter().any(|k| text.contains(k)) {
                    concepts.push(concept.to_string());
                }
            }

            concepts
        }

        fn is_universal(&self, concept: &str) -> bool {
            self.universal_concepts().contains(&concept)
        }

        fn universal_concepts(&self) -> Vec<&'static str> {
            vec![
                "error handling",
                "validation",
                "caching",
                "logging",
                "testing",
            ]
        }
    }

    /// Evaluador de contexto para lenguajes de programacion.
    #[derive(Debug, Default)]
    pub struct ProgrammingLanguageMatcher;

    impl ContextMatcher for ProgrammingLanguageMatcher {
        fn context_type_name(&self) -> &'static str {
            "programming_language"
        }

        fn available_contexts(&self) -> Vec<&'static str> {
            vec![
                "rust",
                "python",
                "javascript",
                "typescript",
                "go",
                "java",
                "c",
                "cpp",
                "csharp",
                "ruby",
                "php",
                "swift",
                "kotlin",
            ]
        }

        fn compatibility(&self, ctx1: &str, ctx2: &str) -> f32 {
            if ctx1 == ctx2 {
                return 1.0;
            }

            let family1 = self.context_family(ctx1);
            let family2 = self.context_family(ctx2);

            if family1.is_some() && family1 == family2 {
                0.8
            } else {
                0.3
            }
        }

        fn context_family(&self, context: &str) -> Option<&'static str> {
            match context.to_lowercase().as_str() {
                "javascript" | "typescript" => Some("js_family"),
                "c" | "cpp" | "rust" => Some("systems"),
                "java" | "kotlin" | "scala" => Some("jvm"),
                "python" | "ruby" => Some("dynamic"),
                "swift" | "objective-c" => Some("apple"),
                _ => None,
            }
        }
    }

    /// Calculador de prioridad para desarrollo de software.
    #[derive(Debug, Default)]
    pub struct SoftwarePriorityCalculator;

    impl PriorityCalculator for SoftwarePriorityCalculator {
        fn calculate(&self, description: &str, content: &str, outcome: &str) -> Priority {
            let text = format!("{} {} {}", description, content, outcome).to_lowercase();

            // Critical: security, production issues, data loss
            if self.critical_keywords().iter().any(|k| text.contains(k)) {
                return Priority::Critical;
            }

            // High: bugs, errors, performance
            if self.high_keywords().iter().any(|k| text.contains(k)) {
                return Priority::High;
            }

            // Low: style, comments, documentation
            if self.low_keywords().iter().any(|k| text.contains(k)) {
                return Priority::Low;
            }

            Priority::Normal
        }

        fn critical_keywords(&self) -> Vec<&'static str> {
            vec![
                "security",
                "vulnerability",
                "cve",
                "injection",
                "xss",
                "csrf",
                "production",
                "outage",
                "data loss",
                "corruption",
                "breach",
                "critical",
                "urgent",
                "emergency",
                "hotfix",
            ]
        }

        fn high_keywords(&self) -> Vec<&'static str> {
            vec![
                "bug",
                "error",
                "exception",
                "crash",
                "failure",
                "broken",
                "performance",
                "slow",
                "memory leak",
                "timeout",
                "important",
                "priority",
                "blocking",
            ]
        }

        fn low_keywords(&self) -> Vec<&'static str> {
            vec![
                "style",
                "formatting",
                "comment",
                "typo",
                "rename",
                "refactor",
                "cleanup",
                "todo",
                "nice to have",
            ]
        }
    }

    /// Preset para desarrollo de software.
    pub struct SoftwareDevelopment;

    impl DomainPreset for SoftwareDevelopment {
        type Domain = SoftwareDomainClassifier;
        type Concepts = SoftwareConceptExtractor;
        type Context = ProgrammingLanguageMatcher;
        type Priority = SoftwarePriorityCalculator;

        fn name() -> &'static str {
            "Software Development"
        }

        fn description() -> &'static str {
            "Memory system for software development agents with code-aware transfer"
        }

        fn default_decay() -> DecayConfig {
            // Code knowledge decays slowly (90 days)
            DecayConfig::slow()
        }

        fn default_weights() -> PriorityWeights {
            // Prioritize usefulness for code
            PriorityWeights {
                base_priority: 0.3,
                frequency: 0.25,
                usefulness: 0.35,
                recency: 0.1,
            }
        }
    }

    // ------------------------------------------------------------------------
    // Conversational Preset (Chatbots)
    // ------------------------------------------------------------------------

    /// Clasificador de dominios conversacionales.
    #[derive(Debug, Default)]
    pub struct ConversationalDomainClassifier;

    impl DomainClassifier for ConversationalDomainClassifier {
        fn domain_type_name(&self) -> &'static str {
            "conversation_domain"
        }

        fn available_domains(&self) -> Vec<&'static str> {
            vec![
                "support",
                "sales",
                "entertainment",
                "education",
                "casual",
                "professional",
            ]
        }

        fn classify(&self, content: &str) -> String {
            let lower = content.to_lowercase();

            if lower.contains("help") || lower.contains("problem") || lower.contains("issue") {
                "support".into()
            } else if lower.contains("buy")
                || lower.contains("price")
                || lower.contains("offer")
                || lower.contains("cost")
            {
                "sales".into()
            } else if lower.contains("joke") || lower.contains("fun") || lower.contains("play") {
                "entertainment".into()
            } else if lower.contains("learn") || lower.contains("explain") || lower.contains("how")
            {
                "education".into()
            } else if lower.contains("meeting")
                || lower.contains("report")
                || lower.contains("deadline")
            {
                "professional".into()
            } else {
                "casual".into()
            }
        }

        fn related(&self, domain1: &str, domain2: &str) -> bool {
            let formal = ["support", "sales", "professional"];
            let informal = ["entertainment", "casual"];
            let learning = ["education", "support"];

            (formal.contains(&domain1) && formal.contains(&domain2))
                || (informal.contains(&domain1) && informal.contains(&domain2))
                || (learning.contains(&domain1) && learning.contains(&domain2))
        }
    }

    /// Extractor de conceptos conversacionales.
    #[derive(Debug, Default)]
    pub struct ConversationalConceptExtractor;

    impl ConceptExtractor for ConversationalConceptExtractor {
        fn extract(&self, description: &str, content: &str) -> Vec<String> {
            let text = format!("{} {}", description, content).to_lowercase();
            let mut concepts = Vec::new();

            let patterns = [
                (
                    "greeting",
                    &["hello", "hi", "hey", "good morning", "hola"][..],
                ),
                ("farewell", &["bye", "goodbye", "see you", "adios"]),
                ("gratitude", &["thank", "thanks", "gracias", "appreciate"]),
                ("apology", &["sorry", "apologize", "excuse", "disculpa"]),
                ("empathy", &["understand", "feel", "sorry to hear"]),
                (
                    "clarification",
                    &["mean", "clarify", "explain", "what do you"],
                ),
                ("confirmation", &["yes", "correct", "right", "exactly"]),
                ("negation", &["no", "not", "don't", "can't"]),
                ("urgency", &["urgent", "asap", "immediately", "now"]),
                ("frustration", &["angry", "upset", "frustrated", "annoyed"]),
            ];

            for (concept, keywords) in patterns {
                if keywords.iter().any(|k| text.contains(k)) {
                    concepts.push(concept.to_string());
                }
            }

            concepts
        }

        fn is_universal(&self, concept: &str) -> bool {
            self.universal_concepts().contains(&concept)
        }

        fn universal_concepts(&self) -> Vec<&'static str> {
            vec![
                "greeting",
                "farewell",
                "gratitude",
                "empathy",
                "clarification",
            ]
        }
    }

    /// Evaluador de tono conversacional.
    #[derive(Debug, Default)]
    pub struct ConversationalToneMatcher;

    impl ContextMatcher for ConversationalToneMatcher {
        fn context_type_name(&self) -> &'static str {
            "conversational_tone"
        }

        fn available_contexts(&self) -> Vec<&'static str> {
            vec![
                "formal",
                "informal",
                "friendly",
                "professional",
                "technical",
                "casual",
                "empathetic",
            ]
        }

        fn compatibility(&self, ctx1: &str, ctx2: &str) -> f32 {
            if ctx1 == ctx2 {
                return 1.0;
            }

            let family1 = self.context_family(ctx1);
            let family2 = self.context_family(ctx2);

            if family1.is_some() && family1 == family2 {
                0.8
            } else {
                0.4
            }
        }

        fn context_family(&self, context: &str) -> Option<&'static str> {
            match context.to_lowercase().as_str() {
                "formal" | "professional" | "technical" => Some("formal"),
                "informal" | "friendly" | "casual" => Some("informal"),
                "empathetic" => Some("supportive"),
                _ => None,
            }
        }
    }

    /// Calculador de prioridad conversacional.
    #[derive(Debug, Default)]
    pub struct ConversationalPriorityCalculator;

    impl PriorityCalculator for ConversationalPriorityCalculator {
        fn calculate(&self, description: &str, content: &str, outcome: &str) -> Priority {
            let text = format!("{} {} {}", description, content, outcome).to_lowercase();

            // Critical: user preferences, safety, explicit requests
            if self.critical_keywords().iter().any(|k| text.contains(k)) {
                return Priority::Critical;
            }

            // High: emotional states, important preferences
            if self.high_keywords().iter().any(|k| text.contains(k)) {
                return Priority::High;
            }

            // Low: casual interactions, generic responses
            if self.low_keywords().iter().any(|k| text.contains(k)) {
                return Priority::Low;
            }

            Priority::Normal
        }

        fn critical_keywords(&self) -> Vec<&'static str> {
            vec![
                "never",
                "always",
                "hate",
                "love",
                "allergy",
                "allergic",
                "important",
                "remember",
                "don't forget",
                "must",
                "preference",
                "please don't",
                "stop",
            ]
        }

        fn high_keywords(&self) -> Vec<&'static str> {
            vec![
                "frustrated",
                "angry",
                "upset",
                "disappointed",
                "happy",
                "excited",
                "grateful",
                "thank",
                "favorite",
                "prefer",
                "like",
                "dislike",
            ]
        }

        fn low_keywords(&self) -> Vec<&'static str> {
            vec![
                "ok", "fine", "sure", "maybe", "whatever", "casual", "just", "random",
            ]
        }
    }

    /// Preset para chatbots y agentes conversacionales.
    pub struct Conversational;

    impl DomainPreset for Conversational {
        type Domain = ConversationalDomainClassifier;
        type Concepts = ConversationalConceptExtractor;
        type Context = ConversationalToneMatcher;
        type Priority = ConversationalPriorityCalculator;

        fn name() -> &'static str {
            "Conversational"
        }

        fn description() -> &'static str {
            "Memory system for chatbots and conversational agents"
        }

        fn default_decay() -> DecayConfig {
            // Conversations decay faster (1 week)
            DecayConfig::fast()
        }

        fn default_weights() -> PriorityWeights {
            // Prioritize recency for conversations
            PriorityWeights::recency_focused()
        }
    }

    // ------------------------------------------------------------------------
    // Customer Service Preset
    // ------------------------------------------------------------------------

    /// Clasificador de dominios de servicio al cliente.
    #[derive(Debug, Default)]
    pub struct CustomerServiceDomainClassifier;

    impl DomainClassifier for CustomerServiceDomainClassifier {
        fn domain_type_name(&self) -> &'static str {
            "service_domain"
        }

        fn available_domains(&self) -> Vec<&'static str> {
            vec![
                "billing",
                "technical",
                "returns",
                "shipping",
                "account",
                "product_info",
                "complaints",
                "general",
            ]
        }

        fn classify(&self, content: &str) -> String {
            let lower = content.to_lowercase();

            if lower.contains("bill") || lower.contains("charge") || lower.contains("payment") {
                "billing".into()
            } else if lower.contains("broken")
                || lower.contains("not working")
                || lower.contains("bug")
            {
                "technical".into()
            } else if lower.contains("return")
                || lower.contains("refund")
                || lower.contains("exchange")
            {
                "returns".into()
            } else if lower.contains("ship")
                || lower.contains("deliver")
                || lower.contains("tracking")
            {
                "shipping".into()
            } else if lower.contains("account")
                || lower.contains("password")
                || lower.contains("login")
            {
                "account".into()
            } else if lower.contains("product")
                || lower.contains("feature")
                || lower.contains("spec")
            {
                "product_info".into()
            } else if lower.contains("complain")
                || lower.contains("unhappy")
                || lower.contains("terrible")
            {
                "complaints".into()
            } else {
                "general".into()
            }
        }

        fn related(&self, domain1: &str, domain2: &str) -> bool {
            let money = ["billing", "returns"];
            let logistics = ["shipping", "returns"];
            let tech = ["technical", "account"];

            (money.contains(&domain1) && money.contains(&domain2))
                || (logistics.contains(&domain1) && logistics.contains(&domain2))
                || (tech.contains(&domain1) && tech.contains(&domain2))
        }
    }

    /// Extractor de conceptos de servicio al cliente.
    #[derive(Debug, Default)]
    pub struct CustomerServiceConceptExtractor;

    impl ConceptExtractor for CustomerServiceConceptExtractor {
        fn extract(&self, description: &str, content: &str) -> Vec<String> {
            let text = format!("{} {}", description, content).to_lowercase();
            let mut concepts = Vec::new();

            let patterns = [
                (
                    "escalation needed",
                    &["manager", "supervisor", "escalate"][..],
                ),
                ("resolution", &["solved", "fixed", "resolved", "done"]),
                ("compensation", &["refund", "credit", "discount", "free"]),
                ("verification", &["verify", "confirm", "check identity"]),
                ("policy reference", &["policy", "terms", "conditions"]),
                ("empathy response", &["understand", "sorry", "apologize"]),
                (
                    "follow up needed",
                    &["follow up", "callback", "contact again"],
                ),
                ("urgent", &["urgent", "emergency", "asap"]),
            ];

            for (concept, keywords) in patterns {
                if keywords.iter().any(|k| text.contains(k)) {
                    concepts.push(concept.to_string());
                }
            }

            concepts
        }

        fn is_universal(&self, concept: &str) -> bool {
            self.universal_concepts().contains(&concept)
        }

        fn universal_concepts(&self) -> Vec<&'static str> {
            vec![
                "empathy response",
                "verification",
                "resolution",
                "follow up needed",
            ]
        }
    }

    /// Evaluador de tipo de cliente.
    #[derive(Debug, Default)]
    pub struct CustomerTierMatcher;

    impl ContextMatcher for CustomerTierMatcher {
        fn context_type_name(&self) -> &'static str {
            "customer_tier"
        }

        fn available_contexts(&self) -> Vec<&'static str> {
            vec!["vip", "premium", "standard", "new", "at_risk", "churned"]
        }

        fn compatibility(&self, ctx1: &str, ctx2: &str) -> f32 {
            if ctx1 == ctx2 {
                return 1.0;
            }

            let family1 = self.context_family(ctx1);
            let family2 = self.context_family(ctx2);

            if family1.is_some() && family1 == family2 {
                0.7
            } else {
                0.5 // Customer service patterns are often broadly applicable
            }
        }

        fn context_family(&self, context: &str) -> Option<&'static str> {
            match context.to_lowercase().as_str() {
                "vip" | "premium" => Some("high_value"),
                "standard" | "new" => Some("regular"),
                "at_risk" | "churned" => Some("retention"),
                _ => None,
            }
        }
    }

    /// Calculador de prioridad para servicio al cliente.
    #[derive(Debug, Default)]
    pub struct CustomerServicePriorityCalculator;

    impl PriorityCalculator for CustomerServicePriorityCalculator {
        fn calculate(&self, description: &str, content: &str, outcome: &str) -> Priority {
            let text = format!("{} {} {}", description, content, outcome).to_lowercase();

            // Critical: VIP, legal, escalations
            if self.critical_keywords().iter().any(|k| text.contains(k)) {
                return Priority::Critical;
            }

            // High: complaints, refunds, unhappy
            if self.high_keywords().iter().any(|k| text.contains(k)) {
                return Priority::High;
            }

            // Low: general inquiries, routine
            if self.low_keywords().iter().any(|k| text.contains(k)) {
                return Priority::Low;
            }

            Priority::Normal
        }

        fn critical_keywords(&self) -> Vec<&'static str> {
            vec![
                "vip",
                "enterprise",
                "legal",
                "lawyer",
                "sue",
                "escalate",
                "manager",
                "supervisor",
                "ceo",
                "fraud",
                "breach",
                "unauthorized",
            ]
        }

        fn high_keywords(&self) -> Vec<&'static str> {
            vec![
                "complaint",
                "unhappy",
                "refund",
                "cancel",
                "broken",
                "defective",
                "wrong",
                "missing",
                "urgent",
                "immediately",
                "asap",
            ]
        }

        fn low_keywords(&self) -> Vec<&'static str> {
            vec![
                "question",
                "inquiry",
                "information",
                "how to",
                "general",
                "routine",
                "standard",
            ]
        }
    }

    /// Preset para servicio al cliente.
    pub struct CustomerService;

    impl DomainPreset for CustomerService {
        type Domain = CustomerServiceDomainClassifier;
        type Concepts = CustomerServiceConceptExtractor;
        type Context = CustomerTierMatcher;
        type Priority = CustomerServicePriorityCalculator;

        fn name() -> &'static str {
            "Customer Service"
        }

        fn description() -> &'static str {
            "Memory system for customer service agents"
        }

        fn default_decay() -> DecayConfig {
            // Customer interactions decay moderately (30 days)
            DecayConfig::default()
        }

        fn default_weights() -> PriorityWeights {
            // Prioritize manual priority for customer service
            PriorityWeights::manual_focused()
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_transfer_level_ordering() {
        assert!(TransferLevel::Universal > TransferLevel::Domain);
        assert!(TransferLevel::Domain > TransferLevel::Context);
        assert!(TransferLevel::Context > TransferLevel::Instance);
    }

    #[test]
    fn test_transfer_level_scores() {
        assert_eq!(TransferLevel::Universal.transfer_score(), 1.0);
        assert_eq!(TransferLevel::Domain.transfer_score(), 0.75);
        assert_eq!(TransferLevel::Context.transfer_score(), 0.5);
        assert_eq!(TransferLevel::Instance.transfer_score(), 0.25);
    }

    #[test]
    fn test_instance_context_builder() {
        let ctx = InstanceContext::new("my-project")
            .with_context("rust")
            .with_domain("web_backend")
            .with_extra("framework", "actix");

        assert_eq!(ctx.instance_id, "my-project");
        assert_eq!(ctx.context, "rust");
        assert_eq!(ctx.domain, "web_backend");
        assert_eq!(ctx.extra.get("framework"), Some(&"actix".to_string()));
    }

    #[test]
    fn test_software_domain_classifier() {
        let classifier = SoftwareDomainClassifier;

        assert_eq!(classifier.classify("REST API endpoint"), "web_backend");
        assert_eq!(classifier.classify("React component"), "web_frontend");
        assert_eq!(classifier.classify("CLI tool"), "cli");
        assert_eq!(classifier.classify("pandas dataframe"), "data_science");
    }

    #[test]
    fn test_software_concept_extractor() {
        let extractor = SoftwareConceptExtractor;

        let concepts = extractor.extract(
            "JWT authentication with rate limiting",
            "middleware auth jwt token",
        );

        assert!(concepts.contains(&"authentication".to_string()));
        assert!(concepts.contains(&"rate limiting".to_string()));
        assert!(concepts.contains(&"middleware".to_string()));
    }

    #[test]
    fn test_programming_language_matcher() {
        let matcher = ProgrammingLanguageMatcher;

        assert_eq!(matcher.compatibility("rust", "rust"), 1.0);
        assert_eq!(matcher.compatibility("javascript", "typescript"), 0.8);
        assert!(matcher.compatibility("rust", "python") < 0.5);
    }

    #[test]
    fn test_conversational_domain_classifier() {
        let classifier = ConversationalDomainClassifier;

        assert_eq!(classifier.classify("I need help with my order"), "support");
        assert_eq!(classifier.classify("How much does it cost?"), "sales");
        assert_eq!(classifier.classify("Tell me a joke"), "entertainment");
    }

    #[test]
    fn test_conversational_concept_extractor() {
        let extractor = ConversationalConceptExtractor;

        let concepts = extractor.extract("User greeting", "Hello, how are you?");
        assert!(concepts.contains(&"greeting".to_string()));

        let concepts = extractor.extract("User frustrated", "I'm very upset about this");
        assert!(concepts.contains(&"frustration".to_string()));
    }

    #[test]
    fn test_customer_service_domain_classifier() {
        let classifier = CustomerServiceDomainClassifier;

        assert_eq!(classifier.classify("Wrong charge on my bill"), "billing");
        assert_eq!(classifier.classify("Product not working"), "technical");
        assert_eq!(classifier.classify("I want to return this"), "returns");
    }

    #[test]
    fn test_generic_memory_creation() {
        let memory = GenericMemory::<SoftwareDevelopment>::new(4).unwrap();
        assert_eq!(memory.stats().preset_name, "Software Development");
        assert!(!memory.stats().has_context);
    }

    #[test]
    fn test_generic_memory_set_context() {
        let memory = GenericMemory::<Conversational>::new(4).unwrap();

        memory.set_instance("@user123", "casual", "support");

        let ctx = memory.current_context().unwrap();
        assert_eq!(ctx.instance_id, "@user123");
        assert_eq!(ctx.context, "casual");
        assert_eq!(ctx.domain, "support");
    }

    #[test]
    fn test_domain_relatedness() {
        let classifier = SoftwareDomainClassifier;

        assert!(classifier.related("web_backend", "web_frontend"));
        assert!(classifier.related("systems", "embedded"));
        assert!(!classifier.related("web_backend", "gamedev"));
    }

    #[test]
    fn test_preset_names() {
        assert_eq!(SoftwareDevelopment::name(), "Software Development");
        assert_eq!(Conversational::name(), "Conversational");
        assert_eq!(CustomerService::name(), "Customer Service");
    }

    // ========================================================================
    // Priority System Tests
    // ========================================================================

    #[test]
    fn test_priority_ordering() {
        assert!(Priority::Critical > Priority::High);
        assert!(Priority::High > Priority::Normal);
        assert!(Priority::Normal > Priority::Low);
    }

    #[test]
    fn test_priority_scores() {
        assert_eq!(Priority::Critical.base_score(), 1.0);
        assert_eq!(Priority::High.base_score(), 0.75);
        assert_eq!(Priority::Normal.base_score(), 0.5);
        assert_eq!(Priority::Low.base_score(), 0.25);
    }

    #[test]
    fn test_priority_from_str() {
        assert_eq!(Priority::from_str("critical"), Some(Priority::Critical));
        assert_eq!(Priority::from_str("urgent"), Some(Priority::Critical));
        assert_eq!(Priority::from_str("high"), Some(Priority::High));
        assert_eq!(Priority::from_str("normal"), Some(Priority::Normal));
        assert_eq!(Priority::from_str("low"), Some(Priority::Low));
        assert_eq!(Priority::from_str("unknown"), None);
    }

    #[test]
    fn test_usage_stats_frequency_score() {
        let mut stats = UsageStats::new();
        assert_eq!(stats.frequency_score(), 0.0);

        stats.access_count = 1;
        assert!(stats.frequency_score() > 0.0);

        stats.access_count = 100;
        assert!(stats.frequency_score() > 0.5);
        assert!(stats.frequency_score() <= 1.0);
    }

    #[test]
    fn test_usage_stats_usefulness() {
        let mut stats = UsageStats::new();
        assert_eq!(stats.usefulness_score(), 0.5); // Neutral when no access

        stats.access_count = 10;
        stats.useful_count = 8;
        assert_eq!(stats.usefulness_score(), 0.8);
    }

    #[test]
    fn test_decay_config_calculation() {
        let config = DecayConfig::default();

        // Critical priority should not decay
        assert_eq!(config.calculate_decay(1000000, Priority::Critical), 1.0);

        // Normal priority should decay
        let decay = config.calculate_decay(30 * 24 * 60 * 60, Priority::Normal);
        assert!(decay < 1.0);
        assert!(decay >= 0.4); // After half-life, should be around 0.5
    }

    #[test]
    fn test_decay_config_no_decay() {
        let config = DecayConfig::no_decay();
        assert_eq!(config.calculate_decay(1000000, Priority::Low), 1.0);
    }

    #[test]
    fn test_priority_weights() {
        let weights = PriorityWeights::default();
        let score = weights.calculate_score(0.5, 0.3, 0.8, 0.6);
        assert!(score > 0.0 && score <= 1.0);
    }

    #[test]
    fn test_recency_score() {
        // Very recent should be high
        assert!(recency_score(0) > 0.99);

        // 1 week old should be around 0.37 (e^-1)
        let week_old = recency_score(7 * 24 * 60 * 60);
        assert!(week_old > 0.3 && week_old < 0.5);

        // Very old should be low
        assert!(recency_score(365 * 24 * 60 * 60) < 0.1);
    }

    #[test]
    fn test_software_priority_calculator() {
        let calc = SoftwarePriorityCalculator;

        // Security issue = Critical
        assert_eq!(
            calc.calculate("XSS vulnerability fix", "sanitize input", "fixed"),
            Priority::Critical
        );

        // Bug = High
        assert_eq!(
            calc.calculate("Bug fix", "crash on startup", "resolved"),
            Priority::High
        );

        // Style = Low
        assert_eq!(
            calc.calculate("Formatting", "apply prettier", "done"),
            Priority::Low
        );

        // Normal code = Normal
        assert_eq!(
            calc.calculate("Add feature", "new button", "completed"),
            Priority::Normal
        );
    }

    #[test]
    fn test_conversational_priority_calculator() {
        let calc = ConversationalPriorityCalculator;

        // User preference = Critical
        assert_eq!(
            calc.calculate("User preference", "I never want spam", "noted"),
            Priority::Critical
        );

        // Emotional state = High
        assert_eq!(
            calc.calculate("User upset", "I'm frustrated", "apologized"),
            Priority::High
        );

        // Casual = Low
        assert_eq!(
            calc.calculate("Casual chat", "just ok", "acknowledged"),
            Priority::Low
        );
    }

    #[test]
    fn test_customer_service_priority_calculator() {
        let calc = CustomerServicePriorityCalculator;

        // VIP = Critical
        assert_eq!(
            calc.calculate("VIP customer", "enterprise account", "handled"),
            Priority::Critical
        );

        // Complaint = High
        assert_eq!(
            calc.calculate("Customer complaint", "refund request", "processed"),
            Priority::High
        );

        // Inquiry = Low
        assert_eq!(
            calc.calculate("General question", "product information", "answered"),
            Priority::Low
        );
    }

    #[test]
    fn test_priority_weights_presets() {
        let manual = PriorityWeights::manual_focused();
        assert!(manual.base_priority > manual.frequency);

        let usage = PriorityWeights::usage_focused();
        assert!(usage.frequency > usage.base_priority);

        let recency = PriorityWeights::recency_focused();
        assert!(recency.recency > recency.base_priority);
    }

    #[test]
    fn test_memory_stats_includes_usage() {
        let memory = GenericMemory::<SoftwareDevelopment>::new(4).unwrap();
        let stats = memory.stats();
        assert_eq!(stats.total_accesses, 0);
        assert_eq!(stats.avg_usefulness, 0.0);
    }
}