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
//! When the session behind each memory happened. `created_at` is the time a
//! row was ingested or distilled, which bulk re-ingests and re-distillation
//! moved by weeks, so recall needs a separate date that only ever comes from
//! evidence of the session itself and is left unknown otherwise.

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

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

use crate::schema::{EXPLICIT_SOURCES, Memory, Tier};
use crate::sqlite_store::{MEMORY_COLS, SqliteStore, parse_dt, parse_uuid, row_to_memory};

/// A distillate or merge is as recent as the latest session it drew on.
pub fn latest_session<'a>(members: impl IntoIterator<Item = &'a Memory>) -> Option<DateTime<Utc>> {
    members.into_iter().filter_map(|m| m.session_at).max()
}

/// Session evidence that lives outside the store: transcripts and note
/// files, which only the machine that captured the sessions has.
pub trait SessionEvidence {
    /// Time of the line in the transcript at `transcript` that holds `text`.
    fn line_time(&self, transcript: &str, text: &str) -> Option<DateTime<Utc>>;
    /// Time of the first timestamped line in the transcript.
    fn first_time(&self, transcript: &str) -> Option<DateTime<Utc>>;
    /// Modification time of the note file at `path`. None for a transcript,
    /// whose mtime is its last line rather than when its content was said.
    fn note_modified_at(&self, path: &str) -> Option<DateTime<Utc>>;
}

/// Where a backfilled date came from, strongest first. Everything after
/// `TranscriptLine` except `RememberedAt` is a lower bound: a session start
/// dates knowledge written later in that session as older than it was, the
/// safe direction when judging staleness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionTier {
    TranscriptLine,
    ConversationStart,
    TranscriptStart,
    FileMtime,
    RememberedAt,
    Unknown,
}

#[derive(Debug, Default, Serialize)]
#[serde(transparent)]
pub struct TierCounts(BTreeMap<SessionTier, u64>);

impl TierCounts {
    pub fn get(&self, tier: SessionTier) -> u64 {
        self.0.get(&tier).copied().unwrap_or(0)
    }

    fn add(&mut self, tier: SessionTier) {
        *self.0.entry(tier).or_insert(0) += 1;
    }
}

#[derive(Debug, Serialize)]
pub struct SessionSample {
    pub id: Uuid,
    pub tier: SessionTier,
    pub session_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
    pub source: String,
    pub source_id: String,
    pub content: String,
}

#[derive(Debug, Default, Serialize)]
pub struct SessionBackfillReport {
    pub dry_run: bool,
    /// Rows that had no session date when the run started.
    pub candidates: u64,
    pub all: TierCounts,
    /// The subset recall can return: hot and not superseded.
    pub live: TierCounts,
    /// Conversations whose `started_at` was stamped at ingest because the
    /// transcript carried no timestamp, so it was not used as evidence.
    pub fallback_conversations_skipped: u64,
    pub written: u64,
    pub reemitted: u64,
    pub sample: Vec<SessionSample>,
}

const SAMPLE_SIZE: usize = 20;
const WRITE_BATCH: usize = 500;

struct ConversationLink {
    id: Uuid,
    source: String,
    started_at: DateTime<Utc>,
}

/// Everything the tiers read from the store, loaded once so the evidence
/// lookups run outside any transaction.
struct StoreFacts {
    memories: Vec<Memory>,
    raws_of: HashMap<Uuid, Vec<Uuid>>,
    conversations_of: HashMap<Uuid, Vec<ConversationLink>>,
}

