brainos-hippocampus 0.1.0

Episodic and semantic memory engine with hybrid search for Brain OS
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
//! Semantic memory — RuVector-backed vector memory.
//!
//! Stores extracted facts, user model data, and knowledge
//! as vector embeddings for similarity-based retrieval.

use storage::{RuVectorStore, SqlitePool, VectorResult};
use thiserror::Error;
use uuid::Uuid;

/// Errors from the semantic memory layer.
#[derive(Debug, Error)]
pub enum SemanticError {
    #[error("SQLite error: {0}")]
    Sqlite(#[from] storage::sqlite::SqliteError),

    #[error("RuVector error: {0}")]
    RuVector(#[from] storage::ruvector::RuVectorError),

    #[error("Fact not found: {0}")]
    NotFound(String),
}

/// A semantic fact — a structured piece of knowledge.
#[derive(Debug, Clone)]
pub struct Fact {
    pub id: String,
    pub namespace: String,
    pub category: String,
    pub subject: String,
    pub predicate: String,
    pub object: String,
    pub confidence: f64,
    pub source_episode_id: Option<String>,
    /// Originating AI agent (e.g. "claude-code", "opencode"). None for direct user input.
    pub agent: Option<String>,
}

/// A vector search result with the associated fact.
#[derive(Debug, Clone)]
pub struct SemanticResult {
    pub fact: Fact,
    pub distance: f32,
    /// When this fact was last updated (ISO 8601).
    pub created_at: String,
}

/// Semantic memory store — dual-writes to SQLite + RuVector.
///
/// SQLite stores the structured fact data (subject-predicate-object),
/// while RuVector stores the vector embeddings for similarity search.
#[derive(Clone)]
pub struct SemanticStore {
    db: SqlitePool,
    ruv: RuVectorStore,
}

impl SemanticStore {
    /// Create a new semantic store.
    pub fn new(db: SqlitePool, ruv: RuVectorStore) -> Self {
        Self { db, ruv }
    }

    /// Store a new fact in both SQLite and RuVector.
    ///
    /// The `vector` should be the embedding of the fact's content
    /// (typically: "{subject} {predicate} {object}").
    /// The `namespace` scopes the fact (e.g. "personal", "work").
    #[allow(clippy::too_many_arguments)]
    pub async fn store_fact(
        &self,
        namespace: &str,
        category: &str,
        subject: &str,
        predicate: &str,
        object: &str,
        confidence: f64,
        source_episode_id: Option<&str>,
        vector: Vec<f32>,
        agent: Option<&str>,
    ) -> Result<String, SemanticError> {
        let content = format!("{subject} {predicate} {object}");
        let now = chrono::Utc::now().to_rfc3339();

        // Deduplication: check for highly similar facts in the same namespace and category.
        let similar = self.search_similar(vector.clone(), 1, Some(namespace), agent).await?;
        if let Some(hit) = similar.first() {
            // Distance < 0.1 means similarity > 0.9 (cosine distance = 1 - similarity)
            if hit.distance < 0.1 && hit.fact.category == category {
                // If the content is identical, just return the existing ID.
                if hit.fact.subject == subject && hit.fact.predicate == predicate && hit.fact.object == object {
                    return Ok(hit.fact.id.clone());
                }
                // Otherwise, mark the existing fact as superseded and insert the new one.
                let id = self.do_store_fact(namespace, category, subject, predicate, object, confidence, source_episode_id, vector, agent, &content, &now).await?;
                self.db.with_conn(|conn| {
                    conn.execute(
                        "UPDATE semantic_facts SET superseded_by = ?1 WHERE id = ?2",
                        rusqlite::params![id, hit.fact.id],
                    )?;
                    Ok(())
                })?;
                return Ok(id);
            }
        }

        self.do_store_fact(namespace, category, subject, predicate, object, confidence, source_episode_id, vector, agent, &content, &now).await
    }

    #[allow(clippy::too_many_arguments)]
    async fn do_store_fact(
        &self,
        namespace: &str,
        category: &str,
        subject: &str,
        predicate: &str,
        object: &str,
        confidence: f64,
        source_episode_id: Option<&str>,
        vector: Vec<f32>,
        agent: Option<&str>,
        content: &str,
        now: &str,
    ) -> Result<String, SemanticError> {
        let id = Uuid::new_v4().to_string();

        // Encrypt the object field (the main content) if encryption is enabled.
        let stored_object = self.db.encrypt_content(object);

        // Write to SQLite
        self.db.with_conn(|conn| {
            conn.execute(
                "INSERT INTO semantic_facts (id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                rusqlite::params![id, namespace, category, subject, predicate, stored_object, confidence, source_episode_id, agent],
            )?;
            Ok(())
        })?;

        // Write vector to RuVector
        self.ruv
            .add_vectors(
                "facts_vec",
                vec![id.clone()],
                vec![content.to_string()],
                vec![vector],
                vec![now.to_string()],
                "semantic",
            )
            .await?;

        Ok(id)
    }

    /// Search for similar facts by vector, optionally scoped to a namespace.
    ///
    /// Returns facts ranked by vector similarity (closest first).
    /// If `namespace` is `None`, results from all namespaces are returned.
    pub async fn search_similar(
        &self,
        query_vector: Vec<f32>,
        top_k: usize,
        namespace: Option<&str>,
        agent: Option<&str>,
    ) -> Result<Vec<SemanticResult>, SemanticError> {
        // Fetch more candidates so we have enough after filtering
        let fetch_k = if namespace.is_some() || agent.is_some() {
            top_k * 4
        } else {
            top_k
        };
        let ruv_results: Vec<VectorResult> =
            self.ruv.search("facts_vec", query_vector, fetch_k).await?;

        let mut results = Vec::new();
        for vr in ruv_results {
            if results.len() >= top_k {
                break;
            }
            // Look up the full fact + timestamp from SQLite
            let fact_opt = self.get_fact_with_timestamp(&vr.id)?;
            if let Some((fact, created_at)) = fact_opt {
                // Skip superseded facts
                let is_superseded = self.db.with_conn(|conn| {
                    let superseded: Option<String> = conn.query_row(
                        "SELECT superseded_by FROM semantic_facts WHERE id = ?1",
                        [&vr.id],
                        |row| row.get(0)
                    ).unwrap_or(None);
                    Ok(superseded.is_some())
                }).unwrap_or(false);

                if is_superseded {
                    continue;
                }

                // Filter by namespace if specified
                if namespace.is_some_and(|ns| ns != fact.namespace) {
                    continue;
                }
                // Filter by agent if specified
                if agent.is_some_and(|a| fact.agent.as_deref() != Some(a)) {
                    continue;
                }
                results.push(SemanticResult {
                    fact,
                    distance: vr.distance,
                    created_at,
                });
            }
        }

        Ok(results)
    }

    /// Get a fact by ID from SQLite.
    pub fn get_fact(&self, fact_id: &str) -> Result<Option<Fact>, SemanticError> {
        let pool = &self.db;
        Ok(self.db.with_conn(|conn| {
            let result = conn.query_row(
                "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                 FROM semantic_facts WHERE id = ?1",
                [fact_id],
                |row| {
                    let raw_object: String = row.get(5)?;
                    Ok(Fact {
                        id: row.get(0)?,
                        namespace: row.get(1)?,
                        category: row.get(2)?,
                        subject: row.get(3)?,
                        predicate: row.get(4)?,
                        object: pool.decrypt_content(&raw_object),
                        confidence: row.get(6)?,
                        source_episode_id: row.get(7)?,
                        agent: row.get(8)?,
                    })
                },
            );
            match result {
                Ok(fact) => Ok(Some(fact)),
                Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
                Err(e) => Err(e.into()),
            }
        })?)
    }

    /// Get a fact and its updated_at timestamp by ID.
    fn get_fact_with_timestamp(
        &self,
        fact_id: &str,
    ) -> Result<Option<(Fact, String)>, SemanticError> {
        let pool = &self.db;
        Ok(self.db.with_conn(|conn| {
            let result = conn.query_row(
                "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, updated_at, agent
                 FROM semantic_facts WHERE id = ?1",
                [fact_id],
                |row| {
                    let raw_object: String = row.get(5)?;
                    let updated_at: String = row.get(8)?;
                    Ok((Fact {
                        id: row.get(0)?,
                        namespace: row.get(1)?,
                        category: row.get(2)?,
                        subject: row.get(3)?,
                        predicate: row.get(4)?,
                        object: pool.decrypt_content(&raw_object),
                        confidence: row.get(6)?,
                        source_episode_id: row.get(7)?,
                        agent: row.get(9)?,
                    }, updated_at))
                },
            );
            match result {
                Ok(pair) => Ok(Some(pair)),
                Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
                Err(e) => Err(e.into()),
            }
        })?)
    }

    /// Get all facts by category, optionally filtered by namespace.
    pub fn get_facts_by_category(
        &self,
        category: &str,
        namespace: Option<&str>,
    ) -> Result<Vec<Fact>, SemanticError> {
        let pool = &self.db;
        Ok(self.db.with_conn(|conn| {
            let (sql, params): (String, Vec<Box<dyn rusqlite::types::ToSql>>) = match namespace {
                Some(ns) => (
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts 
                     WHERE category = ?1 AND (namespace = ?2 OR namespace LIKE ?3) AND superseded_by IS NULL
                     ORDER BY updated_at DESC".to_string(),
                    vec![Box::new(category.to_string()), Box::new(ns.to_string()), Box::new(format!("{}/%", ns))],
                ),
                None => (
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts WHERE category = ?1 AND superseded_by IS NULL
                     ORDER BY updated_at DESC".to_string(),
                    vec![Box::new(category.to_string())],
                ),
            };

            let mut stmt = conn.prepare(&sql)?;
            let params_ref: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();

            let facts = stmt
                .query_map(params_ref.as_slice(), |row| {
                    let raw_object: String = row.get(5)?;
                    Ok(Fact {
                        id: row.get(0)?,
                        namespace: row.get(1)?,
                        category: row.get(2)?,
                        subject: row.get(3)?,
                        predicate: row.get(4)?,
                        object: pool.decrypt_content(&raw_object),
                        confidence: row.get(6)?,
                        source_episode_id: row.get(7)?,
                        agent: row.get(8)?,
                    })
                })?
                .collect::<Result<Vec<_>, _>>()?;

            Ok(facts)
        })?)
    }

    /// Get all facts about a specific subject.
    pub fn get_facts_about(&self, subject: &str) -> Result<Vec<Fact>, SemanticError> {
        self.get_facts_about_in_namespace(subject, None)
    }

    /// Get facts about a specific subject, optionally filtered by namespace.
    pub fn get_facts_about_in_namespace(
        &self,
        subject: &str,
        namespace: Option<&str>,
    ) -> Result<Vec<Fact>, SemanticError> {
        let pool = &self.db;
        Ok(self.db.with_conn(|conn| {
            let row_to_fact = |row: &rusqlite::Row<'_>| -> rusqlite::Result<Fact> {
                let raw_object: String = row.get(5)?;
                Ok(Fact {
                    id: row.get(0)?,
                    namespace: row.get(1)?,
                    category: row.get(2)?,
                    subject: row.get(3)?,
                    predicate: row.get(4)?,
                    object: pool.decrypt_content(&raw_object),
                    confidence: row.get(6)?,
                    source_episode_id: row.get(7)?,
                    agent: row.get(8)?,
                })
            };

            let facts: Vec<Fact> = if let Some(ns) = namespace {
                let mut stmt = conn.prepare(
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts
                     WHERE subject = ?1 AND (namespace = ?2 OR namespace LIKE ?3)
                     ORDER BY confidence DESC",
                )?;
                let prefix = format!("{}/%", ns);
                let rows = stmt.query_map(rusqlite::params![subject, ns, &prefix], row_to_fact)?;
                rows.collect::<Result<Vec<_>, _>>()?
            } else {
                let mut stmt = conn.prepare(
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts
                     WHERE subject = ?1
                     ORDER BY confidence DESC",
                )?;
                let rows = stmt.query_map([subject], row_to_fact)?;
                rows.collect::<Result<Vec<_>, _>>()?
            };

            Ok(facts)
        })?)
    }

    /// Update a fact (supersedes the old version).
    pub async fn update_fact(
        &self,
        old_fact_id: &str,
        new_object: &str,
        new_vector: Vec<f32>,
    ) -> Result<String, SemanticError> {
        // Get the old fact for its metadata
        let old_fact = self
            .get_fact(old_fact_id)?
            .ok_or_else(|| SemanticError::NotFound(old_fact_id.to_string()))?;

        // Store new fact (preserve namespace and agent)
        let new_id = self
            .store_fact(
                &old_fact.namespace,
                &old_fact.category,
                &old_fact.subject,
                &old_fact.predicate,
                new_object,
                old_fact.confidence,
                old_fact.source_episode_id.as_deref(),
                new_vector,
                old_fact.agent.as_deref(),
            )
            .await?;

        // Mark old fact as superseded
        self.db.with_conn(|conn| {
            conn.execute(
                "UPDATE semantic_facts SET superseded_by = ?1 WHERE id = ?2",
                rusqlite::params![new_id, old_fact_id],
            )?;
            Ok(())
        })?;

        Ok(new_id)
    }

    /// List all active (non-superseded) facts, optionally scoped to a namespace.
    pub fn list_all(&self) -> Result<Vec<Fact>, SemanticError> {
        self.list_by_namespace(None)
    }

    /// List all active facts in a specific namespace.
    pub fn list_by_namespace(&self, namespace: Option<&str>) -> Result<Vec<Fact>, SemanticError> {
        let pool = &self.db;
        Ok(self.db.with_conn(|conn| {
            let row_to_fact = |row: &rusqlite::Row<'_>| -> rusqlite::Result<Fact> {
                let raw_object: String = row.get(5)?;
                Ok(Fact {
                    id: row.get(0)?,
                    namespace: row.get(1)?,
                    category: row.get(2)?,
                    subject: row.get(3)?,
                    predicate: row.get(4)?,
                    object: pool.decrypt_content(&raw_object),
                    confidence: row.get(6)?,
                    source_episode_id: row.get(7)?,
                    agent: row.get(8)?,
                })
            };

            let facts: Vec<Fact> = if let Some(ns) = namespace {
                let mut stmt = conn.prepare(
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts 
                     WHERE superseded_by IS NULL AND (namespace = ?1 OR namespace LIKE ?2)
                     ORDER BY rowid DESC",
                )?;
                let prefix = format!("{}/%", ns);
                let rows = stmt.query_map(rusqlite::params![ns, &prefix], row_to_fact)?.collect::<Result<Vec<_>, _>>()?;
                rows
            } else {
                let mut stmt = conn.prepare(
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts WHERE superseded_by IS NULL
                     ORDER BY rowid DESC",
                )?;
                let rows = stmt.query_map([], row_to_fact)?.collect::<Result<Vec<_>, _>>()?;
                rows
            };
            Ok(facts)
        })?)
    }

