Skip to main content

khive_runtime/
portability.rs

1//! KG export / import — portable JSON archive for namespace-scoped knowledge graphs.
2//!
3//! Embeddings are excluded (regenerable from text + model). Edges are collected by
4//! querying all entity IDs in the namespace first, then fetching incident edges.
5
6use std::collections::{HashMap, HashSet};
7
8use anyhow::Context;
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use uuid::Uuid;
12
13use khive_storage::entity::EntityAlias;
14use khive_storage::types::{EdgeFilter, LinkId, PageRequest};
15use khive_storage::{EdgeRelation, EntityFilter};
16use khive_types::{EntityKind, ImportKindPolicy};
17use std::str::FromStr;
18
19use crate::error::{RuntimeError, RuntimeResult};
20use crate::runtime::{KhiveRuntime, NamespaceToken};
21
22mod conflicts;
23pub use conflicts::{
24    ImportConflictMode, ImportConflictSummary, ImportOptions, ImportPolicySkipCause,
25    ImportPolicySkippedEdge,
26};
27mod names;
28pub use names::{import_key_conflict, validate_archive_key_uniqueness, validate_entity_names};
29
30/// Parse an optional archive timestamp, using `fallback` only when absent.
31///
32/// Present values must be RFC3339 and are converted to UTC. Invalid values keep
33/// their parser error with the original timestamp as context.
34pub fn parse_archive_timestamp(
35    value: Option<&str>,
36    fallback: DateTime<Utc>,
37) -> anyhow::Result<DateTime<Utc>> {
38    let Some(raw) = value else {
39        return Ok(fallback);
40    };
41    DateTime::parse_from_rfc3339(raw)
42        .map(|dt| dt.with_timezone(&Utc))
43        .with_context(|| format!("timestamp {raw:?} must be RFC3339"))
44}
45
46// ── Archive types ─────────────────────────────────────────────────────────────
47
48/// Portable JSON archive of a namespace-scoped knowledge graph.
49///
50/// The `format` field is always `"khive-kg"`. The `version` field identifies
51/// the serialization schema; parsers should reject unknown versions.
52#[derive(Clone, Debug, Serialize, Deserialize)]
53pub struct KgArchive {
54    pub format: String,
55    pub version: String,
56    pub namespace: String,
57    pub exported_at: DateTime<Utc>,
58    pub entities: Vec<ExportedEntity>,
59    pub edges: Vec<ExportedEdge>,
60}
61
62/// An entity record in the portable archive.
63#[derive(Clone, Debug, Serialize, Deserialize)]
64pub struct ExportedEntity {
65    pub id: Uuid,
66    /// Pack-owned kind string (e.g. `"concept"`, `"person"`).
67    pub kind: String,
68    /// Pack-governed subtype token (e.g. `"paper"`, `"snapshot"`).
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub entity_type: Option<String>,
71    pub name: String,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub description: Option<String>,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub properties: Option<serde_json::Value>,
76    #[serde(default)]
77    pub tags: Vec<String>,
78    /// The caller keys the entity holds, as plain strings under its own
79    /// kind, sorted (ADR-221 section 4). Omitted when empty.
80    #[serde(default, skip_serializing_if = "Vec::is_empty")]
81    pub keys: Vec<String>,
82    /// The entity's aliases with the origin that wrote each, sorted by
83    /// alias. Omitted when empty.
84    #[serde(default, skip_serializing_if = "Vec::is_empty")]
85    pub aliases: Vec<EntityAlias>,
86    pub created_at: DateTime<Utc>,
87    pub updated_at: DateTime<Utc>,
88}
89
90/// A directed edge record in the portable archive.
91#[derive(Clone, Debug, Serialize, Deserialize)]
92pub struct ExportedEdge {
93    /// Stable edge identity across export/import cycles.
94    ///
95    /// Old archives (pre-0.2) omit this field. `serde(default)` assigns a fresh
96    /// UUID on import so backward-compatible archives are accepted as-is.
97    #[serde(default = "Uuid::new_v4")]
98    pub edge_id: Uuid,
99    pub source: Uuid,
100    pub target: Uuid,
101    /// One of the canonical edge relations (closed enum).
102    pub relation: EdgeRelation,
103    pub weight: f64,
104    /// Portable edge metadata, named `properties` in the ADR-020 wire shape.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub properties: Option<serde_json::Value>,
107    /// Edge creation time. Older archives may omit it; those imports use the
108    /// time at which the archive is decoded.
109    #[serde(
110        default = "default_import_timestamp",
111        deserialize_with = "deserialize_import_timestamp"
112    )]
113    pub created_at: DateTime<Utc>,
114    /// Edge last-update time. Kept independent from `created_at` so imported
115    /// provenance is not collapsed during a round trip.
116    #[serde(
117        default = "default_import_timestamp",
118        deserialize_with = "deserialize_import_timestamp"
119    )]
120    pub updated_at: DateTime<Utc>,
121}
122
123fn default_import_timestamp() -> DateTime<Utc> {
124    Utc::now()
125}
126
127fn deserialize_import_timestamp<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
128where
129    D: serde::Deserializer<'de>,
130{
131    let raw = String::deserialize(deserializer)?;
132    DateTime::parse_from_rfc3339(&raw)
133        .map(|timestamp| timestamp.with_timezone(&Utc))
134        .map_err(|error| serde::de::Error::custom(format!("timestamp must be RFC3339: {error}")))
135}
136
137/// Why an archive edge was skipped during a successful import.
138#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(rename_all = "snake_case")]
140pub enum ImportEdgeSkipCause {
141    /// The source entity was not found during the initial endpoint check.
142    MissingSource,
143    /// The source exists, but the target entity was not found.
144    MissingTarget,
145    /// The later endpoint-contract check returned InvalidInput or NotFound.
146    EndpointContract,
147}
148
149/// One skipped archive edge, retaining its identity and endpoint-contract error.
150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
151pub struct ImportSkippedEdge {
152    pub edge_id: Uuid,
153    pub source: Uuid,
154    pub target: Uuid,
155    pub relation: EdgeRelation,
156    pub cause: ImportEdgeSkipCause,
157    /// The original RuntimeError display text for EndpointContract only.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub error: Option<String>,
160}
161
162/// Outcome of a successful import operation.
163#[derive(Clone, Debug, Serialize, Deserialize)]
164pub struct ImportSummary {
165    pub entities_imported: usize,
166    pub edges_imported: usize,
167    /// Number of edges skipped for missing endpoints or endpoint-contract refusal.
168    ///
169    /// Newly successful imports set this to skipped_edges.len(). Historical
170    /// summaries can retain a non-zero count without individual details.
171    pub edges_skipped: usize,
172    /// Every skipped entry in archive order, including duplicates. Missing-source
173    /// takes precedence when both endpoints are absent. Empty lists are omitted
174    /// from JSON to preserve the previous zero-skip summary shape.
175    #[serde(default, skip_serializing_if = "Vec::is_empty")]
176    pub skipped_edges: Vec<ImportSkippedEdge>,
177    /// Aggregate actual outcomes from reindexing imported entities. Source
178    /// text remains complete in the entity store and FTS when this is non-zero.
179    #[serde(default)]
180    pub embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
181}
182
183/// Pure preflight result. Unknown kinds are distinct and in first-record order.
184/// Preflight emits no warnings and opens no destination store.
185#[derive(Clone, Debug, Default, PartialEq, Eq)]
186pub struct ImportValidation {
187    pub unknown_entity_kinds: Vec<String>,
188}
189
190// ── KhiveRuntime impl ─────────────────────────────────────────────────────────
191
192impl KhiveRuntime {
193    /// Export all entities and edges in a namespace to a portable JSON archive.
194    ///
195    /// Edge collection: all entity IDs in the namespace are gathered first;
196    /// `query_edges` is then called with those IDs as `source_ids`. This
197    /// captures every edge whose source entity belongs to the namespace.
198    pub async fn export_kg(&self, token: &NamespaceToken) -> RuntimeResult<KgArchive> {
199        let ns = token.namespace().as_str().to_owned();
200
201        let entity_page = self
202            .entities(token)?
203            .query_entities(
204                &ns,
205                EntityFilter::default(),
206                PageRequest {
207                    offset: 0,
208                    limit: u32::MAX,
209                },
210            )
211            .await?;
212
213        // ADR-221 section 4: each entity carries the keys it holds, as plain
214        // strings under its own kind, and its aliases with their origins.
215        let mut namespace_keys = self.namespace_keys(token).await?;
216        let entities: Vec<ExportedEntity> = entity_page
217            .items
218            .into_iter()
219            .map(|e| {
220                let created_at =
221                    DateTime::from_timestamp_micros(e.created_at).unwrap_or_else(Utc::now);
222                let updated_at =
223                    DateTime::from_timestamp_micros(e.updated_at).unwrap_or_else(Utc::now);
224                let mut keys = Vec::new();
225                for row in namespace_keys.rows.remove(&e.id).unwrap_or_default() {
226                    if !row.held {
227                        continue;
228                    }
229                    if row.kind != e.kind {
230                        return Err(RuntimeError::Internal(format!(
231                            "entity {} holds a key under kind {:?}, not its own kind {:?}; \
232                             the archive cannot carry it",
233                            e.id, row.kind, e.kind
234                        )));
235                    }
236                    keys.push(row.key);
237                }
238                keys.sort();
239                let mut aliases = e.aliases;
240                aliases.sort();
241                Ok(ExportedEntity {
242                    id: e.id,
243                    kind: e.kind.to_string(),
244                    entity_type: e.entity_type,
245                    name: e.name,
246                    description: e.description,
247                    properties: e.properties,
248                    tags: e.tags,
249                    keys,
250                    aliases,
251                    created_at,
252                    updated_at,
253                })
254            })
255            .collect::<RuntimeResult<_>>()?;
256
257        let source_ids: Vec<Uuid> = entities.iter().map(|e| e.id).collect();
258        let edges = if source_ids.is_empty() {
259            Vec::new()
260        } else {
261            let filter = EdgeFilter {
262                source_ids: source_ids.clone(),
263                ..Default::default()
264            };
265            let edge_page = self
266                .graph(token)?
267                .query_edges(
268                    filter,
269                    Vec::new(),
270                    PageRequest {
271                        offset: 0,
272                        limit: u32::MAX,
273                    },
274                )
275                .await?;
276
277            let id_set: HashSet<Uuid> = source_ids.into_iter().collect();
278            edge_page
279                .items
280                .into_iter()
281                .filter(|e| id_set.contains(&e.source_id))
282                .map(|e| ExportedEdge {
283                    edge_id: e.id.into(),
284                    source: e.source_id,
285                    target: e.target_id,
286                    relation: e.relation,
287                    weight: e.weight,
288                    properties: e.metadata,
289                    created_at: e.created_at,
290                    updated_at: e.updated_at,
291                })
292                .collect()
293        };
294
295        Ok(KgArchive {
296            format: "khive-kg".to_string(),
297            version: "0.1".to_string(),
298            namespace: ns,
299            exported_at: Utc::now(),
300            entities,
301            edges,
302        })
303    }
304
305    /// Export to a JSON string (convenience wrapper around `export_kg`).
306    pub async fn export_kg_json(&self, token: &NamespaceToken) -> RuntimeResult<String> {
307        let archive = self.export_kg(token).await?;
308        serde_json::to_string(&archive).map_err(|e| RuntimeError::InvalidInput(e.to_string()))
309    }
310
311    /// Import an archive into `target_namespace`.
312    ///
313    /// If `target_namespace` is `None`, the archive's own namespace is used.
314    ///
315    /// - Entities: upserted by ID; existing records are overwritten. A stored
316    ///   entity keeps its keys and aliases and gains the archive's; a key
317    ///   another live entity holds refuses the import before any write.
318    /// - Edges: upserted; existing records are overwritten.
319    /// - Validation: `format != "khive-kg"` or unsupported version → `InvalidInput`.
320    ///   Invalid edge relations are caught at JSON deserialization time.
321    pub async fn import_kg(
322        &self,
323        archive: &KgArchive,
324        token: &NamespaceToken,
325    ) -> RuntimeResult<ImportSummary> {
326        self.import_kg_with_policy(archive, token, ImportKindPolicy::Strict)
327            .await
328    }
329
330    /// Validate the complete archive without destination access or warnings.
331    pub fn validate_kg_import(
332        &self,
333        archive: &KgArchive,
334        policy: ImportKindPolicy,
335    ) -> RuntimeResult<ImportValidation> {
336        if archive.format != "khive-kg" {
337            return Err(RuntimeError::InvalidInput(format!(
338                "unsupported archive format {:?}; expected \"khive-kg\"",
339                archive.format
340            )));
341        }
342        if archive.version != "0.1" {
343            return Err(RuntimeError::InvalidInput(format!(
344                "unsupported archive version {:?}; supported: \"0.1\"",
345                archive.version
346            )));
347        }
348
349        // Complete deterministic validation before opening a store or issuing
350        // the first write. Endpoint existence and namespace checks remain at
351        // write time because they depend on mutable target state.
352        let kinds = self.import_entity_kind_registry()?;
353        let mut validation = ImportValidation::default();
354        let mut seen_unknown = HashSet::new();
355        for (index, entity) in archive.entities.iter().enumerate() {
356            if entity.kind.trim().is_empty() {
357                return Err(RuntimeError::InvalidInput(format!(
358                    "archive entity {index} kind must be non-blank"
359                )));
360            }
361            let base_kind = EntityKind::from_str(&entity.kind).is_ok();
362            let normalized = entity.kind.trim().to_ascii_lowercase();
363            let known =
364                kinds.iter().any(|kind| kind == &entity.kind) || (kinds.is_empty() && base_kind);
365            if !known {
366                // A recognized alias/case variant is not an unknown kind. Keep
367                // archive exact-vocabulary validation; adapters normalize first.
368                let recognized = base_kind
369                    || kinds
370                        .iter()
371                        .any(|kind| kind.eq_ignore_ascii_case(&normalized));
372                if policy == ImportKindPolicy::Strict || recognized {
373                    let valid = if kinds.is_empty() {
374                        EntityKind::ALL
375                            .iter()
376                            .map(|kind| kind.name())
377                            .collect::<Vec<_>>()
378                            .join(", ")
379                    } else {
380                        kinds.join(", ")
381                    };
382                    return Err(RuntimeError::InvalidInput(format!(
383                        "archive entity {index} ({}) has unknown entity kind {:?} (or non-canonical spelling); valid: {valid}",
384                        entity.id, entity.kind
385                    )));
386                }
387                if seen_unknown.insert(entity.kind.clone()) {
388                    validation.unknown_entity_kinds.push(entity.kind.clone());
389                }
390            }
391            // Archive content is caller-controlled input: the runtime-owned
392            // `khive:secret_gate` property key is reservation-only on import,
393            // exactly as on every other properties-bearing write path
394            // (ADR-115 Amendment 1 §3). Import never consumes exemptions.
395            crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
396            if entity.name.trim().is_empty() {
397                return Err(RuntimeError::InvalidInput(format!(
398                    "archive entity {index} ({}) name must be non-blank",
399                    entity.id
400                )));
401            }
402            validate_entity_names(entity.id, &entity.name, &entity.keys, &entity.aliases)?;
403        }
404        validate_archive_key_uniqueness(
405            archive
406                .entities
407                .iter()
408                .map(|entity| (entity.id, entity.kind.as_str(), entity.keys.as_slice())),
409        )?;
410        for (index, edge) in archive.edges.iter().enumerate() {
411            let record = format!("edge[{index}]");
412            crate::operations::validate_edge_weight(edge.weight)?;
413            // Edge properties are caller-controlled input: the runtime-owned
414            // `khive:secret_gate` key is reservation-only on import, and edge
415            // metadata is in ADR-115 Amendment 1 §3's unchanged blocking-scanner
416            // class, so credential-shaped values are rejected here as well.
417            crate::secret_gate::reject_reserved_secret_gate_property(edge.properties.as_ref())?;
418            if let Some(p) = edge.properties.as_ref() {
419                crate::secret_gate::check_json_at(p, &record, "properties")?;
420            }
421        }
422
423        Ok(validation)
424    }
425
426    /// Import with explicit admission for unknown entity kinds only.
427    /// Every other deterministic check precedes writes; operational store/index
428    /// failures retain the existing import behavior and are not transactional.
429    pub async fn import_kg_with_policy(
430        &self,
431        archive: &KgArchive,
432        token: &NamespaceToken,
433        policy: ImportKindPolicy,
434    ) -> RuntimeResult<ImportSummary> {
435        let validation = self.validate_kg_import(archive, policy)?;
436        for kind in validation.unknown_entity_kinds {
437            tracing::warn!(target: "khive.import.schema",
438                kind = %crate::secret_gate::bounded_masked_log_text(&kind),
439                "preserving unknown entity kind during explicit import");
440        }
441        let ns = token.namespace().as_str().to_owned();
442
443        let store = self.entities(token)?;
444        // ADR-221 section 4: before the first write, every archive key is
445        // free or already held by the entity carrying it, and no archive
446        // entity changes the kind of a stored entity whose rows hold keys.
447        let namespace_keys = self.namespace_keys(token).await?;
448        for ee in &archive.entities {
449            for key in &ee.keys {
450                let holder = namespace_keys.holders.get(&(ee.kind.clone(), key.clone()));
451                if holder.is_some_and(|holder| *holder != ee.id) {
452                    return Err(import_key_conflict(ee.id, &ee.kind, key));
453                }
454            }
455            if namespace_keys
456                .rows
457                .get(&ee.id)
458                .is_some_and(|rows| rows.iter().any(|row| row.kind != ee.kind))
459            {
460                return Err(RuntimeError::InvalidInput(format!(
461                    "archive entity {} changes the kind of an entity that holds keys",
462                    ee.id
463                )));
464            }
465        }
466        let mut entities_imported = 0usize;
467        let mut embedding_truncation = crate::retrieval::EmbeddingTruncationReport::default();
468        for page in archive
469            .entities
470            .chunks(crate::retrieval::EMBEDDING_BATCH_PAGE_SIZE)
471        {
472            let mut entities = Vec::with_capacity(page.len());
473            for ee in page {
474                let mut entity = khive_storage::entity::Entity {
475                    entity_type: ee.entity_type.clone(),
476                    description: ee.description.clone(),
477                    properties: ee.properties.clone(),
478                    tags: ee.tags.clone(),
479                    ..khive_storage::entity::Entity::minimal(
480                        ee.id,
481                        ns.clone(),
482                        ee.kind.clone(),
483                        ee.name.clone(),
484                        ee.created_at.timestamp_micros(),
485                        ee.updated_at.timestamp_micros(),
486                    )
487                };
488                // A stored row keeps its aliases and keys; the archive's are
489                // added to them (ADR-221 section 4).
490                if let Some(stored) = store
491                    .get_entity(ee.id)
492                    .await?
493                    .filter(|stored| stored.namespace == ns)
494                {
495                    entity.aliases = stored.aliases;
496                }
497                let named = namespace_keys.named_by(ee.id, &ee.kind);
498                let writes = names::archive_name_writes(&mut entity, &ee.keys, &ee.aliases, &named);
499                entities.push((entity, writes));
500            }
501            let texts: Vec<String> = entities
502                .iter()
503                .map(|(entity, _)| crate::curation::entity_embedding_text(entity))
504                .collect();
505            let mut embeddings: Vec<HashMap<String, crate::retrieval::DocumentEmbeddingOutcome>> =
506                (0..entities.len()).map(|_| HashMap::new()).collect();
507            for model_name in self.registered_embedding_model_names() {
508                match self
509                    .embed_document_batch_with_model_outcomes_for_token(token, &model_name, &texts)
510                    .await
511                {
512                    Ok(outcomes) => {
513                        for (slot, outcome) in embeddings.iter_mut().zip(outcomes) {
514                            slot.insert(model_name.clone(), outcome);
515                        }
516                    }
517                    Err(error) => {
518                        tracing::warn!(
519                            model = %model_name,
520                            error = %error,
521                            "import_kg: batch embed failed; retrying records individually"
522                        );
523                    }
524                }
525            }
526            for ((entity, writes), outcomes) in entities.into_iter().zip(embeddings) {
527                if writes.statements.is_empty() {
528                    store.upsert_entity(entity.clone()).await?;
529                } else {
530                    self.upsert_archive_entity(&entity, writes).await?;
531                }
532                // Publish each record through the same guarded FTS/vector writer
533                // as an ordinary reindex, including its best-effort model failures.
534                embedding_truncation.merge(
535                    self.reindex_entity_with_precomputed(token, &entity, outcomes)
536                        .await?,
537                );
538                entities_imported += 1;
539            }
540        }
541
542        // Untrusted archives may reference entities absent from the target namespace;
543        // check both endpoints and skip edges with a missing source or target to avoid
544        // dangling references in the graph store.
545        let graph = self.graph(token)?;
546        let mut edges_imported = 0usize;
547        let mut skipped_edges = Vec::new();
548        for ee in &archive.edges {
549            let source_ok = match self.get_entity(token, ee.source).await {
550                Ok(_) => true,
551                Err(RuntimeError::NotFound(_)) => false,
552                Err(e) => return Err(e),
553            };
554            if !source_ok {
555                tracing::warn!(
556                    source = %ee.source,
557                    target = %ee.target,
558                    relation = ?ee.relation,
559                    "import_kg: skipping edge — source entity not found in namespace {ns:?}"
560                );
561                skipped_edges.push(ImportSkippedEdge {
562                    edge_id: ee.edge_id,
563                    source: ee.source,
564                    target: ee.target,
565                    relation: ee.relation,
566                    cause: ImportEdgeSkipCause::MissingSource,
567                    error: None,
568                });
569                continue;
570            }
571            let target_ok = match self.get_entity(token, ee.target).await {
572                Ok(_) => true,
573                Err(RuntimeError::NotFound(_)) => false,
574                Err(e) => return Err(e),
575            };
576            if !target_ok {
577                tracing::warn!(
578                    source = %ee.source,
579                    target = %ee.target,
580                    relation = ?ee.relation,
581                    "import_kg: skipping edge — target entity not found in namespace {ns:?}"
582                );
583                skipped_edges.push(ImportSkippedEdge {
584                    edge_id: ee.edge_id,
585                    source: ee.source,
586                    target: ee.target,
587                    relation: ee.relation,
588                    cause: ImportEdgeSkipCause::MissingTarget,
589                    error: None,
590                });
591                continue;
592            }
593            // Only a contract verdict (InvalidInput) or an endpoint-resolution
594            // miss (NotFound) is a property of the edge being imported; any
595            // other error is an operational failure of the check itself and
596            // must abort the import rather than silently discard a valid edge.
597            match self
598                .validate_edge_relation_endpoints(token, ee.source, ee.target, ee.relation)
599                .await
600            {
601                Ok(_) => {}
602                Err(e @ (RuntimeError::InvalidInput(_) | RuntimeError::NotFound(_))) => {
603                    tracing::warn!(
604                        source = %ee.source,
605                        target = %ee.target,
606                        relation = ?ee.relation,
607                        error = %e,
608                        "import_kg: skipping edge — endpoint contract violation in namespace {ns:?}"
609                    );
610                    skipped_edges.push(ImportSkippedEdge {
611                        edge_id: ee.edge_id,
612                        source: ee.source,
613                        target: ee.target,
614                        relation: ee.relation,
615                        cause: ImportEdgeSkipCause::EndpointContract,
616                        error: Some(e.to_string()),
617                    });
618                    continue;
619                }
620                Err(e) => return Err(e),
621            }
622            let edge = khive_storage::types::Edge {
623                id: LinkId::from(ee.edge_id),
624                namespace: ns.clone(),
625                source_id: ee.source,
626                target_id: ee.target,
627                relation: ee.relation,
628                weight: ee.weight,
629                created_at: ee.created_at,
630                updated_at: ee.updated_at,
631                deleted_at: None,
632                metadata: ee.properties.clone(),
633                target_backend: None,
634            };
635            graph.upsert_edge(edge).await?;
636            edges_imported += 1;
637        }
638
639        Ok(ImportSummary {
640            entities_imported,
641            edges_imported,
642            edges_skipped: skipped_edges.len(),
643            skipped_edges,
644            embedding_truncation,
645        })
646    }
647
648    /// Import from a JSON string (convenience wrapper around `import_kg`).
649    pub async fn import_kg_json(
650        &self,
651        json: &str,
652        token: &NamespaceToken,
653    ) -> RuntimeResult<ImportSummary> {
654        self.import_kg_json_with_policy(json, token, ImportKindPolicy::Strict)
655            .await
656    }
657
658    /// Decode and import JSON with explicit unknown-entity-kind admission.
659    /// Closed edge relations still fail during deserialization.
660    pub async fn import_kg_json_with_policy(
661        &self,
662        json: &str,
663        token: &NamespaceToken,
664        policy: ImportKindPolicy,
665    ) -> RuntimeResult<ImportSummary> {
666        let archive: KgArchive =
667            serde_json::from_str(json).map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;
668        self.import_kg_with_policy(&archive, token, policy).await
669    }
670}
671
672#[cfg(test)]
673#[path = "portability_import_policy_tests.rs"]
674mod import_policy_tests;
675
676// ── Tests ─────────────────────────────────────────────────────────────────────
677
678// Kept inline: these tests exercise round-trip invariants over private encoding
679// helpers that would otherwise need to be made pub to test from tests/.
680#[cfg(test)]
681mod tests {
682    use std::sync::atomic::{AtomicUsize, Ordering};
683    use std::sync::Arc;
684
685    use super::*;
686    use crate::runtime::{KhiveRuntime, NamespaceToken};
687    use crate::{EmbedderProvider, Namespace};
688    use async_trait::async_trait;
689    use khive_storage::EdgeRelation;
690    use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_BYTES};
691
692    const IMPORT_TEST_MODEL: &str = "all-minilm-l6-v2";
693    const IMPORT_BATCH_MODEL: &str = "import-batch-model";
694    const IMPORT_BATCH_MODEL_TWO: &str = "import-batch-model-two";
695
696    struct CountingImportService {
697        calls: Arc<AtomicUsize>,
698        reject_poison: bool,
699    }
700
701    #[async_trait]
702    impl EmbeddingService for CountingImportService {
703        async fn embed(
704            &self,
705            texts: &[String],
706            _model: EmbeddingModel,
707        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
708            self.calls.fetch_add(1, Ordering::SeqCst);
709            if self.reject_poison
710                && (texts.len() > 1 || texts.iter().any(|text| text.contains("poison")))
711            {
712                return Err(EmbedError::InferenceFailed("poison input".into()));
713            }
714            Ok(texts
715                .iter()
716                .map(|text| {
717                    vec![
718                        text.len() as f32,
719                        text.bytes().map(u32::from).sum::<u32>() as f32,
720                        text.as_bytes().first().copied().unwrap_or_default() as f32,
721                        text.as_bytes().last().copied().unwrap_or_default() as f32,
722                    ]
723                })
724                .collect())
725        }
726
727        fn supports_model(&self, _model: EmbeddingModel) -> bool {
728            true
729        }
730
731        fn name(&self) -> &'static str {
732            "import-batch-counting-service"
733        }
734    }
735
736    struct CountingImportProvider {
737        name: &'static str,
738        calls: Arc<AtomicUsize>,
739        reject_poison: bool,
740    }
741
742    #[async_trait]
743    impl EmbedderProvider for CountingImportProvider {
744        fn name(&self) -> &str {
745            self.name
746        }
747
748        fn dimensions(&self) -> usize {
749            4
750        }
751
752        async fn build(&self) -> std::result::Result<Arc<dyn EmbeddingService>, RuntimeError> {
753            Ok(Arc::new(CountingImportService {
754                calls: Arc::clone(&self.calls),
755                reject_poison: self.reject_poison,
756            }))
757        }
758    }
759
760    fn batch_archive(names: impl IntoIterator<Item = String>) -> KgArchive {
761        KgArchive {
762            format: "khive-kg".to_string(),
763            version: "0.1".to_string(),
764            namespace: "local".to_string(),
765            exported_at: Utc::now(),
766            entities: names
767                .into_iter()
768                .map(|name| ExportedEntity {
769                    keys: Vec::new(),
770                    aliases: Vec::new(),
771                    id: Uuid::new_v4(),
772                    kind: "concept".to_string(),
773                    entity_type: None,
774                    name,
775                    description: Some("batch body".to_string()),
776                    properties: None,
777                    tags: vec![],
778                    created_at: Utc::now(),
779                    updated_at: Utc::now(),
780                })
781                .collect(),
782            edges: vec![],
783        }
784    }
785
786    struct ImportEmbeddingService;
787
788    #[async_trait]
789    impl EmbeddingService for ImportEmbeddingService {
790        async fn embed(
791            &self,
792            texts: &[String],
793            _model: EmbeddingModel,
794        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
795            let dimensions = EmbeddingModel::AllMiniLmL6V2.dimensions();
796            Ok(texts.iter().map(|_| vec![1.0; dimensions]).collect())
797        }
798
799        fn supports_model(&self, _model: EmbeddingModel) -> bool {
800            true
801        }
802
803        fn name(&self) -> &'static str {
804            "kg-import-truncation-test"
805        }
806    }
807
808    struct ImportEmbeddingProvider;
809
810    #[async_trait]
811    impl EmbedderProvider for ImportEmbeddingProvider {
812        fn name(&self) -> &str {
813            IMPORT_TEST_MODEL
814        }
815
816        fn dimensions(&self) -> usize {
817            EmbeddingModel::AllMiniLmL6V2.dimensions()
818        }
819
820        async fn build(&self) -> std::result::Result<Arc<dyn EmbeddingService>, RuntimeError> {
821            Ok(Arc::new(ImportEmbeddingService))
822        }
823    }
824
825    async fn make_rt() -> KhiveRuntime {
826        KhiveRuntime::memory().expect("in-memory runtime")
827    }
828
829    fn make_rt_with_embedder() -> KhiveRuntime {
830        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
831        runtime.register_embedder(ImportEmbeddingProvider);
832        runtime
833    }
834
835    #[test]
836    fn archive_timestamp_falls_back_only_when_absent_and_converts_offsets_to_utc() {
837        let fallback = DateTime::parse_from_rfc3339("2020-01-01T00:00:00Z")
838            .unwrap()
839            .with_timezone(&Utc);
840        assert_eq!(parse_archive_timestamp(None, fallback).unwrap(), fallback);
841
842        let utc = parse_archive_timestamp(Some("2024-05-06T07:08:09Z"), fallback).unwrap();
843        assert_eq!(utc.to_rfc3339(), "2024-05-06T07:08:09+00:00");
844
845        let offset = parse_archive_timestamp(Some("2024-05-06T09:08:09+02:00"), fallback).unwrap();
846        assert_eq!(offset, utc);
847
848        let err = parse_archive_timestamp(Some("2024-05-06 07:08:09"), fallback).unwrap_err();
849        let text = format!("{err:#}");
850        assert!(text.contains("\"2024-05-06 07:08:09\""), "{text}");
851        assert!(text.contains("must be RFC3339"), "{text}");
852        assert!(
853            err.chain().count() > 1,
854            "parser source error is kept: {text}"
855        );
856    }
857
858    #[tokio::test]
859    async fn import_batches_provider_calls_and_matches_per_record_reindex_vectors() {
860        let token = NamespaceToken::local();
861        let archive = batch_archive((0..257).map(|index| format!("Batch entity {index}")));
862        let ids: Vec<Uuid> = archive.entities.iter().map(|entity| entity.id).collect();
863        let calls = Arc::new(AtomicUsize::new(0));
864        let runtime = KhiveRuntime::memory().unwrap();
865        runtime.register_embedder(CountingImportProvider {
866            name: IMPORT_BATCH_MODEL,
867            calls: Arc::clone(&calls),
868            reject_poison: false,
869        });
870        let usage = crate::usage::UsageContext::new();
871        let summary = crate::usage::scope(usage.clone(), runtime.import_kg(&archive, &token))
872            .await
873            .unwrap();
874        assert_eq!(summary.entities_imported, ids.len());
875        assert_eq!(usage.snapshot()["embed_calls"], ids.len() as u64);
876        assert_eq!(
877            calls.load(Ordering::SeqCst),
878            2,
879            "257 records need two provider batches"
880        );
881
882        let singles = KhiveRuntime::memory().unwrap();
883        let singleton_calls = Arc::new(AtomicUsize::new(0));
884        singles.register_embedder(CountingImportProvider {
885            name: IMPORT_BATCH_MODEL,
886            calls: Arc::clone(&singleton_calls),
887            reject_poison: false,
888        });
889        for id in &ids {
890            let entity = runtime.get_entity(&token, *id).await.unwrap();
891            singles
892                .entities(&token)
893                .unwrap()
894                .upsert_entity(entity.clone())
895                .await
896                .unwrap();
897            singles.reindex_entity(&token, &entity).await.unwrap();
898        }
899        assert_eq!(singleton_calls.load(Ordering::SeqCst), ids.len());
900        let batched_vectors = runtime
901            .vectors_for_model(&token, IMPORT_BATCH_MODEL)
902            .unwrap()
903            .get_vectors(&ids, "local", "entity.body")
904            .await
905            .unwrap();
906        let singleton_vectors = singles
907            .vectors_for_model(&token, IMPORT_BATCH_MODEL)
908            .unwrap()
909            .get_vectors(&ids, "local", "entity.body")
910            .await
911            .unwrap();
912        assert_eq!(batched_vectors.len(), ids.len());
913        assert_eq!(batched_vectors, singleton_vectors);
914    }
915
916    #[tokio::test]
917    async fn import_batches_each_registered_model_once_per_page() {
918        let token = NamespaceToken::local();
919        let archive = batch_archive(["alpha", "beta", "gamma"].map(str::to_string));
920        let calls_a = Arc::new(AtomicUsize::new(0));
921        let calls_b = Arc::new(AtomicUsize::new(0));
922        let runtime = KhiveRuntime::memory().unwrap();
923        for (name, calls) in [
924            (IMPORT_BATCH_MODEL, Arc::clone(&calls_a)),
925            (IMPORT_BATCH_MODEL_TWO, Arc::clone(&calls_b)),
926        ] {
927            runtime.register_embedder(CountingImportProvider {
928                name,
929                calls,
930                reject_poison: false,
931            });
932        }
933        runtime.import_kg(&archive, &token).await.unwrap();
934        assert_eq!(calls_a.load(Ordering::SeqCst), 1);
935        assert_eq!(calls_b.load(Ordering::SeqCst), 1);
936        let ids: Vec<Uuid> = archive.entities.iter().map(|entity| entity.id).collect();
937        for model in [IMPORT_BATCH_MODEL, IMPORT_BATCH_MODEL_TWO] {
938            assert_eq!(
939                runtime
940                    .vectors_for_model(&token, model)
941                    .unwrap()
942                    .get_vectors(&ids, "local", "entity.body")
943                    .await
944                    .unwrap()
945                    .len(),
946                ids.len()
947            );
948        }
949    }
950
951    #[tokio::test]
952    async fn import_failed_batch_isolates_poison_without_duplicate_vector_writes() {
953        use khive_storage::types::{SqlStatement, SqlValue};
954
955        let token = NamespaceToken::local();
956        let archive = batch_archive(["good one", "poison", "good two"].map(str::to_string));
957        let ids: Vec<Uuid> = archive.entities.iter().map(|entity| entity.id).collect();
958        let calls = Arc::new(AtomicUsize::new(0));
959        let runtime = KhiveRuntime::memory().unwrap();
960        runtime.register_embedder(CountingImportProvider {
961            name: IMPORT_BATCH_MODEL,
962            calls: Arc::clone(&calls),
963            reject_poison: true,
964        });
965        let summary = runtime.import_kg(&archive, &token).await.unwrap();
966        assert_eq!(summary.entities_imported, 3);
967        assert_eq!(
968            calls.load(Ordering::SeqCst),
969            4,
970            "one failed page plus three singleton retries"
971        );
972        let vectors = runtime
973            .vectors_for_model(&token, IMPORT_BATCH_MODEL)
974            .unwrap()
975            .get_vectors(&ids, "local", "entity.body")
976            .await
977            .unwrap();
978        assert_eq!(vectors.len(), 2);
979        assert!(!vectors.contains_key(&ids[1]));
980        let mut reader = runtime.sql().reader().await.unwrap();
981        let rows = reader
982            .query_all(SqlStatement {
983                sql: "SELECT COUNT(*) FROM ann_write_log WHERE embedding_model = ?1 AND op = 'upsert'".into(),
984                params: vec![SqlValue::Text(IMPORT_BATCH_MODEL.into())],
985                label: Some("import-batch-upsert-count".into()),
986            })
987            .await
988            .unwrap();
989        assert!(matches!(&rows[0].columns[0].value, SqlValue::Integer(2)));
990        let provenance = reader
991            .query_scalar(SqlStatement {
992                sql: "SELECT COUNT(*) FROM vector_provenance WHERE model_key = ?1".into(),
993                params: vec![SqlValue::Text(crate::config::sanitize_key(
994                    IMPORT_BATCH_MODEL,
995                ))],
996                label: Some("import-batch-provenance-count".into()),
997            })
998            .await
999            .unwrap();
1000        assert!(matches!(provenance, Some(SqlValue::Integer(0))));
1001    }
1002
1003    #[tokio::test]
1004    async fn import_summary_reports_actual_embedding_truncation() {
1005        let runtime = make_rt_with_embedder();
1006        let token = NamespaceToken::local();
1007        let archive = KgArchive {
1008            format: "khive-kg".to_string(),
1009            version: "0.1".to_string(),
1010            namespace: "local".to_string(),
1011            exported_at: Utc::now(),
1012            entities: vec![ExportedEntity {
1013                keys: Vec::new(),
1014                aliases: Vec::new(),
1015                id: Uuid::new_v4(),
1016                kind: "concept".to_string(),
1017                entity_type: None,
1018                name: "Imported long entity".to_string(),
1019                description: Some("x".repeat(MAX_TEXT_BYTES + 1)),
1020                properties: None,
1021                tags: vec![],
1022                created_at: Utc::now(),
1023                updated_at: Utc::now(),
1024            }],
1025            edges: vec![],
1026        };
1027
1028        let summary = runtime
1029            .import_kg(&archive, &token)
1030            .await
1031            .expect("import with bounded embedding input");
1032
1033        assert_eq!(summary.entities_imported, 1);
1034        assert_eq!(summary.embedding_truncation.truncated, 1);
1035        assert!(summary.embedding_truncation.discarded_bytes > 0);
1036        let wire = serde_json::to_value(&summary).expect("serialize import summary");
1037        assert_eq!(wire["embedding_truncation"]["truncated"], 1);
1038    }
1039
1040    #[tokio::test]
1041    async fn import_rejects_whitespace_name_before_any_entity_write() {
1042        let runtime = make_rt().await;
1043        let token = NamespaceToken::local();
1044        let valid_id = Uuid::new_v4();
1045        let archive = KgArchive {
1046            format: "khive-kg".to_string(),
1047            version: "0.1".to_string(),
1048            namespace: "local".to_string(),
1049            exported_at: Utc::now(),
1050            entities: vec![
1051                ExportedEntity {
1052                    keys: Vec::new(),
1053                    aliases: Vec::new(),
1054                    id: valid_id,
1055                    kind: "concept".to_string(),
1056                    entity_type: None,
1057                    name: "Must not be written".to_string(),
1058                    description: None,
1059                    properties: None,
1060                    tags: vec![],
1061                    created_at: Utc::now(),
1062                    updated_at: Utc::now(),
1063                },
1064                ExportedEntity {
1065                    keys: Vec::new(),
1066                    aliases: Vec::new(),
1067                    id: Uuid::new_v4(),
1068                    kind: "concept".to_string(),
1069                    entity_type: None,
1070                    name: " \t\n ".to_string(),
1071                    description: None,
1072                    properties: None,
1073                    tags: vec![],
1074                    created_at: Utc::now(),
1075                    updated_at: Utc::now(),
1076                },
1077            ],
1078            edges: vec![],
1079        };
1080
1081        let err = runtime
1082            .import_kg(&archive, &token)
1083            .await
1084            .expect_err("whitespace-only entity names must fail the whole import");
1085        assert!(
1086            err.to_string().contains("non-blank"),
1087            "error must explain the name invariant: {err}"
1088        );
1089        assert!(
1090            runtime.get_entity(&token, valid_id).await.is_err(),
1091            "deterministic validation must finish before the first entity write"
1092        );
1093    }
1094
1095    /// 1. Roundtrip: 3 entities + 2 edges survive export → import on a fresh runtime.
1096    #[tokio::test]
1097    async fn roundtrip_entities_and_edges() {
1098        let src = make_rt().await;
1099        let tok = NamespaceToken::local();
1100        let e1 = src
1101            .create_entity(
1102                &tok,
1103                "concept",
1104                None,
1105                "FlashAttention",
1106                Some("fast attention"),
1107                None,
1108                vec![],
1109            )
1110            .await
1111            .unwrap();
1112        let e2 = src
1113            .create_entity(
1114                &tok,
1115                "concept",
1116                None,
1117                "FlashAttention-2",
1118                None,
1119                None,
1120                vec![],
1121            )
1122            .await
1123            .unwrap();
1124        let e3 = src
1125            .create_entity(
1126                &tok,
1127                "person",
1128                None,
1129                "Tri Dao",
1130                None,
1131                None,
1132                vec!["author".into()],
1133            )
1134            .await
1135            .unwrap();
1136        src.link(&tok, e2.id, e1.id, EdgeRelation::Extends, 1.0, None)
1137            .await
1138            .unwrap();
1139        src.link(&tok, e1.id, e3.id, EdgeRelation::IntroducedBy, 0.9, None)
1140            .await
1141            .unwrap();
1142
1143        let archive = src.export_kg(&tok).await.unwrap();
1144        assert_eq!(archive.entities.len(), 3);
1145        assert_eq!(archive.edges.len(), 2);
1146        assert_eq!(archive.format, "khive-kg");
1147        assert_eq!(archive.version, "0.1");
1148
1149        let dst = make_rt().await;
1150        let summary = dst.import_kg(&archive, &tok).await.unwrap();
1151        assert_eq!(summary.entities_imported, 3);
1152        assert_eq!(summary.edges_imported, 2);
1153
1154        let got = dst.get_entity(&tok, e1.id).await.unwrap();
1155        assert_eq!(got.name, "FlashAttention");
1156        assert_eq!(got.description.as_deref(), Some("fast attention"));
1157    }
1158
1159    /// 2. JSON roundtrip: export_kg_json → import_kg_json produces equivalent state.
1160    #[tokio::test]
1161    async fn json_roundtrip() {
1162        let src = make_rt().await;
1163        let tok = NamespaceToken::local();
1164        let e1 = src
1165            .create_entity(
1166                &tok,
1167                "concept",
1168                None,
1169                "LoRA",
1170                Some("low-rank adaptation"),
1171                Some(serde_json::json!({"year": "2021"})),
1172                vec!["fine-tuning".into()],
1173            )
1174            .await
1175            .unwrap();
1176        let e2 = src
1177            .create_entity(&tok, "concept", None, "QLoRA", None, None, vec![])
1178            .await
1179            .unwrap();
1180        src.link(&tok, e2.id, e1.id, EdgeRelation::VariantOf, 0.9, None)
1181            .await
1182            .unwrap();
1183
1184        let json_str = src.export_kg_json(&tok).await.unwrap();
1185        assert!(json_str.contains("khive-kg"));
1186
1187        let dst = make_rt().await;
1188        let summary = dst.import_kg_json(&json_str, &tok).await.unwrap();
1189        assert_eq!(summary.entities_imported, 2);
1190        assert_eq!(summary.edges_imported, 1);
1191
1192        let got = dst.get_entity(&tok, e1.id).await.unwrap();
1193        assert_eq!(got.tags, vec!["fine-tuning"]);
1194    }
1195
1196    /// 3. Namespace targeting: export from namespace "a", import into namespace "b" on a
1197    ///    fresh runtime — entities land in "b", and the source runtime's "a" is unaffected.
1198    ///
1199    ///    Note: source and destination are separate runtimes (separate in-memory DBs).
1200    ///    Same-DB cross-namespace copy is not a portability use case — portability is about
1201    ///    moving graphs between instances, not between namespaces within one instance.
1202    #[tokio::test]
1203    async fn namespace_targeting() {
1204        let src = make_rt().await;
1205        let tok_a = NamespaceToken::for_namespace(Namespace::parse("a").unwrap());
1206        let tok_b = NamespaceToken::for_namespace(Namespace::parse("b").unwrap());
1207        src.create_entity(&tok_a, "concept", None, "Sinkhorn", None, None, vec![])
1208            .await
1209            .unwrap();
1210
1211        let archive = src.export_kg(&tok_a).await.unwrap();
1212        assert_eq!(archive.namespace, "a");
1213
1214        let dst = make_rt().await;
1215        let summary = dst.import_kg(&archive, &tok_b).await.unwrap();
1216        assert_eq!(summary.entities_imported, 1);
1217
1218        let in_b = dst.list_entities(&tok_b, None, None, 100, 0).await.unwrap();
1219        assert_eq!(in_b.len(), 1);
1220        assert_eq!(in_b[0].name, "Sinkhorn");
1221
1222        let in_a = src.list_entities(&tok_a, None, None, 100, 0).await.unwrap();
1223        assert_eq!(in_a.len(), 1);
1224
1225        let dst_a = dst.list_entities(&tok_a, None, None, 100, 0).await.unwrap();
1226        assert_eq!(dst_a.len(), 0);
1227    }
1228
1229    /// 4. Format validation: wrong `format` field → InvalidInput.
1230    #[tokio::test]
1231    async fn format_validation_rejects_wrong_format() {
1232        let rt = make_rt().await;
1233        let tok = NamespaceToken::local();
1234        let bad = KgArchive {
1235            format: "wrong".to_string(),
1236            version: "0.1".to_string(),
1237            namespace: "local".to_string(),
1238            exported_at: Utc::now(),
1239            entities: vec![],
1240            edges: vec![],
1241        };
1242        let err = rt.import_kg(&bad, &tok).await.unwrap_err();
1243        assert!(matches!(err, RuntimeError::InvalidInput(_)));
1244    }
1245
1246    /// 5. Unsupported archive version → InvalidInput.
1247    #[tokio::test]
1248    async fn import_unsupported_archive_version_returns_error() {
1249        let rt = make_rt().await;
1250        let tok = NamespaceToken::local();
1251        let bad = KgArchive {
1252            format: "khive-kg".to_string(),
1253            version: "999.0".to_string(),
1254            namespace: "local".to_string(),
1255            exported_at: Utc::now(),
1256            entities: vec![],
1257            edges: vec![],
1258        };
1259        let err = rt.import_kg(&bad, &tok).await.unwrap_err();
1260        assert!(
1261            matches!(err, RuntimeError::InvalidInput(_)),
1262            "expected InvalidInput, got {err:?}"
1263        );
1264        if let RuntimeError::InvalidInput(msg) = err {
1265            assert!(
1266                msg.contains("999.0"),
1267                "error message should mention the unsupported version, got: {msg:?}"
1268            );
1269        }
1270    }
1271
1272    /// ADR-115 Amendment 1 §3: an archive entity carrying the reserved
1273    /// `khive:secret_gate` property key must be rejected before any upsert —
1274    /// import is a caller-controlled write path and stays reservation-only.
1275    #[tokio::test]
1276    async fn import_entity_with_reserved_secret_gate_property_is_rejected() {
1277        let rt = make_rt().await;
1278        let tok = NamespaceToken::local();
1279        let archive = KgArchive {
1280            format: "khive-kg".to_string(),
1281            version: "0.1".to_string(),
1282            namespace: "local".to_string(),
1283            exported_at: Utc::now(),
1284            entities: vec![ExportedEntity {
1285                keys: Vec::new(),
1286                aliases: Vec::new(),
1287                id: Uuid::new_v4(),
1288                kind: "concept".to_string(),
1289                entity_type: None,
1290                name: "ReservedKeyImport".to_string(),
1291                description: None,
1292                properties: Some(serde_json::json!({
1293                    "khive:secret_gate": "exempted:content-sha256-manifest-v1"
1294                })),
1295                tags: vec![],
1296                created_at: Utc::now(),
1297                updated_at: Utc::now(),
1298            }],
1299            edges: vec![],
1300        };
1301
1302        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
1303        assert!(
1304            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
1305            "expected a reservation rejection, got {err:?}"
1306        );
1307
1308        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
1309        assert!(
1310            !entities.iter().any(|e| e.name == "ReservedKeyImport"),
1311            "rejected archive import must not create the entity"
1312        );
1313    }
1314
1315    /// ADR-115 Amendment 1 section 3 on the keyed import route: an archive
1316    /// entity that carries keys and aliases is written with them in one
1317    /// transaction, and the reserved property is refused before that write.
1318    #[tokio::test]
1319    async fn keyed_import_entity_with_reserved_secret_gate_property_is_rejected() {
1320        let rt = make_rt().await;
1321        let tok = NamespaceToken::local();
1322        let archive = KgArchive {
1323            format: "khive-kg".to_string(),
1324            version: "0.1".to_string(),
1325            namespace: "local".to_string(),
1326            exported_at: Utc::now(),
1327            entities: vec![ExportedEntity {
1328                keys: vec!["reserved-keyed-import".to_string()],
1329                aliases: Vec::new(),
1330                id: Uuid::new_v4(),
1331                kind: "concept".to_string(),
1332                entity_type: None,
1333                name: "ReservedKeyedImport".to_string(),
1334                description: None,
1335                properties: Some(serde_json::json!({
1336                    "khive:secret_gate": "exempted:content-sha256-manifest-v1"
1337                })),
1338                tags: vec![],
1339                created_at: Utc::now(),
1340                updated_at: Utc::now(),
1341            }],
1342            edges: vec![],
1343        };
1344
1345        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
1346        assert!(
1347            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
1348            "expected a reservation rejection, got {err:?}"
1349        );
1350
1351        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
1352        assert!(
1353            !entities.iter().any(|e| e.name == "ReservedKeyedImport"),
1354            "rejected keyed archive import must not create the entity"
1355        );
1356    }
1357
1358    /// ADR-115 Amendment 1 §3: an archive edge carrying the reserved
1359    /// `khive:secret_gate` property key is rejected in the same deterministic
1360    /// pre-write pass as entities — edge metadata is a properties-bearing
1361    /// write path.
1362    #[tokio::test]
1363    async fn import_edge_with_reserved_secret_gate_property_is_rejected() {
1364        let rt = make_rt().await;
1365        let tok = NamespaceToken::local();
1366        let a = Uuid::new_v4();
1367        let b = Uuid::new_v4();
1368        let mk = |id: Uuid, name: &str| ExportedEntity {
1369            keys: Vec::new(),
1370            aliases: Vec::new(),
1371            id,
1372            kind: "concept".to_string(),
1373            entity_type: None,
1374            name: name.to_string(),
1375            description: None,
1376            properties: None,
1377            tags: vec![],
1378            created_at: Utc::now(),
1379            updated_at: Utc::now(),
1380        };
1381        let archive = KgArchive {
1382            format: "khive-kg".to_string(),
1383            version: "0.1".to_string(),
1384            namespace: "local".to_string(),
1385            exported_at: Utc::now(),
1386            entities: vec![mk(a, "EdgeGateA"), mk(b, "EdgeGateB")],
1387            edges: vec![ExportedEdge {
1388                edge_id: Uuid::new_v4(),
1389                source: a,
1390                target: b,
1391                relation: EdgeRelation::Extends,
1392                weight: 0.5,
1393                properties: Some(serde_json::json!({
1394                    "khive:secret_gate": "exempted:content-sha256-manifest-v1"
1395                })),
1396                created_at: Utc::now(),
1397                updated_at: Utc::now(),
1398            }],
1399        };
1400
1401        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
1402        assert!(
1403            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
1404            "expected a reservation rejection, got {err:?}"
1405        );
1406
1407        // The rejection happens before any write, so the archive's entities
1408        // must not have been created either.
1409        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
1410        assert!(
1411            !entities.iter().any(|e| e.name == "EdgeGateA"),
1412            "rejected archive import must not create any records"
1413        );
1414    }
1415
1416    /// ADR-115 Amendment 1 §3: edge metadata is in the unchanged
1417    /// blocking-scanner class, so a credential-shaped value in edge
1418    /// properties fails the import in the same pre-write pass.
1419    #[tokio::test]
1420    async fn import_edge_with_credential_shaped_property_is_rejected() {
1421        let rt = make_rt().await;
1422        let tok = NamespaceToken::local();
1423        let a = Uuid::new_v4();
1424        let b = Uuid::new_v4();
1425        let mk = |id: Uuid, name: &str| ExportedEntity {
1426            keys: Vec::new(),
1427            aliases: Vec::new(),
1428            id,
1429            kind: "concept".to_string(),
1430            entity_type: None,
1431            name: name.to_string(),
1432            description: None,
1433            properties: None,
1434            tags: vec![],
1435            created_at: Utc::now(),
1436            updated_at: Utc::now(),
1437        };
1438        let archive = KgArchive {
1439            format: "khive-kg".to_string(),
1440            version: "0.1".to_string(),
1441            namespace: "local".to_string(),
1442            exported_at: Utc::now(),
1443            entities: vec![mk(a, "EdgeScanA"), mk(b, "EdgeScanB")],
1444            edges: vec![ExportedEdge {
1445                edge_id: Uuid::new_v4(),
1446                source: a,
1447                target: b,
1448                relation: EdgeRelation::Extends,
1449                weight: 0.5,
1450                properties: Some(serde_json::json!({
1451                    "api_key": "AKIAFAKEKEY1234567890"
1452                })),
1453                created_at: Utc::now(),
1454                updated_at: Utc::now(),
1455            }],
1456        };
1457
1458        let err = rt.import_kg(&archive, &tok).await.unwrap_err();
1459        assert!(
1460            matches!(err, RuntimeError::SecretDetected(_)),
1461            "expected the blocking scanner to reject the value, got {err:?}"
1462        );
1463
1464        let entities = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
1465        assert!(
1466            !entities.iter().any(|e| e.name == "EdgeScanA"),
1467            "rejected archive import must not create any records"
1468        );
1469    }
1470
1471    /// 6. Invalid relation in archive → InvalidInput.
1472    #[test]
1473    fn invalid_relation_rejected_at_deserialize() {
1474        let json = r#"{
1475            "format":"khive-kg","version":"0.1","namespace":"local",
1476            "exported_at":"2026-01-01T00:00:00Z",
1477            "entities":[],
1478            "edges":[{"edge_id":"00000000-0000-0000-0000-000000000099",
1479                       "source":"00000000-0000-0000-0000-000000000001",
1480                       "target":"00000000-0000-0000-0000-000000000002",
1481                       "relation":"related_to","weight":0.5}]
1482        }"#;
1483        let result: Result<KgArchive, _> = serde_json::from_str(json);
1484        assert!(
1485            result.is_err(),
1486            "non-canonical relation should fail to deserialize"
1487        );
1488    }
1489
1490    // ── Dangling-edge validation tests ────────────────────────────────────────
1491
1492    /// 6. Edge with dangling source (source UUID not in entity table) is skipped.
1493    ///
1494    /// The archive has one entity + one edge whose source is a phantom UUID.
1495    /// Import succeeds, entities_imported=1, edges_imported=0, edges_skipped=1.
1496    #[tokio::test]
1497    async fn import_edge_with_dangling_source_is_skipped() {
1498        let phantom_source = Uuid::parse_str("deadbeef-dead-4ead-dead-deadbeefcafe").unwrap();
1499
1500        let rt = make_rt().await;
1501        let tok = NamespaceToken::local();
1502        let real = rt
1503            .create_entity(&tok, "concept", None, "Real", None, None, vec![])
1504            .await
1505            .unwrap();
1506
1507        let archive = KgArchive {
1508            format: "khive-kg".to_string(),
1509            version: "0.1".to_string(),
1510            namespace: "local".to_string(),
1511            exported_at: Utc::now(),
1512            entities: vec![ExportedEntity {
1513                keys: Vec::new(),
1514                aliases: Vec::new(),
1515                id: real.id,
1516                kind: "concept".to_string(),
1517                entity_type: None,
1518                name: "Real".to_string(),
1519                description: None,
1520                properties: None,
1521                tags: vec![],
1522                created_at: Utc::now(),
1523                updated_at: Utc::now(),
1524            }],
1525            edges: vec![ExportedEdge {
1526                edge_id: Uuid::new_v4(),
1527                source: phantom_source,
1528                target: real.id,
1529                relation: EdgeRelation::Extends,
1530                weight: 1.0,
1531                properties: None,
1532                created_at: Utc::now(),
1533                updated_at: Utc::now(),
1534            }],
1535        };
1536
1537        let dst = make_rt().await;
1538        let summary = dst.import_kg(&archive, &tok).await.unwrap();
1539        assert_eq!(summary.entities_imported, 1);
1540        assert_eq!(
1541            summary.edges_imported, 0,
1542            "dangling source must not be imported"
1543        );
1544        assert_eq!(
1545            summary.edges_skipped, 1,
1546            "dangling source must be counted as skipped"
1547        );
1548    }
1549
1550    /// 7. Edge with dangling target (target UUID not in entity table) is skipped.
1551    ///
1552    /// The archive has one entity + one edge whose target is a phantom UUID.
1553    /// Import succeeds, entities_imported=1, edges_imported=0, edges_skipped=1.
1554    #[tokio::test]
1555    async fn import_edge_with_dangling_target_is_skipped() {
1556        let phantom_target = Uuid::parse_str("cafebabe-cafe-4abe-cafe-cafebabecafe").unwrap();
1557
1558        let rt = make_rt().await;
1559        let tok = NamespaceToken::local();
1560        let real = rt
1561            .create_entity(&tok, "concept", None, "Source", None, None, vec![])
1562            .await
1563            .unwrap();
1564
1565        let archive = KgArchive {
1566            format: "khive-kg".to_string(),
1567            version: "0.1".to_string(),
1568            namespace: "local".to_string(),
1569            exported_at: Utc::now(),
1570            entities: vec![ExportedEntity {
1571                keys: Vec::new(),
1572                aliases: Vec::new(),
1573                id: real.id,
1574                kind: "concept".to_string(),
1575                entity_type: None,
1576                name: "Source".to_string(),
1577                description: None,
1578                properties: None,
1579                tags: vec![],
1580                created_at: Utc::now(),
1581                updated_at: Utc::now(),
1582            }],
1583            edges: vec![ExportedEdge {
1584                edge_id: Uuid::new_v4(),
1585                source: real.id,
1586                target: phantom_target,
1587                relation: EdgeRelation::DependsOn,
1588                weight: 0.8,
1589                properties: None,
1590                created_at: Utc::now(),
1591                updated_at: Utc::now(),
1592            }],
1593        };
1594
1595        let dst = make_rt().await;
1596        let summary = dst.import_kg(&archive, &tok).await.unwrap();
1597        assert_eq!(summary.entities_imported, 1);
1598        assert_eq!(
1599            summary.edges_imported, 0,
1600            "dangling target must not be imported"
1601        );
1602        assert_eq!(
1603            summary.edges_skipped, 1,
1604            "dangling target must be counted as skipped"
1605        );
1606    }
1607
1608    /// 8. Mixed batch: some valid edges and some dangling edges — correct counts reported.
1609    ///
1610    /// Archive has 3 entities, 2 valid edges, and 1 dangling edge (phantom target).
1611    /// Import succeeds with edges_imported=2, edges_skipped=1.
1612    #[tokio::test]
1613    async fn import_mixed_edges_reports_correct_counts() {
1614        let phantom = Uuid::parse_str("11111111-1111-4111-8111-111111111111").unwrap();
1615
1616        let src = make_rt().await;
1617        let tok = NamespaceToken::local();
1618        let a = src
1619            .create_entity(&tok, "concept", None, "A", None, None, vec![])
1620            .await
1621            .unwrap();
1622        let b = src
1623            .create_entity(&tok, "concept", None, "B", None, None, vec![])
1624            .await
1625            .unwrap();
1626        let c = src
1627            .create_entity(&tok, "concept", None, "C", None, None, vec![])
1628            .await
1629            .unwrap();
1630
1631        let archive = KgArchive {
1632            format: "khive-kg".to_string(),
1633            version: "0.1".to_string(),
1634            namespace: "local".to_string(),
1635            exported_at: Utc::now(),
1636            entities: vec![
1637                ExportedEntity {
1638                    keys: Vec::new(),
1639                    aliases: Vec::new(),
1640                    id: a.id,
1641                    kind: "concept".to_string(),
1642                    entity_type: None,
1643                    name: "A".to_string(),
1644                    description: None,
1645                    properties: None,
1646                    tags: vec![],
1647                    created_at: Utc::now(),
1648                    updated_at: Utc::now(),
1649                },
1650                ExportedEntity {
1651                    keys: Vec::new(),
1652                    aliases: Vec::new(),
1653                    id: b.id,
1654                    kind: "concept".to_string(),
1655                    entity_type: None,
1656                    name: "B".to_string(),
1657                    description: None,
1658                    properties: None,
1659                    tags: vec![],
1660                    created_at: Utc::now(),
1661                    updated_at: Utc::now(),
1662                },
1663                ExportedEntity {
1664                    keys: Vec::new(),
1665                    aliases: Vec::new(),
1666                    id: c.id,
1667                    kind: "concept".to_string(),
1668                    entity_type: None,
1669                    name: "C".to_string(),
1670                    description: None,
1671                    properties: None,
1672                    tags: vec![],
1673                    created_at: Utc::now(),
1674                    updated_at: Utc::now(),
1675                },
1676            ],
1677            edges: vec![
1678                ExportedEdge {
1679                    edge_id: Uuid::new_v4(),
1680                    source: a.id,
1681                    target: b.id,
1682                    relation: EdgeRelation::Extends,
1683                    weight: 1.0,
1684                    properties: None,
1685                    created_at: Utc::now(),
1686                    updated_at: Utc::now(),
1687                },
1688                ExportedEdge {
1689                    edge_id: Uuid::new_v4(),
1690                    source: b.id,
1691                    target: c.id,
1692                    // #1235: concept->concept is not in depends_on's endpoint
1693                    // contract; use variant_of (concept->concept is valid) so
1694                    // this fixture exercises "one dangling edge skipped" only,
1695                    // not an endpoint-contract violation this test isn't about.
1696                    relation: EdgeRelation::VariantOf,
1697                    weight: 0.9,
1698                    properties: None,
1699                    created_at: Utc::now(),
1700                    updated_at: Utc::now(),
1701                },
1702                ExportedEdge {
1703                    edge_id: Uuid::new_v4(),
1704                    source: a.id,
1705                    target: phantom,
1706                    relation: EdgeRelation::Enables,
1707                    weight: 0.5,
1708                    properties: None,
1709                    created_at: Utc::now(),
1710                    updated_at: Utc::now(),
1711                },
1712            ],
1713        };
1714
1715        let dst = make_rt().await;
1716        let summary = dst.import_kg(&archive, &tok).await.unwrap();
1717        assert_eq!(summary.entities_imported, 3);
1718        assert_eq!(
1719            summary.edges_imported, 2,
1720            "only valid edges must be imported"
1721        );
1722        assert_eq!(
1723            summary.edges_skipped, 1,
1724            "one dangling edge must be reported"
1725        );
1726    }
1727
1728    /// 9. All-valid edges produce edges_skipped=0 (no regression on the happy path).
1729    #[tokio::test]
1730    async fn import_all_valid_edges_reports_zero_skipped() {
1731        let src = make_rt().await;
1732        let tok = NamespaceToken::local();
1733        let e1 = src
1734            .create_entity(&tok, "concept", None, "E1", None, None, vec![])
1735            .await
1736            .unwrap();
1737        let e2 = src
1738            .create_entity(&tok, "concept", None, "E2", None, None, vec![])
1739            .await
1740            .unwrap();
1741        src.link(&tok, e1.id, e2.id, EdgeRelation::VariantOf, 0.7, None)
1742            .await
1743            .unwrap();
1744
1745        let archive = src.export_kg(&tok).await.unwrap();
1746        let dst = make_rt().await;
1747        let summary = dst.import_kg(&archive, &tok).await.unwrap();
1748        assert_eq!(summary.edges_imported, 1);
1749        assert_eq!(
1750            summary.edges_skipped, 0,
1751            "no edges should be skipped when all endpoints exist"
1752        );
1753    }
1754
1755    /// #1235: an edge whose (source kind, relation, target kind) triple violates the
1756    /// endpoint contract (here: `precedes` between two `concept` entities — `precedes`
1757    /// is restricted to document/dataset/artifact/service/project pairs) must be
1758    /// skipped by import the same way a dangling endpoint is, not written straight
1759    /// through with `graph.upsert_edge`.
1760    #[tokio::test]
1761    async fn import_edge_violating_endpoint_contract_is_skipped() {
1762        let src = make_rt().await;
1763        let tok = NamespaceToken::local();
1764        let e1 = src
1765            .create_entity(&tok, "concept", None, "E1", None, None, vec![])
1766            .await
1767            .unwrap();
1768        let e2 = src
1769            .create_entity(&tok, "concept", None, "E2", None, None, vec![])
1770            .await
1771            .unwrap();
1772
1773        let archive = KgArchive {
1774            format: "khive-kg".to_string(),
1775            version: "0.1".to_string(),
1776            namespace: "local".to_string(),
1777            exported_at: Utc::now(),
1778            entities: vec![
1779                ExportedEntity {
1780                    keys: Vec::new(),
1781                    aliases: Vec::new(),
1782                    id: e1.id,
1783                    kind: "concept".to_string(),
1784                    entity_type: None,
1785                    name: "E1".to_string(),
1786                    description: None,
1787                    properties: None,
1788                    tags: vec![],
1789                    created_at: Utc::now(),
1790                    updated_at: Utc::now(),
1791                },
1792                ExportedEntity {
1793                    keys: Vec::new(),
1794                    aliases: Vec::new(),
1795                    id: e2.id,
1796                    kind: "concept".to_string(),
1797                    entity_type: None,
1798                    name: "E2".to_string(),
1799                    description: None,
1800                    properties: None,
1801                    tags: vec![],
1802                    created_at: Utc::now(),
1803                    updated_at: Utc::now(),
1804                },
1805            ],
1806            edges: vec![ExportedEdge {
1807                edge_id: Uuid::new_v4(),
1808                source: e1.id,
1809                target: e2.id,
1810                relation: EdgeRelation::Precedes,
1811                weight: 1.0,
1812                properties: None,
1813                created_at: Utc::now(),
1814                updated_at: Utc::now(),
1815            }],
1816        };
1817
1818        let dst = make_rt().await;
1819        let summary = dst.import_kg(&archive, &tok).await.unwrap();
1820        assert_eq!(summary.entities_imported, 2);
1821        assert_eq!(
1822            summary.edges_imported, 0,
1823            "an endpoint-contract-violating edge must not be imported"
1824        );
1825        assert_eq!(
1826            summary.edges_skipped, 1,
1827            "an endpoint-contract-violating edge must be counted as skipped"
1828        );
1829        assert!(
1830            dst.neighbors(
1831                &tok,
1832                e1.id,
1833                khive_storage::types::Direction::Out,
1834                None,
1835                None
1836            )
1837            .await
1838            .unwrap()
1839            .is_empty(),
1840            "the contract-violating edge must not exist in the destination graph"
1841        );
1842    }
1843
1844    // ── edge_id contract tests ────────────────────────────────────────────────
1845
1846    /// 10. export_kg sets edge_id in the archive to the LinkId returned by link.
1847    #[tokio::test]
1848    async fn export_kg_preserves_edge_id() {
1849        let rt = make_rt().await;
1850        let tok = NamespaceToken::local();
1851        let a = rt
1852            .create_entity(&tok, "concept", None, "Alpha", None, None, vec![])
1853            .await
1854            .unwrap();
1855        let b = rt
1856            .create_entity(&tok, "concept", None, "Beta", None, None, vec![])
1857            .await
1858            .unwrap();
1859        let stored_edge = rt
1860            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
1861            .await
1862            .unwrap();
1863        let stored_id: Uuid = stored_edge.id.into();
1864
1865        let archive = rt.export_kg(&tok).await.unwrap();
1866        assert_eq!(archive.edges.len(), 1);
1867        assert_eq!(
1868            archive.edges[0].edge_id, stored_id,
1869            "exported edge_id must equal the LinkId returned by link"
1870        );
1871    }
1872
1873    /// 11. import_kg writes the archive edge identity and timestamps exactly.
1874    #[tokio::test]
1875    async fn import_kg_persists_edge_id_and_timestamps() {
1876        let src = make_rt().await;
1877        let tok = NamespaceToken::local();
1878        let a = src
1879            .create_entity(&tok, "concept", None, "Alpha", None, None, vec![])
1880            .await
1881            .unwrap();
1882        let b = src
1883            .create_entity(&tok, "concept", None, "Beta", None, None, vec![])
1884            .await
1885            .unwrap();
1886        let stored_edge = src
1887            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
1888            .await
1889            .unwrap();
1890        let original_id: Uuid = stored_edge.id.into();
1891
1892        let expected_created = chrono::DateTime::parse_from_rfc3339("2026-03-03T00:00:00Z")
1893            .unwrap()
1894            .with_timezone(&Utc);
1895        let expected_updated = chrono::DateTime::parse_from_rfc3339("2026-04-04T00:00:00Z")
1896            .unwrap()
1897            .with_timezone(&Utc);
1898        let mut archive = src.export_kg(&tok).await.unwrap();
1899        archive.edges[0].created_at = expected_created;
1900        archive.edges[0].updated_at = expected_updated;
1901        archive.edges[0].properties = Some(serde_json::json!({"confidence": 0.95}));
1902        let dst = make_rt().await;
1903        dst.import_kg(&archive, &tok).await.unwrap();
1904
1905        let imported_edge = dst.get_edge(&tok, original_id).await.unwrap();
1906        assert!(
1907            imported_edge.is_some(),
1908            "imported edge must be retrievable by the original edge_id"
1909        );
1910        let imported_edge = imported_edge.unwrap();
1911        assert_eq!(
1912            Uuid::from(imported_edge.id),
1913            original_id,
1914            "stored edge id must equal the archive edge_id"
1915        );
1916        assert_eq!(
1917            imported_edge.created_at, expected_created,
1918            "present edge created_at must not be replaced with import time"
1919        );
1920        assert_eq!(
1921            imported_edge.updated_at, expected_updated,
1922            "present edge updated_at must not be replaced with created_at or import time"
1923        );
1924        assert_eq!(
1925            imported_edge.metadata,
1926            Some(serde_json::json!({"confidence": 0.95})),
1927            "edge properties must persist as storage metadata"
1928        );
1929
1930        let reexported = dst.export_kg(&tok).await.unwrap();
1931        assert_eq!(
1932            reexported.edges[0].properties,
1933            Some(serde_json::json!({"confidence": 0.95})),
1934            "edge metadata must re-export as portable properties"
1935        );
1936    }
1937
1938    /// 12. Old archive (no edge_id field) deserializes, imports, and re-exports with the
1939    ///     same generated UUID — proving the generated ID survives the full round trip.
1940    ///
1941    ///     The fixture includes two entities so the edge is not skipped during import.
1942    #[tokio::test]
1943    async fn old_archive_missing_edge_id_round_trips() {
1944        let src_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
1945        let tgt_id = Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap();
1946
1947        // Simulate a pre-0.2 archive JSON where the edge lacks an edge_id field.
1948        let json = format!(
1949            r#"{{
1950                "format": "khive-kg",
1951                "version": "0.1",
1952                "namespace": "local",
1953                "exported_at": "2026-01-01T00:00:00Z",
1954                "entities": [
1955                    {{"id":"{src_id}","kind":"concept","name":"SrcNode","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}},
1956                    {{"id":"{tgt_id}","kind":"concept","name":"TgtNode","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}}
1957                ],
1958                "edges": [
1959                    {{
1960                        "source": "{src_id}",
1961                        "target": "{tgt_id}",
1962                        "relation": "extends",
1963                        "weight": 0.9
1964                    }}
1965                ]
1966            }}"#
1967        );
1968
1969        // serde(default) must assign a fresh non-nil UUID when edge_id is absent.
1970        let archive: KgArchive = serde_json::from_str(&json)
1971            .expect("old archive without edge_id must deserialize successfully");
1972        assert_eq!(archive.edges.len(), 1);
1973        let generated_id = archive.edges[0].edge_id;
1974        assert_ne!(
1975            generated_id,
1976            Uuid::nil(),
1977            "missing edge_id in old archive must get a fresh non-nil UUID"
1978        );
1979
1980        let rt = make_rt().await;
1981        let tok = NamespaceToken::local();
1982        let summary = rt.import_kg(&archive, &tok).await.unwrap();
1983        assert_eq!(summary.entities_imported, 2);
1984        assert_eq!(
1985            summary.edges_imported, 1,
1986            "edge must be imported when both endpoints exist"
1987        );
1988
1989        let stored = rt.get_edge(&tok, generated_id).await.unwrap();
1990        assert!(
1991            stored.is_some(),
1992            "imported edge must be retrievable by the generated edge_id"
1993        );
1994        assert_eq!(
1995            Uuid::from(stored.unwrap().id),
1996            generated_id,
1997            "stored edge id must equal the generated edge_id"
1998        );
1999
2000        let re_archive = rt.export_kg(&tok).await.unwrap();
2001        assert_eq!(re_archive.edges.len(), 1);
2002        assert_eq!(
2003            re_archive.edges[0].edge_id, generated_id,
2004            "re-exported edge_id must equal the ID generated on first import"
2005        );
2006    }
2007
2008    /// 13. Explicit export → import → export equality: the edge_id is unchanged across
2009    ///     a full round trip when the source archive already contains an edge_id.
2010    ///
2011    ///     Verifies by (source, target, relation) key that re-export emits the original ID.
2012    #[tokio::test]
2013    async fn export_import_export_edge_id_equality() {
2014        let src = make_rt().await;
2015        let tok = NamespaceToken::local();
2016        let a = src
2017            .create_entity(&tok, "concept", None, "NodeA", None, None, vec![])
2018            .await
2019            .unwrap();
2020        let b = src
2021            .create_entity(&tok, "concept", None, "NodeB", None, None, vec![])
2022            .await
2023            .unwrap();
2024        let stored = src
2025            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
2026            .await
2027            .unwrap();
2028        let original_edge_id: Uuid = stored.id.into();
2029
2030        let archive1 = src.export_kg(&tok).await.unwrap();
2031        assert_eq!(archive1.edges.len(), 1);
2032        assert_eq!(
2033            archive1.edges[0].edge_id, original_edge_id,
2034            "first export must carry the stored edge_id"
2035        );
2036
2037        let dst = make_rt().await;
2038        dst.import_kg(&archive1, &tok).await.unwrap();
2039
2040        let archive2 = dst.export_kg(&tok).await.unwrap();
2041        assert_eq!(archive2.edges.len(), 1);
2042
2043        let re_edge = archive2
2044            .edges
2045            .iter()
2046            .find(|e| e.source == a.id && e.target == b.id && e.relation == EdgeRelation::Extends)
2047            .expect(
2048                "re-exported archive must contain the original edge by (source,target,relation)",
2049            );
2050        assert_eq!(
2051            re_edge.edge_id, original_edge_id,
2052            "edge_id must be identical across export → import → export"
2053        );
2054    }
2055
2056    // Skipped-edge details retain archive identity, order and the original refusal.
2057    fn skip_report_entity(id: Uuid, name: &str) -> ExportedEntity {
2058        let timestamp = DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
2059            .unwrap()
2060            .with_timezone(&Utc);
2061        ExportedEntity {
2062            keys: Vec::new(),
2063            aliases: Vec::new(),
2064            id,
2065            kind: "document".into(),
2066            entity_type: None,
2067            name: name.into(),
2068            description: None,
2069            properties: None,
2070            tags: vec![],
2071            created_at: timestamp,
2072            updated_at: timestamp,
2073        }
2074    }
2075
2076    fn skip_report_edge(
2077        id: u128,
2078        source: Uuid,
2079        target: Uuid,
2080        relation: EdgeRelation,
2081    ) -> ExportedEdge {
2082        let timestamp = DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
2083            .unwrap()
2084            .with_timezone(&Utc);
2085        ExportedEdge {
2086            edge_id: Uuid::from_u128(id),
2087            source,
2088            target,
2089            relation,
2090            weight: 0.7,
2091            properties: None,
2092            created_at: timestamp,
2093            updated_at: timestamp,
2094        }
2095    }
2096
2097    fn skip_report_archive(entities: Vec<ExportedEntity>, edges: Vec<ExportedEdge>) -> KgArchive {
2098        KgArchive {
2099            format: "khive-kg".into(),
2100            version: "0.1".into(),
2101            namespace: "local".into(),
2102            exported_at: Utc::now(),
2103            entities,
2104            edges,
2105        }
2106    }
2107
2108    #[tokio::test]
2109    async fn skipped_edge_details_cover_three_causes_and_retain_the_valid_edge() {
2110        let runtime = make_rt().await;
2111        let token = NamespaceToken::local();
2112        let source = Uuid::from_u128(1);
2113        let target = Uuid::from_u128(2);
2114        let absent = Uuid::from_u128(3);
2115        let mut valid = skip_report_edge(101, source, target, EdgeRelation::LinksTo);
2116        valid.properties = Some(serde_json::json!({"retained": true}));
2117        let archive = skip_report_archive(
2118            vec![
2119                skip_report_entity(source, "Source"),
2120                skip_report_entity(target, "Target"),
2121            ],
2122            vec![
2123                skip_report_edge(100, absent, source, EdgeRelation::LinksTo),
2124                valid.clone(),
2125                skip_report_edge(102, source, absent, EdgeRelation::DependsOn),
2126                skip_report_edge(103, source, target, EdgeRelation::Annotates),
2127            ],
2128        );
2129        let summary = runtime.import_kg(&archive, &token).await.unwrap();
2130        let expected = vec![
2131            ImportSkippedEdge {
2132                edge_id: Uuid::from_u128(100),
2133                source: absent,
2134                target: source,
2135                relation: EdgeRelation::LinksTo,
2136                cause: ImportEdgeSkipCause::MissingSource,
2137                error: None,
2138            },
2139            ImportSkippedEdge {
2140                edge_id: Uuid::from_u128(102),
2141                source,
2142                target: absent,
2143                relation: EdgeRelation::DependsOn,
2144                cause: ImportEdgeSkipCause::MissingTarget,
2145                error: None,
2146            },
2147            ImportSkippedEdge {
2148                edge_id: Uuid::from_u128(103),
2149                source,
2150                target,
2151                relation: EdgeRelation::Annotates,
2152                cause: ImportEdgeSkipCause::EndpointContract,
2153                error: Some(format!(
2154                    "invalid input: annotates source {source} must be a note"
2155                )),
2156            },
2157        ];
2158        assert_eq!(summary.entities_imported, 2);
2159        assert_eq!(summary.edges_imported, 1);
2160        assert_eq!(summary.edges_skipped, 3);
2161        assert_eq!(summary.skipped_edges, expected);
2162        let wire = serde_json::to_value(&summary).unwrap();
2163        assert_eq!(
2164            wire["skipped_edges"],
2165            serde_json::json!([
2166                {"edge_id":Uuid::from_u128(100),"source":absent,"target":source,
2167                 "relation":"links_to","cause":"missing_source"},
2168                {"edge_id":Uuid::from_u128(102),"source":source,"target":absent,
2169                 "relation":"depends_on","cause":"missing_target"},
2170                {"edge_id":Uuid::from_u128(103),"source":source,"target":target,
2171                 "relation":"annotates","cause":"endpoint_contract",
2172                 "error":format!("invalid input: annotates source {source} must be a note")}
2173            ])
2174        );
2175        let decoded: ImportSummary = serde_json::from_value(wire).unwrap();
2176        assert_eq!(decoded.skipped_edges, expected);
2177        assert_eq!(decoded.edges_skipped, 3);
2178        for id in [100, 102, 103] {
2179            assert!(runtime
2180                .get_edge(&token, Uuid::from_u128(id))
2181                .await
2182                .unwrap()
2183                .is_none());
2184        }
2185        let stored = runtime
2186            .get_edge(&token, valid.edge_id)
2187            .await
2188            .unwrap()
2189            .unwrap();
2190        assert_eq!(Uuid::from(stored.id), valid.edge_id);
2191        assert_eq!(stored.source_id, source);
2192        assert_eq!(stored.target_id, target);
2193        assert_eq!(stored.relation, EdgeRelation::LinksTo);
2194        assert_eq!(stored.metadata, valid.properties);
2195        assert_eq!(stored.created_at, valid.created_at);
2196        assert_eq!(stored.updated_at, valid.updated_at);
2197        let exported = runtime.export_kg(&token).await.unwrap();
2198        assert_eq!(exported.edges.len(), 1);
2199        assert_eq!(exported.edges[0].edge_id, valid.edge_id);
2200    }
2201
2202    #[tokio::test]
2203    async fn skipped_edge_details_preserve_duplicates_order_and_both_missing_precedence() {
2204        let runtime = make_rt().await;
2205        let token = NamespaceToken::local();
2206        let present = Uuid::from_u128(1);
2207        let absent = Uuid::from_u128(3);
2208        let other_absent = Uuid::from_u128(4);
2209        let repeated = skip_report_edge(111, absent, present, EdgeRelation::LinksTo);
2210        let archive = skip_report_archive(
2211            vec![skip_report_entity(present, "Present")],
2212            vec![
2213                skip_report_edge(110, present, absent, EdgeRelation::DependsOn),
2214                repeated.clone(),
2215                skip_report_edge(112, absent, present, EdgeRelation::LinksTo),
2216                repeated,
2217                skip_report_edge(113, absent, other_absent, EdgeRelation::Extends),
2218            ],
2219        );
2220        let summary = runtime.import_kg(&archive, &token).await.unwrap();
2221        assert_eq!(summary.edges_imported, 0);
2222        assert_eq!(summary.edges_skipped, 5);
2223        assert_eq!(
2224            summary.skipped_edges,
2225            vec![
2226                ImportSkippedEdge {
2227                    edge_id: Uuid::from_u128(110),
2228                    source: present,
2229                    target: absent,
2230                    relation: EdgeRelation::DependsOn,
2231                    cause: ImportEdgeSkipCause::MissingTarget,
2232                    error: None,
2233                },
2234                ImportSkippedEdge {
2235                    edge_id: Uuid::from_u128(111),
2236                    source: absent,
2237                    target: present,
2238                    relation: EdgeRelation::LinksTo,
2239                    cause: ImportEdgeSkipCause::MissingSource,
2240                    error: None,
2241                },
2242                ImportSkippedEdge {
2243                    edge_id: Uuid::from_u128(112),
2244                    source: absent,
2245                    target: present,
2246                    relation: EdgeRelation::LinksTo,
2247                    cause: ImportEdgeSkipCause::MissingSource,
2248                    error: None,
2249                },
2250                ImportSkippedEdge {
2251                    edge_id: Uuid::from_u128(111),
2252                    source: absent,
2253                    target: present,
2254                    relation: EdgeRelation::LinksTo,
2255                    cause: ImportEdgeSkipCause::MissingSource,
2256                    error: None,
2257                },
2258                ImportSkippedEdge {
2259                    edge_id: Uuid::from_u128(113),
2260                    source: absent,
2261                    target: other_absent,
2262                    relation: EdgeRelation::Extends,
2263                    cause: ImportEdgeSkipCause::MissingSource,
2264                    error: None,
2265                },
2266            ]
2267        );
2268        assert!(runtime.export_kg(&token).await.unwrap().edges.is_empty());
2269    }
2270
2271    #[tokio::test]
2272    async fn successful_imports_without_skips_keep_the_previous_json_shape() {
2273        let token = NamespaceToken::local();
2274        let a = Uuid::from_u128(1);
2275        let b = Uuid::from_u128(2);
2276        for (archive, entities, edges) in [
2277            (skip_report_archive(vec![], vec![]), 0, 0),
2278            (
2279                skip_report_archive(
2280                    vec![skip_report_entity(a, "A"), skip_report_entity(b, "B")],
2281                    vec![skip_report_edge(101, a, b, EdgeRelation::LinksTo)],
2282                ),
2283                2,
2284                1,
2285            ),
2286        ] {
2287            let runtime = make_rt().await;
2288            let summary = runtime.import_kg(&archive, &token).await.unwrap();
2289            assert!(summary.skipped_edges.is_empty());
2290            assert_eq!(summary.edges_skipped, 0);
2291            assert_eq!(
2292                serde_json::to_value(&summary).unwrap(),
2293                serde_json::json!({
2294                    "entities_imported":entities,"edges_imported":edges,"edges_skipped":0,
2295                    "embedding_truncation":{"truncated":0,"discarded_bytes":0}
2296                })
2297            );
2298        }
2299    }
2300
2301    #[test]
2302    fn historical_summary_counts_do_not_invent_skipped_edge_details() {
2303        for count in [0, 2] {
2304            let old = serde_json::json!({
2305                "entities_imported":1,"edges_imported":0,"edges_skipped":count
2306            });
2307            let summary: ImportSummary = serde_json::from_value(old).unwrap();
2308            assert_eq!(summary.edges_skipped, count);
2309            assert!(summary.skipped_edges.is_empty());
2310            assert_eq!(
2311                serde_json::to_value(summary).unwrap(),
2312                serde_json::json!({
2313                    "entities_imported":1,"edges_imported":0,"edges_skipped":count,
2314                    "embedding_truncation":{"truncated":0,"discarded_bytes":0}
2315                })
2316            );
2317        }
2318    }
2319
2320    #[test]
2321    fn skipped_edge_cause_spellings_are_closed_and_error_is_preserved_verbatim() {
2322        let wire = serde_json::json!({
2323            "edge_id":"00000000-0000-0000-0000-000000000103",
2324            "source":"00000000-0000-0000-0000-000000000001",
2325            "target":"00000000-0000-0000-0000-000000000002",
2326            "relation":"annotates","cause":"endpoint_contract",
2327            "error":"not found: link target changed during endpoint validation"
2328        });
2329        let detail: ImportSkippedEdge = serde_json::from_value(wire.clone()).unwrap();
2330        assert_eq!(detail.cause, ImportEdgeSkipCause::EndpointContract);
2331        assert_eq!(
2332            detail.error.as_deref(),
2333            Some("not found: link target changed during endpoint validation")
2334        );
2335        assert_eq!(serde_json::to_value(detail).unwrap(), wire);
2336        let mut invalid = wire;
2337        invalid["cause"] = serde_json::json!("storage_failure");
2338        assert!(serde_json::from_value::<ImportSkippedEdge>(invalid).is_err());
2339    }
2340}