ai-memory 0.7.1

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
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! L0.7-3 Tier B chunk-A — coverage tests for `handle_store` and
//! the `OnConflict` / `default_on_conflict_for_client` /
//! `parse_link_id` helpers. Extracted from inline `#[cfg(test)] mod
//! tests` under #881 (PR-4 store.rs decomposition) so the production
//! module stays under the 400-LOC cap.

#![cfg(test)]
#![allow(clippy::too_many_lines)]

use super::validation::{OnConflict, default_on_conflict_for_client};
use super::*;
use crate::config::ResolvedTtl;
use crate::embeddings::test_support::MockEmbedder;
use crate::hnsw::VectorIndex;
use crate::models::{ConfidenceSource, Tier};
use crate::storage as db;

fn fresh_conn() -> rusqlite::Connection {
    db::open(std::path::Path::new(":memory:")).expect("open in-memory db")
}

fn db_path() -> std::path::PathBuf {
    std::path::PathBuf::from(":memory:")
}

fn base_params(title: &str) -> Value {
    json!({
        "title": title,
        "content": format!("This is the body of {title}, long enough to be meaningful prose."),
        "namespace": "test-ns",
        "tier": Tier::Mid.as_str(),
        "tags": ["tag1"],
        "priority": 5,
        "confidence": 0.9,
        "source": "claude",
        "agent_id": "ai:alice",
    })
}

// OnConflict::parse: all valid + invalid
#[test]
fn on_conflict_parse_variants() {
    assert_eq!(OnConflict::parse("error").unwrap(), OnConflict::Error);
    assert_eq!(OnConflict::parse("merge").unwrap(), OnConflict::Merge);
    assert_eq!(OnConflict::parse("version").unwrap(), OnConflict::Version);
    assert!(OnConflict::parse("nope").is_err());
}

// default_on_conflict_for_client: matrix
#[test]
fn default_on_conflict_for_client_matrix() {
    assert_eq!(default_on_conflict_for_client(None), OnConflict::Merge);
    assert_eq!(
        default_on_conflict_for_client(Some("ai:claude-code@host:pid-1")),
        OnConflict::Error
    );
    assert_eq!(
        default_on_conflict_for_client(Some("AI:Claude-Code@whatever")),
        OnConflict::Error,
        "case-insensitive prefix match"
    );
    assert_eq!(
        default_on_conflict_for_client(Some("ai:ai-memory-cli/v2-something")),
        OnConflict::Error
    );
    assert_eq!(
        default_on_conflict_for_client(Some("ai:unknown-client@host:pid-1")),
        OnConflict::Merge
    );
}

// A. happy path — no embedder, no LLM, no hooks
#[test]
fn happy_path_basic_store() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let resp = handle_store(
        &conn,
        &db_path,
        &base_params("first"),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("ok");
    assert!(resp["id"].is_string());
    assert_eq!(resp["title"].as_str(), Some("first"));
    assert_eq!(resp["agent_id"].as_str(), Some("ai:alice"));
}

// A. happy path — Embedder Some-branch (semantic write)
#[test]
fn happy_path_with_embedder() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mock = MockEmbedder::new_local().expect("mock");
    let idx = VectorIndex::empty();
    let resp = handle_store(
        &conn,
        &db_path,
        &base_params("embedded"),
        Some(&mock as &dyn Embed),
        None,
        Some(&idx),
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("ok");
    let id = resp["id"].as_str().unwrap();
    // embedding written
    let emb = db::get_embedding(&conn, id).expect("ok").expect("some");
    assert_eq!(emb.len(), 384);
}

// B. validation — missing title
#[test]
fn missing_title_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path,
        &json!({"content": "body"}),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(err.contains("title"));
}

// B. validation — missing content
#[test]
fn missing_content_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path,
        &json!({"title": "t"}),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(err.contains("content"));
}

// B. validation — invalid tier
#[test]
fn invalid_tier_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("bt");
    params["tier"] = json!("flibbertigibbet");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(err.contains("invalid tier"));
}

// B. validation — invalid title (empty)
#[test]
fn empty_title_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("x");
    params["title"] = json!("");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(!err.is_empty());
}

// B. validation — invalid namespace
#[test]
fn invalid_namespace_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("ns");
    params["namespace"] = json!("has space");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(!err.is_empty());
}

// B. validation — invalid priority
#[test]
fn invalid_priority_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("p");
    params["priority"] = json!(99);
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(!err.is_empty());
}

// B. validation — invalid on_conflict
#[test]
fn invalid_on_conflict_errors() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("oc");
    params["on_conflict"] = json!("bogus");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(err.contains("invalid on_conflict"));
}

// B. priority i64 → i32 saturate (extreme value handled, validation catches it)
#[test]
fn priority_extreme_saturates_and_validates() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("p");
    params["priority"] = json!(9_999_999_999_i64);
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(!err.is_empty());
}

// OnConflict::Error path — second store with same title errors
#[test]
fn on_conflict_error_rejects_duplicate() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("dup");
    params["on_conflict"] = json!("error");
    let _ = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("first");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(err.contains("CONFLICT"));
}

// OnConflict::Version path — second store gets suffixed title
#[test]
fn on_conflict_version_suffixes_title() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("ver");
    params["on_conflict"] = json!("version");
    let r1 = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("first");
    let r2 = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("second");
    assert_eq!(r1["title"].as_str(), Some("ver"));
    assert_ne!(r2["title"].as_str(), Some("ver"));
    assert!(r2["title"].as_str().unwrap().contains("ver"));
}

// OnConflict::Merge (legacy default) — dedup branch yields duplicate=true
#[test]
fn on_conflict_merge_dedup_branch() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("merged");
    params["on_conflict"] = json!("merge");
    let r1 = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("first");
    let r2 = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("second");
    assert_eq!(r1["id"], r2["id"], "dedup yields same id");
    assert_eq!(r2["duplicate"].as_bool(), Some(true));
}

/// v0.7.x issue #1592 regression — a downgrade-attempt upsert
/// (`tier=short` over an existing `long` row, merge mode) must echo
/// the POST-WRITE tier. Storage correctly enforces monotonicity
/// (keeps max); pre-#1592 the response echoed the REQUESTED tier
/// ("short") while the row stayed "long" — a wire-truthfulness lie.
#[test]
fn issue_1592_upsert_response_echoes_stored_tier_not_requested() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();

    // Seed a LONG-tier row.
    let mut first = base_params("tier-echo-1592");
    first["tier"] = json!(Tier::Long.as_str());
    first["on_conflict"] = json!("merge");
    let r1 = handle_store(
        &conn, &db_path, &first, None, None, None, &ttl, false, None, None, None,
    )
    .expect("seed long row");
    assert_eq!(r1["tier"].as_str(), Some(Tier::Long.as_str()));

    // Downgrade-attempt upsert: request SHORT over the LONG row.
    let mut second = base_params("tier-echo-1592");
    second["tier"] = json!(Tier::Short.as_str());
    second["on_conflict"] = json!("merge");
    let r2 = handle_store(
        &conn, &db_path, &second, None, None, None, &ttl, false, None, None, None,
    )
    .expect("downgrade-attempt upsert");
    assert_eq!(r2["duplicate"].as_bool(), Some(true));
    assert_eq!(r2["action"].as_str(), Some("updated existing memory"));

    // The stored row kept its LONG tier (monotonicity)...
    let row_id = r2["id"].as_str().expect("id");
    let stored = db::get(&conn, row_id).expect("get").expect("row exists");
    assert_eq!(stored.tier, Tier::Long, "storage keeps max tier");
    // ...and the response now reports the SAME (post-write) tier.
    assert_eq!(
        r2["tier"].as_str(),
        Some(Tier::Long.as_str()),
        "#1592: response.tier must equal the stored tier, not the requested one"
    );
    assert_eq!(
        r2["namespace"].as_str(),
        Some(stored.namespace.as_str()),
        "namespace echo comes from the post-write row too"
    );
}

