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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::time::Duration;

use anyhow::Result;
use chrono::{DateTime, Utc};
use second_brain_adapters::raw_text::raw_passages;
use second_brain_core::index::EMBEDDING_DIM;
use second_brain_core::index::raw::{RawHit, RawIndex, RawOrigin, RawPassage, text_hash};
use second_brain_core::project_path;
use second_brain_core::residency;
use second_brain_core::sealed::{SealError, SealKeys, seal_error};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::transcript_archive::{ArchiveEntry, TranscriptArchive};
use uuid::Uuid;

const EMBED_BATCH: usize = 8;
const COMMIT_EVERY: usize = 20;
/// Embedding sessions are handed out without fairness, so without this gap
/// the indexer takes the session straight back and an ingest or recall
/// waiting for it times out.
pub const PAUSE_AFTER_EMBED: Duration = Duration::from_millis(100);
const PASS_INTERVAL: Duration = Duration::from_secs(600);

/// Opens the raw index, or rebuilds it from scratch when its files cannot
/// be read as an index, for example after a schema change: everything in it
/// is derived from the transcript archive and the store, so the next pass
/// refills it. An I/O error opening the directories themselves is returned
/// instead; tantivy and usearch report their own I/O faults without an I/O
/// cause, so those still rebuild.
pub fn open_or_rebuild(dir: &Path) -> Result<RawIndex> {
    open_or_rebuild_keyed(dir, None)
}

/// `open_or_rebuild` with the index sealed at rest under `keys` when given.
/// Files sealed under a key not given, or sealed when no keys are, cannot be
/// opened, so the index is rebuilt like one with an unreadable schema.
pub fn open_or_rebuild_keyed(dir: &Path, keys: Option<&SealKeys>) -> Result<RawIndex> {
    let open = || match keys {
        Some(keys) => RawIndex::open_keyed(dir, keys),
        None => RawIndex::open(dir),
    };
    match open() {
        Ok(index) => Ok(index),
        Err(e) if seal_error(&e) == Some(&SealError::KeyRequired) => Err(e),
        Err(e)
            if seal_error(&e).is_none()
                && e.chain()
                    .any(|c| c.downcast_ref::<std::io::Error>().is_some()) =>
        {
            Err(e)
        }
        Err(e) => {
            tracing::warn!(
                "raw index at {} cannot be opened, rebuilding it: {e:#}",
                dir.display()
            );
            std::fs::remove_dir_all(dir)?;
            open()
        }
    }
}

pub type EmbedBatch = dyn Fn(&[&str]) -> Result<Vec<Vec<f32>>> + Send + Sync;

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct PassSummary {
    pub transcripts: usize,
    pub memories: usize,
    pub passages: usize,
    pub restored: usize,
    /// Sources that could not be read or embedded; they are retried next pass.
    pub failed: usize,
    /// Passages left out because their source is older than the age bound.
    pub skipped_by_age: usize,
    /// Passages withdrawn because what they came from was deleted.
    pub purged: usize,
}

/// The age bound an indexer works to and what its last pass left out,
/// shared with status. It also remembers when each transcript left out
/// was last active, so later passes skip it without reading it again.
pub struct RawCoverage {
    max_age_days: u32,
    skipped_by_age: AtomicUsize,
    aged: Mutex<HashMap<String, Dated>>,
}

#[derive(Clone, Copy)]
struct Dated {
    newest: DateTime<Utc>,
    passages: usize,
}

impl RawCoverage {
    pub fn new(max_age_days: u32) -> Self {
        Self {
            max_age_days,
            skipped_by_age: AtomicUsize::new(0),
            aged: Mutex::new(HashMap::new()),
        }
    }

    pub fn max_age_days(&self) -> u32 {
        self.max_age_days
    }

    /// Passages the last finished pass left out for age.
    pub fn skipped_by_age(&self) -> usize {
        self.skipped_by_age.load(Ordering::Relaxed)
    }

    fn cutoff(&self) -> DateTime<Utc> {
        Utc::now()
            .checked_sub_signed(chrono::Duration::days(i64::from(self.max_age_days)))
            .unwrap_or(DateTime::<Utc>::MIN_UTC)
    }

    fn aged(&self) -> std::sync::MutexGuard<'_, HashMap<String, Dated>> {
        self.aged.lock().unwrap_or_else(|p| p.into_inner())
    }
}

