Skip to main content

kernel/graph/
edge_data.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Per-family edge runtime data structs and semantic IRI mapping.
5//! Extracted from `edge_taxonomy.rs` per the 600-LOC ceiling.
6
7use std::collections::BTreeSet;
8
9use rkyv::{Archive, Deserialize, Serialize};
10
11use crate::types::{GraphScope, mint_local_statement_id};
12
13use super::edge_taxonomy::{
14    ArrangementSubKind, ContainmentSubKind, ImportedSubKind, NavigationTrigger, ProvenanceSubKind,
15    RelationDurability, SemanticSubKind,
16};
17
18/// A temporal traversal event recorded on an edge.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
20pub struct Traversal {
21    pub timestamp_ms: u64,
22    pub trigger: NavigationTrigger,
23}
24
25impl Traversal {
26    pub fn now(trigger: NavigationTrigger) -> Self {
27        let timestamp_ms = crate::time::unix_epoch_millis();
28        Self {
29            timestamp_ms,
30            trigger,
31        }
32    }
33}
34
35/// Durable traversal aggregates retained even when rolling-window records are evicted.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
37pub struct EdgeMetrics {
38    pub total_navigations: u64,
39    pub forward_navigations: u64,
40    pub backward_navigations: u64,
41    pub last_navigated_at: Option<u64>,
42}
43
44impl EdgeMetrics {
45    fn new() -> Self {
46        Self {
47            total_navigations: 0,
48            forward_navigations: 0,
49            backward_navigations: 0,
50            last_navigated_at: None,
51        }
52    }
53
54    fn record(&mut self, traversal: Traversal) {
55        self.total_navigations = self.total_navigations.saturating_add(1);
56        if traversal.trigger.contributes_to_forward_count() {
57            self.forward_navigations = self.forward_navigations.saturating_add(1);
58        } else {
59            self.backward_navigations = self.backward_navigations.saturating_add(1);
60        }
61        self.last_navigated_at = Some(traversal.timestamp_ms);
62    }
63}
64
65impl Default for EdgeMetrics {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
72pub struct SemanticStatement {
73    pub statement_id: String,
74    pub predicate: String,
75    pub recognized_sub_kind: Option<SemanticSubKind>,
76    pub label: Option<String>,
77    pub graph_scope: GraphScope,
78    pub provenance_iri: Option<String>,
79    pub asserted_at_ms: Option<u64>,
80}
81
82impl SemanticStatement {
83    pub fn new(
84        predicate: String,
85        recognized_sub_kind: Option<SemanticSubKind>,
86        label: Option<String>,
87        graph_scope: GraphScope,
88        provenance_iri: Option<String>,
89        asserted_at_ms: Option<u64>,
90    ) -> Self {
91        Self {
92            statement_id: mint_local_statement_id(),
93            predicate,
94            recognized_sub_kind,
95            label,
96            graph_scope,
97            provenance_iri,
98            asserted_at_ms,
99        }
100    }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
104pub struct SemanticData {
105    /// Compatibility aggregate: kept during the bucket migration so existing
106    /// readers can keep asking the pair-local edge what semantic kinds it
107    /// carries. The statement list below is the durable truth.
108    pub sub_kinds: BTreeSet<SemanticSubKind>,
109    /// Compatibility aggregate over the statement labels.
110    pub label: Option<String>,
111    /// Open predicate IRI (the statements-over-schema substrate, linked-data
112    /// plan Phase 0). `None` when the edge's meaning is fully carried by
113    /// `sub_kinds`; a canonical IRI ([`predicate_iri`]) for a recognized
114    /// predicate, or a raw IRI for an unrecognized one. `sub_kinds` stays
115    /// authoritative for behaviour; `predicate` carries identity + round-trip.
116    /// During the statement-bucket migration this is a compatibility view over
117    /// the statement predicates, not the durable truth.
118    pub predicate: Option<String>,
119    /// The durable semantic facts carried between one node pair.
120    pub statements: Vec<SemanticStatement>,
121}
122
123/// A statement to assert: everything a [`SemanticStatement`] carries except
124/// its id, which the kernel mints (device-safe) at assert time. The
125/// statement-aware write API's input — the petgraph-RDF plan's Phase 1
126/// requirement that interactive writes can carry per-statement metadata, not
127/// just the legacy edge-wide predicate stamp.
128#[derive(Debug, Clone, PartialEq, Eq, Default)]
129pub struct SemanticStatementSpec {
130    pub predicate: String,
131    pub recognized_sub_kind: Option<SemanticSubKind>,
132    pub label: Option<String>,
133    pub graph_scope: GraphScope,
134    pub provenance_iri: Option<String>,
135    pub asserted_at_ms: Option<u64>,
136}
137
138/// What [`SemanticData::assert_statement`] did.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct StatementAssert {
141    /// The asserted fact's handle — freshly minted, or the existing
142    /// statement's id when content-dedup matched.
143    pub statement_id: String,
144    /// Whether anything changed (a new statement, or metadata updated on the
145    /// deduped one). `false` = the exact statement already existed.
146    pub changed: bool,
147}
148
149impl SemanticData {
150    pub fn statements(&self) -> &[SemanticStatement] {
151        &self.statements
152    }
153
154    /// Statement-aware assert: content-dedup on
155    /// `(recognized_sub_kind, predicate, graph_scope)` (same key as
156    /// [`insert_statement`](Self::insert_statement)), updating the deduped
157    /// statement's metadata in place; a miss mints a device-safe id and
158    /// appends. Always returns the fact handle.
159    pub fn assert_statement(&mut self, spec: SemanticStatementSpec) -> StatementAssert {
160        if let Some(existing) = self.statements.iter_mut().find(|statement| {
161            statement.recognized_sub_kind == spec.recognized_sub_kind
162                && statement.predicate == spec.predicate
163                && statement.graph_scope == spec.graph_scope
164        }) {
165            let changed = existing.label != spec.label
166                || existing.provenance_iri != spec.provenance_iri
167                || existing.asserted_at_ms != spec.asserted_at_ms;
168            let statement_id = existing.statement_id.clone();
169            if changed {
170                existing.label = spec.label;
171                existing.provenance_iri = spec.provenance_iri;
172                existing.asserted_at_ms = spec.asserted_at_ms;
173                self.rebuild_compat();
174            }
175            return StatementAssert {
176                statement_id,
177                changed,
178            };
179        }
180        let statement = SemanticStatement::new(
181            spec.predicate,
182            spec.recognized_sub_kind,
183            spec.label,
184            spec.graph_scope,
185            spec.provenance_iri,
186            spec.asserted_at_ms,
187        );
188        let statement_id = statement.statement_id.clone();
189        self.statements.push(statement);
190        self.rebuild_compat();
191        StatementAssert {
192            statement_id,
193            changed: true,
194        }
195    }
196
197    /// Precise retract by fact handle. Bucket-local linear scan by design
198    /// (buckets stay small; a global id index waits for evidence). Returns
199    /// whether a statement was removed.
200    pub fn retract_statement(&mut self, statement_id: &str) -> bool {
201        let before = self.statements.len();
202        self.statements
203            .retain(|statement| statement.statement_id != statement_id);
204        if self.statements.len() == before {
205            return false;
206        }
207        self.rebuild_compat();
208        true
209    }
210
211    pub fn insert_statement(
212        &mut self,
213        recognized_sub_kind: Option<SemanticSubKind>,
214        predicate: String,
215        label: Option<String>,
216        graph_scope: GraphScope,
217        provenance_iri: Option<String>,
218        asserted_at_ms: Option<u64>,
219    ) -> bool {
220        if let Some(existing) = self.statements.iter_mut().find(|statement| {
221            statement.recognized_sub_kind == recognized_sub_kind
222                && statement.predicate == predicate
223                && statement.graph_scope == graph_scope
224        }) {
225            if existing.label != label
226                || existing.provenance_iri != provenance_iri
227                || existing.asserted_at_ms != asserted_at_ms
228            {
229                existing.label = label;
230                existing.provenance_iri = provenance_iri;
231                existing.asserted_at_ms = asserted_at_ms;
232                self.rebuild_compat();
233                return true;
234            }
235            return false;
236        }
237
238        self.statements.push(SemanticStatement::new(
239            predicate,
240            recognized_sub_kind,
241            label,
242            graph_scope,
243            provenance_iri,
244            asserted_at_ms,
245        ));
246        self.rebuild_compat();
247        true
248    }
249
250    pub fn push_persisted_statement(&mut self, statement: SemanticStatement) -> bool {
251        if self
252            .statements
253            .iter()
254            .any(|existing| existing.statement_id == statement.statement_id)
255        {
256            return false;
257        }
258        self.statements.push(statement);
259        self.rebuild_compat();
260        true
261    }
262
263    pub fn remove_statements_with_sub_kind(&mut self, sub_kind: SemanticSubKind) -> bool {
264        let before = self.statements.len();
265        self.statements
266            .retain(|statement| statement.recognized_sub_kind != Some(sub_kind));
267        if self.statements.len() == before {
268            return false;
269        }
270        self.rebuild_compat();
271        true
272    }
273
274    pub fn set_statement_predicate(&mut self, predicate: Option<String>) {
275        match predicate {
276            Some(predicate) => {
277                if self.statements.is_empty() {
278                    self.statements.push(SemanticStatement::new(
279                        predicate,
280                        None,
281                        self.label.clone(),
282                        GraphScope::Default,
283                        None,
284                        None,
285                    ));
286                } else {
287                    for statement in &mut self.statements {
288                        statement.predicate = predicate.clone();
289                    }
290                }
291            }
292            None => {
293                self.statements
294                    .retain(|statement| statement.recognized_sub_kind.is_some());
295                for statement in &mut self.statements {
296                    if let Some(sub_kind) = statement.recognized_sub_kind {
297                        statement.predicate = predicate_iri(sub_kind).to_string();
298                    }
299                }
300            }
301        }
302        self.rebuild_compat();
303    }
304
305    fn rebuild_compat(&mut self) {
306        self.sub_kinds = self
307            .statements
308            .iter()
309            .filter_map(|statement| statement.recognized_sub_kind)
310            .collect();
311
312        let mut labels = self
313            .statements
314            .iter()
315            .filter_map(|statement| statement.label.clone())
316            .collect::<Vec<_>>();
317        labels.sort();
318        labels.dedup();
319        self.label = match labels.len() {
320            0 => None,
321            1 => labels.into_iter().next(),
322            _ => self
323                .statements
324                .iter()
325                .rev()
326                .find_map(|statement| statement.label.clone()),
327        };
328
329        let mut predicates = self
330            .statements
331            .iter()
332            .map(|statement| statement.predicate.clone())
333            .collect::<Vec<_>>();
334        predicates.sort();
335        predicates.dedup();
336        self.predicate = if predicates.len() == 1 {
337            predicates.into_iter().next()
338        } else {
339            None
340        };
341    }
342}
343
344/// Base IRI for Mere's canonical relation vocabulary. Recognized
345/// [`SemanticSubKind`]s map to `{REL_VOCAB}{slug}` (the "small Mere vocabulary
346/// of canonical IRIs"); the JSON-LD export layer maps these onto standard
347/// vocabularies (CiTO, schema.org, …) through its `@context`. Provisional base.
348pub const REL_VOCAB: &str = "https://mere.computer/ns/rel#";
349
350/// The canonical relation IRI for a recognized semantic sub-kind. Inverse of
351/// [`sub_kind_from_iri`].
352pub fn predicate_iri(sub_kind: SemanticSubKind) -> &'static str {
353    match sub_kind {
354        SemanticSubKind::Hyperlink => "https://mere.computer/ns/rel#hyperlink",
355        SemanticSubKind::UserGrouped => "https://mere.computer/ns/rel#user-grouped",
356        SemanticSubKind::AgentDerived => "https://mere.computer/ns/rel#agent-derived",
357        SemanticSubKind::Cites => "https://mere.computer/ns/rel#cites",
358        SemanticSubKind::Quotes => "https://mere.computer/ns/rel#quotes",
359        SemanticSubKind::Summarizes => "https://mere.computer/ns/rel#summarizes",
360        SemanticSubKind::Elaborates => "https://mere.computer/ns/rel#elaborates",
361        SemanticSubKind::ExampleOf => "https://mere.computer/ns/rel#example-of",
362        SemanticSubKind::Supports => "https://mere.computer/ns/rel#supports",
363        SemanticSubKind::Contradicts => "https://mere.computer/ns/rel#contradicts",
364        SemanticSubKind::Questions => "https://mere.computer/ns/rel#questions",
365        SemanticSubKind::SameEntityAs => "https://mere.computer/ns/rel#same-entity-as",
366        SemanticSubKind::DuplicateOf => "https://mere.computer/ns/rel#duplicate-of",
367        SemanticSubKind::CanonicalMirrorOf => "https://mere.computer/ns/rel#canonical-mirror-of",
368        SemanticSubKind::DependsOn => "https://mere.computer/ns/rel#depends-on",
369        SemanticSubKind::Blocks => "https://mere.computer/ns/rel#blocks",
370        SemanticSubKind::NextStep => "https://mere.computer/ns/rel#next-step",
371    }
372}
373
374/// The recognized semantic sub-kind for a canonical relation IRI, if any.
375/// Inverse of [`predicate_iri`]; `None` for an unrecognized (raw) IRI, which is
376/// stored as an open predicate without a sub-kind.
377pub fn sub_kind_from_iri(iri: &str) -> Option<SemanticSubKind> {
378    use strum::IntoEnumIterator;
379    SemanticSubKind::iter().find(|&sub_kind| predicate_iri(sub_kind) == iri)
380}
381
382/// Every recognized semantic sub-kind, in declaration order. The kernel owns the
383/// enumeration of its recognized relation vocabulary; downstream projection code
384/// (e.g. linked-data's standard-vocabulary alignment) maps over it without
385/// re-deriving the list or pulling in `strum`.
386pub fn all_semantic_sub_kinds() -> impl Iterator<Item = SemanticSubKind> {
387    use strum::IntoEnumIterator;
388    SemanticSubKind::iter()
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
392pub struct TraversalData {
393    pub traversals: Vec<Traversal>,
394    pub metrics: EdgeMetrics,
395}
396
397impl TraversalData {
398    pub(crate) fn push(&mut self, traversal: Traversal) {
399        self.metrics.record(traversal);
400        self.traversals.push(traversal);
401    }
402}
403
404#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
405pub struct ArrangementData {
406    pub sub_kinds: BTreeSet<ArrangementSubKind>,
407}
408
409#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
410pub struct ContainmentData {
411    pub sub_kinds: BTreeSet<ContainmentSubKind>,
412}
413
414#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
415pub struct ImportedData {
416    pub sub_kinds: BTreeSet<ImportedSubKind>,
417}
418
419#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
420pub struct ProvenanceData {
421    pub sub_kinds: BTreeSet<ProvenanceSubKind>,
422}
423
424impl ContainmentData {
425    pub(crate) fn insert(&mut self, sub_kind: ContainmentSubKind) -> bool {
426        self.sub_kinds.insert(sub_kind)
427    }
428
429    pub(crate) fn remove(&mut self, sub_kind: ContainmentSubKind) -> bool {
430        self.sub_kinds.remove(&sub_kind)
431    }
432
433    pub(crate) fn contains(&self, sub_kind: ContainmentSubKind) -> bool {
434        self.sub_kinds.contains(&sub_kind)
435    }
436
437    pub(crate) fn is_empty(&self) -> bool {
438        self.sub_kinds.is_empty()
439    }
440}
441
442impl ArrangementData {
443    pub(crate) fn insert(&mut self, sub_kind: ArrangementSubKind) -> bool {
444        self.sub_kinds.insert(sub_kind)
445    }
446
447    pub(crate) fn remove(&mut self, sub_kind: ArrangementSubKind) -> bool {
448        self.sub_kinds.remove(&sub_kind)
449    }
450
451    pub(crate) fn contains(&self, sub_kind: ArrangementSubKind) -> bool {
452        self.sub_kinds.contains(&sub_kind)
453    }
454
455    pub(crate) fn is_empty(&self) -> bool {
456        self.sub_kinds.is_empty()
457    }
458
459    pub(crate) fn has_durable_relation(&self) -> bool {
460        self.sub_kinds
461            .iter()
462            .copied()
463            .any(|sub_kind| sub_kind.durability() == RelationDurability::Durable)
464    }
465
466    pub(crate) fn has_session_relation(&self) -> bool {
467        self.sub_kinds
468            .iter()
469            .copied()
470            .any(|sub_kind| sub_kind.durability() == RelationDurability::Session)
471    }
472}