mere-kernel 0.0.3

Portable identity, authority, and mutation kernel for the Mere browser. Renamed from graphshell-core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
// Copyright 2026 Mark Alan Boykin
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// SPDX-License-Identifier: MPL-2.0

//! Portable leaf types used by the graph model and persistence schema.
//!
//! These types are shared between `kernel` modules and must be
//! WASM-clean: no platform I/O, no UI framework dependencies.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

use rkyv::{Archive, Deserialize, Serialize};

use crate::graph::ProvenanceSubKind;

// ---------------------------------------------------------------------------
// Frame layout types
// ---------------------------------------------------------------------------

/// Durable member reference used by frame layout hints.
///
/// `NodeKey` is process-local and not stable across restart, so persistent frame
/// layout metadata uses the member node's stable UUID string instead.
pub type FrameLayoutNodeId = String;

#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum SplitOrientation {
    Vertical,
    Horizontal,
}

#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum DominantEdge {
    Left,
    Right,
    Top,
    Bottom,
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum GraphScope {
    #[default]
    Default,
    Source,
    User,
    Agent,
    Moot,
    Custom(String),
}

/// Retained record-time tombstone for an assertion withdrawal.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub struct AssertionWithdrawal {
    /// Informative caller-supplied or authored record time; `None` stays
    /// undated for legacy/imported withdrawals.
    pub at_ms: Option<u64>,
    /// Actor IRI when the source supplies one.
    pub by: Option<String>,
}

/// Optional account of why an assertion exists. `occurrences` remain with
/// traversal sidecars until their P6 convergence phase.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub struct AssertionBasis {
    /// Compatibility projection of the legacy assertion label.
    #[serde(default)]
    pub note: Option<String>,
    #[serde(default)]
    pub method: Option<AssertionMethod>,
    /// Source order is retained; reason-key comparison sorts a copy.
    #[serde(default)]
    pub evidence: Vec<String>,
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub struct AssertionMethod {
    pub iri: String,
    #[serde(default)]
    pub version: Option<String>,
}

impl AssertionBasis {
    /// L13 reason identity: method IRI without version plus sorted evidence
    /// references. A plain explicit claim has the empty key.
    pub fn same_reason_as(&self, other: &Self) -> bool {
        if self.method.as_ref().map(|method| method.iri.as_str())
            != other.method.as_ref().map(|method| method.iri.as_str())
        {
            return false;
        }
        let mut left = self.evidence.iter().map(String::as_str).collect::<Vec<_>>();
        let mut right = other
            .evidence
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>();
        left.sort_unstable();
        right.sort_unstable();
        left.dedup();
        right.dedup();
        left == right
    }

    pub fn is_empty(&self) -> bool {
        self.note.is_none() && self.method.is_none() && self.evidence.is_empty()
    }
}

static NEXT_LOCAL_STATEMENT_NONCE: AtomicU64 = AtomicU64::new(1);
static STATEMENT_MINTER_SALT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();

/// Seed the statement-id minter's per-process salt. The kernel's identity
/// doctrine: OS randomness is native-only, wasm hosts supply theirs — a wasm
/// host should call this once at boot with 64 host-random bits (unseeded wasm
/// falls back to `0`, i.e. the pre-salt time+nonce behaviour, and loses the
/// cross-device guarantee). Native self-seeds from `Uuid::new_v4()` on first
/// mint; a later seed call is a no-op.
pub fn seed_statement_minter(salt: u64) {
    let _ = STATEMENT_MINTER_SALT.set(salt);
}

fn statement_minter_salt() -> u64 {
    *STATEMENT_MINTER_SALT.get_or_init(|| {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let bytes = uuid::Uuid::new_v4();
            u64::from_le_bytes(bytes.as_bytes()[..8].try_into().expect("8 bytes"))
        }
        #[cfg(target_arch = "wasm32")]
        {
            0
        }
    })
}

/// Mint a [`SemanticStatement`](crate::graph::SemanticStatement) id — the
/// FEDERATION-SAFE story the petgraph-RDF plan's Phase 1 required (the fact
/// handle reification, precise retract, snapshot migration, and federation
/// tombstones point at):
///
/// `{unix_ms:012x}-{process_salt:016x}-{counter:016x}`
///
/// - Device-safe: two devices collide only on a 64-bit salt collision
///   (2^-64 per process pair), independent of clocks and counters.
/// - Time-sortable by prefix (12 hex ms digits reach year ~10889).
/// - Opaque to consumers: dedup happens on statement CONTENT, never by
///   parsing this id, so legacy `{ts:016x}-{nonce:016x}` ids already in
///   snapshots remain valid handles forever.
pub(crate) fn mint_local_statement_id() -> String {
    let timestamp_ms = crate::time::unix_epoch_millis();
    let salt = statement_minter_salt();
    let nonce = NEXT_LOCAL_STATEMENT_NONCE.fetch_add(1, Ordering::Relaxed);
    format!("{timestamp_ms:012x}-{salt:016x}-{nonce:016x}")
}

