remem-ai 0.6.93

Local-first coding agent memory for Claude Code and OpenAI Codex
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
//! remem Benchmark Evaluation Framework
//!
//! Quantitative evaluation of memory capture, search precision/recall,
//! context injection quality, cross-session continuity, and cross-project sharing.
//!
//! All tests use in-memory SQLite — no external AI service needed.

mod bench_fixtures;

use anyhow::Result;
use rusqlite::Connection;

use remem::{
    db, memory,
    retrieval::{entity, search, search_multihop},
    summarize,
};

use bench_fixtures::{
    coding_session_fixtures, insert_memory_at, insert_seed_memories, search_eval_memories,
    setup_full_schema, summary_xml_partial, summary_xml_skip, summary_xml_with_all_fields,
};

// ===========================================================================
// Metric helpers
// ===========================================================================

/// Precision@K: fraction of top-K results that are relevant.
fn precision_at_k(result_ids: &[i64], relevant_ids: &[i64], k: usize) -> f64 {
    let top_k: Vec<i64> = result_ids.iter().copied().take(k).collect();
    if top_k.is_empty() {
        return 0.0;
    }
    let hits = top_k.iter().filter(|id| relevant_ids.contains(id)).count();
    hits as f64 / top_k.len() as f64
}

/// Recall@K: fraction of all relevant items found in top-K results.
fn recall_at_k(result_ids: &[i64], relevant_ids: &[i64], k: usize) -> f64 {
    if relevant_ids.is_empty() {
        return 1.0;
    }
    let top_k: Vec<i64> = result_ids.iter().copied().take(k).collect();
    let hits = relevant_ids.iter().filter(|id| top_k.contains(id)).count();
    hits as f64 / relevant_ids.len() as f64
}

// ===========================================================================
// Scenario 1: Memory Capture Pipeline
// ===========================================================================

#[test]
fn bench_memory_capture_rate() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let fixtures = coding_session_fixtures();
    let mut total_meaningful = 0;
    let mut total_captured = 0;

    for session in &fixtures {
        // Insert events
        for event in &session.events {
            memory::insert_event(
                &conn,
                &session.session_id,
                &session.project,
                &event.event_type,
                &event.summary,
                event.detail.as_deref(),
                event.files.as_deref(),
                None,
            )?;

            // Count meaningful events (file edits with detail are "meaningful")
            if event.event_type == "file_edit" && event.detail.is_some() {
                total_meaningful += 1;

                // Simulate active memory after review. Summary-derived facts now
                // enter the candidate lifecycle before activation.
                memory::insert_memory(
                    &conn,
                    Some(&session.session_id),
                    &session.project,
                    None,
                    &event.summary,
                    event.detail.as_deref().unwrap_or(&event.summary),
                    "discovery",
                    event.files.as_deref(),
                )?;
                total_captured += 1;
            }
        }
    }

    let mcr = if total_meaningful > 0 {
        total_captured as f64 / total_meaningful as f64
    } else {
        0.0
    };

    eprintln!(
        "[MCR] meaningful={} captured={} rate={:.2}",
        total_meaningful, total_captured, mcr
    );
    assert!(
        mcr >= 0.8,
        "Memory Capture Rate {:.2} below threshold 0.8",
        mcr
    );

    // Verify memories are actually queryable
    let memories = memory::get_recent_memories(&conn, "tools/remem", 50)?;
    assert!(
        !memories.is_empty(),
        "No memories found after capture pipeline"
    );

    Ok(())
}

// ===========================================================================
// Scenario 2: Search Precision@K and Recall@K
// ===========================================================================