    /// List all namespaces with their fact and episode counts.
    ///
    /// Returns `(namespace, fact_count, episode_count)` tuples.
    pub fn list_namespaces(&self) -> Result<Vec<NamespaceStats>, SemanticError> {
        Ok(self.db.with_conn(|conn| {
            let mut stmt = conn.prepare(
                "SELECT namespace, COUNT(*) as fact_count FROM semantic_facts
                 WHERE superseded_by IS NULL
                 GROUP BY namespace ORDER BY namespace",
            )?;
            let fact_ns: Vec<(String, i64)> = stmt
                .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
                .collect::<Result<Vec<_>, _>>()?;

            let mut stmt2 = conn.prepare(
                "SELECT namespace, COUNT(*) as ep_count FROM episodes
                 GROUP BY namespace ORDER BY namespace",
            )?;
            let ep_ns: Vec<(String, i64)> = stmt2
                .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
                .collect::<Result<Vec<_>, _>>()?;

            // Merge both lists by namespace
            let mut map: std::collections::HashMap<String, (i64, i64)> =
                std::collections::HashMap::new();
            for (ns, cnt) in &fact_ns {
                map.entry(ns.clone()).or_default().0 = *cnt;
            }
            for (ns, cnt) in &ep_ns {
                map.entry(ns.clone()).or_default().1 = *cnt;
            }

            let mut result: Vec<NamespaceStats> = map
                .into_iter()
                .map(|(namespace, (fact_count, episode_count))| NamespaceStats {
                    namespace,
                    fact_count,
                    episode_count,
                })
                .collect();
            result.sort_by(|a, b| a.namespace.cmp(&b.namespace));
            Ok(result)
        })?)
    }