#[cfg(test)]
mod minting_tests {
    use super::*;

    /// The minted id is device-safe in shape: time prefix + a non-zero
    /// process salt (native self-seeds) + a monotonic counter, all distinct
    /// across consecutive mints.
    #[test]
    fn statement_ids_carry_salt_and_stay_unique() {
        let a = mint_local_statement_id();
        let b = mint_local_statement_id();
        assert_ne!(a, b);
        let parts: Vec<&str> = a.split('-').collect();
        assert_eq!(parts.len(), 3, "ts-salt-counter shape: {a}");
        assert_eq!(parts[0].len(), 12);
        assert_eq!(parts[1].len(), 16);
        assert_eq!(parts[2].len(), 16);
        assert_ne!(parts[1], "0000000000000000", "native salt self-seeds");
        let b_parts: Vec<&str> = b.split('-').collect();
        assert_eq!(parts[1], b_parts[1], "salt is per-process stable");
    }
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum FrameLayoutHint {
    SplitHalf {
        first: FrameLayoutNodeId,
        second: FrameLayoutNodeId,
        orientation: SplitOrientation,
    },
    SplitPamphlet {
        members: [FrameLayoutNodeId; 3],
        orientation: SplitOrientation,
    },
    SplitTriptych {
        dominant: FrameLayoutNodeId,
        dominant_edge: DominantEdge,
        wings: [FrameLayoutNodeId; 2],
    },
    SplitQuartered {
        top_left: FrameLayoutNodeId,
        top_right: FrameLayoutNodeId,
        bottom_left: FrameLayoutNodeId,
        bottom_right: FrameLayoutNodeId,
    },
}

// ---------------------------------------------------------------------------
// Import provenance types
// ---------------------------------------------------------------------------

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct NodeImportProvenance {
    pub source_id: String,
    pub source_label: String,
}

/// Cross-graph derivation provenance: a record that this node was derived from
/// a node in another graph (the tear-out "fork" / cross-graph copy).
///
/// This is the node-anchored analog of an in-graph `Provenance` edge. A
/// node→node derivation *within* one graph rides a petgraph `Provenance` edge,
/// but a cross-graph derivation has its object node in a *different* graph, so
/// it cannot be a petgraph edge — it is recorded here on the derived node
/// instead, beside [`NodeImportProvenance`] and `NodeClassification`. It
/// projects to a `<this> {provenance predicate} <source>` statement when the
/// RDF projection lands (per the petgraph-rdf projection profile).
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct NodeDerivation {
    /// Which provenance relation this is (e.g. [`ProvenanceSubKind::CopiedFrom`]).
    pub sub_kind: ProvenanceSubKind,
    /// The source node's stable id, as a string (matches the kernel's
    /// node-id-as-string convention in persisted records). The object of the
    /// derivation statement.
    pub source_node: String,
    /// The source graph's id (the constellation `GraphId` rendered as a string),
    /// or `None` when same-graph or unknown — the named-graph scope of the source.
    pub source_graph: Option<String>,
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct ImportRecordMembership {
    pub node_id: String,
    pub suppressed: bool,
}

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct ImportRecord {
    pub record_id: String,
    pub source_id: String,
    pub source_label: String,
    pub imported_at_secs: u64,
    pub memberships: Vec<ImportRecordMembership>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeImportRecordSummary {
    pub record_id: String,
    pub source_id: String,
    pub source_label: String,
    pub imported_at_secs: u64,
}

pub fn format_imported_at_secs(imported_at_secs: u64) -> String {
    time::OffsetDateTime::from_unix_timestamp(imported_at_secs as i64)
        .ok()
        .and_then(|timestamp| {
            timestamp
                .format(&time::format_description::well_known::Rfc3339)
                .ok()
        })
        .unwrap_or_else(|| format!("{}s", imported_at_secs))
}

// ---------------------------------------------------------------------------
// Node classification — Stage A durable enrichment schema
// ---------------------------------------------------------------------------

/// Classification scheme identifier.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub enum ClassificationScheme {
    /// Universal Decimal Classification (primary semantic taxonomy).
    #[default]
    Udc,
    /// Content-kind classification (page, article, repo, …).
    ContentKind,
    /// Custom namespaced scheme (e.g. `"myns:custom"`).
    Custom(String),
}

/// Origin of a classification or tag.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub enum ClassificationProvenance {
    /// Explicitly authored by the user.
    #[default]
    UserAuthored,
    /// Imported from an external data source (bookmarks, history, file, …).
    Imported,
    /// Inherited from a source/parent node relationship.
    InheritedFromSource,
    /// Derived by the knowledge registry (UDC lookup, content analysis, …).
    RegistryDerived,
    /// Proposed by an agent/model; not yet accepted by the user.
    AgentSuggested,
    /// Synced from the community/Verse network.
    CommunitySynced,
}

/// Lifecycle status of a classification record.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
pub enum ClassificationStatus {
    /// User has explicitly accepted this classification.
    Accepted,
    /// Proposed but not yet reviewed (e.g. agent-suggested).
    #[default]
    Suggested,
    /// User has explicitly rejected this classification.
    Rejected,
    /// Verified by an authoritative external source.
    Verified,
    /// Imported from an external record without explicit user review.
    Imported,
}

impl ClassificationStatus {
    /// Classifications used by ordinary selection, display and affirmative export.
    pub fn is_affirmative(&self) -> bool {
        matches!(self, Self::Accepted | Self::Verified | Self::Imported)
    }
}

/// A single provenance-bearing classification record on a node.
///
/// Multiple records can coexist; at most one should have `primary: true` per scheme.
#[derive(
    Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
)]
pub struct NodeClassification {
    pub scheme: ClassificationScheme,
    /// Scheme-specific classification value (e.g. `"udc:519.6"`, `"article"`).
    pub value: String,
    /// Human-readable label resolved from the scheme (e.g. `"Computational mathematics"`).
    pub label: Option<String>,
    /// Confidence score in `[0.0, 1.0]`; `1.0` for user-authored.
    pub confidence: f32,
    pub provenance: ClassificationProvenance,
    pub status: ClassificationStatus,
    /// Whether this is the primary presentation classification for its scheme.
    pub primary: bool,
}