/// What a purge removed from the raw index and the transcript archive.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct RawPurge {
    pub passages: usize,
    pub archive_entries: usize,
}

static PURGES: Mutex<()> = Mutex::new(());

/// Withdraws from the raw index every passage of a tombstoned memory, of an
/// archived transcript whose session was deleted, or with the text of one
/// of that transcript's lines (an older copy of a grown transcript holds
/// them under another source), then drops those transcripts from the
/// archive. The index stores each text once, so a passage whose text a kept
/// transcript still holds is filed under that transcript instead. `memories`
/// are ids the caller just deleted, checked without a store lookup. The
/// archive is read, and the vector segments and text files rewritten,
/// without the index's write lock, so recall keeps answering; the lock is
/// held from the last check for doomed passages until the doomed
/// transcripts leave the archive, so an indexer pass cannot add one back in
/// between.
pub fn purge_deleted(
    index: Option<&RwLock<RawIndex>>,
    archive: Option<&TranscriptArchive>,
    store: &SqliteStore,
    memories: &[Uuid],
) -> Result<RawPurge> {
    let _one_at_a_time = PURGES.lock().unwrap_or_else(|p| p.into_inner());
    let doomed = match archive {
        Some(archive) => doomed_entries(archive, store)?,
        None => Vec::new(),
    };
    let mut gone = Gone::new(store, memories);
    match index {
        Some(index) => purge_index(index, archive, &doomed, &mut gone),
        None => Ok(RawPurge {
            passages: 0,
            archive_entries: match archive {
                Some(archive) => remove_entries(archive, &doomed)?,
                None => 0,
            },
        }),
    }
}

fn doomed_entries(archive: &TranscriptArchive, store: &SqliteStore) -> Result<Vec<ArchiveEntry>> {
    let mut doomed = Vec::new();
    for entry in archive.entries() {
        if store.session_deleted(&entry.source)? {
            doomed.push(entry);
        }
    }
    Ok(doomed)
}

fn purge_index(
    lock: &RwLock<RawIndex>,
    archive: Option<&TranscriptArchive>,
    doomed: &[ArchiveEntry],
    gone: &mut Gone<'_>,
) -> Result<RawPurge> {
    let (memories, recorded_sources) = {
        let index = read_lock(lock);
        (index.passage_memories()?, index.sources()?)
    };
    let live = live_entries(archive, doomed);
    let live_shas: HashSet<&str> = live.iter().map(|e| e.sha256.as_str()).collect();
    let mut stale = Vec::new();
    for id in memories {
        if gone.check(id)? {
            stale.push(id);
        }
    }
    let mut sources: Vec<RawOrigin> = doomed
        .iter()
        .filter(|e| !live_shas.contains(e.sha256.as_str()))
        .map(|e| RawOrigin::Transcript {
            sha256: e.sha256.clone(),
        })
        .collect();
    for origin in recorded_sources {
        if let RawOrigin::Memory { id } = origin
            && gone.check(id)?
        {
            sources.push(origin);
        }
    }
    if doomed.is_empty() && sources.is_empty() && stale.is_empty() {
        return Ok(RawPurge::default());
    }
    let texts = transcript_texts(archive, doomed)?;
    let texts: Vec<&str> = texts.iter().map(String::as_str).collect();
    let doomed_sources: HashSet<String> = sources.iter().map(RawOrigin::source_key).collect();

    let (candidates, recorded) = {
        let index = read_lock(lock);
        (
            index.matching(&sources, &stale, &texts)?,
            recorded_entries(&index, &live),
        )
    };
    let mut holders = Holders::default();
    if let Some(archive) = archive
        && !candidates.is_empty()
    {
        holders.read(archive, &recorded, &candidates, gone)?;
    }

    let mut index = write_lock(lock);
    index.commit_without_merging()?;
    let current = index.matching(&sources, &stale, &texts)?;
    if let Some(archive) = archive
        && !current.is_empty()
    {
        let late: Vec<ArchiveEntry> = recorded_entries(&index, &live)
            .into_iter()
            .filter(|e| !holders.has_read(e))
            .collect();
        holders.read(archive, &late, &current, gone)?;
    }
    let mut dropped = Vec::new();
    for hit in &current {
        let memory_gone = match hit.memory {
            Some(id) => gone.check(id)?,
            None => false,
        };
        let memory_holder = match hit.memory {
            Some(id) => !memory_gone && index.has_source(&RawOrigin::Memory { id }),
            None => false,
        };
        match fate(hit, &doomed_sources, &holders, memory_gone, memory_holder) {
            Fate::Keep => {}
            Fate::Move(holder) => index.rekey(
                hit.key,
                &holder.origin,
                &RawPassage {
                    text: holder.text,
                    at: holder.at,
                    project: holder.project,
                    memory: holder.memory,
                },
            )?,
            Fate::Drop => dropped.push(hit.key),
        }
    }
    index.withdraw(&dropped)?;
    index.forget_sources(&sources)?;
    let rewrite = index.seal_for_rewrite(&dropped)?;
    index.commit_without_merging()?;
    let archive_entries = match archive {
        Some(archive) => remove_entries(archive, doomed)?,
        None => 0,
    };
    let compaction = index.start_compaction()?;
    drop(index);

    let rewritten = rewrite.run();
    let merged = compaction.wait();
    let mut index = write_lock(lock);
    index.reload_sealed(&rewrite)?;
    index.finish_compaction(merged)?;
    rewritten?;
    Ok(RawPurge {
        passages: dropped.len(),
        archive_entries,
    })
}

