second-brain-api 0.13.5

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
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
mod common;

use std::path::{Path, PathBuf};
use std::sync::mpsc::Sender;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use anyhow::Result;
use axum::http::StatusCode;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use tower::ServiceExt;

use common::{json_body, post_json, state_in};
use second_brain_api::AppState;
use second_brain_api::clock_gate::ClockGate;
use second_brain_api::ingest::{FileOutcome, capture_transcript, ingest_memory_file};
use second_brain_api::maintenance::{DrainLoop, DrainRequest, WriterSlot};
use second_brain_api::raw_index::{RawCoverage, RawIndexer};
use second_brain_api::routes;
use second_brain_core::cold::{ArchiveKeys, ColdTier, Kek, KekLabel, KeyId, Zeroizing};
use second_brain_core::config::MaintenanceConfig;
use second_brain_core::index::raw::RawIndex;
use second_brain_core::index::{EMBEDDING_DIM, IndexClaim, Indexes};
use second_brain_core::schema::{Memory, MemoryType, SyncEntry, SyncRecord};
use second_brain_core::sqlite_store::{DeleteScope, SqliteStore};
use second_brain_core::store::{Store, StoreAdmin};
use second_brain_core::transcript_archive::TranscriptArchive;

const PROJECT: &str = "-srv-garden";
const GONE: &str = "5e55a000-0000-4000-8000-000000000001";
const KEPT: &str = "5e55a000-0000-4000-8000-000000000002";

fn embed(text: &str) -> Vec<f32> {
    let mut v = vec![0.0f32; EMBEDDING_DIM];
    for word in text.split_whitespace() {
        let slot = word
            .bytes()
            .fold(7usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize));
        v[slot % EMBEDDING_DIM] += 1.0;
    }
    let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);
    v.iter().map(|x| x / norm).collect()
}

struct Keys;

fn label() -> KekLabel {
    KekLabel {
        epoch: 1,
        key_id: KeyId([1; 8]),
    }
}

impl ArchiveKeys for Keys {
    fn current(&self) -> Result<Option<Kek>> {
        Ok(Some(Kek {
            label: label(),
            key: Zeroizing::new([1; 32]),
        }))
    }

    fn by_label(&self, wanted: &KekLabel) -> Result<Option<Zeroizing<[u8; 32]>>> {
        Ok((*wanted == label()).then(|| Zeroizing::new([1; 32])))
    }
}

fn line(session: &str, kind: &str, text: &str) -> String {
    let message = if kind == "assistant" {
        json!({"content": [{"type": "text", "text": text}]})
    } else {
        json!({"content": text})
    };
    json!({"type": kind, "sessionId": session, "timestamp": "2026-10-01T09:30:05Z",
           "message": message})
    .to_string()
}

struct Daemon {
    dir: tempfile::TempDir,
    machine: String,
    state: Arc<AppState>,
    app: axum::Router,
    archive: Arc<TranscriptArchive>,
    raw: Arc<RwLock<RawIndex>>,
    reader: Option<Arc<RwLock<Indexes>>>,
    drain: Option<Sender<DrainRequest>>,
}

