Skip to main content

kernel/graph/
edge_data.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Per-family edge runtime data structs and semantic IRI mapping.
8//! Extracted from `edge_taxonomy.rs` per the 600-LOC ceiling.
9
10use std::collections::BTreeSet;
11
12use rkyv::{Archive, Deserialize, Serialize};
13
14use crate::types::{AssertionBasis, AssertionWithdrawal, GraphScope, mint_local_statement_id};
15
16use super::edge_taxonomy::{
17    ArrangementSubKind, ContainmentSubKind, ImportedSubKind, NavigationTrigger, ProvenanceSubKind,
18    RelationDurability, SemanticSubKind,
19};
20
21/// A temporal traversal event recorded on an edge.
22#[derive(
23    Debug,
24    Clone,
25    Copy,
26    PartialEq,
27    Eq,
28    Archive,
29    Serialize,
30    Deserialize,
31    serde::Serialize,
32    serde::Deserialize,
33)]
34pub struct Traversal {
35    pub timestamp_ms: u64,
36    pub trigger: NavigationTrigger,
37}
38
39impl Traversal {
40    pub fn now(trigger: NavigationTrigger) -> Self {
41        let timestamp_ms = crate::time::unix_epoch_millis();
42        Self {
43            timestamp_ms,
44            trigger,
45        }
46    }
47}
48
49/// Durable traversal aggregates retained even when rolling-window records are evicted.
50#[derive(
51    Debug,
52    Clone,
53    Copy,
54    PartialEq,
55    Eq,
56    Archive,
57    Serialize,
58    Deserialize,
59    serde::Serialize,
60    serde::Deserialize,
61)]
62pub struct EdgeMetrics {
63    pub total_navigations: u64,
64    pub forward_navigations: u64,
65    pub backward_navigations: u64,
66    pub last_navigated_at: Option<u64>,
67}
68
69impl EdgeMetrics {
70    fn new() -> Self {
71        Self {
72            total_navigations: 0,
73            forward_navigations: 0,
74            backward_navigations: 0,
75            last_navigated_at: None,
76        }
77    }
78
79    fn record(&mut self, traversal: Traversal) {
80        self.total_navigations = self.total_navigations.saturating_add(1);
81        if traversal.trigger.contributes_to_forward_count() {
82            self.forward_navigations = self.forward_navigations.saturating_add(1);
83        } else {
84            self.backward_navigations = self.backward_navigations.saturating_add(1);
85        }
86        self.last_navigated_at = Some(traversal.timestamp_ms);
87    }
88}
89
90impl Default for EdgeMetrics {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96/// Attribution for stored assertions whose original asserter is unknown.
97pub const UNKNOWN_LEGACY_ASSERTER_IRI: &str = "https://mere.computer/ns/agent#unknown-legacy";
98
99#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, serde::Serialize)]
100pub struct SemanticStatement {
101    pub statement_id: String,
102    pub predicate: String,
103    pub recognized_sub_kind: Option<SemanticSubKind>,
104    pub label: Option<String>,
105    /// Why this assertion exists. `label` remains a compatibility projection.
106    pub basis: AssertionBasis,
107    pub graph_scope: GraphScope,
108    pub provenance_iri: Option<String>,
109    /// First record time. `None` is retained for legacy/imported records whose
110    /// source did not provide a time.
111    pub first_asserted_ms: Option<u64>,
112    /// Latest confirmation time; kept under its legacy field name for stored
113    /// compatibility.
114    pub asserted_at_ms: Option<u64>,
115    /// Withdrawal is a retained tombstone, not a hard delete.
116    pub withdrawn: Option<AssertionWithdrawal>,
117}
118
119/// All-family assertion record. The legacy semantic name remains source compatible.
120pub type RelationAssertion = SemanticStatement;
121pub type RelationAssertionSpec = SemanticStatementSpec;
122pub type AssertionData = SemanticData;
123
124impl SemanticStatement {
125    /// Classify the assertion by its canonical predicate. The old semantic
126    /// discriminant remains a compatibility input for existing records.
127    pub fn relation_kind(&self) -> super::RelationKind {
128        super::RelationKind::from_predicate_iri(&self.predicate)
129            .or_else(|| self.recognized_sub_kind.map(super::RelationKind::Semantic))
130            .unwrap_or(super::RelationKind::OpenPredicate)
131    }
132
133    pub fn is_semantic(&self) -> bool {
134        self.relation_kind().family() == super::EdgeFamily::Semantic
135    }
136
137    pub fn is_held(&self) -> bool {
138        self.withdrawn.is_none()
139    }
140
141    /// Whether both records are one claim under a carried handle: predicate, sub-kind,
142    /// scope, asserter and basis reason. Labels, times and method version may differ.
143    pub fn same_claim_as(&self, other: &Self) -> bool {
144        self.predicate == other.predicate
145            && self.recognized_sub_kind == other.recognized_sub_kind
146            && self.graph_scope == other.graph_scope
147            && self.provenance_iri == other.provenance_iri
148            && self.basis.same_reason_as(&other.basis)
149    }
150
151    pub fn normalize_basis_compat(&mut self) {
152        if self.basis.note.is_none() {
153            self.basis.note = self.label.clone();
154        }
155        self.label = self.basis.note.clone();
156    }
157
158    /// Normalize missing attribution on a legacy record without inventing authorship.
159    pub fn normalize_legacy_asserter(&mut self) -> bool {
160        if self.provenance_iri.is_some() {
161            return false;
162        }
163        self.provenance_iri = Some(UNKNOWN_LEGACY_ASSERTER_IRI.to_string());
164        true
165    }
166
167    pub fn new(
168        predicate: String,
169        recognized_sub_kind: Option<SemanticSubKind>,
170        label: Option<String>,
171        graph_scope: GraphScope,
172        provenance_iri: Option<String>,
173        asserted_at_ms: Option<u64>,
174    ) -> Self {
175        Self {
176            statement_id: mint_local_statement_id(),
177            predicate,
178            recognized_sub_kind,
179            label: label.clone(),
180            basis: AssertionBasis {
181                note: label.clone(),
182                ..Default::default()
183            },
184            graph_scope,
185            provenance_iri,
186            first_asserted_ms: asserted_at_ms,
187            asserted_at_ms,
188            withdrawn: None,
189        }
190    }
191}
192
193// Keep the missing-vs-explicit-null distinction for first_asserted_ms. Old
194// serialized statements omitted the field, so only that case falls back to
195// the legacy asserted_at_ms value. An explicitly unknown first time stays
196// unknown after every reopen.
197struct PresentOptionU64(Option<Option<u64>>);
198struct PresentBasis(Option<Option<AssertionBasis>>);
199
200impl Default for PresentOptionU64 {
201    fn default() -> Self {
202        Self(None)
203    }
204}
205
206impl Default for PresentBasis {
207    fn default() -> Self {
208        Self(None)
209    }
210}
211
212impl<'de> serde::Deserialize<'de> for PresentBasis {
213    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
214    where
215        D: serde::Deserializer<'de>,
216    {
217        Ok(Self(Some(Option::<AssertionBasis>::deserialize(
218            deserializer,
219        )?)))
220    }
221}
222
223impl<'de> serde::Deserialize<'de> for PresentOptionU64 {
224    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225    where
226        D: serde::Deserializer<'de>,
227    {
228        let value = <Option<u64> as serde::Deserialize>::deserialize(deserializer)?;
229        Ok(Self(Some(value)))
230    }
231}
232
233impl<'de> serde::Deserialize<'de> for SemanticStatement {
234    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
235    where
236        D: serde::Deserializer<'de>,
237    {
238        #[derive(serde::Deserialize)]
239        struct Fields {
240            statement_id: String,
241            predicate: String,
242            #[serde(default)]
243            recognized_sub_kind: Option<SemanticSubKind>,
244            #[serde(default)]
245            label: Option<String>,
246            #[serde(default)]
247            basis: PresentBasis,
248            #[serde(default)]
249            graph_scope: GraphScope,
250            #[serde(default)]
251            provenance_iri: Option<String>,
252            #[serde(default)]
253            asserted_at_ms: Option<u64>,
254            #[serde(default)]
255            first_asserted_ms: PresentOptionU64,
256            #[serde(default)]
257            withdrawn: Option<AssertionWithdrawal>,
258        }
259
260        let fields = <Fields as serde::Deserialize>::deserialize(deserializer)?;
261        let basis = fields.basis.0.flatten().unwrap_or_else(|| AssertionBasis {
262            note: fields.label.clone(),
263            ..Default::default()
264        });
265        let label = basis.note.clone();
266        Ok(Self {
267            statement_id: fields.statement_id,
268            predicate: fields.predicate,
269            recognized_sub_kind: fields.recognized_sub_kind,
270            label,
271            basis,
272            graph_scope: fields.graph_scope,
273            provenance_iri: fields.provenance_iri,
274            first_asserted_ms: fields.first_asserted_ms.0.unwrap_or(fields.asserted_at_ms),
275            asserted_at_ms: fields.asserted_at_ms,
276            withdrawn: fields.withdrawn,
277        })
278    }
279}
280
281#[derive(
282    Debug,
283    Clone,
284    PartialEq,
285    Eq,
286    Archive,
287    Serialize,
288    Deserialize,
289    serde::Serialize,
290    serde::Deserialize,
291    Default,
292)]
293pub struct SemanticData {
294    /// Compatibility aggregate: kept during the bucket migration so existing
295    /// readers can keep asking the pair-local edge what semantic kinds it
296    /// carries. The statement list below is the durable truth.
297    pub sub_kinds: BTreeSet<SemanticSubKind>,
298    /// Compatibility aggregate over the statement labels.
299    pub label: Option<String>,
300    /// Open predicate IRI (the statements-over-schema substrate, linked-data
301    /// plan Phase 0). `None` when the edge's meaning is fully carried by
302    /// `sub_kinds`; a canonical IRI ([`predicate_iri`]) for a recognized
303    /// predicate, or a raw IRI for an unrecognized one. `sub_kinds` stays
304    /// authoritative for behaviour; `predicate` carries identity + round-trip.
305    /// During the statement-bucket migration this is a compatibility view over
306    /// the statement predicates, not the durable truth.
307    pub predicate: Option<String>,
308    /// The one durable assertion list carried between a directed pair.
309    pub statements: Vec<SemanticStatement>,
310}
311
312/// A statement to assert: everything a [`SemanticStatement`] carries except
313/// its id, which the kernel mints (device-safe) at assert time. The
314/// statement-aware write API's input — the petgraph-RDF plan's Phase 1
315/// requirement that interactive writes can carry per-statement metadata, not
316/// just the legacy edge-wide predicate stamp.
317#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
318pub struct SemanticStatementSpec {
319    pub predicate: String,
320    pub recognized_sub_kind: Option<SemanticSubKind>,
321    pub label: Option<String>,
322    /// Optional reason metadata; on admission `basis.note` is authoritative.
323    pub basis: AssertionBasis,
324    pub graph_scope: GraphScope,
325    pub provenance_iri: Option<String>,
326    pub asserted_at_ms: Option<u64>,
327}
328
329impl SemanticStatementSpec {
330    pub fn normalized(mut self) -> Self {
331        if self.basis.note.is_none() {
332            self.basis.note = self.label.clone();
333        }
334        self.label = self.basis.note.clone();
335        self
336    }
337}
338
339/// What [`SemanticData::assert_statement`] did.
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct StatementAssert {
342    /// The asserted fact's handle — freshly minted, or the existing
343    /// statement's id when content-dedup matched.
344    pub statement_id: String,
345    /// Whether anything changed (a new statement, or metadata updated on the
346    /// deduped one). `false` = the exact statement already existed.
347    pub changed: bool,
348}
349
350impl SemanticData {
351    pub fn statements(&self) -> &[SemanticStatement] {
352        &self.statements
353    }
354
355    pub fn held_statements(&self) -> impl Iterator<Item = &SemanticStatement> {
356        self.statements
357            .iter()
358            .filter(|statement| statement.is_held())
359    }
360
361    /// Membership ensure: content-dedup on held statements by
362    /// `(recognized_sub_kind, predicate, graph_scope, provenance_iri)` (same key as
363    /// [`insert_statement`](Self::insert_statement)), updating the deduped
364    /// statement's metadata in place; a miss mints a device-safe id and
365    /// appends. Always returns the fact handle.
366    pub fn assert_statement(&mut self, spec: SemanticStatementSpec) -> StatementAssert {
367        let spec = spec.normalized();
368        if let Some(existing) = self.statements.iter_mut().find(|statement| {
369            statement.is_held()
370                && statement.recognized_sub_kind == spec.recognized_sub_kind
371                && statement.predicate == spec.predicate
372                && statement.graph_scope == spec.graph_scope
373                && statement.provenance_iri == spec.provenance_iri
374                && statement.basis.same_reason_as(&spec.basis)
375        }) {
376            let update_time = spec.asserted_at_ms.is_some();
377            let changed = existing.label != spec.label
378                || existing.basis != spec.basis
379                || (update_time && existing.asserted_at_ms != spec.asserted_at_ms);
380            let statement_id = existing.statement_id.clone();
381            if changed {
382                existing.label = spec.label;
383                existing.basis = spec.basis;
384                if update_time {
385                    existing.asserted_at_ms = spec.asserted_at_ms;
386                }
387                self.rebuild_compat();
388            }
389            return StatementAssert {
390                statement_id,
391                changed,
392            };
393        }
394        let mut statement = SemanticStatement::new(
395            spec.predicate,
396            spec.recognized_sub_kind,
397            spec.label,
398            spec.graph_scope,
399            spec.provenance_iri,
400            spec.asserted_at_ms,
401        );
402        statement.basis = spec.basis;
403        let statement_id = statement.statement_id.clone();
404        self.statements.push(statement);
405        self.rebuild_compat();
406        StatementAssert {
407            statement_id,
408            changed: true,
409        }
410    }
411
412    /// Mark one exact held assertion withdrawn without deleting its history.
413    pub fn withdraw_statement(
414        &mut self,
415        statement_id: &str,
416        withdrawal: AssertionWithdrawal,
417    ) -> bool {
418        let Some(statement) = self
419            .statements
420            .iter_mut()
421            .find(|statement| statement.statement_id == statement_id)
422        else {
423            return false;
424        };
425        if statement.withdrawn.is_some() {
426            return false;
427        }
428        statement.withdrawn = Some(withdrawal);
429        self.rebuild_compat();
430        true
431    }
432
433    /// Retention compaction only: physically remove an assertion after its
434    /// tombstone has been captured by the owning checkpoint.
435    pub(crate) fn compact_statement(&mut self, statement_id: &str) -> bool {
436        let before = self.statements.len();
437        self.statements
438            .retain(|statement| statement.statement_id != statement_id);
439        if self.statements.len() == before {
440            return false;
441        }
442        self.rebuild_compat();
443        true
444    }
445
446    pub fn insert_statement(
447        &mut self,
448        recognized_sub_kind: Option<SemanticSubKind>,
449        predicate: String,
450        label: Option<String>,
451        graph_scope: GraphScope,
452        provenance_iri: Option<String>,
453        asserted_at_ms: Option<u64>,
454    ) -> bool {
455        let basis = AssertionBasis {
456            note: label.clone(),
457            ..Default::default()
458        };
459        if let Some(existing) = self.statements.iter_mut().find(|statement| {
460            statement.is_held()
461                && statement.recognized_sub_kind == recognized_sub_kind
462                && statement.predicate == predicate
463                && statement.graph_scope == graph_scope
464                && statement.provenance_iri == provenance_iri
465                && statement.basis.same_reason_as(&basis)
466        }) {
467            let update_time = asserted_at_ms.is_some();
468            if existing.label != label || (update_time && existing.asserted_at_ms != asserted_at_ms)
469            {
470                existing.label = label;
471                existing.basis.note = existing.label.clone();
472                if update_time {
473                    existing.asserted_at_ms = asserted_at_ms;
474                }
475                self.rebuild_compat();
476                return true;
477            }
478            return false;
479        }
480
481        let mut statement = SemanticStatement::new(
482            predicate,
483            recognized_sub_kind,
484            label,
485            graph_scope,
486            provenance_iri,
487            asserted_at_ms,
488        );
489        statement.basis = basis;
490        self.statements.push(statement);
491        self.rebuild_compat();
492        true
493    }
494
495    pub(crate) fn upsert_persisted_statement(&mut self, mut statement: SemanticStatement) -> bool {
496        statement.normalize_basis_compat();
497        if let Some(existing) = self
498            .statements
499            .iter_mut()
500            .find(|existing| existing.statement_id == statement.statement_id)
501        {
502            // A withdrawn ID is a tombstone: stale exact-ID replay/import must
503            // not revive it or overwrite its lifecycle.
504            if existing.withdrawn.is_some() {
505                return false;
506            }
507            if existing.predicate == statement.predicate
508                && existing.recognized_sub_kind == statement.recognized_sub_kind
509                && existing.graph_scope == statement.graph_scope
510                && existing.provenance_iri == statement.provenance_iri
511                && existing.label == statement.label
512                && existing.basis == statement.basis
513                && existing.asserted_at_ms == statement.asserted_at_ms
514                && existing.withdrawn == statement.withdrawn
515            {
516                return false;
517            }
518            existing.predicate = statement.predicate;
519            existing.recognized_sub_kind = statement.recognized_sub_kind;
520            existing.graph_scope = statement.graph_scope;
521            existing.provenance_iri = statement.provenance_iri;
522            existing.label = statement.label;
523            existing.basis = statement.basis;
524            existing.asserted_at_ms = statement.asserted_at_ms;
525            existing.withdrawn = statement.withdrawn;
526            self.rebuild_compat();
527            return true;
528        }
529        self.push_persisted_statement(statement)
530    }
531
532    /// Exact restore preserves every stored handle, including legacy records.
533    pub fn push_persisted_statement(&mut self, mut statement: SemanticStatement) -> bool {
534        statement.normalize_basis_compat();
535        if self
536            .statements
537            .iter()
538            .any(|existing| existing.statement_id == statement.statement_id)
539        {
540            return false;
541        }
542        self.statements.push(statement);
543        self.rebuild_compat();
544        true
545    }
546
547    /// Migration/retention compaction primitive. Authored graph retractions
548    /// must use Graph's exact-ID withdrawal API instead.
549    pub(crate) fn remove_statements_with_sub_kind(&mut self, sub_kind: SemanticSubKind) -> bool {
550        let before = self.statements.len();
551        self.statements.retain(|statement| {
552            !statement.is_held() || statement.recognized_sub_kind != Some(sub_kind)
553        });
554        if self.statements.len() == before {
555            return false;
556        }
557        self.rebuild_compat();
558        true
559    }
560
561    pub fn set_statement_predicate(&mut self, predicate: Option<String>) {
562        match predicate {
563            Some(predicate) => {
564                if !self.held_statements().any(SemanticStatement::is_semantic) {
565                    self.statements.push(SemanticStatement::new(
566                        predicate,
567                        None,
568                        self.label.clone(),
569                        GraphScope::Default,
570                        None,
571                        None,
572                    ));
573                } else {
574                    for statement in self
575                        .statements
576                        .iter_mut()
577                        .filter(|statement| statement.is_held() && statement.is_semantic())
578                    {
579                        statement.predicate = predicate.clone();
580                    }
581                }
582            },
583            None => {
584                for statement in self
585                    .statements
586                    .iter_mut()
587                    .filter(|s| s.is_held() && s.is_semantic())
588                {
589                    if let Some(sub_kind) = statement.recognized_sub_kind {
590                        statement.predicate = predicate_iri(sub_kind).to_string();
591                    } else {
592                        // This compatibility setter has no authored event
593                        // envelope. Preserve an undated tombstone; callers
594                        // that need record time/actor use Graph's writer API.
595                        statement.withdrawn = Some(AssertionWithdrawal {
596                            at_ms: None,
597                            by: None,
598                        });
599                    }
600                }
601            },
602        }
603        self.rebuild_compat();
604    }
605
606    pub(crate) fn rebuild_compat(&mut self) {
607        // Semantic-only access remains a borrowed contiguous slice, even with
608        // a large non-semantic withdrawal history. Stable partitioning keeps
609        // the original relative order inside both groups.
610        self.statements
611            .sort_by_key(|statement| !statement.is_semantic());
612        self.sub_kinds = self
613            .statements
614            .iter()
615            .filter(|statement| statement.is_held() && statement.is_semantic())
616            .filter_map(|statement| match statement.relation_kind() {
617                super::RelationKind::Semantic(kind) => Some(kind),
618                _ => None,
619            })
620            .collect();
621
622        let mut labels = self
623            .statements
624            .iter()
625            .filter(|statement| statement.is_held() && statement.is_semantic())
626            .filter_map(|statement| statement.label.clone())
627            .collect::<Vec<_>>();
628        labels.sort();
629        labels.dedup();
630        self.label = match labels.len() {
631            0 => None,
632            1 => labels.into_iter().next(),
633            _ => self
634                .statements
635                .iter()
636                .rev()
637                .filter(|statement| statement.is_held() && statement.is_semantic())
638                .find_map(|statement| statement.label.clone()),
639        };
640
641        let mut predicates = self
642            .statements
643            .iter()
644            .filter(|statement| statement.is_held() && statement.is_semantic())
645            .map(|statement| statement.predicate.clone())
646            .collect::<Vec<_>>();
647        predicates.sort();
648        predicates.dedup();
649        self.predicate = if predicates.len() == 1 {
650            predicates.into_iter().next()
651        } else {
652            None
653        };
654    }
655}
656
657/// Base IRI for Mere's canonical relation vocabulary. Recognized
658/// [`SemanticSubKind`]s map to `{REL_VOCAB}{slug}` (the "small Mere vocabulary
659/// of canonical IRIs"); the JSON-LD export layer maps these onto standard
660/// vocabularies (CiTO, schema.org, …) through its `@context`. Provisional base.
661pub const REL_VOCAB: &str = "https://mere.computer/ns/rel#";
662
663/// The canonical relation IRI for a recognized semantic sub-kind. Inverse of
664/// [`sub_kind_from_iri`].
665pub fn predicate_iri(sub_kind: SemanticSubKind) -> &'static str {
666    match sub_kind {
667        SemanticSubKind::Hyperlink => "https://mere.computer/ns/rel#hyperlink",
668        SemanticSubKind::UserGrouped => "https://mere.computer/ns/rel#user-grouped",
669        SemanticSubKind::AgentDerived => "https://mere.computer/ns/rel#agent-derived",
670        SemanticSubKind::Cites => "https://mere.computer/ns/rel#cites",
671        SemanticSubKind::Quotes => "https://mere.computer/ns/rel#quotes",
672        SemanticSubKind::Summarizes => "https://mere.computer/ns/rel#summarizes",
673        SemanticSubKind::Elaborates => "https://mere.computer/ns/rel#elaborates",
674        SemanticSubKind::ExampleOf => "https://mere.computer/ns/rel#example-of",
675        SemanticSubKind::Supports => "https://mere.computer/ns/rel#supports",
676        SemanticSubKind::Contradicts => "https://mere.computer/ns/rel#contradicts",
677        SemanticSubKind::Questions => "https://mere.computer/ns/rel#questions",
678        SemanticSubKind::SameEntityAs => "https://mere.computer/ns/rel#same-entity-as",
679        SemanticSubKind::DuplicateOf => "https://mere.computer/ns/rel#duplicate-of",
680        SemanticSubKind::CanonicalMirrorOf => "https://mere.computer/ns/rel#canonical-mirror-of",
681        SemanticSubKind::DependsOn => "https://mere.computer/ns/rel#depends-on",
682        SemanticSubKind::Blocks => "https://mere.computer/ns/rel#blocks",
683        SemanticSubKind::NextStep => "https://mere.computer/ns/rel#next-step",
684    }
685}
686
687/// The recognized semantic sub-kind for a canonical relation IRI, if any.
688/// Inverse of [`predicate_iri`]; `None` for an unrecognized (raw) IRI, which is
689/// stored as an open predicate without a sub-kind.
690pub fn sub_kind_from_iri(iri: &str) -> Option<SemanticSubKind> {
691    use strum::IntoEnumIterator;
692    SemanticSubKind::iter().find(|&sub_kind| predicate_iri(sub_kind) == iri)
693}
694
695/// Every recognized semantic sub-kind, in declaration order. The kernel owns the
696/// enumeration of its recognized relation vocabulary; downstream projection code
697/// (e.g. linked-data's standard-vocabulary alignment) maps over it without
698/// re-deriving the list or pulling in `strum`.
699pub fn all_semantic_sub_kinds() -> impl Iterator<Item = SemanticSubKind> {
700    use strum::IntoEnumIterator;
701    SemanticSubKind::iter()
702}
703
704#[derive(
705    Debug,
706    Clone,
707    PartialEq,
708    Eq,
709    Archive,
710    Serialize,
711    Deserialize,
712    serde::Serialize,
713    serde::Deserialize,
714    Default,
715)]
716pub struct TraversalData {
717    pub traversals: Vec<Traversal>,
718    pub metrics: EdgeMetrics,
719}
720
721impl TraversalData {
722    pub(crate) fn push(&mut self, traversal: Traversal) {
723        self.metrics.record(traversal);
724        self.traversals.push(traversal);
725    }
726}
727
728#[derive(
729    Debug,
730    Clone,
731    PartialEq,
732    Eq,
733    Archive,
734    Serialize,
735    Deserialize,
736    serde::Serialize,
737    serde::Deserialize,
738    Default,
739)]
740pub struct ArrangementData {
741    pub sub_kinds: BTreeSet<ArrangementSubKind>,
742}
743
744#[derive(
745    Debug,
746    Clone,
747    PartialEq,
748    Eq,
749    Archive,
750    Serialize,
751    Deserialize,
752    serde::Serialize,
753    serde::Deserialize,
754    Default,
755)]
756pub struct ContainmentData {
757    pub sub_kinds: BTreeSet<ContainmentSubKind>,
758}
759
760#[derive(
761    Debug,
762    Clone,
763    PartialEq,
764    Eq,
765    Archive,
766    Serialize,
767    Deserialize,
768    serde::Serialize,
769    serde::Deserialize,
770    Default,
771)]
772pub struct ImportedData {
773    pub sub_kinds: BTreeSet<ImportedSubKind>,
774}
775
776#[derive(
777    Debug,
778    Clone,
779    PartialEq,
780    Eq,
781    Archive,
782    Serialize,
783    Deserialize,
784    serde::Serialize,
785    serde::Deserialize,
786    Default,
787)]
788pub struct ProvenanceData {
789    pub sub_kinds: BTreeSet<ProvenanceSubKind>,
790}
791
792impl ContainmentData {
793    pub(crate) fn insert(&mut self, sub_kind: ContainmentSubKind) -> bool {
794        self.sub_kinds.insert(sub_kind)
795    }
796
797    pub(crate) fn remove(&mut self, sub_kind: ContainmentSubKind) -> bool {
798        self.sub_kinds.remove(&sub_kind)
799    }
800
801    pub(crate) fn contains(&self, sub_kind: ContainmentSubKind) -> bool {
802        self.sub_kinds.contains(&sub_kind)
803    }
804
805    pub(crate) fn is_empty(&self) -> bool {
806        self.sub_kinds.is_empty()
807    }
808}
809
810impl ArrangementData {
811    pub(crate) fn insert(&mut self, sub_kind: ArrangementSubKind) -> bool {
812        self.sub_kinds.insert(sub_kind)
813    }
814
815    pub(crate) fn remove(&mut self, sub_kind: ArrangementSubKind) -> bool {
816        self.sub_kinds.remove(&sub_kind)
817    }
818
819    pub(crate) fn contains(&self, sub_kind: ArrangementSubKind) -> bool {
820        self.sub_kinds.contains(&sub_kind)
821    }
822
823    pub(crate) fn is_empty(&self) -> bool {
824        self.sub_kinds.is_empty()
825    }
826
827    pub(crate) fn has_durable_relation(&self) -> bool {
828        self.sub_kinds
829            .iter()
830            .copied()
831            .any(|sub_kind| sub_kind.durability() == RelationDurability::Durable)
832    }
833
834    pub(crate) fn has_session_relation(&self) -> bool {
835        self.sub_kinds
836            .iter()
837            .copied()
838            .any(|sub_kind| sub_kind.durability() == RelationDurability::Session)
839    }
840}
841
842#[cfg(test)]
843mod canonical_family_controls {
844    use super::*;
845    use crate::graph::{ContainmentSubKind, EdgeFamily, RelationKind};
846
847    #[test]
848    fn canonical_predicate_owns_classification_and_legacy_hint_is_only_a_fallback() {
849        let mut record = SemanticStatement::new(
850            RelationKind::Containment(ContainmentSubKind::CollectionMember)
851                .predicate_iri()
852                .unwrap()
853                .into(),
854            Some(SemanticSubKind::Cites),
855            None,
856            GraphScope::Default,
857            None,
858            None,
859        );
860        assert_eq!(
861            record.relation_kind(),
862            RelationKind::Containment(ContainmentSubKind::CollectionMember)
863        );
864        assert!(!record.is_semantic());
865        let mut data = SemanticData {
866            statements: vec![record.clone()],
867            ..Default::default()
868        };
869        data.rebuild_compat();
870        assert!(data.sub_kinds.is_empty());
871        record.predicate = predicate_iri(SemanticSubKind::Quotes).into();
872        assert_eq!(
873            record.relation_kind(),
874            RelationKind::Semantic(SemanticSubKind::Quotes)
875        );
876        data.statements = vec![record.clone()];
877        data.rebuild_compat();
878        assert_eq!(data.sub_kinds, BTreeSet::from([SemanticSubKind::Quotes]));
879        record.predicate = "urn:legacy:custom-predicate".into();
880        assert_eq!(
881            record.relation_kind(),
882            RelationKind::Semantic(SemanticSubKind::Cites)
883        );
884        record.recognized_sub_kind = None;
885        assert_eq!(record.relation_kind(), RelationKind::OpenPredicate);
886        assert_eq!(record.relation_kind().family(), EdgeFamily::Semantic);
887    }
888}