second-brain-api 0.13.4

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

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use axum::http::StatusCode;
use tower::ServiceExt;

use common::{json_body, post_json};
use second_brain_api::AppState;
use second_brain_api::health::Health;
use second_brain_api::maintenance::{DrainLoop, DrainRequest, WriterSlot};
use second_brain_api::routes;
use second_brain_core::cold::{ArchiveKeys, ColdTier, Kek, KekLabel, Zeroizing};
use second_brain_core::config::MaintenanceConfig;
use second_brain_core::index::{IndexClaim, Indexes};
use second_brain_core::keys::{
    BackupKeys, BackupRestore, KeyStorage, WRAPPED_STORE_KEY_FILE, create_device_keys,
    encrypt_store, every_held_epoch_in, found_identity, load_device_keys, restore_backup_with,
    store_key_for,
};
use second_brain_core::machine::MachineIdentity;
use second_brain_core::schema::{Memory, MemoryType};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::sqlite_store::encrypt_migration::{FileState, db_file_state};
use second_brain_core::store::{Store, StoreAdmin};
use second_brain_core::transcript_archive::TranscriptArchive;

const NOW: i64 = 1_800_000_000_000_000;

struct NoKeys;

impl ArchiveKeys for NoKeys {
    fn current(&self) -> anyhow::Result<Option<Kek>> {
        Ok(None)
    }

    fn by_label(&self, _label: &KekLabel) -> anyhow::Result<Option<Zeroizing<[u8; 32]>>> {
        Ok(None)
    }
}

fn memory(content: &str) -> Memory {
    Memory::new(
        content.to_string(),
        MemoryType::Semantic,
        "test".to_string(),
        String::new(),
    )
}

struct Device {
    _home: tempfile::TempDir,
    data_dir: PathBuf,
    machine: MachineIdentity,
}

/// A paired, encrypted device's data dir, holding everything a live one
/// does that a backup must leave behind.
fn encrypted_device() -> Device {
    let home = tempfile::tempdir().unwrap();
    let data_dir = home.path().join(".second-brain");
    let machine = MachineIdentity::load_or_create(&data_dir).unwrap();
    let device = create_device_keys(&data_dir, &KeyStorage::File).unwrap();
    {
        let store = SqliteStore::open(&data_dir.join("brain.db"), machine.id.clone()).unwrap();
        store.register_machine(&machine).unwrap();
        found_identity(&store, &device, &machine.name, &[], NOW).unwrap();
        for n in 0..3 {
            store
                .store_memory(&memory(&format!("memory {n} kept by the backup")))
                .unwrap();
        }
        encrypt_store(&store, &data_dir, &device).unwrap();
    }
    assert!(data_dir.join(WRAPPED_STORE_KEY_FILE).exists());
    fs::write(data_dir.join("api.token"), "token").unwrap();
    fs::write(
        data_dir.join("brain.db.stale-20260731164409"),
        "SQLite format 3\0",
    )
    .unwrap();
    fs::create_dir_all(data_dir.join("fastembed/models")).unwrap();
    fs::write(data_dir.join("fastembed/models/model.onnx"), "weights").unwrap();
    fs::create_dir_all(data_dir.join("queue")).unwrap();
    fs::write(data_dir.join("queue/0001.sealed"), "queued").unwrap();
    fs::write(data_dir.join("known_hosts"), "peer ssh-ed25519 AAAA\n").unwrap();
    fs::write(home.path().join("shared-config.toml"), "[llm]\n").unwrap();
    std::os::unix::fs::symlink(
        home.path().join("shared-config.toml"),
        data_dir.join("config.toml"),
    )
    .unwrap();
    Device {
        _home: home,
        data_dir,
        machine,
    }
}

fn open_store(device: &Device) -> SqliteStore {
    let keys = load_device_keys(&device.data_dir).unwrap().unwrap();
    let db = device.data_dir.join("brain.db");
    let key = store_key_for(&db, &keys).unwrap();
    SqliteStore::open_with_key(&db, device.machine.id.clone(), &key).unwrap()
}

