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

//! Full-autonomy loop — stacks on the Track A curator daemon (#278).
//!
//! This module provides the four passes beyond auto-tag that are
//! required to earn a defensible "100% autonomous" claim:
//!
//! 1. **Consolidation** — find near-duplicate memories in the same
//!    namespace, LLM-summarise them into a single canonical memory,
//!    archive the originals. Uses `db::consolidate` for the DB work
//!    and `AutonomyLlm::summarize_memories` for the synthesis.
//! 2. **Forgetting of superseded memories** — when a memory carries
//!    `metadata.confirmed_contradictions`, demote or forget the older
//!    contradicted entry (the curator keeps the fresher one). Uses
//!    `db::forget_count` with a targeted id list.
//! 3. **Priority feedback** — nudge `priority` up for memories that
//!    are getting recalled, nudge it down for cold ones. Purely
//!    arithmetic; no LLM call.
//! 4. **Rollback log + self-report** — every autonomous action lands
//!    in a `_curator/rollback/<ts>` memory describing what happened
//!    and how to reverse it, and every cycle lands in
//!    `_curator/reports/<ts>` as a summary the operator (and other
//!    agents) can recall.
//!
//! ## Trait boundary — `AutonomyLlm`
//!
//! The curator previously coupled directly to `llm::OllamaClient`,
//! which blocked unit-testable end-to-end coverage. This module
//! defines a narrow trait that both `OllamaClient` (in prod) and
//! the [`tests::StubLlm`] (in tests) implement. The autonomy passes
//! are generic over `&dyn AutonomyLlm`.

use crate::models::ConfidenceSource;
use crate::models::field_names;
use anyhow::Result;
use rusqlite::Connection;
use serde::{Deserialize, Serialize};

use crate::db;
use crate::llm::OllamaClient;
use crate::models::{Memory, Tier};

/// Source label stamped on memories the autonomy curator writes
/// (one spelling across the three write paths — #1558).
const CURATOR_SOURCE_LABEL: &str = "ai-memory curator (autonomy)";

/// Minimum Jaccard-keyword overlap required to treat two memories as
/// "near-duplicates" candidates for a consolidation cluster. Tuned
/// loosely — actual merge decision is still gated by an LLM pass.
///
/// v0.7.0 R3-S2 — Jaccard is now a *cheap pre-filter* (O(N) per pair)
/// when embeddings are available; cosine on the 384d MiniLM
/// embeddings is the primary signal at
/// [`CONSOLIDATE_COSINE_THRESHOLD`]. The Jaccard threshold is
/// retained as the keyword-tier fall-back when no embeddings are
/// present (so consolidation still works on a keyword-only
/// deployment) and as a pre-filter to skip the embedding lookup on
/// obviously-unrelated pairs.
pub const CONSOLIDATE_JACCARD_THRESHOLD: f64 = 0.55;

/// v0.7.0 R3-S2 — cosine similarity threshold (on 384d L2-normalised
/// MiniLM embeddings) above which two memories cluster for
/// consolidation. Default `0.75` per playbook §2.7 + ROADMAP §5.2:
/// it captures rephrasings and semantically near-equivalent content
/// without merging merely topically-adjacent memories.
///
/// Applied as the primary signal whenever both memories carry an
/// embedding row in the DB (`db::get_embedding` returns `Some`).
/// Jaccard is the cheap pre-filter (skips the embedding lookup) and
/// the fall-back signal when embeddings are missing
/// (keyword-tier deployments).
pub const CONSOLIDATE_COSINE_THRESHOLD: f64 = 0.75;

/// Cap on the number of memories in a single consolidation cluster —
/// prevents pathological mega-merges that would destroy provenance.
pub const CONSOLIDATE_MAX_CLUSTER_SIZE: usize = 8;

/// Reserved namespace prefix the curator writes to. Excluded from
/// further curator passes (the curator never acts on its own rollback
/// / report memories).
pub const CURATOR_NAMESPACE: &str = "_curator";

/// LLM surface the autonomy passes use. Implemented for `OllamaClient`
/// in prod and stubbed in tests. The `auto_tag` and `detect_contradiction`
/// methods are here for completeness — the autonomy passes themselves
/// currently only call `summarize_memories`, but exposing the three
/// together keeps the trait a single, testable LLM boundary that the
/// curator's `run_once` path can switch to in a follow-up PR.
#[allow(dead_code)]
pub trait AutonomyLlm {
    /// Generate tags for a memory.
    fn auto_tag(&self, title: &str, content: &str) -> Result<Vec<String>>;

    /// Return true iff the two pieces of content contradict each other.
    fn detect_contradiction(&self, mem_a: &str, mem_b: &str) -> Result<bool>;

    /// Produce a consolidated summary of N memories.
    fn summarize_memories(&self, memories: &[(String, String)]) -> Result<String>;
}

impl AutonomyLlm for OllamaClient {
    fn auto_tag(&self, title: &str, content: &str) -> Result<Vec<String>> {
        // L15: autonomy-tier trait passes None so the client uses its
        // configured default; callers that want a dedicated tag model
        // call `OllamaClient::auto_tag` directly with `Some(model)`.
        Self::auto_tag(self, title, content, None)
    }
    fn detect_contradiction(&self, mem_a: &str, mem_b: &str) -> Result<bool> {
        Self::detect_contradiction(self, mem_a, mem_b)
    }
    fn summarize_memories(&self, memories: &[(String, String)]) -> Result<String> {
        Self::summarize_memories(self, memories)
    }
}

/// Rollback-log entry stored as a memory in `_curator/rollback/<rfc3339>`.
///
/// Serialised as JSON in the memory's `content`. The memory's `metadata`
/// carries the `action` discriminator so operators can filter the
/// rollback log by kind via the normal `memory_list` + `tags_filter`
/// path.
///
/// The `Consolidate` variant is deliberately large (carries full
/// pre-merge memory snapshots) compared to `PriorityAdjust`. That's the
/// cost of being able to reverse a merge without network round-trips.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum RollbackEntry {
    /// A consolidation was applied. `originals` are the full Memory
    /// snapshots pre-merge; `result_id` is the consolidated memory id.
    Consolidate {
        originals: Vec<Memory>,
        result_id: String,
    },
    /// A memory was forgotten (archived). `snapshot` is the memory as
    /// it was immediately before forgetting.
    Forget { snapshot: Memory },
    /// A priority adjustment. `memory_id`, `before`, `after`.
    PriorityAdjust {
        memory_id: String,
        before: i32,
        after: i32,
    },
}

impl RollbackEntry {
    fn action_tag(&self) -> &'static str {
        match self {
            Self::Consolidate { .. } => crate::audit::OP_CONSOLIDATE,
            Self::Forget { .. } => "forget",
            Self::PriorityAdjust { .. } => "priority_adjust",
        }
    }
}

/// Structured outcome of a single autonomy pass. Aggregated into the
/// curator cycle's `CuratorReport` and also written back as a self-
/// report memory.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AutonomyPassReport {
    pub clusters_formed: usize,
    pub memories_consolidated: usize,
    pub memories_forgotten: usize,
    pub priority_adjustments: usize,
    pub rollback_entries_written: usize,
    pub errors: Vec<String>,
}

