ai-memory 0.6.4

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use crate::models::Tier;

// ---------------------------------------------------------------------------
// Embedding models
// ---------------------------------------------------------------------------

/// Supported embedding models for semantic search.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EmbeddingModel {
    /// sentence-transformers/all-MiniLM-L6-v2 — 384-dim, ~90 MB
    MiniLmL6V2,
    /// nomic-ai/nomic-embed-text-v1.5 — 768-dim, ~270 MB
    NomicEmbedV15,
}

impl EmbeddingModel {
    /// Embedding vector dimensionality.
    pub fn dim(self) -> usize {
        match self {
            Self::MiniLmL6V2 => 384,
            Self::NomicEmbedV15 => 768,
        }
    }

    /// `HuggingFace` model identifier.
    pub fn hf_model_id(&self) -> &str {
        match self {
            Self::MiniLmL6V2 => "sentence-transformers/all-MiniLM-L6-v2",
            Self::NomicEmbedV15 => "nomic-ai/nomic-embed-text-v1.5",
        }
    }
}

// ---------------------------------------------------------------------------
// LLM models
// ---------------------------------------------------------------------------

/// Supported LLM models (served via Ollama).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LlmModel {
    /// Google Gemma 4 Effective 2B — ~1 GB Q4
    Gemma4E2B,
    /// Google Gemma 4 Effective 4B — ~2.3 GB Q4
    Gemma4E4B,
}

impl LlmModel {
    /// Ollama model tag used to pull / run this model.
    pub fn ollama_model_id(&self) -> &str {
        match self {
            Self::Gemma4E2B => "gemma4:e2b",
            Self::Gemma4E4B => "gemma4:e4b",
        }
    }

    /// Human-readable display name.
    pub fn display_name(&self) -> &str {
        match self {
            Self::Gemma4E2B => "Gemma 4 Effective 2B (Q4)",
            Self::Gemma4E4B => "Gemma 4 Effective 4B (Q4)",
        }
    }
}

// ---------------------------------------------------------------------------
// Feature tiers
// ---------------------------------------------------------------------------

/// Feature tiers control which AI capabilities are active based on the
/// available memory budget on the host machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FeatureTier {
    /// FTS5 keyword search only — 0 MB extra.
    Keyword,
    /// `MiniLM` embeddings + HNSW index — ~256 MB.
    Semantic,
    /// nomic-embed + Gemma 4 E2B via Ollama — ~1 GB.
    Smart,
    /// nomic-embed + Gemma 4 E4B + cross-encoder via Ollama — ~4 GB.
    Autonomous,
}

impl FeatureTier {
    /// Parse a tier name (case-insensitive).
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "keyword" => Some(Self::Keyword),
            "semantic" => Some(Self::Semantic),
            "smart" => Some(Self::Smart),
            "autonomous" => Some(Self::Autonomous),
            _ => None,
        }
    }

    /// Canonical lowercase name.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Keyword => "keyword",
            Self::Semantic => "semantic",
            Self::Smart => "smart",
            Self::Autonomous => "autonomous",
        }
    }

    /// Build the full [`TierConfig`] for this tier.
    pub fn config(self) -> TierConfig {
        match self {
            Self::Keyword => TierConfig {
                tier: self,
                embedding_model: None,
                llm_model: None,
                cross_encoder: false,
                max_memory_mb: 0,
            },
            Self::Semantic => TierConfig {
                tier: self,
                embedding_model: Some(EmbeddingModel::MiniLmL6V2),
                llm_model: None,
                cross_encoder: false,
                max_memory_mb: 256,
            },
            Self::Smart => TierConfig {
                tier: self,
                embedding_model: Some(EmbeddingModel::NomicEmbedV15),
                llm_model: Some(LlmModel::Gemma4E2B),
                cross_encoder: false,
                max_memory_mb: 1024,
            },
            Self::Autonomous => TierConfig {
                tier: self,
                embedding_model: Some(EmbeddingModel::NomicEmbedV15),
                llm_model: Some(LlmModel::Gemma4E4B),
                cross_encoder: true,
                max_memory_mb: 4096,
            },
        }
    }

    /// Automatically select the best tier that fits within `mb` megabytes.
    #[allow(dead_code)]
    pub fn from_memory_budget(mb: usize) -> Self {
        if mb >= 4096 {
            Self::Autonomous
        } else if mb >= 1024 {
            Self::Smart
        } else if mb >= 256 {
            Self::Semantic
        } else {
            Self::Keyword
        }
    }
}

impl std::fmt::Display for FeatureTier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---------------------------------------------------------------------------
// Tier configuration
// ---------------------------------------------------------------------------

/// Runtime configuration derived from a [`FeatureTier`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TierConfig {
    pub tier: FeatureTier,
    pub embedding_model: Option<EmbeddingModel>,
    pub llm_model: Option<LlmModel>,
    pub cross_encoder: bool,
    pub max_memory_mb: usize,
}

impl TierConfig {
    /// Produce a [`Capabilities`] (schema v2) report suitable for JSON
    /// serialisation. The MCP / HTTP `handle_capabilities_with_conn`
    /// wrapper overlays live runtime state (recall mode, reranker mode,
    /// embedder-loaded flag) and live DB counts (active rules, hook
    /// registrations, pending approvals) before the report goes on the
    /// wire.
    ///
    /// v2 honesty patch (P1, v0.6.3.1): `recall_mode_active` and
    /// `reranker_active` start at conservative defaults (`disabled` /
    /// `off`); the wrapper updates them based on the *runtime* embedder
    /// + reranker handles, not the *configured* tier values.
    pub fn capabilities(&self) -> Capabilities {
        let has_embeddings = self.embedding_model.is_some();
        let has_llm = self.llm_model.is_some();

        Capabilities {
            // Capabilities schema v2 — see `Capabilities` doc comment.
            schema_version: "2".to_string(),
            tier: self.tier.as_str().to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            features: CapabilityFeatures {
                keyword_search: true,
                semantic_search: has_embeddings,
                hybrid_recall: has_embeddings,
                query_expansion: has_llm,
                auto_consolidation: has_llm,
                auto_tagging: has_llm,
                contradiction_analysis: has_llm,
                cross_encoder_reranking: self.cross_encoder,
                // Honesty patch: planned-not-implemented. The flag was
                // previously a `bool` whose `true` value implied a wired
                // feature that does not exist in this build.
                memory_reflection: PlannedFeature::planned("v0.7+"),
                // Default false — the HTTP/MCP capabilities handler
                // overwrites this with the live runtime state when it
                // has access to the embedder handle.
                embedder_loaded: false,
                // Conservative defaults; the handler wrapper overlays the
                // live runtime state (`hybrid` when embedder is loaded,
                // `keyword_only` when it is not, `degraded` if the load
                // failed, `disabled` for the keyword tier).
                recall_mode_active: RecallMode::Disabled,
                // Conservative default; overwritten when the wrapper has
                // the actual reranker handle. `off` means no reranker is
                // configured; `lexical_fallback` means the neural model
                // failed to materialize; `neural` means the BERT
                // cross-encoder is loaded.
                reranker_active: RerankerMode::Off,
            },
            models: CapabilityModels {
                embedding: self
                    .embedding_model
                    .map_or_else(|| "none".to_string(), |m| m.hf_model_id().to_string()),
                embedding_dim: self.embedding_model.map_or(0, EmbeddingModel::dim),
                llm: self
                    .llm_model
                    .map_or_else(|| "none".to_string(), |m| m.ollama_model_id().to_string()),
                cross_encoder: if self.cross_encoder {
                    "cross-encoder/ms-marco-MiniLM-L-6-v2".to_string()
                } else {
                    "none".to_string()
                },
            },
            // v2 dynamic blocks — start at zero-state defaults. The MCP
            // and HTTP `handle_capabilities` wrappers overwrite these
            // with live counts when they have a `&Connection` handle.
            //
            // Honesty patch (P1): `permissions.mode` is `"advisory"`
            // until P4 lands the enforcement gate. Was `"ask"`, which
            // implied an active prompt loop that does not exist.
            // `rule_summary`, `hooks.by_event`, `approval.subscribers`,
            // and `approval.default_timeout_seconds` were dropped in v2
            // because they have no backing implementation.
            permissions: CapabilityPermissions {
                mode: "advisory".to_string(),
                active_rules: 0,
                // v0.6.3.1 (P4, G1): chain-walking enforcement landed
                // in this release. Surface "enforced" so consumers can
                // distinguish a governed deployment from the historical
                // "display_only" posture.
                inheritance: Some("enforced".to_string()),
            },
            hooks: CapabilityHooks::default(),
            compaction: CapabilityCompaction::planned(),
            approval: CapabilityApproval {
                pending_requests: 0,
            },
            transcripts: CapabilityTranscripts::planned(),
            hnsw: CapabilityHnsw::default(),
        }
    }
}

// ---------------------------------------------------------------------------
// Capability reporting
// ---------------------------------------------------------------------------

/// Top-level capabilities report for a running instance.
///
/// Schema versions:
/// - **v1** (legacy, pre-v0.6.3.1): `tier`, `version`, `features`,
///   `models`. Reachable via `Accept-Capabilities: v1` (HTTP) or the MCP
///   `accept` argument set to `"v1"`. See [`CapabilitiesV1`].
/// - **v2** (v0.6.3.1 honesty patch): `schema_version="2"` plus the
///   `permissions`, `hooks`, `compaction`, `approval`, `transcripts`
///   blocks. v1 fields preserved at the same top-level paths — old
///   clients that read v2 by name continue to work for the un-dropped
///   fields. Default response shape.
///
/// **v2 honesty patch (P1, v0.6.3.1):**
/// - `features.recall_mode_active` and `features.reranker_active` are
///   *runtime* state, not config-derived flags.
/// - `features.memory_reflection` is now a `{planned, version, enabled}`
///   object, not a `bool`.
/// - `compaction` and `transcripts` carry the same planned-feature
///   shape so operators can distinguish "disabled but built" from "not
///   in this build."
/// - `permissions.mode = "advisory"` until the enforcement gate ships
///   in P4. Was `"ask"`, which implied an active interactive loop.
/// - The following fields were **removed** because no backing
///   implementation exists: `permissions.rule_summary`,
///   `hooks.by_event`, `approval.subscribers`,
///   `approval.default_timeout_seconds`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Capabilities {
    /// Schema-version discriminator. Always `"2"` since v0.6.3.
    pub schema_version: String,
    pub tier: String,
    pub version: String,
    pub features: CapabilityFeatures,
    pub models: CapabilityModels,

    /// Active permission/governance rules. Pre-P4 reports the count of
    /// namespaces that have a `metadata.governance` policy attached to
    /// their standard memory; the underlying permission system itself
    /// is P4 work.
    pub permissions: CapabilityPermissions,

    /// Registered hooks. Pre-v0.7 reports webhook subscriptions as a
    /// proxy (hook system itself is v0.7 Bucket 0).
    pub hooks: CapabilityHooks,

    /// Compaction state. v0.8 work — reports `{planned, version,
    /// enabled}` until the subsystem ships.
    pub compaction: CapabilityCompaction,

    /// Approval API state. Reports the live count of pending actions
    /// from the existing `pending_actions` table.
    pub approval: CapabilityApproval,

    /// Sidechain-transcript state. v0.7 Bucket 1.7 work — reports
    /// `{planned, version, enabled}` until the subsystem ships.
    pub transcripts: CapabilityTranscripts,

    /// v0.6.3.1 (P3, G2): HNSW vector-index health. Defaults to a
    /// quiet zero-state report; the MCP/HTTP capabilities wrapper
    /// overwrites with live process counters when the index module
    /// has run an eviction.
    #[serde(default)]
    pub hnsw: CapabilityHnsw,
}

