erinra 0.2.0

Memory MCP server for LLM coding assistants
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
//! Sync operations: JSONL export/import, tombstones, and conflict resolution.
//!
//! Uses `unchecked_transaction()` for the same reason as `ops_core` — see that module's
//! doc comment for the full rationale (`Database` exposes `&self`, not `&mut self`).

use rusqlite::OptionalExtension;
use rusqlite::types::Value;

use super::Database;
use super::error::{DbError, DbResult};
use super::helpers::*;
use super::types::*;

impl Database {
    // ── tombstones ───────────────────────────────────────────────────────

    /// Create a tombstone entry directly (used in tests).
    /// Production import uses `apply_tombstone` which handles conflict resolution.
    #[cfg(test)]
    pub fn create_tombstone(
        &self,
        entity_type: EntityType,
        entity_id: &str,
        action: TombstoneAction,
    ) -> DbResult<()> {
        self.conn().execute(
            "INSERT OR REPLACE INTO tombstones (entity_type, entity_id, action) \
             VALUES (?1, ?2, ?3)",
            rusqlite::params![entity_type.as_str(), entity_id, action.as_str()],
        )?;
        Ok(())
    }

    // ── sync export/import ─────────────────────────────────────────────

    /// Export all memories (including archived), sorted by created_at ASC, id ASC.
    /// If `since` is provided, only memories with updated_at > since are returned.
    pub fn export_memories(&self, since: Option<&str>) -> DbResult<Vec<Memory>> {
        let conn = self.conn();

        let (sql, params): (String, Vec<Value>) = if let Some(ts) = since {
            (
                "SELECT id, content, type, created_at, updated_at, archived_at, \
                        last_accessed_at, access_count \
                 FROM memories WHERE updated_at > ?1 \
                 ORDER BY created_at ASC, id ASC"
                    .to_string(),
                vec![Value::Text(ts.to_string())],
            )
        } else {
            (
                "SELECT id, content, type, created_at, updated_at, archived_at, \
                        last_accessed_at, access_count \
                 FROM memories ORDER BY created_at ASC, id ASC"
                    .to_string(),
                vec![],
            )
        };

        let mut stmt = conn.prepare(&sql)?;
        let mut memories: Vec<Memory> = stmt
            .query_map(rusqlite::params_from_iter(&params), map_memory_row)?
            .collect::<Result<_, _>>()?;

        let ids: Vec<String> = memories.iter().map(|m| m.id.clone()).collect();
        let id_refs: Vec<&str> = ids.iter().map(|s| s.as_str()).collect();
        fill_projects_and_tags(conn, &mut memories, &id_refs)?;

        Ok(memories)
    }

    /// Export all links, sorted by created_at ASC, id ASC.
    /// If `since` is provided, only links with created_at > since are returned.
    pub fn export_links(&self, since: Option<&str>) -> DbResult<Vec<Link>> {
        let conn = self.conn();

        let (sql, params): (String, Vec<Value>) = if let Some(ts) = since {
            (
                "SELECT id, source_id, target_id, relation, created_at \
                 FROM links WHERE created_at > ?1 \
                 ORDER BY created_at ASC, id ASC"
                    .to_string(),
                vec![Value::Text(ts.to_string())],
            )
        } else {
            (
                "SELECT id, source_id, target_id, relation, created_at \
                 FROM links ORDER BY created_at ASC, id ASC"
                    .to_string(),
                vec![],
            )
        };

        let mut stmt = conn.prepare(&sql)?;
        let links: Vec<Link> = stmt
            .query_map(rusqlite::params_from_iter(&params), map_link)?
            .collect::<Result<_, _>>()?;

        Ok(links)
    }