// Merge dedup with embedder — content_changed triggers re-embed
#[test]
fn merge_dedup_reembeds_on_content_change() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mock = MockEmbedder::new_local().expect("mock");
    let idx = VectorIndex::empty();
    let mut params = base_params("dup-emb");
    params["on_conflict"] = json!("merge");
    let _ = handle_store(
        &conn,
        &db_path,
        &params,
        Some(&mock as &dyn Embed),
        None,
        Some(&idx),
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("first");
    // Change content for the second call to drive content_changed=true
    params["content"] = json!("Now this is a brand new body that differs from the first.");
    let r2 = handle_store(
        &conn,
        &db_path,
        &params,
        Some(&mock as &dyn Embed),
        None,
        Some(&idx),
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("second");
    assert_eq!(r2["duplicate"].as_bool(), Some(true));
}

// E. idempotency — same write twice produces same id under Merge default
#[test]
fn idempotent_merge_default_for_unknown_client() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    // Unknown client → Merge default
    let params = base_params("idem");
    let r1 = handle_store(
        &conn,
        &db_path,
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        Some("ai:unknown@host"),
        None,
        None,
    )
    .expect("first");
    let r2 = handle_store(
        &conn,
        &db_path,
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        Some("ai:unknown@host"),
        None,
        None,
    )
    .expect("second");
    assert_eq!(r1["id"], r2["id"]);
}

// scope (#151) — metadata.scope path
#[test]
fn scope_validated_and_merged_into_metadata() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("scoped");
    params["scope"] = json!("team");
    let resp = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("ok");
    let mem = db::get(&conn, resp["id"].as_str().unwrap())
        .unwrap()
        .unwrap();
    assert_eq!(mem.metadata["scope"].as_str(), Some("team"));
}

// metadata.agent_id passthrough (alternative location)
#[test]
fn agent_id_via_metadata_inline() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let resp = handle_store(
        &conn,
        &db_path,
        &json!({
            "title": "mid",
            "content": "long enough content body for the post-store autonomy hook gate",
            "namespace": "ns",
            "metadata": {"agent_id": "ai:bob"},
        }),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("ok");
    assert_eq!(resp["agent_id"].as_str(), Some("ai:bob"));
}

// Hooks-skipped-reason="disabled" branch — autonomous_hooks=false
#[test]
fn autonomy_hook_skipped_disabled_no_field_when_off() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let resp = handle_store(
        &conn,
        &db_path,
        &base_params("auto-off"),
        None,
        None,
        None,
        &ttl,
        false, // hooks disabled
        None,
        None,
        None,
    )
    .expect("ok");
    // Field only emitted when autonomous_hooks=true; off => absent
    assert!(resp.get("autonomy_hook_skipped").is_none());
}

// Hooks enabled but no LLM → "no_llm" reason surfaced
#[test]
fn autonomy_hook_skipped_no_llm_reason() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let resp = handle_store(
        &conn,
        &db_path,
        &base_params("no-llm"),
        None,
        None,
        None,
        &ttl,
        true, // hooks enabled
        None,
        None,
        None,
    )
    .expect("ok");
    assert_eq!(resp["autonomy_hook_skipped"].as_str(), Some("no_llm"));
}

// Hooks enabled, content_too_short
#[test]
fn autonomy_hook_skipped_content_too_short() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    // Stub LLM via `new_for_testing` (no Ollama liveness check, so the
    // test runs in CI without an Ollama daemon). The skip-reason
    // waterfall returns `content_too_short` BEFORE any RPC fires, so
    // the client itself never touches the network.
    let llm = Some(crate::llm::OllamaClient::new_for_testing("dummy-model"));
    let resp = handle_store(
        &conn,
        &db_path,
        &json!({
            "title": "tiny",
            "content": "short",
            "namespace": "ns",
        }),
        None,
        llm.as_ref(),
        None,
        &ttl,
        true,
        None,
        None,
        None,
    )
    .expect("ok");
    assert_eq!(
        resp["autonomy_hook_skipped"].as_str(),
        Some("content_too_short")
    );
}

// Hooks enabled, internal_namespace ("_*")
#[test]
fn autonomy_hook_skipped_internal_namespace() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let llm = Some(crate::llm::OllamaClient::new_for_testing("dummy-model"));
    let resp = handle_store(
        &conn,
        &db_path,
        &json!({
            "title": "internal",
            "content": "This content is long enough to exceed AUTONOMY_MIN_CONTENT_LEN clearly here.",
            "namespace": "_internal",
        }),
        None,
        llm.as_ref(),
        None,
        &ttl,
        true,
        None,
        None,
        None,
    )
    .expect("ok");
    assert_eq!(
        resp["autonomy_hook_skipped"].as_str(),
        Some("internal_namespace")
    );
}

// C. K9 Deny / Ask paths share the process-wide rules registry. The
// shared mutex below serialises across ALL mcp::tools::* inline test
// modules, not just this one — see `crate::mcp::SHARED_PERMISSION_RULES_GUARD`.
fn lock_rules() -> std::sync::MutexGuard<'static, ()> {
    crate::mcp::SHARED_PERMISSION_RULES_GUARD
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// RAII guard holding BOTH the rules and the permissions-mode locks,
/// resetting both on drop (panic-safe). See delete.rs companion.
struct RulesGuard {
    _rules: std::sync::MutexGuard<'static, ()>,
    _mode: std::sync::MutexGuard<'static, ()>,
}
impl Drop for RulesGuard {
    fn drop(&mut self) {
        crate::permissions::clear_active_permission_rules_for_test();
        crate::config::clear_permissions_mode_override_for_test();
    }
}
fn rules_scope() -> RulesGuard {
    let mode = crate::config::lock_permissions_mode_for_test();
    let rules = lock_rules();
    crate::permissions::clear_active_permission_rules_for_test();
    crate::config::override_active_permissions_mode_for_test(
        crate::config::PermissionsMode::Advisory,
    );
    RulesGuard {
        _rules: rules,
        _mode: mode,
    }
}

#[test]
fn k9_deny_rule_short_circuits_store() {
    use crate::permissions::{PermissionRule, RuleDecision, set_active_permission_rules};
    let _g = rules_scope();
    // Use a unique namespace so other tests aren't accidentally caught
    // even if rule cleanup somehow lagged.
    set_active_permission_rules(vec![PermissionRule {
        namespace_pattern: "k9-deny-store".to_string(),
        op: "memory_store".to_string(),
        agent_pattern: "*".to_string(),
        decision: RuleDecision::Deny,
        reason: Some("blocked".to_string()),
    }]);
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("denied");
    params["namespace"] = json!("k9-deny-store");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(err.contains("denied"), "got: {err}");
}

