mnemoria 0.3.5

Persistent, git-friendly memory storage for AI agents with hybrid semantic + full-text search
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
//! # Mnemoria
//!
//! Persistent, git-friendly memory storage for AI agents with hybrid
//! semantic + full-text search.
//!
//! Mnemoria provides a single-file, append-only memory store that AI assistants
//! (Claude, GPT, Cursor, or any LLM-based tool) can use to remember information
//! across conversations and sessions. Memories are stored in a binary log with
//! CRC32 checksum chaining for corruption detection and crash recovery.
//!
//! ## Key features
//!
//! - **Hybrid search** — combines BM25 full-text search (via [Tantivy]) with
//!   semantic vector search (via [model2vec]) using Reciprocal Rank Fusion.
//! - **Git-friendly** — the append-only binary format produces clean diffs and
//!   merges well in version control.
//! - **Corruption-resistant** — CRC32 checksum chain with automatic crash
//!   recovery and log truncation on open.
//! - **Multi-process safe** — advisory file locking and per-process ephemeral
//!   search indexes allow concurrent readers and writers.
//!
//! [Tantivy]: https://docs.rs/tantivy
//! [model2vec]: https://docs.rs/model2vec
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use mnemoria::{Mnemoria, EntryType};
//! use std::path::Path;
//!
//! # async fn example() -> Result<(), mnemoria::Error> {
//! // Create a new memory store
//! let memory = Mnemoria::create(Path::new("./my-memories")).await?;
//!
//! // Store a memory
//! let id = memory.remember(
//!     "my-agent",
//!     EntryType::Discovery,
//!     "Rust async patterns",
//!     "Use tokio::spawn for CPU-bound work inside async contexts",
//! ).await?;
//!
//! // Search by meaning
//! let results = memory.search_memory("async concurrency", 5, None).await?;
//! for result in &results {
//!     println!("[{}] {} (score: {:.3})", result.entry.entry_type, result.entry.summary, result.score);
//! }
//!
//! // Retrieve by ID
//! let entry = memory.get(&id).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Storage format
//!
//! A memory store is a directory containing:
//!
//! | File              | Purpose                          |
//! |-------------------|----------------------------------|
//! | `log.bin`         | Append-only binary log (rkyv)    |
//! | `manifest.json`   | Metadata and checksum state      |
//! | `mnemoria.lock`   | Advisory file lock               |
//!
//! The search index is ephemeral — rebuilt from `log.bin` on each open — and
//! is stored in the OS temp directory, not in the memory store itself.
//!
//! ## Feature flags
//!
//! | Flag       | Default | Description                                    |
//! |------------|---------|------------------------------------------------|
//! | `model2vec` | **yes** | Enables semantic embeddings via model2vec.    |
//!
//! Without `model2vec`, only BM25 keyword search is available.

pub mod api;
pub mod constants;
pub mod embeddings;
pub mod error;
pub mod search;
pub mod storage;
pub mod types;

pub use api::Mnemoria;
pub use constants::{APP_NAME, DEFAULT_MODEL_ID};
pub use error::{Error, Result, lock_mutex};
pub use types::{
    Config, DurabilityMode, EntryType, MemoryEntry, MemoryStats, SearchResult, TimelineOptions,
};

#[cfg(test)]
mod tests {
    use super::{Config, DurabilityMode, EntryType, Mnemoria, TimelineOptions};
    use crate::storage::{LogWriter, Manifest};
    use crate::types::MemoryEntry;
    use std::fs::OpenOptions;
    use std::io::Write;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn create_temp_dir() -> TempDir {
        tempfile::tempdir().unwrap()
    }

    #[tokio::test]
    async fn test_create_and_open() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        drop(memory);

