mindreader 0.5.0

Selective durable graph memory MCP server for AI agents, backed by Neo4j
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
//! Permanent same-kind unify and advisory duplicate suggestions.
//!
//! MCP `unify` calls [`memory_unify`]: source memberships, history, and
//! edges move onto a surviving target of the same canonical kind, with no
//! `scope` filter. Bootstrap-seeded Class/Property IRIs cannot be sources.
//! `write` and `revise` may attach [`merge_suggestions_in_txn`] results as
//! review-only `{source,target}` IRI pairs.

use crate::domain::{DomainError, NodeHandle};
use crate::graph::{
    acquire_fact_locks_in_txn, create_episode_in_txn, fetch_all_txn, fetch_one_txn, node_json,
    Episode,
};
use crate::iri::identity_kind_from_labels;
use crate::payload::{finish_mutation, unify_review_item};
use crate::vocabulary::{is_bootstrap_seeded, is_system_relationship, structural_relationship_for};
use crate::{
    error::{Error, Result},
    operation_error,
};
use neo4rs::{query, BoltType, Graph, Node, Relation, Txn};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use tokio::time::{sleep, Duration};

const FORBIDDEN_ENTITY_LABELS: &[&str] = &[
    "Literal",
    "Episode",
    "FactLock",
    "MindreaderMeta",
    "SemanticActivation",
    "TTL",
];
const FACT_LOCK_SCOPE: &str = "@fact";
const LAYERS_PROPERTY: &str = "mindreader:property/layers";
const PREDICATE_USAGE_PROPERTY: &str = "mindreader:property/predicate-usage";
const WEIGHT_PROPERTY: &str = "mindreader:property/weight";

/// Escape a display name and append `~2` for the keyword merge-candidate index.
fn lucene_fuzzy_term(name: &str) -> String {
    let mut query = String::with_capacity(name.len() + 3);
    for character in name.to_lowercase().chars() {
        if character.is_whitespace() || "+-&|!(){}[]^\"~*?:\\/".contains(character) {
            query.push('\\');
        }
        query.push(character);
    }
    query.push_str("~2");
    query
}

/// MCP `unify` arguments: surviving `target` node absorbs `source`.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UnifyArgs {
    /// Same-kind node permanently absorbed; bootstrap-seeded IRIs cannot be sources.
    pub source: NodeHandle,
    /// Surviving node whose IRI and name remain.
    pub target: NodeHandle,
}

impl UnifyArgs {
    /// Build unify arguments from two node IRIs (smoke, bench, and in-process callers).
    #[cfg(feature = "developer-tools")]
    pub fn from_iris(source: impl Into<String>, target: impl Into<String>) -> Self {
        Self {
            source: NodeHandle::from_iri(source),
            target: NodeHandle::from_iri(target),
        }
    }
}

/// Permanent same-kind `unify` with no `scope` filter: source memberships, edges, and history move onto `target`.
///
/// Bootstrap-seeded IRIs cannot be sources. Retries Neo4j transients and lock-set drift (`ConcurrentMutation`).
pub async fn memory_unify(graph: &Graph, args: UnifyArgs) -> Result<Value> {
    for attempt in 0..3_u64 {
        match memory_unify_once(graph, &args).await {
            Err(error) if attempt < 2 && is_transient(&error) => {
                sleep(Duration::from_millis(25 * (attempt + 1))).await;
            }
            result => return result,
        }
    }
    unreachable!("bounded retry loop always returns")
}

/// Retry unify on Neo4j transients and lock-set drift (`ConcurrentMutation`).
fn is_transient(error: &Error) -> bool {
    error.is_transient_neo4j() || matches!(error, Error::ConcurrentMutation(_))
}

/// One unify attempt: validate kinds, move history in one transaction, commit or roll back.
async fn memory_unify_once(graph: &Graph, args: &UnifyArgs) -> Result<Value> {
    let source = args.source.iri()?.to_string();
    let target = args.target.iri()?.to_string();
    let source = source.as_str();
    let target = target.as_str();
    if source.is_empty() || target.is_empty() {
        return Err(DomainError::InvalidInput("source and target must not be empty".into()).into());
    }
    if source == target {
        return Err(DomainError::InvalidInput("source and target must be different".into()).into());
    }
    if is_bootstrap_seeded(source) {
        return Err(DomainError::InvalidInput(
            "bootstrap-seeded Class and Property IRIs cannot be merge sources".into(),
        )
        .into());
    }
    let mut txn = graph.start_txn().await?;
    let result = merge_in_txn(&mut txn, source, target).await;
    match result {
        Ok(node) => {
            txn.commit()
                .await
                .map_err(|source| Error::AmbiguousCommit {
                    operation: "unify",
                    source,
                })?;
            Ok(node)
        }
        Err(error) => {
            let _ = txn.rollback().await;
            Err(error)
        }
    }
}