/// A literal property on a node: an open predicate IRI and its value. Holds the
/// non-curated literals an ingest preserves — the kernel has no other general
/// key→value bag (`title` / `tags` stay the curated fast-paths).
#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, serde::Deserialize)]
pub struct NodeProperty {
    /// Stable handle for this literal statement.
    #[serde(default = "mint_local_statement_id")]
    pub statement_id: String,
    /// The predicate IRI (e.g. `https://schema.org/datePublished`).
    pub predicate: String,
    /// The literal value.
    pub value: String,
    /// Explicit datatype IRI when the literal is not the default `xsd:string`.
    #[serde(default)]
    pub datatype: Option<String>,
    /// BCP47 language tag for an RDF language-tagged string.
    #[serde(default)]
    pub lang: Option<String>,
    /// Named-graph scope for this literal statement.
    #[serde(default)]
    pub graph_scope: GraphScope,
    /// Optional provenance agent/persona IRI for this assertion.
    #[serde(default)]
    pub provenance_iri: Option<String>,
    /// Optional assertion time in unix epoch milliseconds.
    #[serde(default)]
    pub asserted_at_ms: Option<u64>,
}

impl serde::Serialize for NodeProperty {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;

        let human = serializer.is_human_readable();
        let scoped = self.graph_scope != GraphScope::Default;
        let fields = if human {
            3 + usize::from(self.datatype.is_some())
                + usize::from(self.lang.is_some())
                + usize::from(scoped)
                + usize::from(self.provenance_iri.is_some())
                + usize::from(self.asserted_at_ms.is_some())
        } else {
            8
        };
        // Positional codecs keep the complete legacy field order.
        let mut state = serializer.serialize_struct("NodeProperty", fields)?;
        state.serialize_field("statement_id", &self.statement_id)?;
        state.serialize_field("predicate", &self.predicate)?;
        state.serialize_field("value", &self.value)?;
        if !human || self.datatype.is_some() {
            state.serialize_field("datatype", &self.datatype)?;
        }
        if !human || self.lang.is_some() {
            state.serialize_field("lang", &self.lang)?;
        }
        if !human || scoped {
            state.serialize_field("graph_scope", &self.graph_scope)?;
        }
        if !human || self.provenance_iri.is_some() {
            state.serialize_field("provenance_iri", &self.provenance_iri)?;
        }
        if !human || self.asserted_at_ms.is_some() {
            state.serialize_field("asserted_at_ms", &self.asserted_at_ms)?;
        }
        state.end()
    }
}