        let memory = Mnemoria::open(&path).await.unwrap();
        let stats = memory.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 0);
    }

    #[tokio::test]
    async fn test_remember_entry() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        let id = memory
            .remember(
                "test-agent",
                EntryType::Decision,
                "Test decision",
                "This is a test decision content",
            )
            .await
            .unwrap();

        assert!(!id.is_empty());

        let stats = memory.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 1);

        // Verify agent_name is stored
        let entry = memory.get(&id).await.unwrap().unwrap();
        assert_eq!(entry.agent_name, "test-agent");
    }

    #[tokio::test]
    async fn test_search_memory() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember(
                "agent-a",
                EntryType::Decision,
                "User prefers dark mode",
                "The user prefers dark mode in their IDE for reduced eye strain.",
            )
            .await
            .unwrap();

        memory
            .remember(
                "agent-b",
                EntryType::Feature,
                "User likes autocomplete",
                "The user heavily relies on AI autocomplete for coding efficiency.",
            )
            .await
            .unwrap();

        let results = memory
            .search_memory("dark mode preference", 5, None)
            .await
            .unwrap();
        assert!(!results.is_empty());
        assert!(results[0].score >= 0.0);
    }

    #[tokio::test]
    async fn test_search_memory_filter_by_agent() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember(
                "agent-a",
                EntryType::Decision,
                "Dark mode setting",
                "User prefers dark mode in their IDE.",
            )
            .await
            .unwrap();

        memory
            .remember(
                "agent-b",
                EntryType::Decision,
                "Dark theme preference",
                "Dark theme is preferred for the web app.",
            )
            .await
            .unwrap();

        // Search with agent filter should only return agent-a's entry
        let results = memory
            .search_memory("dark mode", 5, Some("agent-a"))
            .await
            .unwrap();
        assert!(!results.is_empty());
        for result in &results {
            assert_eq!(result.entry.agent_name, "agent-a");
        }

        // Search without filter returns both
        let all_results = memory.search_memory("dark", 5, None).await.unwrap();
        assert!(all_results.len() >= 2);
    }

    #[tokio::test]
    async fn test_timeline() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("test-agent", EntryType::Discovery, "First", "First entry")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Second", "Second entry")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Third", "Third entry")
            .await
            .unwrap();

        let timeline = memory
            .timeline(TimelineOptions {
                limit: 10,
                since: None,
                until: None,
                reverse: true,
                agent_name: None,
            })
            .await
            .unwrap();

        assert_eq!(timeline.len(), 3);
    }

    #[tokio::test]
    async fn test_timeline_filter_by_agent() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("agent-a", EntryType::Discovery, "A entry", "From agent A")
            .await
            .unwrap();
        memory
            .remember("agent-b", EntryType::Discovery, "B entry", "From agent B")
            .await
            .unwrap();
        memory
            .remember(
                "agent-a",
                EntryType::Discovery,
                "A entry 2",
                "From agent A again",
            )
            .await
            .unwrap();

        let timeline = memory
            .timeline(TimelineOptions {
                limit: 10,
                since: None,
                until: None,
                reverse: true,
                agent_name: Some("agent-a".to_string()),
            })
            .await
            .unwrap();

        assert_eq!(timeline.len(), 2);
        for entry in &timeline {
            assert_eq!(entry.agent_name, "agent-a");
        }
    }

    #[tokio::test]
    async fn test_verify_checksums() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("test-agent", EntryType::Decision, "Test", "Content")
            .await
            .unwrap();

        let valid = memory.verify().await.unwrap();
        assert!(valid);
    }

    #[tokio::test]
    async fn test_memory_stats() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("test-agent", EntryType::Discovery, "Test 1", "Content 1")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Test 2", "Content 2")
            .await
            .unwrap();

        let stats = memory.memory_stats().await.unwrap();

        assert_eq!(stats.total_entries, 2);
        assert!(stats.file_size_bytes > 0);
        assert!(stats.oldest_timestamp.is_some());
        assert!(stats.newest_timestamp.is_some());
    }

    #[tokio::test]
    async fn test_export_import() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("test-agent", EntryType::Decision, "Test", "Content")
            .await
            .unwrap();

        let export_path = temp_dir.path().join("export.json");
        memory.export(&export_path).await.unwrap();

        let mem2_path = temp_dir.path().join("mem2");
        let memory2 = Mnemoria::create(&mem2_path).await.unwrap();
        let count = memory2.import(&export_path).await.unwrap();

        assert_eq!(count, 1);

        // Verify agent_name survives export/import
        let entries = memory2.timeline(TimelineOptions::default()).await.unwrap();
        assert_eq!(entries[0].agent_name, "test-agent");
    }

    #[tokio::test]
    async fn test_get_entry() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        let id = memory
            .remember("test-agent", EntryType::Decision, "Test", "Content")
            .await
            .unwrap();

        let entry = memory.get(&id).await.unwrap();
        assert!(entry.is_some());
        let entry = entry.unwrap();
        assert_eq!(entry.summary, "Test");
        assert_eq!(entry.agent_name, "test-agent");
    }

    #[tokio::test]
    async fn test_compact() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("test-agent", EntryType::Discovery, "Test 1", "Content 1")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Test 2", "Content 2")
            .await
            .unwrap();

        memory.compact().await.unwrap();

        let stats = memory.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 2);
    }

    #[tokio::test]
    async fn test_rebuild_index() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        memory
            .remember("test-agent", EntryType::Discovery, "Test", "Content")
            .await
            .unwrap();

        memory.rebuild_index().await.unwrap();

        let results = memory.search_memory("Test", 5, None).await.unwrap();
        assert!(!results.is_empty());
    }

    #[tokio::test]
    async fn test_config_with_max_entries() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let config = Config {
            max_entries: Some(2),
            ..Config::default()
        };

        let memory = Mnemoria::create_with_config(&path, config).await.unwrap();

        memory
            .remember("test-agent", EntryType::Discovery, "Entry 1", "Content 1")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Entry 2", "Content 2")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Entry 3", "Content 3")
            .await
            .unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Entry 4", "Content 4")
            .await
            .unwrap();

        let stats = memory.memory_stats().await.unwrap();
        assert!(stats.total_entries <= 2);
    }

    #[tokio::test]
    async fn test_open_recovers_when_manifest_update_was_missed() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Entry 1", "Content 1")
            .await
            .unwrap();

        let manifest_before = Manifest::load(&path).unwrap();
        let entry2 = MemoryEntry::new(
            "test-agent".to_string(),
            EntryType::Discovery,
            "Entry 2".to_string(),
            "Content 2".to_string(),
            manifest_before.last_checksum,
        );

        let log_path = Manifest::log_path(&path);
        let mut writer = LogWriter::new(&log_path).unwrap();
        writer.append(&entry2).unwrap();
        drop(writer);
        drop(memory);

        let reopened = Mnemoria::open(&path).await.unwrap();
        let stats = reopened.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 2);
        assert!(reopened.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_open_truncates_partial_tail_record() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Entry 1", "Content 1")
            .await
            .unwrap();

        let log_path = Manifest::log_path(&path);
        let valid_size = std::fs::metadata(&log_path).unwrap().len();

        let mut file = OpenOptions::new().append(true).open(&log_path).unwrap();
        file.write_all(&[1, 2, 3, 4, 5, 6]).unwrap();
        file.sync_all().unwrap();
        drop(file);
        drop(memory);

        let reopened = Mnemoria::open(&path).await.unwrap();
        let stats = reopened.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 1);
        assert_eq!(stats.file_size_bytes, valid_size);
        assert!(reopened.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_open_recovers_from_corrupt_manifest_json() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        memory
            .remember("test-agent", EntryType::Discovery, "Entry 1", "Content 1")
            .await
            .unwrap();
        drop(memory);

        let manifest_path = Manifest::path(&path);
        std::fs::write(&manifest_path, "{not-valid-json").unwrap();

        let reopened = Mnemoria::open(&path).await.unwrap();
        let stats = reopened.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 1);
        assert!(reopened.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_semantic_hybrid_search_parity_after_reopen() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        memory
            .remember(
                "test-agent",
                EntryType::Discovery,
                "Neural memory retrieval",
                "Vector embeddings help retrieve semantically related memories.",
            )
            .await
            .unwrap();
        memory
            .remember(
                "test-agent",
                EntryType::Discovery,
                "CLI ergonomics",
                "Improve command ergonomics and shell UX.",
            )
            .await
            .unwrap();

        let query = "semantic retrieval with embeddings";
        let before = memory.search_memory(query, 5, None).await.unwrap();

        if before.is_empty() {
            return;
        }

        let before_ids: Vec<String> = before.iter().map(|r| r.id.clone()).collect();
        drop(memory);

        let reopened = Mnemoria::open(&path).await.unwrap();
        let after = reopened.search_memory(query, 5, None).await.unwrap();
        let after_ids: Vec<String> = after.iter().map(|r| r.id.clone()).collect();

        assert_eq!(after_ids, before_ids);
    }

    #[tokio::test]
    async fn test_open_rebuilds_index_from_log() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        memory
            .remember(
                "test-agent",
                EntryType::Discovery,
                "Index rebuild candidate",
                "This entry should remain searchable after reopen.",
            )
            .await
            .unwrap();
        drop(memory);

        // Each open() creates a fresh per-process index from the log,
        // so entries are always searchable after reopen.
        let reopened = Mnemoria::open(&path).await.unwrap();
        let results = reopened
            .search_memory("searchable after reopen", 5, None)
            .await
            .unwrap();
        assert!(!results.is_empty());
    }

    #[tokio::test]
    async fn test_search_recovers_after_reopen_with_deferred_index_commits() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();
        memory
            .remember(
                "test-agent",
                EntryType::Discovery,
                "Deferred index entry",
                "This entry is written before any explicit search commit.",
            )
            .await
            .unwrap();
        drop(memory);

        let reopened = Mnemoria::open(&path).await.unwrap();
        let results = reopened
            .search_memory("deferred explicit search", 5, None)
            .await
            .unwrap();
        assert!(!results.is_empty());
    }

    #[tokio::test]
    async fn test_two_instances_see_each_others_writes() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let instance_a = Mnemoria::create(&path).await.unwrap();
        instance_a
            .remember(
                "agent-a",
                EntryType::Discovery,
                "From A",
                "Written by instance A",
            )
            .await
            .unwrap();

        // Open a second instance on the same directory
        let instance_b = Mnemoria::open(&path).await.unwrap();
        let stats_b = instance_b.memory_stats().await.unwrap();
        assert_eq!(stats_b.total_entries, 1, "B should see A's entry on open");

        // A writes another entry
        instance_a
            .remember(
                "agent-a",
                EntryType::Decision,
                "From A again",
                "Second write by A",
            )
            .await
            .unwrap();

        // B should detect the change via refresh_if_stale
        let stats_b = instance_b.memory_stats().await.unwrap();
        assert_eq!(
            stats_b.total_entries, 2,
            "B should see A's second entry via cache invalidation"
        );

        // B writes an entry
        instance_b
            .remember(
                "agent-b",
                EntryType::Problem,
                "From B",
                "Written by instance B",
            )
            .await
            .unwrap();

        // A should see it
        let stats_a = instance_a.memory_stats().await.unwrap();
        assert_eq!(
            stats_a.total_entries, 3,
            "A should see B's entry via cache invalidation"
        );

        // Checksum chain must still be valid
        assert!(instance_a.verify().await.unwrap());
        assert!(instance_b.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_concurrent_writers_preserve_checksum_chain() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let instance_a = Mnemoria::create(&path).await.unwrap();
        let instance_b = Mnemoria::open(&path).await.unwrap();

        // Alternate writes between instances
        for i in 0..10 {
            if i % 2 == 0 {
                instance_a
                    .remember(
                        "agent-a",
                        EntryType::Discovery,
                        &format!("A-{i}"),
                        &format!("Content from A iteration {i}"),
                    )
                    .await
                    .unwrap();
            } else {
                instance_b
                    .remember(
                        "agent-b",
                        EntryType::Decision,
                        &format!("B-{i}"),
                        &format!("Content from B iteration {i}"),
                    )
                    .await
                    .unwrap();
            }
        }

        // Both should see all 10 entries
        let stats_a = instance_a.memory_stats().await.unwrap();
        let stats_b = instance_b.memory_stats().await.unwrap();
        assert_eq!(stats_a.total_entries, 10);
        assert_eq!(stats_b.total_entries, 10);

        // Checksum chain must be intact
        assert!(instance_a.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_compact_while_other_instance_open() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let instance_a = Mnemoria::create(&path).await.unwrap();
        instance_a
            .remember("agent-a", EntryType::Discovery, "Entry 1", "Content 1")
            .await
            .unwrap();
        instance_a
            .remember("agent-a", EntryType::Discovery, "Entry 2", "Content 2")
            .await
            .unwrap();

        let instance_b = Mnemoria::open(&path).await.unwrap();

        // A compacts
        instance_a.compact().await.unwrap();

        // B should still be able to read and write
        let stats_b = instance_b.memory_stats().await.unwrap();
        assert_eq!(stats_b.total_entries, 2);

        instance_b
            .remember("agent-b", EntryType::Decision, "Entry 3", "Content 3")
            .await
            .unwrap();

        let stats_a = instance_a.memory_stats().await.unwrap();
        assert_eq!(stats_a.total_entries, 3);
        assert!(instance_a.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_durability_mode_flush_only() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let config = Config {
            durability: DurabilityMode::FlushOnly,
            ..Config::default()
        };

        let memory = Mnemoria::create_with_config(&path, config).await.unwrap();

        for i in 0..10 {
            memory
                .remember(
                    "test-agent",
                    EntryType::Discovery,
                    &format!("Entry {i}"),
                    &format!("Content {i}"),
                )
                .await
                .unwrap();
        }

        let stats = memory.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 10);
        assert!(memory.verify().await.unwrap());
    }

    #[tokio::test]
    async fn test_ask_memory_with_non_ascii_content() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let memory = Mnemoria::create(&path).await.unwrap();

        // Create content with multi-byte UTF-8 characters that would panic
        // if sliced at an arbitrary byte offset.
        // Emoji (4 bytes each), CJK (3 bytes each), accented chars (2 bytes each)
        let long_content = "Hello \u{1F600}\u{1F600}\u{1F600} ".to_string()
            + &"\u{4E16}\u{754C}".repeat(50) // CJK: 世界 repeated
            + " caf\u{00E9} r\u{00E9}sum\u{00E9}"
            + &"x".repeat(200); // Ensure content > 200 bytes

        memory
            .remember(
                "test-agent",
                EntryType::Discovery,
                "Non-ASCII test",
                &long_content,
            )
            .await
            .unwrap();

        // This must not panic even though content > 200 bytes with multi-byte chars
        let answer = memory.ask_memory("Non-ASCII test", None).await.unwrap();
        assert!(answer.contains("...") || answer.contains("Non-ASCII"));
    }

    #[tokio::test]
    async fn test_durability_mode_none() {
        let temp_dir = create_temp_dir();
        let path = PathBuf::from(temp_dir.path());

        let config = Config {
            durability: DurabilityMode::None,
            ..Config::default()
        };

        let memory = Mnemoria::create_with_config(&path, config).await.unwrap();

        for i in 0..10 {
            memory
                .remember(
                    "test-agent",
                    EntryType::Discovery,
                    &format!("Entry {i}"),
                    &format!("Content {i}"),
                )
                .await
                .unwrap();
        }

        let stats = memory.memory_stats().await.unwrap();
        assert_eq!(stats.total_entries, 10);
        assert!(memory.verify().await.unwrap());
    }
}