/// Subject/predicate guards for every current edge that names `source` or `target`.
async fn affected_fact_locks_in_txn(
    txn: &mut Txn,
    source_iri: &str,
    target_iri: &str,
) -> Result<Vec<(String, String, String)>> {
    let mut locks = fetch_all_txn(
        txn,
        query(
            "MATCH (s:Entity)-[r]->(o:Entity) \
             WHERE s.iri IN [$source, $target] OR o.iri IN [$source, $target] \
                OR r.propertyIri IN [$source, $target] \
             WITH DISTINCT s, r \
             UNWIND [ \
               {subject: s.iri, property: r.propertyIri}, \
               {subject: r.iri, property: $weightProperty} \
             ] AS guard \
             RETURN DISTINCT guard.subject AS subject, guard.property AS property",
        )
        .param("source", source_iri.to_string())
        .param("target", target_iri.to_string())
        .param("weightProperty", WEIGHT_PROPERTY),
    )
    .await?
    .into_iter()
    .map(|row| {
        Ok::<_, Error>((
            row.get::<String>("subject")?,
            row.get::<String>("property")?,
            FACT_LOCK_SCOPE.into(),
        ))
    })
    .collect::<Result<Vec<_>>>()?;
    locks.sort();
    locks.dedup();
    Ok(locks)
}