fn daemon(machine: &str, with_indexes: bool) -> Daemon {
    let dir = tempfile::tempdir().unwrap();
    let store = SqliteStore::open(&dir.path().join("brain.db"), machine.to_string()).unwrap();
    let tier = Arc::new(ColdTier::open(dir.path().join("brain.cold"), Arc::new(Keys)).unwrap());
    assert!(store.attach_cold_tier(tier));
    let base = Arc::into_inner(state_in(store, dir.path(), ClockGate::open_for_tests())).unwrap();
    let archive = Arc::new(TranscriptArchive::open(dir.path().join("transcripts")).unwrap());
    let raw = Arc::new(RwLock::new(
        RawIndex::open(&dir.path().join("brain.raw-index")).unwrap(),
    ));
    let (reader, drain) = if with_indexes {
        let index_dir = dir.path().join("brain.indexes");
        let mut writer = Indexes::open(&index_dir).unwrap();
        writer.persist().unwrap();
        let reader = Arc::new(RwLock::new(Indexes::open_readonly(&index_dir).unwrap()));
        let claim = IndexClaim::acquire(&index_dir).unwrap();
        let (tx, requests) = std::sync::mpsc::channel();
        DrainLoop {
            store: base.sqlite.clone(),
            reader: reader.clone(),
            writer: WriterSlot::new(writer, claim),
            embedder: None,
            summary: Arc::new(RwLock::new(None)),
            near_duplicates: Arc::new(RwLock::new(None)),
            near_duplicate_threshold: 0.97,
            config: MaintenanceConfig {
                enabled: false,
                interval_secs: 3600,
            },
            requests,
            health: base.health.clone(),
        }
        .spawn();
        (Some(reader), Some(tx))
    } else {
        (None, None)
    };
    let state = Arc::new(AppState {
        indexes: reader.clone(),
        raw_index: Some(raw.clone()),
        archive: Some(archive.clone()),
        repair_tx: drain.clone(),
        ..base
    });
    let app = routes::router().with_state(state.clone());
    Daemon {
        dir,
        machine: machine.to_string(),
        state,
        app,
        archive,
        raw,
        reader,
        drain,
    }
}

impl Daemon {
    fn sqlite(&self) -> &SqliteStore {
        &self.state.sqlite
    }

    fn transcript(&self, session: &str) -> PathBuf {
        self.dir
            .path()
            .join("projects")
            .join(PROJECT)
            .join(format!("{session}.jsonl"))
    }

    fn write_session(&self, session: &str, lines: &[String]) -> PathBuf {
        let path = self.transcript(session);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, lines.join("\n") + "\n").unwrap();
        path
    }

    fn capture(&self, path: &Path) -> FileOutcome {
        let store: Arc<dyn StoreAdmin> = self.state.sqlite.clone();
        capture_transcript(&store, None, Some(&self.archive), path, &self.machine).unwrap()
    }

    fn indexer(&self) -> RawIndexer {
        RawIndexer {
            index: self.raw.clone(),
            archive: Some(self.archive.clone()),
            store: self.state.sqlite.clone(),
            embed: Arc::new(|texts: &[&str]| Ok(texts.iter().map(|t| embed(t)).collect())),
            pause: Duration::ZERO,
            coverage: Arc::new(RawCoverage::new(36500)),
        }
    }

    fn drain_indexes(&self) {
        let (reply, done) = std::sync::mpsc::channel();
        self.drain
            .as_ref()
            .unwrap()
            .send(DrainRequest::CompactIndexes(reply))
            .unwrap();
        done.recv_timeout(Duration::from_secs(60)).unwrap().unwrap();
    }

    fn bm25(&self, words: &str) -> Vec<uuid::Uuid> {
        self.reader
            .as_ref()
            .unwrap()
            .read()
            .unwrap()
            .bm25_search(words, 10)
            .unwrap()
            .into_iter()
            .map(|(id, _)| id)
            .collect()
    }

    fn raw_texts(&self, words: &str) -> Vec<String> {
        let index = self.raw.read().unwrap();
        index
            .bm25_search(words, 10, None)
            .unwrap()
            .into_iter()
            .filter_map(|(key, _)| index.passage(key).unwrap())
            .map(|hit| hit.text)
            .collect()
    }

    fn contents(&self) -> Vec<String> {
        self.sqlite()
            .all_memories_with_embeddings()
            .unwrap()
            .into_iter()
            .map(|m| m.content)
            .collect()
    }

    async fn delete(&self, body: Value) -> (StatusCode, Value) {
        let response = self
            .app
            .clone()
            .oneshot(post_json("/v1/delete", body))
            .await
            .unwrap();
        let status = response.status();
        (status, json_body(response).await)
    }
}

fn old() -> DateTime<Utc> {
    "2026-08-01T12:00:00Z".parse().unwrap()
}