#[test]
fn bench_search_precision_and_recall_fts() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let seeds = search_eval_memories();
    let ids = insert_seed_memories(&conn, &seeds)?;

    // Build relevance ground truth for "FTS5 search" query
    let relevant_ids: Vec<i64> = seeds
        .iter()
        .zip(ids.iter())
        .filter(|(s, _)| s.relevant_to_fts_query)
        .map(|(_, id)| *id)
        .collect();

    // Execute search
    let results = search::search(
        &conn,
        Some("FTS5 search"),
        Some("tools/remem"),
        None,
        10,
        0,
        true,
    )?;
    let result_ids: Vec<i64> = results.iter().map(|m| m.id).collect();

    let p5 = precision_at_k(&result_ids, &relevant_ids, 5);
    let r10 = recall_at_k(&result_ids, &relevant_ids, 10);

    eprintln!(
        "[Search FTS5] results={} relevant={} P@5={:.2} R@10={:.2}",
        results.len(),
        relevant_ids.len(),
        p5,
        r10
    );

    // Targets: P@5 >= 0.6, R@10 >= 0.5
    assert!(
        p5 >= 0.6,
        "Precision@5 {:.2} below threshold 0.6 (results: {:?})",
        p5,
        results.iter().map(|m| &m.title).collect::<Vec<_>>()
    );
    assert!(r10 >= 0.5, "Recall@10 {:.2} below threshold 0.5", r10);

    Ok(())
}

#[test]
fn bench_search_precision_decay_query() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let seeds = search_eval_memories();
    let ids = insert_seed_memories(&conn, &seeds)?;

    let relevant_ids: Vec<i64> = seeds
        .iter()
        .zip(ids.iter())
        .filter(|(s, _)| s.relevant_to_decay_query)
        .map(|(_, id)| *id)
        .collect();

    let results = search::search(
        &conn,
        Some("time decay"),
        Some("tools/remem"),
        None,
        10,
        0,
        true,
    )?;
    let result_ids: Vec<i64> = results.iter().map(|m| m.id).collect();

    let p5 = precision_at_k(&result_ids, &relevant_ids, 5);
    let r10 = recall_at_k(&result_ids, &relevant_ids, 10);

    eprintln!(
        "[Search Decay] results={} relevant={} P@5={:.2} R@10={:.2}",
        results.len(),
        relevant_ids.len(),
        p5,
        r10
    );

    // At least some relevant results should appear
    assert!(
        r10 > 0.0,
        "No relevant results found for 'time decay' query"
    );

    Ok(())
}

// ===========================================================================
// Scenario 3: Context Injection Quality (scoring logic)
// ===========================================================================