    /// Delete a fact from both SQLite and RuVector.
    pub async fn delete_fact(&self, fact_id: &str) -> Result<(), SemanticError> {
        // Delete from SQLite
        self.db.with_conn(|conn| {
            conn.execute("DELETE FROM semantic_facts WHERE id = ?1", [fact_id])?;
            Ok(())
        })?;

        // Delete from RuVector
        self.ruv.delete("facts_vec", fact_id).await?;

        Ok(())
    }

    /// Find facts whose subject, predicate, or object contains the query string.
    ///
    /// Used by the Forget intent to find facts matching a target description.
    pub fn find_facts_matching(
        &self,
        query: &str,
        namespace: Option<&str>,
    ) -> Result<Vec<Fact>, SemanticError> {
        let pool = &self.db;
        let pattern = format!("%{query}%");
        Ok(self.db.with_conn(|conn| {
            let row_to_fact = |row: &rusqlite::Row<'_>| -> rusqlite::Result<Fact> {
                let raw_object: String = row.get(5)?;
                Ok(Fact {
                    id: row.get(0)?,
                    namespace: row.get(1)?,
                    category: row.get(2)?,
                    subject: row.get(3)?,
                    predicate: row.get(4)?,
                    object: pool.decrypt_content(&raw_object),
                    confidence: row.get(6)?,
                    source_episode_id: row.get(7)?,
                    agent: row.get(8)?,
                })
            };

            let facts: Vec<Fact> = if let Some(ns) = namespace {
                let mut stmt = conn.prepare(
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts
                     WHERE superseded_by IS NULL
                       AND (namespace = ?2 OR namespace LIKE ?3)
                       AND (subject LIKE ?1 OR predicate LIKE ?1 OR object LIKE ?1)
                     ORDER BY rowid DESC
                     LIMIT 50",
                )?;
                let prefix = format!("{}/%", ns);
                let rows = stmt.query_map(rusqlite::params![&pattern, ns, &prefix], row_to_fact)?;
                rows.collect::<Result<Vec<_>, _>>()?
            } else {
                let mut stmt = conn.prepare(
                    "SELECT id, namespace, category, subject, predicate, object, confidence, source_episode_id, agent
                     FROM semantic_facts
                     WHERE superseded_by IS NULL
                       AND (subject LIKE ?1 OR predicate LIKE ?1 OR object LIKE ?1)
                     ORDER BY rowid DESC
                     LIMIT 50",
                )?;
                let rows = stmt.query_map([&pattern], row_to_fact)?;
                rows.collect::<Result<Vec<_>, _>>()?
            };

            Ok(facts)
        })?)
    }

    /// Count total active facts.
    pub fn count(&self) -> Result<i64, SemanticError> {
        Ok(self.db.with_conn(|conn| {
            let count: i64 = conn.query_row(
                "SELECT COUNT(*) FROM semantic_facts WHERE superseded_by IS NULL",
                [],
                |row| row.get(0),
            )?;
            Ok(count)
        })?)
    }
}