/// Live recall-mode tag (P1 honesty patch). Reflects the *runtime*
/// state of the embedder + LLM, not the configured tier.
///
/// - `Hybrid` — embedder loaded; semantic + keyword blending active.
/// - `KeywordOnly` — no embedder loaded; FTS5 only.
/// - `Degraded` — embedder configured but `Embedder::load()` failed
///   (offline runner, read-only fs, missing HF token, etc.).
/// - `Disabled` — keyword-tier daemon, semantic recall not configured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecallMode {
    Hybrid,
    KeywordOnly,
    Degraded,
    Disabled,
}

/// Live reranker-mode tag (P1 honesty patch). Reflects the *runtime*
/// `CrossEncoder` enum variant, not the configured `cross_encoder` flag.
///
/// - `Neural` — `CrossEncoder::Neural` loaded successfully.
/// - `LexicalFallback` — `cross_encoder` was requested but neural model
///   download or load failed; running on the lexical scorer.
/// - `Off` — no reranker handle in the daemon (non-autonomous tier).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RerankerMode {
    Neural,
    LexicalFallback,
    Off,
}

/// Generic "planned but not implemented" marker used by v2 capability
/// fields whose underlying subsystem is on the roadmap but not in this
/// build. Operators reading the JSON can distinguish "disabled but
/// available" from "not in this build" by inspecting `planned`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlannedFeature {
    /// `true` when the feature exists only on the roadmap.
    pub planned: bool,
    /// Earliest release that is expected to ship the feature, e.g.
    /// `"v0.7+"` or `"v0.8+"`. Free-form string; clients should treat
    /// it as advisory.
    pub version: String,
    /// `true` only when the feature is built **and** turned on in this
    /// daemon. Always `false` when `planned == true`.
    pub enabled: bool,
}

impl PlannedFeature {
    /// A planned-not-yet-shipped feature. `enabled = false`.
    #[must_use]
    pub fn planned(version: &str) -> Self {
        Self {
            planned: true,
            version: version.to_string(),
            enabled: false,
        }
    }
}

/// Boolean feature flags exposed in the capabilities report.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityFeatures {
    pub keyword_search: bool,
    pub semantic_search: bool,
    pub hybrid_recall: bool,
    pub query_expansion: bool,
    pub auto_consolidation: bool,
    pub auto_tagging: bool,
    pub contradiction_analysis: bool,
    pub cross_encoder_reranking: bool,
    /// Memory-reflection (v0.7+): planned, not yet implemented.
    /// Was a `bool` before the P1 honesty patch; an object now so
    /// operators can tell "feature exists but disabled" apart from
    /// "feature not in this build".
    pub memory_reflection: PlannedFeature,
    /// v0.6.2 (S18): runtime-observed embedder state. `semantic_search`
    /// above reflects *configured* capability (derived from the tier's
    /// `embedding_model` setting). `embedder_loaded` reflects *actual*
    /// state after `Embedder::load()` attempted to materialize the
    /// `HuggingFace` model on startup. When an operator configures the
    /// `semantic` tier but the model download or mmap fails (offline
    /// runner, read-only fs, missing tokens), `semantic_search=true`
    /// would mislead. This flag exposes the truth so setup scripts can
    /// assert the daemon is actually ready for semantic recall before
    /// dispatching scenarios. Default false; populated by
    /// `handle_capabilities` when the HTTP/MCP wrapper hands in the
    /// live embedder handle.
    #[serde(default)]
    pub embedder_loaded: bool,
    /// v0.6.3.1 (P1 honesty patch): runtime recall-mode tag. Reflects
    /// the live embedder + LLM availability, not the configured tier.
    /// See [`RecallMode`].
    #[serde(default = "default_recall_mode")]
    pub recall_mode_active: RecallMode,
    /// v0.6.3.1 (P1 honesty patch): runtime reranker-mode tag.
    /// Reflects the live `CrossEncoder` variant. See [`RerankerMode`].
    #[serde(default = "default_reranker_mode")]
    pub reranker_active: RerankerMode,
}

fn default_recall_mode() -> RecallMode {
    RecallMode::Disabled
}

fn default_reranker_mode() -> RerankerMode {
    RerankerMode::Off
}

/// Model identifiers exposed in the capabilities report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityModels {
    pub embedding: String,
    pub embedding_dim: usize,
    pub llm: String,
    pub cross_encoder: String,
}

/// Permissions block (capabilities schema v2). Pre-P4 reports a live
/// count of namespace standards carrying a `metadata.governance` policy;
/// the full enforcement gate lands in P4. The honesty patch (P1)
/// renames the mode from `"ask"` (which implied an interactive prompt
/// loop) to `"advisory"` (governance metadata is recorded but not
/// enforced).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CapabilityPermissions {
    /// Enforcement mode. `"advisory"` until P4 ships the gate.
    pub mode: String,
    /// Number of namespace standards whose `metadata.governance` is
    /// non-null. Counts policies, not memories.
    pub active_rules: usize,
    // P1 honesty patch: `rule_summary` was always empty — no per-rule
    // serializer existed. Dropped from the v2 wire schema.
    /// v0.6.3.1 (P4, audit G1): governance-inheritance posture.
    /// `"enforced"` = `resolve_governance_policy` walks the namespace
    /// chain leaf-first and returns the most-specific policy (with
    /// `inherit: false` short-circuiting). Pre-v0.6.3.1 was
    /// `"display_only"` — the UI surfaced the chain but the gate
    /// consulted only the leaf, leaving children of governed parents
    /// completely ungoverned. The field is `Option<String>` so older
    /// capabilities responses (without the field) round-trip cleanly
    /// via `#[serde(default)]`.
    #[serde(default)]
    pub inheritance: Option<String>,
}

/// Hook-pipeline block (capabilities schema v2). Pre-v0.7 reports webhook
/// subscriptions as the closest analogue. The full hook pipeline lands in
/// v0.7 Bucket 0 (arch-enhancement-spec §2).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityHooks {
    /// Number of registered hook subscribers (proxy: webhook subscriptions).
    pub registered_count: usize,
    // P1 honesty patch: `by_event` was always an empty map — no event
    // registry exists. Dropped from the v2 wire schema.
    /// v0.6.3.1 P5 (G9): canonical list of webhook event types the
    /// daemon emits. Integrators pin the `subscribe(event_types: …)`
    /// filter against these strings. Always populated so downstream
    /// callers do not have to handle a missing field.
    #[serde(default = "default_webhook_events")]
    pub webhook_events: Vec<String>,
}

impl Default for CapabilityHooks {
    fn default() -> Self {
        Self {
            registered_count: 0,
            webhook_events: default_webhook_events(),
        }
    }
}

/// Default webhook events list — kept in sync with
/// `crate::subscriptions::WEBHOOK_EVENT_TYPES`. The constant lives in
/// `subscriptions.rs` (the surface that uses it at runtime); this
/// helper exists so `serde(default = …)` and `CapabilityHooks::default`
/// can fill the field without a cross-module dep on `subscriptions`.
fn default_webhook_events() -> Vec<String> {
    vec![
        "memory_store".to_string(),
        "memory_promote".to_string(),
        "memory_delete".to_string(),
        "memory_link_created".to_string(),
        "memory_consolidated".to_string(),
    ]
}

/// Compaction block (capabilities schema v2). v0.8 Pillar 2.5 work —
/// reports `{planned, version, enabled}` plus optional run stats. The
/// honesty patch (P1) replaced the bare `enabled: false` with the
/// planned-feature shape so operators can distinguish "feature exists
/// but disabled" from "feature not in this build".
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityCompaction {
    /// Planned-feature marker. `planned = true` while compaction lives
    /// only on the roadmap. When the subsystem ships the daemon will
    /// flip `planned = false` and `enabled` will reflect runtime state.
    #[serde(flatten)]
    pub status: PlannedFeature,
    /// Once shipped: scheduled compaction interval in minutes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_minutes: Option<u64>,
    /// Once shipped: timestamp of the most recent compaction run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_run_at: Option<String>,
    /// Once shipped: arbitrary JSON describing the most recent run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_run_stats: Option<serde_json::Value>,
}

impl CapabilityCompaction {
    /// Pre-v0.8 zero-state: planned, not enabled.
    #[must_use]
    pub fn planned() -> Self {
        Self {
            status: PlannedFeature::planned("v0.8+"),
            interval_minutes: None,
            last_run_at: None,
            last_run_stats: None,
        }
    }
}

impl Default for CapabilityCompaction {
    fn default() -> Self {
        Self::planned()
    }
}

/// Approval-API block (capabilities schema v2). `pending_requests`
/// counts the existing `pending_actions` table (live signal).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CapabilityApproval {
    /// Live count of `pending_actions` with status='pending'.
    pub pending_requests: usize,
    // P1 honesty patch: `subscribers` (no subscription API exists) and
    // `default_timeout_seconds` (no sweeper enforces timeouts) dropped
    // from the v2 wire schema.
}

/// Sidechain-transcript block (capabilities schema v2). v0.7 Bucket 1.7
/// work — reports `{planned, version, enabled}` until the subsystem
/// ships. The honesty patch (P1) replaced the bare `enabled: false`
/// with the planned-feature shape.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityTranscripts {
    /// Planned-feature marker. `planned = true` while sidechain
    /// transcripts live only on the roadmap.
    #[serde(flatten)]
    pub status: PlannedFeature,
    /// Once shipped: number of stored transcripts.
    #[serde(default, skip_serializing_if = "is_zero_usize")]
    pub total_count: usize,
    /// Once shipped: total transcript storage in megabytes.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub total_size_mb: u64,
}

impl CapabilityTranscripts {
    /// Pre-v0.7 zero-state: planned, not enabled.
    #[must_use]
    pub fn planned() -> Self {
        Self {
            status: PlannedFeature::planned("v0.7+"),
            total_count: 0,
            total_size_mb: 0,
        }
    }
}

impl Default for CapabilityTranscripts {
    fn default() -> Self {
        Self::planned()
    }
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero_usize(n: &usize) -> bool {
    *n == 0
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero_u64(n: &u64) -> bool {
    *n == 0
}

/// HNSW vector-index health (capabilities schema v2, v0.6.3.1 P3).
///
/// Closes the G2 audit gap by surfacing both the cumulative oldest-eviction
/// count and a rolling-window flag so operators can distinguish "this
/// process has hit the cap once, long ago" from "we are currently
/// sustained at the cap and shedding embeddings now". Both numbers are
/// process-local — the index itself resets on restart so persistence
/// would be misleading.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CapabilityHnsw {
    /// Cumulative count of vectors evicted by the `MAX_ENTRIES`-cap path
    /// since this process started.
    pub evictions_total: u64,
    /// True when at least one eviction has occurred in the last 60 s.
    /// Lets dashboards alert on *active* pressure rather than only the
    /// historical counter.
    pub evicted_recently: bool,
}

// ---------------------------------------------------------------------------
// Capabilities v1 — legacy shape retained for backward compat
// ---------------------------------------------------------------------------

/// Legacy (v1) capabilities shape — the structure shipped before the
/// v0.6.3.1 honesty patch. Returned only when a client opts in via
/// `Accept-Capabilities: v1` (HTTP) or the MCP `accept` argument set
/// to `"v1"`. Default response is v2.
///
/// The v1 schema is frozen — do not extend it. New fields go into v2
/// (see [`Capabilities`]).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilitiesV1 {
    pub tier: String,
    pub version: String,
    pub features: CapabilityFeaturesV1,
    pub models: CapabilityModels,
}