#[test]
fn bench_context_score_prefers_decisions_and_recent() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let now = chrono::Utc::now().timestamp();

    // Insert memories with varying types and ages
    let decision_recent = insert_memory_at(
        &conn,
        "tools/remem",
        "Use FTS5 over Tantivy",
        "Decided to use SQLite FTS5 for simplicity",
        "decision",
        now - 2 * 86400, // 2 days old
        "project",
    )?;
    let bugfix_recent = insert_memory_at(
        &conn,
        "tools/remem",
        "Fix search crash on hyphen",
        "Wrapped tokens in quotes for FTS5 MATCH safety",
        "bugfix",
        now - 86400, // 1 day old
        "project",
    )?;
    let discovery_old = insert_memory_at(
        &conn,
        "tools/remem",
        "SQLite WAL mode",
        "WAL journal mode improves concurrency",
        "discovery",
        now - 60 * 86400, // 60 days old
        "project",
    )?;
    let decision_old = insert_memory_at(
        &conn,
        "tools/remem",
        "Chose Rust over Python",
        "Single binary deployment without runtime",
        "decision",
        now - 45 * 86400, // 45 days old
        "project",
    )?;
    let session_activity = insert_memory_at(
        &conn,
        "tools/remem",
        "Session: fixed CI pipeline",
        "Updated GitHub Actions workflow",
        "session_activity",
        now - 3 * 86400, // 3 days old
        "project",
    )?;

    // Fetch and score memories using the same logic as context.rs
    let memories = memory::get_recent_memories(&conn, "tools/remem", 50)?;
    assert!(!memories.is_empty(), "No memories found");

    // Score each memory
    let mut scored: Vec<(i64, &str, &str, f64)> = memories
        .iter()
        .map(|m| {
            let type_weight: f64 = match m.memory_type.as_str() {
                "decision" => 3.0,
                "bugfix" => 2.5,
                "architecture" => 2.0,
                "preference" => 1.5,
                "discovery" => 1.0,
                _ => 0.5,
            };
            let age_days = (now - m.updated_at_epoch) / 86400;
            let time_decay: f64 = if age_days <= 7 {
                1.0
            } else if age_days <= 30 {
                0.7
            } else {
                0.4
            };
            let score = type_weight * time_decay;
            (m.id, m.title.as_str(), m.memory_type.as_str(), score)
        })
        .collect();

    scored.sort_by(|a, b| b.3.partial_cmp(&a.3).unwrap());

    eprintln!("[Context Score] Ranking:");
    for (id, title, mtype, score) in &scored {
        eprintln!("  #{} [{:.1}] {} ({})", id, score, title, mtype);
    }

    // Assertions on ranking:
    // 1. Recent decision (score = 3.0 * 1.0 = 3.0) should be top
    assert_eq!(
        scored[0].0, decision_recent,
        "Recent decision should rank #1"
    );

    // 2. Recent bugfix (2.5 * 1.0 = 2.5) should be #2
    assert_eq!(scored[1].0, bugfix_recent, "Recent bugfix should rank #2");

    // 3. Old decision (3.0 * 0.4 = 1.2) should outrank old discovery (1.0 * 0.4 = 0.4)
    let old_decision_score = scored.iter().find(|s| s.0 == decision_old).unwrap().3;
    let old_discovery_score = scored.iter().find(|s| s.0 == discovery_old).unwrap().3;
    assert!(
        old_decision_score > old_discovery_score,
        "Old decision ({:.1}) should outrank old discovery ({:.1})",
        old_decision_score,
        old_discovery_score
    );

    // 4. Session activity should rank lowest (0.5 * 1.0 = 0.5)
    let session_score = scored.iter().find(|s| s.0 == session_activity).unwrap().3;
    assert!(
        session_score < 1.0,
        "Session activity score {:.1} should be low",
        session_score
    );

    // Context Relevance Score: high-value items (decision/bugfix) in top 3
    let top3_high_value = scored
        .iter()
        .take(3)
        .filter(|s| s.2 == "decision" || s.2 == "bugfix")
        .count();
    let context_score = top3_high_value as f64 / 3.0;
    eprintln!(
        "[Context Score] high_value_in_top3={}/3 = {:.2}",
        top3_high_value, context_score
    );
    assert!(
        context_score >= 0.6,
        "Context relevance {:.2} below threshold 0.6",
        context_score
    );

    Ok(())
}

// ===========================================================================
// Scenario 4: Cross-Session Decision Continuity
// ===========================================================================

#[test]
fn bench_cross_session_decision_retrieval() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    // Session A: store a decision
    memory::insert_memory(
        &conn,
        Some("sess-A"),
        "tools/remem",
        Some("fts5-vs-tantivy"),
        "Chose FTS5 over Tantivy for search",
        "Decision: Use SQLite FTS5 instead of Tantivy. Rationale: single-file DB, \
         no additional binary, trigram tokenizer handles CJK, good enough performance \
         for <100k memories.",
        "decision",
        None,
    )?;

    // Session B: search for that decision
    let results = search::search(
        &conn,
        Some("FTS5 Tantivy search decision"),
        Some("tools/remem"),
        None,
        5,
        0,
        true,
    )?;

    eprintln!(
        "[Cross-Session] query='FTS5 Tantivy' results={}",
        results.len()
    );
    assert!(
        !results.is_empty(),
        "Cross-session decision not found by search"
    );
    assert_eq!(
        results[0].title, "Chose FTS5 over Tantivy for search",
        "Decision should be the top result"
    );
    assert_eq!(
        results[0].memory_type, "decision",
        "Result should be a decision type"
    );

    // Verify topic_key enables upsert (Session C updates same decision)
    memory::insert_memory(
        &conn,
        Some("sess-C"),
        "tools/remem",
        Some("fts5-vs-tantivy"),
        "Chose FTS5 over Tantivy for search",
        "Updated decision: Still using FTS5. Added LIKE fallback for short queries. \
         Performance confirmed at 5ms for 10k records.",
        "decision",
        None,
    )?;

    // Should still be one memory (upserted, not duplicated)
    let all_fts = search::search(
        &conn,
        Some("FTS5 Tantivy"),
        Some("tools/remem"),
        None,
        10,
        0,
        true,
    )?;
    let fts_decisions: Vec<_> = all_fts
        .iter()
        .filter(|m| m.topic_key.as_deref() == Some("fts5-vs-tantivy"))
        .collect();
    assert_eq!(
        fts_decisions.len(),
        1,
        "topic_key upsert should prevent duplicates, found {}",
        fts_decisions.len()
    );
    assert!(
        fts_decisions[0].text.contains("LIKE fallback"),
        "Memory should contain updated content"
    );

    Ok(())
}