/// Run all autonomy passes over the provided candidates in order:
/// consolidate → forget superseded → priority feedback → record
/// rollback log → write self-report. `dry_run` suppresses all writes.
///
/// Returns an `AutonomyPassReport` rather than `Result<…>` because
/// per-pass errors are already aggregated into `report.errors`;
/// the function itself cannot fail at the outer level.
pub fn run_autonomy_passes(
    conn: &Connection,
    llm: &dyn AutonomyLlm,
    candidates: &[Memory],
    dry_run: bool,
) -> AutonomyPassReport {
    let mut report = AutonomyPassReport::default();

    // Pass 1 — consolidation.
    let clusters = find_consolidation_clusters(conn, candidates);
    report.clusters_formed = clusters.len();
    for cluster in clusters {
        match consolidate_cluster(conn, llm, &cluster, dry_run) {
            Ok(Some(entry)) => {
                if !dry_run && let Err(e) = persist_rollback_entry(conn, &entry) {
                    report.errors.push(rollback_log_write_failed(&e));
                } else {
                    report.rollback_entries_written += 1;
                }
                if let RollbackEntry::Consolidate { originals, .. } = entry {
                    report.memories_consolidated += originals.len();
                }
            }
            Ok(None) => {}
            Err(e) => report.errors.push(format!("consolidate failed: {e}")),
        }
    }

    // Pass 2 — forget superseded.
    for mem in candidates {
        match forget_if_superseded(conn, mem, candidates, dry_run) {
            Ok(Some(entry)) => {
                if !dry_run && let Err(e) = persist_rollback_entry(conn, &entry) {
                    report.errors.push(rollback_log_write_failed(&e));
                } else {
                    report.rollback_entries_written += 1;
                }
                report.memories_forgotten += 1;
            }
            Ok(None) => {}
            Err(e) => report.errors.push(format!("forget failed: {e}")),
        }
    }

    // Pass 3 — priority feedback.
    #[allow(unused_assignments)]
    for mem in candidates {
        match apply_priority_feedback(conn, mem, dry_run) {
            Ok(Some(entry)) => {
                if !dry_run && let Err(e) = persist_rollback_entry(conn, &entry) {
                    report.errors.push(rollback_log_write_failed(&e));
                } else {
                    report.rollback_entries_written += 1;
                }
                report.priority_adjustments += 1;
            }
            Ok(None) => {}
            Err(e) => report.errors.push(format!("priority feedback failed: {e}")),
        }
    }

    report
}

/// v0.7.0 R3-S2 — Two-stage clustering per playbook §2.7 /
/// ROADMAP §5.2:
///
///   1. **Jaccard pre-filter** (cheap, O(N) per pair) — pairs that
///      fail [`CONSOLIDATE_JACCARD_THRESHOLD`] are dropped without
///      paying the embedding lookup. This keeps the pass fast on the
///      typical workload (most pairs are obviously unrelated).
///   2. **Cosine primary** — pairs that survive Jaccard are scored
///      against [`CONSOLIDATE_COSINE_THRESHOLD`] on their 384d
///      MiniLM embeddings (`db::get_embedding`). Above-threshold
///      pairs join the cluster.
///
/// When *either* memory in a pair has no embedding row (e.g.,
/// keyword-tier deployment that never ran the embedder), the cosine
/// stage is skipped for that pair and the Jaccard signal alone
/// decides — preserving v0.6.x behaviour on keyword deployments
/// while making cosine the primary signal anywhere the embedder is
/// available. The function never errors on a DB read miss; it
/// silently degrades to Jaccard so a partial-coverage corpus (some
/// embedded, some not) still clusters productively.
fn find_consolidation_clusters(conn: &Connection, candidates: &[Memory]) -> Vec<Vec<Memory>> {
    // Group by namespace first — we never merge across namespaces.
    let mut by_ns: std::collections::HashMap<&str, Vec<&Memory>> = std::collections::HashMap::new();
    for m in candidates {
        if m.namespace.starts_with('_') {
            continue;
        }
        by_ns.entry(&m.namespace).or_default().push(m);
    }

    let mut clusters: Vec<Vec<Memory>> = Vec::new();
    for (_ns, group) in by_ns {
        let mut used = vec![false; group.len()];
        for i in 0..group.len() {
            if used[i] {
                continue;
            }
            let mut cluster = vec![group[i].clone()];
            used[i] = true;
            // Cache the seed memory's embedding (looked up once per
            // outer-loop iteration). `None` means "embedding missing
            // for this memory" — we fall back to Jaccard-only on the
            // inner pairs.
            let seed_emb = db::get_embedding(conn, &group[i].id).ok().flatten();
            for j in (i + 1)..group.len() {
                if used[j] {
                    continue;
                }
                if cluster.len() >= CONSOLIDATE_MAX_CLUSTER_SIZE {
                    break;
                }
                // Stage 1 — Jaccard pre-filter (cheap).
                let j_sim = jaccard_similarity(&group[i].content, &group[j].content);
                if j_sim < CONSOLIDATE_JACCARD_THRESHOLD {
                    continue;
                }
                // Stage 2 — cosine primary, when embeddings exist
                // for both sides of the pair.
                let pair_emb = db::get_embedding(conn, &group[j].id).ok().flatten();
                let matches_cluster = match (seed_emb.as_ref(), pair_emb.as_ref()) {
                    (Some(a), Some(b)) => {
                        let cos = f64::from(crate::embeddings::Embedder::cosine_similarity(a, b));
                        cos >= CONSOLIDATE_COSINE_THRESHOLD
                    }
                    // At least one side has no embedding — fall back
                    // to Jaccard-only (already passed the pre-filter
                    // above so the pair clusters).
                    _ => true,
                };
                if matches_cluster {
                    cluster.push(group[j].clone());
                    used[j] = true;
                }
            }
            if cluster.len() >= 2 {
                clusters.push(cluster);
            }
        }
    }
    clusters
}

fn jaccard_similarity(a: &str, b: &str) -> f64 {
    use std::collections::HashSet;
    let tokens = |s: &str| -> HashSet<String> {
        s.split(|c: char| !c.is_alphanumeric())
            .filter(|t| t.len() >= 3)
            .map(str::to_lowercase)
            .collect()
    };
    let ta = tokens(a);
    let tb = tokens(b);
    if ta.is_empty() && tb.is_empty() {
        return 0.0;
    }
    let inter = ta.intersection(&tb).count();
    let union = ta.union(&tb).count();
    if union == 0 {
        0.0
    } else {
        #[allow(clippy::cast_precision_loss)]
        let result = inter as f64 / union as f64;
        result
    }
}

fn consolidate_cluster(
    conn: &Connection,
    llm: &dyn AutonomyLlm,
    cluster: &[Memory],
    dry_run: bool,
) -> Result<Option<RollbackEntry>> {
    if cluster.len() < 2 {
        return Ok(None);
    }
    // Skip clusters inside reserved namespaces (defensive; already
    // filtered at find_consolidation_clusters).
    if cluster.iter().any(|m| m.namespace.starts_with('_')) {
        return Ok(None);
    }

    let input: Vec<(String, String)> = cluster
        .iter()
        .map(|m| (m.title.clone(), m.content.clone()))
        .collect();
    let summary = llm.summarize_memories(&input)?;
    // Prefix the consolidated title so it never collides with one of
    // the source memories' (title, namespace) UNIQUE key. Source
    // rows still exist at INSERT time — db::consolidate deletes them
    // only after the new row lands.
    let base_title = cluster
        .iter()
        .map(|m| m.title.as_str())
        .next()
        .unwrap_or("(consolidated)");
    let title = format!("[consolidated] {base_title}");

    if dry_run {
        return Ok(Some(RollbackEntry::Consolidate {
            originals: cluster.to_vec(),
            result_id: "dry-run".to_string(),
        }));
    }

    let ids: Vec<String> = cluster.iter().map(|m| m.id.clone()).collect();
    let namespace = cluster[0].namespace.clone();
    // Tier = max of cluster (consolidate never downgrades).
    let tier = cluster
        .iter()
        .map(|m| m.tier.clone())
        .max_by_key(tier_rank)
        .unwrap_or(Tier::Mid);

    let result_id = db::consolidate(
        conn,
        &ids,
        &title,
        &summary,
        &namespace,
        &tier,
        CURATOR_SOURCE_LABEL,
        crate::identity::sentinels::AI_CURATOR,
    )?;

    Ok(Some(RollbackEntry::Consolidate {
        originals: cluster.to_vec(),
        result_id,
    }))
}