/// Legacy v1 feature-flag block. Notably, `memory_reflection` is a
/// `bool` here (it became a `PlannedFeature` object in v2).
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityFeaturesV1 {
    pub keyword_search: bool,
    pub semantic_search: bool,
    pub hybrid_recall: bool,
    pub query_expansion: bool,
    pub auto_consolidation: bool,
    pub auto_tagging: bool,
    pub contradiction_analysis: bool,
    pub cross_encoder_reranking: bool,
    pub memory_reflection: bool,
    #[serde(default)]
    pub embedder_loaded: bool,
}

impl Capabilities {
    /// Project the v2 report down to the legacy v1 shape. Used to
    /// honour `Accept-Capabilities: v1` from older clients.
    ///
    /// `memory_reflection` collapses from `{planned, enabled}` to a
    /// single bool (`enabled` value). All v2-only fields
    /// (`recall_mode_active`, `reranker_active`, `permissions`,
    /// `hooks`, `compaction`, `approval`, `transcripts`) are dropped.
    #[must_use]
    pub fn to_v1(&self) -> CapabilitiesV1 {
        CapabilitiesV1 {
            tier: self.tier.clone(),
            version: self.version.clone(),
            features: CapabilityFeaturesV1 {
                keyword_search: self.features.keyword_search,
                semantic_search: self.features.semantic_search,
                hybrid_recall: self.features.hybrid_recall,
                query_expansion: self.features.query_expansion,
                auto_consolidation: self.features.auto_consolidation,
                auto_tagging: self.features.auto_tagging,
                contradiction_analysis: self.features.contradiction_analysis,
                cross_encoder_reranking: self.features.cross_encoder_reranking,
                memory_reflection: self.features.memory_reflection.enabled,
                embedder_loaded: self.features.embedder_loaded,
            },
            models: self.models.clone(),
        }
    }
}

// ---------------------------------------------------------------------------
// TTL configuration
// ---------------------------------------------------------------------------

/// Per-tier TTL overrides loaded from `[ttl]` section of config.toml.
#[allow(clippy::struct_field_names)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TtlConfig {
    /// Short-tier default TTL in seconds (default: 21600 = 6 hours)
    pub short_ttl_secs: Option<i64>,
    /// Mid-tier default TTL in seconds (default: 604800 = 7 days)
    pub mid_ttl_secs: Option<i64>,
    /// Long-tier TTL in seconds (default: none = never expires). Set >0 to add expiry.
    pub long_ttl_secs: Option<i64>,
    /// Short-tier TTL extension on access in seconds (default: 3600 = 1 hour)
    pub short_extend_secs: Option<i64>,
    /// Mid-tier TTL extension on access in seconds (default: 86400 = 1 day)
    pub mid_extend_secs: Option<i64>,
}

/// Resolved TTL values after merging config overrides with compiled defaults.
#[derive(Debug, Clone)]
#[allow(clippy::struct_field_names)]
pub struct ResolvedTtl {
    pub short_ttl_secs: Option<i64>,
    pub mid_ttl_secs: Option<i64>,
    pub long_ttl_secs: Option<i64>,
    pub short_extend_secs: i64,
    pub mid_extend_secs: i64,
}

impl Default for ResolvedTtl {
    fn default() -> Self {
        Self {
            short_ttl_secs: Tier::Short.default_ttl_secs(),
            mid_ttl_secs: Tier::Mid.default_ttl_secs(),
            long_ttl_secs: Tier::Long.default_ttl_secs(),
            short_extend_secs: crate::models::SHORT_TTL_EXTEND_SECS,
            mid_extend_secs: crate::models::MID_TTL_EXTEND_SECS,
        }
    }
}

/// Maximum configurable TTL: 10 years in seconds. Prevents integer overflow
/// when adding Duration to `Utc::now()`.
const MAX_TTL_SECS: i64 = 315_360_000;

#[allow(dead_code)]
impl ResolvedTtl {
    /// Build from optional config overrides, falling back to compiled defaults.
    /// TTL values are clamped to `MAX_TTL_SECS` (10 years) to prevent overflow.
    /// Extension values are clamped to non-negative.
    pub fn from_config(cfg: Option<&TtlConfig>) -> Self {
        let defaults = Self::default();
        let Some(c) = cfg else {
            return defaults;
        };
        let clamp_ttl = |v: i64| -> Option<i64> {
            if v <= 0 {
                None
            } else {
                Some(v.min(MAX_TTL_SECS))
            }
        };
        Self {
            short_ttl_secs: c.short_ttl_secs.map_or(defaults.short_ttl_secs, clamp_ttl),
            mid_ttl_secs: c.mid_ttl_secs.map_or(defaults.mid_ttl_secs, clamp_ttl),
            long_ttl_secs: c.long_ttl_secs.map_or(defaults.long_ttl_secs, clamp_ttl),
            short_extend_secs: c
                .short_extend_secs
                .unwrap_or(defaults.short_extend_secs)
                .max(0),
            mid_extend_secs: c.mid_extend_secs.unwrap_or(defaults.mid_extend_secs).max(0),
        }
    }

    /// Get the default TTL for a given tier.
    pub fn ttl_for_tier(&self, tier: &Tier) -> Option<i64> {
        match tier {
            Tier::Short => self.short_ttl_secs,
            Tier::Mid => self.mid_ttl_secs,
            Tier::Long => self.long_ttl_secs,
        }
    }

    /// Get the TTL extension on access for a given tier.
    pub fn extend_for_tier(&self, tier: &Tier) -> Option<i64> {
        match tier {
            Tier::Short => Some(self.short_extend_secs),
            Tier::Mid => Some(self.mid_extend_secs),
            Tier::Long => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Recall scoring (time-decay half-life) — v0.6.0.0
// ---------------------------------------------------------------------------

/// Per-tier half-life (days) overrides loaded from `[scoring]` section of
/// `config.toml`.
///
/// The half-life is the number of days it takes for a memory's recall score
/// to drop to 50% of its undecayed value. Shorter half-lives prioritize fresh
/// memories; longer half-lives give older memories more weight. Defaults are
/// chosen so each tier's decay curve matches its retention expectations:
/// `short` memories decay quickly (7 d), `mid` moderately (30 d), `long`
/// slowly (365 d).
///
/// Setting `legacy_scoring = true` disables the decay multiplier entirely,
/// restoring the pre-v0.6.0.0 blended-score behavior for A/B comparison or
/// if a recall-quality regression is reported.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RecallScoringConfig {
    /// Half-life for `short`-tier memories, in days (default 7).
    pub half_life_days_short: Option<f64>,
    /// Half-life for `mid`-tier memories, in days (default 30).
    pub half_life_days_mid: Option<f64>,
    /// Half-life for `long`-tier memories, in days (default 365).
    pub half_life_days_long: Option<f64>,
    /// When true, skip the decay multiplier entirely. Default false.
    #[serde(default)]
    pub legacy_scoring: bool,
}

/// Resolved scoring values after merging config overrides with compiled
/// defaults. Half-lives are clamped to the range `[0.1, 36_500.0]` days
/// (≈100 years) to keep the decay math well-behaved.
#[derive(Debug, Clone, Copy)]
pub struct ResolvedScoring {
    pub half_life_days_short: f64,
    pub half_life_days_mid: f64,
    pub half_life_days_long: f64,
    pub legacy_scoring: bool,
}

impl Default for ResolvedScoring {
    fn default() -> Self {
        Self {
            half_life_days_short: 7.0,
            half_life_days_mid: 30.0,
            half_life_days_long: 365.0,
            legacy_scoring: false,
        }
    }
}

impl ResolvedScoring {
    const MIN_HALF_LIFE: f64 = 0.1;
    const MAX_HALF_LIFE: f64 = 36_500.0;

    /// Build from optional config overrides, falling back to compiled
    /// defaults. Out-of-range values are silently clamped.
    pub fn from_config(cfg: Option<&RecallScoringConfig>) -> Self {
        let defaults = Self::default();
        let Some(c) = cfg else {
            return defaults;
        };
        let clamp = |v: f64| -> f64 { v.clamp(Self::MIN_HALF_LIFE, Self::MAX_HALF_LIFE) };
        Self {
            half_life_days_short: c
                .half_life_days_short
                .map_or(defaults.half_life_days_short, clamp),
            half_life_days_mid: c
                .half_life_days_mid
                .map_or(defaults.half_life_days_mid, clamp),
            half_life_days_long: c
                .half_life_days_long
                .map_or(defaults.half_life_days_long, clamp),
            legacy_scoring: c.legacy_scoring,
        }
    }

    /// Half-life in days for a given tier.
    pub fn half_life_for_tier(&self, tier: &Tier) -> f64 {
        match tier {
            Tier::Short => self.half_life_days_short,
            Tier::Mid => self.half_life_days_mid,
            Tier::Long => self.half_life_days_long,
        }
    }

    /// Compute the decay multiplier `exp(-ln(2) * age_days / half_life)`
    /// for a memory of the given tier and age. Returns `1.0` when
    /// `legacy_scoring` is true (no decay) or when `age_days` is non-positive
    /// (future timestamps, clock skew, or new memories).
    #[must_use]
    pub fn decay_multiplier(&self, tier: &Tier, age_days: f64) -> f64 {
        if self.legacy_scoring || age_days <= 0.0 {
            return 1.0;
        }
        let half_life = self.half_life_for_tier(tier);
        (-std::f64::consts::LN_2 * age_days / half_life).exp()
    }
}

// ---------------------------------------------------------------------------
// Persistent config file (~/.config/ai-memory/config.toml)
// ---------------------------------------------------------------------------

const CONFIG_DIR: &str = ".config/ai-memory";
const CONFIG_FILE: &str = "config.toml";

/// Persistent configuration loaded from `~/.config/ai-memory/config.toml`.
///
/// All fields are optional — CLI flags override file values, which override
/// compiled defaults.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AppConfig {
    /// Feature tier: keyword, semantic, smart, autonomous
    pub tier: Option<String>,
    /// Path to the `SQLite` database file
    pub db: Option<String>,
    /// Ollama base URL for LLM generation (default: <http://localhost:11434>)
    pub ollama_url: Option<String>,
    /// Separate URL for embedding model (defaults to `ollama_url` if unset)
    pub embed_url: Option<String>,
    /// Embedding model override: `mini_lm_l6_v2` or `nomic_embed_v15`
    pub embedding_model: Option<String>,
    /// LLM model override (Ollama tag, e.g. "gemma4:e2b")
    pub llm_model: Option<String>,
    /// Enable cross-encoder reranking (true/false)
    pub cross_encoder: Option<bool>,
    /// Default namespace for new memories
    pub default_namespace: Option<String>,
    /// Maximum memory budget in MB (used for auto tier selection)
    pub max_memory_mb: Option<usize>,
    /// Per-tier TTL overrides
    pub ttl: Option<TtlConfig>,
    /// Archive memories before GC deletion (default: true)
    pub archive_on_gc: Option<bool>,
    /// Optional API key for HTTP API authentication
    pub api_key: Option<String>,
    /// Maximum archive age in days for automatic purge during GC (default: disabled)
    pub archive_max_days: Option<i64>,
    /// Identity-resolution overrides (Task 1.2 follow-up #198).
    pub identity: Option<IdentityConfig>,
    /// Recall scoring — per-tier half-life for time-decay, and `legacy_scoring`
    /// kill switch (v0.6.0.0).
    pub scoring: Option<RecallScoringConfig>,
    /// v0.6.0.0: when true, fire LLM autonomy hooks (`auto_tag` +
    /// `detect_contradiction`) synchronously on every successful
    /// `memory_store`. Off by default — the hook blocks store latency
    /// behind an Ollama round-trip. `AI_MEMORY_AUTONOMOUS_HOOKS=1`
    /// env var overrides the config file.
    pub autonomous_hooks: Option<bool>,
    /// v0.6.3.1 (PR-5 / issue #487) — operational logging facility.
    /// Default-OFF for privacy; opt-in turns on the rolling file
    /// appender that captures every `tracing::*` call site to disk.
    pub logging: Option<LoggingConfig>,
    /// v0.6.3.1 (PR-5 / issue #487) — security audit trail. Default-OFF
    /// for privacy; opt-in emits a hash-chained, tamper-evident JSON
    /// log of every memory mutation suitable for SIEM ingestion and
    /// SOC2 / HIPAA / GDPR / FedRAMP compliance evidence.
    pub audit: Option<AuditConfig>,
    /// v0.6.3.1 (PR-9h / issue #487 PR #497 req #73) — boot privacy
    /// kill-switch. Default-ON (existing users see no behavior change);
    /// `[boot] enabled = false` silences boot entirely (empty stdout +
    /// empty stderr, exit 0) for privacy-sensitive hosts where memory
    /// titles must not enter CI logs. `[boot] redact_titles = true`
    /// keeps the manifest header but replaces row titles with
    /// `<redacted>` for compliance contexts that need the audit-trail
    /// signal of "boot ran with N memories" without exposing subjects.
    pub boot: Option<BootConfig>,
    /// v0.6.4 — MCP server tunables. Today this only carries `profile`
    /// (the named tool surface). Future v0.6.4 phases add the
    /// `[mcp.allowlist]` per-agent capability table (Track D —
    /// v0.6.4-008).
    pub mcp: Option<McpConfig>,
}

// ---------------------------------------------------------------------------
// Logging facility (PR-5)
// ---------------------------------------------------------------------------

/// `[logging]` block in `config.toml`. Every field is `Option`; missing
/// fields fall back to the documented defaults.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Master toggle. Default `false`.
    pub enabled: Option<bool>,
    /// Directory for rotated logs. Default `~/.local/state/ai-memory/logs/`.
    pub path: Option<String>,
    /// Soft cap on a single rotated file (advisory — informs rotation
    /// configuration; the appender enforces this via the chosen
    /// `rotation` cadence). Default 100.
    pub max_size_mb: Option<u64>,
    /// Maximum number of rotated files retained on disk. Default 30.
    pub max_files: Option<usize>,
    /// Days of log history to keep before `ai-memory logs archive`
    /// would compress them. Default 90.
    pub retention_days: Option<u32>,
    /// Emit JSON lines instead of the human-readable fmt layer. Default `false`.
    pub structured: Option<bool>,
    /// Tracing level / `EnvFilter` directive. Default `"info"`.
    pub level: Option<String>,
    /// Rotation policy: `minutely | hourly | daily | never`. Default `"daily"`.
    pub rotation: Option<String>,
    /// Override the rotated-file prefix. Default `"ai-memory.log"`.
    pub filename_prefix: Option<String>,
}

