second-brain-api 0.13.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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use sha2::{Digest, Sha256};

use second_brain_adapters::claude_code::ClaudeCodeAdapter;
use second_brain_adapters::claude_memory::ClaudeMemoryAdapter;
use second_brain_adapters::cursor::CursorAdapter;
use second_brain_adapters::{Adapter, ConversationSource, store_ingest_result};
use second_brain_core::embedding::{DocumentEmbedder, Embedder};
use second_brain_core::schema::IngestRecord;
use second_brain_core::store::StoreAdmin;
use second_brain_core::transcript_archive::TranscriptArchive;

#[derive(Debug, Default)]
pub struct IngestStats {
    pub new_memories: usize,
    pub new_conversations: usize,
    pub new_entities: usize,
    pub skipped_dupes: usize,
    pub unchanged: usize,
    pub errors: usize,
    pub files_processed: usize,
}

/// Every adapter an ingest can run, by the `source` name it stores.
pub const SOURCES: [&str; 3] = ["claude-code", "claude-memory", "cursor"];

fn adapter_named(source: &str, machine_id: &str) -> Option<Box<dyn Adapter>> {
    let machine_id = machine_id.to_string();
    match source {
        "claude-code" => Some(Box::new(ClaudeCodeAdapter::new(machine_id))),
        "claude-memory" => Some(Box::new(ClaudeMemoryAdapter::new(machine_id))),
        "cursor" => Some(Box::new(CursorAdapter::new(machine_id))),
        _ => None,
    }
}

/// The adapters an ingest of `source` runs: the one named, or all of them
/// when no source is given. An unknown name is the caller's mistake and is
/// answered with a message listing the sources that exist.
pub fn adapters_for(
    source: Option<&str>,
    machine_id: &str,
) -> Result<Vec<Box<dyn Adapter>>, String> {
    match source {
        None => Ok(SOURCES
            .iter()
            .filter_map(|name| adapter_named(name, machine_id))
            .collect()),
        Some(name) => adapter_named(name, machine_id)
            .map(|a| vec![a])
            .ok_or_else(|| {
                format!(
                    "unknown ingest source '{name}'; valid values: {}",
                    SOURCES.join(", ")
                )
            }),
    }
}

pub fn run_ingest(
    store: &Arc<dyn StoreAdmin>,
    embedder: Option<&Embedder>,
    machine_id: &str,
    source: Option<&str>,
) -> Result<IngestStats> {
    let adapters = adapters_for(source, machine_id).map_err(anyhow::Error::msg)?;
    let embedder = embedder.map(|e| e as &dyn DocumentEmbedder);
    Ok(ingest_with_adapters(
        store.as_ref(),
        embedder,
        machine_id,
        &adapters,
    ))
}

pub fn ingest_with_adapters(
    store: &dyn StoreAdmin,
    embedder: Option<&dyn DocumentEmbedder>,
    machine_id: &str,
    adapters: &[Box<dyn Adapter>],
) -> IngestStats {
    let mut total = IngestStats::default();
    for adapter in adapters {
        let sources = match adapter.discover_conversations() {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!("ingest: {} discovery failed: {e}", adapter.name());
                continue;
            }
        };
        total.files_processed += sources.len();
        ingest_sources(
            adapter.as_ref(),
            &sources,
            store,
            embedder,
            machine_id,
            &mut total,
        );
    }
    total
}

/// Re-runs every adapter after forgetting which files it saw, except files
/// ingested before raw ids became deterministic: re-parsing one would bring
/// back, under new ids, raws that were deleted under their old random ones.
/// Returns the number of forgotten files with the ingest stats.
pub fn reingest(
    store: &Arc<dyn StoreAdmin>,
    embedder: Option<&Embedder>,
    machine_id: &str,
) -> Result<(usize, IngestStats)> {
    let adapters = adapters_for(None, machine_id).map_err(anyhow::Error::msg)?;
    reingest_with_adapters(
        store.as_ref(),
        embedder.map(|e| e as &dyn DocumentEmbedder),
        machine_id,
        &adapters,
    )
}