// ===========================================================================
// Scenario 5: Cross-Project Global Memory Visibility
// ===========================================================================

#[test]
fn bench_global_scope_cross_project() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let now = chrono::Utc::now().timestamp();

    // Project A: insert a global preference
    insert_memory_at(
        &conn,
        "tools/remem",
        "Prefer English commit messages",
        "Always use English for git commit messages and code comments",
        "preference",
        now,
        "global",
    )?;

    // Project A: insert a project-scoped memory
    insert_memory_at(
        &conn,
        "tools/remem",
        "FTS5 search design",
        "Search implementation details specific to remem",
        "architecture",
        now,
        "project",
    )?;

    // Query from Project B: should see global preference but NOT project-scoped memory
    let project_b_memories = memory::get_recent_memories(&conn, "web/dashboard", 50)?;

    let global_visible = project_b_memories
        .iter()
        .any(|m| m.title == "Prefer English commit messages");
    let project_leaked = project_b_memories
        .iter()
        .any(|m| m.title == "FTS5 search design");

    eprintln!(
        "[Global Scope] project_b sees: {} memories, global_visible={}, project_leaked={}",
        project_b_memories.len(),
        global_visible,
        project_leaked
    );

    assert!(
        global_visible,
        "Global preference should be visible in Project B"
    );
    assert!(
        !project_leaked,
        "Project-scoped memory should NOT leak to Project B"
    );

    Ok(())
}

// ===========================================================================
// Scenario 6: Time Decay Ranking
// ===========================================================================

#[test]
fn bench_time_decay_ranks_newer_higher() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let now = chrono::Utc::now().timestamp();

    // Insert two memories with identical relevance but different ages
    let new_id = insert_memory_at(
        &conn,
        "tools/remem",
        "Database connection pooling strategy",
        "Use single connection with WAL mode for SQLite",
        "decision",
        now - 2 * 86400, // 2 days ago
        "project",
    )?;
    let old_id = insert_memory_at(
        &conn,
        "tools/remem",
        "Database connection pooling approach",
        "Originally considered connection pool but SQLite works better single-threaded",
        "decision",
        now - 60 * 86400, // 60 days ago
        "project",
    )?;

    let results = search::search(
        &conn,
        Some("database connection pooling"),
        Some("tools/remem"),
        None,
        10,
        0,
        true,
    )?;

    assert!(
        results.len() >= 2,
        "Should find both memories, found {}",
        results.len()
    );

    eprintln!("[Time Decay] Results:");
    for m in &results {
        let age = (now - m.updated_at_epoch) / 86400;
        eprintln!("  #{} age={}d {}", m.id, age, m.title);
    }

    // Note: FTS5 ranking is by text relevance, not time decay.
    // Time decay is applied in context scoring, not in raw search.
    // So here we test that both are found; the context scoring test (Scenario 3)
    // verifies decay ordering.
    let found_new = results.iter().any(|m| m.id == new_id);
    let found_old = results.iter().any(|m| m.id == old_id);
    assert!(found_new, "New memory should be in search results");
    assert!(found_old, "Old memory should be in search results");

    // Apply context scoring manually and verify decay ordering
    let score = |m: &memory::Memory| -> f64 {
        let type_weight: f64 = match m.memory_type.as_str() {
            "decision" => 3.0,
            "bugfix" => 2.5,
            _ => 1.0,
        };
        let age_days = (now - m.updated_at_epoch) / 86400;
        let decay: f64 = if age_days <= 7 {
            1.0
        } else if age_days <= 30 {
            0.7
        } else {
            0.4
        };
        type_weight * decay
    };

    let new_mem = results.iter().find(|m| m.id == new_id).unwrap();
    let old_mem = results.iter().find(|m| m.id == old_id).unwrap();
    let new_score = score(new_mem);
    let old_score = score(old_mem);

    eprintln!(
        "[Time Decay] new_score={:.1} old_score={:.1}",
        new_score, old_score
    );
    assert!(
        new_score > old_score,
        "Newer memory score ({:.1}) should exceed older ({:.1})",
        new_score,
        old_score
    );

    Ok(())
}

