kimetsu-brain 2.8.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
/// Epic S3 — Personal brain sync (event-log replication).
///
/// Design insight: `events` is the durable source of truth and the projector
/// rebuilds everything from it.  Sync = EVENT-LOG REPLICATION, not SQLite file
/// copying.  We export durable events and import them through the projector with
/// per-event idempotency.  No server, no merge daemon.
///
/// # Allowed (durable memory-lifecycle) kinds — exported
/// - `memory.accepted`
/// - `memory.proposed`
/// - `memory.rejected`
/// - `memory.invalidated`
/// - `memory.restored`
/// - `memory.corrected`
/// - `memory.cited`
/// - `memory.superseded`
///
/// # Excluded kinds — never exported
/// - `work.episode`         — episodes are LOCAL-ONLY (Flagship 1)
/// - `context.served`       — local telemetry
/// - `retrieval.regret`     — local telemetry
/// - `digest_served`        — local telemetry
/// - `resume_served`        — local telemetry
/// - `context.injected`     — raw query bearing
/// - `run.started`          — local run metadata
/// - `run.finished`         — local run metadata
/// - `run.failed`           — local run metadata
/// - `run.aborted`          — local run metadata
///
/// Everything else that is not on the allowlist is also excluded by default.
///
/// # Cursor
/// The monotonic ordering column is `rowid` (the implicit SQLite integer
/// primary key alias).  A cursor is the last exported `rowid`.  The next
/// export picks up WHERE rowid > cursor.  Cursor 0 means "from the beginning".
///
/// # Idempotency
/// Import checks `event_id` (ULID) against the local `events` table.
/// `INSERT OR IGNORE` in `insert_event` already provides this, but we also
/// count skipped events so the caller can report applied/skipped.
///
/// # Directory protocol (3.2)
/// `<sync_dir>/<machine_id>/<cursor>.jsonl` — each batch file is atomically
/// written (temp + rename).  A per-source-cursor registry lives at
/// `.kimetsu/sync-cursors.json`.  `kimetsu brain sync` (no args):
///   1. Write this machine's new events under `<sync_dir>/<machine_id>/`.
///   2. For every OTHER subdirectory (= other machine), read batches after
///      the locally stored cursor for that machine, import them (idempotent),
///      and advance the cursor.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::{BufRead, BufReader, Write as IoWrite};
use std::path::{Path, PathBuf};

use kimetsu_core::KimetsuResult;
use kimetsu_core::event::Event;
use kimetsu_core::ids::{EventId, RunId};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use ulid::Ulid;

use crate::projector;
use crate::redact;

// ---------------------------------------------------------------------------
// Allowlist
// ---------------------------------------------------------------------------

/// Kinds that carry durable memory-lifecycle meaning and SHOULD be replicated.
const SYNC_ALLOWED_KINDS: &[&str] = &[
    "memory.accepted",
    "memory.proposed",
    "memory.rejected",
    "memory.invalidated",
    "memory.restored",
    "memory.corrected",
    "memory.cited",
    "memory.superseded",
];

/// Returns `true` when `kind` is allowed in a sync batch.
pub fn is_sync_allowed(kind: &str) -> bool {
    SYNC_ALLOWED_KINDS.contains(&kind)
}

// ---------------------------------------------------------------------------
// Event wire format
// ---------------------------------------------------------------------------

/// One line in a sync JSONL batch.  Carries the full event so the remote
/// projector can replay it.  `payload` is the redacted payload (same
/// redaction the projector applies at ingest).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncEvent {
    pub event_id: String,
    pub run_id: String,
    #[serde(with = "time::serde::rfc3339")]
    pub ts: OffsetDateTime,
    pub kind: String,
    pub schema_version: u32,
    pub payload: serde_json::Value,
    /// v2.6 #3: who/where wrote this event (`<machine_id>/<agent>`). Carried so a
    /// replicated/team brain can attribute each event. `#[serde(default)]` keeps
    /// pre-v8 sync batches (no `origin`) importable.
    #[serde(default)]
    pub origin: Option<String>,
    /// v2.6 #3 Slice B: the event's HLC (canonical string) for convergent
    /// total-order replay. `#[serde(default)]` keeps pre-v9 batches importable
    /// (the importer synthesizes a local HLC for those).
    #[serde(default)]
    pub hlc: Option<String>,
}

impl From<&Event> for SyncEvent {
    fn from(e: &Event) -> Self {
        // Apply the same payload redaction the projector does so sync batches
        // are never a second secret store (matches projector::redact_memory_event).
        let payload = redact_event_payload(e);
        Self {
            event_id: e.event_id.to_string(),
            run_id: e.run_id.to_string(),
            ts: e.ts,
            kind: e.kind.clone(),
            schema_version: e.schema_version,
            payload,
            origin: e.origin.clone(),
            hlc: e.hlc.clone(),
        }
    }
}

impl TryFrom<SyncEvent> for Event {
    type Error = Box<dyn std::error::Error + Send + Sync>;

    fn try_from(s: SyncEvent) -> Result<Self, Self::Error> {
        let event_id = EventId(
            Ulid::from_string(&s.event_id)
                .map_err(|e| format!("invalid event_id {:?}: {e}", s.event_id))?,
        );
        let run_id = RunId(
            Ulid::from_string(&s.run_id)
                .map_err(|e| format!("invalid run_id {:?}: {e}", s.run_id))?,
        );
        // Preserve the REMOTE HLC; advance the local clock past it so subsequent
        // LOCAL events sort after everything imported (causality). A pre-v9 peer
        // sends no HLC → synthesize a current local one so the event still sorts.
        let hlc = match s.hlc {
            Some(h) => {
                if let Some(parsed) = kimetsu_core::clock::Hlc::parse(&h) {
                    kimetsu_core::clock::observe(&parsed);
                }
                Some(h)
            }
            None => Some(kimetsu_core::clock::now().to_canonical()),
        };
        Ok(Event {
            event_id,
            run_id,
            ts: s.ts,
            parent_event_id: None,
            kind: s.kind,
            schema_version: s.schema_version,
            payload: s.payload,
            // Preserve the REMOTE origin — do NOT stamp the local process origin.
            origin: s.origin,
            hlc,
        })
    }
}