pub fn reingest_with_adapters(
    store: &dyn StoreAdmin,
    embedder: Option<&dyn DocumentEmbedder>,
    machine_id: &str,
    adapters: &[Box<dyn Adapter>],
) -> Result<(usize, IngestStats)> {
    let cleared = store.clear_reparseable_ingest_log()?;
    Ok((
        cleared,
        ingest_with_adapters(store, embedder, machine_id, adapters),
    ))
}

/// What a watcher-triggered ingest did with one file. Write failures are
/// returned as errors, without the path, so they can be reported as health.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileOutcome {
    /// Stored, or already stored with the same content.
    Captured,
    /// Unreadable or not a parseable conversation.
    Skipped,
}

pub fn capture_transcript(
    store: &Arc<dyn StoreAdmin>,
    embedder: Option<&Embedder>,
    archive: Option<&TranscriptArchive>,
    path: &Path,
    machine_id: &str,
) -> Result<FileOutcome> {
    if store.session_deleted(&path.to_string_lossy())? {
        return Ok(FileOutcome::Skipped);
    }
    let archived = match archive.map(|a| a.archive(path)) {
        Some(Err(_)) if std::fs::File::open(path).is_err() => return Ok(FileOutcome::Skipped),
        archived => archived,
    };
    let outcome = ingest_file(store, embedder, path, machine_id)?;
    if let Some(Err(e)) = archived {
        return Err(e.context("archiving a transcript"));
    }
    Ok(outcome)
}

pub fn ingest_file(
    store: &Arc<dyn StoreAdmin>,
    embedder: Option<&Embedder>,
    path: &std::path::Path,
    machine_id: &str,
) -> Result<FileOutcome> {
    let path_str = path.to_string_lossy().to_string();
    let adapter = ClaudeCodeAdapter::new(machine_id.to_string());

    let changed = match check_file(store.as_ref(), &adapter, path) {
        Some(FileCheck::Changed(changed)) => changed,
        Some(FileCheck::Unchanged) => return Ok(FileOutcome::Captured),
        None => return Ok(FileOutcome::Skipped),
    };

    let source = ConversationSource {
        id: path_str.clone(),
        path: path_str.clone(),
        source_name: "claude-code".to_string(),
        machine_id: machine_id.to_string(),
    };

    let result = match adapter.ingest_conversation(&source) {
        Ok(r) => r,
        Err(e) => {
            tracing::debug!("watcher: failed to parse {}: {e}", path_str);
            changed
                .record_unreadable(store.as_ref(), path, "claude-code")
                .context("recording a transcript that cannot be parsed")?;
            return Ok(FileOutcome::Skipped);
        }
    };

    let outcome = store_ingest_result(
        store.as_ref(),
        embedder.map(|e| e as &dyn DocumentEmbedder),
        &result,
        machine_id,
    );

    if outcome.errors > 0 {
        tracing::warn!(
            "watcher: ingested {} with {} write errors ({} memories stored)",
            path_str,
            outcome.errors,
            outcome.stored
        );
        bail!(
            "{} memory writes failed while ingesting a transcript",
            outcome.errors
        );
    }
    changed
        .record(store.as_ref(), &path_str, outcome.stored, "claude-code")
        .context("recording an ingested transcript")?;
    if outcome.stored > 0 {
        tracing::info!(
            "watcher: ingested {} ({} memories)",
            path_str,
            outcome.stored
        );
    }
    Ok(FileOutcome::Captured)
}

/// A Claude Code memory note: a `.md` file in a `memory` directory, other
/// than the `MEMORY.md` index.
pub(crate) fn is_memory_file(path: &Path) -> bool {
    path.extension().is_some_and(|e| e == "md")
        && path
            .parent()
            .is_some_and(|p| p.file_name().is_some_and(|n| n == "memory"))
        && !path
            .file_name()
            .is_some_and(|n| n.eq_ignore_ascii_case("MEMORY.md"))
}