// ===========================================================================
// Scenario 7: Summary Parse & Memory Promotion
// ===========================================================================

#[test]
fn bench_summary_parse_full() -> Result<()> {
    let xml = summary_xml_with_all_fields();
    let parsed = summarize::parse_summary(&xml);

    assert!(parsed.is_some(), "Full summary should parse successfully");
    let p = parsed.unwrap();

    assert!(
        p.request
            .as_ref()
            .is_some_and(|r| r.contains("SessionStart preferences")),
        "request field should be extracted"
    );
    assert!(
        p.decisions.as_ref().is_some_and(|d| d.contains("project")),
        "decisions field should be extracted"
    );
    assert!(
        p.learned.as_ref().is_some_and(|l| l.contains("FTS5")),
        "learned field should be extracted"
    );
    assert!(
        p.preferences
            .as_ref()
            .is_some_and(|pref| pref.contains("English")),
        "preferences field should be extracted"
    );
    assert!(p.completed.is_some(), "completed field should be extracted");
    assert!(
        p.next_steps.is_some(),
        "next_steps field should be extracted"
    );

    eprintln!(
        "[Summary Parse] All 6 fields extracted: request={} completed={} decisions={} learned={} next_steps={} preferences={}",
        p.request.is_some(),
        p.completed.is_some(),
        p.decisions.is_some(),
        p.learned.is_some(),
        p.next_steps.is_some(),
        p.preferences.is_some(),
    );

    Ok(())
}

#[test]
fn bench_summary_parse_skip() {
    let xml = summary_xml_skip();
    let parsed = summarize::parse_summary(&xml);
    assert!(parsed.is_none(), "skip_summary should return None");
}

#[test]
fn bench_summary_parse_partial() -> Result<()> {
    let xml = summary_xml_partial();
    let parsed = summarize::parse_summary(&xml);

    assert!(parsed.is_some(), "Partial summary should parse");
    let p = parsed.unwrap();

    assert!(p.request.is_some(), "request should be present");
    assert!(p.completed.is_some(), "completed should be present");
    assert!(p.decisions.is_none(), "decisions should be absent");
    assert!(p.learned.is_none(), "learned should be absent");
    assert!(p.preferences.is_none(), "preferences should be absent");

    Ok(())
}

