mindreader 0.6.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
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
//! Neo4j driver setup, bootstrap, and persistence primitives for the inspectable graph.
//!
//! Owns the model marker, embedding-space marker, full-text and activation vector
//! indexes, Cypher identifier allowlisting, agent-facing node/fact JSON, in-txn
//! MERGE, FactLock writer order, and Episode provenance. Bootstrap is idempotent
//! for the current model marker; incompatible or unversioned non-empty databases
//! fail closed with reset guidance rather than migrating data.

use crate::config::{Config, EmbeddingSpace};
use crate::domain::literal_iri;
use crate::iri::{
    default_lower_for_kind, identity_kind_from_labels, kind_for_label, kind_from_iri,
    label_for_kind, mint_iri, name_from_iri, property_iri, split_camel_case,
};
use crate::vocabulary::SEARCHABLE_RELATIONSHIPS;
use crate::{
    error::{Context, Error, Result},
    graph_error,
};
use chrono::{DateTime, FixedOffset, SecondsFormat, Utc};
use neo4rs::{query, Graph, Node, Path, Relation, Row, Txn, UnboundedRelation};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use uuid::Uuid;

const LABEL_OK: &str = "label";

/// Property key on the singleton model marker node.
pub const MODEL_MARKER_KEY: &str = "model";
/// Current graph model version; incompatible databases must be recreated.
pub const MODEL_VERSION: i64 = 9;
/// Vector index name for expiring semantic activations.
pub const SEMANTIC_INDEX: &str = "semantic_activation_v4_embeddings";
/// Keyword full-text index used for advisory merge candidate names.
pub const MERGE_CANDIDATE_INDEX: &str = "merge_candidate_names";
const EMBEDDING_MARKER_KEY: &str = "embedding";

/// Whether bootstrap may replace an incompatible semantic embedding space.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpaceReplace {
    /// Drop the activation index and stored activations, then rebuild for this process.
    Allow,
    /// Fail closed when the stored provider/model/dimension triple does not match.
    #[cfg(any(feature = "developer-tools", test))]
    Refuse,
}

const RESET_REQUIRED: &str = "recreate the Neo4j database or volume before starting Mindreader";
const REQUIRED_FULLTEXT_INDEXES: &[(&str, &str)] = &[
    ("wakeup_nodes", "NODE"),
    ("wakeup_facts", "RELATIONSHIP"),
    (MERGE_CANDIDATE_INDEX, "NODE"),
];
const WAKEUP_NODE_PROPERTIES: &[&str] = &["name", "iri", "searchText", "value"];

/// Configure the Neo4j driver from the exact endpoint supplied by the user.
pub async fn connect(cfg: &Config) -> Result<Graph> {
    let password = cfg.neo4j_password()?;
    Graph::new(cfg.uri.as_str(), cfg.user.as_str(), password)
        .map_err(Error::from)
        .context(format!("configure Neo4j endpoint {}", cfg.uri))
}

/// Ensure model marker, constraints, indexes, seed catalog, and embedding space for an empty or current-version database.
///
/// Fails closed on an incompatible model marker or unversioned non-empty graph.
/// When an embedding space is configured, applies `space_replace` instead of migrating activations.
pub async fn bootstrap(
    graph: &Graph,
    embedding: Option<&EmbeddingSpace>,
    space_replace: SpaceReplace,
) -> Result<()> {
    ensure_model_marker(graph).await?;
    verify_required_apoc(graph).await?;

    graph
        .run(query(
            "CREATE CONSTRAINT entity_iri IF NOT EXISTS FOR (n:Entity) REQUIRE n.iri IS UNIQUE",
        ))
        .await
        .context("create iri uniqueness constraint")?;
    graph
        .run(query(
            "CREATE CONSTRAINT fact_lock_key IF NOT EXISTS FOR (n:FactLock) REQUIRE n.key IS UNIQUE",
        ))
        .await
        .context("create fact lock key uniqueness constraint")?;

    graph
        .run(query(
            "CREATE FULLTEXT INDEX wakeup_nodes IF NOT EXISTS FOR (n:Entity) ON EACH [n.name, n.iri, n.searchText, n.value]",
        ))
        .await
        .context("create required wakeup_nodes full-text index")?;
    graph
        .run(query(
            "CREATE FULLTEXT INDEX wakeup_facts IF NOT EXISTS FOR ()-[r:ASSERTS|ABOUT|INSTANCE_OF|SUBCLASS_OF|SUBPROPERTY_OF|DOMAIN|RANGE|EVIDENCE_FOR|DERIVED_FROM|SUPPORTS]-() ON EACH [r.factText]",
        ))
        .await
        .context("create required wakeup_facts full-text index")?;
    graph
        .run(query(
            "CREATE FULLTEXT INDEX merge_candidate_names IF NOT EXISTS FOR (n:Entity) ON EACH [n.mergeName] OPTIONS {indexConfig: {`fulltext.analyzer`: 'keyword', `fulltext.eventually_consistent`: false}}",
        ))
        .await
        .context("create required merge_candidate_names full-text index")?;

    if let Some(embedding) = embedding {
        ensure_semantic_index(graph, embedding, space_replace).await?;
    }

    graph
        .run(query(
            r#"
            UNWIND [
              {iri: 'mindreader:class/Class', name: 'Class'},
              {iri: 'mindreader:class/Property', name: 'Property'},
              {iri: 'mindreader:class/Element', name: 'Element'}
            ] AS row
            MERGE (c:Entity:Class {iri: row.iri})
            ON CREATE SET c.name = row.name, c.createdAt = datetime(),
              c.weight = 0, c.layers = [], c.stub = false
            SET c.searchText = trim(coalesce(c.name, row.name) + ' ' + c.iri),
                c.mergeName = toLower(coalesce(c.name, row.name))
            "#,
        ))
        .await
        .context("seed Class/Property/Element")?;

    graph
        .run(query(
            r#"
            UNWIND [
              {iri: 'mindreader:property/ABOUT', name: 'ABOUT'},
              {iri: 'mindreader:property/INSTANCE_OF', name: 'INSTANCE_OF'},
              {iri: 'mindreader:property/SUBCLASS_OF', name: 'SUBCLASS_OF'},
              {iri: 'mindreader:property/SUBPROPERTY_OF', name: 'SUBPROPERTY_OF'},
              {iri: 'mindreader:property/DOMAIN', name: 'DOMAIN'},
              {iri: 'mindreader:property/RANGE', name: 'RANGE'},
              {iri: 'mindreader:property/EVIDENCE_FOR', name: 'EVIDENCE_FOR'},
              {iri: 'mindreader:property/DERIVED_FROM', name: 'DERIVED_FROM'},
              {iri: 'mindreader:property/SUPPORTS', name: 'SUPPORTS'},
              {iri: 'mindreader:property/CONTRADICTS', name: 'CONTRADICTS'},
              {iri: 'mindreader:property/SUPERSEDES', name: 'SUPERSEDES'}
            ] AS row
            MERGE (p:Entity:Property {iri: row.iri})
            ON CREATE SET p.name = row.name, p.createdAt = datetime(),
              p.weight = 0, p.layers = [], p.stub = false
            SET p.searchText = trim(coalesce(p.name, row.name) + ' ' + p.iri),
                p.mergeName = toLower(coalesce(p.name, row.name))
            "#,
        ))
        .await
        .context("seed structural properties")?;

    graph
        .run(query("CALL db.awaitIndexes($timeout_seconds)").param("timeout_seconds", 300_i64))
        .await
        .context("wait for required Neo4j indexes to become online")?;
    verify_required_constraints(graph).await?;
    verify_required_fulltext_indexes(graph).await?;
    if embedding.is_some() {
        verify_semantic_index(graph).await?;
    }

    Ok(())
}