/// Apply export-time redaction to the event payload — same logic as
/// `projector::redact_memory_event` but returns an owned `Value`.
fn redact_event_payload(event: &Event) -> serde_json::Value {
    if !matches!(
        event.kind.as_str(),
        "memory.accepted" | "memory.proposed" | "memory.cited" | "memory.corrected"
    ) {
        return event.payload.clone();
    }
    redact_json_strings_owned(&event.payload)
}

fn redact_json_strings_owned(value: &serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::String(text) => {
            serde_json::Value::String(redact::redact_secrets(text).text)
        }
        serde_json::Value::Array(arr) => {
            serde_json::Value::Array(arr.iter().map(redact_json_strings_owned).collect())
        }
        serde_json::Value::Object(map) => {
            let out = map
                .iter()
                .map(|(k, v)| (k.clone(), redact_json_strings_owned(v)))
                .collect();
            serde_json::Value::Object(out)
        }
        other => other.clone(),
    }
}

// ---------------------------------------------------------------------------
// 3.1 — Export
// ---------------------------------------------------------------------------

/// Summary returned by [`export_events`].
#[derive(Debug, Clone, Default)]
pub struct ExportSummary {
    /// Number of events written to the batch.
    pub exported: usize,
    /// The highest rowid included in this batch (= next cursor).
    pub next_cursor: i64,
}

/// Export durable events from `conn` after `since_rowid` (exclusive).
///
/// Only events whose `kind` is on the sync allowlist are included.
/// Redaction is applied inline (no workspace paths / secrets leak).
///
/// When `out_path` is `None`, returns the JSONL as a `String`.
/// When `out_path` is `Some(path)`, writes atomically via temp+rename.
pub fn export_events(
    conn: &Connection,
    since_rowid: i64,
    out_path: Option<&Path>,
    dry_run: bool,
) -> KimetsuResult<(ExportSummary, Option<String>)> {
    let rows = read_durable_events_after(conn, since_rowid)?;

    let mut lines = Vec::new();
    let mut next_cursor = since_rowid;
    for (rowid, event) in &rows {
        if !is_sync_allowed(&event.kind) {
            continue;
        }
        let se = SyncEvent::from(event);
        let line = serde_json::to_string(&se)
            .map_err(|e| format!("sync export: serialize event {}: {e}", event.event_id))?;
        lines.push(line);
        if *rowid > next_cursor {
            next_cursor = *rowid;
        }
    }

    let summary = ExportSummary {
        exported: lines.len(),
        next_cursor,
    };

    if dry_run {
        return Ok((summary, None));
    }

    let jsonl = lines.join("\n");
    if let Some(path) = out_path {
        atomic_write(path, jsonl.as_bytes())?;
        Ok((summary, None))
    } else {
        Ok((summary, Some(jsonl)))
    }
}

/// Read all (rowid, Event) pairs from the `events` table with rowid > `after`.
fn read_durable_events_after(conn: &Connection, after: i64) -> KimetsuResult<Vec<(i64, Event)>> {
    let mut stmt = conn.prepare(
        "SELECT rowid, event_id, run_id, ts, kind, schema_version, payload_json, origin, hlc
         FROM events
         WHERE rowid > ?1
         ORDER BY rowid",
    )?;
    let rows = stmt.query_map(rusqlite::params![after], |row| {
        let rowid: i64 = row.get(0)?;
        let event_id_str: String = row.get(1)?;
        let run_id_str: String = row.get(2)?;
        let ts_str: String = row.get(3)?;
        let kind: String = row.get(4)?;
        let schema_version: u32 = row.get(5)?;
        let payload_json: String = row.get(6)?;
        let origin: Option<String> = row.get(7)?;
        let hlc: Option<String> = row.get(8)?;
        Ok((
            rowid,
            event_id_str,
            run_id_str,
            ts_str,
            kind,
            schema_version,
            payload_json,
            origin,
            hlc,
        ))
    })?;

    let mut out = Vec::new();
    for row in rows {
        let (
            rowid,
            event_id_str,
            run_id_str,
            ts_str,
            kind,
            schema_version,
            payload_json,
            origin,
            hlc,
        ) = row?;
        let event_id = EventId(
            Ulid::from_string(&event_id_str)
                .map_err(|e| format!("invalid event_id {event_id_str:?}: {e}"))?,
        );
        let run_id = RunId(
            Ulid::from_string(&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)?;
        out.push((
            rowid,
            Event {
                event_id,
                run_id,
                ts,
                parent_event_id: None,
                kind,
                schema_version,
                payload,
                origin,
                hlc,
            },
        ));
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// 3.1 — Import
// ---------------------------------------------------------------------------

/// Summary returned by [`import_events`].
#[derive(Debug, Clone, Default)]
pub struct ImportSummary {
    /// Events actually applied (projected into derived tables).
    pub applied: usize,
    /// Events skipped because their `event_id` already existed locally.
    pub skipped: usize,
}

/// Import a JSONL batch (one `SyncEvent` per line) into `conn`.
///
/// Per-event idempotency: if the `event_id` already exists in the local
/// `events` table, the event is skipped (no double-apply).
/// `INSERT OR IGNORE` in `projector::insert_event` provides the underlying
/// dedup; we additionally count skips for reporting.
///
/// When `dry_run` is true, parse and count but do NOT write anything.
/// Otherwise, stage the entire batch and replay the merged durable log under
/// one writer lock. Historical edits must not project against today's state.
pub fn import_events(
    conn: &Connection,
    jsonl: &str,
    dry_run: bool,
) -> KimetsuResult<ImportSummary> {
    let mut excluded = 0;
    let mut events = Vec::new();
    for (line_no, line) in jsonl.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let se: SyncEvent = serde_json::from_str(line)
            .map_err(|e| format!("sync import: malformed JSON on line {}: {e}", line_no + 1))?;

        // Validate it's an allowed kind — defence-in-depth (the exporter
        // already filters, but a hand-crafted batch might not).
        if !is_sync_allowed(&se.kind) {
            // Skip silently — telemetry/local kinds should never appear.
            excluded += 1;
            continue;
        }

        let event: Event = Event::try_from(se)
            .map_err(|e| format!("sync import: invalid event on line {}: {e}", line_no + 1))?;

        events.push(event);
    }

    let mut summary = ImportSummary::default();
    let mut import = |c: &Connection| -> KimetsuResult<()> {
        summary = ImportSummary {
            applied: 0,
            skipped: excluded,
        };
        let mut seen = BTreeSet::new();
        for event in &events {
            // Both the count and insertion run under the writer lock. Include
            // in-batch duplicates in dry-run counts without writing them.
            let exists: bool = !seen.insert(event.event_id.to_string())
                || c.query_row(
                    "SELECT 1 FROM events WHERE event_id = ?1",
                    rusqlite::params![event.event_id.to_string()],
                    |_| Ok(true),
                )
                .optional()?
                .unwrap_or(false);

            if exists {
                summary.skipped += 1;
                continue;
            }
            if !dry_run {
                let redacted = Event {
                    payload: redact_event_payload(event),
                    ..event.clone()
                };
                projector::insert_event(c, &redacted)?;
            }
            summary.applied += 1;
        }
        if !dry_run && summary.applied > 0 {
            projector::replay_locked(c)?;
        }
        Ok(())
    };
    if dry_run {
        import(conn)?;
    } else {
        projector::with_write_txn(conn, import)?;
    }
    Ok(summary)
}

/// Slice B: count unresolved concurrent-supersede conflicts surfaced by team
/// sync (a member superseded to two different survivors). Deterministic across
/// brains; shown by `kimetsu brain sync --status`.
pub fn sync_conflict_count(conn: &Connection) -> KimetsuResult<i64> {
    let n: i64 = conn.query_row("SELECT COUNT(*) FROM sync_conflicts", [], |r| r.get(0))?;
    Ok(n)
}

/// Read a JSONL batch file and import it.
pub fn import_events_from_file(
    conn: &Connection,
    path: &Path,
    dry_run: bool,
) -> KimetsuResult<ImportSummary> {
    import_events(conn, &read_batch_file(path)?, dry_run)
}

fn read_batch_file(path: &Path) -> KimetsuResult<String> {
    let file = fs::File::open(path)
        .map_err(|e| format!("sync import: cannot open {:?}: {e}", path.display()))?;
    let reader = BufReader::new(file);
    let mut buf = String::new();
    for line in reader.lines() {
        let l = line.map_err(|e| format!("sync import: read error {:?}: {e}", path.display()))?;
        buf.push_str(&l);
        buf.push('\n');
    }
    Ok(buf)
}

// ---------------------------------------------------------------------------
// 3.2 — Sync cursor registry
// ---------------------------------------------------------------------------

/// Per-source cursor state persisted at `.kimetsu/sync-cursors.json`.
///
/// Keys are machine_id strings; values are the last rowid imported from that
/// machine.  Our OWN machine_id is in here too (last exported rowid).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SyncCursors {
    /// map machine_id → last imported rowid (0 = never imported).
    #[serde(default)]
    pub sources: BTreeMap<String, i64>,
}

impl SyncCursors {
    pub fn load(path: &Path) -> KimetsuResult<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let text = fs::read_to_string(path)
            .map_err(|e| format!("sync-cursors: cannot read {:?}: {e}", path.display()))?;
        serde_json::from_str(&text)
            .map_err(|e| format!("sync-cursors: malformed JSON at {:?}: {e}", path.display()))
            .map_err(Into::into)
    }

    pub fn save(&self, path: &Path) -> KimetsuResult<()> {
        let text = serde_json::to_string_pretty(self)
            .map_err(|e| format!("sync-cursors: serialize error: {e}"))?;
        atomic_write(path, text.as_bytes())
    }

    pub fn cursor_for(&self, machine_id: &str) -> i64 {
        *self.sources.get(machine_id).unwrap_or(&0)
    }

    pub fn set_cursor(&mut self, machine_id: &str, rowid: i64) {
        self.sources.insert(machine_id.to_string(), rowid);
    }
}