/// True unless ingest_log holds this file's current content; an unreadable
/// file has nothing to ingest.
pub(crate) fn changed_since_ingest(store: &dyn StoreAdmin, path: &Path) -> bool {
    let Ok(bytes) = std::fs::read(path) else {
        return false;
    };
    !ingested_as(store, path, &sha256_hex(&bytes))
}

/// True when ingest_log records `content_hash` for `path`.
pub(crate) fn ingested_as(store: &dyn StoreAdmin, path: &Path, content_hash: &str) -> bool {
    let path_str = path.to_string_lossy();
    match store.is_file_changed(&path_str, content_hash) {
        Ok(changed) => !changed,
        Err(e) => {
            tracing::warn!("ingest: reading the ingest log for {path_str} failed: {e}");
            false
        }
    }
}

pub fn ingest_memory_file(
    store: &Arc<dyn StoreAdmin>,
    embedder: Option<&Embedder>,
    path: &std::path::Path,
    machine_id: &str,
) -> Result<FileOutcome> {
    let path_str = path.to_string_lossy().to_string();
    let adapter = ClaudeMemoryAdapter::new(machine_id.to_string());

    let changed = match check_file(store.as_ref(), &adapter, path) {
        Some(FileCheck::Changed(changed)) => changed,
        Some(FileCheck::Unchanged) => return Ok(FileOutcome::Captured),
        None => return Ok(FileOutcome::Skipped),
    };

    // remove the previous memory for this file before re-ingesting so stale
    // content does not accumulate alongside the updated version
    store
        .delete_memories_by_source_id(&path_str)
        .context("removing the previous memory of a memory file")?;

    let source = ConversationSource {
        id: path_str.clone(),
        path: path_str.clone(),
        source_name: "claude-memory".to_string(),
        machine_id: machine_id.to_string(),
    };

    let result = match adapter.ingest_conversation(&source) {
        Ok(r) => r,
        Err(e) => {
            tracing::debug!("watcher: failed to parse memory file {}: {e}", path_str);
            changed
                .record_unreadable(store.as_ref(), path, "claude-memory")
                .context("recording a memory file that cannot be parsed")?;
            return Ok(FileOutcome::Skipped);
        }
    };

    let outcome = store_ingest_result(
        store.as_ref(),
        embedder.map(|e| e as &dyn DocumentEmbedder),
        &result,
        machine_id,
    );

    if outcome.stored > 0 || outcome.errors > 0 {
        tracing::info!(
            "watcher: ingested memory file {} ({} memories, {} errors)",
            path_str,
            outcome.stored,
            outcome.errors
        );
    }
    if outcome.errors > 0 {
        bail!(
            "{} memory writes failed while ingesting a memory file",
            outcome.errors
        );
    }
    changed
        .record(store.as_ref(), &path_str, outcome.stored, "claude-memory")
        .context("recording an ingested memory file")?;
    Ok(FileOutcome::Captured)
}

fn ingest_sources(
    adapter: &dyn Adapter,
    sources: &[ConversationSource],
    store: &dyn StoreAdmin,
    embedder: Option<&dyn DocumentEmbedder>,
    machine_id: &str,
    stats: &mut IngestStats,
) {
    for source in sources {
        let changed = match check_file(store, adapter, std::path::Path::new(&source.path)) {
            Some(FileCheck::Changed(changed)) => changed,
            Some(FileCheck::Unchanged) => {
                stats.unchanged += 1;
                continue;
            }
            None => {
                stats.errors += 1;
                continue;
            }
        };

        let result = match adapter.ingest_conversation(source) {
            Ok(r) => r,
            Err(e) => {
                tracing::warn!("ingest: failed to parse {}: {e}", source.path);
                stats.errors += 1;
                continue;
            }
        };

        let outcome = store_ingest_result(store, embedder, &result, machine_id);
        if !result.memories.is_empty() {
            stats.new_conversations += 1;
        }
        stats.new_memories += outcome.stored;
        stats.skipped_dupes += outcome.dupes;
        stats.new_entities += outcome.entities;
        stats.errors += outcome.errors;

        if outcome.errors > 0 {
            continue;
        }
        if let Err(e) = changed.record(store, &source.path, outcome.stored, adapter.name()) {
            tracing::warn!("ingest: mark_ingested failed for {}: {e}", source.path);
            stats.errors += 1;
        }
    }
}