#[test]
fn bench_summary_promote_creates_candidates() -> Result<()> {
    let mut conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let session_id = "promote-test-001";
    let project = "tools/remem";

    db::record_captured_event(
        &conn,
        &db::CaptureEventInput {
            host: "codex-cli",
            session_id,
            project,
            cwd: Some(project),
            event_type: "session_stop",
            role: None,
            tool_name: None,
            content: "summary source payload",
            task_kind: None,
        },
    )?;

    // Summary-derived durable facts become reviewable candidates, not active memories.
    memory::promote_summary_to_memory_candidates(
        &mut conn,
        session_id,
        project,
        Some("Implement benchmark framework"),
        Some("Use FTS5 for search, chose Rust for single-binary deployment"),
        Some("FTS5 trigram tokenizer handles CJK well"),
        Some("Always run cargo check before cargo test"),
    )?;

    let memory_count: i64 =
        conn.query_row("SELECT COUNT(*) FROM memories", [], |row| row.get(0))?;
    let decisions: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memory_candidates WHERE memory_type = 'decision'",
        [],
        |row| row.get(0),
    )?;
    let discoveries: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memory_candidates WHERE memory_type = 'discovery'",
        [],
        |row| row.get(0),
    )?;
    let preferences: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memory_candidates WHERE memory_type = 'preference'",
        [],
        |row| row.get(0),
    )?;

    eprintln!(
        "[Promote] active_memories={} decisions={} discoveries={} preferences={}",
        memory_count, decisions, discoveries, preferences,
    );

    assert_eq!(memory_count, 0, "Summaries must not write active memories");
    assert!(
        decisions > 0,
        "Decisions should be promoted to memory candidates"
    );
    assert!(
        discoveries > 0,
        "Discoveries should be promoted to memory candidates"
    );
    assert!(preferences > 0, "Preferences should become candidates");

    let project_prefs: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memory_candidates
         WHERE memory_type = 'preference' AND scope = 'project'",
        [],
        |row| row.get(0),
    )?;
    eprintln!("[Promote] project preference candidates: {project_prefs}/{preferences}");
    assert!(
        project_prefs > 0,
        "Preference candidates should default to project scope"
    );

    Ok(())
}

// ===========================================================================
// Scenario 8: Search filters by type
// ===========================================================================

#[test]
fn bench_search_filter_by_type() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    memory::insert_memory(
        &conn,
        Some("s1"),
        "tools/remem",
        None,
        "FTS5 search design",
        "Technical architecture for search",
        "architecture",
        None,
    )?;
    memory::insert_memory(
        &conn,
        Some("s1"),
        "tools/remem",
        None,
        "Fixed FTS5 crash",
        "Wrapped tokens in quotes",
        "bugfix",
        None,
    )?;
    memory::insert_memory(
        &conn,
        Some("s1"),
        "tools/remem",
        None,
        "Search uses FTS5",
        "Decision to use FTS5",
        "decision",
        None,
    )?;

    // Filter by type
    let decisions = search::search(
        &conn,
        Some("FTS5"),
        Some("tools/remem"),
        Some("decision"),
        10,
        0,
        true,
    )?;
    assert_eq!(
        decisions.len(),
        1,
        "Type filter should return only decisions"
    );
    assert_eq!(decisions[0].memory_type, "decision");

    let bugfixes = search::search(
        &conn,
        Some("FTS5"),
        Some("tools/remem"),
        Some("bugfix"),
        10,
        0,
        true,
    )?;
    assert_eq!(bugfixes.len(), 1, "Type filter should return only bugfixes");

    // No filter: all 3
    let all = search::search(&conn, Some("FTS5"), Some("tools/remem"), None, 10, 0, true)?;
    assert_eq!(all.len(), 3, "Without type filter should return all 3");

    Ok(())
}

// ===========================================================================
// Scenario 9: Topic key deduplication
// ===========================================================================

#[test]
fn bench_topic_key_dedup() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let project = "tools/remem";
    let topic = "search-strategy";

    // Insert v1
    let id1 = memory::insert_memory(
        &conn,
        Some("s1"),
        project,
        Some(topic),
        "Search strategy v1",
        "Initial FTS5 approach",
        "decision",
        None,
    )?;

    // Insert v2 with same topic_key (should upsert)
    let id2 = memory::insert_memory(
        &conn,
        Some("s2"),
        project,
        Some(topic),
        "Search strategy v2",
        "FTS5 with LIKE fallback for short tokens",
        "decision",
        None,
    )?;

    assert_eq!(id1, id2, "Same topic_key should return same ID (upsert)");

    let all = memory::get_recent_memories(&conn, project, 50)?;
    let strategy_mems: Vec<_> = all
        .iter()
        .filter(|m| m.topic_key.as_deref() == Some(topic))
        .collect();
    assert_eq!(
        strategy_mems.len(),
        1,
        "Should have exactly 1 memory for topic_key"
    );
    assert!(
        strategy_mems[0].text.contains("LIKE fallback"),
        "Content should be the updated version"
    );

    Ok(())
}

