second-brain-api 0.12.0

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
use std::sync::RwLock;

use second_brain_core::index::raw::{RawIndex, RawOrigin};
use second_brain_core::redact::redact_for_store;
use second_brain_core::retrieval::RerankScorer;
use second_brain_core::retrieval::raw_fallback::{RawAnswer, judge, raw_candidates};
use second_brain_core::sqlite_store::{RawMemoryState, SqliteStore};
use serde::Serialize;
use uuid::Uuid;

#[derive(Serialize)]
pub(super) struct RawPassageResponse {
    text: String,
    /// When the session the passage comes from happened, if known.
    session_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    project_path: Option<String>,
    relevance: f32,
    /// `transcript` or `archived-memory`.
    origin: &'static str,
    /// The archived memory's id, or the transcript blob's sha256.
    #[serde(rename = "ref")]
    reference: String,
    /// The stored memory this passage stands for, which `forget` withdraws.
    #[serde(skip_serializing_if = "Option::is_none")]
    memory: Option<String>,
}

impl RawPassageResponse {
    pub(super) fn memory_id(&self) -> Option<Uuid> {
        self.memory
            .as_deref()
            .and_then(|id| Uuid::parse_str(id).ok())
    }
}

/// What the hot path concluded. The fallback runs only when abstention was
/// on and left nothing to show, and the recall was not narrowed by type or
/// source, which raw passages do not carry. Nor does it run for a recall
/// with a deadline or an excluded session (the prompt hook's): a raw
/// passage carries no session to exclude, and its rerank is not measured
/// against the hook's budget.
#[derive(Clone, Copy)]
pub(super) struct HotOutcome {
    pub results: usize,
    pub abstention_on: bool,
    pub narrowed: bool,
    pub budgeted: bool,
    pub excludes_session: bool,
}

#[derive(Clone, Copy)]
pub(super) struct RawQuery<'a> {
    pub text: &'a str,
    pub embedding: &'a [f32],
    pub project: Option<&'a str>,
    pub limit: usize,
}

/// Raw passages for a recall nothing hot answered, or none when the hot
/// outcome does not call for them. A failure here only costs the fallback,
/// so it is logged and the recall stays empty.
pub(super) fn fallback(
    index: Option<&RwLock<RawIndex>>,
    scorer: Option<&dyn RerankScorer>,
    hot: HotOutcome,
    sqlite: &SqliteStore,
    query: RawQuery<'_>,
) -> Vec<RawPassageResponse> {
    let (Some(index), Some(scorer)) = (index, scorer) else {
        return Vec::new();
    };
    if hot.results > 0 || !hot.abstention_on || hot.narrowed || hot.budgeted || hot.excludes_session
    {
        return Vec::new();
    }
    match answer(index, scorer, sqlite, query) {
        Ok(passages) => passages,
        Err(e) => {
            tracing::warn!("raw transcript fallback failed: {e:#}");
            Vec::new()
        }
    }
}

fn answer(
    index: &RwLock<RawIndex>,
    scorer: &dyn RerankScorer,
    sqlite: &SqliteStore,
    query: RawQuery<'_>,
) -> anyhow::Result<Vec<RawPassageResponse>> {
    let hits = {
        let guard = index.read().unwrap_or_else(|p| p.into_inner());
        raw_candidates(&guard, query.text, query.embedding, query.project)?
    };
    Ok(judge(query.text, hits, scorer)?
        .into_iter()
        .filter_map(|a| {
            let memory = standing_memory(sqlite, &a)?;
            Some(to_response(a, memory))
        })
        .take(query.limit)
        .collect())
}

/// `None` when the passage must not answer: an archived memory only answers
/// while it stays archived and in force, and a transcript passage stops once
/// the raw memory ingest made from it is forgotten, corrected or deleted.
/// Otherwise the stored memory behind the passage, if there is one.
fn standing_memory(sqlite: &SqliteStore, answer: &RawAnswer) -> Option<Option<Uuid>> {
    let standing = match (&answer.hit.origin, answer.hit.memory) {
        (RawOrigin::Memory { id }, _) => sqlite
            .is_archived_raw(*id)
            .map(|ok| ok.then_some(Some(*id))),
        (RawOrigin::Transcript { .. }, Some(id)) => sqlite.raw_memory_state(id).map(|s| match s {
            RawMemoryState::Withdrawn => None,
            RawMemoryState::InForce { id } => Some(Some(id)),
            RawMemoryState::Unknown => Some(None),
        }),
        (RawOrigin::Transcript { .. }, None) => Ok(Some(None)),
    };
    standing.unwrap_or_else(|e| {
        tracing::warn!("raw passage withheld, its memory could not be checked: {e:#}");
        None
    })
}