enum FileCheck {
    Unchanged,
    Changed(ChangedFile),
}

struct ChangedFile {
    content_hash: String,
    session_key: Option<String>,
}

impl ChangedFile {
    fn record(
        &self,
        store: &dyn StoreAdmin,
        path: &str,
        memory_count: usize,
        source: &str,
    ) -> Result<()> {
        store.record_ingested(&IngestRecord {
            file_path: path,
            content_hash: &self.content_hash,
            session_key: self.session_key.as_deref(),
            legacy_ids: false,
            memory_count,
            source,
        })
    }

    /// True when recorded: only bytes that are still the hashed ones and are
    /// not text, so a rewrite, unlink or transient read error is retried.
    fn record_unreadable(&self, store: &dyn StoreAdmin, path: &Path, source: &str) -> Result<bool> {
        let Ok(bytes) = std::fs::read(path) else {
            return Ok(false);
        };
        if sha256_hex(&bytes) != self.content_hash || std::str::from_utf8(&bytes).is_ok() {
            return Ok(false);
        }
        self.record(store, &path.to_string_lossy(), 0, source)?;
        Ok(true)
    }
}

/// Whether `path` needs parsing. A file is unchanged when its own row holds
/// its content, when any row holds the same session and content (a copy), or
/// when its bytes match a pre-SHA-256 legacy row at this path or any path
/// with the same stem; those legacy rows are upgraded in place on the way.
/// None when the file can't be read.
fn check_file(store: &dyn StoreAdmin, adapter: &dyn Adapter, path: &Path) -> Option<FileCheck> {
    let bytes = std::fs::read(path).ok()?;
    let content_hash = sha256_hex(&bytes);
    let path_str = path.to_string_lossy();
    if adapter.name() == "claude-code" {
        match store.session_deleted(&path_str) {
            Ok(true) => return Some(FileCheck::Unchanged),
            Ok(false) => {}
            Err(e) => {
                tracing::warn!("ingest: checking whether {path_str} was deleted failed: {e}");
                return None;
            }
        }
    }

    if let Ok(false) = store.is_file_changed(&path_str, &content_hash) {
        return Some(FileCheck::Unchanged);
    }
    let session_key = adapter.session_key(path, &String::from_utf8_lossy(&bytes));
    let legacy_hash = legacy_file_hash(&bytes);
    let changed = || {
        Some(FileCheck::Changed(ChangedFile {
            content_hash: content_hash.clone(),
            session_key: session_key.clone(),
        }))
    };

    let own_row = store.ingest_log_entry(&path_str).unwrap_or_else(|e| {
        tracing::warn!("ingest: reading the ingest log for {path_str} failed: {e}");
        None
    });
    if let Some(row) = own_row.filter(|r| r.content_hash.is_none() && r.file_hash == legacy_hash) {
        upgrade(store, &row.file_path, &content_hash, session_key.as_deref());
        return Some(FileCheck::Unchanged);
    }

    let Some(key) = session_key.as_deref() else {
        return changed();
    };
    match store.ingested_session(key, &content_hash) {
        Ok(Some(copy_of)) => {
            record_copy(
                store,
                &path_str,
                &content_hash,
                key,
                copy_of.legacy_ids,
                adapter.name(),
            );
            return Some(FileCheck::Unchanged);
        }
        Ok(None) => {}
        Err(e) => tracing::warn!("ingest: session lookup for {path_str} failed: {e}"),
    }

    let Some(stem) = path.file_stem() else {
        return changed();
    };
    let legacy_rows = store
        .legacy_ingest_entries_with_stem(&stem.to_string_lossy())
        .unwrap_or_else(|e| {
            tracing::warn!("ingest: legacy lookup for {path_str} failed: {e}");
            Vec::new()
        });
    if let Some(row) = legacy_rows.into_iter().find(|r| r.file_hash == legacy_hash) {
        upgrade(store, &row.file_path, &content_hash, Some(key));
        record_copy(store, &path_str, &content_hash, key, true, adapter.name());
        return Some(FileCheck::Unchanged);
    }
    changed()
}

