yantrikdb 0.14.1

Cognitive memory engine for persistent AI systems
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
use super::*;

// ── Saga task 20: bundled-embedder auto-attach ──
//
// These tests pin the contract that, on default builds (feature
// `bundled-embedder` is on), `record_text()` and `recall_text()` work
// out of the box — no `set_embedder()` call required. The
// architectural decision (memory rid 019e0686) was that the engine
// ships a default embedder so the user-facing API contract isn't
// "engine plus required side-installs."

#[cfg(feature = "bundled-embedder")]
#[test]
fn bundled_embedder_auto_attaches_on_default_dim() {
    // dim=64 matches BUNDLED_EMBEDDER_DIM (potion-base-2M), so the
    // auto-attach fires. Updated for Slice B (saga task 20, 2026-05-08):
    // bundled embedder switched from hash-trick dim=384 to potion-2M dim=64.
    use crate::embedder::BUNDLED_EMBEDDER_DIM;
    let db = YantrikDB::new(":memory:", BUNDLED_EMBEDDER_DIM).unwrap();
    assert!(
        db.has_embedder(),
        "default-build YantrikDB::new with bundled dim must auto-attach BundledEmbedder"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn with_default_constructor_attaches_bundled_embedder() {
    // YantrikDB::with_default(path) is the constructor that lets callers
    // stay agnostic to the bundled model's dimension. Stays in sync if
    // a future Slice C swaps the bundle to a different-dim variant.
    let db = YantrikDB::with_default(":memory:").unwrap();
    assert!(
        db.has_embedder(),
        "with_default must auto-attach BundledEmbedder"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn bundled_embedder_does_not_attach_on_mismatched_dim() {
    // dim=384 != BUNDLED_EMBEDDER_DIM (64). Auto-attach is silently
    // skipped — caller must set their own embedder. The skip avoids
    // silent dim-mismatch corruption when a caller is intentionally
    // running with a non-default dim (e.g. for an external MiniLM).
    let db = YantrikDB::new(":memory:", 384).unwrap();
    assert!(
        !db.has_embedder(),
        "dim mismatch should NOT auto-attach (avoids silent corruption)"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn bundled_embedder_record_text_round_trip() {
    // The integration shape that actually matters: pip install yantrikdb;
    // YantrikDB::with_default(...); record_text(...); recall_text(...).
    // All works without configuration on default builds.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let _rid = db
        .record_text(
            "Alice met Acme yesterday",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .expect("record_text should work without explicit set_embedder");

    let results = db.recall_text("Alice", 5).expect("recall_text should work");
    assert!(!results.is_empty(), "recall finds the recorded memory");
    assert!(
        results[0].text.contains("Alice"),
        "potion-2M finds the recorded memory; got: {:?}",
        results[0].text
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn record_text_strips_leaked_tool_call_artifact_end_to_end() {
    // Task 29 (Ingest Integrity) wiring regression. Proves the sanitizer is
    // actually invoked on the `record_text` path — not just unit-correct —
    // by storing the exact corpus-signature artifact and asserting the
    // persisted text is clean. The leaked tail must never reach storage or
    // the embedding.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let mangled = "Decision: adopt keyset cursors for list_records.</text>\n\
         <parameter name=\"memory_type\">episodic";
    let rid = db
        .record_text(
            mangled,
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .expect("record_text stores sanitized text");

    let results = db.recall_text("keyset cursors list_records", 5).unwrap();
    let hit = results
        .iter()
        .find(|r| r.rid == rid)
        .expect("the recorded memory is retrievable");
    assert!(
        hit.text.contains("keyset cursors"),
        "real content is preserved; got: {:?}",
        hit.text
    );
    assert!(
        !hit.text.contains("</text>"),
        "the leaked closing tag must be stripped; got: {:?}",
        hit.text
    );
    assert!(
        !hit.text.contains("<parameter name="),
        "the leaked parameter fragment must be stripped; got: {:?}",
        hit.text
    );
    assert_eq!(
        hit.text, "Decision: adopt keyset cursors for list_records.",
        "stored text is exactly the cleaned content"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn repair_tool_call_artifacts_cleans_legacy_corpus() {
    // Task 30 end-to-end. Simulates a row corrupted BEFORE the write-time
    // sanitizer existed, then proves the repair migration detects it
    // (dry-run, no mutation), cleans + re-embeds it (apply), preserves the
    // original for recovery, is idempotent, and leaves recall working.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let clean = "Postgres was chosen for the metadata store";
    let rid = db
        .record_text(
            clean,
            "semantic",
            0.6,
            0.0,
            604800.0,
            &empty_meta(),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();

    // Inject a legacy artifact directly into storage, bypassing record_text
    // (which would now sanitize it). The :memory: db has no encryption, so
    // the stored text is plaintext.
    let dirty = "Postgres was chosen for the metadata store</text>\n\
                 <parameter name=\"memory_type\">semantic";
    {
        let conn = db.conn();
        conn.execute(
            "UPDATE memories SET text = ?1 WHERE rid = ?2",
            rusqlite::params![dirty, rid],
        )
        .unwrap();
    }

    // Dry run detects but does not mutate.
    let dry = db.repair_tool_call_artifacts(true).unwrap();
    assert!(dry.dry_run);
    assert_eq!(dry.artifacts_found, 1);
    assert_eq!(dry.repaired, 0);
    assert!(dry.stripped_bytes > 0);
    {
        let conn = db.conn();
        let t: String = conn
            .query_row(
                "SELECT text FROM memories WHERE rid = ?1",
                rusqlite::params![rid],
                |r| r.get(0),
            )
            .unwrap();
        assert!(t.contains("</text>"), "dry run must NOT mutate");
    }

    // Apply: clean + re-embed + update.
    let applied = db.repair_tool_call_artifacts(false).unwrap();
    assert!(!applied.dry_run);
    assert_eq!(applied.artifacts_found, 1);
    assert_eq!(applied.repaired, 1);
    assert_eq!(applied.skipped_concurrent_modification, 0);
    assert!(applied.errors.is_empty(), "errors: {:?}", applied.errors);

    // The row is now clean.
    {
        let conn = db.conn();
        let t: String = conn
            .query_row(
                "SELECT text FROM memories WHERE rid = ?1",
                rusqlite::params![rid],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(t, clean);
    }

    // The original was preserved for recovery.
    {
        let conn = db.conn();
        let orig: String = conn
            .query_row(
                "SELECT original_text FROM artifact_repair_audit WHERE rid = ?1",
                rusqlite::params![rid],
                |r| r.get(0),
            )
            .unwrap();
        assert!(
            orig.contains("</text>"),
            "audit preserves the dirty original"
        );
    }

    // Idempotent: a second apply finds nothing.
    let again = db.repair_tool_call_artifacts(false).unwrap();
    assert_eq!(again.artifacts_found, 0);
    assert_eq!(again.repaired, 0);

    // Recall still works — the vector index was rebuilt consistently.
    let hits = db.recall_text("database for metadata", 5).unwrap();
    assert!(
        hits.iter().any(|h| h.rid == rid),
        "repaired memory is still retrievable"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn importance_calibration_deflates_saturated_namespace() {
    // Task 31 end-to-end. A fresh namespace preserves importance exactly
    // (identity — this is why existing exact-importance tests still pass);
    // a namespace saturated with max-importance writes deflates further
    // high marks below 1.0 while keeping them in the high band.
    let db = YantrikDB::with_default(":memory:").unwrap();

    let read_importance = |rid: &str| -> f64 {
        let conn = db.conn();
        conn.query_row(
            "SELECT importance FROM memories WHERE rid = ?1",
            rusqlite::params![rid],
            |r| r.get(0),
        )
        .unwrap()
    };

    // Fresh namespace: a single max mark is stored exactly.
    let rid0 = db
        .record_text(
            "first genuinely critical fact",
            "semantic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "fresh",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    assert!(
        (read_importance(&rid0) - 1.0).abs() < 1e-9,
        "fresh namespace preserves importance exactly: {}",
        read_importance(&rid0)
    );

    // Saturate a different namespace with max-importance writes.
    for i in 0..12 {
        db.record_text(
            &format!("everything here is marked critical {i}"),
            "semantic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "saturated",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    }

    // The next max-importance write is deflated.
    let rid = db
        .record_text(
            "yet another self-declared critical fact",
            "semantic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "saturated",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    let imp = read_importance(&rid);
    assert!(imp < 1.0, "saturated namespace deflates importance: {imp}");
    assert!(imp >= 0.70, "but keeps it in the high band: {imp}");

    // The deflated memory is still retrievable.
    let hits = db.recall_text("self-declared critical fact", 5).unwrap();
    assert!(hits.iter().any(|h| h.rid == rid));
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn recalibrate_unused_importance_reverts_stale_high_marks() {
    // Task 32 end-to-end. A high-importance memory that is never accessed
    // reverts toward baseline; a recently-written one is untouched; and the
    // pass is idempotent (re-running does not compound the reversion).
    let db = YantrikDB::with_default(":memory:").unwrap();
    let read_imp = |rid: &str| -> f64 {
        let conn = db.conn();
        conn.query_row(
            "SELECT importance FROM memories WHERE rid = ?1",
            rusqlite::params![rid],
            |r| r.get(0),
        )
        .unwrap()
    };

    let stale = db
        .record_text(
            "a once-critical fact nobody revisits",
            "semantic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    let fresh = db
        .record_text(
            "a fact that was just written",
            "semantic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();

    // Age the first far into the past, never re-accessed.
    {
        let conn = db.conn();
        conn.execute(
            "UPDATE memories SET last_access = 1000.0, access_count = 0 WHERE rid = ?1",
            rusqlite::params![stale],
        )
        .unwrap();
    }

    // Dry run detects exactly the stale candidate, mutating nothing.
    let dry = db.recalibrate_unused_importance(true).unwrap();
    assert!(dry.dry_run);
    assert_eq!(dry.adjusted, 1);
    assert!(
        (read_imp(&stale) - 1.0).abs() < 1e-9,
        "dry run must not mutate"
    );

    // Apply: the stale mark reverts; the fresh one is untouched.
    let applied = db.recalibrate_unused_importance(false).unwrap();
    assert_eq!(applied.adjusted, 1);
    assert!(applied.total_drift > 0.0);
    let reverted = read_imp(&stale);
    assert!(
        reverted < 1.0,
        "stale unused high mark reverted: {reverted}"
    );
    assert!(reverted >= 0.5, "but not below baseline: {reverted}");
    assert!(
        (read_imp(&fresh) - 1.0).abs() < 1e-9,
        "a freshly-written memory is untouched"
    );

    // Idempotent: re-running at the same staleness changes nothing further.
    let again = db.recalibrate_unused_importance(false).unwrap();
    assert_eq!(
        again.adjusted, 0,
        "reversion does not compound across passes"
    );
    assert!((read_imp(&stale) - reverted).abs() < 1e-9);
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn split_oversized_episodes_extracts_linked_atomic_facts() {
    // Task 33 end-to-end. An oversized episodic dump is split into atomic
    // facts, each linked back to the source episode; the parent is demoted
    // out of primary recall; and a query for a specific fact returns the
    // atomic child, not the wall-of-text parent.
    let db = YantrikDB::with_default(":memory:").unwrap();

    let episode = "Session recap. Alice was promoted to engineering lead this week. \
                   The team chose Postgres for the metadata store after benchmarking. \
                   The production launch slipped to March 30 because of the migration. \
                   Bob will own the on-call rotation starting next sprint. \
                   We agreed to cap importance writes so the signal stays meaningful.";
    let parent = db
        .record_text(
            episode,
            "episodic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "recap",
            0.9,
            "work",
            "user",
            None,
        )
        .unwrap();

    // Dry run reports the split without performing it.
    let dry = db.split_oversized_episodes(true, 120).unwrap();
    assert_eq!(dry.episodes_scanned, 1);
    assert_eq!(dry.episodes_split, 0);
    assert!(dry.atomic_facts_created >= 2);

    // Apply.
    let applied = db.split_oversized_episodes(false, 120).unwrap();
    assert_eq!(applied.episodes_split, 1);
    assert!(applied.atomic_facts_created >= 2, "{applied:?}");
    assert!(applied.errors.is_empty(), "errors: {:?}", applied.errors);

    // The parent is demoted to consolidated (retained, out of primary recall).
    {
        let conn = db.conn();
        let status: String = conn
            .query_row(
                "SELECT consolidation_status FROM memories WHERE rid = ?1",
                rusqlite::params![parent],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(status, "consolidated", "parent episode demoted from recall");
    }

    // Atomic-fact children exist, linked back to the parent.
    let children = db
        .linked_records(&parent, crate::types::LinkDirection::Inbound, None)
        .unwrap();
    assert!(
        children.len() >= 2,
        "parent has atomic-fact children linked back: {}",
        children.len()
    );
    assert!(children.iter().all(|c| c.link_type == "derived_from"));

    // A query for a specific fact returns the atomic child, not the parent.
    let hits = db.recall_text("who owns the on-call rotation", 5).unwrap();
    assert!(!hits.is_empty());
    assert_ne!(
        hits[0].rid, parent,
        "top hit is an atomic fact, not the dump"
    );
    assert!(
        hits[0].text.chars().count() < episode.chars().count(),
        "the returned fact is shorter than the original dump"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn conflict_stamping_and_auto_resolution() {
    // Tasks 25 + 26. An open conflict between two memories is surfaced on
    // recall hits (stamp), then auto-resolved by newer-supersedes when it is
    // an unambiguous low/medium type.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let older = db
        .record_text(
            "The launch date is March 15",
            "semantic",
            0.7,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();
    // Force the first memory to be strictly older than the second.
    {
        let conn = db.conn();
        conn.execute(
            "UPDATE memories SET created_at = 1000.0 WHERE rid = ?1",
            rusqlite::params![older],
        )
        .unwrap();
    }
    let newer = db
        .record_text(
            "The launch date is March 30",
            "semantic",
            0.7,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();

    // Insert an open, auto-resolvable (temporal, medium) conflict.
    {
        let conn = db.conn();
        conn.execute(
            "INSERT INTO conflicts \
             (conflict_id, conflict_type, priority, status, memory_a, memory_b, \
              detected_at, detected_by, detection_reason, hlc, origin_actor) \
             VALUES ('cf1', 'temporal', 'medium', 'open', ?1, ?2, 2000.0, 'test', \
                     'same attribute, different value', X'00', 'test')",
            rusqlite::params![older, newer],
        )
        .unwrap();
    }

    // Task 25: the conflict is surfaced on the affected recall hits.
    let hits = db.recall_text("when is the launch date", 5).unwrap();
    let flagged = hits.iter().any(|h| {
        (h.rid == older || h.rid == newer)
            && h.why_retrieved
                .iter()
                .any(|w| w.contains("unresolved") && w.contains("conflict"))
    });
    assert!(flagged, "recall hits carry the conflict warning");

    // Task 26: dry-run reports it as auto-resolvable, mutating nothing.
    let dry = db.auto_resolve_conflicts(true).unwrap();
    assert_eq!(dry.open_before, 1);
    assert_eq!(dry.auto_resolved, 1);
    assert_eq!(dry.routed_to_operator, 0);

    // Apply: newer wins, older is tombstoned, the conflict is resolved.
    let applied = db.auto_resolve_conflicts(false).unwrap();
    assert_eq!(applied.auto_resolved, 1);
    {
        let conn = db.conn();
        let status: String = conn
            .query_row(
                "SELECT status FROM conflicts WHERE conflict_id = 'cf1'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(status, "resolved");
        let older_status: String = conn
            .query_row(
                "SELECT consolidation_status FROM memories WHERE rid = ?1",
                rusqlite::params![older],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(
            older_status, "tombstoned",
            "the older, superseded memory is tombstoned"
        );
    }
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn auto_resolve_routes_identity_conflicts_to_operator() {
    // High-stakes conflicts are never auto-resolved.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let a = db
        .record_text(
            "Pranab lives in Seattle",
            "semantic",
            0.9,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.9,
            "people",
            "user",
            None,
        )
        .unwrap();
    let b = db
        .record_text(
            "Pranab lives in Austin",
            "semantic",
            0.9,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.9,
            "people",
            "user",
            None,
        )
        .unwrap();
    {
        let conn = db.conn();
        conn.execute(
            "INSERT INTO conflicts \
             (conflict_id, conflict_type, priority, status, memory_a, memory_b, \
              detected_at, detected_by, detection_reason, hlc, origin_actor) \
             VALUES ('cf2', 'identity_fact', 'high', 'open', ?1, ?2, 1.0, 'test', \
                     'identity conflict', X'00', 'test')",
            rusqlite::params![a, b],
        )
        .unwrap();
    }
    let report = db.auto_resolve_conflicts(false).unwrap();
    assert_eq!(
        report.auto_resolved, 0,
        "identity/high conflicts are not auto-resolved"
    );
    assert_eq!(report.routed_to_operator, 1);
    let conn = db.conn();
    let status: String = conn
        .query_row(
            "SELECT status FROM conflicts WHERE conflict_id = 'cf2'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(status, "open", "left open for an operator");
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn trigger_prune_bounds_pending_backlog() {
    // Task 27. Overdue triggers expire (TTL); the remaining pending backlog
    // is bounded to max_pending by evicting the lowest-urgency excess;
    // acknowledge removes a trigger from pending. Idempotent.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let insert = |id: &str, urgency: f64, expires_at: Option<f64>| {
        let conn = db.conn();
        conn.execute(
            "INSERT INTO trigger_log \
             (trigger_id, trigger_type, urgency, status, reason, suggested_action, \
              source_rids, context, created_at, expires_at, hlc, origin_actor) \
             VALUES (?1, 'decay_review', ?2, 'pending', 'r', 'a', '[]', '{}', 100.0, ?3, \
                     X'00', 'test')",
            rusqlite::params![id, urgency, expires_at],
        )
        .unwrap();
    };
    insert("t_overdue1", 0.9, Some(1.0));
    insert("t_overdue2", 0.9, Some(1.0));
    insert("t_live_lo", 0.1, None);
    insert("t_live_mid", 0.5, None);
    insert("t_live_hi1", 0.8, None);
    insert("t_live_hi2", 0.9, None);
    insert("t_live_hi3", 0.95, None);

    let count_pending = || -> i64 {
        let conn = db.conn();
        conn.query_row(
            "SELECT COUNT(*) FROM trigger_log WHERE status = 'pending'",
            [],
            |r| r.get(0),
        )
        .unwrap()
    };

    // Dry run: 7 pending, 2 overdue, 5 live capped to 3 → 2 over-cap.
    let dry = db.prune_triggers(true, 3).unwrap();
    assert_eq!(dry.pending_before, 7);
    assert_eq!(dry.expired_overdue, 2);
    assert_eq!(dry.expired_over_cap, 2);
    assert_eq!(dry.pending_after, 3);
    assert_eq!(count_pending(), 7, "dry run mutates nothing");

    // Apply: bound to 3.
    let applied = db.prune_triggers(false, 3).unwrap();
    assert_eq!(applied.pending_after, 3);
    assert_eq!(count_pending(), 3);
    {
        let conn = db.conn();
        let lo: String = conn
            .query_row(
                "SELECT status FROM trigger_log WHERE trigger_id = 't_live_lo'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(lo, "expired", "lowest-urgency evicted");
        let hi: String = conn
            .query_row(
                "SELECT status FROM trigger_log WHERE trigger_id = 't_live_hi3'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(hi, "pending", "highest-urgency retained");
    }

    // Re-running is stable now that the backlog is at the cap.
    let again = db.prune_triggers(false, 3).unwrap();
    assert_eq!(again.expired_overdue, 0);
    assert_eq!(again.expired_over_cap, 0);
    assert_eq!(again.pending_after, 3);
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn skill_outcomes_are_recorded_durably() {
    // Task 28. Each real skill outcome appends to the durable timeline so the
    // count rises; outcomes against a non-existent skill record nothing.
    let db = YantrikDB::with_default(":memory:").unwrap();
    assert_eq!(db.skill_outcome_count().unwrap(), 0);

    let taught = db
        .teach_skill(
            "deploy the staging build".to_string(),
            "k1".to_string(),
            vec![],
            crate::skills::SkillTrigger::default(),
        )
        .unwrap();
    assert!(taught);

    assert!(db.skill_succeeded("k1").unwrap());
    assert!(db.skill_failed("k1").unwrap());
    assert!(db.skill_accepted("k1").unwrap());
    assert!(!db.skill_succeeded("does_not_exist").unwrap());

    assert_eq!(
        db.skill_outcome_count().unwrap(),
        3,
        "one durable event per real outcome, none for the missing skill"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn maintenance_cycle_runs_passes_and_records_last_run() {
    // Task 24. The cycle runs the default hygiene passes with per-pass error
    // isolation, leaves the opt-in heavy passes off, and persists a last-run
    // summary for stats / the boot digest.
    let db = YantrikDB::with_default(":memory:").unwrap();
    db.record_text(
        "fact one about the project",
        "semantic",
        0.6,
        0.0,
        604800.0,
        &empty_meta(),
        "ns",
        0.8,
        "work",
        "user",
        None,
    )
    .unwrap();
    db.record_text(
        "fact two about the project",
        "semantic",
        0.6,
        0.0,
        604800.0,
        &empty_meta(),
        "ns",
        0.8,
        "work",
        "user",
        None,
    )
    .unwrap();

    assert!(
        db.last_maintenance_cycle().unwrap().is_none(),
        "no cycle yet"
    );

    let report = db
        .run_maintenance_cycle(&crate::MaintenanceCycleConfig::default())
        .unwrap();
    assert!(report.errors.is_empty(), "errors: {:?}", report.errors);
    assert!(report.ran_at > 0.0);
    // Default config: think + entities + relations + conflicts + triggers + importance ran.
    assert!(report.think_consolidations.is_some());
    assert!(report.entities_linked.is_some());
    assert!(report.relations_upserted.is_some());
    assert!(report.conflicts.is_some());
    assert!(report.triggers.is_some());
    assert!(report.importance.is_some());
    // Heavy passes are opt-in.
    assert!(report.split.is_none());
    assert!(report.repair.is_none());

    // The last-run summary is persisted and retrievable.
    let last = db
        .last_maintenance_cycle()
        .unwrap()
        .expect("last run recorded");
    assert!(last.contains("ran_at"));

    // Idempotent: a second cycle also succeeds with no errors.
    let again = db
        .run_maintenance_cycle(&crate::MaintenanceCycleConfig::default())
        .unwrap();
    assert!(again.errors.is_empty());
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn recall_emits_structural_intent_hint() {
    // Task 35. A recency-intent query gets a hint pointing at the exact
    // structural path instead of silently returning a similarity-ranked guess.
    let db = YantrikDB::with_default(":memory:").unwrap();
    db.record_text(
        "entry one of the narrative",
        "episodic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        "chain",
        0.8,
        "self",
        "user",
        None,
    )
    .unwrap();

    let emb = db.embed("the most recent entry in the chain").unwrap();
    let response = db
        .recall_with_response(
            &emb,
            5,
            None,
            None,
            false,
            true,
            Some("what is the most recent entry in the chain"),
            true,
            None,
            None,
            None,
        )
        .unwrap();
    assert!(
        response
            .hints
            .iter()
            .any(|h| h.hint_type == "structural" && h.suggestion.contains("chain_head")),
        "a recency query yields a structural hint: {:?}",
        response.hints
    );

    // A plain semantic query gets no structural hint.
    let emb2 = db.embed("tell me about the narrative").unwrap();
    let plain = db
        .recall_with_response(
            &emb2,
            5,
            None,
            None,
            false,
            true,
            Some("tell me about the narrative content"),
            true,
            None,
            None,
            None,
        )
        .unwrap();
    assert!(
        !plain.hints.iter().any(|h| h.hint_type == "structural"),
        "no structural hint for a non-structural query"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn draft_memories_from_summary_atomizes_and_flags_provisional() {
    // Task 40. An agent's end-of-session summary is atomized into provisional,
    // retrievable candidate memories without the agent calling remember.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let summary = "We decided to use keyset cursors for list_records. \
                   Alice will own the database migration next sprint. \
                   The production launch slipped to March 30 because of it.";
    let rids = db
        .draft_memories_from_summary(summary, "session", "work")
        .unwrap();
    assert!(
        rids.len() >= 2,
        "summary atomized into facts: {}",
        rids.len()
    );

    for rid in &rids {
        let conn = db.conn();
        let meta: String = conn
            .query_row(
                "SELECT metadata FROM memories WHERE rid = ?1",
                rusqlite::params![rid],
                |r| r.get(0),
            )
            .unwrap();
        assert!(
            meta.contains("provisional"),
            "drafted memory is flagged provisional"
        );
    }

    let hits = db
        .recall_text("who owns the database migration", 5)
        .unwrap();
    assert!(hits.iter().any(|h| h.text.contains("migration")));
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn recall_stamps_trust_metadata() {
    // Task 41. An aged, rarely-confirmed memory and a superseded memory each
    // arrive on recall with a trust hedge in why_retrieved.
    //
    // v0.10 Item 1: serving a superseded result at all is LEGACY-policy
    // behavior (fresh DBs exclude it from eligibility), so this test pins
    // the stamped-hedge contract for pre-v0.10 databases.
    let db = YantrikDB::with_default(":memory:").unwrap();
    db.set_status_read_policy(false).unwrap();

    let aged = db
        .record_text(
            "an old fact about the deployment process",
            "semantic",
            0.7,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();
    {
        let conn = db.conn();
        conn.execute(
            "UPDATE memories SET created_at = ?1, access_count = 0 WHERE rid = ?2",
            rusqlite::params![crate::time::now_secs() - 200.0 * 86_400.0, aged],
        )
        .unwrap();
    }
    let hits = db.recall_text("deployment process fact", 5).unwrap();
    let h = hits
        .iter()
        .find(|h| h.rid == aged)
        .expect("aged hit present");
    assert!(
        h.why_retrieved
            .iter()
            .any(|w| w.contains("old") && w.contains("verify")),
        "aged-unconfirmed hedge present: {:?}",
        h.why_retrieved
    );

    // Supersession hedge.
    let old_v = db
        .record_text(
            "the API key rotates monthly",
            "semantic",
            0.6,
            0.0,
            604800.0,
            &empty_meta(),
            "ns2",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();
    let new_v = db
        .record_text(
            "the API key rotates weekly now",
            "semantic",
            0.6,
            0.0,
            604800.0,
            &empty_meta(),
            "ns2",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();
    db.link(
        &new_v,
        &crate::types::RecordLink {
            target_rid: old_v.clone(),
            link_type: crate::types::LinkType::Supersedes,
        },
    )
    .unwrap();
    let hits2 = db
        .recall_text("how often does the API key rotate", 5)
        .unwrap();
    let ho = hits2
        .iter()
        .find(|h| h.rid == old_v)
        .expect("superseded hit present");
    assert!(
        ho.why_retrieved.iter().any(|w| w.contains("superseded")),
        "superseded hedge present: {:?}",
        ho.why_retrieved
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn auto_relate_creates_cooccurrence_edges() {
    // Task 44. Entities that co-occur in a memory get linked, raising graph
    // density from plain writes. Idempotent.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let r1 = db
        .record_text(
            "Alice and Acme launched the Falcon project",
            "semantic",
            0.7,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();
    let r2 = db
        .record_text(
            "Alice and Acme shipped Falcon version two",
            "semantic",
            0.7,
            0.0,
            604800.0,
            &empty_meta(),
            "ns",
            0.8,
            "work",
            "user",
            None,
        )
        .unwrap();
    // Simulate the entity extraction (async materializer in production) having
    // linked entities to these memories, so auto-relate has co-occurrences.
    {
        let conn = db.conn();
        for (rid, ent) in [(&r1, "Alice"), (&r1, "Acme"), (&r2, "Alice"), (&r2, "Acme")] {
            conn.execute(
                "INSERT OR IGNORE INTO memory_entities (memory_rid, entity_name) VALUES (?1, ?2)",
                rusqlite::params![rid, ent],
            )
            .unwrap();
        }
    }

    let dry = db.auto_relate(true, 100).unwrap();
    assert!(
        dry.pairs_considered >= 1,
        "co-occurring pairs: {}",
        dry.pairs_considered
    );
    assert_eq!(dry.edges_upserted, 0, "dry run upserts nothing");

    let applied = db.auto_relate(false, 100).unwrap();
    assert!(
        applied.edges_upserted >= 1,
        "edges created: {}",
        applied.edges_upserted
    );

    // Idempotent: re-running considers the same pairs and errors-free.
    let again = db.auto_relate(false, 100).unwrap();
    assert_eq!(again.pairs_considered, applied.pairs_considered);
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn session_digest_assembles_boot_briefing() {
    // Task 38. One call returns the narrative head (latest, not
    // highest-importance), the top live decisions (high importance only), and
    // the open-conflict / pending-trigger counts.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let _n1 = db
        .record_text(
            "narrative entry one",
            "episodic",
            0.9,
            0.0,
            604800.0,
            &empty_meta(),
            "narr",
            0.9,
            "self",
            "user",
            None,
        )
        .unwrap();
    let n2 = db
        .record_text(
            "narrative entry two, the latest self-state",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            "narr",
            0.9,
            "self",
            "user",
            None,
        )
        .unwrap();
    db.record_text(
        "decided to adopt keyset cursors for enumeration",
        "semantic",
        0.95,
        0.0,
        604800.0,
        &empty_meta(),
        "work",
        0.9,
        "work",
        "user",
        None,
    )
    .unwrap();
    db.record_text(
        "a trivial passing aside",
        "semantic",
        0.2,
        0.0,
        604800.0,
        &empty_meta(),
        "work",
        0.5,
        "work",
        "user",
        None,
    )
    .unwrap();

    let cfg = crate::SessionDigestConfig {
        narrative_namespace: Some("narr".to_string()),
        ..Default::default()
    };
    let digest = db.session_digest(&cfg).unwrap();

    // Head is the latest entry, not the higher-importance one.
    let head = digest.narrative_head.expect("narrative head present");
    assert_eq!(head.rid, n2);
    assert!(head.snippet.contains("latest self-state"));

    // Top decisions: high-importance only.
    assert!(digest
        .top_decisions
        .iter()
        .any(|d| d.snippet.contains("keyset cursors")));
    assert!(!digest
        .top_decisions
        .iter()
        .any(|d| d.snippet.contains("trivial passing aside")));

    assert_eq!(digest.open_conflict_count, 0);
    assert_eq!(digest.pending_trigger_count, 0);
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn chain_head_returns_exact_latest_entry() {
    // Task 36. The chain head is exactly the latest write, independent of
    // importance — proving it is not the recall lottery.
    let db = YantrikDB::with_default(":memory:").unwrap();
    assert!(
        db.chain_head("chain").unwrap().is_none(),
        "empty chain has no head"
    );

    let _e1 = db
        .record_text(
            "entry one of the narrative",
            "episodic",
            1.0,
            0.0,
            604800.0,
            &empty_meta(),
            "chain",
            0.8,
            "self",
            "user",
            None,
        )
        .unwrap();
    let _e2 = db
        .record_text(
            "entry two of the narrative",
            "episodic",
            0.6,
            0.0,
            604800.0,
            &empty_meta(),
            "chain",
            0.8,
            "self",
            "user",
            None,
        )
        .unwrap();
    // The most recent entry is given the LOWEST importance, so a recall would
    // rank it last — chain_head must still return it.
    let e3 = db
        .record_text(
            "entry three, the most recent",
            "episodic",
            0.3,
            0.0,
            604800.0,
            &empty_meta(),
            "chain",
            0.8,
            "self",
            "user",
            None,
        )
        .unwrap();

    let head = db.chain_head("chain").unwrap().expect("head exists");
    assert_eq!(
        head.rid, e3,
        "head is the latest write, not the highest-importance"
    );
    assert!(head.text.contains("most recent"));

    // A different namespace is unaffected.
    assert!(db.chain_head("other").unwrap().is_none());
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn evict_protects_frequently_recalled_memories() {
    // Feature A (v0.9.0): hot/cold tiering uses recall frequency — a stale but
    // frequently-recalled memory is NOT evicted just for being old, while
    // equally-stale never-recalled peers are.
    let db = YantrikDB::with_default(":memory:").unwrap();
    let mut rids = Vec::new();
    for i in 0..5 {
        rids.push(
            db.record_text(
                &format!("memory number {i} about assorted unrelated topics"),
                "semantic",
                0.5,
                0.0,
                604800.0,
                &empty_meta(),
                "ns",
                0.8,
                "general",
                "user",
                None,
            )
            .unwrap(),
        );
    }
    let hot = rids[0].clone();
    {
        let conn = db.conn();
        // Make ALL equally old / stale / never-recalled...
        conn.execute(
            "UPDATE memories SET created_at = 1000.0, last_access = 1000.0, access_count = 0",
            [],
        )
        .unwrap();
        // ...except one, which has been recalled many times.
        conn.execute(
            "UPDATE memories SET access_count = 50 WHERE rid = ?1",
            rusqlite::params![hot],
        )
        .unwrap();
    }

    let evicted = db.evict(2).unwrap();
    assert_eq!(evicted.len(), 3, "evicts down to max_active = 2");
    assert!(
        !evicted.contains(&hot),
        "the frequently-recalled memory survives"
    );

    let tier: String = {
        let conn = db.conn();
        conn.query_row(
            "SELECT storage_tier FROM memories WHERE rid = ?1",
            rusqlite::params![hot],
            |r| r.get(0),
        )
        .unwrap()
    };
    assert_eq!(tier, "hot", "the hot memory stays hot");
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn recall_logs_demand_and_surfaces_gaps() {
    // Feature B (v0.9.0): a user-facing recall auto-logs demand; a frequently
    // asked, poorly-answered query surfaces as a knowledge gap.
    let db = YantrikDB::with_default(":memory:").unwrap();
    // One unrelated memory so recall reaches the demand-logging tail (an empty
    // corpus short-circuits before it). The query stays poorly answered.
    db.record_text(
        "the orchard wall was painted blue last spring",
        "semantic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        "ns",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();
    for _ in 0..4 {
        let _ = db
            .recall_text("how do I rotate the encryption keys", 5)
            .unwrap();
    }
    // recall_text issues an unscoped recall, so its demand lands in the
    // global bucket (namespace = None) per the v0.9.3 isolation contract.
    let (count, avg_top) = db
        .recall_demand_for(None, "how do I rotate the encryption keys")
        .unwrap()
        .expect("the query was logged as demand");
    assert_eq!(count, 4, "asked four times");

    // Surfaces as a gap at a threshold just above its (low) answer quality.
    let gaps = db.knowledge_gaps(None, 3, avg_top + 0.01, 10).unwrap();
    assert!(
        gaps.iter()
            .any(|g| g.query.contains("rotate the encryption keys")),
        "frequent poorly-answered query surfaces as a gap: {gaps:?}"
    );

    // An internal recall (skip_reinforce) must NOT pollute the demand log.
    let emb = db.embed("a different internal probe query").unwrap();
    let _ = db
        .recall(
            &emb,
            5,
            None,
            None,
            false,
            true,
            Some("a different internal probe query"),
            true,
            None,
            None,
            None,
            None,
            None,
            false,
        )
        .unwrap();
    assert!(
        db.recall_demand_for(None, "a different internal probe query")
            .unwrap()
            .is_none(),
        "internal (skip_reinforce) recalls are not logged as demand"
    );
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn migration_v33_purges_unscopable_demand_rows() {
    // v0.9.3 isolation repair (sol converged plan item 2). Databases written
    // by v0.9.0–v0.9.2 have a GLOBAL-keyed recall_demand table with raw
    // query text; those legacy rows are unscopable (no namespace recorded),
    // so the v32→v33 migration PURGES them and SCHEMA_SQL recreates the
    // namespace-keyed shape. This simulates such a populated pre-fix DB.
    use tempfile::NamedTempFile;
    let tmp = NamedTempFile::new().unwrap();
    let path = tmp.path().to_str().unwrap();

    // Current-schema DB first (so all OTHER tables are in place)...
    {
        let _db = YantrikDB::new(path, 8).unwrap();
    }
    // ...then regress recall_demand to the v0.9.0 shape with a legacy row
    // and rewind the version stamp to 32.
    {
        let conn = rusqlite::Connection::open(path).unwrap();
        conn.execute_batch(
            "DROP TABLE recall_demand;
             CREATE TABLE recall_demand (
                 query_norm TEXT PRIMARY KEY,
                 sample_text TEXT NOT NULL,
                 count INTEGER NOT NULL,
                 sum_top_score REAL NOT NULL,
                 sum_results INTEGER NOT NULL,
                 last_seen REAL NOT NULL
             );
             INSERT INTO recall_demand VALUES
                 ('legacy unscopable query', 'Legacy Unscopable Query?', 7, 0.4, 3, 1.0);
             INSERT OR REPLACE INTO meta (key, value) VALUES ('schema_version', '32');",
        )
        .unwrap();
    }

    // Reopen: V32_TO_V33 drops the legacy table; SCHEMA_SQL recreates the
    // namespace-keyed shape. Legacy rows are gone (purged, not guessed).
    let db = YantrikDB::new(path, 8).expect("v33 migration must succeed on a populated v32 DB");
    {
        let conn = db.conn();
        let rows: i64 = conn
            .query_row("SELECT COUNT(*) FROM recall_demand", [], |r| r.get(0))
            .unwrap();
        assert_eq!(rows, 0, "unscopable legacy demand rows are purged");
        // The new shape is namespace-keyed (this errors if the column is absent).
        conn.query_row("SELECT namespace FROM recall_demand LIMIT 1", [], |r| {
            r.get::<_, String>(0)
        })
        .ok();
    }
    // Demand logging works post-migration under the new key.
    db.record_recall_demand(Some("ns-a"), "post migration question", 0, 0.0)
        .unwrap();
    assert!(db
        .recall_demand_for(Some("ns-a"), "post migration question")
        .unwrap()
        .is_some());
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn session_digest_scopes_decisions_and_conflicts_to_namespace() {
    // v0.9.3: a namespace-scoped digest must not mix another tenant's
    // high-importance memories into top_decisions.
    let db = YantrikDB::with_default(":memory:").unwrap();
    db.record_text(
        "tenant A signed the enterprise contract",
        "semantic",
        0.95,
        0.0,
        604800.0,
        &empty_meta(),
        "tenant-a",
        0.9,
        "work",
        "user",
        None,
    )
    .unwrap();
    db.record_text(
        "tenant B is migrating to postgres",
        "semantic",
        0.95,
        0.0,
        604800.0,
        &empty_meta(),
        "tenant-b",
        0.9,
        "work",
        "user",
        None,
    )
    .unwrap();

    let scoped = db
        .session_digest(&crate::SessionDigestConfig {
            namespace: Some("tenant-a".into()),
            ..Default::default()
        })
        .unwrap();
    assert!(
        !scoped.top_decisions.is_empty(),
        "tenant-a's own decision is present"
    );
    assert!(
        scoped
            .top_decisions
            .iter()
            .all(|d| d.namespace == "tenant-a"),
        "no cross-tenant decisions in a scoped digest: {:?}",
        scoped.top_decisions
    );

    // Unscoped (explicit-global) digest still sees both — unchanged behavior.
    let global = db
        .session_digest(&crate::SessionDigestConfig::default())
        .unwrap();
    let namespaces: std::collections::HashSet<_> = global
        .top_decisions
        .iter()
        .map(|d| d.namespace.clone())
        .collect();
    assert!(namespaces.contains("tenant-a") && namespaces.contains("tenant-b"));
}

#[test]
fn digest_packet_is_status_led_and_reports_changes_since() {
    // v0.10 Item 1c / trace T10 "packet-correctness". Fixture: decisions
    // A (superseded), B (head), C (open question), D (disputed, vs E) in
    // one namespace. The packet main view carries B, C, D-with-flag; A
    // exists only behind include_superseded; what_changed_since(T)
    // returns exactly the records and status transitions after T.
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let rec = |text: &str, seed: f32| {
        db.record(
            text,
            "semantic",
            0.9,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(seed, 8),
            "t10",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap()
    };
    let a = rec("decision A: deploy to staging", 1.0);
    let b = rec("decision B: deploy to production (corrects A)", 1.05);
    let c = rec("open question C: which region", 2.0);
    let d = rec("decision D: use postgres", 3.0);
    let e = rec("decision E: use sqlite (rival of D)", 3.05);

    db.link(
        &b,
        &crate::types::RecordLink {
            target_rid: a.clone(),
            link_type: crate::types::LinkType::Supersedes,
        },
    )
    .unwrap();
    crate::create_conflict(
        &db,
        &crate::types::ConflictType::Preference,
        &d,
        &e,
        None,
        None,
        "T10 fixture: D vs E",
    )
    .unwrap();

    // Deterministic timeline (no wall-clock asserts): A predates T=1500,
    // everything else follows it. The supersedes link keeps its real
    // (post-T) commit time.
    {
        let conn = db.conn();
        conn.execute(
            "UPDATE memories SET created_at = 1000.0 WHERE rid = ?1",
            rusqlite::params![a],
        )
        .unwrap();
        conn.execute(
            "UPDATE memories SET created_at = 2000.0 WHERE rid IN (?1, ?2, ?3, ?4)",
            rusqlite::params![b, c, d, e],
        )
        .unwrap();
    }

    // Main view: status-led (fresh DB → policy active).
    let digest = db
        .session_digest(&crate::SessionDigestConfig {
            namespace: Some("t10".into()),
            ..Default::default()
        })
        .unwrap();
    let rids: Vec<&str> = digest
        .top_decisions
        .iter()
        .map(|x| x.rid.as_str())
        .collect();
    assert!(rids.contains(&b.as_str()), "head B in main view");
    assert!(rids.contains(&c.as_str()), "open question C in main view");
    assert!(
        rids.contains(&d.as_str()),
        "disputed D in main view (not dropped)"
    );
    assert!(
        !rids.contains(&a.as_str()),
        "superseded A absent from main view"
    );
    let d_entry = digest.top_decisions.iter().find(|x| x.rid == d).unwrap();
    assert!(d_entry.disputed, "D carries the typed disputed flag");
    let b_entry = digest.top_decisions.iter().find(|x| x.rid == b).unwrap();
    assert!(!b_entry.disputed);
    assert_eq!(b_entry.current_status, crate::types::RecordStatus::Active);

    // Expansion: A re-admitted, stamped.
    let expanded = db
        .session_digest(&crate::SessionDigestConfig {
            namespace: Some("t10".into()),
            include_superseded: true,
            ..Default::default()
        })
        .unwrap();
    let a_entry = expanded
        .top_decisions
        .iter()
        .find(|x| x.rid == a)
        .expect("A only behind include_superseded");
    assert_eq!(
        a_entry.current_status,
        crate::types::RecordStatus::Superseded
    );
    assert_eq!(a_entry.superseded_by.as_deref(), Some(b.as_str()));

    // what_changed_since(T=1500): B/C/D/E are new, A is not; exactly one
    // status transition (A → Superseded by B, committed after T).
    let changes = db.what_changed_since(1500.0, Some("t10"), 240).unwrap();
    let new_rids: Vec<&str> = changes.new_records.iter().map(|x| x.rid.as_str()).collect();
    for rid in [&b, &c, &d, &e] {
        assert!(new_rids.contains(&rid.as_str()), "{rid} is new since T");
    }
    assert!(!new_rids.contains(&a.as_str()), "A predates T");
    assert_eq!(
        changes.status_transitions.len(),
        1,
        "exactly one transition"
    );
    let tr = &changes.status_transitions[0];
    assert_eq!(tr.rid, a);
    assert_eq!(tr.from, crate::types::RecordStatus::Active);
    assert_eq!(tr.to, crate::types::RecordStatus::Superseded);
    assert_eq!(tr.by_rid.as_deref(), Some(b.as_str()));
    assert!(tr.at > 1500.0, "transition committed after T");

    // Nothing changed since a T after everything.
    let quiet = db
        .what_changed_since(crate::time::now_secs() + 10.0, Some("t10"), 240)
        .unwrap();
    assert!(quiet.new_records.is_empty());
    assert!(quiet.status_transitions.is_empty());
}

#[cfg(feature = "bundled-embedder")]
#[test]
fn explicit_set_embedder_overrides_bundled() {
    // Slim-build path or custom-model path: set_embedder() after new()
    // takes precedence. The bundled embedder gets dropped; the user's
    // takes over.
    struct DummyEmbedder;
    impl crate::types::Embedder for DummyEmbedder {
        fn embed(
            &self,
            _t: &str,
        ) -> std::result::Result<Vec<f32>, Box<dyn std::error::Error + Send + Sync>> {
            // Distinct sentinel value so we can detect this implementation was used.
            let mut v = vec![0.0; 64];
            v[0] = 0.7777;
            Ok(v)
        }
        fn dim(&self) -> usize {
            64
        }
    }

    let mut db = YantrikDB::with_default(":memory:").unwrap();
    assert!(db.has_embedder(), "starts with bundled");
    // Issue #41 layer 2 / brainstorm-3: set_embedder is now mode-aware
    // and returns Result. For an empty DB (no memories indexed yet)
    // the call accepts ANY embedder regardless of fingerprint match,
    // updating provenance based on candidate.fingerprint().
    // DummyEmbedder returns None from fingerprint() so provenance
    // stays ExternalOrUnknown; runtime_embedder slot updates.
    db.set_embedder(Box::new(DummyEmbedder)).unwrap();
    let v = db.embed("anything").unwrap();
    assert!(
        (v[0] - 0.7777).abs() < 1e-6,
        "DummyEmbedder's sentinel must be visible — set_embedder overrode bundled"
    );
}