second-brain-core 0.11.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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
mod chunks;
mod compaction;
mod ddl;
mod payload_redaction;
pub(crate) mod pool;
mod rewrite;
mod stored_redaction;
mod sync_apply;
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;

pub use chunks::{ChunkWork, MemoryChunk};
pub use compaction::VacuumSpace;
pub use ddl::{BASELINE_VERSION, SCHEMA_VERSION};
pub use rewrite::RewriteOutcome;
pub use stored_redaction::{KindCounts, RedactionPhase, RedactionReport, RedactionRun, SkippedRow};

use std::collections::HashSet;
use std::path::Path;
use std::sync::{Mutex, MutexGuard};

use anyhow::Result;
use chrono::{DateTime, Utc};
use rusqlite::{Connection, OptionalExtension, Row, Transaction, params};
use uuid::Uuid;

use crate::schema::{
    Conversation, Distillation, Entity, Memory, MemoryType, Relation, RelationType, SyncNodeType,
    SyncOp, Tier,
};
use crate::store::Store;

pub(crate) const MEMORY_COLS: &str = "id, content, context, memory_type, confidence, created_at, updated_at, \
     last_accessed, access_count, source, source_id, project_path, machine_id, conversation_id, \
     tier, archived_segment, superseded_by, retired_reason, session_at";

/// Cap on what one `traverse` call returns. The walk also stops expanding
/// after `TRAVERSE_MAX_WALK` (id, depth) pairs, because a hub entity can
/// connect one memory to tens of thousands and the context pack that asks
/// only shows a handful.
pub const TRAVERSE_MAX_RESULTS: usize = 50;
const TRAVERSE_MAX_WALK: i64 = 2000;

/// The characters `str::trim` strips (every char with the Unicode White_Space
/// property) as a SQLite `char()` call, so the dedup key trims in SQL exactly
/// as `remember` trims in Rust. It must match the expression in
/// migrations/0003_memories_dedup_key.sql, or the dedup lookup stops reading
/// that index and scans the table instead.
const DEDUP_TRIM_SET: &str = "char(9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, \
     8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288)";

/// The oldest live memory whose dedup key equals ?1, a key the caller has
/// already trimmed and lowercased. `idx_memories_dedup_key` indexes the
/// 128-character prefix, so the full comparison runs only on rows sharing
/// it. `+project_path` keeps the planner off the project_path index, which
/// would read a whole project instead of the few rows the key names.
fn dedup_query(with_project: bool) -> String {
    let project = if with_project {
        " AND +project_path = ?2"
    } else {
        ""
    };
    format!(
        "SELECT {MEMORY_COLS} FROM memories \
         WHERE substr(lower(trim(content, {DEDUP_TRIM_SET})), 1, 128) = substr(?1, 1, 128) \
         AND lower(trim(content, {DEDUP_TRIM_SET})) = ?1 \
         AND tier = 'hot' AND superseded_by IS NULL{project} \
         ORDER BY rowid LIMIT 1"
    )
}

/// Every write (via `with_txn` or a direct `execute`) goes through `writer`,
/// the single connection WAL reserves for the one process-wide writer. Reads
/// go through `readers`: a pool of separate connections in file-backed mode,
/// or the same connection as the writer for `in_memory`, where a second
/// connection would just see an empty, unrelated database.
pub struct SqliteStore {
    writer: Mutex<Connection>,
    readers: ReadBackend,
    machine_id: String,
}

enum ReadBackend {
    Pooled(pool::ReaderPool),
    SameAsWriter,
}

#[allow(private_interfaces)]
pub(crate) enum ReaderGuard<'a> {
    Pooled(pool::PooledConn<'a>),
    Writer(MutexGuard<'a, Connection>),
}

impl std::ops::Deref for ReaderGuard<'_> {
    type Target = Connection;

    fn deref(&self) -> &Connection {
        match self {
            ReaderGuard::Pooled(p) => p,
            ReaderGuard::Writer(g) => g,
        }
    }
}

impl SqliteStore {
    pub fn open(path: &Path, machine_id: String) -> Result<Self> {
        Self::open_with_pool_size(path, machine_id, pool::default_pool_size())
    }

    /// Same as `open`, with an explicit reader pool size instead of the
    /// parallelism-derived default. `reader_pool_size` is clamped to at
    /// least 1 so a caller passing 0 still gets a working store.
    pub fn open_with_pool_size(
        path: &Path,
        machine_id: String,
        reader_pool_size: usize,
    ) -> Result<Self> {
        let writer = pool::open_connection(path)?;
        ddl::init_schema(&writer)?;
        let readers = pool::ReaderPool::open(path, reader_pool_size.max(1))?;
        Ok(Self {
            writer: Mutex::new(writer),
            readers: ReadBackend::Pooled(readers),
            machine_id,
        })
    }

