shodh-memory 0.2.0

Persistent cognitive memory for AI agents and robots — Hebbian learning, knowledge graph, spatial recall. Zenoh/ROS2 native. Single binary, runs offline.
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
//! Decision Lineage Graph - Causal Memory System (SHO-118)
//!
//! Transforms Shodh from a memory system into a reasoning system by tracking
//! causal relationships between memories. Enables:
//!
//! 1. "Why" Audit Trail - Trace decisions back to root causes
//! 2. Lineage Branching - Git-like branches when projects pivot
//! 3. Automatic Post-Mortems - Synthesize learnings on task completion
//!
//! Storage schema:
//! - `lineage:edges:{user_id}:{edge_id}` - Causal edges between memories
//! - `lineage:by_from:{user_id}:{from_id}:{edge_id}` - Index by source memory
//! - `lineage:by_to:{user_id}:{to_id}:{edge_id}` - Index by target memory
//! - `lineage:branches:{user_id}:{branch_id}` - Branch metadata

use anyhow::Result;
use chrono::{DateTime, Utc};
use rocksdb::{IteratorMode, DB};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use uuid::Uuid;

use super::types::{ExperienceType, Memory, MemoryId};

/// Causal relationship types between memories
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CausalRelation {
    /// Error/Bug caused a Todo to be created
    Caused,
    /// Todo was resolved by a Learning/Fix
    ResolvedBy,
    /// Decision was informed by a Learning/Discovery
    InformedBy,
    /// Old decision/pattern was superseded by new one
    SupersededBy,
    /// Discovery/Learning triggered a Todo
    TriggeredBy,
    /// Memory branched from another (project pivot)
    BranchedFrom,
    /// Generic relation when type is unclear
    RelatedTo,
}

impl CausalRelation {
    /// Get the inverse relation for bidirectional traversal.
    ///
    /// When edge A→B has relation R, traversing B→A should show R.inverse().
    /// True pairs: Caused↔ResolvedBy. Directional relations (InformedBy,
    /// TriggeredBy) are self-inverse because the from/to already encodes
    /// directionality — "A informed-by B" reversed is "B informed A".
    pub fn inverse(&self) -> Self {
        match self {
            CausalRelation::Caused => CausalRelation::ResolvedBy,
            CausalRelation::ResolvedBy => CausalRelation::Caused,
            CausalRelation::InformedBy => CausalRelation::InformedBy,
            CausalRelation::TriggeredBy => CausalRelation::TriggeredBy,
            CausalRelation::SupersededBy => CausalRelation::SupersededBy,
            CausalRelation::BranchedFrom => CausalRelation::BranchedFrom,
            CausalRelation::RelatedTo => CausalRelation::RelatedTo,
        }
    }

    /// Human-readable description of the relationship
    pub fn description(&self) -> &'static str {
        match self {
            CausalRelation::Caused => "caused",
            CausalRelation::ResolvedBy => "was resolved by",
            CausalRelation::InformedBy => "was informed by",
            CausalRelation::SupersededBy => "was superseded by",
            CausalRelation::TriggeredBy => "triggered",
            CausalRelation::BranchedFrom => "branched from",
            CausalRelation::RelatedTo => "is related to",
        }
    }
}

/// Source of a lineage edge
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LineageSource {
    /// Automatically inferred by the system
    Inferred,
    /// Explicitly confirmed by user/agent
    Confirmed,
    /// Manually added by user/agent
    Explicit,
}

/// A causal edge between two memories
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineageEdge {
    /// Unique edge identifier
    pub id: String,
    /// Source memory (cause)
    pub from: MemoryId,
    /// Target memory (effect)
    pub to: MemoryId,
    /// Type of causal relationship
    pub relation: CausalRelation,
    /// Confidence in this causal link (0.0-1.0)
    pub confidence: f32,
    /// How this edge was created
    pub source: LineageSource,
    /// Branch this edge belongs to (None = main branch)
    pub branch_id: Option<String>,
    /// When the edge was created
    pub created_at: DateTime<Utc>,
    /// Last time this edge was reinforced/confirmed
    pub last_reinforced: DateTime<Utc>,
    /// Number of times this edge was reinforced
    pub reinforcement_count: u32,
}

impl LineageEdge {
    /// Create a new inferred edge
    pub fn inferred(
        from: MemoryId,
        to: MemoryId,
        relation: CausalRelation,
        confidence: f32,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            from,
            to,
            relation,
            confidence,
            source: LineageSource::Inferred,
            branch_id: None,
            created_at: now,
            last_reinforced: now,
            reinforcement_count: 1,
        }
    }

    /// Create a new explicit edge
    pub fn explicit(from: MemoryId, to: MemoryId, relation: CausalRelation) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            from,
            to,
            relation,
            confidence: 1.0, // Explicit edges have full confidence
            source: LineageSource::Explicit,
            branch_id: None,
            created_at: now,
            last_reinforced: now,
            reinforcement_count: 1,
        }
    }

    /// Confirm an inferred edge
    pub fn confirm(&mut self) {
        self.source = LineageSource::Confirmed;
        self.confidence = 1.0;
        self.last_reinforced = Utc::now();
        self.reinforcement_count += 1;
    }

    /// Reinforce this edge (increase confidence)
    pub fn reinforce(&mut self) {
        self.confidence = (self.confidence + 0.1).min(1.0);
        self.last_reinforced = Utc::now();
        self.reinforcement_count += 1;
    }

    /// Weaken this edge (decrease confidence via multiplicative decay).
    ///
    /// Asymmetric with reinforce: weakening is multiplicative (×0.90, −10%) while
    /// strengthening is additive (+0.1). This follows van Rossum et al. (2000)'s
    /// multiplicative LTD model where depression scales with current weight.
    ///
    /// The 10% per event sits at the conservative end of Dudek & Bear (1992)'s
    /// validated range of 10–30% long-term depression per induction. At w=1.0
    /// the depression/potentiation ratio is 1.0:1 (symmetric), rising to 2.25:1
    /// at w=0.45 — closer to Song, Miller & Abbott (2000)'s steady-state ratio
    /// of ~1.05:1 than the previous 0.85 multiplier which produced 1.5:1 at w=1.0.
    ///
    /// Pruning threshold 0.05 is in the 5th percentile range suggested by
    /// Chechik (1998) for optimal memory capacity in sparse networks.
    ///
    /// Returns true if the edge should be pruned (confidence dropped below 0.05).
    /// Callers should delete pruned edges to prevent the lineage graph from
    /// accumulating zombie edges with negligible confidence.
    ///
    /// References:
    /// - Dudek & Bear (1992) "Homosynaptic long-term depression" — 10-30% LTD
    /// - van Rossum et al. (2000) "Stable Hebbian learning from spike timing" — multiplicative LTD
    /// - Song, Miller & Abbott (2000) "Competitive Hebbian learning" — ~1.05:1 ratio
    /// - Chechik (1998) "Synaptic pruning in development" — 5-50th percentile threshold
    pub fn weaken(&mut self) -> bool {
        self.confidence *= 0.90;
        self.last_reinforced = Utc::now();
        self.confidence < 0.05
    }
}