/// Two sessions on one daemon: GONE with a transcript, a note filed under
/// it carrying a vector, and a sealed cold raw; KEPT with a transcript.
fn seeded(d: &Daemon) -> (PathBuf, Memory) {
    let gone = d.write_session(
        GONE,
        &[
            line(GONE, "user", "where does the heron nest these days"),
            line(
                GONE,
                "assistant",
                "The heron nests behind the boathouse on the east bank of the lake, and it returns there every single spring to raise its young.",
            ),
        ],
    );
    let kept = d.write_session(
        KEPT,
        &[
            line(KEPT, "user", "what colour is the shed"),
            line(
                KEPT,
                "assistant",
                "The shed at the bottom of the garden is painted green, and the paint was renewed last summer after the storm damaged it.",
            ),
        ],
    );
    assert_eq!(d.capture(&gone), FileOutcome::Captured);
    assert_eq!(d.capture(&kept), FileOutcome::Captured);

    let mut note = Memory::new(
        "a note about the heron filed under the session".to_string(),
        MemoryType::Semantic,
        "agent-note".to_string(),
        GONE.to_string(),
    )
    .with_project_path(Some(PROJECT.to_string()));
    note.embedding = embed(&note.content);
    d.sqlite().store_memory(&note).unwrap();

    let mut cold = Memory::new(
        "an old heron sighting that went cold".to_string(),
        MemoryType::Episodic,
        "claude-code".to_string(),
        gone.to_string_lossy().into_owned(),
    )
    .with_project_path(Some(PROJECT.to_string()));
    cold.embedding = embed(&cold.content);
    cold.session_at = Some(old());
    d.sqlite().store_memory(&cold).unwrap();
    d.sqlite().archive_memory(cold.id).unwrap();
    d.sqlite().run_stored_redaction(None).unwrap();
    let pass = d
        .sqlite()
        .run_cold_pass(Utc::now(), Duration::ZERO)
        .unwrap();
    assert_eq!(pass.sealed_rows, 1);
    (gone, note)
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deleting_a_session_removes_it_from_every_layer_and_it_is_never_captured_again() {
    let d = daemon("machine-a", true);
    let (gone, note) = seeded(&d);
    d.drain_indexes();
    d.indexer().pass().unwrap();
    assert!(!d.bm25("heron boathouse").is_empty());
    assert!(!d.raw_texts("heron nest").is_empty());
    assert!(d.archive.entry(&gone).is_some());

    let (status, body) = d.delete(json!({"session": GONE})).await;

    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["scope"], "session");
    assert_eq!(body["target"], GONE);
    assert_eq!(body["dry_run"], false);
    assert_eq!(body["drained"], true, "{body}");
    assert_eq!(body["warnings"], json!([]), "{body}");
    assert!(body["removed"]["memories"].as_u64().unwrap() >= 3, "{body}");
    assert_eq!(body["removed"]["conversations"], 1, "{body}");
    assert_eq!(body["layers"]["archive"], 1, "{body}");
    assert_eq!(body["layers"]["cold_records"], 1, "{body}");
    assert!(body["layers"]["raw_index"].as_u64().unwrap() > 0, "{body}");
    assert!(body["layers"]["vector"].as_u64().unwrap() >= 1, "{body}");
    assert!(body["layers"]["bm25"].as_u64().unwrap() >= 2, "{body}");

    assert!(d.contents().iter().all(|c| !c.contains("heron")));
    assert!(d.contents().iter().any(|c| c.contains("shed")));
    assert!(d.bm25("heron boathouse").is_empty());
    let nearest = d
        .reader
        .as_ref()
        .unwrap()
        .read()
        .unwrap()
        .vector_search(d.sqlite(), &note.embedding, 5)
        .unwrap();
    assert!(nearest.iter().all(|(m, _)| *m != note.id));
    assert!(d.raw_texts("heron nest boathouse").is_empty());
    assert!(!d.raw_texts("shed green").is_empty());
    assert!(d.archive.entry(&gone).is_none());
    assert_eq!(d.sqlite().cold_stats().unwrap().rows, 0);

    let mut grown = std::fs::read_to_string(&gone).unwrap();
    grown.push_str(&line(
        GONE,
        "assistant",
        "The heron came back today and stood on the jetty for an hour before it flew off towards the reeds on the far shore.",
    ));
    grown.push('\n');
    std::fs::write(&gone, grown).unwrap();
    assert_eq!(d.capture(&gone), FileOutcome::Skipped);
    d.indexer().pass().unwrap();
    assert!(d.archive.entry(&gone).is_none());
    assert!(d.contents().iter().all(|c| !c.contains("heron")));
    assert!(d.raw_texts("heron").is_empty());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_dry_run_counts_and_leaves_everything_in_place() {
    let d = daemon("machine-a", true);
    let (gone, _) = seeded(&d);
    let before = d.contents().len();

    let (status, body) = d.delete(json!({"session": GONE, "dry_run": true})).await;

    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["dry_run"], true);
    assert!(body["removed"]["memories"].as_u64().unwrap() >= 3, "{body}");
    assert_eq!(body["layers"]["archive"], 1, "{body}");
    assert_eq!(d.contents().len(), before);
    assert!(d.archive.entry(&gone).is_some());
    assert!(!d.sqlite().session_deleted(&gone.to_string_lossy()).unwrap());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_bad_or_empty_scope_is_refused() {
    let d = daemon("machine-a", false);
    seeded(&d);

    for body in [
        json!({}),
        json!({"memory": "not-a-uuid"}),
        json!({"session": GONE, "project": PROJECT}),
        json!({"session": ""}),
        json!({"session": "MEMORY"}),
        json!({"project": "/"}),
    ] {
        let (status, reply) = d.delete(body.clone()).await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{body} -> {reply}");
    }
    let (status, reply) = d
        .delete(json!({"session": "5e55a000-0000-4000-8000-0000000000ff"}))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "{reply}");
    let (status, reply) = d.delete(json!({"project": "-srv-gardne"})).await;
    assert_eq!(status, StatusCode::NOT_FOUND, "{reply}");
    assert!(
        reply["error"].as_str().unwrap().contains(PROJECT),
        "{reply}"
    );
    for body in [
        json!({"project": "/srv/garden", "dry_run": true}),
        json!({"project": "/srv/garden/", "dry_run": true}),
        json!({"session": GONE.to_uppercase(), "dry_run": true}),
    ] {
        let (status, reply) = d.delete(body.clone()).await;
        assert_eq!(status, StatusCode::OK, "{body} -> {reply}");
        assert!(
            reply["removed"]["memories"].as_u64().unwrap() > 0,
            "{reply}"
        );
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn without_open_search_indexes_the_delete_says_their_removal_is_pending() {
    let d = daemon("machine-a", false);
    seeded(&d);

    let (status, body) = d.delete(json!({"project": PROJECT})).await;

    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["drained"], false);
    assert_eq!(body["warnings"].as_array().unwrap().len(), 1, "{body}");
    assert!(d.contents().is_empty());
    assert_eq!(body["layers"]["archive"], 2, "{body}");
}

fn to_record(entry: &SyncEntry) -> SyncRecord {
    SyncRecord {
        local_seq: entry.local_seq as u64,
        origin_machine_id: entry.origin_machine_id.clone(),
        origin_seq: entry.origin_seq as u64,
        op: entry.op,
        node_type: entry.node_type,
        node_id: entry.node_id.clone(),
        timestamp: entry.timestamp,
        data: entry
            .data
            .as_deref()
            .map(|d| serde_json::from_str(d).unwrap()),
    }
}

fn relay(from: &SqliteStore, to: &SqliteStore, after: u64) -> u64 {
    for entry in from.sync_log_since(after).unwrap() {
        to.apply_record(&to_record(&entry)).unwrap();
    }
    from.max_sync_seq().unwrap()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_peer_that_holds_a_copy_of_the_transcript_drops_it_at_its_next_raw_pass() {
    let a = daemon("machine-a", false);
    let b = daemon("machine-b", false);
    let (gone, _) = seeded(&a);
    let on_b = b.write_session(GONE, &[std::fs::read_to_string(&gone).unwrap()]);
    assert_eq!(b.capture(&on_b), FileOutcome::Captured);
    let seen = relay(a.sqlite(), b.sqlite(), 0);
    b.indexer().pass().unwrap();
    assert!(!b.raw_texts("heron nest").is_empty());

    a.sqlite()
        .delete_scope(&DeleteScope::Session(GONE.to_string()), &[GONE.to_string()])
        .unwrap();
    relay(a.sqlite(), b.sqlite(), seen);
    assert!(b.sqlite().session_deleted(&on_b.to_string_lossy()).unwrap());

    let summary = b.indexer().pass().unwrap();
    assert!(summary.purged > 0);
    assert!(b.raw_texts("heron").is_empty());
    assert!(b.archive.entry(&on_b).is_none());
    assert!(b.contents().iter().all(|c| !c.contains("heron")));
    assert_eq!(b.capture(&on_b), FileOutcome::Skipped);
    assert!(b.contents().iter().all(|c| !c.contains("heron")));
}

fn write_note(path: &Path, body: &str) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(
        path,
        format!("---\nname: heron\ndescription: where the heron nests\ntype: project\n---\n{body}"),
    )
    .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_deleted_memory_note_is_not_ingested_again_while_its_file_keeps_the_text() {
    let d = daemon("machine-a", false);
    let store: Arc<dyn StoreAdmin> = d.state.sqlite.clone();
    let note = d
        .dir
        .path()
        .join("projects")
        .join(PROJECT)
        .join("memory")
        .join("heron.md");
    let body = "The heron nests behind the boathouse every spring.\n";
    write_note(&note, body);
    assert_eq!(
        ingest_memory_file(&store, None, &note, &d.machine).unwrap(),
        FileOutcome::Captured
    );
    let id = d
        .sqlite()
        .all_memories_with_embeddings()
        .unwrap()
        .into_iter()
        .find(|m| m.content.contains("heron nests"))
        .unwrap()
        .id;

    let (status, body_json) = d.delete(json!({"memory": id.to_string()})).await;
    assert_eq!(status, StatusCode::OK, "{body_json}");
    assert!(body_json["delete_id"].is_string(), "{body_json}");
    assert!(d.contents().iter().all(|c| !c.contains("heron nests")));

    let head = d.sqlite().max_sync_seq().unwrap();
    write_note(&note, &format!("{body}\n"));
    ingest_memory_file(&store, None, &note, &d.machine).unwrap();
    d.sqlite().clear_reparseable_ingest_log().unwrap();
    ingest_memory_file(&store, None, &note, &d.machine).unwrap();
    assert!(d.contents().iter().all(|c| !c.contains("heron nests")));
    assert_eq!(
        d.sqlite().max_sync_seq().unwrap(),
        head,
        "a blocked note logs nothing, not even its conversation"
    );

    write_note(&note, "The heron moved to the reeds.\n");
    ingest_memory_file(&store, None, &note, &d.machine).unwrap();
    assert!(
        d.contents()
            .iter()
            .any(|c| c.contains("moved to the reeds"))
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_project_delete_status_is_found_by_its_directory() {
    let d = daemon("machine-a", false);
    seeded(&d);
    let (status, body) = d.delete(json!({"project": PROJECT})).await;
    assert_eq!(status, StatusCode::OK, "{body}");

    let response = d
        .app
        .clone()
        .oneshot(common::get("/v1/delete/%2Fsrv%2Fgarden%2F"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let found = json_body(response).await;
    assert_eq!(found["id"], body["delete_id"], "{found}");
    assert_eq!(found["target"], PROJECT);

    let response = d
        .app
        .clone()
        .oneshot(common::get("/v1/delete/nothing-here"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}