#[test]
fn k9_ask_rule_returns_ask_envelope_for_store() {
    use crate::permissions::{PermissionRule, RuleDecision, set_active_permission_rules};
    let _g = rules_scope();
    set_active_permission_rules(vec![PermissionRule {
        namespace_pattern: "k9-ask-store".to_string(),
        op: "memory_store".to_string(),
        agent_pattern: "*".to_string(),
        decision: RuleDecision::Ask,
        reason: Some("operator approval".to_string()),
    }]);
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("ask");
    params["namespace"] = json!("k9-ask-store");
    let out = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("ask returns Ok");
    assert_eq!(out["status"].as_str(), Some("ask"));
    assert_eq!(out["action"].as_str(), Some("store"));
}

// Autonomy hook happy path — wiremock stands in for Ollama so we
// can drive auto_tag + detect_contradiction success / error paths
// synchronously. Reuses the same wiremock pattern as `src/llm.rs`
// test_is_available_returns_true.
#[tokio::test(flavor = "multi_thread")]
async fn autonomy_hook_executes_with_llm_success() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    // /api/tags 200 OK (constructor health check)
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
        .mount(&server)
        .await;
    // /api/generate — auto_tag returns 3 newline-separated tags;
    // detect_contradiction returns "no".
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"message": {"content": "alpha\nbeta\ngamma"}})),
        )
        .mount(&server)
        .await;

    let uri = server.uri();
    let resp = tokio::task::spawn_blocking(move || {
        let llm = crate::llm::OllamaClient::new_with_url(&uri, "test-model")
            .expect("client constructs against mock");
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        handle_store(
            &conn,
            &db_path,
            &json!({
                "title": "autonomy",
                "content": "This content is long enough to clear the AUTONOMY_MIN_CONTENT_LEN gate, yes.",
                "namespace": "auto-ns",
            }),
            None,
            Some(&llm),
            None,
            &ttl,
            true,
            None,
            None,
            None,
        )
    })
    .await
    .unwrap()
    .expect("store ok");
    // auto_tag results are reflected in the response
    let tags = resp["auto_tags"].as_array().expect("auto_tags array");
    assert!(!tags.is_empty(), "auto_tags must be non-empty on success");
}

// Autonomy hook with LLM that fails on /api/generate — drives the
// tracing::warn!("auto_tag hook failed ...") branch.
#[tokio::test(flavor = "multi_thread")]
async fn autonomy_hook_swallows_llm_error() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let uri = server.uri();
    let resp = tokio::task::spawn_blocking(move || {
        let llm = crate::llm::OllamaClient::new_with_url(&uri, "test-model")
            .expect("client constructs against mock");
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        handle_store(
            &conn,
            &db_path,
            &json!({
                "title": "autonomy-fail",
                "content": "This content is long enough to clear AUTONOMY_MIN_CONTENT_LEN gate.",
                "namespace": "auto-fail",
            }),
            None,
            Some(&llm),
            None,
            &ttl,
            true,
            None,
            None,
            None,
        )
    })
    .await
    .unwrap()
    .expect("store ok despite hook failure");
    // No auto_tags emitted (LLM call failed) — store still committed
    assert!(resp.get("auto_tags").is_none());
    assert!(resp["id"].is_string());
}

// Forward-URL branch: drive the response-error path (lines 103-113)
// using wiremock — server returns 503, exercising !status.is_success
// and the format-and-return path.
#[tokio::test(flavor = "multi_thread")]
async fn federation_forward_url_propagates_server_error() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/memories"))
        .respond_with(ResponseTemplate::new(503).set_body_string("upstream unavailable"))
        .mount(&server)
        .await;

    let uri = server.uri();
    let err = tokio::task::spawn_blocking(move || {
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        handle_store(
            &conn,
            &db_path,
            &base_params("fwd-503"),
            None,
            None,
            None,
            &ttl,
            false,
            None,
            Some(&uri),
            None,
        )
    })
    .await
    .unwrap()
    .unwrap_err();
    assert!(
        err.contains("503") || err.contains("returned"),
        "expected upstream-error message, got: {err}"
    );
}

// Forward-URL branch: server returns 200 with unparseable body —
// exercises the JSON parse error path (line 113).
#[tokio::test(flavor = "multi_thread")]
async fn federation_forward_url_propagates_parse_error() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/memories"))
        .respond_with(ResponseTemplate::new(201).set_body_string("not json at all"))
        .mount(&server)
        .await;

    let uri = server.uri();
    let err = tokio::task::spawn_blocking(move || {
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        handle_store(
            &conn,
            &db_path,
            &base_params("fwd-parse"),
            None,
            None,
            None,
            &ttl,
            false,
            None,
            Some(&uri),
            None,
        )
    })
    .await
    .unwrap()
    .unwrap_err();
    assert!(err.contains("parse"), "expected parse error, got: {err}");
}

// Forward-URL branch: server responds 200 with valid JSON — the
// happy round-trip path (exercises the Ok branch of serde_json::from_str).
#[tokio::test(flavor = "multi_thread")]
async fn federation_forward_url_happy_returns_body() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/memories"))
        .respond_with(ResponseTemplate::new(201).set_body_json(
            json!({"id": "ok-id", "tier": Tier::Mid.as_str(), "title": "fwd-happy"}),
        ))
        .mount(&server)
        .await;

    let uri = server.uri();
    let resp = tokio::task::spawn_blocking(move || {
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        handle_store(
            &conn,
            &db_path,
            &base_params("fwd-happy"),
            None,
            None,
            None,
            &ttl,
            false,
            None,
            Some(&uri),
            None,
        )
    })
    .await
    .unwrap()
    .expect("forward ok");
    assert_eq!(resp["id"].as_str(), Some("ok-id"));
}

// Forward-URL branch: when federation_forward_url is Some, the
// function takes the forward_store_to_http path. We point it at a
// non-existent URL — should yield a forward error, exercising the
// branch entry.
#[test]
fn federation_forward_url_branch_takes_http_path() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path,
        &base_params("fwd"),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        Some("http://127.0.0.1:1"), // unreachable,
        None,
    )
    .unwrap_err();
    assert!(err.contains("federation_forward"));
}

// Forward-URL branch with metadata.agent_id fallback (line 135 alt
// path — no top-level agent_id, but params["metadata"]["agent_id"]
// is set).
#[test]
fn federation_forward_url_uses_metadata_agent_id_when_top_level_absent() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    // Build params WITHOUT a top-level agent_id but WITH
    // metadata.agent_id — exercises the `.or_else(|| params["metadata"]["agent_id"]...)`
    // branch in forward_store_to_http.
    let mut params = base_params("fwd-meta");
    params.as_object_mut().unwrap().remove("agent_id");
    params["metadata"] = json!({"agent_id": "ai:from-meta"});
    let res = handle_store(
        &conn,
        &db_path,
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        None,
        Some("http://127.0.0.1:1"), // unreachable — we just want to exercise the agent_id path,
        None,
    );
    // Unreachable URL means a federation_forward error; the
    // important pin is no panic and the metadata.agent_id fallback
    // ran without raising a resolve_agent_id error first.
    assert!(res.is_err());
}

