second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
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
use std::collections::HashSet;

use anyhow::Result;
use uuid::Uuid;

use crate::schema::Memory;
use crate::store::Store;

#[derive(Debug, Clone)]
pub struct QueryRequest {
    pub text: String,
    pub embedding: Vec<f32>,
    pub limit: usize,
    pub filters: QueryFilters,
}

#[derive(Debug, Clone, Default)]
pub struct QueryFilters {
    pub source: Option<String>,
    pub memory_type: Option<crate::schema::MemoryType>,
    pub min_confidence: Option<f32>,
    pub entity_names: Vec<String>,
    pub project_path: Option<String>,
}

#[derive(Debug, Clone)]
pub struct QueryResult {
    pub memory: Memory,
    pub score: f32,
    /// The term membership was judged on: the cross-encoder score when the
    /// answer was reranked, else cosine similarity.
    pub relevance: f32,
    pub path: Vec<Uuid>,
}

use crate::retrieval::blend::{self, MIN_SIMILARITY, PROJECT_AFFINITY_BOOST};

pub struct QueryEngine<'a, S: Store + ?Sized> {
    store: &'a S,
    vector_weight: f32,
    graph_weight: f32,
    recency_weight: f32,
}

impl<'a, S: Store + ?Sized> QueryEngine<'a, S> {
    pub fn new(store: &'a S) -> Self {
        Self {
            store,
            vector_weight: 0.5,
            graph_weight: 0.3,
            recency_weight: 0.2,
        }
    }

    pub fn with_weights(mut self, vector: f32, graph: f32, recency: f32) -> Self {
        self.vector_weight = vector;
        self.graph_weight = graph;
        self.recency_weight = recency;
        self
    }

    pub fn recall(&self, request: &QueryRequest) -> Result<Vec<QueryResult>> {
        // A scoped recall must scan the scope, not trim an unfiltered top-k:
        // the filters below can only reject, so anything the unfiltered search
        // misses stays missing however narrow the scope is.
        let vector_results = if request.filters.source.is_some()
            || request.filters.memory_type.is_some()
            || request.filters.project_path.is_some()
        {
            self.store.filtered_vector_search(
                &request.embedding,
                request.filters.source.as_deref(),
                request.filters.memory_type,
                request.filters.project_path.as_deref(),
                request.limit * 3,
            )?
        } else {
            self.store
                .vector_search(&request.embedding, request.limit * 3)?
        };

        let query_entity_ids = self.resolve_query_entities(&request.filters.entity_names);

        let mut scored: Vec<QueryResult> = Vec::new();

        for (memory, similarity) in vector_results {
            // Gate membership on similarity alone. Graph and recency only
            // re-rank, so folding them into the cutoff caps the similarity
            // term below any useful threshold and would silently drop aged,
            // unconnected memories that match the query perfectly.
            if similarity < MIN_SIMILARITY {
                continue;
            }
            if let Some(min_conf) = request.filters.min_confidence
                && memory.confidence < min_conf
            {
                continue;
            }
            if let Some(ref source) = request.filters.source
                && !self.store.source_admits(&memory, source)?
            {
                continue;
            }
            if let Some(ref mt) = request.filters.memory_type
                && &memory.memory_type != mt
            {
                continue;
            }

            let recency_score = self.compute_recency(&memory);
            let graph_score = self
                .compute_graph_relevance(&memory, &query_entity_ids)
                .unwrap_or(0.0);

            let mut rank_score = (similarity * self.vector_weight)
                + (graph_score * self.graph_weight)
                + (recency_score * self.recency_weight);

            if let Some(ref qp) = request.filters.project_path
                && memory.project_path.as_deref() == Some(qp.as_str())
            {
                rank_score *= PROJECT_AFFINITY_BOOST;
            }

            scored.push(QueryResult {
                memory,
                score: rank_score,
                relevance: similarity,
                path: Vec::new(),
            });
        }

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

        Ok(scored)
    }

    fn compute_recency(&self, memory: &Memory) -> f32 {
        blend::compute_recency(memory)
    }

    fn resolve_query_entities(&self, names: &[String]) -> HashSet<Uuid> {
        blend::resolve_query_entities(self.store, names)
    }

    fn compute_graph_relevance(
        &self,
        memory: &Memory,
        query_entity_ids: &HashSet<Uuid>,
    ) -> Result<f32> {
        blend::compute_graph_relevance(self.store, memory, query_entity_ids)
    }

