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
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
//! Near-duplicate distillates: consolidation often distills one fact from
//! several conversations, and the paraphrases crowd each other out of
//! recall's top-k. The daemon finds the groups and applies a merge written
//! elsewhere (it has no LLM); a pair the writer judged distinct or
//! contradictory is recorded as reviewed so it is not offered again.

use std::collections::{HashMap, HashSet};

use anyhow::Result;
use chrono::{DateTime, Utc};
use rusqlite::{OptionalExtension, params};
use serde::Serialize;
use uuid::Uuid;

use crate::index::{EMBEDDING_DIM, Indexes};
use crate::retrieval::cosine;
use crate::schema::{Memory, MemoryType, Relation, RelationType, Scope, Tier};
use crate::session_dates::latest_session;
use crate::sqlite_store::{MEMORY_COLS, SqliteStore, parse_uuid, row_to_memory};
use crate::store::Store;

/// Context of a separate or conflict review. A pair linked by a relation
/// whose context is this, or starts with `REVIEW_CONTEXT:`, is not grouped
/// again until the review is reopened.
pub const REVIEW_CONTEXT: &str = "near-duplicate-review";
/// A pair the model judged the same but could not merge without losing a
/// fact; kept apart from `separate` so it can be reopened on its own.
pub const UNMERGED_CONTEXT: &str = "near-duplicate-review:unmerged";
pub const MAX_GROUP: usize = 4;
/// ANN neighbours fetched per distillate. Raws and other projects share the
/// index, so this leaves room beyond the three a full group needs.
const NEIGHBOURS: usize = 10;
const DISTILLATE: &str = "source = 'consolidation' AND tier = 'hot' AND superseded_by IS NULL";

#[derive(Debug, Clone, Serialize)]
pub struct NearDupMember {
    pub id: Uuid,
    pub content: String,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize)]
pub struct NearDupPair {
    pub a: Uuid,
    pub b: Uuid,
    pub similarity: f32,
}

#[derive(Debug, Clone, Serialize)]
pub struct NearDupGroup {
    pub project_path: Option<String>,
    pub memory_type: MemoryType,
    pub members: Vec<NearDupMember>,
    /// Every member pair at or above the threshold, closest first.
    pub pairs: Vec<NearDupPair>,
}