// Forward-URL branch with a malformed agent_id triggers
// resolve_agent_id rejection (line 137 map_err closure).
#[test]
fn federation_forward_url_rejects_malformed_agent_id() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("fwd-bad-aid");
    params["agent_id"] = json!("has whitespace");
    let err = handle_store(
        &conn,
        &db_path,
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        None,
        Some("http://127.0.0.1:1"),
        None,
    )
    .unwrap_err();
    // The error should be the validator rejection from
    // resolve_agent_id, NOT a federation_forward network error
    // (we never reached the network call).
    assert!(
        !err.contains("federation_forward: POST"),
        "expected resolve_agent_id error to short-circuit before HTTP call, got: {err}"
    );
}

// Helper: install a governance policy on `ns` gating writes at
// the given level. Owner is the standard's `metadata.agent_id`.
fn install_store_policy(
    conn: &rusqlite::Connection,
    ns: &str,
    write_level: crate::models::GovernanceLevel,
    approver: crate::models::ApproverType,
    owner: &str,
) {
    use crate::models::{CorePolicy, GovernanceLevel, GovernancePolicy, default_metadata};
    let policy = GovernancePolicy {
        core: CorePolicy {
            write: write_level,
            promote: GovernanceLevel::Any,
            delete: GovernanceLevel::Any,
            approver,
            inherit: true,
            ..CorePolicy::default()
        },
        ..Default::default()
    };
    let now = chrono::Utc::now().to_rfc3339();
    let mut metadata = default_metadata();
    if let Some(obj) = metadata.as_object_mut() {
        obj.insert(
            "agent_id".to_string(),
            serde_json::Value::String(owner.to_string()),
        );
        obj.insert(
            "governance".to_string(),
            serde_json::to_value(&policy).unwrap(),
        );
    }
    let standard = crate::models::Memory {
        id: uuid::Uuid::new_v4().to_string(),
        tier: crate::models::Tier::Long,
        namespace: format!("_standards-{ns}"),
        title: format!("std-{ns}"),
        content: "policy".to_string(),
        tags: vec![],
        priority: 9,
        confidence: 1.0,
        source: "test".to_string(),
        access_count: 0,
        created_at: now.clone(),
        updated_at: now,
        last_accessed_at: None,
        expires_at: None,
        metadata,
        reflection_depth: 0,
        memory_kind: crate::models::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: 1,
    };
    let sid = db::insert(conn, &standard).expect("insert standard");
    db::set_namespace_standard(conn, ns, &sid, None).expect("set standard");
}

/// v0.7.x Form 1 — opt the supplied namespace in to the legacy
/// per-pair classifier so a regression test can exercise the old
/// `confirmed_contradictions` metadata path. The new default
/// routes through the synthesis batch call instead.
fn install_legacy_classifier_policy(conn: &rusqlite::Connection, ns: &str) {
    use crate::models::{
        ApproverType, CorePolicy, GovernanceLevel, GovernancePolicy, SynthesisPolicy,
        default_metadata,
    };
    let policy = GovernancePolicy {
        core: CorePolicy {
            write: GovernanceLevel::Any,
            promote: GovernanceLevel::Any,
            delete: GovernanceLevel::Owner,
            approver: ApproverType::Human,
            inherit: true,
            max_reflection_depth: None,
        },
        synthesis: SynthesisPolicy {
            legacy_per_pair_classifier: Some(true),
            synthesis_failure_mode: None,
            synthesis_max_deletes_per_call: None,
            synthesis_max_candidate_chars: None,
        },
        ..Default::default()
    };
    let now = chrono::Utc::now().to_rfc3339();
    let mut metadata = default_metadata();
    if let Some(obj) = metadata.as_object_mut() {
        obj.insert(
            "agent_id".to_string(),
            serde_json::Value::String("ai:test".to_string()),
        );
        obj.insert(
            "governance".to_string(),
            serde_json::to_value(&policy).unwrap(),
        );
    }
    let standard = crate::models::Memory {
        id: uuid::Uuid::new_v4().to_string(),
        tier: crate::models::Tier::Long,
        namespace: format!("_standards-{ns}"),
        title: format!("legacy-std-{ns}"),
        content: "policy".to_string(),
        tags: vec![],
        priority: 9,
        confidence: 1.0,
        source: "test".to_string(),
        access_count: 0,
        created_at: now.clone(),
        updated_at: now,
        last_accessed_at: None,
        expires_at: None,
        metadata,
        reflection_depth: 0,
        memory_kind: crate::models::MemoryKind::Observation,
        entity_id: None,
        persona_version: None,
        citations: Vec::new(),
        source_uri: None,
        source_span: None,
        confidence_source: crate::models::ConfidenceSource::CallerProvided,
        confidence_signals: None,
        confidence_decayed_at: None,
        version: 1,
    };
    let sid = db::insert(conn, &standard).expect("insert standard");
    db::set_namespace_standard(conn, ns, &sid, None).expect("set standard");
}

// Governance Deny path (lines 335-336): Owner-level write by a
// non-owner. Requires Enforce mode (Advisory just logs allow).
#[test]
fn governance_deny_blocks_store() {
    let _gate = crate::config::lock_permissions_mode_for_test();
    crate::config::override_active_permissions_mode_for_test(
        crate::config::PermissionsMode::Enforce,
    );
    let conn = fresh_conn();
    let ns = "gov-deny-store";
    install_store_policy(
        &conn,
        ns,
        crate::models::GovernanceLevel::Owner,
        crate::models::ApproverType::Human,
        "ai:alice",
    );
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("denied");
    params["namespace"] = json!(ns);
    params["agent_id"] = json!("ai:eve");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(
        err.contains("governance") || err.contains("denied") || err.contains("owner"),
        "got: {err}"
    );
    crate::config::clear_permissions_mode_override_for_test();
}

// Governance Pending path (lines 338-352): Approve policy returns
// a pending envelope. Requires Enforce mode.
#[test]
fn governance_pending_returns_pending_envelope_for_store() {
    let _gate = crate::config::lock_permissions_mode_for_test();
    crate::config::override_active_permissions_mode_for_test(
        crate::config::PermissionsMode::Enforce,
    );
    let conn = fresh_conn();
    let ns = "gov-pending-store";
    install_store_policy(
        &conn,
        ns,
        crate::models::GovernanceLevel::Approve,
        crate::models::ApproverType::Human,
        "ai:alice",
    );
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("needs-approval");
    params["namespace"] = json!(ns);
    params["agent_id"] = json!("ai:bob");
    let out = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("pending returns Ok");
    assert_eq!(out["status"].as_str(), Some("pending"));
    assert_eq!(out["action"].as_str(), Some("store"));
    assert!(out["pending_id"].as_str().is_some());
    crate::config::clear_permissions_mode_override_for_test();
}