impl SqliteStore {
    /// Fills a NULL `session_at` from the strongest evidence each memory has
    /// (see `SessionTier`) and logs a sync Update per row, without touching
    /// `updated_at`: peers merge the date apart from last-write-wins, so the
    /// Update never beats a newer edit made elsewhere. A date already set is
    /// never replaced, so a second run writes nothing. `reemit` also relogs
    /// every date set before this run, for a peer that upgraded late.
    pub fn backfill_session_at(
        &self,
        evidence: &dyn SessionEvidence,
        dry_run: bool,
        reemit: bool,
    ) -> Result<SessionBackfillReport> {
        let facts = self.session_facts()?;
        let by_id: HashMap<Uuid, &Memory> = facts.memories.iter().map(|m| (m.id, m)).collect();

        let candidates: Vec<&Memory> = facts
            .memories
            .iter()
            .filter(|m| m.session_at.is_none())
            .collect();
        let line_times = transcript_line_times(&candidates, &facts.raws_of, &by_id, evidence);

        let mut report = SessionBackfillReport {
            dry_run,
            candidates: candidates.len() as u64,
            ..Default::default()
        };
        let mut fallbacks: HashSet<Uuid> = HashSet::new();
        let mut dated: Vec<(&Memory, SessionTier, DateTime<Utc>)> = Vec::new();
        for m in &candidates {
            let raws = raws_of(m, &facts.raws_of, &by_id);
            let (tier, at) = date_of(
                m,
                &raws,
                &line_times,
                &facts.conversations_of,
                evidence,
                &mut fallbacks,
            );
            report.all.add(tier);
            if m.tier == Tier::Hot && m.superseded_by.is_none() {
                report.live.add(tier);
            }
            if let Some(at) = at {
                dated.push((m, tier, at));
            }
        }
        report.fallback_conversations_skipped = fallbacks.len() as u64;
        report.sample = sample(&dated);

        if dry_run {
            return Ok(report);
        }
        for batch in dated.chunks(WRITE_BATCH) {
            report.written += self.with_txn(|tx| {
                let mut written = 0;
                for (m, _, at) in batch {
                    let changed = tx.execute(
                        "UPDATE memories SET session_at = ?2 WHERE id = ?1 AND session_at IS NULL",
                        params![m.id.to_string(), at.to_rfc3339()],
                    )?;
                    if changed == 1
                        && let Some(row) = Self::memory_on_tx(tx, m.id)?
                    {
                        self.log_memory_update(tx, &row)?;
                        written += 1;
                    }
                }
                Ok(written)
            })?;
        }
        if reemit {
            let predated: Vec<Uuid> = facts
                .memories
                .iter()
                .filter(|m| m.session_at.is_some())
                .map(|m| m.id)
                .collect();
            for batch in predated.chunks(WRITE_BATCH) {
                report.reemitted += self.with_txn(|tx| {
                    let mut logged = 0;
                    for &id in batch {
                        if let Some(row) = Self::memory_on_tx(tx, id)? {
                            self.log_memory_update(tx, &row)?;
                            logged += 1;
                        }
                    }
                    Ok(logged)
                })?;
            }
        }
        Ok(report)
    }

    fn session_facts(&self) -> Result<StoreFacts> {
        let conn = self.reader();
        let memories = {
            let mut stmt =
                conn.prepare(&format!("SELECT {MEMORY_COLS} FROM memories ORDER BY id"))?;
            stmt.query_map([], |r| row_to_memory(r, false))?
                .collect::<rusqlite::Result<Vec<_>>>()?
        };

        let mut raws_of: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
        {
            let mut stmt = conn.prepare(
                "SELECT distilled_id, memory_id FROM distillation_log \
                 WHERE memory_id <> distilled_id",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok((
                    parse_uuid(&r.get::<_, String>(0)?)?,
                    parse_uuid(&r.get::<_, String>(1)?)?,
                ))
            })?;
            for row in rows {
                let (distilled, raw) = row?;
                raws_of.entry(distilled).or_default().push(raw);
            }
        }

        let mut conversations_of: HashMap<Uuid, Vec<ConversationLink>> = HashMap::new();
        {
            let mut stmt = conn.prepare(
                "SELECT r.from_id, c.id, c.source, c.started_at FROM relations r \
                 JOIN conversations c ON c.id = r.to_id \
                 WHERE r.relation_type = 'derived_from'",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok((
                    parse_uuid(&r.get::<_, String>(0)?)?,
                    ConversationLink {
                        id: parse_uuid(&r.get::<_, String>(1)?)?,
                        source: r.get(2)?,
                        started_at: parse_dt(&r.get::<_, String>(3)?)?,
                    },
                ))
            })?;
            for row in rows {
                let (memory, link) = row?;
                conversations_of.entry(memory).or_default().push(link);
            }
        }

        Ok(StoreFacts {
            memories,
            raws_of,
            conversations_of,
        })
    }
}

fn is_distillate(m: &Memory) -> bool {
    m.source == "consolidation"
}

fn is_explicit(m: &Memory) -> bool {
    EXPLICIT_SOURCES.contains(&m.source.as_str())
}

/// The transcript rows a memory's session is read from: its own row for a
/// raw, the raws that still exist for a distillate, none for a note.
fn raws_of<'a>(
    m: &'a Memory,
    raws_of: &HashMap<Uuid, Vec<Uuid>>,
    by_id: &HashMap<Uuid, &'a Memory>,
) -> Vec<&'a Memory> {
    if is_explicit(m) {
        Vec::new()
    } else if is_distillate(m) {
        raws_of
            .get(&m.id)
            .into_iter()
            .flatten()
            .filter_map(|id| by_id.get(id).copied())
            .filter(|raw| !is_distillate(raw) && !is_explicit(raw))
            .collect()
    } else {
        vec![m]
    }
}