/// A branch in the lineage graph (for project pivots)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineageBranch {
    /// Unique branch identifier
    pub id: String,
    /// Human-readable branch name
    pub name: String,
    /// Description of what this branch represents
    pub description: Option<String>,
    /// Parent branch (None for main branch)
    pub parent_branch: Option<String>,
    /// Memory where this branch diverged from parent
    pub branch_point: Option<MemoryId>,
    /// When the branch was created
    pub created_at: DateTime<Utc>,
    /// Whether this branch is currently active
    pub active: bool,
    /// Tags for categorization
    pub tags: Vec<String>,
}

impl LineageBranch {
    /// Create the main branch
    pub fn main() -> Self {
        Self {
            id: "main".to_string(),
            name: "Main".to_string(),
            description: Some("Primary project lineage".to_string()),
            parent_branch: None,
            branch_point: None,
            created_at: Utc::now(),
            active: true,
            tags: vec![],
        }
    }

    /// Create a new branch from a parent
    pub fn new(
        name: &str,
        parent: &str,
        branch_point: MemoryId,
        description: Option<&str>,
    ) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.to_string(),
            description: description.map(|s| s.to_string()),
            parent_branch: Some(parent.to_string()),
            branch_point: Some(branch_point),
            created_at: Utc::now(),
            active: true,
            tags: vec![],
        }
    }
}

/// Result of lineage trace operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineageTrace {
    /// The memory we started from
    pub root: MemoryId,
    /// Direction of traversal
    pub direction: TraceDirection,
    /// Edges in the trace (ordered by distance from root)
    pub edges: Vec<LineageEdge>,
    /// Memory IDs in traversal order
    pub path: Vec<MemoryId>,
    /// Total depth traversed
    pub depth: usize,
}

/// Direction for lineage traversal
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TraceDirection {
    /// Trace backward to find causes
    Backward,
    /// Trace forward to find effects
    Forward,
    /// Trace in both directions
    Both,
}

/// Configuration for lineage inference
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferenceConfig {
    /// Maximum days between memories for causal inference
    pub max_temporal_gap_days: i64,
    /// Minimum entity overlap for causal inference
    pub min_entity_overlap: f32,
    /// Confidence thresholds for each relation type
    pub relation_confidence: HashMap<CausalRelation, f32>,
}

impl Default for InferenceConfig {
    fn default() -> Self {
        use crate::constants::*;

        let mut relation_confidence = HashMap::new();
        relation_confidence.insert(CausalRelation::Caused, LINEAGE_CONFIDENCE_CAUSED);
        relation_confidence.insert(CausalRelation::ResolvedBy, LINEAGE_CONFIDENCE_RESOLVED_BY);
        relation_confidence.insert(CausalRelation::InformedBy, LINEAGE_CONFIDENCE_INFORMED_BY);
        relation_confidence.insert(
            CausalRelation::SupersededBy,
            LINEAGE_CONFIDENCE_SUPERSEDED_BY,
        );
        relation_confidence.insert(CausalRelation::TriggeredBy, LINEAGE_CONFIDENCE_TRIGGERED_BY);
        relation_confidence.insert(
            CausalRelation::BranchedFrom,
            LINEAGE_CONFIDENCE_BRANCHED_FROM,
        );
        relation_confidence.insert(CausalRelation::RelatedTo, LINEAGE_CONFIDENCE_RELATED_TO);

        Self {
            max_temporal_gap_days: LINEAGE_MAX_TEMPORAL_GAP_DAYS,
            min_entity_overlap: LINEAGE_MIN_ENTITY_OVERLAP,
            relation_confidence,
        }
    }
}

/// Statistics about the lineage graph
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LineageStats {
    pub total_edges: usize,
    pub inferred_edges: usize,
    pub confirmed_edges: usize,
    pub explicit_edges: usize,
    pub total_branches: usize,
    pub active_branches: usize,
    pub edges_by_relation: HashMap<String, usize>,
    pub avg_confidence: f32,
}

/// The Lineage Graph - stores and infers causal relationships
pub struct LineageGraph {
    db: Arc<DB>,
    config: InferenceConfig,
}

impl LineageGraph {
    /// Create a new lineage graph backed by RocksDB
    pub fn new(db: Arc<DB>) -> Self {
        Self {
            db,
            config: InferenceConfig::default(),
        }
    }

    /// Create with custom inference config
    pub fn with_config(db: Arc<DB>, config: InferenceConfig) -> Self {
        Self { db, config }
    }

    // =========================================================================
    // EDGE STORAGE
    // =========================================================================

    /// Store a lineage edge
    pub fn store_edge(&self, user_id: &str, edge: &LineageEdge) -> Result<()> {
        // Primary storage
        let key = format!("lineage:edges:{}:{}", user_id, edge.id);
        let value = crate::serialization::encode(edge)?;
        self.db.put(key.as_bytes(), &value)?;

        // Index by source (from)
        let from_key = format!("lineage:by_from:{}:{}:{}", user_id, edge.from.0, edge.id);
        self.db.put(from_key.as_bytes(), edge.id.as_bytes())?;

        // Index by target (to)
        let to_key = format!("lineage:by_to:{}:{}:{}", user_id, edge.to.0, edge.id);
        self.db.put(to_key.as_bytes(), edge.id.as_bytes())?;

        Ok(())
    }

    /// Get an edge by ID
    pub fn get_edge(&self, user_id: &str, edge_id: &str) -> Result<Option<LineageEdge>> {
        let key = format!("lineage:edges:{}:{}", user_id, edge_id);
        match self.db.get(key.as_bytes())? {
            Some(data) => {
                let (edge, _) = crate::serialization::try_decode::<LineageEdge>(&data)?;
                Ok(Some(edge))
            }
            None => Ok(None),
        }
    }