// ---------------------------------------------------------------------------
// Audit facility (PR-5)
// ---------------------------------------------------------------------------

/// `[audit]` block in `config.toml`. Drives the hash-chained audit
/// trail emitted from every memory mutation call site.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditConfig {
    /// Master toggle. Default `false`.
    pub enabled: Option<bool>,
    /// Audit log path. Either a directory (in which case `audit.log`
    /// is appended) or an explicit file path. Default
    /// `~/.local/state/ai-memory/audit/`.
    pub path: Option<String>,
    /// Documented schema version on the wire. The binary always emits
    /// `audit::SCHEMA_VERSION`; this knob is reserved for forward
    /// compatibility and must equal the binary's emitted version
    /// today (validated at init).
    pub schema_version: Option<u32>,
    /// Whether to redact `memory.content` from emitted events. **The
    /// only supported value in v1 is `true`** — the audit schema does
    /// not expose a content field at all; this flag is reserved for a
    /// future per-namespace exception API.
    pub redact_content: Option<bool>,
    /// Whether to compute and verify the per-line hash chain. Default `true`.
    pub hash_chain: Option<bool>,
    /// Cadence in minutes for the periodic `CHECKPOINT.sig`
    /// attestation marker. The marker is a synthetic audit event that
    /// pins the chain head into the log so an attacker who truncates
    /// the file can't silently rewind history. Default 60. 0 disables.
    pub attestation_cadence_minutes: Option<u32>,
    /// Apply the platform-appropriate "append-only" file flag at
    /// startup. Best-effort defense in depth; the chain is the
    /// load-bearing tamper-evidence. Default `true`.
    pub append_only: Option<bool>,
    /// Retention horizon (days). `ai-memory logs purge` warns about
    /// deleting audit records younger than this, and `audit verify`
    /// surfaces gaps when retention is shorter than the chain extent.
    /// Default 90. Compliance presets override.
    pub retention_days: Option<u32>,
    /// Compliance presets — apply industry-standard retention /
    /// redaction policy on top of the base config. See
    /// `docs/security/audit-trail.md` §Compliance.
    pub compliance: Option<AuditComplianceConfig>,
}

impl AuditConfig {
    /// Resolve the effective retention horizon after applying any
    /// active compliance preset. Presets win when `applied = true`;
    /// when multiple presets are applied the most-conservative
    /// (longest) retention wins so the binary never picks a value
    /// that violates any active policy.
    #[must_use]
    pub fn effective_retention_days(&self) -> u32 {
        let mut chosen = self.retention_days.unwrap_or(90);
        if let Some(comp) = &self.compliance {
            for preset in comp.applied_presets() {
                if let Some(d) = preset.retention_days
                    && d > chosen
                {
                    chosen = d;
                }
            }
        }
        chosen
    }

    /// Resolve the effective attestation cadence — the most-frequent
    /// (smallest non-zero) cadence across the base config and applied
    /// presets so the strictest compliance rule wins.
    #[must_use]
    pub fn effective_attestation_cadence_minutes(&self) -> u32 {
        let base = self.attestation_cadence_minutes.unwrap_or(60);
        let mut chosen = base;
        if let Some(comp) = &self.compliance {
            for preset in comp.applied_presets() {
                if let Some(m) = preset.attestation_cadence_minutes
                    && m > 0
                    && (chosen == 0 || m < chosen)
                {
                    chosen = m;
                }
            }
        }
        chosen
    }
}

// ---------------------------------------------------------------------------
// Boot privacy controls (PR-9h, v0.6.3.1, issue #487 PR #497 req #73)
// ---------------------------------------------------------------------------

/// `[boot]` block in `config.toml`. Drives the privacy kill-switch +
/// title-redaction behaviour of `ai-memory boot`. Both fields default
/// to the historical (pre-v0.6.3.1) behaviour so existing users see no
/// change.
///
/// Precedence for `enabled`:
///   `AI_MEMORY_BOOT_ENABLED=0` env var (truthy "0/false/no/off") >
///   `[boot] enabled` config value > compiled default `true`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BootConfig {
    /// Master toggle. Default `true`. When set to `false`, `ai-memory
    /// boot` exits 0 with **empty stdout AND empty stderr** — the
    /// privacy-sensitive escape hatch for hosts where memory titles
    /// must never enter CI logs. The hook injects nothing.
    pub enabled: Option<bool>,
    /// When `true`, the manifest header still appears but every
    /// memory row's `title` field is replaced with `<redacted>` —
    /// useful for compliance contexts that need an audit trail of
    /// "boot ran with N memories" without exposing memory subjects.
    /// Default `false`.
    pub redact_titles: Option<bool>,
}

impl BootConfig {
    /// Resolve the effective `enabled` value with env-var precedence.
    /// `AI_MEMORY_BOOT_ENABLED=0/false/no/off` forces disabled;
    /// `=1/true/yes/on` forces enabled. Anything else falls through to
    /// the config file value (or the compiled default `true`).
    #[must_use]
    pub fn effective_enabled(&self) -> bool {
        if let Ok(v) = std::env::var("AI_MEMORY_BOOT_ENABLED") {
            let v = v.trim().to_ascii_lowercase();
            if matches!(v.as_str(), "0" | "false" | "no" | "off") {
                return false;
            }
            if matches!(v.as_str(), "1" | "true" | "yes" | "on") {
                return true;
            }
        }
        self.enabled.unwrap_or(true)
    }

    /// Resolve the effective `redact_titles` value. Default `false`.
    #[must_use]
    pub fn effective_redact_titles(&self) -> bool {
        self.redact_titles.unwrap_or(false)
    }
}

// ---------------------------------------------------------------------------
// MCP server tunables (v0.6.4)
// ---------------------------------------------------------------------------

/// `[mcp]` block in `config.toml` — v0.6.4 addition. Today this only
/// carries the named tool `profile`. v0.6.4 Track D will extend with
/// `[mcp.allowlist]` for per-agent capability gating.
///
/// Resolution for `profile`: CLI flag > `AI_MEMORY_PROFILE` env (both
/// merged by clap) > this config field > compiled default `"core"`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpConfig {
    /// Named tool profile. One of `core`, `graph`, `admin`, `power`,
    /// `full`, or a comma-separated custom list (e.g.,
    /// `core,graph,archive`). Default `core` (v0.6.4 default flip).
    pub profile: Option<String>,

    /// v0.6.4-008 — per-agent capability allowlist. Maps an agent_id
    /// pattern to the families that agent may request via
    /// `memory_capabilities --include-schema family=<f>`. Patterns
    /// resolve to a Vec<String> (the family names). The wildcard
    /// pattern `"*"` is the default for agents not otherwise listed.
    /// When the entire allowlist is absent (`mcp.allowlist = None`),
    /// the gate is disabled — every caller may expand any family
    /// (Tier-1 single-process semantics, profile flag rules).
    ///
    /// Example config.toml:
    /// ```toml
    /// [mcp.allowlist]
    /// "alice" = ["core", "graph"]
    /// "bob"   = ["full"]
    /// "*"     = ["core"]
    /// ```
    pub allowlist: Option<std::collections::HashMap<String, Vec<String>>>,
}