/// The daemon's state with its drain thread, cold tier and transcript
/// archive running over `device`'s data dir.
fn daemon(device: &Device) -> (axum::Router, Arc<AppState>) {
    let store = open_store(device);
    let db = device.data_dir.join("brain.db");
    let cold = ColdTier::open(second_brain_core::cold::dir_for_db(&db), Arc::new(NoKeys)).unwrap();
    fs::write(cold.dir().join("segment-1.seg"), "sealed segment").unwrap();
    assert!(store.attach_cold_tier(Arc::new(cold)));
    let archive = TranscriptArchive::open(device.data_dir.join("transcripts")).unwrap();
    let transcript = device.data_dir.join("session.jsonl");
    fs::write(&transcript, "{\"line\":\"a session\"}\n").unwrap();
    archive.archive(&transcript).unwrap();
    fs::remove_file(&transcript).unwrap();
    let raw = second_brain_core::index::raw::dir_for_db(&db);
    fs::create_dir_all(&raw).unwrap();
    fs::write(raw.join("meta.json"), "{}").unwrap();

    let base = Arc::into_inner(common::state_in(
        store,
        &device.data_dir,
        second_brain_api::clock_gate::ClockGate::open_for_tests(),
    ))
    .unwrap();
    let index_dir = db.with_extension("indexes");
    let mut writer = Indexes::open(&index_dir).unwrap();
    writer.drain(&base.sqlite).unwrap();
    let reader = Arc::new(RwLock::new(Indexes::open_readonly(&index_dir).unwrap()));
    let claim = IndexClaim::acquire(&index_dir).unwrap();
    let (drain_tx, requests) = std::sync::mpsc::channel::<DrainRequest>();
    DrainLoop {
        store: base.sqlite.clone(),
        reader,
        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: Arc::new(Health::new(chrono::Utc::now(), None)),
    }
    .spawn();
    let state = Arc::new(AppState {
        repair_tx: Some(drain_tx),
        archive: Some(Arc::new(archive)),
        ..base
    });
    (routes::router().with_state(state.clone()), state)
}

async fn backup(app: &axum::Router, dest: &Path) -> (StatusCode, serde_json::Value) {
    let response = app
        .clone()
        .oneshot(post_json(
            "/v1/maintenance/backup",
            serde_json::json!({ "dest": dest }),
        ))
        .await
        .unwrap();
    let status = response.status();
    (status, json_body(response).await)
}