// ---------------------------------------------------------------------------
// 3.2 — Directory protocol
// ---------------------------------------------------------------------------

/// The max rowid among all rows in the local `events` table with an allowed
/// kind.  This is what we compare against the stored export cursor to decide
/// whether there's anything new to push.
pub fn max_local_sync_rowid(conn: &Connection) -> KimetsuResult<i64> {
    let placeholders: String = SYNC_ALLOWED_KINDS
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 1))
        .collect::<Vec<_>>()
        .join(", ");
    let sql = format!("SELECT COALESCE(MAX(rowid), 0) FROM events WHERE kind IN ({placeholders})");
    let mut stmt = conn.prepare(&sql)?;
    let params: Vec<Box<dyn rusqlite::ToSql>> = SYNC_ALLOWED_KINDS
        .iter()
        .map(|k| -> Box<dyn rusqlite::ToSql> { Box::new(k.to_string()) })
        .collect();
    let refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    let max: i64 = stmt.query_row(refs.as_slice(), |r| r.get(0))?;
    Ok(max)
}

/// Write this machine's new events as a JSONL batch under
/// `<sync_dir>/<machine_id>/<cursor>.jsonl` (atomic write).
///
/// Returns the number of events written and the new export cursor.
pub fn push_machine_batch(
    conn: &Connection,
    sync_dir: &Path,
    machine_id: &str,
    since_rowid: i64,
    dry_run: bool,
) -> KimetsuResult<ExportSummary> {
    let (dry_summary, _content) = export_events(conn, since_rowid, None, true)?;
    if dry_summary.exported == 0 || dry_run {
        return Ok(dry_summary);
    }

    // Re-run for real (not dry_run) to get the content.
    let (summary, content) = export_events(conn, since_rowid, None, false)?;
    let jsonl = content.unwrap_or_default();

    let machine_dir = sync_dir.join(machine_id);
    fs::create_dir_all(&machine_dir).map_err(|e| {
        format!(
            "sync push: cannot create dir {:?}: {e}",
            machine_dir.display()
        )
    })?;

    let batch_name = format!("{}.jsonl", summary.next_cursor);
    let batch_path = machine_dir.join(&batch_name);
    atomic_write(&batch_path, jsonl.as_bytes())?;

    Ok(summary)
}

/// Pull and import all batches from `<sync_dir>/<source_machine_id>/` that
/// come AFTER `since_cursor`.  Updates the cursor in the registry.
///
/// Batches are files named `<rowid>.jsonl`; we sort numerically and process
/// only those whose stem > since_cursor.
pub fn pull_machine_batches(
    conn: &Connection,
    sync_dir: &Path,
    source_machine_id: &str,
    since_cursor: i64,
    dry_run: bool,
) -> KimetsuResult<(ImportSummary, i64)> {
    let (jsonl, cursor) = read_machine_batches(sync_dir, source_machine_id, since_cursor)?;
    Ok((import_events(conn, &jsonl, dry_run)?, cursor))
}

