Skip to main content

kernel/graph/
edge_taxonomy.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//! Edge taxonomy types — families, kinds, and sub-kinds.
8//!
9//! Extracted from `graph/mod.rs` per the 2026-05-11 kernel-mod
10//! decomposition pass. Per-family runtime data structs (Traversal,
11//! EdgeMetrics, *Data types, predicate IRI mapping) live in `edge_data.rs`.
12//! [`EdgePayload`](super::EdgePayload) in `edge_payload.rs` is the primary
13//! consumer; `Graph` methods in `mod.rs` reach for these types via re-exports.
14
15use rkyv::{Archive, Deserialize, Serialize};
16
17#[derive(
18    Debug,
19    Clone,
20    Copy,
21    PartialEq,
22    Eq,
23    Hash,
24    PartialOrd,
25    Ord,
26    Archive,
27    Serialize,
28    Deserialize,
29    serde::Serialize,
30    serde::Deserialize,
31)]
32#[rkyv(compare(PartialEq, PartialOrd), derive(PartialEq, Eq, PartialOrd, Ord))]
33pub enum EdgeFamily {
34    Semantic,
35    Traversal,
36    Containment,
37    Arrangement,
38    Imported,
39    Provenance,
40}
41
42#[derive(
43    Debug,
44    Clone,
45    Copy,
46    PartialEq,
47    Eq,
48    Hash,
49    PartialOrd,
50    Ord,
51    Archive,
52    Serialize,
53    Deserialize,
54    serde::Serialize,
55    serde::Deserialize,
56)]
57#[rkyv(compare(PartialEq, PartialOrd), derive(PartialEq, Eq, PartialOrd, Ord))]
58#[derive(strum::EnumIter, strum::FromRepr)]
59pub enum SemanticSubKind {
60    Hyperlink,
61    UserGrouped,
62    AgentDerived,
63    Cites,
64    Quotes,
65    Summarizes,
66    Elaborates,
67    ExampleOf,
68    Supports,
69    Contradicts,
70    Questions,
71    SameEntityAs,
72    DuplicateOf,
73    CanonicalMirrorOf,
74    DependsOn,
75    Blocks,
76    NextStep,
77}
78
79#[derive(
80    Debug,
81    Clone,
82    Copy,
83    PartialEq,
84    Eq,
85    Hash,
86    PartialOrd,
87    Ord,
88    Archive,
89    Serialize,
90    Deserialize,
91    serde::Serialize,
92    serde::Deserialize,
93)]
94#[rkyv(compare(PartialEq, PartialOrd), derive(PartialEq, Eq, PartialOrd, Ord))]
95#[derive(strum::EnumIter, strum::FromRepr)]
96pub enum ArrangementSubKind {
97    FrameMember,
98    TileGroup,
99    SplitPair,
100}
101
102#[derive(
103    Debug,
104    Clone,
105    Copy,
106    PartialEq,
107    Eq,
108    Hash,
109    PartialOrd,
110    Ord,
111    Archive,
112    Serialize,
113    Deserialize,
114    serde::Serialize,
115    serde::Deserialize,
116)]
117#[rkyv(compare(PartialEq, PartialOrd), derive(PartialEq, Eq, PartialOrd, Ord))]
118#[derive(strum::EnumIter, strum::FromRepr)]
119pub enum ContainmentSubKind {
120    UrlPath,
121    Domain,
122    FileSystem,
123    UserFolder,
124    ClipSource,
125    NotebookSection,
126    CollectionMember,
127}
128
129impl ContainmentSubKind {
130    pub fn as_tag(self) -> &'static str {
131        match self {
132            Self::UrlPath => "url-path",
133            Self::Domain => "domain",
134            Self::FileSystem => "filesystem",
135            Self::UserFolder => "user-folder",
136            Self::ClipSource => "clip-source",
137            Self::NotebookSection => "notebook-section",
138            Self::CollectionMember => "collection-member",
139        }
140    }
141}
142
143#[derive(
144    Debug,
145    Clone,
146    Copy,
147    PartialEq,
148    Eq,
149    Hash,
150    PartialOrd,
151    Ord,
152    Archive,
153    Serialize,
154    Deserialize,
155    serde::Serialize,
156    serde::Deserialize,
157)]
158#[rkyv(compare(PartialEq, PartialOrd), derive(PartialEq, Eq, PartialOrd, Ord))]
159#[derive(strum::EnumIter, strum::FromRepr)]
160pub enum ImportedSubKind {
161    BookmarkFolder,
162    HistoryImport,
163    SessionImport,
164    RssMembership,
165    FileSystemImport,
166    ArchiveMembership,
167    SharedCollection,
168}
169
170#[derive(
171    Debug,
172    Clone,
173    Copy,
174    PartialEq,
175    Eq,
176    Hash,
177    PartialOrd,
178    Ord,
179    Archive,
180    Serialize,
181    Deserialize,
182    serde::Serialize,
183    serde::Deserialize,
184)]
185#[rkyv(compare(PartialEq, PartialOrd), derive(PartialEq, Eq, PartialOrd, Ord))]
186#[derive(strum::EnumIter, strum::FromRepr)]
187pub enum ProvenanceSubKind {
188    ClippedFrom,
189    ExcerptedFrom,
190    SummarizedFrom,
191    TranslatedFrom,
192    RewrittenFrom,
193    GeneratedFrom,
194    ExtractedFrom,
195    ImportedFromSource,
196    /// A verbatim duplicate of the source — the cross-graph copy/tear-out
197    /// "fork" relation (tear-out brief §7.5). Unlike the content-transformation
198    /// sub-kinds above, the copy carries the source's content unchanged; only
199    /// its identity and host graph differ. Appended last so existing ordinals
200    /// (and the positional `tag` encoding) stay stable.
201    CopiedFrom,
202    /// A node a merge-in brought from another session: a branch's node merged
203    /// back into its parent, or a picked-off part's node merged back into the
204    /// session it was picked from (session merge-in note, M4). The reverse of
205    /// [`CopiedFrom`](Self::CopiedFrom), recorded on the target node. Appended
206    /// last to keep ordinals stable.
207    MergedFrom,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
211pub enum RelationDurability {
212    Durable,
213    Session,
214}
215
216impl RelationDurability {
217    pub fn as_tag(self) -> &'static str {
218        match self {
219            Self::Durable => "durable",
220            Self::Session => "session",
221        }
222    }
223}
224
225impl ArrangementSubKind {
226    pub fn as_tag(self) -> &'static str {
227        match self {
228            Self::FrameMember => "frame-member",
229            Self::TileGroup => "tile-group",
230            Self::SplitPair => "split-pair",
231        }
232    }
233
234    pub fn durability(self) -> RelationDurability {
235        match self {
236            Self::FrameMember => RelationDurability::Durable,
237            Self::TileGroup | Self::SplitPair => RelationDurability::Session,
238        }
239    }
240
241    pub fn provenance(self) -> &'static str {
242        match self {
243            Self::FrameMember => "workbench.frame_snapshot",
244            Self::TileGroup => "workbench.tile_grouping",
245            Self::SplitPair => "workbench.split_pairing",
246        }
247    }
248}
249
250#[derive(
251    Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
252)]
253#[serde(deny_unknown_fields)]
254pub enum EdgeAssertion {
255    Semantic {
256        sub_kind: SemanticSubKind,
257        label: Option<String>,
258    },
259    Containment {
260        sub_kind: ContainmentSubKind,
261    },
262    Arrangement {
263        sub_kind: ArrangementSubKind,
264    },
265    Imported {
266        sub_kind: ImportedSubKind,
267    },
268    Provenance {
269        sub_kind: ProvenanceSubKind,
270    },
271}
272
273#[derive(
274    Debug,
275    Clone,
276    Copy,
277    PartialEq,
278    Eq,
279    Hash,
280    Archive,
281    Serialize,
282    Deserialize,
283    serde::Serialize,
284    serde::Deserialize,
285)]
286pub enum RelationSelector {
287    Family(EdgeFamily),
288    Semantic(SemanticSubKind),
289    Containment(ContainmentSubKind),
290    Arrangement(ArrangementSubKind),
291    Imported(ImportedSubKind),
292    Provenance(ProvenanceSubKind),
293}
294
295/// Trigger classification for a traversal event.
296///
297/// Expanded per the 2026-05-11 relation-taxonomy-and-edge-mutation
298/// plan §2: `Traversal` stays the one family without sub-kinds;
299/// temporal nuance instead lives here in the trigger vocabulary.
300/// Five additions to cover the cases the prior plan called out:
301/// HTTP / meta redirects, session-restore navigations, in-document
302/// fragment jumps, find-in-page-style jumps, and imported-history
303/// hypotheses.
304#[derive(
305    Debug,
306    Clone,
307    Copy,
308    PartialEq,
309    Eq,
310    Archive,
311    Serialize,
312    Deserialize,
313    serde::Serialize,
314    serde::Deserialize,
315)]
316pub enum NavigationTrigger {
317    Unknown,
318    LinkClick,
319    Back,
320    Forward,
321    AddressBarEntry,
322    PanePromotion,
323    Programmatic,
324    /// Server redirect (3xx) or meta-refresh — the user didn't
325    /// directly initiate this hop.
326    Redirect,
327    /// Navigation re-issued by a session restore (window reopen,
328    /// "restore previous tabs," persisted-session rehydration).
329    ReopenSession,
330    /// In-document anchor jump (fragment / `#section`) — same
331    /// document, scroll destination changes.
332    JumpAnchor,
333    /// "Find in page" or analogous within-document search jumps
334    /// that surface as a navigation event.
335    InPageSearchJump,
336    /// Imported from another browser's history database. Distinct
337    /// from `Unknown` so importers can tag confidence-bounded
338    /// traversal hypotheses without conflating them with native
339    /// user navigation.
340    ImportedHistory,
341}
342
343impl NavigationTrigger {
344    #[allow(dead_code)]
345    pub(crate) fn contributes_to_forward_count(self) -> bool {
346        !matches!(self, Self::Back)
347    }
348}
349
350/// Canonical read-side classifier for an edge's relation. Combines
351/// family + sub-kind into one enum that callers reaching for "what
352/// kind of relation is this?" can match on without touching the
353/// write-side `EdgeAssertion` payload.
354///
355/// Per the 2026-05-11 relation-taxonomy plan §3: `RelationKind`
356/// is the discriminant shape (`RelationKind ≈
357/// discriminant(EdgeAssertion)`), used by canvas hit-tests, render
358/// policy, filter UIs, action-target inference, and view-local
359/// hide keys. `EdgeAssertion` remains the write contract — it
360/// carries construction-time payload (labels, decay state, etc.)
361/// that read sites don't need.
362///
363/// `Traversal` is the one variant without a sub-kind: traversal
364/// is event-shaped, with temporal nuance in [`NavigationTrigger`]
365/// rather than a `TraversalSubKind` enum.
366///
367/// `OpenPredicate` is a Semantic statement whose predicate IRI has no
368/// recognized [`SemanticSubKind`] (minted by `assert_semantic_predicate`
369/// / JSON-LD ingest). It exists so `relations()` emits one row per
370/// statement, matching `has_relation(Family(Semantic))` (Q1 ruling,
371/// 2026-09-12). The IRI is reached through the typed payload
372/// (`semantic_statements()`), not carried on the row, so the kind stays
373/// `Copy`.
374#[derive(
375    Debug,
376    Clone,
377    Copy,
378    PartialEq,
379    Eq,
380    Hash,
381    Archive,
382    Serialize,
383    Deserialize,
384    serde::Serialize,
385    serde::Deserialize,
386)]
387pub enum RelationKind {
388    Semantic(SemanticSubKind),
389    OpenPredicate,
390    Traversal,
391    Containment(ContainmentSubKind),
392    Arrangement(ArrangementSubKind),
393    Imported(ImportedSubKind),
394    Provenance(ProvenanceSubKind),
395}
396
397/// Sub-kind ordinal reserved in the Semantic family byte for
398/// [`RelationKind::OpenPredicate`] in [`RelationKind::tag`].
399const OPEN_PREDICATE_TAG_SUB: u32 = 0x00ff_ffff;
400
401impl RelationKind {
402    /// The canonical predicate IRI for a recognized relation kind.
403    ///
404    /// Semantic predicates retain their established byte-for-byte IRIs.
405    /// The other sub-kind families use an explicit family-qualified local
406    /// name so their predicate identity is stable across refactors. Traversal
407    /// and open predicates do not name one fixed predicate here.
408    pub fn predicate_iri(self) -> Option<&'static str> {
409        use super::edge_data::predicate_iri as semantic_predicate_iri;
410
411        match self {
412            RelationKind::Semantic(sub_kind) => Some(semantic_predicate_iri(sub_kind)),
413            RelationKind::OpenPredicate | RelationKind::Traversal => None,
414            RelationKind::Containment(sub_kind) => Some(match sub_kind {
415                ContainmentSubKind::UrlPath => "https://mere.computer/ns/rel#containment.url-path",
416                ContainmentSubKind::Domain => "https://mere.computer/ns/rel#containment.domain",
417                ContainmentSubKind::FileSystem => {
418                    "https://mere.computer/ns/rel#containment.filesystem"
419                },
420                ContainmentSubKind::UserFolder => {
421                    "https://mere.computer/ns/rel#containment.user-folder"
422                },
423                ContainmentSubKind::ClipSource => {
424                    "https://mere.computer/ns/rel#containment.clip-source"
425                },
426                ContainmentSubKind::NotebookSection => {
427                    "https://mere.computer/ns/rel#containment.notebook-section"
428                },
429                ContainmentSubKind::CollectionMember => {
430                    "https://mere.computer/ns/rel#containment.collection-member"
431                },
432            }),
433            RelationKind::Arrangement(sub_kind) => Some(match sub_kind {
434                ArrangementSubKind::FrameMember => {
435                    "https://mere.computer/ns/rel#arrangement.frame-member"
436                },
437                ArrangementSubKind::TileGroup => {
438                    "https://mere.computer/ns/rel#arrangement.tile-group"
439                },
440                ArrangementSubKind::SplitPair => {
441                    "https://mere.computer/ns/rel#arrangement.split-pair"
442                },
443            }),
444            RelationKind::Imported(sub_kind) => Some(match sub_kind {
445                ImportedSubKind::BookmarkFolder => {
446                    "https://mere.computer/ns/rel#imported.bookmark-folder"
447                },
448                ImportedSubKind::HistoryImport => {
449                    "https://mere.computer/ns/rel#imported.history-import"
450                },
451                ImportedSubKind::SessionImport => {
452                    "https://mere.computer/ns/rel#imported.session-import"
453                },
454                ImportedSubKind::RssMembership => {
455                    "https://mere.computer/ns/rel#imported.rss-membership"
456                },
457                ImportedSubKind::FileSystemImport => {
458                    "https://mere.computer/ns/rel#imported.filesystem-import"
459                },
460                ImportedSubKind::ArchiveMembership => {
461                    "https://mere.computer/ns/rel#imported.archive-membership"
462                },
463                ImportedSubKind::SharedCollection => {
464                    "https://mere.computer/ns/rel#imported.shared-collection"
465                },
466            }),
467            RelationKind::Provenance(sub_kind) => Some(match sub_kind {
468                ProvenanceSubKind::ClippedFrom => {
469                    "https://mere.computer/ns/rel#provenance.clipped-from"
470                },
471                ProvenanceSubKind::ExcerptedFrom => {
472                    "https://mere.computer/ns/rel#provenance.excerpted-from"
473                },
474                ProvenanceSubKind::SummarizedFrom => {
475                    "https://mere.computer/ns/rel#provenance.summarized-from"
476                },
477                ProvenanceSubKind::TranslatedFrom => {
478                    "https://mere.computer/ns/rel#provenance.translated-from"
479                },
480                ProvenanceSubKind::RewrittenFrom => {
481                    "https://mere.computer/ns/rel#provenance.rewritten-from"
482                },
483                ProvenanceSubKind::GeneratedFrom => {
484                    "https://mere.computer/ns/rel#provenance.generated-from"
485                },
486                ProvenanceSubKind::ExtractedFrom => {
487                    "https://mere.computer/ns/rel#provenance.extracted-from"
488                },
489                ProvenanceSubKind::ImportedFromSource => {
490                    "https://mere.computer/ns/rel#provenance.imported-from-source"
491                },
492                ProvenanceSubKind::CopiedFrom => {
493                    "https://mere.computer/ns/rel#provenance.copied-from"
494                },
495                ProvenanceSubKind::MergedFrom => {
496                    "https://mere.computer/ns/rel#provenance.merged-from"
497                },
498            }),
499        }
500    }
501
502    /// Decode a canonical predicate IRI produced by [`Self::predicate_iri`].
503    /// Unknown and open predicates remain outside the closed relation-kind
504    /// vocabulary.
505    pub fn from_predicate_iri(iri: &str) -> Option<Self> {
506        use super::edge_data::sub_kind_from_iri as semantic_sub_kind_from_iri;
507
508        if let Some(sub_kind) = semantic_sub_kind_from_iri(iri) {
509            return Some(RelationKind::Semantic(sub_kind));
510        }
511
512        [
513            ContainmentSubKind::UrlPath,
514            ContainmentSubKind::Domain,
515            ContainmentSubKind::FileSystem,
516            ContainmentSubKind::UserFolder,
517            ContainmentSubKind::ClipSource,
518            ContainmentSubKind::NotebookSection,
519            ContainmentSubKind::CollectionMember,
520        ]
521        .into_iter()
522        .map(RelationKind::Containment)
523        .chain(
524            [
525                ArrangementSubKind::FrameMember,
526                ArrangementSubKind::TileGroup,
527                ArrangementSubKind::SplitPair,
528            ]
529            .into_iter()
530            .map(RelationKind::Arrangement),
531        )
532        .chain(
533            [
534                ImportedSubKind::BookmarkFolder,
535                ImportedSubKind::HistoryImport,
536                ImportedSubKind::SessionImport,
537                ImportedSubKind::RssMembership,
538                ImportedSubKind::FileSystemImport,
539                ImportedSubKind::ArchiveMembership,
540                ImportedSubKind::SharedCollection,
541            ]
542            .into_iter()
543            .map(RelationKind::Imported),
544        )
545        .chain(
546            [
547                ProvenanceSubKind::ClippedFrom,
548                ProvenanceSubKind::ExcerptedFrom,
549                ProvenanceSubKind::SummarizedFrom,
550                ProvenanceSubKind::TranslatedFrom,
551                ProvenanceSubKind::RewrittenFrom,
552                ProvenanceSubKind::GeneratedFrom,
553                ProvenanceSubKind::ExtractedFrom,
554                ProvenanceSubKind::ImportedFromSource,
555                ProvenanceSubKind::CopiedFrom,
556                ProvenanceSubKind::MergedFrom,
557            ]
558            .into_iter()
559            .map(RelationKind::Provenance),
560        )
561        .find(|kind| kind.predicate_iri() == Some(iri))
562    }
563
564    /// Project to the relation's family. Pure function — no payload
565    /// access required.
566    pub fn family(self) -> EdgeFamily {
567        match self {
568            RelationKind::Semantic(_) | RelationKind::OpenPredicate => EdgeFamily::Semantic,
569            RelationKind::Traversal => EdgeFamily::Traversal,
570            RelationKind::Containment(_) => EdgeFamily::Containment,
571            RelationKind::Arrangement(_) => EdgeFamily::Arrangement,
572            RelationKind::Imported(_) => EdgeFamily::Imported,
573            RelationKind::Provenance(_) => EdgeFamily::Provenance,
574        }
575    }
576
577    /// Encode this relation as an opaque `u32` tag for transport
578    /// through layers that can't depend on `kernel` (e.g.
579    /// `graph-canvas::CanvasEdge::tag` / `HitProxy::Edge::tag`).
580    /// The top byte is the family ordinal (0..5); the bottom three
581    /// bytes are the sub-kind ordinal within the family.
582    /// [`OpenPredicate`](Self::OpenPredicate) keeps the Semantic family
583    /// byte and uses the all-ones sub-ordinal
584    /// ([`OPEN_PREDICATE_TAG_SUB`]) as its sentinel, so a consumer that
585    /// reads only the family byte still sees Semantic.
586    /// [`Self::from_tag`] is the inverse.
587    pub fn tag(self) -> u32 {
588        let (family, sub) = match self {
589            RelationKind::Semantic(sk) => (0u32, sk as u32),
590            RelationKind::OpenPredicate => (0, OPEN_PREDICATE_TAG_SUB),
591            RelationKind::Traversal => (1, 0),
592            RelationKind::Containment(sk) => (2, sk as u32),
593            RelationKind::Arrangement(sk) => (3, sk as u32),
594            RelationKind::Imported(sk) => (4, sk as u32),
595            RelationKind::Provenance(sk) => (5, sk as u32),
596        };
597        (family << 24) | (sub & 0x00ff_ffff)
598    }
599
600    /// Decode a `u32` tag produced by [`Self::tag`]. Returns `None`
601    /// for tags that don't correspond to a known relation (unknown
602    /// family byte or sub-kind ordinal out of range).
603    pub fn from_tag(tag: u32) -> Option<Self> {
604        let family = tag >> 24;
605        let sub = tag & 0x00ff_ffff;
606        match family {
607            0 if sub == OPEN_PREDICATE_TAG_SUB => Some(RelationKind::OpenPredicate),
608            0 => SemanticSubKind::from_repr(sub as usize).map(RelationKind::Semantic),
609            1 => (sub == 0).then_some(RelationKind::Traversal),
610            2 => ContainmentSubKind::from_repr(sub as usize).map(RelationKind::Containment),
611            3 => ArrangementSubKind::from_repr(sub as usize).map(RelationKind::Arrangement),
612            4 => ImportedSubKind::from_repr(sub as usize).map(RelationKind::Imported),
613            5 => ProvenanceSubKind::from_repr(sub as usize).map(RelationKind::Provenance),
614            _ => None,
615        }
616    }
617}