impl McpConfig {
    /// v0.6.4-008 — resolve the allowlist decision for an agent
    /// requesting a family.
    ///
    /// Returns:
    /// - `AllowlistDecision::Disabled` if the entire allowlist is
    ///   absent (Tier-1 default — gate is off).
    /// - `AllowlistDecision::Allow` if a matching pattern includes
    ///   the requested family (or `"full"`).
    /// - `AllowlistDecision::Deny` if a pattern matches but does
    ///   not list the family.
    /// - `AllowlistDecision::Deny` if no pattern matches and there
    ///   is no `"*"` wildcard.
    ///
    /// Pattern matching: exact match wins; otherwise the wildcard
    /// `"*"` is consulted. Multiple-pattern precedence follows
    /// longest-prefix order with stable tie-break by config order
    /// (since `HashMap` is unordered, we sort by key length
    /// descending for the comparison).
    #[must_use]
    pub fn allowlist_decision(&self, agent_id: Option<&str>, family: &str) -> AllowlistDecision {
        let table = match self.allowlist.as_ref() {
            Some(t) if !t.is_empty() => t,
            _ => return AllowlistDecision::Disabled,
        };
        // Tier-1: no agent_id → only the wildcard rule applies. Same
        // restrictive default as for an unknown agent.
        let aid = agent_id.unwrap_or("");
        // Exact match first.
        if let Some(families) = table.get(aid) {
            return decide(families, family);
        }
        // Longest-prefix match next (excluding `"*"`).
        let mut keys: Vec<&String> = table
            .keys()
            .filter(|k| k.as_str() != "*" && aid.starts_with(k.as_str()))
            .collect();
        keys.sort_by_key(|k| std::cmp::Reverse(k.len()));
        if let Some(k) = keys.first() {
            if let Some(families) = table.get(*k) {
                return decide(families, family);
            }
        }
        // Wildcard fallback.
        if let Some(families) = table.get("*") {
            return decide(families, family);
        }
        AllowlistDecision::Deny
    }
}

fn decide(families: &[String], requested: &str) -> AllowlistDecision {
    if families.iter().any(|f| f == "full" || f == requested) {
        AllowlistDecision::Allow
    } else {
        AllowlistDecision::Deny
    }
}

/// v0.6.4-008 — outcome of an allowlist check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AllowlistDecision {
    /// Allowlist is not configured; no gate.
    Disabled,
    /// Pattern match grants access to the requested family.
    Allow,
    /// Pattern match denies (or no pattern matched).
    Deny,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditComplianceConfig {
    pub soc2: Option<CompliancePreset>,
    pub hipaa: Option<CompliancePreset>,
    pub gdpr: Option<CompliancePreset>,
    pub fedramp: Option<CompliancePreset>,
}

impl AuditComplianceConfig {
    /// Iterate over every preset whose `applied = true`.
    pub fn applied_presets(&self) -> impl Iterator<Item = &CompliancePreset> {
        [
            self.soc2.as_ref(),
            self.hipaa.as_ref(),
            self.gdpr.as_ref(),
            self.fedramp.as_ref(),
        ]
        .into_iter()
        .flatten()
        .filter(|p| p.applied.unwrap_or(false))
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CompliancePreset {
    pub applied: Option<bool>,
    pub retention_days: Option<u32>,
    pub redact_content: Option<bool>,
    pub attestation_cadence_minutes: Option<u32>,
    /// Reserved for compliance contexts that mandate at-rest crypto.
    /// HIPAA preset surfaces this so operators can pair audit with
    /// `--features sqlcipher` for end-to-end at-rest encryption.
    pub encrypt_at_rest: Option<bool>,
    /// GDPR-style actor pseudonymization toggle. Reserved for v0.7+.
    pub pseudonymize_actors: Option<bool>,
}

/// Identity-resolution configuration (Task 1.2 follow-up #198).
///
/// Lets operators opt out of the default `host:<hostname>:pid-<pid>-<uuid8>`
/// fallback when no explicit `agent_id` is supplied. `anonymize_default = true`
/// swaps the hostname-revealing default for `anonymous:pid-<pid>-<uuid8>`,
/// matching what the `AI_MEMORY_ANONYMIZE=1` env var does ephemerally.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IdentityConfig {
    /// When true, the "no flag, no env, no MCP clientInfo" fallback uses
    /// `anonymous:pid-<pid>-<uuid8>` instead of the hostname-revealing
    /// `host:<hostname>:pid-<pid>-<uuid8>`. Default false.
    #[serde(default)]
    pub anonymize_default: bool,
}

impl AppConfig {
    /// Returns the config file path: `~/.config/ai-memory/config.toml`
    pub fn config_path() -> Option<PathBuf> {
        let home = std::env::var("HOME").ok()?;
        Some(Path::new(&home).join(CONFIG_DIR).join(CONFIG_FILE))
    }

    /// Load config from disk. Returns `AppConfig::default()` if file is missing.
    /// Set `AI_MEMORY_NO_CONFIG=1` to skip config loading (used by integration tests).
    pub fn load() -> Self {
        if std::env::var("AI_MEMORY_NO_CONFIG").is_ok() {
            return Self::default();
        }
        let Some(path) = Self::config_path() else {
            return Self::default();
        };
        Self::load_from(&path)
    }

    /// Load config from a specific path.
    pub fn load_from(path: &Path) -> Self {
        match std::fs::read_to_string(path) {
            Ok(contents) => match toml::from_str(&contents) {
                Ok(cfg) => {
                    eprintln!("ai-memory: loaded config from {}", path.display());
                    cfg
                }
                Err(e) => {
                    eprintln!("ai-memory: config parse error ({}): {}", path.display(), e);
                    Self::default()
                }
            },
            Err(_) => Self::default(),
        }
    }

    /// Resolve the effective feature tier from config (CLI flag overrides).
    pub fn effective_tier(&self, cli_tier: Option<&str>) -> FeatureTier {
        let tier_str = cli_tier.or(self.tier.as_deref()).unwrap_or("semantic");
        FeatureTier::from_str(tier_str).unwrap_or(FeatureTier::Semantic)
    }

    /// Resolve the effective database path (CLI flag overrides config).
    pub fn effective_db(&self, cli_db: &Path) -> PathBuf {
        // If CLI provided a non-default path, use it
        let default_db = PathBuf::from("ai-memory.db");
        if cli_db != default_db {
            return cli_db.to_path_buf();
        }
        // Otherwise check config
        self.db
            .as_ref()
            .map_or_else(|| cli_db.to_path_buf(), PathBuf::from)
    }

    /// Resolve Ollama URL for LLM generation (config or default).
    pub fn effective_ollama_url(&self) -> &str {
        self.ollama_url
            .as_deref()
            .unwrap_or("http://localhost:11434")
    }

    /// Resolve TTL configuration from config file, falling back to compiled defaults.
    pub fn effective_ttl(&self) -> ResolvedTtl {
        ResolvedTtl::from_config(self.ttl.as_ref())
    }

    /// Resolve recall-scoring configuration (time-decay half-life) from the
    /// config file, falling back to compiled defaults. v0.6.0.0.
    pub fn effective_scoring(&self) -> ResolvedScoring {
        ResolvedScoring::from_config(self.scoring.as_ref())
    }

    /// Whether to archive memories before GC deletion (default: true).
    pub fn effective_archive_on_gc(&self) -> bool {
        self.archive_on_gc.unwrap_or(true)
    }

    /// v0.6.4-001 — resolve the effective MCP tool profile.
    ///
    /// Resolution order:
    /// 1. `cli_or_env` (already merged by clap's `#[arg(env="AI_MEMORY_PROFILE")]`)
    /// 2. `[mcp].profile` config field
    /// 3. compiled default `"core"`
    ///
    /// # Errors
    ///
    /// Returns [`crate::profile::ProfileParseError`] if any layer's
    /// value is malformed (unknown family or mixed-case token).
    pub fn effective_profile(
        &self,
        cli_or_env: Option<&str>,
    ) -> Result<crate::profile::Profile, crate::profile::ProfileParseError> {
        let raw = cli_or_env
            .or_else(|| self.mcp.as_ref().and_then(|m| m.profile.as_deref()))
            .unwrap_or("core");
        crate::profile::Profile::parse(raw)
    }

    /// Whether post-store autonomy hooks (`auto_tag` + `detect_contradiction`)
    /// fire on every successful `memory_store`. v0.6.0.0.
    /// Precedence: `AI_MEMORY_AUTONOMOUS_HOOKS=1` env var (truthy) >
    /// config file > default false. `AI_MEMORY_AUTONOMOUS_HOOKS=0` also
    /// honored for explicit-off.
    pub fn effective_autonomous_hooks(&self) -> bool {
        if let Ok(v) = std::env::var("AI_MEMORY_AUTONOMOUS_HOOKS") {
            let v = v.trim().to_ascii_lowercase();
            if matches!(v.as_str(), "1" | "true" | "yes" | "on") {
                return true;
            }
            if matches!(v.as_str(), "0" | "false" | "no" | "off" | "") {
                return false;
            }
        }
        self.autonomous_hooks.unwrap_or(false)
    }

    /// Whether to anonymize the default `agent_id` fallback (Task 1.2 #198).
    /// Precedence: `AI_MEMORY_ANONYMIZE=1` env var (truthy) > config file > default false.
    pub fn effective_anonymize_default(&self) -> bool {
        if let Ok(v) = std::env::var("AI_MEMORY_ANONYMIZE") {
            let v = v.trim().to_ascii_lowercase();
            if matches!(v.as_str(), "1" | "true" | "yes" | "on") {
                return true;
            }
            if matches!(v.as_str(), "0" | "false" | "no" | "off" | "") {
                return false;
            }
        }
        self.identity.as_ref().is_some_and(|i| i.anonymize_default)
    }

    /// Resolve the [`LoggingConfig`] block, returning a default
    /// (disabled) instance when the config file omits it.
    pub fn effective_logging(&self) -> LoggingConfig {
        self.logging.clone().unwrap_or_default()
    }

    /// Resolve the [`AuditConfig`] block, returning a default
    /// (disabled) instance when the config file omits it.
    pub fn effective_audit(&self) -> AuditConfig {
        self.audit.clone().unwrap_or_default()
    }

    /// Resolve the [`BootConfig`] block, returning a default
    /// (enabled, no redaction) instance when the config file omits
    /// it. v0.6.3.1 (PR-9h / issue #487 PR #497 req #73).
    pub fn effective_boot(&self) -> BootConfig {
        self.boot.clone().unwrap_or_default()
    }

    /// Resolve URL for embedding model (falls back to `ollama_url`).
    pub fn effective_embed_url(&self) -> &str {
        self.embed_url
            .as_deref()
            .or(self.ollama_url.as_deref())
            .unwrap_or("http://localhost:11434")
    }