/// Read every pending batch before importing: prerequisites can be in a later
/// batch or on another peer, so directory sync merges these before replay.
fn read_machine_batches(
    sync_dir: &Path,
    source_machine_id: &str,
    since_cursor: i64,
) -> KimetsuResult<(String, i64)> {
    let machine_dir = sync_dir.join(source_machine_id);
    if !machine_dir.exists() {
        return Ok((String::new(), since_cursor));
    }

    // Collect batch files, parse their numeric stem (= the export cursor at
    // the time they were written, i.e. the highest rowid in that batch on
    // the source machine).
    let mut batches: Vec<(i64, PathBuf)> = Vec::new();
    let entries = fs::read_dir(&machine_dir).map_err(|e| {
        format!(
            "sync pull: cannot read dir {:?}: {e}",
            machine_dir.display()
        )
    })?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("sync pull: dir entry error: {e}"))?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
            if let Ok(cursor_val) = stem.parse::<i64>() {
                if cursor_val > since_cursor {
                    batches.push((cursor_val, path));
                }
            }
        }
    }
    batches.sort_by_key(|(c, _)| *c);

    let mut jsonl = String::new();
    let mut new_cursor = since_cursor;
    for (cursor_val, batch_path) in &batches {
        jsonl.push_str(&read_batch_file(batch_path)?);
        if *cursor_val > new_cursor {
            new_cursor = *cursor_val;
        }
    }
    Ok((jsonl, new_cursor))
}

/// Full sync cycle:
/// 1. Push this machine's new events.
/// 2. Pull every other machine's new batches.
/// 3. Persist updated cursors.
///
/// Returns a summary of what happened.
pub fn sync_dir(
    conn: &Connection,
    sync_dir: &Path,
    machine_id: &str,
    cursors_path: &Path,
    dry_run: bool,
) -> KimetsuResult<SyncReport> {
    let mut cursors = SyncCursors::load(cursors_path)?;
    let export_since = cursors.cursor_for(machine_id);

    // --- push ---
    let push_summary = push_machine_batch(conn, sync_dir, machine_id, export_since, dry_run)?;
    if !dry_run && push_summary.exported > 0 {
        cursors.set_cursor(machine_id, push_summary.next_cursor);
        cursors.save(cursors_path)?;
    }

    // --- pull ---
    let mut total_applied = 0usize;
    let mut total_skipped = 0usize;
    let mut machines_pulled: Vec<String> = Vec::new();

    // List subdirs (each = one machine's batch directory).
    if sync_dir.exists() {
        let entries = fs::read_dir(sync_dir)
            .map_err(|e| format!("sync: cannot read sync_dir {:?}: {e}", sync_dir.display()))?;
        let mut other_machines: Vec<String> = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|e| format!("sync: dir entry error: {e}"))?;
            if entry.path().is_dir() {
                if let Some(name) = entry.file_name().to_str() {
                    if name != machine_id {
                        other_machines.push(name.to_string());
                    }
                }
            }
        }
        other_machines.sort(); // deterministic order

        let mut incoming = String::new();
        for other_id in &other_machines {
            let since = cursors.cursor_for(other_id);
            let (jsonl, new_cursor) = read_machine_batches(sync_dir, other_id, since)?;
            if !dry_run && new_cursor > since {
                cursors.set_cursor(other_id, new_cursor);
                machines_pulled.push(other_id.clone());
            } else if dry_run && !jsonl.trim().is_empty() {
                machines_pulled.push(other_id.clone());
            }
            incoming.push_str(&jsonl);
        }

        // Commit all peer events and their causal projection together before
        // advancing pull cursors. A failed import leaves both unchanged.
        let pull_summary = import_events(conn, &incoming, dry_run)?;
        total_applied = pull_summary.applied;
        total_skipped = pull_summary.skipped;

        if !dry_run && !machines_pulled.is_empty() {
            cursors.save(cursors_path)?;
        }
    }

    Ok(SyncReport {
        pushed: push_summary.exported,
        pulled_applied: total_applied,
        pulled_skipped: total_skipped,
        machines_pulled,
        dry_run,
    })
}

/// Summary of a full sync cycle.
#[derive(Debug, Clone, Default)]
pub struct SyncReport {
    pub pushed: usize,
    pub pulled_applied: usize,
    pub pulled_skipped: usize,
    pub machines_pulled: Vec<String>,
    pub dry_run: bool,
}

// ---------------------------------------------------------------------------
// 3.3 — Doctor / status
// ---------------------------------------------------------------------------

/// Status of the sync configuration and state.
#[derive(Debug, Clone)]
pub struct SyncStatus {
    pub sync_dir: Option<PathBuf>,
    pub machine_id: String,
    /// Per-source: (machine_id, cursor, pending_count)
    pub sources: Vec<(String, i64, usize)>,
    pub local_pending: usize,
}

/// Compute the sync status without performing any writes.
pub fn sync_status(
    conn: &Connection,
    sync_dir_opt: Option<&Path>,
    machine_id: &str,
    cursors_path: &Path,
) -> KimetsuResult<SyncStatus> {
    let cursors = SyncCursors::load(cursors_path)?;
    let export_since = cursors.cursor_for(machine_id);

    // Count this machine's unpushed events.
    let (push_dry, _) = export_events(conn, export_since, None, true)?;
    let local_pending = push_dry.exported;

    let mut sources: Vec<(String, i64, usize)> = Vec::new();
    if let Some(sd) = sync_dir_opt {
        if sd.exists() {
            let entries = fs::read_dir(sd)
                .map_err(|e| format!("sync status: cannot read {:?}: {e}", sd.display()))?;
            let mut other_machines: Vec<String> = Vec::new();
            for entry in entries {
                let entry = entry.map_err(|e| format!("sync status: dir entry error: {e}"))?;
                if entry.path().is_dir() {
                    if let Some(name) = entry.file_name().to_str() {
                        if name != machine_id {
                            other_machines.push(name.to_string());
                        }
                    }
                }
            }
            other_machines.sort();
            for other_id in &other_machines {
                let since = cursors.cursor_for(other_id);
                let (pull_summary, _) = pull_machine_batches(conn, sd, other_id, since, true)?;
                sources.push((
                    other_id.clone(),
                    since,
                    pull_summary.applied + pull_summary.skipped,
                ));
            }
        }
    }

    Ok(SyncStatus {
        sync_dir: sync_dir_opt.map(|p| p.to_path_buf()),
        machine_id: machine_id.to_string(),
        sources,
        local_pending,
    })
}