/// Absorb `source` into `target` in one transaction: lock, merge nodes, rewrite predicates, consolidate dupes.
async fn merge_in_txn(txn: &mut Txn, source_iri: &str, target_iri: &str) -> Result<Value> {
    let initial_affected = affected_fact_locks_in_txn(txn, source_iri, target_iri).await?;
    let mut locks = vec![
        (
            source_iri.into(),
            PREDICATE_USAGE_PROPERTY.into(),
            FACT_LOCK_SCOPE.into(),
        ),
        (
            target_iri.into(),
            PREDICATE_USAGE_PROPERTY.into(),
            FACT_LOCK_SCOPE.into(),
        ),
        (
            source_iri.into(),
            LAYERS_PROPERTY.into(),
            FACT_LOCK_SCOPE.into(),
        ),
        (
            source_iri.into(),
            WEIGHT_PROPERTY.into(),
            FACT_LOCK_SCOPE.into(),
        ),
        (
            target_iri.into(),
            LAYERS_PROPERTY.into(),
            FACT_LOCK_SCOPE.into(),
        ),
        (
            target_iri.into(),
            WEIGHT_PROPERTY.into(),
            FACT_LOCK_SCOPE.into(),
        ),
    ];
    locks.extend(initial_affected.iter().cloned());
    acquire_fact_locks_in_txn(txn, &locks).await?;
    let locked_affected = affected_fact_locks_in_txn(txn, source_iri, target_iri).await?;
    if locked_affected != initial_affected {
        return Err(Error::ConcurrentMutation(
            "the relationships affected by unify; retry the operation".into(),
        ));
    }
    let row = fetch_one_txn(
        txn,
        query(
            "MATCH (source:Entity {iri: $source}), (target:Entity {iri: $target}) \
             RETURN source, target",
        )
        .param("source", source_iri.to_string())
        .param("target", target_iri.to_string()),
    )
    .await?
    .ok_or_else(|| {
        DomainError::Precondition(format!(
            "source {source_iri} and target {target_iri} must both exist"
        ))
    })?;
    let source: Node = row.get("source")?;
    let target: Node = row.get("target")?;
    reject_internal_node(&source, "source")?;
    reject_internal_node(&target, "target")?;
    let kind = require_same_kind(&source, &target)?;
    let property_merge = kind == "Property";
    if property_merge {
        require_compatible_property_merge(source_iri, target_iri)?;
    }

    let source_layers = source.get::<Vec<String>>("layers")?;
    let target_layers = target.get::<Vec<String>>("layers")?;
    let layers = merge_memberships(&target_layers, &source_layers);
    let weight = node_weight(&target)?.saturating_add(node_weight(&source)?);
    let episode = create_episode_in_txn(txn, "unify", None).await?;

    let source_relationships_row = fetch_all_txn(
        txn,
        query(
            "MATCH (source:Entity {iri: $source})-[r]-() \
             RETURN collect(DISTINCT r.iri) AS iris",
        )
        .param("source", source_iri.to_string()),
    )
    .await?
    .into_iter()
    .next()
    .ok_or_else(|| operation_error!("source relationship lookup returned no row"))?;
    let source_relationships = source_relationships_row.get::<Vec<String>>("iris")?;

    txn.run(
        query(
            "MATCH (source:Entity {iri: $source})-[r]-(target:Entity {iri: $target}) \
             WHERE r.validTo IS NULL \
             SET r.validTo = datetime(), r.mergeEpisodeId = $episode",
        )
        .param("source", source_iri.to_string())
        .param("target", target_iri.to_string())
        .param("episode", episode.iri.clone()),
    )
    .await?;

    let merged = fetch_one_txn(
        txn,
        query(
            r#"
            MATCH (source:Entity {iri: $source}), (target:Entity {iri: $target})
            WITH source, target
            CALL apoc.refactor.mergeNodes(
              [target, source],
              {properties: 'discard', mergeRels: false,
               produceSelfRel: true, preserveExistingSelfRels: true}
            ) YIELD node
            SET node.layers = $layers,
                node.weight = $weight,
                node.mergeName = toLower(coalesce(node.name, '')),
                node.searchText = trim(coalesce(node.name, '') + ' ' + node.iri + ' ' + coalesce(node.value, '')),
                node.mergeEpisodeId = $episode
            RETURN node
            "#,
        )
        .param("source", source_iri.to_string())
        .param("target", target_iri.to_string())
        .param("layers", layers)
        .param("weight", weight)
        .param("episode", episode.iri.clone()),
    )
    .await?
    .ok_or_else(|| operation_error!("APOC did not return the merged target node"))?;
    let merged_node: Node = merged.get("node")?;

    if !source_relationships.is_empty() {
        txn.run(
            query(
                "MATCH ()-[r]->() WHERE r.iri IN $iris \
                 SET r.mergeEpisodeId = $episode",
            )
            .param("iris", source_relationships)
            .param("episode", episode.iri.clone()),
        )
        .await?;
    }
    if property_merge {
        txn.run(
            query(
                "MATCH ()-[r]->() WHERE r.propertyIri = $source \
                 SET r.propertyIri = $target, r.mergeEpisodeId = $episode",
            )
            .param("source", source_iri.to_string())
            .param("target", target_iri.to_string())
            .param("episode", episode.iri.clone()),
        )
        .await?;
    }
    txn.run(
        query(
            r#"
            MATCH (s:Entity)-[r]->(o:Entity)
            WHERE r.mergeEpisodeId = $episode
               OR ($propertyMerge AND r.propertyIri = $target)
            WITH s, r, o,
                 r.propertyIri AS property
            WITH s, r, o,
                 CASE
                   WHEN property CONTAINS '/' THEN last(split(property, '/'))
                   WHEN property CONTAINS ':' THEN last(split(property, ':'))
                   ELSE property
                 END AS propertyName
            SET r.factText = trim(
              coalesce(s.name, s.iri) + ' ' + propertyName + ' ' +
              coalesce(o.value, o.name, o.iri)
            )
            "#,
        )
        .param("episode", episode.iri.clone())
        .param("propertyMerge", property_merge)
        .param("target", target_iri.to_string()),
    )
    .await?;
    consolidate_current_duplicates(txn, target_iri, property_merge, &episode).await?;
    let node = node_json(&merged_node)?;
    let current = node.get("target").cloned();
    finish_mutation(
        json!({
            "ok": true,
            "noop": false,
            "node": node.clone(),
            "episode": {
                "iri": episode.iri,
                "at": episode.at,
                "tool": episode.tool,
            },
        }),
        &[],
        &[node],
        current,
        None,
    )
}

/// Minimum Levenshtein similarity for advisory unify suggestions.
const MERGE_SIMILARITY_FLOOR: f64 = 0.85;
/// Stricter floor for Property suggestions.
const PROPERTY_MERGE_SIMILARITY_FLOOR: f64 = 0.92;

/// Whether an advisory unify suggestion clears the kind-specific similarity floor.
pub(crate) fn merge_similarity_accepted(kind: &str, similarity: f64) -> bool {
    if kind == "Property" {
        similarity >= PROPERTY_MERGE_SIMILARITY_FLOOR
    } else {
        similarity >= MERGE_SIMILARITY_FLOOR
    }
}