    /// Export tombstones newer than max_age_days.
    /// Sorted by timestamp ASC, entity_id ASC.
    pub fn export_tombstones(&self, max_age_days: u32) -> DbResult<Vec<Tombstone>> {
        let conn = self.conn();
        let mut stmt = conn.prepare(
            "SELECT entity_type, entity_id, action, timestamp \
             FROM tombstones \
             WHERE timestamp > strftime('%Y-%m-%dT%H:%M:%fZ', 'now', ?1) \
             ORDER BY timestamp ASC, entity_id ASC",
        )?;
        let cutoff = format!("-{max_age_days} days");
        let rows: Vec<Tombstone> = stmt
            .query_map([&cutoff], |row| {
                Ok(Tombstone {
                    entity_type: row.get(0)?,
                    entity_id: row.get(1)?,
                    action: row.get(2)?,
                    timestamp: row.get(3)?,
                })
            })?
            .collect::<Result<_, _>>()?;
        Ok(rows)
    }

    /// Delete tombstones older than max_age_days. Returns count deleted.
    pub fn purge_old_tombstones(&self, max_age_days: u32) -> DbResult<usize> {
        let cutoff = format!("-{max_age_days} days");
        let deleted = self.conn().execute(
            "DELETE FROM tombstones WHERE timestamp <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now', ?1)",
            [&cutoff],
        )?;
        Ok(deleted)
    }

    /// Read-only reconciliation: decide Insert/Update/Skip based on timestamp comparison.
    pub fn reconcile_memory(
        &self,
        id: &str,
        remote_updated_at: &str,
    ) -> DbResult<ReconcileDecision> {
        let existing: Option<String> = self
            .conn()
            .query_row(
                "SELECT updated_at FROM memories WHERE id = ?1",
                [id],
                |row| row.get(0),
            )
            .optional()?;

        match existing {
            None => Ok(ReconcileDecision::Insert),
            Some(local_ts) if local_ts.as_str() >= remote_updated_at => Ok(ReconcileDecision::Skip),
            Some(_) => Ok(ReconcileDecision::Update),
        }
    }

    /// Import a memory via upsert: insert if new, update if remote is newer, skip otherwise.
    /// Returns the action taken.
    pub fn import_memory(&self, params: &ImportMemoryParams) -> DbResult<ImportAction> {
        let decision = self.reconcile_memory(params.id, params.updated_at)?;
        self.write_import_memory(params, decision)
    }

    /// Write a memory import with a pre-determined decision (no reconciliation query).
    pub(crate) fn write_import_memory(
        &self,
        params: &ImportMemoryParams,
        decision: ReconcileDecision,
    ) -> DbResult<ImportAction> {
        let ImportMemoryParams {
            id,
            content,
            memory_type,
            projects,
            tags,
            created_at,
            updated_at,
            archived_at,
            embedding,
        } = params;

        // Safety net: enforce limit regardless of caller (MCP, import, etc.).
        let max = self.max_content_size();
        if content.len() > max {
            return Err(DbError::ContentTooLarge {
                actual: content.len(),
                max,
            });
        }

        match decision {
            ReconcileDecision::Skip => Ok(ImportAction::Skipped),
            ReconcileDecision::Insert => {
                let emb_bytes = embedding_to_bytes(embedding);
                let conn = self.conn();
                let tx = conn.unchecked_transaction()?;

                tx.execute(
                    "INSERT INTO memories (id, content, type, created_at, updated_at, archived_at, embedding) \
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                    rusqlite::params![id, content, memory_type, created_at, updated_at, archived_at, emb_bytes],
                )?;

                insert_projects(&tx, id, projects)?;
                insert_tags(&tx, id, tags)?;

                // The embedding BLOB was written inline in the INSERT above; the vec0
                // index is populated by the `memories_embeddings_insert` trigger
                // (migration_v3).

                tx.commit()?;
                Ok(ImportAction::Inserted)
            }
            ReconcileDecision::Update => {
                let emb_bytes = embedding_to_bytes(embedding);
                let conn = self.conn();
                let tx = conn.unchecked_transaction()?;

                let rows = tx.execute(
                    "UPDATE memories SET content = ?1, type = ?2, \
                     updated_at = ?3, archived_at = ?4, \
                     embedding = ?5 WHERE id = ?6",
                    rusqlite::params![content, memory_type, updated_at, archived_at, emb_bytes, id],
                )?;
                if rows == 0 {
                    tx.commit()?;
                    return Ok(ImportAction::Skipped);
                }

                tx.execute("DELETE FROM memory_projects WHERE memory_id = ?1", [id])?;
                tx.execute("DELETE FROM tags WHERE memory_id = ?1", [id])?;
                insert_projects(&tx, id, projects)?;
                insert_tags(&tx, id, tags)?;

                // The embedding BLOB was written in the UPDATE above; the vec0 index is
                // replaced by the `memories_embeddings_update` trigger (migration_v3),
                // which fires on `UPDATE OF embedding`.

                tx.commit()?;
                Ok(ImportAction::Updated)
            }
        }
    }