    pub fn in_memory(machine_id: String) -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        ddl::init_schema(&conn)?;
        Ok(Self {
            writer: Mutex::new(conn),
            readers: ReadBackend::SameAsWriter,
            machine_id,
        })
    }

    pub fn machine_id(&self) -> &str {
        &self.machine_id
    }

    pub(crate) fn conn(&self) -> MutexGuard<'_, Connection> {
        self.writer.lock().unwrap()
    }

    pub(crate) fn reader(&self) -> ReaderGuard<'_> {
        match &self.readers {
            ReadBackend::Pooled(pool) => ReaderGuard::Pooled(pool.checkout()),
            ReadBackend::SameAsWriter => ReaderGuard::Writer(self.writer.lock().unwrap()),
        }
    }

    pub(crate) fn with_txn<T>(&self, f: impl FnOnce(&Transaction<'_>) -> Result<T>) -> Result<T> {
        let mut conn = self.conn();
        let tx = conn.transaction()?;
        let value = f(&tx)?;
        tx.commit()?;
        Ok(value)
    }

    pub fn tombstone_exists(&self, id: Uuid) -> Result<bool> {
        let conn = self.reader();
        let hit: Option<i64> = conn
            .query_row(
                "SELECT 1 FROM tombstones WHERE node_id = ?1",
                params![id.to_string()],
                |r| r.get(0),
            )
            .optional()?;
        Ok(hit.is_some())
    }

    pub fn memory_content_exists(&self, content_prefix: &str) -> Result<bool> {
        let conn = self.reader();
        let hit: Option<i64> = conn
            .query_row(
                "SELECT 1 FROM memories WHERE substr(content, 1, length(?1)) = ?1 LIMIT 1",
                params![content_prefix],
                |r| r.get(0),
            )
            .optional()?;
        Ok(hit.is_some())
    }

    pub fn max_sync_seq(&self) -> Result<u64> {
        let conn = self.reader();
        let max: i64 = conn.query_row(
            "SELECT COALESCE(MAX(local_seq), 0) FROM sync_log",
            [],
            |r| r.get(0),
        )?;
        Ok(max as u64)
    }

    /// The highest migration applied to the database file, which exceeds
    /// `SCHEMA_VERSION` when a newer binary migrated it.
    pub fn schema_version(&self) -> Result<i64> {
        ddl::schema_version(&self.reader())
    }

    pub fn get_conversation(&self, id: Uuid) -> Result<Option<Conversation>> {
        let conn = self.reader();
        conn.query_row(
            "SELECT id, source, machine_id, started_at, project_path FROM conversations WHERE id = ?1",
            params![id.to_string()],
            |r| {
                Ok(Conversation {
                    id: parse_uuid(&r.get::<_, String>(0)?)?,
                    source: r.get(1)?,
                    machine_id: r.get(2)?,
                    started_at: parse_dt(&r.get::<_, String>(3)?)?,
                    project_path: r.get(4)?,
                })
            },
        )
        .optional()
        .map_err(Into::into)
    }

    fn insert_memory(tx: &Transaction<'_>, memory: &Memory) -> Result<()> {
        let embedding = if memory.embedding.is_empty() {
            None
        } else {
            Some(embedding_to_blob(&memory.embedding))
        };
        tx.execute(
            &format!(
                "INSERT OR REPLACE INTO memories ({MEMORY_COLS}, embedding) \
                 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20)"
            ),
            params![
                memory.id.to_string(),
                memory.content,
                memory.context,
                memory_type_to_str(memory.memory_type),
                memory.confidence as f64,
                memory.created_at.to_rfc3339(),
                memory.updated_at.to_rfc3339(),
                memory.last_accessed.to_rfc3339(),
                memory.access_count as i64,
                memory.source,
                memory.source_id,
                memory.project_path,
                memory.machine_id,
                memory.conversation_id.map(|u| u.to_string()),
                tier_to_str(memory.tier),
                memory.archived_segment,
                memory.superseded_by.map(|u| u.to_string()),
                memory.retired_reason,
                memory.session_at.map(|t| t.to_rfc3339()),
                embedding,
            ],
        )?;
        Ok(())
    }

    pub(crate) fn append_outbox(tx: &Transaction<'_>, memory_id: Uuid, op: &str) -> Result<()> {
        tx.execute(
            "INSERT INTO index_outbox (memory_id, op) VALUES (?1, ?2)",
            params![memory_id.to_string(), op],
        )?;
        Ok(())
    }

    fn tombstoned(tx: &Transaction<'_>, id: Uuid) -> Result<bool> {
        Self::tombstone_row_exists(tx, &id.to_string())
    }

    /// String-keyed sibling of `tombstoned`: memory sync records carry
    /// node_id as a String, and not every value is guaranteed to parse as
    /// a Uuid, so the import-side idempotency check needs this instead of
    /// forcing a parse first.
    fn tombstone_row_exists(tx: &Transaction<'_>, node_id: &str) -> Result<bool> {
        let hit: Option<i64> = tx
            .query_row(
                "SELECT 1 FROM tombstones WHERE node_id = ?1",
                params![node_id],
                |r| r.get(0),
            )
            .optional()?;
        Ok(hit.is_some())
    }

    fn upsert_tombstone(
        tx: &Transaction<'_>,
        node_id: &str,
        node_type: &str,
        machine_id: &str,
    ) -> Result<()> {
        tx.execute(
            "INSERT INTO tombstones (node_id, node_type, deleted_at, machine_id) VALUES (?1,?2,?3,?4) \
             ON CONFLICT(node_id) DO UPDATE SET node_type = excluded.node_type, \
             deleted_at = excluded.deleted_at, machine_id = excluded.machine_id",
            params![node_id, node_type, Utc::now().to_rfc3339(), machine_id],
        )?;
        Ok(())
    }

    fn insert_distillation(tx: &Transaction<'_>, entry: &Distillation) -> Result<()> {
        tx.execute(
            "INSERT OR REPLACE INTO distillation_log \
             (memory_id, distilled_id, distilled_at, model, status) VALUES (?1,?2,?3,?4,?5)",
            params![
                entry.memory_id.to_string(),
                entry.distilled_id.map(|v| v.to_string()),
                entry.distilled_at.map(|v| v.to_rfc3339()),
                entry.model,
                entry.status,
            ],
        )?;
        Ok(())
    }

    pub(crate) fn append_sync_log(
        tx: &Transaction<'_>,
        op: SyncOp,
        node_type: SyncNodeType,
        node_id: &str,
        data: Option<&str>,
        origin_machine_id: &str,
        origin_seq: Option<i64>,
    ) -> Result<()> {
        let local_seq: i64 = tx.query_row(
            "SELECT COALESCE(MAX(local_seq), 0) + 1 FROM sync_log",
            [],
            |r| r.get(0),
        )?;
        let origin_seq = origin_seq.unwrap_or(local_seq);
        let id = format!("{origin_machine_id}:{origin_seq}");
        let duplicate: Option<i64> = tx
            .query_row("SELECT 1 FROM sync_log WHERE id = ?1", params![id], |r| {
                r.get(0)
            })
            .optional()?;
        if duplicate.is_some() {
            return Ok(());
        }
        tx.execute(
            "INSERT INTO sync_log (id, local_seq, origin_machine_id, origin_seq, op, node_type, \
             node_id, timestamp, data) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
            params![
                id,
                local_seq,
                origin_machine_id,
                origin_seq,
                sync_op_to_str(op),
                sync_node_type_to_str(node_type),
                node_id,
                Utc::now().to_rfc3339(),
                data,
            ],
        )?;
        Ok(())
    }
}

impl SqliteStore {
    /// False when `memory.id` is tombstoned: sync deletes must win over
    /// re-ingest replays, so the write is skipped entirely.
    pub(crate) fn store_memory_on_tx(&self, tx: &Transaction<'_>, memory: &Memory) -> Result<bool> {
        if Self::tombstoned(tx, memory.id)? {
            return Ok(false);
        }
        let data = serde_json::to_string(memory).ok();
        Self::insert_memory(tx, memory)?;
        Self::append_outbox(tx, memory.id, "upsert")?;
        Self::append_sync_log(
            tx,
            SyncOp::Create,
            SyncNodeType::Memory,
            &memory.id.to_string(),
            data.as_deref(),
            &self.machine_id,
            None,
        )?;
        Ok(true)
    }

    /// Stores `memory` only when its id is neither a row (in any state) nor
    /// tombstoned, checked in the writer transaction so two writers of the
    /// same id cannot both insert; `insert_memory` would otherwise replace a
    /// retired row. True when it wrote.
    pub fn store_memory_if_absent(&self, memory: &Memory) -> Result<bool> {
        self.with_txn(|tx| {
            if Self::memory_on_tx(tx, memory.id)?.is_some() {
                return Ok(false);
            }
            self.store_memory_on_tx(tx, memory)
        })
    }

    /// Deletes the edge and logs the delete so a peer drops it too instead of
    /// pushing it back on the next sync. False when no such edge existed.
    pub(crate) fn delete_relation_on_tx(
        &self,
        tx: &Transaction<'_>,
        relation: &Relation,
    ) -> Result<bool> {
        let rel_type = relation_type_to_str(relation.relation_type);
        let changed = tx.execute(
            "DELETE FROM relations WHERE from_id = ?1 AND to_id = ?2 AND relation_type = ?3",
            params![
                relation.from_id.to_string(),
                relation.to_id.to_string(),
                rel_type,
            ],
        )?;
        if changed == 0 {
            return Ok(false);
        }
        let node_id = format!("{}:{}:{}", relation.from_id, relation.to_id, rel_type);
        let data = serde_json::to_string(relation).ok();
        Self::append_sync_log(
            tx,
            SyncOp::Delete,
            SyncNodeType::Relation,
            &node_id,
            data.as_deref(),
            &self.machine_id,
            None,
        )?;
        Ok(true)
    }

