second-brain-core 0.13.0

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
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
use std::collections::{BTreeMap, BTreeSet};

use anyhow::{Result, bail};
use chrono::Utc;
use rusqlite::{Connection, OptionalExtension, Transaction, params};
use serde::Serialize;
use uuid::Uuid;

use super::authored_order::{self, Tombstone};
use super::sessions::session_of;
use super::{SqliteStore, blocklist, delete_status, settled, sync_dedup};
use crate::schema::{AGENT_NOTE_SOURCE, Conversation, Memory, SyncNodeType, SyncOp};

const PURGE_REQUESTED: &str = "delete_purge_requested";

/// What one delete removes: a memory by id, everything a Claude Code
/// session produced (its transcript's raws, its subagents', notes filed
/// under it), or everything filed under a stored project path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeleteScope {
    Memory(Uuid),
    Session(String),
    Project(String),
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct DeleteCounts {
    pub memories: u64,
    /// Memories some distillation marker names as its distillate.
    pub distillates: u64,
    pub chunks: u64,
    pub relations: u64,
    pub markers: u64,
    pub conversations: u64,
    pub vector_keys: u64,
    pub chunk_vector_keys: u64,
    pub bm25: u64,
    pub cold_records: u64,
    /// Memories a removed memory had superseded, live again.
    pub restored: u64,
    /// Earlier create and update log records of the removed rows, reclaimed.
    pub log_records: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeleteReport {
    pub counts: DeleteCounts,
    pub memory_ids: Vec<Uuid>,
    /// Claude Code sessions whose conversation is now tombstoned, so their
    /// transcripts leave the archive and are never captured again.
    pub sessions: Vec<String>,
    pub conversations: Vec<Uuid>,
    /// Set once the delete ran, never by a preview: its id for
    /// `delete_status` and the log seq a peer must acknowledge.
    pub delete_id: Option<Uuid>,
    pub seq: Option<u64>,
}

impl DeleteReport {
    pub fn is_empty(&self) -> bool {
        self.memory_ids.is_empty() && self.sessions.is_empty() && self.conversations.is_empty()
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct ColdPurge {
    pub retired: u64,
    pub rewritten: u64,
    pub removed_files: u64,
}

struct Target {
    id: String,
    distillate: bool,
}

struct Plan {
    targets: Vec<Target>,
    markers: BTreeSet<String>,
    /// Out-of-scope raws whose marker named a removed distillate, moved to
    /// the restored member of their own session.
    repoint: BTreeMap<String, Uuid>,
    restored: Vec<Uuid>,
    conversations: BTreeSet<Uuid>,
    sessions: BTreeSet<String>,
}

struct Matched {
    source: String,
    source_id: String,
    conversation: Option<String>,
}

const MEMORY_COLUMNS: &str = "SELECT id, source, source_id, conversation_id FROM memories";

impl SqliteStore {
    /// Removes the scope's memories, the distillates any of them was
    /// distilled into, their chunks, relations and markers, and the scope's
    /// conversations, all in one transaction. Every removed memory and
    /// conversation is tombstoned and the delete logged, so it wins on
    /// every peer, and the earlier log records of each removed row are
    /// reclaimed so the log keeps none of its content.
    /// `archived_sessions` are sessions the caller found in the transcript
    /// archive under this scope; their conversations are tombstoned even
    /// when the store holds nothing of them.
    pub fn delete_scope(
        &self,
        scope: &DeleteScope,
        archived_sessions: &[String],
    ) -> Result<DeleteReport> {
        check_scope(scope)?;
        self.with_txn(|tx| {
            let plan = plan(tx, scope, archived_sessions)?;
            let mut report = self.execute(tx, &plan)?;
            if !report.is_empty() {
                let (id, seq) = delete_status::record(tx, scope)?;
                report.delete_id = Some(id);
                report.seq = Some(seq);
            }
            Ok(report)
        })
    }

    fn execute(&self, tx: &Transaction<'_>, plan: &Plan) -> Result<DeleteReport> {
        let mut report = counted(tx, plan)?;
        if report.is_empty() {
            return Ok(report);
        }
        for raw in &plan.markers {
            let Ok(raw_id) = Uuid::parse_str(raw) else {
                continue;
            };
            if let Some(member) = plan.repoint.get(raw) {
                self.repoint_marker_on_tx(tx, raw_id, *member)?;
            } else if self.drop_marker_on_tx(tx, raw_id)? {
                report.counts.markers += 1;
            }
        }
        for id in &plan.restored {
            self.restore_superseded_on_tx(tx, *id)?;
        }
        for target in &plan.targets {
            report.counts.log_records += erase_memory_traces(tx, &target.id)?;
            blocklist::block_row(tx, &target.id, None)?;
            tx.execute("DELETE FROM memories WHERE id = ?1", params![target.id])?;
            let authored = self.authored_now(tx)?;
            Self::upsert_tombstone(tx, &target.id, "memory", &self.machine_id, authored)?;
            if let Ok(id) = Uuid::parse_str(&target.id) {
                Self::append_outbox(tx, id, "delete")?;
            }
            self.append_local_log_at(
                tx,
                SyncOp::Delete,
                SyncNodeType::Memory,
                &target.id,
                None,
                authored,
            )?;
        }
        for id in &plan.conversations {
            let id = id.to_string();
            report.counts.log_records += erase_conversation_traces(tx, &id)?;
            let removed = tx.execute("DELETE FROM conversations WHERE id = ?1", params![id])?;
            if removed > 0 {
                tx.execute("DELETE FROM relations WHERE to_id = ?1", params![id])?;
            }
            let authored = self.authored_now(tx)?;
            let tombstone = Tombstone {
                deleted_at: authored.timestamp_micros(),
                origin: self.machine_id.clone(),
            };
            authored_order::record_tombstone(tx, "conversation", &id, &tombstone)?;
            let data = authored_order::data_with_updated_by(
                &serde_json::json!({ "id": id }),
                &self.machine_id,
            )?;
            self.append_local_log_at(
                tx,
                SyncOp::Delete,
                SyncNodeType::Conversation,
                &id,
                Some(&data),
                authored,
            )?;
        }
        Ok(report)
    }

    /// Deletes, tombstoned and logged as this store's own, every row of an
    /// applied conversation delete's session that the deleting peer never
    /// named because it never held them, so they reach no store again.
    pub(super) fn cascade_conversation_delete(
        &self,
        tx: &Transaction<'_>,
        conversation_id: &str,
    ) -> Result<()> {
        let Ok(id) = Uuid::parse_str(conversation_id) else {
            return Ok(());
        };
        let mut matched: BTreeMap<String, Matched> = matching(
            tx,
            &format!("{MEMORY_COLUMNS} WHERE conversation_id = ?1"),
            conversation_id,
        )?
        .into_iter()
        .collect();
        let mut sessions = BTreeSet::new();
        for m in matched.values() {
            if let Some(session) = session_source(&m.source, &m.source_id)
                && Conversation::claude_code_id(&session) == id
            {
                sessions.insert(session);
            }
        }
        for key in ingested_session_keys(tx)? {
            let base = key.split('/').next().unwrap_or(&key);
            if Conversation::claude_code_id(&key) == id || Conversation::claude_code_id(base) == id
            {
                sessions.insert(base.to_string());
            }
        }
        for session in &sessions {
            matched.extend(session_rows(tx, session)?);
        }
        if matched.is_empty() {
            return Ok(());
        }
        let conversations = scope_conversations(&matched, &sessions);
        let plan = plan_of(tx, matched, conversations, sessions)?;
        self.execute(tx, &plan)?;
        Ok(())
    }

    fn repoint_marker_on_tx(&self, tx: &Transaction<'_>, raw: Uuid, member: Uuid) -> Result<()> {
        let Some((marker, _)) = authored_order::marker_stamp(tx, raw)? else {
            return Ok(());
        };
        let model = marker.model.clone().unwrap_or_default();
        self.mark_distillation_on_tx(tx, raw, member, &model, &marker.status)
    }

    fn restore_superseded_on_tx(&self, tx: &Transaction<'_>, id: Uuid) -> Result<()> {
        let changed = tx.execute(
            "UPDATE memories SET superseded_by = NULL, updated_at = ?2 \
             WHERE id = ?1 AND superseded_by IS NOT NULL",
            params![id.to_string(), Utc::now().to_rfc3339()],
        )?;
        if changed == 0 {
            return Ok(());
        }
        Self::append_outbox(tx, id, "upsert")?;
        if let Some(memory) = Self::memory_on_tx(tx, id)? {
            self.log_memory_update(tx, &memory)?;
        }
        Ok(())
    }

    /// A token while a delete applied from a peer still waits for the index
    /// compaction and cold purge the deleting daemon ran itself.
    pub fn delete_purge_requested(&self) -> Result<Option<String>> {
        Ok(self
            .reader()
            .query_row(
                "SELECT value FROM index_meta WHERE key = ?1",
                params![PURGE_REQUESTED],
                |r| r.get(0),
            )
            .optional()?)
    }

    /// Clears the request `token` named, unless a delete applied since.
    pub fn delete_purge_done(&self, token: &str) -> Result<()> {
        self.conn().execute(
            "DELETE FROM index_meta WHERE key = ?1 AND value = ?2",
            params![PURGE_REQUESTED, token],
        )?;
        Ok(())
    }

    /// What `delete_scope` would remove, counted without writing anything.
    pub fn preview_delete(
        &self,
        scope: &DeleteScope,
        archived_sessions: &[String],
    ) -> Result<DeleteReport> {
        check_scope(scope)?;
        let conn = self.reader();
        let plan = plan(&conn, scope, archived_sessions)?;
        let mut report = counted(&conn, &plan)?;
        report.counts.markers = (plan.markers.len() - plan.repoint.len()) as u64;
        Ok(report)
    }

    pub fn conversation_deleted(&self, id: Uuid) -> Result<bool> {
        conversation_tombstoned(&self.reader(), id)
    }

    /// Whether the Claude Code session a transcript at `path` belongs to was
    /// deleted, in which case nothing of it may be archived or ingested.
    pub fn session_deleted(&self, path: &str) -> Result<bool> {
        let Some(session) = session_of(path) else {
            return Ok(false);
        };
        self.conversation_deleted(Conversation::claude_code_id(&session))
    }

    /// Retires or rewrites every cold segment holding records no row points
    /// at any more, then deletes the files left without a manifest, so a
    /// deleted cold row's text leaves the disk now rather than at the next
    /// cold pass. A store without a cold tier has nothing to purge.
    pub fn purge_cold_segments(&self) -> Result<ColdPurge> {
        let Some(tier) = self.cold_tier() else {
            return Ok(ColdPurge::default());
        };
        let _pass = tier.pass_guard();
        let (retired, rewritten) = self.retire_dead_records(tier)?;
        let (removed_files, _) = self.sweep_cold_files(tier)?;
        Ok(ColdPurge {
            retired,
            rewritten,
            removed_files,
        })
    }
}

fn matching(conn: &Connection, sql: &str, value: &str) -> Result<Vec<(String, Matched)>> {
    let mut stmt = conn.prepare(sql)?;
    let rows = stmt.query_map(params![value], |r| {
        Ok((
            r.get::<_, String>(0)?,
            Matched {
                source: r.get(1)?,
                source_id: r.get(2)?,
                conversation: r.get(3)?,
            },
        ))
    })?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

fn check_scope(scope: &DeleteScope) -> Result<()> {
    match scope {
        DeleteScope::Session(key) if key.trim().is_empty() => {
            bail!("a session delete needs a session id")
        }
        DeleteScope::Project(path) if path.trim().is_empty() => {
            bail!("a project delete needs a project")
        }
        _ => Ok(()),
    }
}

/// The Claude Code session a row came from: transcript raws and the
/// distillates filed under a transcript by its path, agent notes by their
/// bare session id. Other sources (memory files, documents) have file
/// stems too, but no session.
fn session_source(source: &str, source_id: &str) -> Option<String> {
    let transcript =
        matches!(source, "claude-code" | "consolidation") && source_id.ends_with(".jsonl");
    if transcript || source == AGENT_NOTE_SOURCE {
        session_of(source_id)
    } else {
        None
    }
}

/// Whether `memory` belongs to a deleted conversation or session, so no
/// local or applied write may store it again. Checked inside the writing
/// transaction, which a concurrent delete commits before or after whole.
pub(super) fn in_deleted_session(conn: &Connection, memory: &Memory) -> Result<bool> {
    if let Some(c) = memory.conversation_id
        && conversation_tombstoned(conn, c)?
    {
        return Ok(true);
    }
    match session_source(&memory.source, &memory.source_id) {
        Some(session) => conversation_tombstoned(conn, Conversation::claude_code_id(&session)),
        None => Ok(false),
    }
}

/// Asks the daemon to compact its indexes and purge cold segments, as the
/// deleting daemon did, once a peer's delete has applied here.
pub(super) fn request_purge(tx: &Transaction<'_>) -> Result<()> {
    tx.execute(
        "INSERT INTO index_meta (key, value) VALUES (?1, '1') \
         ON CONFLICT(key) DO UPDATE SET value = CAST(value AS INTEGER) + 1",
        params![PURGE_REQUESTED],
    )?;
    Ok(())
}

fn ingested_session_keys(conn: &Connection) -> Result<Vec<String>> {
    let mut stmt =
        conn.prepare("SELECT DISTINCT session_key FROM ingest_log WHERE session_key IS NOT NULL")?;
    let keys = stmt
        .query_map([], |r| r.get(0))?
        .collect::<rusqlite::Result<_>>()?;
    Ok(keys)
}

/// A session's rows by the session their source names, or by the
/// conversation its main transcript was ingested under; neither needs a
/// project path, which older rows may lack.
fn session_rows(conn: &Connection, key: &str) -> Result<Vec<(String, Matched)>> {
    let mut rows = matching(
        conn,
        &format!("{MEMORY_COLUMNS} WHERE instr(source_id, ?1) > 0"),
        key,
    )?;
    rows.retain(|(_, m)| session_source(&m.source, &m.source_id).as_deref() == Some(key));
    rows.extend(matching(
        conn,
        &format!("{MEMORY_COLUMNS} WHERE conversation_id = ?1"),
        &Conversation::claude_code_id(key).to_string(),
    )?);
    Ok(rows)
}

/// The named memory and every earlier version it superseded: deleting a
/// fact leaves none of its paraphrases to come back.
fn versions_of(conn: &Connection, id: Uuid) -> Result<BTreeMap<String, Matched>> {
    let mut found = BTreeMap::new();
    let mut frontier = vec![id.to_string()];
    let mut older = conn.prepare("SELECT id FROM memories WHERE superseded_by = ?1")?;
    while let Some(id) = frontier.pop() {
        if found.contains_key(&id) {
            continue;
        }
        let Some((_, m)) = matching(conn, &format!("{MEMORY_COLUMNS} WHERE id = ?1"), &id)?
            .into_iter()
            .next()
        else {
            continue;
        };
        for prior in older.query_map(params![id], |r| r.get::<_, String>(0))? {
            frontier.push(prior?);
        }
        found.insert(id, m);
    }
    Ok(found)
}

fn plan(conn: &Connection, scope: &DeleteScope, archived_sessions: &[String]) -> Result<Plan> {
    let matched: BTreeMap<String, Matched> = match scope {
        DeleteScope::Memory(id) => versions_of(conn, *id)?,
        DeleteScope::Session(key) => session_rows(conn, key)?.into_iter().collect(),
        DeleteScope::Project(path) => {
            let mut rows = matching(
                conn,
                &format!("{MEMORY_COLUMNS} WHERE project_path = ?1"),
                path,
            )?;
            for session in archived_sessions {
                rows.extend(session_rows(conn, session)?);
            }
            rows.into_iter().collect()
        }
    };
    let sessions = scope_sessions(scope, &matched, archived_sessions);
    let mut conversations = BTreeSet::new();
    match scope {
        DeleteScope::Memory(_) => {}
        DeleteScope::Session(_) => conversations = scope_conversations(&matched, &sessions),
        DeleteScope::Project(path) => {
            conversations = scope_conversations(&matched, &sessions);
            let mut stmt = conn.prepare("SELECT id FROM conversations WHERE project_path = ?1")?;
            for id in stmt.query_map(params![path], |r| r.get::<_, String>(0))? {
                if let Ok(id) = Uuid::parse_str(&id?) {
                    conversations.insert(id);
                }
            }
        }
    }
    plan_of(conn, matched, conversations, sessions)
}

fn scope_conversations(
    matched: &BTreeMap<String, Matched>,
    sessions: &BTreeSet<String>,
) -> BTreeSet<Uuid> {
    let mut conversations: BTreeSet<Uuid> = matched
        .values()
        .filter_map(|m| m.conversation.as_deref())
        .filter_map(|c| Uuid::parse_str(c).ok())
        .collect();
    conversations.extend(sessions.iter().map(|s| Conversation::claude_code_id(s)));
    conversations
}

fn plan_of(
    conn: &Connection,
    matched: BTreeMap<String, Matched>,
    conversations: BTreeSet<Uuid>,
    sessions: BTreeSet<String>,
) -> Result<Plan> {
    let mut distilled_into = BTreeSet::new();
    let mut markers = BTreeSet::new();
    {
        let mut by_raw =
            conn.prepare("SELECT distilled_id FROM distillation_log WHERE memory_id = ?1")?;
        let mut onto =
            conn.prepare("SELECT memory_id FROM distillation_log WHERE distilled_id = ?1")?;
        for id in matched.keys() {
            for distilled in by_raw.query_map(params![id], |r| r.get::<_, Option<String>>(0))? {
                if let Some(distilled) = distilled? {
                    distilled_into.insert(distilled);
                }
                markers.insert(id.clone());
            }
        }
        for id in matched.keys().chain(distilled_into.iter()) {
            for raw in onto.query_map(params![id], |r| r.get::<_, String>(0))? {
                markers.insert(raw?);
            }
        }
    }

    let mut targets = Vec::new();
    let mut exists = conn.prepare("SELECT EXISTS (SELECT 1 FROM memories WHERE id = ?1)")?;
    let mut is_distillate =
        conn.prepare("SELECT EXISTS (SELECT 1 FROM distillation_log WHERE distilled_id = ?1)")?;
    let extra = distilled_into
        .iter()
        .filter(|d| !matched.contains_key(d.as_str()));
    for id in matched.keys().chain(extra) {
        if !exists.query_row(params![id], |r| r.get::<_, bool>(0))? {
            continue;
        }
        targets.push(Target {
            id: id.clone(),
            distillate: is_distillate.query_row(params![id], |r| r.get::<_, bool>(0))?,
        });
    }

    let doomed: BTreeSet<String> = targets.iter().map(|t| t.id.clone()).collect();
    let revived = restore_plan(conn, &doomed, &markers)?;
    for id in revived.derived {
        targets.push(Target {
            id: id.to_string(),
            distillate: true,
        });
    }
    let (restored, repoint) = (revived.restored, revived.repoint);

    let mut pending = BTreeSet::new();
    for id in conversations {
        let held: bool = conn.query_row(
            "SELECT EXISTS (SELECT 1 FROM conversations WHERE id = ?1)",
            params![id.to_string()],
            |r| r.get(0),
        )?;
        if held || !conversation_tombstoned(conn, id)? {
            pending.insert(id);
        }
    }
    Ok(Plan {
        targets,
        markers,
        repoint,
        restored,
        conversations: pending,
        sessions,
    })
}

struct Revived {
    restored: Vec<Uuid>,
    derived: Vec<Uuid>,
    repoint: BTreeMap<String, Uuid>,
}

#[derive(Clone)]
struct Superseded {
    id: String,
    source: String,
    source_id: String,
}

/// The memories each removed row superseded, and below them the ones those
/// superseded, as merges of merges leave them.
struct SupersedeTree<'c> {
    older: rusqlite::Statement<'c>,
    doomed: &'c BTreeSet<String>,
    fed_sessions: &'c BTreeSet<String>,
    tainted: BTreeMap<String, bool>,
}

impl<'c> SupersedeTree<'c> {
    fn new(
        conn: &'c Connection,
        doomed: &'c BTreeSet<String>,
        fed_sessions: &'c BTreeSet<String>,
    ) -> Result<Self> {
        Ok(Self {
            older: conn
                .prepare("SELECT id, source, source_id FROM memories WHERE superseded_by = ?1")?,
            doomed,
            fed_sessions,
            tainted: BTreeMap::new(),
        })
    }

    fn children(&mut self, id: &str) -> Result<Vec<Superseded>> {
        let rows = self.older.query_map(params![id], |r| {
            Ok(Superseded {
                id: r.get(0)?,
                source: r.get(1)?,
                source_id: r.get(2)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }

    /// A distillate summarising a removed row: one of a session whose raw
    /// fed a removed distillate, or a merge of anything removed or tainted.
    fn tainted(&mut self, node: &Superseded) -> Result<bool> {
        if let Some(known) = self.tainted.get(&node.id) {
            return Ok(*known);
        }
        self.tainted.insert(node.id.clone(), false);
        let tainted = if node.source != "consolidation" {
            false
        } else if session_source(&node.source, &node.source_id)
            .is_some_and(|s| self.fed_sessions.contains(&s))
        {
            true
        } else {
            let mut any = false;
            for child in self.children(&node.id)? {
                if self.doomed.contains(&child.id) || self.tainted(&child)? {
                    any = true;
                    break;
                }
            }
            any
        };
        self.tainted.insert(node.id.clone(), tainted);
        Ok(tainted)
    }
}

/// A near-duplicate merge or a correction supersedes memories of other
/// sessions; removing the superseding row must make them live again, or
/// recall loses them for good. A superseded member of the session of a
/// removed raw that fed the removed distillate summarised that raw, so it
/// goes too. A raw outside the scope whose marker named a removed
/// distillate moves to the restored member of its own session.
fn restore_plan(
    conn: &Connection,
    doomed: &BTreeSet<String>,
    markers: &BTreeSet<String>,
) -> Result<Revived> {
    let mut marker = conn.prepare(
        "SELECT d.distilled_id, m.source, m.source_id FROM distillation_log d \
         JOIN memories m ON m.id = d.memory_id WHERE d.memory_id = ?1",
    )?;
    let mut marker_of = |raw: &str| -> Result<Option<(Option<String>, String, String)>> {
        Ok(marker
            .query_row(params![raw], |r| {
                Ok((
                    r.get::<_, Option<String>>(0)?,
                    r.get::<_, String>(1)?,
                    r.get::<_, String>(2)?,
                ))
            })
            .optional()?)
    };
    let mut fed_sessions = BTreeSet::new();
    for id in doomed {
        if let Some((Some(distilled), source, source_id)) = marker_of(id)?
            && distilled != *id
            && doomed.contains(&distilled)
            && let Some(session) = session_source(&source, &source_id)
        {
            fed_sessions.insert(session);
        }
    }
    let mut tree = SupersedeTree::new(conn, doomed, &fed_sessions)?;
    let mut restored: BTreeMap<Uuid, Option<String>> = BTreeMap::new();
    let mut derived = Vec::new();
    let mut frontier: Vec<String> = doomed.iter().cloned().collect();
    let mut visited = BTreeSet::new();
    while let Some(parent) = frontier.pop() {
        for child in tree.children(&parent)? {
            if doomed.contains(&child.id) || !visited.insert(child.id.clone()) {
                continue;
            }
            let Ok(id) = Uuid::parse_str(&child.id) else {
                continue;
            };
            if tree.tainted(&child)? {
                derived.push(id);
                frontier.push(child.id);
            } else {
                restored.insert(id, session_source(&child.source, &child.source_id));
            }
        }
    }
    let mut repoint = BTreeMap::new();
    if !restored.is_empty() {
        for raw in markers {
            if doomed.contains(raw) {
                continue;
            }
            let Some((distilled, source, source_id)) = marker_of(raw)? else {
                continue;
            };
            if !distilled.is_some_and(|d| doomed.contains(&d)) {
                continue;
            }
            let Some(session) = session_source(&source, &source_id) else {
                continue;
            };
            if let Some((member, _)) = restored
                .iter()
                .find(|(_, s)| s.as_deref() == Some(session.as_str()))
            {
                repoint.insert(raw.clone(), *member);
            }
        }
    }
    derived.sort();
    derived.dedup();
    Ok(Revived {
        restored: restored.into_keys().collect(),
        derived,
        repoint,
    })
}

/// A session counts as deleted once anything of it matched: a stored row
/// or a transcript the caller found in the archive.
fn scope_sessions(
    scope: &DeleteScope,
    matched: &BTreeMap<String, Matched>,
    archived_sessions: &[String],
) -> BTreeSet<String> {
    match scope {
        DeleteScope::Memory(_) => BTreeSet::new(),
        DeleteScope::Session(key) => {
            if matched.is_empty() && archived_sessions.is_empty() {
                BTreeSet::new()
            } else {
                BTreeSet::from([key.clone()])
            }
        }
        DeleteScope::Project(_) => {
            let mut sessions: BTreeSet<String> = archived_sessions.iter().cloned().collect();
            for m in matched.values() {
                if let Some(session) = session_source(&m.source, &m.source_id) {
                    sessions.insert(session);
                }
            }
            sessions
        }
    }
}

fn conversation_tombstoned(conn: &Connection, id: Uuid) -> Result<bool> {
    Ok(conn.query_row(
        "SELECT EXISTS (SELECT 1 FROM type_tombstones \
         WHERE node_type = 'conversation' AND node_id = ?1)",
        params![id.to_string()],
        |r| r.get(0),
    )?)
}

fn count(conn: &Connection, sql: &str, id: &str) -> Result<u64> {
    Ok(conn.query_row(sql, params![id], |r| r.get::<_, i64>(0))? as u64)
}

fn counted(conn: &Connection, plan: &Plan) -> Result<DeleteReport> {
    let mut counts = DeleteCounts::default();
    let mut memory_ids = Vec::new();
    let mut relations = BTreeSet::new();
    let mut related = conn.prepare(
        "SELECT from_id || ':' || to_id || ':' || relation_type FROM relations \
         WHERE from_id = ?1 OR to_id = ?1",
    )?;
    for target in &plan.targets {
        let id = target.id.as_str();
        if target.distillate {
            counts.distillates += 1;
        } else {
            counts.memories += 1;
        }
        counts.chunks += count(
            conn,
            "SELECT COUNT(*) FROM memory_chunks WHERE memory_id = ?1",
            id,
        )?;
        counts.vector_keys += count(
            conn,
            "SELECT COUNT(*) FROM vec_keys WHERE memory_id = ?1",
            id,
        )?;
        counts.chunk_vector_keys += count(
            conn,
            "SELECT COUNT(*) FROM chunk_vec_keys WHERE memory_id = ?1",
            id,
        )?;
        counts.bm25 += count(
            conn,
            "SELECT COUNT(*) FROM memories WHERE id = ?1 AND tier = 'hot' AND superseded_by IS NULL",
            id,
        )?;
        counts.cold_records += count(
            conn,
            "SELECT COUNT(*) FROM memories WHERE id = ?1 AND archived_segment IS NOT NULL",
            id,
        )?;
        for key in related.query_map(params![id], |r| r.get::<_, String>(0))? {
            relations.insert(key?);
        }
        if let Ok(uuid) = Uuid::parse_str(id) {
            memory_ids.push(uuid);
        }
    }
    for id in &plan.conversations {
        counts.conversations += count(
            conn,
            "SELECT COUNT(*) FROM conversations WHERE id = ?1",
            &id.to_string(),
        )?;
    }
    counts.relations = relations.len() as u64;
    counts.restored = plan.restored.len() as u64;
    Ok(DeleteReport {
        counts,
        memory_ids,
        sessions: plan.sessions.iter().cloned().collect(),
        conversations: plan.conversations.iter().copied().collect(),
        delete_id: None,
        seq: None,
    })
}

/// Drops what a removed memory leaves outside its row: its chunks, its
/// relations, and its earlier create and update log records with their
/// relations', which carry its content. Those records go as repair's log
/// GC reclaims them, keys kept in `sync_dedup`, so a relay of one is still
/// skipped and a puller that never read them gets only the delete. Runs in
/// the transaction that logs the memory's delete; returns the records
/// reclaimed.
pub(super) fn erase_memory_traces(tx: &Transaction<'_>, memory_id: &str) -> Result<u64> {
    tx.execute(
        "DELETE FROM memory_chunks WHERE memory_id = ?1",
        params![memory_id],
    )?;
    let relation_keys: Vec<String> = {
        let mut stmt = tx.prepare(
            "SELECT from_id || ':' || to_id || ':' || relation_type FROM relations \
             WHERE from_id = ?1 OR to_id = ?1",
        )?;
        stmt.query_map(params![memory_id], |r| r.get(0))?
            .collect::<rusqlite::Result<_>>()?
    };
    tx.execute(
        "DELETE FROM relations WHERE from_id = ?1 OR to_id = ?1",
        params![memory_id],
    )?;
    let mut reclaimed = reclaim_writes(tx, "memory", memory_id)?;
    settled::drop_failed_of(tx, memory_id)?;
    for key in &relation_keys {
        reclaimed += reclaim_writes(tx, "relation", key)?;
        settled::drop_failed_of(tx, key)?;
    }
    Ok(reclaimed)
}

/// The conversation counterpart of `erase_memory_traces`: its log records
/// carry its project path, and its distillate state goes with it.
pub(super) fn erase_conversation_traces(
    tx: &Transaction<'_>,
    conversation_id: &str,
) -> Result<u64> {
    tx.execute(
        "DELETE FROM distillates WHERE conversation_id = ?1",
        params![conversation_id],
    )?;
    settled::drop_failed_of(tx, conversation_id)?;
    reclaim_writes(tx, "conversation", conversation_id)
}

fn reclaim_writes(tx: &Transaction<'_>, node_type: &str, node_id: &str) -> Result<u64> {
    let seqs: Vec<i64> = {
        let mut stmt = tx.prepare(
            "SELECT local_seq FROM sync_log \
             WHERE node_type = ?1 AND node_id = ?2 AND op IN ('create', 'update')",
        )?;
        stmt.query_map(params![node_type, node_id], |r| r.get(0))?
            .collect::<rusqlite::Result<_>>()?
    };
    if seqs.is_empty() {
        return Ok(0);
    }
    sync_dedup::keep_keys_of(tx, &seqs)?;
    let mut removed = 0;
    for seq in &seqs {
        removed += tx.execute("DELETE FROM sync_log WHERE local_seq = ?1", params![seq])? as u64;
    }
    Ok(removed)
}