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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail, ensure};
use chrono::{DateTime, NaiveDateTime};

use super::device::sync_dir;
use super::{KeyStorage, open_device_store};
use crate::machine::MachineIdentity;
use crate::sqlite_store::SqliteStore;
use crate::sqlite_store::encrypt_migration::{FileState, db_file_state};

/// How long a data dir moved aside by a restore or a pairing is kept
/// before the daemon deletes it.
pub const ASIDE_RETENTION_MICROS: i64 = 90 * 86_400 * 1_000_000;

pub(super) const RESTORE_MARKER: &str = ".before-restore-";
const PAIR_MARKER: &str = ".before-pair-";
const ASIDE_MARKERS: &[&str] = &[RESTORE_MARKER, PAIR_MARKER];
const DB_FILE: &str = "brain.db";
const MACHINE_FILE: &str = "machine.toml";
/// Host files a data dir moved aside for pairing leaves in its fresh
/// replacement.
const KEPT_HOST_FILES: &[&str] = &["config.toml", "service.json"];
const STAMP_FORMAT: &str = "%Y%m%d-%H%M%S";
const STAMP_LEN: usize = 15;

/// A data dir moved aside beside `data_dir` and when it was moved, read
/// from its name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MovedAside {
    pub path: PathBuf,
    pub moved_at_micros: i64,
}

/// The data dirs a restore or a pairing moved aside beside `data_dir`. Symlinks and
/// names whose stamp does not parse are left out, so nothing else is ever
/// taken for one.
pub fn moved_aside_dirs(data_dir: &Path) -> Result<Vec<MovedAside>> {
    let (Some(parent), Some(base)) = (data_dir.parent(), data_dir.file_name()) else {
        return Ok(Vec::new());
    };
    let base = base.to_string_lossy();
    let entries = match fs::read_dir(parent) {
        Ok(entries) => entries,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e).with_context(|| format!("reading {}", parent.display())),
    };
    let mut found = Vec::new();
    for entry in entries {
        let entry = entry?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        let Some(stamp) = ASIDE_MARKERS
            .iter()
            .find_map(|marker| name.strip_prefix(&*base)?.strip_prefix(marker))
        else {
            continue;
        };
        let Some(moved_at_micros) = parse_stamp(stamp) else {
            continue;
        };
        if !entry.file_type()?.is_dir() {
            continue;
        }
        found.push(MovedAside {
            path: entry.path(),
            moved_at_micros,
        });
    }
    found.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(found)
}

/// Deletes the moved-aside data dirs older than `ASIDE_RETENTION_MICROS`
/// and returns them. One that cannot be deleted is logged and does not stop
/// the others.
pub fn remove_expired_asides(data_dir: &Path, now_micros: i64) -> Result<Vec<PathBuf>> {
    let mut removed = Vec::new();
    for aside in moved_aside_dirs(data_dir)? {
        if now_micros.saturating_sub(aside.moved_at_micros) < ASIDE_RETENTION_MICROS {
            continue;
        }
        match fs::remove_dir_all(&aside.path) {
            Ok(()) => removed.push(aside.path),
            Err(e) => tracing::warn!("could not delete {}: {e}", aside.path.display()),
        }
    }
    Ok(removed)
}