/// Require both nodes to share the same identity kind (Class, Property, or Element).
fn require_same_kind(source: &Node, target: &Node) -> Result<String> {
    let source_kind = identity_kind_from_labels(source.labels());
    let target_kind = identity_kind_from_labels(target.labels());
    match (source_kind, target_kind) {
        (Some(source_kind), Some(target_kind)) if source_kind == target_kind => {
            Ok(source_kind.to_string())
        }
        _ => Err(DomainError::InvalidInput(
            "source and target must have the same single canonical kind".into(),
        )
        .into()),
    }
}

/// Forbid merging system-owned Properties or Properties with different structural types.
fn require_compatible_property_merge(source_iri: &str, target_iri: &str) -> Result<()> {
    let source_rel = structural_relationship_for(source_iri);
    let target_rel = structural_relationship_for(target_iri);
    if is_system_relationship(source_iri) || is_system_relationship(target_iri) {
        return Err(DomainError::InvalidInput(
            "system-owned CONTRADICTS and SUPERSEDES Properties cannot be merged".into(),
        )
        .into());
    }
    if source_rel != target_rel {
        return Err(DomainError::InvalidInput(
            "Properties can be merged only when both use the same structural relationship type"
                .into(),
        )
        .into());
    }
    Ok(())
}

/// Reject Literal, Episode, lock, meta, and activation nodes as unify endpoints.
fn reject_internal_node(node: &Node, field: &str) -> Result<()> {
    if node.labels().iter().any(|label| {
        FORBIDDEN_ENTITY_LABELS
            .iter()
            .any(|internal| label == internal)
    }) {
        return Err(DomainError::InvalidInput(format!(
            "{field} must be a user-visible non-literal entity"
        ))
        .into());
    }
    Ok(())
}

/// Signed judgment weight stored on the node (saturating-added onto the survivor).
fn node_weight(node: &Node) -> Result<i64> {
    Ok(node.get::<i64>("weight")?)
}

/// Signed judgment weight stored on a current fact (saturating-added during dupe collapse).
fn relation_weight(relation: &Relation) -> Result<i64> {
    Ok(relation.get::<i64>("weight")?)
}

