lorekeeper 0.3.3

Agent long-term memory bank — MCP server with SQLite and FTS5
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
//! `SQLite` implementation of the `EntryRepository`.

use crate::config::LoreConfig;
use crate::error::LoreError;
use crate::model::entry::{Entry, NewEntry, UpdateEntry};
use crate::model::types::{EntryType, ReflectCriteria, ReflectReport, SimilarEntry};
use crate::model::validation::{
    validate_new_entry, validate_related_entries, validate_state_transition,
};
use crate::store::repository::{EntryRepository, Filters, MemoryStats, SearchQuery};
use chrono::{DateTime, Utc};
use rusqlite::{Connection, Row, params};
use std::sync::Mutex;
use uuid::Uuid;

/// A thread-safe repository that uses `SQLite` for persistent storage.
pub struct SqliteEntryRepo {
    conn: Mutex<Connection>,
}

impl std::fmt::Debug for SqliteEntryRepo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SqliteEntryRepo").finish_non_exhaustive()
    }
}

impl SqliteEntryRepo {
    /// Creates a new `SqliteEntryRepo` from an existing connection.
    pub const fn new(conn: Connection) -> Self {
        Self { conn: Mutex::new(conn) }
    }
}

#[allow(clippy::significant_drop_tightening, clippy::redundant_closure_for_method_calls)]
impl EntryRepository for SqliteEntryRepo {
    fn store(&self, mut input: NewEntry) -> Result<Entry, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;

        // Validation
        input.normalize_tags();
        validate_new_entry(&input)?;
        if let Some(related) = &input.related_entries {
            validate_related_entries(related)?;
        }

        let id = Uuid::now_v7().to_string();
        let now = Utc::now();

        let tags_json = serde_json::to_string(&input.tags.clone().unwrap_or_default())
            .map_err(LoreError::Serialization)?;
        let related_json =
            serde_json::to_string(&input.related_entries.clone().unwrap_or_default())
                .map_err(LoreError::Serialization)?;
        let data_json =
            serde_json::to_string(&input.data.clone().unwrap_or(serde_json::Value::Null))
                .map_err(LoreError::Serialization)?;