    /// Write a default config file if one doesn't exist yet.
    pub fn write_default_if_missing() {
        let Some(path) = Self::config_path() else {
            return;
        };
        if path.exists() {
            return;
        }
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let default_toml = r#"# ai-memory configuration
# See: https://github.com/alphaonedev/ai-memory-mcp

# Feature tier: keyword, semantic, smart, autonomous
# tier = "semantic"

# Path to SQLite database
# db = "~/.claude/ai-memory.db"

# Ollama base URL (for smart/autonomous tiers)
# ollama_url = "http://localhost:11434"

# Embedding model: mini_lm_l6_v2 (384-dim) or nomic_embed_v15 (768-dim)
# embedding_model = "mini_lm_l6_v2"

# LLM model tag for Ollama
# llm_model = "gemma4:e2b"

# Enable neural cross-encoder reranking (autonomous tier)
# cross_encoder = true

# Default namespace for new memories
# default_namespace = "global"

# Memory budget in MB (for auto tier selection)
# max_memory_mb = 4096

# Archive expired memories before GC deletion (default: true)
# archive_on_gc = true

# Per-tier TTL overrides (uncomment to customize)
# [ttl]
# short_ttl_secs = 21600        # 6 hours (default)
# mid_ttl_secs = 604800         # 7 days (default)
# long_ttl_secs = 0             # 0 = never expires (default)
# short_extend_secs = 3600      # +1h on access (default)
# mid_extend_secs = 86400       # +1d on access (default)

# v0.6.3.1 (PR-5 / issue #487) — operational logging facility.
# Default-OFF. Uncomment + set enabled = true to capture every
# `tracing::*` call site to a rotating on-disk log file. See
# `docs/security/audit-trail.md` §SIEM ingestion guide for Splunk /
# Datadog / Elastic / Loki recipes.
# [logging]
# enabled = false
# path = "~/.local/state/ai-memory/logs/"
# max_size_mb = 100
# max_files = 30
# retention_days = 90
# structured = false              # true = emit JSON lines for SIEM ingest
# level = "info"                  # tracing EnvFilter directive
# rotation = "daily"              # minutely | hourly | daily | never

# v0.6.3.1 (PR-5 / issue #487) — security audit trail. Default-OFF.
# When enabled, every memory mutation emits one hash-chained JSON
# line per event suitable for SOC2 / HIPAA / GDPR / FedRAMP evidence.
# `ai-memory audit verify` walks the chain; `ai-memory logs tail`
# streams events.
# [audit]
# enabled = false
# path = "~/.local/state/ai-memory/audit/"
# schema_version = 1
# redact_content = true            # v1 schema never emits content; reserved
# hash_chain = true
# attestation_cadence_minutes = 60
# append_only = true               # best-effort chflags(2) / FS_IOC_SETFLAGS

# Compliance presets. Set `applied = true` and the documented retention
# / cadence values override the defaults above. See
# `docs/security/audit-trail.md` §Compliance.
# [audit.compliance.soc2]
# applied = false
# retention_days = 730
# redact_content = true
# attestation_cadence_minutes = 60
#
# [audit.compliance.hipaa]
# applied = false
# retention_days = 2190
# redact_content = true
# encrypt_at_rest = true           # pair with --features sqlcipher
#
# [audit.compliance.gdpr]
# applied = false
# retention_days = 1095
# redact_content = true
# pseudonymize_actors = true       # reserved for v0.7+
#
# [audit.compliance.fedramp]
# applied = false
# retention_days = 1095
# redact_content = true
# attestation_cadence_minutes = 30

# v0.6.3.1 (PR-9h / issue #487 PR #497 req #73) — boot privacy controls.
# Default-ON (omit the section entirely for the historical pre-v0.6.3.1
# behavior). Two knobs:
#
# - `enabled = false` silences `ai-memory boot` entirely: empty stdout,
#   empty stderr, exit 0. The SessionStart hook injects nothing. Use on
#   privacy-sensitive hosts where memory titles must never enter CI
#   logs. The env var `AI_MEMORY_BOOT_ENABLED=0` takes precedence over
#   this config (same precedence pattern as PR-5's log-dir resolution).
#
# - `redact_titles = true` keeps the manifest header but replaces row
#   `title` fields with `<redacted>` — useful for compliance contexts
#   that need the audit-trail signal of "boot ran with N memories"
#   without exposing memory subjects.
# [boot]
# enabled = true
# redact_titles = false
"#;
        let _ = std::fs::write(&path, default_toml);
    }
}

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

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

    #[test]
    fn tier_roundtrip() {
        for tier in [
            FeatureTier::Keyword,
            FeatureTier::Semantic,
            FeatureTier::Smart,
            FeatureTier::Autonomous,
        ] {
            assert_eq!(FeatureTier::from_str(tier.as_str()), Some(tier));
        }
    }

    #[test]
    fn budget_selection() {
        assert_eq!(FeatureTier::from_memory_budget(0), FeatureTier::Keyword);
        assert_eq!(FeatureTier::from_memory_budget(128), FeatureTier::Keyword);
        assert_eq!(FeatureTier::from_memory_budget(256), FeatureTier::Semantic);
        assert_eq!(FeatureTier::from_memory_budget(512), FeatureTier::Semantic);
        assert_eq!(FeatureTier::from_memory_budget(1024), FeatureTier::Smart);
        assert_eq!(FeatureTier::from_memory_budget(2048), FeatureTier::Smart);
        assert_eq!(
            FeatureTier::from_memory_budget(4096),
            FeatureTier::Autonomous
        );
        assert_eq!(
            FeatureTier::from_memory_budget(8192),
            FeatureTier::Autonomous
        );
    }

    #[test]
    fn embedding_dimensions() {
        assert_eq!(EmbeddingModel::MiniLmL6V2.dim(), 384);
        assert_eq!(EmbeddingModel::NomicEmbedV15.dim(), 768);
    }

    #[test]
    fn autonomous_has_cross_encoder() {
        let cfg = FeatureTier::Autonomous.config();
        assert!(cfg.cross_encoder);
        let caps = cfg.capabilities();
        assert!(caps.features.cross_encoder_reranking);
        // P1 honesty patch: memory_reflection is a planned-feature
        // object now. Even on the autonomous tier the underlying
        // subsystem is roadmap (v0.7+), so `planned == true` and
        // `enabled == false` regardless of tier.
        assert!(caps.features.memory_reflection.planned);
        assert!(!caps.features.memory_reflection.enabled);
        assert_eq!(caps.features.memory_reflection.version, "v0.7+");
    }

    #[test]
    fn keyword_has_no_models() {
        let cfg = FeatureTier::Keyword.config();
        assert!(cfg.embedding_model.is_none());
        assert!(cfg.llm_model.is_none());
        assert!(!cfg.cross_encoder);
        assert_eq!(cfg.max_memory_mb, 0);
    }

    #[test]
    fn capabilities_serialize() {
        let caps = FeatureTier::Smart.config().capabilities();
        let json = serde_json::to_string_pretty(&caps).unwrap();
        assert!(json.contains("\"tier\": \"smart\""));
        assert!(json.contains("nomic"));
        assert!(json.contains("gemma4:e2b"));
    }

    /// v0.6.3.1 (capabilities schema v2, P1 honesty patch).
    /// Round-trip the new struct through serde_json and assert the v2
    /// honesty contract: dropped fields absent, planned-feature blocks
    /// shaped correctly, runtime-state defaults conservative.
    #[test]
    fn capabilities_v2_zero_state_round_trip() {
        let caps = FeatureTier::Keyword.config().capabilities();
        let val: serde_json::Value = serde_json::to_value(&caps).unwrap();

        assert_eq!(val["schema_version"], "2");

        // permissions zero-state: mode="advisory" (was "ask" in v1),
        // active_rules=0. `rule_summary` dropped from v2.
        assert_eq!(val["permissions"]["mode"], "advisory");
        assert_eq!(val["permissions"]["active_rules"], 0);
        assert!(
            val["permissions"].get("rule_summary").is_none(),
            "v2 honesty patch drops `permissions.rule_summary` (no per-rule serializer)"
        );
        // v0.6.3.1 (P4, audit G1): inheritance posture surfaced.
        assert_eq!(val["permissions"]["inheritance"], "enforced");

        // hooks zero-state: 0 registered. `by_event` dropped from v2.
        assert_eq!(val["hooks"]["registered_count"], 0);
        assert!(
            val["hooks"].get("by_event").is_none(),
            "v2 honesty patch drops `hooks.by_event` (no event registry)"
        );

        // hooks zero-state: 0 registered, by_event dropped (P1 honesty)
        assert_eq!(val["hooks"]["registered_count"], 0);
        assert!(
            val["hooks"].get("by_event").is_none(),
            "v2 drops hooks.by_event (no event registry)"
        );
        // P5 (G9): webhook_events must always surface the canonical
        // five lifecycle events so integrators can pin a subscribe
        // filter against them.
        let events = val["hooks"]["webhook_events"].as_array().unwrap();
        assert_eq!(events.len(), 5);
        for expected in [
            "memory_store",
            "memory_promote",
            "memory_delete",
            "memory_link_created",
            "memory_consolidated",
        ] {
            assert!(
                events.iter().any(|v| v.as_str() == Some(expected)),
                "webhook_events missing {expected}"
            );
        }

        // compaction zero-state: planned, not enabled, optional fields omitted
        assert_eq!(val["compaction"]["planned"], true);
        assert_eq!(val["compaction"]["enabled"], false);
        assert_eq!(val["compaction"]["version"], "v0.8+");
        assert!(
            val["compaction"].get("interval_minutes").is_none(),
            "Option::None values must be skipped in serialization"
        );
        assert!(val["compaction"].get("last_run_at").is_none());
        assert!(val["compaction"].get("last_run_stats").is_none());

        // approval zero-state: 0 pending. `subscribers` and
        // `default_timeout_seconds` dropped from v2.
        assert_eq!(val["approval"]["pending_requests"], 0);
        assert!(
            val["approval"].get("subscribers").is_none(),
            "v2 honesty patch drops `approval.subscribers` (no subscription API)"
        );
        assert!(
            val["approval"].get("default_timeout_seconds").is_none(),
            "v2 honesty patch drops `approval.default_timeout_seconds` (no sweeper)"
        );

        // transcripts zero-state: planned, not enabled, zero counts skipped
        assert_eq!(val["transcripts"]["planned"], true);
        assert_eq!(val["transcripts"]["enabled"], false);
        assert_eq!(val["transcripts"]["version"], "v0.7+");

        // memory_reflection: planned-feature object (was bool)
        assert_eq!(val["features"]["memory_reflection"]["planned"], true);
        assert_eq!(val["features"]["memory_reflection"]["enabled"], false);
        assert_eq!(val["features"]["memory_reflection"]["version"], "v0.7+");

        // Runtime-state defaults are conservative — they get overlaid
        // at the handler boundary based on the live embedder + reranker
        // handles. With no overlays, the keyword-tier daemon reports
        // `disabled` / `off`.
        assert_eq!(val["features"]["recall_mode_active"], "disabled");
        assert_eq!(val["features"]["reranker_active"], "off");

        // Round-trip back to a typed Capabilities and confirm field
        // identity (proves Deserialize works for all reshaped structs).
        let restored: Capabilities = serde_json::from_value(val).unwrap();
        assert_eq!(restored.schema_version, "2");
        assert_eq!(restored.permissions.mode, "advisory");
        assert!(restored.compaction.status.planned);
        assert!(restored.transcripts.status.planned);
        assert_eq!(restored.features.recall_mode_active, RecallMode::Disabled);
        assert_eq!(restored.features.reranker_active, RerankerMode::Off);
    }

