ai-memory 0.7.0

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
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::default_metadata;

// Canonical `MemoryKind` spellings duplicated across `as_str` / `from_str`
// (#1558 batch 6).
const KIND_OBSERVATION: &str = "observation";
const KIND_REFLECTION: &str = "reflection";

/// L1-1 (v0.7.0) — typed memory-kind discriminator stored in the
/// `memories.memory_kind` column (schema v30).
///
/// `Observation` and `Reflection` exist since v0.7.0. `Persona`
/// landed in v0.7.0 QW-2 (schema v36) as the substrate-native
/// Tencent-pattern L3 persona artefact.
///
/// v0.7.x Form 6 (issue #759) — Batman taxonomy extension. The
/// `Concept | Entity | Claim | Relation | Event | Conversation |
/// Decision` variants give downstream readers a richer atom-type
/// vocabulary aligned with the Batman framework's exemplar
/// (Tolaria's frontmatter-as-type schema). All seven variants
/// serialize as snake_case strings via the existing
/// `memory_kind TEXT` column — no schema migration is required
/// because the column has no CHECK constraint. Old rows with no
/// kind read as `Observation` (the SQL `DEFAULT 'observation'`).
/// A future-schema variant a binary doesn't recognise reads as
/// `Observation` via the `unwrap_or_default()` chain in
/// `row_to_memory` (forward-compat).
///
/// `Observation` is the default for every memory created before v30 (the
/// `DEFAULT 'observation'` SQL column handles the backfill contract for
/// rows that pre-date the migration; new inserts that omit the field also
/// land at `Observation`). `Reflection` is set by the `memory_reflect`
/// write path in addition to the existing `metadata.type='reflection'`
/// back-compat marker. `Persona` is set by the QW-2
/// `PersonaGenerator` and the `memory_persona_generate` MCP tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum MemoryKind {
    /// Default — a direct observation or note from the caller.
    #[default]
    Observation,
    /// A memory synthesised by the reflection pass over lower-depth
    /// peers (set by `memory_reflect` and the curator reflection pass).
    Reflection,
    /// v0.7.0 QW-2 — Persona-as-artifact. A curator-generated
    /// Markdown profile summarising an entity, derived from a
    /// cluster of Reflection-kind memories about that entity. The
    /// `entity_id` + `persona_version` columns on `memories` are
    /// populated only for this variant.
    Persona,
    /// v0.7.x Form 6 — abstract definition / vocabulary term
    /// ("ownership is a Rust borrow-checker rule").
    Concept,
    /// v0.7.x Form 6 — named real-world thing (person, org, product,
    /// system component). Pairs with `entity_id` on the row when the
    /// caller has registered the entity in the KG.
    Entity,
    /// v0.7.x Form 6 — factual assertion the caller is recording
    /// ("the build broke at 14:32 UTC"). Distinct from
    /// `Observation` in that a `Claim` is a propositional commitment;
    /// a `Reflection` chain may agree or contradict it.
    Claim,
    /// v0.7.x Form 6 — typed pair / triple. Anchors a KG relation
    /// inside the memory substrate so an operator can query the
    /// relation set with the same recall pipeline used for free-text.
    Relation,
    /// v0.7.x Form 6 — temporally-bounded happening
    /// ("deploy at 09:00", "incident at 14:32"). Distinct from
    /// `Observation` only when the caller wants the
    /// downstream-filtering surface to separate "what I saw" from
    /// "what happened".
    Event,
    /// v0.7.x Form 6 — captured dialogue turn (the substrate also
    /// stores conversations as `Observation`-kind today; this kind
    /// makes the type explicit for callers that want to filter to
    /// just conversational atoms).
    Conversation,
    /// v0.7.x Form 6 (L1-6 reservation) — choice point with
    /// rationale. Distinct from `Reflection` in that a `Decision`
    /// commits to a course of action; reflections summarise. The
    /// L1-6 work (v0.8.0) will likely add columns for
    /// rationale / alternatives, but the variant lands now so
    /// callers can start typing decisions.
    Decision,
}

impl MemoryKind {
    /// Column-wire string (matches the SQL `DEFAULT 'observation'` value).
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Observation => KIND_OBSERVATION,
            Self::Reflection => KIND_REFLECTION,
            Self::Persona => "persona",
            Self::Concept => "concept",
            Self::Entity => "entity",
            Self::Claim => "claim",
            Self::Relation => "relation",
            Self::Event => "event",
            Self::Conversation => "conversation",
            Self::Decision => "decision",
        }
    }

    /// Parse the column-wire string. Returns `None` on unrecognised values
    /// so callers can fall back to `Observation` (forward-compat with
    /// future variants that land in a newer DB on an older binary).
    #[must_use]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            KIND_OBSERVATION => Some(Self::Observation),
            KIND_REFLECTION => Some(Self::Reflection),
            "persona" => Some(Self::Persona),
            "concept" => Some(Self::Concept),
            "entity" => Some(Self::Entity),
            "claim" => Some(Self::Claim),
            "relation" => Some(Self::Relation),
            "event" => Some(Self::Event),
            "conversation" => Some(Self::Conversation),
            "decision" => Some(Self::Decision),
            _ => None,
        }
    }

    /// Enumerate every variant in declaration order. Used by the
    /// capabilities surface (Form 6 `CapabilityMemoryKindVocab`) and
    /// by the recall filter parser when the caller passes `"all"`.
    #[must_use]
    pub fn all() -> &'static [Self] {
        &[
            Self::Observation,
            Self::Reflection,
            Self::Persona,
            Self::Concept,
            Self::Entity,
            Self::Claim,
            Self::Relation,
            Self::Event,
            Self::Conversation,
            Self::Decision,
        ]
    }

    /// v0.7.x Form 6 — parse a comma-separated list of kind names
    /// into a deduplicated `Vec<MemoryKind>`.
    ///
    /// Two distinct empty cases are intentionally preserved (Cluster E
    /// audit COR-4 — issue #767):
    ///   * Input is **empty** (whitespace-only or zero non-empty tokens
    ///     after trim) → `None`. Callers treat this as "no filter
    ///     declared, return everything".
    ///   * Input is **non-empty but every token is unrecognised** (e.g.
    ///     `"reflektion,observetion"`) → `Some(vec![])`. Callers treat
    ///     this as "an intentional filter was declared and matched
    ///     nothing", returning zero rows. Collapsing this case to
    ///     `None` (the pre-COR-4 behaviour) silently inverted a typo
    ///     into "show ALL kinds", which is the bug the v0.7.0 audit
    ///     flagged.
    ///
    /// Known tokens are deduplicated; unknown tokens are dropped
    /// silently (forward-compat — a future variant emitted by a newer
    /// client should not break recall on an older binary), but the
    /// distinction above means dropping every token does NOT collapse
    /// into "no filter".
    #[must_use]
    pub fn parse_csv(s: &str) -> Option<Vec<Self>> {
        let mut out: Vec<Self> = Vec::new();
        let mut saw_any_token = false;
        for tok in s.split(',') {
            let t = tok.trim();
            if t.is_empty() {
                continue;
            }
            saw_any_token = true;
            if let Some(k) = Self::from_str(t)
                && !out.contains(&k)
            {
                out.push(k);
            }
        }
        if !saw_any_token {
            // Input was empty / whitespace-only — caller treats as
            // "no filter declared".
            None
        } else {
            // At least one non-empty token was supplied. Return the
            // recognised set verbatim — including the empty-vec case
            // when every token was unknown, so the caller can apply a
            // strict "match nothing" filter rather than silently
            // collapsing to "match everything".
            Some(out)
        }
    }
}

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

/// v0.7.0 Form 5 (issue #758) — typed discriminator for the provenance
/// of a memory's `confidence` value.
///
/// Stored on `memories.confidence_source TEXT NOT NULL DEFAULT
/// 'caller_provided'` (schema v39 sqlite / v38 postgres). The auto-
/// derive engine in [`crate::confidence::derive`] writes
/// `AutoDerived` when [`crate::confidence::derive`] computes a fresh
/// value; the calibration sweep writes `Calibrated` when it replaces
/// the live value with a per-source baseline; the decay updater writes
/// `Decayed` after applying [`crate::confidence::decay::decayed`] on
/// recall touch. The (overwhelming-majority) legacy + default bucket
/// is `CallerProvided`, matching the SQL `DEFAULT` clause.
///
/// The discriminator lets recall ranking and the forensic bundle
/// reason about the trust path of a confidence score without re-running
/// the derivation. The calibration CLI scans the partial index
/// `idx_memories_confidence_source` (which excludes `caller_provided`)
/// to enumerate derived / calibrated / decayed rows cheaply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ConfidenceSource {
    /// The legacy and default bucket — the caller's value was accepted
    /// verbatim. Matches the SQL `DEFAULT 'caller_provided'` clause on
    /// the `confidence_source` column added in schema v39 (sqlite) /
    /// v38 (postgres).
    #[default]
    CallerProvided,
    /// The Form 5 auto-derive engine (`crate::confidence::derive`)
    /// computed the value at write time from row signals (atom
    /// derivation, prior-corroboration count, source age, namespace
    /// baseline). Opt-in via `AI_MEMORY_AUTO_CONFIDENCE=1`.
    AutoDerived,
    /// The calibration sweep (`ai-memory calibrate confidence
    /// --from-shadow`) replaced the live value with a per-source
    /// baseline computed from observed shadow-mode samples.
    Calibrated,
    /// The freshness-decay updater (`crate::confidence::decay`) wrote
    /// a decayed copy of the previous value, bumping
    /// `confidence_decayed_at`. Fires when
    /// `AI_MEMORY_CONFIDENCE_DECAY=1` or the namespace policy
    /// `confidence_decay_half_life_days` is set.
    Decayed,
    /// v0.7.0 issue #1242 — the curator engine (atomisation
    /// `LlmCurator`, persona generator) computed the value at row-
    /// mint time without an explicit caller-supplied number. Atom
    /// rows inherit `confidence` from their parent memory; persona
    /// rows pin `confidence = 1.0` per the QW-2 brief. In both
    /// cases the value is engine-derived, not caller-supplied, and
    /// must be discoverable to the calibration sweep + the partial
    /// index `idx_memories_confidence_source` (which excludes
    /// `caller_provided`). Pre-#1242 these rows mis-labelled
    /// `confidence_source = CallerProvided`, hiding them from the
    /// derived-row enumeration and violating the audit-honesty
    /// invariant.
    CuratorDerived,
    /// v0.7.x issue #1591 — the caller OMITTED `confidence` and the
    /// store surface stamped the compiled [`DEFAULT_CONFIDENCE`]
    /// fallback. Pre-#1591 these rows mis-labelled
    /// `confidence_source = 'caller_provided'` — a false provenance
    /// claim that made an unexamined 1.0 indistinguishable from a
    /// caller's deliberate full-confidence assertion. The Form-5
    /// calibration / decay engines treat this bucket exactly like
    /// `caller_provided` (the value is not engine-derived), but
    /// auditors and recall ranking can now discount the compiled
    /// fallback honestly.
    Default,
}

impl ConfidenceSource {
    /// Column-wire string (matches the SQL `DEFAULT 'caller_provided'`
    /// value and the four documented discriminator values).
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::CallerProvided => "caller_provided",
            Self::AutoDerived => "auto_derived",
            Self::Calibrated => "calibrated",
            Self::Decayed => "decayed",
            Self::CuratorDerived => "curator_derived",
            Self::Default => "default",
        }
    }

    /// Parse the column-wire string. Returns `None` on unrecognised
    /// values so callers can fall back to `CallerProvided` (forward-
    /// compat with future variants that land in a newer DB on an
    /// older binary).
    #[must_use]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "caller_provided" => Some(Self::CallerProvided),
            "auto_derived" => Some(Self::AutoDerived),
            "calibrated" => Some(Self::Calibrated),
            "decayed" => Some(Self::Decayed),
            "curator_derived" => Some(Self::CuratorDerived),
            "default" => Some(Self::Default),
            _ => None,
        }
    }
}

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

