khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
//! KG export / import — portable JSON archive for namespace-scoped knowledge graphs.
//!
//! Embeddings are excluded (regenerable from text + model). Edges are collected by
//! querying all entity IDs in the namespace first, then fetching incident edges.

use std::collections::{HashMap, HashSet};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use khive_storage::types::{EdgeFilter, LinkId, PageRequest};
use khive_storage::{EdgeRelation, EntityFilter};

use crate::error::{RuntimeError, RuntimeResult};
use crate::runtime::{KhiveRuntime, NamespaceToken};

// ── Archive types ─────────────────────────────────────────────────────────────

/// Portable JSON archive of a namespace-scoped knowledge graph.
///
/// The `format` field is always `"khive-kg"`. The `version` field identifies
/// the serialization schema; parsers should reject unknown versions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct KgArchive {
    pub format: String,
    pub version: String,
    pub namespace: String,
    pub exported_at: DateTime<Utc>,
    pub entities: Vec<ExportedEntity>,
    pub edges: Vec<ExportedEdge>,
}

/// An entity record in the portable archive.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExportedEntity {
    pub id: Uuid,
    /// Pack-owned kind string (e.g. `"concept"`, `"person"`).
    pub kind: String,
    /// Pack-governed subtype token (e.g. `"paper"`, `"snapshot"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entity_type: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<serde_json::Value>,
    #[serde(default)]
    pub tags: Vec<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// A directed edge record in the portable archive.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExportedEdge {
    /// Stable edge identity across export/import cycles.
    ///
    /// Old archives (pre-0.2) omit this field. `serde(default)` assigns a fresh
    /// UUID on import so backward-compatible archives are accepted as-is.
    #[serde(default = "Uuid::new_v4")]
    pub edge_id: Uuid,
    pub source: Uuid,
    pub target: Uuid,
    /// One of the canonical edge relations (closed enum).
    pub relation: EdgeRelation,
    pub weight: f64,
    /// Portable edge metadata, named `properties` in the ADR-020 wire shape.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<serde_json::Value>,
    /// Edge creation time. Older archives may omit it; those imports use the
    /// time at which the archive is decoded.
    #[serde(
        default = "default_import_timestamp",
        deserialize_with = "deserialize_import_timestamp"
    )]
    pub created_at: DateTime<Utc>,
    /// Edge last-update time. Kept independent from `created_at` so imported
    /// provenance is not collapsed during a round trip.
    #[serde(
        default = "default_import_timestamp",
        deserialize_with = "deserialize_import_timestamp"
    )]
    pub updated_at: DateTime<Utc>,
}

fn default_import_timestamp() -> DateTime<Utc> {
    Utc::now()
}

fn deserialize_import_timestamp<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = String::deserialize(deserializer)?;
    DateTime::parse_from_rfc3339(&raw)
        .map(|timestamp| timestamp.with_timezone(&Utc))
        .map_err(|error| serde::de::Error::custom(format!("timestamp must be RFC3339: {error}")))
}

/// Outcome of a successful import operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ImportSummary {
    pub entities_imported: usize,
    pub edges_imported: usize,
    /// Number of edges that were skipped because one or both endpoint UUIDs
    /// were not found in the target namespace after entity import.
    ///
    /// A non-zero value indicates the archive contained dangling edges (edges
    /// referencing entities not present in the archive or the existing graph).
    pub edges_skipped: usize,
    /// Aggregate actual outcomes from reindexing imported entities. Source
    /// text remains complete in the entity store and FTS when this is non-zero.
    #[serde(default)]
    pub embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
}

// ── KhiveRuntime impl ─────────────────────────────────────────────────────────