    pub(crate) fn store_entity_on_tx(
        &self,
        tx: &Transaction<'_>,
        entity: &Entity,
        op: SyncOp,
    ) -> Result<()> {
        let data = serde_json::to_string(entity).ok();
        let embedding = if entity.embedding.is_empty() {
            None
        } else {
            Some(embedding_to_blob(&entity.embedding))
        };
        tx.execute(
            "INSERT OR REPLACE INTO entities (id, name, entity_type, embedding, aliases) \
             VALUES (?1,?2,?3,?4,?5)",
            params![
                entity.id.to_string(),
                entity.name,
                entity.entity_type,
                embedding,
                serde_json::to_string(&entity.aliases)?,
            ],
        )?;
        Self::append_sync_log(
            tx,
            op,
            SyncNodeType::Entity,
            &entity.id.to_string(),
            data.as_deref(),
            &self.machine_id,
            None,
        )
    }

    pub(crate) fn store_relation_on_tx(
        &self,
        tx: &Transaction<'_>,
        relation: &Relation,
    ) -> Result<()> {
        let rel_type = relation_type_to_str(relation.relation_type);
        let node_id = format!("{}:{}:{}", relation.from_id, relation.to_id, rel_type);
        let data = serde_json::to_string(relation).ok();
        tx.execute(
            "INSERT INTO relations (from_id, to_id, relation_type, strength, context, created_at) \
             VALUES (?1,?2,?3,?4,?5,?6) \
             ON CONFLICT(from_id, to_id, relation_type) DO UPDATE SET \
             strength = excluded.strength, context = excluded.context",
            params![
                relation.from_id.to_string(),
                relation.to_id.to_string(),
                rel_type,
                relation.strength as f64,
                relation.context,
                Utc::now().to_rfc3339(),
            ],
        )?;
        Self::append_sync_log(
            tx,
            SyncOp::Create,
            SyncNodeType::Relation,
            &node_id,
            data.as_deref(),
            &self.machine_id,
            None,
        )
    }
}

impl Store for SqliteStore {
    fn store_memory(&self, memory: &Memory) -> Result<()> {
        self.with_txn(|tx| self.store_memory_on_tx(tx, memory).map(|_| ()))
    }

    fn get_memory(&self, id: Uuid) -> Result<Option<Memory>> {
        let conn = self.reader();
        conn.query_row(
            &format!("SELECT {MEMORY_COLS} FROM memories WHERE id = ?1"),
            params![id.to_string()],
            |r| row_to_memory(r, false),
        )
        .optional()
        .map_err(Into::into)
    }

    fn get_memory_with_embedding(&self, id: Uuid) -> Result<Option<Memory>> {
        let conn = self.reader();
        conn.query_row(
            &format!("SELECT {MEMORY_COLS}, embedding FROM memories WHERE id = ?1"),
            params![id.to_string()],
            |r| row_to_memory(r, true),
        )
        .optional()
        .map_err(Into::into)
    }

    fn delete_memory(&self, id: Uuid) -> Result<()> {
        self.remove_memory(id).map(|_| ())
    }

    fn remove_memory(&self, id: Uuid) -> Result<bool> {
        let id_string = id.to_string();
        self.with_txn(|tx| {
            let removed = tx.execute("DELETE FROM memories WHERE id = ?1", params![id_string])?;
            // Only a row that was actually here has anything to tombstone,
            // evict from the indexes, or tell peers about. Re-logging an id
            // already gone grew sync_log to 32M delete rows against 88k real
            // deletions, and a forget of an id this machine never held would
            // otherwise mint a tombstone and a sync entry for nothing.
            if removed == 0 {
                return Ok(false);
            }
            tx.execute(
                "DELETE FROM relations WHERE from_id = ?1 OR to_id = ?1",
                params![id_string],
            )?;
            Self::upsert_tombstone(tx, &id_string, "memory", &self.machine_id)?;
            Self::append_outbox(tx, id, "delete")?;
            Self::append_sync_log(
                tx,
                SyncOp::Delete,
                SyncNodeType::Memory,
                &id_string,
                None,
                &self.machine_id,
                None,
            )?;
            Ok(true)
        })
    }

    fn store_entity(&self, entity: &Entity) -> Result<()> {
        self.with_txn(|tx| self.store_entity_on_tx(tx, entity, SyncOp::Create))
    }

    fn get_entity(&self, id: Uuid) -> Result<Option<Entity>> {
        let conn = self.reader();
        conn.query_row(
            "SELECT id, name, entity_type, embedding, aliases FROM entities WHERE id = ?1",
            params![id.to_string()],
            row_to_entity,
        )
        .optional()
        .map_err(Into::into)
    }

    fn find_entity_by_name(&self, name: &str) -> Result<Option<Entity>> {
        let conn = self.reader();
        conn.query_row(
            "SELECT id, name, entity_type, embedding, aliases FROM entities WHERE name = ?1 LIMIT 1",
            params![name],
            row_to_entity,
        )
        .optional()
        .map_err(Into::into)
    }

    fn store_conversation(&self, conversation: &Conversation) -> Result<()> {
        let data = serde_json::to_string(conversation).ok();
        self.with_txn(|tx| {
            tx.execute(
                "INSERT OR REPLACE INTO conversations (id, source, machine_id, started_at, project_path) \
                 VALUES (?1,?2,?3,?4,?5)",
                params![
                    conversation.id.to_string(),
                    conversation.source,
                    conversation.machine_id,
                    conversation.started_at.to_rfc3339(),
                    conversation.project_path,
                ],
            )?;
            Self::append_sync_log(
                tx,
                SyncOp::Create,
                SyncNodeType::Conversation,
                &conversation.id.to_string(),
                data.as_deref(),
                &self.machine_id,
                None,
            )
        })
    }

    fn store_relation(&self, relation: &Relation) -> Result<()> {
        self.with_txn(|tx| self.store_relation_on_tx(tx, relation))
    }

    fn get_relations(
        &self,
        node_id: Uuid,
        relation_type: Option<RelationType>,
    ) -> Result<Vec<Relation>> {
        let conn = self.reader();
        let collect = |sql: &str, p: &[&dyn rusqlite::ToSql]| -> Result<Vec<Relation>> {
            let mut stmt = conn.prepare(sql)?;
            let rows = stmt.query_map(p, |r| {
                let to_id = parse_uuid(&r.get::<_, String>(0)?)?;
                let rt = parse_relation_type(&r.get::<_, String>(1)?)?;
                // Edge properties are intentionally discarded to match the
                // Store contract: get_relations always reports strength 1.0
                // and no context (see the trait doc on all_relations).
                Ok(Relation {
                    from_id: node_id,
                    to_id,
                    relation_type: rt,
                    strength: 1.0,
                    context: None,
                })
            })?;
            Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
        };
        match relation_type {
            Some(rt) => collect(
                "SELECT to_id, relation_type FROM relations WHERE from_id = ?1 AND relation_type = ?2",
                &[&node_id.to_string(), &relation_type_to_str(rt)],
            ),
            None => collect(
                "SELECT to_id, relation_type FROM relations WHERE from_id = ?1",
                &[&node_id.to_string()],
            ),
        }
    }