/// Line times for every raw some candidate needs, looked up in source_id
/// order so an evidence source that keeps only its last transcript parsed
/// reads each transcript once.
fn transcript_line_times(
    candidates: &[&Memory],
    raws: &HashMap<Uuid, Vec<Uuid>>,
    by_id: &HashMap<Uuid, &Memory>,
    evidence: &dyn SessionEvidence,
) -> HashMap<Uuid, DateTime<Utc>> {
    let mut needed: Vec<&Memory> = candidates
        .iter()
        .flat_map(|m| raws_of(m, raws, by_id))
        .collect();
    needed.sort_by(|a, b| (&a.source_id, a.id).cmp(&(&b.source_id, b.id)));
    needed.dedup_by_key(|m| m.id);
    needed
        .into_iter()
        .filter_map(|raw| {
            evidence
                .line_time(&raw.source_id, &raw.content)
                .map(|at| (raw.id, at))
        })
        .collect()
}

fn date_of(
    m: &Memory,
    raws: &[&Memory],
    line_times: &HashMap<Uuid, DateTime<Utc>>,
    conversations_of: &HashMap<Uuid, Vec<ConversationLink>>,
    evidence: &dyn SessionEvidence,
    fallbacks: &mut HashSet<Uuid>,
) -> (SessionTier, Option<DateTime<Utc>>) {
    if is_explicit(m) {
        // Every explicit source except claude-memory is written by remember
        // during the session it describes; a claude-memory note is a file
        // whose conversation is always stamped at ingest.
        return if m.source == "claude-memory" {
            match note_time(m, evidence) {
                Some(at) => (SessionTier::FileMtime, Some(at)),
                None => (SessionTier::Unknown, None),
            }
        } else {
            (SessionTier::RememberedAt, Some(m.created_at))
        };
    }

    if let Some(at) = raws.iter().filter_map(|r| line_times.get(&r.id)).max() {
        return (SessionTier::TranscriptLine, Some(*at));
    }

    let started = raws
        .iter()
        .flat_map(|raw| {
            conversations_of
                .get(&raw.id)
                .into_iter()
                .flatten()
                .map(move |c| (raw, c))
        })
        .filter(|(raw, c)| {
            if c.source == "claude-memory" {
                return false;
            }
            // An adapter stamps `started_at` with the clock only after it
            // has built the conversation's memories, so a start that is not
            // before the memory's creation was never read from a transcript.
            let parsed = c.started_at < raw.created_at;
            if !parsed {
                fallbacks.insert(c.id);
            }
            parsed
        })
        .map(|(_, c)| c.started_at)
        .max();
    if let Some(at) = started {
        return (SessionTier::ConversationStart, Some(at));
    }

    if let Some(at) = evidence.first_time(&m.source_id) {
        return (SessionTier::TranscriptStart, Some(at));
    }
    // Consolidation once distilled claude-memory notes, and such a
    // distillate's source_id is the note file rather than a transcript.
    match note_time(m, evidence) {
        Some(at) => (SessionTier::FileMtime, Some(at)),
        None => (SessionTier::Unknown, None),
    }
}

/// A note's mtime dates a memory only while the file is unchanged since the
/// memory was made from it, because a later edit would date it too new.
fn note_time(m: &Memory, evidence: &dyn SessionEvidence) -> Option<DateTime<Utc>> {
    evidence
        .note_modified_at(&m.source_id)
        .filter(|at| *at <= m.created_at)
}

/// Evenly spaced over the dated rows, which are in id order, so the sample
/// spreads across sources and ages instead of clustering on one transcript.
fn sample(dated: &[(&Memory, SessionTier, DateTime<Utc>)]) -> Vec<SessionSample> {
    let step = (dated.len() / SAMPLE_SIZE).max(1);
    dated
        .iter()
        .step_by(step)
        .take(SAMPLE_SIZE)
        .map(|(m, tier, at)| SessionSample {
            id: m.id,
            tier: *tier,
            session_at: *at,
            created_at: m.created_at,
            source: m.source.clone(),
            source_id: m.source_id.clone(),
            content: m.content.chars().take(160).collect(),
        })
        .collect()
}