// ===========================================================================
// Scenario 10: Multi-hop Entity Graph Expansion
// ===========================================================================

#[test]
fn bench_multi_hop_entity_graph_retrieval() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    // Simulate multi-hop scenario: "What do Melanie's kids like?"
    // Memory 1: mentions Melanie and her son Tom
    let id1 = memory::insert_memory(
        &conn,
        Some("s1"),
        "personal",
        None,
        "Family update from Melanie",
        "Melanie mentioned her son Tom started kindergarten this fall. \
         She also talked about her daughter Sarah who is in 3rd grade.",
        "discovery",
        None,
    )?;

    // Memory 2: mentions Tom's interests (no direct mention of Melanie)
    let id2 = memory::insert_memory(
        &conn,
        Some("s2"),
        "personal",
        None,
        "Tom's hobbies",
        "Tom loves dinosaurs and building Lego sets. He wants a T-Rex for his birthday.",
        "discovery",
        None,
    )?;

    // Memory 3: mentions Sarah's interests (no direct mention of Melanie)
    let id3 = memory::insert_memory(
        &conn,
        Some("s3"),
        "personal",
        None,
        "Sarah's school activities",
        "Sarah is on the school swim team and loves reading Harry Potter books.",
        "discovery",
        None,
    )?;

    // Noise memory
    memory::insert_memory(
        &conn,
        Some("s4"),
        "personal",
        None,
        "Weekend plans",
        "Going hiking at the national park this Saturday.",
        "discovery",
        None,
    )?;

    // Link entities to memories
    entity::link_entities(
        &conn,
        id1,
        &[
            "Melanie".to_string(),
            "Tom".to_string(),
            "Sarah".to_string(),
        ],
    )?;
    entity::link_entities(&conn, id2, &["Tom".to_string(), "Lego".to_string()])?;
    entity::link_entities(&conn, id3, &["Sarah".to_string()])?;

    // Standard search: "Melanie's kids" — should find memory about Melanie
    let standard = search::search(
        &conn,
        Some("Melanie kids"),
        Some("personal"),
        None,
        10,
        0,
        true,
    )?;
    let standard_ids: Vec<i64> = standard.iter().map(|m| m.id).collect();

    // Multi-hop search: should find Melanie + Tom's hobbies + Sarah's activities
    let multi = search_multihop::search_multi_hop(
        &conn,
        "Melanie kids",
        Some("personal"),
        10,
        0,
        None,
        None,
        true,
        false,
    )?;
    let multi_ids: Vec<i64> = multi.memories.iter().map(|m| m.id).collect();

    eprintln!("[Multi-hop] Standard search found: {:?}", standard_ids);
    eprintln!("[Multi-hop] Multi-hop search found: {:?}", multi_ids);
    eprintln!("[Multi-hop] Hops: {}", multi.hops);
    eprintln!(
        "[Multi-hop] Entities discovered: {:?}",
        multi.entities_discovered
    );

    // Standard search should find at least the Melanie memory
    assert!(
        standard_ids.contains(&id1),
        "Standard search should find Melanie memory"
    );

    // Multi-hop should find all three relevant memories
    assert!(
        multi_ids.contains(&id1),
        "Multi-hop should find Melanie memory"
    );
    assert!(
        multi_ids.contains(&id2),
        "Multi-hop should find Tom's hobbies via entity graph"
    );
    assert!(
        multi_ids.contains(&id3),
        "Multi-hop should find Sarah's activities via entity graph"
    );

    // Multi-hop should have discovered entities from first-hop results
    assert!(
        !multi.entities_discovered.is_empty(),
        "Should have discovered entities from first-hop results",
    );

    // The key assertion: multi-hop recall must be perfect (find all 3)
    let relevant = vec![id1, id2, id3];
    let multi_recall = recall_at_k(&multi_ids, &relevant, 10);
    eprintln!("[Multi-hop] Multi-hop R@10={:.2}", multi_recall);
    assert!(
        multi_recall >= 1.0,
        "Multi-hop should find all relevant memories, R@10={:.2}",
        multi_recall,
    );

    Ok(())
}