/// v0.7.0 Form 5 (issue #758) — JSON snapshot of the signals that
/// produced an auto-derived or calibrated confidence value.
///
/// Stored on `memories.confidence_signals TEXT NULL` (schema v39
/// sqlite / v38 postgres) as a JSON-encoded envelope. NULL on legacy
/// rows and on rows whose `confidence_source = 'caller_provided'`.
/// Also written verbatim into the `confidence_shadow_observations.signals`
/// column per recall when shadow mode is enabled.
///
/// An auditor can reconstruct the derivation after the fact by
/// inspecting this snapshot — the recall ranker and the forensic
/// bundle preserve it across reads, so a downstream review never
/// needs to re-query the substrate at the then-current state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ConfidenceSignals {
    /// Age (in days) of the source memory at the moment of derivation.
    /// Drives the `freshness_factor` exponent.
    pub source_age_days: f64,
    /// Whether the row is an atom of an existing memory (`atom_of IS
    /// NOT NULL`). Atom rows inherit higher base confidence because
    /// their provenance is anchored to a curator-validated parent.
    pub atom_derivation: bool,
    /// Count of related memories (via `memory_links`) at the moment of
    /// derivation. More corroboration → higher confidence; the
    /// formula uses `log10(1 + count)` to keep the bump sub-linear.
    pub prior_corroboration_count: i64,
    /// Pre-computed freshness factor `exp(-age / half_life)` clamped
    /// to `[0, 1]`. Stored alongside `source_age_days` so a future
    /// review can verify the half-life used at write time.
    pub freshness_factor: f64,
    /// Per-source baseline from the calibration table (median derived
    /// confidence for the row's `(namespace, source)` pair). `0.5`
    /// when no calibrated baseline exists yet.
    pub baseline_per_source: f64,
}

impl Default for ConfidenceSignals {
    fn default() -> Self {
        Self {
            source_age_days: 0.0,
            atom_derivation: false,
            prior_corroboration_count: 0,
            freshness_factor: 1.0,
            baseline_per_source: 0.5,
        }
    }
}

/// Memory-lifecycle tier — short (6h TTL) / mid (7d TTL) / long
/// (permanent). Drives the create-time backstop, the touch-time
/// sliding window, the auto-promotion at 5 accesses (mid → long),
/// the GC sweep, and the recall ranker's per-tier bonus.
///
/// # Disambiguation (issue #970)
///
/// The codebase has three enums whose names end in `Tier`. They are
/// orthogonal — same descriptive substring, distinct domains:
///
/// - [`Tier`] (this enum) — memory-lifecycle TTL bucket.
/// - [`ConfidenceTier`] — confidence-value bucket (Confirmed /
///   Likely / Ambiguous) derived from `Memory.confidence` thresholds.
///   Operator dashboards / human-review queues filter on it.
/// - [`crate::config::FeatureTier`] — host capability tier
///   (Keyword / Semantic / Smart / Autonomous) that gates which AI
///   features the host can fit in RAM.
///
/// They do not share variants, do not share wire strings, and are
/// never substitutable. See `docs/internal/enum-proliferation-audit-970.md`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Tier {
    Short,
    Mid,
    Long,
}

impl Tier {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Short => "short",
            Self::Mid => "mid",
            Self::Long => "long",
        }
    }

    /// Parse a tier wire string into the typed enum.
    ///
    /// The string literals in the match arms below are the **canonical
    /// deserializer** for the `Tier` wire form. They are the one place
    /// in the codebase where raw `"short"` / `"mid"` / `"long"` literals
    /// legitimately appear, because this is the boundary where a
    /// caller-supplied `&str` (HTTP body field, MCP JSON param, CLI
    /// flag value, TOML config field) gets dispatched into the typed
    /// enum. They are intentionally byte-equal to
    /// [`Tier::as_str`]'s outputs so the round-trip is identity.
    /// Anywhere else that *constructs* a tier wire value MUST route
    /// through `Tier::<X>.as_str()` instead of restamping a fresh
    /// literal. See pm-v3.1 PR6 (#1174) for the sweep that pinned this
    /// invariant.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "short" => Some(Self::Short),
            "mid" => Some(Self::Mid),
            "long" => Some(Self::Long),
            _ => None,
        }
    }

    /// Numeric rank for tier comparison: Short=0, Mid=1, Long=2.
    #[cfg(test)]
    pub fn rank(&self) -> u8 {
        match self {
            Self::Short => 0,
            Self::Mid => 1,
            Self::Long => 2,
        }
    }

    pub fn default_ttl_secs(&self) -> Option<i64> {
        match self {
            Self::Short => Some(6 * crate::SECS_PER_HOUR),
            Self::Mid => Some(crate::SECS_PER_WEEK),
            Self::Long => None,
        }
    }
}

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Memory {
    pub id: String,
    pub tier: Tier,
    pub namespace: String,
    pub title: String,
    pub content: String,
    pub tags: Vec<String>,
    pub priority: i32,
    /// 0.0-1.0 — how certain is this memory
    pub confidence: f64,
    /// Who/what created this row. Role-categorical, not vendor-specific.
    /// Canonical closed set lives in [`crate::validate::VALID_SOURCES`]
    /// at v0.7.0:
    ///   `user`, `nhi` ([`crate::validate::DEFAULT_NHI_SOURCE`] — the
    ///   vendor-neutral substrate default for AI-NHI-minted writes per
    ///   #1175), `claude` (deprecated; back-compat only, removal in
    ///   v0.8.x), `hook`, `api`, `cli`, `import`, `consolidation`,
    ///   `system`, `chaos`, `notify` (S32 inbox replication path).
    /// Validator surface: [`crate::validate::validate_source`].
    pub source: String,
    pub access_count: i64,
    pub created_at: String,
    pub updated_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_accessed_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    #[serde(default = "default_metadata")]
    pub metadata: Value,
    /// v0.7.0 Task 1/8 (recursive learning) — depth in the substrate-native
    /// reflection recursion tree. `0` for memories minted directly from a
    /// caller (or any pre-v0.7.0 row), positive for memories synthesised by
    /// the reflection pass over lower-depth peers. Operators can cap recursion
    /// depth at write time; readers can filter / sort by it.
    ///
    /// `#[serde(default)]` lets pre-v0.7.0 JSON payloads (and older federation
    /// peers) deserialize cleanly — missing → 0, which matches the SQL
    /// `DEFAULT 0` on the column added in schema v29 (SQLite) / v31 (Postgres).
    #[serde(default)]
    pub reflection_depth: i32,
    /// L1-1 (v0.7.0) — typed memory-kind discriminator.  Stored in
    /// `memories.memory_kind TEXT NOT NULL DEFAULT 'observation'` (schema v30).
    /// `Observation` for every pre-v30 row (SQL default); `Reflection` for
    /// memories minted by `memory_reflect` or the curator reflection pass.
    ///
    /// `#[serde(default)]` ensures round-trips with pre-v30 federation peers
    /// that don't yet emit the field.
    #[serde(default)]
    pub memory_kind: MemoryKind,
    /// v0.7.0 QW-2 — populated only when `memory_kind == Persona`.
    /// Identifies the subject of the persona. Stored on the SQL
    /// column `memories.entity_id TEXT NULL` (schema v36).
    /// `skip_serializing_if = "Option::is_none"` keeps the absent
    /// shape on the wire for pre-QW-2 federation peers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entity_id: Option<String>,
    /// v0.7.0 QW-2 — monotonic per-(entity_id, namespace) version
    /// counter for the Persona artefact. Populated only when
    /// `memory_kind == Persona`. Each `PersonaGenerator::generate`
    /// call writes a new row with `version + 1`; older rows stay
    /// queryable for audit / rollback.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub persona_version: Option<i32>,
    /// v0.7.0 Form 4 (issue #757) — fact-provenance citations array.
    /// Each entry carries a typed [`Citation`] envelope (uri,
    /// accessed_at, optional hash, optional span). Stored on the
    /// `memories.citations` TEXT column (schema v38) as a JSON-encoded
    /// array — legacy rows default to an empty vector via the SQL
    /// `DEFAULT '[]'` clause and the serde default below. Validator
    /// surface lives at `crate::validate::validate_citation`.
    ///
    /// **NSA CSI MCP Security mapping.** Part of the Form 4
    /// fact-provenance triple (`citations` + `source_uri` +
    /// `source_span`) that addresses NSA concerns (b) Insecure
    /// context or data serialization + (g) Poor or missing audit
    /// logs, and contributes to NSA recommendations (c) Validate
    /// parameters + (f) Filter and monitor output pipelines per the
    /// National Security Agency Cybersecurity Information document
    /// on MCP security (U/OO/6030316-26 | PP-26-1834, May 2026
    /// Version 1.0). Capability inventory anchor:
    /// `form_4_fact_provenance`. The mapping is described — without
    /// implying NSA endorsement of ai-memory or AlphaOne LLC — at
    /// `docs/compliance/nsa-csi-mcp.html` §3.2 / §3.7 / §4.3 / §4.6.
    #[serde(default)]
    pub citations: Vec<Citation>,
    /// v0.7.0 Form 4 (issue #757) — first-class URI-form pointer to
    /// the cited source body. Distinct from the role-label `source`
    /// column. Accepted schemes: `uri:` (HTTP URL), `doc:` (substrate
    /// doc id), `file:` (filesystem path). Validator surface lives at
    /// `crate::validate::validate_source_uri`. Mapped onto the
    /// `memories.source_uri` TEXT column (schema v38). NULL on legacy
    /// rows and on rows that do not yet carry a URI form.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_uri: Option<String>,
    /// v0.7.0 Form 4 (issue #757) — byte-range into the parent source
    /// body. Populated by the WT-1-B atomisation writer for each atom
    /// (atom-grain span fact-provenance) and may be set by callers
    /// who can pin the offset of a memory inside its referenced
    /// source. Mapped onto the `memories.source_span` TEXT column
    /// (schema v38) as a JSON `{start, end}` envelope. Validator
    /// surface lives at `crate::validate::validate_source_span`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_span: Option<SourceSpan>,
    /// v0.7.0 Form 5 (issue #758) — typed discriminator naming the
    /// provenance of the `confidence` value. Stored on
    /// `memories.confidence_source TEXT NOT NULL DEFAULT
    /// 'caller_provided'` (schema v39 sqlite / v38 postgres). Defaults
    /// to `CallerProvided` for every legacy row and every write that
    /// arrives with the auto-derive engine disabled.
    #[serde(default)]
    pub confidence_source: ConfidenceSource,
    /// v0.7.0 Form 5 — JSON snapshot of the signals that produced an
    /// auto-derived or calibrated confidence value. Mapped onto
    /// `memories.confidence_signals TEXT NULL` (schema v39 sqlite /
    /// v38 postgres). NULL on legacy rows and on rows whose
    /// `confidence_source = CallerProvided`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence_signals: Option<ConfidenceSignals>,
    /// v0.7.0 Form 5 — RFC3339 stamp of the last decay computation.
    /// Mapped onto `memories.confidence_decayed_at TEXT NULL` (schema
    /// v39 sqlite / v38 postgres). NULL on legacy rows and on rows
    /// never touched by the decay updater.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence_decayed_at: Option<String>,
    /// v0.7.0 Provenance Gap 1 (issue #884, schema v45 sqlite) —
    /// optimistic-concurrency counter. Bumped on every mutation:
    /// `storage::update` AND the `(title, namespace)` upsert-merge arm
    /// of `storage::insert` (#1632). Two callers writing against the
    /// same `expected_version` race exactly one winner; the loser
    /// receives a typed `CONFLICT` envelope naming the current stored
    /// version. The confidence-decay sweep is the only documented
    /// non-bumping mutator (tests/non_version_bumping_sites_1036.rs).
    /// Legacy rows land at `version = 1` via the SQL DEFAULT
    /// clause. `#[serde(default = "default_memory_version")]` keeps
    /// pre-v45 federation peers / JSON payloads deserialising cleanly.
    #[serde(default = "default_memory_version")]
    pub version: i64,
}