    fn vector_search(&self, embedding: &[f32], limit: usize) -> Result<Vec<(Memory, f32)>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS}, embedding FROM memories \
             WHERE embedding IS NOT NULL AND tier = 'hot' AND superseded_by IS NULL"
        ))?;
        let rows = stmt.query_map([], |r| row_to_memory(r, true))?;
        let mut scored: Vec<(Memory, f32)> = Vec::new();
        for row in rows {
            let mut memory = row?;
            let similarity = cosine(embedding, &memory.embedding);
            memory.embedding = Vec::new();
            scored.push((memory, similarity));
        }
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(limit);
        Ok(scored)
    }

    fn filtered_vector_search(
        &self,
        embedding: &[f32],
        source: Option<&str>,
        memory_type: Option<MemoryType>,
        project_path: Option<&str>,
        limit: usize,
    ) -> Result<Vec<(Memory, f32)>> {
        if limit == 0 {
            return Ok(Vec::new());
        }
        let (predicate, args) = Self::scope_predicate(source, memory_type, project_path);
        // Score from ids and raw vectors alone, keeping only the running best
        // `limit`. Peak memory must not grow with the scope: a source pool is
        // unbounded over time, and this scan reads every row in one, so
        // collecting per-row state here would make a wide recall's footprint a
        // function of how long the store has been running.
        let mut top: Vec<(f32, Uuid)> = Vec::with_capacity(limit + 1);
        {
            let conn = self.reader();
            let mut stmt = conn.prepare(&format!(
                "SELECT id, embedding FROM memories \
                 WHERE embedding IS NOT NULL AND tier = 'hot' AND superseded_by IS NULL{predicate}"
            ))?;
            let bound: Vec<&dyn rusqlite::ToSql> =
                args.iter().map(|a| a as &dyn rusqlite::ToSql).collect();
            let query_norm = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
            let mut rows = stmt.query(bound.as_slice())?;
            let mut floor = f32::NEG_INFINITY;
            while let Some(row) = rows.next()? {
                let Some(blob) = row.get_ref(1)?.as_blob_or_null()? else {
                    continue;
                };
                let similarity = cosine_blob(embedding, query_norm, blob);
                // Read and parse the id only for a row that actually places,
                // so the common rejection costs no allocation at all.
                if top.len() == limit && similarity <= floor {
                    continue;
                }
                let id = parse_uuid(row.get_ref(0)?.as_str()?)?;
                // Place after equal scores, so ties keep scan order exactly as
                // a stable sort of the whole scan would have left them.
                let at = top.partition_point(|(s, _)| *s >= similarity);
                top.insert(at, (similarity, id));
                top.truncate(limit);
                if top.len() == limit {
                    floor = top[limit - 1].0;
                }
            }
        }

        let mut out = Vec::with_capacity(top.len());
        for (similarity, id) in top {
            if let Some(memory) = self.get_memory(id)? {
                out.push((memory, similarity));
            }
        }
        Ok(out)
    }

    /// Live memories within `depth` hops of `start_id`, newest first, capped
    /// at `TRAVERSE_MAX_RESULTS`. Ingest writes no memory-to-memory edges
    /// (only mentions, derived_from and distilled_from), so a hop is any of:
    /// a memory-to-memory relation in either direction, a shared mentioned
    /// entity, or a shared conversation.
    fn traverse(&self, start_id: Uuid, depth: u32) -> Result<Vec<(Memory, Vec<Relation>)>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "WITH RECURSIVE walk(id, d) AS ( \
               SELECT ?1, 0 \
               UNION \
               SELECT r.to_id, w.d + 1 FROM walk w \
                 JOIN relations r ON r.from_id = w.id \
               WHERE w.d < ?2 AND r.relation_type <> 'mentions' \
               UNION \
               SELECT r.from_id, w.d + 1 FROM walk w \
                 JOIN relations r ON r.to_id = w.id \
               WHERE w.d < ?2 AND r.relation_type <> 'mentions' \
               UNION \
               SELECT peer.from_id, w.d + 1 FROM walk w \
                 JOIN relations own ON own.from_id = w.id AND own.relation_type = 'mentions' \
                 JOIN relations peer ON peer.to_id = own.to_id AND peer.relation_type = 'mentions' \
               WHERE w.d < ?2 \
               UNION \
               SELECT peer.id, w.d + 1 FROM walk w \
                 JOIN memories own ON own.id = w.id \
                 JOIN memories peer ON peer.conversation_id = own.conversation_id \
               WHERE w.d < ?2 AND own.conversation_id IS NOT NULL \
               LIMIT ?3 \
             ) \
             SELECT {MEMORY_COLS} FROM memories \
             WHERE id IN (SELECT id FROM walk WHERE d > 0) AND id <> ?1 \
               AND tier = 'hot' AND superseded_by IS NULL \
             ORDER BY created_at DESC LIMIT ?4"
        ))?;
        let rows = stmt.query_map(
            params![
                start_id.to_string(),
                depth as i64,
                TRAVERSE_MAX_WALK,
                TRAVERSE_MAX_RESULTS as i64
            ],
            |r| row_to_memory(r, false),
        )?;
        let mut results = Vec::new();
        for row in rows {
            results.push((row?, Vec::new()));
        }
        Ok(results)
    }

    fn memories_by_source(&self, source: &str) -> Result<Vec<Memory>> {
        self.memories_where("source = ?1", params![source])
    }

    fn source_admits(&self, memory: &Memory, source: &str) -> Result<bool> {
        if memory.source == source {
            return Ok(true);
        }
        // SQLite flattens the subquery, so the outer distilled_id test lands
        // on idx_distillation_log_distilled instead of materialising every
        // distillate of the source per candidate.
        let conn = self.reader();
        let descends: bool = conn.query_row(
            &format!(
                "SELECT EXISTS (SELECT 1 FROM ({}) d WHERE d.distilled_id = ?)",
                Self::DISTILLED_FROM_SOURCE
            ),
            params![source, memory.id.to_string()],
            |r| r.get(0),
        )?;
        Ok(descends)
    }

    fn memories_by_type(&self, memory_type: MemoryType) -> Result<Vec<Memory>> {
        self.memories_where("memory_type = ?1", params![memory_type_to_str(memory_type)])
    }

    fn chunk_window(&self, memory_id: Uuid, ord: usize) -> Result<Option<String>> {
        self.chunk_window_text(memory_id, ord)
    }

    fn update_memory(&self, memory: &Memory) -> Result<()> {
        let data = serde_json::to_string(memory).ok();
        self.with_txn(|tx| {
            tx.execute(
                "UPDATE memories SET confidence = ?2, last_accessed = ?3, access_count = ?4, \
                 project_path = ?5, updated_at = ?6, machine_id = ?7 WHERE id = ?1",
                params![
                    memory.id.to_string(),
                    memory.confidence as f64,
                    memory.last_accessed.to_rfc3339(),
                    memory.access_count as i64,
                    memory.project_path,
                    memory.updated_at.to_rfc3339(),
                    memory.machine_id,
                ],
            )?;
            Self::append_outbox(tx, memory.id, "upsert")?;
            Self::append_sync_log(
                tx,
                SyncOp::Update,
                SyncNodeType::Memory,
                &memory.id.to_string(),
                data.as_deref(),
                &self.machine_id,
                None,
            )
        })
    }

    fn record_access(&self, memory: &Memory) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "UPDATE memories SET last_accessed = ?2, access_count = ?3, confidence = ?4 WHERE id = ?1",
            params![
                memory.id.to_string(),
                memory.last_accessed.to_rfc3339(),
                memory.access_count as i64,
                memory.confidence as f64,
            ],
        )?;
        Ok(())
    }

    fn record_accesses(&self, ids: &[Uuid]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }
        let now = Utc::now().to_rfc3339();
        self.with_txn(|tx| {
            let mut stmt = tx.prepare_cached(
                "UPDATE memories SET last_accessed = ?2, access_count = access_count + 1 \
                 WHERE id = ?1",
            )?;
            for id in ids {
                stmt.execute(params![id.to_string(), now])?;
            }
            Ok(())
        })
    }

    fn bm25_search(&self, query: &str, limit: usize) -> Result<Vec<Memory>> {
        self.scoped_text_search(query, None, None, None, limit)
    }

    fn memory_count(&self) -> Result<usize> {
        let conn = self.reader();
        let count: i64 = conn.query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))?;
        Ok(count as usize)
    }

    fn all_memory_ids(&self) -> Result<Vec<Uuid>> {
        let conn = self.reader();
        let mut stmt = conn.prepare("SELECT id FROM memories")?;
        let rows = stmt.query_map([], |r| parse_uuid(&r.get::<_, String>(0)?))?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn all_relations(&self) -> Result<Vec<Relation>> {
        let conn = self.reader();
        let mut stmt = conn.prepare("SELECT from_id, to_id, relation_type FROM relations")?;
        let rows = stmt.query_map([], |r| {
            Ok(Relation {
                from_id: parse_uuid(&r.get::<_, String>(0)?)?,
                to_id: parse_uuid(&r.get::<_, String>(1)?)?,
                relation_type: parse_relation_type(&r.get::<_, String>(2)?)?,
                strength: 1.0,
                context: None,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }
}

impl SqliteStore {
    fn memories_where(&self, predicate: &str, p: impl rusqlite::Params) -> Result<Vec<Memory>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS} FROM memories WHERE {predicate}"
        ))?;
        let rows = stmt.query_map(p, |r| row_to_memory(r, false))?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }
}

