Skip to main content

kernel/
types.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Portable leaf types used by the graph model and persistence schema.
5//!
6//! These types are shared between `kernel` modules and must be
7//! WASM-clean: no platform I/O, no UI framework dependencies.
8
9use std::collections::HashMap;
10use std::sync::atomic::{AtomicU64, Ordering};
11
12use rkyv::{Archive, Deserialize, Serialize};
13
14use crate::graph::ProvenanceSubKind;
15
16// ---------------------------------------------------------------------------
17// Frame layout types
18// ---------------------------------------------------------------------------
19
20/// Durable member reference used by frame layout hints.
21///
22/// `NodeKey` is process-local and not stable across restart, so persistent frame
23/// layout metadata uses the member node's stable UUID string instead.
24pub type FrameLayoutNodeId = String;
25
26#[derive(
27    Debug,
28    Clone,
29    Copy,
30    PartialEq,
31    Eq,
32    Archive,
33    Serialize,
34    Deserialize,
35    serde::Serialize,
36    serde::Deserialize,
37)]
38#[rkyv(derive(Debug, PartialEq, Eq))]
39pub enum SplitOrientation {
40    Vertical,
41    Horizontal,
42}
43
44#[derive(
45    Debug,
46    Clone,
47    Copy,
48    PartialEq,
49    Eq,
50    Archive,
51    Serialize,
52    Deserialize,
53    serde::Serialize,
54    serde::Deserialize,
55)]
56#[rkyv(derive(Debug, PartialEq, Eq))]
57pub enum DominantEdge {
58    Left,
59    Right,
60    Top,
61    Bottom,
62}
63
64#[derive(
65    Debug,
66    Clone,
67    PartialEq,
68    Eq,
69    PartialOrd,
70    Ord,
71    Hash,
72    Default,
73    Archive,
74    Serialize,
75    Deserialize,
76    serde::Serialize,
77    serde::Deserialize,
78)]
79#[rkyv(derive(Debug, PartialEq, Eq))]
80pub enum GraphScope {
81    #[default]
82    Default,
83    Source,
84    User,
85    Agent,
86    Moot,
87    Custom(String),
88}
89
90static NEXT_LOCAL_STATEMENT_NONCE: AtomicU64 = AtomicU64::new(1);
91static STATEMENT_MINTER_SALT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
92
93/// Seed the statement-id minter's per-process salt. The kernel's identity
94/// doctrine: OS randomness is native-only, wasm hosts supply theirs — a wasm
95/// host should call this once at boot with 64 host-random bits (unseeded wasm
96/// falls back to `0`, i.e. the pre-salt time+nonce behaviour, and loses the
97/// cross-device guarantee). Native self-seeds from `Uuid::new_v4()` on first
98/// mint; a later seed call is a no-op.
99pub fn seed_statement_minter(salt: u64) {
100    let _ = STATEMENT_MINTER_SALT.set(salt);
101}
102
103fn statement_minter_salt() -> u64 {
104    *STATEMENT_MINTER_SALT.get_or_init(|| {
105        #[cfg(not(target_arch = "wasm32"))]
106        {
107            let bytes = uuid::Uuid::new_v4();
108            u64::from_le_bytes(bytes.as_bytes()[..8].try_into().expect("8 bytes"))
109        }
110        #[cfg(target_arch = "wasm32")]
111        {
112            0
113        }
114    })
115}
116
117/// Mint a [`SemanticStatement`](crate::graph::SemanticStatement) id — the
118/// FEDERATION-SAFE story the petgraph-RDF plan's Phase 1 required (the fact
119/// handle reification, precise retract, snapshot migration, and federation
120/// tombstones point at):
121///
122/// `{unix_ms:012x}-{process_salt:016x}-{counter:016x}`
123///
124/// - Device-safe: two devices collide only on a 64-bit salt collision
125///   (2^-64 per process pair), independent of clocks and counters.
126/// - Time-sortable by prefix (12 hex ms digits reach year ~10889).
127/// - Opaque to consumers: dedup happens on statement CONTENT, never by
128///   parsing this id, so legacy `{ts:016x}-{nonce:016x}` ids already in
129///   snapshots remain valid handles forever.
130pub(crate) fn mint_local_statement_id() -> String {
131    let timestamp_ms = crate::time::unix_epoch_millis();
132    let salt = statement_minter_salt();
133    let nonce = NEXT_LOCAL_STATEMENT_NONCE.fetch_add(1, Ordering::Relaxed);
134    format!("{timestamp_ms:012x}-{salt:016x}-{nonce:016x}")
135}
136
137#[cfg(test)]
138mod minting_tests {
139    use super::*;
140
141    /// The minted id is device-safe in shape: time prefix + a non-zero
142    /// process salt (native self-seeds) + a monotonic counter, all distinct
143    /// across consecutive mints.
144    #[test]
145    fn statement_ids_carry_salt_and_stay_unique() {
146        let a = mint_local_statement_id();
147        let b = mint_local_statement_id();
148        assert_ne!(a, b);
149        let parts: Vec<&str> = a.split('-').collect();
150        assert_eq!(parts.len(), 3, "ts-salt-counter shape: {a}");
151        assert_eq!(parts[0].len(), 12);
152        assert_eq!(parts[1].len(), 16);
153        assert_eq!(parts[2].len(), 16);
154        assert_ne!(parts[1], "0000000000000000", "native salt self-seeds");
155        let b_parts: Vec<&str> = b.split('-').collect();
156        assert_eq!(parts[1], b_parts[1], "salt is per-process stable");
157    }
158}
159
160#[derive(
161    Debug,
162    Clone,
163    PartialEq,
164    Eq,
165    Archive,
166    Serialize,
167    Deserialize,
168    serde::Serialize,
169    serde::Deserialize,
170)]
171#[rkyv(derive(Debug, PartialEq, Eq))]
172pub enum FrameLayoutHint {
173    SplitHalf {
174        first: FrameLayoutNodeId,
175        second: FrameLayoutNodeId,
176        orientation: SplitOrientation,
177    },
178    SplitPamphlet {
179        members: [FrameLayoutNodeId; 3],
180        orientation: SplitOrientation,
181    },
182    SplitTriptych {
183        dominant: FrameLayoutNodeId,
184        dominant_edge: DominantEdge,
185        wings: [FrameLayoutNodeId; 2],
186    },
187    SplitQuartered {
188        top_left: FrameLayoutNodeId,
189        top_right: FrameLayoutNodeId,
190        bottom_left: FrameLayoutNodeId,
191        bottom_right: FrameLayoutNodeId,
192    },
193}
194
195// ---------------------------------------------------------------------------
196// Import provenance types
197// ---------------------------------------------------------------------------
198
199#[derive(
200    Debug,
201    Clone,
202    PartialEq,
203    Eq,
204    PartialOrd,
205    Ord,
206    Archive,
207    Serialize,
208    Deserialize,
209    serde::Serialize,
210    serde::Deserialize,
211)]
212pub struct NodeImportProvenance {
213    pub source_id: String,
214    pub source_label: String,
215}
216
217/// Cross-graph derivation provenance: a record that this node was derived from
218/// a node in another graph (the tear-out "fork" / cross-graph copy).
219///
220/// This is the node-anchored analog of an in-graph `Provenance` edge. A
221/// node→node derivation *within* one graph rides a petgraph `Provenance` edge,
222/// but a cross-graph derivation has its object node in a *different* graph, so
223/// it cannot be a petgraph edge — it is recorded here on the derived node
224/// instead, beside [`NodeImportProvenance`] and `NodeClassification`. It
225/// projects to a `<this> {provenance predicate} <source>` statement when the
226/// RDF projection lands (per the petgraph-rdf projection profile).
227#[derive(
228    Debug,
229    Clone,
230    PartialEq,
231    Eq,
232    Archive,
233    Serialize,
234    Deserialize,
235    serde::Serialize,
236    serde::Deserialize,
237)]
238pub struct NodeDerivation {
239    /// Which provenance relation this is (e.g. [`ProvenanceSubKind::CopiedFrom`]).
240    pub sub_kind: ProvenanceSubKind,
241    /// The source node's stable id, as a string (matches the kernel's
242    /// node-id-as-string convention in persisted records). The object of the
243    /// derivation statement.
244    pub source_node: String,
245    /// The source graph's id (the constellation `GraphId` rendered as a string),
246    /// or `None` when same-graph or unknown — the named-graph scope of the source.
247    pub source_graph: Option<String>,
248}
249
250#[derive(
251    Debug,
252    Clone,
253    PartialEq,
254    Eq,
255    PartialOrd,
256    Ord,
257    Hash,
258    Default,
259    Archive,
260    Serialize,
261    Deserialize,
262    serde::Serialize,
263    serde::Deserialize,
264)]
265pub struct ImportRecordMembership {
266    pub node_id: String,
267    pub suppressed: bool,
268}
269
270#[derive(
271    Debug,
272    Clone,
273    PartialEq,
274    Eq,
275    PartialOrd,
276    Ord,
277    Hash,
278    Default,
279    Archive,
280    Serialize,
281    Deserialize,
282    serde::Serialize,
283    serde::Deserialize,
284)]
285pub struct ImportRecord {
286    pub record_id: String,
287    pub source_id: String,
288    pub source_label: String,
289    pub imported_at_secs: u64,
290    pub memberships: Vec<ImportRecordMembership>,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct NodeImportRecordSummary {
295    pub record_id: String,
296    pub source_id: String,
297    pub source_label: String,
298    pub imported_at_secs: u64,
299}
300
301pub fn format_imported_at_secs(imported_at_secs: u64) -> String {
302    time::OffsetDateTime::from_unix_timestamp(imported_at_secs as i64)
303        .ok()
304        .and_then(|timestamp| {
305            timestamp
306                .format(&time::format_description::well_known::Rfc3339)
307                .ok()
308        })
309        .unwrap_or_else(|| format!("{}s", imported_at_secs))
310}
311
312// ---------------------------------------------------------------------------
313// Node classification — Stage A durable enrichment schema
314// ---------------------------------------------------------------------------
315
316/// Classification scheme identifier.
317#[derive(
318    Debug,
319    Clone,
320    PartialEq,
321    Eq,
322    PartialOrd,
323    Ord,
324    Hash,
325    Default,
326    Archive,
327    Serialize,
328    Deserialize,
329    serde::Serialize,
330    serde::Deserialize,
331)]
332pub enum ClassificationScheme {
333    /// Universal Decimal Classification (primary semantic taxonomy).
334    #[default]
335    Udc,
336    /// Content-kind classification (page, article, repo, …).
337    ContentKind,
338    /// Custom namespaced scheme (e.g. `"myns:custom"`).
339    Custom(String),
340}
341
342/// Origin of a classification or tag.
343#[derive(
344    Debug,
345    Clone,
346    PartialEq,
347    Eq,
348    PartialOrd,
349    Ord,
350    Hash,
351    Default,
352    Archive,
353    Serialize,
354    Deserialize,
355    serde::Serialize,
356    serde::Deserialize,
357)]
358pub enum ClassificationProvenance {
359    /// Explicitly authored by the user.
360    #[default]
361    UserAuthored,
362    /// Imported from an external data source (bookmarks, history, file, …).
363    Imported,
364    /// Inherited from a source/parent node relationship.
365    InheritedFromSource,
366    /// Derived by the knowledge registry (UDC lookup, content analysis, …).
367    RegistryDerived,
368    /// Proposed by an agent/model; not yet accepted by the user.
369    AgentSuggested,
370    /// Synced from the community/Verse network.
371    CommunitySynced,
372}
373
374/// Lifecycle status of a classification record.
375#[derive(
376    Debug,
377    Clone,
378    PartialEq,
379    Eq,
380    PartialOrd,
381    Ord,
382    Hash,
383    Default,
384    Archive,
385    Serialize,
386    Deserialize,
387    serde::Serialize,
388    serde::Deserialize,
389)]
390pub enum ClassificationStatus {
391    /// User has explicitly accepted this classification.
392    Accepted,
393    /// Proposed but not yet reviewed (e.g. agent-suggested).
394    #[default]
395    Suggested,
396    /// User has explicitly rejected this classification.
397    Rejected,
398    /// Verified by an authoritative external source.
399    Verified,
400    /// Imported from an external record without explicit user review.
401    Imported,
402}
403
404/// A single provenance-bearing classification record on a node.
405///
406/// Multiple records can coexist; at most one should have `primary: true` per scheme.
407#[derive(
408    Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
409)]
410pub struct NodeClassification {
411    pub scheme: ClassificationScheme,
412    /// Scheme-specific classification value (e.g. `"udc:519.6"`, `"article"`).
413    pub value: String,
414    /// Human-readable label resolved from the scheme (e.g. `"Computational mathematics"`).
415    pub label: Option<String>,
416    /// Confidence score in `[0.0, 1.0]`; `1.0` for user-authored.
417    pub confidence: f32,
418    pub provenance: ClassificationProvenance,
419    pub status: ClassificationStatus,
420    /// Whether this is the primary presentation classification for its scheme.
421    pub primary: bool,
422}
423
424/// A literal property on a node: an open predicate IRI and its value. Holds the
425/// non-curated literals an ingest preserves — the kernel has no other general
426/// key→value bag (`title` / `tags` stay the curated fast-paths).
427#[derive(
428    Debug,
429    Clone,
430    PartialEq,
431    Eq,
432    Archive,
433    Serialize,
434    Deserialize,
435    serde::Serialize,
436    serde::Deserialize,
437)]
438pub struct NodeProperty {
439    /// Stable handle for this literal statement.
440    #[serde(default = "mint_local_statement_id")]
441    pub statement_id: String,
442    /// The predicate IRI (e.g. `https://schema.org/datePublished`).
443    pub predicate: String,
444    /// The literal value.
445    pub value: String,
446    /// Explicit datatype IRI when the literal is not the default `xsd:string`.
447    #[serde(default)]
448    pub datatype: Option<String>,
449    /// BCP47 language tag for an RDF language-tagged string.
450    #[serde(default)]
451    pub lang: Option<String>,
452    /// Named-graph scope for this literal statement.
453    #[serde(default)]
454    pub graph_scope: GraphScope,
455    /// Optional provenance agent/persona IRI for this assertion.
456    #[serde(default)]
457    pub provenance_iri: Option<String>,
458    /// Optional assertion time in unix epoch milliseconds.
459    #[serde(default)]
460    pub asserted_at_ms: Option<u64>,
461}
462
463impl NodeProperty {
464    pub fn new(predicate: String, value: String) -> Self {
465        Self {
466            statement_id: mint_local_statement_id(),
467            predicate,
468            value,
469            datatype: None,
470            lang: None,
471            graph_scope: GraphScope::Default,
472            provenance_iri: None,
473            asserted_at_ms: None,
474        }
475    }
476
477    pub fn with_graph_scope(mut self, graph_scope: GraphScope) -> Self {
478        self.graph_scope = graph_scope;
479        self
480    }
481
482    pub fn with_metadata(
483        mut self,
484        provenance_iri: Option<String>,
485        asserted_at_ms: Option<u64>,
486    ) -> Self {
487        self.provenance_iri = provenance_iri;
488        self.asserted_at_ms = asserted_at_ms;
489        self
490    }
491
492    pub fn content_eq(&self, other: &Self) -> bool {
493        self.predicate == other.predicate
494            && self.value == other.value
495            && self.datatype == other.datatype
496            && self.lang == other.lang
497            && self.graph_scope == other.graph_scope
498    }
499}
500
501// ---------------------------------------------------------------------------
502// Preview imagery references (node image externalization plan)
503// ---------------------------------------------------------------------------
504
505/// Which preview-image role a reference fills. A node holds at most one image per
506/// role. `Favicon` is the site icon on the node face; `Preview` the default
507/// thumbnail; `Snapshot` the last-rendered peek the preview card shows. The set
508/// is extensible (per-lane snapshots) by adding variants, which is why the node
509/// keys images by role rather than holding fixed fields. `Ord` so it can key a
510/// `BTreeMap` with a deterministic iteration order.
511#[derive(
512    Debug,
513    Clone,
514    Copy,
515    PartialEq,
516    Eq,
517    Hash,
518    PartialOrd,
519    Ord,
520    Archive,
521    Serialize,
522    Deserialize,
523    serde::Serialize,
524    serde::Deserialize,
525)]
526#[rkyv(
527    compare(PartialEq, PartialOrd),
528    derive(Debug, PartialEq, Eq, PartialOrd, Ord)
529)]
530pub enum ImageRole {
531    Favicon,
532    Preview,
533    Snapshot,
534}
535
536/// A content-addressed reference to a preview image held in the durable blob
537/// store (node image externalization plan): the BLAKE3-256 digest of the stored
538/// PNG bytes plus the decoded dimensions. ~40 bytes and no pixels, so a graph of
539/// 50k nodes carries references, not image data. The kernel only *carries* the
540/// handle; `pandect::image_store` computes the digest and owns the blob
541/// under `content/image/<hex>`, which is why the digest is a plain `[u8; 32]`
542/// here (no eidetic dependency in the kernel).
543#[derive(
544    Debug,
545    Clone,
546    Copy,
547    PartialEq,
548    Eq,
549    Hash,
550    Archive,
551    Serialize,
552    Deserialize,
553    serde::Serialize,
554    serde::Deserialize,
555)]
556#[rkyv(derive(Debug, PartialEq, Eq))]
557pub struct ImageRef {
558    /// BLAKE3-256 digest of the stored PNG bytes — the blob key. Rendered as hex
559    /// in JSON snapshots (compact + hand-inspectable); rkyv archives the raw bytes.
560    #[serde(with = "digest_hex")]
561    pub digest: [u8; 32],
562    /// Decoded pixel width.
563    pub width: u32,
564    /// Decoded pixel height.
565    pub height: u32,
566}
567
568impl ImageRef {
569    pub fn new(digest: [u8; 32], width: u32, height: u32) -> Self {
570        Self {
571            digest,
572            width,
573            height,
574        }
575    }
576
577    /// Lowercase hex of the digest — the `content/image/<hex>` blob-key suffix.
578    /// Matches `eidetic::Hash::to_hex` so a ref built from a saved blob's hash
579    /// reads that same blob back.
580    pub fn hex(&self) -> String {
581        use std::fmt::Write;
582        let mut out = String::with_capacity(64);
583        for byte in &self.digest {
584            let _ = write!(out, "{byte:02x}");
585        }
586        out
587    }
588}
589
590/// Serde helpers rendering a 32-byte digest as a hex string in JSON snapshots.
591mod digest_hex {
592    use serde::{Deserialize, Deserializer, Serializer, de::Error};
593
594    pub fn serialize<S: Serializer>(digest: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error> {
595        use std::fmt::Write;
596        let mut hex = String::with_capacity(64);
597        for byte in digest {
598            let _ = write!(hex, "{byte:02x}");
599        }
600        serializer.serialize_str(&hex)
601    }
602
603    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 32], D::Error> {
604        let hex = String::deserialize(deserializer)?;
605        let bytes = hex.as_bytes();
606        if bytes.len() != 64 {
607            return Err(D::Error::invalid_length(bytes.len(), &"64 hex characters"));
608        }
609        let nibble = |b: u8| -> Result<u8, D::Error> {
610            (b as char)
611                .to_digit(16)
612                .map(|d| d as u8)
613                .ok_or_else(|| D::Error::custom("digest is not valid hex"))
614        };
615        let mut out = [0u8; 32];
616        for (i, pair) in bytes.chunks_exact(2).enumerate() {
617            out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
618        }
619        Ok(out)
620    }
621}
622
623// ---------------------------------------------------------------------------
624// Badge / tag presentation types (from badge.rs carve-out)
625// ---------------------------------------------------------------------------
626
627#[derive(
628    Debug,
629    Clone,
630    PartialEq,
631    Eq,
632    Archive,
633    Serialize,
634    Deserialize,
635    serde::Serialize,
636    serde::Deserialize,
637)]
638#[rkyv(derive(Debug, PartialEq, Eq))]
639pub enum BadgeIcon {
640    Emoji(String),
641    Lucide(String),
642    None,
643}
644
645#[derive(
646    Debug,
647    Clone,
648    Default,
649    PartialEq,
650    Eq,
651    Archive,
652    Serialize,
653    Deserialize,
654    serde::Serialize,
655    serde::Deserialize,
656)]
657#[rkyv(derive(Debug, PartialEq, Eq))]
658pub struct NodeTagPresentationState {
659    pub ordered_tags: Vec<String>,
660    pub icon_overrides: HashMap<String, BadgeIcon>,
661}