        conn.execute(
            "INSERT INTO entry (id, entry_type, title, body, role, tags, related_entries, created_at, updated_at, data)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            params![
                id,
                input.entry_type,
                input.title,
                input.body,
                input.role,
                tags_json,
                related_json,
                now,
                now,
                data_json,
            ],
        )?;

        Ok(Entry {
            id: crate::model::entry::EntryId(id),
            entry_type: input.entry_type,
            title: input.title,
            body: input.body,
            role: input.role,
            tags: input.tags.unwrap_or_default(),
            related_entries: input.related_entries.unwrap_or_default(),
            created_at: now,
            updated_at: now,
            is_deleted: false,
            access_count: 0,
            last_accessed_at: None,
            data: input.data.unwrap_or(serde_json::Value::Null),
        })
    }

    fn get(&self, id: &str) -> Result<Entry, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;
        let mut stmt = conn.prepare(
            "SELECT id, entry_type, title, body, role, tags, related_entries, created_at, updated_at, is_deleted, data, access_count, last_accessed_at FROM entry WHERE id = ?",
        )?;

        let entry = match stmt.query_row(params![id], map_row) {
            Ok(e) => e,
            Err(rusqlite::Error::QueryReturnedNoRows) => {
                return Err(LoreError::NotFound(id.to_owned()));
            }
            Err(e) => return Err(LoreError::Database(e)),
        };

        if entry.is_deleted {
            return Err(LoreError::NotFound(id.to_owned()));
        }

        // Track deliberate access (only on explicit get, not on searches)
        let now = Utc::now();
        conn.execute(
            "UPDATE entry SET access_count = access_count + 1, last_accessed_at = ? WHERE id = ?",
            params![now, id],
        )?;

        Ok(entry)
    }

    fn update(&self, id: &str, mut update: UpdateEntry) -> Result<Entry, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;

        // Get existing to merge
        let mut stmt = conn.prepare(
            "SELECT id, entry_type, title, body, role, tags, related_entries, created_at, updated_at, is_deleted, data, access_count, last_accessed_at FROM entry WHERE id = ?",
        )?;
        let existing = match stmt.query_row(params![id], map_row) {
            Ok(e) => e,
            Err(rusqlite::Error::QueryReturnedNoRows) => {
                return Err(LoreError::NotFound(id.to_owned()));
            }
            Err(e) => return Err(LoreError::Database(e)),
        };

        if existing.is_deleted {
            return Err(LoreError::NotFound(id.to_owned()));
        }

        // Validate state transition for stateful types (PLAN, STUB)
        let current_status = existing.data.get("status").and_then(|v| v.as_str());
        let new_status =
            update.data.as_ref().and_then(|d| d.get("status")).and_then(|v| v.as_str());
        validate_state_transition(existing.entry_type, current_status, new_status)?;

        update.normalize_tags();
        let now = Utc::now();

        let title = update.title.unwrap_or(existing.title);
        let body = update.body.or(existing.body);
        let tags = update.tags.unwrap_or(existing.tags);
        let related = update.related_entries.unwrap_or(existing.related_entries);
        validate_related_entries(&related)?;
        let data = update.data.unwrap_or(existing.data);

        // Validate merged
        let merged_new = NewEntry {
            entry_type: existing.entry_type,
            title: title.clone(),
            body: body.clone(),
            role: existing.role.clone(),
            tags: Some(tags.clone()),
            related_entries: Some(related.clone()),
            data: Some(data.clone()),
        };
        validate_new_entry(&merged_new)?;

        let tags_json = serde_json::to_string(&tags).map_err(LoreError::Serialization)?;
        let related_json = serde_json::to_string(&related).map_err(LoreError::Serialization)?;
        let data_json = serde_json::to_string(&data).map_err(LoreError::Serialization)?;

        conn.execute(
            "UPDATE entry SET title = ?, body = ?, tags = ?, related_entries = ?, data = ?, updated_at = ? WHERE id = ?",
            params![&title, &body, tags_json, related_json, data_json, now, id],
        )?;

        Ok(Entry {
            id: crate::model::entry::EntryId(id.to_owned()),
            entry_type: existing.entry_type,
            title,
            body,
            role: existing.role,
            tags,
            related_entries: related,
            created_at: existing.created_at,
            updated_at: now,
            is_deleted: false,
            access_count: existing.access_count,
            last_accessed_at: existing.last_accessed_at,
            data,
        })
    }

    fn delete(&self, id: &str) -> Result<(), LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;
        let rows = conn.execute("UPDATE entry SET is_deleted = 1 WHERE id = ?", params![id])?;
        if rows == 0 {
            return Err(LoreError::NotFound(id.to_owned()));
        }
        Ok(())
    }

    fn search(&self, query: &SearchQuery) -> Result<Vec<Entry>, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;

        let mut sql = "SELECT e.id, e.entry_type, e.title, e.body, e.role, e.tags, e.related_entries, e.created_at, e.updated_at, e.is_deleted, e.data 
                       FROM entry e 
                       JOIN entry_fts f ON e.rowid = f.rowid 
                       WHERE entry_fts MATCH ? AND e.is_deleted = 0".to_owned();

        let mut params_vec: Vec<rusqlite::types::Value> = vec![query.query.clone().into()];

        if let Some(et) = query.entry_type {
            sql.push_str(" AND e.entry_type = ?");
            params_vec.push(serde_json::to_string(&et).unwrap_or_default().replace('"', "").into());
        }

        sql.push_str(" ORDER BY rank LIMIT ?");
        params_vec.push(i64::from(query.limit).into());

        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(rusqlite::params_from_iter(params_vec), map_row)?;

        let mut results = Vec::new();
        for row in rows {
            results.push(row?);
        }
        Ok(results)
    }

    fn recent(&self, limit: u32) -> Result<Vec<Entry>, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;
        let mut stmt = conn.prepare(
            "SELECT id, entry_type, title, body, role, tags, related_entries, created_at, updated_at, is_deleted, data, access_count, last_accessed_at FROM entry WHERE is_deleted = 0 ORDER BY created_at DESC LIMIT ?",
        )?;

        let rows = stmt.query_map(params![limit], map_row)?;

        let mut results = Vec::new();
        for row in rows {
            results.push(row?);
        }
        Ok(results)
    }

    fn by_type(&self, entry_type: EntryType, filters: &Filters) -> Result<Vec<Entry>, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;

        let mut sql = "SELECT id, entry_type, title, body, role, tags, related_entries, created_at, updated_at, is_deleted, data, access_count, last_accessed_at FROM entry WHERE entry_type = ? AND is_deleted = 0".to_owned();
        let type_str = serde_json::to_string(&entry_type).unwrap_or_default().replace('"', "");
        let mut params_vec: Vec<rusqlite::types::Value> = vec![type_str.into()];

        if let Some(status) = &filters.status {
            sql.push_str(" AND json_extract(data, '$.status') = ?");
            params_vec.push(status.clone().into());
        }

        sql.push_str(" ORDER BY created_at DESC LIMIT ? OFFSET ?");
        params_vec.push(i64::from(filters.limit).into());
        params_vec.push(i64::from(filters.offset).into());

        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(rusqlite::params_from_iter(params_vec), map_row)?;

        let mut results = Vec::new();
        for row in rows {
            results.push(row?);
        }
        Ok(results)
    }

    fn stats(&self) -> Result<MemoryStats, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;

        let mut stmt =
            conn.prepare("SELECT COUNT(*), MAX(updated_at) FROM entry WHERE is_deleted = 0")?;
        let (total, last_updated): (u64, Option<DateTime<Utc>>) =
            stmt.query_row([], |row| Ok((row.get(0)?, row.get(1)?)))?;

        let mut stmt = conn.prepare(
            "SELECT entry_type, COUNT(*) FROM entry WHERE is_deleted = 0 GROUP BY entry_type",
        )?;
        let type_counts = stmt.query_map([], |row| {
            let type_str: String = row.get(0)?;
            let entry_type: EntryType =
                serde_json::from_str(&format!("\"{type_str}\"")).unwrap_or(EntryType::Stub);
            Ok((entry_type, row.get(1)?))
        })?;

        let mut by_type = Vec::new();
        for tc in type_counts {
            by_type.push(tc?);
        }

        let mut stmt = conn.prepare(
            "SELECT json_extract(data, '$.status'), COUNT(*) \
             FROM entry \
             WHERE is_deleted = 0 AND json_extract(data, '$.status') IS NOT NULL \
             GROUP BY json_extract(data, '$.status')",
        )?;
        let status_counts = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;

        let mut by_status = Vec::new();
        for sc in status_counts {
            by_status.push(sc?);
        }

        Ok(MemoryStats { total, by_type, by_status, last_updated })
    }

    fn render_all(&self) -> Result<Vec<Entry>, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;
        let mut stmt = conn.prepare(
            "SELECT id, entry_type, title, body, role, tags, related_entries, created_at, updated_at, is_deleted, data, access_count, last_accessed_at FROM entry WHERE is_deleted = 0 ORDER BY entry_type, created_at ASC",
        )?;

        let rows = stmt.query_map([], map_row)?;

        let mut results = Vec::new();
        for row in rows {
            results.push(row?);
        }
        Ok(results)
    }

    fn find_similar(
        &self,
        title: &str,
        body: Option<String>,
        entry_type: EntryType,
        threshold: f64,
    ) -> Result<Vec<SimilarEntry>, LoreError> {
        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;

        // Build query string combining title and body for richer FTS5 matching
        let query_text = match body.as_deref() {
            Some(b) if !b.is_empty() => format!("{title} {b}"),
            _ => title.to_owned(),
        };

        // Sanitize for FTS5: remove special characters that break the query parser
        let sanitized: String = query_text
            .chars()
            .map(|c| if c.is_ascii_alphanumeric() || c == ' ' { c } else { ' ' })
            .collect();
        let sanitized = sanitized.trim();
        if sanitized.is_empty() {
            return Ok(vec![]);
        }

        let type_str =
            serde_json::to_string(&entry_type).map_err(LoreError::Serialization)?.replace('"', "");

        // BM25 score in FTS5 is negative (more negative = more similar)
        let mut stmt = conn.prepare(
            "SELECT e.id, e.title, e.entry_type, rank \
             FROM entry_fts \
             JOIN entry e ON e.rowid = entry_fts.rowid \
             WHERE entry_fts MATCH ? AND e.entry_type = ? AND e.is_deleted = 0 \
             ORDER BY rank \
             LIMIT 3",
        )?;

        let rows = stmt.query_map(rusqlite::params![sanitized, type_str], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, f64>(3)?,
            ))
        })?;

        let mut results = Vec::new();
        for row in rows {
            let (id, row_title, et, score) = row?;
            // BM25 scores are negative; convert to positive for comparison
            let abs_score = score.abs();
            if abs_score >= threshold {
                results.push(SimilarEntry { id, title: row_title, entry_type: et, score });
            }
        }
        Ok(results)
    }

    #[allow(clippy::too_many_lines)]
    fn reflect(
        &self,
        criteria: &ReflectCriteria,
        config: &LoreConfig,
    ) -> Result<ReflectReport, LoreError> {
        use crate::model::types::{MemoryState, ReflectFinding, ReflectFocus, ReflectSummary};

        let conn = self.conn.lock().map_err(|e| LoreError::Poison(e.to_string()))?;
        let limit = i64::from(criteria.limit.unwrap_or(20));

        // Determine memory state
        let total_count: i64 =
            conn.query_row("SELECT COUNT(*) FROM entry WHERE is_deleted = 0", [], |row| {
                row.get(0)
            })?;

        let state = match total_count {
            0 => MemoryState::Empty,
            1..=4 => MemoryState::Nascent,
            5..=99 => MemoryState::Active,
            _ => MemoryState::Mature,
        };

        let guidance = match &state {
            MemoryState::Empty => Some(
                "No entries yet. Store your first memory with lorekeeper_store to get started."
                    .to_owned(),
            ),
            MemoryState::Nascent => Some(
                "Memory bank is nascent (<5 entries). Results may not be representative yet."
                    .to_owned(),
            ),
            _ => None,
        };

        let stale_days = i64::from(criteria.stale_days.unwrap_or(config.reflect.stale_days));
        let hot_threshold =
            i64::from(criteria.min_access_count.unwrap_or(config.reflect.hot_access_threshold));
        let dead_days = i64::from(config.reflect.dead_entry_days);

        let mut findings: Vec<ReflectFinding> = Vec::new();
        let mut summary = ReflectSummary::default();

        let run_stale = matches!(criteria.focus, ReflectFocus::Stale | ReflectFocus::All);
        let run_dead = matches!(criteria.focus, ReflectFocus::Dead | ReflectFocus::All);
        let run_hot = matches!(criteria.focus, ReflectFocus::Hot | ReflectFocus::All);
        let run_orphaned = matches!(criteria.focus, ReflectFocus::Orphaned | ReflectFocus::All);
        let run_contradictions =
            matches!(criteria.focus, ReflectFocus::Contradictions | ReflectFocus::All);

        let run_coverage_gaps =
            matches!(criteria.focus, ReflectFocus::CoverageGaps | ReflectFocus::All);
        let run_lonely = matches!(criteria.focus, ReflectFocus::Lonely | ReflectFocus::All);

        // Stale: entries not updated within stale_days
        if run_stale {
            let mut stmt = conn.prepare(
                "SELECT id, entry_type, title, updated_at FROM entry \
                 WHERE is_deleted = 0 \
                 AND CAST(julianday('now') - julianday(updated_at) AS INTEGER) >= ? \
                 ORDER BY updated_at ASC \
                 LIMIT ?",
            )?;
            let rows = stmt.query_map(rusqlite::params![stale_days, limit], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                ))
            })?;
            for row in rows {
                let (id, et, title, updated_at) = row?;
                summary.stale += 1;
                findings.push(ReflectFinding {
                    category: "stale".to_owned(),
                    entry_id: id,
                    entry_type: et,
                    title,
                    reason: format!("Not updated since {updated_at} (>{stale_days} days)"),
                });
            }
        }

        // Dead: entries with access_count = 0 and older than dead_days
        if run_dead {
            let mut stmt = conn.prepare(
                "SELECT id, entry_type, title, created_at FROM entry \
                 WHERE is_deleted = 0 AND access_count = 0 \
                 AND CAST(julianday('now') - julianday(created_at) AS INTEGER) >= ? \
                 ORDER BY created_at ASC \
                 LIMIT ?",
            )?;
            let rows = stmt.query_map(rusqlite::params![dead_days, limit], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                ))
            })?;
            for row in rows {
                let (id, et, title, created_at) = row?;
                summary.dead += 1;
                findings.push(ReflectFinding {
                    category: "dead".to_owned(),
                    entry_id: id,
                    entry_type: et,
                    title,
                    reason: format!("Never accessed since creation ({created_at})"),
                });
            }
        }

        // Hot: frequently accessed entries (may need review/split)
        if run_hot {
            let mut stmt = conn.prepare(
                "SELECT id, entry_type, title, access_count FROM entry \
                 WHERE is_deleted = 0 AND access_count >= ? \
                 ORDER BY access_count DESC \
                 LIMIT ?",
            )?;
            let rows = stmt.query_map(rusqlite::params![hot_threshold, limit], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, i64>(3)?,
                ))
            })?;
            for row in rows {
                let (id, et, title, count) = row?;
                summary.hot += 1;
                findings.push(ReflectFinding {
                    category: "hot".to_owned(),
                    entry_id: id,
                    entry_type: et,
                    title,
                    reason: format!("Accessed {count} times — consider reviewing for freshness"),
                });
            }
        }

        // Orphaned: entries referencing non-existent or deleted related_entries
        if run_orphaned {
            let mut stmt = conn.prepare(
                "SELECT e.id, e.entry_type, e.title, ref.value FROM entry e, \
                 json_each(e.related_entries) AS ref \
                 WHERE e.is_deleted = 0 \
                 AND NOT EXISTS (SELECT 1 FROM entry r WHERE r.id = ref.value AND r.is_deleted = 0) \
                 LIMIT ?",
            )?;
            let rows = stmt.query_map(rusqlite::params![limit], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                ))
            })?;
            for row in rows {
                let (id, et, title, broken_ref) = row?;
                summary.orphaned += 1;
                findings.push(ReflectFinding {
                    category: "orphaned".to_owned(),
                    entry_id: id,
                    entry_type: et,
                    title,
                    reason: format!("Related entry {broken_ref} no longer exists"),
                });
            }
        }

        // Contradictions: same-type entries with high FTS5 similarity
        if run_contradictions {
            let mut stmt = conn.prepare(
                "SELECT a.id, a.entry_type, a.title, b.title FROM entry a \
                 JOIN entry_fts fa ON fa.rowid = a.rowid \
                 JOIN entry_fts(fa.title || ' ' || COALESCE(fa.body, '')) fb ON TRUE \
                 JOIN entry b ON b.rowid = fb.rowid \
                 WHERE a.is_deleted = 0 AND b.is_deleted = 0 \
                 AND a.entry_type = b.entry_type \
                 AND a.id != b.id \
                 AND fb.rank < -0.5 \
                 LIMIT ?",
            )?;
            let rows = stmt.query_map(rusqlite::params![limit], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                ))
            })?;
            for (id, et, title, similar_title) in rows.flatten() {
                summary.contradictions += 1;
                findings.push(ReflectFinding {
                    category: "contradictions".to_owned(),
                    entry_id: id,
                    entry_type: et,
                    title,
                    reason: format!("Textually similar to: \"{similar_title}\""),
                });
            }
        }

        // Coverage Gaps: missing entry types
        if run_coverage_gaps {
            let mut stmt =
                conn.prepare("SELECT DISTINCT entry_type FROM entry WHERE is_deleted = 0")?;
            let present_types: Vec<String> =
                stmt.query_map([], |row| row.get(0))?.collect::<rusqlite::Result<Vec<String>>>()?;

            let all_types = vec![
                EntryType::Decision,
                EntryType::Commit,
                EntryType::Constraint,
                EntryType::Lesson,
                EntryType::Plan,
                EntryType::Feature,
                EntryType::Stub,
                EntryType::Deferred,
                EntryType::BuilderNote,
                EntryType::TechDebt,
                EntryType::SessionSummary,
            ];

            for et in all_types {
                let s = serde_json::to_string(&et).unwrap_or_default().replace('"', "");
                if !present_types.contains(&s) {
                    summary.coverage_gaps += 1;
                    findings.push(ReflectFinding {
                        category: "coverage_gaps".to_owned(),
                        entry_id: "N/A".to_owned(),
                        entry_type: s.clone(),
                        title: "Missing Entry Type".to_owned(),
                        reason: format!("No {s} entries found in memory bank"),
                    });
                }
            }
        }

        // Lonely: entries with no cross-references
        if run_lonely {
            let mut stmt = conn.prepare(
                "SELECT id, entry_type, title FROM entry \
                 WHERE is_deleted = 0 AND (related_entries IS NULL OR related_entries = '[]') \
                 ORDER BY created_at ASC \
                 LIMIT ?",
            )?;
            let rows = stmt.query_map(rusqlite::params![limit], |row| {
                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?))
            })?;
            for row in rows {
                let (id, et, title) = row?;
                summary.lonely += 1;
                findings.push(ReflectFinding {
                    category: "lonely".to_owned(),
                    entry_id: id,
                    entry_type: et,
                    title,
                    reason: "Entry has no related entries (lonely)".to_owned(),
                });
            }
        }

        summary.total = findings.len();

        Ok(ReflectReport { state, findings, summary, guidance })
    }
}

