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
//! # ReasonKit Memory Infrastructure
//!
//! `reasonkit-mem` provides long-term memory, retrieval, and hybrid search infrastructure
//! for the ReasonKit ecosystem. This crate serves as the "Hippocampus" - the memory and
//! retrieval backbone for AI reasoning systems.
//!
//! ## Overview
//!
//! This crate implements a production-grade memory system combining:
//! - **Vector storage** with Qdrant for semantic search
//! - **BM25 indexing** with Tantivy for keyword matching
//! - **Hybrid retrieval** combining dense and sparse methods
//! - **RAPTOR trees** for hierarchical document understanding
//! - **Dual-layer memory** with hot/cold storage tiers
//!
//! ## Architecture
//!
//! ```text
//! reasonkit-mem/
//! +-- storage/ # Qdrant vector + dual-layer memory
//! +-- embedding/ # Dense vector embeddings (BGE-M3, OpenAI)
//! +-- retrieval/ # Hybrid search, fusion, reranking
//! +-- raptor/ # RAPTOR hierarchical tree structure
//! +-- indexing/ # BM25/Tantivy sparse indexing
//! +-- rag/ # RAG pipeline orchestration
//! +-- service/ # MemoryService trait implementation for reasonkit-core
//! ```
//!
//! ## Quick Start
//!
//! ### Basic Document Indexing and Search
//!
//! ```rust,ignore
//! use reasonkit_mem::{
//! retrieval::{KnowledgeBase, HybridResult},
//! Document, DocumentType, Source, SourceType,
//! };
//! use chrono::Utc;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create an in-memory knowledge base
//! let kb = KnowledgeBase::in_memory()?;
//!
//! // Create a document
//! let source = Source {
//! source_type: SourceType::Local,
//! url: None,
//! path: Some("/docs/example.md".to_string()),
//! arxiv_id: None,
//! github_repo: None,
//! retrieved_at: Utc::now(),
//! version: None,
//! };
//!
//! let doc = Document::new(DocumentType::Documentation, source)
//! .with_content("Machine learning enables computers to learn from data.".into());
//!
//! // Add to knowledge base
//! kb.add(&doc).await?;
//!
//! // Search using BM25 (no embeddings required)
//! let results = kb.retriever().search_sparse("machine learning", 10).await?;
//!
//! for result in results {
//! println!("Score: {:.3}, Text: {}", result.score, result.text);
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### Using the MemoryService Trait
//!
//! The `service` module provides a standardized interface for integration with
//! `reasonkit-core`. This enables loose coupling between crates.
//!
//! ```rust,ignore
//! use reasonkit_mem::service::{MemServiceImpl, MemoryService, Document};
//! use std::collections::HashMap;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create in-memory service
//! let service = MemServiceImpl::in_memory()?;
//!
//! // Store a document
//! let doc = Document {
//! id: None,
//! content: "Machine learning is a subset of AI.".to_string(),
//! metadata: HashMap::new(),
//! source: Some("/path/to/doc.md".to_string()),
//! created_at: None,
//! };
//!
//! let id = service.store_document(&doc).await?;
//! println!("Stored document with ID: {}", id);
//!
//! // Get statistics
//! let stats = service.get_stats().await?;
//! println!("Total documents: {}", stats.total_documents);
//!
//! Ok(())
//! }
//! ```
//!
//! ### Hybrid Search with Embeddings
//!
//! ```rust,ignore
//! use reasonkit_mem::{
//! embedding::{EmbeddingPipeline, OpenAIEmbedding, EmbeddingConfig},
//! retrieval::HybridRetriever,
//! RetrievalConfig,
//! };
//! use std::sync::Arc;
//!
//! // Create embedding pipeline
//! let config = EmbeddingConfig::default();
//! let provider = Arc::new(OpenAIEmbedding::new(config)?);
//! let pipeline = Arc::new(EmbeddingPipeline::new(provider));
//!
//! // Create hybrid retriever with embeddings
//! let retriever = HybridRetriever::in_memory()?
//! .with_embedding_pipeline(pipeline);
//!
//! // Search combines vector + BM25 results
//! let results = retriever.search("semantic search query", 10).await?;
//! ```
//!
//! ### Dual-Layer Memory System
//!
//! ```rust,ignore
//! use reasonkit_mem::storage::{DualLayerMemory, DualLayerConfig, MemoryEntry};
//!
//! // Create dual-layer memory with hot/cold tiers
//! let config = DualLayerConfig::default();
//! let memory = DualLayerMemory::new(config).await?;
//!
//! // Store a memory entry (goes to hot layer first)
//! let entry = MemoryEntry::new("Important context to remember")
//! .with_importance(0.9)
//! .with_metadata("source", "user_input");
//!
//! let id = memory.store(entry).await?;
//!
//! // Retrieve context for a query
//! let results = memory.retrieve_context("context query", 10).await?;
//!
//! // Graceful shutdown
//! memory.shutdown().await?;
//! ```
//!
//! ## Features
//!
//! - **Hybrid Search**: Dense (Qdrant) + Sparse (Tantivy BM25) fusion with RRF
//! - **RAPTOR Trees**: Hierarchical retrieval for long-form QA (Sarthi et al. 2024)
//! - **Cross-Encoder Reranking**: Precision boosting for final results
//! - **Embedded Mode**: Zero-config development with Qdrant embedded
//! - **Dual-Layer Memory**: Hot/cold storage with automatic migration
//! - **Write-Ahead Log**: Durability and crash recovery
//!
//! ## Cargo Features
//!
//! - `default`: Core functionality
//! - `local-embeddings`: Enable local ONNX-based embeddings (BGE-M3, E5)
//! - `python`: Python bindings via PyO3
//!
//! ## Research Foundation
//!
//! This crate implements techniques from:
//! - **RAPTOR**: Sarthi et al. 2024 - "Recursive Abstractive Processing for Tree-Organized Retrieval"
//! - **RRF Fusion**: Cormack et al. 2009 - "Reciprocal Rank Fusion"
//! - **Cross-Encoders**: Nogueira et al. 2020 - arXiv:2010.06467
// Re-export commonly used types
pub use ;
pub use *;
/// Crate version string.
///
/// Matches the version in Cargo.toml. Used for runtime logging and API responses.
///
/// # Example
///
/// ```rust
/// println!("ReasonKit Memory v{}", reasonkit_mem::VERSION);
/// ```
pub const VERSION: &str = env!;
/// Error types for memory operations.
///
/// This module provides a unified error type [`MemError`] for all memory operations,
/// including storage, embedding, retrieval, and indexing errors.
///
/// # Example
///
/// ```rust
/// use reasonkit_mem::error::{MemError, MemResult};
///
/// fn process_document() -> MemResult<()> {
/// // Operations that might fail
/// Err(MemError::storage("Connection failed"))
/// }
/// ```
/// Core types shared across all modules.
///
/// This module defines the fundamental data structures used throughout the crate:
/// - [`Document`]: A document in the knowledge base
/// - [`Chunk`]: A text chunk from a document
/// - [`Source`]: Source information for a document
/// - [`Metadata`]: Document metadata (title, authors, etc.)
/// - [`RetrievalConfig`]: Configuration for retrieval operations
/// - [`SearchResult`]: Result from a search query
///
/// # Example
///
/// ```rust
/// use reasonkit_mem::{Document, DocumentType, Source, SourceType};
/// use chrono::Utc;
///
/// let source = Source {
/// source_type: SourceType::Local,
/// url: None,
/// path: Some("/path/to/file.md".to_string()),
/// arxiv_id: None,
/// github_repo: None,
/// retrieved_at: Utc::now(),
/// version: None,
/// };
///
/// let doc = Document::new(DocumentType::Note, source)
/// .with_content("Document content here".to_string());
/// ```
/// Alias for backward compatibility with [`MemError`].
pub type Error = MemError;
/// Result type alias using [`MemError`].
pub type Result<T> = ;
/// Vector and file-based storage backends.
///
/// This module provides storage functionality including:
/// - **Qdrant Integration**: Vector storage for semantic search
/// - **Dual-Layer Memory**: Hot/cold tier storage with automatic migration
/// - **Write-Ahead Log**: Durability and crash recovery
///
/// # Dual-Layer Architecture
///
/// ```text
/// +-------------------+
/// | DualLayerMemory | Unified interface
/// +-------------------+
/// |
/// +-----+-----+
/// | |
/// +------+ +------+
/// | Hot | | Cold | Hot = recent/active, Cold = historical
/// +------+ +------+
/// | |
/// +-----+-----+
/// |
/// +----------+
/// | WAL | Write-ahead log for durability
/// +----------+
/// ```
///
/// # Key Types
///
/// - [`storage::Storage`]: Main storage interface for documents
/// - [`storage::DualLayerMemory`]: Dual-layer memory with hot/cold tiers
/// - [`storage::MemoryEntry`]: A memory entry for storage
/// - [`storage::DualLayerConfig`]: Configuration for dual-layer storage
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::storage::{DualLayerMemory, DualLayerConfig, MemoryEntry};
///
/// let config = DualLayerConfig::default();
/// let memory = DualLayerMemory::new(config).await?;
///
/// let entry = MemoryEntry::new("Context to remember")
/// .with_importance(0.8);
///
/// let id = memory.store(entry).await?;
/// ```
/// Dense vector embedding services.
///
/// This module provides text embedding functionality for semantic search:
/// - **API-based**: OpenAI, Anthropic, Cohere, local servers
/// - **Local ONNX**: BGE-M3, E5 (requires `local-embeddings` feature)
/// - **Caching**: Built-in embedding cache to reduce API calls
///
/// # Key Types
///
/// - [`embedding::EmbeddingPipeline`]: Pipeline for batch embedding operations
/// - [`embedding::OpenAIEmbedding`]: OpenAI-compatible embedding provider
/// - [`embedding::EmbeddingConfig`]: Configuration for embedding providers
/// - [`embedding::EmbeddingCache`]: LRU cache for embeddings
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::embedding::{
/// EmbeddingPipeline, OpenAIEmbedding, EmbeddingConfig, EmbeddingProvider
/// };
/// use std::sync::Arc;
///
/// // Create OpenAI embedding provider
/// let config = EmbeddingConfig::default();
/// let provider = Arc::new(OpenAIEmbedding::new(config)?);
/// let pipeline = EmbeddingPipeline::new(provider);
///
/// // Embed text
/// let embedding = pipeline.embed_text("Hello, world!").await?;
/// println!("Embedding dimension: {}", embedding.len());
/// ```
///
/// # Utility Functions
///
/// - [`embedding::normalize_vector`]: Normalize a vector to unit length
/// - [`embedding::cosine_similarity`]: Compute cosine similarity between vectors
/// Hybrid retrieval with fusion and reranking.
///
/// This module implements state-of-the-art retrieval techniques:
/// - **Hybrid Search**: Combines BM25 (sparse) and vector (dense) retrieval
/// - **RRF Fusion**: Reciprocal Rank Fusion for combining result sets
/// - **Cross-Encoder Reranking**: Precision improvement using cross-encoders
/// - **Query Expansion**: Better recall through query augmentation
///
/// # Key Types
///
/// - [`retrieval::HybridRetriever`]: Main hybrid search interface
/// - [`retrieval::KnowledgeBase`]: High-level knowledge base wrapper
/// - [`retrieval::FusionEngine`]: Combines results from multiple methods
/// - [`retrieval::Reranker`]: Cross-encoder reranking for precision
///
/// # Research Foundation
///
/// - **RRF Fusion**: Cormack et al. 2009 - "Reciprocal Rank Fusion"
/// - **Cross-Encoder**: Nogueira et al. 2020 - arXiv:2010.06467
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::retrieval::{HybridRetriever, KnowledgeBase};
///
/// // Create in-memory knowledge base
/// let kb = KnowledgeBase::in_memory()?;
///
/// // Add documents
/// kb.add(&document).await?;
///
/// // Query with hybrid search
/// let results = kb.query("search query", 10).await?;
///
/// for result in results {
/// println!("Score: {:.3}, Source: {:?}", result.score, result.match_source);
/// }
/// ```
/// RAPTOR hierarchical tree structure.
///
/// Implements the RAPTOR (Recursive Abstractive Processing for Tree-Organized
/// Retrieval) algorithm for hierarchical document understanding and retrieval.
///
/// # Overview
///
/// RAPTOR builds a tree structure where:
/// - **Leaf nodes**: Original document chunks with embeddings
/// - **Internal nodes**: Summaries of child node clusters
/// - **Root nodes**: High-level summaries of the entire document
///
/// This enables retrieval at multiple levels of abstraction.
///
/// # Key Types
///
/// - [`raptor::RaptorTree`]: Main RAPTOR tree structure
/// - [`raptor::RaptorNode`]: A node in the RAPTOR tree
/// - [`raptor::RaptorStats`]: Statistics about the tree
/// - [`raptor::OptimizedRaptorTree`]: Performance-optimized implementation
/// - [`raptor::CodeGraph`]: Code entity graph for code understanding
///
/// # Research Foundation
///
/// Based on: Sarthi et al. 2024 - "RAPTOR: Recursive Abstractive Processing
/// for Tree-Organized Retrieval"
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::raptor::RaptorTree;
///
/// let mut tree = RaptorTree::new(
/// 3, // max_depth
/// 4, // cluster_size
/// );
///
/// // Build tree from chunks
/// tree.build_from_chunks(&chunks, &embedder, &summarizer).await?;
///
/// // Search the tree
/// let results = tree.search(&query_embedding, 10)?;
///
/// let stats = tree.stats();
/// println!("Total nodes: {}, Leaf nodes: {}", stats.total_nodes, stats.leaf_nodes);
/// ```
/// BM25/Tantivy sparse indexing.
///
/// This module provides full-text search indexing using the Tantivy search engine,
/// implementing BM25 scoring for keyword-based retrieval.
///
/// # Key Types
///
/// - [`indexing::IndexManager`]: Manages all index types
/// - [`indexing::BM25Index`]: BM25 text index using Tantivy
/// - [`indexing::IndexConfig`]: Configuration for indexing
/// - [`indexing::IndexStats`]: Statistics about the index
/// - [`indexing::BM25Result`]: Result from a BM25 search
///
/// # Features
///
/// - Fast full-text search with BM25 scoring
/// - In-memory or persistent index storage
/// - Incremental document updates
/// - Index optimization (segment merging)
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::indexing::{IndexManager, BM25Index};
///
/// // Create in-memory index manager
/// let manager = IndexManager::in_memory()?;
///
/// // Index a document
/// manager.index_document(&document)?;
///
/// // Search using BM25
/// let results = manager.search_bm25("machine learning", 10)?;
///
/// for result in results {
/// println!("Score: {:.2}, Text: {}", result.score, result.text);
/// }
/// ```
/// RAG pipeline orchestration.
///
/// This module coordinates the full RAG (Retrieval-Augmented Generation) pipeline:
/// - Query processing and analysis
/// - Multi-stage retrieval (sparse, dense, hybrid)
/// - Context assembly and ranking
/// - Response generation coordination
/// Docset ingestion (Cursor-like `@Docs`) for URL documentation crawling.
///
/// This module enables indexing documentation sites (start URL + allowed prefixes),
/// with refresh scheduling that can run without `reasonkit-org`.
/// MemoryService trait implementation for reasonkit-core integration.
///
/// This module provides the [`service::MemServiceImpl`] struct that implements the
/// `MemoryService` trait defined in `reasonkit-core::traits::memory`. It wraps the
/// existing reasonkit-mem infrastructure into a unified interface for cross-crate
/// integration.
///
/// # Architecture
///
/// ```text
/// reasonkit-core reasonkit-mem
/// +------------------+ +------------------+
/// | MemoryService | <-- trait | MemServiceImpl |
/// | (trait) | | (implementation) |
/// +------------------+ +------------------+
/// |
/// +---------------------+---------------------+
/// | | |
/// +----------+ +------------+ +------------+
/// | Storage | | Embedding | | Retrieval |
/// +----------+ +------------+ +------------+
/// ```
///
/// # Key Types
///
/// - [`service::MemServiceImpl`]: Implementation of the MemoryService trait
/// - [`service::MemoryService`]: The trait interface (mirrored from reasonkit-core)
/// - [`service::Document`]: Simplified document type for the service interface
/// - [`service::SearchResult`]: Search result from the service
/// - [`service::MemoryConfig`]: Configuration for the memory service
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::service::{MemServiceImpl, MemoryService, Document};
/// use std::collections::HashMap;
///
/// // Create in-memory service
/// let service = MemServiceImpl::in_memory()?;
///
/// // Store a document
/// let doc = Document {
/// id: None,
/// content: "Machine learning is a subset of AI.".to_string(),
/// metadata: HashMap::new(),
/// source: Some("/path/to/doc.md".to_string()),
/// created_at: None,
/// };
///
/// let id = service.store_document(&doc).await?;
///
/// // Search for documents
/// let results = service.search("machine learning", 10).await?;
///
/// // Get index statistics
/// let stats = service.get_stats().await?;
/// println!("Documents: {}, Chunks: {}", stats.total_documents, stats.total_chunks);
/// ```
/// vDreamTeam AI Agent Memory System.
///
/// This module provides structured memory for AI agent teams, enabling:
/// - Constitutional layer (shared identity, constraints, governance)
/// - Role-specific memory (per-agent decisions, lessons, PxP logs)
/// - Cross-agent coordination logging
///
/// Requires the `vdreamteam` feature flag.
///
/// # Example
///
/// ```rust,ignore
/// use reasonkit_mem::vdreamteam::{VDreamMemory, PxPEntry, Consultation};
///
/// let mut memory = VDreamMemory::load(".agents").await?;
///
/// let entry = PxPEntry::new("vcto", "Architecture decision")
/// .add_consultation(Consultation {
/// model: "deepseek-v3.2".to_string(),
/// cli_command: "ollama run deepseek-v3.2:cloud".to_string(),
/// prompt_summary: "Validate design".to_string(),
/// response_summary: "Design approved".to_string(),
/// confidence: 0.90,
/// });
///
/// memory.log_pxp(entry).await?;
/// ```
// Phase 2 Research Integrations (2026-01-18)
// Phase 3 Research Integrations (2026-01-18)
/// Prelude for convenient imports.
///
/// This module re-exports the most commonly used types for convenience.
///
/// # Example
///
/// ```rust
/// use reasonkit_mem::prelude::*;
/// ```
// ============================================================================
// Python Bindings Infrastructure
// ============================================================================
use crate;
use *;
use Arc;
use Mutex;
/// Python wrapper for the RAPTOR tree.
///
/// Provides a Python-friendly interface to the RAPTOR hierarchical tree
/// for document retrieval. Requires the `python` feature.
///
/// # Python Example
///
/// ```python
/// from reasonkit_mem import RaptorTree
///
/// # Create tree with optional configuration
/// tree = RaptorTree(max_depth=3, cluster_size=4)
///
/// # Ingest documents with custom embed and summarize functions
/// tree.ingest_documents(
/// documents=["doc1", "doc2", "doc3"],
/// embed_fn=my_embed_function,
/// summarize_fn=my_summarize_function
/// )
///
/// # Query the tree
/// results = tree.query(query_vector, top_k=10)
/// for chunk_id, score in results:
/// print(f"Chunk {chunk_id}: {score:.3f}")
/// ```
/// Python module definition for reasonkit_mem.
///
/// Exposes the RAPTOR tree functionality to Python.