fn to_response(answer: RawAnswer, memory: Option<Uuid>) -> RawPassageResponse {
    let (origin, reference) = match answer.hit.origin {
        RawOrigin::Transcript { sha256 } => ("transcript", sha256),
        RawOrigin::Memory { id } => ("archived-memory", id.to_string()),
    };
    RawPassageResponse {
        text: redact_for_store(&answer.hit.text),
        session_at: answer.hit.at.map(|t| t.to_rfc3339()),
        project_path: answer.hit.project,
        relevance: answer.relevance,
        origin,
        reference,
        memory: memory.map(|id| id.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use anyhow::Result;
    use second_brain_core::index::EMBEDDING_DIM;
    use second_brain_core::index::raw::{RawHit, RawPassage};
    use second_brain_core::schema::{Memory, MemoryType};
    use second_brain_core::store::Store;
    use uuid::Uuid;

    #[derive(Default)]
    struct Mirror(AtomicUsize);

    impl RerankScorer for Mirror {
        fn rerank(&self, _: &str, docs: &[&str]) -> Result<Vec<f32>> {
            self.0.fetch_add(1, Ordering::SeqCst);
            Ok(docs
                .iter()
                .map(|d| if d.contains("mirror") { 0.9 } else { 0.0 })
                .collect())
        }
    }

    const ABSTAINED: HotOutcome = HotOutcome {
        results: 0,
        abstention_on: true,
        narrowed: false,
        budgeted: false,
        excludes_session: false,
    };

    fn unit(i: usize) -> Vec<f32> {
        let mut v = vec![0.0; EMBEDDING_DIM];
        v[i] = 1.0;
        v
    }

    fn passage(text: &str, memory: Option<Uuid>) -> RawPassage {
        RawPassage {
            text: text.to_string(),
            at: None,
            project: None,
            memory,
        }
    }

    fn transcript(byte: &str) -> RawOrigin {
        RawOrigin::Transcript {
            sha256: byte.repeat(32),
        }
    }

    struct Fixture {
        _dir: tempfile::TempDir,
        index: RwLock<RawIndex>,
        store: SqliteStore,
        embedding: Vec<f32>,
    }

    impl Fixture {
        fn new(store: SqliteStore, sources: &[(RawOrigin, RawPassage)]) -> Self {
            let dir = tempfile::tempdir().unwrap();
            let mut index = RawIndex::open(dir.path()).unwrap();
            for (origin, passage) in sources {
                index
                    .add_source(origin, &[(passage.clone(), unit(1))])
                    .unwrap();
            }
            index.commit().unwrap();
            Self {
                _dir: dir,
                index: RwLock::new(index),
                store,
                embedding: unit(1),
            }
        }

        fn query(&self, limit: usize) -> RawQuery<'_> {
            RawQuery {
                text: "mirror",
                embedding: &self.embedding,
                project: None,
                limit,
            }
        }

        fn ask(&self, scorer: &dyn RerankScorer, hot: HotOutcome) -> Vec<(&'static str, String)> {
            let mut out: Vec<_> = fallback(
                Some(&self.index),
                Some(scorer),
                hot,
                &self.store,
                self.query(5),
            )
            .into_iter()
            .map(|p| (p.origin, p.text))
            .collect();
            out.sort();
            out
        }
    }

    fn store() -> SqliteStore {
        SqliteStore::in_memory("machine-a".to_string()).unwrap()
    }

    fn raw_memory(store: &SqliteStore, content: &str) -> Uuid {
        let mut m = Memory::new(
            content.to_string(),
            MemoryType::Semantic,
            "claude-code".to_string(),
            String::new(),
        );
        m.embedding = unit(1);
        store.store_memory(&m).unwrap();
        m.id
    }

    #[test]
    fn raw_passages_answer_only_after_the_hot_path_abstained_with_nothing() {
        let f = Fixture::new(
            store(),
            &[(transcript("ab"), passage("the mirror runs nightly", None))],
        );
        let scorer = Mirror::default();

        assert_eq!(
            f.ask(&scorer, ABSTAINED),
            vec![("transcript", "the mirror runs nightly".to_string())]
        );
        for hot in [
            HotOutcome {
                results: 1,
                ..ABSTAINED
            },
            HotOutcome {
                abstention_on: false,
                ..ABSTAINED
            },
            HotOutcome {
                narrowed: true,
                ..ABSTAINED
            },
        ] {
            assert!(f.ask(&scorer, hot).is_empty());
        }
        assert_eq!(scorer.0.load(Ordering::SeqCst), 1);
        assert!(fallback(Some(&f.index), None, ABSTAINED, &f.store, f.query(5)).is_empty());
        assert!(fallback(None, Some(&scorer), ABSTAINED, &f.store, f.query(5)).is_empty());
    }

    #[test]
    fn a_recall_with_a_deadline_or_an_excluded_session_gets_no_raw_passages() {
        let f = Fixture::new(
            store(),
            &[(transcript("ab"), passage("the mirror runs nightly", None))],
        );
        let scorer = Mirror::default();

        for hot in [
            HotOutcome {
                budgeted: true,
                ..ABSTAINED
            },
            HotOutcome {
                excludes_session: true,
                ..ABSTAINED
            },
        ] {
            assert!(f.ask(&scorer, hot).is_empty());
        }
        assert_eq!(scorer.0.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn an_archived_memory_stops_answering_once_it_is_retired() {
        let s = store();
        let id = raw_memory(&s, "the mirror token rotates monthly");
        s.archive_memory(id).unwrap();
        let f = Fixture::new(
            s,
            &[
                (transcript("ab"), passage("the mirror runs nightly", None)),
                (
                    RawOrigin::Memory { id },
                    passage("the mirror token rotates monthly", Some(id)),
                ),
            ],
        );
        let scorer = Mirror::default();

        assert_eq!(f.ask(&scorer, ABSTAINED).len(), 2);
        f.store.retire_memory(id, "wrong").unwrap();
        assert_eq!(
            f.ask(&scorer, ABSTAINED),
            vec![("transcript", "the mirror runs nightly".to_string())]
        );
    }

    #[test]
    fn a_transcript_passage_stops_answering_once_its_raw_memory_is_forgotten() {
        let s = store();
        let id = raw_memory(&s, "the mirror key lives in the vault");
        let f = Fixture::new(
            s,
            &[(
                transcript("ab"),
                passage("the mirror key lives in the vault", Some(id)),
            )],
        );
        let scorer = Mirror::default();

        let served = fallback(
            Some(&f.index),
            Some(&scorer),
            ABSTAINED,
            &f.store,
            f.query(5),
        );
        assert_eq!(served[0].memory, Some(id.to_string()));
        f.store.retire_memory(id, "should not exist").unwrap();
        assert!(f.ask(&scorer, ABSTAINED).is_empty());
    }

    #[test]
    fn served_text_is_redacted_with_the_current_rules() {
        let token = ["gh", "p_"].concat() + &"a1B2".repeat(9);
        let f = Fixture::new(
            store(),
            &[(
                transcript("ab"),
                passage(&format!("the mirror reads {token}"), None),
            )],
        );

        let served = f.ask(&Mirror::default(), ABSTAINED);

        assert_eq!(served.len(), 1);
        assert!(!served[0].1.contains(&token), "{}", served[0].1);
        assert!(served[0].1.contains("[REDACTED:"), "{}", served[0].1);
    }

    #[test]
    fn withdrawn_passages_do_not_shorten_the_answer_below_the_limit() {
        let s = store();
        let gone = raw_memory(&s, "the mirror moved to the old host");
        s.retire_memory(gone, "wrong").unwrap();
        let f = Fixture::new(
            s,
            &[
                (
                    transcript("ab"),
                    passage("the mirror moved to the old host", Some(gone)),
                ),
                (
                    transcript("cd"),
                    passage("the mirror moved to the new host", None),
                ),
            ],
        );

        let served = fallback(
            Some(&f.index),
            Some(&Mirror::default()),
            ABSTAINED,
            &f.store,
            f.query(1),
        );

        assert_eq!(served.len(), 1);
        assert_eq!(served[0].text, "the mirror moved to the new host");
    }

    fn answer(origin: RawOrigin) -> RawAnswer {
        RawAnswer {
            hit: RawHit {
                key: 1,
                text: "the mirror moved".to_string(),
                at: None,
                project: None,
                memory: None,
                origin,
            },
            relevance: 0.9,
        }
    }

    #[test]
    fn memory_id_reads_back_the_served_memory() {
        let id = Uuid::new_v4();
        assert_eq!(
            to_response(answer(RawOrigin::Memory { id }), Some(id)).memory_id(),
            Some(id)
        );
        assert_eq!(
            to_response(answer(transcript("ab")), None).memory_id(),
            None
        );

        let mut malformed = to_response(answer(transcript("ab")), Some(id));
        malformed.memory = Some("not-a-uuid".to_string());
        assert_eq!(malformed.memory_id(), None);
    }
}