/// Require APOC Core/Extended plus TTL before bootstrap continues.
async fn verify_required_apoc(graph: &Graph) -> Result<()> {
    let functions_row = fetch_all(
        graph,
        query(
            "SHOW FUNCTIONS YIELD name WHERE name IN [\
             'apoc.text.fuzzyMatch', 'apoc.text.levenshteinSimilarity'] \
             RETURN collect(name) AS names",
        ),
    )
    .await
    .context("inspect required APOC functions")?
    .into_iter()
    .next()
    .ok_or_else(|| graph_error!("Neo4j returned no APOC function catalog row"))?;
    let functions = functions_row.get::<Vec<String>>("names")?;
    for name in ["apoc.text.fuzzyMatch", "apoc.text.levenshteinSimilarity"] {
        if !functions.iter().any(|actual| actual == name) {
            return Err(graph_error!(
                "required APOC function {name} is unavailable; install matching APOC Core"
            ));
        }
    }

    let procedures_row = fetch_all(
        graph,
        query(
            "SHOW PROCEDURES YIELD name WHERE name IN [\
             'apoc.config.list', 'apoc.merge.node', 'apoc.refactor.mergeNodes', \
             'apoc.ttl.expireIn'] \
             RETURN collect(name) AS names",
        ),
    )
    .await
    .context("inspect required APOC procedures")?
    .into_iter()
    .next()
    .ok_or_else(|| graph_error!("Neo4j returned no APOC procedure catalog row"))?;
    let procedures = procedures_row.get::<Vec<String>>("names")?;
    for name in [
        "apoc.config.list",
        "apoc.merge.node",
        "apoc.refactor.mergeNodes",
        "apoc.ttl.expireIn",
    ] {
        if !procedures.iter().any(|actual| actual == name) {
            return Err(graph_error!(
                "required APOC procedure {name} is unavailable; install matching APOC Core and APOC Extended"
            ));
        }
    }
    let ttl_value = fetch_one(
        graph,
        query(
            "CALL apoc.config.list() YIELD key, value \
             WHERE key = 'apoc.ttl.enabled' \
             RETURN toString(value) AS value",
        ),
    )
    .await
    .context("read APOC TTL configuration")?
    .ok_or_else(|| graph_error!("APOC TTL configuration is missing"))?
    .get::<String>("value")?;
    let ttl_enabled = ttl_value.eq_ignore_ascii_case("true");
    if !ttl_enabled {
        return Err(graph_error!(
            "APOC TTL is disabled; set apoc.ttl.enabled=true before starting Mindreader"
        ));
    }
    Ok(())
}

/// Read the stored provider/model/dimension triple from the embedding-space marker.
fn read_embedding_marker(row: &Row) -> Result<(String, String, i64)> {
    Ok((
        row.get::<String>("provider")?,
        row.get::<String>("model")?,
        row.get::<i64>("dimensions")?,
    ))
}

/// True when the stored activation space is exactly the incoming provider/model/dimension.
fn marker_matches_space(
    provider: &str,
    model: &str,
    dimensions: i64,
    embedding: &EmbeddingSpace,
) -> bool {
    provider == embedding.provider
        && model == embedding.model
        && dimensions == embedding.dimensions as i64
}

/// Whether bootstrap should drop and recreate the activation index for `incoming`.
pub(crate) fn should_replace_embedding_space(
    policy: SpaceReplace,
    current: Option<(&str, &str, i64)>,
    incoming: &EmbeddingSpace,
) -> Result<bool> {
    let Some((provider, model, dimensions)) = current else {
        return Ok(true);
    };
    if marker_matches_space(provider, model, dimensions, incoming) {
        return Ok(false);
    }
    match policy {
        SpaceReplace::Allow => Ok(true),
        #[cfg(any(feature = "developer-tools", test))]
        SpaceReplace::Refuse => Err(Error::EmbeddingSpace(format!(
            "database embedding space {provider}/{model}/{dimensions} is incompatible with {}/{}/{}; refuse to replace it",
            incoming.provider, incoming.model, incoming.dimensions
        ))),
    }
}

/// Fail closed when the stored embedding space cannot serve this process.
pub async fn require_embedding_space(graph: &Graph, embedding: &EmbeddingSpace) -> Result<()> {
    let marker = fetch_one(
        graph,
        query(
            "MATCH (m:MindreaderMeta {key: $key}) \
             RETURN m.provider AS provider, m.model AS model, m.dimensions AS dimensions",
        )
        .param("key", EMBEDDING_MARKER_KEY),
    )
    .await
    .context("read embedding-space marker")?;
    let Some(marker) = marker.as_ref() else {
        return Err(Error::EmbeddingSpace(
            "semantic activation embedding marker is missing".into(),
        ));
    };
    let (provider, model, dimensions) = read_embedding_marker(marker)?;
    if !marker_matches_space(&provider, &model, dimensions, embedding) {
        return Err(Error::EmbeddingSpace(format!(
            "database embedding space {provider}/{model}/{dimensions} does not match {}/{}/{}",
            embedding.provider, embedding.model, embedding.dimensions
        )));
    }
    let index = fetch_one(
        graph,
        query(
            "SHOW VECTOR INDEXES YIELD name, state \
             WHERE name = $name RETURN state",
        )
        .param("name", SEMANTIC_INDEX),
    )
    .await
    .context("inspect semantic activation vector index")?;
    let online = match index.as_ref() {
        Some(row) => row.get::<String>("state")? == "ONLINE",
        None => false,
    };
    if !online {
        return Err(Error::EmbeddingSpace(format!(
            "required vector index {SEMANTIC_INDEX} is missing or not online"
        )));
    }
    Ok(())
}

/// Create or replace the activation vector index; a space change deletes old activations.
async fn ensure_semantic_index(
    graph: &Graph,
    embedding: &EmbeddingSpace,
    space_replace: SpaceReplace,
) -> Result<()> {
    if !(1..=4096).contains(&embedding.dimensions) {
        return Err(graph_error!(
            "embedding dimensions must be between 1 and 4096"
        ));
    }
    let marker = fetch_one(
        graph,
        query(
            "MATCH (m:MindreaderMeta {key: $key}) \
             RETURN m.provider AS provider, m.model AS model, m.dimensions AS dimensions",
        )
        .param("key", EMBEDDING_MARKER_KEY),
    )
    .await
    .context("read embedding-space marker")?;
    let current = marker.as_ref().map(read_embedding_marker).transpose()?;
    let replace = should_replace_embedding_space(
        space_replace,
        current
            .as_ref()
            .map(|(provider, model, dimensions)| (provider.as_str(), model.as_str(), *dimensions)),
        embedding,
    )?;
    if replace {
        // Drop the v4 vector index, then DETACH DELETE label SemanticActivation so an old embedding space cannot leak.
        graph
            .run(query(&format!("DROP INDEX {SEMANTIC_INDEX} IF EXISTS")))
            .await
            .context("drop incompatible semantic activation index")?;
        graph
            .run(query("MATCH (a:SemanticActivation) DETACH DELETE a"))
            .await
            .context("discard activations from an incompatible embedding space")?;
        graph
            .run(
                query(
                    "MERGE (m:MindreaderMeta {key: $key}) \
                     SET m.provider = $provider, m.model = $model, m.dimensions = $dimensions",
                )
                .param("key", EMBEDDING_MARKER_KEY)
                .param("provider", embedding.provider.clone())
                .param("model", embedding.model.clone())
                .param("dimensions", embedding.dimensions as i64),
            )
            .await
            .context("record active embedding space")?;
    }
    let create = format!(
        "CREATE VECTOR INDEX {SEMANTIC_INDEX} IF NOT EXISTS \
         FOR (a:SemanticActivationV4) ON (a.embedding) \
         OPTIONS {{indexConfig: {{`vector.dimensions`: {}, \
         `vector.similarity_function`: 'cosine'}}}}",
        embedding.dimensions
    );
    graph
        .run(query(&create))
        .await
        .context("create semantic activation vector index")?;
    Ok(())
}