fn live_entries(archive: Option<&TranscriptArchive>, doomed: &[ArchiveEntry]) -> Vec<ArchiveEntry> {
    let Some(archive) = archive else {
        return Vec::new();
    };
    let doomed: HashSet<&str> = doomed.iter().map(|e| e.source.as_str()).collect();
    archive
        .entries()
        .into_iter()
        .filter(|e| !doomed.contains(e.source.as_str()))
        .collect()
}

fn transcript_texts(
    archive: Option<&TranscriptArchive>,
    entries: &[ArchiveEntry],
) -> Result<Vec<String>> {
    let Some(archive) = archive else {
        return Ok(Vec::new());
    };
    let mut texts = Vec::new();
    for entry in entries {
        let source = Path::new(&entry.source);
        if let Some(content) = archive.read(source)? {
            texts.extend(raw_passages(source, &content).into_iter().map(|p| p.text));
        }
    }
    Ok(texts)
}

/// The entries whose blob the index records as a source. Only these can
/// take over a passage: filing one under a transcript not indexed yet would
/// mark that transcript indexed and the rest of it would never be read.
fn recorded_entries(index: &RawIndex, entries: &[ArchiveEntry]) -> Vec<ArchiveEntry> {
    entries
        .iter()
        .filter(|e| {
            index.has_source(&RawOrigin::Transcript {
                sha256: e.sha256.clone(),
            })
        })
        .cloned()
        .collect()
}

/// Whether a memory is deleted, each id looked up in the store once.
struct Gone<'a> {
    store: &'a SqliteStore,
    known: HashMap<Uuid, bool>,
}

impl<'a> Gone<'a> {
    fn new(store: &'a SqliteStore, just_deleted: &[Uuid]) -> Self {
        Self {
            store,
            known: just_deleted.iter().map(|id| (*id, true)).collect(),
        }
    }

    fn check(&mut self, id: Uuid) -> Result<bool> {
        if let Some(gone) = self.known.get(&id) {
            return Ok(*gone);
        }
        let gone = self.store.tombstone_exists(id)?;
        self.known.insert(id, gone);
        Ok(gone)
    }
}

/// Where a passage moves to, with the text it is filed under there: an
/// archived memory's passage carries no text of its own.
#[derive(Clone)]
struct Holder {
    origin: RawOrigin,
    text: String,
    project: Option<String>,
    at: Option<DateTime<Utc>>,
    memory: Option<Uuid>,
}

/// Kept transcripts that hold the text of a passage being purged, by the
/// text's hash, leaving out lines whose raw memory was deleted.
#[derive(Default)]
struct Holders {
    by_hash: HashMap<String, Vec<Holder>>,
    read: HashSet<String>,
}

impl Holders {
    fn has_read(&self, entry: &ArchiveEntry) -> bool {
        self.read.contains(&entry.sha256)
    }