/// Moves `data_dir` aside to `<base>.before-pair-<stamp>` and puts an empty
/// private dir in its place holding only the host's config.toml and
/// service.json, plus an empty file for each name in `marks`. The moved dir
/// keeps its own machine id and keys, so
/// `open_moved_aside` still reads it. When a step after the rename fails,
/// the old dir is moved back.
pub fn move_aside_for_pairing(data_dir: &Path, now_micros: i64, marks: &[&str]) -> Result<PathBuf> {
    let meta = fs::symlink_metadata(data_dir)
        .with_context(|| format!("reading {}", data_dir.display()))?;
    ensure!(
        !meta.file_type().is_symlink(),
        "{} is a symlink; only a real data dir is moved aside",
        data_dir.display()
    );
    ensure!(meta.is_dir(), "{} is not a directory", data_dir.display());
    let parent = match data_dir.parent() {
        Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
        Some(_) => PathBuf::from("."),
        None => bail!("{} has no parent directory", data_dir.display()),
    };
    let base = data_dir
        .file_name()
        .ok_or_else(|| anyhow!("{} has no directory name", data_dir.display()))?
        .to_string_lossy();
    let aside = aside_path(&parent, &base, PAIR_MARKER, now_micros);
    fs::rename(data_dir, &aside)
        .with_context(|| format!("moving {} aside to {}", data_dir.display(), aside.display()))?;
    if let Err(e) = create_private_dir(data_dir) {
        return Err(put_back(e, &aside, data_dir, false));
    }
    let carried = KEPT_HOST_FILES
        .iter()
        .try_for_each(|name| carry_over(&aside.join(name), &data_dir.join(name)))
        .and_then(|()| {
            marks.iter().try_for_each(|name| {
                let path = data_dir.join(name);
                fs::write(&path, b"").with_context(|| format!("writing {}", path.display()))
            })
        })
        .and_then(|()| sync_dir(data_dir))
        .and_then(|()| sync_dir(&parent));
    match carried {
        Ok(()) => Ok(aside),
        Err(e) => Err(put_back(e, &aside, data_dir, true)),
    }
}

fn put_back(error: anyhow::Error, aside: &Path, data_dir: &Path, created: bool) -> anyhow::Error {
    let cleared = if created {
        fs::remove_dir_all(data_dir)
    } else {
        Ok(())
    };
    match cleared.and_then(|()| fs::rename(aside, data_dir)) {
        Ok(()) => error,
        Err(back) => error.context(format!(
            "the data dir is now {} and could not be moved back to {} ({back})",
            aside.display(),
            data_dir.display()
        )),
    }
}

/// Opens the store of a data dir moved aside under the machine id and keys
/// that dir holds. Nothing missing is created in it.
pub fn open_moved_aside(aside: &Path) -> Result<SqliteStore> {
    let machine_file = aside.join(MACHINE_FILE);
    let machine = MachineIdentity::load(aside)
        .with_context(|| format!("reading {}", machine_file.display()))?
        .ok_or_else(|| anyhow!("{} is missing", machine_file.display()))?;
    let db = aside.join(DB_FILE);
    ensure!(
        db_file_state(&db)? != FileState::Absent,
        "{} is missing or empty",
        db.display()
    );
    let opened =
        open_device_store(&db, aside, machine.id, &KeyStorage::detect_for(aside)).map(|o| o.store);
    opened.with_context(|| format!("opening {}", db.display()))
}

/// Where `<base>` moves aside under `marker` at `now_micros`, beside it in
/// `parent`, in the form `moved_aside_dirs` reads back.
pub(super) fn aside_path(parent: &Path, base: &str, marker: &str, now_micros: i64) -> PathBuf {
    let stamp = DateTime::from_timestamp_micros(now_micros)
        .unwrap_or_default()
        .format(STAMP_FORMAT);
    free_path(parent, &format!("{base}{marker}{stamp}"))
}

fn free_path(parent: &Path, name: &str) -> PathBuf {
    let first = parent.join(name);
    if !first.exists() {
        return first;
    }
    (2..)
        .map(|n| parent.join(format!("{name}-{n}")))
        .find(|p| !p.exists())
        .unwrap_or(first)
}

pub(super) fn carry_over(from: &Path, to: &Path) -> Result<()> {
    match fs::copy(from, to).and_then(|_| fs::File::open(to)?.sync_all()) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e).with_context(|| format!("copying {} to {}", from.display(), to.display())),
    }
}

pub(super) fn create_private_dir(dir: &Path) -> Result<()> {
    let mut builder = fs::DirBuilder::new();
    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut builder, crate::private_files::PRIVATE_DIR_MODE);
    builder
        .create(dir)
        .with_context(|| format!("creating {}", dir.display()))
}

