rmcp-memex 0.3.1

RAG/memory MCP server with LanceDB vector storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
//! High-level MemexEngine API for library consumers.
//!
//! The `MemexEngine` provides a simple, ergonomic interface for storing and
//! searching vector embeddings. It wraps the lower-level `StorageManager` and
//! `EmbeddingClient` to provide a unified API.
//!
//! # Example
//!
//! ```rust,ignore
//! use rmcp_memex::{MemexEngine, MemexConfig};
//! use serde_json::json;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     // Quick setup for an app
//!     let engine = MemexEngine::for_app("my-app", "documents").await?;
//!
//!     // Store a document
//!     engine.store("doc-1", "Hello world!", json!({"source": "test"})).await?;
//!
//!     // Search for similar documents
//!     let results = engine.search("greeting", 5).await?;
//!
//!     // Get by ID
//!     if let Some(doc) = engine.get("doc-1").await? {
//!         println!("Found: {}", doc.text);
//!     }
//!
//!     // Delete
//!     engine.delete("doc-1").await?;
//!
//!     Ok(())
//! }
//! ```

use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{debug, info};

use crate::embeddings::{EmbeddingClient, EmbeddingConfig};
use crate::rag::SearchResult;
use crate::search::{BM25Config, BM25Index};
use crate::storage::{ChromaDocument, StorageManager};

// Re-export SearchResult for convenience
pub use crate::rag::SearchResult as Document;

/// Configuration for MemexEngine.
///
/// Provides sensible defaults while allowing customization of all components.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemexConfig {
    /// Application name (used for default db_path)
    pub app_name: String,
    /// Namespace for document isolation
    pub namespace: String,
    /// Path to LanceDB storage (defaults to ~/.rmcp-servers/{app_name}/lancedb)
    #[serde(default)]
    pub db_path: Option<String>,
    /// Embedding vector dimension (must match your embedding model)
    #[serde(default = "default_dimension")]
    pub dimension: usize,
    /// Embedding provider configuration
    #[serde(default)]
    pub embedding_config: EmbeddingConfig,
    /// Enable BM25 keyword search (hybrid search)
    #[serde(default)]
    pub enable_bm25: bool,
    /// BM25 configuration (if enabled)
    #[serde(default)]
    pub bm25_config: Option<BM25Config>,
}

fn default_dimension() -> usize {
    4096 // qwen3-embedding default
}

impl Default for MemexConfig {
    fn default() -> Self {
        Self {
            app_name: "memex".to_string(),
            namespace: "default".to_string(),
            db_path: None,
            dimension: default_dimension(),
            embedding_config: EmbeddingConfig::default(),
            enable_bm25: false,
            bm25_config: None,
        }
    }
}

impl MemexConfig {
    /// Create a new config for an app with a namespace
    pub fn new(app_name: impl Into<String>, namespace: impl Into<String>) -> Self {
        Self {
            app_name: app_name.into(),
            namespace: namespace.into(),
            ..Default::default()
        }
    }

    /// Set custom database path
    pub fn with_db_path(mut self, path: impl Into<String>) -> Self {
        self.db_path = Some(path.into());
        self
    }

    /// Set embedding dimension
    pub fn with_dimension(mut self, dimension: usize) -> Self {
        self.dimension = dimension;
        self.embedding_config.required_dimension = dimension;
        self
    }

    /// Set embedding configuration
    pub fn with_embedding_config(mut self, config: EmbeddingConfig) -> Self {
        self.embedding_config = config;
        self
    }

    /// Enable BM25 hybrid search
    pub fn with_bm25(mut self, config: BM25Config) -> Self {
        self.enable_bm25 = true;
        self.bm25_config = Some(config);
        self
    }

    /// Get the effective database path
    pub fn effective_db_path(&self) -> String {
        self.db_path
            .clone()
            .unwrap_or_else(|| format!("~/.rmcp-servers/{}/lancedb", self.app_name))
    }

    /// Get the effective BM25 path
    pub fn effective_bm25_path(&self) -> String {
        self.bm25_config
            .as_ref()
            .map(|c| c.index_path.clone())
            .unwrap_or_else(|| format!("~/.rmcp-servers/{}/bm25", self.app_name))
    }
}