    fn read(
        &mut self,
        archive: &TranscriptArchive,
        entries: &[ArchiveEntry],
        hits: &[RawHit],
        gone: &mut Gone<'_>,
    ) -> Result<()> {
        let wanted: HashSet<&str> = hits.iter().map(|h| h.text_hash.as_str()).collect();
        for entry in entries {
            if !self.read.insert(entry.sha256.clone()) {
                continue;
            }
            let source = Path::new(&entry.source);
            let Some(content) = archive.read(source)? else {
                continue;
            };
            let project = project_path::from_transcript(&entry.source);
            for passage in raw_passages(source, &content) {
                let hash = text_hash(&passage.text);
                if !wanted.contains(hash.as_str()) {
                    continue;
                }
                if let Some(id) = passage.memory
                    && gone.check(id)?
                {
                    continue;
                }
                self.by_hash.entry(hash).or_default().push(Holder {
                    origin: RawOrigin::Transcript {
                        sha256: entry.sha256.clone(),
                    },
                    text: passage.text,
                    project: project.clone(),
                    at: passage.at,
                    memory: passage.memory,
                });
            }
        }
        Ok(())
    }
}

enum Fate {
    Keep,
    Move(Holder),
    Drop,
}

/// A passage under a kept memory or held by its own kept transcript stays,
/// taking that line's metadata when its own raw memory was deleted; one
/// whose text another kept transcript holds, or whose kept raw memory the
/// index records, moves there; the rest go. A text no recorded
/// transcript was read for has no holder: a transcript the index records
/// had every text it holds indexed, so a passage added since the holders
/// were read carries a text none of them holds.
fn fate(
    hit: &RawHit,
    doomed_sources: &HashSet<String>,
    holders: &Holders,
    memory_gone: bool,
    memory_holder: bool,
) -> Fate {
    if matches!(hit.origin, RawOrigin::Memory { .. })
        && !doomed_sources.contains(&hit.origin.source_key())
    {
        return Fate::Keep;
    }
    if let Some(held) = holders.by_hash.get(&hit.text_hash) {
        if let Some(own) = held.iter().find(|h| h.origin == hit.origin) {
            return if memory_gone {
                Fate::Move(own.clone())
            } else {
                Fate::Keep
            };
        }
        if let Some(holder) = held.first() {
            return Fate::Move(holder.clone());
        }
    }
    match hit.memory {
        Some(id) if memory_holder => Fate::Move(Holder {
            origin: RawOrigin::Memory { id },
            text: hit.text.clone(),
            project: hit.project.clone(),
            at: hit.at,
            memory: Some(id),
        }),
        _ => Fate::Drop,
    }
}

fn read_lock(index: &RwLock<RawIndex>) -> RwLockReadGuard<'_, RawIndex> {
    index.read().unwrap_or_else(|p| p.into_inner())
}

fn write_lock(index: &RwLock<RawIndex>) -> RwLockWriteGuard<'_, RawIndex> {
    index.write().unwrap_or_else(|p| p.into_inner())
}

fn remove_entries(archive: &TranscriptArchive, doomed: &[ArchiveEntry]) -> Result<usize> {
    if doomed.is_empty() {
        return Ok(0);
    }
    let sources: HashSet<&str> = doomed.iter().map(|e| e.source.as_str()).collect();
    Ok(archive
        .remove_where(|e| sources.contains(e.source.as_str()))?
        .len())
}

/// Feeds the raw fallback index from the transcript archive and from raw
/// memories consolidation archived, embedding outside the index lock so
/// recall is never held behind the model.
pub struct RawIndexer {
    pub index: Arc<RwLock<RawIndex>>,
    pub archive: Option<Arc<TranscriptArchive>>,
    pub store: Arc<SqliteStore>,
    pub embed: Arc<EmbedBatch>,
    pub pause: Duration,
    pub coverage: Arc<RawCoverage>,
}