/// One page of groups plus how many exist in all, from a single grouping
/// pass so a caller can report the backlog without grouping twice.
#[derive(Debug, Clone, Serialize)]
pub struct NearDupListing {
    pub groups: Vec<NearDupGroup>,
    pub total: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReviewVerdict {
    Separate,
    Conflict,
    Unmerged,
}

impl ReviewVerdict {
    fn relation(self) -> (RelationType, &'static str, &'static str) {
        match self {
            ReviewVerdict::Separate => (RelationType::RelatesTo, "relates_to", REVIEW_CONTEXT),
            ReviewVerdict::Conflict => (RelationType::Contradicts, "contradicts", REVIEW_CONTEXT),
            ReviewVerdict::Unmerged => (RelationType::RelatesTo, "relates_to", UNMERGED_CONTEXT),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum MergeRefusal {
    /// The member is gone, superseded or no longer hot: another merge or
    /// peer got there first.
    Stale(Uuid),
    /// The request can never succeed as written.
    Invalid(String),
}

#[derive(Debug, Clone, Serialize)]
pub struct MergeReport {
    pub merged_id: Uuid,
    pub superseded: Vec<Uuid>,
    pub markers_repointed: u64,
}

struct Candidate {
    id: Uuid,
    project_path: Option<String>,
    memory_type: MemoryType,
    scope: Scope,
    created_at: DateTime<Utc>,
    embedding: Vec<f32>,
}

/// Candidate indexes ordered by creation, and the above-threshold pairs
/// among them as (candidate, candidate, similarity), closest first.
type Grouping = (Vec<usize>, Vec<(usize, usize, f32)>);

impl SqliteStore {
    /// Groups of live distillates sharing a project and type whose cosine is
    /// at least `threshold`, closest group first, at most `limit`, with the
    /// total number of groups.
    pub fn near_duplicate_groups(
        &self,
        indexes: &Indexes,
        threshold: f32,
        limit: usize,
    ) -> Result<NearDupListing> {
        let (candidates, groups) = self.group_near_duplicates(indexes, threshold)?;
        let total = groups.len();
        let groups: Vec<Grouping> = groups.into_iter().take(limit).collect();
        let mut out = Vec::with_capacity(groups.len());
        for (members, pairs) in groups {
            let first = &candidates[members[0]];
            let mut listed = Vec::with_capacity(members.len());
            for &i in &members {
                listed.push(NearDupMember {
                    id: candidates[i].id,
                    content: self.content_of(candidates[i].id)?,
                    created_at: candidates[i].created_at,
                });
            }
            out.push(NearDupGroup {
                project_path: first.project_path.clone(),
                memory_type: first.memory_type,
                members: listed,
                pairs: pairs
                    .into_iter()
                    .map(|(a, b, similarity)| NearDupPair {
                        a: candidates[a].id,
                        b: candidates[b].id,
                        similarity,
                    })
                    .collect(),
            });
        }
        Ok(NearDupListing { groups: out, total })
    }

    pub fn near_duplicate_group_count(&self, indexes: &Indexes, threshold: f32) -> Result<usize> {
        Ok(self.group_near_duplicates(indexes, threshold)?.1.len())
    }

    /// The member checks `merge_distillates` makes, read-only, so a caller
    /// can refuse a doomed merge before paying for its embedding.
    pub fn check_merge(&self, member_ids: &[Uuid]) -> Result<Result<(), MergeRefusal>> {
        if let Err(refusal) = check_member_ids(member_ids) {
            return Ok(Err(refusal));
        }
        let mut found = Vec::with_capacity(member_ids.len());
        for &id in member_ids {
            found.push((id, self.get_memory(id)?));
        }
        Ok(merge_members(found).map(|_| ()))
    }

    /// One transaction: store `content` as a distillate of the members'
    /// project, type and scope, supersede every member by it and move each
    /// raw's distillation marker onto it. Refused without writing anything
    /// unless the members are 2 to 4 distinct live distillates sharing all
    /// three. Merges for the store's owner: members by different authors
    /// give a distillate authored by this store.
    pub fn merge_distillates(
        &self,
        member_ids: &[Uuid],
        content: &str,
        embedding: Vec<f32>,
        model: &str,
    ) -> Result<Result<MergeReport, MergeRefusal>> {
        if let Err(refusal) = check_member_ids(member_ids) {
            return Ok(Err(refusal));
        }
        if content.trim().is_empty() {
            return Ok(Err(MergeRefusal::Invalid("content is empty".into())));
        }
        if embedding.len() != EMBEDDING_DIM {
            return Ok(Err(MergeRefusal::Invalid(format!(
                "embedding has {} dimensions, expected {EMBEDDING_DIM}",
                embedding.len()
            ))));
        }
        self.with_txn(|tx| {
            let mut found = Vec::with_capacity(member_ids.len());
            for &id in member_ids {
                found.push((id, Self::memory_on_tx(tx, id)?));
            }
            let members = match merge_members(found) {
                Ok(members) => members,
                Err(refusal) => return Ok(Err(refusal)),
            };
            let first = &members[0];

            let newest = members
                .iter()
                .max_by_key(|m| m.created_at)
                .expect("check_member_ids guarantees two members");
            let mut merged = Memory::new(
                content.to_string(),
                first.memory_type,
                "consolidation".to_string(),
                newest.source_id.clone(),
            )
            .with_project_path(first.project_path.clone())
            .with_machine_id(self.machine_id().to_string());
            merged.author = members
                .iter()
                .all(|m| m.author == first.author)
                .then(|| first.author.clone())
                .flatten();
            merged.scope = first.scope;
            // The merged fact is as old as its newest paraphrase, so recency
            // ranking treats it like the members rather than as fresh news.
            merged.created_at = newest.created_at;
            merged.session_at = latest_session(&members);
            merged.confidence = members
                .iter()
                .map(|m| m.confidence)
                .fold(f32::MIN, f32::max);
            merged.embedding = embedding;
            self.store_memory_on_tx(tx, &merged)?;

            let mut superseded = Vec::with_capacity(members.len());
            for m in &members {
                self.supersede_on_tx(tx, m.id, merged.id)?;
                superseded.push(m.id);
            }

            let raws: Vec<Uuid> = {
                let placeholders = vec!["?"; member_ids.len()].join(",");
                let mut stmt = tx.prepare(&format!(
                    "SELECT memory_id FROM distillation_log \
                     WHERE distilled_id IN ({placeholders}) AND memory_id <> distilled_id \
                     ORDER BY memory_id"
                ))?;
                let ids: Vec<String> = member_ids.iter().map(Uuid::to_string).collect();
                let rows = stmt.query_map(rusqlite::params_from_iter(ids), |r| {
                    parse_uuid(&r.get::<_, String>(0)?)
                })?;
                rows.collect::<rusqlite::Result<Vec<_>>>()?
            };
            for &raw in &raws {
                self.mark_consolidated_on_tx(tx, raw, merged.id, model)?;
                // Most raws were purged or archived long ago; a relation to a
                // missing row would be dropped by every peer's import.
                if Self::memory_on_tx(tx, raw)?.is_some() {
                    self.store_relation_on_tx(
                        tx,
                        &Relation {
                            from_id: merged.id,
                            to_id: raw,
                            relation_type: RelationType::DistilledFrom,
                            strength: 1.0,
                            context: Some(model.to_string()),
                        },
                    )?;
                }
            }

            Ok(Ok(MergeReport {
                merged_id: merged.id,
                superseded,
                markers_repointed: raws.len() as u64,
            }))
        })
    }

    /// Links every pair of `member_ids` with the verdict's relation and
    /// context (see `ReviewVerdict::relation`); returns how many links were
    /// new. A pair holds one edge per relation type, so a later `separate`
    /// or `unmerged` verdict replaces the earlier one.
    pub fn record_near_duplicate_review(
        &self,
        member_ids: &[Uuid],
        verdict: ReviewVerdict,
    ) -> Result<Result<u64, MergeRefusal>> {
        if let Err(refusal) = check_member_ids(member_ids) {
            return Ok(Err(refusal));
        }
        let (relation_type, type_name, context) = verdict.relation();
        self.with_txn(|tx| {
            for &id in member_ids {
                if Self::memory_on_tx(tx, id)?.is_none() {
                    return Ok(Err(MergeRefusal::Invalid(format!(
                        "no memory with id {id}"
                    ))));
                }
            }
            let mut sorted = member_ids.to_vec();
            sorted.sort();
            let mut recorded = 0u64;
            for (i, &a) in sorted.iter().enumerate() {
                for &b in &sorted[i + 1..] {
                    let exists: Option<i64> = tx
                        .query_row(
                            "SELECT 1 FROM relations WHERE from_id = ?1 AND to_id = ?2 \
                             AND relation_type = ?3 AND context = ?4",
                            params![a.to_string(), b.to_string(), type_name, context],
                            |r| r.get(0),
                        )
                        .optional()?;
                    if exists.is_some() {
                        continue;
                    }
                    self.store_relation_on_tx(
                        tx,
                        &Relation {
                            from_id: a,
                            to_id: b,
                            relation_type,
                            strength: 1.0,
                            context: Some(context.to_string()),
                        },
                    )?;
                    recorded += 1;
                }
            }
            Ok(Ok(recorded))
        })
    }

    /// Deletes the review edges of `verdicts`, replicated as relation
    /// deletes, so their pairs are grouped again on every peer. Returns how
    /// many edges were removed; a rerun removes nothing.
    pub fn reopen_near_duplicate_reviews(&self, verdicts: &[ReviewVerdict]) -> Result<u64> {
        let mut edges = Vec::new();
        {
            let conn = self.reader();
            for &verdict in verdicts {
                let (relation_type, type_name, context) = verdict.relation();
                let mut stmt = conn.prepare(
                    "SELECT from_id, to_id, strength FROM relations \
                     WHERE relation_type = ?1 AND context = ?2",
                )?;
                let rows = stmt.query_map(params![type_name, context], |r| {
                    Ok(Relation {
                        from_id: parse_uuid(&r.get::<_, String>(0)?)?,
                        to_id: parse_uuid(&r.get::<_, String>(1)?)?,
                        relation_type,
                        strength: r.get::<_, f64>(2)? as f32,
                        context: Some(context.to_string()),
                    })
                })?;
                for edge in rows {
                    edges.push(edge?);
                }
            }
        }
        self.with_txn(|tx| {
            let mut removed = 0u64;
            for edge in &edges {
                if self.delete_relation_on_tx(tx, edge)? {
                    removed += 1;
                }
            }
            Ok(removed)
        })
    }

    /// Holds one embedding per live distillate (about 1.5 KB each) and at
    /// most `NEIGHBOURS` edges per distillate, never an all-pairs matrix.
    fn group_near_duplicates(
        &self,
        indexes: &Indexes,
        threshold: f32,
    ) -> Result<(Vec<Candidate>, Vec<Grouping>)> {
        let candidates = self.live_distillates()?;
        let position: HashMap<Uuid, usize> = candidates
            .iter()
            .enumerate()
            .map(|(i, c)| (c.id, i))
            .collect();
        let reviewed = self.reviewed_pairs()?;

        let mut edges: HashMap<(usize, usize), f32> = HashMap::new();
        for (i, c) in candidates.iter().enumerate() {
            for (id, _) in indexes.vector_search(self, &c.embedding, NEIGHBOURS)? {
                let Some(&j) = position.get(&id) else {
                    continue;
                };
                let other = &candidates[j];
                if j == i
                    || other.project_path != c.project_path
                    || other.memory_type != c.memory_type
                    || other.scope != c.scope
                {
                    continue;
                }
                let key = (i.min(j), i.max(j));
                if edges.contains_key(&key) {
                    continue;
                }
                let (x, y) = (candidates[key.0].id, candidates[key.1].id);
                if reviewed.contains(&(x.min(y), x.max(y))) {
                    continue;
                }
                // The index stores quantized vectors, so its score only
                // nominates; the stored embeddings decide.
                let similarity = cosine(&c.embedding, &other.embedding);
                if similarity >= threshold {
                    edges.insert(key, similarity);
                }
            }
        }

        let mut edges: Vec<((usize, usize), f32)> = edges.into_iter().collect();
        edges.sort_by(|(ka, sa), (kb, sb)| {
            sb.total_cmp(sa)
                .then_with(|| candidates[ka.0].id.cmp(&candidates[kb.0].id))
                .then_with(|| candidates[ka.1].id.cmp(&candidates[kb.1].id))
        });

        let mut sets = DisjointSets::new(candidates.len());
        for &((a, b), _) in &edges {
            sets.union_capped(a, b, MAX_GROUP);
        }
        let mut by_root: HashMap<usize, Vec<usize>> = HashMap::new();
        for &((a, b), _) in &edges {
            for i in [a, b] {
                let members = by_root.entry(sets.find(i)).or_default();
                if !members.contains(&i) {
                    members.push(i);
                }
            }
        }
        let mut groups: Vec<Grouping> = by_root
            .into_values()
            .filter(|members| members.len() > 1)
            .map(|mut members| {
                members.sort_by(|&x, &y| {
                    candidates[x]
                        .created_at
                        .cmp(&candidates[y].created_at)
                        .then_with(|| candidates[x].id.cmp(&candidates[y].id))
                });
                let pairs = edges
                    .iter()
                    .filter(|((a, b), _)| members.contains(a) && members.contains(b))
                    .map(|&((a, b), s)| (a, b, s))
                    .collect();
                (members, pairs)
            })
            .collect();
        groups.sort_by(|(ma, pa), (mb, pb)| {
            pb[0]
                .2
                .total_cmp(&pa[0].2)
                .then_with(|| candidates[ma[0]].id.cmp(&candidates[mb[0]].id))
        });
        Ok((candidates, groups))
    }

    fn live_distillates(&self) -> Result<Vec<Candidate>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS}, embedding FROM memories \
             WHERE {DISTILLATE} AND embedding IS NOT NULL ORDER BY id"
        ))?;
        let rows = stmt.query_map([], |r| row_to_memory(r, true))?;
        let mut out = Vec::new();
        for m in rows {
            let m = m?;
            if m.embedding.len() != EMBEDDING_DIM {
                continue;
            }
            out.push(Candidate {
                id: m.id,
                project_path: m.project_path,
                memory_type: m.memory_type,
                scope: m.scope,
                created_at: m.created_at,
                embedding: m.embedding,
            });
        }
        Ok(out)
    }