/// Fail closed unless the current activation vector index is online.
async fn verify_semantic_index(graph: &Graph) -> Result<()> {
    let row = fetch_one(
        graph,
        query(
            "SHOW VECTOR INDEXES YIELD name, state, entityType, labelsOrTypes, properties, options \
             WHERE name = $name \
             RETURN state, entityType, labelsOrTypes, properties, \
                    toInteger(options.indexConfig.`vector.dimensions`) AS dimensions",
        )
        .param("name", SEMANTIC_INDEX),
    )
    .await
    .context("inspect semantic activation vector index")?
    .ok_or_else(|| graph_error!("required vector index {SEMANTIC_INDEX} is missing"))?;
    let state = row.get::<String>("state")?;
    let entity_type = row.get::<String>("entityType")?;
    let labels = row.get::<Vec<String>>("labelsOrTypes")?;
    let properties = row.get::<Vec<String>>("properties")?;
    if state != "ONLINE"
        || entity_type != "NODE"
        || !same_string_members(&labels, &["SemanticActivationV4"])
        || !same_string_members(&properties, &["embedding"])
    {
        return Err(graph_error!(
            "required vector index {SEMANTIC_INDEX} is incompatible or not online"
        ));
    }
    Ok(())
}

/// Require uniqueness constraints on meta keys, entity IRIs, and fact-lock keys.
async fn verify_required_constraints(graph: &Graph) -> Result<()> {
    let rows = fetch_all(
        graph,
        query(
            r#"
            SHOW CONSTRAINTS
            YIELD name, type, entityType, labelsOrTypes, properties
            WHERE name IN ['mindreader_meta_key', 'entity_iri', 'fact_lock_key']
            RETURN name, type AS constraintType, entityType, labelsOrTypes, properties
            "#,
        ),
    )
    .await
    .context("inspect required Neo4j constraints")?;

    for (name, label, property) in [
        ("mindreader_meta_key", "MindreaderMeta", "key"),
        ("entity_iri", "Entity", "iri"),
        ("fact_lock_key", "FactLock", "key"),
    ] {
        let row = rows
            .iter()
            .find(|row| matches!(row.get::<String>("name"), Ok(actual) if actual == name))
            .ok_or_else(|| graph_error!("required Neo4j constraint {name} is missing"))?;
        let constraint_type = row
            .get::<String>("constraintType")
            .with_context(|| format!("read type of Neo4j constraint {name}"))?;
        let entity_type = row
            .get::<String>("entityType")
            .with_context(|| format!("read entity type of Neo4j constraint {name}"))?;
        let labels_or_types = row
            .get::<Vec<String>>("labelsOrTypes")
            .with_context(|| format!("read labels of Neo4j constraint {name}"))?;
        let properties = row
            .get::<Vec<String>>("properties")
            .with_context(|| format!("read properties of Neo4j constraint {name}"))?;
        if !matches!(
            constraint_type.as_str(),
            "UNIQUENESS" | "NODE_PROPERTY_UNIQUENESS"
        ) || entity_type != "NODE"
            || !same_string_members(&labels_or_types, &[label])
            || !same_string_members(&properties, &[property])
        {
            return Err(graph_error!(
                "required Neo4j constraint {name} has an incompatible definition: type={constraint_type}, entityType={entity_type}, labelsOrTypes={labels_or_types:?}, properties={properties:?}; {RESET_REQUIRED}"
            ));
        }
    }
    Ok(())
}

/// Write the model marker on an empty database; reject unversioned non-empty graphs.
async fn ensure_model_marker(graph: &Graph) -> Result<()> {
    let markers = fetch_all(
        graph,
        query("MATCH (m:MindreaderMeta {key: $key}) RETURN m.version AS version")
            .param("key", MODEL_MARKER_KEY),
    )
    .await
    .context("read Mindreader database model marker")?;

    if markers.len() > 1 {
        return Err(graph_error!(
            "multiple Mindreader database model markers found; {RESET_REQUIRED}"
        ));
    }

    if let Some(marker) = markers.first() {
        let version = marker.get::<i64>("version").map_err(|_| {
            graph_error!("invalid Mindreader database model marker; {RESET_REQUIRED}")
        })?;
        validate_model_version(version)?;
        ensure_model_marker_constraint(graph).await?;
        return Ok(());
    }

    let node_count = fetch_one(graph, query("MATCH (n) RETURN count(n) AS nodeCount"))
        .await
        .context("check whether the Neo4j database is empty")?
        .ok_or_else(|| graph_error!("Neo4j did not return a node count"))?
        .get::<i64>("nodeCount")
        .context("read Neo4j node count")?;

    if node_count > 0 {
        let concurrent_markers = fetch_all(
            graph,
            query("MATCH (m:MindreaderMeta {key: $key}) RETURN m.version AS version")
                .param("key", MODEL_MARKER_KEY),
        )
        .await
        .context("recheck model marker after concurrent bootstrap activity")?;
        if concurrent_markers.len() == 1
            && concurrent_markers[0].get::<i64>("version").ok() == Some(MODEL_VERSION)
        {
            ensure_model_marker_constraint(graph).await?;
            return Ok(());
        }
        return Err(graph_error!(
            "found {node_count} pre-existing node(s) without a Mindreader database model marker; no data migration is supported, so {RESET_REQUIRED}"
        ));
    }

    ensure_model_marker_constraint(graph).await?;

    graph
        .run(
            query(
                "MERGE (m:MindreaderMeta {key: $key}) ON CREATE SET m.version = $version, m.createdAt = datetime()",
            )
            .param("key", MODEL_MARKER_KEY)
            .param("version", MODEL_VERSION),
        )
        .await
        .context("create Mindreader database model marker")?;

    Ok(())
}

/// Accept only the current model marker; never migrate an older or newer graph.
fn validate_model_version(version: i64) -> Result<()> {
    if version == MODEL_VERSION {
        return Ok(());
    }
    Err(graph_error!(
        "Mindreader database model version {version} is incompatible with required version {MODEL_VERSION}; {RESET_REQUIRED}"
    ))
}

/// Create the singleton-key uniqueness constraint used by the model marker node.
async fn ensure_model_marker_constraint(graph: &Graph) -> Result<()> {
    graph
        .run(query(
            "CREATE CONSTRAINT mindreader_meta_key IF NOT EXISTS FOR (m:MindreaderMeta) REQUIRE m.key IS UNIQUE",
        ))
        .await
        .context("create model marker key uniqueness constraint")?;
    Ok(())
}