    /// Import a link. Inserts if the link ID doesn't exist, skips otherwise.
    pub fn import_link(&self, link: &Link) -> DbResult<ImportAction> {
        let conn = self.conn();

        // Check if link already exists.
        let exists: bool = conn.query_row(
            "SELECT EXISTS(SELECT 1 FROM links WHERE id = ?1)",
            [&link.id],
            |row| row.get(0),
        )?;

        if exists {
            return Ok(ImportAction::Skipped);
        }

        // Verify both memory endpoints exist.
        let source_exists: bool = conn.query_row(
            "SELECT EXISTS(SELECT 1 FROM memories WHERE id = ?1)",
            [&link.source_id],
            |row| row.get(0),
        )?;
        let target_exists: bool = conn.query_row(
            "SELECT EXISTS(SELECT 1 FROM memories WHERE id = ?1)",
            [&link.target_id],
            |row| row.get(0),
        )?;

        if !source_exists || !target_exists {
            tracing::warn!(
                link_id = link.id,
                source_id = link.source_id,
                target_id = link.target_id,
                source_exists,
                target_exists,
                "import_link skipped: one or both endpoint memories do not exist"
            );
            return Ok(ImportAction::Skipped);
        }

        conn.execute(
            "INSERT INTO links (id, source_id, target_id, relation, created_at) \
             VALUES (?1, ?2, ?3, ?4, ?5)",
            rusqlite::params![
                link.id,
                link.source_id,
                link.target_id,
                link.relation,
                link.created_at
            ],
        )?;

        Ok(ImportAction::Inserted)
    }