/// Union named memberships; either empty list is global and wins.
fn merge_memberships(left: &[String], right: &[String]) -> Vec<String> {
    if left.is_empty() || right.is_empty() {
        return Vec::new();
    }
    left.iter()
        .chain(right)
        .cloned()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

/// Current fact that collided with another `(s, type, property, o)` after unify.
#[derive(Clone)]
struct DuplicateFact {
    iri: String,
    layers: Vec<String>,
    weight: i64,
    episodes: Vec<String>,
}

/// Membership, weight, and provenance written onto the surviving duplicate fact.
#[derive(Debug, PartialEq)]
struct SurvivorUpdate {
    iri: String,
    layers: Vec<String>,
    weight: i64,
    provenance: Vec<String>,
}

/// Soft-retired duplicate fact (`validTo`) pointing at the surviving IRI.
#[derive(Debug, PartialEq)]
struct DuplicateRetirement {
    iri: String,
    survivor: String,
}

/// Exact current relationship identity, including optional world-time qualification.
type FactIdentity = (
    String,
    String,
    String,
    String,
    bool,
    Option<String>,
    Option<String>,
);

/// Keep the lowest IRI in each exact-triple group; merge memberships, weights, and provenance.
fn duplicate_consolidation_plan(
    groups: &mut BTreeMap<FactIdentity, Vec<DuplicateFact>>,
) -> (Vec<SurvivorUpdate>, Vec<DuplicateRetirement>) {
    let mut updates = Vec::new();
    let mut retirements = Vec::new();
    for facts in groups.values_mut().filter(|facts| facts.len() > 1) {
        facts.sort_by(|left, right| left.iri.cmp(&right.iri));
        let survivor = facts[0].iri.clone();
        let mut layers = facts[0].layers.clone();
        let mut weight = 0_i64;
        let mut provenance = BTreeSet::new();
        for fact in facts.iter() {
            layers = merge_memberships(&layers, &fact.layers);
            weight = weight.saturating_add(fact.weight);
            provenance.extend(fact.episodes.iter().cloned());
        }
        updates.push(SurvivorUpdate {
            iri: survivor.clone(),
            layers,
            weight,
            provenance: provenance.into_iter().collect(),
        });
        retirements.extend(facts.iter().skip(1).map(|fact| DuplicateRetirement {
            iri: fact.iri.clone(),
            survivor: survivor.clone(),
        }));
    }
    (updates, retirements)
}

/// Bolt maps for the batched survivor `SET` after duplicate collapse.
fn survivor_update_params(updates: &[SurvivorUpdate]) -> Vec<HashMap<String, BoltType>> {
    updates
        .iter()
        .map(|update| {
            HashMap::from([
                ("iri".into(), update.iri.clone().into()),
                ("layers".into(), update.layers.clone().into()),
                ("weight".into(), update.weight.into()),
                ("provenance".into(), update.provenance.clone().into()),
            ])
        })
        .collect()
}

/// Bolt maps that soft-retire absorbed duplicate facts (`validTo` + `mergedInto`).
fn duplicate_retirement_params(
    retirements: &[DuplicateRetirement],
) -> Vec<HashMap<String, String>> {
    retirements
        .iter()
        .map(|retirement| {
            HashMap::from([
                ("iri".into(), retirement.iri.clone()),
                ("survivor".into(), retirement.survivor.clone()),
            ])
        })
        .collect()
}

/// Collapse exact current triples that became duplicates after the node merge.
async fn consolidate_current_duplicates(
    txn: &mut Txn,
    target_iri: &str,
    include_property_facts: bool,
    episode: &Episode,
) -> Result<()> {
    let rows = fetch_all_txn(
        txn,
        query(
            "MATCH (s:Entity)-[r]->(o:Entity) \
             WHERE r.validTo IS NULL AND (s.iri = $target OR o.iri = $target \
                OR ($includePropertyFacts AND r.propertyIri = $target)) \
             RETURN s.iri AS s, type(r) AS type, r.propertyIri AS property, \
                    o.iri AS o, coalesce(r.effectiveQualified, false) AS effectiveQualified, \
                    toString(r.effectiveFrom) AS effectiveFrom, \
                    toString(r.effectiveTo) AS effectiveTo, r",
        )
        .param("target", target_iri.to_string())
        .param("includePropertyFacts", include_property_facts),
    )
    .await?;
    let mut groups: BTreeMap<FactIdentity, Vec<DuplicateFact>> = BTreeMap::new();
    for row in rows {
        let relation: Relation = row.get("r")?;
        let iri = relation.get::<String>("iri")?;
        let mut episodes = relation
            .get::<Vec<String>>("provenanceEpisodeIds")
            .unwrap_or_default();
        if let Ok(original) = relation.get::<String>("episodeId") {
            episodes.push(original);
        }
        episodes.sort();
        episodes.dedup();
        groups
            .entry((
                row.get("s")?,
                row.get("type")?,
                row.get("property")?,
                row.get("o")?,
                row.get("effectiveQualified")?,
                row.get::<String>("effectiveFrom").ok(),
                row.get::<String>("effectiveTo").ok(),
            ))
            .or_default()
            .push(DuplicateFact {
                iri,
                layers: relation.get::<Vec<String>>("layers")?,
                weight: relation_weight(&relation)?,
                episodes,
            });
    }
    let (updates, retirements) = duplicate_consolidation_plan(&mut groups);
    if !updates.is_empty() {
        let expected = updates.len() as i64;
        let row = fetch_one_txn(
            txn,
            query(
                "UNWIND $updates AS update \
                 MATCH ()-[r]->() WHERE r.iri = update.iri AND r.validTo IS NULL \
                 SET r.layers = update.layers, r.weight = update.weight, \
                     r.provenanceEpisodeIds = update.provenance, r.mergeEpisodeId = $episode \
                 RETURN count(r) AS updated",
            )
            .param("updates", survivor_update_params(&updates))
            .param("episode", episode.iri.clone()),
        )
        .await?
        .ok_or_else(|| operation_error!("duplicate survivor update returned no count"))?;
        let updated = row.get::<i64>("updated")?;
        if updated != expected {
            return Err(operation_error!(
                "duplicate survivor update affected {updated} relationships; expected {expected}"
            ));
        }
    }
    if !retirements.is_empty() {
        let expected = retirements.len() as i64;
        let row = fetch_one_txn(
            txn,
            query(
                "UNWIND $retirements AS retirement \
                 MATCH ()-[r]->() WHERE r.iri = retirement.iri AND r.validTo IS NULL \
                 SET r.validTo = datetime(), r.mergedInto = retirement.survivor, \
                     r.mergeEpisodeId = $episode \
                 RETURN count(r) AS retired",
            )
            .param("retirements", duplicate_retirement_params(&retirements))
            .param("episode", episode.iri.clone()),
        )
        .await?
        .ok_or_else(|| operation_error!("duplicate retirement returned no count"))?;
        let retired = row.get::<i64>("retired")?;
        if retired != expected {
            return Err(operation_error!(
                "duplicate retirement affected {retired} relationships; expected {expected}"
            ));
        }
    }
    Ok(())
}

/// Advisory fuzzy name matches for newly created IRIs; never auto-merges.
pub async fn merge_suggestions_in_txn(
    txn: &mut Txn,
    created_iris: &[String],
    layers: &[String],
) -> Result<Vec<Value>> {
    if created_iris.is_empty() {
        return Ok(Vec::new());
    }
    let mut suggestions = Vec::new();
    let created_set = created_iris.iter().cloned().collect::<BTreeSet<_>>();
    let created_specs = fetch_all_txn(
        txn,
        query(
            "UNWIND $createdIris AS iri \
             MATCH (created:Entity {iri: iri}) \
             WHERE created.name IS NOT NULL AND created.name <> '' \
             RETURN created.iri AS iri, created.name AS name",
        )
        .param("createdIris", created_iris.to_vec()),
    )
    .await?
    .into_iter()
    .map(|row| {
        let iri = row.get::<String>("iri")?;
        let name = row.get::<String>("name")?;
        Ok(HashMap::from([
            ("iri".to_string(), iri),
            ("nameQuery".to_string(), lucene_fuzzy_term(&name)),
        ]))
    })
    .collect::<Result<Vec<_>>>()?;
    if created_specs.is_empty() {
        return Ok(Vec::new());
    }
    let rows = fetch_all_txn(
        txn,
        query(
            r#"
            UNWIND $created AS spec
            MATCH (created:Entity {iri: spec.iri})
            CALL {
              WITH created, spec
              CALL db.index.fulltext.queryNodes('merge_candidate_names', spec.nameQuery)
              YIELD node
              RETURN node AS candidate
              UNION
              WITH created, spec
              MATCH (candidate:Entity)
              WHERE candidate.iri IN $createdIris
              RETURN candidate
            }
            WITH created, candidate
            WHERE candidate <> created
              AND candidate.name IS NOT NULL
              AND (size(candidate.layers) = 0
                   OR any(layer IN candidate.layers WHERE layer IN $layers))
              AND none(label IN labels(created) WHERE label IN $forbidden)
              AND none(label IN labels(candidate) WHERE label IN $forbidden)
              AND apoc.text.fuzzyMatch(toLower(created.name), toLower(candidate.name))
            WITH created, candidate,
                 CASE
                   WHEN created:Class THEN 'Class'
                   WHEN created:Property THEN 'Property'
                   WHEN created:Element THEN 'Element'
                   ELSE null
                 END AS createdKind,
                 CASE
                   WHEN candidate:Class THEN 'Class'
                   WHEN candidate:Property THEN 'Property'
                   WHEN candidate:Element THEN 'Element'
                   ELSE null
                 END AS candidateKind,
                 apoc.text.levenshteinSimilarity(
                   toLower(created.name), toLower(candidate.name)
                 ) AS similarity
            WHERE createdKind IS NOT NULL
              AND createdKind = candidateKind
              AND similarity >= $similarityFloor
              AND (createdKind <> 'Property' OR similarity >= $propertyFloor)
            ORDER BY created.iri ASC, similarity DESC,
                     size(candidate.name) ASC, candidate.iri ASC
            WITH created, collect({
              candidateIri: candidate.iri,
              candidateName: candidate.name,
              canonicalKind: createdKind,
              similarity: similarity
            })[..3] AS candidates
            UNWIND candidates AS candidate
            RETURN created.iri AS createdIri, created.name AS createdName,
                   candidate.candidateIri AS candidateIri,
                   candidate.candidateName AS candidateName,
                   candidate.canonicalKind AS canonicalKind,
                   candidate.similarity AS similarity
            "#,
        )
        .param("created", created_specs)
        .param("createdIris", created_iris.to_vec())
        .param("layers", layers.to_vec())
        .param(
            "forbidden",
            FORBIDDEN_ENTITY_LABELS
                .iter()
                .map(|label| label.to_string())
                .collect::<Vec<_>>(),
        )
        .param("similarityFloor", MERGE_SIMILARITY_FLOOR)
        .param("propertyFloor", PROPERTY_MERGE_SIMILARITY_FLOOR),
    )
    .await?;
    for row in rows {
        let created_iri: String = row.get("createdIri")?;
        let created_name: String = row.get("createdName")?;
        let candidate_iri: String = row.get("candidateIri")?;
        let candidate_name: String = row.get("candidateName")?;
        let canonical_kind: String = row.get("canonicalKind")?;
        let similarity: f64 = row.get("similarity")?;
        if !merge_similarity_accepted(&canonical_kind, similarity) {
            continue;
        }
        if canonical_kind == "Property"
            && require_compatible_property_merge(&created_iri, &candidate_iri).is_err()
        {
            continue;
        }
        // Orient review pairs so bootstrap seeds stay targets; else shorter name, then lower created IRI.
        let candidate_was_created = created_set.contains(&candidate_iri);
        let created_first_on_tie = candidate_was_created && created_iri < candidate_iri;
        let created_is_target = is_bootstrap_seeded(&created_iri)
            || (!is_bootstrap_seeded(&candidate_iri)
                && (created_name.chars().count() < candidate_name.chars().count()
                    || (created_name.chars().count() == candidate_name.chars().count()
                        && created_first_on_tie)));
        let (source, source_name, target, target_name) = if created_is_target {
            (candidate_iri, candidate_name, created_iri, created_name)
        } else {
            (created_iri, created_name, candidate_iri, candidate_name)
        };
        suggestions.push(unify_review_item(
            &source,
            &source_name,
            &target,
            &target_name,
            row.get::<f64>("similarity")?,
        ));
    }
    suggestions.sort_by(|left, right| {
        right["similarity"]
            .as_f64()
            .partial_cmp(&left["similarity"].as_f64())
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| {
                left["source"]["iri"]
                    .as_str()
                    .cmp(&right["source"]["iri"].as_str())
            })
            .then_with(|| {
                left["target"]["iri"]
                    .as_str()
                    .cmp(&right["target"]["iri"].as_str())
            })
    });
    suggestions.dedup_by(|left, right| {
        left["source"]["iri"] == right["source"]["iri"]
            && left["target"]["iri"] == right["target"]["iri"]
    });
    Ok(suggestions)
}