impl Memory {
    /// Total number of declared `pub <name>: <type>` fields on the
    /// `Memory` struct at v0.7.0. SSOT for the "26-field struct at
    /// v0.7.0 (was 15 at v0.6.x)" narrative in CLAUDE.md / README.md /
    /// ROADMAP.md / release-notes. Adding or removing a field requires
    /// bumping this const in the same commit, OR the parity test pin
    /// at `tests/memory_field_count_invariant.rs` fails the build.
    ///
    /// Multi-agent literal-sweep reference: scanner B finding F-B1.x
    /// (Memory shape drift), mirrors the
    /// `MemoryLinkRelation::COUNT` + `EXPECTED_CLI_SUBCOMMANDS_*`
    /// drift-blocker pattern landed in commits 960578cfd + 233e8a247.
    pub const FIELD_COUNT: usize = 26;

    /// v0.7.0 #1466 — the `expires_at` value a fresh store must persist.
    /// An explicit value the caller supplied wins; otherwise a non-`Long`
    /// row is stamped with `created_at + Tier::default_ttl_secs()` so it
    /// is reapable by GC (`expires_at IS NOT NULL AND expires_at < now`).
    /// `Long` rows have no TTL and stay immortal (returns `None`).
    ///
    /// Single SSOT for the tier-default backfill across every store
    /// backend (SQLite `storage::insert` + the `insert_with_conflict` /
    /// `insert_if_newer` / `consolidate` siblings, and the Postgres
    /// `store` path). Before this, those paths bound `expires_at`
    /// verbatim, so any internal caller that hand-built a `mid`/`short`
    /// Memory with `expires_at: None` created an immortal row GC could
    /// never collect. The interval comes from `Tier::default_ttl_secs()`
    /// — no hardcoded TTL literal — so it can never drift from the
    /// canonical per-tier TTL. Output mirrors the normal store path
    /// (`to_rfc3339`) so the string comparison in `gc()` stays
    /// monotonic; a malformed `created_at` falls back to `now` rather
    /// than silently dropping the expiry.
    #[must_use]
    pub fn effective_expires_at(&self) -> Option<String> {
        if self.expires_at.is_some() {
            return self.expires_at.clone();
        }
        let ttl = self.tier.default_ttl_secs()?;
        let base = chrono::DateTime::parse_from_rfc3339(&self.created_at)
            .map(|dt| dt.with_timezone(&chrono::Utc))
            .unwrap_or_else(|_| chrono::Utc::now());
        Some((base + chrono::Duration::seconds(ttl)).to_rfc3339())
    }
}

/// Default for [`Memory::version`] on rows that pre-date schema v45
/// (or JSON payloads from clients that haven't learned about the
/// column yet). Matches the SQL DEFAULT clause on the column.
#[must_use]
pub fn default_memory_version() -> i64 {
    1
}

/// v0.7.0 Provenance Gap 5 (issue #888) — typed edit-source
/// discriminator gating the `storage::update` write-path branch.
///
/// * [`EditSource::Human`] (default) — direct in-place mutation, the
///   v0.6.x / pre-Gap-5 behaviour. Content is overwritten; the row's
///   `version` is bumped; no archive is created.
/// * [`EditSource::Llm`] / [`EditSource::Hook`] — append-and-archive.
///   A NEW memory row is minted carrying the patched content; a
///   `supersedes` link is written pointing new→old; the OLD row is
///   archived with `archive_reason = 'superseded'` so callers can
///   rewind via `memory_archive_list` to read the pre-edit state.
///
/// The split exists so caller intent (human-typed correction vs.
/// curator/LLM rewrite) is preserved in the audit trail. Mem9's
/// pattern: in-place for human edits, append-and-archive for
/// programmatic rewrites where the new content semantically replaces
/// the old.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum EditSource {
    /// Direct in-place mutation of the existing row. Default.
    #[default]
    Human,
    /// Append-and-archive: mint a NEW row + supersedes link + archive
    /// the OLD row with `archive_reason='superseded'`.
    Llm,
    /// Append-and-archive: same shape as [`EditSource::Llm`] but
    /// records that a substrate hook triggered the rewrite.
    Hook,
    /// v0.7.x issue #1600 — direct in-place mutation performed by an
    /// AI/NHI agent. Mutation semantics are IDENTICAL to
    /// [`EditSource::Human`] (does NOT route through
    /// append-and-archive); the variant exists so the audit trail can
    /// distinguish a human-typed correction from an agent-initiated
    /// in-place edit. When `edit_source` is omitted on `memory_update`
    /// the default is derived from the resolved caller id via
    /// [`EditSource::default_for_agent_id`].
    Agent,
}

impl EditSource {
    /// #1600 — the closed wire vocabulary, in declaration order. The
    /// `memory_update` validation error names the valid set from this
    /// const so the message can never drift from the parser below.
    pub const ALL: [Self; 4] = [Self::Human, Self::Llm, Self::Hook, Self::Agent];

    /// Column-wire string used in audit log entries + the archive
    /// row's `archive_reason`-adjacent metadata.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Human => "human",
            Self::Llm => "llm",
            Self::Hook => "hook",
            Self::Agent => "agent",
        }
    }

    /// Parse the column-wire string. Returns `None` on unrecognised
    /// values; per #1600 the MCP `memory_update` surface now surfaces
    /// `None` as a validation ERROR naming [`EditSource::ALL`] instead
    /// of silently defaulting to [`EditSource::Human`].
    #[must_use]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "human" => Some(Self::Human),
            "llm" => Some(Self::Llm),
            "hook" => Some(Self::Hook),
            "agent" => Some(Self::Agent),
            _ => None,
        }
    }

    /// #1600 — default edit-source for an UPDATE whose caller omitted
    /// `edit_source`, derived from the resolved caller agent id: ids
    /// under [`crate::identity::sentinels::AI_AGENT_ID_PREFIX`]
    /// (`ai:…`) default to [`EditSource::Agent`]; every other shape
    /// (`host:…`, `anonymous:…`, bare operator ids) keeps the
    /// historical [`EditSource::Human`] default.
    #[must_use]
    pub fn default_for_agent_id(agent_id: &str) -> Self {
        if agent_id.starts_with(crate::identity::sentinels::AI_AGENT_ID_PREFIX) {
            Self::Agent
        } else {
            Self::Human
        }
    }

    /// `true` when the edit-source semantics call for the
    /// append-and-archive write path (vs. in-place mutation).
    #[must_use]
    pub fn appends_and_archives(&self) -> bool {
        matches!(self, Self::Llm | Self::Hook)
    }
}

/// v0.7.0 Form 4 (issue #757) — fact-provenance citation envelope.
///
/// One entry inside `Memory::citations`. The shape mirrors common
/// scholarly-citation needs while staying substrate-friendly:
///
/// * `uri` — URL, `doc:<id>` substrate pointer, or `file:<path>`. The
///   validator (`crate::validate::validate_citation`) rejects bare
///   strings; callers must use one of the typed schemes.
/// * `accessed_at` — RFC3339 timestamp at which the cited source was
///   read by the agent. Captures the fact-grain "when did this claim
///   become known to me" datum.
/// * `hash` — optional SHA-256 of the cited content. Lets a downstream
///   verifier confirm the source has not drifted since capture.
/// * `span` — optional byte-range pinning the specific quote inside
///   the cited body. Composes with `Memory::source_span` for
///   atom-grain lineage (the parent's span points into the source,
///   the atom's `source_span` points into the parent's body).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Citation {
    pub uri: String,
    pub accessed_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<SourceSpan>,
}

/// v0.7.0 Form 4 (issue #757) — byte-range envelope used by
/// `Memory::source_span` and `Citation::span`.
///
/// `start` and `end` are zero-based byte offsets into the parent
/// body. The half-open convention `[start, end)` matches Rust's
/// slice semantics, so the cited slice is `body[start..end]`. The
/// validator (`crate::validate::validate_source_span`) requires
/// `start < end` and bounds both within `usize::MAX`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct SourceSpan {
    pub start: usize,
    pub end: usize,
}

/// v0.7.0 Gap 4 (issue #887) — derived enum partitioning the
/// `confidence` real into operator-meaningful buckets so callers
/// (especially read-side reviewers) can filter by tier instead of
/// re-deriving thresholds at every site.
///
/// Thresholds are stable and load-bearing — operators have wired
/// dashboards / human-review queues against them and a change here
/// is a wire-level break. Bumping a threshold is therefore a
/// schema-bump-class decision, NOT a code-tuning decision.
///
/// - [`ConfidenceTier::Confirmed`] — `>= 0.95`. High-confidence
///   substrate-curated atoms, typically calibrated by the Form 5
///   pipeline or asserted by a trusted upstream.
/// - [`ConfidenceTier::Likely`] — `0.7 ..= 0.949…`. Default
///   caller-provided observations sit here.
/// - [`ConfidenceTier::Ambiguous`] — `< 0.7`. The human-review
///   queue: the caller themselves flagged uncertainty (or the
///   decay updater walked the value down). Operators commonly
///   filter their review tool against this tier.
///
/// Surfaced to MCP callers via the `confidence_calibration.tier_thresholds`
/// block on `memory_capabilities` (Gap 4 read-path closeout).
///
/// # Disambiguation (issue #970)
///
/// The codebase has three enums whose names end in `Tier`.
/// `ConfidenceTier` (this enum) is the **confidence-value bucket**;
/// it is unrelated to:
///
/// - [`Tier`] — memory-lifecycle TTL bucket (Short/Mid/Long).
/// - [`crate::config::FeatureTier`] — host capability tier
///   (Keyword/Semantic/Smart/Autonomous).
///
/// They do not share variants, wire strings, or call sites. See
/// `docs/internal/enum-proliferation-audit-970.md`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfidenceTier {
    Confirmed,
    Likely,
    Ambiguous,
}

impl ConfidenceTier {
    /// Inclusive lower bound for [`ConfidenceTier::Confirmed`]. Above
    /// this is a high-confidence observation / calibration result.
    pub const CONFIRMED_MIN: f64 = 0.95;
    /// Inclusive lower bound for [`ConfidenceTier::Likely`]. Below
    /// this is the human-review tier ([`ConfidenceTier::Ambiguous`]).
    pub const LIKELY_MIN: f64 = 0.7;

    /// Bucket a raw confidence value. NaN is conservatively mapped
    /// to [`ConfidenceTier::Ambiguous`] so a corrupt input lands in
    /// the human-review queue rather than masquerading as confirmed.
    #[must_use]
    pub fn from_confidence(c: f64) -> Self {
        if c.is_nan() {
            return Self::Ambiguous;
        }
        if c >= Self::CONFIRMED_MIN {
            Self::Confirmed
        } else if c >= Self::LIKELY_MIN {
            Self::Likely
        } else {
            Self::Ambiguous
        }
    }

    /// Wire string for this tier. Matches the serde `rename_all =
    /// "snake_case"` derive above so the JSON and the unstructured
    /// helper agree.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Confirmed => "confirmed",
            Self::Likely => "likely",
            Self::Ambiguous => "ambiguous",
        }
    }

    /// Parse a wire string back into the enum. Returns `None` on
    /// unrecognised input so callers can decide whether to error or
    /// fall through to "no filter".
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "confirmed" => Some(Self::Confirmed),
            "likely" => Some(Self::Likely),
            "ambiguous" => Some(Self::Ambiguous),
            _ => None,
        }
    }
}