/// Metadata filter for search and deletion operations.
///
/// Used for filtering documents by metadata fields (e.g., patient_id, visit_id).
/// Supports GDPR-compliant data deletion by patient.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MetaFilter {
    /// Filter by patient ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub patient_id: Option<String>,
    /// Filter by visit ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visit_id: Option<String>,
    /// Filter by document type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub doc_type: Option<String>,
    /// Filter by date range (start)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date_from: Option<String>,
    /// Filter by date range (end)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date_to: Option<String>,
    /// Custom metadata key-value filters
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom: Vec<(String, String)>,
}

impl MetaFilter {
    /// Create a filter for a specific patient (GDPR deletion use case)
    pub fn for_patient(patient_id: impl Into<String>) -> Self {
        Self {
            patient_id: Some(patient_id.into()),
            ..Default::default()
        }
    }

    /// Create a filter for a specific visit
    pub fn for_visit(visit_id: impl Into<String>) -> Self {
        Self {
            visit_id: Some(visit_id.into()),
            ..Default::default()
        }
    }

    /// Add a custom metadata filter
    pub fn with_custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.custom.push((key.into(), value.into()));
        self
    }

    /// Check if this filter matches a document's metadata
    pub fn matches(&self, metadata: &Value) -> bool {
        if let Some(ref patient_id) = self.patient_id
            && metadata.get("patient_id").and_then(|v| v.as_str()) != Some(patient_id)
        {
            return false;
        }

        if let Some(ref visit_id) = self.visit_id
            && metadata.get("visit_id").and_then(|v| v.as_str()) != Some(visit_id)
        {
            return false;
        }

        if let Some(ref doc_type) = self.doc_type
            && metadata.get("doc_type").and_then(|v| v.as_str()) != Some(doc_type)
        {
            return false;
        }

        // Date range filtering
        if let Some(ref date_from) = self.date_from
            && let Some(doc_date) = metadata.get("date").and_then(|v| v.as_str())
            && doc_date < date_from.as_str()
        {
            return false;
        }

        if let Some(ref date_to) = self.date_to
            && let Some(doc_date) = metadata.get("date").and_then(|v| v.as_str())
            && doc_date > date_to.as_str()
        {
            return false;
        }

        // Custom filters
        for (key, value) in &self.custom {
            if metadata.get(key).and_then(|v| v.as_str()) != Some(value) {
                return false;
            }
        }

        true
    }
}

/// Item for batch storage operations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreItem {
    /// Unique document ID
    pub id: String,
    /// Text content to embed and store
    pub text: String,
    /// Optional metadata
    #[serde(default)]
    pub metadata: Value,
}

impl StoreItem {
    /// Create a new store item
    pub fn new(id: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            text: text.into(),
            metadata: Value::Object(serde_json::Map::new()),
        }
    }

    /// Add metadata to this item
    pub fn with_metadata(mut self, metadata: Value) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Result of a batch operation
#[derive(Debug, Clone)]
pub struct BatchResult {
    /// Number of items successfully processed
    pub success_count: usize,
    /// Number of items that failed
    pub failure_count: usize,
    /// IDs of failed items (if any)
    pub failed_ids: Vec<String>,
}

/// High-level API for vector memory operations.
///
/// MemexEngine provides a simple interface for storing, searching, and managing
/// vector embeddings. It orchestrates the embedding client and storage manager.
pub struct MemexEngine {
    storage: Arc<StorageManager>,
    embeddings: Arc<Mutex<EmbeddingClient>>,
    bm25: Option<BM25Index>,
    namespace: String,
    config: MemexConfig,
}