#[cfg(test)]
mod tests {
    use super::{
        duplicate_consolidation_plan, is_transient, lucene_fuzzy_term, merge_memberships,
        merge_similarity_accepted, require_compatible_property_merge, DuplicateFact,
        DuplicateRetirement, SurvivorUpdate, UnifyArgs,
    };
    use crate::error::Error;
    use crate::vocabulary::is_bootstrap_seeded;
    use std::collections::BTreeMap;

    #[test]
    fn global_membership_dominates_merge() {
        assert!(merge_memberships(&[], &["project:a".into()]).is_empty());
        assert_eq!(
            merge_memberships(&["project:b".into()], &["project:a".into()]),
            vec!["project:a", "project:b"]
        );
    }

    #[test]
    fn unify_args_reject_decorated_or_unknown_fields() {
        assert!(serde_json::from_value::<UnifyArgs>(serde_json::json!({
            "source": {"kind": "node", "iri": "mindreader:element/a"},
            "target": {"kind": "node", "iri": "mindreader:element/b"},
            "scope": []
        }))
        .is_err());
    }

    #[test]
    fn merge_similarity_accepted_drops_false_friends() {
        assert!(!merge_similarity_accepted("Element", 0.667));
        assert!(merge_similarity_accepted("Element", 0.96));
        assert!(!merge_similarity_accepted("Property", 0.85));
        assert!(merge_similarity_accepted("Property", 0.96));
    }