/// `free_path` adds `-<n>` when the stamped name is taken.
fn parse_stamp(rest: &str) -> Option<i64> {
    let stamp = rest.get(..STAMP_LEN)?;
    let suffix = &rest[STAMP_LEN..];
    if !suffix.is_empty()
        && !suffix
            .strip_prefix('-')
            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
    {
        return None;
    }
    let moved = NaiveDateTime::parse_from_str(stamp, STAMP_FORMAT).ok()?;
    Some(moved.and_utc().timestamp_micros())
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::machine::MachineIdentity;
    use crate::schema::{Memory, MemoryType};
    use crate::store::Store;

    const DAY: i64 = 86_400 * 1_000_000;

    fn micros(stamp: &str) -> i64 {
        parse_stamp(stamp).unwrap()
    }

    #[test]
    fn asides_older_than_ninety_days_are_deleted_and_nothing_else() {
        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join(".second-brain");
        fs::create_dir(&data_dir).unwrap();
        let old = home
            .path()
            .join(".second-brain.before-restore-20260101-120000");
        let old_again = home
            .path()
            .join(".second-brain.before-restore-20260101-120000-2");
        let recent = home
            .path()
            .join(".second-brain.before-restore-20260301-000000");
        let unrelated = home.path().join(".second-brain.before-restore-notes");
        let other_base = home.path().join(".other.before-restore-20260101-120000");
        let file = home
            .path()
            .join(".second-brain.before-restore-20250101-000000");
        for dir in [&old, &old_again, &recent, &unrelated, &other_base] {
            fs::create_dir(dir).unwrap();
            fs::write(dir.join("brain.db"), b"x").unwrap();
        }
        fs::write(&file, b"not a dir").unwrap();
        let link = home
            .path()
            .join(".second-brain.before-restore-20250102-000000");
        std::os::unix::fs::symlink(&data_dir, &link).unwrap();

        let now = micros("20260101-120000") + 90 * DAY;
        let removed = remove_expired_asides(&data_dir, now).unwrap();
        assert_eq!(removed, vec![old.clone(), old_again.clone()]);
        assert!(!old.exists() && !old_again.exists());
        for kept in [&recent, &unrelated, &other_base, &file, &data_dir] {
            assert!(kept.exists(), "{} must stay", kept.display());
        }
        assert!(fs::symlink_metadata(&link).is_ok());
        assert!(data_dir.exists());

        assert!(
            remove_expired_asides(&data_dir, now - 1)
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn an_aside_that_cannot_be_deleted_does_not_stop_the_others() {
        use std::os::unix::fs::PermissionsExt;

        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join(".second-brain");
        fs::create_dir(&data_dir).unwrap();
        let stuck = home
            .path()
            .join(".second-brain.before-restore-20250101-000000");
        let gone = home
            .path()
            .join(".second-brain.before-restore-20250102-000000");
        for dir in [&stuck, &gone] {
            fs::create_dir_all(dir.join("indexes")).unwrap();
            fs::write(dir.join("indexes").join("seg"), b"x").unwrap();
        }
        fs::set_permissions(stuck.join("indexes"), fs::Permissions::from_mode(0o500)).unwrap();

        let now = micros("20260601-000000");
        let removed = remove_expired_asides(&data_dir, now);
        fs::set_permissions(stuck.join("indexes"), fs::Permissions::from_mode(0o700)).unwrap();
        assert_eq!(removed.unwrap(), vec![gone.clone()]);
        assert!(!gone.exists());
        assert!(stuck.exists());
    }

    #[test]
    fn a_stamp_with_trailing_text_is_not_an_aside() {
        assert!(parse_stamp("20260101-120000").is_some());
        assert!(parse_stamp("20260101-120000-12").is_some());
        assert!(parse_stamp("20260101-120000-").is_none());
        assert!(parse_stamp("20260101-120000x").is_none());
        assert!(parse_stamp("2026").is_none());
    }

    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
    }

    fn populated_data_dir(home: &Path) -> PathBuf {
        let data_dir = home.join(".second-brain");
        fs::create_dir(&data_dir).unwrap();
        for (name, body) in [
            ("brain.db", "db"),
            ("machine.toml", "machine"),
            ("device.key", "device"),
            ("store.key", "store"),
            ("sync.key", "sync"),
            ("config.toml", "config"),
            ("service.json", "service"),
        ] {
            fs::write(data_dir.join(name), body).unwrap();
        }
        fs::create_dir(data_dir.join("indexes")).unwrap();
        fs::write(data_dir.join("indexes").join("seg"), "seg").unwrap();
        data_dir
    }

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

    #[test]
    fn moving_aside_for_pairing_keeps_the_old_dir_and_carries_only_host_files() {
        use std::os::unix::fs::PermissionsExt;

        let home = tempfile::tempdir().unwrap();
        let data_dir = populated_data_dir(home.path());
        let now = micros("20261103-101500");

        let aside = move_aside_for_pairing(&data_dir, now, &["join-marker"]).unwrap();
        assert_eq!(
            aside,
            home.path()
                .join(".second-brain.before-pair-20261103-101500")
        );
        assert_eq!(
            names(&aside),
            [
                "brain.db",
                "config.toml",
                "device.key",
                "indexes",
                "machine.toml",
                "service.json",
                "store.key",
                "sync.key"
            ]
        );
        assert_eq!(
            fs::read_to_string(aside.join("device.key")).unwrap(),
            "device"
        );
        assert_eq!(
            fs::read_to_string(aside.join("indexes").join("seg")).unwrap(),
            "seg"
        );
        assert_eq!(
            names(&data_dir),
            ["config.toml", "join-marker", "service.json"]
        );
        assert_eq!(
            fs::read_to_string(data_dir.join("config.toml")).unwrap(),
            "config"
        );
        assert_eq!(
            fs::read_to_string(data_dir.join("service.json")).unwrap(),
            "service"
        );
        let mode = fs::metadata(&data_dir).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, crate::private_files::PRIVATE_DIR_MODE);

        let again = move_aside_for_pairing(&data_dir, now, &[]).unwrap();
        assert_eq!(
            again,
            home.path()
                .join(".second-brain.before-pair-20261103-101500-2")
        );
        assert_eq!(
            names(&again),
            ["config.toml", "join-marker", "service.json"]
        );
        assert_eq!(names(&data_dir), ["config.toml", "service.json"]);

        assert_eq!(
            moved_aside_dirs(&data_dir).unwrap(),
            vec![
                MovedAside {
                    path: aside.clone(),
                    moved_at_micros: now,
                },
                MovedAside {
                    path: again.clone(),
                    moved_at_micros: now,
                },
            ]
        );
        assert!(
            remove_expired_asides(&data_dir, now + 90 * DAY - 1)
                .unwrap()
                .is_empty()
        );
        assert_eq!(
            remove_expired_asides(&data_dir, now + 90 * DAY).unwrap(),
            vec![aside.clone(), again.clone()]
        );
        assert!(!aside.exists() && !again.exists());
        assert!(data_dir.exists());
    }

    #[test]
    fn a_data_dir_without_host_files_moves_aside_into_an_empty_dir() {
        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join(".second-brain");
        fs::create_dir(&data_dir).unwrap();
        fs::write(data_dir.join("brain.db"), "db").unwrap();

        let aside = move_aside_for_pairing(&data_dir, micros("20261103-101500"), &[]).unwrap();
        assert_eq!(names(&aside), ["brain.db"]);
        assert!(names(&data_dir).is_empty());
    }

    #[test]
    fn a_missing_or_linked_data_dir_is_not_moved() {
        let home = tempfile::tempdir().unwrap();
        let now = micros("20261103-101500");
        let missing = home.path().join(".second-brain");
        let err = format!(
            "{:#}",
            move_aside_for_pairing(&missing, now, &[]).unwrap_err()
        );
        assert!(err.contains(&missing.display().to_string()), "{err}");
        assert!(names(home.path()).is_empty());

        fs::create_dir(home.path().join("elsewhere")).unwrap();
        let target = populated_data_dir(&home.path().join("elsewhere"));
        std::os::unix::fs::symlink(&target, &missing).unwrap();
        let err = format!(
            "{:#}",
            move_aside_for_pairing(&missing, now, &[]).unwrap_err()
        );
        assert!(err.contains("symlink"), "{err}");
        assert!(
            fs::symlink_metadata(&missing)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(names(home.path()), [".second-brain", "elsewhere"]);
        assert!(target.join("brain.db").exists());
    }

    #[test]
    fn a_move_that_fails_after_the_rename_puts_the_data_dir_back() {
        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join(".second-brain");
        fs::create_dir(&data_dir).unwrap();
        fs::write(data_dir.join("brain.db"), "db").unwrap();
        fs::create_dir(data_dir.join("config.toml")).unwrap();

        assert!(move_aside_for_pairing(&data_dir, micros("20261103-101500"), &[]).is_err());
        assert_eq!(names(home.path()), [".second-brain"]);
        assert_eq!(names(&data_dir), ["brain.db", "config.toml"]);
    }

    #[test]
    fn a_moved_aside_plaintext_store_opens_with_its_own_machine_id() {
        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join(".second-brain");
        let machine = MachineIdentity::load_or_create(&data_dir).unwrap();
        let kept = memory("written before pairing");
        {
            let store = SqliteStore::open(&data_dir.join("brain.db"), machine.id.clone()).unwrap();
            store.store_memory(&kept).unwrap();
        }

        let aside = move_aside_for_pairing(&data_dir, micros("20261103-101500"), &[]).unwrap();
        let store = open_moved_aside(&aside).unwrap();
        assert_eq!(store.machine_id(), machine.id);
        assert_eq!(
            store.get_memory(kept.id).unwrap().unwrap().content,
            kept.content
        );
    }

    #[test]
    fn an_aside_without_a_store_or_machine_file_names_what_is_missing() {
        let home = tempfile::tempdir().unwrap();
        let aside = home
            .path()
            .join(".second-brain.before-pair-20261103-101500");
        fs::create_dir(&aside).unwrap();
        let err = format!("{:#}", open_moved_aside(&aside).err().unwrap());
        assert!(
            err.contains(&aside.join("machine.toml").display().to_string()),
            "{err}"
        );

        MachineIdentity::load_or_create(&aside).unwrap();
        let err = format!("{:#}", open_moved_aside(&aside).err().unwrap());
        assert!(
            err.contains(&aside.join("brain.db").display().to_string()),
            "{err}"
        );
        assert!(!aside.join("brain.db").exists());
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn a_moved_aside_encrypted_store_opens_with_the_asides_own_keys() {
        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join(".second-brain");
        let machine = MachineIdentity::load_or_create(&data_dir).unwrap();
        let device =
            crate::keys::create_device_keys(&data_dir, &crate::keys::KeyStorage::File).unwrap();
        let kept = memory("encrypted before pairing");
        {
            let store = SqliteStore::open(&data_dir.join("brain.db"), machine.id.clone()).unwrap();
            store.store_memory(&kept).unwrap();
            crate::keys::encrypt_store(&store, &data_dir, &device).unwrap();
        }

        let aside = move_aside_for_pairing(&data_dir, micros("20261103-101500"), &[]).unwrap();
        assert_eq!(
            crate::sqlite_store::encrypt_migration::db_file_state(&aside.join("brain.db")).unwrap(),
            crate::sqlite_store::encrypt_migration::FileState::Encrypted
        );
        let store = open_moved_aside(&aside).unwrap();
        assert_eq!(
            store.get_memory(kept.id).unwrap().unwrap().content,
            kept.content
        );
        drop(store);

        fs::remove_file(aside.join(crate::keys::DEVICE_KEY_FILE)).unwrap();
        let err = format!("{:#}", open_moved_aside(&aside).err().unwrap());
        assert!(err.contains(&aside.display().to_string()), "{err}");
    }

    #[test]
    fn a_missing_parent_has_no_asides() {
        let home = tempfile::tempdir().unwrap();
        let data_dir = home.path().join("gone").join(".second-brain");
        assert!(moved_aside_dirs(&data_dir).unwrap().is_empty());
    }
}