impl MemexEngine {
    /// Create a new MemexEngine with the given configuration.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = MemexConfig::new("my-app", "documents")
    ///     .with_dimension(1024);
    /// let engine = MemexEngine::new(config).await?;
    /// ```
    pub async fn new(config: MemexConfig) -> Result<Self> {
        let db_path = config.effective_db_path();

        info!(
            "Initializing MemexEngine: app={}, namespace={}, db={}",
            config.app_name, config.namespace, db_path
        );

        // Initialize storage
        let storage = StorageManager::new_lance_only(&db_path).await?;
        storage.ensure_collection().await?;

        // Initialize embedding client
        let embeddings = EmbeddingClient::new(&config.embedding_config).await?;

        info!(
            "Connected to embedding provider: {} (dim={})",
            embeddings.connected_to(),
            embeddings.required_dimension()
        );

        // Validate dimension matches config
        if embeddings.required_dimension() != config.dimension {
            return Err(anyhow!(
                "Embedding dimension mismatch! Config: {}, Provider: {}. \
                 Update config.dimension to match your embedding model.",
                config.dimension,
                embeddings.required_dimension()
            ));
        }

        // Initialize BM25 if enabled
        let bm25 = if config.enable_bm25 {
            let bm25_config = config
                .bm25_config
                .clone()
                .unwrap_or_else(|| BM25Config::default().with_path(config.effective_bm25_path()));
            Some(BM25Index::new(&bm25_config)?)
        } else {
            None
        };

        Ok(Self {
            storage: Arc::new(storage),
            embeddings: Arc::new(Mutex::new(embeddings)),
            bm25,
            namespace: config.namespace.clone(),
            config,
        })
    }

    /// Quick setup for an application.
    ///
    /// Uses default embedding configuration and auto-detects providers.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let engine = MemexEngine::for_app("vista", "patient-notes").await?;
    /// ```
    pub async fn for_app(app_name: &str, namespace: &str) -> Result<Self> {
        let config = MemexConfig::new(app_name, namespace);
        Self::new(config).await
    }

    /// Vista-optimized setup with 1024-dimension embeddings.
    ///
    /// Uses smaller embedding model (qwen3-embedding:0.6b) for faster inference.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let engine = MemexEngine::for_vista().await?;
    /// ```
    pub async fn for_vista() -> Result<Self> {
        use crate::embeddings::ProviderConfig;

        let config = MemexConfig {
            app_name: "vista".to_string(),
            namespace: "default".to_string(),
            db_path: Some("~/.rmcp-servers/vista/lancedb".to_string()),
            dimension: 1024,
            embedding_config: EmbeddingConfig {
                required_dimension: 1024,
                providers: vec![ProviderConfig {
                    name: "ollama-vista".to_string(),
                    base_url: "http://localhost:11434".to_string(),
                    model: "qwen3-embedding:0.6b".to_string(),
                    priority: 1,
                    endpoint: "/v1/embeddings".to_string(),
                }],
                ..EmbeddingConfig::default()
            },
            enable_bm25: false,
            bm25_config: None,
        };
        Self::new(config).await
    }

    /// Get the namespace this engine operates on
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Get the configuration
    pub fn config(&self) -> &MemexConfig {
        &self.config
    }

    /// Get the underlying storage manager (for advanced operations)
    pub fn storage(&self) -> Arc<StorageManager> {
        self.storage.clone()
    }

    // =========================================================================
    // CORE CRUD OPERATIONS
    // =========================================================================

    /// Store a document with embedding.
    ///
    /// The text is automatically embedded using the configured embedding provider.
    ///
    /// # Arguments
    /// * `id` - Unique document identifier
    /// * `text` - Text content to embed and store
    /// * `metadata` - Additional metadata (JSON object)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// engine.store(
    ///     "visit-123",
    ///     "Patient presented with lethargy and decreased appetite...",
    ///     json!({"patient_id": "P-456", "visit_type": "checkup"})
    /// ).await?;
    /// ```
    pub async fn store(&self, id: &str, text: &str, metadata: Value) -> Result<()> {
        debug!("Storing document: id={}, text_len={}", id, text.len());

        // Generate embedding
        let embedding = self.embeddings.lock().await.embed(text).await?;

        // Create document
        let doc = ChromaDocument::new_flat(
            id.to_string(),
            self.namespace.clone(),
            embedding,
            metadata.clone(),
            text.to_string(),
        );

        // Store in vector DB
        self.storage.add_to_store(vec![doc]).await?;

        // Also index in BM25 if enabled
        if let Some(ref bm25) = self.bm25 {
            bm25.add_documents(&[(id.to_string(), self.namespace.clone(), text.to_string())])
                .await?;
        }

        debug!("Stored document: id={}", id);
        Ok(())
    }