fn map_row(row: &Row) -> rusqlite::Result<Entry> {
    let tags_json: String = row.get(5)?;
    let related_json: String = row.get(6)?;
    let data_json: String = row.get(10)?;

    Ok(Entry {
        id: crate::model::entry::EntryId(row.get(0)?),
        entry_type: row.get(1)?,
        title: row.get(2)?,
        body: row.get(3)?,
        role: row.get(4)?,
        tags: serde_json::from_str(&tags_json).unwrap_or_default(),
        related_entries: serde_json::from_str(&related_json).unwrap_or_default(),
        created_at: row.get(7)?,
        updated_at: row.get(8)?,
        is_deleted: row.get(9)?,
        access_count: row.get(11).unwrap_or(0),
        last_accessed_at: row.get(12).unwrap_or(None),
        data: serde_json::from_str(&data_json).unwrap_or(serde_json::Value::Null),
    })
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic)]
    use super::*;
    use crate::db::Database;
    use crate::model::types::{PlanData, ReflectFocus};

    fn setup_repo() -> SqliteEntryRepo {
        let db = Database::open_in_memory().unwrap();
        SqliteEntryRepo::new(db.into_connection())
    }

    #[test]
    fn store_entry_returns_entry_with_id() {
        let repo = setup_repo();
        let new = NewEntry {
            entry_type: EntryType::Plan,
            title: "Test Plan".into(),
            body: Some("Description".into()),
            role: "architect".into(),
            tags: Some(vec!["tag1".into()]),
            related_entries: None,
            data: Some(
                serde_json::to_value(PlanData {
                    scope: "Phase 2".into(),
                    tier: "L".into(),
                    status: "active".into(),
                })
                .unwrap(),
            ),
        };

        let entry = repo.store(new).unwrap();
        assert!(!entry.id.0.is_empty());
        assert_eq!(entry.title, "Test Plan");
        assert_eq!(entry.tags, vec!["tag1"]);
    }

    #[test]
    fn store_entry_validates_input() {
        let repo = setup_repo();
        let new = NewEntry {
            entry_type: EntryType::Plan,
            title: String::new(), // Invalid: empty title
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        };

        let res = repo.store(new);
        assert!(matches!(res, Err(LoreError::Validation(_))));
    }

    #[test]
    fn get_entry_by_id() {
        let repo = setup_repo();
        let new = NewEntry {
            entry_type: EntryType::Decision,
            title: "D1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        };
        let stored = repo.store(new).unwrap();
        let fetched = repo.get(&stored.id.0).unwrap();
        assert_eq!(fetched.title, "D1");
    }

    #[test]
    fn get_entry_not_found() {
        let repo = setup_repo();
        let res = repo.get("none");
        assert!(matches!(res, Err(LoreError::NotFound(_))));
    }

    #[test]
    fn update_entry_partial() {
        let repo = setup_repo();
        let stored = repo
            .store(NewEntry {
                entry_type: EntryType::Decision,
                title: "Original".into(),
                body: Some("Old body".into()),
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: None,
            })
            .unwrap();

        let update = UpdateEntry {
            title: Some("New Title".into()),
            body: None,
            tags: None,
            related_entries: None,
            data: None,
        };

        let updated = repo.update(&stored.id.0, update).unwrap();
        assert_eq!(updated.title, "New Title");
        assert_eq!(updated.body, Some("Old body".into()));
        assert!(updated.updated_at > stored.updated_at);
    }

    #[test]
    fn delete_entry_soft() {
        let repo = setup_repo();
        let stored = repo
            .store(NewEntry {
                entry_type: EntryType::Decision,
                title: "To Delete".into(),
                body: None,
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: None,
            })
            .unwrap();

        repo.delete(&stored.id.0).unwrap();

        let res = repo.get(&stored.id.0);
        assert!(matches!(res, Err(LoreError::NotFound(_))));
    }

    #[test]
    fn search_fts_title_match() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "Super Unique Title".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let results = repo
            .search(&SearchQuery { query: "Super".into(), entry_type: None, limit: 10 })
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "Super Unique Title");
    }

    #[test]
    fn search_fts_body_match() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "T1".into(),
            body: Some("The quick brown fox".into()),
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let results = repo
            .search(&SearchQuery { query: "quick".into(), entry_type: None, limit: 10 })
            .unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn search_fts_tag_match() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "T1".into(),
            body: None,
            role: "architect".into(),
            tags: Some(vec!["experimental".into()]),
            related_entries: None,
            data: None,
        })
        .unwrap();

        let results = repo
            .search(&SearchQuery { query: "experimental".into(), entry_type: None, limit: 10 })
            .unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn search_filter_by_type() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "Match".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();
        repo.store(NewEntry {
            entry_type: EntryType::Commit,
            title: "Match".into(),
            body: None,
            role: "builder".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let results = repo
            .search(&SearchQuery {
                query: "Match".into(),
                entry_type: Some(EntryType::Decision),
                limit: 10,
            })
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].entry_type, EntryType::Decision);
    }

    #[test]
    fn recent_returns_ordered() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "First".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "Second".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let recent = repo.recent(10).unwrap();
        assert_eq!(recent.len(), 2);
        assert_eq!(recent[0].title, "Second");
    }

    #[test]
    fn by_type_with_pagination() {
        let repo = setup_repo();
        for i in 1..=5 {
            repo.store(NewEntry {
                entry_type: EntryType::Decision,
                title: format!("D{i}"),
                body: None,
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: None,
            })
            .unwrap();
        }

        let page1 = repo
            .by_type(EntryType::Decision, &Filters { status: None, limit: 2, offset: 0 })
            .unwrap();
        assert_eq!(page1.len(), 2);

        let page2 = repo
            .by_type(EntryType::Decision, &Filters { status: None, limit: 2, offset: 2 })
            .unwrap();
        assert_eq!(page2.len(), 2);
        assert_ne!(page1[0].id, page2[0].id);
    }

    #[test]
    fn stats_returns_counts() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "D1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();
        repo.store(NewEntry {
            entry_type: EntryType::Commit,
            title: "C1".into(),
            body: None,
            role: "builder".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let stats = repo.stats().unwrap();
        assert_eq!(stats.total, 2);
    }

    #[test]
    fn stats_returns_status_breakdown() {
        let repo = setup_repo();
        // Store a planned PLAN
        repo.store(NewEntry {
            entry_type: EntryType::Plan,
            title: "P1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: Some(serde_json::json!({ "scope": "s", "tier": "S", "status": "planned" })),
        })
        .unwrap();
        // Store a planned PLAN (second one — same status to check count)
        repo.store(NewEntry {
            entry_type: EntryType::Plan,
            title: "P2".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: Some(serde_json::json!({ "scope": "s", "tier": "S", "status": "planned" })),
        })
        .unwrap();
        // Store a STUB with a different status
        repo.store(NewEntry {
            entry_type: EntryType::Stub,
            title: "S1".into(),
            body: None,
            role: "builder".into(),
            tags: None,
            related_entries: None,
            data: Some(serde_json::json!({
                "phase_number": 1,
                "contract": "c",
                "module": "m",
                "status": "open"
            })),
        })
        .unwrap();

        let stats = repo.stats().unwrap();
        assert_eq!(stats.total, 3);

        // Find the counts in by_status
        let planned_count =
            stats.by_status.iter().find(|(s, _)| s == "planned").map_or(0, |(_, n)| *n);
        let open_count = stats.by_status.iter().find(|(s, _)| s == "open").map_or(0, |(_, n)| *n);

        assert_eq!(planned_count, 2, "expected 2 PLANs with status=planned");
        assert_eq!(open_count, 1, "expected 1 STUB with status=open");
    }

    #[test]
    fn update_rejects_invalid_plan_transition() {
        let repo = setup_repo();
        let stored = repo
            .store(NewEntry {
                entry_type: EntryType::Plan,
                title: "P1".into(),
                body: None,
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: Some(serde_json::json!({
                    "scope": "test",
                    "tier": "S",
                    "status": "executed"
                })),
            })
            .unwrap();

        let res = repo.update(
            &stored.id.0,
            UpdateEntry {
                data: Some(serde_json::json!({
                    "scope": "test",
                    "tier": "S",
                    "status": "planned"
                })), // Invalid revert
                ..Default::default()
            },
        );

        assert!(matches!(res, Err(crate::error::LoreError::Validation(_))));
    }

    #[test]
    fn store_rejects_invalid_related_entry_uuid() {
        let repo = setup_repo();
        let res = repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "D1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: Some(vec![crate::model::entry::EntryId("invalid-uuid".into())]),
            data: None,
        });

        assert!(matches!(res, Err(crate::error::LoreError::Validation(_))));
    }

    #[test]
    fn update_deleted_entry_returns_not_found() {
        let repo = setup_repo();
        let stored = repo
            .store(NewEntry {
                entry_type: EntryType::Decision,
                title: "To Delete".into(),
                body: None,
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: None,
            })
            .unwrap();

        repo.delete(&stored.id.0).unwrap();

        let res = repo.update(&stored.id.0, UpdateEntry::default());
        assert!(matches!(res, Err(LoreError::NotFound(_))));
    }

    #[test]
    fn by_type_with_status_filter() {
        let repo = setup_repo();
        // Store 2 planned and 1 executed
        repo.store(NewEntry {
            entry_type: EntryType::Plan,
            title: "P1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: Some(serde_json::json!({ "scope": "s", "tier": "S", "status": "planned" })),
        })
        .unwrap();
        repo.store(NewEntry {
            entry_type: EntryType::Plan,
            title: "P2".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: Some(serde_json::json!({ "scope": "s", "tier": "S", "status": "planned" })),
        })
        .unwrap();
        repo.store(NewEntry {
            entry_type: EntryType::Plan,
            title: "P3".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: Some(serde_json::json!({ "scope": "s", "tier": "S", "status": "executed" })),
        })
        .unwrap();

        let filtered = repo
            .by_type(
                EntryType::Plan,
                &Filters { status: Some("planned".into()), limit: 10, offset: 0 },
            )
            .unwrap();
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn search_returns_empty_for_no_match() {
        let repo = setup_repo();
        let results = repo
            .search(&SearchQuery { query: "nonexistent".into(), entry_type: None, limit: 10 })
            .unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn stats_empty_database() {
        let repo = setup_repo();
        let stats = repo.stats().unwrap();
        assert_eq!(stats.total, 0);
        assert!(stats.by_type.is_empty());
        assert!(stats.last_updated.is_none());
    }

    #[test]
    fn reflect_detects_coverage_gaps() {
        let repo = setup_repo();
        // Store only 2 types
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "D1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();
        repo.store(NewEntry {
            entry_type: EntryType::Commit,
            title: "C1".into(),
            body: None,
            role: "builder".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let criteria = ReflectCriteria { focus: ReflectFocus::CoverageGaps, ..Default::default() };
        let report = repo.reflect(&criteria, &LoreConfig::default()).unwrap();

        // 11 total types - 2 present = 9 missing
        assert_eq!(report.summary.coverage_gaps, 9);
        assert!(report.findings.iter().all(|f| f.category == "coverage_gaps"));
        let missing_types: Vec<_> = report.findings.iter().map(|f| f.entry_type.as_str()).collect();
        assert!(missing_types.contains(&"CONSTRAINT"));
        assert!(missing_types.contains(&"LESSON"));
        assert!(!missing_types.contains(&"DECISION"));
        assert!(!missing_types.contains(&"COMMIT"));
    }

    #[test]
    fn reflect_no_coverage_gaps_when_all_present() {
        let repo = setup_repo();
        let types = vec![
            (EntryType::Decision, "architect", None),
            (EntryType::Commit, "builder", Some(serde_json::json!({ "hash": "abc", "files": [] }))),
            (EntryType::Constraint, "architect", Some(serde_json::json!({ "source": "x" }))),
            (EntryType::Lesson, "architect", Some(serde_json::json!({ "root_cause": "x" }))),
            (
                EntryType::Plan,
                "architect",
                Some(serde_json::json!({ "scope": "x", "tier": "S", "status": "planned" })),
            ),
            (EntryType::Feature, "architect", Some(serde_json::json!({ "status": "x" }))),
            (
                EntryType::Stub,
                "builder",
                Some(
                    serde_json::json!({ "phase_number": 1, "contract": "x", "module": "x", "status": "open" }),
                ),
            ),
            (
                EntryType::Deferred,
                "architect",
                Some(serde_json::json!({ "reason": "x", "target_phase": 1 })),
            ),
            (
                EntryType::BuilderNote,
                "builder",
                Some(serde_json::json!({ "note_type": "x", "step_ref": "x", "plan_ref": "x" })),
            ),
            (
                EntryType::TechDebt,
                "builder",
                Some(serde_json::json!({ "severity": "low", "origin_phase": 1 })),
            ),
            (
                EntryType::SessionSummary,
                "architect",
                Some(serde_json::json!({ "session_date": "2024-01-01" })),
            ),
        ];

        for (et, role, data) in types {
            repo.store(NewEntry {
                entry_type: et,
                title: format!("Test {et:?}"),
                body: None,
                role: role.into(),
                tags: None,
                related_entries: None,
                data,
            })
            .unwrap();
        }

        let criteria = ReflectCriteria { focus: ReflectFocus::CoverageGaps, ..Default::default() };
        let report = repo.reflect(&criteria, &LoreConfig::default()).unwrap();
        assert_eq!(report.summary.coverage_gaps, 0);
    }

    #[test]
    fn reflect_detects_lonely_entries() {
        let repo = setup_repo();
        for i in 1..=3 {
            repo.store(NewEntry {
                entry_type: EntryType::Decision,
                title: format!("Lonely {i}"),
                body: None,
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: None,
            })
            .unwrap();
        }

        let criteria = ReflectCriteria { focus: ReflectFocus::Lonely, ..Default::default() };
        let report = repo.reflect(&criteria, &LoreConfig::default()).unwrap();
        assert_eq!(report.summary.lonely, 3);
        assert!(report.findings.iter().all(|f| f.category == "lonely"));
    }

    #[test]
    fn reflect_lonely_excludes_linked_entries() {
        let repo = setup_repo();
        let e1 = repo
            .store(NewEntry {
                entry_type: EntryType::Decision,
                title: "E1".into(),
                body: None,
                role: "architect".into(),
                tags: None,
                related_entries: None,
                data: None,
            })
            .unwrap();

        // Linked entry
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "E2".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: Some(vec![e1.id]),
            data: None,
        })
        .unwrap();

        let criteria = ReflectCriteria { focus: ReflectFocus::Lonely, ..Default::default() };
        let report = repo.reflect(&criteria, &LoreConfig::default()).unwrap();
        // Only E1 is lonely (E2 has a related entry)
        // Wait, E1 is also lonely because no one points to IT?
        // No, the logic I planned is: check if `related_entries` IS NULL OR EMPTY.
        // E1 has related_entries = [] (empty). E2 has related_entries = ["id_of_e1"].
        // So E1 is lonely, E2 is not.
        assert_eq!(report.summary.lonely, 1);
        assert_eq!(report.findings[0].title, "E1");
    }

    #[test]
    fn reflect_all_includes_new_categories() {
        let repo = setup_repo();
        repo.store(NewEntry {
            entry_type: EntryType::Decision,
            title: "D1".into(),
            body: None,
            role: "architect".into(),
            tags: None,
            related_entries: None,
            data: None,
        })
        .unwrap();

        let criteria = ReflectCriteria { focus: ReflectFocus::All, ..Default::default() };
        let report = repo.reflect(&criteria, &LoreConfig::default()).unwrap();
        assert!(report.summary.coverage_gaps > 0);
        assert!(report.summary.lonely > 0);
    }
}