    /// P1 honesty patch: legacy v1 projection preserves the old shape
    /// for clients that opt in via `Accept-Capabilities: v1`.
    #[test]
    fn capabilities_v1_projection_preserves_legacy_shape() {
        let caps = FeatureTier::Autonomous.config().capabilities();
        let v1 = caps.to_v1();
        let val: serde_json::Value = serde_json::to_value(&v1).unwrap();

        // v1: no schema_version, no v2-only blocks
        assert!(
            val.get("schema_version").is_none(),
            "v1 has no schema_version"
        );
        assert!(
            val.get("permissions").is_none(),
            "v1 has no permissions block"
        );
        assert!(val.get("hooks").is_none());
        assert!(val.get("compaction").is_none());
        assert!(val.get("approval").is_none());
        assert!(val.get("transcripts").is_none());

        // v1 keeps the four legacy top-level keys
        assert!(val["tier"].is_string());
        assert!(val["version"].is_string());
        assert!(val["features"].is_object());
        assert!(val["models"].is_object());

        // v1 features.memory_reflection collapses to a bool — autonomous
        // tier had cross_encoder + has_llm but the planned object's
        // `enabled = false`, so the v1 bool is `false`.
        assert!(val["features"]["memory_reflection"].is_boolean());
        assert_eq!(val["features"]["memory_reflection"], false);

        // v1 features carry no recall_mode_active / reranker_active
        assert!(val["features"].get("recall_mode_active").is_none());
        assert!(val["features"].get("reranker_active").is_none());
    }

    #[test]
    fn config_default_is_empty() {
        let cfg = AppConfig::default();
        assert!(cfg.tier.is_none());
        assert!(cfg.db.is_none());
        assert!(cfg.ollama_url.is_none());
    }