impl Memory {
    /// v0.7.0 Gap 4 (#887) — derived [`ConfidenceTier`] for this
    /// memory's `confidence` value. Stable mapping; see
    /// [`ConfidenceTier::from_confidence`] for the thresholds.
    #[must_use]
    pub fn confidence_tier(&self) -> ConfidenceTier {
        ConfidenceTier::from_confidence(self.confidence)
    }
}

impl Default for Memory {
    /// All-zero / empty defaults. Useful as a base for ad-hoc test fixtures
    /// — `Memory { id: ..., title: ..., ..Default::default() }` — and for
    /// `#[serde(default)]` deserialisation of partial JSON. Tier defaults to
    /// `Mid` to match the API-layer default in [`CreateMemory`].
    fn default() -> Self {
        Self {
            id: String::new(),
            tier: Tier::Mid,
            namespace: crate::DEFAULT_NAMESPACE.to_string(),
            title: String::new(),
            content: String::new(),
            tags: Vec::new(),
            priority: 5,
            confidence: DEFAULT_CONFIDENCE,
            source: "api".to_string(),
            access_count: 0,
            created_at: String::new(),
            updated_at: String::new(),
            last_accessed_at: None,
            expires_at: None,
            metadata: default_metadata(),
            reflection_depth: 0,
            memory_kind: MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: default_memory_version(),
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct CreateMemory {
    #[serde(default = "default_tier")]
    pub tier: Tier,
    #[serde(default = "default_namespace")]
    pub namespace: String,
    pub title: String,
    pub content: String,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default = "default_priority")]
    pub priority: i32,
    /// Confidence 0.0–1.0. `None` (caller omitted the field) resolves
    /// to [`DEFAULT_CONFIDENCE`] with truthful
    /// `confidence_source = "default"` provenance (#1591) via
    /// [`CreateMemory::resolved_confidence`] /
    /// [`CreateMemory::resolved_confidence_source`].
    #[serde(default)]
    pub confidence: Option<f64>,
    #[serde(default = "default_source")]
    pub source: String,
    #[serde(default)]
    pub expires_at: Option<String>,
    #[serde(default)]
    pub ttl_secs: Option<i64>,
    #[serde(default = "default_metadata")]
    pub metadata: Value,
    /// Optional agent identifier. When unset, the server resolves a default
    /// via `crate::identity` (NHI-hardened precedence chain).
    #[serde(default)]
    pub agent_id: Option<String>,
    /// Optional visibility scope (Task 1.5). One of `VALID_SCOPES`. When
    /// unset, treated as `private` by the query layer.
    #[serde(default)]
    pub scope: Option<String>,
    /// v0.6.3.1 P2 (G6) — collision policy when (title, namespace) already
    /// exists. One of `error` | `merge` | `version`. When unset, the
    /// daemon defaults to `error` for HTTP callers (HTTP is not legacy
    /// like MCP v1; clients that want the legacy silent-merge contract
    /// must opt in explicitly).
    #[serde(default)]
    pub on_conflict: Option<String>,
    /// v0.7.0 (issue #519) — when `Some(true)`, run a proactive
    /// `detect_contradiction` LLM probe against same-namespace memories
    /// BEFORE returning 201, regardless of `autonomous_hooks`. When
    /// `Some(false)`, force-disable detection even if `autonomous_hooks`
    /// is on. When `None`, defer to `autonomous_hooks`.
    ///
    /// Surface: the 201 response body grows a `conflicts: [{...}]` array
    /// listing every same-namespace candidate the LLM flags as
    /// contradictory. Each entry carries the candidate id, title, and
    /// (when LLM produces one) a `suggested_merge` content string the
    /// caller can pass to a follow-up `memory_consolidate`.
    #[serde(default)]
    pub detect_conflicts: Option<bool>,
    /// v0.7.0 (issue #519) — proactive contradiction detection bypass.
    /// When `true`, the substrate-level `proactive_conflict_check` is
    /// skipped on this write so a near-duplicate-with-differing-content
    /// row is inserted anyway. Default `false` preserves the new v0.7.0
    /// refuse-by-default posture; callers that explicitly want the
    /// conflicting fact to land alongside the existing one set
    /// `force=true`.
    #[serde(default)]
    pub force: bool,
    /// v0.7.0 Form 4 (issue #757) — fact-provenance citations
    /// supplied at write time. Each entry must satisfy
    /// `validate::validate_citation`. Empty by default.
    #[serde(default)]
    pub citations: Vec<Citation>,
    /// v0.7.0 Form 4 — optional URI-form pointer to the cited source
    /// body. Must satisfy `validate::validate_source_uri` when set.
    #[serde(default)]
    pub source_uri: Option<String>,
    /// v0.7.0 Form 4 — optional byte-range into the parent source
    /// body. Must satisfy `validate::validate_source_span` when set.
    #[serde(default)]
    pub source_span: Option<SourceSpan>,
    /// v0.7.x Form 6 (#1385) — Batman-taxonomy memory-kind selector for
    /// the new row. Accepts any [`MemoryKind`] wire token
    /// (`observation` | `reflection` | `persona` | `concept` | `entity`
    /// | `claim` | `relation` | `event` | `conversation` | `decision`).
    /// Unknown values are silently ignored (treated as omission) for
    /// forward-compat with future variants, mirroring the MCP
    /// `memory_store` `params["kind"]` contract at
    /// `src/mcp/tools/store/validation.rs:207-213`. Absent / unknown
    /// → handler defaults to `MemoryKind::Observation`. Stored as
    /// `Option<String>` (not `Option<MemoryKind>`) so unknown future
    /// tokens deserialise without breaking the request envelope.
    ///
    /// Pre-#1385 this field did not exist on `CreateMemory`, so HTTP
    /// `POST /api/v1/memories` silently dropped the caller's `kind`
    /// and every HTTP-created row landed as `Observation`. The Form 6
    /// recall `kinds` filter then returned zero rows against HTTP-
    /// written data even when the caller had stored `kind: "claim"`
    /// (the v3 NHI assessment defect D-v3-3 reproducible against the
    /// alice lan-parity postgres-backed daemon).
    #[serde(default)]
    pub kind: Option<String>,
    /// #626 Layer-3 (C7) — detached Ed25519 agent-attestation signature,
    /// standard base64, over the `SignableWrite` envelope
    /// (`agent_id + namespace + title + kind + created_at +
    /// sha256(content)`). When present, `created_at` MUST also be supplied
    /// (the signer cannot predict the server clock); a signature that
    /// fails to verify against the agent's bound public key is rejected
    /// with 403. Absent ⇒ legacy unsigned write unless the operator set
    /// `AI_MEMORY_REQUIRE_AGENT_ATTESTATION`, in which case the gate
    /// rejects the unsigned store.
    #[serde(default)]
    pub signature: Option<String>,
    /// #626 Layer-3 (C7) — RFC3339 timestamp the caller signed. Required
    /// when `signature` is present; the server validates it against the
    /// ±300s attestation freshness window and then adopts it verbatim so
    /// the verifier re-derives the identical signed envelope.
    #[serde(default)]
    pub created_at: Option<String>,
}

/// Compiled default `confidence` stamped when a store surface (MCP
/// `memory_store`, HTTP `POST /api/v1/memories`, CLI `ai-memory store`)
/// receives no explicit caller value. #1591 — rows minted from this
/// fallback carry `confidence_source = `[`ConfidenceSource::Default`]
/// instead of falsely claiming `caller_provided`.
pub const DEFAULT_CONFIDENCE: f64 = 1.0;

impl CreateMemory {
    /// #1591 — effective confidence for this request: the caller's
    /// explicit value, else the compiled [`DEFAULT_CONFIDENCE`].
    #[must_use]
    pub fn resolved_confidence(&self) -> f64 {
        self.confidence.unwrap_or(DEFAULT_CONFIDENCE)
    }

    /// #1591 — truthful confidence provenance for this request:
    /// [`ConfidenceSource::CallerProvided`] only when the caller
    /// actually sent a `confidence` value;
    /// [`ConfidenceSource::Default`] when the compiled fallback was
    /// stamped.
    #[must_use]
    pub fn resolved_confidence_source(&self) -> ConfidenceSource {
        if self.confidence.is_some() {
            ConfidenceSource::CallerProvided
        } else {
            ConfidenceSource::Default
        }
    }
}

fn default_tier() -> Tier {
    Tier::Mid
}
fn default_namespace() -> String {
    // #1590 — honour the operator-configured `[storage].default_namespace`
    // (seeded process-wide at boot from `AppConfig::resolve_storage`) on
    // the HTTP store surface; unconfigured deployments keep the
    // historical compiled default.
    crate::config::configured_default_namespace()
        .unwrap_or_else(|| crate::DEFAULT_NAMESPACE.to_string())
}
fn default_priority() -> i32 {
    5
}
fn default_source() -> String {
    "api".to_string()
}

#[derive(Debug, Deserialize)]
pub struct UpdateMemory {
    pub title: Option<String>,
    pub content: Option<String>,
    pub tier: Option<Tier>,
    pub namespace: Option<String>,
    pub tags: Option<Vec<String>>,
    pub priority: Option<i32>,
    pub confidence: Option<f64>,
    pub expires_at: Option<String>,
    pub metadata: Option<Value>,
    /// v0.7.0 Provenance Gap 2 (#906) — opt-in `source_uri` patch.
    /// `None` leaves the stored value alone (COALESCE on the SQL
    /// layer); `Some("scheme:payload")` rewrites the row's source_uri
    /// (doc rename / URI scheme migration / bad-data correction).
    /// Validated by `validate::validate_source_uri` before reaching
    /// storage.
    pub source_uri: Option<String>,
    /// v0.7.0 #930 SECURITY-high (Track A P9, 2026-05-20) — optional
    /// caller-asserted `agent_id` for body/header parity. When set,
    /// MUST match the resolved `X-Agent-Id` header (Full-Measure-A
    /// posture). Mismatch → HTTP 403. Pre-fix the sqlite UPDATE path
    /// silently accepted ANY body.agent_id (or none) and never gated
    /// the writer against the row's recorded owner — enabling
    /// cross-tenant write hijack with forged provenance.
    #[serde(default)]
    pub agent_id: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SearchQuery {
    /// FTS query string. v0.7.0 Provenance Gap 6 (#889/#891): may be
    /// empty when `source_uri` is supplied (reciprocal source-only
    /// query). Handler rejects only when BOTH are empty.
    #[serde(default)]
    pub q: String,
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default)]
    pub tier: Option<Tier>,
    #[serde(default = "default_limit")]
    pub limit: Option<usize>,
    #[serde(default)]
    pub min_priority: Option<i32>,
    #[serde(default)]
    pub since: Option<String>,
    #[serde(default)]
    pub until: Option<String>,
    #[serde(default)]
    pub tags: Option<String>, // comma-separated
    /// Filter by `metadata.agent_id` (exact match).
    #[serde(default)]
    pub agent_id: Option<String>,
    /// Task 1.5 visibility: the querying agent's namespace position.
    /// When set, results are filtered per `metadata.scope` rules.
    #[serde(default)]
    pub as_agent: Option<String>,
    /// v0.7.0 Provenance Gap 6 (#889) — reciprocal source filter.
    /// When `source_uri=X` is supplied, the result set is narrowed
    /// to memories whose `source_uri` column equals X verbatim. The
    /// partial `idx_memories_source_uri` index (v38) covers the
    /// lookup so the query is O(log N).
    #[serde(default)]
    pub source_uri: Option<String>,
    /// #1579 B4 — response format negotiation: `json` (default) |
    /// `toon` | `toon_compact`. Reuses the MCP TOON encoder
    /// (`crate::toon`); invalid values are rejected with `400`
    /// carrying the SSOT message from
    /// `crate::toon::invalid_format_msg`.
    #[serde(default)]
    pub format: Option<String>,
}

#[allow(clippy::unnecessary_wraps)]
fn default_limit() -> Option<usize> {
    Some(20)
}