#[test]
fn bench_entity_graph_expansion_finds_related() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    // Memory A mentions entities X and Y
    let id_a = memory::insert_memory(
        &conn,
        Some("s1"),
        "proj",
        None,
        "Project setup with React and TypeScript",
        "Configured React with TypeScript template.",
        "architecture",
        None,
    )?;
    // Memory B mentions entity Y and Z (related to A via Y)
    let id_b = memory::insert_memory(
        &conn,
        Some("s2"),
        "proj",
        None,
        "TypeScript strict mode config",
        "Enabled strict mode in tsconfig.",
        "decision",
        None,
    )?;
    // Memory C mentions entity Z only (related to B via Z, 2-hop from A)
    let id_c = memory::insert_memory(
        &conn,
        Some("s3"),
        "proj",
        None,
        "ESLint config for strict mode",
        "Added eslint-config-strict rules.",
        "decision",
        None,
    )?;

    entity::link_entities(
        &conn,
        id_a,
        &["React".to_string(), "TypeScript".to_string()],
    )?;
    entity::link_entities(&conn, id_b, &["TypeScript".to_string()])?;
    entity::link_entities(&conn, id_c, &["ESLint".to_string()])?;

    // From seed [id_a], entity graph should find id_b (shares TypeScript)
    let expanded = entity::expand_via_entity_graph(&conn, &[id_a], &[], None, 10)?;
    assert!(
        expanded.contains(&id_b),
        "Graph expansion from A should find B (shared entity: TypeScript). Got: {:?}",
        expanded,
    );
    // id_c should NOT be found (no shared entity with A)
    assert!(
        !expanded.contains(&id_c),
        "Graph expansion from A should NOT find C (no shared entity)",
    );

    Ok(())
}

// ===========================================================================
// Aggregate Report
// ===========================================================================

#[test]
fn bench_aggregate_report() -> Result<()> {
    let conn = Connection::open_in_memory()?;
    setup_full_schema(&conn)?;

    let seeds = search_eval_memories();
    let ids = insert_seed_memories(&conn, &seeds)?;

    let fts_relevant: Vec<i64> = seeds
        .iter()
        .zip(ids.iter())
        .filter(|(s, _)| s.relevant_to_fts_query)
        .map(|(_, id)| *id)
        .collect();
    let decay_relevant: Vec<i64> = seeds
        .iter()
        .zip(ids.iter())
        .filter(|(s, _)| s.relevant_to_decay_query)
        .map(|(_, id)| *id)
        .collect();

    let fts_results = search::search(
        &conn,
        Some("FTS5 search"),
        Some("tools/remem"),
        None,
        10,
        0,
        true,
    )?;
    let fts_ids: Vec<i64> = fts_results.iter().map(|m| m.id).collect();

    let decay_results = search::search(
        &conn,
        Some("time decay ranking"),
        Some("tools/remem"),
        None,
        10,
        0,
        true,
    )?;
    let decay_ids: Vec<i64> = decay_results.iter().map(|m| m.id).collect();

    eprintln!("\n========================================");
    eprintln!("  remem Benchmark Report");
    eprintln!("========================================");
    eprintln!(
        "  FTS5 Search    P@5={:.2}  R@10={:.2}",
        precision_at_k(&fts_ids, &fts_relevant, 5),
        recall_at_k(&fts_ids, &fts_relevant, 10)
    );
    eprintln!(
        "  Decay Search   P@5={:.2}  R@10={:.2}",
        precision_at_k(&decay_ids, &decay_relevant, 5),
        recall_at_k(&decay_ids, &decay_relevant, 10)
    );
    eprintln!("  Total seeds: {}", seeds.len());
    eprintln!("  FTS relevant: {}", fts_relevant.len());
    eprintln!("  Decay relevant: {}", decay_relevant.len());
    eprintln!("========================================\n");

    Ok(())
}