impl NodeProperty {
    pub fn new(predicate: String, value: String) -> Self {
        Self {
            statement_id: mint_local_statement_id(),
            predicate,
            value,
            datatype: None,
            lang: None,
            graph_scope: GraphScope::Default,
            provenance_iri: None,
            asserted_at_ms: None,
        }
    }

    pub fn with_graph_scope(mut self, graph_scope: GraphScope) -> Self {
        self.graph_scope = graph_scope;
        self
    }

    pub fn with_metadata(
        mut self,
        provenance_iri: Option<String>,
        asserted_at_ms: Option<u64>,
    ) -> Self {
        self.provenance_iri = provenance_iri;
        self.asserted_at_ms = asserted_at_ms;
        self
    }

    pub fn content_eq(&self, other: &Self) -> bool {
        self.predicate == other.predicate
            && self.value == other.value
            && self.datatype == other.datatype
            && self.lang == other.lang
            && self.graph_scope == other.graph_scope
            && self.provenance_iri == other.provenance_iri
    }
}

// ---------------------------------------------------------------------------
// Preview imagery references (node image externalization plan)
// ---------------------------------------------------------------------------

/// Which preview-image role a reference fills. A node holds at most one image per
/// role. `Favicon` is the site icon on the node face; `Preview` the default
/// thumbnail; `Snapshot` the last-rendered peek the preview card shows. The set
/// is extensible (per-lane snapshots) by adding variants, which is why the node
/// keys images by role rather than holding fixed fields. `Ord` so it can key a
/// `BTreeMap` with a deterministic iteration order.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    PartialOrd,
    Ord,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(
    compare(PartialEq, PartialOrd),
    derive(Debug, PartialEq, Eq, PartialOrd, Ord)
)]
pub enum ImageRole {
    Favicon,
    Preview,
    Snapshot,
}

/// A content-addressed reference to a preview image held in the durable blob
/// store (node image externalization plan): the BLAKE3-256 digest of the stored
/// PNG bytes plus the decoded dimensions. ~40 bytes and no pixels, so a graph of
/// 50k nodes carries references, not image data. The kernel only *carries* the
/// handle; `pandect::image_store` computes the digest and owns the blob
/// under `content/image/<hex>`, which is why the digest is a plain `[u8; 32]`
/// here (no eidetic dependency in the kernel).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub struct ImageRef {
    /// BLAKE3-256 digest of the stored PNG bytes — the blob key. Rendered as hex
    /// in JSON snapshots (compact + hand-inspectable); rkyv archives the raw bytes.
    #[serde(with = "digest_hex")]
    pub digest: [u8; 32],
    /// Decoded pixel width.
    pub width: u32,
    /// Decoded pixel height.
    pub height: u32,
}

impl ImageRef {
    pub fn new(digest: [u8; 32], width: u32, height: u32) -> Self {
        Self {
            digest,
            width,
            height,
        }
    }

    /// Lowercase hex of the digest — the `content/image/<hex>` blob-key suffix.
    /// Matches `eidetic::Hash::to_hex` so a ref built from a saved blob's hash
    /// reads that same blob back.
    pub fn hex(&self) -> String {
        use std::fmt::Write;
        let mut out = String::with_capacity(64);
        for byte in &self.digest {
            let _ = write!(out, "{byte:02x}");
        }
        out
    }
}

/// Serde helpers rendering a 32-byte digest as a hex string in JSON snapshots.
mod digest_hex {
    use serde::{Deserialize, Deserializer, Serializer, de::Error};

    pub fn serialize<S: Serializer>(digest: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error> {
        use std::fmt::Write;
        let mut hex = String::with_capacity(64);
        for byte in digest {
            let _ = write!(hex, "{byte:02x}");
        }
        serializer.serialize_str(&hex)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 32], D::Error> {
        let hex = String::deserialize(deserializer)?;
        let bytes = hex.as_bytes();
        if bytes.len() != 64 {
            return Err(D::Error::invalid_length(bytes.len(), &"64 hex characters"));
        }
        let nibble = |b: u8| -> Result<u8, D::Error> {
            (b as char)
                .to_digit(16)
                .map(|d| d as u8)
                .ok_or_else(|| D::Error::custom("digest is not valid hex"))
        };
        let mut out = [0u8; 32];
        for (i, pair) in bytes.chunks_exact(2).enumerate() {
            out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
        }
        Ok(out)
    }
}

// ---------------------------------------------------------------------------
// Badge / tag presentation types (from badge.rs carve-out)
// ---------------------------------------------------------------------------

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum BadgeIcon {
    Emoji(String),
    Lucide(String),
    None,
}

#[derive(
    Debug,
    Clone,
    Default,
    PartialEq,
    Eq,
    Archive,
    Serialize,
    Deserialize,
    serde::Serialize,
    serde::Deserialize,
)]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub struct NodeTagPresentationState {
    pub ordered_tags: Vec<String>,
    pub icon_overrides: HashMap<String, BadgeIcon>,
}