#[derive(Debug, Deserialize)]
pub struct ListQuery {
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default)]
    pub tier: Option<Tier>,
    #[serde(default = "default_limit")]
    pub limit: Option<usize>,
    #[serde(default)]
    pub offset: Option<usize>,
    #[serde(default)]
    pub min_priority: Option<i32>,
    #[serde(default)]
    pub since: Option<String>,
    #[serde(default)]
    pub until: Option<String>,
    #[serde(default)]
    pub tags: Option<String>,
    /// Filter by `metadata.agent_id` (exact match).
    #[serde(default)]
    pub agent_id: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct RecallQuery {
    pub context: Option<String>,
    /// `query` alias for `context` — the cert harness (S79) uses
    /// `?query=…`. Both forms route to the same code path; `context`
    /// wins when both are supplied.
    #[serde(default)]
    pub query: Option<String>,
    /// `q` alias for `context`/`query` — matches the search-style API
    /// surface (`/api/v1/memories?q=…`) so callers can use the same
    /// query token field across both endpoints.
    #[serde(default)]
    pub q: Option<String>,
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default = "default_recall_limit")]
    pub limit: Option<usize>,
    #[serde(default)]
    pub tags: Option<String>,
    #[serde(default)]
    pub since: Option<String>,
    #[serde(default)]
    pub until: Option<String>,
    /// Task 1.5 visibility filtering.
    #[serde(default)]
    pub as_agent: Option<String>,
    /// Task 1.11 — context-budget-aware recall. When set, return the
    /// top-scored memories whose cumulative estimated tokens fit within
    /// this budget.
    #[serde(default)]
    pub budget_tokens: Option<usize>,
    /// #1622 — salience tokens biasing the recall query embedding,
    /// comma-separated (`context_tokens=alpha,beta`), mirroring the
    /// `kinds` CSV convention for GET query params.
    #[serde(default)]
    pub context_tokens: Option<String>,
    /// v0.7.0 (issue #518) — when `true`, splice defaults from
    /// `[agents.defaults.recall_scope]` in `config.toml` for any
    /// filter field not explicitly set on this request. Resolution:
    /// explicit args > recall_scope defaults > compiled defaults.
    /// Default `false` preserves v0.6.x recall semantics exactly.
    #[serde(default)]
    pub session_default: Option<bool>,
    /// v0.7.0 Form 4 (issue #757) — restrict to memories whose
    /// `citations` array is non-empty. Composes with the other
    /// filters; default `None` preserves v0.7.0 recall semantics.
    #[serde(default)]
    pub has_citations: Option<bool>,
    /// v0.7.0 Form 4 (issue #757) — restrict to memories whose
    /// `source_uri` column begins with this exact prefix.
    #[serde(default)]
    pub source_uri_prefix: Option<String>,
    /// v0.7.x Form 6 (issue #759) — Batman-taxonomy memory-kind
    /// filter. Comma-separated string (`kinds=concept,claim`).
    /// OR-of-kinds within the param; AND with namespace / tags /
    /// time-window / visibility. `None` (default) preserves the
    /// pre-Form-6 "no kind filter" semantics. Unknown tokens are
    /// silently dropped (forward-compat with future variants).
    #[serde(default)]
    pub kinds: Option<String>,
    /// v0.7.0 (issue #518) — per-session "recently accessed" boost.
    /// When set and non-empty, the rerank post-step adds +0.05 to any
    /// recall candidate already in this session's ring buffer (cap
    /// 50 ids, FIFO eviction); the recall hit set is appended to the
    /// ring so subsequent recalls in the same session reuse the new
    /// context. `None`/empty preserves pre-#518 recall semantics
    /// exactly.
    #[serde(default)]
    pub session_id: Option<String>,
    /// v0.7.0 #1098 — WT-1-E include atomised sources alongside atoms.
    /// HTTP parity with the MCP `RecallRequest`. Pre-#1098 this field
    /// was hard-coded to `None` in `RecallRequest::from_http_query`.
    #[serde(default)]
    pub include_archived: Option<bool>,
    /// v0.7.0 #1098 — Gap 4 (#887) confidence-tier filter. HTTP
    /// parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub confidence_tier: Option<String>,
    /// v0.7.0 #1098 — Gap 7 (#890) per-row provenance decoration.
    /// HTTP parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub verbose_provenance: Option<bool>,
    /// v0.7.0 #1098 — response format selector (e.g. `toon_compact`).
    /// HTTP parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub format: Option<String>,
}

#[allow(clippy::unnecessary_wraps)]
fn default_recall_limit() -> Option<usize> {
    Some(10)
}

#[derive(Debug, Deserialize)]
pub struct RecallBody {
    /// Recall context. Accepts either `context` (canonical), `query`
    /// (cert harness alias used by S79), or `q` (matches the
    /// search-style API surface). At least one must be present and
    /// non-empty.
    #[serde(default)]
    pub context: Option<String>,
    #[serde(default)]
    pub query: Option<String>,
    #[serde(default)]
    pub q: Option<String>,
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default = "default_recall_limit")]
    pub limit: Option<usize>,
    #[serde(default)]
    pub tags: Option<String>,
    #[serde(default)]
    pub since: Option<String>,
    #[serde(default)]
    pub until: Option<String>,
    /// Task 1.5 visibility filtering.
    #[serde(default)]
    pub as_agent: Option<String>,
    /// Task 1.11 — context-budget-aware recall.
    #[serde(default)]
    pub budget_tokens: Option<usize>,
    /// #1622 — salience tokens biasing the recall query embedding
    /// (70/30 blend). Pre-#1622 this field was unreachable from HTTP
    /// (hard-coded `None` in `from_http_body`) while MCP + CLI honored
    /// it — the same class #1098 fixed for four other fields.
    #[serde(default)]
    pub context_tokens: Option<Vec<String>>,
    /// v0.7.0 (issue #518) — when `true`, splice defaults from
    /// `[agents.defaults.recall_scope]` in `config.toml` for any
    /// filter field not explicitly set on this request body.
    /// Resolution: explicit args > recall_scope defaults > compiled
    /// defaults. Default `false` preserves v0.6.x recall semantics.
    #[serde(default)]
    pub session_default: Option<bool>,
    /// v0.7.0 Form 4 (issue #757) — restrict to memories whose
    /// `citations` array is non-empty. Composes with the other
    /// filters.
    #[serde(default)]
    pub has_citations: Option<bool>,
    /// v0.7.0 Form 4 (issue #757) — restrict to memories whose
    /// `source_uri` column begins with this exact prefix.
    #[serde(default)]
    pub source_uri_prefix: Option<String>,
    /// v0.7.x Form 6 (issue #759) — Batman-taxonomy memory-kind
    /// filter. Accepts either a JSON array of strings
    /// (`{"kinds": ["concept", "claim"]}`) or a comma-separated
    /// string (`{"kinds": "concept,claim"}`). OR-of-kinds within
    /// the param; AND with the other filters.
    #[serde(default)]
    pub kinds: Option<serde_json::Value>,
    /// v0.7.0 (issue #518) — per-session recency boost. See the
    /// matching field on [`RecallQuery`].
    #[serde(default)]
    pub session_id: Option<String>,
    /// v0.7.0 #1098 — WT-1-E include atomised sources alongside
    /// atoms. HTTP parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub include_archived: Option<bool>,
    /// v0.7.0 #1098 — Gap 4 (#887) confidence-tier filter. HTTP
    /// parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub confidence_tier: Option<String>,
    /// v0.7.0 #1098 — Gap 7 (#890) per-row provenance decoration.
    /// HTTP parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub verbose_provenance: Option<bool>,
    /// v0.7.0 #1098 — response format selector (e.g. `toon_compact`).
    /// HTTP parity with the MCP `RecallRequest`.
    #[serde(default)]
    pub format: Option<String>,
}

impl RecallBody {
    /// Resolve the recall query string from `context`, `query`, or `q`.
    /// Returns the trimmed value, or an empty string when all three are
    /// absent — the caller is expected to reject empty.
    #[must_use]
    pub fn resolved_query(&self) -> String {
        self.context
            .as_deref()
            .or(self.query.as_deref())
            .or(self.q.as_deref())
            .unwrap_or("")
            .trim()
            .to_string()
    }

    /// v0.7.x Form 6 — parse the optional `kinds` JSON field.
    /// Accepts a JSON array of strings or a single comma-separated
    /// string. Treats `"all"` as "no filter" (returns `None`).
    /// Drops unknown tokens silently.
    ///
    /// Cluster E audit COR-4 (issue #767): mirrors
    /// [`MemoryKind::parse_csv`] semantics — an explicit array of
    /// only-unknown tokens (e.g. `["reflektion"]`) returns
    /// `Some(vec![])` (intentional zero-match filter), distinct from
    /// the absent / empty / `"all"` cases which return `None`
    /// (no filter declared).
    #[must_use]
    pub fn resolved_kinds(&self) -> Option<Vec<MemoryKind>> {
        let raw = self.kinds.as_ref()?;
        if let Some(s) = raw.as_str() {
            if s.trim().eq_ignore_ascii_case("all") {
                return None;
            }
            return MemoryKind::parse_csv(s);
        }
        if let Some(arr) = raw.as_array() {
            // Empty JSON array → no filter declared (matches the
            // CSV "" case in parse_csv).
            if arr.is_empty() {
                return None;
            }
            let mut out: Vec<MemoryKind> = Vec::new();
            for v in arr {
                if let Some(name) = v.as_str()
                    && let Some(k) = MemoryKind::from_str(name.trim())
                    && !out.contains(&k)
                {
                    out.push(k);
                }
            }
            // Non-empty array (even if every entry was unknown)
            // returns Some(out); collapsing to None would silently
            // invert a typo'd filter into "match all" (COR-4 bug).
            Some(out)
        } else {
            None
        }
    }
}

impl RecallQuery {
    /// v0.7.x Form 6 — parse the optional `kinds` query string.
    /// Comma-separated. `"all"` (case-insensitive) is treated as "no
    /// filter" (returns `None`). Drops unknown tokens silently.
    #[must_use]
    pub fn resolved_kinds(&self) -> Option<Vec<MemoryKind>> {
        let s = self.kinds.as_deref()?;
        if s.trim().eq_ignore_ascii_case("all") {
            return None;
        }
        MemoryKind::parse_csv(s)
    }
}

#[derive(Debug, Deserialize)]
pub struct ForgetQuery {
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default)]
    pub pattern: Option<String>, // FTS pattern
    #[serde(default)]
    pub tier: Option<Tier>,
}

/// v0.6.3.1 (P3): per-request observability for the recall pipeline.
///
/// Surfaces *which* recall path actually ran, *which* reranker was active,
/// the candidate pool sizes coming out of FTS and HNSW (before fusion), and
/// the blend weight applied to the semantic component. Always present in
/// `memory_recall` responses; older clients ignore unknown fields per the
/// JSON-RPC convention.
///
/// Closes G2/G8/G11 from the v0.6.3 audit by making every silent-degrade
/// path observable at request time. The capabilities surface (P1) reports
/// the same state at startup; this struct is the per-call mirror.
#[derive(Debug, Clone, Serialize)]
pub struct RecallMeta {
    /// Which recall path executed.
    /// - `"hybrid"` — embedder + FTS, blended (G11 happy path).
    /// - `"keyword_only"` — embedder unavailable or query-embed failed,
    ///   keyword-only recall served (G11 silent-degrade now visible).
    pub recall_mode: String,
    /// Which reranker scored the final ordering.
    /// - `"neural"` — BERT cross-encoder (autonomous tier, model loaded).
    /// - `"lexical"` — operator opted for the lexical variant, or the
    ///   tier never asked for a neural cross-encoder.
    /// - `"degraded_lexical"` — v0.7.0 R3-S2 — a configured neural
    ///   cross-encoder failed to initialise or errored mid-flight and
    ///   the runtime fell back. Distinct from `"lexical"` so clients
    ///   can detect the silent downgrade *in band* (previously this
    ///   was only a `tracing::warn!` event, which the G8 closure
    ///   claim overstated as "fail loud").
    /// - `"none"` — reranking disabled at this tier.
    pub reranker_used: String,
    /// Candidate-pool sizes coming out of each retrieval stage *before*
    /// fusion. Useful for spotting empty-FTS or empty-HNSW degradations.
    pub candidate_counts: CandidateCounts,
    /// Semantic blend weight applied during fusion. `0.0` for
    /// `keyword_only` mode; otherwise the average semantic weight across
    /// the returned candidates (varies 0.50→0.15 with content length).
    pub blend_weight: f64,
}