    /// Delete an edge (for rejection)
    pub fn delete_edge(&self, user_id: &str, edge_id: &str) -> Result<bool> {
        if let Some(edge) = self.get_edge(user_id, edge_id)? {
            // Delete indices
            let from_key = format!("lineage:by_from:{}:{}:{}", user_id, edge.from.0, edge_id);
            self.db.delete(from_key.as_bytes())?;

            let to_key = format!("lineage:by_to:{}:{}:{}", user_id, edge.to.0, edge_id);
            self.db.delete(to_key.as_bytes())?;

            // Delete primary
            let key = format!("lineage:edges:{}:{}", user_id, edge_id);
            self.db.delete(key.as_bytes())?;

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Get all edges from a memory (outgoing)
    pub fn get_edges_from(&self, user_id: &str, memory_id: &MemoryId) -> Result<Vec<LineageEdge>> {
        let prefix = format!("lineage:by_from:{}:{}:", user_id, memory_id.0);
        self.get_edges_by_prefix(user_id, &prefix)
    }

    /// Get all edges to a memory (incoming)
    pub fn get_edges_to(&self, user_id: &str, memory_id: &MemoryId) -> Result<Vec<LineageEdge>> {
        let prefix = format!("lineage:by_to:{}:{}:", user_id, memory_id.0);
        self.get_edges_by_prefix(user_id, &prefix)
    }

    /// Helper to get edges by index prefix
    fn get_edges_by_prefix(&self, user_id: &str, prefix: &str) -> Result<Vec<LineageEdge>> {
        let mut edges = Vec::new();

        let iter = self.db.iterator(IteratorMode::From(
            prefix.as_bytes(),
            rocksdb::Direction::Forward,
        ));

        for item in iter {
            let (key, value) = item?;
            let key_str = String::from_utf8_lossy(&key);

            if !key_str.starts_with(prefix) {
                break;
            }

            let edge_id = String::from_utf8_lossy(&value);
            if let Some(edge) = self.get_edge(user_id, &edge_id)? {
                edges.push(edge);
            }
        }

        Ok(edges)
    }

    /// List all edges for a user
    pub fn list_edges(&self, user_id: &str, limit: usize) -> Result<Vec<LineageEdge>> {
        let prefix = format!("lineage:edges:{}:", user_id);
        let mut edges = Vec::new();

        let iter = self.db.iterator(IteratorMode::From(
            prefix.as_bytes(),
            rocksdb::Direction::Forward,
        ));

        for item in iter {
            let (key, value) = item?;
            let key_str = String::from_utf8_lossy(&key);

            if !key_str.starts_with(&prefix) {
                break;
            }

            if let Ok((edge, _)) = crate::serialization::try_decode::<LineageEdge>(&value) {
                edges.push(edge);
                if edges.len() >= limit {
                    break;
                }
            }
        }

        // Sort by creation time (newest first)
        edges.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        Ok(edges)
    }

    // =========================================================================
    // BRANCH MANAGEMENT
    // =========================================================================

    /// Store a branch
    pub fn store_branch(&self, user_id: &str, branch: &LineageBranch) -> Result<()> {
        let key = format!("lineage:branches:{}:{}", user_id, branch.id);
        let value = crate::serialization::encode(branch)?;
        self.db.put(key.as_bytes(), &value)?;
        Ok(())
    }

    /// Get a branch by ID
    pub fn get_branch(&self, user_id: &str, branch_id: &str) -> Result<Option<LineageBranch>> {
        let key = format!("lineage:branches:{}:{}", user_id, branch_id);
        match self.db.get(key.as_bytes())? {
            Some(data) => {
                let (branch, _) = crate::serialization::try_decode::<LineageBranch>(&data)?;
                Ok(Some(branch))
            }
            None => Ok(None),
        }
    }

    /// List all branches for a user
    pub fn list_branches(&self, user_id: &str) -> Result<Vec<LineageBranch>> {
        let prefix = format!("lineage:branches:{}:", user_id);
        let mut branches = Vec::new();

        let iter = self.db.iterator(IteratorMode::From(
            prefix.as_bytes(),
            rocksdb::Direction::Forward,
        ));

        for item in iter {
            let (key, value) = item?;
            let key_str = String::from_utf8_lossy(&key);

            if !key_str.starts_with(&prefix) {
                break;
            }

            if let Ok((branch, _)) = crate::serialization::try_decode::<LineageBranch>(&value) {
                branches.push(branch);
            }
        }

        // Sort by creation time (newest first)
        branches.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        Ok(branches)
    }

    /// Create a new branch from current state
    pub fn create_branch(
        &self,
        user_id: &str,
        name: &str,
        parent_branch: &str,
        branch_point: MemoryId,
        description: Option<&str>,
    ) -> Result<LineageBranch> {
        let branch = LineageBranch::new(name, parent_branch, branch_point, description);
        self.store_branch(user_id, &branch)?;
        Ok(branch)
    }

    /// Ensure main branch exists for user
    pub fn ensure_main_branch(&self, user_id: &str) -> Result<()> {
        if self.get_branch(user_id, "main")?.is_none() {
            self.store_branch(user_id, &LineageBranch::main())?;
        }
        Ok(())
    }

    // =========================================================================
    // LINEAGE INFERENCE ENGINE
    // =========================================================================

    /// Infer causal relationship between two memories.
    ///
    /// Uses three complementary signals:
    /// 1. **Type-pair rules**: ExperienceType combinations → CausalRelation + base confidence
    /// 2. **Semantic overlap**: max(Jaccard entity overlap, cosine embedding similarity)
    /// 3. **Temporal proximity**: linear decay over the temporal gap
    ///
    /// The semantic overlap combines entity tags (precise but brittle — exact string match)
    /// with embedding similarity (fuzzy but robust — captures synonyms and paraphrases).
    /// Using `max()` ensures we never regress when entities work well, while rescuing
    /// cases where NER fails or different surface forms describe the same concept.
    pub fn infer_relation(&self, from: &Memory, to: &Memory) -> Option<(CausalRelation, f32)> {
        // Must be in temporal order (from before to)
        if from.created_at >= to.created_at {
            return None;
        }

        // Check temporal gap
        let gap = to.created_at.signed_duration_since(from.created_at);
        if gap.num_days() > self.config.max_temporal_gap_days {
            return None;
        }

        // Signal 1: Entity overlap (Jaccard on entity tags)
        let entity_overlap =
            Self::calculate_entity_overlap(&from.experience.entities, &to.experience.entities);

        // Signal 2: Embedding similarity (cosine between content embeddings)
        let embedding_sim = match (&from.experience.embeddings, &to.experience.embeddings) {
            (Some(emb_a), Some(emb_b)) if emb_a.len() == emb_b.len() && !emb_a.is_empty() => {
                Self::cosine_similarity(emb_a, emb_b).max(0.0) // clamp negatives
            }
            _ => 0.0,
        };

        // Combined semantic signal: best of entity overlap and embedding similarity.
        // This ensures neither signal pathway can suppress the other.
        let semantic_signal = entity_overlap.max(embedding_sim);

        // Gate: when we have both entities AND embeddings, require minimum semantic signal.
        // When either is missing, let inference proceed at whatever signal we have.
        let has_entities =
            !from.experience.entities.is_empty() && !to.experience.entities.is_empty();
        let has_embeddings =
            from.experience.embeddings.is_some() && to.experience.embeddings.is_some();

        if has_entities && !has_embeddings && entity_overlap < self.config.min_entity_overlap {
            // Only entities available, and they don't overlap enough
            return None;
        }
        if has_embeddings && !has_entities && embedding_sim < self.config.min_entity_overlap {
            // Only embeddings available, and similarity too low
            return None;
        }
        if has_entities && has_embeddings && semantic_signal < self.config.min_entity_overlap {
            // Both signals available, but neither reaches threshold
            return None;
        }

        // Infer based on memory types
        let (relation, base_confidence) = self.infer_by_types(
            &from.experience.experience_type,
            &to.experience.experience_type,
        )?;

        // Compute effective overlap for confidence scaling.
        // When no entities and no embeddings, use a floor of 0.3 to avoid zeroing out.
        let effective_overlap = if semantic_signal > 0.0 {
            semantic_signal
        } else if has_entities {
            entity_overlap
        } else {
            0.3 // floor for memories with no semantic signals
        };

        // Signal 3: Temporal proximity (linear decay)
        let temporal_factor =
            1.0 - (gap.num_days() as f32 / self.config.max_temporal_gap_days as f32);
        let confidence = base_confidence * effective_overlap * (0.5 + 0.5 * temporal_factor);

        Some((relation, confidence))
    }

    /// Cosine similarity between two embedding vectors.
    /// Delegates to the SIMD-optimized implementation in similarity.rs.
    fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
        crate::similarity::cosine_similarity(a, b)
    }

    /// Infer relation based on memory types.
    ///
    /// Type-pair modifiers (0.70–0.90) for bridge types (Observation, Conversation)
    /// encode source reliability following Johnson & Raye (1981)'s Source Monitoring
    /// Framework: memories from different sources carry different diagnostic weight
    /// for causal attribution. Specific modifier rationale:
    ///
    /// - **0.90** (Conversation → Decision): Conversations are high-fidelity causal
    ///   sources — they carry explicit reasoning and intent. Closest to "direct
    ///   experience" in the SMF hierarchy.
    ///
    /// - **0.85** (Observation/Conversation → Task/Learning/Discovery): Moderate
    ///   reliability — observations and discussions often precede work but the causal
    ///   link is indirect (correlation, not demonstrated causation).
    ///
    /// - **0.75** (Observation → Error): Observations rarely *cause* errors directly;
    ///   they *reveal* pre-existing conditions. The lower modifier reflects this
    ///   weaker causal claim (closer to "associated with" than "caused by").
    ///
    /// - **0.70** (Conversation → Error): Weakest bridge — conversations surfacing
    ///   bugs is informational, not causal. Bovens & Hartmann (2003) show that
    ///   indirect testimony requires larger discounts than direct observation.
    ///
    /// These are engineering choices grounded in the SMF taxonomy but not
    /// empirically calibrated. The confidence formula (base × modifier × overlap ×
    /// temporal) means modifiers affect the starting point, not the final ranking,
    /// which is dominated by entity overlap and temporal proximity.
    ///
    /// References:
    /// - Johnson & Raye (1981) "Reality monitoring" — source monitoring framework
    /// - Bovens & Hartmann (2003) "Bayesian Epistemology" — testimony reliability
    fn infer_by_types(
        &self,
        from_type: &ExperienceType,
        to_type: &ExperienceType,
    ) -> Option<(CausalRelation, f32)> {
        use ExperienceType::*;

        match (from_type, to_type) {
            // Error → Todo = Caused
            (Error, Task) => Some((
                CausalRelation::Caused,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::Caused)
                    .unwrap_or(&0.8),
            )),

            // Todo → Learning = ResolvedBy (when todo leads to learning)
            (Task, Learning) => Some((
                CausalRelation::ResolvedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::ResolvedBy)
                    .unwrap_or(&0.85),
            )),

            // Learning → Decision = InformedBy
            (Learning, Decision) | (Discovery, Decision) => Some((
                CausalRelation::InformedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::InformedBy)
                    .unwrap_or(&0.7),
            )),