pub(crate) fn embedding_to_blob(embedding: &[f32]) -> Vec<u8> {
    embedding.iter().flat_map(|f| f.to_le_bytes()).collect()
}

/// Cosine against a stored embedding read straight from its blob, so a wide
/// scan does not allocate a Vec<f32> per row. `query_norm` is hoisted because
/// it is constant across the scan.
pub(crate) fn cosine_blob(query: &[f32], query_norm: f32, blob: &[u8]) -> f32 {
    let mut dot = 0.0_f32;
    let mut norm = 0.0_f32;
    // The norm covers the whole stored vector while the dot product stops at
    // the shorter of the two, matching `cosine` exactly on a length mismatch.
    for (i, chunk) in blob.as_chunks::<4>().0.iter().enumerate() {
        let y = f32::from_le_bytes(*chunk);
        norm += y * y;
        if let Some(x) = query.get(i) {
            dot += x * y;
        }
    }
    let norm = norm.sqrt();
    if query_norm == 0.0 || norm == 0.0 {
        return 0.0;
    }
    dot / (query_norm * norm)
}

pub(crate) fn blob_to_embedding(blob: &[u8]) -> Vec<f32> {
    blob.as_chunks::<4>()
        .0
        .iter()
        .map(|c| f32::from_le_bytes(*c))
        .collect()
}

fn cosine(a: &[f32], b: &[f32]) -> f32 {
    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
    let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
    if na == 0.0 || nb == 0.0 {
        return 0.0;
    }
    dot / (na * nb)
}

fn conversion_err(err: impl std::error::Error + Send + Sync + 'static) -> rusqlite::Error {
    rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
}

pub(crate) fn parse_dt(s: &str) -> rusqlite::Result<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(s)
        .map(|d| d.with_timezone(&Utc))
        .map_err(conversion_err)
}

pub(crate) fn parse_uuid(s: &str) -> rusqlite::Result<Uuid> {
    Uuid::parse_str(s).map_err(conversion_err)
}

fn memory_type_to_str(t: MemoryType) -> &'static str {
    match t {
        MemoryType::Episodic => "episodic",
        MemoryType::Semantic => "semantic",
        MemoryType::Procedural => "procedural",
        MemoryType::Decision => "decision",
        MemoryType::Architecture => "architecture",
        MemoryType::Debugging => "debugging",
        MemoryType::Task => "task",
        MemoryType::Question => "question",
    }
}

fn parse_memory_type(s: &str) -> rusqlite::Result<MemoryType> {
    match s {
        "episodic" => Ok(MemoryType::Episodic),
        "semantic" => Ok(MemoryType::Semantic),
        "procedural" => Ok(MemoryType::Procedural),
        "decision" => Ok(MemoryType::Decision),
        "architecture" => Ok(MemoryType::Architecture),
        "debugging" => Ok(MemoryType::Debugging),
        "task" => Ok(MemoryType::Task),
        "question" => Ok(MemoryType::Question),
        other => Err(conversion_err(std::io::Error::other(format!(
            "unknown memory_type: {other}"
        )))),
    }
}

fn relation_type_to_str(t: RelationType) -> &'static str {
    match t {
        RelationType::RelatesTo => "relates_to",
        RelationType::Mentions => "mentions",
        RelationType::DerivedFrom => "derived_from",
        RelationType::Contradicts => "contradicts",
        RelationType::Reinforces => "reinforces",
        RelationType::Supersedes => "supersedes",
        RelationType::DistilledFrom => "distilled_from",
    }
}

fn parse_relation_type(s: &str) -> rusqlite::Result<RelationType> {
    match s {
        "relates_to" => Ok(RelationType::RelatesTo),
        "mentions" => Ok(RelationType::Mentions),
        "derived_from" => Ok(RelationType::DerivedFrom),
        "contradicts" => Ok(RelationType::Contradicts),
        "reinforces" => Ok(RelationType::Reinforces),
        "supersedes" => Ok(RelationType::Supersedes),
        "distilled_from" => Ok(RelationType::DistilledFrom),
        other => Err(conversion_err(std::io::Error::other(format!(
            "unknown relation_type: {other}"
        )))),
    }
}

fn tier_to_str(t: Tier) -> &'static str {
    match t {
        Tier::Hot => "hot",
        Tier::Archived => "archived",
    }
}

fn parse_tier(s: &str) -> rusqlite::Result<Tier> {
    match s {
        "hot" => Ok(Tier::Hot),
        "archived" => Ok(Tier::Archived),
        other => Err(conversion_err(std::io::Error::other(format!(
            "unknown tier: {other}"
        )))),
    }
}