/// v0.6.3.1 (P3): retrieval-stage candidate counts feeding `RecallMeta`.
#[derive(Debug, Clone, Serialize)]
pub struct CandidateCounts {
    /// Number of candidates retrieved by FTS5 keyword scoring.
    pub fts: usize,
    /// Number of candidates retrieved by HNSW (or linear-scan fallback)
    /// semantic search. `0` in keyword-only mode.
    pub hnsw: usize,
}

/// v0.6.3.1 (P3): internal telemetry returned alongside recall results.
///
/// Plumbed from `db::recall_hybrid_with_telemetry` /
/// `db::recall_with_telemetry` up to `mcp::handle_recall`, which uses it
/// to populate `RecallMeta`. Not serialized — `RecallMeta` is the public
/// shape.
#[derive(Debug, Clone, Default)]
pub struct RecallTelemetry {
    /// Candidates returned by the FTS5 stage before fusion.
    pub fts_candidates: usize,
    /// Candidates returned by the HNSW (or linear-scan fallback) stage
    /// before fusion. `0` for keyword-only recall.
    pub hnsw_candidates: usize,
    /// Average semantic blend weight applied across the returned set.
    /// `0.0` for keyword-only recall.
    pub blend_weight_avg: f64,
    /// v0.7.0 H7 — count of stored embeddings whose dimensionality
    /// disagreed with the active embedder model during this recall, so
    /// their semantic signal was forced to `0.0` and excluded from the
    /// ranking. `0` in steady state; non-zero means the embedder model
    /// changed and the affected rows need re-embedding. The recall path
    /// also emits one aggregated `warn!` per query when this is non-zero.
    pub embedding_dim_mismatch: usize,
}

#[derive(Debug, Serialize)]
pub struct Stats {
    pub total: usize,
    pub by_tier: Vec<TierCount>,
    pub by_namespace: Vec<NamespaceCount>,
    pub expiring_soon: usize,
    pub links_count: usize,
    pub db_size_bytes: u64,
    /// v0.6.3.1 P2 (G4) — count of rows whose stored `embedding_dim`
    /// disagrees with the BLOB length (or whose column is missing while
    /// a BLOB exists). 0 on a fresh database; non-zero indicates legacy
    /// rows the operator should re-embed. Consumed by the P7 doctor.
    #[serde(default)]
    pub dim_violations: u64,
    /// v0.6.3.1 (P3, G2): cumulative HNSW oldest-eviction count since this
    /// process started. Non-zero indicates the in-memory vector index has
    /// hit its `MAX_ENTRIES` cap and silently dropped older embeddings —
    /// recall quality may have degraded for evicted ids. Process-local
    /// (not persisted) because the index itself is process-local.
    #[serde(default)]
    pub index_evictions_total: u64,
}

#[derive(Debug, Serialize)]
pub struct TierCount {
    pub tier: String,
    pub count: usize,
}

#[derive(Debug, Serialize)]
pub struct NamespaceCount {
    pub namespace: String,
    pub count: usize,
}