fn tier_rank(t: &Tier) -> u8 {
    match t {
        Tier::Short => 0,
        Tier::Mid => 1,
        Tier::Long => 2,
    }
}

fn forget_if_superseded(
    conn: &Connection,
    mem: &Memory,
    all: &[Memory],
    dry_run: bool,
) -> Result<Option<RollbackEntry>> {
    // Only act on memories whose `confirmed_contradictions` list is
    // non-empty — i.e., a previous detect_contradiction pass already
    // flagged this pair.
    let contradictions = mem
        .metadata
        .get(field_names::CONFIRMED_CONTRADICTIONS)
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    if contradictions.is_empty() {
        return Ok(None);
    }

    // The current memory is superseded if a contradicting memory is
    // both newer AND has higher-or-equal confidence. We never forget
    // based on the contradicting memory alone — the decision requires
    // both freshness and trust.
    let by_id: std::collections::HashMap<&str, &Memory> =
        all.iter().map(|m| (m.id.as_str(), m)).collect();
    let mut superseder: Option<&Memory> = None;
    for v in contradictions {
        let Some(other_id) = v.as_str() else {
            continue;
        };
        if let Some(other) = by_id.get(other_id)
            && other.updated_at > mem.updated_at
            && other.confidence >= mem.confidence
        {
            superseder = Some(other);
            break;
        }
    }
    let Some(_) = superseder else {
        return Ok(None);
    };

    if dry_run {
        return Ok(Some(RollbackEntry::Forget {
            snapshot: mem.clone(),
        }));
    }

    // IMPORTANT: `db::delete` hard-deletes (no archive row). Recovery
    // for a forgotten memory relies on the RollbackEntry::Forget
    // snapshot we return — the caller persists it in `_curator/rollback`
    // with the full pre-forget memory embedded. That rollback entry
    // is long-tier so it's not auto-GC'd; `ai-memory curator --rollback
    // <id>` reverses the forget from that snapshot. (#300 item 1:
    // comment previously claimed db::delete archives; it does not.)
    db::delete(conn, &mem.id)?;

    Ok(Some(RollbackEntry::Forget {
        snapshot: mem.clone(),
    }))
}

fn apply_priority_feedback(
    conn: &Connection,
    mem: &Memory,
    dry_run: bool,
) -> Result<Option<RollbackEntry>> {
    // Access-signal policy:
    //   access_count >= 10 AND last_accessed_at within 7d → +1 (cap 10)
    //   access_count == 0 AND created_at older than 30d     → -1 (floor 1)
    //   else no change.
    let now = chrono::Utc::now();
    let before = mem.priority;
    let mut after = before;

    let last_accessed = mem
        .last_accessed_at
        .as_deref()
        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
        .map(chrono::DateTime::<chrono::Utc>::from);

    let created = chrono::DateTime::parse_from_rfc3339(&mem.created_at)
        .ok()
        .map(chrono::DateTime::<chrono::Utc>::from);

    let recent = last_accessed.is_some_and(|t| (now - t).num_days() <= 7);
    let cold_enough = created.is_some_and(|t| (now - t).num_days() >= 30);

    if mem.access_count >= 10 && recent && after < 10 {
        after = after.saturating_add(1).min(10);
    } else if mem.access_count == 0 && cold_enough && after > 1 {
        after = after.saturating_sub(1).max(1);
    }

    if after == before {
        return Ok(None);
    }

    if !dry_run {
        db::update(
            conn,
            &mem.id,
            None,
            None,
            None,
            None,
            None,
            Some(after),
            None,
            None,
            None,
        )?;
    }

    Ok(Some(RollbackEntry::PriorityAdjust {
        memory_id: mem.id.clone(),
        before,
        after,
    }))
}

/// #1558 batch 5 wave 2 — canonical `"rollback-log write failed: {e}"`
/// report-error line shared by the three [`persist_rollback_entry`]
/// failure sites in the autonomy passes. Byte-identical message.
fn rollback_log_write_failed(e: &dyn std::fmt::Display) -> String {
    format!("rollback-log write failed: {e}")
}

fn persist_rollback_entry(conn: &Connection, entry: &RollbackEntry) -> Result<()> {
    let now = chrono::Utc::now();
    let ts = now.to_rfc3339();
    let mem = Memory {
        id: uuid::Uuid::new_v4().to_string(),
        tier: Tier::Long,
        namespace: format!("{CURATOR_NAMESPACE}/rollback"),
        title: format!("curator {} @ {}", entry.action_tag(), ts),
        content: serde_json::to_string(entry)?,
        tags: vec![
            "_curator".to_string(),
            "_rollback".to_string(),
            entry.action_tag().to_string(),
        ],
        priority: 3,
        confidence: 1.0,
        source: CURATOR_SOURCE_LABEL.to_string(),
        access_count: 0,
        created_at: ts.clone(),
        updated_at: ts,
        last_accessed_at: None,
        expires_at: None,
        metadata: serde_json::json!({
            "agent_id": crate::identity::sentinels::AI_CURATOR,
            "action": entry.action_tag(),
        }),
        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,
    };
    db::insert(conn, &mem)?;
    Ok(())
}

/// Write the cycle's report as a memory in `_curator/reports/<ts>`
/// so other agents can recall "what did the curator do".
pub fn persist_self_report(
    conn: &Connection,
    cycle_duration_ms: u128,
    pass_report: &AutonomyPassReport,
    auto_tagged: usize,
    contradictions_found: usize,
    // Issue #816 — count of `__persona_<entity_id>_v<n>` rows the
    // curator's auto-persona sweep produced this cycle. Surfaces in the
    // self-report JSON alongside the existing per-pass counters so an
    // operator inspecting `_curator/reports/*` can audit auto-persona
    // activity over time without joining against the persona rows
    // themselves.
    personas_generated: usize,
    errors_total: usize,
) -> Result<()> {
    let now = chrono::Utc::now();
    let ts = now.to_rfc3339();
    let body = serde_json::json!({
        "cycle_ts": ts,
        "cycle_duration_ms": cycle_duration_ms,
        "auto_tagged": auto_tagged,
        "contradictions_found": contradictions_found,
        "personas_generated": personas_generated,
        "clusters_formed": pass_report.clusters_formed,
        "memories_consolidated": pass_report.memories_consolidated,
        "memories_forgotten": pass_report.memories_forgotten,
        "priority_adjustments": pass_report.priority_adjustments,
        "rollback_entries_written": pass_report.rollback_entries_written,
        "errors_total": errors_total,
    });
    let mem = Memory {
        id: uuid::Uuid::new_v4().to_string(),
        tier: Tier::Mid,
        namespace: format!("{CURATOR_NAMESPACE}/reports"),
        title: format!("curator cycle @ {ts}"),
        content: serde_json::to_string_pretty(&body)?,
        tags: vec!["_curator".to_string(), "_report".to_string()],
        priority: 2,
        confidence: 1.0,
        source: CURATOR_SOURCE_LABEL.to_string(),
        access_count: 0,
        created_at: ts.clone(),
        updated_at: ts,
        last_accessed_at: None,
        expires_at: None,
        metadata: serde_json::json!({"agent_id": crate::identity::sentinels::AI_CURATOR}),
        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,
    };
    db::insert(conn, &mem)?;
    Ok(())
}

