kimetsu-brain 2.5.0

Project + user-scope memory, hybrid retrieval (lexical + cosine), ambient context, secret redaction at ingest for kimetsu.
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
use std::borrow::Cow;
use std::str::FromStr;
use std::time::Duration;

use kimetsu_core::KimetsuResult;
use kimetsu_core::event::Event;
use kimetsu_core::ids::{EventId, RunId};
use rusqlite::{Connection, OptionalExtension, params};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;

use crate::redact;
use crate::schema;

/// Max attempts for a write transaction that loses the race to `SQLITE_BUSY`
/// after the 15s busy_timeout (rare; a fleet burst). The whole transaction is
/// retried from a clean state — safe because BUSY can only surface at `BEGIN`
/// (the IMMEDIATE write lock is held for the entire body once acquired).
const WRITE_TXN_MAX_ATTEMPTS: u32 = 5;

/// True when `err` is a SQLite busy/locked condition (downcastable through the
/// boxed `KimetsuResult` error, since `?` preserves the concrete type).
fn is_sqlite_busy(err: &(dyn std::error::Error + 'static)) -> bool {
    err.downcast_ref::<rusqlite::Error>()
        .and_then(|e| e.sqlite_error_code())
        .is_some_and(|code| {
            matches!(
                code,
                rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
            )
        })
}

/// Run `body` inside a single `BEGIN IMMEDIATE` transaction (concurrent-write
/// safe): the write lock is taken at `BEGIN`, so two processes writing the same
/// brain.db serialize cleanly and read-modify-write projections (use_count,
/// confidence) never interleave across writers. Retries the whole transaction on
/// `SQLITE_BUSY`/`LOCKED` (which can only occur at `BEGIN`). `&Connection` can't
/// use `transaction_with_behavior`, so the transaction is driven manually.
fn with_write_txn<F>(conn: &Connection, mut body: F) -> KimetsuResult<()>
where
    F: FnMut(&Connection) -> KimetsuResult<()>,
{
    let mut attempt = 0u32;
    loop {
        attempt += 1;
        // BEGIN IMMEDIATE — acquires the write lock now. BUSY surfaces here.
        if let Err(e) = conn.execute_batch("BEGIN IMMEDIATE") {
            let boxed: Box<dyn std::error::Error + Send + Sync> = e.into();
            if is_sqlite_busy(boxed.as_ref()) && attempt < WRITE_TXN_MAX_ATTEMPTS {
                std::thread::sleep(Duration::from_millis(20 * attempt as u64));
                continue;
            }
            return Err(boxed);
        }
        // Lock held — run the body, then COMMIT (or ROLLBACK on any error).
        match body(conn) {
            Ok(()) => match conn.execute_batch("COMMIT") {
                Ok(()) => return Ok(()),
                Err(e) => {
                    let _ = conn.execute_batch("ROLLBACK");
                    return Err(e.into());
                }
            },
            Err(e) => {
                let _ = conn.execute_batch("ROLLBACK");
                return Err(e);
            }
        }
    }
}

/// Event-schema durability seam. Normalizes an event written under an older
/// `EVENT_SCHEMA_VERSION` to the current payload shape *before projection*,
/// so a future version bump is a localized addition here rather than a
/// projector rewrite. Identity today (`EVENT_SCHEMA_VERSION == 1`: every
/// stored event is already current). When the event schema first changes,
/// add `(kind, schema_version)`-keyed transforms that return `Cow::Owned`
/// with the upgraded payload.
fn upcast_event(event: &Event) -> Cow<'_, Event> {
    // No historical versions to upcast yet.
    Cow::Borrowed(event)
}

pub fn rebuild(conn: &Connection, events: &[Event]) -> KimetsuResult<()> {
    reset_projection(conn)?;
    apply_events(conn, events)
}

/// Rebuild the projection from the durable events table (in place). Reads
/// every stored event, resets the derived tables, and re-projects — WITHOUT
/// re-inserting events (so no duplication). Returns the number of events
/// replayed.
pub fn rebuild_in_place(conn: &Connection) -> KimetsuResult<usize> {
    let events = read_events_ordered(conn)?;
    with_write_txn(conn, |c| {
        reset_projection(c)?;
        for event in &events {
            project_event(c, event)?;
        }
        Ok(())
    })?;
    Ok(events.len())
}

/// Read all stored events from the durable `events` table, ordered by
/// (ts, rowid) so replay is deterministic AND causal.
///
/// `rowid` is the implicit, insertion-monotonic key, so within an equal `ts`
/// it preserves append order — the true causal order (e.g. a `memory.cited`
/// appended before the `memory.superseded` that reassigns it). The previous
/// `event_id` tiebreak was NOT causal: event ids are ULIDs whose ordering is
/// only random-tail-stable within the same millisecond, so equal-`ts` events
/// replayed in a platform-dependent order — non-deterministic rebuilds.
fn read_events_ordered(conn: &Connection) -> KimetsuResult<Vec<Event>> {
    // Order by HLC (Hybrid Logical Clock): a globally-deterministic, causal total
    // order. On a single brain this generalizes the old (ts, rowid) order; across
    // synced brains it makes the merged-log replay converge (same projection on
    // every brain regardless of import order). `rowid` is a stable final tiebreak.
    let mut stmt = conn.prepare(
        "
        SELECT event_id, run_id, ts, kind, schema_version, payload_json, origin, hlc
        FROM events
        ORDER BY hlc, rowid
        ",
    )?;
    let rows = stmt.query_map([], |row| {
        let event_id_str: String = row.get(0)?;
        let run_id_str: String = row.get(1)?;
        let ts_str: String = row.get(2)?;
        let kind: String = row.get(3)?;
        let schema_version: u32 = row.get(4)?;
        let payload_json: String = row.get(5)?;
        let origin: Option<String> = row.get(6)?;
        let hlc: Option<String> = row.get(7)?;
        Ok((
            event_id_str,
            run_id_str,
            ts_str,
            kind,
            schema_version,
            payload_json,
            origin,
            hlc,
        ))
    })?;

    let mut events = Vec::new();
    for row in rows {
        let (event_id_str, run_id_str, ts_str, kind, schema_version, payload_json, origin, hlc) =
            row?;
        let event_id = EventId(
            ulid::Ulid::from_str(&event_id_str)
                .map_err(|e| format!("invalid event_id {event_id_str:?}: {e}"))?,
        );
        let run_id = RunId(
            ulid::Ulid::from_str(&run_id_str)
                .map_err(|e| format!("invalid run_id {run_id_str:?}: {e}"))?,
        );
        let ts = OffsetDateTime::parse(&ts_str, &Rfc3339)
            .map_err(|e| format!("invalid ts {ts_str:?}: {e}"))?;
        let payload: serde_json::Value = serde_json::from_str(&payload_json)?;
        events.push(Event {
            event_id,
            run_id,
            ts,
            parent_event_id: None, // not stored; never read by the projector
            kind,
            schema_version,
            payload,
            origin, // preserved across rebuild (NULL for pre-v8 events)
            hlc,    // preserved across rebuild (backfilled for pre-v9 events)
        });
    }
    Ok(events)
}

pub fn apply_events(conn: &Connection, events: &[Event]) -> KimetsuResult<()> {
    with_write_txn(conn, |c| {
        for event in events {
            apply_event(c, event)?;
        }
        Ok(())
    })
}

fn reset_projection(conn: &Connection) -> KimetsuResult<()> {
    // Wipe ONLY the derived/projected tables. The `events` table is the
    // durable log and MUST survive a rebuild (rebuild replays it).
    conn.execute_batch(
        "
        DELETE FROM runs;
        DELETE FROM sources;
        DELETE FROM memories;
        DELETE FROM memory_proposals;
        DELETE FROM memories_fts;
        DELETE FROM memory_citations;
        DELETE FROM memory_conflicts;
        DELETE FROM sync_conflicts;
        DELETE FROM memory_edges;
        DELETE FROM work_episodes;
        ",
    )?;
    Ok(())
}

fn apply_event(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let event = redact_memory_event(event);
    let event = event.as_ref();
    // Persist the event after memory payload redaction so durable replay tables
    // never become a second secret store.
    insert_event(conn, event)?;
    // Project the now-stored event into the derived tables.
    project_event(conn, event)
}