    #[test]
    fn config_parse_toml() {
        let toml_str = r#"
            tier = "smart"
            db = "/tmp/test.db"
            ollama_url = "http://localhost:11434"
            cross_encoder = true
        "#;
        let cfg: AppConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.tier.as_deref(), Some("smart"));
        assert_eq!(cfg.db.as_deref(), Some("/tmp/test.db"));
        assert!(cfg.cross_encoder.unwrap());
    }

    #[test]
    fn resolved_ttl_defaults_match_hardcoded() {
        let resolved = ResolvedTtl::default();
        assert_eq!(resolved.short_ttl_secs, Some(6 * 3600));
        assert_eq!(resolved.mid_ttl_secs, Some(7 * 24 * 3600));
        assert_eq!(resolved.long_ttl_secs, None);
        assert_eq!(resolved.short_extend_secs, 3600);
        assert_eq!(resolved.mid_extend_secs, 86400);
    }

    #[test]
    fn resolved_ttl_from_partial_config() {
        let cfg = TtlConfig {
            mid_ttl_secs: Some(90 * 24 * 3600), // ~3 months
            ..Default::default()
        };
        let resolved = ResolvedTtl::from_config(Some(&cfg));
        assert_eq!(resolved.short_ttl_secs, Some(6 * 3600)); // unchanged
        assert_eq!(resolved.mid_ttl_secs, Some(90 * 24 * 3600)); // overridden
        assert_eq!(resolved.long_ttl_secs, None); // unchanged
    }

    #[test]
    fn resolved_ttl_zero_means_no_expiry() {
        let cfg = TtlConfig {
            short_ttl_secs: Some(0),
            mid_ttl_secs: Some(0),
            ..Default::default()
        };
        let resolved = ResolvedTtl::from_config(Some(&cfg));
        assert_eq!(resolved.short_ttl_secs, None); // 0 → no expiry
        assert_eq!(resolved.mid_ttl_secs, None);
    }

    #[test]
    fn resolved_ttl_clamps_overflow() {
        let cfg = TtlConfig {
            mid_ttl_secs: Some(i64::MAX),
            short_extend_secs: Some(-3600),
            ..Default::default()
        };
        let resolved = ResolvedTtl::from_config(Some(&cfg));
        // i64::MAX should be clamped to MAX_TTL_SECS (10 years)
        assert_eq!(resolved.mid_ttl_secs, Some(super::MAX_TTL_SECS));
        // negative extend should be clamped to 0
        assert_eq!(resolved.short_extend_secs, 0);
    }

    #[test]
    fn ttl_config_parse_toml() {
        let toml_str = r#"
            tier = "semantic"
            archive_on_gc = false
            [ttl]
            mid_ttl_secs = 7776000
            short_extend_secs = 7200
        "#;
        let cfg: AppConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.ttl.as_ref().unwrap().mid_ttl_secs, Some(7776000));
        assert_eq!(cfg.ttl.as_ref().unwrap().short_extend_secs, Some(7200));
        assert!(!cfg.effective_archive_on_gc());
    }

    #[test]
    fn resolved_ttl_tier_methods() {
        let resolved = ResolvedTtl::default();
        assert_eq!(resolved.ttl_for_tier(&Tier::Short), Some(6 * 3600));
        assert_eq!(resolved.ttl_for_tier(&Tier::Mid), Some(7 * 24 * 3600));
        assert_eq!(resolved.ttl_for_tier(&Tier::Long), None);
        assert_eq!(resolved.extend_for_tier(&Tier::Short), Some(3600));
        assert_eq!(resolved.extend_for_tier(&Tier::Mid), Some(86400));
        assert_eq!(resolved.extend_for_tier(&Tier::Long), None);
    }

    #[test]
    fn config_effective_tier() {
        let cfg = AppConfig {
            tier: Some("smart".to_string()),
            ..Default::default()
        };
        // CLI override wins
        assert_eq!(
            cfg.effective_tier(Some("autonomous")),
            FeatureTier::Autonomous
        );
        // Config value used when no CLI
        assert_eq!(cfg.effective_tier(None), FeatureTier::Smart);
    }

    // --- v0.6.0.0 recall scoring (time-decay half-life) ---

    #[test]
    fn scoring_defaults_match_spec() {
        let s = ResolvedScoring::default();
        assert!((s.half_life_days_short - 7.0).abs() < f64::EPSILON);
        assert!((s.half_life_days_mid - 30.0).abs() < f64::EPSILON);
        assert!((s.half_life_days_long - 365.0).abs() < f64::EPSILON);
        assert!(!s.legacy_scoring);
    }

    #[test]
    fn scoring_from_config_overrides() {
        let cfg = RecallScoringConfig {
            half_life_days_short: Some(3.5),
            half_life_days_mid: Some(14.0),
            half_life_days_long: Some(730.0),
            legacy_scoring: false,
        };
        let s = ResolvedScoring::from_config(Some(&cfg));
        assert!((s.half_life_days_short - 3.5).abs() < f64::EPSILON);
        assert!((s.half_life_days_mid - 14.0).abs() < f64::EPSILON);
        assert!((s.half_life_days_long - 730.0).abs() < f64::EPSILON);
    }

    #[test]
    fn scoring_clamps_out_of_range() {
        let cfg = RecallScoringConfig {
            half_life_days_short: Some(-10.0),
            half_life_days_mid: Some(0.0),
            half_life_days_long: Some(1_000_000.0),
            legacy_scoring: false,
        };
        let s = ResolvedScoring::from_config(Some(&cfg));
        assert!(s.half_life_days_short >= ResolvedScoring::MIN_HALF_LIFE);
        assert!(s.half_life_days_mid >= ResolvedScoring::MIN_HALF_LIFE);
        assert!(s.half_life_days_long <= ResolvedScoring::MAX_HALF_LIFE);
    }

    #[test]
    fn scoring_decay_at_half_life_is_half() {
        let s = ResolvedScoring::default();
        // Short tier half-life is 7 days → at age=7d, decay=0.5
        let d = s.decay_multiplier(&Tier::Short, 7.0);
        assert!((d - 0.5).abs() < 1e-9);
        let d = s.decay_multiplier(&Tier::Mid, 30.0);
        assert!((d - 0.5).abs() < 1e-9);
        let d = s.decay_multiplier(&Tier::Long, 365.0);
        assert!((d - 0.5).abs() < 1e-9);
    }

    #[test]
    fn scoring_decay_monotonic() {
        let s = ResolvedScoring::default();
        let d_new = s.decay_multiplier(&Tier::Mid, 1.0);
        let d_old = s.decay_multiplier(&Tier::Mid, 60.0);
        // Older memories decay more (lower multiplier).
        assert!(d_new > d_old);
        assert!(d_new < 1.0);
        assert!(d_old > 0.0);
    }

    #[test]
    fn scoring_decay_zero_age_is_one() {
        let s = ResolvedScoring::default();
        assert!((s.decay_multiplier(&Tier::Short, 0.0) - 1.0).abs() < f64::EPSILON);
        // Negative ages (clock skew, future timestamps) are also treated as fresh.
        assert!((s.decay_multiplier(&Tier::Short, -5.0) - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn scoring_legacy_disables_decay() {
        let cfg = RecallScoringConfig {
            legacy_scoring: true,
            ..Default::default()
        };
        let s = ResolvedScoring::from_config(Some(&cfg));
        // No decay regardless of age.
        assert!((s.decay_multiplier(&Tier::Short, 100.0) - 1.0).abs() < f64::EPSILON);
        assert!((s.decay_multiplier(&Tier::Mid, 1000.0) - 1.0).abs() < f64::EPSILON);
        assert!((s.decay_multiplier(&Tier::Long, 10_000.0) - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn effective_scoring_on_empty_config() {
        let cfg = AppConfig::default();
        let s = cfg.effective_scoring();
        assert_eq!(s.half_life_days_short, 7.0);
        assert!(!s.legacy_scoring);
    }

    #[test]
    fn scoring_roundtrip_through_toml() {
        let toml_src = r"
[scoring]
half_life_days_short = 5.0
half_life_days_mid = 25.0
legacy_scoring = false
";
        let cfg: AppConfig = toml::from_str(toml_src).expect("parses");
        let s = cfg.effective_scoring();
        assert!((s.half_life_days_short - 5.0).abs() < f64::EPSILON);
        assert!((s.half_life_days_mid - 25.0).abs() < f64::EPSILON);
        // Unset long defaults.
        assert!((s.half_life_days_long - 365.0).abs() < f64::EPSILON);
    }

    // ---- Wave 3 (Closer T) tests for uncovered effective_* helpers
    // and write_default_if_missing. ----

    #[test]
    fn effective_tier_cli_overrides_config() {
        let cfg = AppConfig {
            tier: Some("smart".to_string()),
            ..AppConfig::default()
        };
        // CLI flag wins over config.
        assert_eq!(
            cfg.effective_tier(Some("autonomous")),
            FeatureTier::Autonomous
        );
        // No CLI flag → config used.
        assert_eq!(cfg.effective_tier(None), FeatureTier::Smart);
    }

    #[test]
    fn effective_tier_unknown_falls_back_to_semantic() {
        let cfg = AppConfig::default();
        assert_eq!(
            cfg.effective_tier(Some("invalid-tier")),
            FeatureTier::Semantic
        );
        // No CLI, no config → default semantic.
        assert_eq!(cfg.effective_tier(None), FeatureTier::Semantic);
    }

    // ---- v0.6.4-001 — `effective_profile` resolution tests.
    //
    // Resolution order: CLI/env > [mcp].profile config > "core" default.
    // Clap merges CLI and env into the same `Option<&str>` before this
    // function sees it, so the function only needs to test "explicit
    // override > config > default". Env-var precedence over CLI cannot
    // happen by design (clap precedence is CLI > env), so it is not
    // tested at this layer.

    #[test]
    fn effective_profile_cli_or_env_overrides_config() {
        let cfg = AppConfig {
            mcp: Some(McpConfig {
                profile: Some("graph".to_string()),
                allowlist: None,
            }),
            ..AppConfig::default()
        };
        // CLI/env value beats the config value.
        assert_eq!(
            cfg.effective_profile(Some("admin")).unwrap(),
            crate::profile::Profile::admin()
        );
        // No CLI/env → config used.
        assert_eq!(
            cfg.effective_profile(None).unwrap(),
            crate::profile::Profile::graph()
        );
    }

    #[test]
    fn effective_profile_falls_back_to_core_default() {
        let cfg = AppConfig::default();
        // No mcp config, no CLI → core (the v0.6.4 default flip).
        assert_eq!(
            cfg.effective_profile(None).unwrap(),
            crate::profile::Profile::core()
        );
    }

    #[test]
    fn effective_profile_surfaces_parse_error_for_unknown_family() {
        let cfg = AppConfig::default();
        assert!(matches!(
            cfg.effective_profile(Some("xyz")),
            Err(crate::profile::ProfileParseError::UnknownFamily(_))
        ));
    }

    #[test]
    fn effective_profile_surfaces_parse_error_for_mixed_case() {
        let cfg = AppConfig::default();
        assert!(matches!(
            cfg.effective_profile(Some("Core")),
            Err(crate::profile::ProfileParseError::CaseMismatch(_))
        ));
    }

    // ---- v0.6.4-008 — `[mcp.allowlist]` resolution tests.

    fn allowlist_table(rows: &[(&str, &[&str])]) -> McpConfig {
        let mut map = std::collections::HashMap::new();
        for (k, v) in rows {
            map.insert(
                (*k).to_string(),
                v.iter().map(|s| (*s).to_string()).collect(),
            );
        }
        McpConfig {
            profile: None,
            allowlist: Some(map),
        }
    }

    #[test]
    fn allowlist_disabled_when_table_absent() {
        let cfg = McpConfig::default();
        assert_eq!(
            cfg.allowlist_decision(Some("alice"), "graph"),
            AllowlistDecision::Disabled
        );
    }

    #[test]
    fn allowlist_disabled_when_table_empty() {
        let cfg = McpConfig {
            profile: None,
            allowlist: Some(std::collections::HashMap::new()),
        };
        assert_eq!(
            cfg.allowlist_decision(Some("alice"), "graph"),
            AllowlistDecision::Disabled
        );
    }

    #[test]
    fn allowlist_exact_match_grants_or_denies_per_family_set() {
        let cfg = allowlist_table(&[("alice", &["core", "graph"]), ("*", &["core"])]);
        assert_eq!(
            cfg.allowlist_decision(Some("alice"), "graph"),
            AllowlistDecision::Allow
        );
        assert_eq!(
            cfg.allowlist_decision(Some("alice"), "power"),
            AllowlistDecision::Deny
        );
    }

    #[test]
    fn allowlist_full_grants_every_family() {
        let cfg = allowlist_table(&[("bob", &["full"])]);
        assert_eq!(
            cfg.allowlist_decision(Some("bob"), "graph"),
            AllowlistDecision::Allow
        );
        assert_eq!(
            cfg.allowlist_decision(Some("bob"), "archive"),
            AllowlistDecision::Allow
        );
    }

    #[test]
    fn allowlist_wildcard_default_for_unknown_agents() {
        let cfg = allowlist_table(&[("alice", &["full"]), ("*", &["core"])]);
        assert_eq!(
            cfg.allowlist_decision(Some("eve"), "core"),
            AllowlistDecision::Allow
        );
        assert_eq!(
            cfg.allowlist_decision(Some("eve"), "graph"),
            AllowlistDecision::Deny
        );
    }

    #[test]
    fn allowlist_default_deny_when_no_wildcard() {
        let cfg = allowlist_table(&[("alice", &["full"])]);
        assert_eq!(
            cfg.allowlist_decision(Some("eve"), "core"),
            AllowlistDecision::Deny
        );
    }

    #[test]
    fn allowlist_longest_prefix_match_wins() {
        let cfg = allowlist_table(&[
            ("ai:", &["core"]),
            ("ai:claude-code", &["full"]),
            ("*", &["core"]),
        ]);
        // The longer prefix takes precedence over the shorter one.
        assert_eq!(
            cfg.allowlist_decision(Some("ai:claude-code@host"), "graph"),
            AllowlistDecision::Allow
        );
        // Shorter prefix still works for other ai:* agents.
        assert_eq!(
            cfg.allowlist_decision(Some("ai:codex@host"), "graph"),
            AllowlistDecision::Deny
        );
    }

    #[test]
    fn allowlist_no_agent_id_uses_wildcard() {
        // Tier-1 / anonymous: no agent_id provided → only the wildcard
        // rule is consulted.
        let cfg = allowlist_table(&[("alice", &["full"]), ("*", &["core"])]);
        assert_eq!(
            cfg.allowlist_decision(None, "core"),
            AllowlistDecision::Allow
        );
        assert_eq!(
            cfg.allowlist_decision(None, "graph"),
            AllowlistDecision::Deny
        );
    }

    #[test]
    fn effective_db_cli_path_wins_when_non_default() {
        let cfg = AppConfig {
            db: Some("/from/config.db".to_string()),
            ..AppConfig::default()
        };
        let cli_path = Path::new("/from/cli.db");
        assert_eq!(cfg.effective_db(cli_path), PathBuf::from("/from/cli.db"));
    }

    #[test]
    fn effective_db_falls_back_to_config_when_cli_default() {
        let cfg = AppConfig {
            db: Some("/from/config.db".to_string()),
            ..AppConfig::default()
        };
        // The CLI default is "ai-memory.db" — config wins for that case.
        assert_eq!(
            cfg.effective_db(Path::new("ai-memory.db")),
            PathBuf::from("/from/config.db")
        );
    }

    #[test]
    fn effective_db_falls_back_to_cli_when_no_config() {
        let cfg = AppConfig::default();
        let cli_path = Path::new("ai-memory.db");
        assert_eq!(cfg.effective_db(cli_path), PathBuf::from("ai-memory.db"));
    }

    #[test]
    fn effective_ollama_url_default_when_unset() {
        let cfg = AppConfig::default();
        assert_eq!(cfg.effective_ollama_url(), "http://localhost:11434");
    }

    #[test]
    fn effective_ollama_url_uses_configured_value() {
        let cfg = AppConfig {
            ollama_url: Some("http://my-host:9999".to_string()),
            ..AppConfig::default()
        };
        assert_eq!(cfg.effective_ollama_url(), "http://my-host:9999");
    }

    #[test]
    fn effective_embed_url_falls_back_to_ollama_url() {
        let cfg = AppConfig {
            ollama_url: Some("http://ollama:11434".to_string()),
            ..AppConfig::default()
        };
        // No embed_url → fall back to ollama_url.
        assert_eq!(cfg.effective_embed_url(), "http://ollama:11434");
    }

    #[test]
    fn effective_embed_url_uses_dedicated_value_when_set() {
        let cfg = AppConfig {
            ollama_url: Some("http://ollama:11434".to_string()),
            embed_url: Some("http://embed:8080".to_string()),
            ..AppConfig::default()
        };
        // Dedicated embed_url wins.
        assert_eq!(cfg.effective_embed_url(), "http://embed:8080");
    }

    #[test]
    fn effective_embed_url_uses_default_when_neither_set() {
        let cfg = AppConfig::default();
        assert_eq!(cfg.effective_embed_url(), "http://localhost:11434");
    }

    #[test]
    fn effective_archive_on_gc_default_is_true() {
        let cfg = AppConfig::default();
        assert!(cfg.effective_archive_on_gc());
    }

    #[test]
    fn effective_archive_on_gc_respects_explicit_false() {
        let cfg = AppConfig {
            archive_on_gc: Some(false),
            ..AppConfig::default()
        };
        assert!(!cfg.effective_archive_on_gc());
    }

    #[test]
    fn effective_autonomous_hooks_default_is_false() {
        // SAFETY: clear env so this test is deterministic; tests run with
        // --test-threads=1 in CI for env-based tests, but we stay
        // defensive and set+unset locally.
        // SAFETY: env mutation is acceptable here because we set then unset.
        unsafe { std::env::remove_var("AI_MEMORY_AUTONOMOUS_HOOKS") };
        let cfg = AppConfig::default();
        assert!(!cfg.effective_autonomous_hooks());
    }

    #[test]
    fn effective_autonomous_hooks_config_value_used_when_env_unset() {
        unsafe { std::env::remove_var("AI_MEMORY_AUTONOMOUS_HOOKS") };
        let cfg = AppConfig {
            autonomous_hooks: Some(true),
            ..AppConfig::default()
        };
        assert!(cfg.effective_autonomous_hooks());
    }

    #[test]
    fn effective_anonymize_default_falls_back_to_config() {
        unsafe { std::env::remove_var("AI_MEMORY_ANONYMIZE") };
        let cfg = AppConfig::default();
        assert!(!cfg.effective_anonymize_default());
    }

    #[test]
    fn write_default_if_missing_creates_file_then_noops() {
        // Use a temp dir as $HOME so we don't clobber a real config.
        let tmp = tempfile::tempdir().unwrap();
        // SAFETY: env mutation is contained; we restore at end.
        unsafe { std::env::set_var("HOME", tmp.path()) };
        // First call writes the file.
        AppConfig::write_default_if_missing();
        let expected = AppConfig::config_path().unwrap();
        assert!(expected.exists(), "config not written at {expected:?}");
        let original = std::fs::read_to_string(&expected).unwrap();
        assert!(original.contains("ai-memory configuration"));
        // Second call must NOT overwrite (idempotent).
        std::fs::write(&expected, "# user-edited\n").unwrap();
        AppConfig::write_default_if_missing();
        let after = std::fs::read_to_string(&expected).unwrap();
        assert_eq!(after, "# user-edited\n");
    }

    #[test]
    fn config_path_returns_some_when_home_set() {
        // SAFETY: env mutation contained to this test.
        unsafe { std::env::set_var("HOME", "/some/home") };
        let path = AppConfig::config_path().unwrap();
        assert!(path.starts_with("/some/home"));
    }

    #[test]
    fn load_from_returns_default_for_missing_file() {
        // Non-existent path → default config.
        let cfg = AppConfig::load_from(Path::new("/non/existent/path.toml"));
        assert!(cfg.tier.is_none());
        assert!(cfg.db.is_none());
    }

    #[test]
    fn load_from_returns_default_for_unparseable_toml() {
        // Garbage TOML → load_from prints a warning and returns default.
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp.path(), "this is not [valid toml]]]").unwrap();
        let cfg = AppConfig::load_from(tmp.path());
        assert!(cfg.tier.is_none());
    }

    #[test]
    fn load_from_parses_valid_toml() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(
            tmp.path(),
            r#"
                tier = "smart"
                db = "/disk.db"
            "#,
        )
        .unwrap();
        let cfg = AppConfig::load_from(tmp.path());
        assert_eq!(cfg.tier.as_deref(), Some("smart"));
        assert_eq!(cfg.db.as_deref(), Some("/disk.db"));
    }
}