// -----------------------------------------------------------------
// L0.7-2 Tier A — memory.rs unit coverage
// Covers serde defaults (default_tier/default_namespace/etc.), Tier
// ↔ string round-trips, Memory::default, Tier::default_ttl_secs,
// RecallBody::resolved_query precedence.
// -----------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tier_round_trips_strings() {
        for (s, v) in [
            ("short", Tier::Short),
            ("mid", Tier::Mid),
            ("long", Tier::Long),
        ] {
            assert_eq!(Tier::from_str(s), Some(v.clone()));
            assert_eq!(v.as_str(), s);
            assert_eq!(format!("{v}"), s);
        }
    }

    #[test]
    fn tier_from_str_returns_none_for_unknown() {
        assert_eq!(Tier::from_str("unknown"), None);
        assert_eq!(Tier::from_str(""), None);
        assert_eq!(Tier::from_str("SHORT"), None); // case-sensitive
    }

    #[test]
    fn tier_default_ttl_secs_short_is_six_hours() {
        assert_eq!(
            Tier::Short.default_ttl_secs(),
            Some(6 * crate::SECS_PER_HOUR)
        );
    }

    #[test]
    fn tier_default_ttl_secs_mid_is_seven_days() {
        assert_eq!(Tier::Mid.default_ttl_secs(), Some(crate::SECS_PER_WEEK));
    }

    #[test]
    fn tier_default_ttl_secs_long_is_none() {
        assert_eq!(Tier::Long.default_ttl_secs(), None);
    }

    #[test]
    fn tier_rank_orders_short_mid_long() {
        assert!(Tier::Short.rank() < Tier::Mid.rank());
        assert!(Tier::Mid.rank() < Tier::Long.rank());
    }

    // #1466 — `effective_expires_at` is the single SSOT backfill used by
    // every store path. These pin the immortal-row regression: a non-Long
    // memory with `expires_at: None` must come back stamped at
    // `created_at + Tier::default_ttl_secs()`, Long stays None, and an
    // explicit value is preserved verbatim.

    #[test]
    fn effective_expires_at_backfills_mid_at_created_plus_one_week() {
        let mut m = Memory::default();
        m.tier = Tier::Mid;
        m.created_at = "2026-01-01T00:00:00+00:00".to_string();
        m.expires_at = None;
        let got = m.effective_expires_at().expect("mid must backfill");
        let parsed = chrono::DateTime::parse_from_rfc3339(&got).unwrap();
        let base = chrono::DateTime::parse_from_rfc3339(&m.created_at).unwrap();
        assert_eq!(
            (parsed - base).num_seconds(),
            crate::SECS_PER_WEEK,
            "mid backfill must equal created_at + SECS_PER_WEEK"
        );
    }

    #[test]
    fn effective_expires_at_backfills_short_at_created_plus_six_hours() {
        let mut m = Memory::default();
        m.tier = Tier::Short;
        m.created_at = "2026-01-01T00:00:00+00:00".to_string();
        m.expires_at = None;
        let got = m.effective_expires_at().expect("short must backfill");
        let parsed = chrono::DateTime::parse_from_rfc3339(&got).unwrap();
        let base = chrono::DateTime::parse_from_rfc3339(&m.created_at).unwrap();
        assert_eq!(
            (parsed - base).num_seconds(),
            6 * crate::SECS_PER_HOUR,
            "short backfill must equal created_at + 6h"
        );
    }

    #[test]
    fn effective_expires_at_long_stays_none() {
        let mut m = Memory::default();
        m.tier = Tier::Long;
        m.created_at = "2026-01-01T00:00:00+00:00".to_string();
        m.expires_at = None;
        assert_eq!(
            m.effective_expires_at(),
            None,
            "long has no TTL — must stay immortal"
        );
    }

    #[test]
    fn effective_expires_at_preserves_explicit_value() {
        let explicit = "2027-06-15T12:00:00+00:00".to_string();
        for tier in [Tier::Short, Tier::Mid, Tier::Long] {
            let mut m = Memory::default();
            m.tier = tier;
            m.created_at = "2026-01-01T00:00:00+00:00".to_string();
            m.expires_at = Some(explicit.clone());
            assert_eq!(
                m.effective_expires_at(),
                Some(explicit.clone()),
                "an explicit expiry must win over the tier default"
            );
        }
    }

    #[test]
    fn effective_expires_at_output_is_rfc3339_for_lexical_gc_compare() {
        // gc() compares `expires_at < now` as rfc3339 STRINGS, so the
        // backfill must emit the same `...THH:MM:SS+00:00` shape
        // `Utc::now().to_rfc3339()` produces — never a space-separated
        // SQLite datetime() form (which would sort wrong).
        let mut m = Memory::default();
        m.tier = Tier::Mid;
        m.created_at = "2026-01-01T00:00:00+00:00".to_string();
        m.expires_at = None;
        let got = m.effective_expires_at().unwrap();
        assert!(got.contains('T'), "must be ISO 'T'-separated: {got}");
        assert!(!got.contains(' '), "must not contain a space: {got}");
        assert!(
            chrono::DateTime::parse_from_rfc3339(&got).is_ok(),
            "must round-trip through rfc3339 parse: {got}"
        );
    }

    #[test]
    fn tier_serializes_to_snake_case() {
        let v = serde_json::to_value(Tier::Short).unwrap();
        assert_eq!(v, serde_json::Value::String("short".to_string()));
        let v = serde_json::to_value(Tier::Mid).unwrap();
        assert_eq!(v, serde_json::Value::String("mid".to_string()));
        let v = serde_json::to_value(Tier::Long).unwrap();
        assert_eq!(v, serde_json::Value::String("long".to_string()));
    }

    #[test]
    fn memory_default_uses_mid_tier_and_global_namespace() {
        let m = Memory::default();
        assert_eq!(m.tier, Tier::Mid);
        assert_eq!(m.namespace, "global");
        assert_eq!(m.priority, 5);
        assert!((m.confidence - 1.0).abs() < f64::EPSILON);
        assert_eq!(m.source, "api");
        assert_eq!(m.access_count, 0);
        assert_eq!(m.reflection_depth, 0);
        assert!(m.last_accessed_at.is_none());
        assert!(m.expires_at.is_none());
    }

    #[test]
    fn memory_round_trips_through_serde_with_reflection_depth() {
        let mut m = Memory::default();
        m.id = "mem-1".to_string();
        m.title = "test".to_string();
        m.content = "body".to_string();
        m.created_at = "2026-01-01T00:00:00Z".to_string();
        m.updated_at = "2026-01-01T00:00:00Z".to_string();
        m.reflection_depth = 3;
        let s = serde_json::to_string(&m).unwrap();
        let back: Memory = serde_json::from_str(&s).unwrap();
        assert_eq!(back.id, "mem-1");
        assert_eq!(back.reflection_depth, 3);
    }

    #[test]
    fn memory_deserialises_pre_v070_payload_without_reflection_depth() {
        // Pre-v0.7.0 payloads have no reflection_depth field. serde
        // default must populate it as 0.
        let json = serde_json::json!({
            "id": "old-mem",
            "tier": Tier::Mid.as_str(),
            "namespace": "ns",
            "title": "t",
            "content": "c",
            "tags": [],
            "priority": 5,
            "confidence": 1.0,
            "source": "api",
            "access_count": 0,
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "metadata": {},
        });
        let m: Memory = serde_json::from_value(json).unwrap();
        assert_eq!(m.reflection_depth, 0);
    }

    fn cm_minimal() -> serde_json::Value {
        serde_json::json!({
            "title": "t",
            "content": "c",
        })
    }

    #[test]
    fn create_memory_defaults_tier_to_mid() {
        // Lines 175-177: default_tier returns Tier::Mid via #[serde(default)].
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.tier, Tier::Mid);
    }

    #[test]
    fn create_memory_defaults_namespace_to_global() {
        // #1590 — the serde default now consults the process-wide
        // operator-configured default namespace; hold the test gate so
        // a concurrently-running #1590 seeding test can't bleed into
        // this unconfigured-deployment assertion.
        let _gate = crate::config::lock_configured_default_namespace_for_test();
        crate::config::set_configured_default_namespace(None);
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.namespace, "global");
    }

    /// #1590 regression — with an operator-configured
    /// `[storage].default_namespace` seeded at boot, an HTTP
    /// `CreateMemory` body that omits `namespace` lands in the
    /// configured namespace instead of the compiled `"global"`.
    /// An explicit body `namespace` still wins.
    #[test]
    fn create_memory_namespace_default_honours_configured_1590() {
        let _gate = crate::config::lock_configured_default_namespace_for_test();
        crate::config::set_configured_default_namespace(Some("alphaone".to_string()));
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.namespace, "alphaone", "#1590: configured default wins");
        let mut v = cm_minimal();
        v["namespace"] = serde_json::json!("explicit-ns");
        let cm: CreateMemory = serde_json::from_value(v).unwrap();
        assert_eq!(cm.namespace, "explicit-ns", "explicit body value wins");
        crate::config::set_configured_default_namespace(None);
    }

    #[test]
    fn create_memory_defaults_priority_to_5() {
        // Lines 181-183.
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.priority, 5);
    }

    #[test]
    fn create_memory_defaults_confidence_to_one() {
        // #1591 — the field is now `Option<f64>` so omission is
        // observable; the RESOLVED value still defaults to the
        // compiled DEFAULT_CONFIDENCE (1.0) with truthful
        // `confidence_source = "default"` provenance.
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.confidence, None, "omitted confidence must be None");
        assert!((cm.resolved_confidence() - DEFAULT_CONFIDENCE).abs() < f64::EPSILON);
        assert_eq!(
            cm.resolved_confidence_source(),
            ConfidenceSource::Default,
            "#1591: omitted confidence must stamp source=default"
        );
    }

    /// #1591 regression — an EXPLICIT caller `confidence` keeps the
    /// historical `caller_provided` provenance.
    #[test]
    fn create_memory_explicit_confidence_is_caller_provided_1591() {
        let mut v = cm_minimal();
        v["confidence"] = serde_json::json!(0.8);
        let cm: CreateMemory = serde_json::from_value(v).unwrap();
        assert_eq!(cm.confidence, Some(0.8));
        assert!((cm.resolved_confidence() - 0.8).abs() < f64::EPSILON);
        assert_eq!(
            cm.resolved_confidence_source(),
            ConfidenceSource::CallerProvided
        );
    }

    #[test]
    fn create_memory_defaults_source_to_api() {
        // Lines 187-189.
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.source, "api");
    }

    #[test]
    fn create_memory_defaults_metadata_to_empty_object() {
        let cm: CreateMemory = serde_json::from_value(cm_minimal()).unwrap();
        assert_eq!(cm.metadata, serde_json::json!({}));
    }

    #[test]
    fn recall_body_resolved_query_prefers_context() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "context": "c-value",
            "query": "q-value",
            "q": "qq-value",
        }))
        .unwrap();
        assert_eq!(body.resolved_query(), "c-value");
    }

    #[test]
    fn recall_body_resolved_query_falls_back_to_query_then_q() {
        let body: RecallBody =
            serde_json::from_value(serde_json::json!({"query": "q-value", "q": "qq"})).unwrap();
        assert_eq!(body.resolved_query(), "q-value");
        let body: RecallBody = serde_json::from_value(serde_json::json!({"q": "qq"})).unwrap();
        assert_eq!(body.resolved_query(), "qq");
    }

    #[test]
    fn recall_body_resolved_query_empty_when_all_absent() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(body.resolved_query(), "");
    }

    #[test]
    fn recall_body_resolved_query_trims_whitespace() {
        let body: RecallBody =
            serde_json::from_value(serde_json::json!({"context": "  spaced  "})).unwrap();
        assert_eq!(body.resolved_query(), "spaced");
    }

    #[test]
    fn search_query_defaults_limit_to_20() {
        // default_limit() returns Some(20)
        let q: SearchQuery = serde_json::from_value(serde_json::json!({"q": "x"})).unwrap();
        assert_eq!(q.limit, Some(20));
    }

    #[test]
    fn recall_query_defaults_limit_to_10() {
        // default_recall_limit() returns Some(10)
        let q: RecallQuery = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(q.limit, Some(10));
    }

    #[test]
    fn list_query_defaults_limit_to_20() {
        let q: ListQuery = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(q.limit, Some(20));
    }

    // -----------------------------------------------------------------
    // v0.7-polish coverage recovery (issue #767) — Forms 4/5/6 surface.
    // Covers the new MemoryKind variants, ConfidenceSource enum, the
    // Form 4 Citation / SourceSpan structs, and the v0.7.0 Memory
    // serde round-trip with every new field populated.
    // -----------------------------------------------------------------

    #[test]
    fn memory_kind_round_trips_every_variant_string() {
        for (s, v) in [
            ("observation", MemoryKind::Observation),
            ("reflection", MemoryKind::Reflection),
            ("persona", MemoryKind::Persona),
            ("concept", MemoryKind::Concept),
            ("entity", MemoryKind::Entity),
            ("claim", MemoryKind::Claim),
            ("relation", MemoryKind::Relation),
            ("event", MemoryKind::Event),
            ("conversation", MemoryKind::Conversation),
            ("decision", MemoryKind::Decision),
        ] {
            assert_eq!(MemoryKind::from_str(s), Some(v));
            assert_eq!(v.as_str(), s);
            assert_eq!(format!("{v}"), s);
        }
    }

    #[test]
    fn memory_kind_from_str_returns_none_for_unknown() {
        assert_eq!(MemoryKind::from_str("unknown"), None);
        assert_eq!(MemoryKind::from_str(""), None);
        assert_eq!(MemoryKind::from_str("OBSERVATION"), None); // case-sensitive
    }

    #[test]
    fn memory_kind_all_enumerates_in_declaration_order() {
        let all = MemoryKind::all();
        assert_eq!(all.len(), 10);
        assert_eq!(all[0], MemoryKind::Observation);
        assert_eq!(all[1], MemoryKind::Reflection);
        assert_eq!(all[2], MemoryKind::Persona);
        assert_eq!(all[9], MemoryKind::Decision);
    }

    #[test]
    fn memory_kind_default_is_observation() {
        let k: MemoryKind = MemoryKind::default();
        assert_eq!(k, MemoryKind::Observation);
    }

    #[test]
    fn memory_kind_parse_csv_empty_string_returns_none() {
        // Whitespace-only / empty → "no filter declared" → None.
        assert_eq!(MemoryKind::parse_csv(""), None);
        assert_eq!(MemoryKind::parse_csv("   "), None);
        assert_eq!(MemoryKind::parse_csv(",,, "), None);
    }

    #[test]
    fn memory_kind_parse_csv_all_unknown_returns_empty_vec() {
        // Non-empty input with only-unknown tokens → "intentional zero
        // filter" → Some(vec![]). Distinct from None per COR-4.
        let parsed = MemoryKind::parse_csv("reflektion,observetion");
        assert_eq!(parsed, Some(Vec::new()));
    }

    #[test]
    fn memory_kind_parse_csv_mixed_known_and_unknown_drops_unknown() {
        let parsed = MemoryKind::parse_csv("reflection,bogus,concept");
        assert_eq!(
            parsed,
            Some(vec![MemoryKind::Reflection, MemoryKind::Concept])
        );
    }

    #[test]
    fn memory_kind_parse_csv_dedups_repeated_tokens() {
        let parsed = MemoryKind::parse_csv("claim,claim,event,claim");
        assert_eq!(parsed, Some(vec![MemoryKind::Claim, MemoryKind::Event]));
    }

    #[test]
    fn memory_kind_parse_csv_trims_whitespace() {
        let parsed = MemoryKind::parse_csv("  concept ,  entity ");
        assert_eq!(parsed, Some(vec![MemoryKind::Concept, MemoryKind::Entity]));
    }

    #[test]
    fn memory_kind_serialises_to_snake_case() {
        let v = serde_json::to_value(MemoryKind::Conversation).unwrap();
        assert_eq!(v, serde_json::Value::String("conversation".to_string()));
    }

    #[test]
    fn confidence_source_round_trips_every_variant_string() {
        for (s, v) in [
            ("caller_provided", ConfidenceSource::CallerProvided),
            ("auto_derived", ConfidenceSource::AutoDerived),
            ("calibrated", ConfidenceSource::Calibrated),
            ("decayed", ConfidenceSource::Decayed),
            // v0.7.0 issue #1242 — curator-engine output bucket
            // (atom rows + persona rows). Distinct from
            // `auto_derived` (which is the Form 5 engine's
            // signal-based derivation).
            ("curator_derived", ConfidenceSource::CuratorDerived),
            // v0.7.x issue #1591 — caller omitted `confidence`; the
            // compiled DEFAULT_CONFIDENCE fallback was stamped.
            ("default", ConfidenceSource::Default),
        ] {
            assert_eq!(ConfidenceSource::from_str(s), Some(v));
            assert_eq!(v.as_str(), s);
            assert_eq!(format!("{v}"), s);
        }
    }

    /// #1600 regression — `EditSource` wire vocabulary round-trips
    /// every variant (incl. the new `agent`), `ALL` covers the closed
    /// set, and `agent` keeps Human's in-place mutation semantics
    /// (does NOT route append-and-archive).
    #[test]
    fn edit_source_agent_variant_wire_and_semantics_1600() {
        for v in EditSource::ALL {
            assert_eq!(
                EditSource::from_str(v.as_str()),
                Some(v),
                "EditSource wire string must round-trip"
            );
        }
        assert_eq!(EditSource::from_str("agent"), Some(EditSource::Agent));
        assert_eq!(EditSource::Agent.as_str(), "agent");
        assert!(
            !EditSource::Agent.appends_and_archives(),
            "#1600: Agent mutates in place exactly like Human"
        );
        assert!(EditSource::Llm.appends_and_archives());
        assert!(EditSource::Hook.appends_and_archives());
        // serde wire compat: snake_case rename matches as_str.
        assert_eq!(
            serde_json::to_value(EditSource::Agent).unwrap(),
            serde_json::Value::String("agent".to_string())
        );
        assert_eq!(EditSource::from_str("robot"), None, "unknown stays None");
    }

    /// #1600 regression — omitted `edit_source` derives from the
    /// resolved caller id: `ai:`-prefixed NHI ids default to `Agent`,
    /// every other shape keeps the historical `Human` default.
    #[test]
    fn edit_source_default_for_agent_id_matrix_1600() {
        assert_eq!(
            EditSource::default_for_agent_id("ai:claude-code@host:pid-1"),
            EditSource::Agent
        );
        assert_eq!(
            EditSource::default_for_agent_id("host:box:pid-2-abcd1234"),
            EditSource::Human
        );
        assert_eq!(
            EditSource::default_for_agent_id("anonymous:pid-3-ffff0000"),
            EditSource::Human
        );
        assert_eq!(EditSource::default_for_agent_id("alice"), EditSource::Human);
    }

    #[test]
    fn confidence_source_from_str_returns_none_for_unknown() {
        assert_eq!(ConfidenceSource::from_str("unknown"), None);
        assert_eq!(ConfidenceSource::from_str(""), None);
    }

    #[test]
    fn confidence_source_default_is_caller_provided() {
        let v: ConfidenceSource = ConfidenceSource::default();
        assert_eq!(v, ConfidenceSource::CallerProvided);
    }

    #[test]
    fn confidence_source_serialises_to_snake_case() {
        let v = serde_json::to_value(ConfidenceSource::AutoDerived).unwrap();
        assert_eq!(v, serde_json::Value::String("auto_derived".to_string()));
    }

    #[test]
    fn confidence_signals_default_has_expected_values() {
        let s = ConfidenceSignals::default();
        assert!((s.source_age_days - 0.0).abs() < f64::EPSILON);
        assert!(!s.atom_derivation);
        assert_eq!(s.prior_corroboration_count, 0);
        assert!((s.freshness_factor - 1.0).abs() < f64::EPSILON);
        assert!((s.baseline_per_source - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn confidence_signals_round_trips_through_serde() {
        let s = ConfidenceSignals {
            source_age_days: 12.5,
            atom_derivation: true,
            prior_corroboration_count: 3,
            freshness_factor: 0.75,
            baseline_per_source: 0.62,
        };
        let v = serde_json::to_value(&s).unwrap();
        let back: ConfidenceSignals = serde_json::from_value(v).unwrap();
        assert_eq!(back, s);
    }

    #[test]
    fn source_span_round_trips_through_serde() {
        let span = SourceSpan { start: 12, end: 34 };
        let v = serde_json::to_value(span).unwrap();
        let back: SourceSpan = serde_json::from_value(v.clone()).unwrap();
        assert_eq!(back, span);
        // JSON shape: {"start": 12, "end": 34}.
        assert_eq!(v["start"], 12);
        assert_eq!(v["end"], 34);
    }

    #[test]
    fn citation_round_trips_through_serde_with_optional_fields_unset() {
        let c = Citation {
            uri: "doc:abc123".to_string(),
            accessed_at: "2026-01-01T00:00:00Z".to_string(),
            hash: None,
            span: None,
        };
        let s = serde_json::to_string(&c).unwrap();
        // skip_serializing_if drops the None fields entirely.
        assert!(!s.contains("hash"));
        assert!(!s.contains("span"));
        let back: Citation = serde_json::from_str(&s).unwrap();
        assert_eq!(back, c);
    }

    #[test]
    fn citation_round_trips_with_hash_and_span_set() {
        let c = Citation {
            uri: "uri:https://example.com/paper".to_string(),
            accessed_at: "2026-02-03T04:05:06Z".to_string(),
            hash: Some("a".repeat(64)),
            span: Some(SourceSpan { start: 0, end: 100 }),
        };
        let v = serde_json::to_value(&c).unwrap();
        let back: Citation = serde_json::from_value(v).unwrap();
        assert_eq!(back, c);
    }

    #[test]
    fn memory_default_populates_form4_and_form5_defaults() {
        let m = Memory::default();
        assert!(m.citations.is_empty());
        assert!(m.source_uri.is_none());
        assert!(m.source_span.is_none());
        assert_eq!(m.confidence_source, ConfidenceSource::CallerProvided);
        assert!(m.confidence_signals.is_none());
        assert!(m.confidence_decayed_at.is_none());
        assert_eq!(m.memory_kind, MemoryKind::Observation);
        assert!(m.entity_id.is_none());
        assert!(m.persona_version.is_none());
    }

    #[test]
    fn memory_round_trips_with_all_v070_form_fields_populated() {
        let mut m = Memory::default();
        m.id = "mem-form".to_string();
        m.title = "fact-bearer".to_string();
        m.content = "the build broke at 14:32".to_string();
        m.created_at = "2026-05-01T00:00:00Z".to_string();
        m.updated_at = "2026-05-01T00:00:00Z".to_string();
        m.memory_kind = MemoryKind::Claim;
        m.entity_id = Some("entity-xyz".to_string());
        m.persona_version = Some(7);
        m.citations = vec![Citation {
            uri: "doc:src-1".to_string(),
            accessed_at: "2026-05-01T00:00:00Z".to_string(),
            hash: None,
            span: None,
        }];
        m.source_uri = Some("uri:https://example.com".to_string());
        m.source_span = Some(SourceSpan { start: 5, end: 10 });
        m.confidence_source = ConfidenceSource::Calibrated;
        m.confidence_signals = Some(ConfidenceSignals::default());
        m.confidence_decayed_at = Some("2026-04-01T00:00:00Z".to_string());

        let s = serde_json::to_string(&m).unwrap();
        let back: Memory = serde_json::from_str(&s).unwrap();
        assert_eq!(back.id, m.id);
        assert_eq!(back.memory_kind, MemoryKind::Claim);
        assert_eq!(back.entity_id.as_deref(), Some("entity-xyz"));
        assert_eq!(back.persona_version, Some(7));
        assert_eq!(back.citations.len(), 1);
        assert_eq!(back.citations[0].uri, "doc:src-1");
        assert_eq!(back.source_uri.as_deref(), Some("uri:https://example.com"));
        assert_eq!(back.source_span, Some(SourceSpan { start: 5, end: 10 }));
        assert_eq!(back.confidence_source, ConfidenceSource::Calibrated);
        assert!(back.confidence_signals.is_some());
        assert_eq!(
            back.confidence_decayed_at.as_deref(),
            Some("2026-04-01T00:00:00Z")
        );
    }

    #[test]
    fn memory_deserialises_pre_form4_payload_without_form4_fields() {
        // A pre-Form-4 payload omits citations / source_uri / source_span /
        // confidence_source / confidence_signals / confidence_decayed_at.
        // serde defaults must populate them.
        let json = serde_json::json!({
            "id": "old-mem",
            "tier": Tier::Long.as_str(),
            "namespace": "ns",
            "title": "t",
            "content": "c",
            "tags": [],
            "priority": 5,
            "confidence": 1.0,
            "source": "api",
            "access_count": 0,
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "metadata": {},
        });
        let m: Memory = serde_json::from_value(json).unwrap();
        assert!(m.citations.is_empty());
        assert!(m.source_uri.is_none());
        assert!(m.source_span.is_none());
        assert_eq!(m.confidence_source, ConfidenceSource::CallerProvided);
        assert!(m.confidence_signals.is_none());
        assert!(m.confidence_decayed_at.is_none());
        assert!(m.entity_id.is_none());
        assert!(m.persona_version.is_none());
        assert_eq!(m.memory_kind, MemoryKind::Observation);
    }

    #[test]
    fn recall_body_resolved_kinds_handles_all_keyword() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "kinds": "ALL",
        }))
        .unwrap();
        assert_eq!(body.resolved_kinds(), None);
    }

    #[test]
    fn recall_body_resolved_kinds_csv_parses_known_tokens() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "kinds": "concept,claim",
        }))
        .unwrap();
        let kinds = body.resolved_kinds().unwrap();
        assert!(kinds.contains(&MemoryKind::Concept));
        assert!(kinds.contains(&MemoryKind::Claim));
    }

    #[test]
    fn recall_body_resolved_kinds_array_parses_known_tokens() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "kinds": ["event", "entity", "bogus", "entity"],
        }))
        .unwrap();
        let kinds = body.resolved_kinds().unwrap();
        // Deduped + unknown dropped.
        assert_eq!(kinds, vec![MemoryKind::Event, MemoryKind::Entity]);
    }

    #[test]
    fn recall_body_resolved_kinds_empty_array_returns_none() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "kinds": [],
        }))
        .unwrap();
        assert_eq!(body.resolved_kinds(), None);
    }

    #[test]
    fn recall_body_resolved_kinds_only_unknown_array_returns_empty_vec() {
        // COR-4 distinction: explicit array with only unknowns returns
        // Some(vec![]) (intentional zero-match) — not None.
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "kinds": ["reflektion"],
        }))
        .unwrap();
        assert_eq!(body.resolved_kinds(), Some(Vec::new()));
    }

    #[test]
    fn recall_body_resolved_kinds_absent_returns_none() {
        let body: RecallBody = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(body.resolved_kinds(), None);
    }

    #[test]
    fn recall_body_resolved_kinds_non_string_non_array_returns_none() {
        // A number, object, bool etc. is neither string nor array → None.
        let body: RecallBody = serde_json::from_value(serde_json::json!({
            "kinds": 42,
        }))
        .unwrap();
        assert_eq!(body.resolved_kinds(), None);
    }

    #[test]
    fn recall_query_resolved_kinds_handles_all_keyword() {
        let q: RecallQuery = serde_json::from_value(serde_json::json!({
            "kinds": "all",
        }))
        .unwrap();
        assert_eq!(q.resolved_kinds(), None);
    }

    #[test]
    fn recall_query_resolved_kinds_parses_csv() {
        let q: RecallQuery = serde_json::from_value(serde_json::json!({
            "kinds": "decision,relation",
        }))
        .unwrap();
        let kinds = q.resolved_kinds().unwrap();
        assert!(kinds.contains(&MemoryKind::Decision));
        assert!(kinds.contains(&MemoryKind::Relation));
    }

    #[test]
    fn recall_query_resolved_kinds_absent_returns_none() {
        let q: RecallQuery = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(q.resolved_kinds(), None);
    }

    #[test]
    fn create_memory_accepts_form4_fields_when_present() {
        let cm: CreateMemory = serde_json::from_value(serde_json::json!({
            "title": "t",
            "content": "c",
            "citations": [{
                "uri": "doc:abc",
                "accessed_at": "2026-01-01T00:00:00Z",
            }],
            "source_uri": "uri:https://example.com",
            "source_span": {"start": 0, "end": 5},
        }))
        .unwrap();
        assert_eq!(cm.citations.len(), 1);
        assert_eq!(cm.source_uri.as_deref(), Some("uri:https://example.com"));
        assert_eq!(cm.source_span, Some(SourceSpan { start: 0, end: 5 }));
    }

    // ─────────────────────────────────────────────────────────────────────
    // #1385 — CreateMemory now honours caller-supplied `kind`. Pre-fix
    // the field did not exist on the struct, so HTTP `POST
    // /api/v1/memories` silently dropped it and every HTTP-created row
    // landed as `Observation`. That made the Form 6 recall `kinds`
    // filter useless against the HTTP write surface (a v3 NHI
    // assessment defect; live alice repro returned 0 rows for
    // kinds=["claim","decision"] against rows the caller had stored
    // with those exact kind tokens).
    // ─────────────────────────────────────────────────────────────────────

    #[test]
    fn create_memory_kind_field_deserialises_known_tokens() {
        for token in [
            "observation",
            "reflection",
            "persona",
            "concept",
            "entity",
            "claim",
            "relation",
            "event",
            "conversation",
            "decision",
        ] {
            let cm: CreateMemory = serde_json::from_value(serde_json::json!({
                "title": "t",
                "content": "c",
                "kind": token,
            }))
            .unwrap();
            assert_eq!(
                cm.kind.as_deref(),
                Some(token),
                "kind={token} must round-trip on the wire"
            );
            // And the handler parses it back into the typed enum on
            // assembly. Mirror the exact pattern the handler uses.
            let parsed = cm.kind.as_deref().and_then(MemoryKind::from_str);
            assert_eq!(
                parsed.map(|k| k.as_str()),
                Some(token),
                "kind={token} must parse back into MemoryKind",
            );
        }
    }

    #[test]
    fn create_memory_kind_field_absent_defaults_to_none() {
        let cm: CreateMemory = serde_json::from_value(serde_json::json!({
            "title": "t",
            "content": "c",
        }))
        .unwrap();
        assert_eq!(cm.kind, None);
        // Handler-side: absent → falls through to `Observation`.
        let resolved = cm
            .kind
            .as_deref()
            .and_then(MemoryKind::from_str)
            .unwrap_or_default();
        assert_eq!(resolved, MemoryKind::Observation);
    }

    #[test]
    fn create_memory_kind_field_unknown_token_silently_falls_through_to_observation() {
        // Matches MCP `memory_store` forward-compat posture
        // (`src/mcp/tools/store/validation.rs:207-213`): an unknown
        // kind token is treated as omission so a newer-client variant
        // landing on an older daemon still writes, just without the
        // typed discriminator. Distinct from the COR-4 invariant on
        // recall `kinds` filters where an explicit zero-match filter
        // must NOT collapse into "match all".
        let cm: CreateMemory = serde_json::from_value(serde_json::json!({
            "title": "t",
            "content": "c",
            "kind": "future_variant_v100",
        }))
        .unwrap();
        assert_eq!(cm.kind.as_deref(), Some("future_variant_v100"));
        let resolved = cm
            .kind
            .as_deref()
            .and_then(MemoryKind::from_str)
            .unwrap_or_default();
        assert_eq!(
            resolved,
            MemoryKind::Observation,
            "unknown kind token must silently fall through to Observation \
             for forward-compat with future-variant clients",
        );
    }
}