impl RawIndexer {
    pub fn spawn(self) {
        std::thread::Builder::new()
            .name("raw-index".to_string())
            .spawn(move || {
                loop {
                    match self.pass() {
                        Ok(s)
                            if PassSummary {
                                skipped_by_age: 0,
                                ..s
                            } != PassSummary::default() =>
                        {
                            tracing::info!(
                                "raw index: {} transcripts, {} archived memories, {} passages, {} vectors restored, {} sources failed, {} passages older than {} days skipped, {} deleted passages withdrawn",
                                s.transcripts,
                                s.memories,
                                s.passages,
                                s.restored,
                                s.failed,
                                s.skipped_by_age,
                                self.coverage.max_age_days(),
                                s.purged
                            );
                            residency::release_free_heap();
                        }
                        Ok(_) => {}
                        Err(e) => {
                            tracing::warn!("raw index pass failed: {e:#}");
                            residency::release_free_heap();
                        }
                    }
                    std::thread::sleep(PASS_INTERVAL);
                }
            })
            .expect("spawning the raw index thread");
    }

    /// Indexes every source not indexed yet that is within the age bound,
    /// newest first. A source that fails is counted, skipped and retried on
    /// the next pass, so one bad blob or a passing embedder error never stops
    /// the rest.
    pub fn pass(&self) -> Result<PassSummary> {
        let mut summary = PassSummary::default();
        match purge_deleted(Some(&self.index), self.archive.as_deref(), &self.store, &[]) {
            Ok(purge) => summary.purged = purge.passages,
            Err(e) => tracing::warn!("raw index: purging deleted sources failed: {e:#}"),
        }
        let mut first_error = None;
        let mut pending = 0;
        let cutoff = self.coverage.cutoff();
        if let Some(archive) = &self.archive {
            let mut queue = Vec::new();
            let mut aged = HashMap::new();
            for entry in archive.entries() {
                let origin = RawOrigin::Transcript {
                    sha256: entry.sha256.clone(),
                };
                if self.indexed(&origin) {
                    continue;
                }
                match self.date_transcript(archive, &entry) {
                    Ok(dated) if dated.newest < cutoff => {
                        summary.skipped_by_age += dated.passages;
                        aged.insert(entry.sha256.clone(), dated);
                    }
                    Ok(dated) => queue.push((dated.newest, entry, origin)),
                    Err(e) => {
                        summary.failed += 1;
                        first_error.get_or_insert(e);
                    }
                }
            }
            *self.coverage.aged() = aged;
            queue.sort_by_key(|q| std::cmp::Reverse(q.0));
            for (_, entry, origin) in queue {
                match self.add_transcript(archive, &entry, &origin) {
                    Ok(added) => {
                        summary.passages += added;
                        summary.transcripts += 1;
                        pending = self.commit_every(pending + 1)?;
                    }
                    Err(e) => {
                        summary.failed += 1;
                        first_error.get_or_insert(e);
                    }
                }
            }
        }

        let raws = self.store.archived_raws_since(cutoff)?;
        summary.skipped_by_age += raws
            .older
            .into_iter()
            .filter(|&id| !self.indexed(&RawOrigin::Memory { id }))
            .count();
        for id in raws.recent {
            let origin = RawOrigin::Memory { id };
            if self.indexed(&origin) {
                continue;
            }
            match self.add_memory(id, &origin) {
                Ok((added, restored)) => {
                    summary.passages += added;
                    summary.restored += usize::from(restored);
                    summary.memories += 1;
                    pending = self.commit_every(pending + 1)?;
                }
                Err(e) => {
                    summary.failed += 1;
                    first_error.get_or_insert(e);
                }
            }
        }
        if pending > 0 {
            self.write().commit()?;
        }
        self.coverage
            .skipped_by_age
            .store(summary.skipped_by_age, Ordering::Relaxed);
        if let Some(e) = first_error {
            tracing::warn!(
                "raw index: {} sources failed and will be retried, first: {e:#}",
                summary.failed
            );
        }
        Ok(summary)
    }

    /// When a transcript was last active: its newest passage time, or when
    /// it was archived if no line carries one. A transcript left out for age
    /// is dated from memory rather than read again.
    fn date_transcript(&self, archive: &TranscriptArchive, entry: &ArchiveEntry) -> Result<Dated> {
        if let Some(dated) = self.coverage.aged().get(&entry.sha256) {
            return Ok(*dated);
        }
        let source = Path::new(&entry.source);
        let passages = match archive.read(source)? {
            Some(content) => raw_passages(source, &content),
            None => Vec::new(),
        };
        Ok(Dated {
            newest: passages
                .iter()
                .filter_map(|p| p.at)
                .max()
                .unwrap_or(entry.archived_at),
            passages: passages.len(),
        })
    }