            // Decision → Decision = SupersededBy (newer supersedes older)
            (Decision, Decision) => Some((
                CausalRelation::SupersededBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::SupersededBy)
                    .unwrap_or(&0.6),
            )),

            // Discovery/Learning → Todo = TriggeredBy
            (Discovery, Task) | (Learning, Task) => Some((
                CausalRelation::TriggeredBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::TriggeredBy)
                    .unwrap_or(&0.75),
            )),

            // Pattern → Learning = InformedBy (patterns inform learnings)
            (Pattern, Learning) | (Pattern, Decision) => Some((
                CausalRelation::InformedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::InformedBy)
                    .unwrap_or(&0.7),
            )),

            // Error → Learning = ResolvedBy (error led to learning)
            (Error, Learning) => Some((
                CausalRelation::ResolvedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::ResolvedBy)
                    .unwrap_or(&0.85),
            )),

            // Observation → Discovery = TriggeredBy
            (Observation, Discovery) => Some((
                CausalRelation::TriggeredBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::TriggeredBy)
                    .unwrap_or(&0.75),
            )),

            // Observation → Task = TriggeredBy (observation led to work)
            (Observation, Task) => Some((
                CausalRelation::TriggeredBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::TriggeredBy)
                    .unwrap_or(&0.75)
                    * 0.85, // slightly lower — observations are less direct triggers than discoveries
            )),

            // Observation → Decision = InformedBy (observation informed a decision)
            (Observation, Decision) => Some((
                CausalRelation::InformedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::InformedBy)
                    .unwrap_or(&0.7)
                    * 0.85,
            )),

            // Observation → Error = Caused (observation of a problem → error report)
            (Observation, Error) => Some((
                CausalRelation::Caused,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::Caused)
                    .unwrap_or(&0.8)
                    * 0.75, // observations rarely directly cause errors; lower confidence
            )),

            // Observation → Learning = TriggeredBy (observation sparked learning)
            (Observation, Learning) => Some((
                CausalRelation::TriggeredBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::TriggeredBy)
                    .unwrap_or(&0.75)
                    * 0.85,
            )),

            // Conversation → Decision = InformedBy (discussion informed a decision)
            (Conversation, Decision) => Some((
                CausalRelation::InformedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::InformedBy)
                    .unwrap_or(&0.7)
                    * 0.9, // conversations are strong informational sources
            )),

            // Conversation → Task = TriggeredBy (discussion spawned work)
            (Conversation, Task) => Some((
                CausalRelation::TriggeredBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::TriggeredBy)
                    .unwrap_or(&0.75)
                    * 0.85,
            )),

            // Conversation → Learning = InformedBy (discussion led to learning)
            (Conversation, Learning) => Some((
                CausalRelation::InformedBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::InformedBy)
                    .unwrap_or(&0.7)
                    * 0.85,
            )),

            // Conversation → Error = Caused (discussion surfaced a bug)
            (Conversation, Error) => Some((
                CausalRelation::Caused,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::Caused)
                    .unwrap_or(&0.8)
                    * 0.7, // conversations weakly cause error reports
            )),

            // Conversation → Discovery = TriggeredBy (discussion led to discovery)
            (Conversation, Discovery) => Some((
                CausalRelation::TriggeredBy,
                *self
                    .config
                    .relation_confidence
                    .get(&CausalRelation::TriggeredBy)
                    .unwrap_or(&0.75)
                    * 0.85,
            )),

            // Default: RelatedTo if same type or generic relation
            _ => {
                // Only suggest RelatedTo for semantically related types
                if Self::are_types_related(from_type, to_type) {
                    Some((
                        CausalRelation::RelatedTo,
                        *self
                            .config
                            .relation_confidence
                            .get(&CausalRelation::RelatedTo)
                            .unwrap_or(&0.5),
                    ))
                } else {
                    None
                }
            }
        }
    }

    /// Check if two experience types are semantically related.
    ///
    /// Returns true for same-group pairs AND for cross-group bridging types.
    /// Observation and Conversation are "bridge" types — they can relate to
    /// any other type because observations and conversations often span domains.
    fn are_types_related(a: &ExperienceType, b: &ExperienceType) -> bool {
        use ExperienceType::*;

        // Same type is always related
        if std::mem::discriminant(a) == std::mem::discriminant(b) {
            return true;
        }

        // Bridge types: Observation and Conversation can relate to anything.
        // These are the most common types in production (segmentation fallback
        // and hook ingestion), so they must bridge across groups to form chains.
        let is_bridge = |t: &ExperienceType| matches!(t, Observation | Conversation);
        if is_bridge(a) || is_bridge(b) {
            return true;
        }

        // Define related type groups for non-bridge types
        let knowledge_types = [Learning, Discovery, Pattern];
        let action_types = [Task, Decision, Command, CodeEdit];
        let context_types = [Context, FileAccess, Search];

        let in_knowledge = |t: &ExperienceType| {
            knowledge_types
                .iter()
                .any(|k| std::mem::discriminant(k) == std::mem::discriminant(t))
        };
        let in_action = |t: &ExperienceType| {
            action_types
                .iter()
                .any(|k| std::mem::discriminant(k) == std::mem::discriminant(t))
        };
        let in_context = |t: &ExperienceType| {
            context_types
                .iter()
                .any(|k| std::mem::discriminant(k) == std::mem::discriminant(t))
        };

        // Types in same group are related
        (in_knowledge(a) && in_knowledge(b))
            || (in_action(a) && in_action(b))
            || (in_context(a) && in_context(b))
    }

    /// Calculate entity overlap using Jaccard similarity
    fn calculate_entity_overlap(tags_a: &[String], tags_b: &[String]) -> f32 {
        if tags_a.is_empty() && tags_b.is_empty() {
            return 0.0;
        }

        let set_a: HashSet<&str> = tags_a.iter().map(|s| s.as_str()).collect();
        let set_b: HashSet<&str> = tags_b.iter().map(|s| s.as_str()).collect();

        let intersection = set_a.intersection(&set_b).count();
        let union = set_a.union(&set_b).count();

        if union == 0 {
            0.0
        } else {
            intersection as f32 / union as f32
        }
    }

    /// Detect branch point from memory content (pivot language).
    ///
    /// Uses strong phrase-level signals to avoid false positives from common words
    /// like "actually" or "instead" which appear in normal discourse.
    /// Requires either one strong signal or two weak signals to trigger.
    pub fn detect_branch_signal(content: &str) -> bool {
        let content_lower = content.to_lowercase();

        // Strong signals: unambiguous pivot language
        let strong_signals = [
            "pivot to",
            "change direction",
            "start fresh",
            "start over",
            "complete rewrite",
            "should rewrite",
            "need to rewrite",
            "scrap this",
            "scrap the",
            "different strategy",
            "new strategy",
            "abandon",
        ];

        // Weak signals: common words that only indicate a pivot when combined
        let weak_signals = ["instead", "new approach", "rethink", "rewrite", "pivot"];

        let strong_count = strong_signals
            .iter()
            .filter(|s| content_lower.contains(*s))
            .count();
        let weak_count = weak_signals
            .iter()
            .filter(|s| content_lower.contains(*s))
            .count();

        strong_count >= 1 || weak_count >= 2
    }

    // =========================================================================
    // LINEAGE TRAVERSAL
    // =========================================================================

    /// Trace lineage from a memory
    pub fn trace(
        &self,
        user_id: &str,
        memory_id: &MemoryId,
        direction: TraceDirection,
        max_depth: usize,
    ) -> Result<LineageTrace> {
        let mut visited = HashSet::new();
        let mut edges = Vec::new();
        let mut path = vec![memory_id.clone()];
        let mut queue: VecDeque<(MemoryId, usize)> = VecDeque::new();

        queue.push_back((memory_id.clone(), 0));
        visited.insert(memory_id.clone());

        while let Some((current_id, depth)) = queue.pop_front() {
            if depth >= max_depth {
                continue;
            }

            let next_edges = match direction {
                TraceDirection::Backward => self.get_edges_to(user_id, &current_id)?,
                TraceDirection::Forward => self.get_edges_from(user_id, &current_id)?,
                TraceDirection::Both => {
                    let mut all = self.get_edges_to(user_id, &current_id)?;
                    all.extend(self.get_edges_from(user_id, &current_id)?);
                    all
                }
            };

            for edge in next_edges {
                let next_id = match direction {
                    TraceDirection::Backward => edge.from.clone(),
                    TraceDirection::Forward => edge.to.clone(),
                    TraceDirection::Both => {
                        if edge.from == current_id {
                            edge.to.clone()
                        } else {
                            edge.from.clone()
                        }
                    }
                };

                if !visited.contains(&next_id) {
                    visited.insert(next_id.clone());
                    path.push(next_id.clone());
                    edges.push(edge);
                    queue.push_back((next_id, depth + 1));
                }
            }
        }

        let depth = path.len().saturating_sub(1);
        Ok(LineageTrace {
            root: memory_id.clone(),
            direction,
            edges,
            path,
            depth,
        })
    }

    /// Find the root cause of a memory (trace all the way back)
    ///
    /// Returns `None` if the memory has no ancestors (is itself a root).
    pub fn find_root_cause(&self, user_id: &str, memory_id: &MemoryId) -> Result<Option<MemoryId>> {
        let trace = self.trace(user_id, memory_id, TraceDirection::Backward, 100)?;
        // path[0] is the starting memory — only return a root if we found ancestors
        if trace.path.len() <= 1 {
            Ok(None)
        } else {
            Ok(trace.path.last().cloned())
        }
    }

    /// Find all effects of a memory (trace all the way forward)
    ///
    /// Returns effects only (excludes the starting memory itself).
    pub fn find_effects(
        &self,
        user_id: &str,
        memory_id: &MemoryId,
        max_depth: usize,
    ) -> Result<Vec<MemoryId>> {
        let trace = self.trace(user_id, memory_id, TraceDirection::Forward, max_depth)?;
        // Skip the first element (the starting memory itself)
        Ok(trace.path.into_iter().skip(1).collect())
    }

    // =========================================================================
    // USER OPERATIONS
    // =========================================================================

    /// Confirm an inferred edge
    pub fn confirm_edge(&self, user_id: &str, edge_id: &str) -> Result<bool> {
        if let Some(mut edge) = self.get_edge(user_id, edge_id)? {
            edge.confirm();
            self.store_edge(user_id, &edge)?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Reject (delete) an inferred edge
    pub fn reject_edge(&self, user_id: &str, edge_id: &str) -> Result<bool> {
        self.delete_edge(user_id, edge_id)
    }

    /// Add an explicit edge
    pub fn add_explicit_edge(
        &self,
        user_id: &str,
        from: MemoryId,
        to: MemoryId,
        relation: CausalRelation,
    ) -> Result<LineageEdge> {
        let edge = LineageEdge::explicit(from, to, relation);
        self.store_edge(user_id, &edge)?;
        Ok(edge)
    }

    /// Check if an edge already exists between two memories
    pub fn edge_exists(&self, user_id: &str, from: &MemoryId, to: &MemoryId) -> Result<bool> {
        let edges = self.get_edges_from(user_id, from)?;
        Ok(edges.iter().any(|e| &e.to == to))
    }

    // =========================================================================
    // STATISTICS
    // =========================================================================

    /// Get lineage statistics for a user.
    ///
    /// Caps the scan at 10,000 edges. For users with more edges, the stats
    /// will be approximate (counts capped, averages computed over the sample).
    pub fn stats(&self, user_id: &str) -> Result<LineageStats> {
        const STATS_SCAN_LIMIT: usize = 10_000;
        let edges = self.list_edges(user_id, STATS_SCAN_LIMIT)?;
        let branches = self.list_branches(user_id)?;

        let mut stats = LineageStats {
            total_edges: edges.len(),
            total_branches: branches.len(),
            active_branches: branches.iter().filter(|b| b.active).count(),
            ..Default::default()
        };

        let mut total_confidence: f32 = 0.0;

        for edge in &edges {
            match edge.source {
                LineageSource::Inferred => stats.inferred_edges += 1,
                LineageSource::Confirmed => stats.confirmed_edges += 1,
                LineageSource::Explicit => stats.explicit_edges += 1,
            }

            let relation_name = format!("{:?}", edge.relation);
            *stats.edges_by_relation.entry(relation_name).or_insert(0) += 1;

            total_confidence += edge.confidence;
        }

        if !edges.is_empty() {
            stats.avg_confidence = total_confidence / edges.len() as f32;
        }

        Ok(stats)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::types::Experience;
    use chrono::Duration;
    use tempfile::TempDir;

    fn create_test_graph() -> (LineageGraph, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let db = Arc::new(DB::open_default(temp_dir.path()).unwrap());
        (LineageGraph::new(db), temp_dir)
    }

    fn create_test_memory(exp_type: ExperienceType, entities: Vec<&str>) -> Memory {
        let experience = Experience {
            experience_type: exp_type,
            content: "Test memory".to_string(),
            entities: entities.into_iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        };
        Memory::new(
            MemoryId(Uuid::new_v4()),
            experience,
            0.5,  // importance
            None, // agent_id
            None, // run_id
            None, // actor_id
            None, // created_at (uses Utc::now())
        )
    }

    #[test]
    fn test_store_and_get_edge() {
        let (graph, _dir) = create_test_graph();
        let from = MemoryId(Uuid::new_v4());
        let to = MemoryId(Uuid::new_v4());

        let edge = LineageEdge::explicit(from.clone(), to.clone(), CausalRelation::Caused);
        graph.store_edge("user-1", &edge).unwrap();

        let retrieved = graph.get_edge("user-1", &edge.id).unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().relation, CausalRelation::Caused);
    }

    #[test]
    fn test_get_edges_from_and_to() {
        let (graph, _dir) = create_test_graph();
        let from = MemoryId(Uuid::new_v4());
        let to1 = MemoryId(Uuid::new_v4());
        let to2 = MemoryId(Uuid::new_v4());

        let edge1 = LineageEdge::explicit(from.clone(), to1.clone(), CausalRelation::Caused);
        let edge2 = LineageEdge::explicit(from.clone(), to2.clone(), CausalRelation::TriggeredBy);

        graph.store_edge("user-1", &edge1).unwrap();
        graph.store_edge("user-1", &edge2).unwrap();

        let from_edges = graph.get_edges_from("user-1", &from).unwrap();
        assert_eq!(from_edges.len(), 2);

        let to_edges = graph.get_edges_to("user-1", &to1).unwrap();
        assert_eq!(to_edges.len(), 1);
    }

    #[test]
    fn test_infer_error_to_task() {
        let (graph, _dir) = create_test_graph();

        // Use same entities for high overlap
        let error = create_test_memory(ExperienceType::Error, vec!["auth", "login"]);
        let mut task = create_test_memory(ExperienceType::Task, vec!["auth", "login"]);
        task.created_at = error.created_at + Duration::days(1);

        let result = graph.infer_relation(&error, &task);
        assert!(result.is_some());
        let (relation, confidence) = result.unwrap();
        assert_eq!(relation, CausalRelation::Caused);
        // With perfect overlap (1.0) and 1 day gap: 0.8 * 1.0 * 0.93 ≈ 0.74
        assert!(confidence > 0.4, "confidence was {}", confidence);
    }

    #[test]
    fn test_infer_learning_to_decision() {
        let (graph, _dir) = create_test_graph();

        let learning = create_test_memory(ExperienceType::Learning, vec!["react", "hooks"]);
        let mut decision =
            create_test_memory(ExperienceType::Decision, vec!["react", "hooks", "state"]);
        decision.created_at = learning.created_at + Duration::days(2);

        let result = graph.infer_relation(&learning, &decision);
        assert!(result.is_some());
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::InformedBy);
    }

    #[test]
    fn test_no_inference_wrong_order() {
        let (graph, _dir) = create_test_graph();

        let task = create_test_memory(ExperienceType::Task, vec!["auth"]);
        let mut error = create_test_memory(ExperienceType::Error, vec!["auth"]);
        error.created_at = task.created_at - Duration::days(1); // Error BEFORE task

        // Task to Error (wrong causal direction) should not infer Caused
        let result = graph.infer_relation(&task, &error);
        assert!(result.is_none());
    }

    #[test]
    fn test_branch_creation() {
        let (graph, _dir) = create_test_graph();
        let branch_point = MemoryId(Uuid::new_v4());

        graph.ensure_main_branch("user-1").unwrap();

        let branch = graph
            .create_branch(
                "user-1",
                "v2-rewrite",
                "main",
                branch_point,
                Some("Complete rewrite"),
            )
            .unwrap();

        let retrieved = graph.get_branch("user-1", &branch.id).unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "v2-rewrite");
    }

    #[test]
    fn test_detect_branch_signal() {
        assert!(LineageGraph::detect_branch_signal(
            "Let's pivot to a new approach"
        ));
        assert!(LineageGraph::detect_branch_signal(
            "Actually, we should rewrite this"
        ));
        assert!(LineageGraph::detect_branch_signal(
            "I think we need to start fresh"
        ));
        assert!(!LineageGraph::detect_branch_signal("Fixed the bug in auth"));
    }

    #[test]
    fn test_confirm_and_reject_edge() {
        let (graph, _dir) = create_test_graph();
        let from = MemoryId(Uuid::new_v4());
        let to = MemoryId(Uuid::new_v4());

        let edge = LineageEdge::inferred(from.clone(), to.clone(), CausalRelation::Caused, 0.7);
        graph.store_edge("user-1", &edge).unwrap();

        // Confirm
        assert!(graph.confirm_edge("user-1", &edge.id).unwrap());
        let confirmed = graph.get_edge("user-1", &edge.id).unwrap().unwrap();
        assert_eq!(confirmed.source, LineageSource::Confirmed);
        assert_eq!(confirmed.confidence, 1.0);

        // Reject another edge
        let edge2 = LineageEdge::inferred(from, to, CausalRelation::RelatedTo, 0.5);
        graph.store_edge("user-1", &edge2).unwrap();
        assert!(graph.reject_edge("user-1", &edge2.id).unwrap());
        assert!(graph.get_edge("user-1", &edge2.id).unwrap().is_none());
    }

    #[test]
    fn test_lineage_stats() {
        let (graph, _dir) = create_test_graph();

        let from = MemoryId(Uuid::new_v4());
        let to = MemoryId(Uuid::new_v4());

        graph
            .store_edge(
                "user-1",
                &LineageEdge::inferred(from.clone(), to.clone(), CausalRelation::Caused, 0.8),
            )
            .unwrap();
        graph
            .store_edge(
                "user-1",
                &LineageEdge::explicit(from.clone(), to.clone(), CausalRelation::InformedBy),
            )
            .unwrap();
        graph.ensure_main_branch("user-1").unwrap();

        let stats = graph.stats("user-1").unwrap();
        assert_eq!(stats.total_edges, 2);
        assert_eq!(stats.inferred_edges, 1);
        assert_eq!(stats.explicit_edges, 1);
        assert_eq!(stats.total_branches, 1);
    }

    // =========================================================================
    // Observation type inference tests (#205)
    // =========================================================================

    #[test]
    fn test_infer_observation_to_task() {
        let (graph, _dir) = create_test_graph();
        let obs = create_test_memory(ExperienceType::Observation, vec!["auth", "login"]);
        let mut task = create_test_memory(ExperienceType::Task, vec!["auth", "login"]);
        task.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &task);
        assert!(result.is_some(), "Observation → Task should infer");
        let (relation, confidence) = result.unwrap();
        assert_eq!(relation, CausalRelation::TriggeredBy);
        assert!(confidence > 0.3, "confidence was {}", confidence);
    }

    #[test]
    fn test_infer_observation_to_decision() {
        let (graph, _dir) = create_test_graph();
        let obs = create_test_memory(ExperienceType::Observation, vec!["perf", "latency"]);
        let mut decision =
            create_test_memory(ExperienceType::Decision, vec!["perf", "latency", "cache"]);
        decision.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &decision);
        assert!(result.is_some(), "Observation → Decision should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::InformedBy);
    }

    #[test]
    fn test_infer_observation_to_error() {
        let (graph, _dir) = create_test_graph();
        let obs = create_test_memory(ExperienceType::Observation, vec!["mutex", "deadlock"]);
        let mut error = create_test_memory(ExperienceType::Error, vec!["mutex", "deadlock"]);
        error.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &error);
        assert!(result.is_some(), "Observation → Error should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::Caused);
    }

    #[test]
    fn test_infer_observation_to_learning() {
        let (graph, _dir) = create_test_graph();
        let obs = create_test_memory(ExperienceType::Observation, vec!["rocksdb", "column"]);
        let mut learning = create_test_memory(
            ExperienceType::Learning,
            vec!["rocksdb", "column", "family"],
        );
        learning.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &learning);
        assert!(result.is_some(), "Observation → Learning should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::TriggeredBy);
    }

    // =========================================================================
    // Conversation type inference tests (#205)
    // =========================================================================

    #[test]
    fn test_infer_conversation_to_decision() {
        let (graph, _dir) = create_test_graph();
        let conv = create_test_memory(ExperienceType::Conversation, vec!["api", "design"]);
        let mut decision =
            create_test_memory(ExperienceType::Decision, vec!["api", "design", "rest"]);
        decision.created_at = conv.created_at + Duration::days(1);

        let result = graph.infer_relation(&conv, &decision);
        assert!(result.is_some(), "Conversation → Decision should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::InformedBy);
    }

    #[test]
    fn test_infer_conversation_to_task() {
        let (graph, _dir) = create_test_graph();
        let conv = create_test_memory(ExperienceType::Conversation, vec!["bug", "deploy"]);
        let mut task = create_test_memory(ExperienceType::Task, vec!["bug", "deploy"]);
        task.created_at = conv.created_at + Duration::days(1);

        let result = graph.infer_relation(&conv, &task);
        assert!(result.is_some(), "Conversation → Task should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::TriggeredBy);
    }

    #[test]
    fn test_infer_conversation_to_learning() {
        let (graph, _dir) = create_test_graph();
        let conv = create_test_memory(ExperienceType::Conversation, vec!["hebbian", "memory"]);
        let mut learning =
            create_test_memory(ExperienceType::Learning, vec!["hebbian", "memory", "decay"]);
        learning.created_at = conv.created_at + Duration::days(1);

        let result = graph.infer_relation(&conv, &learning);
        assert!(result.is_some(), "Conversation → Learning should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::InformedBy);
    }

    #[test]
    fn test_infer_conversation_to_error() {
        let (graph, _dir) = create_test_graph();
        let conv = create_test_memory(ExperienceType::Conversation, vec!["auth", "token"]);
        let mut error = create_test_memory(ExperienceType::Error, vec!["auth", "token"]);
        error.created_at = conv.created_at + Duration::days(1);

        let result = graph.infer_relation(&conv, &error);
        assert!(result.is_some(), "Conversation → Error should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::Caused);
    }

    #[test]
    fn test_infer_conversation_to_discovery() {
        let (graph, _dir) = create_test_graph();
        let conv = create_test_memory(ExperienceType::Conversation, vec!["graph", "edge"]);
        let mut discovery =
            create_test_memory(ExperienceType::Discovery, vec!["graph", "edge", "weight"]);
        discovery.created_at = conv.created_at + Duration::days(1);

        let result = graph.infer_relation(&conv, &discovery);
        assert!(result.is_some(), "Conversation → Discovery should infer");
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::TriggeredBy);
    }

    // =========================================================================
    // Bridge type tests — reverse direction (action → Observation/Conversation)
    // =========================================================================

    #[test]
    fn test_infer_decision_to_observation_related() {
        let (graph, _dir) = create_test_graph();
        let decision = create_test_memory(ExperienceType::Decision, vec!["cache", "redis"]);
        let mut obs = create_test_memory(ExperienceType::Observation, vec!["cache", "redis"]);
        obs.created_at = decision.created_at + Duration::days(1);

        let result = graph.infer_relation(&decision, &obs);
        assert!(
            result.is_some(),
            "Decision → Observation should produce RelatedTo via bridge"
        );
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::RelatedTo);
    }

    #[test]
    fn test_infer_task_to_conversation_related() {
        let (graph, _dir) = create_test_graph();
        let task = create_test_memory(ExperienceType::Task, vec!["deploy", "staging"]);
        let mut conv = create_test_memory(ExperienceType::Conversation, vec!["deploy", "staging"]);
        conv.created_at = task.created_at + Duration::days(1);

        let result = graph.infer_relation(&task, &conv);
        assert!(
            result.is_some(),
            "Task → Conversation should produce RelatedTo via bridge"
        );
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::RelatedTo);
    }

    #[test]
    fn test_observation_no_entities_still_bridges() {
        let (graph, _dir) = create_test_graph();
        // No entities — tests the 0.3 floor path
        let obs = create_test_memory(ExperienceType::Observation, vec![]);
        let mut task = create_test_memory(ExperienceType::Task, vec![]);
        task.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &task);
        assert!(
            result.is_some(),
            "Observation → Task should infer even without entities"
        );
        let (relation, confidence) = result.unwrap();
        assert_eq!(relation, CausalRelation::TriggeredBy);
        // With no entities: effective_overlap=0.3, temporal_factor≈0.97
        // base * 0.85 * 0.3 * (0.5 + 0.5*0.97) ≈ 0.75 * 0.85 * 0.3 * 0.985 ≈ 0.19
        assert!(
            confidence > 0.1,
            "low-entity confidence should still be nonzero, was {}",
            confidence
        );
    }

    // =========================================================================
    // Embedding similarity tests (#208)
    // =========================================================================

    fn create_test_memory_with_embeddings(
        exp_type: ExperienceType,
        entities: Vec<&str>,
        embeddings: Option<Vec<f32>>,
    ) -> Memory {
        let experience = Experience {
            experience_type: exp_type,
            content: "Test memory".to_string(),
            entities: entities.into_iter().map(|s| s.to_string()).collect(),
            embeddings,
            ..Default::default()
        };
        Memory::new(
            MemoryId(Uuid::new_v4()),
            experience,
            0.5,
            None,
            None,
            None,
            None,
        )
    }

    #[test]
    fn test_infer_with_high_embedding_similarity() {
        let (graph, _dir) = create_test_graph();

        // High cosine similarity embeddings (identical), no entity overlap
        let emb = vec![0.1, 0.5, 0.8, 0.3, 0.9];
        let obs = create_test_memory_with_embeddings(
            ExperienceType::Observation,
            vec![],
            Some(emb.clone()),
        );
        let mut task = create_test_memory_with_embeddings(ExperienceType::Task, vec![], Some(emb));
        task.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &task);
        assert!(
            result.is_some(),
            "High embedding similarity should produce inference even without entities"
        );
        let (relation, confidence) = result.unwrap();
        assert_eq!(relation, CausalRelation::TriggeredBy);
        // cosine_sim=1.0, entity_overlap=0.0, semantic_signal=max(0,1)=1.0
        assert!(confidence > 0.4, "confidence was {}", confidence);
    }

    #[test]
    fn test_infer_embedding_rescues_low_entity_overlap() {
        let (graph, _dir) = create_test_graph();

        // Low entity overlap but high embedding similarity
        let emb_a = vec![0.1, 0.5, 0.8, 0.3, 0.9];
        let emb_b = vec![0.12, 0.48, 0.82, 0.28, 0.88]; // very similar
        let learning =
            create_test_memory_with_embeddings(ExperienceType::Learning, vec!["rust"], Some(emb_a));
        let mut decision = create_test_memory_with_embeddings(
            ExperienceType::Decision,
            vec!["go", "lang", "rust"],
            Some(emb_b),
        );
        decision.created_at = learning.created_at + Duration::days(1);

        let result = graph.infer_relation(&learning, &decision);
        assert!(
            result.is_some(),
            "Embedding similarity should rescue low entity overlap"
        );
        let (relation, _) = result.unwrap();
        assert_eq!(relation, CausalRelation::InformedBy);
    }

    #[test]
    fn test_infer_low_embedding_similarity_blocked() {
        let (graph, _dir) = create_test_graph();

        // Low embedding similarity, no entities
        let emb_a = vec![1.0, 0.0, 0.0, 0.0, 0.0];
        let emb_b = vec![0.0, 0.0, 0.0, 0.0, 1.0]; // orthogonal
        let obs =
            create_test_memory_with_embeddings(ExperienceType::Observation, vec![], Some(emb_a));
        let mut task =
            create_test_memory_with_embeddings(ExperienceType::Task, vec![], Some(emb_b));
        task.created_at = obs.created_at + Duration::days(1);

        let result = graph.infer_relation(&obs, &task);
        assert!(
            result.is_none(),
            "Orthogonal embeddings with no entities should block inference"
        );
    }

    #[test]
    fn test_weaken_uses_090_multiplier() {
        let mut edge = LineageEdge::inferred(
            MemoryId(Uuid::new_v4()),
            MemoryId(Uuid::new_v4()),
            CausalRelation::Caused,
            1.0,
        );

        // First weakening: 1.0 * 0.90 = 0.90
        let should_prune = edge.weaken();
        assert!(!should_prune);
        assert!(
            (edge.confidence - 0.90).abs() < 0.001,
            "expected ~0.90, got {}",
            edge.confidence
        );

        // After many weakenings, should eventually prune
        for _ in 0..50 {
            edge.weaken();
        }
        assert!(
            edge.confidence < 0.05,
            "should be below prune threshold after 50 weakenings"
        );
    }
}