Skip to main content

khive_runtime/operations/
link_ops.rs

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