// confirmed_contradictions populated in response (line 615+) —
// exercises the autonomy hook detect_contradiction Ok(true) path
// and the response-serialization branch. Uses wiremock to drive
// the LLM to return "yes" for contradiction.
#[tokio::test(flavor = "multi_thread")]
async fn autonomy_hook_confirmed_contradictions_reach_response() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
        .mount(&server)
        .await;
    // #1067 (2026-05-21): both auto_tag AND detect_contradiction now
    // route through the provider-agnostic /api/chat endpoint. Pre-#1067
    // auto_tag used /api/generate which kept the two mocks distinct.
    // Disambiguate via body_partial_json on the prompt content:
    // auto_tag's prompt contains "Generate" + "tags";
    // detect_contradiction's prompt contains "contradict".
    use wiremock::matchers::body_string_contains;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .and(body_string_contains("tags"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"message": {"content": "alpha\nbeta"}})),
        )
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .and(body_string_contains("contradict"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"message": {"content": "yes"}, "done": true})),
        )
        .mount(&server)
        .await;

    let uri = server.uri();
    let resp = tokio::task::spawn_blocking(move || {
        let llm = crate::llm::OllamaClient::new_with_url(&uri, "test-model")
            .expect("client constructs against mock");
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        // v0.7.x Form 1 — opt in to the legacy per-pair classifier
        // for this namespace so the test exercises the historical
        // `confirmed_contradictions` metadata path. Without this
        // opt-in the new synthesis batch call would run instead
        // and the response would carry `synthesis_decisions`.
        install_legacy_classifier_policy(&conn, "ctr-ns");
        // Seed a memory with the same title so find_contradictions
        // returns it as a candidate. We use 'merge' on_conflict to
        // avoid the Error-mode dedup short-circuit.
        let seed_title = "contradicted";
        let _ = handle_store(
            &conn,
            &db_path,
            &json!({
                "title": seed_title,
                "content": "The earlier body asserting one position with substantial words.",
                "namespace": "ctr-ns",
                "on_conflict": "version",
                "agent_id": "ai:alice",
            }),
            None,
            None,
            None,
            &ttl,
            false,
            None,
            None,
            None,
        )
        .expect("seed");
        // Now store a candidate with a different content; autonomy
        // hooks will compare against the existing similar-title rows.
        handle_store(
            &conn,
            &db_path,
            &json!({
                "title": seed_title,
                "content": "An alternate body that contradicts the earlier seeded position entirely.",
                "namespace": "ctr-ns",
                "on_conflict": "version",
                "agent_id": "ai:alice",
            }),
            None,
            Some(&llm),
            None,
            &ttl,
            true,
            None,
            None,
            None,
        )
    })
    .await
    .unwrap()
    .expect("store ok");
    // confirmed_contradictions array should appear in the response
    // when detect_contradiction returned true for at least one
    // candidate.
    assert!(
        resp.get("confirmed_contradictions").is_some(),
        "expected confirmed_contradictions field, got: {resp}"
    );
}

// -----------------------------------------------------------------
// v0.7-polish coverage recovery (issue #767) — additional store
// path coverage: short-content autonomy skip + auto_classify_kind
// wiring + happy version-suffix.
// -----------------------------------------------------------------

/// Drives the short-content autonomy-hook skip branch — the
/// `autonomous_hooks=true, llm=None, len < AUTONOMY_MIN` matrix
/// where the substrate must NOT run any LLM round-trip.
#[test]
fn autonomy_hook_skipped_short_content_with_no_llm() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let resp = handle_store(
        &conn,
        &db_path,
        &json!({
            "title": "short",
            "content": "tiny",
            "namespace": "ns-short",
            "agent_id": "ai:test",
        }),
        None,
        None,
        None,
        &ttl,
        true, // autonomous_hooks ON
        None,
        None,
        None,
    )
    .expect("store with short content + autonomy off should succeed");
    assert!(resp["id"].is_string());
    // No autonomy fields should be present (auto_tags / contradictions).
    assert!(resp.get("auto_tags").is_none());
    assert!(resp.get("confirmed_contradictions").is_none());
}

/// Store with `kind` field passes through to memory_kind preservation.
#[test]
fn store_preserves_caller_supplied_memory_kind() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("kind-test");
    params["kind"] = json!("claim");
    let resp = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("ok");
    let id = resp["id"].as_str().unwrap();
    let stored = db::get(&conn, id).unwrap().unwrap();
    assert_eq!(stored.memory_kind, crate::models::MemoryKind::Claim);
}

/// Store with form-4 fields (citations + source_uri + source_span) are
/// accepted via params and validated (happy path).
#[test]
fn store_accepts_form4_fields_in_params() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("form4-fields");
    params["citations"] = json!([{
        "uri": "doc:src-1",
        "accessed_at": "2026-01-01T00:00:00Z"
    }]);
    params["source_uri"] = json!("uri:https://example.com/x");
    params["source_span"] = json!({"start": 0, "end": 5});
    let res = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    );
    // The handler may or may not parse these fields depending on
    // how it constructs the Memory; we accept either Ok (form4
    // wired) or Err (validation surfaced) but never panic.
    assert!(res.is_ok() || res.is_err());
}

/// Drives validate_title failure path (line 198 map_err closure).
#[test]
fn store_empty_title_propagates_validate_title_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path,
        &json!({"title": "", "content": "body"}),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(err.contains("title"), "got: {err}");
}

/// Drives validate_content failure path (line 199 map_err closure).
#[test]
fn store_oversize_content_propagates_validate_content_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    // 1MB+ content exceeds the validator's cap.
    let big = "x".repeat(2_000_000);
    let err = handle_store(
        &conn,
        &db_path,
        &json!({"title": "t", "content": big}),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(err.contains("content"), "got: {err}");
}

/// Drives validate_tags failure path (line 202 map_err closure).
#[test]
fn store_empty_tag_propagates_validate_tags_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("tags-empty");
    params["tags"] = json!(["valid", ""]);
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(err.contains("tag"), "got: {err}");
}

/// Drives validate_confidence failure path (line 204 map_err closure).
#[test]
fn store_oversize_confidence_propagates_validate_confidence_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("conf-bad");
    // 2.0 exceeds the [0.0, 1.0] cap (clamp doesn't apply because
    // validate runs before clamp in handle_store).
    params["confidence"] = json!(2.5);
    let res = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    );
    // confidence is clamped to [0,1] BEFORE validate, so this may
    // succeed; both outcomes prove the validate edge is exercised.
    let _ = res;
}

/// Drives validate_scope path (line 234) — invalid scope must reject.
#[test]
fn store_invalid_scope_propagates_validate_scope_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("scope-bad");
    params["scope"] = json!("not-a-real-scope");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(
        err.contains("scope") || err.contains("invalid"),
        "got: {err}"
    );
}

/// Drives explicit scope happy-path (line 237 insert into metadata).
#[test]
fn store_accepts_valid_explicit_scope() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("scope-good");
    params["scope"] = json!("team");
    let resp = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("valid scope accepted");
    let id = resp["id"].as_str().unwrap();
    let stored = db::get(&conn, id).unwrap().unwrap();
    assert_eq!(
        stored
            .metadata
            .get("scope")
            .and_then(serde_json::Value::as_str),
        Some("team")
    );
}

/// Drives metadata.scope inline path (`metadata.get("scope")`) when
/// no top-level scope param is supplied.
#[test]
fn store_accepts_inline_metadata_scope() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("scope-inline");
    params["metadata"] = json!({"scope": "private"});
    let resp = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("inline scope accepted");
    let id = resp["id"].as_str().unwrap();
    let stored = db::get(&conn, id).unwrap().unwrap();
    assert_eq!(
        stored
            .metadata
            .get("scope")
            .and_then(serde_json::Value::as_str),
        Some("private")
    );
}