/// Require wakeup and merge-candidate full-text indexes to be online with the expected definition.
async fn verify_required_fulltext_indexes(graph: &Graph) -> Result<()> {
    let rows = fetch_all(
        graph,
        query(
            r#"
            SHOW INDEXES
            YIELD name, type, entityType, labelsOrTypes, properties, state, options
            WHERE name IN ['wakeup_nodes', 'wakeup_facts', 'merge_candidate_names']
            RETURN name, type AS indexType, entityType, labelsOrTypes, properties, state,
                   coalesce(toString(options.indexConfig['fulltext.analyzer']), '') AS analyzer,
                   coalesce(toString(options.indexConfig['fulltext.eventually_consistent']), 'false') AS eventuallyConsistent
            "#,
        ),
    )
    .await
    .context("inspect required Neo4j full-text indexes")?;

    for (required_name, required_entity_type) in REQUIRED_FULLTEXT_INDEXES {
        let row = rows
            .iter()
            .find(|row| matches!(row.get::<String>("name"), Ok(name) if name == *required_name))
            .ok_or_else(|| {
                graph_error!("required Neo4j full-text index {required_name} is missing")
            })?;
        let index_type = row
            .get::<String>("indexType")
            .with_context(|| format!("read type of Neo4j index {required_name}"))?;
        let entity_type = row
            .get::<String>("entityType")
            .with_context(|| format!("read entity type of Neo4j index {required_name}"))?;
        let state = row
            .get::<String>("state")
            .with_context(|| format!("read state of Neo4j index {required_name}"))?;
        let labels_or_types = row
            .get::<Vec<String>>("labelsOrTypes")
            .with_context(|| format!("read labels or types of Neo4j index {required_name}"))?;
        let properties = row
            .get::<Vec<String>>("properties")
            .with_context(|| format!("read properties of Neo4j index {required_name}"))?;

        let (expected_labels_or_types, expected_properties): (&[&str], &[&str]) =
            match *required_name {
                "wakeup_nodes" => (&["Entity"], WAKEUP_NODE_PROPERTIES),
                "wakeup_facts" => (SEARCHABLE_RELATIONSHIPS, &["factText"]),
                MERGE_CANDIDATE_INDEX => (&["Entity"], &["mergeName"]),
                _ => unreachable!("required full-text index catalog is exhaustive"),
            };

        let merge_options_valid = if *required_name == MERGE_CANDIDATE_INDEX {
            row.get::<String>("analyzer").ok().as_deref() == Some("keyword")
                && row
                    .get::<String>("eventuallyConsistent")
                    .ok()
                    .is_some_and(|value| value.eq_ignore_ascii_case("false"))
        } else {
            true
        };

        if index_type != "FULLTEXT"
            || entity_type != *required_entity_type
            || state != "ONLINE"
            || !same_string_members(&labels_or_types, expected_labels_or_types)
            || !same_string_members(&properties, expected_properties)
            || !merge_options_valid
        {
            return Err(graph_error!(
                "required Neo4j index {required_name} has an incompatible definition or is not ready: type={index_type}, entityType={entity_type}, labelsOrTypes={labels_or_types:?}, properties={properties:?}, state={state}; {RESET_REQUIRED}"
            ));
        }
    }

    Ok(())
}

/// Order-independent exact set equality for Neo4j index/constraint member lists.
fn same_string_members(actual: &[String], expected: &[&str]) -> bool {
    actual.len() == expected.len()
        && expected
            .iter()
            .all(|expected| actual.iter().any(|actual| actual == expected))
}

/// Allowlist a Neo4j node label safe to interpolate into Cypher.
pub fn safe_label(label: &str) -> Result<String> {
    let Some(first) = label.chars().next() else {
        return Err(graph_error!("invalid label: {label}"));
    };
    if !first.is_ascii_alphabetic() || !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        return Err(graph_error!("invalid label: {label}"));
    }
    let _ = LABEL_OK;
    Ok(label.to_string())
}

/// Allowlist and normalize a relationship type safe to interpolate into Cypher.
pub fn safe_rel(rel: &str) -> Result<String> {
    let up = rel.to_ascii_uppercase();
    let Some(first) = up.chars().next() else {
        return Err(graph_error!("invalid relationship type: {rel}"));
    };
    if !first.is_ascii_uppercase()
        || !up
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
    {
        return Err(graph_error!("invalid relationship type: {rel}"));
    }
    Ok(up)
}

/// First row of a graph-level query. Must not run while a transaction is open on this connection.
pub async fn fetch_one(graph: &Graph, q: neo4rs::Query) -> Result<Option<Row>> {
    let mut stream = graph.execute(q).await?;
    Ok(stream.next().await?)
}

/// Every row of a graph-level query. Must not run while a transaction is open on this connection.
pub async fn fetch_all(graph: &Graph, q: neo4rs::Query) -> Result<Vec<Row>> {
    let mut stream = graph.execute(q).await?;
    let mut rows = Vec::new();
    while let Some(row) = stream.next().await? {
        rows.push(row);
    }
    Ok(rows)
}

/// Execute a query through an existing transaction and return its first row.
///
/// Keeping the transaction handle in the row stream is required by neo4rs; callers
/// must not issue graph-level queries while the transaction is open.
pub async fn fetch_one_txn(txn: &mut Txn, q: neo4rs::Query) -> Result<Option<Row>> {
    let mut stream = txn.execute(q).await?;
    Ok(stream.next(txn.handle()).await?)
}

/// Exhaust a transactional query. The row stream must keep `txn.handle()`; do not issue graph-level queries until the txn ends.
pub async fn fetch_all_txn(txn: &mut Txn, q: neo4rs::Query) -> Result<Vec<Row>> {
    let mut stream = txn.execute(q).await?;
    let mut rows = Vec::new();
    while let Some(row) = stream.next(txn.handle()).await? {
        rows.push(row);
    }
    Ok(rows)
}

/// Signed judgment weight on a node; missing values fail closed.
fn node_weight(node: &Node) -> Result<i64> {
    Ok(node.get::<i64>("weight")?)
}

/// Signed judgment weight on a bounded current fact.
fn relation_weight(rel: &Relation) -> Result<i64> {
    Ok(rel.get::<i64>("weight")?)
}

/// Serialize a node as agent-facing JSON: signed weight, scope from layers; literals use `kind=literal`.
pub fn node_json(node: &Node) -> Result<Value> {
    let labels: Vec<String> = node
        .labels()
        .into_iter()
        .filter(|l| *l != "Entity")
        .map(|s| s.to_string())
        .collect();
    let iri = node.get::<String>("iri")?;
    let name = node.get::<String>("name").ok();
    let is_literal = labels.iter().any(|label| label == "Literal");
    let mut obj = json!({
        "kind": if is_literal { "literal" } else { "node" },
        "iri": iri,
        "name": name,
        "labels": labels,
    });
    if is_literal {
        obj["value"] = json!(node.get::<String>("value")?);
        obj["datatype"] = json!(node.get::<String>("datatype")?);
    }
    if labels
        .iter()
        .any(|label| label == "Class" || label == "Property")
    {
        obj["stub"] = json!(node.get::<bool>("stub")?);
    } else if let Ok(stub) = node.get::<bool>("stub") {
        obj["stub"] = json!(stub);
    }
    if let Ok(v) = node.get::<String>("tool") {
        obj["tool"] = json!(v);
    }
    obj["scope"] = json!(node.get::<Vec<String>>("layers")?);
    obj["weight"] = json!(node_weight(node)?);
    obj["target"] = json!({ "kind": "node", "iri": iri });
    Ok(obj)
}

