Skip to main content

khive_runtime/operations/
link_ops.rs

1use khive_storage::{EdgeInsertIfAbsentOutcome, GraphStatementGuard};
2
3use super::{
4    accepted_entity_relations_description, base_entity_rule_allows, canonical_edge_endpoint_kinds,
5    canonical_edge_endpoints, compose_graph_mutation_events, merge_dependency_kind,
6    pack_rule_allows, validate_edge_metadata, validate_edge_weight, Edge, EdgeEndpointKind,
7    EdgeRelation, EdgeUpsertDisposition, EdgeUpsertRefusal, EdgeUpsertRequest, EdgeUpsertResult,
8    Event, EventKind, GraphMutationOutcome, GraphMutationPreconditions, GraphMutationRequest,
9    GuardedEdgeUpsertOutcome, GuardedWriteFailure, KhiveRuntime, LinkId, LinkSpec, NamespaceToken,
10    Resolved, RuntimeError, RuntimeResult, SubstrateKind, Uuid,
11};
12
13pub(super) fn guarded_link_batch_failure(
14    spec: &LinkSpec,
15    entry_index: usize,
16    missing: khive_storage::MissingEndpoints,
17) -> GuardedWriteFailure {
18    // Storage flags describe the canonical edge built from this spec, not the
19    // caller's potentially reversed spelling of a symmetric relation.
20    let (source_id, target_id) =
21        canonical_edge_endpoints(spec.relation, spec.source_id, spec.target_id);
22    GuardedWriteFailure {
23        entry_index: Some(entry_index),
24        missing_source: missing.source.then_some(source_id),
25        missing_target: missing.target.then_some(target_id),
26    }
27}
28
29impl KhiveRuntime {
30    // ---- Edge operations ----
31
32    /// Validate that `source_id` and `target_id` are legal endpoints for `relation`.
33    ///
34    /// Centralises the three-case relation contract so that both
35    /// `link()` and `update_edge()` share identical enforcement:
36    ///
37    /// - `annotates`: source MUST be a note; target may be any substrate.
38    /// - `supersedes` / `supports` / `refutes`: same-substrate only (note→note or entity→entity).
39    /// - All other relations: both endpoints MUST be entities.
40    ///
41    /// Returns the validated endpoint substrates when valid; otherwise
42    /// `InvalidInput` or `NotFound` for an invalid endpoint pair.
43    ///
44    /// `pub(crate)`: the atomic prepare pass (`crate::atomic_prepare`) reuses
45    /// this exact endpoint-type validation during its async prepare step,
46    /// before building a `LinkPlan`, rather than re-deriving the checks.
47    pub(crate) async fn validate_edge_relation_endpoints(
48        &self,
49        token: &NamespaceToken,
50        source_id: Uuid,
51        target_id: Uuid,
52        relation: EdgeRelation,
53    ) -> RuntimeResult<(EdgeEndpointKind, EdgeEndpointKind)> {
54        if source_id == target_id {
55            return Err(RuntimeError::InvalidInput(
56                "self-loop edges are not allowed: source_id and target_id must be different".into(),
57            ));
58        }
59        if relation == EdgeRelation::Annotates {
60            // Source must be a note. By-ID endpoint resolution is namespace-agnostic:
61            // link consumes two by-ID endpoints, so it must resolve exactly what
62            // get() resolves, regardless of caller namespace.
63            match self.resolve_edge_endpoint(token, source_id).await? {
64                Some(Resolved::Note(_)) => {}
65                Some(_) => {
66                    return Err(RuntimeError::InvalidInput(format!(
67                        "annotates source {source_id} must be a note"
68                    )));
69                }
70                None => {
71                    // Existing edge used as annotates source: wrong kind, not absent.
72                    if self.get_edge(token, source_id).await?.is_some() {
73                        return Err(RuntimeError::InvalidInput(format!(
74                            "annotates source {source_id} must be a note"
75                        )));
76                    }
77                    return Err(RuntimeError::NotFound(format!(
78                        "link source {source_id} not found"
79                    )));
80                }
81            }
82            // Target may be any substrate (entity, note, event, or edge) — by-ID, unfiltered.
83            let target_kind = match self.resolve_edge_endpoint(token, target_id).await? {
84                Some(Resolved::Entity(_)) => EdgeEndpointKind::Entity,
85                Some(Resolved::Note(_)) => EdgeEndpointKind::Note,
86                Some(Resolved::Event(_)) => EdgeEndpointKind::Event,
87                Some(Resolved::PackRecord { .. }) => {
88                    return Err(RuntimeError::InvalidInput(
89                        "pack-private record is not a valid edge endpoint for annotates".into(),
90                    ));
91                }
92                None => match self.get_edge(token, target_id).await {
93                    Ok(Some(_)) => EdgeEndpointKind::Edge,
94                    Ok(None) | Err(RuntimeError::NotFound(_)) => {
95                        return Err(RuntimeError::NotFound(format!(
96                            "link target {target_id} not found"
97                        )));
98                    }
99                    Err(error) => return Err(error),
100                },
101            };
102            return Ok((EdgeEndpointKind::Note, target_kind));
103        } else if crate::pack::is_special_relation(relation) {
104            // supersedes / supports / refutes: same-substrate only (note→note or entity→entity).
105            // Event and edge endpoints are invalid regardless of the other endpoint.
106            // Endpoint resolution is by-ID and namespace-agnostic.
107            let rel_name = relation.as_str();
108            let src = match self.resolve_edge_endpoint(token, source_id).await? {
109                Some(r) => r,
110                None => {
111                    if self.get_edge(token, source_id).await?.is_some() {
112                        return Err(RuntimeError::InvalidInput(format!(
113                            "{rel_name} source {source_id} must be a note or entity (got edge)"
114                        )));
115                    }
116                    return Err(RuntimeError::NotFound(format!(
117                        "link source {source_id} not found"
118                    )));
119                }
120            };
121            let tgt = match self.resolve_edge_endpoint(token, target_id).await? {
122                Some(r) => r,
123                None => {
124                    if self.get_edge(token, target_id).await?.is_some() {
125                        return Err(RuntimeError::InvalidInput(format!(
126                            "{rel_name} target {target_id} must be a note or entity (got edge)"
127                        )));
128                    }
129                    return Err(RuntimeError::NotFound(format!(
130                        "link target {target_id} not found"
131                    )));
132                }
133            };
134            return match (&src, &tgt) {
135                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
136                    if !base_entity_rule_allows(&src_e.kind, relation, &tgt_e.kind) {
137                        let legal_relations = accepted_entity_relations_description(
138                            &self.pack_edge_rules(),
139                            &src_e.kind,
140                            src_e.entity_type.as_deref(),
141                            &tgt_e.kind,
142                            tgt_e.entity_type.as_deref(),
143                        );
144                        let rule_hint = match relation {
145                            EdgeRelation::Supports | EdgeRelation::Refutes => {
146                                "requires concept|document|dataset|artifact -> concept \
147                                 (or same-substrate note -> note)"
148                            }
149                            _ => "requires same-kind entity endpoints",
150                        };
151                        return Err(RuntimeError::InvalidInput(format!(
152                            "({}) -[{rel_name}]-> ({}) is not in the base endpoint \
153                             allowlist; {rel_name} {rule_hint}; currently legal relations for \
154                             {} -> {} under the loaded endpoint rules: {legal_relations}",
155                            src_e.kind, tgt_e.kind, src_e.kind, tgt_e.kind
156                        )));
157                    }
158                    Ok((EdgeEndpointKind::Entity, EdgeEndpointKind::Entity))
159                }
160                (Resolved::Note(_), Resolved::Note(_)) => {
161                    Ok((EdgeEndpointKind::Note, EdgeEndpointKind::Note))
162                }
163                (Resolved::Event(_), _) => {
164                    return Err(RuntimeError::InvalidInput(format!(
165                        "{rel_name} does not apply to events; source {source_id} is an event"
166                    )));
167                }
168                (_, Resolved::Event(_)) => {
169                    return Err(RuntimeError::InvalidInput(format!(
170                        "{rel_name} does not apply to events; target {target_id} is an event"
171                    )));
172                }
173                (Resolved::Entity(_), Resolved::Note(_)) => {
174                    return Err(RuntimeError::InvalidInput(format!(
175                        "{rel_name} endpoints must be the same substrate (note→note or entity→entity); \
176                         got source={source_id} (entity) target={target_id} (note)"
177                    )));
178                }
179                (Resolved::Note(_), Resolved::Entity(_)) => {
180                    return Err(RuntimeError::InvalidInput(format!(
181                        "{rel_name} endpoints must be the same substrate (note→note or entity→entity); \
182                         got source={source_id} (note) target={target_id} (entity)"
183                    )));
184                }
185                (Resolved::PackRecord { .. }, _) | (_, Resolved::PackRecord { .. }) => {
186                    return Err(RuntimeError::InvalidInput(format!(
187                        "pack-private record is not a valid edge endpoint for {rel_name}"
188                    )));
189                }
190            };
191        } else {
192            // All remaining base relations require entity→entity with kind-level
193            // restrictions (see base allowlist). Packs may extend the allowlist
194            // additively via EDGE_RULES.
195            //
196            // Strategy: resolve both endpoints once (by-ID, unfiltered), consult pack
197            // rules; on miss, fall through to the original base-rule error messages.
198            let src_res = self.resolve_edge_endpoint(token, source_id).await?;
199            let tgt_res = self.resolve_edge_endpoint(token, target_id).await?;
200            let pack_rules = self.pack_edge_rules();
201
202            if pack_rule_allows(&pack_rules, relation, src_res.as_ref(), tgt_res.as_ref()) {
203                let kind = |resolved: Option<&Resolved>| match resolved {
204                    Some(Resolved::Entity(_)) => Some(EdgeEndpointKind::Entity),
205                    Some(Resolved::Note(_)) => Some(EdgeEndpointKind::Note),
206                    _ => None,
207                };
208                return match (kind(src_res.as_ref()), kind(tgt_res.as_ref())) {
209                    (Some(source_kind), Some(target_kind)) => Ok((source_kind, target_kind)),
210                    _ => Err(RuntimeError::Internal(
211                        "pack endpoint rule admitted an unsupported substrate".into(),
212                    )),
213                };
214            }
215
216            // Substrate check: both endpoints must be entities.
217            let (src_kind, src_entity_type) = match src_res.as_ref() {
218                Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
219                Some(_) => {
220                    return Err(RuntimeError::InvalidInput(format!(
221                        "link source {source_id} must be an entity for relation {relation:?} \
222                         (only `annotates` crosses substrates)"
223                    )));
224                }
225                None => {
226                    if self.get_edge(token, source_id).await?.is_some() {
227                        return Err(RuntimeError::InvalidInput(format!(
228                            "link source {source_id} must be an entity for relation {relation:?} \
229                             (only `annotates` crosses substrates)"
230                        )));
231                    }
232                    return Err(RuntimeError::NotFound(format!(
233                        "link source {source_id} not found"
234                    )));
235                }
236            };
237            let (tgt_kind, tgt_entity_type) = match tgt_res.as_ref() {
238                Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
239                Some(_) => {
240                    return Err(RuntimeError::InvalidInput(format!(
241                        "link target {target_id} must be an entity for relation {relation:?} \
242                         (only `annotates` crosses substrates)"
243                    )));
244                }
245                None => {
246                    if self.get_edge(token, target_id).await?.is_some() {
247                        return Err(RuntimeError::InvalidInput(format!(
248                            "link target {target_id} must be an entity for relation {relation:?} \
249                             (only `annotates` crosses substrates)"
250                        )));
251                    }
252                    return Err(RuntimeError::NotFound(format!(
253                        "link target {target_id} not found"
254                    )));
255                }
256            };
257            if !base_entity_rule_allows(src_kind, relation, tgt_kind) {
258                let legal_relations = accepted_entity_relations_description(
259                    &pack_rules,
260                    src_kind,
261                    src_entity_type,
262                    tgt_kind,
263                    tgt_entity_type,
264                );
265                return Err(RuntimeError::InvalidInput(format!(
266                    "({src_kind}) -[{}]-> ({tgt_kind}) is not in the base endpoint \
267                     allowlist; use pack EDGE_RULES to extend the allowlist; currently legal \
268                     relations for {src_kind} -> {tgt_kind} under the loaded endpoint rules: \
269                     {legal_relations}",
270                    relation.as_str()
271                )));
272            }
273        }
274        Ok((EdgeEndpointKind::Entity, EdgeEndpointKind::Entity))
275    }
276
277    /// Public delegator for cross-backend link validation.
278    ///
279    /// Exposes `validate_edge_relation_endpoints` for the `SubstrateCoordinator`
280    /// so it can validate the relation before writing the edge on the source backend.
281    pub async fn validate_link_endpoints(
282        &self,
283        token: &NamespaceToken,
284        source_id: Uuid,
285        target_id: Uuid,
286        relation: EdgeRelation,
287    ) -> RuntimeResult<()> {
288        self.validate_edge_relation_endpoints(token, source_id, target_id, relation)
289            .await
290            .map(|_| ())
291    }
292
293    /// Validate an edge relation using pre-fetched endpoint records.
294    ///
295    /// For cross-backend links the source and target live on different backends —
296    /// the source runtime cannot resolve the target. The coordinator fetches each
297    /// endpoint from its own backend, then calls this method to enforce the
298    /// kind-pairing rules without a second DB round-trip.
299    ///
300    /// `src` and `tgt` are the `resolve_edge_endpoint` results from each backend. The
301    /// `token` supplies the pack edge rules installed on this (source) runtime;
302    /// no DB access is performed.
303    pub fn validate_link_endpoints_by_resolved(
304        &self,
305        source_id: Uuid,
306        target_id: Uuid,
307        relation: EdgeRelation,
308        src: Option<&Resolved>,
309        tgt: Option<&Resolved>,
310    ) -> RuntimeResult<()> {
311        self.validate_link_endpoints_by_resolved_with_rules(
312            source_id,
313            target_id,
314            relation,
315            src,
316            tgt,
317            &self.pack_edge_rules(),
318        )
319    }
320
321    pub(crate) fn validate_link_endpoints_by_resolved_with_rules(
322        &self,
323        source_id: Uuid,
324        target_id: Uuid,
325        relation: EdgeRelation,
326        src: Option<&Resolved>,
327        tgt: Option<&Resolved>,
328        pack_rules: &[khive_types::EdgeEndpointRule],
329    ) -> RuntimeResult<()> {
330        if source_id == target_id {
331            return Err(RuntimeError::InvalidInput(
332                "self-loop edges are not allowed: source_id and target_id must be different".into(),
333            ));
334        }
335
336        if relation == EdgeRelation::Annotates {
337            match src {
338                Some(Resolved::Note(_)) => {}
339                Some(_) => {
340                    return Err(RuntimeError::InvalidInput(format!(
341                        "annotates source {source_id} must be a note"
342                    )));
343                }
344                None => {
345                    return Err(RuntimeError::NotFound(format!(
346                        "link source {source_id} not found"
347                    )));
348                }
349            }
350            if tgt.is_none() {
351                return Err(RuntimeError::NotFound(format!(
352                    "link target {target_id} not found"
353                )));
354            }
355            return Ok(());
356        }
357
358        if crate::pack::is_special_relation(relation) {
359            let rel_name = relation.as_str();
360            let src = src.ok_or_else(|| {
361                RuntimeError::NotFound(format!("link source {source_id} not found"))
362            })?;
363            let tgt = tgt.ok_or_else(|| {
364                RuntimeError::NotFound(format!("link target {target_id} not found"))
365            })?;
366            match (src, tgt) {
367                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
368                    if !base_entity_rule_allows(&src_e.kind, relation, &tgt_e.kind) {
369                        let legal_relations = accepted_entity_relations_description(
370                            pack_rules,
371                            &src_e.kind,
372                            src_e.entity_type.as_deref(),
373                            &tgt_e.kind,
374                            tgt_e.entity_type.as_deref(),
375                        );
376                        let rule_hint = match relation {
377                            EdgeRelation::Supports | EdgeRelation::Refutes => {
378                                "requires concept|document|dataset|artifact -> concept \
379                                 (or same-substrate note -> note)"
380                            }
381                            _ => "requires same-kind entity endpoints",
382                        };
383                        return Err(RuntimeError::InvalidInput(format!(
384                            "({}) -[{rel_name}]-> ({}) is not in the base endpoint \
385                             allowlist; {rel_name} {rule_hint}; currently legal relations for \
386                             {} -> {} under the loaded endpoint rules: {legal_relations}",
387                            src_e.kind, tgt_e.kind, src_e.kind, tgt_e.kind
388                        )));
389                    }
390                }
391                (Resolved::Note(_), Resolved::Note(_)) => {}
392                (Resolved::Entity(_), Resolved::Note(_)) => {
393                    return Err(RuntimeError::InvalidInput(format!(
394                        "{rel_name} endpoints must be the same substrate \
395                         (note→note or entity→entity); got source={source_id} (entity) \
396                         target={target_id} (note)"
397                    )));
398                }
399                (Resolved::Note(_), Resolved::Entity(_)) => {
400                    return Err(RuntimeError::InvalidInput(format!(
401                        "{rel_name} endpoints must be the same substrate \
402                         (note→note or entity→entity); got source={source_id} (note) \
403                         target={target_id} (entity)"
404                    )));
405                }
406                (Resolved::PackRecord { .. }, _) | (_, Resolved::PackRecord { .. }) => {
407                    return Err(RuntimeError::InvalidInput(format!(
408                        "pack-private record is not a valid edge endpoint for {rel_name}"
409                    )));
410                }
411                _ => {
412                    return Err(RuntimeError::InvalidInput(format!(
413                        "{rel_name} endpoints must be notes or entities (not events)"
414                    )));
415                }
416            }
417            return Ok(());
418        }
419
420        // All remaining base relations: entity→entity with kind-level restrictions.
421        // Consult pack rules installed on this (source) runtime first.
422        if pack_rule_allows(pack_rules, relation, src, tgt) {
423            return Ok(());
424        }
425
426        let (src_kind, src_entity_type) = match src {
427            Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
428            Some(_) => {
429                return Err(RuntimeError::InvalidInput(format!(
430                    "link source {source_id} must be an entity for relation {relation:?} \
431                     (only `annotates` crosses substrates)"
432                )));
433            }
434            None => {
435                return Err(RuntimeError::NotFound(format!(
436                    "link source {source_id} not found"
437                )));
438            }
439        };
440        let (tgt_kind, tgt_entity_type) = match tgt {
441            Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
442            Some(_) => {
443                return Err(RuntimeError::InvalidInput(format!(
444                    "link target {target_id} must be an entity for relation {relation:?} \
445                     (only `annotates` crosses substrates)"
446                )));
447            }
448            None => {
449                return Err(RuntimeError::NotFound(format!(
450                    "link target {target_id} not found"
451                )));
452            }
453        };
454
455        if !base_entity_rule_allows(src_kind, relation, tgt_kind) {
456            let legal_relations = accepted_entity_relations_description(
457                pack_rules,
458                src_kind,
459                src_entity_type,
460                tgt_kind,
461                tgt_entity_type,
462            );
463            return Err(RuntimeError::InvalidInput(format!(
464                "({src_kind}) -[{}]-> ({tgt_kind}) is not in the base endpoint \
465                 allowlist; use pack EDGE_RULES to extend the allowlist; currently legal relations \
466                 for {src_kind} -> {tgt_kind} under the loaded endpoint rules: {legal_relations}",
467                relation.as_str()
468            )));
469        }
470
471        Ok(())
472    }
473
474    /// Validate an `annotates` edge relation using pre-located endpoint kinds.
475    ///
476    /// Sibling of [`Self::validate_link_endpoints_by_resolved`] for callers that
477    /// only have an [`EdgeEndpointKind`] (entity/note/event/edge) rather than a
478    /// full [`Resolved`] record — the `SubstrateCoordinator`'s cross-backend
479    /// `locate_endpoint` resolves edge-substrate UUIDs too (matching `get`'s
480    /// by-ID resolution order), but edges have no `Resolved` variant, so
481    /// `validate_link_endpoints_by_resolved` cannot express them.
482    ///
483    /// `annotates` is the only relation this covers: source must be a note,
484    /// target may be any substrate (entity, note, event, or edge).
485    pub fn validate_annotates_endpoint_kinds(
486        &self,
487        source_id: Uuid,
488        target_id: Uuid,
489        source: Option<EdgeEndpointKind>,
490        target: Option<EdgeEndpointKind>,
491    ) -> RuntimeResult<()> {
492        if source_id == target_id {
493            return Err(RuntimeError::InvalidInput(
494                "self-loop edges are not allowed: source_id and target_id must be different".into(),
495            ));
496        }
497        match source {
498            Some(EdgeEndpointKind::Note) => {}
499            Some(_) => {
500                return Err(RuntimeError::InvalidInput(format!(
501                    "annotates source {source_id} must be a note"
502                )));
503            }
504            None => {
505                return Err(RuntimeError::NotFound(format!(
506                    "link source {source_id} not found"
507                )));
508            }
509        }
510        if target.is_none() {
511            return Err(RuntimeError::NotFound(format!(
512                "link target {target_id} not found"
513            )));
514        }
515        Ok(())
516    }
517
518    /// Create a directed edge between two substrates.
519    ///
520    /// Enforces the three-case relation contract via
521    /// `validate_edge_relation_endpoints`. See that method for the full contract.
522    ///
523    /// For symmetric relations (`competes_with`, `composed_with`) the endpoint
524    /// pair is canonicalised to `source_uuid < target_uuid` so that A→B and B→A
525    /// deduplicate to one row.
526    ///
527    /// `metadata` is validated against governed keys; `dependency_kind` is
528    /// inferred for `depends_on` edges when absent.
529    ///
530    /// `target_backend` is always `None` for locally-routed edges written through
531    /// this path. Both endpoints must exist in the local namespace, so setting
532    /// `target_backend = None` is the only valid choice.
533    ///
534    /// Endpoint existence is a by-ID check and namespace-agnostic: a record
535    /// that exists in a different namespace than the caller still resolves,
536    /// exactly as `get()` would.
537    pub async fn link(
538        &self,
539        token: &NamespaceToken,
540        source_id: Uuid,
541        target_id: Uuid,
542        relation: EdgeRelation,
543        weight: f64,
544        metadata: Option<serde_json::Value>,
545    ) -> RuntimeResult<Edge> {
546        self.link_observed(
547            token, source_id, target_id, relation, weight, metadata, false,
548        )
549        .await
550        .map(|result| result.edge)
551    }
552
553    /// Observable form of [`Self::link`]. Live natural-key conflicts retain
554    /// the accepted replace semantics, while tombstones require the explicit
555    /// `resurrect` opt-in. The returned preimage and disposition are derived
556    /// inside the graph writer transaction and drive the lifecycle event.
557    #[allow(clippy::too_many_arguments)]
558    pub async fn link_observed(
559        &self,
560        token: &NamespaceToken,
561        source_id: Uuid,
562        target_id: Uuid,
563        relation: EdgeRelation,
564        weight: f64,
565        metadata: Option<serde_json::Value>,
566        resurrect: bool,
567    ) -> RuntimeResult<EdgeUpsertResult> {
568        validate_edge_weight(weight)?;
569        validate_edge_metadata(relation, metadata.as_ref())?;
570        let (source_kind, target_kind) = self
571            .validate_edge_relation_endpoints(token, source_id, target_id, relation)
572            .await?;
573        let (canonical_source, canonical_target) =
574            canonical_edge_endpoints(relation, source_id, target_id);
575        let (source_kind, target_kind) =
576            canonical_edge_endpoint_kinds(source_id, canonical_source, source_kind, target_kind);
577        let (source_id, target_id) = (canonical_source, canonical_target);
578        let metadata = if relation == EdgeRelation::DependsOn {
579            // By-ID, unfiltered — matches the namespace-agnostic endpoint validation
580            // above. The visible-set-scoped `resolve` would silently drop the
581            // dependency_kind inference for endpoints validation now allows outside
582            // the caller's visible set.
583            match (
584                self.resolve_edge_endpoint(token, source_id).await?,
585                self.resolve_edge_endpoint(token, target_id).await?,
586            ) {
587                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
588                    Self::prepare_link_metadata(
589                        relation,
590                        Some(&src_e.kind),
591                        Some(&tgt_e.kind),
592                        metadata,
593                    )
594                }
595                _ => metadata,
596            }
597        } else {
598            metadata
599        };
600        validate_edge_metadata(relation, metadata.as_ref())?;
601        let now = chrono::Utc::now();
602        let ns = token.namespace().as_str();
603        let edge = Edge {
604            id: LinkId::from(Uuid::new_v4()),
605            namespace: ns.to_string(),
606            source_id,
607            target_id,
608            relation,
609            weight,
610            created_at: now,
611            updated_at: now,
612            deleted_at: None,
613            metadata,
614            target_backend: None,
615        };
616        // `upsert_edge_guarded` re-checks both endpoints exist as part of the same
617        // write, not the separate `validate_edge_relation_endpoints` read above: a
618        // concurrent hard-delete landing between that read and this write can no
619        // longer create a durably dangling edge. Which endpoint(s) were missing is
620        // reported by the guard's own in-transaction probe (`GuardedWriteOutcome::
621        // Refused`), not reconstructed here by re-reading the endpoints after the
622        // fact: a second concurrent write landing between the refusal and a
623        // post-hoc read could otherwise misreport which endpoint was actually
624        // missing at write time.
625        let attribution = crate::EventAttribution::from_token(token);
626        let outcome = compose_graph_mutation_events(
627            self.backend(),
628            GraphMutationRequest::Single {
629                request: EdgeUpsertRequest { edge, resurrect },
630                guard_endpoints: true,
631            },
632            GraphMutationPreconditions::default(),
633            Vec::new(),
634            move |outcome| match &outcome.mutation {
635                GraphMutationOutcome::Single(GuardedEdgeUpsertOutcome::Written(result)) => {
636                    Ok(vec![Self::link_mutation_event(
637                        &attribution,
638                        result,
639                        source_kind,
640                        target_kind,
641                    )])
642                }
643                _ => Err(Self::link_composition_shape_error(
644                    "expected a written singleton",
645                )),
646            },
647        )
648        .await?;
649        let GraphMutationOutcome::Single(outcome) = outcome.mutation else {
650            return Err(RuntimeError::Internal(
651                "link: unexpected composition outcome".into(),
652            ));
653        };
654        let result = match outcome {
655            GuardedEdgeUpsertOutcome::Written(result) => result,
656            GuardedEdgeUpsertOutcome::Refused(EdgeUpsertRefusal::MissingEndpoints(missing)) => {
657                return Err(RuntimeError::GuardedWriteFailed(GuardedWriteFailure {
658                    entry_index: None,
659                    missing_source: missing.source.then_some(source_id),
660                    missing_target: missing.target.then_some(target_id),
661                }));
662            }
663            GuardedEdgeUpsertOutcome::Refused(EdgeUpsertRefusal::ResurrectionRequired { edge }) => {
664                return Err(RuntimeError::InvalidInput(format!(
665                    "edge {} is soft-deleted; pass resurrect=true to link explicitly",
666                    edge.id
667                )))
668            }
669        };
670        Ok(result)
671    }
672
673    /// Write an edge with an explicit `target_backend` stamp (ADR-029 D3).
674    ///
675    /// Called by the `SubstrateCoordinator` when source and target are on
676    /// different backends. The coordinator validates endpoints before calling
677    /// this method via [`Self::validate_link_endpoints`], and supplies the
678    /// resolved endpoint kinds for the lifecycle event. Endpoint validation is
679    /// skipped here. The edge is written on the source backend only.
680    #[allow(clippy::too_many_arguments)]
681    pub async fn link_with_target_backend(
682        &self,
683        token: &NamespaceToken,
684        source_id: Uuid,
685        target_id: Uuid,
686        source_kind: EdgeEndpointKind,
687        target_kind: EdgeEndpointKind,
688        relation: EdgeRelation,
689        weight: f64,
690        metadata: Option<serde_json::Value>,
691        target_backend: Option<String>,
692    ) -> RuntimeResult<Edge> {
693        self.link_with_target_backend_observed(
694            token,
695            source_id,
696            target_id,
697            source_kind,
698            target_kind,
699            relation,
700            weight,
701            metadata,
702            target_backend,
703            false,
704        )
705        .await
706        .map(|result| result.edge)
707    }
708
709    /// Apply dependency defaults using entity kinds resolved by the caller.
710    ///
711    /// Only `depends_on` uses the shared inference table. Explicit metadata is
712    /// preserved, including invalid values for the write boundary to reject.
713    /// Missing kinds and pairs without a default leave metadata unchanged.
714    /// This does not validate endpoints or make their kinds a write precondition.
715    /// Both the local link route and the coordinator route use this preparation
716    /// before writing; each retains its existing validation responsibilities.
717    pub fn prepare_link_metadata(
718        relation: EdgeRelation,
719        source_entity_kind: Option<&str>,
720        target_entity_kind: Option<&str>,
721        metadata: Option<serde_json::Value>,
722    ) -> Option<serde_json::Value> {
723        match (relation, source_entity_kind, target_entity_kind) {
724            (EdgeRelation::DependsOn, Some(source), Some(target)) => {
725                merge_dependency_kind(source, target, metadata)
726            }
727            _ => metadata,
728        }
729    }
730
731    /// Policy-aware cross-backend form of [`Self::link_observed`]. Endpoint
732    /// validation remains the coordinator's responsibility; mutation
733    /// classification and tombstone handling stay inside the source store.
734    #[allow(clippy::too_many_arguments)]
735    pub async fn link_with_target_backend_observed(
736        &self,
737        token: &NamespaceToken,
738        source_id: Uuid,
739        target_id: Uuid,
740        source_kind: EdgeEndpointKind,
741        target_kind: EdgeEndpointKind,
742        relation: EdgeRelation,
743        weight: f64,
744        metadata: Option<serde_json::Value>,
745        target_backend: Option<String>,
746        resurrect: bool,
747    ) -> RuntimeResult<EdgeUpsertResult> {
748        validate_edge_weight(weight)?;
749        let (canonical_source, canonical_target) =
750            canonical_edge_endpoints(relation, source_id, target_id);
751        let (source_kind, target_kind) =
752            canonical_edge_endpoint_kinds(source_id, canonical_source, source_kind, target_kind);
753        let (source_id, target_id) = (canonical_source, canonical_target);
754        validate_edge_metadata(relation, metadata.as_ref())?;
755        let metadata = if relation == EdgeRelation::DependsOn && target_backend.is_none() {
756            // Same-backend coordinator calls have both records here. Cross-backend
757            // callers prepare metadata from records on their respective runtimes.
758            // As on the local route, resolution is by-ID and namespace-unfiltered.
759            match (
760                self.resolve_edge_endpoint(token, source_id).await?,
761                self.resolve_edge_endpoint(token, target_id).await?,
762            ) {
763                (Some(Resolved::Entity(source)), Some(Resolved::Entity(target))) => {
764                    Self::prepare_link_metadata(
765                        relation,
766                        Some(&source.kind),
767                        Some(&target.kind),
768                        metadata,
769                    )
770                }
771                _ => metadata,
772            }
773        } else {
774            metadata
775        };
776        let now = chrono::Utc::now();
777        let ns = token.namespace().as_str();
778        let edge = Edge {
779            id: LinkId::from(Uuid::new_v4()),
780            namespace: ns.to_string(),
781            source_id,
782            target_id,
783            relation,
784            weight,
785            created_at: now,
786            updated_at: now,
787            deleted_at: None,
788            metadata,
789            target_backend,
790        };
791        let attribution = crate::EventAttribution::from_token(token);
792        let outcome = compose_graph_mutation_events(
793            self.backend(),
794            GraphMutationRequest::Single {
795                request: EdgeUpsertRequest { edge, resurrect },
796                guard_endpoints: false,
797            },
798            GraphMutationPreconditions::default(),
799            Vec::new(),
800            move |outcome| match &outcome.mutation {
801                GraphMutationOutcome::Single(GuardedEdgeUpsertOutcome::Written(result)) => {
802                    Ok(vec![Self::link_mutation_event(
803                        &attribution,
804                        result,
805                        source_kind,
806                        target_kind,
807                    )])
808                }
809                _ => Err(Self::link_composition_shape_error(
810                    "expected a written singleton",
811                )),
812            },
813        )
814        .await?;
815        match outcome.mutation {
816            GraphMutationOutcome::Single(GuardedEdgeUpsertOutcome::Written(result)) => Ok(result),
817            GraphMutationOutcome::Single(GuardedEdgeUpsertOutcome::Refused(
818                EdgeUpsertRefusal::ResurrectionRequired { edge },
819            )) => {
820                let error = khive_storage::StorageError::Conflict {
821                    capability: khive_storage::StorageCapability::Graph,
822                    operation: "upsert_edge_observed".into(),
823                    message: format!(
824                        "edge {} is soft-deleted; explicit resurrection is required",
825                        edge.id,
826                    ),
827                };
828                Err(RuntimeError::InvalidInput(format!(
829                    "edge natural key is soft-deleted; pass resurrect=true to link explicitly: {error}"
830                )))
831            }
832            _ => Err(RuntimeError::Internal(
833                "link: unexpected composition outcome".into(),
834            )),
835        }
836    }
837
838    fn link_mutation_event(
839        attribution: &crate::EventAttribution,
840        result: &EdgeUpsertResult,
841        source_kind: EdgeEndpointKind,
842        target_kind: EdgeEndpointKind,
843    ) -> Event {
844        let kind = match result.disposition {
845            EdgeUpsertDisposition::Created => EventKind::LinkCreated,
846            EdgeUpsertDisposition::Updated | EdgeUpsertDisposition::Resurrected => {
847                EventKind::EdgeUpdated
848            }
849        };
850        let edge_id = Uuid::from(result.edge.id);
851        let mut payload = serde_json::json!({
852            "id": edge_id,
853            "namespace": result.edge.namespace,
854            "mutation": result.disposition.name(),
855            "source_id": result.edge.source_id,
856            "target_id": result.edge.target_id,
857            "relation": result.edge.relation,
858            "weight": result.edge.weight,
859            "metadata": result.edge.metadata,
860            "previous": result.previous,
861        });
862        if kind == EventKind::LinkCreated {
863            payload["source_kind"] = serde_json::json!(source_kind.name());
864            payload["target_kind"] = serde_json::json!(target_kind.name());
865        }
866        attribution.stamp(
867            Event::new(
868                result.edge.namespace.clone(),
869                "link",
870                kind,
871                SubstrateKind::Entity,
872                "",
873            )
874            .with_target(edge_id)
875            .with_payload(payload),
876        )
877    }
878
879    fn link_composition_shape_error(message: &'static str) -> khive_storage::StorageError {
880        khive_storage::StorageError::InvalidInput {
881            capability: khive_storage::StorageCapability::Graph,
882            operation: "link_mutation_event".into(),
883            message: message.into(),
884        }
885    }
886
887    /// Validate and construct an edge from a [`LinkSpec`] without writing to storage.
888    ///
889    /// Applies the full edge contract (endpoint validation, symmetric
890    /// canonicalization, `dependency_kind` inference and metadata validation).
891    /// Returns the constructed `Edge` on success; the caller is responsible for
892    /// persisting it (e.g. via `upsert_edge` or `link_many`).
893    ///
894    /// The `token` must be a pre-authorized namespace token from the dispatch
895    /// layer. If `spec.namespace` is set it must match `token.namespace()`;
896    /// a mismatch returns `RuntimeError::InvalidInput`.
897    pub async fn build_edge(&self, token: &NamespaceToken, spec: &LinkSpec) -> RuntimeResult<Edge> {
898        self.build_edge_with_endpoint_kinds(token, spec)
899            .await
900            .map(|(edge, _)| edge)
901    }
902
903    async fn build_edge_with_endpoint_kinds(
904        &self,
905        token: &NamespaceToken,
906        spec: &LinkSpec,
907    ) -> RuntimeResult<(Edge, (EdgeEndpointKind, EdgeEndpointKind))> {
908        validate_edge_metadata(spec.relation, spec.metadata.as_ref())?;
909        let ns_str = match &spec.namespace {
910            Some(s) => {
911                let spec_ns = crate::Namespace::parse(s)
912                    .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}")))?;
913                if &spec_ns != token.namespace() {
914                    return Err(RuntimeError::InvalidInput(
915                        "LinkSpec namespace does not match token namespace".into(),
916                    ));
917                }
918                s.as_str()
919            }
920            None => token.namespace().as_str(),
921        };
922        let endpoint_kinds = self
923            .validate_edge_relation_endpoints(token, spec.source_id, spec.target_id, spec.relation)
924            .await?;
925        let (source_id, target_id) =
926            canonical_edge_endpoints(spec.relation, spec.source_id, spec.target_id);
927        let endpoint_kinds = canonical_edge_endpoint_kinds(
928            spec.source_id,
929            source_id,
930            endpoint_kinds.0,
931            endpoint_kinds.1,
932        );
933        let metadata = if spec.relation == EdgeRelation::DependsOn {
934            // By-ID, unfiltered — matches the namespace-agnostic endpoint validation
935            // above. The visible-set-scoped `resolve` would silently drop the
936            // dependency_kind inference for endpoints validation now allows outside
937            // the caller's visible set.
938            match (
939                self.resolve_edge_endpoint(token, source_id).await?,
940                self.resolve_edge_endpoint(token, target_id).await?,
941            ) {
942                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
943                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, spec.metadata.clone())
944                }
945                _ => spec.metadata.clone(),
946            }
947        } else {
948            spec.metadata.clone()
949        };
950        validate_edge_metadata(spec.relation, metadata.as_ref())?;
951        let now = chrono::Utc::now();
952        Ok((
953            Edge {
954                id: LinkId::from(Uuid::new_v4()),
955                namespace: ns_str.to_string(),
956                source_id,
957                target_id,
958                relation: spec.relation,
959                weight: spec.weight,
960                created_at: now,
961                updated_at: now,
962                deleted_at: None,
963                metadata,
964                target_backend: None,
965            },
966            endpoint_kinds,
967        ))
968    }
969
970    /// Validate and atomically upsert a batch of edges.
971    ///
972    /// All edges are validated and constructed with `build_edge` before any
973    /// write. If validation fails for any entry the entire batch is rejected
974    /// (no writes occur). On success, all edges are persisted in a single
975    /// source transaction with every lifecycle event and observation projection.
976    ///
977    /// After the bulk upsert, each edge is read back by its natural key
978    /// (namespace, source_id, target_id, relation) so that the returned IDs
979    /// are always the persisted row IDs, not the locally-generated UUIDs that
980    /// may have been displaced by an ON CONFLICT DO UPDATE. This mirrors the
981    /// same read-back applied to singleton `link()` and prevents phantom-ID
982    /// exposure when callers upsert overlapping triples with `verbose=true`.
983    ///
984    /// All specs must share the same namespace; the namespace is taken from
985    /// `token` (or validated against it if `spec.namespace` is set).
986    pub async fn link_many(
987        &self,
988        token: &NamespaceToken,
989        specs: Vec<LinkSpec>,
990    ) -> RuntimeResult<Vec<Edge>> {
991        self.link_many_observed(token, specs)
992            .await
993            .map(|rows| rows.into_iter().map(|row| row.edge).collect())
994    }
995
996    /// Observed all-or-nothing bulk link upsert. Every row carries its own
997    /// create/update/resurrection disposition, and every tombstone policy is
998    /// preflighted inside the same writer transaction before any mutation.
999    pub async fn link_many_observed(
1000        &self,
1001        token: &NamespaceToken,
1002        specs: Vec<LinkSpec>,
1003    ) -> RuntimeResult<Vec<EdgeUpsertResult>> {
1004        self.link_many_guarded_observed(
1005            token,
1006            specs,
1007            GraphMutationPreconditions::default(),
1008            Vec::new(),
1009        )
1010        .await
1011        .map(|(rows, _)| rows)
1012    }
1013
1014    /// Internal seam for khive-runtime; no compatibility promise.
1015    ///
1016    /// Guarded composition seam for packs.
1017    #[doc(hidden)]
1018    pub async fn link_many_guarded_observed(
1019        &self,
1020        token: &NamespaceToken,
1021        specs: Vec<LinkSpec>,
1022        preconditions: GraphMutationPreconditions,
1023        retirements: Vec<Edge>,
1024    ) -> RuntimeResult<(Vec<EdgeUpsertResult>, Vec<LinkId>)> {
1025        let namespace = token.namespace().as_str();
1026        let foreign_document = preconditions
1027            .document
1028            .as_ref()
1029            .is_some_and(|guard| guard.namespace != namespace);
1030        let foreign_edge = preconditions.edges.iter().any(|guard| {
1031            guard.namespace != namespace
1032                || guard
1033                    .expected
1034                    .as_ref()
1035                    .is_some_and(|edge| edge.namespace != namespace)
1036        });
1037        if foreign_document
1038            || foreign_edge
1039            || retirements.iter().any(|edge| edge.namespace != namespace)
1040        {
1041            return Err(RuntimeError::InvalidInput(
1042                "guarded link namespace does not match token namespace".into(),
1043            ));
1044        }
1045        if specs.is_empty()
1046            && preconditions.document.is_none()
1047            && preconditions.edges.is_empty()
1048            && preconditions.statement_guards.is_empty()
1049            && retirements.is_empty()
1050        {
1051            return Ok((Vec::new(), Vec::new()));
1052        }
1053        let mut edges = Vec::with_capacity(specs.len());
1054        let mut endpoint_kinds = Vec::with_capacity(specs.len());
1055        for spec in &specs {
1056            let (edge, kinds) = self.build_edge_with_endpoint_kinds(token, spec).await?;
1057            edges.push(edge);
1058            endpoint_kinds.push(kinds);
1059        }
1060        // `upsert_edges_guarded` re-checks every edge's endpoints as part of the
1061        // same write, not the separate per-spec `build_edge` validation reads
1062        // above. A concurrent hard-delete of any endpoint landing between those
1063        // reads and this write aborts the whole batch (all-or-nothing, no
1064        // partial write) instead of persisting a dangling edge. The failing
1065        // entry's index and its missing endpoint(s) come from the guard's own
1066        // in-transaction pre-check (`GuardedBatchOutcome::refused`), not a
1067        // post-hoc re-read of the batch after the write already failed.
1068        let requests = edges
1069            .into_iter()
1070            .zip(specs.iter())
1071            .map(|(edge, spec)| EdgeUpsertRequest {
1072                edge,
1073                resurrect: spec.resurrect,
1074            })
1075            .collect();
1076        let attribution = crate::EventAttribution::from_token(token);
1077        let outcome = compose_graph_mutation_events(
1078            self.backend(),
1079            GraphMutationRequest::Batch {
1080                requests,
1081                guard_endpoints: true,
1082            },
1083            preconditions,
1084            retirements,
1085            move |outcome| {
1086                let GraphMutationOutcome::Batch(batch) = &outcome.mutation else {
1087                    return Err(Self::link_composition_shape_error(
1088                        "expected a written batch",
1089                    ));
1090                };
1091                if batch.rows.len() != endpoint_kinds.len() {
1092                    return Err(Self::link_composition_shape_error(
1093                        "edge result count differs from validated endpoint count",
1094                    ));
1095                }
1096                let mut events = Vec::with_capacity(batch.rows.len() + outcome.retired.len());
1097                for (row, (source_kind, target_kind)) in batch.rows.iter().zip(endpoint_kinds) {
1098                    events.push(Self::link_mutation_event(
1099                        &attribution,
1100                        row,
1101                        source_kind,
1102                        target_kind,
1103                    ));
1104                }
1105                for edge in &outcome.retired {
1106                    let edge_id = Uuid::from(edge.id);
1107                    events.push(
1108                        attribution.stamp(
1109                            Event::new(
1110                                edge.namespace.clone(),
1111                                "delete",
1112                                EventKind::EdgeDeleted,
1113                                SubstrateKind::Entity,
1114                                "",
1115                            )
1116                            .with_target(edge_id)
1117                            .with_payload(serde_json::json!({
1118                                "id": edge_id, "namespace": edge.namespace, "hard": false,
1119                            })),
1120                        ),
1121                    );
1122                }
1123                Ok(events)
1124            },
1125        )
1126        .await?;
1127        let retired = outcome.retired.into_iter().map(|edge| edge.id).collect();
1128        let outcome = match outcome.mutation {
1129            GraphMutationOutcome::Batch(outcome) => outcome,
1130            GraphMutationOutcome::GuardFailed(failure) => {
1131                return Err(khive_storage::StorageError::Conflict {
1132                    capability: khive_storage::StorageCapability::Graph,
1133                    operation: "link_many_guarded_observed".into(),
1134                    message: failure.to_string(),
1135                }
1136                .into());
1137            }
1138            _ => {
1139                return Err(RuntimeError::Internal(
1140                    "link_many: unexpected composition outcome".into(),
1141                ));
1142            }
1143        };
1144        if let Some(refusal) = outcome.refusal {
1145            return match refusal.reason {
1146                EdgeUpsertRefusal::MissingEndpoints(missing) => {
1147                    Err(RuntimeError::GuardedWriteFailed(guarded_link_batch_failure(
1148                        &specs[refusal.entry_index],
1149                        refusal.entry_index,
1150                        missing,
1151                    )))
1152                }
1153                EdgeUpsertRefusal::ResurrectionRequired { edge } => {
1154                    Err(RuntimeError::InvalidInput(format!(
1155                        "batch entry {} targets soft-deleted edge {}; pass resurrect=true for that link",
1156                        refusal.entry_index, edge.id
1157                    )))
1158                }
1159            };
1160        }
1161        Ok((outcome.rows, retired))
1162    }
1163
1164    /// Create an edge only when its natural key is absent and all supplied guards pass.
1165    ///
1166    /// Endpoint and namespace validation precede the write. Guards run in order in the
1167    /// same writer transaction as insertion; only a created edge emits LinkCreated.
1168    /// Existing live edges and tombstones are never changed. Registry link hooks
1169    /// remain the dispatch layer's responsibility, as with [`Self::build_edge`].
1170    pub async fn link_if_absent_with_guards(
1171        &self,
1172        token: &NamespaceToken,
1173        spec: LinkSpec,
1174        guards: Vec<GraphStatementGuard>,
1175    ) -> RuntimeResult<EdgeInsertIfAbsentOutcome> {
1176        if spec.resurrect {
1177            return Err(RuntimeError::InvalidInput(
1178                "create-only link does not accept resurrect=true".into(),
1179            ));
1180        }
1181        validate_edge_weight(spec.weight)?;
1182        let (edge, (source_kind, target_kind)) =
1183            self.build_edge_with_endpoint_kinds(token, &spec).await?;
1184        let attribution = crate::EventAttribution::from_token(token);
1185        let outcome = compose_graph_mutation_events(
1186            self.backend(),
1187            GraphMutationRequest::InsertIfAbsent { edge },
1188            GraphMutationPreconditions {
1189                statement_guards: guards,
1190                ..Default::default()
1191            },
1192            Vec::new(),
1193            move |outcome| match &outcome.mutation {
1194                GraphMutationOutcome::InsertIfAbsent(EdgeInsertIfAbsentOutcome::Created(edge)) => {
1195                    Ok(vec![Self::link_mutation_event(
1196                        &attribution,
1197                        &EdgeUpsertResult {
1198                            edge: edge.clone(),
1199                            disposition: EdgeUpsertDisposition::Created,
1200                            previous: None,
1201                        },
1202                        source_kind,
1203                        target_kind,
1204                    )])
1205                }
1206                _ => Err(Self::link_composition_shape_error(
1207                    "expected a created edge",
1208                )),
1209            },
1210        )
1211        .await?;
1212        match outcome.mutation {
1213            GraphMutationOutcome::InsertIfAbsent(outcome) => Ok(outcome),
1214            GraphMutationOutcome::GuardFailed(failure) => {
1215                Ok(EdgeInsertIfAbsentOutcome::GuardFailed(failure))
1216            }
1217            _ => Err(RuntimeError::Internal(
1218                "create-only link: unexpected composition outcome".into(),
1219            )),
1220        }
1221    }
1222}