    /// Search for similar documents.
    ///
    /// Returns documents ordered by similarity score (highest first).
    ///
    /// # Arguments
    /// * `query` - Search query text
    /// * `limit` - Maximum number of results
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let results = engine.search("lethargy symptoms", 10).await?;
    /// for result in results {
    ///     println!("{}: {} (score: {})", result.id, result.text, result.score);
    /// }
    /// ```
    pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchResult>> {
        debug!("Searching: query='{}', limit={}", query, limit);

        // Generate query embedding
        let query_embedding = self.embeddings.lock().await.embed(query).await?;

        // Search vector store
        let candidates = self
            .storage
            .search_store(Some(&self.namespace), query_embedding, limit)
            .await?;

        // Convert to SearchResult
        let results: Vec<SearchResult> = candidates
            .into_iter()
            .enumerate()
            .map(|(idx, doc)| {
                // Simple inverse-index scoring (better results have lower index)
                let score = 1.0 - (idx as f32 / (limit as f32 + 1.0));
                let layer = doc.slice_layer();
                SearchResult {
                    id: doc.id,
                    namespace: doc.namespace,
                    text: doc.document,
                    score,
                    metadata: doc.metadata,
                    layer,
                    parent_id: doc.parent_id,
                    children_ids: doc.children_ids,
                    keywords: doc.keywords,
                }
            })
            .collect();

        debug!("Search returned {} results", results.len());
        Ok(results)
    }

    /// Get a document by ID.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if let Some(doc) = engine.get("visit-123").await? {
    ///     println!("Found: {}", doc.text);
    /// }
    /// ```
    pub async fn get(&self, id: &str) -> Result<Option<SearchResult>> {
        debug!("Getting document: id={}", id);

        if let Some(doc) = self.storage.get_document(&self.namespace, id).await? {
            let layer = doc.slice_layer();
            return Ok(Some(SearchResult {
                id: doc.id,
                namespace: doc.namespace,
                text: doc.document,
                score: 1.0,
                metadata: doc.metadata,
                layer,
                parent_id: doc.parent_id,
                children_ids: doc.children_ids,
                keywords: doc.keywords,
            }));
        }

        Ok(None)
    }

    /// Delete a document by ID.
    ///
    /// Returns true if a document was deleted, false if not found.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if engine.delete("visit-123").await? {
    ///     println!("Document deleted");
    /// }
    /// ```
    pub async fn delete(&self, id: &str) -> Result<bool> {
        debug!("Deleting document: id={}", id);

        let deleted = self.storage.delete_document(&self.namespace, id).await?;

        // Also delete from BM25 if enabled
        if let Some(ref bm25) = self.bm25 {
            bm25.delete_documents(&[id.to_string()]).await?;
        }

        Ok(deleted > 0)
    }

    // =========================================================================
    // BATCH OPERATIONS
    // =========================================================================

    /// Store multiple documents in a batch.
    ///
    /// More efficient than calling `store()` multiple times as embeddings
    /// are generated in batches.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let items = vec![
    ///     StoreItem::new("doc-1", "First document").with_metadata(json!({"type": "note"})),
    ///     StoreItem::new("doc-2", "Second document").with_metadata(json!({"type": "note"})),
    /// ];
    /// let result = engine.store_batch(items).await?;
    /// println!("Stored {} documents", result.success_count);
    /// ```
    pub async fn store_batch(&self, items: Vec<StoreItem>) -> Result<BatchResult> {
        if items.is_empty() {
            return Ok(BatchResult {
                success_count: 0,
                failure_count: 0,
                failed_ids: vec![],
            });
        }

        info!("Batch storing {} documents", items.len());

        // Extract texts for batch embedding
        let texts: Vec<String> = items.iter().map(|i| i.text.clone()).collect();

        // Generate embeddings in batch
        let embeddings = self.embeddings.lock().await.embed_batch(&texts).await?;

        // Create documents
        let mut docs = Vec::with_capacity(items.len());
        let mut bm25_docs = Vec::new();

        for (item, embedding) in items.iter().zip(embeddings.into_iter()) {
            let doc = ChromaDocument::new_flat(
                item.id.clone(),
                self.namespace.clone(),
                embedding,
                item.metadata.clone(),
                item.text.clone(),
            );
            docs.push(doc);

            if self.bm25.is_some() {
                bm25_docs.push((item.id.clone(), self.namespace.clone(), item.text.clone()));
            }
        }

        // Store in vector DB
        self.storage.add_to_store(docs).await?;

        // Also index in BM25 if enabled
        if let Some(ref bm25) = self.bm25 {
            bm25.add_documents(&bm25_docs).await?;
        }

        Ok(BatchResult {
            success_count: items.len(),
            failure_count: 0,
            failed_ids: vec![],
        })
    }