    fn add_transcript(
        &self,
        archive: &TranscriptArchive,
        entry: &ArchiveEntry,
        origin: &RawOrigin,
    ) -> Result<usize> {
        let source = Path::new(&entry.source);
        let Some(content) = archive.read(source)? else {
            return self.add(origin, Vec::new(), Some((archive, entry)));
        };
        let project = project_path::from_transcript(&entry.source);
        let passages = raw_passages(source, &content)
            .into_iter()
            .map(|p| RawPassage {
                text: p.text,
                at: p.at,
                project: project.clone(),
                memory: p.memory,
            })
            .collect();
        self.add(origin, passages, Some((archive, entry)))
    }

    fn add_memory(&self, id: Uuid, origin: &RawOrigin) -> Result<(usize, bool)> {
        let Some(memory) = self.store.get_memory_full(id)? else {
            return Ok((0, false));
        };
        let mut restored = false;
        let embedding = if memory.embedding.len() == EMBEDDING_DIM {
            memory.embedding.clone()
        } else {
            let embedding = self
                .embed_and_yield(&[memory.content.as_str()])?
                .into_iter()
                .next()
                .unwrap_or_default();
            if embedding.len() == EMBEDDING_DIM {
                restored = self.store.restore_archived_embedding(id, &embedding)?;
            }
            embedding
        };
        let passage = RawPassage {
            text: memory.content.clone(),
            at: memory.session_at,
            project: memory.project_path.clone(),
            memory: Some(id),
        };
        let added = self.write().add_source(origin, &[(passage, embedding)])?;
        Ok((added, restored))
    }

    /// Embeds only passages whose text is not indexed yet, so a transcript
    /// archived again as it grows costs only its new text, and none whose
    /// raw memory was deleted, which a purge would only withdraw again. A
    /// transcript is added only if the archive still holds it once the
    /// write lock is taken, since a purge may have removed it while it was
    /// embedded, and its source is not recorded if a purge withdrew or
    /// rekeyed passages meanwhile, since a text it skipped as indexed may
    /// be gone; the next pass reads it again.
    fn add(
        &self,
        origin: &RawOrigin,
        passages: Vec<RawPassage>,
        archived: Option<(&TranscriptArchive, &ArchiveEntry)>,
    ) -> Result<usize> {
        let (unindexed, generation) = {
            let index = self.read();
            let unindexed: Vec<RawPassage> = passages
                .into_iter()
                .filter(|p| !index.has_text(&p.text))
                .collect();
            (unindexed, index.purge_generation())
        };
        let mut seen = HashSet::new();
        let mut passages = Vec::with_capacity(unindexed.len());
        for passage in unindexed {
            if let Some(id) = passage.memory
                && self.store.tombstone_exists(id)?
            {
                continue;
            }
            if seen.insert(passage.text.trim().to_string()) {
                passages.push(passage);
            }
        }
        let mut embedded = Vec::with_capacity(passages.len());
        for batch in passages.chunks(EMBED_BATCH) {
            let texts: Vec<&str> = batch.iter().map(|p| p.text.as_str()).collect();
            let vectors = self.embed_and_yield(&texts)?;
            embedded.extend(batch.iter().cloned().zip(vectors));
        }
        let mut index = self.write();
        if let Some((archive, entry)) = archived
            && archive
                .entry(Path::new(&entry.source))
                .is_none_or(|held| held.sha256 != entry.sha256)
        {
            return Ok(0);
        }
        if index.purge_generation() != generation {
            return Ok(0);
        }
        index.add_source(origin, &embedded)
    }

    fn embed_and_yield(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        let vectors = (self.embed)(texts);
        std::thread::sleep(self.pause);
        vectors
    }

    fn commit_every(&self, pending: usize) -> Result<usize> {
        if pending < COMMIT_EVERY {
            return Ok(pending);
        }
        self.write().commit()?;
        Ok(0)
    }

    fn indexed(&self, origin: &RawOrigin) -> bool {
        self.read().has_source(origin)
    }

    fn read(&self) -> RwLockReadGuard<'_, RawIndex> {
        read_lock(&self.index)
    }

    fn write(&self) -> RwLockWriteGuard<'_, RawIndex> {
        write_lock(&self.index)
    }
}