/// Serialize a relationship as `kind=fact` with endpoint IRIs, scope, Spike, and signed weight.
///
/// Callers must pass a current edge; this helper does not check `validTo`.
pub fn rel_json(rel: &Relation, from: &str, to: &str) -> Result<Value> {
    if from.is_empty() || to.is_empty() {
        return Err(graph_error!("fact endpoints must have non-empty IRIs"));
    }
    let mut obj = json!({
        "type": rel.typ(),
        "from": from,
        "to": to,
        "iri": rel.get::<String>("iri")?,
        "propertyIri": rel.get::<String>("propertyIri")?,
    });
    obj["kind"] = json!("fact");
    if let Ok(v) = rel.get::<String>("episodeId") {
        obj["episodeId"] = json!(v);
    }
    if let Ok(v) = rel.get::<String>("reason") {
        obj["reason"] = json!(v);
    }
    if let Ok(v) = rel.get::<String>("spike") {
        obj["spike"] = json!(v);
    }
    obj["effective"] = if rel.get::<bool>("effectiveQualified").unwrap_or(false) {
        let mut effective = serde_json::Map::new();
        if let Some(from) = rel
            .get::<DateTime<FixedOffset>>("effectiveFrom")
            .ok()
            .map(|value| {
                value
                    .with_timezone(&Utc)
                    .to_rfc3339_opts(SecondsFormat::AutoSi, true)
            })
        {
            effective.insert("from".into(), json!(from));
        }
        if let Some(to) = rel
            .get::<DateTime<FixedOffset>>("effectiveTo")
            .ok()
            .map(|value| {
                value
                    .with_timezone(&Utc)
                    .to_rfc3339_opts(SecondsFormat::AutoSi, true)
            })
        {
            effective.insert("to".into(), json!(to));
        }
        Value::Object(effective)
    } else {
        Value::Null
    };
    obj["scope"] = json!(rel.get::<Vec<String>>("layers")?);
    obj["weight"] = json!(relation_weight(rel)?);
    Ok(obj)
}

/// Serialize only the fields exposed by a compact directed witness edge.
fn compact_path_edge_json(rel: &UnboundedRelation, from: &str, to: &str) -> Result<Value> {
    if from.is_empty() || to.is_empty() {
        return Err(graph_error!("path edge endpoints must have non-empty IRIs"));
    }
    Ok(json!({
        "iri": rel.get::<String>("iri")?,
        "from": from,
        "p": rel.get::<String>("propertyIri")?,
        "to": to,
    }))
}

/// Require a stored node IRI; missing identity fails serialization.
fn node_iri(node: &Node) -> Result<String> {
    Ok(node.get::<String>("iri")?)
}

/// Expand a Neo4j path into node JSON, compact witness edges, and ordered node IRIs.
pub fn path_to_json(path: &Path) -> Result<(Vec<Value>, Vec<Value>, Vec<String>)> {
    let nodes = path.nodes_as::<Node>()?;
    let rels = path.relationships_as::<UnboundedRelation>()?;
    let indices = path.indices_as::<i64>()?;
    let node_jsons = nodes.iter().map(node_json).collect::<Result<Vec<_>>>()?;
    let iris = nodes.iter().map(node_iri).collect::<Result<Vec<_>>>()?;

    if indices.len() % 2 != 0 {
        return Err(graph_error!("Neo4j returned a path with malformed indices"));
    }
    if !rels.is_empty() && indices.is_empty() {
        return Err(graph_error!(
            "Neo4j returned a path without relationship indices"
        ));
    }

    let mut edges = Vec::new();
    let mut cursor = 0usize;
    let mut k = 0usize;
    while k + 1 < indices.len() {
        let rel_signed = indices[k];
        let next = indices[k + 1] as usize;
        k += 2;
        let abs = rel_signed.unsigned_abs() as usize;
        if abs == 0 || abs > rels.len() || next >= nodes.len() || cursor >= nodes.len() {
            return Err(graph_error!("Neo4j returned out-of-range path indices"));
        }
        // Neo4j path indices are signed: negative means the unbounded rel is stored reversed.
        let (from_i, to_i) = if rel_signed >= 0 {
            (cursor, next)
        } else {
            (next, cursor)
        };
        edges.push(compact_path_edge_json(
            &rels[abs - 1],
            &iris[from_i],
            &iris[to_i],
        )?);
        cursor = next;
    }
    Ok((node_jsons, edges, iris))
}

/// Result of merging an entity or literal inside a transaction.
#[derive(Debug, Clone)]
pub struct MergedNode {
    /// Stored node identity after MERGE; callers use this as the subject/object handle.
    pub iri: String,
    /// Display name coalesced onto the node; literals use the literal value.
    pub name: String,
    /// Identity and extra labels excluding `Entity`; Class/Property stay catalog kinds.
    pub labels: Vec<String>,
    /// True when this MERGE created the node in the current transaction.
    pub created: bool,
    /// Agent-facing node JSON including memberships and weight.
    pub json: Value,
}

/// Input for resolving or creating an entity node (IRI and/or name plus labels).
#[derive(Debug, Clone, Default)]
pub struct NodeSpec {
    /// Existing IRI when known; otherwise a name is required to mint one.
    pub iri: Option<String>,
    /// Display name used to mint an IRI when `iri` is absent; required unless `iri` is set.
    pub name: Option<String>,
    /// Extra labels merged with the inferred kind label; `Entity` is stripped before MERGE.
    pub labels: Vec<String>,
}

/// Collision-resistant subject/predicate/layer guard used for writer lock order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FactLockSpec {
    key: String,
    subject_iri: String,
    predicate_iri: String,
    layer: String,
}

/// Infer mint kind from IRI path, identity labels, or a caller-supplied fallback.
pub fn infer_kind(spec: &NodeSpec, fallback: &str) -> String {
    if let Some(iri) = &spec.iri {
        if let Some(k) = kind_from_iri(iri) {
            return k;
        }
    }
    if let Some(label) = identity_kind_from_labels(&spec.labels) {
        if let Some(kind) = kind_for_label(label) {
            return kind.to_string();
        }
    }
    fallback.to_string()
}

/// Resolve IRI, display name, and allowlisted labels before MERGE; never mint an unnamed node.
fn resolved_node_parts(
    spec: &NodeSpec,
    default_kind: &str,
    extra_labels: &[String],
) -> Result<(String, String, Vec<String>)> {
    let kind = infer_kind(spec, default_kind);
    let iri = if let Some(iri) = spec.iri.as_deref().filter(|value| !value.is_empty()) {
        iri.to_string()
    } else {
        let seed = spec
            .name
            .as_deref()
            .filter(|value| !value.is_empty())
            .ok_or_else(|| graph_error!("node requires a non-empty iri or name"))?;
        mint_iri(&kind, seed, default_lower_for_kind(&kind))
    };
    let name = spec.name.clone().unwrap_or_else(|| name_from_iri(&iri));
    let mut labels = Vec::new();
    if let Some(label) = label_for_kind(&kind) {
        labels.push(label.to_string());
    }
    labels.extend(spec.labels.iter().cloned());
    labels.extend(extra_labels.iter().cloned());
    labels.retain(|label| label != "Entity");
    let mut seen = std::collections::HashSet::new();
    labels.retain(|label| seen.insert(label.clone()));
    for label in &labels {
        safe_label(label)?;
    }
    Ok((iri, name, labels))
}