impl KhiveRuntime {
    /// Export all entities and edges in a namespace to a portable JSON archive.
    ///
    /// Edge collection: all entity IDs in the namespace are gathered first;
    /// `query_edges` is then called with those IDs as `source_ids`. This
    /// captures every edge whose source entity belongs to the namespace.
    pub async fn export_kg(&self, token: &NamespaceToken) -> RuntimeResult<KgArchive> {
        let ns = token.namespace().as_str().to_owned();

        let entity_page = self
            .entities(token)?
            .query_entities(
                &ns,
                EntityFilter::default(),
                PageRequest {
                    offset: 0,
                    limit: u32::MAX,
                },
            )
            .await?;

        let entities: Vec<ExportedEntity> = entity_page
            .items
            .into_iter()
            .map(|e| {
                let created_at =
                    DateTime::from_timestamp_micros(e.created_at).unwrap_or_else(Utc::now);
                let updated_at =
                    DateTime::from_timestamp_micros(e.updated_at).unwrap_or_else(Utc::now);
                ExportedEntity {
                    id: e.id,
                    kind: e.kind.to_string(),
                    entity_type: e.entity_type,
                    name: e.name,
                    description: e.description,
                    properties: e.properties,
                    tags: e.tags,
                    created_at,
                    updated_at,
                }
            })
            .collect();

        let source_ids: Vec<Uuid> = entities.iter().map(|e| e.id).collect();
        let edges = if source_ids.is_empty() {
            Vec::new()
        } else {
            let filter = EdgeFilter {
                source_ids: source_ids.clone(),
                ..Default::default()
            };
            let edge_page = self
                .graph(token)?
                .query_edges(
                    filter,
                    Vec::new(),
                    PageRequest {
                        offset: 0,
                        limit: u32::MAX,
                    },
                )
                .await?;

            let id_set: HashSet<Uuid> = source_ids.into_iter().collect();
            edge_page
                .items
                .into_iter()
                .filter(|e| id_set.contains(&e.source_id))
                .map(|e| ExportedEdge {
                    edge_id: e.id.into(),
                    source: e.source_id,
                    target: e.target_id,
                    relation: e.relation,
                    weight: e.weight,
                    properties: e.metadata,
                    created_at: e.created_at,
                    updated_at: e.updated_at,
                })
                .collect()
        };

        Ok(KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: ns,
            exported_at: Utc::now(),
            entities,
            edges,
        })
    }

    /// Export to a JSON string (convenience wrapper around `export_kg`).
    pub async fn export_kg_json(&self, token: &NamespaceToken) -> RuntimeResult<String> {
        let archive = self.export_kg(token).await?;
        serde_json::to_string(&archive).map_err(|e| RuntimeError::InvalidInput(e.to_string()))
    }

    /// Import an archive into `target_namespace`.
    ///
    /// If `target_namespace` is `None`, the archive's own namespace is used.
    ///
    /// - Entities: upserted by ID; existing records are overwritten.
    /// - Edges: upserted; existing records are overwritten.
    /// - Validation: `format != "khive-kg"` or unsupported version → `InvalidInput`.
    ///   Invalid edge relations are caught at JSON deserialization time.
    pub async fn import_kg(
        &self,
        archive: &KgArchive,
        token: &NamespaceToken,
    ) -> RuntimeResult<ImportSummary> {
        if archive.format != "khive-kg" {
            return Err(RuntimeError::InvalidInput(format!(
                "unsupported archive format {:?}; expected \"khive-kg\"",
                archive.format
            )));
        }
        if archive.version != "0.1" {
            return Err(RuntimeError::InvalidInput(format!(
                "unsupported archive version {:?}; supported: \"0.1\"",
                archive.version
            )));
        }

        let ns = token.namespace().as_str().to_owned();

        // Complete deterministic validation before opening a store or issuing
        // the first write. Endpoint existence and namespace checks remain at
        // write time because they depend on mutable target state.
        for (index, entity) in archive.entities.iter().enumerate() {
            self.validate_entity_kind(&entity.kind)?;
            // Archive content is caller-controlled input: the runtime-owned
            // `khive:secret_gate` property key is reservation-only on import,
            // exactly as on every other properties-bearing write path
            // (ADR-115 Amendment 1 §3). Import never consumes exemptions.
            crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
            if entity.name.trim().is_empty() {
                return Err(RuntimeError::InvalidInput(format!(
                    "archive entity {index} ({}) name must be non-blank",
                    entity.id
                )));
            }
        }
        for (index, edge) in archive.edges.iter().enumerate() {
            let record = format!("edge[{index}]");
            crate::operations::validate_edge_weight(edge.weight)?;
            // Edge properties are caller-controlled input: the runtime-owned
            // `khive:secret_gate` key is reservation-only on import, and edge
            // metadata is in ADR-115 Amendment 1 §3's unchanged blocking-scanner
            // class, so credential-shaped values are rejected here as well.
            crate::secret_gate::reject_reserved_secret_gate_property(edge.properties.as_ref())?;
            if let Some(p) = edge.properties.as_ref() {
                crate::secret_gate::check_json_at(p, &record, "properties")?;
            }
        }

        let store = self.entities(token)?;
        let mut entities_imported = 0usize;
        let mut embedding_truncation = crate::retrieval::EmbeddingTruncationReport::default();
        for page in archive
            .entities
            .chunks(crate::retrieval::EMBEDDING_BATCH_PAGE_SIZE)
        {
            let entities: Vec<khive_storage::entity::Entity> = page
                .iter()
                .map(|ee| khive_storage::entity::Entity {
                    id: ee.id,
                    namespace: ns.clone(),
                    kind: ee.kind.clone(),
                    entity_type: ee.entity_type.clone(),
                    name: ee.name.clone(),
                    description: ee.description.clone(),
                    properties: ee.properties.clone(),
                    tags: ee.tags.clone(),
                    created_at: ee.created_at.timestamp_micros(),
                    updated_at: ee.updated_at.timestamp_micros(),
                    deleted_at: None,
                    merged_into: None,
                    merge_event_id: None,
                    version: 1,
                    content_ref: None,
                })
                .collect();
            let texts: Vec<String> = entities
                .iter()
                .map(crate::curation::entity_embedding_text)
                .collect();
            let mut embeddings: Vec<HashMap<String, crate::retrieval::DocumentEmbeddingOutcome>> =
                (0..entities.len()).map(|_| HashMap::new()).collect();
            for model_name in self.registered_embedding_model_names() {
                match self
                    .embed_document_batch_with_model_outcomes_for_token(token, &model_name, &texts)
                    .await
                {
                    Ok(outcomes) => {
                        for (slot, outcome) in embeddings.iter_mut().zip(outcomes) {
                            slot.insert(model_name.clone(), outcome);
                        }
                    }
                    Err(error) => {
                        tracing::warn!(
                            model = %model_name,
                            error = %error,
                            "import_kg: batch embed failed; retrying records individually"
                        );
                    }
                }
            }
            for (entity, outcomes) in entities.into_iter().zip(embeddings) {
                store.upsert_entity(entity.clone()).await?;
                // Publish each record through the same guarded FTS/vector writer
                // as an ordinary reindex, including its best-effort model failures.
                embedding_truncation.merge(
                    self.reindex_entity_with_precomputed(token, &entity, outcomes)
                        .await?,
                );
                entities_imported += 1;
            }
        }

        // Untrusted archives may reference entities absent from the target namespace;
        // check both endpoints and skip edges with a missing source or target to avoid
        // dangling references in the graph store.
        let graph = self.graph(token)?;
        let mut edges_imported = 0usize;
        let mut edges_skipped = 0usize;
        for ee in &archive.edges {
            let source_ok = match self.get_entity(token, ee.source).await {
                Ok(_) => true,
                Err(RuntimeError::NotFound(_)) => false,
                Err(e) => return Err(e),
            };
            if !source_ok {
                tracing::warn!(
                    source = %ee.source,
                    target = %ee.target,
                    relation = ?ee.relation,
                    "import_kg: skipping edge — source entity not found in namespace {ns:?}"
                );
                edges_skipped += 1;
                continue;
            }
            let target_ok = match self.get_entity(token, ee.target).await {
                Ok(_) => true,
                Err(RuntimeError::NotFound(_)) => false,
                Err(e) => return Err(e),
            };
            if !target_ok {
                tracing::warn!(
                    source = %ee.source,
                    target = %ee.target,
                    relation = ?ee.relation,
                    "import_kg: skipping edge — target entity not found in namespace {ns:?}"
                );
                edges_skipped += 1;
                continue;
            }
            // Only a contract verdict (InvalidInput) or an endpoint-resolution
            // miss (NotFound) is a property of the edge being imported; any
            // other error is an operational failure of the check itself and
            // must abort the import rather than silently discard a valid edge.
            match self
                .validate_edge_relation_endpoints(token, ee.source, ee.target, ee.relation)
                .await
            {
                Ok(_) => {}
                Err(e @ (RuntimeError::InvalidInput(_) | RuntimeError::NotFound(_))) => {
                    tracing::warn!(
                        source = %ee.source,
                        target = %ee.target,
                        relation = ?ee.relation,
                        error = %e,
                        "import_kg: skipping edge — endpoint contract violation in namespace {ns:?}"
                    );
                    edges_skipped += 1;
                    continue;
                }
                Err(e) => return Err(e),
            }
            let edge = khive_storage::types::Edge {
                id: LinkId::from(ee.edge_id),
                namespace: ns.clone(),
                source_id: ee.source,
                target_id: ee.target,
                relation: ee.relation,
                weight: ee.weight,
                created_at: ee.created_at,
                updated_at: ee.updated_at,
                deleted_at: None,
                metadata: ee.properties.clone(),
                target_backend: None,
            };
            graph.upsert_edge(edge).await?;
            edges_imported += 1;
        }

        Ok(ImportSummary {
            entities_imported,
            edges_imported,
            edges_skipped,
            embedding_truncation,
        })
    }

    /// Import from a JSON string (convenience wrapper around `import_kg`).
    pub async fn import_kg_json(
        &self,
        json: &str,
        token: &NamespaceToken,
    ) -> RuntimeResult<ImportSummary> {
        let archive: KgArchive =
            serde_json::from_str(json).map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;
        self.import_kg(&archive, token).await
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

// Kept inline: these tests exercise round-trip invariants over private encoding
// helpers that would otherwise need to be made pub to test from tests/.
#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    use super::*;
    use crate::runtime::{KhiveRuntime, NamespaceToken};
    use crate::{EmbedderProvider, Namespace};
    use async_trait::async_trait;
    use khive_storage::EdgeRelation;
    use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_BYTES};

    const IMPORT_TEST_MODEL: &str = "all-minilm-l6-v2";
    const IMPORT_BATCH_MODEL: &str = "import-batch-model";
    const IMPORT_BATCH_MODEL_TWO: &str = "import-batch-model-two";

    struct CountingImportService {
        calls: Arc<AtomicUsize>,
        reject_poison: bool,
    }

    #[async_trait]
    impl EmbeddingService for CountingImportService {
        async fn embed(
            &self,
            texts: &[String],
            _model: EmbeddingModel,
        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            if self.reject_poison
                && (texts.len() > 1 || texts.iter().any(|text| text.contains("poison")))
            {
                return Err(EmbedError::InferenceFailed("poison input".into()));
            }
            Ok(texts
                .iter()
                .map(|text| {
                    vec![
                        text.len() as f32,
                        text.bytes().map(u32::from).sum::<u32>() as f32,
                        text.as_bytes().first().copied().unwrap_or_default() as f32,
                        text.as_bytes().last().copied().unwrap_or_default() as f32,
                    ]
                })
                .collect())
        }

        fn supports_model(&self, _model: EmbeddingModel) -> bool {
            true
        }

        fn name(&self) -> &'static str {
            "import-batch-counting-service"
        }
    }

    struct CountingImportProvider {
        name: &'static str,
        calls: Arc<AtomicUsize>,
        reject_poison: bool,
    }

    #[async_trait]
    impl EmbedderProvider for CountingImportProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn dimensions(&self) -> usize {
            4
        }

        async fn build(&self) -> std::result::Result<Arc<dyn EmbeddingService>, RuntimeError> {
            Ok(Arc::new(CountingImportService {
                calls: Arc::clone(&self.calls),
                reject_poison: self.reject_poison,
            }))
        }
    }

    fn batch_archive(names: impl IntoIterator<Item = String>) -> KgArchive {
        KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: names
                .into_iter()
                .map(|name| ExportedEntity {
                    id: Uuid::new_v4(),
                    kind: "concept".to_string(),
                    entity_type: None,
                    name,
                    description: Some("batch body".to_string()),
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                })
                .collect(),
            edges: vec![],
        }
    }

    struct ImportEmbeddingService;

    #[async_trait]
    impl EmbeddingService for ImportEmbeddingService {
        async fn embed(
            &self,
            texts: &[String],
            _model: EmbeddingModel,
        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
            let dimensions = EmbeddingModel::AllMiniLmL6V2.dimensions();
            Ok(texts.iter().map(|_| vec![1.0; dimensions]).collect())
        }

        fn supports_model(&self, _model: EmbeddingModel) -> bool {
            true
        }

        fn name(&self) -> &'static str {
            "kg-import-truncation-test"
        }
    }

    struct ImportEmbeddingProvider;

    #[async_trait]
    impl EmbedderProvider for ImportEmbeddingProvider {
        fn name(&self) -> &str {
            IMPORT_TEST_MODEL
        }

        fn dimensions(&self) -> usize {
            EmbeddingModel::AllMiniLmL6V2.dimensions()
        }

        async fn build(&self) -> std::result::Result<Arc<dyn EmbeddingService>, RuntimeError> {
            Ok(Arc::new(ImportEmbeddingService))
        }
    }

    async fn make_rt() -> KhiveRuntime {
        KhiveRuntime::memory().expect("in-memory runtime")
    }

    fn make_rt_with_embedder() -> KhiveRuntime {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        runtime.register_embedder(ImportEmbeddingProvider);
        runtime
    }

    #[tokio::test]
    async fn import_batches_provider_calls_and_matches_per_record_reindex_vectors() {
        let token = NamespaceToken::local();
        let archive = batch_archive((0..257).map(|index| format!("Batch entity {index}")));
        let ids: Vec<Uuid> = archive.entities.iter().map(|entity| entity.id).collect();
        let calls = Arc::new(AtomicUsize::new(0));
        let runtime = KhiveRuntime::memory().unwrap();
        runtime.register_embedder(CountingImportProvider {
            name: IMPORT_BATCH_MODEL,
            calls: Arc::clone(&calls),
            reject_poison: false,
        });
        let usage = crate::usage::UsageContext::new();
        let summary = crate::usage::scope(usage.clone(), runtime.import_kg(&archive, &token))
            .await
            .unwrap();
        assert_eq!(summary.entities_imported, ids.len());
        assert_eq!(usage.snapshot()["embed_calls"], ids.len() as u64);
        assert_eq!(
            calls.load(Ordering::SeqCst),
            2,
            "257 records need two provider batches"
        );

        let singles = KhiveRuntime::memory().unwrap();
        let singleton_calls = Arc::new(AtomicUsize::new(0));
        singles.register_embedder(CountingImportProvider {
            name: IMPORT_BATCH_MODEL,
            calls: Arc::clone(&singleton_calls),
            reject_poison: false,
        });
        for id in &ids {
            let entity = runtime.get_entity(&token, *id).await.unwrap();
            singles
                .entities(&token)
                .unwrap()
                .upsert_entity(entity.clone())
                .await
                .unwrap();
            singles.reindex_entity(&token, &entity).await.unwrap();
        }
        assert_eq!(singleton_calls.load(Ordering::SeqCst), ids.len());
        let batched_vectors = runtime
            .vectors_for_model(&token, IMPORT_BATCH_MODEL)
            .unwrap()
            .get_vectors(&ids, "local", "entity.body")
            .await
            .unwrap();
        let singleton_vectors = singles
            .vectors_for_model(&token, IMPORT_BATCH_MODEL)
            .unwrap()
            .get_vectors(&ids, "local", "entity.body")
            .await
            .unwrap();
        assert_eq!(batched_vectors.len(), ids.len());
        assert_eq!(batched_vectors, singleton_vectors);
    }

    #[tokio::test]
    async fn import_batches_each_registered_model_once_per_page() {
        let token = NamespaceToken::local();
        let archive = batch_archive(["alpha", "beta", "gamma"].map(str::to_string));
        let calls_a = Arc::new(AtomicUsize::new(0));
        let calls_b = Arc::new(AtomicUsize::new(0));
        let runtime = KhiveRuntime::memory().unwrap();
        for (name, calls) in [
            (IMPORT_BATCH_MODEL, Arc::clone(&calls_a)),
            (IMPORT_BATCH_MODEL_TWO, Arc::clone(&calls_b)),
        ] {
            runtime.register_embedder(CountingImportProvider {
                name,
                calls,
                reject_poison: false,
            });
        }
        runtime.import_kg(&archive, &token).await.unwrap();
        assert_eq!(calls_a.load(Ordering::SeqCst), 1);
        assert_eq!(calls_b.load(Ordering::SeqCst), 1);
        let ids: Vec<Uuid> = archive.entities.iter().map(|entity| entity.id).collect();
        for model in [IMPORT_BATCH_MODEL, IMPORT_BATCH_MODEL_TWO] {
            assert_eq!(
                runtime
                    .vectors_for_model(&token, model)
                    .unwrap()
                    .get_vectors(&ids, "local", "entity.body")
                    .await
                    .unwrap()
                    .len(),
                ids.len()
            );
        }
    }

    #[tokio::test]
    async fn import_failed_batch_isolates_poison_without_duplicate_vector_writes() {
        use khive_storage::types::{SqlStatement, SqlValue};

        let token = NamespaceToken::local();
        let archive = batch_archive(["good one", "poison", "good two"].map(str::to_string));
        let ids: Vec<Uuid> = archive.entities.iter().map(|entity| entity.id).collect();
        let calls = Arc::new(AtomicUsize::new(0));
        let runtime = KhiveRuntime::memory().unwrap();
        runtime.register_embedder(CountingImportProvider {
            name: IMPORT_BATCH_MODEL,
            calls: Arc::clone(&calls),
            reject_poison: true,
        });
        let summary = runtime.import_kg(&archive, &token).await.unwrap();
        assert_eq!(summary.entities_imported, 3);
        assert_eq!(
            calls.load(Ordering::SeqCst),
            4,
            "one failed page plus three singleton retries"
        );
        let vectors = runtime
            .vectors_for_model(&token, IMPORT_BATCH_MODEL)
            .unwrap()
            .get_vectors(&ids, "local", "entity.body")
            .await
            .unwrap();
        assert_eq!(vectors.len(), 2);
        assert!(!vectors.contains_key(&ids[1]));
        let mut reader = runtime.sql().reader().await.unwrap();
        let rows = reader
            .query_all(SqlStatement {
                sql: "SELECT COUNT(*) FROM ann_write_log WHERE embedding_model = ?1 AND op = 'upsert'".into(),
                params: vec![SqlValue::Text(IMPORT_BATCH_MODEL.into())],
                label: Some("import-batch-upsert-count".into()),
            })
            .await
            .unwrap();
        assert!(matches!(&rows[0].columns[0].value, SqlValue::Integer(2)));
        let provenance = reader
            .query_scalar(SqlStatement {
                sql: "SELECT COUNT(*) FROM vector_provenance WHERE model_key = ?1".into(),
                params: vec![SqlValue::Text(crate::config::sanitize_key(
                    IMPORT_BATCH_MODEL,
                ))],
                label: Some("import-batch-provenance-count".into()),
            })
            .await
            .unwrap();
        assert!(matches!(provenance, Some(SqlValue::Integer(0))));
    }

    #[tokio::test]
    async fn import_summary_reports_actual_embedding_truncation() {
        let runtime = make_rt_with_embedder();
        let token = NamespaceToken::local();
        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![ExportedEntity {
                id: Uuid::new_v4(),
                kind: "concept".to_string(),
                entity_type: None,
                name: "Imported long entity".to_string(),
                description: Some("x".repeat(MAX_TEXT_BYTES + 1)),
                properties: None,
                tags: vec![],
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            edges: vec![],
        };

        let summary = runtime
            .import_kg(&archive, &token)
            .await
            .expect("import with bounded embedding input");

        assert_eq!(summary.entities_imported, 1);
        assert_eq!(summary.embedding_truncation.truncated, 1);
        assert!(summary.embedding_truncation.discarded_bytes > 0);
        let wire = serde_json::to_value(&summary).expect("serialize import summary");
        assert_eq!(wire["embedding_truncation"]["truncated"], 1);
    }

    #[tokio::test]
    async fn import_rejects_whitespace_name_before_any_entity_write() {
        let runtime = make_rt().await;
        let token = NamespaceToken::local();
        let valid_id = Uuid::new_v4();
        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![
                ExportedEntity {
                    id: valid_id,
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: "Must not be written".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
                ExportedEntity {
                    id: Uuid::new_v4(),
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: " \t\n ".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
            ],
            edges: vec![],
        };

        let err = runtime
            .import_kg(&archive, &token)
            .await
            .expect_err("whitespace-only entity names must fail the whole import");
        assert!(
            err.to_string().contains("non-blank"),
            "error must explain the name invariant: {err}"
        );
        assert!(
            runtime.get_entity(&token, valid_id).await.is_err(),
            "deterministic validation must finish before the first entity write"
        );
    }

    /// 1. Roundtrip: 3 entities + 2 edges survive export → import on a fresh runtime.
    #[tokio::test]
    async fn roundtrip_entities_and_edges() {
        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let e1 = src
            .create_entity(
                &tok,
                "concept",
                None,
                "FlashAttention",
                Some("fast attention"),
                None,
                vec![],
            )
            .await
            .unwrap();
        let e2 = src
            .create_entity(
                &tok,
                "concept",
                None,
                "FlashAttention-2",
                None,
                None,
                vec![],
            )
            .await
            .unwrap();
        let e3 = src
            .create_entity(
                &tok,
                "person",
                None,
                "Tri Dao",
                None,
                None,
                vec!["author".into()],
            )
            .await
            .unwrap();
        src.link(&tok, e2.id, e1.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        src.link(&tok, e1.id, e3.id, EdgeRelation::IntroducedBy, 0.9, None)
            .await
            .unwrap();

        let archive = src.export_kg(&tok).await.unwrap();
        assert_eq!(archive.entities.len(), 3);
        assert_eq!(archive.edges.len(), 2);
        assert_eq!(archive.format, "khive-kg");
        assert_eq!(archive.version, "0.1");

        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 3);
        assert_eq!(summary.edges_imported, 2);

        let got = dst.get_entity(&tok, e1.id).await.unwrap();
        assert_eq!(got.name, "FlashAttention");
        assert_eq!(got.description.as_deref(), Some("fast attention"));
    }

    /// 2. JSON roundtrip: export_kg_json → import_kg_json produces equivalent state.
    #[tokio::test]
    async fn json_roundtrip() {
        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let e1 = src
            .create_entity(
                &tok,
                "concept",
                None,
                "LoRA",
                Some("low-rank adaptation"),
                Some(serde_json::json!({"year": "2021"})),
                vec!["fine-tuning".into()],
            )
            .await
            .unwrap();
        let e2 = src
            .create_entity(&tok, "concept", None, "QLoRA", None, None, vec![])
            .await
            .unwrap();
        src.link(&tok, e2.id, e1.id, EdgeRelation::VariantOf, 0.9, None)
            .await
            .unwrap();

        let json_str = src.export_kg_json(&tok).await.unwrap();
        assert!(json_str.contains("khive-kg"));

        let dst = make_rt().await;
        let summary = dst.import_kg_json(&json_str, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 2);
        assert_eq!(summary.edges_imported, 1);

        let got = dst.get_entity(&tok, e1.id).await.unwrap();
        assert_eq!(got.tags, vec!["fine-tuning"]);
    }

    /// 3. Namespace targeting: export from namespace "a", import into namespace "b" on a
    ///    fresh runtime — entities land in "b", and the source runtime's "a" is unaffected.
    ///
    ///    Note: source and destination are separate runtimes (separate in-memory DBs).
    ///    Same-DB cross-namespace copy is not a portability use case — portability is about
    ///    moving graphs between instances, not between namespaces within one instance.
    #[tokio::test]
    async fn namespace_targeting() {
        let src = make_rt().await;
        let tok_a = NamespaceToken::for_namespace(Namespace::parse("a").unwrap());
        let tok_b = NamespaceToken::for_namespace(Namespace::parse("b").unwrap());
        src.create_entity(&tok_a, "concept", None, "Sinkhorn", None, None, vec![])
            .await
            .unwrap();

        let archive = src.export_kg(&tok_a).await.unwrap();
        assert_eq!(archive.namespace, "a");

        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok_b).await.unwrap();
        assert_eq!(summary.entities_imported, 1);

        let in_b = dst.list_entities(&tok_b, None, None, 100, 0).await.unwrap();
        assert_eq!(in_b.len(), 1);
        assert_eq!(in_b[0].name, "Sinkhorn");

        let in_a = src.list_entities(&tok_a, None, None, 100, 0).await.unwrap();
        assert_eq!(in_a.len(), 1);

        let dst_a = dst.list_entities(&tok_a, None, None, 100, 0).await.unwrap();
        assert_eq!(dst_a.len(), 0);
    }

    /// 4. Format validation: wrong `format` field → InvalidInput.
    #[tokio::test]
    async fn format_validation_rejects_wrong_format() {
        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let bad = KgArchive {
            format: "wrong".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![],
            edges: vec![],
        };
        let err = rt.import_kg(&bad, &tok).await.unwrap_err();
        assert!(matches!(err, RuntimeError::InvalidInput(_)));
    }

    /// 5. Unsupported archive version → InvalidInput.
    #[tokio::test]
    async fn import_unsupported_archive_version_returns_error() {
        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let bad = KgArchive {
            format: "khive-kg".to_string(),
            version: "999.0".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![],
            edges: vec![],
        };
        let err = rt.import_kg(&bad, &tok).await.unwrap_err();
        assert!(
            matches!(err, RuntimeError::InvalidInput(_)),
            "expected InvalidInput, got {err:?}"
        );
        if let RuntimeError::InvalidInput(msg) = err {
            assert!(
                msg.contains("999.0"),
                "error message should mention the unsupported version, got: {msg:?}"
            );
        }
    }

    /// ADR-115 Amendment 1 §3: an archive entity carrying the reserved
    /// `khive:secret_gate` property key must be rejected before any upsert —
    /// import is a caller-controlled write path and stays reservation-only.
    #[tokio::test]
    async fn import_entity_with_reserved_secret_gate_property_is_rejected() {
        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![ExportedEntity {
                id: Uuid::new_v4(),
                kind: "concept".to_string(),
                entity_type: None,
                name: "ReservedKeyImport".to_string(),
                description: None,
                properties: Some(serde_json::json!({
                    "khive:secret_gate": "exempted:content-sha256-manifest-v1"
                })),
                tags: vec![],
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            edges: vec![],
        };

        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
        assert!(
            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
            "expected a reservation rejection, got {err:?}"
        );

        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
        assert!(
            !entities.iter().any(|e| e.name == "ReservedKeyImport"),
            "rejected archive import must not create the entity"
        );
    }

    /// ADR-115 Amendment 1 §3: an archive edge carrying the reserved
    /// `khive:secret_gate` property key is rejected in the same deterministic
    /// pre-write pass as entities — edge metadata is a properties-bearing
    /// write path.
    #[tokio::test]
    async fn import_edge_with_reserved_secret_gate_property_is_rejected() {
        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let a = Uuid::new_v4();
        let b = Uuid::new_v4();
        let mk = |id: Uuid, name: &str| ExportedEntity {
            id,
            kind: "concept".to_string(),
            entity_type: None,
            name: name.to_string(),
            description: None,
            properties: None,
            tags: vec![],
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };
        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![mk(a, "EdgeGateA"), mk(b, "EdgeGateB")],
            edges: vec![ExportedEdge {
                edge_id: Uuid::new_v4(),
                source: a,
                target: b,
                relation: EdgeRelation::Extends,
                weight: 0.5,
                properties: Some(serde_json::json!({
                    "khive:secret_gate": "exempted:content-sha256-manifest-v1"
                })),
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
        };

        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
        assert!(
            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
            "expected a reservation rejection, got {err:?}"
        );

        // The rejection happens before any write, so the archive's entities
        // must not have been created either.
        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
        assert!(
            !entities.iter().any(|e| e.name == "EdgeGateA"),
            "rejected archive import must not create any records"
        );
    }

    /// ADR-115 Amendment 1 §3: edge metadata is in the unchanged
    /// blocking-scanner class, so a credential-shaped value in edge
    /// properties fails the import in the same pre-write pass.
    #[tokio::test]
    async fn import_edge_with_credential_shaped_property_is_rejected() {
        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let a = Uuid::new_v4();
        let b = Uuid::new_v4();
        let mk = |id: Uuid, name: &str| ExportedEntity {
            id,
            kind: "concept".to_string(),
            entity_type: None,
            name: name.to_string(),
            description: None,
            properties: None,
            tags: vec![],
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };
        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![mk(a, "EdgeScanA"), mk(b, "EdgeScanB")],
            edges: vec![ExportedEdge {
                edge_id: Uuid::new_v4(),
                source: a,
                target: b,
                relation: EdgeRelation::Extends,
                weight: 0.5,
                properties: Some(serde_json::json!({
                    "api_key": "AKIAFAKEKEY1234567890"
                })),
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
        };

        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
        assert!(
            matches!(err, RuntimeError::SecretDetected(_)),
            "expected the blocking scanner to reject the value, got {err:?}"
        );

        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
        assert!(
            !entities.iter().any(|e| e.name == "EdgeScanA"),
            "rejected archive import must not create any records"
        );
    }

    /// 6. Invalid relation in archive → InvalidInput.
    #[test]
    fn invalid_relation_rejected_at_deserialize() {
        let json = r#"{
            "format":"khive-kg","version":"0.1","namespace":"local",
            "exported_at":"2026-01-01T00:00:00Z",
            "entities":[],
            "edges":[{"edge_id":"00000000-0000-0000-0000-000000000099",
                       "source":"00000000-0000-0000-0000-000000000001",
                       "target":"00000000-0000-0000-0000-000000000002",
                       "relation":"related_to","weight":0.5}]
        }"#;
        let result: Result<KgArchive, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "non-canonical relation should fail to deserialize"
        );
    }

    // ── Dangling-edge validation tests ────────────────────────────────────────

    /// 6. Edge with dangling source (source UUID not in entity table) is skipped.
    ///
    /// The archive has one entity + one edge whose source is a phantom UUID.
    /// Import succeeds, entities_imported=1, edges_imported=0, edges_skipped=1.
    #[tokio::test]
    async fn import_edge_with_dangling_source_is_skipped() {
        let phantom_source = Uuid::parse_str("deadbeef-dead-4ead-dead-deadbeefcafe").unwrap();

        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let real = rt
            .create_entity(&tok, "concept", None, "Real", None, None, vec![])
            .await
            .unwrap();

        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![ExportedEntity {
                id: real.id,
                kind: "concept".to_string(),
                entity_type: None,
                name: "Real".to_string(),
                description: None,
                properties: None,
                tags: vec![],
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            edges: vec![ExportedEdge {
                edge_id: Uuid::new_v4(),
                source: phantom_source,
                target: real.id,
                relation: EdgeRelation::Extends,
                weight: 1.0,
                properties: None,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
        };

        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 1);
        assert_eq!(
            summary.edges_imported, 0,
            "dangling source must not be imported"
        );
        assert_eq!(
            summary.edges_skipped, 1,
            "dangling source must be counted as skipped"
        );
    }

    /// 7. Edge with dangling target (target UUID not in entity table) is skipped.
    ///
    /// The archive has one entity + one edge whose target is a phantom UUID.
    /// Import succeeds, entities_imported=1, edges_imported=0, edges_skipped=1.
    #[tokio::test]
    async fn import_edge_with_dangling_target_is_skipped() {
        let phantom_target = Uuid::parse_str("cafebabe-cafe-4abe-cafe-cafebabecafe").unwrap();

        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let real = rt
            .create_entity(&tok, "concept", None, "Source", None, None, vec![])
            .await
            .unwrap();

        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![ExportedEntity {
                id: real.id,
                kind: "concept".to_string(),
                entity_type: None,
                name: "Source".to_string(),
                description: None,
                properties: None,
                tags: vec![],
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            edges: vec![ExportedEdge {
                edge_id: Uuid::new_v4(),
                source: real.id,
                target: phantom_target,
                relation: EdgeRelation::DependsOn,
                weight: 0.8,
                properties: None,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
        };

        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 1);
        assert_eq!(
            summary.edges_imported, 0,
            "dangling target must not be imported"
        );
        assert_eq!(
            summary.edges_skipped, 1,
            "dangling target must be counted as skipped"
        );
    }

    /// 8. Mixed batch: some valid edges and some dangling edges — correct counts reported.
    ///
    /// Archive has 3 entities, 2 valid edges, and 1 dangling edge (phantom target).
    /// Import succeeds with edges_imported=2, edges_skipped=1.
    #[tokio::test]
    async fn import_mixed_edges_reports_correct_counts() {
        let phantom = Uuid::parse_str("11111111-1111-4111-8111-111111111111").unwrap();

        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let a = src
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = src
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = src
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();

        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![
                ExportedEntity {
                    id: a.id,
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: "A".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
                ExportedEntity {
                    id: b.id,
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: "B".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
                ExportedEntity {
                    id: c.id,
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: "C".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
            ],
            edges: vec![
                ExportedEdge {
                    edge_id: Uuid::new_v4(),
                    source: a.id,
                    target: b.id,
                    relation: EdgeRelation::Extends,
                    weight: 1.0,
                    properties: None,
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
                ExportedEdge {
                    edge_id: Uuid::new_v4(),
                    source: b.id,
                    target: c.id,
                    // #1235: concept->concept is not in depends_on's endpoint
                    // contract; use variant_of (concept->concept is valid) so
                    // this fixture exercises "one dangling edge skipped" only,
                    // not an endpoint-contract violation this test isn't about.
                    relation: EdgeRelation::VariantOf,
                    weight: 0.9,
                    properties: None,
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
                ExportedEdge {
                    edge_id: Uuid::new_v4(),
                    source: a.id,
                    target: phantom,
                    relation: EdgeRelation::Enables,
                    weight: 0.5,
                    properties: None,
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
            ],
        };

        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 3);
        assert_eq!(
            summary.edges_imported, 2,
            "only valid edges must be imported"
        );
        assert_eq!(
            summary.edges_skipped, 1,
            "one dangling edge must be reported"
        );
    }

    /// 9. All-valid edges produce edges_skipped=0 (no regression on the happy path).
    #[tokio::test]
    async fn import_all_valid_edges_reports_zero_skipped() {
        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let e1 = src
            .create_entity(&tok, "concept", None, "E1", None, None, vec![])
            .await
            .unwrap();
        let e2 = src
            .create_entity(&tok, "concept", None, "E2", None, None, vec![])
            .await
            .unwrap();
        src.link(&tok, e1.id, e2.id, EdgeRelation::VariantOf, 0.7, None)
            .await
            .unwrap();

        let archive = src.export_kg(&tok).await.unwrap();
        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.edges_imported, 1);
        assert_eq!(
            summary.edges_skipped, 0,
            "no edges should be skipped when all endpoints exist"
        );
    }

    /// #1235: an edge whose (source kind, relation, target kind) triple violates the
    /// endpoint contract (here: `precedes` between two `concept` entities — `precedes`
    /// is restricted to document/dataset/artifact/service/project pairs) must be
    /// skipped by import the same way a dangling endpoint is, not written straight
    /// through with `graph.upsert_edge`.
    #[tokio::test]
    async fn import_edge_violating_endpoint_contract_is_skipped() {
        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let e1 = src
            .create_entity(&tok, "concept", None, "E1", None, None, vec![])
            .await
            .unwrap();
        let e2 = src
            .create_entity(&tok, "concept", None, "E2", None, None, vec![])
            .await
            .unwrap();

        let archive = KgArchive {
            format: "khive-kg".to_string(),
            version: "0.1".to_string(),
            namespace: "local".to_string(),
            exported_at: Utc::now(),
            entities: vec![
                ExportedEntity {
                    id: e1.id,
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: "E1".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
                ExportedEntity {
                    id: e2.id,
                    kind: "concept".to_string(),
                    entity_type: None,
                    name: "E2".to_string(),
                    description: None,
                    properties: None,
                    tags: vec![],
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                },
            ],
            edges: vec![ExportedEdge {
                edge_id: Uuid::new_v4(),
                source: e1.id,
                target: e2.id,
                relation: EdgeRelation::Precedes,
                weight: 1.0,
                properties: None,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
        };

        let dst = make_rt().await;
        let summary = dst.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 2);
        assert_eq!(
            summary.edges_imported, 0,
            "an endpoint-contract-violating edge must not be imported"
        );
        assert_eq!(
            summary.edges_skipped, 1,
            "an endpoint-contract-violating edge must be counted as skipped"
        );
        assert!(
            dst.neighbors(
                &tok,
                e1.id,
                khive_storage::types::Direction::Out,
                None,
                None
            )
            .await
            .unwrap()
            .is_empty(),
            "the contract-violating edge must not exist in the destination graph"
        );
    }

    // ── edge_id contract tests ────────────────────────────────────────────────

    /// 10. export_kg sets edge_id in the archive to the LinkId returned by link.
    #[tokio::test]
    async fn export_kg_preserves_edge_id() {
        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "Alpha", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "Beta", None, None, vec![])
            .await
            .unwrap();
        let stored_edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let stored_id: Uuid = stored_edge.id.into();

        let archive = rt.export_kg(&tok).await.unwrap();
        assert_eq!(archive.edges.len(), 1);
        assert_eq!(
            archive.edges[0].edge_id, stored_id,
            "exported edge_id must equal the LinkId returned by link"
        );
    }

    /// 11. import_kg writes the archive edge identity and timestamps exactly.
    #[tokio::test]
    async fn import_kg_persists_edge_id_and_timestamps() {
        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let a = src
            .create_entity(&tok, "concept", None, "Alpha", None, None, vec![])
            .await
            .unwrap();
        let b = src
            .create_entity(&tok, "concept", None, "Beta", None, None, vec![])
            .await
            .unwrap();
        let stored_edge = src
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let original_id: Uuid = stored_edge.id.into();

        let expected_created = chrono::DateTime::parse_from_rfc3339("2026-03-03T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let expected_updated = chrono::DateTime::parse_from_rfc3339("2026-04-04T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let mut archive = src.export_kg(&tok).await.unwrap();
        archive.edges[0].created_at = expected_created;
        archive.edges[0].updated_at = expected_updated;
        archive.edges[0].properties = Some(serde_json::json!({"confidence": 0.95}));
        let dst = make_rt().await;
        dst.import_kg(&archive, &tok).await.unwrap();

        let imported_edge = dst.get_edge(&tok, original_id).await.unwrap();
        assert!(
            imported_edge.is_some(),
            "imported edge must be retrievable by the original edge_id"
        );
        let imported_edge = imported_edge.unwrap();
        assert_eq!(
            Uuid::from(imported_edge.id),
            original_id,
            "stored edge id must equal the archive edge_id"
        );
        assert_eq!(
            imported_edge.created_at, expected_created,
            "present edge created_at must not be replaced with import time"
        );
        assert_eq!(
            imported_edge.updated_at, expected_updated,
            "present edge updated_at must not be replaced with created_at or import time"
        );
        assert_eq!(
            imported_edge.metadata,
            Some(serde_json::json!({"confidence": 0.95})),
            "edge properties must persist as storage metadata"
        );

        let reexported = dst.export_kg(&tok).await.unwrap();
        assert_eq!(
            reexported.edges[0].properties,
            Some(serde_json::json!({"confidence": 0.95})),
            "edge metadata must re-export as portable properties"
        );
    }

    /// 12. Old archive (no edge_id field) deserializes, imports, and re-exports with the
    ///     same generated UUID — proving the generated ID survives the full round trip.
    ///
    ///     The fixture includes two entities so the edge is not skipped during import.
    #[tokio::test]
    async fn old_archive_missing_edge_id_round_trips() {
        let src_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
        let tgt_id = Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap();

        // Simulate a pre-0.2 archive JSON where the edge lacks an edge_id field.
        let json = format!(
            r#"{{
                "format": "khive-kg",
                "version": "0.1",
                "namespace": "local",
                "exported_at": "2026-01-01T00:00:00Z",
                "entities": [
                    {{"id":"{src_id}","kind":"concept","name":"SrcNode","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}},
                    {{"id":"{tgt_id}","kind":"concept","name":"TgtNode","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}}
                ],
                "edges": [
                    {{
                        "source": "{src_id}",
                        "target": "{tgt_id}",
                        "relation": "extends",
                        "weight": 0.9
                    }}
                ]
            }}"#
        );

        // serde(default) must assign a fresh non-nil UUID when edge_id is absent.
        let archive: KgArchive = serde_json::from_str(&json)
            .expect("old archive without edge_id must deserialize successfully");
        assert_eq!(archive.edges.len(), 1);
        let generated_id = archive.edges[0].edge_id;
        assert_ne!(
            generated_id,
            Uuid::nil(),
            "missing edge_id in old archive must get a fresh non-nil UUID"
        );

        let rt = make_rt().await;
        let tok = NamespaceToken::local();
        let summary = rt.import_kg(&archive, &tok).await.unwrap();
        assert_eq!(summary.entities_imported, 2);
        assert_eq!(
            summary.edges_imported, 1,
            "edge must be imported when both endpoints exist"
        );

        let stored = rt.get_edge(&tok, generated_id).await.unwrap();
        assert!(
            stored.is_some(),
            "imported edge must be retrievable by the generated edge_id"
        );
        assert_eq!(
            Uuid::from(stored.unwrap().id),
            generated_id,
            "stored edge id must equal the generated edge_id"
        );

        let re_archive = rt.export_kg(&tok).await.unwrap();
        assert_eq!(re_archive.edges.len(), 1);
        assert_eq!(
            re_archive.edges[0].edge_id, generated_id,
            "re-exported edge_id must equal the ID generated on first import"
        );
    }

    /// 13. Explicit export → import → export equality: the edge_id is unchanged across
    ///     a full round trip when the source archive already contains an edge_id.
    ///
    ///     Verifies by (source, target, relation) key that re-export emits the original ID.
    #[tokio::test]
    async fn export_import_export_edge_id_equality() {
        let src = make_rt().await;
        let tok = NamespaceToken::local();
        let a = src
            .create_entity(&tok, "concept", None, "NodeA", None, None, vec![])
            .await
            .unwrap();
        let b = src
            .create_entity(&tok, "concept", None, "NodeB", None, None, vec![])
            .await
            .unwrap();
        let stored = src
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let original_edge_id: Uuid = stored.id.into();

        let archive1 = src.export_kg(&tok).await.unwrap();
        assert_eq!(archive1.edges.len(), 1);
        assert_eq!(
            archive1.edges[0].edge_id, original_edge_id,
            "first export must carry the stored edge_id"
        );

        let dst = make_rt().await;
        dst.import_kg(&archive1, &tok).await.unwrap();

        let archive2 = dst.export_kg(&tok).await.unwrap();
        assert_eq!(archive2.edges.len(), 1);

        let re_edge = archive2
            .edges
            .iter()
            .find(|e| e.source == a.id && e.target == b.id && e.relation == EdgeRelation::Extends)
            .expect(
                "re-exported archive must contain the original edge by (source,target,relation)",
            );
        assert_eq!(
            re_edge.edge_id, original_edge_id,
            "edge_id must be identical across export → import → export"
        );
    }
}