// ---------------------------------------------------------------------------
// Atomic write helper
// ---------------------------------------------------------------------------

/// Write `data` to `path` atomically via a sibling temp file + rename.
pub fn atomic_write(path: &Path, data: &[u8]) -> KimetsuResult<()> {
    let parent = path.parent().unwrap_or(Path::new("."));
    fs::create_dir_all(parent).map_err(|e| {
        format!(
            "atomic_write: cannot create dir {:?}: {e}",
            parent.display()
        )
    })?;
    let tmp_path = path.with_extension("tmp");
    {
        let mut file = fs::File::create(&tmp_path).map_err(|e| {
            format!(
                "atomic_write: cannot create tmp {:?}: {e}",
                tmp_path.display()
            )
        })?;
        file.write_all(data)
            .map_err(|e| format!("atomic_write: write error {:?}: {e}", tmp_path.display()))?;
        file.flush()
            .map_err(|e| format!("atomic_write: flush error {:?}: {e}", tmp_path.display()))?;
    }
    fs::rename(&tmp_path, path).map_err(|e| {
        format!(
            "atomic_write: rename {:?} -> {:?}: {e}",
            tmp_path.display(),
            path.display()
        )
    })?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Extension trait for Option with rusqlite
// ---------------------------------------------------------------------------

trait OptionalExt<T> {
    fn optional(self) -> KimetsuResult<Option<T>>;
}

impl<T> OptionalExt<T> for rusqlite::Result<T> {
    fn optional(self) -> KimetsuResult<Option<T>> {
        match self {
            Ok(v) => Ok(Some(v)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use kimetsu_core::ids::RunId;
    use rusqlite::Connection;
    use serde_json::json;

    use super::*;
    use crate::projector::apply_events;
    use crate::schema;

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

    fn wire(events: &[Event]) -> String {
        events
            .iter()
            .map(|event| serde_json::to_string(&SyncEvent::from(event)).unwrap())
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn sync_replays_historical_correction_before_local_retirement() {
        for reason in ["retired", "forgotten/archived"] {
            let a = make_conn();
            let b = make_conn();
            let run = RunId::new();
            let accepted = Event::new(
                run,
                "memory.accepted",
                json!({"memory_id":"m", "text":"old claim", "scope":"project", "kind":"fact"}),
            );
            apply_events(&a, std::slice::from_ref(&accepted)).unwrap();
            apply_events(&b, &[accepted]).unwrap();
            let exposure = Event::new(run, "context.injected", json!({"memory_ids":["m"]}));
            apply_events(&b, std::slice::from_ref(&exposure)).unwrap();
            let correction = Event::new(
                run,
                "memory.corrected",
                json!({"memory_id":"m", "text":"corrected claim"}),
            );
            apply_events(&a, std::slice::from_ref(&correction)).unwrap();
            apply_events(
                &b,
                &[Event::new(
                    run,
                    "memory.invalidated",
                    json!({"memory_id":"m", "reason":reason}),
                )],
            )
            .unwrap();
            let tmp = tempfile::tempdir().unwrap();
            let sd = tmp.path().join("sync");
            push_machine_batch(&a, &sd, "a", 0, false).unwrap();
            let cp = tmp.path().join("b-cursors.json");
            let report = sync_dir(&b, &sd, "b", &cp, false)
                .expect("historical correction must replay before retirement");
            assert_eq!((report.pulled_applied, report.pulled_skipped), (1, 1));
            for _ in 0..2 {
                let state: (String, String) = b
                    .query_row(
                        "SELECT text, invalidated_reason FROM memories WHERE memory_id='m'",
                        [],
                        |r| Ok((r.get(0)?, r.get(1)?)),
                    )
                    .unwrap();
                assert_eq!(state, ("corrected claim".into(), reason.into()));
                let binding: String = b.query_row("SELECT json_extract(payload_json,'$.memory_revisions.m') FROM events WHERE event_id=?1", [exposure.event_id.to_string()], |r| r.get(0)).unwrap();
                assert_eq!(binding, "baseline:m");
                assert_eq!(
                    b.query_row(
                        "SELECT count(*) FROM memories_fts WHERE memory_id='m'",
                        [],
                        |r| r.get::<_, i64>(0)
                    )
                    .unwrap(),
                    0
                );
                projector::rebuild_in_place(&b).unwrap();
            }
            assert_eq!(SyncCursors::load(&cp).unwrap().cursor_for("a"), 2);
            assert_eq!(
                sync_dir(&b, &sd, "b", &cp, false).unwrap().pulled_applied,
                0
            );
        }
    }

    #[test]
    fn sync_archive_restore_round_trip() {
        let a = make_conn();
        let b = make_conn();
        let run = RunId::new();
        apply_events(&a, &[Event::new(run, "memory.accepted", json!({"memory_id":"m", "text":"restorable claim", "scope":"project", "kind":"fact"}))]).unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let sd = tmp.path().join("sync");
        let ca = tmp.path().join("a.json");
        let cb = tmp.path().join("b.json");
        sync_dir(&a, &sd, "a", &ca, false).unwrap();
        sync_dir(&b, &sd, "b", &cb, false).unwrap();
        for (kind, archived) in [("memory.invalidated", true), ("memory.restored", false)] {
            apply_events(
                &a,
                &[Event::new(
                    run,
                    kind,
                    json!({"memory_id":"m", "reason":"forgotten/archived"}),
                )],
            )
            .unwrap();
            assert!(sync_dir(&a, &sd, "a", &ca, false).unwrap().pushed > 0);
            assert_eq!(
                sync_dir(&b, &sd, "b", &cb, false).unwrap().pulled_applied,
                1
            );
            let actual: bool = b
                .query_row(
                    "SELECT invalidated_at IS NOT NULL FROM memories WHERE memory_id='m'",
                    [],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(actual, archived);
            assert_eq!(
                b.query_row(
                    "SELECT count(*) FROM memories_fts WHERE memory_id='m'",
                    [],
                    |r| r.get::<_, i64>(0)
                )
                .unwrap(),
                if archived { 0 } else { 1 }
            );
        }
        assert_eq!(
            sync_dir(&b, &sd, "b", &cb, false).unwrap().pulled_applied,
            0
        );
    }

    #[test]
    fn sync_import_failure_rolls_back_entire_batch() {
        for malformed_json in [false, true] {
            let conn = make_conn();
            let run = RunId::new();
            let accepted = Event::new(
                run,
                "memory.accepted",
                json!({"memory_id":"m", "text":"kept claim", "scope":"project", "kind":"fact"}),
            );
            let bad = Event::new(
                run,
                "memory.corrected",
                json!({"memory_id":"missing", "text":"bad claim"}),
            );
            let input = if malformed_json {
                format!("{}\n{{bad", wire(&[accepted]))
            } else {
                wire(&[accepted, bad])
            };
            assert!(import_events(&conn, &input, false).is_err());
            for table in ["events", "memories", "memory_revisions", "memories_fts"] {
                assert_eq!(
                    conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r
                        .get::<_, i64>(0))
                        .unwrap(),
                    0,
                    "{table} must roll back"
                );
            }
        }
    }

    #[test]
    fn sync_directory_merges_peer_dependencies_before_replay() {
        let conn = make_conn();
        let run = RunId::new();
        let accepted = Event::new(
            run,
            "memory.accepted",
            json!({"memory_id":"m", "text":"old", "scope":"project", "kind":"fact"}),
        );
        let correction = Event::new(
            run,
            "memory.corrected",
            json!({"memory_id":"m", "text":"new"}),
        );
        let tmp = tempfile::tempdir().unwrap();
        let sd = tmp.path().join("sync");
        atomic_write(&sd.join("a/2.jsonl"), wire(&[correction]).as_bytes()).unwrap();
        atomic_write(&sd.join("z/1.jsonl"), wire(&[accepted]).as_bytes()).unwrap();
        let cp = tmp.path().join("cursors.json");
        let report = sync_dir(&conn, &sd, "local", &cp, false)
            .expect("replay must include all peers before resolving dependencies");
        assert_eq!(report.pulled_applied, 2);
        assert_eq!(
            conn.query_row("SELECT text FROM memories WHERE memory_id='m'", [], |r| {
                r.get::<_, String>(0)
            })
            .unwrap(),
            "new"
        );
        let cursors = SyncCursors::load(&cp).unwrap();
        assert_eq!((cursors.cursor_for("a"), cursors.cursor_for("z")), (2, 1));
    }

    #[test]
    fn sync_directory_failure_preserves_projection_and_pull_cursors() {
        let conn = make_conn();
        let run = RunId::new();
        let accepted = Event::new(
            run,
            "memory.accepted",
            json!({"memory_id":"m", "text":"old", "scope":"project", "kind":"fact"}),
        );
        apply_events(&conn, &[accepted]).unwrap();
        let correction = Event::new(
            run,
            "memory.corrected",
            json!({"memory_id":"m", "text":"new"}),
        );
        let bad = Event::new(
            run,
            "memory.corrected",
            json!({"memory_id":"missing", "text":"bad"}),
        );
        let tmp = tempfile::tempdir().unwrap();
        let sd = tmp.path().join("sync");
        atomic_write(&sd.join("a/2.jsonl"), wire(&[correction]).as_bytes()).unwrap();
        atomic_write(&sd.join("z/3.jsonl"), wire(&[bad]).as_bytes()).unwrap();
        let cp = tmp.path().join("cursors.json");
        assert!(sync_dir(&conn, &sd, "local", &cp, false).is_err());
        assert_eq!(
            conn.query_row("SELECT text FROM memories WHERE memory_id='m'", [], |r| {
                r.get::<_, String>(0)
            })
            .unwrap(),
            "old"
        );
        assert_eq!(
            conn.query_row("SELECT count(*) FROM events", [], |r| r.get::<_, i64>(0))
                .unwrap(),
            1
        );
        let cursors = SyncCursors::load(&cp).unwrap();
        assert_eq!((cursors.cursor_for("a"), cursors.cursor_for("z")), (0, 0));
    }

    #[test]
    fn sync_import_refuses_to_erase_unlogged_memory() {
        let conn = make_conn();
        conn.execute("INSERT INTO memories(memory_id,scope,kind,text,normalized_text,confidence,provenance_snapshot_json,created_at) VALUES ('legacy','global_user','fact','original','original',0.7,'{}','2020-01-01T00:00:00Z')", []).unwrap();
        let accepted = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({"memory_id":"m", "text":"new", "scope":"project", "kind":"fact"}),
        );
        let error = import_events(&conn, &wire(&[accepted]), false).unwrap_err();
        assert!(error.to_string().contains("absent from replay"));
        assert_eq!(
            conn.query_row("SELECT count(*) FROM events", [], |r| r.get::<_, i64>(0))
                .unwrap(),
            0
        );
        assert_eq!(
            conn.query_row(
                "SELECT text FROM memories WHERE memory_id='legacy'",
                [],
                |r| r.get::<_, String>(0)
            )
            .unwrap(),
            "original"
        );
    }

    #[test]
    fn sync_import_counts_duplicate_lines_in_dry_run_and_commit() {
        let conn = make_conn();
        let accepted = Event::new(
            RunId::new(),
            "memory.accepted",
            json!({"memory_id":"m", "text":"new", "scope":"project", "kind":"fact"}),
        );
        let input = wire(&[accepted.clone(), accepted]);
        for dry in [true, false] {
            let summary = import_events(&conn, &input, dry).unwrap();
            assert_eq!((summary.applied, summary.skipped), (1, 1));
        }
        let summary = import_events(&conn, &input, false).unwrap();
        assert_eq!((summary.applied, summary.skipped), (0, 2));
    }

    fn seed_events(conn: &Connection) -> (RunId, String, String) {
        let run_id = RunId::new();
        let mem_id_a = format!("mem-{}", ulid::Ulid::new());
        let mem_id_b = format!("mem-{}", ulid::Ulid::new());
        apply_events(
            conn,
            &[
                kimetsu_core::event::Event::new(
                    run_id,
                    "run.started",
                    json!({"project_id":"p","task":"t"}),
                ),
                kimetsu_core::event::Event::new(
                    run_id,
                    "memory.accepted",
                    json!({"memory_id": mem_id_a, "text": "always use cargo --locked", "scope": "project", "kind": "fact"}),
                ),
                kimetsu_core::event::Event::new(
                    run_id,
                    "memory.accepted",
                    json!({"memory_id": mem_id_b, "text": "prefer ripgrep over grep", "scope": "global_user", "kind": "preference"}),
                ),
                kimetsu_core::event::Event::new(
                    run_id,
                    "work.episode",
                    json!({"task":"local task","project_id":"p"}),
                ),
                kimetsu_core::event::Event::new(
                    run_id,
                    "context.served",
                    json!({"query":"test","results":[]}),
                ),
                kimetsu_core::event::Event::new(
                    run_id,
                    "run.finished",
                    json!({"total_cost_usd":0.01}),
                ),
            ],
        )
        .expect("seed events");
        (run_id, mem_id_a, mem_id_b)
    }

    // Slice B headline: two brains that exchange the same events CONVERGE to an
    // identical projection regardless of the order edits were made/imported —
    // including the one genuinely-divergent op (memory.superseded), which an HLC
    // replay resolves last-writer-wins, plus a surfaced conflict.
    #[test]
    fn two_brains_converge_after_exchange() {
        use kimetsu_core::event::Event;
        let a = make_conn();
        let b = make_conn();
        let run = RunId(ulid::Ulid::nil()); // legacy standalone reliance metadata
        let (m1, s1, s2) = ("mem-m1", "mem-s1", "mem-s2");

        // Shared base: identical accepted events on both brains.
        let base = vec![
            Event::new(
                run,
                "memory.accepted",
                json!({"memory_id": m1, "text":"alpha rule", "scope":"project","kind":"fact"}),
            ),
            Event::new(
                run,
                "memory.accepted",
                json!({"memory_id": s1, "text":"survivor one", "scope":"project","kind":"fact"}),
            ),
            Event::new(
                run,
                "memory.accepted",
                json!({"memory_id": s2, "text":"survivor two", "scope":"project","kind":"fact"}),
            ),
        ];
        apply_events(&a, &base).unwrap();
        apply_events(&b, &base).unwrap();

        // Divergent edits, created in sequence so B's supersede has a LATER HLC.
        let a_mut = vec![
            Event::new(run, "memory.cited", json!({"memory_id": m1, "turn": 0})),
            Event::new(
                run,
                "memory.superseded",
                json!({"memory_id": m1, "survivor_id": s1}),
            ),
        ];
        apply_events(&a, &a_mut).unwrap();
        let b_mut = vec![
            Event::new(run, "memory.cited", json!({"memory_id": m1, "turn": 0})),
            Event::new(
                run,
                "memory.superseded",
                json!({"memory_id": m1, "survivor_id": s2}),
            ),
        ];
        apply_events(&b, &b_mut).unwrap();

        // Cross-exchange the full logs, then converge (rebuild in HLC order).
        let ax = export_events(&a, 0, None, false).unwrap().1.unwrap();
        let bx = export_events(&b, 0, None, false).unwrap().1.unwrap();
        import_events(&b, &ax, false).unwrap();
        import_events(&a, &bx, false).unwrap();
        crate::projector::rebuild_in_place(&a).unwrap();
        crate::projector::rebuild_in_place(&b).unwrap();

        // superseded_by converges to the LATER-HLC survivor (s2) on BOTH brains.
        let superseded = |c: &Connection| -> Option<String> {
            c.query_row(
                "SELECT superseded_by FROM memories WHERE memory_id = ?1",
                [m1],
                |r| r.get::<_, Option<String>>(0),
            )
            .unwrap()
        };
        assert_eq!(
            superseded(&a),
            superseded(&b),
            "superseded_by must converge"
        );
        assert_eq!(
            superseded(&a),
            Some(s2.to_string()),
            "later-HLC supersede wins deterministically"
        );

        // Reliance metadata converges without manufacturing outcome credit.
        let use_count = |c: &Connection| -> i64 {
            c.query_row(
                "SELECT use_count FROM memories WHERE memory_id = ?1",
                [m1],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(use_count(&a), use_count(&b), "use_count must converge");
        assert_eq!(use_count(&a), 0, "citations alone are not outcome credit");
        for brain in [&a, &b] {
            assert_eq!(
                brain
                    .query_row("SELECT count(*) FROM memory_citations", [], |r| r
                        .get::<_, i64>(0))
                    .unwrap(),
                2
            );
        }

        // Even order-sensitive confidence converges (same HLC replay order).
        let confidence = |c: &Connection| -> f64 {
            c.query_row(
                "SELECT confidence FROM memories WHERE memory_id = ?1",
                [m1],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert!(
            (confidence(&a) - confidence(&b)).abs() < 1e-9,
            "confidence must converge: {} vs {}",
            confidence(&a),
            confidence(&b)
        );

        // The genuine concurrent supersede is surfaced (once) on both brains.
        assert_eq!(sync_conflict_count(&a).unwrap(), 1);
        assert_eq!(sync_conflict_count(&b).unwrap(), 1);
    }

    // S3-1: Export excludes telemetry + work.episode; only memory.* kinds appear.
    #[test]
    fn export_excludes_local_only_kinds() {
        let conn = make_conn();
        seed_events(&conn);
        let (summary, content) = export_events(&conn, 0, None, false).expect("export");
        let jsonl = content.expect("content must be Some when out_path is None");
        assert!(summary.exported > 0, "must export at least 1 event");
        assert!(
            summary.exported <= 2,
            "only memory.accepted events (2 max); got {}",
            summary.exported
        );
        for line in jsonl.lines() {
            if line.trim().is_empty() {
                continue;
            }
            let se: SyncEvent = serde_json::from_str(line).expect("valid json");
            assert!(
                is_sync_allowed(&se.kind),
                "exported kind {:?} is NOT on the allowlist",
                se.kind
            );
            assert_ne!(
                se.kind, "work.episode",
                "work.episode must never be exported"
            );
            assert_ne!(
                se.kind, "context.served",
                "context.served must never be exported"
            );
            assert_ne!(
                se.kind, "run.started",
                "run metadata must never be exported"
            );
            assert_ne!(
                se.kind, "run.finished",
                "run metadata must never be exported"
            );
        }
    }

    // S3-2: Import is idempotent — re-importing the same batch is a NO-OP.
    #[test]
    fn import_is_idempotent() {
        let conn_a = make_conn();
        seed_events(&conn_a);
        let (_, content) = export_events(&conn_a, 0, None, false).expect("export");
        let jsonl = content.expect("content");

        let conn_b = make_conn();
        let s1 = import_events(&conn_b, &jsonl, false).expect("first import");
        assert!(s1.applied > 0, "first import must apply events");
        assert_eq!(s1.skipped, 0, "first import must have 0 skipped");

        let s2 = import_events(&conn_b, &jsonl, false).expect("second import");
        assert_eq!(s2.applied, 0, "re-import must apply 0 (idempotent)");
        assert_eq!(
            s2.skipped, s1.applied,
            "all events must be skipped on re-import"
        );
    }

    // S3-3: Round-trip — memories exported from brain A appear in brain B.
    #[test]
    fn round_trip_export_import() {
        let conn_a = make_conn();
        let (_, mem_id_a, mem_id_b) = seed_events(&conn_a);
        let (_, content) = export_events(&conn_a, 0, None, false).expect("export");
        let jsonl = content.expect("content");

        let conn_b = make_conn();
        let s = import_events(&conn_b, &jsonl, false).expect("import");
        assert!(s.applied > 0, "must have applied events");

        // Verify memories are projected in brain B.
        let count: i64 = conn_b
            .query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))
            .expect("count");
        assert!(
            count >= 1,
            "at least one memory must appear in B after import"
        );

        // Both memory ids should exist.
        for mid in [&mem_id_a, &mem_id_b] {
            let exists: i64 = conn_b
                .query_row(
                    "SELECT COUNT(*) FROM memories WHERE memory_id = ?1",
                    rusqlite::params![mid],
                    |r| r.get(0),
                )
                .expect("exists check");
            assert_eq!(exists, 1, "memory {} must exist in B after import", mid);
        }
    }

    // S3-4: Cursor advance — second export only emits the new event.
    #[test]
    fn cursor_advances_correctly() {
        let conn = make_conn();
        seed_events(&conn);
        let (summary1, _) = export_events(&conn, 0, None, false).expect("export 1");
        let cursor_after_first = summary1.next_cursor;

        // Add one more memory.accepted event.
        let run_id = RunId::new();
        let mem_id_c = format!("mem-c-{}", ulid::Ulid::new());
        apply_events(
            &conn,
            &[kimetsu_core::event::Event::new(
                run_id,
                "memory.accepted",
                json!({"memory_id": mem_id_c, "text": "new after cursor", "scope": "project", "kind": "fact"}),
            )],
        )
        .expect("add new event");

        let (summary2, content2) =
            export_events(&conn, cursor_after_first, None, false).expect("export 2");
        let jsonl2 = content2.expect("content");
        assert_eq!(
            summary2.exported, 1,
            "second export must emit exactly 1 new event"
        );
        let se: SyncEvent = serde_json::from_str(jsonl2.trim()).expect("parse");
        let payload_mid = se
            .payload
            .get("memory_id")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        assert_eq!(
            payload_mid, mem_id_c,
            "cursor must only export the new event"
        );
    }

    // S3-5: Redaction — secrets in memory.accepted payloads are redacted in export.
    #[test]
    fn export_redacts_secrets() {
        let conn = make_conn();
        let run_id = RunId::new();
        let secret = "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv0123456789AbCdEf";
        apply_events(
            &conn,
            &[kimetsu_core::event::Event::new(
                run_id,
                "memory.accepted",
                json!({
                    "memory_id": "mem-secret",
                    "text": format!("do not use {secret}"),
                    "scope": "project",
                    "kind": "fact"
                }),
            )],
        )
        .expect("seed");
        let (_, content) = export_events(&conn, 0, None, false).expect("export");
        let jsonl = content.expect("content");
        assert!(
            !jsonl.contains(secret),
            "exported batch must NOT contain the secret"
        );
        assert!(
            jsonl.contains("[REDACTED:anthropic_oauth]"),
            "exported batch must contain the REDACTED placeholder"
        );
    }

    // S3-6: Dry-run on import reports what WOULD apply without writing.
    #[test]
    fn dry_run_import_does_not_write() {
        let conn_a = make_conn();
        seed_events(&conn_a);
        let (_, content) = export_events(&conn_a, 0, None, false).expect("export");
        let jsonl = content.expect("content");

        let conn_b = make_conn();
        let s = import_events(&conn_b, &jsonl, true).expect("dry-run import");
        assert!(s.applied > 0, "dry-run must report events it WOULD apply");

        let count: i64 = conn_b
            .query_row("SELECT COUNT(*) FROM events", [], |r| r.get(0))
            .expect("count");
        assert_eq!(count, 0, "dry-run must NOT write any events");
    }

    // S3-7: Directory protocol — push writes a file; pull reads and imports it.
    #[test]
    fn directory_protocol_push_pull() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let sync_dir = tmp.path().join("sync");
        let cursors_path = tmp.path().join("sync-cursors.json");

        // Brain A.
        let conn_a = make_conn();
        seed_events(&conn_a);
        let machine_a = "machine-a";
        let report =
            sync_dir_fn(&conn_a, &sync_dir, machine_a, &cursors_path, false).expect("sync A");
        assert!(report.pushed > 0, "A must push events");

        // Brain B — pull from A.
        let conn_b = make_conn();
        let cursors_b_path = tmp.path().join("cursors-b.json");
        let machine_b = "machine-b";
        let report_b =
            sync_dir_fn(&conn_b, &sync_dir, machine_b, &cursors_b_path, false).expect("sync B");
        assert!(report_b.pulled_applied > 0, "B must import events from A");

        // Idempotent: sync B again — nothing new to apply.
        let report_b2 = sync_dir_fn(&conn_b, &sync_dir, machine_b, &cursors_b_path, false)
            .expect("sync B again");
        assert_eq!(
            report_b2.pulled_applied, 0,
            "second sync B must be idempotent (0 applied)"
        );
    }

    /// Thin wrapper so the test can call the module function by its short name.
    fn sync_dir_fn(
        conn: &Connection,
        sd: &Path,
        mid: &str,
        cp: &Path,
        dry: bool,
    ) -> KimetsuResult<SyncReport> {
        sync_dir(conn, sd, mid, cp, dry)
    }
}