/// MERGE an entity using only the supplied transaction.
///
/// `searchText` deliberately contains intrinsic node data only. Fact text belongs
/// on relationships and must not accumulate on nodes when facts are revised or
/// withdrawn.
pub async fn merge_node_in_txn(
    txn: &mut Txn,
    spec: &NodeSpec,
    default_kind: &str,
    extra_labels: &[String],
) -> Result<MergedNode> {
    let (iri, name, labels) = resolved_node_parts(spec, default_kind, extra_labels)?;
    // UUID create-marker is the only reliable created bit: APOC MERGE cannot return ON CREATE vs ON MATCH.
    let creation_marker = Uuid::new_v4().to_string();
    // Class/Property MERGE always forces stub=false and layers=[] so catalog nodes stay global.
    let row = fetch_one_txn(
        txn,
        query(
            r#"
            CALL apoc.merge.node(
              ['Entity'],
              {iri: $iri},
              {name: $name, createdAt: datetime(), weight: 0, layers: [],
               mindreaderCreateMarker: $creationMarker},
              {}
            ) YIELD node
            WITH node, coalesce(node.mindreaderCreateMarker = $creationMarker, false) AS created
            REMOVE node.mindreaderCreateMarker
            SET node:$($labels)
            FOREACH (_ IN CASE WHEN 'Class' IN $labels OR 'Property' IN $labels THEN [1] ELSE [] END |
              SET node.stub = false, node.layers = [])
            SET node.name = coalesce(node.name, $name),
                node.mergeName = toLower(coalesce(node.name, $name)),
                node.searchText = trim(coalesce(node.name, $name) + ' ' + node.iri + ' ' + coalesce(node.value, ''))
            RETURN node, created
            "#,
        )
        .param("iri", iri.clone())
        .param("name", name.clone())
        .param("labels", labels)
        .param("creationMarker", creation_marker),
    )
    .await?
    .ok_or_else(|| graph_error!("failed to MERGE node {iri}"))?;
    let created = row.get::<bool>("created")?;

    let node: Node = row.get("node")?;
    let labels = node
        .labels()
        .into_iter()
        .filter(|label| *label != "Entity")
        .map(str::to_string)
        .collect();
    Ok(MergedNode {
        iri,
        name,
        labels,
        created,
        json: node_json(&node)?,
    })
}

/// MERGE a literal using the canonical domain-level literal IRI algorithm.
pub async fn merge_literal_in_txn(
    txn: &mut Txn,
    value: &str,
    datatype: &str,
) -> Result<MergedNode> {
    let iri = literal_iri(value, datatype);
    let row = fetch_one_txn(
        txn,
        query(
            r#"
            OPTIONAL MATCH (existing:Entity {iri: $iri})
            MERGE (n:Entity:Literal {iri: $iri})
            ON CREATE SET n.name = $name, n.value = $value, n.datatype = $datatype,
              n.createdAt = datetime(), n.weight = 0, n.layers = []
            ON MATCH SET n.name = coalesce(n.name, $name),
              n.value = coalesce(n.value, $value), n.datatype = coalesce(n.datatype, $datatype)
            SET n.searchText = trim(coalesce(n.name, $name) + ' ' + n.iri + ' ' + coalesce(n.value, $value))
            RETURN n, existing IS NULL AS created
            "#,
        )
        .param("iri", iri.clone())
        .param("name", value.to_string())
        .param("value", value.to_string())
        .param("datatype", datatype.to_string()),
    )
    .await?
    .ok_or_else(|| graph_error!("failed to MERGE literal {iri}"))?;
    let node: Node = row.get("n")?;
    let created = row.get::<bool>("created")?;
    Ok(MergedNode {
        iri,
        name: value.to_string(),
        labels: vec!["Literal".into()],
        created,
        json: node_json(&node)?,
    })
}

/// MERGE a global Property (`stub=false`, `layers=[]`) inside the caller's transaction.
pub async fn ensure_property_in_txn(
    txn: &mut Txn,
    property: &str,
) -> Result<(String, bool, Value)> {
    let iri = property_iri(property);
    let name = name_from_iri(&iri);
    let row = fetch_one_txn(
        txn,
        query(
            r#"
            OPTIONAL MATCH (existing:Entity {iri: $iri})
            MERGE (n:Entity:Property {iri: $iri})
            ON CREATE SET n.name = $name, n.createdAt = datetime(), n.stub = false,
              n.weight = 0, n.layers = []
            ON MATCH SET n.name = coalesce(n.name, $name)
            SET n.mergeName = toLower(coalesce(n.name, $name)),
                n.searchText = trim(coalesce(n.name, $name) + ' ' + n.iri + ' ' + coalesce(n.value, ''))
            RETURN n, existing IS NULL AS created
            "#,
        )
        .param("iri", iri.clone())
        .param("name", name),
    )
    .await?
    .ok_or_else(|| graph_error!("failed to MERGE property {iri}"))?;
    let node: Node = row.get("n")?;
    let created = row.get::<bool>("created")?;
    Ok((iri, created, node_json(&node)?))
}