fn sync_op_to_str(op: SyncOp) -> &'static str {
    match op {
        SyncOp::Create => "create",
        SyncOp::Update => "update",
        SyncOp::Delete => "delete",
    }
}

fn sync_node_type_to_str(t: SyncNodeType) -> &'static str {
    match t {
        SyncNodeType::Memory => "memory",
        SyncNodeType::Entity => "entity",
        SyncNodeType::Conversation => "conversation",
        SyncNodeType::Relation => "relation",
        SyncNodeType::Distillation => "distillation",
    }
}

pub(crate) fn row_to_memory(r: &Row<'_>, with_embedding: bool) -> rusqlite::Result<Memory> {
    let embedding = if with_embedding {
        r.get::<_, Option<Vec<u8>>>(19)?
            .map(|b| blob_to_embedding(&b))
            .unwrap_or_default()
    } else {
        Vec::new()
    };
    Ok(Memory {
        id: parse_uuid(&r.get::<_, String>(0)?)?,
        content: r.get(1)?,
        context: r.get(2)?,
        embedding,
        memory_type: parse_memory_type(&r.get::<_, String>(3)?)?,
        confidence: r.get::<_, f64>(4)? as f32,
        created_at: parse_dt(&r.get::<_, String>(5)?)?,
        updated_at: parse_dt(&r.get::<_, String>(6)?)?,
        last_accessed: parse_dt(&r.get::<_, String>(7)?)?,
        access_count: r.get::<_, i64>(8)? as u32,
        source: r.get(9)?,
        source_id: r.get(10)?,
        project_path: r.get(11)?,
        machine_id: r.get(12)?,
        conversation_id: r
            .get::<_, Option<String>>(13)?
            .map(|s| parse_uuid(&s))
            .transpose()?,
        tier: parse_tier(&r.get::<_, String>(14)?)?,
        archived_segment: r.get(15)?,
        superseded_by: r
            .get::<_, Option<String>>(16)?
            .map(|s| parse_uuid(&s))
            .transpose()?,
        retired_reason: r.get(17)?,
        session_at: r
            .get::<_, Option<String>>(18)?
            .map(|s| parse_dt(&s))
            .transpose()?,
    })
}

fn row_to_entity(r: &Row<'_>) -> rusqlite::Result<Entity> {
    Ok(Entity {
        id: parse_uuid(&r.get::<_, String>(0)?)?,
        name: r.get(1)?,
        entity_type: r.get(2)?,
        embedding: r
            .get::<_, Option<Vec<u8>>>(3)?
            .map(|b| blob_to_embedding(&b))
            .unwrap_or_default(),
        aliases: serde_json::from_str(&r.get::<_, String>(4)?).map_err(conversion_err)?,
    })
}

/// Store-side shape the index drainer consumes; `body` is context + content,
/// the same text the embedding was computed over.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetireOutcome {
    Retired,
    /// The row was already archived, by an earlier forget or by
    /// consolidation; it is left as it was.
    AlreadyRetired,
    NotFound,
}

pub struct IndexableMemory {
    pub embedding: Vec<f32>,
    pub body: String,
    pub hot: bool,
    /// `chunk::content_hash` of the content alone, which a stored chunk set
    /// must match to still describe this row.
    pub content_hash: String,
}

pub struct OutboxRow {
    pub seq: i64,
    pub memory_id: Uuid,
    pub op: String,
}

pub(crate) fn body_of(context: Option<String>, content: String) -> String {
    match context {
        Some(c) if !c.is_empty() => format!("{c}\n{content}"),
        _ => content,
    }
}

impl SqliteStore {
    pub fn index_watermark(&self) -> Result<i64> {
        let conn = self.reader();
        let value: Option<String> = conn
            .query_row(
                "SELECT value FROM index_meta WHERE key = 'watermark'",
                [],
                |r| r.get(0),
            )
            .optional()?;
        Ok(value.and_then(|v| v.parse().ok()).unwrap_or(0))
    }