    // =========================================================================
    // FILTERED OPERATIONS
    // =========================================================================

    /// Search with metadata filter.
    ///
    /// Performs vector search and then filters results by metadata.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let filter = MetaFilter::for_patient("P-456");
    /// let results = engine.search_filtered("symptoms", filter, 10).await?;
    /// ```
    pub async fn search_filtered(
        &self,
        query: &str,
        filter: MetaFilter,
        limit: usize,
    ) -> Result<Vec<SearchResult>> {
        // Fetch more candidates than needed, then filter
        let candidates = self.search(query, limit * 3).await?;

        // Apply metadata filter
        let filtered: Vec<SearchResult> = candidates
            .into_iter()
            .filter(|r| filter.matches(&r.metadata))
            .take(limit)
            .collect();

        debug!(
            "Filtered search: query='{}', filter={:?}, results={}",
            query,
            filter,
            filtered.len()
        );

        Ok(filtered)
    }

    /// Delete all documents matching a filter.
    ///
    /// This is the primary method for GDPR-compliant data deletion.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Delete all documents for a patient (GDPR request)
    /// let filter = MetaFilter::for_patient("P-456");
    /// let deleted = engine.delete_by_filter(filter).await?;
    /// println!("Deleted {} documents", deleted);
    /// ```
    pub async fn delete_by_filter(&self, filter: MetaFilter) -> Result<usize> {
        info!("Deleting documents by filter: {:?}", filter);

        // We need to search for all matching documents first
        // This is expensive but necessary for metadata-based filtering
        // Note: A more efficient implementation would add filter support to StorageManager

        // For now, we'll search with a broad query and filter
        // TODO: Add native metadata filtering to LanceDB queries

        let mut deleted_count = 0;
        let mut deleted_ids = Vec::new();

        // Search with empty query to get all documents (expensive!)
        // We use a high limit and paginate if needed
        const BATCH_SIZE: usize = 1000;

        // Generate a dummy embedding for the search
        // (we'll rely on metadata filtering, not vector similarity)
        let dummy_embedding = vec![0.0f32; self.config.dimension];

        let candidates = self
            .storage
            .search_store(Some(&self.namespace), dummy_embedding, BATCH_SIZE)
            .await?;

        for doc in candidates {
            if filter.matches(&doc.metadata) {
                self.storage
                    .delete_document(&self.namespace, &doc.id)
                    .await?;
                deleted_ids.push(doc.id);
                deleted_count += 1;
            }
        }

        // Delete from BM25 if enabled
        if let Some(ref bm25) = self.bm25
            && !deleted_ids.is_empty()
        {
            bm25.delete_documents(&deleted_ids).await?;
        }

        info!("Deleted {} documents by filter", deleted_count);
        Ok(deleted_count)
    }

    /// Delete all documents in the namespace.
    ///
    /// Use with caution - this removes all data!
    pub async fn purge_namespace(&self) -> Result<usize> {
        info!("Purging namespace: {}", self.namespace);

        let deleted = self.storage.purge_namespace(&self.namespace).await?;

        if let Some(ref bm25) = self.bm25 {
            bm25.purge_namespace(&self.namespace).await?;
        }

        Ok(deleted)
    }

    // =========================================================================
    // HYBRID SEARCH (BM25 + Vector)
    // =========================================================================