    pub fn store(&self) -> &S {
        self.store
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{Conversation, Entity, MemoryType, Relation, RelationType};
    use chrono::{Duration, Utc};

    struct StubStore {
        vector_results: Vec<(Memory, f32)>,
        relations: Vec<Relation>,
        entities: Vec<Entity>,
    }

    impl StubStore {
        fn new(vector_results: Vec<(Memory, f32)>, relations: Vec<Relation>) -> Self {
            Self {
                vector_results,
                relations,
                entities: Vec::new(),
            }
        }
    }

    impl Store for StubStore {
        // Truncates like a real store, so a test can put a memory past the
        // cutoff and see whether the filters below it can still reach one.
        fn vector_search(&self, _embedding: &[f32], limit: usize) -> Result<Vec<(Memory, f32)>> {
            Ok(self.vector_results.iter().take(limit).cloned().collect())
        }

        // The stub's whole corpus is vector_results, so a scoped exhaustive
        // scan is that list filtered, not the unfiltered prefix it returns
        // above.
        fn filtered_vector_search(
            &self,
            _embedding: &[f32],
            source: Option<&str>,
            memory_type: Option<MemoryType>,
            project_path: Option<&str>,
            limit: usize,
        ) -> Result<Vec<(Memory, f32)>> {
            Ok(self
                .vector_results
                .iter()
                .filter(|(m, _)| source.is_none_or(|s| self.source_admits(m, s).unwrap()))
                .filter(|(m, _)| memory_type.is_none_or(|t| m.memory_type == t))
                .filter(|(m, _)| project_path.is_none_or(|p| m.project_path.as_deref() == Some(p)))
                .take(limit)
                .cloned()
                .collect())
        }

        // Stands in for the sqlite lookup through distillation_log: every
        // distillate here descends from a "cursor" raw.
        fn source_admits(&self, memory: &Memory, source: &str) -> Result<bool> {
            Ok(memory.source == source || (memory.source == "consolidation" && source == "cursor"))
        }

        fn get_relations(
            &self,
            node_id: Uuid,
            relation_type: Option<RelationType>,
        ) -> Result<Vec<Relation>> {
            Ok(self
                .relations
                .iter()
                .filter(|r| r.from_id == node_id)
                .filter(|r| {
                    relation_type
                        .map(|rt| rt == r.relation_type)
                        .unwrap_or(true)
                })
                .cloned()
                .collect())
        }

        fn store_memory(&self, _m: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn get_memory(&self, _id: Uuid) -> Result<Option<Memory>> {
            unimplemented!()
        }
        fn delete_memory(&self, _id: Uuid) -> Result<()> {
            unimplemented!()
        }
        fn store_entity(&self, _e: &Entity) -> Result<()> {
            unimplemented!()
        }
        fn get_entity(&self, _id: Uuid) -> Result<Option<Entity>> {
            unimplemented!()
        }
        fn find_entity_by_name(&self, name: &str) -> Result<Option<Entity>> {
            Ok(self.entities.iter().find(|e| e.name == name).cloned())
        }
        fn store_conversation(&self, _c: &Conversation) -> Result<()> {
            unimplemented!()
        }
        fn store_relation(&self, _r: &Relation) -> Result<()> {
            unimplemented!()
        }
        fn traverse(&self, _id: Uuid, _depth: u32) -> Result<Vec<(Memory, Vec<Relation>)>> {
            unimplemented!()
        }
        fn memories_by_source(&self, _s: &str) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn memories_by_type(&self, _mt: MemoryType) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn update_memory(&self, _m: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn record_access(&self, _memory: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn bm25_search(&self, _q: &str, _limit: usize) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn get_memory_with_embedding(&self, _id: Uuid) -> Result<Option<Memory>> {
            unimplemented!()
        }
        fn memory_count(&self) -> Result<usize> {
            unimplemented!()
        }
        fn all_memory_ids(&self) -> Result<Vec<Uuid>> {
            unimplemented!()
        }
        fn all_relations(&self) -> Result<Vec<Relation>> {
            unimplemented!()
        }
    }

    fn memory_aged(content: &str, days_old: i64) -> Memory {
        let when = Utc::now() - Duration::days(days_old);
        let mut m = Memory::new(
            content.to_string(),
            MemoryType::Semantic,
            "test".to_string(),
            String::new(),
        );
        m.created_at = when;
        m.last_accessed = when;
        m
    }

    fn query() -> QueryRequest {
        QueryRequest {
            text: "query text".to_string(),
            embedding: vec![0.0_f32; 384],
            limit: 10,
            filters: QueryFilters::default(),
        }
    }

    #[test]
    fn source_filter_reaches_past_the_unfiltered_cutoff() {
        // recall() fetches limit*3 vectors, so 30 same-source memories fill the
        // window completely. A post-filter over that window can only return
        // nothing; the scoped scan has to look at the whole corpus.
        let mut corpus: Vec<(Memory, f32)> = (0..30)
            .map(|i| (memory_aged(&format!("crowding note {i}"), 1), 0.95))
            .collect();
        let mut wanted = memory_aged("the memory the caller asked to scope to", 1);
        wanted.source = "ask".to_string();
        let wanted_id = wanted.id;
        corpus.push((wanted, 0.80));

        let store = StubStore::new(corpus, Vec::new());
        let mut request = query();
        request.filters.source = Some("ask".to_string());

        let results = QueryEngine::new(&store).recall(&request).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].memory.id, wanted_id);
    }

    #[test]
    fn source_filter_defers_to_the_store_for_distillates() {
        let mut distillate = memory_aged("distilled from a cursor transcript", 1);
        distillate.source = "consolidation".to_string();
        let mut other = memory_aged("distilled from something else", 1);
        other.source = "claude-code".to_string();
        let distillate_id = distillate.id;
        let store = StubStore::new(vec![(distillate, 0.9), (other, 0.9)], Vec::new());
        let mut request = query();
        request.filters.source = Some("cursor".to_string());

        let results = QueryEngine::new(&store).recall(&request).unwrap();
        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![distillate_id]);
    }

    #[test]
    fn aged_unconnected_memory_survives_on_strong_similarity() {
        // The memory is 180 days old with no relations, so graph and recency
        // contribute nothing; it must still be recalled because a strong
        // semantic match is what relevance means.
        let store = StubStore::new(
            vec![(
                memory_aged("kuzu was chosen as the embedded graph store", 180),
                0.92,
            )],
            Vec::new(),
        );
        let results = QueryEngine::new(&store).recall(&query()).unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn well_connected_low_similarity_memory_is_excluded() {
        // A fresh, heavily reinforced memory whose similarity is weak must be
        // dropped, because graph and recency re-rank matches but must not
        // promote an irrelevant memory past the similarity floor.
        let weak = memory_aged("an entirely unrelated topic", 0);
        let weak_id = weak.id;
        let reinforces = |to| Relation {
            from_id: weak_id,
            to_id: to,
            relation_type: RelationType::Reinforces,
            strength: 1.0,
            context: None,
        };
        let store = StubStore::new(
            vec![(weak, 0.45)],
            vec![
                reinforces(Uuid::new_v4()),
                reinforces(Uuid::new_v4()),
                reinforces(Uuid::new_v4()),
            ],
        );
        let results = QueryEngine::new(&store).recall(&query()).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn results_are_ranked_by_blended_score() {
        // Both memories clear the similarity floor with equal similarity, so
        // recency must break the tie and rank the fresher memory first.
        let store = StubStore::new(
            vec![
                (memory_aged("older relevant note", 200), 0.80),
                (memory_aged("fresher relevant note", 0), 0.80),
            ],
            Vec::new(),
        );
        let results = QueryEngine::new(&store).recall(&query()).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].memory.content, "fresher relevant note");
    }

    fn mentions(from: Uuid, to: Uuid) -> Relation {
        Relation {
            from_id: from,
            to_id: to,
            relation_type: RelationType::Mentions,
            strength: 1.0,
            context: None,
        }
    }

    #[test]
    fn memory_mentioning_a_query_entity_outranks_an_equal_match_that_does_not() {
        // Two memories, same similarity and same age. One mentions the entity
        // the query is about; it must rank first because graph proximity is now
        // query-conditioned rather than a raw connectedness prior.
        let on_topic = memory_aged("note about the kuzu store", 10);
        let off_topic = memory_aged("note about something else", 10);
        let kuzu = Entity::new("kuzu".to_string(), "technology".to_string());

        let mut store = StubStore::new(
            vec![(off_topic.clone(), 0.80), (on_topic.clone(), 0.80)],
            vec![mentions(on_topic.id, kuzu.id)],
        );
        store.entities = vec![kuzu];

        let mut req = query();
        req.filters.entity_names = vec!["kuzu".to_string()];

        let results = QueryEngine::new(&store).recall(&req).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].memory.content, "note about the kuzu store");
    }

    #[test]
    fn unresolvable_query_entity_falls_back_to_structural_ranking() {
        // An entity name the store has never seen resolves to nothing, so the
        // graph term reverts to the structural prior and recency breaks the tie
        // exactly as when no entities are named.
        let store = StubStore::new(
            vec![
                (memory_aged("older relevant note", 200), 0.80),
                (memory_aged("fresher relevant note", 0), 0.80),
            ],
            Vec::new(),
        );
        let mut req = query();
        req.filters.entity_names = vec!["never-seen-entity".to_string()];

        let results = QueryEngine::new(&store).recall(&req).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].memory.content, "fresher relevant note");
    }
}