    pub fn set_index_watermark(&self, seq: i64) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "INSERT OR REPLACE INTO index_meta (key, value) VALUES ('watermark', ?1)",
            params![seq.to_string()],
        )?;
        Ok(())
    }

    pub fn outbox_after(&self, seq: i64) -> Result<Vec<OutboxRow>> {
        let conn = self.reader();
        let mut stmt = conn
            .prepare("SELECT seq, memory_id, op FROM index_outbox WHERE seq > ?1 ORDER BY seq")?;
        let rows = stmt.query_map(params![seq], |r| {
            Ok(OutboxRow {
                seq: r.get(0)?,
                memory_id: parse_uuid(&r.get::<_, String>(1)?)?,
                op: r.get(2)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    pub fn prune_outbox(&self, upto: i64) -> Result<()> {
        let conn = self.conn();
        conn.execute("DELETE FROM index_outbox WHERE seq <= ?1", params![upto])?;
        Ok(())
    }

    pub fn max_outbox_seq(&self) -> Result<i64> {
        let conn = self.reader();
        Ok(
            conn.query_row("SELECT COALESCE(MAX(seq), 0) FROM index_outbox", [], |r| {
                r.get(0)
            })?,
        )
    }

    /// Stable u64 usearch key for a memory id, allocated on first use.
    pub fn vec_key(&self, memory_id: Uuid) -> Result<u64> {
        let conn = self.conn();
        conn.execute(
            "INSERT OR IGNORE INTO vec_keys (memory_id) VALUES (?1)",
            params![memory_id.to_string()],
        )?;
        let key: i64 = conn.query_row(
            "SELECT key FROM vec_keys WHERE memory_id = ?1",
            params![memory_id.to_string()],
            |r| r.get(0),
        )?;
        Ok(key as u64)
    }

    pub fn existing_vec_key(&self, memory_id: Uuid) -> Result<Option<u64>> {
        let conn = self.reader();
        let key: Option<i64> = conn
            .query_row(
                "SELECT key FROM vec_keys WHERE memory_id = ?1",
                params![memory_id.to_string()],
                |r| r.get(0),
            )
            .optional()?;
        Ok(key.map(|k| k as u64))
    }

    /// Drops the key row once the vector is gone from usearch, so `vec_keys`
    /// only ever holds keys the index can still resolve.
    pub fn delete_vec_key(&self, memory_id: Uuid) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "DELETE FROM vec_keys WHERE memory_id = ?1",
            params![memory_id.to_string()],
        )?;
        Ok(())
    }

    /// The live memory `content` duplicates under `remember`'s rule: equal
    /// once surrounding whitespace is trimmed and both sides are lowercased.
    /// With `project_path`, only memories filed under that project count;
    /// among several matches the oldest wins. SQLite's `lower()` folds ASCII
    /// only, so a stored memory that differs from `content` just in the case
    /// of a non-ASCII letter is not found, which the substring shortlist this
    /// replaces could not find either.
    pub fn find_exact_duplicate(
        &self,
        content: &str,
        project_path: Option<&str>,
    ) -> Result<Option<Memory>> {
        let key = content.trim().to_lowercase();
        let conn = self.reader();
        let mut stmt = conn.prepare(&dedup_query(project_path.is_some()))?;
        let found = match project_path {
            Some(p) => stmt.query_row(params![key, p], |r| row_to_memory(r, false)),
            None => stmt.query_row(params![key], |r| row_to_memory(r, false)),
        }
        .optional()?;
        Ok(found)
    }

    /// SQL fragment and bindings for a source/type/project scope, appended to
    /// an existing WHERE clause. All three columns are indexed, so a scoped
    /// scan reads only the matching rows.
    /// Ids of distillates that descend from at least one raw of the bound
    /// source. `source_admits` and `scope_predicate` must agree, so both
    /// are built from this one fragment.
    const DISTILLED_FROM_SOURCE: &str = "SELECT dl.distilled_id FROM distillation_log dl          JOIN memories raw ON raw.id = dl.memory_id WHERE raw.source = ?";

    pub(crate) fn scope_predicate(
        source: Option<&str>,
        memory_type: Option<MemoryType>,
        project_path: Option<&str>,
    ) -> (String, Vec<String>) {
        let mut predicate = String::new();
        let mut args = Vec::new();
        if let Some(s) = source {
            // The IN-subquery form lets SQLite serve both arms from indexes
            // (idx_memories_source and the primary key) instead of testing a
            // correlated EXISTS against every row of the scan.
            predicate.push_str(&format!(
                " AND (source = ? OR id IN ({}))",
                Self::DISTILLED_FROM_SOURCE
            ));
            args.push(s.to_string());
            args.push(s.to_string());
        }
        if let Some(t) = memory_type {
            predicate.push_str(" AND memory_type = ?");
            args.push(memory_type_to_str(t).to_string());
        }
        if let Some(p) = project_path {
            predicate.push_str(" AND project_path = ?");
            args.push(p.to_string());
        }
        (predicate, args)
    }

    /// `bm25_search`'s match with a source/type/project scope inside the
    /// query, so `limit` counts only rows the scope admits instead of cutting
    /// before a caller's filter could run. The match is a substring test over
    /// `content` on hot, unsuperseded rows, with no relevance score to order
    /// by (tantivy, not SQLite, holds the text index), so matches come back
    /// newest first. Case folding is SQLite's `lower()`, which is ASCII only.
    pub fn scoped_text_search(
        &self,
        query: &str,
        source: Option<&str>,
        memory_type: Option<MemoryType>,
        project_path: Option<&str>,
        limit: usize,
    ) -> Result<Vec<Memory>> {
        let (predicate, args) = Self::scope_predicate(source, memory_type, project_path);
        let needle = query.to_lowercase();
        let limit = limit as i64;
        let bound: Vec<&dyn rusqlite::ToSql> = std::iter::once(&needle as &dyn rusqlite::ToSql)
            .chain(args.iter().map(|a| a as &dyn rusqlite::ToSql))
            .chain(std::iter::once(&limit as &dyn rusqlite::ToSql))
            .collect();
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS} FROM memories \
             WHERE instr(lower(content), ?) > 0 AND tier = 'hot' AND superseded_by IS NULL\
             {predicate} ORDER BY created_at DESC LIMIT ?"
        ))?;
        let rows = stmt.query_map(bound.as_slice(), |r| row_to_memory(r, false))?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    /// How many live memories a source/type/project scope holds. Answered by
    /// COUNT off the source, memory_type, and project_path indexes, so it
    /// stays O(1) in memory however large the scope grows.
    pub fn scoped_count(
        &self,
        source: Option<&str>,
        memory_type: Option<MemoryType>,
        project_path: Option<&str>,
    ) -> Result<usize> {
        let (predicate, args) = Self::scope_predicate(source, memory_type, project_path);
        let conn = self.reader();
        let bound: Vec<&dyn rusqlite::ToSql> =
            args.iter().map(|a| a as &dyn rusqlite::ToSql).collect();
        let count: i64 = conn.query_row(
            &format!(
                "SELECT COUNT(*) FROM memories \
                 WHERE tier = 'hot' AND superseded_by IS NULL{predicate}"
            ),
            bound.as_slice(),
            |r| r.get(0),
        )?;
        Ok(count as usize)
    }

    /// Which of `ids` fall inside a source/type/project scope.
    ///
    /// Asks the database about the candidates in hand rather than reading the
    /// scope out to test membership locally, so the cost tracks the caller's
    /// list and not the scope. Batched because SQLite caps how many bound
    /// parameters one statement may carry.
    pub fn retain_in_scope(
        &self,
        ids: &[Uuid],
        source: Option<&str>,
        memory_type: Option<MemoryType>,
        project_path: Option<&str>,
    ) -> Result<HashSet<Uuid>> {
        const BATCH: usize = 400;
        let (predicate, args) = Self::scope_predicate(source, memory_type, project_path);
        let mut kept = HashSet::new();
        let conn = self.reader();
        for chunk in ids.chunks(BATCH) {
            let holes = std::iter::repeat_n("?", chunk.len())
                .collect::<Vec<_>>()
                .join(",");
            let mut stmt = conn.prepare(&format!(
                "SELECT id FROM memories \
                 WHERE tier = 'hot' AND superseded_by IS NULL{predicate} AND id IN ({holes})"
            ))?;
            let texts: Vec<String> = chunk.iter().map(|id| id.to_string()).collect();
            let bound: Vec<&dyn rusqlite::ToSql> = args
                .iter()
                .map(|a| a as &dyn rusqlite::ToSql)
                .chain(texts.iter().map(|t| t as &dyn rusqlite::ToSql))
                .collect();
            let rows = stmt.query_map(bound.as_slice(), |r| parse_uuid(&r.get::<_, String>(0)?))?;
            for id in rows {
                kept.insert(id?);
            }
        }
        Ok(kept)
    }

    pub fn memory_id_for_vec_key(&self, key: u64) -> Result<Option<Uuid>> {
        let conn = self.reader();
        let id: Option<String> = conn
            .query_row(
                "SELECT memory_id FROM vec_keys WHERE key = ?1",
                params![key as i64],
                |r| r.get(0),
            )
            .optional()?;
        Ok(id.as_deref().map(Uuid::parse_str).transpose()?)
    }

    pub fn memory_for_indexing(&self, memory_id: Uuid) -> Result<Option<IndexableMemory>> {
        let conn = self.reader();
        conn.query_row(
            "SELECT content, context, embedding, tier, superseded_by FROM memories WHERE id = ?1",
            params![memory_id.to_string()],
            |r| {
                let content: String = r.get(0)?;
                let context: Option<String> = r.get(1)?;
                let embedding = r
                    .get::<_, Option<Vec<u8>>>(2)?
                    .map(|b| blob_to_embedding(&b))
                    .unwrap_or_default();
                let tier: String = r.get(3)?;
                let superseded_by: Option<String> = r.get(4)?;
                Ok(IndexableMemory {
                    embedding,
                    content_hash: crate::chunk::content_hash(&content),
                    body: body_of(context, content),
                    hot: tier == "hot" && superseded_by.is_none(),
                })
            },
        )
        .optional()
        .map_err(Into::into)
    }

    pub fn all_indexable(&self) -> Result<Vec<(Uuid, Vec<f32>, String)>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(
            "SELECT id, content, context, embedding FROM memories \
             WHERE tier = 'hot' AND superseded_by IS NULL",
        )?;
        let rows = stmt.query_map([], |r| {
            let id = parse_uuid(&r.get::<_, String>(0)?)?;
            let content: String = r.get(1)?;
            let context: Option<String> = r.get(2)?;
            let embedding = r
                .get::<_, Option<Vec<u8>>>(3)?
                .map(|b| blob_to_embedding(&b))
                .unwrap_or_default();
            Ok((id, embedding, body_of(context, content)))
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    /// Hot rows whose stored embedding has exactly `dim` components: the
    /// only rows the vector index can hold, so a row still waiting for an
    /// embedding does not read as index drift.
    pub fn vector_indexable_count(&self, dim: usize) -> Result<usize> {
        let conn = self.reader();
        let count: i64 = conn.query_row(
            "SELECT COUNT(*) FROM memories WHERE tier = 'hot' AND superseded_by IS NULL \
             AND embedding IS NOT NULL AND length(embedding) = ?1",
            params![(dim * 4) as i64],
            |r| r.get(0),
        )?;
        Ok(count as usize)
    }

    pub fn indexable_count(&self) -> Result<usize> {
        let conn = self.reader();
        let count: i64 = conn.query_row(
            "SELECT COUNT(*) FROM memories WHERE tier = 'hot' AND superseded_by IS NULL",
            [],
            |r| r.get(0),
        )?;
        Ok(count as usize)
    }

    pub(crate) fn memory_on_tx(tx: &Transaction<'_>, id: Uuid) -> Result<Option<Memory>> {
        tx.query_row(
            &format!("SELECT {MEMORY_COLS}, embedding FROM memories WHERE id = ?1"),
            params![id.to_string()],
            |r| row_to_memory(r, true),
        )
        .optional()
        .map_err(Into::into)
    }

    /// Logs the row's full current state (embedding included) as a sync
    /// Update. The peer's Update path replaces the whole row, so a record
    /// serialized without the embedding would null it there.
    pub(crate) fn log_memory_update(&self, tx: &Transaction<'_>, memory: &Memory) -> Result<()> {
        let data = serde_json::to_string(memory)?;
        Self::append_sync_log(
            tx,
            SyncOp::Update,
            SyncNodeType::Memory,
            &memory.id.to_string(),
            Some(&data),
            &self.machine_id,
            None,
        )
    }

    /// Zep-style soft invalidation: the row stays, the indexes drop it via the
    /// outbox, and peers learn of it through a sync Update carrying the row.
    pub fn supersede_memory(&self, memory_id: Uuid, by: Uuid) -> Result<()> {
        self.with_txn(|tx| self.supersede_on_tx(tx, memory_id, by).map(|_| ()))
    }

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

    /// Local cold tier: the row keeps its content and embedding but leaves
    /// both retrieval indexes and every recall predicate. `archived_segment`
    /// stays NULL, which is what distinguishes this from `mark_archived`'s
    /// uploaded-segment stub. Replicated as an Update so peers retire the
    /// same row instead of keeping it hot beside the distillate.
    pub fn archive_memory(&self, memory_id: Uuid) -> Result<()> {
        self.with_txn(|tx| self.archive_on_tx(tx, memory_id).map(|_| ()))
    }

    /// Returns whether a row was actually flipped, so a batch caller can
    /// count real retirements rather than attempts.
    pub(crate) fn archive_on_tx(&self, tx: &Transaction<'_>, memory_id: Uuid) -> Result<bool> {
        let changed = tx.execute(
            "UPDATE memories SET tier = 'archived', updated_at = ?2 \
             WHERE id = ?1 AND tier <> 'archived'",
            params![memory_id.to_string(), Utc::now().to_rfc3339()],
        )?;
        if changed == 0 {
            return Ok(false);
        }
        Self::append_outbox(tx, memory_id, "delete")?;
        if let Some(memory) = Self::memory_on_tx(tx, memory_id)? {
            self.log_memory_update(tx, &memory)?;
        }
        Ok(true)
    }

    /// `forget`'s default: archives the row as `archive_memory` does and
    /// records why, so the memory leaves recall on every peer while its
    /// content stays recoverable. Nothing is tombstoned, and an id this store
    /// does not hold changes nothing.
    pub fn retire_memory(&self, memory_id: Uuid, reason: &str) -> Result<RetireOutcome> {
        self.with_txn(|tx| {
            let changed = tx.execute(
                "UPDATE memories SET tier = 'archived', retired_reason = ?2, updated_at = ?3 \
                 WHERE id = ?1 AND tier <> 'archived'",
                params![memory_id.to_string(), reason, Utc::now().to_rfc3339()],
            )?;
            if changed == 0 {
                return Ok(match Self::memory_on_tx(tx, memory_id)? {
                    Some(_) => RetireOutcome::AlreadyRetired,
                    None => RetireOutcome::NotFound,
                });
            }
            Self::append_outbox(tx, memory_id, "delete")?;
            if let Some(memory) = Self::memory_on_tx(tx, memory_id)? {
                self.log_memory_update(tx, &memory)?;
            }
            Ok(RetireOutcome::Retired)
        })
    }

    /// Cold-tier flip: content becomes a 200-char stub, the embedding is
    /// dropped (the full row lives in the archived segment), and the outbox
    /// evicts the memory from both indexes.
    pub fn mark_archived(&self, memory_id: Uuid, segment: &str) -> Result<()> {
        self.with_txn(|tx| {
            tx.execute(
                "UPDATE memories SET tier = 'archived', archived_segment = ?2, \
                 embedding = NULL, content = substr(content, 1, 200) WHERE id = ?1",
                params![memory_id.to_string(), segment],
            )?;
            Self::append_outbox(tx, memory_id, "delete")
        })
    }
}

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

    fn plan(store: &SqliteStore, with_project: bool) -> Vec<String> {
        let conn = store.reader();
        let mut stmt = conn
            .prepare(&format!("EXPLAIN QUERY PLAN {}", dedup_query(with_project)))
            .unwrap();
        let detail = |r: &Row<'_>| r.get::<_, String>(3);
        let rows = if with_project {
            stmt.query_map(params!["k", "/p"], detail)
                .unwrap()
                .collect::<rusqlite::Result<Vec<_>>>()
        } else {
            stmt.query_map(params!["k"], detail)
                .unwrap()
                .collect::<rusqlite::Result<Vec<_>>>()
        };
        rows.unwrap()
    }

    #[test]
    fn the_dedup_lookup_reads_the_dedup_key_index() {
        let store = SqliteStore::in_memory("m".to_string()).unwrap();
        for with_project in [false, true] {
            let plan = plan(&store, with_project);
            assert!(
                plan.iter().any(|d| d.contains("idx_memories_dedup_key")),
                "with_project={with_project}: {plan:?}"
            );
        }
    }

    #[test]
    fn the_dedup_trim_set_is_exactly_what_str_trim_strips() {
        let listed: Vec<u32> = DEDUP_TRIM_SET
            .trim_start_matches("char(")
            .trim_end_matches(')')
            .split(", ")
            .map(|n| n.parse().unwrap())
            .collect();
        let rust: Vec<u32> = (0..=char::MAX as u32)
            .filter_map(char::from_u32)
            .filter(|c| c.is_whitespace())
            .map(u32::from)
            .collect();
        assert_eq!(listed, rust);
    }
}