/// Project a single event into the derived tables (the dispatch half of
/// `apply_event`, WITHOUT inserting into the events table). Used by both the
/// write path (after insert) and the in-place rebuild (events already stored).
fn project_event(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    // Project through the durability seam so older-schema events normalize
    // to the current shape before dispatch.
    let upcasted = upcast_event(event);
    let redacted = redact_memory_event(upcasted.as_ref());
    let event = redacted.as_ref();

    match event.kind.as_str() {
        "run.started" => apply_run_started(conn, event),
        "run.finished" | "run.failed" | "run.aborted" => apply_terminal_run(conn, event),
        "memory.accepted" => apply_memory_accepted(conn, event),
        "memory.proposed" => apply_memory_proposed(conn, event),
        "memory.rejected" => apply_memory_rejected(conn, event),
        "memory.invalidated" => apply_memory_invalidated(conn, event),
        // v0.5.1: per-turn memory citation. The model emits this
        // via the `cite_memory` tool when it consciously leveraged
        // a retrieved capsule. Best-effort — a missing or
        // malformed payload just no-ops.
        "memory.cited" => apply_memory_cited(conn, event),
        // Story 2.4: explicit regret (negative outcome) on a memory. Only
        // manual regrets mutate stats (see apply_retrieval_regret); auto
        // telemetry regrets are projected as no-ops.
        "retrieval.regret" => apply_retrieval_regret(conn, event),
        // Testing/benchmark affordance: backdate created_at / last_useful_at so
        // age-sensitive policies (forgetting) can be exercised.
        "memory.aged" => apply_memory_aged(conn, event),
        // Story 3.1: near-duplicate merge — stamp superseded_by on merged members,
        // remove their FTS rows, and drop them from the ANN index.
        "memory.superseded" => apply_memory_superseded(conn, event),
        // #2 knowledge graph: a typed relation edge between two memories, written
        // by `kimetsu brain graph build`. Projected into `memory_edges` so the
        // graph-lite / petgraph retrieval backends can traverse it. Rebuild-safe:
        // the edge is re-derived by replaying this event.
        "memory.edge" => apply_memory_edge(conn, event),
        // Flagship 1 / Story 1.4: temporal validity — stamp valid_from / valid_to.
        "memory.temporal" => apply_memory_temporal(conn, event),
        // Flagship 1 / Story 1.3: episodic work-resume.
        "work.episode" => crate::episode::project_work_episode(conn, event),
        _ => Ok(()),
    }
}

fn redact_memory_event(event: &Event) -> Cow<'_, Event> {
    if !matches!(
        event.kind.as_str(),
        "memory.accepted" | "memory.proposed" | "memory.cited"
    ) {
        return Cow::Borrowed(event);
    }
    let (payload, changed) = redact_json_strings(&event.payload);
    if changed {
        Cow::Owned(Event {
            payload,
            ..event.clone()
        })
    } else {
        Cow::Borrowed(event)
    }
}

fn redact_json_strings(value: &serde_json::Value) -> (serde_json::Value, bool) {
    match value {
        serde_json::Value::String(text) => {
            let redaction = redact::redact_secrets(text);
            let changed = redaction.was_redacted();
            (serde_json::Value::String(redaction.text), changed)
        }
        serde_json::Value::Array(values) => {
            let mut changed = false;
            let values = values
                .iter()
                .map(|value| {
                    let (value, did_change) = redact_json_strings(value);
                    changed |= did_change;
                    value
                })
                .collect();
            (serde_json::Value::Array(values), changed)
        }
        serde_json::Value::Object(map) => {
            let mut changed = false;
            let map = map
                .iter()
                .map(|(key, value)| {
                    let (value, did_change) = redact_json_strings(value);
                    changed |= did_change;
                    (key.clone(), value)
                })
                .collect();
            (serde_json::Value::Object(map), changed)
        }
        other => (other.clone(), false),
    }
}

fn apply_memory_cited(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event
        .payload
        .get("memory_id")
        .and_then(|value| value.as_str())
    else {
        // No memory_id -> drop. Citations are best-effort metadata,
        // not load-bearing — silently skipping malformed payloads
        // keeps the run from breaking.
        return Ok(());
    };
    let turn = event
        .payload
        .get("turn")
        .and_then(|value| value.as_i64())
        .unwrap_or(0);
    let rationale = event
        .payload
        .get("rationale")
        .and_then(|value| value.as_str());
    let cited_at = ts_text(event)?;
    conn.execute(
        "
        INSERT OR REPLACE INTO memory_citations (
            run_id, memory_id, turn, cited_at, rationale
        )
        VALUES (?1, ?2, ?3, ?4, ?5)
        ",
        params![
            event.run_id.to_string(),
            memory_id,
            turn,
            cited_at,
            rationale,
        ],
    )?;

    // Flagship 2 / Story 2.4: a STANDALONE citation (sentinel/nil run_id, i.e.
    // the `record_mcp_citation` / `brain cite` path) is an explicit outcome
    // signal with no run finalization behind it, so apply the cited-memory
    // delta here. Citations tied to a REAL run keep metadata-only here and are
    // bumped by `apply_memory_usefulness_for_run` on the terminal run event —
    // gating on the sentinel avoids double-counting.
    if event.run_id.0 == ulid::Ulid::nil() {
        apply_cited_outcome(conn, memory_id, 1.0, 1.0, &cited_at, true)?;
    }
    Ok(())
}

/// Story 2.4: a memory the model flagged as unhelpful/misleading. Mirrors the
/// `run.failed` cited delta. Only EXPLICIT manual regrets (`payload.source ==
/// "manual"`, set by `record_regret` / `brain regret`) mutate stats; the
/// auto-emitted regret telemetry (no `source`) stays a no-op so existing
/// behavior is unchanged.
fn apply_retrieval_regret(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let is_manual = event
        .payload
        .get("source")
        .and_then(|v| v.as_str())
        .map(|s| s == "manual")
        .unwrap_or(false);
    if !is_manual {
        return Ok(());
    }
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let ts = ts_text(event)?;
    apply_cited_outcome(conn, memory_id, -1.0, 0.0, &ts, false)?;
    Ok(())
}

/// Backdate a memory's `created_at` / `last_useful_at` from a `memory.aged`
/// event (absolute timestamps in the payload → rebuild-deterministic).
fn apply_memory_aged(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    if let Some(created) = event.payload.get("created_at").and_then(|v| v.as_str()) {
        conn.execute(
            "UPDATE memories SET created_at = ?2 WHERE memory_id = ?1",
            params![memory_id, created],
        )?;
    }
    if let Some(last_useful) = event.payload.get("last_useful_at").and_then(|v| v.as_str()) {
        conn.execute(
            "UPDATE memories SET last_useful_at = ?2 WHERE memory_id = ?1",
            params![memory_id, last_useful],
        )?;
    }
    Ok(())
}

/// Confidence calibration smoothing factor (Bayesian-ish nudge per outcome).
const CONF_ALPHA: f64 = 0.05;

/// Apply a single cited-memory OUTCOME to one memory row, shared by the run
/// attribution path and the standalone cite/regret path: bump `use_count`,
/// add `usefulness_delta`, stamp `last_used_at` (and `last_useful_at` when
/// `bump_last_useful`), and nudge `confidence` toward `conf_target`
/// (`new = old + 0.05*(target-old)`, clamped to [0.1, 0.99]). Read-modify-write
/// on the deterministic event order → rebuild-safe.
fn apply_cited_outcome(
    conn: &Connection,
    memory_id: &str,
    usefulness_delta: f64,
    conf_target: f64,
    ts: &str,
    bump_last_useful: bool,
) -> KimetsuResult<()> {
    conn.execute(
        "UPDATE memories
         SET use_count = use_count + 1,
             usefulness_score = usefulness_score + ?2,
             last_used_at = ?3
         WHERE memory_id = ?1",
        params![memory_id, usefulness_delta, ts],
    )?;
    if bump_last_useful {
        conn.execute(
            "UPDATE memories SET last_useful_at = ?2 WHERE memory_id = ?1",
            params![memory_id, ts],
        )?;
    }
    let old_conf: f64 = conn
        .query_row(
            "SELECT confidence FROM memories WHERE memory_id = ?1",
            params![memory_id],
            |row| row.get::<_, f64>(0),
        )
        .unwrap_or(1.0);
    let new_conf = (old_conf + CONF_ALPHA * (conf_target - old_conf)).clamp(0.1, 0.99);
    conn.execute(
        "UPDATE memories SET confidence = ?2 WHERE memory_id = ?1",
        params![memory_id, new_conf],
    )?;
    Ok(())
}