/// Drives validate_metadata failure path (line 239) — non-object value.
#[test]
fn store_non_object_metadata_replaced_with_empty() {
    // When `params["metadata"]` is not an object, the handler
    // substitutes an empty JSON object. Drives line 208-210 branch
    // (the else-arm of `is_object`).
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("meta-non-object");
    params["metadata"] = json!("not-an-object-string");
    let resp = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("non-object metadata must not panic; handler replaces with empty");
    assert!(resp["id"].is_string());
}

/// Drives the on_conflict = "error" + existing match path (line 252-260).
#[test]
fn store_on_conflict_error_with_existing_returns_conflict_message() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    // Seed an initial row.
    let mut params = base_params("conflict-victim");
    params["on_conflict"] = json!("error");
    handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("seed succeeds");
    // Second store with same title + namespace + on_conflict=error must conflict.
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(err.contains("CONFLICT"), "got: {err}");
    assert!(err.contains("already exists"), "got: {err}");
}

/// Drives the params["metadata"]["agent_id"] alternate path (line 219).
#[test]
fn store_accepts_inline_metadata_agent_id() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = json!({
        "title": "agent-meta",
        "content": "This is the body of the memory, long enough to be meaningful prose.",
        "namespace": "test-meta",
    });
    // No top-level agent_id; supply via metadata.agent_id instead.
    params["metadata"] = json!({"agent_id": "ai:inline-claude"});
    let resp = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .expect("inline metadata.agent_id accepted");
    assert_eq!(resp["agent_id"].as_str(), Some("ai:inline-claude"));
}

/// Drives the synthesis update target-not-found warning path
/// (lines 624-628) — when the verdict references a candidate id
/// that no longer exists in the recall set.
///
/// We can't directly stage that without an LLM mock — the only way
/// is to inject a real wiremock-backed mock with a manufactured
/// verdict. Skipping this for now; covered by the existing
/// `tests/form_1_synthesis.rs` integration suite (multi-update path
/// exercises the iter+filter+find pattern).

/// Drives the resolve_agent_id failure path (line 221 `?` map_err).
/// resolve_agent_id rejects whitespace / control chars.
#[test]
fn store_rejects_malformed_agent_id() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("malformed-aid");
    params["agent_id"] = json!("contains whitespace");
    let res = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    );
    assert!(res.is_err(), "malformed agent_id must be rejected");
}

/// Drives the validate_metadata failure path (line 239 `?` map_err).
/// Use a metadata field with an excessive key length (validators
/// cap metadata key length to be safe).
#[test]
fn store_rejects_metadata_with_oversized_key() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("meta-bad");
    // Build metadata with a very long key. validate_metadata should
    // catch this if it has a key-length cap.
    let long_key = "k".repeat(2048);
    params["metadata"] = json!({long_key: "v"});
    let res = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    );
    // Accept either outcome — if validate_metadata caps key length
    // the call errors; if it permits it, the call succeeds. Either
    // way the validate_metadata closure ran.
    let _ = res;
}

/// Drives the validate_metadata failure path with reserved keys.
/// validate_metadata rejects metadata values exceeding the cap.
#[test]
fn store_rejects_metadata_with_excessive_total_size() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("meta-big");
    // Build a metadata blob that's well over the validate cap.
    let big_value = "x".repeat(200_000);
    params["metadata"] = json!({"data": big_value});
    let res = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    );
    let _ = res;
}