/// Reverse a single rollback-log entry. Returns `true` if a reverse
/// action was applied, `false` if the entry was already superseded
/// (idempotent rollback).
///
/// Collision safety (#300 item 2): before re-inserting a snapshot we
/// check whether another memory now owns the same
/// `(title, namespace)` key. If it does, we refuse to overwrite —
/// `db::insert` is an UPSERT on that key and would silently replace
/// the unrelated memory's content. We return an error so the operator
/// can resolve the conflict manually (delete the offender or rename
/// one of them) rather than clobbering user data.
pub fn reverse_rollback_entry(conn: &Connection, entry: &RollbackEntry) -> Result<bool> {
    match entry {
        RollbackEntry::Consolidate {
            originals,
            result_id,
        } => {
            // Pre-flight: no title+ns collision against a different id?
            for m in originals {
                check_no_collision(conn, &m.title, &m.namespace, &m.id)?;
            }
            // Delete the consolidated memory; re-insert the originals.
            let existed = db::delete(conn, result_id)?;
            for m in originals {
                db::insert(conn, m)?;
            }
            Ok(existed)
        }
        RollbackEntry::Forget { snapshot } => {
            check_no_collision(conn, &snapshot.title, &snapshot.namespace, &snapshot.id)?;
            db::insert(conn, snapshot)?;
            Ok(true)
        }
        RollbackEntry::PriorityAdjust {
            memory_id,
            before,
            after: _,
        } => {
            let _ = db::update(
                conn,
                memory_id,
                None,
                None,
                None,
                None,
                None,
                Some(*before),
                None,
                None,
                None,
            )?;
            Ok(true)
        }
    }
}

