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