pub(crate) fn insert_event(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let payload = serde_json::to_string(&event.payload)?;
    conn.execute(
        "
        INSERT OR IGNORE INTO events (
            event_id, run_id, ts, kind, schema_version, payload_json, origin, hlc
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
        ",
        params![
            event.event_id.to_string(),
            event.run_id.to_string(),
            ts_text(event)?,
            event.kind,
            event.schema_version,
            payload,
            event.origin,
            event.hlc,
        ],
    )?;
    Ok(())
}

fn apply_run_started(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let project_id = event
        .payload
        .get("project_id")
        .and_then(|value| value.as_str())
        .unwrap_or("unknown");
    let task = event
        .payload
        .get("task")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let model = event
        .payload
        .get("model")
        .and_then(|value| value.as_str())
        .map(str::to_string);

    conn.execute(
        "
        INSERT OR IGNORE INTO runs (
            run_id, project_id, task, started_at, model, total_cost_usd
        )
        VALUES (?1, ?2, ?3, ?4, ?5, 0)
        ",
        params![
            event.run_id.to_string(),
            project_id,
            task,
            ts_text(event)?,
            model
        ],
    )?;
    Ok(())
}

fn apply_terminal_run(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let total_cost = event
        .payload
        .get("total_cost_usd")
        .and_then(|value| value.as_f64())
        .unwrap_or(0.0);

    conn.execute(
        "
        UPDATE runs
        SET ended_at = ?2,
            terminal_kind = ?3,
            total_cost_usd = ?4
        WHERE run_id = ?1
        ",
        params![
            event.run_id.to_string(),
            ts_text(event)?,
            event.kind,
            total_cost
        ],
    )?;

    apply_memory_usefulness_for_run(conn, event)?;
    Ok(())
}

/// MP-4a + v0.5.1 outcome attribution: when a run terminates, walk every
/// `context.injected` event AND every `memory.cited` event the run emitted,
/// split the unique memory ids into "cited" vs "silent passenger", and
/// update each memory's `use_count` + `usefulness_score`.
///
/// Delta rules:
///   run.finished:
///     cited memory     -> +1.0 usefulness (matches MP-4a baseline)
///     silent passenger -> +0.1 usefulness (weaker signal — it was on
///                         screen but the model didn't reach for it)
///   run.failed (cat != "Gate"):
///     cited memory     -> -1.0 usefulness (the brain pushed wrong)
///     silent passenger -> -0.1 usefulness (was retrieved, didn't help)
///   run.failed (cat == "Gate"):
///     no update (graceful early-exit; the plan-create existence guard
///     doesn't reflect on the memory)
///   run.aborted:
///     no update (user-initiated stop)
///
/// Pre-v0.5.1 behavior: cited == silent (both got the full ±1). When no
/// `memory.cited` events exist (e.g. older runs, models that never call
/// `cite_memory`), every retrieved memory is treated as a silent
/// passenger — i.e. weak ±0.1 instead of strong ±1. This is intentional:
/// without citation evidence we shouldn't claim a memory "helped." The
/// blame command surfaces the discrepancy so operators can encourage
/// citation usage where the brain is under-rewarding good capsules.
fn apply_memory_usefulness_for_run(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let (strong, weak): (f64, f64) = match event.kind.as_str() {
        "run.finished" => (1.0, 0.1),
        "run.failed" => {
            let category = event
                .payload
                .get("category")
                .and_then(|value| value.as_str())
                .unwrap_or("");
            if category == "Gate" {
                return Ok(());
            }
            (-1.0, -0.1)
        }
        _ => return Ok(()), // run.aborted, anything else: no update
    };

    let run_id = event.run_id.to_string();
    let retrieved = collect_injected_memory_ids(conn, &run_id)?;
    if retrieved.is_empty() {
        return Ok(());
    }
    let cited = collect_cited_memory_ids(conn, &run_id)?;
    let ts = ts_text(event)?;
    // v0.5.1: bump `last_useful_at` only on cited + run.finished.
    // Cited + run.failed doesn't count (the memory misled the
    // model). Silent passengers never bump regardless of outcome.
    let bump_last_useful = event.kind == "run.finished";

    // Flagship 2 / Story 2.4: confidence calibration target.
    // run.finished → target 1.0 (success), run.failed → target 0.0 (failure).
    // alpha = 0.05: conservative Bayesian-ish smoothing.
    let conf_target: Option<f64> = match event.kind.as_str() {
        "run.finished" => Some(1.0),
        "run.failed" => Some(0.0),
        _ => None,
    };

    for memory_id in &retrieved {
        let is_cited = cited.contains(memory_id);
        let delta = if is_cited { strong } else { weak };
        conn.execute(
            "
            UPDATE memories
            SET use_count = use_count + 1,
                usefulness_score = usefulness_score + ?2,
                last_used_at = ?3
            WHERE memory_id = ?1
            ",
            params![memory_id, delta, ts],
        )?;
        if is_cited && bump_last_useful {
            // v0.5.1: separate column for the decay reference. We
            // intentionally only touch it for confirmed successful
            // citations so the half-life curve in `usefulness_-
            // multiplier` reflects when the memory was last
            // PROVEN to help — not just when it was retrieved.
            conn.execute(
                "UPDATE memories SET last_useful_at = ?2 WHERE memory_id = ?1",
                params![memory_id, ts],
            )?;
        }
        // Flagship 2 / Story 2.4: update confidence only for cited memories.
        // Silent passengers do not get a confidence update — only explicitly
        // cited memories affect the calibration.
        if is_cited {
            if let Some(target) = conf_target {
                // Read current confidence, apply Bayesian-ish posterior, clamp.
                let old_conf: f64 = conn
                    .query_row(
                        "SELECT confidence FROM memories WHERE memory_id = ?1",
                        params![memory_id],
                        |row| row.get::<_, f64>(0),
                    )
                    .unwrap_or(1.0);
                let new_conf = (old_conf + CONF_ALPHA * (target - old_conf)).clamp(0.1, 0.99);
                conn.execute(
                    "UPDATE memories SET confidence = ?2 WHERE memory_id = ?1",
                    params![memory_id, new_conf],
                )?;
            }
        }
    }
    Ok(())
}

/// v0.5.1: walk this run's `memory_citations` rows and return the unique
/// memory ids that the model explicitly cited via the `cite_memory` tool.
/// Used by `apply_memory_usefulness_for_run` to give the strong delta
/// only to memories that actually contributed to the model's reasoning.
fn collect_cited_memory_ids(
    conn: &Connection,
    run_id: &str,
) -> KimetsuResult<std::collections::BTreeSet<String>> {
    let mut stmt = conn.prepare(
        "
        SELECT DISTINCT memory_id
        FROM memory_citations
        WHERE run_id = ?1
        ",
    )?;
    let rows = stmt.query_map(params![run_id], |row| row.get::<_, String>(0))?;
    let mut out = std::collections::BTreeSet::new();
    for row in rows {
        out.insert(row?);
    }
    Ok(out)
}

/// Walk this run's `context.injected` events and return the unique memory
/// ids that were surfaced into any stage's broker bundle. Per-run counting:
/// a memory injected into Localization AND PatchPlan in the same run counts
/// once.
fn collect_injected_memory_ids(conn: &Connection, run_id: &str) -> KimetsuResult<Vec<String>> {
    let mut stmt = conn.prepare(
        "
        SELECT payload_json
        FROM events
        WHERE run_id = ?1 AND kind = 'context.injected'
        ",
    )?;
    let rows = stmt.query_map(params![run_id], |row| row.get::<_, String>(0))?;

    let mut seen = std::collections::BTreeSet::new();
    for row in rows {
        let payload_json = row?;
        let payload: serde_json::Value = serde_json::from_str(&payload_json)?;
        if let Some(ids) = payload.get("memory_ids").and_then(|v| v.as_array()) {
            for id in ids {
                if let Some(id_str) = id.as_str()
                    && !id_str.is_empty()
                {
                    seen.insert(id_str.to_string());
                }
            }
        }
    }
    Ok(seen.into_iter().collect())
}

fn apply_memory_accepted(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event
        .payload
        .get("memory_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let scope = event
        .payload
        .get("scope")
        .and_then(|value| value.as_str())
        .unwrap_or("global_user");
    let kind = event
        .payload
        .get("kind")
        .and_then(|value| value.as_str())
        .unwrap_or("fact");
    let text = event
        .payload
        .get("text")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let normalized_text = event
        .payload
        .get("normalized_text")
        .and_then(|value| value.as_str())
        .unwrap_or(text);
    let confidence = event
        .payload
        .get("confidence")
        .and_then(|value| value.as_f64())
        .unwrap_or(1.0);
    // Flagship 2 / Story 2.1: initial usefulness seed.
    // Pre-Flagship-2 events don't carry this field → default 0.0 (backward compat).
    let initial_usefulness = event
        .payload
        .get("initial_usefulness")
        .and_then(|value| value.as_f64())
        .unwrap_or(0.0) as f32;
    let provenance_snapshot = event
        .payload
        .get("provenance_snapshot")
        .cloned()
        .unwrap_or_else(
            || serde_json::json!({ "source": "event", "event_id": event.event_id.to_string() }),
        );

    conn.execute(
        "
        INSERT OR REPLACE INTO memories (
            memory_id, scope, kind, text, normalized_text, confidence,
            source_event_id, provenance_snapshot_json, created_at, use_count,
            usefulness_score
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 0, ?10)
        ",
        params![
            memory_id,
            scope,
            kind,
            text,
            normalized_text,
            confidence,
            event.event_id.to_string(),
            serde_json::to_string(&provenance_snapshot)?,
            ts_text(event)?,
            initial_usefulness
        ],
    )?;

    conn.execute(
        "DELETE FROM memories_fts WHERE memory_id = ?1",
        params![memory_id],
    )?;
    conn.execute(
        "INSERT INTO memories_fts (memory_id, text, kind, scope) VALUES (?1, ?2, ?3, ?4)",
        params![memory_id, text, kind, scope],
    )?;
    Ok(())
}

fn apply_memory_proposed(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(proposal_id) = event
        .payload
        .get("proposal_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let scope = event
        .payload
        .get("scope")
        .and_then(|value| value.as_str())
        .unwrap_or("run");
    let kind = event
        .payload
        .get("kind")
        .and_then(|value| value.as_str())
        .unwrap_or("fact");
    let text = event
        .payload
        .get("text")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let rationale = event
        .payload
        .get("rationale")
        .and_then(|value| value.as_str())
        .unwrap_or("");
    let confidence = event
        .payload
        .get("proposed_confidence")
        .and_then(|value| value.as_f64())
        .unwrap_or(0.5);
    let source_event_ids = event
        .payload
        .get("source_event_ids")
        .cloned()
        .unwrap_or_else(|| serde_json::json!([]));

    conn.execute(
        "
        INSERT OR REPLACE INTO memory_proposals (
            proposal_id, run_id, scope, kind, text, rationale,
            proposed_confidence, source_event_ids_json, status
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending')
        ",
        params![
            proposal_id,
            event.run_id.to_string(),
            scope,
            kind,
            text,
            rationale,
            confidence,
            serde_json::to_string(&source_event_ids)?
        ],
    )?;
    Ok(())
}

fn apply_memory_rejected(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(proposal_id) = event
        .payload
        .get("proposal_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let reason = event
        .payload
        .get("reason")
        .and_then(|value| value.as_str())
        .map(|s| s.to_string());

    conn.execute(
        "
        UPDATE memory_proposals
        SET status = 'rejected',
            decided_at = ?2,
            decided_by = 'cli',
            decided_reason = ?3
        WHERE proposal_id = ?1
        ",
        params![proposal_id, ts_text(event)?, reason],
    )?;
    Ok(())
}

/// MP-4d: human-invalidated memories are flagged so the broker excludes
/// them from retrieval and `kimetsu brain memory list` can render the
/// reason. The canonical trace still holds the original memory.accepted
/// event; invalidation is additive metadata, not a delete.
fn apply_memory_invalidated(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event
        .payload
        .get("memory_id")
        .and_then(|value| value.as_str())
    else {
        return Ok(());
    };
    let reason = event
        .payload
        .get("reason")
        .and_then(|value| value.as_str())
        .map(|s| s.to_string());
    conn.execute(
        "
        UPDATE memories
        SET invalidated_at = ?2,
            invalidated_reason = ?3
        WHERE memory_id = ?1
        ",
        params![memory_id, ts_text(event)?, reason],
    )?;
    #[cfg(feature = "embeddings")]
    crate::ann::on_invalidate(conn, memory_id);
    Ok(())
}

/// Story 3.1: project a `memory.superseded` event.
///
/// Payload fields:
///   `memory_id`       — the member being superseded (merged into survivor)
///   `survivor_id`     — the memory that absorbs the cluster
///   `use_count_delta` — member's use_count contribution (optional, default 0)
///   `score_delta`     — member's usefulness_score contribution (optional, default 0)
///
/// Projection:
///   1. Stamp `superseded_by = survivor_id` on the member row.
///   2. Add member's use_count_delta / score_delta to the survivor row.
///   3. Reassign the member's citations to the survivor.
///   4. Delete the member's FTS row so it stops appearing in lexical retrieval.
///   5. Remove the member from the ANN index (embeddings feature only).
///
/// The member row is intentionally NOT invalidated — `blame` can still see
/// it and trace it to its survivor via `superseded_by`.
///
/// This is the single canonical projection path used by BOTH the live
/// consolidation path (via `apply_events`) and `rebuild_in_place` (replay),
/// so the two can never drift.
fn apply_memory_superseded(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let Some(survivor_id) = event.payload.get("survivor_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let use_count_delta = event
        .payload
        .get("use_count_delta")
        .and_then(|v| v.as_i64())
        .unwrap_or(0);
    let score_delta = event
        .payload
        .get("score_delta")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.0);

    // Slice B: detect a concurrent-supersede conflict. If this member is already
    // superseded by a DIFFERENT survivor, two edits (typically from different
    // brains' consolidations) disagree. HLC-order replay still picks a
    // deterministic winner (the supersede applied last in HLC order — see below),
    // so brains converge; we record the collision for human review. Replay-safe:
    // sync_conflicts is a projection cleared by reset_projection and the pair is
    // canonicalized + INSERT OR IGNORE, so it records once.
    let prior_survivor: Option<String> = conn
        .query_row(
            "SELECT superseded_by FROM memories WHERE memory_id = ?1",
            params![memory_id],
            |r| r.get::<_, Option<String>>(0),
        )
        .optional()?
        .flatten();
    if let Some(prev) = prior_survivor {
        if prev != survivor_id {
            let (a, b) = if prev.as_str() < survivor_id {
                (prev.as_str(), survivor_id)
            } else {
                (survivor_id, prev.as_str())
            };
            let detected_at = ts_text(event)?;
            conn.execute(
                "INSERT OR IGNORE INTO sync_conflicts
                     (member_id, survivor_a, survivor_b, detected_at)
                 VALUES (?1, ?2, ?3, ?4)",
                params![memory_id, a, b, detected_at],
            )?;
        }
    }

    // 1. Stamp superseded_by on the member (last supersede in HLC replay order
    //    wins → deterministic survivor on every brain).
    conn.execute(
        "UPDATE memories SET superseded_by = ?2 WHERE memory_id = ?1",
        params![memory_id, survivor_id],
    )?;

    // 2. Accumulate the member's stats onto the survivor.
    if use_count_delta != 0 || score_delta != 0.0 {
        conn.execute(
            "UPDATE memories
             SET use_count       = use_count       + ?2,
                 usefulness_score = usefulness_score + ?3
             WHERE memory_id = ?1",
            params![survivor_id, use_count_delta, score_delta],
        )?;
    }

    // 3. Reassign citations from member to survivor (shared helper).
    reassign_citations_projection(conn, memory_id, survivor_id)?;

    // 4. Remove from FTS index.
    conn.execute(
        "DELETE FROM memories_fts WHERE memory_id = ?1",
        params![memory_id],
    )?;

    // 5. Remove from ANN index (embeddings feature only).
    #[cfg(feature = "embeddings")]
    crate::ann::on_supersede(conn, memory_id);

    // 6. S5.2: insert a `supersedes` edge from survivor → member into the
    //    typed-edge projection table so graph-lite traversal can follow it.
    let edge_ts = ts_text(event)?;
    insert_memory_edge(conn, survivor_id, memory_id, "supersedes", &edge_ts)?;

    Ok(())
}

/// Flagship 1 / Story 1.4: project a `memory.temporal` event.
///
/// Payload fields:
///   `memory_id`  — the memory whose validity window is being stamped.
///   `valid_from` — optional RFC 3339 lower bound (inclusive). NULL = "since creation".
///   `valid_to`   — optional RFC 3339 upper bound (exclusive). NULL = "never expires".
///                  When set to a past timestamp the memory is "expired" and the
///                  default retrieval path (`valid_to IS NULL OR valid_to > now`)
///                  will exclude it.
///
/// The update is additive: only the fields present in the payload are written.
/// A `memory.temporal` event with only `valid_to` leaves `valid_from` unchanged.
fn apply_memory_temporal(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(memory_id) = event.payload.get("memory_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let valid_from = event
        .payload
        .get("valid_from")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let valid_to = event
        .payload
        .get("valid_to")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Build a partial update: only stamp the fields that are present in the payload.
    // Both absent → no-op (caller sent an empty event — treat gracefully).
    match (valid_from, valid_to) {
        (Some(vf), Some(vt)) => {
            conn.execute(
                "UPDATE memories SET valid_from = ?2, valid_to = ?3 WHERE memory_id = ?1",
                params![memory_id, vf, vt],
            )?;
        }
        (Some(vf), None) => {
            conn.execute(
                "UPDATE memories SET valid_from = ?2 WHERE memory_id = ?1",
                params![memory_id, vf],
            )?;
        }
        (None, Some(vt)) => {
            conn.execute(
                "UPDATE memories SET valid_to = ?2 WHERE memory_id = ?1",
                params![memory_id, vt],
            )?;
        }
        (None, None) => {} // no-op
    }
    Ok(())
}

/// Flagship 1 / Story 1.4: programmatic API for stamping a memory's temporal
/// validity window.
///
/// Emits a `memory.temporal` event into the event log (so the action is
/// rebuild-safe and replay-correct) and applies it immediately by projecting
/// it into the `memories` table.
///
/// Used by the bench seeder (`brain_bench_single`) and will be used by
/// Flagship 1 Pass B (resolution) once it is implemented.
///
/// `valid_from` and `valid_to` are RFC 3339 / ISO-8601 strings. Pass `None`
/// to leave a bound unchanged.
pub fn mark_memory_temporal(
    conn: &Connection,
    memory_id: &str,
    valid_from: Option<&str>,
    valid_to: Option<&str>,
) -> KimetsuResult<()> {
    // Build a synthetic event to go through the standard projection path.
    // We use a throwaway RunId (zero ULID) since this is an out-of-band
    // operation (not part of a live agent run).
    use kimetsu_core::ids::RunId;
    let run_id = RunId::new();
    let mut payload = serde_json::json!({ "memory_id": memory_id });
    if let Some(vf) = valid_from {
        payload["valid_from"] = serde_json::Value::String(vf.to_string());
    }
    if let Some(vt) = valid_to {
        payload["valid_to"] = serde_json::Value::String(vt.to_string());
    }
    let event = kimetsu_core::event::Event::new(run_id, "memory.temporal", payload);
    // Use apply_event so the event is persisted AND projected in one step.
    apply_event(conn, &event)
}

/// #2 knowledge graph: project a `memory.edge` event into `memory_edges`.
///
/// Payload fields:
///   `src_id`    — source memory id.
///   `dst_id`    — destination memory id.
///   `edge_type` — relation kind (e.g. `"relates_to"`, `"refines"`).
///
/// A missing/malformed payload no-ops (best-effort, matching the other memory
/// projectors). The `OR IGNORE` insert makes replay idempotent.
fn apply_memory_edge(conn: &Connection, event: &Event) -> KimetsuResult<()> {
    let Some(src_id) = event.payload.get("src_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let Some(dst_id) = event.payload.get("dst_id").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    let Some(edge_type) = event.payload.get("edge_type").and_then(|v| v.as_str()) else {
        return Ok(());
    };
    // Never self-loop.
    if src_id == dst_id {
        return Ok(());
    }
    let edge_ts = ts_text(event)?;
    insert_memory_edge(conn, src_id, dst_id, edge_type, &edge_ts)
}

/// #2 knowledge graph: programmatic API for writing a batch of typed relation
/// edges. Each `(src_id, dst_id, edge_type)` is emitted as a `memory.edge` event
/// (so the action is rebuild-safe — replay reconstructs the edges) and projected
/// into `memory_edges` in a single transaction via `apply_events`.
///
/// Self-loops (`src == dst`) are skipped. Returns the number of edges written.
/// Used by `kimetsu brain graph build`.
pub fn add_memory_edges(
    conn: &Connection,
    edges: &[(String, String, String)],
) -> KimetsuResult<usize> {
    use kimetsu_core::ids::RunId;
    let run_id = RunId::new();
    let mut events = Vec::with_capacity(edges.len());
    let mut written = 0usize;
    for (src_id, dst_id, edge_type) in edges {
        if src_id == dst_id {
            continue;
        }
        let payload = serde_json::json!({
            "src_id": src_id,
            "dst_id": dst_id,
            "edge_type": edge_type,
        });
        events.push(kimetsu_core::event::Event::new(
            run_id,
            "memory.edge",
            payload,
        ));
        written += 1;
    }
    apply_events(conn, &events)?;
    Ok(written)
}

/// S5.2: insert a typed edge into `memory_edges`.
///
/// This is the **single canonical path** for writing to `memory_edges`.
/// Call it from any projector that wants to populate an edge type.
///
/// Currently populated edge types:
///   * `"supersedes"` — populated here by `apply_memory_superseded`.
///
/// Reserved edge types (populated by Flagship 1 / Story 1.7):
///   * `"refines"`          — memory A refines / narrows memory B.
///   * `"dead_end_of"`      — task outcome closes a dead-end chain.
///   * `"decision_touches"` — decision memory touches a file path.
///   * `"lesson_from"`      — lesson memory derived from a source memory.
///
/// The INSERT is `OR IGNORE` so replaying the same event twice is safe.
pub(crate) fn insert_memory_edge(
    conn: &Connection,
    src_id: &str,
    dst_id: &str,
    edge_type: &str,
    created_at: &str,
) -> KimetsuResult<()> {
    conn.execute(
        "INSERT OR IGNORE INTO memory_edges (src_id, dst_id, edge_type, created_at)
         VALUES (?1, ?2, ?3, ?4)",
        params![src_id, dst_id, edge_type, created_at],
    )?;
    Ok(())
}

/// Shared citation-reassignment helper used by both the live consolidation
/// path and the replay path (`apply_memory_superseded`).  Keeping a single
/// implementation prevents the two paths from drifting.
///
/// Copies every `memory_citations` row from `from_id` to `to_id`
/// (INSERT OR IGNORE — skip conflicts), then deletes the originals.
pub(crate) fn reassign_citations_projection(
    conn: &Connection,
    from_id: &str,
    to_id: &str,
) -> KimetsuResult<()> {
    // Collect existing citations for `from_id`.
    let rows: Vec<(String, i64, String, Option<String>)> = {
        let mut stmt = conn.prepare(
            "SELECT run_id, turn, cited_at, rationale
             FROM memory_citations WHERE memory_id = ?1",
        )?;
        stmt.query_map(params![from_id], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, i64>(1)?,
                r.get::<_, String>(2)?,
                r.get::<_, Option<String>>(3)?,
            ))
        })?
        .collect::<Result<_, _>>()?
    };

    for (run_id, turn, cited_at, rationale) in &rows {
        conn.execute(
            "INSERT OR IGNORE INTO memory_citations
             (run_id, memory_id, turn, cited_at, rationale)
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![run_id, to_id, turn, cited_at, rationale],
        )?;
    }

    conn.execute(
        "DELETE FROM memory_citations WHERE memory_id = ?1",
        params![from_id],
    )?;

    Ok(())
}

pub fn ensure_schema(conn: &Connection) -> KimetsuResult<()> {
    schema::initialize(conn)
}

fn ts_text(event: &Event) -> KimetsuResult<String> {
    Ok(event.ts.format(&Rfc3339)?)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use kimetsu_core::event::Event;
    use kimetsu_core::ids::RunId;
    use rusqlite::{Connection, params};
    use serde_json::json;

    use super::{apply_events, rebuild_in_place, upcast_event};
    use crate::schema;

    fn make_conn() -> Connection {
        let conn = Connection::open_in_memory().expect("open_in_memory");
        schema::initialize(&conn).expect("schema::initialize");
        conn
    }

    fn make_event(run_id: RunId, kind: &str, payload: serde_json::Value) -> Event {
        Event::new(run_id, kind, payload)
    }

    /// The nil-ULID sentinel run id: a STANDALONE `memory.cited` (this run id)
    /// applies a real outcome delta (+use_count) via `apply_cited_outcome`.
    fn sentinel_run() -> RunId {
        RunId(ulid::Ulid::nil())
    }

    // ------------------------------------------------------------------
    // v3.0 #3: concurrent writers to ONE on-disk brain.db must not lose
    // updates. Independent Connections behave like independent processes for
    // SQLite locking, so this exercises the IMMEDIATE-transaction + busy-retry
    // write path under real contention.
    // ------------------------------------------------------------------
    #[test]
    fn concurrent_cites_lose_no_updates() {
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::sync::{Arc, Barrier};

        static CTR: AtomicU64 = AtomicU64::new(0);
        let n = CTR.fetch_add(1, Ordering::Relaxed);
        let db_path =
            std::env::temp_dir().join(format!("kimetsu-concurrency-{}-{n}.db", std::process::id()));
        let _ = std::fs::remove_file(&db_path);

        // Seed one accepted memory (use_count starts at 0).
        let mem_id = "mem-concurrency";
        {
            let conn = Connection::open(&db_path).expect("open seed");
            schema::initialize(&conn).expect("init seed");
            let accepted = Event::new(
                sentinel_run(),
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "hammer me",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            );
            apply_events(&conn, std::slice::from_ref(&accepted)).expect("seed accepted");
        }

        const THREADS: usize = 6;
        const CITES_PER_THREAD: usize = 25;
        let barrier = Arc::new(Barrier::new(THREADS));
        let path = Arc::new(db_path.clone());

        let mut handles = Vec::new();
        for _ in 0..THREADS {
            let b = Arc::clone(&barrier);
            let p = Arc::clone(&path);
            handles.push(std::thread::spawn(move || {
                // Each thread = its own connection (≈ its own process).
                let conn = Connection::open(&*p).expect("open writer");
                schema::initialize(&conn).expect("init writer");
                b.wait(); // maximize contention
                for _ in 0..CITES_PER_THREAD {
                    let cited = Event::new(
                        sentinel_run(),
                        "memory.cited",
                        json!({ "memory_id": mem_id, "turn": 0 }),
                    );
                    // Must not error under contention (busy-retry + IMMEDIATE).
                    apply_events(&conn, std::slice::from_ref(&cited))
                        .expect("concurrent cite must succeed");
                }
            }));
        }
        for h in handles {
            h.join().expect("thread join");
        }

        let expected = (THREADS * CITES_PER_THREAD) as i64;

        let conn = Connection::open(&db_path).expect("open verify");
        schema::initialize(&conn).expect("init verify");

        // No lost increments: every concurrent cite landed.
        let use_count: i64 = conn
            .query_row(
                "SELECT use_count FROM memories WHERE memory_id = ?1",
                params![mem_id],
                |r| r.get(0),
            )
            .expect("read use_count");
        assert_eq!(
            use_count, expected,
            "lost updates under concurrency: got {use_count}, expected {expected}"
        );

        // All events durably appended (1 accepted + N*M cited).
        let event_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .expect("count events");
        assert_eq!(event_count, expected + 1, "missing durable events");

        // Rebuild is deterministic: replay reproduces the same use_count.
        rebuild_in_place(&conn).expect("rebuild");
        let after: i64 = conn
            .query_row(
                "SELECT use_count FROM memories WHERE memory_id = ?1",
                params![mem_id],
                |r| r.get(0),
            )
            .expect("read use_count after rebuild");
        assert_eq!(after, expected, "rebuild changed the projected use_count");

        drop(conn);
        let _ = std::fs::remove_file(&db_path);
        // WAL sidecars.
        let _ = std::fs::remove_file(db_path.with_extension("db-wal"));
        let _ = std::fs::remove_file(db_path.with_extension("db-shm"));
    }

    #[test]
    fn event_carries_and_roundtrips_origin() {
        use super::{insert_event, read_events_ordered};

        let conn = make_conn();
        kimetsu_core::event::set_process_origin("test-machine/unit");

        let ev = Event::new(
            sentinel_run(),
            "memory.accepted",
            json!({
                "memory_id": "m-origin",
                "text": "with origin",
                "scope": "global_user",
                "kind": "fact"
            }),
        );
        // process_origin() is a OnceLock — first setter wins; assert the event
        // carries SOME origin and that it round-trips through the events table.
        let stamped = ev.origin.clone();
        insert_event(&conn, &ev).expect("insert");
        let read_back = read_events_ordered(&conn).expect("read");
        assert_eq!(read_back.len(), 1);
        assert_eq!(read_back[0].origin, stamped, "origin must round-trip");
    }

    // ------------------------------------------------------------------
    // A6-1. upcast_event is identity (Cow::Borrowed) at schema_version 1
    // ------------------------------------------------------------------
    #[test]
    fn upcast_is_identity_at_v1() {
        let run_id = RunId::new();
        let event = make_event(
            run_id,
            "run.started",
            json!({"project_id": "p1", "task": "t"}),
        );
        assert_eq!(
            event.schema_version, 1,
            "Event::new must stamp schema_version=1"
        );

        let cow = upcast_event(&event);
        // Must be a Borrowed reference, not an owned clone.
        assert!(
            matches!(cow, Cow::Borrowed(_)),
            "upcast_event must return Cow::Borrowed for current schema_version"
        );
        // The payload fields must be unchanged.
        let out = cow.as_ref();
        assert_eq!(out.kind, event.kind);
        assert_eq!(out.schema_version, event.schema_version);
        assert_eq!(out.payload, event.payload);
    }

    // ------------------------------------------------------------------
    // A6-2. Per-kind missing-field durability: every dispatched kind with
    // an empty payload replays without panic/error.
    // ------------------------------------------------------------------

    fn assert_empty_payload_ok(kind: &str) {
        let conn = make_conn();
        let run_id = RunId::new();
        let event = make_event(run_id, kind, json!({}));
        let result = apply_events(&conn, &[event]);
        assert!(
            result.is_ok(),
            "apply_events with empty payload for kind={kind:?} must return Ok(()), got: {result:?}"
        );
    }

    #[test]
    fn empty_payload_run_started() {
        assert_empty_payload_ok("run.started");
    }

    #[test]
    fn empty_payload_run_finished() {
        assert_empty_payload_ok("run.finished");
    }

    #[test]
    fn empty_payload_run_failed() {
        assert_empty_payload_ok("run.failed");
    }

    #[test]
    fn empty_payload_run_aborted() {
        assert_empty_payload_ok("run.aborted");
    }

    #[test]
    fn empty_payload_memory_accepted() {
        assert_empty_payload_ok("memory.accepted");
    }

    #[test]
    fn empty_payload_memory_proposed() {
        assert_empty_payload_ok("memory.proposed");
    }

    #[test]
    fn empty_payload_memory_rejected() {
        assert_empty_payload_ok("memory.rejected");
    }

    #[test]
    fn empty_payload_memory_invalidated() {
        assert_empty_payload_ok("memory.invalidated");
    }

    #[test]
    fn empty_payload_memory_cited() {
        assert_empty_payload_ok("memory.cited");
    }

    // F1: empty payload work.episode must not panic/error.
    #[test]
    fn empty_payload_work_episode() {
        assert_empty_payload_ok("work.episode");
    }

    // F1A: empty payload memory.temporal must not panic/error.
    #[test]
    fn empty_payload_memory_temporal() {
        assert_empty_payload_ok("memory.temporal");
    }

    // ------------------------------------------------------------------
    // A6-3. A well-formed run.started event still projects correctly
    // after routing through the upcast seam.
    // ------------------------------------------------------------------
    #[test]
    fn well_formed_run_started_projects_correctly() {
        let conn = make_conn();
        let run_id = RunId::new();
        let event = make_event(
            run_id,
            "run.started",
            json!({
                "project_id": "proj-abc",
                "task": "fix the bug",
                "model": "claude-sonnet-4-6"
            }),
        );
        apply_events(&conn, &[event])
            .expect("apply_events must succeed for well-formed run.started");

        let row: (String, String, String) = conn
            .query_row(
                "SELECT run_id, project_id, task FROM runs WHERE run_id = ?1",
                [run_id.to_string()],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
            )
            .expect("runs row must exist after apply_events");

        assert_eq!(row.0, run_id.to_string());
        assert_eq!(row.1, "proj-abc");
        assert_eq!(row.2, "fix the bug");
    }

    // ------------------------------------------------------------------
    // W1.1: reset_projection keeps the events table intact while wiping
    // all derived/projected tables.
    // ------------------------------------------------------------------
    #[test]
    fn reset_projection_keeps_events() {
        use super::reset_projection;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-reset-test";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "hello",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        // Preconditions: both events stored, memory projected.
        let event_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert!(event_count > 0, "events must be stored before reset");
        let mem_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .unwrap();
        assert_eq!(mem_count, 1, "memory must be projected before reset");

        reset_projection(&conn).expect("reset_projection");

        // Events MUST survive.
        let event_count_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            event_count_after, event_count,
            "reset_projection must NOT delete from events"
        );

        // All derived tables must be empty.
        let memories_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            memories_after, 0,
            "memories must be cleared by reset_projection"
        );

        let runs_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM runs", [], |r| r.get(0))
            .unwrap();
        assert_eq!(runs_after, 0, "runs must be cleared by reset_projection");

        let citations_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_citations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            citations_after, 0,
            "memory_citations must be cleared by reset_projection"
        );

        let conflicts_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_conflicts", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            conflicts_after, 0,
            "memory_conflicts must be cleared by reset_projection"
        );

        // work_episodes must also be cleared.
        let episodes_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM work_episodes", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            episodes_after, 0,
            "work_episodes must be cleared by reset_projection"
        );
    }

    // ------------------------------------------------------------------
    // W1.2a: rebuild_in_place round-trips without duplicating events.
    // ------------------------------------------------------------------
    #[test]
    fn rebuild_in_place_no_dup_events() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-dup-test";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "no dup",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            ),
            make_event(run_id, "run.finished", json!({"total_cost_usd": 0.01})),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let event_count_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(event_count_before, 3, "expected 3 events seeded");

        // Manually wipe derived tables to simulate a corrupted projection.
        conn.execute_batch("DELETE FROM memories; DELETE FROM memories_fts;")
            .unwrap();
        let mem_count_wiped: i64 = conn
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .unwrap();
        assert_eq!(mem_count_wiped, 0, "memories wiped before rebuild_in_place");

        let replayed = rebuild_in_place(&conn).expect("rebuild_in_place");

        // Correct replay count.
        assert_eq!(
            replayed, 3,
            "rebuild_in_place must return the number of events replayed"
        );

        // Memory is back.
        let mem_exists: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(
            mem_exists, 1,
            "memory must be re-projected after rebuild_in_place"
        );

        // NO duplicate events inserted.
        let event_count_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            event_count_after, event_count_before,
            "rebuild_in_place must NOT insert duplicate events"
        );
    }

    // ------------------------------------------------------------------
    // W1.2b: rebuild_in_place reconstructs memory_citations (proves
    // project_event runs the full dispatch including memory.cited).
    // ------------------------------------------------------------------
    #[test]
    fn rebuild_in_place_reconstructs_citations() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-cite-test";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "cite me",
                    "scope": "global_user",
                    "kind": "fact"
                }),
            ),
            make_event(
                run_id,
                "memory.cited",
                json!({
                    "memory_id": mem_id,
                    "turn": 2,
                    "rationale": "relevant context"
                }),
            ),
            make_event(run_id, "run.finished", json!({"total_cost_usd": 0.0})),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let citations_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_citations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            citations_before, 1,
            "citation must exist after apply_events"
        );

        let replayed = rebuild_in_place(&conn).expect("rebuild_in_place");
        assert_eq!(replayed, 4, "expected 4 events replayed");

        let citations_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_citations", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            citations_after, 1,
            "memory_citations must be repopulated by rebuild_in_place"
        );
    }

    #[test]
    fn add_memory_edges_writes_and_survives_rebuild() {
        use super::{add_memory_edges, rebuild_in_place};

        let conn = make_conn();
        let run_id = RunId::new();
        let m1 = "mem-edge-a";
        let m2 = "mem-edge-b";

        let events = vec![
            make_event(
                run_id,
                "memory.accepted",
                json!({"memory_id": m1, "text": "alpha", "scope": "global_user", "kind": "fact"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({"memory_id": m2, "text": "beta", "scope": "global_user", "kind": "fact"}),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        // Self-loop is skipped; a real edge is written.
        let written = add_memory_edges(
            &conn,
            &[
                (m1.to_string(), m1.to_string(), "relates_to".to_string()),
                (m1.to_string(), m2.to_string(), "relates_to".to_string()),
            ],
        )
        .expect("add_memory_edges");
        assert_eq!(
            written, 1,
            "self-loop must be skipped, one real edge written"
        );

        let edge_count = |c: &Connection| -> i64 {
            c.query_row(
                "SELECT COUNT(*) FROM memory_edges WHERE src_id=?1 AND dst_id=?2 AND edge_type='relates_to'",
                params![m1, m2],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(edge_count(&conn), 1, "edge present after write");

        // Rebuild from the durable log: the edge is re-derived (replayed event).
        let total_edges_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_edges", [], |r| r.get(0))
            .unwrap();
        rebuild_in_place(&conn).expect("rebuild_in_place");
        let total_edges_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_edges", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            total_edges_before, total_edges_after,
            "rebuild must reproduce exactly the same edge set"
        );
        assert_eq!(edge_count(&conn), 1, "edge survives rebuild_in_place");
    }

    // ------------------------------------------------------------------
    // W1.2c: Event reconstruction fidelity — after rebuild_in_place the
    // projected memory's text/scope/kind match the original.
    // ------------------------------------------------------------------
    #[test]
    fn memory_proposed_redacts_event_and_projection_payloads() {
        let conn = make_conn();
        let run_id = RunId::new();
        let secret = "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv0123456789AbCdEf";
        let event = make_event(
            run_id,
            "memory.proposed",
            json!({
                "proposal_id": "prop-redact",
                "scope": "project",
                "kind": "fact",
                "text": format!("lesson uses {secret}"),
                "rationale": format!("model repeated {secret}"),
                "proposed_confidence": 0.5,
                "source_event_ids": [],
            }),
        );
        apply_events(&conn, &[event]).expect("apply_events");

        let payload: String = conn
            .query_row(
                "SELECT payload_json FROM events WHERE kind = 'memory.proposed'",
                [],
                |r| r.get(0),
            )
            .expect("event payload");
        assert!(!payload.contains(secret), "event leaked secret: {payload}");
        assert!(payload.contains("[REDACTED:anthropic_oauth]"));

        let row: (String, String) = conn
            .query_row(
                "SELECT text, rationale FROM memory_proposals WHERE proposal_id = 'prop-redact'",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .expect("proposal row");
        assert!(!row.0.contains(secret), "proposal text leaked: {}", row.0);
        assert!(
            !row.1.contains(secret),
            "proposal rationale leaked: {}",
            row.1
        );
    }

    #[test]
    fn memory_cited_redacts_event_and_projection_rationale() {
        let conn = make_conn();
        let run_id = RunId::new();
        let secret = "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv0123456789AbCdEf";
        let event = make_event(
            run_id,
            "memory.cited",
            json!({
                "memory_id": "mem-redact",
                "turn": 1,
                "rationale": format!("used because output showed {secret}"),
            }),
        );
        apply_events(&conn, &[event]).expect("apply_events");

        let payload: String = conn
            .query_row(
                "SELECT payload_json FROM events WHERE kind = 'memory.cited'",
                [],
                |r| r.get(0),
            )
            .expect("event payload");
        assert!(!payload.contains(secret), "event leaked secret: {payload}");
        assert!(payload.contains("[REDACTED:anthropic_oauth]"));

        let rationale: String = conn
            .query_row(
                "SELECT rationale FROM memory_citations WHERE memory_id = 'mem-redact'",
                [],
                |r| r.get(0),
            )
            .expect("citation rationale");
        assert!(
            !rationale.contains(secret),
            "citation rationale leaked: {rationale}"
        );
        assert!(rationale.contains("[REDACTED:anthropic_oauth]"));
    }

    // ------------------------------------------------------------------
    // F1A: memory.temporal event stamps valid_from/valid_to and survives
    // rebuild_in_place (rebuild-safe).
    // ------------------------------------------------------------------
    #[test]
    fn memory_temporal_stamps_validity_and_survives_rebuild() {
        use super::{mark_memory_temporal, rebuild_in_place};

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-temporal-test";

        let events = vec![make_event(
            run_id,
            "memory.accepted",
            json!({
                "memory_id": mem_id,
                "text": "old fact that expired",
                "scope": "project",
                "kind": "fact",
                "confidence": 0.9
            }),
        )];
        apply_events(&conn, &events).expect("apply_events");

        // Stamp valid_to to a past timestamp (expired).
        mark_memory_temporal(
            &conn,
            mem_id,
            Some("2020-01-01T00:00:00Z"),
            Some("2025-01-01T00:00:00Z"),
        )
        .expect("mark_memory_temporal");

        // Verify both columns are set.
        let (vf, vt): (Option<String>, Option<String>) = conn
            .query_row(
                "SELECT valid_from, valid_to FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .expect("query valid_from/valid_to");
        assert_eq!(
            vf.as_deref(),
            Some("2020-01-01T00:00:00Z"),
            "valid_from must be set"
        );
        assert_eq!(
            vt.as_deref(),
            Some("2025-01-01T00:00:00Z"),
            "valid_to must be set"
        );

        // Rebuild in-place: temporal state must be restored from the event log.
        rebuild_in_place(&conn).expect("rebuild_in_place");

        let (vf2, vt2): (Option<String>, Option<String>) = conn
            .query_row(
                "SELECT valid_from, valid_to FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .expect("query valid_from/valid_to after rebuild");
        assert_eq!(
            vf2.as_deref(),
            Some("2020-01-01T00:00:00Z"),
            "valid_from must survive rebuild_in_place"
        );
        assert_eq!(
            vt2.as_deref(),
            Some("2025-01-01T00:00:00Z"),
            "valid_to must survive rebuild_in_place"
        );
    }

    #[test]
    fn rebuild_in_place_payload_fidelity() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "mem-fidelity-test";
        let expected_text = "Rust edition 2024 requires explicit use of `use` for trait impls";
        let expected_scope = "project";
        let expected_kind = "guideline";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": expected_text,
                    "scope": expected_scope,
                    "kind": expected_kind,
                    "confidence": 0.9
                }),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        // Wipe derived tables to force a full rebuild.
        conn.execute_batch("DELETE FROM memories; DELETE FROM memories_fts; DELETE FROM runs;")
            .unwrap();

        rebuild_in_place(&conn).expect("rebuild_in_place");

        let row: (String, String, String) = conn
            .query_row(
                "SELECT text, scope, kind FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
            )
            .expect("memory must exist after rebuild_in_place");

        assert_eq!(row.0, expected_text, "text must round-trip through rebuild");
        assert_eq!(
            row.1, expected_scope,
            "scope must round-trip through rebuild"
        );
        assert_eq!(row.2, expected_kind, "kind must round-trip through rebuild");
    }

    // ------------------------------------------------------------------
    // Flagship 2 / Story 2.1: importance scoring at write time
    // ------------------------------------------------------------------

    /// Story 2.1: a memory.accepted event carrying `initial_usefulness` seeds
    /// the memory's usefulness_score (rebuild-safe), so a salient new memory
    /// outranks a freshly-added neutral one with score 0.
    #[test]
    fn initial_usefulness_seeds_score_and_survives_rebuild() {
        use super::rebuild_in_place;

        let conn = make_conn();
        let run_id = RunId::new();

        let events = vec![
            // Salient: failure_pattern seeded at 0.3.
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": "salient",
                    "text": "rm -rf node_modules then reinstall fixes the EBUSY lock",
                    "scope": "project",
                    "kind": "failure_pattern",
                    "confidence": 1.0,
                    "initial_usefulness": 0.3
                }),
            ),
            // Neutral: no initial_usefulness field → default 0.0 (back-compat).
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": "neutral",
                    "text": "the readme mentions a port number",
                    "scope": "project",
                    "kind": "fact",
                    "confidence": 1.0
                }),
            ),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let read = |id: &str| -> f64 {
            conn.query_row(
                "SELECT usefulness_score FROM memories WHERE memory_id = ?1",
                [id],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert!(
            (read("salient") - 0.3).abs() < 1e-6,
            "salient memory must be seeded to 0.3"
        );
        assert!(
            read("neutral").abs() < 1e-6,
            "memory without initial_usefulness must default to 0.0"
        );
        assert!(
            read("salient") > read("neutral"),
            "salient new memory must outrank a neutral one from day one"
        );

        // Rebuild-safe: the seed is in the event payload, so it survives replay.
        conn.execute_batch("DELETE FROM memories; DELETE FROM memories_fts;")
            .unwrap();
        rebuild_in_place(&conn).expect("rebuild_in_place");
        assert!(
            (read("salient") - 0.3).abs() < 1e-6,
            "initial_usefulness seed must survive rebuild"
        );
    }

    // ------------------------------------------------------------------
    // Flagship 2 / Story 2.4: confidence calibration from outcomes
    // ------------------------------------------------------------------

    /// Run a full cycle that injects + cites `mem_id`, then terminates with
    /// `terminal_kind` ("run.finished" or "run.failed"). Returns the memory's
    /// confidence afterward.
    fn cite_and_terminate_confidence(terminal_kind: &str) -> (Connection, f64) {
        let conn = make_conn();
        let run_id = RunId::new();
        let mem_id = "cal-mem";

        let events = vec![
            make_event(
                run_id,
                "run.started",
                json!({"project_id": "p", "task": "t"}),
            ),
            make_event(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": mem_id,
                    "text": "use lld linker on windows",
                    "scope": "project",
                    "kind": "convention",
                    "confidence": 0.7
                }),
            ),
            // Mark it as retrieved so usefulness/confidence attribution fires.
            make_event(
                run_id,
                "context.injected",
                json!({"stage": "loc", "memory_ids": [mem_id], "used_tokens": 100}),
            ),
            // Explicitly cited so it earns the strong (cited) confidence update.
            make_event(
                run_id,
                "memory.cited",
                json!({"memory_id": mem_id, "turn": 1}),
            ),
            make_event(run_id, terminal_kind, json!({"total_cost_usd": 0.0})),
        ];
        apply_events(&conn, &events).expect("apply_events");

        let conf: f64 = conn
            .query_row(
                "SELECT confidence FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| r.get(0),
            )
            .unwrap();
        (conn, conf)
    }

    /// Story 2.4 (headline): a cited memory in a successful run ends with
    /// HIGHER confidence than one in a failed run, and the calibrated value
    /// is reproduced exactly after rebuild_in_place.
    #[test]
    fn confidence_calibration_rewards_success_and_survives_rebuild() {
        use super::rebuild_in_place;

        let (success_conn, success_conf) = cite_and_terminate_confidence("run.finished");
        let (_fail_conn, fail_conf) = cite_and_terminate_confidence("run.failed");

        // Started at 0.7. Success nudges toward 1.0; failure toward 0.0.
        assert!(
            success_conf > 0.7,
            "successful citation must raise confidence above 0.7, got {success_conf}"
        );
        assert!(
            fail_conf < 0.7,
            "failed citation must lower confidence below 0.7, got {fail_conf}"
        );
        assert!(
            success_conf > fail_conf,
            "cited-in-success must beat cited-in-failure: {success_conf} vs {fail_conf}"
        );

        // Rebuild-safe: the calibration is derived purely from replayed events.
        let mem_id = "cal-mem";
        success_conn
            .execute_batch("DELETE FROM memories; DELETE FROM memories_fts;")
            .unwrap();
        rebuild_in_place(&success_conn).expect("rebuild_in_place");
        let post: f64 = success_conn
            .query_row(
                "SELECT confidence FROM memories WHERE memory_id = ?1",
                [mem_id],
                |r| r.get(0),
            )
            .unwrap();
        assert!(
            (post - success_conf).abs() < 1e-9,
            "calibrated confidence must reproduce after rebuild: {post} vs {success_conf}"
        );
    }
}