    /// Hybrid search combining BM25 keyword matching with vector similarity.
    ///
    /// Requires `enable_bm25: true` in config.
    ///
    /// # Arguments
    /// * `query` - Search query
    /// * `limit` - Maximum results
    /// * `bm25_weight` - Weight for BM25 scores (0.0-1.0, default 0.3)
    pub async fn search_hybrid(
        &self,
        query: &str,
        limit: usize,
        bm25_weight: f32,
    ) -> Result<Vec<SearchResult>> {
        let bm25 = self
            .bm25
            .as_ref()
            .ok_or_else(|| anyhow!("BM25 not enabled. Set enable_bm25: true in MemexConfig."))?;

        // Get BM25 results
        let bm25_results = bm25.search(query, Some(&self.namespace), limit * 2)?;
        let bm25_max_score = bm25_results.first().map(|(_, s)| *s).unwrap_or(1.0);

        // Get vector results
        let vector_results = self.search(query, limit * 2).await?;

        // Merge and re-score
        use std::collections::HashMap;
        let mut scores: HashMap<String, (f32, Option<SearchResult>)> = HashMap::new();

        // Add BM25 scores (normalized)
        for (id, score) in bm25_results {
            let normalized = score / bm25_max_score.max(0.001);
            scores.insert(id, (normalized * bm25_weight, None));
        }

        // Add vector scores
        let vector_weight = 1.0 - bm25_weight;
        for result in vector_results {
            let entry = scores.entry(result.id.clone()).or_insert((0.0, None));
            entry.0 += result.score * vector_weight;
            entry.1 = Some(result);
        }

        // Collect and sort by combined score
        let mut combined: Vec<_> = scores
            .into_iter()
            .filter_map(|(_id, (score, result))| {
                // If we have the full result, use it; otherwise fetch from storage
                result.map(|mut r| {
                    r.score = score;
                    r
                })
            })
            .collect();

        combined.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        combined.truncate(limit);

        Ok(combined)
    }
}

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

    #[test]
    fn test_meta_filter_matches() {
        let filter = MetaFilter::for_patient("P-123");

        let matching = serde_json::json!({
            "patient_id": "P-123",
            "visit_id": "V-456"
        });
        assert!(filter.matches(&matching));

        let not_matching = serde_json::json!({
            "patient_id": "P-999",
            "visit_id": "V-456"
        });
        assert!(!filter.matches(&not_matching));
    }

    #[test]
    fn test_meta_filter_custom() {
        let filter = MetaFilter::default()
            .with_custom("doc_type", "soap_note")
            .with_custom("status", "active");

        let matching = serde_json::json!({
            "doc_type": "soap_note",
            "status": "active"
        });
        assert!(filter.matches(&matching));

        let missing_field = serde_json::json!({
            "doc_type": "soap_note"
        });
        assert!(!filter.matches(&missing_field));
    }

    #[test]
    fn test_memex_config_defaults() {
        let config = MemexConfig::default();
        assert_eq!(config.dimension, 4096);
        assert_eq!(config.namespace, "default");
        assert_eq!(config.effective_db_path(), "~/.rmcp-servers/memex/lancedb");
    }

    #[test]
    fn test_memex_config_builder() {
        let config = MemexConfig::new("vista", "patients")
            .with_dimension(1024)
            .with_db_path("/custom/path/db");

        assert_eq!(config.app_name, "vista");
        assert_eq!(config.namespace, "patients");
        assert_eq!(config.dimension, 1024);
        assert_eq!(config.effective_db_path(), "/custom/path/db");
    }

    #[test]
    fn test_store_item() {
        let item = StoreItem::new("doc-1", "Hello world")
            .with_metadata(serde_json::json!({"type": "greeting"}));

        assert_eq!(item.id, "doc-1");
        assert_eq!(item.text, "Hello world");
        assert_eq!(item.metadata["type"], "greeting");
    }

    #[test]
    fn test_store_item_default_metadata() {
        let item = StoreItem::new("doc-1", "Hello world");

        assert_eq!(item.id, "doc-1");
        assert_eq!(item.text, "Hello world");
        assert!(item.metadata.is_object());
        assert!(item.metadata.as_object().unwrap().is_empty());
    }

    #[test]
    fn test_meta_filter_empty_matches_all() {
        let filter = MetaFilter::default();

        // Empty filter should match any metadata
        let any_metadata = serde_json::json!({
            "patient_id": "P-123",
            "visit_id": "V-456",
            "random_field": "value"
        });
        assert!(filter.matches(&any_metadata));

        // Even empty metadata should match
        let empty = serde_json::json!({});
        assert!(filter.matches(&empty));
    }

    #[test]
    fn test_meta_filter_date_range() {
        let filter = MetaFilter {
            date_from: Some("2024-01-01".to_string()),
            date_to: Some("2024-12-31".to_string()),
            ..Default::default()
        };

        // Within range
        let in_range = serde_json::json!({
            "date": "2024-06-15"
        });
        assert!(filter.matches(&in_range));

        // Before range
        let before = serde_json::json!({
            "date": "2023-12-31"
        });
        assert!(!filter.matches(&before));

        // After range
        let after = serde_json::json!({
            "date": "2025-01-01"
        });
        assert!(!filter.matches(&after));

        // No date field still matches (filter only applies if field exists)
        let no_date = serde_json::json!({
            "patient_id": "P-123"
        });
        assert!(filter.matches(&no_date));
    }

    #[test]
    fn test_meta_filter_for_visit() {
        let filter = MetaFilter::for_visit("V-789");

        let matching = serde_json::json!({
            "visit_id": "V-789",
            "patient_id": "P-123"
        });
        assert!(filter.matches(&matching));

        let not_matching = serde_json::json!({
            "visit_id": "V-other",
            "patient_id": "P-123"
        });
        assert!(!filter.matches(&not_matching));
    }

    #[test]
    fn test_meta_filter_combined() {
        let filter = MetaFilter {
            patient_id: Some("P-123".to_string()),
            doc_type: Some("soap_note".to_string()),
            ..Default::default()
        };

        // Both match
        let both_match = serde_json::json!({
            "patient_id": "P-123",
            "doc_type": "soap_note"
        });
        assert!(filter.matches(&both_match));

        // One doesn't match
        let wrong_type = serde_json::json!({
            "patient_id": "P-123",
            "doc_type": "prescription"
        });
        assert!(!filter.matches(&wrong_type));

        // Missing required field
        let missing = serde_json::json!({
            "patient_id": "P-123"
        });
        assert!(!filter.matches(&missing));
    }

    #[test]
    fn test_batch_result_struct() {
        let result = BatchResult {
            success_count: 10,
            failure_count: 2,
            failed_ids: vec!["doc-5".to_string(), "doc-8".to_string()],
        };

        assert_eq!(result.success_count, 10);
        assert_eq!(result.failure_count, 2);
        assert_eq!(result.failed_ids.len(), 2);
        assert!(result.failed_ids.contains(&"doc-5".to_string()));
    }

    #[test]
    fn test_memex_config_with_bm25() {
        use crate::search::BM25Config;

        let bm25_config = BM25Config::default();
        let config = MemexConfig::new("test-app", "docs").with_bm25(bm25_config);

        assert!(config.enable_bm25);
        assert!(config.bm25_config.is_some());
    }

    #[test]
    fn test_memex_config_effective_bm25_path() {
        let config = MemexConfig::new("my-app", "docs");
        assert_eq!(config.effective_bm25_path(), "~/.rmcp-servers/my-app/bm25");
    }

    #[test]
    fn test_meta_filter_serialization() {
        let filter = MetaFilter::for_patient("P-123").with_custom("status", "active");

        let json = serde_json::to_string(&filter).unwrap();
        let deserialized: MetaFilter = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.patient_id, Some("P-123".to_string()));
        assert_eq!(deserialized.custom.len(), 1);
        assert_eq!(
            deserialized.custom[0],
            ("status".to_string(), "active".to_string())
        );
    }

    #[test]
    fn test_memex_config_serialization() {
        let config = MemexConfig::new("test", "ns")
            .with_dimension(512)
            .with_db_path("/tmp/test");

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: MemexConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.app_name, "test");
        assert_eq!(deserialized.namespace, "ns");
        assert_eq!(deserialized.dimension, 512);
        assert_eq!(deserialized.db_path, Some("/tmp/test".to_string()));
    }

    #[test]
    fn test_store_item_serialization() {
        let item =
            StoreItem::new("id-1", "content").with_metadata(serde_json::json!({"key": "value"}));

        let json = serde_json::to_string(&item).unwrap();
        let deserialized: StoreItem = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.id, "id-1");
        assert_eq!(deserialized.text, "content");
        assert_eq!(deserialized.metadata["key"], "value");
    }
}