    #[test]
    fn property_merges_preserve_relationship_representation() {
        assert!(require_compatible_property_merge(
            "mindreader:property/custom-a",
            "mindreader:property/custom-b"
        )
        .is_ok());
        assert!(
            require_compatible_property_merge("example:ABOUT", "mindreader:property/ABOUT").is_ok()
        );
        assert!(require_compatible_property_merge(
            "mindreader:property/custom",
            "mindreader:property/ABOUT"
        )
        .is_err());
        assert!(require_compatible_property_merge(
            "example:CONTRADICTS",
            "mindreader:property/CONTRADICTS"
        )
        .is_err());
    }

    #[test]
    fn bootstrap_seeded_entities_are_permanent_targets_only() {
        assert!(is_bootstrap_seeded("mindreader:class/Element"));
        assert!(is_bootstrap_seeded("mindreader:property/ABOUT"));
        assert!(!is_bootstrap_seeded("mindreader:property/custom"));
    }

    #[test]
    fn affected_set_drift_is_retryable() {
        assert!(is_transient(&Error::ConcurrentMutation(
            "merge relationships".into()
        )));
    }

    #[test]
    fn fuzzy_candidate_terms_escape_whole_names() {
        assert_eq!(lucene_fuzzy_term("Spaceships"), "spaceships~2");
        assert_eq!(lucene_fuzzy_term("space ship"), "space\\ ship~2");
        assert_eq!(
            lucene_fuzzy_term("C++ / A(B)"),
            "c\\+\\+\\ \\/\\ a\\(b\\)~2"
        );
        assert_eq!(lucene_fuzzy_term("007s"), "007s~2");
    }