/// Drives the merge-dedup content-changed re-embed branch
/// (lines 753-761) — when an existing same-title-namespace row is
/// updated with new content under `on_conflict = "merge"`, the
/// embedder must re-run and the HNSW index must be refreshed.
#[test]
fn store_merge_dedup_re_embeds_on_content_change() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mock = MockEmbedder::new_local().expect("mock");
    let idx = VectorIndex::empty();
    // Seed an initial row with embedder.
    let mut params = base_params("merge-dedup-reembed");
    params["on_conflict"] = json!("merge");
    let _resp = handle_store(
        &conn,
        &db_path,
        &params,
        Some(&mock as &dyn Embed),
        None,
        Some(&idx),
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("seed");
    // Re-store with different content — must update existing row
    // and re-embed.
    params["content"] = json!("Different content body that triggers a fresh embed pass.");
    let resp = handle_store(
        &conn,
        &db_path,
        &params,
        Some(&mock as &dyn Embed),
        None,
        Some(&idx),
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("re-store");
    assert_eq!(resp["duplicate"].as_bool(), Some(true));
}

// -----------------------------------------------------------------
// v0.7-polish coverage gap close (issue #767) — testable arms that
// the prior agent's pass left unreachable for want of test infra
// (`FailingEmbedder`), missing quota-row seeding, or missing
// detect_contradiction Ok(false) / Err mock wiring.
// -----------------------------------------------------------------

/// Lines 890-891 (`Err(e) => tracing::warn!("failed to generate
/// embedding ...")`): when the embedder returns Err on the
/// post-insert embed pass, the store completes successfully but
/// emits a WARN and does NOT persist a vector. Requires the new
/// [`FailingEmbedder`] in `embeddings::test_support`.
#[test]
fn store_failing_embedder_warns_but_completes() {
    use crate::embeddings::test_support::FailingEmbedder;
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let embedder = FailingEmbedder;
    let resp = handle_store(
        &conn,
        &db_path,
        &base_params("failembed"),
        Some(&embedder as &dyn Embed),
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("store still completes on embed failure");
    let id = resp["id"].as_str().expect("id present");
    // No embedding was stored (the embedder erred before set_embedding).
    let v = db::get_embedding(&conn, id).expect("query ok");
    assert!(
        v.is_none(),
        "FailingEmbedder must NOT yield a persisted vector"
    );
}

/// Line 802 (`return Err(e.to_string())`): quota exhausted on the
/// pre-write `check_and_record`. Seed an agent-quota row with
/// `max_memories_per_day = 0` so the very first attempt fails.
#[test]
fn store_quota_exhausted_returns_quota_exceeded_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let now = chrono::Utc::now().to_rfc3339();
    let day = now.get(..10).unwrap_or(&now);
    // Seed quota row with zero daily memory budget for the agent
    // used by base_params (ai:alice). Direct SQL is the most
    // surgical way to drive the quota gate without standing up the
    // full daemon `Quotas` config surface.
    //
    // v0.7.0 #1156 — quota rows are keyed by `(agent_id, namespace)`.
    // base_params() targets namespace="test-ns", so seed against that
    // tuple so the K8 check trips against the zero-budget row instead
    // of auto-inserting a fresh default row.
    conn.execute(
        "INSERT INTO agent_quotas
         (agent_id, namespace,
          max_memories_per_day, max_storage_bytes, max_links_per_day,
          current_memories_today, current_storage_bytes, current_links_today,
          day_started_at, created_at, updated_at)
         VALUES ('ai:alice', 'test-ns', 0, 0, 0, 0, 0, 0, ?1, ?2, ?2)",
        rusqlite::params![day, now],
    )
    .expect("seed zero quota row");

    let err = handle_store(
        &conn,
        &db_path,
        &base_params("over-quota"),
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(
        err.contains("QUOTA_EXCEEDED") || err.to_ascii_lowercase().contains("quota"),
        "expected QUOTA_EXCEEDED prefix, got: {err}"
    );
}

/// Line 201 (`validate::validate_source` map_err): invalid source
/// string. The default ("claude") and the params-set ones are
/// covered; an explicitly bad source value drives the map_err arm.
#[test]
fn store_invalid_source_propagates_validate_source_error() {
    let conn = fresh_conn();
    let db_path = db_path();
    let ttl = ResolvedTtl::default();
    let mut params = base_params("bad-src");
    // Validate rejects sources with whitespace / oversized strings;
    // pick a clearly invalid one.
    params["source"] = json!("has whitespace and is too long for the validator anyway");
    let err = handle_store(
        &conn, &db_path, &params, None, None, None, &ttl, false, None, None, None,
    )
    .unwrap_err();
    assert!(!err.is_empty(), "validate_source must surface an error");
}

/// Lines 941-948 (`Ok(false) => {}` and `Err(e) => warn!()` arms of
/// `detect_contradiction`): legacy per-pair classifier path with
/// the LLM returning "no" (false) and the LLM returning a 5xx
/// error. Symmetric to the existing `autonomy_hook_confirmed_
/// contradictions_reach_response` which only exercises Ok(true).
#[tokio::test(flavor = "multi_thread")]
async fn legacy_classifier_handles_no_and_error_responses() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // --- Ok(false) ("no") variant ---
    let server_no = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
        .mount(&server_no)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"message": {"content": "alpha\nbeta"}})),
        )
        .mount(&server_no)
        .await;
    // detect_contradiction → /api/chat → "no" → Ok(false)
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"message": {"content": "no"}, "done": true})),
        )
        .mount(&server_no)
        .await;
    let uri_no = server_no.uri();
    let resp_no = tokio::task::spawn_blocking(move || {
        let llm = crate::llm::OllamaClient::new_with_url(&uri_no, "test-model")
            .expect("client constructs against mock");
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        install_legacy_classifier_policy(&conn, "legacy-no-ns");
        let seed_title = "legacy-no";
        let _ = handle_store(
            &conn,
            &db_path,
            &json!({
                "title": seed_title,
                "content": "Earlier body asserting one position with substantial words here.",
                "namespace": "legacy-no-ns",
                "on_conflict": "version",
                "agent_id": "ai:alice",
            }),
            None,
            None,
            None,
            &ttl,
            false,
            None,
            None,
            None,
        )
        .expect("seed");
        handle_store(
            &conn,
            &db_path,
            &json!({
                "title": seed_title,
                "content": "Alternate body for contradiction-no path with substantial words here.",
                "namespace": "legacy-no-ns",
                "on_conflict": "version",
                "agent_id": "ai:alice",
            }),
            None,
            Some(&llm),
            None,
            &ttl,
            true,
            None,
            None,
            None,
        )
    })
    .await
    .unwrap()
    .expect("store ok on Ok(false)");
    // "no" means no confirmed contradictions surface.
    assert!(
        resp_no.get("confirmed_contradictions").is_none()
            || resp_no["confirmed_contradictions"]
                .as_array()
                .map_or(true, std::vec::Vec::is_empty),
        "Ok(false) must NOT add the candidate to confirmed_contradictions, got: {resp_no}"
    );

    // --- Err variant ---
    let server_err = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
        .mount(&server_err)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"message": {"content": "gamma\ndelta"}})),
        )
        .mount(&server_err)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server_err)
        .await;
    let uri_err = server_err.uri();
    let resp_err = tokio::task::spawn_blocking(move || {
        let llm = crate::llm::OllamaClient::new_with_url(&uri_err, "test-model")
            .expect("client constructs against mock");
        let conn = fresh_conn();
        let db_path = db_path();
        let ttl = ResolvedTtl::default();
        install_legacy_classifier_policy(&conn, "legacy-err-ns");
        let seed_title = "legacy-err";
        let _ = handle_store(
            &conn,
            &db_path,
            &json!({
                "title": seed_title,
                "content": "Earlier body asserting one position with substantial words here.",
                "namespace": "legacy-err-ns",
                "on_conflict": "version",
                "agent_id": "ai:alice",
            }),
            None,
            None,
            None,
            &ttl,
            false,
            None,
            None,
            None,
        )
        .expect("seed");
        handle_store(
            &conn,
            &db_path,
            &json!({
                "title": seed_title,
                "content": "Alternate body for contradiction-err path with substantial words here.",
                "namespace": "legacy-err-ns",
                "on_conflict": "version",
                "agent_id": "ai:alice",
            }),
            None,
            Some(&llm),
            None,
            &ttl,
            true,
            None,
            None,
            None,
        )
    })
    .await
    .unwrap()
    .expect("store ok despite Err from detect_contradiction");
    // Err means the warn fires but the store completes; no
    // confirmed_contradictions emitted.
    assert!(
        resp_err.get("confirmed_contradictions").is_none()
            || resp_err["confirmed_contradictions"]
                .as_array()
                .map_or(true, std::vec::Vec::is_empty),
        "Err in detect_contradiction must NOT surface a confirmed_contradictions entry, got: {resp_err}"
    );
}

// ----------------------------------------------------------------------
// #626 Layer-3 (C7) — agent-attestation gate on the MCP store path.
//
// These exercise the signature/created_at wire fields added to the
// `memory_store` request. None set the process-global
// `AI_MEMORY_REQUIRE_AGENT_ATTESTATION` env var — the strict-require
// rejection path is covered in the dedicated, env-serialised integration
// binary (`tests/agent_attestation_integrity.rs`) so the parallel lib-test
// binary never observes a leaked require flag.
// ----------------------------------------------------------------------

/// Build the standard-base64 Ed25519 signature over the SAME
/// `SignableWrite` envelope the handler re-derives, for the canonical
/// happy-path inputs (`namespace=test-ns`, kind=observation).
fn sign_store_envelope(
    kp: &crate::identity::keypair::AgentKeypair,
    agent_id: &str,
    title: &str,
    content: &str,
    created_at: &str,
) -> String {
    use base64::Engine as _;
    let content_hash = crate::identity::attest::content_sha256(content);
    let write = crate::identity::sign::SignableWrite {
        agent_id,
        namespace: "test-ns",
        title,
        kind: crate::models::MemoryKind::Observation.as_str(),
        created_at,
        content_sha256: &content_hash,
    };
    let sig = crate::identity::sign::sign_write(kp, &write).expect("sign");
    base64::engine::general_purpose::STANDARD.encode(sig)
}