    fn reviewed_pairs(&self) -> Result<HashSet<(Uuid, Uuid)>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(
            "SELECT from_id, to_id FROM relations WHERE context = ?1 OR context LIKE ?1 || ':%'",
        )?;
        let rows = stmt.query_map(params![REVIEW_CONTEXT], |r| {
            Ok((
                parse_uuid(&r.get::<_, String>(0)?)?,
                parse_uuid(&r.get::<_, String>(1)?)?,
            ))
        })?;
        let mut out = HashSet::new();
        for pair in rows {
            let (a, b) = pair?;
            out.insert((a.min(b), a.max(b)));
        }
        Ok(out)
    }

    fn content_of(&self, id: Uuid) -> Result<String> {
        let conn = self.reader();
        Ok(conn.query_row(
            "SELECT content FROM memories WHERE id = ?1",
            params![id.to_string()],
            |r| r.get(0),
        )?)
    }
}

/// Live distillates of one project and type, in request order.
fn merge_members(found: Vec<(Uuid, Option<Memory>)>) -> Result<Vec<Memory>, MergeRefusal> {
    let mut members = Vec::with_capacity(found.len());
    for (id, memory) in found {
        match memory {
            None => return Err(MergeRefusal::Stale(id)),
            Some(m) if m.source != "consolidation" => {
                return Err(MergeRefusal::Invalid(format!("{id} is not a distillate")));
            }
            Some(m) if m.tier != Tier::Hot || m.superseded_by.is_some() => {
                return Err(MergeRefusal::Stale(id));
            }
            Some(m) => members.push(m),
        }
    }
    let first = &members[0];
    if members.iter().any(|m| {
        m.project_path != first.project_path
            || m.memory_type != first.memory_type
            || m.scope != first.scope
    }) {
        return Err(MergeRefusal::Invalid(
            "members span more than one project, memory type or scope".into(),
        ));
    }
    Ok(members)
}