fn names(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = fs::read_dir(dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

#[tokio::test]
async fn a_backup_restores_with_own_keys_to_the_same_memories() {
    let device = encrypted_device();
    let (app, state) = daemon(&device);
    state
        .sqlite
        .store_memory(&memory("written after the drain, before the backup"))
        .unwrap();
    let out = tempfile::tempdir().unwrap();
    let dest = out.path().join("b1");

    let (status, body) = backup(&app, &dest).await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["memory_count"], 4);
    assert_eq!(body["indexes"], "copied");
    assert_eq!(body["raw_index"], "copied");
    assert_eq!(body["outbox_settled"], true);
    assert_eq!(body["path"], dest.to_str().unwrap());
    assert!(!state.gate.is_closed());

    assert_eq!(
        db_file_state(&dest.join("brain.db")).unwrap(),
        FileState::Encrypted
    );
    assert_eq!(
        names(&dest),
        [
            "brain.cold",
            "brain.db",
            "brain.indexes",
            "brain.raw-index",
            "config.toml",
            "known_hosts",
            "queue",
            "store.key.wrapped",
            "transcripts",
        ]
    );
    assert!(dest.join("brain.cold/segment-1.seg").exists());
    assert!(
        fs::symlink_metadata(dest.join("config.toml"))
            .unwrap()
            .is_symlink()
    );
    assert_eq!(
        TranscriptArchive::open(dest.join("transcripts"))
            .unwrap()
            .len(),
        1
    );
    assert_eq!(
        names(out.path()),
        ["b1"],
        "no partial copy is left beside it"
    );

    let at_backup = state.sqlite.live_counts().unwrap();
    state
        .sqlite
        .store_memory(&memory("written after the backup"))
        .unwrap();
    let (reply, compacted) = std::sync::mpsc::channel();
    state
        .repair_tx
        .as_ref()
        .unwrap()
        .send(DrainRequest::CompactIndexes(reply))
        .unwrap();
    compacted
        .recv()
        .unwrap()
        .expect("the drain thread indexes again after the backup");

    let copied = open_store_at(&dest, &device);
    let indexes = Indexes::open_readonly(&dest.join("brain.indexes")).unwrap();
    assert!(indexes.consistent_with(&copied).unwrap());

    let own = every_held_epoch_in(&device.data_dir, &KeyStorage::File).unwrap();
    let home = tempfile::tempdir().unwrap();
    let restored_dir = home.path().join(".second-brain");
    let restored = restore_backup_with(&BackupRestore {
        backup: &dest,
        data_dir: &restored_dir,
        keys: BackupKeys::Epochs(&own),
        storage: &KeyStorage::File,
        now_micros: NOW,
    })
    .unwrap();
    let keys = load_device_keys(&restored_dir).unwrap().unwrap();
    let db = restored_dir.join("brain.db");
    let key = store_key_for(&db, &keys).unwrap();
    let store = SqliteStore::open_with_key(&db, restored.machine.id.clone(), &key).unwrap();
    assert_eq!(store.live_counts().unwrap(), at_backup);
}

#[tokio::test]
async fn a_destination_with_dot_dot_resolves_through_its_real_parent() {
    let device = encrypted_device();
    let (app, _state) = daemon(&device);
    let out = tempfile::tempdir().unwrap();
    fs::create_dir(out.path().join("nested")).unwrap();

    let (status, body) = backup(&app, &out.path().join("nested/../b1")).await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert!(out.path().join("b1/brain.db").exists());
}

#[tokio::test]
async fn agent_writes_stay_live_while_a_backup_holds_maintenance() {
    let dir = tempfile::tempdir().unwrap();
    let state = common::state_with_queue(dir.path().join("queue"));
    let app = second_brain_api::app(state.clone(), "backup-test-token".to_string());
    let (held_tx, held) = std::sync::mpsc::channel();
    let (release_tx, release) = std::sync::mpsc::channel::<()>();
    let gate = state.gate.clone();
    let holder = std::thread::spawn(move || {
        let _held = gate.hold_maintenance();
        held_tx.send(()).unwrap();
        let _ = release.recv();
    });
    held.recv().unwrap();

    let response = app
        .oneshot(
            axum::http::Request::builder()
                .method("POST")
                .uri("/v1/remember")
                .header(
                    axum::http::header::AUTHORIZATION,
                    "Bearer backup-test-token",
                )
                .header(axum::http::header::CONTENT_TYPE, "application/json")
                .body(axum::body::Body::from(
                    serde_json::json!({"content": "written during a backup", "source": "cli"})
                        .to_string(),
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(state.sqlite.memory_count().unwrap(), 1);
    release_tx.send(()).unwrap();
    holder.join().unwrap();
}

fn open_store_at(dir: &Path, device: &Device) -> SqliteStore {
    let keys = load_device_keys(&device.data_dir).unwrap().unwrap();
    let key = store_key_for(&device.data_dir.join("brain.db"), &keys).unwrap();
    SqliteStore::open_with_key(&dir.join("brain.db"), device.machine.id.clone(), &key).unwrap()
}

#[tokio::test]
async fn a_backup_refuses_a_destination_it_could_clobber_or_misplace() {
    let device = encrypted_device();
    let (app, _state) = daemon(&device);
    let out = tempfile::tempdir().unwrap();

    let existing = out.path().join("taken");
    fs::create_dir(&existing).unwrap();
    assert_eq!(backup(&app, &existing).await.0, StatusCode::CONFLICT);
    assert_eq!(
        backup(&app, Path::new("relative/b1")).await.0,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        backup(&app, &device.data_dir.join("inside")).await.0,
        StatusCode::BAD_REQUEST
    );
}

#[tokio::test]
async fn a_partial_copy_left_by_a_killed_backup_is_removed() {
    let device = encrypted_device();
    let (app, _state) = daemon(&device);
    let out = tempfile::tempdir().unwrap();
    let stale = out.path().join(".b1.partial-0123");
    fs::create_dir(&stale).unwrap();
    fs::write(stale.join("brain.db"), "half a copy").unwrap();

    let (status, body) = backup(&app, &out.path().join("b1")).await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(names(out.path()), ["b1"]);
}

#[tokio::test]
async fn an_encrypted_store_without_a_sync_identity_is_refused() {
    let home = tempfile::tempdir().unwrap();
    let data_dir = home.path().join(".second-brain");
    let machine = MachineIdentity::load_or_create(&data_dir).unwrap();
    let device = create_device_keys(&data_dir, &KeyStorage::File).unwrap();
    {
        let store = SqliteStore::open(&data_dir.join("brain.db"), machine.id.clone()).unwrap();
        encrypt_store(&store, &data_dir, &device).unwrap();
    }
    let key = store_key_for(&data_dir.join("brain.db"), &device).unwrap();
    let store =
        SqliteStore::open_with_key(&data_dir.join("brain.db"), machine.id.clone(), &key).unwrap();
    let (app, _store) = common::app_in(store, &data_dir);
    let out = tempfile::tempdir().unwrap();

    let (status, body) = backup(&app, &out.path().join("b1")).await;
    assert_eq!(status, StatusCode::CONFLICT, "{body}");
    assert!(
        body["error"].as_str().unwrap().contains("sb pair"),
        "{body}"
    );
    assert!(names(out.path()).is_empty());
}

#[tokio::test]
async fn a_plaintext_store_backs_up_without_a_wrapped_key() {
    let dir = tempfile::tempdir().unwrap();
    let store = SqliteStore::open(&dir.path().join("brain.db"), "m".into()).unwrap();
    store.store_memory(&memory("plaintext memory")).unwrap();
    let (app, _store) = common::app_in(store, dir.path());
    let out = tempfile::tempdir().unwrap();
    let dest = out.path().join("b1");

    let (status, body) = backup(&app, &dest).await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["indexes"], "unavailable");
    assert_eq!(
        db_file_state(&dest.join("brain.db")).unwrap(),
        FileState::Plaintext
    );
    assert_eq!(
        SqliteStore::open(&dest.join("brain.db"), "m".into())
            .unwrap()
            .memory_count()
            .unwrap(),
        1
    );
}