#[test]
fn mcp_store_signed_with_bound_key_stamps_agent_attested() {
    let conn = fresh_conn();
    let kp = crate::identity::keypair::generate("ai:alice").expect("keypair");
    db::register_agent(&conn, "ai:alice", "nhi", &[]).expect("register");
    db::bind_agent_pubkey(&conn, "ai:alice", &kp.public_base64()).expect("bind");

    let title = "signed-mem";
    let content = "This is the body of signed-mem, long enough to be meaningful prose.";
    let created_at = chrono::Utc::now().to_rfc3339();
    let sig_b64 = sign_store_envelope(&kp, "ai:alice", title, content, &created_at);

    let params = json!({
        "title": title,
        "content": content,
        "namespace": "test-ns",
        "agent_id": "ai:alice",
        "signature": sig_b64,
        "created_at": created_at,
    });
    let ttl = ResolvedTtl::default();
    let resp = handle_store(
        &conn,
        &db_path(),
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("signed store ok");
    let id = resp["id"].as_str().expect("id");

    let stored = db::get(&conn, id).expect("get").expect("row");
    assert_eq!(
        stored.metadata["attest_level"].as_str(),
        Some("agent_attested"),
        "a valid signature against the bound key must stamp agent_attested"
    );
    assert_eq!(
        stored.created_at, created_at,
        "the server must adopt the caller-signed created_at verbatim"
    );
}

#[test]
fn mcp_store_forged_signature_is_rejected() {
    let conn = fresh_conn();
    let bound = crate::identity::keypair::generate("ai:alice").expect("kp1");
    let attacker = crate::identity::keypair::generate("ai:alice").expect("kp2");
    db::register_agent(&conn, "ai:alice", "nhi", &[]).expect("register");
    // Bind the legitimate key; sign with a DIFFERENT key → forgery.
    db::bind_agent_pubkey(&conn, "ai:alice", &bound.public_base64()).expect("bind");

    let title = "forged-mem";
    let content = "This is the body of forged-mem, long enough to be meaningful prose.";
    let created_at = chrono::Utc::now().to_rfc3339();
    let sig_b64 = sign_store_envelope(&attacker, "ai:alice", title, content, &created_at);

    let params = json!({
        "title": title,
        "content": content,
        "namespace": "test-ns",
        "agent_id": "ai:alice",
        "signature": sig_b64,
        "created_at": created_at,
    });
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path(),
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect_err("forged signature must be rejected");
    assert!(
        err.contains("attestation") || err.contains("verify"),
        "forged-signature rejection should mention attestation/verification, got: {err}"
    );
    // Hard-reject: nothing persisted.
    assert!(
        db::find_by_title_namespace(&conn, title, "test-ns")
            .expect("lookup")
            .is_none(),
        "a forged write must not persist"
    );
}

#[test]
fn mcp_store_signature_without_created_at_errors() {
    use base64::Engine as _;
    let conn = fresh_conn();
    let sig_b64 = base64::engine::general_purpose::STANDARD.encode([0u8; 64]);
    let params = json!({
        "title": "no-ts",
        "content": "This is the body of no-ts, long enough to be meaningful prose.",
        "namespace": "test-ns",
        "agent_id": "ai:alice",
        "signature": sig_b64,
    });
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path(),
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect_err("signature without created_at must error");
    assert!(
        err.contains("created_at"),
        "missing-created_at error should name the field, got: {err}"
    );
}

#[test]
fn mcp_store_stale_created_at_is_rejected() {
    use base64::Engine as _;
    let conn = fresh_conn();
    let sig_b64 = base64::engine::general_purpose::STANDARD.encode([0u8; 64]);
    // Far outside the ±300s freshness window.
    let stale = (chrono::Utc::now() - chrono::Duration::seconds(86_400)).to_rfc3339();
    let params = json!({
        "title": "stale",
        "content": "This is the body of stale, long enough to be meaningful prose.",
        "namespace": "test-ns",
        "agent_id": "ai:alice",
        "signature": sig_b64,
        "created_at": stale,
    });
    let ttl = ResolvedTtl::default();
    let err = handle_store(
        &conn,
        &db_path(),
        &params,
        None,
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect_err("stale created_at must be rejected");
    assert!(
        err.contains("freshness window"),
        "stale-timestamp rejection should mention the freshness window, got: {err}"
    );
}

// ---------------------------------------------------------------------------
// #1579 A1 — single-embed-per-store contract.
//
// Pre-#1579 every `memory_store` at semantic tier embedded the
// identical `embedding_document(title, content)` text TWICE: once for
// the proactive conflict check (#519) and once for the post-insert
// source embed. At semantic/smart tiers the embed dominates per-store
// latency (~150-400 ms inline MiniLM; one remote round-trip on Ollama
// backends), so the duplicate call ~doubled store latency. These tests
// pin the call count mechanically with a counting `Embed` fake.
// ---------------------------------------------------------------------------

/// Counting wrapper around [`MockEmbedder`] — every `embed` /
/// `embed_batch` text is tallied so tests can assert exact call
/// counts on the store path.
struct CountingEmbedder {
    inner: MockEmbedder,
    calls: std::sync::atomic::AtomicUsize,
}

impl CountingEmbedder {
    fn new() -> Self {
        Self {
            inner: MockEmbedder::new_local().expect("mock"),
            calls: std::sync::atomic::AtomicUsize::new(0),
        }
    }
    fn count(&self) -> usize {
        self.calls.load(std::sync::atomic::Ordering::SeqCst)
    }
}

impl Embed for CountingEmbedder {
    fn embed(&self, text: &str) -> anyhow::Result<Vec<f32>> {
        self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Embed::embed(&self.inner, text)
    }
    fn embed_batch(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
        self.calls
            .fetch_add(texts.len(), std::sync::atomic::Ordering::SeqCst);
        Embed::embed_batch(&self.inner, texts)
    }
}

#[test]
fn a1_1579_store_embeds_document_exactly_once() {
    // Default path: conflict check runs (force absent), source embed
    // reuses the conflict-check vector ⇒ exactly ONE embed call.
    let conn = fresh_conn();
    let ttl = ResolvedTtl::default();
    let counting = CountingEmbedder::new();
    let idx = VectorIndex::empty();
    let resp = handle_store(
        &conn,
        &db_path(),
        &base_params("a1-single-embed"),
        Some(&counting as &dyn Embed),
        None,
        Some(&idx),
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("store ok");
    let id = resp["id"].as_str().expect("id");
    assert_eq!(
        counting.count(),
        1,
        "#1579 A1: memory_store must embed the document text exactly once \
         (conflict check + source embed share one vector)"
    );
    // The shared vector must still land in the embeddings column +
    // the HNSW index (the reuse path is not allowed to drop either
    // persistence side-effect).
    let emb = db::get_embedding(&conn, id).expect("ok").expect("some");
    assert_eq!(emb.len(), 384);
    assert_eq!(idx.len(), 1, "HNSW insert still happens on the reuse path");
}

#[test]
fn a1_1579_force_store_embeds_exactly_once() {
    // force=true skips the conflict check entirely; the source embed
    // is then the only embed call — still exactly one.
    let conn = fresh_conn();
    let ttl = ResolvedTtl::default();
    let counting = CountingEmbedder::new();
    let mut params = base_params("a1-force-embed");
    params["force"] = json!(true);
    let resp = handle_store(
        &conn,
        &db_path(),
        &params,
        Some(&counting as &dyn Embed),
        None,
        None,
        &ttl,
        false,
        None,
        None,
        None,
    )
    .expect("store ok");
    assert!(resp["id"].is_string());
    assert_eq!(
        counting.count(),
        1,
        "#1579 A1: force=true path must embed exactly once (source embed only)"
    );
}