/// Statistics for a single namespace.
#[derive(Debug, Clone)]
pub struct NamespaceStats {
    pub namespace: String,
    pub fact_count: i64,
    pub episode_count: i64,
}

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

    async fn test_store() -> (SemanticStore, tempfile::TempDir) {
        let db = SqlitePool::open_memory().unwrap();
        let ruv_dir = tempfile::tempdir().unwrap();
        let ruv = RuVectorStore::open(ruv_dir.path(), 384).await.unwrap();
        ruv.ensure_tables().await.unwrap();
        (SemanticStore::new(db, ruv), ruv_dir)
    }

    fn dummy_vector(val: f32) -> Vec<f32> {
        let mut v = vec![0.0; 384];
        let idx = (val * 100.0) as usize % 384;
        v[idx] = 1.0;
        v
    }

    #[tokio::test]
    async fn test_store_and_get_fact() {
        let (store, _dir) = test_store().await;

        let id = store
            .store_fact(
                "personal",
                "personal",
                "user",
                "name_is",
                "Keshav",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();

        let fact = store.get_fact(&id).unwrap().unwrap();
        assert_eq!(fact.namespace, "personal");
        assert_eq!(fact.subject, "user");
        assert_eq!(fact.predicate, "name_is");
        assert_eq!(fact.object, "Keshav");
        assert_eq!(fact.category, "personal");
    }

    #[tokio::test]
    async fn test_get_facts_by_category() {
        let (store, _dir) = test_store().await;

        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "name_is",
                "Keshav",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "likes",
                "Rust",
                0.9,
                None,
                dummy_vector(0.2),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "personal",
                "work",
                "user",
                "role_is",
                "developer",
                0.8,
                None,
                dummy_vector(0.3),
                None,
            )
            .await
            .unwrap();

        // Without namespace filter — returns all
        let personal = store.get_facts_by_category("personal", None).unwrap();
        assert_eq!(personal.len(), 2);

        let work = store.get_facts_by_category("work", None).unwrap();
        assert_eq!(work.len(), 1);

        // With namespace filter — scoped correctly
        let scoped = store
            .get_facts_by_category("personal", Some("personal"))
            .unwrap();
        assert_eq!(scoped.len(), 2);

        // Cross-namespace isolation: "work" category stored under "personal" namespace
        let cross = store.get_facts_by_category("work", Some("other")).unwrap();
        assert_eq!(cross.len(), 0);
    }

    #[tokio::test]
    async fn test_get_facts_about() {
        let (store, _dir) = test_store().await;

        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "name_is",
                "Keshav",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "likes",
                "Rust",
                0.9,
                None,
                dummy_vector(0.2),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "personal",
                "personal",
                "Alice",
                "knows",
                "user",
                0.5,
                None,
                dummy_vector(0.3),
                None,
            )
            .await
            .unwrap();

        let about_user = store.get_facts_about("user").unwrap();
        assert_eq!(about_user.len(), 2);
    }

    #[tokio::test]
    async fn test_fact_count() {
        let (store, _dir) = test_store().await;

        assert_eq!(store.count().unwrap(), 0);
        store
            .store_fact(
                "personal",
                "test",
                "a",
                "b",
                "c",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();
        assert_eq!(store.count().unwrap(), 1);
    }

    #[tokio::test]
    async fn test_vector_search() {
        let (store, _dir) = test_store().await;

        // Insert facts with different vectors
        let mut v1 = vec![0.0f32; 384];
        v1[0] = 1.0;
        let mut v2 = vec![0.0f32; 384];
        v2[1] = 1.0;

        store
            .store_fact(
                "personal",
                "test",
                "rust",
                "is",
                "fast",
                1.0,
                None,
                v1.clone(),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "personal", "test", "python", "is", "popular", 1.0, None, v2, None,
            )
            .await
            .unwrap();

        // Search with v1 — should find "rust is fast" first
        let results = store.search_similar(v1, 2, None, None).await.unwrap();
        assert!(!results.is_empty());
        assert_eq!(results[0].fact.subject, "rust");
    }

    #[tokio::test]
    async fn test_update_fact() {
        let (store, _dir) = test_store().await;

        let old_id = store
            .store_fact(
                "personal",
                "personal",
                "user",
                "location",
                "NYC",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();

        let new_id = store
            .update_fact(&old_id, "SF", dummy_vector(0.2))
            .await
            .unwrap();

        // New fact should have the updated value
        let new_fact = store.get_fact(&new_id).unwrap().unwrap();
        assert_eq!(new_fact.object, "SF");
        assert_eq!(new_fact.namespace, "personal"); // namespace preserved

        // Active count should still be 1 (old is superseded)
        assert_eq!(store.count().unwrap(), 1);
    }

    #[tokio::test]
    async fn test_namespace_isolation() {
        let (store, _dir) = test_store().await;

        // Store facts in different namespaces
        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "hobby",
                "coding",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "work",
                "work",
                "user",
                "role",
                "developer",
                1.0,
                None,
                dummy_vector(0.2),
                None,
            )
            .await
            .unwrap();

        // list_by_namespace filters correctly
        let personal = store.list_by_namespace(Some("personal")).unwrap();
        assert_eq!(personal.len(), 1);
        assert_eq!(personal[0].namespace, "personal");

        let work = store.list_by_namespace(Some("work")).unwrap();
        assert_eq!(work.len(), 1);
        assert_eq!(work[0].namespace, "work");

        // list_all returns both
        let all = store.list_all().unwrap();
        assert_eq!(all.len(), 2);
    }

    #[tokio::test]
    async fn test_list_namespaces() {
        let (store, _dir) = test_store().await;

        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "hobby",
                "coding",
                1.0,
                None,
                dummy_vector(0.1),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "personal",
                "personal",
                "user",
                "name",
                "Keshav",
                1.0,
                None,
                dummy_vector(0.2),
                None,
            )
            .await
            .unwrap();
        store
            .store_fact(
                "work",
                "work",
                "user",
                "role",
                "developer",
                1.0,
                None,
                dummy_vector(0.3),
                None,
            )
            .await
            .unwrap();

        let namespaces = store.list_namespaces().unwrap();
        assert_eq!(namespaces.len(), 2);

        let personal_ns = namespaces
            .iter()
            .find(|n| n.namespace == "personal")
            .unwrap();
        assert_eq!(personal_ns.fact_count, 2);

        let work_ns = namespaces.iter().find(|n| n.namespace == "work").unwrap();
        assert_eq!(work_ns.fact_count, 1);
    }
}