/// The shape every merge and review request must have: 2 to `MAX_GROUP`
/// distinct ids.
pub fn check_member_ids(member_ids: &[Uuid]) -> Result<(), MergeRefusal> {
    if !(2..=MAX_GROUP).contains(&member_ids.len()) {
        return Err(MergeRefusal::Invalid(format!(
            "expected 2 to {MAX_GROUP} member ids, got {}",
            member_ids.len()
        )));
    }
    let distinct: HashSet<&Uuid> = member_ids.iter().collect();
    if distinct.len() != member_ids.len() {
        return Err(MergeRefusal::Invalid("member ids repeat".into()));
    }
    Ok(())
}

/// Union-find whose unions stop at a size cap, so a chain of close pairs
/// cannot snowball into one group too large to merge in a single prompt.
struct DisjointSets {
    parent: Vec<usize>,
    size: Vec<usize>,
}

impl DisjointSets {
    fn new(n: usize) -> Self {
        Self {
            parent: (0..n).collect(),
            size: vec![1; n],
        }
    }

    fn find(&mut self, mut i: usize) -> usize {
        while self.parent[i] != i {
            self.parent[i] = self.parent[self.parent[i]];
            i = self.parent[i];
        }
        i
    }

    fn union_capped(&mut self, a: usize, b: usize, cap: usize) {
        let (ra, rb) = (self.find(a), self.find(b));
        if ra == rb || self.size[ra] + self.size[rb] > cap {
            return;
        }
        let (big, small) = if self.size[ra] >= self.size[rb] {
            (ra, rb)
        } else {
            (rb, ra)
        };
        self.parent[small] = big;
        self.size[big] += self.size[small];
    }
}