/// Refuse to overwrite a memory that took the (title, namespace) slot
/// after the rollback target was forgotten/consolidated.
fn check_no_collision(
    conn: &Connection,
    title: &str,
    namespace: &str,
    expected_id: &str,
) -> Result<()> {
    let rows = db::list(
        conn,
        Some(namespace),
        None,
        50,
        0,
        None,
        None,
        None,
        None,
        None,
    )?;
    for row in rows {
        if row.namespace == namespace && row.title == title && row.id != expected_id {
            anyhow::bail!(
                "rollback aborted: memory {} now occupies (title={:?}, namespace={:?}) — \
                 reverting would overwrite it. Resolve the conflict manually.",
                row.id,
                title,
                namespace
            );
        }
    }
    Ok(())
}

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

    /// In-test LLM stub. Deterministic: returns fixed tags + treats
    /// "contradict" as a sentinel in content to flag contradictions.
    struct StubLlm {
        // Read by the trait impls below; the test paths in this module exercise
        // `summarize_memories` only, so rustc 1.93+ flags these reads as dead.
        // Curator and MCP integration tests (in `mcp.rs`/`curator.rs`) cover
        // `auto_tag` and `detect_contradiction`; this stub keeps the protocol
        // complete so any future autonomy test can exercise either method.
        #[allow(dead_code)]
        auto_tag_result: Vec<String>,
        summary: String,
        #[allow(dead_code)]
        contradiction_sentinel: String,
        calls: Mutex<Vec<String>>,
    }

    impl StubLlm {
        fn new(summary: &str) -> Self {
            Self {
                auto_tag_result: vec!["auto".to_string(), "stub".to_string()],
                summary: summary.to_string(),
                contradiction_sentinel: "CONTRADICTS".to_string(),
                calls: Mutex::new(Vec::new()),
            }
        }
    }

    impl AutonomyLlm for StubLlm {
        fn auto_tag(&self, title: &str, _content: &str) -> Result<Vec<String>> {
            self.calls.lock().unwrap().push(format!("auto_tag:{title}"));
            Ok(self.auto_tag_result.clone())
        }
        fn detect_contradiction(&self, a: &str, b: &str) -> Result<bool> {
            self.calls
                .lock()
                .unwrap()
                .push("detect_contradiction".to_string());
            Ok(
                a.contains(&self.contradiction_sentinel)
                    || b.contains(&self.contradiction_sentinel),
            )
        }
        fn summarize_memories(&self, memories: &[(String, String)]) -> Result<String> {
            self.calls
                .lock()
                .unwrap()
                .push(format!("summarize:{}", memories.len()));
            Ok(self.summary.clone())
        }
    }

    fn sample_mem(id: &str, ns: &str, title: &str, content: &str, tier: Tier) -> Memory {
        let now = chrono::Utc::now().to_rfc3339();
        Memory {
            id: id.to_string(),
            tier,
            namespace: ns.to_string(),
            title: title.to_string(),
            content: content.to_string(),
            tags: vec!["t".to_string()],
            priority: 5,
            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: serde_json::json!({"agent_id":"ai:test"}),
            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,
        }
    }

    fn setup_conn() -> (tempfile::NamedTempFile, Connection) {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let conn = db::open(tmp.path()).unwrap();
        (tmp, conn)
    }

    #[test]
    fn jaccard_similarity_basic() {
        let sim = jaccard_similarity(
            "the quick brown fox jumps over",
            "quick brown fox over the lazy",
        );
        assert!(sim > 0.4, "unexpected sim {sim}");
    }

    #[test]
    fn jaccard_similarity_empty() {
        assert!((jaccard_similarity("", "") - 0.0).abs() < 1e-9);
        assert!((jaccard_similarity("abc", "") - 0.0).abs() < 1e-9);
    }

    #[test]
    fn consolidation_clusters_group_by_namespace() {
        let a = sample_mem(
            "a",
            "ns1",
            "A",
            "the quick brown fox jumps over lazy dog",
            Tier::Mid,
        );
        let b = sample_mem(
            "b",
            "ns1",
            "B",
            "quick brown fox over lazy dog jumps",
            Tier::Mid,
        );
        let c = sample_mem(
            "c",
            "ns2",
            "C",
            "the quick brown fox jumps over lazy dog",
            Tier::Mid,
        );
        let (_tmp, conn) = setup_conn();
        let clusters = find_consolidation_clusters(&conn, &[a, b, c]);
        // ns1 should cluster a+b; ns2 has only one memory so no cluster.
        assert_eq!(clusters.len(), 1);
        assert_eq!(clusters[0].len(), 2);
    }

    #[test]
    fn consolidation_skips_reserved_namespace() {
        let a = sample_mem("a", "_curator/reports", "A", "content aaaa bbbb", Tier::Mid);
        let b = sample_mem("b", "_curator/reports", "B", "content aaaa bbbb", Tier::Mid);
        let (_tmp, conn) = setup_conn();
        let clusters = find_consolidation_clusters(&conn, &[a, b]);
        assert!(clusters.is_empty());
    }

    // -----------------------------------------------------------------
    // v0.7.0 R3-S2 — consolidation clustering uses cosine as primary
    // when embeddings are present; falls back to Jaccard otherwise.
    // -----------------------------------------------------------------

    /// Build a synthetic L2-normalized embedding from a small seed
    /// vector. Used to drive the cosine cluster path without
    /// requiring an actual embedder load.
    fn synth_emb(values: &[f32]) -> Vec<f32> {
        let norm: f32 = values.iter().map(|v| v * v).sum::<f32>().sqrt();
        if norm < 1e-12 {
            return values.to_vec();
        }
        values.iter().map(|v| v / norm).collect()
    }

    /// `test_consolidation_uses_cosine_when_embeddings_present` —
    /// two memories whose contents look *jaccard-similar* but whose
    /// embeddings are deliberately *cosine-DISsimilar* must NOT
    /// cluster. This proves cosine is the primary signal and Jaccard
    /// alone no longer drives consolidation when embeddings exist.
    #[test]
    fn test_consolidation_uses_cosine_when_embeddings_present() {
        let (_tmp, conn) = setup_conn();
        // Same lexical content (Jaccard ≈ 1.0) so the pre-filter
        // would pass — but we attach orthogonal embeddings so cosine
        // is ~0, well below the 0.75 threshold.
        let a = sample_mem(
            "a",
            "ns1",
            "A",
            "the quick brown fox jumps over lazy dog",
            Tier::Mid,
        );
        let b = sample_mem(
            "b",
            "ns1",
            "B",
            "the quick brown fox jumps over lazy dog",
            Tier::Mid,
        );

        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();
        // Orthogonal 4-d embeddings: cosine sim = 0.
        db::set_embedding(&conn, &a.id, &synth_emb(&[1.0, 0.0, 0.0, 0.0])).unwrap();
        db::set_embedding(&conn, &b.id, &synth_emb(&[0.0, 1.0, 0.0, 0.0])).unwrap();

        let clusters = find_consolidation_clusters(&conn, &[a, b]);
        assert!(
            clusters.is_empty(),
            "cosine-dissimilar embeddings must defeat the Jaccard-only cluster (cosine is primary)",
        );

        // Symmetry: cosine-SIMilar embeddings on the same Jaccard
        // pair MUST cluster. Reuse fresh memories to avoid the
        // UPSERT collision.
        let c = sample_mem(
            "c",
            "ns2",
            "C",
            "the quick brown fox jumps over lazy dog",
            Tier::Mid,
        );
        let d = sample_mem(
            "d",
            "ns2",
            "D",
            "the quick brown fox jumps over lazy dog",
            Tier::Mid,
        );
        db::insert(&conn, &c).unwrap();
        db::insert(&conn, &d).unwrap();
        // Nearly-identical embeddings: cosine sim ≈ 1.0.
        db::set_embedding(&conn, &c.id, &synth_emb(&[1.0, 0.0, 0.0, 0.0])).unwrap();
        db::set_embedding(&conn, &d.id, &synth_emb(&[0.99, 0.1, 0.0, 0.0])).unwrap();

        let clusters2 = find_consolidation_clusters(&conn, &[c, d]);
        assert_eq!(
            clusters2.len(),
            1,
            "cosine-similar embeddings on a Jaccard-similar pair must cluster"
        );
        assert_eq!(clusters2[0].len(), 2);
    }

    /// `test_consolidation_falls_back_to_jaccard_no_embeddings` —
    /// keyword-tier corpus (no embeddings persisted) still clusters
    /// via Jaccard alone. This preserves v0.6.x consolidation
    /// behaviour on deployments that never run the embedder.
    #[test]
    fn test_consolidation_falls_back_to_jaccard_no_embeddings() {
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "a",
            "ns",
            "A",
            "kubernetes rolling canary deploy strategy keyword keyword",
            Tier::Long,
        );
        let b = sample_mem(
            "b",
            "ns",
            "B",
            "kubernetes rolling canary deploy strategy keyword keyword",
            Tier::Long,
        );
        // Insert WITHOUT attaching embeddings — get_embedding returns
        // None, the cosine stage is skipped, Jaccard alone decides.
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();

        let clusters = find_consolidation_clusters(&conn, &[a, b]);
        assert_eq!(
            clusters.len(),
            1,
            "keyword-tier corpus (no embeddings) must still cluster via Jaccard"
        );
        assert_eq!(clusters[0].len(), 2);
    }

    #[test]
    fn rollback_entry_serialises() {
        let e = RollbackEntry::PriorityAdjust {
            memory_id: "m1".to_string(),
            before: 5,
            after: 6,
        };
        let json = serde_json::to_string(&e).unwrap();
        assert!(json.contains("priority_adjust"));
        let back: RollbackEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(back.action_tag(), "priority_adjust");
    }

    #[test]
    fn consolidate_cluster_merges_two_memories() {
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "a",
            "app",
            "Deploy plan",
            "kubernetes rolling deploy with canary",
            Tier::Long,
        );
        let b = sample_mem(
            "b",
            "app",
            "Deploy process",
            "kubernetes deploy rolling canary strategy",
            Tier::Long,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();
        let llm = StubLlm::new("consolidated deploy plan");
        let cluster = vec![a.clone(), b.clone()];
        let entry = consolidate_cluster(&conn, &llm, &cluster, false)
            .unwrap()
            .expect("expected rollback entry");
        match entry {
            RollbackEntry::Consolidate {
                originals,
                result_id,
            } => {
                assert_eq!(originals.len(), 2);
                assert_ne!(result_id, "dry-run");
                let got = db::get(&conn, &result_id).unwrap().expect("result memory");
                assert_eq!(got.namespace, "app");
                assert!(got.title.starts_with("[consolidated]"));
                assert!(got.content.contains("consolidated deploy plan"));
            }
            _ => panic!("expected Consolidate"),
        }
    }

    #[test]
    fn dry_run_does_not_write() {
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "a",
            "app",
            "Deploy plan",
            "kubernetes rolling deploy with canary",
            Tier::Long,
        );
        let b = sample_mem(
            "b",
            "app",
            "Deploy process",
            "kubernetes deploy rolling canary strategy",
            Tier::Long,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();
        let llm = StubLlm::new("never persisted");
        let cluster = vec![a.clone(), b.clone()];
        let entry = consolidate_cluster(&conn, &llm, &cluster, true)
            .unwrap()
            .expect("dry-run returns entry");
        if let RollbackEntry::Consolidate { result_id, .. } = entry {
            assert_eq!(result_id, "dry-run");
        }
        // Originals still present, no consolidated row added.
        assert!(db::get(&conn, "a").unwrap().is_some());
        assert!(db::get(&conn, "b").unwrap().is_some());
    }

    #[test]
    fn reverse_consolidation_restores_originals() {
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "a",
            "app",
            "Deploy plan",
            "kubernetes rolling deploy canary",
            Tier::Long,
        );
        let b = sample_mem(
            "b",
            "app",
            "Deploy process",
            "kubernetes rolling canary strategy",
            Tier::Long,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();

        let llm = StubLlm::new("summary");
        let cluster = vec![a.clone(), b.clone()];
        let entry = consolidate_cluster(&conn, &llm, &cluster, false)
            .unwrap()
            .expect("entry");

        // After consolidation, originals should be gone (merged into
        // the result id).
        if let RollbackEntry::Consolidate {
            result_id,
            originals,
        } = &entry
        {
            assert!(db::get(&conn, result_id).unwrap().is_some());
            for orig in originals {
                assert!(
                    db::get(&conn, &orig.id).unwrap().is_none(),
                    "{} should be merged-away",
                    orig.id
                );
            }
        }

        // Rollback: originals come back, result is removed.
        reverse_rollback_entry(&conn, &entry).unwrap();
        assert!(db::get(&conn, "a").unwrap().is_some());
        assert!(db::get(&conn, "b").unwrap().is_some());
        if let RollbackEntry::Consolidate { result_id, .. } = &entry {
            assert!(db::get(&conn, result_id).unwrap().is_none());
        }
    }

    #[test]
    fn full_autonomy_cycle_end_to_end() {
        let (_tmp, conn) = setup_conn();
        let llm = StubLlm::new("consolidated");

        // Seed: two near-duplicates in "deploy", one unrelated doc in
        // "chat", and a pair with a confirmed-contradictions pointer.
        let m_a = sample_mem(
            "ma",
            "deploy",
            "canary deploy plan",
            "kubernetes canary rolling deploy strategy",
            Tier::Long,
        );
        let m_b = sample_mem(
            "mb",
            "deploy",
            "canary deploy overview",
            "kubernetes rolling canary deploy strategy",
            Tier::Long,
        );
        let m_chat = sample_mem(
            "mchat",
            "chat",
            "hello",
            "hi there chat only content here",
            Tier::Mid,
        );

        // Superseded pair: m_old is older AND has a confirmed
        // contradiction against m_new.
        let mut m_old = sample_mem(
            "mold",
            "facts",
            "fact v1",
            "the sky is green always uniformly",
            Tier::Long,
        );
        let m_new_id = "mnew";
        m_old.metadata["confirmed_contradictions"] = serde_json::json!([m_new_id]);
        // Push m_old's updated_at to the past so m_new's default now
        // is strictly newer.
        m_old.updated_at = (chrono::Utc::now() - chrono::Duration::days(30)).to_rfc3339();
        let m_new = sample_mem(
            m_new_id,
            "facts",
            "fact v2",
            "the sky is blue most of the time for sure",
            Tier::Long,
        );

        for m in [&m_a, &m_b, &m_chat, &m_old, &m_new] {
            db::insert(&conn, m).unwrap();
        }

        let candidates = vec![
            m_a.clone(),
            m_b.clone(),
            m_chat.clone(),
            m_old.clone(),
            m_new.clone(),
        ];
        let report = run_autonomy_passes(&conn, &llm, &candidates, false);

        // Consolidated at least once (deploy cluster).
        assert!(report.clusters_formed >= 1);
        assert!(report.memories_consolidated >= 2);
        // Forgot m_old because it's superseded by m_new.
        assert!(
            report.memories_forgotten >= 1,
            "expected ≥1 forget, got {report:?}"
        );
        // Rollback entries written for each action.
        assert!(report.rollback_entries_written >= report.clusters_formed);
        // Rollback-log memories exist.
        let log = db::list(
            &conn,
            Some("_curator/rollback"),
            None,
            100,
            0,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert!(!log.is_empty(), "rollback log should be populated");
    }

    #[test]
    fn self_report_written_to_reports_namespace() {
        let (_tmp, conn) = setup_conn();
        let pass = AutonomyPassReport {
            clusters_formed: 1,
            memories_consolidated: 2,
            memories_forgotten: 0,
            priority_adjustments: 1,
            rollback_entries_written: 2,
            errors: vec![],
        };
        persist_self_report(&conn, 1234, &pass, 3, 0, 0, 0).unwrap();
        let reports = db::list(
            &conn,
            Some("_curator/reports"),
            None,
            10,
            0,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(reports.len(), 1);
        assert!(reports[0].content.contains("memories_consolidated"));
    }

    #[test]
    fn smart_tier_mock_cycle_summarize() {
        // Test that autonomy invokes the LLM's summarize_memories in consolidation.
        let (_tmp, conn) = setup_conn();
        // Use similar enough content to exceed the Jaccard threshold (0.55)
        let a = sample_mem(
            "mem-a",
            "app",
            "Deploy A",
            "kubernetes deployment rolling canary strategy kubernetes rolling deploy canary",
            Tier::Mid,
        );
        let b = sample_mem(
            "mem-b",
            "app",
            "Deploy B",
            "kubernetes deployment rolling canary approach kubernetes rolling canary deploy",
            Tier::Mid,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();

        let llm = StubLlm::new("LLM-generated consolidated summary");
        let candidates = vec![a, b];

        let report = run_autonomy_passes(&conn, &llm, &candidates, false);

        // Key assertions: LLM was used (clusters formed and consolidation happened)
        assert!(report.clusters_formed > 0);
        assert!(report.memories_consolidated > 0);
    }

    #[test]
    fn autonomy_cycle_with_mock_ollama() {
        // Test run_autonomy_passes end-to-end with StubLlm
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "id-1",
            "ns1",
            "Title A",
            "content similar enough for clustering test similar clustering",
            Tier::Mid,
        );
        let b = sample_mem(
            "id-2",
            "ns1",
            "Title B",
            "content similar enough for clustering test similar clustering",
            Tier::Mid,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();

        let llm = StubLlm::new("mock summary result");
        let candidates = vec![a, b];

        let report = run_autonomy_passes(&conn, &llm, &candidates, false);

        // Report should reflect successful cycle
        assert_eq!(report.errors.len(), 0, "autonomy cycle should not error");
        assert!(
            report.rollback_entries_written > 0,
            "autonomy cycle should write rollback entries"
        );
    }

    #[test]
    fn rollback_log_captures_consolidation() {
        // Verify rollback log correctly records a consolidation
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "a",
            "test-ns",
            "Memory A",
            "test content aaaa bbbb cccc aaaa bbbb",
            Tier::Mid,
        );
        let b = sample_mem(
            "b",
            "test-ns",
            "Memory B",
            "test content aaaa bbbb cccc aaaa bbbb",
            Tier::Mid,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();

        let llm = StubLlm::new("consolidated");
        let cluster = vec![a.clone(), b.clone()];
        let entry = consolidate_cluster(&conn, &llm, &cluster, false)
            .unwrap()
            .expect("rollback entry");

        // Persist the entry
        persist_rollback_entry(&conn, &entry).unwrap();

        // Verify it's in the rollback log
        let log = db::list(
            &conn,
            Some("_curator/rollback"),
            None,
            100,
            0,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(log.len(), 1);
        assert!(log[0].content.contains("consolidate"));
    }

    #[test]
    fn priority_feedback_adjusts_memory() {
        // Verify priority feedback changes memory priority based on access.
        // Policy at apply_priority_feedback: access_count >= 10 AND
        // last_accessed_at within 7d → +1. Set both signals for the bump
        // path, plus an explicit recent-access timestamp.
        let (_tmp, conn) = setup_conn();
        let mut mem = sample_mem("id", "ns", "Title", "content", Tier::Mid);
        mem.priority = 5;
        mem.access_count = 100;
        mem.last_accessed_at = Some(chrono::Utc::now().to_rfc3339());
        db::insert(&conn, &mem).unwrap();

        let entry = apply_priority_feedback(&conn, &mem, false)
            .unwrap()
            .expect("priority feedback should produce entry");

        match entry {
            RollbackEntry::PriorityAdjust {
                memory_id,
                before,
                after,
            } => {
                assert_eq!(memory_id, "id");
                assert_eq!(before, 5);
                assert!(after > before, "high access should increase priority");
            }
            _ => panic!("expected PriorityAdjust"),
        }
    }

    #[test]
    fn dry_run_autonomy_does_not_write() {
        // Verify dry-run mode prevents all writes to DB
        let (_tmp, conn) = setup_conn();
        let a = sample_mem(
            "a",
            "test-ns",
            "Memory A",
            "test content aaaa bbbb cccc aaaa bbbb",
            Tier::Mid,
        );
        let b = sample_mem(
            "b",
            "test-ns",
            "Memory B",
            "test content aaaa bbbb cccc aaaa bbbb",
            Tier::Mid,
        );
        db::insert(&conn, &a).unwrap();
        db::insert(&conn, &b).unwrap();

        let initial_count = db::list(
            &conn,
            Some("test-ns"),
            None,
            100,
            0,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap()
        .len();

        let llm = StubLlm::new("consolidated");
        let candidates = vec![a, b];
        let _report = run_autonomy_passes(&conn, &llm, &candidates, true);

        let final_count = db::list(
            &conn,
            Some("test-ns"),
            None,
            100,
            0,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap()
        .len();

        assert_eq!(
            initial_count, final_count,
            "dry-run should not modify database"
        );
    }

    #[test]
    fn autonomy_passes_report_aggregates_errors() {
        // Verify error aggregation in AutonomyPassReport
        let (_tmp, conn) = setup_conn();
        let mem = sample_mem("id", "ns", "Title", "content", Tier::Mid);
        let llm = StubLlm::new("summary");
        let candidates = vec![mem];
        let report = run_autonomy_passes(&conn, &llm, &candidates, false);

        // At minimum, report structure should be valid
        assert!(report.clusters_formed > 0 || report.clusters_formed == 0);
    }

    // ---- Wave 9 (Closer A9) — RollbackEntry::reverse_* matrix +
    // edge cases for consolidate_cluster / forget_if_superseded /
    // StubLlm impls. These target the lines uncovered after W8.

    /// Reversing a `PriorityAdjust` entry rewrites the priority back to
    /// the captured `before` value. Covers `reverse_rollback_entry`'s
    /// `PriorityAdjust` branch which the W8 suite never exercised end-
    /// to-end.
    #[test]
    fn reverse_priority_adjust_restores_before_value() {
        let (_tmp, conn) = setup_conn();
        let mut mem = sample_mem("pa-id", "ns", "Title", "content", Tier::Mid);
        mem.priority = 7;
        db::insert(&conn, &mem).unwrap();
        // Bump the row to priority=9 to simulate a prior +2 adjustment.
        db::update(
            &conn,
            &mem.id,
            None,
            None,
            None,
            None,
            None,
            Some(9),
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(db::get(&conn, &mem.id).unwrap().unwrap().priority, 9);

        let entry = RollbackEntry::PriorityAdjust {
            memory_id: mem.id.clone(),
            before: 7,
            after: 9,
        };
        let applied = reverse_rollback_entry(&conn, &entry).unwrap();
        assert!(applied);
        assert_eq!(db::get(&conn, &mem.id).unwrap().unwrap().priority, 7);
    }

    /// Reversing a `Forget` entry re-inserts the snapshot. Covers the
    /// happy path through `check_no_collision` + `db::insert` round-trip.
    #[test]
    fn reverse_forget_restores_snapshot() {
        let (_tmp, conn) = setup_conn();
        let mem = sample_mem(
            "forget-id",
            "factual",
            "Snapshot",
            "saved content body abc",
            Tier::Long,
        );
        db::insert(&conn, &mem).unwrap();
        // Simulate the forget happening: hard-delete.
        db::delete(&conn, &mem.id).unwrap();
        assert!(db::get(&conn, &mem.id).unwrap().is_none());

        let entry = RollbackEntry::Forget {
            snapshot: mem.clone(),
        };
        let applied = reverse_rollback_entry(&conn, &entry).unwrap();
        assert!(applied);
        let restored = db::get(&conn, &mem.id).unwrap().expect("snapshot restored");
        assert_eq!(restored.title, "Snapshot");
        assert_eq!(restored.namespace, "factual");
    }

    /// Reversing a `Consolidate` aborts with an error when the
    /// (title, namespace) slot of an original is already taken by an
    /// unrelated memory id — this is `check_no_collision`'s defensive
    /// bail (line ~629) which the W8 suite never reached.
    #[test]
    fn reverse_consolidate_collision_aborts() {
        let (_tmp, conn) = setup_conn();
        let original = sample_mem(
            "o1",
            "app",
            "Deploy plan",
            "kubernetes rolling deploy canary",
            Tier::Long,
        );
        let merged_id = "merged".to_string();
        let entry = RollbackEntry::Consolidate {
            originals: vec![original.clone()],
            result_id: merged_id.clone(),
        };

        // Stand up a different memory at (title=Deploy plan, namespace=app)
        // — the collision target for the rollback.
        let collider = sample_mem(
            "collider-id",
            "app",
            "Deploy plan",
            "different content here entirely",
            Tier::Long,
        );
        db::insert(&conn, &collider).unwrap();

        let err = reverse_rollback_entry(&conn, &entry).expect_err("collision must abort");
        let msg = format!("{err}");
        assert!(msg.contains("rollback aborted"), "unexpected msg: {msg}");
        // Collider is untouched.
        assert!(db::get(&conn, "collider-id").unwrap().is_some());
    }

    /// `consolidate_cluster` short-circuits to `None` when the cluster
    /// has fewer than two members. Covers the `cluster.len() < 2` early
    /// return.
    #[test]
    fn consolidate_cluster_returns_none_for_singleton() {
        let (_tmp, conn) = setup_conn();
        let llm = StubLlm::new("never called");
        let solo = sample_mem("a", "ns", "T", "content body word word", Tier::Mid);
        let result = consolidate_cluster(&conn, &llm, std::slice::from_ref(&solo), false).unwrap();
        assert!(result.is_none());
    }

    /// `consolidate_cluster` defensively skips clusters whose members
    /// are in a reserved (`_`-prefixed) namespace. Covers the second
    /// early return path (line ~294).
    #[test]
    fn consolidate_cluster_skips_reserved_namespace_defensive() {
        let (_tmp, conn) = setup_conn();
        let llm = StubLlm::new("never called");
        let a = sample_mem("a", "_curator/rollback", "T1", "abc abc abc abc", Tier::Mid);
        let b = sample_mem("b", "_curator/rollback", "T2", "abc abc abc abc", Tier::Mid);
        let result = consolidate_cluster(&conn, &llm, &[a, b], false).unwrap();
        assert!(
            result.is_none(),
            "reserved-namespace cluster must be skipped"
        );
    }

    /// In dry_run mode, `forget_if_superseded` returns a `Forget`
    /// rollback entry **without** deleting the underlying row. Covers
    /// the dry-run branch (lines ~397-399) of `forget_if_superseded`.
    #[test]
    fn forget_if_superseded_dry_run_returns_entry_without_delete() {
        let (_tmp, conn) = setup_conn();
        let mut older = sample_mem("old", "facts", "fact v1", "the sky is green", Tier::Long);
        older.metadata["confirmed_contradictions"] = serde_json::json!(["new"]);
        older.updated_at = (chrono::Utc::now() - chrono::Duration::days(30)).to_rfc3339();
        let newer = sample_mem("new", "facts", "fact v2", "the sky is blue", Tier::Long);
        db::insert(&conn, &older).unwrap();
        db::insert(&conn, &newer).unwrap();

        let result = forget_if_superseded(&conn, &older, &[older.clone(), newer], true).unwrap();
        match result {
            Some(RollbackEntry::Forget { snapshot }) => {
                assert_eq!(snapshot.id, "old");
            }
            _ => panic!("expected Forget entry from dry-run forget"),
        }
        // Dry-run preserves the row.
        assert!(db::get(&conn, "old").unwrap().is_some());
    }

    /// `forget_if_superseded` skips non-string entries in the
    /// `confirmed_contradictions` array — covers the `let Some(...) =
    /// v.as_str() else { continue; };` branch (line ~382).
    #[test]
    fn forget_if_superseded_skips_non_string_contradiction_ids() {
        let (_tmp, conn) = setup_conn();
        let mut mem = sample_mem("m", "facts", "T", "content body word", Tier::Mid);
        // Mix invalid (number) and valid-but-missing (no matching id) entries.
        mem.metadata["confirmed_contradictions"] = serde_json::json!([42, "missing-id"]);
        let result = forget_if_superseded(&conn, &mem, std::slice::from_ref(&mem), false).unwrap();
        // No superseder identified (numeric id skipped, "missing-id" not in `all`).
        assert!(result.is_none());
    }

    /// Exercise the `StubLlm::auto_tag` and `StubLlm::detect_contradiction`
    /// trait impls directly — they exist for completeness of the
    /// `AutonomyLlm` trait surface but the autonomy code itself only
    /// calls `summarize_memories`, so without a direct hit they are
    /// uncovered (lines ~674-687).
    #[test]
    fn stub_llm_auto_tag_and_detect_contradiction() {
        let llm = StubLlm::new("summary");
        // auto_tag returns the canned tags.
        let tags = AutonomyLlm::auto_tag(&llm, "Some Title", "body").unwrap();
        assert_eq!(tags, vec!["auto".to_string(), "stub".to_string()]);
        // detect_contradiction is sentinel-driven.
        assert!(AutonomyLlm::detect_contradiction(&llm, "this CONTRADICTS that", "ok").unwrap());
        assert!(!AutonomyLlm::detect_contradiction(&llm, "ok", "fine").unwrap());
        // The call log captures both invocations.
        let calls = llm.calls.lock().unwrap();
        assert!(calls.iter().any(|c| c.starts_with("auto_tag:")));
        assert!(calls.iter().any(|c| c == "detect_contradiction"));
    }

    /// `run_autonomy_passes` with `dry_run=true` and a candidate set that
    /// triggers all three pass kinds (consolidate cluster + supersedure
    /// pair + recent-and-hot priority bump candidate) writes nothing to
    /// the DB but still emits a non-trivial report. This stresses the
    /// dry_run branches of every pass at once.
    #[test]
    fn run_autonomy_passes_dry_run_writes_no_changes() {
        let (_tmp, conn) = setup_conn();
        // Cluster pair.
        let m_a = sample_mem(
            "ma",
            "deploy",
            "canary deploy plan",
            "kubernetes canary rolling deploy strategy",
            Tier::Long,
        );
        let m_b = sample_mem(
            "mb",
            "deploy",
            "canary deploy overview",
            "kubernetes rolling canary deploy strategy",
            Tier::Long,
        );
        // Superseded pair.
        let mut m_old = sample_mem(
            "mold",
            "facts",
            "fact v1",
            "the sky is green always uniformly",
            Tier::Long,
        );
        m_old.metadata["confirmed_contradictions"] = serde_json::json!(["mnew"]);
        m_old.updated_at = (chrono::Utc::now() - chrono::Duration::days(30)).to_rfc3339();
        let m_new = sample_mem(
            "mnew",
            "facts",
            "fact v2",
            "the sky is blue most of the time",
            Tier::Long,
        );
        // Hot priority candidate.
        let mut m_hot = sample_mem(
            "hot",
            "ns",
            "Hot",
            "this is hot content for priority bump",
            Tier::Mid,
        );
        m_hot.priority = 5;
        m_hot.access_count = 100;
        m_hot.last_accessed_at = Some(chrono::Utc::now().to_rfc3339());

        for m in [&m_a, &m_b, &m_old, &m_new, &m_hot] {
            db::insert(&conn, m).unwrap();
        }
        let candidates = vec![
            m_a.clone(),
            m_b.clone(),
            m_old.clone(),
            m_new.clone(),
            m_hot.clone(),
        ];

        // Snapshot pre-state.
        let pre_priority = db::get(&conn, &m_hot.id).unwrap().unwrap().priority;
        assert!(db::get(&conn, "mold").unwrap().is_some());

        let llm = StubLlm::new("dry-run summary");
        let report = run_autonomy_passes(&conn, &llm, &candidates, true);

        // Report still reflects the would-be actions.
        assert!(report.clusters_formed >= 1);
        // Dry-run path produces no rollback-log writes (the persist call
        // is gated on `!dry_run`, and even though the counter is bumped,
        // the rollback memories themselves never land).
        let log = db::list(
            &conn,
            Some("_curator/rollback"),
            None,
            100,
            0,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert!(log.is_empty(), "dry-run must not persist rollback memories");

        // Pre-state survives.
        assert_eq!(
            db::get(&conn, &m_hot.id).unwrap().unwrap().priority,
            pre_priority
        );
        assert!(db::get(&conn, "mold").unwrap().is_some());
        assert!(db::get(&conn, "ma").unwrap().is_some());
    }

    /// `run_autonomy_passes` honours an effective max-ops bound in
    /// practice: the cluster-size cap (`CONSOLIDATE_MAX_CLUSTER_SIZE = 8`)
    /// prevents a pathological single mega-cluster, even when many
    /// near-duplicates would otherwise merge. We seed N>cap candidates
    /// and assert the consolidated cluster never exceeds the cap.
    #[test]
    fn consolidation_cluster_respects_max_size_cap() {
        let n = CONSOLIDATE_MAX_CLUSTER_SIZE + 4;
        let mut candidates: Vec<Memory> = Vec::with_capacity(n);
        for i in 0..n {
            candidates.push(sample_mem(
                &format!("m{i}"),
                "deploy",
                &format!("title-{i}"),
                "kubernetes rolling canary deploy strategy",
                Tier::Long,
            ));
        }
        let (_tmp, conn) = setup_conn();
        let clusters = find_consolidation_clusters(&conn, &candidates);
        assert!(!clusters.is_empty());
        for c in &clusters {
            assert!(
                c.len() <= CONSOLIDATE_MAX_CLUSTER_SIZE,
                "cluster size {} exceeded cap {}",
                c.len(),
                CONSOLIDATE_MAX_CLUSTER_SIZE
            );
        }
    }

    /// `apply_priority_feedback` on a cold-and-old memory floors the
    /// priority by -1. Complements the existing hot-and-recent test
    /// (`priority_feedback_adjusts_memory`) — the cold branch is
    /// otherwise unreached.
    #[test]
    fn priority_feedback_decrements_cold_old_memory() {
        let (_tmp, conn) = setup_conn();
        let mut mem = sample_mem(
            "cold-id",
            "ns",
            "Cold",
            "content body content body",
            Tier::Mid,
        );
        mem.priority = 5;
        mem.access_count = 0;
        mem.created_at = (chrono::Utc::now() - chrono::Duration::days(60)).to_rfc3339();
        db::insert(&conn, &mem).unwrap();

        let entry = apply_priority_feedback(&conn, &mem, false)
            .unwrap()
            .expect("cold memory must produce a -1 adjustment");
        match entry {
            RollbackEntry::PriorityAdjust {
                memory_id,
                before,
                after,
            } => {
                assert_eq!(memory_id, "cold-id");
                assert_eq!(before, 5);
                assert_eq!(after, 4);
            }
            _ => panic!("expected PriorityAdjust"),
        }
    }
}