/// Length-prefixed SHA-256 so IRI fragments cannot collide across fields.
fn lock_key(subject_iri: &str, predicate_iri: &str, layer: &str) -> String {
    let mut hasher = Sha256::new();
    for part in [subject_iri, predicate_iri, layer] {
        hasher.update((part.len() as u64).to_be_bytes());
        hasher.update(part.as_bytes());
    }
    hasher
        .finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// Expand each fact into subject-wide and predicate-specific locks, then sort by key.
pub(crate) fn fact_lock_specs(facts: &[(String, String, String)]) -> Vec<FactLockSpec> {
    let mut locks = Vec::with_capacity(facts.len() * 2);
    for (subject_iri, predicate_iri, layer) in facts {
        for predicate_iri in ["*", predicate_iri.as_str()] {
            locks.push(FactLockSpec {
                key: lock_key(subject_iri, predicate_iri, layer),
                subject_iri: subject_iri.clone(),
                predicate_iri: predicate_iri.to_string(),
                layer: layer.clone(),
            });
        }
    }
    locks.sort_by(|left, right| left.key.cmp(&right.key));
    locks.dedup_by(|left, right| left.key == right.key);
    locks
}

/// Bolt maps for ordered FactLock MERGE; key order is the lock order.
fn fact_lock_params(locks: &[FactLockSpec]) -> Vec<HashMap<String, String>> {
    locks
        .iter()
        .map(|lock| {
            HashMap::from([
                ("key".into(), lock.key.clone()),
                ("subjectIri".into(), lock.subject_iri.clone()),
                ("predicateIri".into(), lock.predicate_iri.clone()),
                ("layer".into(), lock.layer.clone()),
            ])
        })
        .collect()
}

/// Acquire deterministic subject and predicate guards for every fact tuple.
///
/// Each `(subject, predicate, layer)` request acquires both `(subject, "*",
/// layer)` and `(subject, predicate, layer)`. Sorting the collision-resistant
/// keys before updating lock nodes gives concurrent writers a consistent lock
/// order and prevents stale precondition reads.
pub async fn acquire_fact_locks_in_txn(
    txn: &mut Txn,
    facts: &[(String, String, String)],
) -> Result<()> {
    let locks = fact_lock_specs(facts);
    if locks.is_empty() {
        return Ok(());
    }
    let expected = locks.len() as i64;
    let row = fetch_one_txn(
        txn,
        query(
            r#"
            UNWIND $locks AS requested
            WITH requested
            ORDER BY requested.key
            MERGE (lock:FactLock {key: requested.key})
            ON CREATE SET lock.subjectIri = requested.subjectIri,
              lock.predicateIri = requested.predicateIri, lock.layer = requested.layer,
              lock.createdAt = datetime(), lock.revision = 0
            SET lock.revision = lock.revision + 1, lock.acquiredAt = datetime()
            RETURN count(lock) AS acquired
            "#,
        )
        .param("locks", fact_lock_params(&locks)),
    )
    .await?
    .ok_or_else(|| graph_error!("failed to acquire fact locks"))?;
    let acquired = row.get::<i64>("acquired")?;
    if acquired != expected {
        return Err(graph_error!(
            "acquired {acquired} fact locks, expected {expected}"
        ));
    }
    Ok(())
}

/// Provenance episode created for a state-changing mutation (none for no-ops).
#[derive(Debug, Clone)]
pub struct Episode {
    /// `mindreader:episode/…` identity recorded on changed facts.
    pub iri: String,
    /// Timestamp string returned by Neo4j for the Episode node.
    pub at: String,
    /// MCP tool name that created this Episode (`write`, …).
    pub tool: String,
}

/// Create a global Episode node (`layers=[]`) attributed to one MCP mutation tool.
fn episode_query(iri: &str, tool: &str, note: Option<&str>) -> neo4rs::Query {
    query(
        r#"
        CREATE (e:Entity:Episode {
            iri: $iri,
            tool: $tool,
            at: datetime(),
            createdAt: datetime(),
            name: $iri,
            weight: 0,
            layers: []
        })
        SET e.note = $note
        RETURN e.iri AS iri, toString(e.at) AS at
        "#,
    )
    .param("iri", iri.to_string())
    .param("tool", tool.to_string())
    .param("note", note.map(|s| s.to_string()))
}

/// Map the created Episode; `tool` is taken from the caller because RETURN yields only `iri`/`at`.
fn episode_from_row(row: &Row, tool: &str) -> Result<Episode> {
    Ok(Episode {
        iri: row.get::<String>("iri")?,
        at: row.get::<String>("at")?,
        tool: tool.to_string(),
    })
}

/// Mint one global Episode (`layers=[]`) in the caller's transaction. Callers must not invoke this for no-op mutations.
pub async fn create_episode_in_txn(
    txn: &mut Txn,
    tool: &str,
    note: Option<&str>,
) -> Result<Episode> {
    let iri = mint_iri("episode", &Uuid::new_v4().to_string(), true);
    let mut stream = txn.execute(episode_query(&iri, tool, note)).await?;
    let row = stream
        .next(txn.handle())
        .await?
        .ok_or_else(|| graph_error!("failed to create episode"))?;
    episode_from_row(&row, tool)
}

/// Build relationship `factText` for full-text indexing from subject, property, and object.
pub fn fact_text(s_name: &str, s_iri: &str, prop_iri: &str, o: &MergedNode) -> String {
    let s_part = if !s_name.is_empty() { s_name } else { s_iri };
    let p_part = name_from_iri(prop_iri);
    let p_split = split_camel_case(&p_part);
    let o_part = o
        .json
        .get("value")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .or({
            if !o.name.is_empty() {
                Some(o.name.as_str())
            } else {
                None
            }
        })
        .unwrap_or(o.iri.as_str());
    if p_split == p_part {
        format!("{s_part} {p_part} {o_part}")
    } else {
        format!("{s_part} {p_part} {o_part} {p_split}")
    }
}

/// Compact endpoint JSON for facts: entities expose name/labels; literals expose value/datatype.
pub fn endpoint_json(node: &Node) -> Result<Value> {
    let labels: Vec<String> = node
        .labels()
        .into_iter()
        .filter(|l| *l != "Entity")
        .map(|s| s.to_string())
        .collect();
    let iri = node.get::<String>("iri")?;
    if labels.iter().any(|l| l == "Literal") {
        let value = node.get::<String>("value")?;
        let datatype = node.get::<String>("datatype")?;
        return Ok(json!({
            "kind": "literal",
            "iri": iri,
            "value": value,
            "datatype": datatype,
            "scope": node.get::<Vec<String>>("layers")?,
            "weight": node_weight(node)?,
            "target": { "kind": "node", "iri": iri },
        }));
    }
    Ok(json!({
        "kind": "node",
        "iri": iri,
        "name": node.get::<String>("name").ok(),
        "labels": labels,
        "scope": node.get::<Vec<String>>("layers")?,
        "weight": node_weight(node)?,
        "target": { "kind": "node", "iri": iri },
    }))
}

/// Local predicate name for agent-facing `p` (IRI or already-local name).
pub fn local_predicate_name(property: &str) -> String {
    name_from_iri(property)
}

/// Agent-facing fact object: pasteable `target` plus local-name `p`.
pub fn fact_envelope(
    subject: Value,
    property: &str,
    object: Value,
    relationship: &Value,
    scope: &[String],
) -> Result<Value> {
    let iri = relationship
        .get("iri")
        .and_then(Value::as_str)
        .filter(|iri| !iri.is_empty())
        .ok_or_else(|| graph_error!("fact relationship is missing its IRI"))?;
    let weight = relationship
        .get("weight")
        .and_then(Value::as_i64)
        .ok_or_else(|| graph_error!("fact relationship is missing its numeric weight"))?;
    // Envelope is current-only; retracted facts must never enter this helper.
    Ok(json!({
        "target": { "kind": "fact", "iri": iri },
        "s": subject,
        "p": local_predicate_name(property),
        "o": object,
        "scope": scope,
        "spike": relationship.get("spike").cloned().unwrap_or(Value::Null),
        "effective": relationship.get("effective").cloned().unwrap_or(Value::Null),
        "weight": weight,
        "current": true,
    }))
}

/// Numeric Spike priority for ranking (Knowledge = 4 … unranked = 0).
pub fn spike_rank(label: Option<&str>) -> i32 {
    match label {
        Some("Knowledge") => 4,
        Some("Insight") => 3,
        Some("Pattern") => 2,
        Some("Signal") => 1,
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        endpoint_json, fact_lock_params, fact_lock_specs, lock_key, node_json, rel_json,
        resolved_node_parts, safe_label, safe_rel, same_string_members,
        should_replace_embedding_space, spike_rank, validate_model_version, NodeSpec, SpaceReplace,
        MODEL_VERSION,
    };
    use crate::config::EmbeddingSpace;
    use neo4rs::{
        BoltBoolean, BoltInteger, BoltList, BoltMap, BoltNode, BoltRelation, BoltString, BoltType,
        Node, Relation,
    };

    fn node_with(properties: impl IntoIterator<Item = (&'static str, BoltType)>) -> Node {
        node_with_labels(&["Entity"], properties)
    }

    fn node_with_labels(
        labels: &[&str],
        properties: impl IntoIterator<Item = (&'static str, BoltType)>,
    ) -> Node {
        let mut map = BoltMap::new();
        for (key, value) in properties {
            map.put(BoltString::from(key), value);
        }
        Node::new(BoltNode::new(
            BoltInteger::new(1),
            BoltList::from(
                labels
                    .iter()
                    .map(|label| BoltType::String(BoltString::from(*label)))
                    .collect::<Vec<_>>(),
            ),
            map,
        ))
    }

    fn relation_with(properties: impl IntoIterator<Item = (&'static str, BoltType)>) -> Relation {
        let mut map = BoltMap::new();
        for (key, value) in properties {
            map.put(BoltString::from(key), value);
        }
        Relation::new(BoltRelation {
            id: BoltInteger::new(1),
            start_node_id: BoltInteger::new(1),
            end_node_id: BoltInteger::new(2),
            typ: BoltString::from("ASSERTS"),
            properties: map,
        })
    }

    #[test]
    fn should_replace_embedding_space_refuses_mismatch() {
        let incoming = EmbeddingSpace {
            provider: "smoke".into(),
            model: "deterministic".into(),
            dimensions: 3,
        };
        assert!(should_replace_embedding_space(SpaceReplace::Allow, None, &incoming).unwrap());
        assert!(!should_replace_embedding_space(
            SpaceReplace::Refuse,
            Some(("smoke", "deterministic", 3)),
            &incoming
        )
        .unwrap());
        assert!(should_replace_embedding_space(
            SpaceReplace::Refuse,
            Some(("openai", "text-embedding-3-small", 1536)),
            &incoming
        )
        .is_err());
        assert!(should_replace_embedding_space(
            SpaceReplace::Allow,
            Some(("openai", "text-embedding-3-small", 1536)),
            &incoming
        )
        .unwrap());
    }

    #[test]
    fn model_v9_requires_recreating_older_databases() {
        assert_eq!(MODEL_VERSION, 9);
        assert!(validate_model_version(9).is_ok());
        assert_eq!(
            validate_model_version(8).unwrap_err().to_string(),
            "Mindreader database model version 8 is incompatible with required version 9; recreate the Neo4j database or volume before starting Mindreader"
        );
    }

    #[test]
    fn serialization_requires_identity_and_preserves_negative_integer_weight() {
        let missing_iri = node_with([
            ("layers", BoltType::List(BoltList::new())),
            ("weight", BoltType::Integer(BoltInteger::new(-3))),
        ]);
        assert!(node_json(&missing_iri).is_err());

        let complete = node_with([
            (
                "iri",
                BoltType::String(BoltString::from("mindreader:element/strict")),
            ),
            ("layers", BoltType::List(BoltList::new())),
            ("weight", BoltType::Integer(BoltInteger::new(-3))),
        ]);
        assert_eq!(node_json(&complete).unwrap()["weight"], -3);

        let literal = node_with_labels(
            &["Entity", "Literal"],
            [
                (
                    "iri",
                    BoltType::String(BoltString::from("mindreader:literal/strict")),
                ),
                ("value", BoltType::String(BoltString::from("strict"))),
                ("datatype", BoltType::String(BoltString::from("xsd:string"))),
                ("layers", BoltType::List(BoltList::new())),
                ("weight", BoltType::Integer(BoltInteger::new(0))),
            ],
        );
        let literal_handle = serde_json::json!({
            "kind": "node",
            "iri": "mindreader:literal/strict"
        });
        assert_eq!(node_json(&literal).unwrap()["target"], literal_handle);
        assert_eq!(endpoint_json(&literal).unwrap()["target"], literal_handle);

        let relation = relation_with([
            (
                "iri",
                BoltType::String(BoltString::from("mindreader:relationship/strict")),
            ),
            (
                "propertyIri",
                BoltType::String(BoltString::from("mindreader:property/strict")),
            ),
            ("layers", BoltType::List(BoltList::new())),
            ("weight", BoltType::Integer(BoltInteger::new(-4))),
            ("spike", BoltType::String(BoltString::from("Insight"))),
        ]);
        let serialized =
            rel_json(&relation, "mindreader:element/a", "mindreader:element/b").unwrap();
        assert_eq!(serialized["weight"], -4);
        assert_eq!(serialized["spike"], "Insight");

        let open_effective = relation_with([
            (
                "iri",
                BoltType::String(BoltString::from("mindreader:relationship/open")),
            ),
            (
                "propertyIri",
                BoltType::String(BoltString::from("mindreader:property/open")),
            ),
            ("layers", BoltType::List(BoltList::new())),
            ("weight", BoltType::Integer(BoltInteger::new(0))),
            (
                "effectiveQualified",
                BoltType::Boolean(BoltBoolean::new(true)),
            ),
        ]);
        let serialized = rel_json(
            &open_effective,
            "mindreader:element/a",
            "mindreader:element/b",
        )
        .unwrap();
        assert_eq!(serialized["effective"], serde_json::json!({}));
    }

    #[test]
    fn node_resolution_rejects_missing_identity_instead_of_minting_unnamed() {
        let error = resolved_node_parts(&NodeSpec::default(), "element", &[]).unwrap_err();
        assert_eq!(error.to_string(), "node requires a non-empty iri or name");
    }

    #[test]
    fn fact_locks_are_complete_deduplicated_and_deterministically_ordered() {
        let facts = vec![
            (
                "mindreader:element/b".into(),
                "mindreader:property/Z".into(),
                "global".into(),
            ),
            (
                "mindreader:element/a".into(),
                "mindreader:property/A".into(),
                "project:test".into(),
            ),
            (
                "mindreader:element/b".into(),
                "mindreader:property/Z".into(),
                "global".into(),
            ),
        ];
        let locks = fact_lock_specs(&facts);
        assert_eq!(
            locks.len(),
            4,
            "each unique fact gets a subject and predicate lock"
        );
        assert!(locks.windows(2).all(|pair| pair[0].key < pair[1].key));
        assert!(locks.iter().all(|lock| lock.key.len() == 64));
        assert_eq!(
            locks
                .iter()
                .filter(|lock| lock.predicate_iri == "*")
                .count(),
            2
        );

        let mut reversed = facts;
        reversed.reverse();
        assert_eq!(locks, fact_lock_specs(&reversed));

        let params = fact_lock_params(&locks);
        for (lock, param) in locks.iter().zip(params) {
            assert_eq!(param.get("key"), Some(&lock.key));
            assert_eq!(param.get("subjectIri"), Some(&lock.subject_iri));
            assert_eq!(param.get("predicateIri"), Some(&lock.predicate_iri));
            assert_eq!(param.get("layer"), Some(&lock.layer));
        }
    }

    #[test]
    fn fact_lock_key_is_length_delimited() {
        assert_ne!(lock_key("ab", "c", "d"), lock_key("a", "bc", "d"));
        assert_ne!(lock_key("a", "b", "cd"), lock_key("a", "bc", "d"));
    }

    #[test]
    fn index_definition_members_are_order_independent_and_exact() {
        assert!(same_string_members(
            &["iri".into(), "name".into()],
            &["name", "iri"]
        ));
        assert!(!same_string_members(&["name".into()], &["name", "iri"]));
        assert!(!same_string_members(
            &["name".into(), "iri".into(), "legacy".into()],
            &["name", "iri"]
        ));
    }

    #[test]
    fn spike_rank_orders() {
        assert!(spike_rank(Some("Knowledge")) > spike_rank(Some("Insight")));
        assert!(spike_rank(Some("Insight")) > spike_rank(Some("Pattern")));
        assert!(spike_rank(Some("Pattern")) > spike_rank(Some("Signal")));
        assert!(spike_rank(Some("Signal")) > spike_rank(None));
    }

    #[test]
    fn safe_label_rejects_injection_shapes() {
        assert!(safe_label("Element").is_ok());
        assert!(safe_label("").is_err());
        assert!(safe_label("1Element").is_err());
        assert!(safe_label("Element-Bad").is_err());
        assert!(safe_label("Element SET n.pwned=true").is_err());
    }

    #[test]
    fn safe_rel_rejects_injection_shapes() {
        assert_eq!(safe_rel("asserts").unwrap(), "ASSERTS");
        assert!(safe_rel("").is_err());
        assert!(safe_rel("ASSERTS-BAD").is_err());
        assert!(safe_rel("ASSERTS MATCH (n)").is_err());
    }
}