#[cfg(test)]
mod property_serialization_tests {
    use super::*;

    fn cases() -> Vec<NodeProperty> {
        let mut plain = NodeProperty::new("urn:predicate:value".into(), "held value".into());
        plain.statement_id = "held\nproperty".into();
        plain.provenance_iri = Some("https://author.test/".into());
        let mut legacy = plain.clone();
        legacy.provenance_iri = None;
        let mut marker = plain.clone();
        marker.provenance_iri = Some(crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into());
        let mut rich = plain.clone();
        rich.statement_id = String::new();
        rich.datatype = Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString".into());
        rich.lang = Some("fr".into());
        rich.graph_scope = GraphScope::Custom("urn:graph:held".into());
        rich.provenance_iri = Some(String::new());
        rich.asserted_at_ms = Some(0);
        let mut explicit = plain.clone();
        explicit.datatype = Some("http://www.w3.org/2001/XMLSchema#string".into());
        explicit.lang = Some(String::new());
        vec![plain, legacy, marker, rich, explicit]
    }

    #[test]
    fn property_json_omits_absent_metadata_and_preserves_explicit_values() {
        let cases = cases();
        let plain = serde_json::to_value(&cases[0]).unwrap();
        assert_eq!(plain.as_object().unwrap().len(), 4);
        assert_eq!(plain["statement_id"], "held\nproperty");
        assert_eq!(plain["provenance_iri"], "https://author.test/");
        for absent in ["datatype", "lang", "graph_scope", "asserted_at_ms"] {
            assert!(plain.get(absent).is_none());
        }
        let legacy = serde_json::to_value(&cases[1]).unwrap();
        assert!(legacy.get("provenance_iri").is_none());
        let decoded: NodeProperty = serde_json::from_value(legacy).unwrap();
        assert_eq!(decoded, cases[1], "missing metadata keeps legacy defaults");
        let marker = serde_json::to_value(&cases[2]).unwrap();
        assert_eq!(
            marker["provenance_iri"],
            crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI
        );
        let rich = serde_json::to_value(&cases[3]).unwrap();
        assert_eq!(rich.as_object().unwrap().len(), 8);
        assert_eq!(rich["statement_id"], "");
        assert_eq!(rich["provenance_iri"], "");
        assert_eq!(rich["asserted_at_ms"], 0);
        assert_eq!(rich["lang"], "fr");
        let explicit = serde_json::to_value(&cases[4]).unwrap();
        assert_eq!(
            explicit["datatype"],
            "http://www.w3.org/2001/XMLSchema#string"
        );
        assert_eq!(explicit["lang"], "");
        for value in cases {
            let bytes = serde_json::to_vec(&value).unwrap();
            assert_eq!(
                serde_json::from_slice::<NodeProperty>(&bytes).unwrap(),
                value
            );
        }
    }

    #[test]
    fn property_binary_bytes_match_the_complete_legacy_shape() {
        #[derive(serde::Serialize)]
        struct Complete<'a> {
            statement_id: &'a String,
            predicate: &'a String,
            value: &'a String,
            datatype: &'a Option<String>,
            lang: &'a Option<String>,
            graph_scope: &'a GraphScope,
            provenance_iri: &'a Option<String>,
            asserted_at_ms: &'a Option<u64>,
        }
        for value in cases() {
            let old = Complete {
                statement_id: &value.statement_id,
                predicate: &value.predicate,
                value: &value.value,
                datatype: &value.datatype,
                lang: &value.lang,
                graph_scope: &value.graph_scope,
                provenance_iri: &value.provenance_iri,
                asserted_at_ms: &value.asserted_at_ms,
            };
            let bytes = postcard::to_allocvec(&value).unwrap();
            assert_eq!(bytes, postcard::to_allocvec(&old).unwrap());
            assert_eq!(postcard::from_bytes::<NodeProperty>(&bytes).unwrap(), value);
            let archive = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
            assert_eq!(
                rkyv::from_bytes::<NodeProperty, rkyv::rancor::Error>(&archive).unwrap(),
                value
            );
        }
    }
}