    /// Apply a tombstone: archive/unarchive/delete the entity, then record the tombstone.
    /// Returns true if the tombstone was applied (state changed), false if skipped.
    pub fn apply_tombstone(&self, tombstone: &Tombstone) -> DbResult<bool> {
        let entity_type_str = tombstone.entity_type.as_str();
        let entity_id = tombstone.entity_id.as_str();
        let action_str = tombstone.action.as_str();
        let timestamp = tombstone.timestamp.as_str();

        let conn = self.conn();
        let tx = conn.unchecked_transaction()?;

        match tombstone.entity_type {
            EntityType::Memory => {
                let archived_at: Option<Option<String>> = tx
                    .query_row(
                        "SELECT archived_at FROM memories WHERE id = ?1",
                        [entity_id],
                        |row| row.get(0),
                    )
                    .optional()?;

                let applied = match (&tombstone.action, archived_at) {
                    (TombstoneAction::Archived, Some(None)) => {
                        // Active memory — archive it.
                        tx.execute(
                            "UPDATE memories SET archived_at = ?1 WHERE id = ?2",
                            rusqlite::params![timestamp, entity_id],
                        )?;
                        true
                    }
                    (TombstoneAction::Unarchived, Some(Some(_))) => {
                        // Archived memory — clear archived_at.
                        tx.execute(
                            "UPDATE memories SET archived_at = NULL, updated_at = ?1 WHERE id = ?2",
                            rusqlite::params![timestamp, entity_id],
                        )?;
                        true
                    }
                    _ => {
                        // Already in desired state or doesn't exist — just record the tombstone.
                        false
                    }
                };

                if !applied {
                    tx.execute(
                        "INSERT OR REPLACE INTO tombstones (entity_type, entity_id, action, timestamp) \
                         VALUES (?1, ?2, ?3, ?4)",
                        rusqlite::params![entity_type_str, entity_id, action_str, timestamp],
                    )?;
                    tx.commit()?;
                    return Ok(false);
                }
            }
            EntityType::Link => {
                let link_exists: bool = tx.query_row(
                    "SELECT EXISTS(SELECT 1 FROM links WHERE id = ?1)",
                    [entity_id],
                    |row| row.get(0),
                )?;
                if !link_exists {
                    tx.execute(
                        "INSERT OR REPLACE INTO tombstones (entity_type, entity_id, action, timestamp) \
                         VALUES (?1, ?2, ?3, ?4)",
                        rusqlite::params![entity_type_str, entity_id, action_str, timestamp],
                    )?;
                    tx.commit()?;
                    return Ok(false);
                }
                tx.execute("DELETE FROM links WHERE id = ?1", [entity_id])?;
            }
        }

        tx.execute(
            "INSERT OR REPLACE INTO tombstones (entity_type, entity_id, action, timestamp) \
             VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![entity_type_str, entity_id, action_str, timestamp],
        )?;
        tx.commit()?;
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::DbConfig;
    use crate::embedding::{Embedder, MockEmbedder};

    fn test_db() -> Database {
        Database::open_in_memory(&DbConfig::default()).unwrap()
    }

    fn mock_embedder() -> MockEmbedder {
        MockEmbedder::new(768)
    }

    fn test_embedding(embedder: &MockEmbedder, text: &str) -> Vec<f32> {
        embedder.embed_documents(&[text]).unwrap().remove(0)
    }

    fn small_content_db() -> Database {
        let config = DbConfig {
            max_content_size: 20,
            ..DbConfig::default()
        };
        Database::open_in_memory(&config).unwrap()
    }

    #[test]
    fn apply_tombstone_link_nonexistent_returns_false() {
        let db = test_db();

        // Apply tombstone for a link that doesn't exist — should return false (not applied).
        let tombstone = Tombstone {
            entity_type: EntityType::Link,
            entity_id: "nonexistent-link-id".into(),
            action: TombstoneAction::Deleted,
            timestamp: "2026-01-01T00:00:00.000000Z".into(),
        };
        let applied = db.apply_tombstone(&tombstone).unwrap();
        assert!(
            !applied,
            "tombstone for nonexistent link should return false"
        );
    }

    #[test]
    fn apply_tombstone_link_idempotent() {
        let db = test_db();
        let emb = mock_embedder();

        // Create two memories and a link between them.
        let id1 = db
            .store(&StoreParams {
                content: "source",
                memory_type: None,
                projects: &[],
                tags: &[],
                links: &[],
                embedding: &test_embedding(&emb, "source"),
            })
            .unwrap();
        let id2 = db
            .store(&StoreParams {
                content: "target",
                memory_type: None,
                projects: &[],
                tags: &[],
                links: &[],
                embedding: &test_embedding(&emb, "target"),
            })
            .unwrap();
        let link = db.link(&id1, &id2, "related_to").unwrap();

        // First application should return true (link was deleted).
        let tombstone = Tombstone {
            entity_type: EntityType::Link,
            entity_id: link.id.clone(),
            action: TombstoneAction::Deleted,
            timestamp: "2026-01-01T00:00:00.000000Z".into(),
        };
        let applied = db.apply_tombstone(&tombstone).unwrap();
        assert!(applied, "first tombstone application should return true");

        // Second application should return false (link already gone).
        let applied2 = db.apply_tombstone(&tombstone).unwrap();
        assert!(
            !applied2,
            "second tombstone application should return false"
        );
    }

    #[test]
    fn apply_tombstone_accepts_tombstone_struct() {
        let db = test_db();
        let emb = mock_embedder();

        // Create a memory.
        let id = db
            .store(&StoreParams {
                content: "to be archived via struct",
                memory_type: None,
                projects: &[],
                tags: &[],
                links: &[],
                embedding: &test_embedding(&emb, "to be archived via struct"),
            })
            .unwrap();

        // Apply tombstone using Tombstone struct.
        let tombstone = Tombstone {
            entity_type: EntityType::Memory,
            entity_id: id.clone(),
            action: TombstoneAction::Archived,
            timestamp: "2026-01-01T00:00:00.000000Z".into(),
        };
        let applied = db.apply_tombstone(&tombstone).unwrap();
        assert!(applied, "should archive active memory");

        // Verify the memory is archived.
        let results = db.get(&[&id]).unwrap();
        assert!(results[0].memory.archived_at.is_some());

        // Second application should return false.
        let applied2 = db.apply_tombstone(&tombstone).unwrap();
        assert!(!applied2, "already archived should return false");
    }

    #[test]
    fn export_tombstones_returns_tombstone_structs() {
        let db = test_db();

        // Create a tombstone directly.
        db.create_tombstone(EntityType::Memory, "mem-abc", TombstoneAction::Archived)
            .unwrap();

        // Export and verify we get Tombstone structs with correct fields.
        let tombstones: Vec<Tombstone> = db.export_tombstones(90).unwrap();
        assert_eq!(tombstones.len(), 1);
        assert_eq!(tombstones[0].entity_type, EntityType::Memory);
        assert_eq!(tombstones[0].entity_id, "mem-abc");
        assert_eq!(tombstones[0].action, TombstoneAction::Archived);
        assert!(
            !tombstones[0].timestamp.is_empty(),
            "timestamp should be set"
        );
    }

    #[test]
    fn import_memory_accepts_params_struct() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "imported via struct");

