Skip to main content

kernel/
types.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//! Portable leaf types used by the graph model and persistence schema.
8//!
9//! These types are shared between `kernel` modules and must be
10//! WASM-clean: no platform I/O, no UI framework dependencies.
11
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use rkyv::{Archive, Deserialize, Serialize};
16
17use crate::graph::ProvenanceSubKind;
18
19// ---------------------------------------------------------------------------
20// Frame layout types
21// ---------------------------------------------------------------------------
22
23/// Durable member reference used by frame layout hints.
24///
25/// `NodeKey` is process-local and not stable across restart, so persistent frame
26/// layout metadata uses the member node's stable UUID string instead.
27pub type FrameLayoutNodeId = String;
28
29#[derive(
30    Debug,
31    Clone,
32    Copy,
33    PartialEq,
34    Eq,
35    Archive,
36    Serialize,
37    Deserialize,
38    serde::Serialize,
39    serde::Deserialize,
40)]
41#[rkyv(derive(Debug, PartialEq, Eq))]
42pub enum SplitOrientation {
43    Vertical,
44    Horizontal,
45}
46
47#[derive(
48    Debug,
49    Clone,
50    Copy,
51    PartialEq,
52    Eq,
53    Archive,
54    Serialize,
55    Deserialize,
56    serde::Serialize,
57    serde::Deserialize,
58)]
59#[rkyv(derive(Debug, PartialEq, Eq))]
60pub enum DominantEdge {
61    Left,
62    Right,
63    Top,
64    Bottom,
65}
66
67#[derive(
68    Debug,
69    Clone,
70    PartialEq,
71    Eq,
72    PartialOrd,
73    Ord,
74    Hash,
75    Default,
76    Archive,
77    Serialize,
78    Deserialize,
79    serde::Serialize,
80    serde::Deserialize,
81)]
82#[rkyv(derive(Debug, PartialEq, Eq))]
83pub enum GraphScope {
84    #[default]
85    Default,
86    Source,
87    User,
88    Agent,
89    Moot,
90    Custom(String),
91}
92
93/// Retained record-time tombstone for an assertion withdrawal.
94#[derive(
95    Debug,
96    Clone,
97    PartialEq,
98    Eq,
99    Archive,
100    Serialize,
101    Deserialize,
102    serde::Serialize,
103    serde::Deserialize,
104)]
105#[rkyv(derive(Debug, PartialEq, Eq))]
106pub struct AssertionWithdrawal {
107    /// Informative caller-supplied or authored record time; `None` stays
108    /// undated for legacy/imported withdrawals.
109    pub at_ms: Option<u64>,
110    /// Actor IRI when the source supplies one.
111    pub by: Option<String>,
112}
113
114/// Optional account of why an assertion exists. `occurrences` remain with
115/// traversal sidecars until their P6 convergence phase.
116#[derive(
117    Debug,
118    Clone,
119    PartialEq,
120    Eq,
121    Default,
122    Archive,
123    Serialize,
124    Deserialize,
125    serde::Serialize,
126    serde::Deserialize,
127)]
128#[rkyv(derive(Debug, PartialEq, Eq))]
129pub struct AssertionBasis {
130    /// Compatibility projection of the legacy assertion label.
131    #[serde(default)]
132    pub note: Option<String>,
133    #[serde(default)]
134    pub method: Option<AssertionMethod>,
135    /// Source order is retained; reason-key comparison sorts a copy.
136    #[serde(default)]
137    pub evidence: Vec<String>,
138}
139
140#[derive(
141    Debug,
142    Clone,
143    PartialEq,
144    Eq,
145    Archive,
146    Serialize,
147    Deserialize,
148    serde::Serialize,
149    serde::Deserialize,
150)]
151#[rkyv(derive(Debug, PartialEq, Eq))]
152pub struct AssertionMethod {
153    pub iri: String,
154    #[serde(default)]
155    pub version: Option<String>,
156}
157
158impl AssertionBasis {
159    /// L13 reason identity: method IRI without version plus sorted evidence
160    /// references. A plain explicit claim has the empty key.
161    pub fn same_reason_as(&self, other: &Self) -> bool {
162        if self.method.as_ref().map(|method| method.iri.as_str())
163            != other.method.as_ref().map(|method| method.iri.as_str())
164        {
165            return false;
166        }
167        let mut left = self.evidence.iter().map(String::as_str).collect::<Vec<_>>();
168        let mut right = other
169            .evidence
170            .iter()
171            .map(String::as_str)
172            .collect::<Vec<_>>();
173        left.sort_unstable();
174        right.sort_unstable();
175        left.dedup();
176        right.dedup();
177        left == right
178    }
179
180    pub fn is_empty(&self) -> bool {
181        self.note.is_none() && self.method.is_none() && self.evidence.is_empty()
182    }
183}
184
185static NEXT_LOCAL_STATEMENT_NONCE: AtomicU64 = AtomicU64::new(1);
186static STATEMENT_MINTER_SALT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
187
188/// Seed the statement-id minter's per-process salt. The kernel's identity
189/// doctrine: OS randomness is native-only, wasm hosts supply theirs — a wasm
190/// host should call this once at boot with 64 host-random bits (unseeded wasm
191/// falls back to `0`, i.e. the pre-salt time+nonce behaviour, and loses the
192/// cross-device guarantee). Native self-seeds from `Uuid::new_v4()` on first
193/// mint; a later seed call is a no-op.
194pub fn seed_statement_minter(salt: u64) {
195    let _ = STATEMENT_MINTER_SALT.set(salt);
196}
197
198fn statement_minter_salt() -> u64 {
199    *STATEMENT_MINTER_SALT.get_or_init(|| {
200        #[cfg(not(target_arch = "wasm32"))]
201        {
202            let bytes = uuid::Uuid::new_v4();
203            u64::from_le_bytes(bytes.as_bytes()[..8].try_into().expect("8 bytes"))
204        }
205        #[cfg(target_arch = "wasm32")]
206        {
207            0
208        }
209    })
210}
211
212/// Mint a [`SemanticStatement`](crate::graph::SemanticStatement) id — the
213/// FEDERATION-SAFE story the petgraph-RDF plan's Phase 1 required (the fact
214/// handle reification, precise retract, snapshot migration, and federation
215/// tombstones point at):
216///
217/// `{unix_ms:012x}-{process_salt:016x}-{counter:016x}`
218///
219/// - Device-safe: two devices collide only on a 64-bit salt collision
220///   (2^-64 per process pair), independent of clocks and counters.
221/// - Time-sortable by prefix (12 hex ms digits reach year ~10889).
222/// - Opaque to consumers: dedup happens on statement CONTENT, never by
223///   parsing this id, so legacy `{ts:016x}-{nonce:016x}` ids already in
224///   snapshots remain valid handles forever.
225pub(crate) fn mint_local_statement_id() -> String {
226    let timestamp_ms = crate::time::unix_epoch_millis();
227    let salt = statement_minter_salt();
228    let nonce = NEXT_LOCAL_STATEMENT_NONCE.fetch_add(1, Ordering::Relaxed);
229    format!("{timestamp_ms:012x}-{salt:016x}-{nonce:016x}")
230}
231
232#[cfg(test)]
233mod minting_tests {
234    use super::*;
235
236    /// The minted id is device-safe in shape: time prefix + a non-zero
237    /// process salt (native self-seeds) + a monotonic counter, all distinct
238    /// across consecutive mints.
239    #[test]
240    fn statement_ids_carry_salt_and_stay_unique() {
241        let a = mint_local_statement_id();
242        let b = mint_local_statement_id();
243        assert_ne!(a, b);
244        let parts: Vec<&str> = a.split('-').collect();
245        assert_eq!(parts.len(), 3, "ts-salt-counter shape: {a}");
246        assert_eq!(parts[0].len(), 12);
247        assert_eq!(parts[1].len(), 16);
248        assert_eq!(parts[2].len(), 16);
249        assert_ne!(parts[1], "0000000000000000", "native salt self-seeds");
250        let b_parts: Vec<&str> = b.split('-').collect();
251        assert_eq!(parts[1], b_parts[1], "salt is per-process stable");
252    }
253}
254
255#[derive(
256    Debug,
257    Clone,
258    PartialEq,
259    Eq,
260    Archive,
261    Serialize,
262    Deserialize,
263    serde::Serialize,
264    serde::Deserialize,
265)]
266#[rkyv(derive(Debug, PartialEq, Eq))]
267pub enum FrameLayoutHint {
268    SplitHalf {
269        first: FrameLayoutNodeId,
270        second: FrameLayoutNodeId,
271        orientation: SplitOrientation,
272    },
273    SplitPamphlet {
274        members: [FrameLayoutNodeId; 3],
275        orientation: SplitOrientation,
276    },
277    SplitTriptych {
278        dominant: FrameLayoutNodeId,
279        dominant_edge: DominantEdge,
280        wings: [FrameLayoutNodeId; 2],
281    },
282    SplitQuartered {
283        top_left: FrameLayoutNodeId,
284        top_right: FrameLayoutNodeId,
285        bottom_left: FrameLayoutNodeId,
286        bottom_right: FrameLayoutNodeId,
287    },
288}
289
290// ---------------------------------------------------------------------------
291// Import provenance types
292// ---------------------------------------------------------------------------
293
294#[derive(
295    Debug,
296    Clone,
297    PartialEq,
298    Eq,
299    PartialOrd,
300    Ord,
301    Archive,
302    Serialize,
303    Deserialize,
304    serde::Serialize,
305    serde::Deserialize,
306)]
307pub struct NodeImportProvenance {
308    pub source_id: String,
309    pub source_label: String,
310}
311
312/// Cross-graph derivation provenance: a record that this node was derived from
313/// a node in another graph (the tear-out "fork" / cross-graph copy).
314///
315/// This is the node-anchored analog of an in-graph `Provenance` edge. A
316/// node→node derivation *within* one graph rides a petgraph `Provenance` edge,
317/// but a cross-graph derivation has its object node in a *different* graph, so
318/// it cannot be a petgraph edge — it is recorded here on the derived node
319/// instead, beside [`NodeImportProvenance`] and `NodeClassification`. It
320/// projects to a `<this> {provenance predicate} <source>` statement when the
321/// RDF projection lands (per the petgraph-rdf projection profile).
322#[derive(
323    Debug,
324    Clone,
325    PartialEq,
326    Eq,
327    Archive,
328    Serialize,
329    Deserialize,
330    serde::Serialize,
331    serde::Deserialize,
332)]
333pub struct NodeDerivation {
334    /// Which provenance relation this is (e.g. [`ProvenanceSubKind::CopiedFrom`]).
335    pub sub_kind: ProvenanceSubKind,
336    /// The source node's stable id, as a string (matches the kernel's
337    /// node-id-as-string convention in persisted records). The object of the
338    /// derivation statement.
339    pub source_node: String,
340    /// The source graph's id (the constellation `GraphId` rendered as a string),
341    /// or `None` when same-graph or unknown — the named-graph scope of the source.
342    pub source_graph: Option<String>,
343}
344
345#[derive(
346    Debug,
347    Clone,
348    PartialEq,
349    Eq,
350    PartialOrd,
351    Ord,
352    Hash,
353    Default,
354    Archive,
355    Serialize,
356    Deserialize,
357    serde::Serialize,
358    serde::Deserialize,
359)]
360pub struct ImportRecordMembership {
361    pub node_id: String,
362    pub suppressed: bool,
363}
364
365#[derive(
366    Debug,
367    Clone,
368    PartialEq,
369    Eq,
370    PartialOrd,
371    Ord,
372    Hash,
373    Default,
374    Archive,
375    Serialize,
376    Deserialize,
377    serde::Serialize,
378    serde::Deserialize,
379)]
380pub struct ImportRecord {
381    pub record_id: String,
382    pub source_id: String,
383    pub source_label: String,
384    pub imported_at_secs: u64,
385    pub memberships: Vec<ImportRecordMembership>,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq)]
389pub struct NodeImportRecordSummary {
390    pub record_id: String,
391    pub source_id: String,
392    pub source_label: String,
393    pub imported_at_secs: u64,
394}
395
396pub fn format_imported_at_secs(imported_at_secs: u64) -> String {
397    time::OffsetDateTime::from_unix_timestamp(imported_at_secs as i64)
398        .ok()
399        .and_then(|timestamp| {
400            timestamp
401                .format(&time::format_description::well_known::Rfc3339)
402                .ok()
403        })
404        .unwrap_or_else(|| format!("{}s", imported_at_secs))
405}
406
407// ---------------------------------------------------------------------------
408// Node classification — Stage A durable enrichment schema
409// ---------------------------------------------------------------------------
410
411/// Classification scheme identifier.
412#[derive(
413    Debug,
414    Clone,
415    PartialEq,
416    Eq,
417    PartialOrd,
418    Ord,
419    Hash,
420    Default,
421    Archive,
422    Serialize,
423    Deserialize,
424    serde::Serialize,
425    serde::Deserialize,
426)]
427pub enum ClassificationScheme {
428    /// Universal Decimal Classification (primary semantic taxonomy).
429    #[default]
430    Udc,
431    /// Content-kind classification (page, article, repo, …).
432    ContentKind,
433    /// Custom namespaced scheme (e.g. `"myns:custom"`).
434    Custom(String),
435}
436
437/// Origin of a classification or tag.
438#[derive(
439    Debug,
440    Clone,
441    PartialEq,
442    Eq,
443    PartialOrd,
444    Ord,
445    Hash,
446    Default,
447    Archive,
448    Serialize,
449    Deserialize,
450    serde::Serialize,
451    serde::Deserialize,
452)]
453pub enum ClassificationProvenance {
454    /// Explicitly authored by the user.
455    #[default]
456    UserAuthored,
457    /// Imported from an external data source (bookmarks, history, file, …).
458    Imported,
459    /// Inherited from a source/parent node relationship.
460    InheritedFromSource,
461    /// Derived by the knowledge registry (UDC lookup, content analysis, …).
462    RegistryDerived,
463    /// Proposed by an agent/model; not yet accepted by the user.
464    AgentSuggested,
465    /// Synced from the community/Verse network.
466    CommunitySynced,
467}
468
469/// Lifecycle status of a classification record.
470#[derive(
471    Debug,
472    Clone,
473    PartialEq,
474    Eq,
475    PartialOrd,
476    Ord,
477    Hash,
478    Default,
479    Archive,
480    Serialize,
481    Deserialize,
482    serde::Serialize,
483    serde::Deserialize,
484)]
485pub enum ClassificationStatus {
486    /// User has explicitly accepted this classification.
487    Accepted,
488    /// Proposed but not yet reviewed (e.g. agent-suggested).
489    #[default]
490    Suggested,
491    /// User has explicitly rejected this classification.
492    Rejected,
493    /// Verified by an authoritative external source.
494    Verified,
495    /// Imported from an external record without explicit user review.
496    Imported,
497}
498
499impl ClassificationStatus {
500    /// Classifications used by ordinary selection, display and affirmative export.
501    pub fn is_affirmative(&self) -> bool {
502        matches!(self, Self::Accepted | Self::Verified | Self::Imported)
503    }
504}
505
506/// A single provenance-bearing classification record on a node.
507///
508/// Multiple records can coexist; at most one should have `primary: true` per scheme.
509#[derive(
510    Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
511)]
512pub struct NodeClassification {
513    pub scheme: ClassificationScheme,
514    /// Scheme-specific classification value (e.g. `"udc:519.6"`, `"article"`).
515    pub value: String,
516    /// Human-readable label resolved from the scheme (e.g. `"Computational mathematics"`).
517    pub label: Option<String>,
518    /// Confidence score in `[0.0, 1.0]`; `1.0` for user-authored.
519    pub confidence: f32,
520    pub provenance: ClassificationProvenance,
521    pub status: ClassificationStatus,
522    /// Whether this is the primary presentation classification for its scheme.
523    pub primary: bool,
524}
525
526/// A literal property on a node: an open predicate IRI and its value. Holds the
527/// non-curated literals an ingest preserves — the kernel has no other general
528/// key→value bag (`title` / `tags` stay the curated fast-paths).
529#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, serde::Deserialize)]
530pub struct NodeProperty {
531    /// Stable handle for this literal statement.
532    #[serde(default = "mint_local_statement_id")]
533    pub statement_id: String,
534    /// The predicate IRI (e.g. `https://schema.org/datePublished`).
535    pub predicate: String,
536    /// The literal value.
537    pub value: String,
538    /// Explicit datatype IRI when the literal is not the default `xsd:string`.
539    #[serde(default)]
540    pub datatype: Option<String>,
541    /// BCP47 language tag for an RDF language-tagged string.
542    #[serde(default)]
543    pub lang: Option<String>,
544    /// Named-graph scope for this literal statement.
545    #[serde(default)]
546    pub graph_scope: GraphScope,
547    /// Optional provenance agent/persona IRI for this assertion.
548    #[serde(default)]
549    pub provenance_iri: Option<String>,
550    /// Optional assertion time in unix epoch milliseconds.
551    #[serde(default)]
552    pub asserted_at_ms: Option<u64>,
553}
554
555impl serde::Serialize for NodeProperty {
556    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
557        use serde::ser::SerializeStruct;
558
559        let human = serializer.is_human_readable();
560        let scoped = self.graph_scope != GraphScope::Default;
561        let fields = if human {
562            3 + usize::from(self.datatype.is_some())
563                + usize::from(self.lang.is_some())
564                + usize::from(scoped)
565                + usize::from(self.provenance_iri.is_some())
566                + usize::from(self.asserted_at_ms.is_some())
567        } else {
568            8
569        };
570        // Positional codecs keep the complete legacy field order.
571        let mut state = serializer.serialize_struct("NodeProperty", fields)?;
572        state.serialize_field("statement_id", &self.statement_id)?;
573        state.serialize_field("predicate", &self.predicate)?;
574        state.serialize_field("value", &self.value)?;
575        if !human || self.datatype.is_some() {
576            state.serialize_field("datatype", &self.datatype)?;
577        }
578        if !human || self.lang.is_some() {
579            state.serialize_field("lang", &self.lang)?;
580        }
581        if !human || scoped {
582            state.serialize_field("graph_scope", &self.graph_scope)?;
583        }
584        if !human || self.provenance_iri.is_some() {
585            state.serialize_field("provenance_iri", &self.provenance_iri)?;
586        }
587        if !human || self.asserted_at_ms.is_some() {
588            state.serialize_field("asserted_at_ms", &self.asserted_at_ms)?;
589        }
590        state.end()
591    }
592}
593
594impl NodeProperty {
595    pub fn new(predicate: String, value: String) -> Self {
596        Self {
597            statement_id: mint_local_statement_id(),
598            predicate,
599            value,
600            datatype: None,
601            lang: None,
602            graph_scope: GraphScope::Default,
603            provenance_iri: None,
604            asserted_at_ms: None,
605        }
606    }
607
608    pub fn with_graph_scope(mut self, graph_scope: GraphScope) -> Self {
609        self.graph_scope = graph_scope;
610        self
611    }
612
613    pub fn with_metadata(
614        mut self,
615        provenance_iri: Option<String>,
616        asserted_at_ms: Option<u64>,
617    ) -> Self {
618        self.provenance_iri = provenance_iri;
619        self.asserted_at_ms = asserted_at_ms;
620        self
621    }
622
623    pub fn content_eq(&self, other: &Self) -> bool {
624        self.predicate == other.predicate
625            && self.value == other.value
626            && self.datatype == other.datatype
627            && self.lang == other.lang
628            && self.graph_scope == other.graph_scope
629            && self.provenance_iri == other.provenance_iri
630    }
631}
632
633// ---------------------------------------------------------------------------
634// Preview imagery references (node image externalization plan)
635// ---------------------------------------------------------------------------
636
637/// Which preview-image role a reference fills. A node holds at most one image per
638/// role. `Favicon` is the site icon on the node face; `Preview` the default
639/// thumbnail; `Snapshot` the last-rendered peek the preview card shows. The set
640/// is extensible (per-lane snapshots) by adding variants, which is why the node
641/// keys images by role rather than holding fixed fields. `Ord` so it can key a
642/// `BTreeMap` with a deterministic iteration order.
643#[derive(
644    Debug,
645    Clone,
646    Copy,
647    PartialEq,
648    Eq,
649    Hash,
650    PartialOrd,
651    Ord,
652    Archive,
653    Serialize,
654    Deserialize,
655    serde::Serialize,
656    serde::Deserialize,
657)]
658#[rkyv(
659    compare(PartialEq, PartialOrd),
660    derive(Debug, PartialEq, Eq, PartialOrd, Ord)
661)]
662pub enum ImageRole {
663    Favicon,
664    Preview,
665    Snapshot,
666}
667
668/// A content-addressed reference to a preview image held in the durable blob
669/// store (node image externalization plan): the BLAKE3-256 digest of the stored
670/// PNG bytes plus the decoded dimensions. ~40 bytes and no pixels, so a graph of
671/// 50k nodes carries references, not image data. The kernel only *carries* the
672/// handle; `pandect::image_store` computes the digest and owns the blob
673/// under `content/image/<hex>`, which is why the digest is a plain `[u8; 32]`
674/// here (no eidetic dependency in the kernel).
675#[derive(
676    Debug,
677    Clone,
678    Copy,
679    PartialEq,
680    Eq,
681    Hash,
682    Archive,
683    Serialize,
684    Deserialize,
685    serde::Serialize,
686    serde::Deserialize,
687)]
688#[rkyv(derive(Debug, PartialEq, Eq))]
689pub struct ImageRef {
690    /// BLAKE3-256 digest of the stored PNG bytes — the blob key. Rendered as hex
691    /// in JSON snapshots (compact + hand-inspectable); rkyv archives the raw bytes.
692    #[serde(with = "digest_hex")]
693    pub digest: [u8; 32],
694    /// Decoded pixel width.
695    pub width: u32,
696    /// Decoded pixel height.
697    pub height: u32,
698}
699
700impl ImageRef {
701    pub fn new(digest: [u8; 32], width: u32, height: u32) -> Self {
702        Self {
703            digest,
704            width,
705            height,
706        }
707    }
708
709    /// Lowercase hex of the digest — the `content/image/<hex>` blob-key suffix.
710    /// Matches `eidetic::Hash::to_hex` so a ref built from a saved blob's hash
711    /// reads that same blob back.
712    pub fn hex(&self) -> String {
713        use std::fmt::Write;
714        let mut out = String::with_capacity(64);
715        for byte in &self.digest {
716            let _ = write!(out, "{byte:02x}");
717        }
718        out
719    }
720}
721
722/// Serde helpers rendering a 32-byte digest as a hex string in JSON snapshots.
723mod digest_hex {
724    use serde::{Deserialize, Deserializer, Serializer, de::Error};
725
726    pub fn serialize<S: Serializer>(digest: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error> {
727        use std::fmt::Write;
728        let mut hex = String::with_capacity(64);
729        for byte in digest {
730            let _ = write!(hex, "{byte:02x}");
731        }
732        serializer.serialize_str(&hex)
733    }
734
735    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 32], D::Error> {
736        let hex = String::deserialize(deserializer)?;
737        let bytes = hex.as_bytes();
738        if bytes.len() != 64 {
739            return Err(D::Error::invalid_length(bytes.len(), &"64 hex characters"));
740        }
741        let nibble = |b: u8| -> Result<u8, D::Error> {
742            (b as char)
743                .to_digit(16)
744                .map(|d| d as u8)
745                .ok_or_else(|| D::Error::custom("digest is not valid hex"))
746        };
747        let mut out = [0u8; 32];
748        for (i, pair) in bytes.chunks_exact(2).enumerate() {
749            out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
750        }
751        Ok(out)
752    }
753}
754
755// ---------------------------------------------------------------------------
756// Badge / tag presentation types (from badge.rs carve-out)
757// ---------------------------------------------------------------------------
758
759#[derive(
760    Debug,
761    Clone,
762    PartialEq,
763    Eq,
764    Archive,
765    Serialize,
766    Deserialize,
767    serde::Serialize,
768    serde::Deserialize,
769)]
770#[rkyv(derive(Debug, PartialEq, Eq))]
771pub enum BadgeIcon {
772    Emoji(String),
773    Lucide(String),
774    None,
775}
776
777#[derive(
778    Debug,
779    Clone,
780    Default,
781    PartialEq,
782    Eq,
783    Archive,
784    Serialize,
785    Deserialize,
786    serde::Serialize,
787    serde::Deserialize,
788)]
789#[rkyv(derive(Debug, PartialEq, Eq))]
790pub struct NodeTagPresentationState {
791    pub ordered_tags: Vec<String>,
792    pub icon_overrides: HashMap<String, BadgeIcon>,
793}
794
795#[cfg(test)]
796mod property_serialization_tests {
797    use super::*;
798
799    fn cases() -> Vec<NodeProperty> {
800        let mut plain = NodeProperty::new("urn:predicate:value".into(), "held value".into());
801        plain.statement_id = "held\nproperty".into();
802        plain.provenance_iri = Some("https://author.test/".into());
803        let mut legacy = plain.clone();
804        legacy.provenance_iri = None;
805        let mut marker = plain.clone();
806        marker.provenance_iri = Some(crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into());
807        let mut rich = plain.clone();
808        rich.statement_id = String::new();
809        rich.datatype = Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString".into());
810        rich.lang = Some("fr".into());
811        rich.graph_scope = GraphScope::Custom("urn:graph:held".into());
812        rich.provenance_iri = Some(String::new());
813        rich.asserted_at_ms = Some(0);
814        let mut explicit = plain.clone();
815        explicit.datatype = Some("http://www.w3.org/2001/XMLSchema#string".into());
816        explicit.lang = Some(String::new());
817        vec![plain, legacy, marker, rich, explicit]
818    }
819
820    #[test]
821    fn property_json_omits_absent_metadata_and_preserves_explicit_values() {
822        let cases = cases();
823        let plain = serde_json::to_value(&cases[0]).unwrap();
824        assert_eq!(plain.as_object().unwrap().len(), 4);
825        assert_eq!(plain["statement_id"], "held\nproperty");
826        assert_eq!(plain["provenance_iri"], "https://author.test/");
827        for absent in ["datatype", "lang", "graph_scope", "asserted_at_ms"] {
828            assert!(plain.get(absent).is_none());
829        }
830        let legacy = serde_json::to_value(&cases[1]).unwrap();
831        assert!(legacy.get("provenance_iri").is_none());
832        let decoded: NodeProperty = serde_json::from_value(legacy).unwrap();
833        assert_eq!(decoded, cases[1], "missing metadata keeps legacy defaults");
834        let marker = serde_json::to_value(&cases[2]).unwrap();
835        assert_eq!(
836            marker["provenance_iri"],
837            crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI
838        );
839        let rich = serde_json::to_value(&cases[3]).unwrap();
840        assert_eq!(rich.as_object().unwrap().len(), 8);
841        assert_eq!(rich["statement_id"], "");
842        assert_eq!(rich["provenance_iri"], "");
843        assert_eq!(rich["asserted_at_ms"], 0);
844        assert_eq!(rich["lang"], "fr");
845        let explicit = serde_json::to_value(&cases[4]).unwrap();
846        assert_eq!(
847            explicit["datatype"],
848            "http://www.w3.org/2001/XMLSchema#string"
849        );
850        assert_eq!(explicit["lang"], "");
851        for value in cases {
852            let bytes = serde_json::to_vec(&value).unwrap();
853            assert_eq!(
854                serde_json::from_slice::<NodeProperty>(&bytes).unwrap(),
855                value
856            );
857        }
858    }
859
860    #[test]
861    fn property_binary_bytes_match_the_complete_legacy_shape() {
862        #[derive(serde::Serialize)]
863        struct Complete<'a> {
864            statement_id: &'a String,
865            predicate: &'a String,
866            value: &'a String,
867            datatype: &'a Option<String>,
868            lang: &'a Option<String>,
869            graph_scope: &'a GraphScope,
870            provenance_iri: &'a Option<String>,
871            asserted_at_ms: &'a Option<u64>,
872        }
873        for value in cases() {
874            let old = Complete {
875                statement_id: &value.statement_id,
876                predicate: &value.predicate,
877                value: &value.value,
878                datatype: &value.datatype,
879                lang: &value.lang,
880                graph_scope: &value.graph_scope,
881                provenance_iri: &value.provenance_iri,
882                asserted_at_ms: &value.asserted_at_ms,
883            };
884            let bytes = postcard::to_allocvec(&value).unwrap();
885            assert_eq!(bytes, postcard::to_allocvec(&old).unwrap());
886            assert_eq!(postcard::from_bytes::<NodeProperty>(&bytes).unwrap(), value);
887            let archive = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
888            assert_eq!(
889                rkyv::from_bytes::<NodeProperty, rkyv::rancor::Error>(&archive).unwrap(),
890                value
891            );
892        }
893    }
894}