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
use std::collections::{BTreeMap, HashMap, HashSet};

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::schema::{Conversation, Memory};
use crate::sqlite_store::{AgentNote, NoteKind, SqliteStore};

pub const DEFAULT_WINDOW: &str = "24h";

pub const MAX_ITEMS_PER_SECTION: usize = 5;

const MAX_WINDOW_MINUTES: i64 = 3652 * 24 * 60;

const NO_PROJECT: &str = "(no project)";

const TIME_FORMAT: &str = "%Y-%m-%d %H:%M";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Window {
    pub since: DateTime<Utc>,
    pub until: DateTime<Utc>,
}

impl Window {
    /// The span `text` names (`90m`, `24h`, `7d`) ending at `until`.
    pub fn parse(text: &str, until: DateTime<Utc>) -> Result<Window, String> {
        let text = text.trim();
        let invalid = || {
            format!(
                "invalid window '{text}': give a whole number of minutes, hours or days \
                 up to ten years, like 90m, 24h or 7d"
            )
        };
        let mut chars = text.chars();
        let minutes_per_unit = match chars.next_back() {
            Some('m') => 1,
            Some('h') => 60,
            Some('d') => 24 * 60,
            _ => return Err(invalid()),
        };
        let count = chars.as_str();
        if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) {
            return Err(invalid());
        }
        let minutes = count
            .parse::<i64>()
            .ok()
            .and_then(|count| count.checked_mul(minutes_per_unit))
            .filter(|minutes| (1..=MAX_WINDOW_MINUTES).contains(minutes))
            .ok_or_else(invalid)?;
        Ok(Window {
            since: until - Duration::minutes(minutes),
            until,
        })
    }

    fn describe(&self) -> String {
        format!(
            "{} to {} UTC",
            self.since.format(TIME_FORMAT),
            self.until.format(TIME_FORMAT)
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DigestItem {
    pub text: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reason: String,
    /// How many notes said it; duplicates are merged into one item.
    pub count: usize,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DigestSection {
    pub items: Vec<DigestItem>,
    /// Items past `MAX_ITEMS_PER_SECTION`, left out.
    pub omitted: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProjectDigest {
    pub project: Option<String>,
    pub noted_sessions: usize,
    pub unnoted_sessions: usize,
    pub decided: DigestSection,
    pub abandoned: DigestSection,
    pub blocked_on_user: DigestSection,
}

/// What agents recorded in their notes over a window, per project, and how
/// many sessions in it have none.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Digest {
    pub window: Window,
    pub project: Option<String>,
    pub projects: Vec<ProjectDigest>,
}

impl Digest {
    pub fn read(
        store: &SqliteStore,
        window: Window,
        project: Option<&str>,
    ) -> anyhow::Result<Digest> {
        let notes = store.notes_created_between(window.since, window.until, project)?;
        let noted: HashSet<Uuid> = store
            .noted_session_ids()?
            .iter()
            .map(|session| Conversation::claude_code_id(session))
            .collect();
        let unnoted: Vec<Option<String>> = store
            .claude_code_sessions_between(window.since, window.until, project)?
            .into_iter()
            .filter(|session| !noted.contains(&session.conversation_id))
            .map(|session| session.project_path)
            .collect();
        Ok(Digest::assemble(
            window,
            project.map(str::to_string),
            &notes,
            &unnoted,
        ))
    }

    /// `notes` newest first; `unnoted` holds the project of each session in
    /// the window that has no note.
    pub fn assemble(
        window: Window,
        project: Option<String>,
        notes: &[(Memory, AgentNote)],
        unnoted: &[Option<String>],
    ) -> Digest {
        let mut projects: BTreeMap<(bool, String), ProjectBuilder> = BTreeMap::new();
        for (index, (memory, note)) in notes.iter().enumerate() {
            let builder = projects
                .entry(project_key(&memory.project_path))
                .or_default();
            builder.sessions.insert(&memory.source_id);
            match note.kind {
                NoteKind::SessionEnd | NoteKind::Decision => {
                    builder.decided.add(&note.decision, &note.reason, index)
                }
                NoteKind::DeadEnd => builder.abandoned.add(&note.decision, &note.reason, index),
                NoteKind::Fact => {}
            }
            for dead_end in &note.dead_ends {
                builder.abandoned.add(dead_end, "", index);
            }
            for blocked in &note.blocked_on_user {
                builder.blocked_on_user.add(blocked, "", index);
            }
        }
        for project in unnoted {
            projects.entry(project_key(project)).or_default().unnoted += 1;
        }
        let projects = projects
            .into_iter()
            .filter_map(|((unnamed, name), builder)| builder.finish((!unnamed).then_some(name)))
            .collect();
        Digest {
            window,
            project,
            projects,
        }
    }

    pub fn render(&self) -> String {
        let span = self.window.describe();
        let scope = self
            .project
            .as_ref()
            .map(|project| format!(" for {project}"))
            .unwrap_or_default();
        if self.projects.is_empty() {
            return format!("Nothing recorded{scope} from {span}.");
        }
        let mut out = format!("Agent digest{scope}, {span}");
        for project in &self.projects {
            out.push_str("\n\n");
            project.render_into(&mut out);
        }
        out
    }
}

impl ProjectDigest {
    fn render_into(&self, out: &mut String) {
        let mut counts = Vec::new();
        if self.noted_sessions > 0 {
            counts.push(sessions(self.noted_sessions, "with notes"));
        }
        if self.unnoted_sessions > 0 {
            counts.push(sessions(self.unnoted_sessions, "without a note"));
        }
        out.push_str(self.project.as_deref().unwrap_or(NO_PROJECT));
        out.push_str(": ");
        out.push_str(&counts.join(", "));
        for (title, section) in [
            ("Decided", &self.decided),
            ("Tried and abandoned", &self.abandoned),
            ("Blocked on you", &self.blocked_on_user),
        ] {
            if section.items.is_empty() {
                continue;
            }
            out.push_str(&format!("\n  {title}:"));
            for item in &section.items {
                out.push_str(&format!("\n  - {}", item.text));
                if item.count > 1 {
                    out.push_str(&format!(" ({} notes)", item.count));
                }
                if !item.reason.is_empty() {
                    out.push_str(&format!("\n    why: {}", item.reason));
                }
            }
            if section.omitted > 0 {
                out.push_str(&format!("\n  and {} more", section.omitted));
            }
        }
    }
}

fn sessions(count: usize, what: &str) -> String {
    let noun = if count == 1 { "session" } else { "sessions" };
    format!("{count} {noun} {what}")
}

/// Named projects sort by name and come before notes filed under none.
fn project_key(project: &Option<String>) -> (bool, String) {
    (project.is_none(), project.clone().unwrap_or_default())
}

/// Case, spacing and closing punctuation don't make two items different.
fn merge_key(text: &str) -> String {
    text.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .trim_end_matches(['.', '!', '?', ',', ';', ':'])
        .trim_end()
        .to_lowercase()
}

#[derive(Default)]
struct SectionBuilder {
    items: Vec<DigestItem>,
    by_key: HashMap<String, (usize, usize)>,
}

impl SectionBuilder {
    /// Counts each note once however often it repeats an item; the first
    /// wording seen is kept, and the first reason given.
    fn add(&mut self, text: &str, reason: &str, note: usize) {
        let key = merge_key(text);
        if key.is_empty() {
            return;
        }
        match self.by_key.get_mut(&key) {
            Some((at, last_note)) => {
                let item = &mut self.items[*at];
                if *last_note != note {
                    item.count += 1;
                    *last_note = note;
                }
                if item.reason.is_empty() {
                    item.reason = reason.to_string();
                }
            }
            None => {
                self.by_key.insert(key, (self.items.len(), note));
                self.items.push(DigestItem {
                    text: text.to_string(),
                    reason: reason.to_string(),
                    count: 1,
                });
            }
        }
    }

    fn finish(mut self) -> DigestSection {
        let omitted = self.items.len().saturating_sub(MAX_ITEMS_PER_SECTION);
        self.items.truncate(MAX_ITEMS_PER_SECTION);
        DigestSection {
            items: self.items,
            omitted,
        }
    }
}

#[derive(Default)]
struct ProjectBuilder<'a> {
    sessions: HashSet<&'a str>,
    unnoted: usize,
    decided: SectionBuilder,
    abandoned: SectionBuilder,
    blocked_on_user: SectionBuilder,
}

impl ProjectBuilder<'_> {
    /// None when the project has nothing to show: only fact notes and no
    /// session without a note.
    fn finish(self, project: Option<String>) -> Option<ProjectDigest> {
        let digest = ProjectDigest {
            project,
            noted_sessions: self.sessions.len(),
            unnoted_sessions: self.unnoted,
            decided: self.decided.finish(),
            abandoned: self.abandoned.finish(),
            blocked_on_user: self.blocked_on_user.finish(),
        };
        let shows_something = digest.unnoted_sessions > 0
            || !digest.decided.items.is_empty()
            || !digest.abandoned.items.is_empty()
            || !digest.blocked_on_user.items.is_empty();
        shows_something.then_some(digest)
    }
}

#[cfg(test)]
mod tests {
    use chrono::TimeZone;

    use super::*;
    use crate::schema::{AGENT_NOTE_SOURCE, Conversation, MemoryType};
    use crate::store::Store;

    fn now() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 11, 2, 8, 0, 0).unwrap()
    }

    fn hours_ago(hours: i64) -> DateTime<Utc> {
        now() - Duration::hours(hours)
    }

    fn day() -> Window {
        Window::parse("24h", now()).unwrap()
    }

    fn note(
        store: &SqliteStore,
        session: &str,
        project: &str,
        hours: i64,
        note: AgentNote,
    ) -> Memory {
        let mut memory = Memory::new(
            note.render(),
            note.kind.memory_type(),
            AGENT_NOTE_SOURCE.to_string(),
            session.to_string(),
        )
        .with_project_path((!project.is_empty()).then(|| project.to_string()));
        memory.created_at = hours_ago(hours);
        store.store_memory(&memory).unwrap();
        memory
    }

    fn transcript_line(store: &SqliteStore, path: &str, session: &str, project: &str, hours: i64) {
        let mut memory = Memory::new(
            format!("{path} {hours}"),
            MemoryType::Episodic,
            "claude-code".to_string(),
            path.to_string(),
        )
        .with_project_path(Some(project.to_string()));
        memory.conversation_id = Some(Conversation::claude_code_id(session));
        memory.session_at = Some(hours_ago(hours));
        store.store_memory(&memory).unwrap();
    }

    fn strings(items: &[&str]) -> Vec<String> {
        items.iter().map(|item| item.to_string()).collect()
    }

    fn three_projects() -> SqliteStore {
        let store = SqliteStore::in_memory("m".to_string()).unwrap();

        let mut cache = AgentNote::new(NoteKind::SessionEnd, "keep the build cache per worktree");
        cache.reason = "a shared cache mixed crates between branches".to_string();
        cache.dead_ends = strings(&["one shared target dir"]);
        cache.open_items = strings(&["rerun the flaky test"]);
        cache.blocked_on_user = strings(&["approve the signing key"]);
        note(&store, "s1", "-srv-app", 20, cache);
        transcript_line(&store, "/p/-srv-app/s1.jsonl", "s1", "-srv-app", 21);
        note(
            &store,
            "s2",
            "-srv-app",
            18,
            AgentNote::new(NoteKind::Decision, "Keep the build  cache per worktree."),
        );
        let mut raced = AgentNote::new(NoteKind::DeadEnd, "One shared target dir");
        raced.reason = "two builds raced on it".to_string();
        note(&store, "s2", "-srv-app", 17, raced);
        transcript_line(&store, "/p/-srv-app/s9.jsonl", "s9", "-srv-app", 3);
        note(
            &store,
            "s0",
            "-srv-app",
            30,
            AgentNote::new(NoteKind::Decision, "an older decision"),
        );
        transcript_line(&store, "/p/-srv-app/s0.jsonl", "s0", "-srv-app", 2);
        let retired = note(
            &store,
            "s8",
            "-srv-app",
            5,
            AgentNote::new(NoteKind::Decision, "a retired decision"),
        );
        store.retire_memory(retired.id, "test").unwrap();

        let mut router = AgentNote::new(NoteKind::SessionEnd, "split the router table by concern");
        router.blocked_on_user = strings(&[
            "pick a port",
            "name the crate",
            "confirm the license",
            "review the API shape",
            "choose a release date",
            "approve the CI secret",
            "sign off the docs",
        ]);
        note(&store, "s3", "-srv-web", 9, router);
        note(
            &store,
            "s4",
            "-srv-web",
            8,
            AgentNote::new(NoteKind::Fact, "the port is 7300"),
        );

        transcript_line(&store, "/p/-srv-tools/s5.jsonl", "s5", "-srv-tools", 6);
        transcript_line(&store, "/p/-srv-tools/s6.jsonl", "s6", "-srv-tools", 4);
        transcript_line(
            &store,
            "/p/-srv-tools/s6/subagents/agent-a.jsonl",
            "s6/a",
            "-srv-tools",
            4,
        );
        transcript_line(&store, "/p/-srv-tools/s7.jsonl", "s7", "-srv-tools", 30);
        let mut toolchain = AgentNote::new(NoteKind::SessionEnd, "pin the toolchain");
        toolchain.blocked_on_user = strings(&["Ship on Friday?", "ship on  friday"]);
        note(&store, "s5", "-srv-tools", 5, toolchain);

        note(
            &store,
            "s10",
            "",
            7,
            AgentNote::new(NoteKind::Decision, "retire the old sync timer"),
        );
        store
    }

    #[test]
    fn notes_from_three_projects_give_the_expected_text() {
        let store = three_projects();
        let digest = Digest::read(&store, day(), None).unwrap();
        assert_eq!(
            digest.render(),
            "Agent digest, 2026-11-01 08:00 to 2026-11-02 08:00 UTC\n\
             \n\
             -srv-app: 2 sessions with notes, 1 session without a note\n\
             \x20 Decided:\n\
             \x20 - Keep the build cache per worktree. (2 notes)\n\
             \x20   why: a shared cache mixed crates between branches\n\
             \x20 Tried and abandoned:\n\
             \x20 - One shared target dir (2 notes)\n\
             \x20   why: two builds raced on it\n\
             \x20 Blocked on you:\n\
             \x20 - approve the signing key\n\
             \n\
             -srv-tools: 1 session with notes, 1 session without a note\n\
             \x20 Decided:\n\
             \x20 - pin the toolchain\n\
             \x20 Blocked on you:\n\
             \x20 - Ship on Friday?\n\
             \n\
             -srv-web: 2 sessions with notes\n\
             \x20 Decided:\n\
             \x20 - split the router table by concern\n\
             \x20 Blocked on you:\n\
             \x20 - pick a port\n\
             \x20 - name the crate\n\
             \x20 - confirm the license\n\
             \x20 - review the API shape\n\
             \x20 - choose a release date\n\
             \x20 and 2 more\n\
             \n\
             (no project): 1 session with notes\n\
             \x20 Decided:\n\
             \x20 - retire the old sync timer"
        );
    }

    #[test]
    fn a_project_filter_keeps_one_project() {
        let store = three_projects();
        let digest = Digest::read(&store, day(), Some("-srv-tools")).unwrap();
        assert_eq!(
            digest.render(),
            "Agent digest for -srv-tools, 2026-11-01 08:00 to 2026-11-02 08:00 UTC\n\
             \n\
             -srv-tools: 1 session with notes, 1 session without a note\n\
             \x20 Decided:\n\
             \x20 - pin the toolchain\n\
             \x20 Blocked on you:\n\
             \x20 - Ship on Friday?"
        );
    }

    #[test]
    fn an_empty_window_prints_one_line() {
        let store = three_projects();
        let window = Window::parse("90m", now() - Duration::days(30)).unwrap();
        assert_eq!(
            Digest::read(&store, window, None).unwrap().render(),
            "Nothing recorded from 2026-10-03 06:30 to 2026-10-03 08:00 UTC."
        );
        let empty = SqliteStore::in_memory("m".to_string()).unwrap();
        assert_eq!(
            Digest::read(&empty, day(), Some("-srv-app"))
                .unwrap()
                .render(),
            "Nothing recorded for -srv-app from 2026-11-01 08:00 to 2026-11-02 08:00 UTC."
        );
    }

    #[test]
    fn a_digest_survives_json() {
        let digest = Digest::read(&three_projects(), day(), None).unwrap();
        let json = serde_json::to_string(&digest).unwrap();
        assert_eq!(serde_json::from_str::<Digest>(&json).unwrap(), digest);
    }

    #[test]
    fn a_window_is_minutes_hours_or_days() {
        for (text, span) in [
            ("90m", Duration::minutes(90)),
            ("24h", Duration::hours(24)),
            (" 7d ", Duration::days(7)),
        ] {
            assert_eq!(
                Window::parse(text, now()),
                Ok(Window {
                    since: now() - span,
                    until: now(),
                }),
                "{text}"
            );
        }
        for text in ["", "24", "h", "0h", "-1h", "1.5h", "24x", "99999999999d"] {
            assert!(Window::parse(text, now()).is_err(), "{text:?}");
        }
    }
}