        let params = ImportMemoryParams {
            id: "import-struct-1",
            content: "imported via struct",
            memory_type: Some("note"),
            projects: &["proj-a"],
            tags: &["rust"],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-01-01T00:00:00.000000Z",
            archived_at: None,
            embedding: &embedding,
        };
        let action = db.import_memory(&params).unwrap();
        assert_eq!(action, ImportAction::Inserted);

        // Verify the memory was stored correctly.
        let results = db.get(&["import-struct-1"]).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].memory.content, "imported via struct");
        assert_eq!(results[0].memory.memory_type.as_deref(), Some("note"));
        assert_eq!(results[0].memory.projects, vec!["proj-a"]);
        assert_eq!(results[0].memory.tags, vec!["rust"]);
    }

    #[test]
    fn import_memory_rejects_oversized_content() {
        let db = small_content_db();
        let emb = mock_embedder();
        let big = "x".repeat(21);
        let embedding = test_embedding(&emb, &big);

        let params = ImportMemoryParams {
            id: "import-id-1",
            content: &big,
            memory_type: None,
            projects: &[],
            tags: &[],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-01-01T00:00:00.000000Z",
            archived_at: None,
            embedding: &embedding,
        };
        let err = db.import_memory(&params).unwrap_err();
        assert!(matches!(
            err,
            DbError::ContentTooLarge {
                actual: 21,
                max: 20
            }
        ));
    }

    #[test]
    fn reconcile_memory_returns_insert_for_unknown_id() {
        let db = test_db();
        let decision = db
            .reconcile_memory("nonexistent-id", "2026-01-01T00:00:00.000000Z")
            .unwrap();
        assert_eq!(decision, ReconcileDecision::Insert);
    }

    #[test]
    fn reconcile_memory_returns_update_when_remote_is_newer() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "existing memory");

        db.import_memory(&ImportMemoryParams {
            id: "rec-1",
            content: "existing memory",
            memory_type: None,
            projects: &[],
            tags: &[],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-01-01T00:00:00.000000Z",
            archived_at: None,
            embedding: &embedding,
        })
        .unwrap();

        let decision = db
            .reconcile_memory("rec-1", "2026-06-01T00:00:00.000000Z")
            .unwrap();
        assert_eq!(decision, ReconcileDecision::Update);
    }

    #[test]
    fn reconcile_memory_returns_skip_when_local_is_newer() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "newer local");

        db.import_memory(&ImportMemoryParams {
            id: "rec-2",
            content: "newer local",
            memory_type: None,
            projects: &[],
            tags: &[],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-06-01T00:00:00.000000Z",
            archived_at: None,
            embedding: &embedding,
        })
        .unwrap();

        let decision = db
            .reconcile_memory("rec-2", "2026-01-01T00:00:00.000000Z")
            .unwrap();
        assert_eq!(decision, ReconcileDecision::Skip);
    }

    #[test]
    fn write_import_memory_inserts_new_memory() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "brand new memory");

        let action = db
            .write_import_memory(
                &ImportMemoryParams {
                    id: "write-1",
                    content: "brand new memory",
                    memory_type: Some("fact"),
                    projects: &["proj-a"],
                    tags: &["rust", "test"],
                    created_at: "2026-01-01T00:00:00.000000Z",
                    updated_at: "2026-01-01T00:00:00.000000Z",
                    archived_at: None,
                    embedding: &embedding,
                },
                ReconcileDecision::Insert,
            )
            .unwrap();

        assert_eq!(action, ImportAction::Inserted);

        let results = db.get(&["write-1"]).unwrap();
        assert_eq!(results.len(), 1);
        let m = &results[0].memory;
        assert_eq!(m.content, "brand new memory");
        assert_eq!(m.memory_type.as_deref(), Some("fact"));
        assert_eq!(m.projects, vec!["proj-a"]);
        assert_eq!(m.tags, vec!["rust", "test"]);
    }

    #[test]
    fn write_import_memory_updates_existing_memory() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding_old = test_embedding(&emb, "old content");

        // Insert an existing memory first.
        db.import_memory(&ImportMemoryParams {
            id: "write-2",
            content: "old content",
            memory_type: Some("note"),
            projects: &["proj-a"],
            tags: &["old"],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-01-01T00:00:00.000000Z",
            archived_at: None,
            embedding: &embedding_old,
        })
        .unwrap();

        // Now update via write_import_memory with Update decision.
        let embedding_new = test_embedding(&emb, "updated content");
        let action = db
            .write_import_memory(
                &ImportMemoryParams {
                    id: "write-2",
                    content: "updated content",
                    memory_type: Some("pattern"),
                    projects: &["proj-b"],
                    tags: &["new"],
                    created_at: "2026-01-01T00:00:00.000000Z",
                    updated_at: "2026-06-01T00:00:00.000000Z",
                    archived_at: None,
                    embedding: &embedding_new,
                },
                ReconcileDecision::Update,
            )
            .unwrap();

        assert_eq!(action, ImportAction::Updated);

        let results = db.get(&["write-2"]).unwrap();
        assert_eq!(results.len(), 1);
        let m = &results[0].memory;
        assert_eq!(m.content, "updated content");
        assert_eq!(m.memory_type.as_deref(), Some("pattern"));
        assert_eq!(m.projects, vec!["proj-b"]);
        assert_eq!(m.tags, vec!["new"]);
    }

    #[test]
    fn reconcile_memory_returns_skip_on_timestamp_tie() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "tie breaker");

        db.import_memory(&ImportMemoryParams {
            id: "rec-3",
            content: "tie breaker",
            memory_type: None,
            projects: &[],
            tags: &[],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-03-15T12:00:00.000000Z",
            archived_at: None,
            embedding: &embedding,
        })
        .unwrap();

        let decision = db
            .reconcile_memory("rec-3", "2026-03-15T12:00:00.000000Z")
            .unwrap();
        assert_eq!(decision, ReconcileDecision::Skip);
    }

    #[test]
    fn unarchive_tombstone_exports_and_applies_correctly() {
        let db = test_db();
        let emb = mock_embedder();

        // Store and archive a memory.
        let id = db
            .store(&StoreParams {
                content: "will be archived then unarchived",
                memory_type: None,
                projects: &[],
                tags: &[],
                links: &[],
                embedding: &test_embedding(&emb, "will be archived then unarchived"),
            })
            .unwrap();
        db.archive(&id).unwrap();

        // Unarchive it — this writes an 'unarchived' tombstone.
        db.unarchive(&id).unwrap();

        // Export tombstones — this must NOT fail even though the action is 'unarchived'.
        let tombstones = db.export_tombstones(90).unwrap();
        assert_eq!(tombstones.len(), 1);
        assert_eq!(tombstones[0].entity_id, id);
        assert_eq!(tombstones[0].action, TombstoneAction::Unarchived);

        // Now test that apply_tombstone handles the Unarchived action:
        // create a fresh DB, store and archive the same memory, then apply the tombstone.
        let db2 = test_db();
        let emb2 = mock_embedder();
        let embedding = test_embedding(&emb2, "will be archived then unarchived");
        db2.import_memory(&ImportMemoryParams {
            id: &id,
            content: "will be archived then unarchived",
            memory_type: None,
            projects: &[],
            tags: &[],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-01-01T00:00:00.000000Z",
            archived_at: Some("2026-01-02T00:00:00.000000Z"),
            embedding: &embedding,
        })
        .unwrap();

        // Memory should be archived.
        let results = db2.get(&[&id]).unwrap();
        assert!(results[0].memory.archived_at.is_some());

        // Apply the unarchive tombstone.
        let applied = db2.apply_tombstone(&tombstones[0]).unwrap();
        assert!(applied, "unarchive tombstone should be applied");

        // Memory should now be unarchived.
        let results = db2.get(&[&id]).unwrap();
        assert!(
            results[0].memory.archived_at.is_none(),
            "archived_at should be cleared after applying unarchive tombstone"
        );
    }

    // ── embedding-storage invariant on import paths (erin-mgre) ──────────

    /// Read the raw embedding BLOB for a memory id.
    fn blob_for(db: &Database, id: &str) -> Option<Vec<u8>> {
        db.conn()
            .query_row(
                "SELECT embedding FROM memories WHERE id = ?1",
                [id],
                |row| row.get::<_, Option<Vec<u8>>>(0),
            )
            .unwrap()
    }

    /// Count vec0 rows for a memory id.
    fn vec_count(db: &Database, id: &str) -> i64 {
        db.conn()
            .query_row(
                "SELECT count(*) FROM memory_embeddings WHERE memory_id = ?1",
                [id],
                |row| row.get(0),
            )
            .unwrap()
    }

    /// Nearest neighbour id for a KNN MATCH (None if empty).
    fn knn_nearest(db: &Database, embedding: &[f32]) -> Option<String> {
        let bytes = embedding_to_bytes(embedding);
        db.conn()
            .query_row(
                "SELECT memory_id FROM memory_embeddings \
                 WHERE embedding MATCH ?1 ORDER BY distance ASC LIMIT 1",
                rusqlite::params![bytes],
                |row| row.get(0),
            )
            .optional()
            .unwrap()
    }

    /// Assert BLOB == expected LE bytes, exactly one vec0 row, and self KNN match.
    fn assert_stores_agree(db: &Database, id: &str, embedding: &[f32]) {
        let expected = embedding_to_bytes(embedding);
        assert_eq!(
            blob_for(db, id).as_deref(),
            Some(expected.as_slice()),
            "memories.embedding BLOB should hold the expected LE bytes"
        );
        assert_eq!(
            vec_count(db, id),
            1,
            "memory_embeddings should have exactly one row for {id}"
        );
        assert_eq!(
            knn_nearest(db, embedding).as_deref(),
            Some(id),
            "KNN MATCH should return {id} as nearest neighbour of its own vector"
        );
    }

    #[test]
    fn stores_agree_after_import_insert() {
        let db = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "imported insert");

        let action = db
            .import_memory(&ImportMemoryParams {
                id: "imp-ins-1",
                content: "imported insert",
                memory_type: None,
                projects: &[],
                tags: &[],
                created_at: "2026-01-01T00:00:00.000000Z",
                updated_at: "2026-01-01T00:00:00.000000Z",
                archived_at: None,
                embedding: &embedding,
            })
            .unwrap();
        assert_eq!(action, ImportAction::Inserted);

        assert_stores_agree(&db, "imp-ins-1", &embedding);
    }

    #[test]
    fn stores_agree_after_import_update() {
        let db = test_db();
        let emb = mock_embedder();

        // Insert an existing memory.
        db.import_memory(&ImportMemoryParams {
            id: "imp-upd-1",
            content: "old content",
            memory_type: None,
            projects: &[],
            tags: &[],
            created_at: "2026-01-01T00:00:00.000000Z",
            updated_at: "2026-01-01T00:00:00.000000Z",
            archived_at: None,
            embedding: &test_embedding(&emb, "old content"),
        })
        .unwrap();

        // Import a newer version — drives the Update path with a new embedding.
        let new_embedding = test_embedding(&emb, "newer content body");
        let action = db
            .import_memory(&ImportMemoryParams {
                id: "imp-upd-1",
                content: "newer content body",
                memory_type: None,
                projects: &[],
                tags: &[],
                created_at: "2026-01-01T00:00:00.000000Z",
                updated_at: "2026-06-01T00:00:00.000000Z",
                archived_at: None,
                embedding: &new_embedding,
            })
            .unwrap();
        assert_eq!(action, ImportAction::Updated);

        assert_stores_agree(&db, "imp-upd-1", &new_embedding);
    }

    #[test]
    fn export_import_roundtrip_rehydrates_vec_index() {
        // Source DB: store a memory with a known embedding.
        let src = test_db();
        let emb = mock_embedder();
        let embedding = test_embedding(&emb, "round trip subject");
        let id = src
            .store(&StoreParams {
                content: "round trip subject",
                memory_type: Some("fact"),
                projects: &["proj"],
                tags: &["tag"],
                links: &[],
                embedding: &embedding,
            })
            .unwrap();

        // Export carries the embedding via the memories.embedding BLOB.
        let exported = src.export_memories(None).unwrap();
        let exported = exported.iter().find(|m| m.id == id).unwrap();

        // Fresh destination DB: import the exported memory. The BLOB travels with the
        // row and the insert trigger must rehydrate the vec0 index.
        let dst = test_db();
        let action = dst
            .import_memory(&ImportMemoryParams {
                id: &exported.id,
                content: &exported.content,
                memory_type: exported.memory_type.as_deref(),
                projects: &exported
                    .projects
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>(),
                tags: &exported.tags.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                created_at: &exported.created_at,
                updated_at: &exported.updated_at,
                archived_at: exported.archived_at.as_deref(),
                embedding: &embedding,
            })
            .unwrap();
        assert_eq!(action, ImportAction::Inserted);

        // Both stores agree in the destination, and a KNN MATCH finds the imported row.
        assert_stores_agree(&dst, &id, &embedding);

        // End-to-end: a vector search in the fresh DB returns the imported memory.
        let query_embedding = emb.embed_query("round trip subject").unwrap();
        let results = dst
            .search(&SearchParams {
                query: "round trip subject",
                query_embedding: &query_embedding,
                ..Default::default()
            })
            .unwrap()
            .results;
        assert!(
            results.iter().any(|h| h.memory.id == id),
            "imported memory should be findable via search after round-trip"
        );
    }
}