fn upgrade(store: &dyn StoreAdmin, path: &str, content_hash: &str, session_key: Option<&str>) {
    if let Err(e) = store.upgrade_ingest_hash(path, content_hash, session_key) {
        tracing::warn!("ingest: upgrading the ingest log hash for {path} failed: {e}");
    }
}

fn record_copy(
    store: &dyn StoreAdmin,
    path: &str,
    content_hash: &str,
    session_key: &str,
    legacy_ids: bool,
    source: &str,
) {
    let record = IngestRecord {
        file_path: path,
        content_hash,
        session_key: Some(session_key),
        legacy_ids,
        memory_count: 0,
        source,
    };
    if let Err(e) = store.record_ingested(&record) {
        tracing::warn!("ingest: recording copied transcript {path} failed: {e}");
    }
}

fn sha256_hex(bytes: &[u8]) -> String {
    Sha256::digest(bytes)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// The hash ingest_log held before SHA-256: std's `DefaultHasher`, whose
/// output is not stable across Rust releases, so it is only ever compared
/// against rows written by an older binary.
pub fn legacy_file_hash(bytes: &[u8]) -> String {
    use std::hash::Hasher;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for chunk in bytes.chunks(8192) {
        hasher.write(chunk);
    }
    format!("{:016x}", hasher.finish())
}

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

    #[test]
    fn a_failed_read_is_recorded_only_when_the_checked_bytes_are_not_text() {
        let store =
            second_brain_core::sqlite_store::SqliteStore::in_memory("m".to_string()).unwrap();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("note.md");
        let checked = |bytes: &[u8]| ChangedFile {
            content_hash: sha256_hex(bytes),
            session_key: None,
        };
        let cut = [b'c', b'a', b'f', 0xC3];

        std::fs::write(&path, [b'x', 0xC3]).unwrap();
        assert!(
            !checked(&cut)
                .record_unreadable(&store, &path, "claude-memory")
                .unwrap()
        );
        assert!(!ingested_as(&store, &path, &sha256_hex(&cut)));

        std::fs::write(&path, b"valid text").unwrap();
        assert!(
            !checked(b"valid text")
                .record_unreadable(&store, &path, "claude-memory")
                .unwrap()
        );
        assert!(!ingested_as(&store, &path, &sha256_hex(b"valid text")));

        std::fs::remove_file(&path).unwrap();
        assert!(
            !checked(&cut)
                .record_unreadable(&store, &path, "claude-memory")
                .unwrap()
        );

        std::fs::write(&path, cut).unwrap();
        assert!(
            checked(&cut)
                .record_unreadable(&store, &path, "claude-memory")
                .unwrap()
        );
        assert!(ingested_as(&store, &path, &sha256_hex(&cut)));
    }

    fn names(source: Option<&str>) -> Result<Vec<String>, String> {
        adapters_for(source, "m")
            .map(|adapters| adapters.iter().map(|a| a.name().to_string()).collect())
    }

    #[test]
    fn a_named_source_runs_only_that_adapter() {
        for source in SOURCES {
            assert_eq!(names(Some(source)).unwrap(), vec![source.to_string()]);
        }
    }

    #[test]
    fn no_source_runs_every_adapter() {
        assert_eq!(names(None).unwrap(), SOURCES.map(str::to_string).to_vec());
    }

    #[test]
    fn an_unknown_source_is_refused_with_the_valid_names() {
        let error = names(Some("bogus")).unwrap_err();
        assert!(error.contains("bogus"), "{error}");
        for source in SOURCES {
            assert!(error.contains(source), "{error}");
        }
    }
}