    #[test]
    fn duplicate_plan_aggregates_every_group_before_batched_writes() {
        let mut groups = BTreeMap::from([
            (
                (
                    "s-a".into(),
                    "REL".into(),
                    "property-a".into(),
                    "o-a".into(),
                    false,
                    None,
                    None,
                ),
                vec![
                    DuplicateFact {
                        iri: "rel-b".into(),
                        layers: vec!["project:b".into()],
                        weight: 7,
                        episodes: vec!["episode-b".into(), "episode-shared".into()],
                    },
                    DuplicateFact {
                        iri: "rel-a".into(),
                        layers: vec!["project:a".into()],
                        weight: i64::MAX,
                        episodes: vec!["episode-a".into(), "episode-shared".into()],
                    },
                ],
            ),
            (
                (
                    "s-b".into(),
                    "REL".into(),
                    "property-b".into(),
                    "o-b".into(),
                    false,
                    None,
                    None,
                ),
                vec![
                    DuplicateFact {
                        iri: "rel-c".into(),
                        layers: Vec::new(),
                        weight: -3,
                        episodes: vec!["episode-c".into()],
                    },
                    DuplicateFact {
                        iri: "rel-d".into(),
                        layers: vec!["project:d".into()],
                        weight: 1,
                        episodes: vec!["episode-d".into()],
                    },
                ],
            ),
            (
                (
                    "s-c".into(),
                    "REL".into(),
                    "property-c".into(),
                    "o-c".into(),
                    false,
                    None,
                    None,
                ),
                vec![DuplicateFact {
                    iri: "rel-single".into(),
                    layers: vec!["project:single".into()],
                    weight: 4,
                    episodes: vec!["episode-single".into()],
                }],
            ),
        ]);

        let (updates, retirements) = duplicate_consolidation_plan(&mut groups);

        assert_eq!(
            updates,
            vec![
                SurvivorUpdate {
                    iri: "rel-a".into(),
                    layers: vec!["project:a".into(), "project:b".into()],
                    weight: i64::MAX,
                    provenance: vec![
                        "episode-a".into(),
                        "episode-b".into(),
                        "episode-shared".into()
                    ],
                },
                SurvivorUpdate {
                    iri: "rel-c".into(),
                    layers: Vec::new(),
                    weight: -2,
                    provenance: vec!["episode-c".into(), "episode-d".into()],
                },
            ]
        );
        assert_eq!(
            retirements,
            vec![
                DuplicateRetirement {
                    iri: "rel-b".into(),
                    survivor: "rel-a".into(),
                },
                DuplicateRetirement {
                    iri: "rel-d".into(),
                    survivor: "rel-c".into(),
                },
            ]
        );
    }

    #[test]
    fn duplicate_plan_keeps_distinct_effective_intervals() {
        let fact = |iri: &str| DuplicateFact {
            iri: iri.into(),
            layers: vec!["project:x".into()],
            weight: 0,
            episodes: Vec::new(),
        };
        let mut groups = BTreeMap::from([
            (
                (
                    "s".into(),
                    "ASSERTS".into(),
                    "p".into(),
                    "o".into(),
                    true,
                    Some("2020-01-01T00:00:00Z".into()),
                    Some("2021-01-01T00:00:00Z".into()),
                ),
                vec![fact("first")],
            ),
            (
                (
                    "s".into(),
                    "ASSERTS".into(),
                    "p".into(),
                    "o".into(),
                    true,
                    Some("2022-01-01T00:00:00Z".into()),
                    None,
                ),
                vec![fact("second")],
            ),
        ]);
        let (updates, retirements) = duplicate_consolidation_plan(&mut groups);
        assert!(updates.is_empty());
        assert!(retirements.is_empty());
    }
}