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
// 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

//! `Graph::from_snapshot` — reconstruct the runtime graph from a
//! persisted [`GraphSnapshot`].
//!
//! Extracted from `graph/snapshot.rs` per the 2026-05-11 kernel
//! decomposition pass.

use euclid::default::Point2D;
use std::collections::BTreeMap;
use uuid::Uuid;

use super::super::import_records::import_records_from_legacy_provenance;
use super::super::*;
use crate::address::{address_from_url, detect_mime};
use crate::persistence::{
    GraphSnapshot, PersistedArrangementSubKind, PersistedContainmentSubKind,
    PersistedCouplingResponse, PersistedEdge, PersistedFieldExtent, PersistedFieldLifecycle,
    PersistedImportedSubKind, PersistedNavigationTrigger, PersistedNodeSelector,
    PersistedProvenanceSubKind, PersistedSemanticSubKind,
};

fn semantic_sub_kind(sub_kind: PersistedSemanticSubKind) -> SemanticSubKind {
    match sub_kind {
        PersistedSemanticSubKind::Hyperlink => SemanticSubKind::Hyperlink,
        PersistedSemanticSubKind::UserGrouped => SemanticSubKind::UserGrouped,
        PersistedSemanticSubKind::AgentDerived => SemanticSubKind::AgentDerived,
        PersistedSemanticSubKind::Cites => SemanticSubKind::Cites,
        PersistedSemanticSubKind::Quotes => SemanticSubKind::Quotes,
        PersistedSemanticSubKind::Summarizes => SemanticSubKind::Summarizes,
        PersistedSemanticSubKind::Elaborates => SemanticSubKind::Elaborates,
        PersistedSemanticSubKind::ExampleOf => SemanticSubKind::ExampleOf,
        PersistedSemanticSubKind::Supports => SemanticSubKind::Supports,
        PersistedSemanticSubKind::Contradicts => SemanticSubKind::Contradicts,
        PersistedSemanticSubKind::Questions => SemanticSubKind::Questions,
        PersistedSemanticSubKind::SameEntityAs => SemanticSubKind::SameEntityAs,
        PersistedSemanticSubKind::DuplicateOf => SemanticSubKind::DuplicateOf,
        PersistedSemanticSubKind::CanonicalMirrorOf => SemanticSubKind::CanonicalMirrorOf,
        PersistedSemanticSubKind::DependsOn => SemanticSubKind::DependsOn,
        PersistedSemanticSubKind::Blocks => SemanticSubKind::Blocks,
        PersistedSemanticSubKind::NextStep => SemanticSubKind::NextStep,
    }
}

impl Graph {
    /// Load a snapshot, stopping on invalid explicit resource data or
    /// navigation indices. Fallible load boundaries should use
    /// [`Self::try_from_snapshot`].
    pub fn from_snapshot(snapshot: &GraphSnapshot) -> Self {
        Self::try_from_snapshot(snapshot)
            .unwrap_or_else(|error| panic!("invalid graph snapshot: {error}"))
    }

    pub(super) fn from_snapshot_unchecked(snapshot: &GraphSnapshot) -> Self {
        Self::materialize_snapshot(snapshot, true)
    }

    pub(super) fn from_recorded_snapshot_unchecked(snapshot: &GraphSnapshot) -> Self {
        Self::materialize_snapshot(snapshot, false)
    }

    fn materialize_snapshot(snapshot: &GraphSnapshot, legacy_derived_containment: bool) -> Self {
        let mut graph = Graph::new();
        // Restore the shared navigation history (one visit space, owner per node)
        // before the node loop, so each node's restored current page reads from it.
        graph.nav = snapshot.navigation.clone();

        // Checked load has already refused an unparseable or repeated Surface id.
        for pnode in &snapshot.nodes {
            let Ok(node_id) = Uuid::parse_str(&pnode.node_id) else {
                continue;
            };
            // Prefer the typed address field (Stage C.2+); fall back to the legacy
            // `url` string field for snapshots written before Stage C.2.
            let node_url = {
                let from_address = pnode.address.as_url_str();
                if from_address.is_empty() {
                    pnode.url.clone()
                } else {
                    from_address.to_string()
                }
            };
            // Positions are no longer graph truth; they live in the cartography
            // sidecar (the Cartography projection's geometry). Seed at the origin and
            // let the sidecar override on load. (Position gut.)
            let (key, inserted) =
                graph.insert_node_if_missing(node_id, node_url, Point2D::new(0.0, 0.0));
            if !inserted {
                continue;
            }
            if let Some(node) = graph.inner.node_mut(key) {
                if node.title != pnode.title {
                    graph.content_revision = graph.content_revision.wrapping_add(1);
                }
                node.title = pnode.title.clone();
                node.tags = pnode.tags.iter().cloned().collect();
                // References only. Legacy inline bytes are externalized by the
                // host before conversion (`pandect::image_store::
                // migrate_legacy_images`), because hashing and blob storage
                // are the store's job, not the kernel's. A snapshot that still
                // carries them here has skipped that pass — see
                // `GraphSnapshot::legacy_image_count`.
                node.images = pnode.images.clone();
                node.media_type = pnode.mime_hint.clone();
                // address was already set by add_node_with_id from pnode.url; no re-derivation needed.
                node.body = pnode.body.clone();
                node.nested = pnode.nested.clone().map(muniment::LogId::new);
                node.content = pnode
                    .content_hash
                    .as_deref()
                    .and_then(muniment::Hash::from_hex);
                if node.content.is_some() {
                    node.body = None;
                }
            }
            // One-time legacy-column import. Canonical saves put these records
            // in `facets.json`; the old graph fields are written empty.
            graph.set_node_facet(
                key,
                super::super::node_facets::PRESENTATION_TAGS,
                &pnode.tag_presentation,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::PROVENANCE_IMPORT,
                &pnode.import_provenance,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::SEMANTIC_CLASSIFICATIONS,
                &pnode.classifications,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::SEMANTIC_PROPERTIES,
                &pnode.properties,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::PROVENANCE_DERIVATIONS,
                &pnode.derivations,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::ARRANGEMENT_PIN,
                &pnode.is_pinned,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::ARRANGEMENT_FRAME_LAYOUT,
                &pnode.frame_layout_hints,
            );
            graph.set_node_facet(
                key,
                super::super::node_facets::ARRANGEMENT_SPLIT_OFFER_SUPPRESSED,
                &pnode.frame_split_offer_suppressed,
            );
            let last_visited_ms = pnode
                .session_state
                .as_ref()
                .and_then(|session| session.last_visited_ms);
            if let Some(last_visited_ms) = last_visited_ms {
                graph.set_node_facet(
                    key,
                    super::super::node_facets::VISIT_HISTORY,
                    &super::super::node_facets::VisitHistoryFacet {
                        last_visited_ms: Some(last_visited_ms),
                        last_session_visited: pnode.last_session_visited,
                    },
                );
            } else if pnode.last_session_visited != 0 {
                // Old snapshots could carry a session ordinal without an
                // explicit visit timestamp. Preserve the creation-time visit
                // installed by `add_node_with_id` while importing that ordinal.
                graph.set_node_last_session_visited(key, pnode.last_session_visited);
            }
            // The saved node address is the owner of the current address. The
            // navigation cursor is only a history position and never rewrites it
            // (SetNodeUrl changes the address without a visit).
        }

        let mut surface_pair_ordinals = BTreeMap::new();
        for pedge in &snapshot.edges {
            let from_id = Uuid::parse_str(&pedge.from_node_id).ok();
            let to_id = Uuid::parse_str(&pedge.to_node_id).ok();
            let from_key = from_id.and_then(|id| graph.get_node_key_by_id(id));
            let to_key = to_id.and_then(|id| graph.get_node_key_by_id(id));
            if let (Some(from), Some(to), Some(from_id), Some(to_id)) =
                (from_key, to_key, from_id, to_id)
            {
                // Legacy assertion identities are scoped to their ordered
                // endpoint pair and bucket position. Replay uses this same
                // pair-local ordinal in `set_edges_between`; an unrelated
                // earlier pair must not change the synthesized identity.
                let ordinal = surface_pair_ordinals.entry((from_id, to_id)).or_insert(0);
                let pair_ordinal = *ordinal;
                *ordinal += 1;
                let mut payload =
                    payload_from_persisted_at(pedge, GraphStratum::Surface, pair_ordinal);
                if legacy_derived_containment
                    && snapshot.assertion_schema == 0
                    && pedge.assertions.is_none()
                {
                    mark_legacy_containment_sidecars_as_derived(&mut payload, pedge);
                }
                for statement in &mut payload.assertions.statements {
                    statement.normalize_legacy_asserter();
                }
                if !payload.is_empty() || pedge.semantic.is_some() || pedge.traversal.is_some() {
                    graph.inner.connect(from, to, payload);
                    graph.bump_revision();
                }
            }
        }

        for record in &snapshot.resources {
            let id = chartulary::resource_id_from_canonical_iri(&record.canonical_iri);
            graph.set_resource_record(id, Some(record.clone()));
        }
        let mut resource_pairs: BTreeMap<(Uuid, Uuid), Vec<PersistedEdge>> = BTreeMap::new();
        for edge in &snapshot.resource_edges {
            let (Ok(from), Ok(to)) = (
                Uuid::parse_str(&edge.from_node_id),
                Uuid::parse_str(&edge.to_node_id),
            ) else {
                continue;
            };
            let mut edge = edge.clone();
            if let Some(semantic) = &mut edge.semantic {
                for statement in &mut semantic.statements {
                    statement
                        .provenance_iri
                        .get_or_insert_with(|| edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.to_owned());
                }
            }
            resource_pairs.entry((from, to)).or_default().push(edge);
        }
        for ((from, to), edges) in resource_pairs {
            graph.set_resource_edges_between(from, to, &edges);
        }
        for shown in &snapshot.shown_resources {
            if let (Ok(surface), Ok(resource)) = (
                Uuid::parse_str(&shown.surface_id),
                Uuid::parse_str(&shown.resource_id),
            ) {
                graph.set_shown_resource(surface, Some(resource));
            }
        }

        // Field layer (field-system Phase 2). Malformed ids / definitions skip the
        // entry rather than failing the whole load, matching the node/edge loops.
        for pfield in &snapshot.fields {
            let Ok(id) = Uuid::parse_str(&pfield.id) else {
                continue;
            };
            let Ok(definition) = serde_json::from_str::<FieldDefinition>(&pfield.definition_json)
            else {
                continue;
            };
            let extent = match &pfield.extent {
                PersistedFieldExtent::Global => FieldExtent::Global,
                PersistedFieldExtent::Region {
                    min_x,
                    min_y,
                    max_x,
                    max_y,
                } => FieldExtent::Region {
                    min_x: *min_x,
                    min_y: *min_y,
                    max_x: *max_x,
                    max_y: *max_y,
                },
                PersistedFieldExtent::AttachedToNode(s) => match Uuid::parse_str(s) {
                    Ok(node_id) => FieldExtent::AttachedToNode(node_id),
                    Err(_) => FieldExtent::Global,
                },
                PersistedFieldExtent::Polygon { points } => FieldExtent::Polygon {
                    points: points.clone(),
                },
            };
            let mut field = Field::new(FieldId::from_uuid(id), definition).with_extent(extent);
            if let Some(name) = &pfield.name {
                field = field.with_name(name.clone());
            }
            field.lifecycle = match pfield.lifecycle {
                PersistedFieldLifecycle::Active => FieldLifecycle::Active,
                PersistedFieldLifecycle::Retired => FieldLifecycle::Retired,
            };
            graph.add_field(field);
        }

        for pcoupling in &snapshot.couplings {
            let Ok(cid) = Uuid::parse_str(&pcoupling.id) else {
                continue;
            };
            let Ok(fid) = Uuid::parse_str(&pcoupling.field_id) else {
                continue;
            };
            let selector = match &pcoupling.selector {
                PersistedNodeSelector::All => NodeSelector::All,
                PersistedNodeSelector::Tagged(t) => NodeSelector::Tagged(t.clone()),
                PersistedNodeSelector::Kind(k) => NodeSelector::Kind(k.clone()),
                PersistedNodeSelector::NotTagged(t) => NodeSelector::NotTagged(t.clone()),
            };
            let response = match &pcoupling.response {
                PersistedCouplingResponse::AttractToMin => CouplingResponse::AttractToMin,
                PersistedCouplingResponse::RepelFromMax => CouplingResponse::RepelFromMax,
                PersistedCouplingResponse::AlignVelocity => CouplingResponse::AlignVelocity,
                PersistedCouplingResponse::FlowAdvect => CouplingResponse::FlowAdvect,
                PersistedCouplingResponse::DampenInside { factor } => {
                    CouplingResponse::DampenInside { factor: *factor }
                },
                PersistedCouplingResponse::ContainmentWall => CouplingResponse::ContainmentWall,
                PersistedCouplingResponse::Open { predicate } => CouplingResponse::Open {
                    predicate: predicate.clone(),
                },
            };
            graph.add_coupling(Coupling::new(
                CouplingId::from_uuid(cid),
                FieldId::from_uuid(fid),
                selector,
                response,
                pcoupling.strength,
            ));
        }

        graph.import_records = if snapshot.import_records.is_empty() {
            // Predates the table: the legacy per-node column is the only source.
            import_records_from_legacy_provenance(
                snapshot.nodes.iter().filter_map(|pnode| {
                    let node_id = Uuid::parse_str(&pnode.node_id).ok()?;
                    Some((node_id, pnode.import_provenance.as_slice()))
                }),
                snapshot.timestamp_secs,
            )
        } else {
            snapshot.import_records.clone()
        };
        normalize_import_records(&mut graph.import_records);
        graph.sync_node_import_provenance_from_records();

        if legacy_derived_containment {
            graph.rebuild_derived_containment_relations();
        }

        graph
    }
}

/// Before canonical assertion records existed, Surface UrlPath and Domain
/// sidecars were compatibility projections of current URLs, not authored
/// claims. Mark just those legacy Surface rows so the ordinary session loader
/// can replace them from current source data without treating canonical or
/// unknown Resource assertions as rule output.
fn mark_legacy_containment_sidecars_as_derived(payload: &mut EdgePayload, edge: &PersistedEdge) {
    let Some(containment) = &edge.containment else {
        return;
    };
    let has_derived_sidecar = containment.sub_kinds.iter().any(|kind| {
        matches!(
            kind,
            PersistedContainmentSubKind::UrlPath | PersistedContainmentSubKind::Domain
        )
    });
    if !has_derived_sidecar {
        return;
    }
    for statement in &mut payload.assertions.statements {
        if statement.provenance_iri.as_deref() != Some(edge_data::UNKNOWN_LEGACY_ASSERTER_IRI)
            || statement.basis.method.is_some()
            || !matches!(
                statement.relation_kind(),
                RelationKind::Containment(ContainmentSubKind::UrlPath | ContainmentSubKind::Domain)
            )
        {
            continue;
        }
        statement.basis.method = Some(crate::types::AssertionMethod {
            iri: "urn:mere:method:derived-containment".into(),
            version: Some("1".into()),
        });
    }
    payload.assertions.rebuild_compat();
}

impl Graph {
    /// Merge one persisted edge into a surface pair, retaining revision behavior.
    pub(crate) fn restore_persisted_edge(
        &mut self,
        from: NodeKey,
        to: NodeKey,
        pedge: &PersistedEdge,
    ) {
        let existing = self.find_edge_key(from, to);
        let mut payload = existing
            .and_then(|key| self.inner.edge(key))
            .cloned()
            .unwrap_or_else(EdgePayload::new);
        let structural_changes = restore_persisted_payload(&mut payload, pedge);
        if pedge.semantic.is_some() || pedge.traversal.is_some() || !payload.is_empty() {
            match existing {
                Some(key) => *self.inner.edge_mut(key).expect("existing edge") = payload,
                None => {
                    self.inner.connect(from, to, payload);
                },
            }
        }
        for _ in 0..structural_changes {
            self.bump_revision();
        }
    }
}

/// Decode a standalone pair without changing carried assertion metadata.
pub(crate) fn payload_from_persisted(pedge: &PersistedEdge) -> EdgePayload {
    payload_from_persisted_at(pedge, GraphStratum::Surface, 0)
}

pub(crate) fn payload_from_persisted_at(
    pedge: &PersistedEdge,
    stratum: GraphStratum,
    ordinal: usize,
) -> EdgePayload {
    let mut payload = EdgePayload::new();
    restore_payload_at(&mut payload, pedge, stratum, ordinal);
    payload
}

/// Merge persisted sidecars; report structural insertions for surface revisions.
pub(crate) fn restore_persisted_payload(payload: &mut EdgePayload, pedge: &PersistedEdge) -> usize {
    restore_payload_at(payload, pedge, GraphStratum::Surface, 0)
}

fn restore_payload_at(
    payload: &mut EdgePayload,
    pedge: &PersistedEdge,
    stratum: GraphStratum,
    ordinal: usize,
) -> usize {
    let mut structural_changes = 0;
    if let Some(records) = &pedge.assertions {
        let mut ids: std::collections::BTreeSet<_> = payload
            .assertions()
            .iter()
            .map(|s| s.statement_id.clone())
            .collect();
        for record in records {
            if ids.insert(record.statement_id.clone()) {
                let mut record = runtime_assertion(record);
                record.normalize_basis_compat();
                payload.assertions.statements.push(record);
                structural_changes += 1;
            }
        }
    }
    let preserved_ids: std::collections::BTreeSet<_> = payload
        .assertions()
        .iter()
        .map(|s| s.statement_id.clone())
        .chain(
            pedge
                .semantic
                .as_ref()
                .into_iter()
                .flat_map(|data| &data.statements)
                .map(|s| s.statement_id.clone()),
        )
        .collect();
    // Canonical records are authoritative. Checked load refuses a nonempty
    // legacy sidecar alongside them instead of inventing a merge precedence.
    if pedge.assertions.is_none() {
        if let Some(semantic) = &pedge.semantic {
            if !semantic.statements.is_empty() {
                for statement in &semantic.statements {
                    let _ = payload.push_persisted_semantic_statement(SemanticStatement {
                        statement_id: statement.statement_id.clone(),
                        predicate: statement.predicate.clone(),
                        recognized_sub_kind: statement.recognized_sub_kind.map(semantic_sub_kind),
                        label: statement.label.clone(),
                        basis: statement.basis.clone(),
                        graph_scope: statement.graph_scope.clone(),
                        provenance_iri: statement.provenance_iri.clone(),
                        first_asserted_ms: statement.first_asserted_ms,
                        asserted_at_ms: statement.asserted_at_ms,
                        withdrawn: statement.withdrawn.clone(),
                    });
                }
            } else {
                for sub_kind in &semantic.sub_kinds {
                    payload.assert_semantic_statement(SemanticStatementSpec {
                        predicate: predicate_iri(semantic_sub_kind(sub_kind.clone())).into(),
                        recognized_sub_kind: Some(semantic_sub_kind(sub_kind.clone())),
                        label: semantic.label.clone(),
                        graph_scope: crate::types::GraphScope::Default,
                        provenance_iri: Some(edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into()),
                        asserted_at_ms: None,
                        basis: Default::default(),
                    });
                }
                if semantic.predicate.is_some() {
                    payload.set_semantic_predicate(semantic.predicate.clone());
                }
            }
        }
        if let Some(arrangement) = &pedge.arrangement {
            for sub_kind in &arrangement.sub_kinds {
                let assertion = match sub_kind {
                    PersistedArrangementSubKind::FrameMember => EdgeAssertion::Arrangement {
                        sub_kind: ArrangementSubKind::FrameMember,
                    },
                    PersistedArrangementSubKind::TileGroup => EdgeAssertion::Arrangement {
                        sub_kind: ArrangementSubKind::TileGroup,
                    },
                    PersistedArrangementSubKind::SplitPair => EdgeAssertion::Arrangement {
                        sub_kind: ArrangementSubKind::SplitPair,
                    },
                    PersistedArrangementSubKind::TabNeighbor
                    | PersistedArrangementSubKind::ActiveTab
                    | PersistedArrangementSubKind::PinnedInFrame => continue,
                };
                structural_changes += usize::from(payload.assert_relation(assertion));
            }
        }
        if let Some(containment) = &pedge.containment {
            for sub_kind in &containment.sub_kinds {
                // Every persisted sub-kind is restored. `UrlPath` and
                // `Domain` are re-derived below by
                // `rebuild_derived_containment_relations`, but the
                // authored ones exist only here: dropping any of them
                // loses user data. Matched exhaustively so a new
                // variant is a compile error rather than a silent
                // omission.
                let sub_kind = match sub_kind {
                    PersistedContainmentSubKind::UrlPath => ContainmentSubKind::UrlPath,
                    PersistedContainmentSubKind::Domain => ContainmentSubKind::Domain,
                    PersistedContainmentSubKind::FileSystem => ContainmentSubKind::FileSystem,
                    PersistedContainmentSubKind::UserFolder => ContainmentSubKind::UserFolder,
                    PersistedContainmentSubKind::ClipSource => ContainmentSubKind::ClipSource,
                    PersistedContainmentSubKind::NotebookSection => {
                        ContainmentSubKind::NotebookSection
                    },
                    PersistedContainmentSubKind::CollectionMember => {
                        ContainmentSubKind::CollectionMember
                    },
                };
                structural_changes +=
                    usize::from(payload.assert_relation(EdgeAssertion::Containment { sub_kind }));
            }
        }
        if let Some(imported) = &pedge.imported {
            for sub_kind in &imported.sub_kinds {
                let assertion = match sub_kind {
                    PersistedImportedSubKind::BookmarkFolder => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::BookmarkFolder,
                    },
                    PersistedImportedSubKind::HistoryImport => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::HistoryImport,
                    },
                    PersistedImportedSubKind::SessionImport => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::SessionImport,
                    },
                    PersistedImportedSubKind::RssMembership => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::RssMembership,
                    },
                    PersistedImportedSubKind::FileSystemImport => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::FileSystemImport,
                    },
                    PersistedImportedSubKind::ArchiveMembership => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::ArchiveMembership,
                    },
                    PersistedImportedSubKind::SharedCollection => EdgeAssertion::Imported {
                        sub_kind: ImportedSubKind::SharedCollection,
                    },
                };
                structural_changes += usize::from(payload.assert_relation(assertion));
            }
        }
        if let Some(provenance) = &pedge.provenance {
            for sub_kind in &provenance.sub_kinds {
                let assertion = match sub_kind {
                    PersistedProvenanceSubKind::ClippedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::ClippedFrom,
                    },
                    PersistedProvenanceSubKind::ExcerptedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::ExcerptedFrom,
                    },
                    PersistedProvenanceSubKind::SummarizedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::SummarizedFrom,
                    },
                    PersistedProvenanceSubKind::TranslatedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::TranslatedFrom,
                    },
                    PersistedProvenanceSubKind::RewrittenFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::RewrittenFrom,
                    },
                    PersistedProvenanceSubKind::GeneratedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::GeneratedFrom,
                    },
                    PersistedProvenanceSubKind::ExtractedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::ExtractedFrom,
                    },
                    PersistedProvenanceSubKind::ImportedFromSource => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::ImportedFromSource,
                    },
                    PersistedProvenanceSubKind::CopiedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::CopiedFrom,
                    },
                    PersistedProvenanceSubKind::MergedFrom => EdgeAssertion::Provenance {
                        sub_kind: ProvenanceSubKind::MergedFrom,
                    },
                };
                structural_changes += usize::from(payload.assert_relation(assertion));
            }
        }
    }
    for statement in &mut payload.assertions.statements {
        if !preserved_ids.contains(&statement.statement_id) {
            statement.statement_id =
                legacy_assertion_id(pedge, stratum, ordinal, &statement.predicate);
            statement.normalize_legacy_asserter();
        }
    }
    payload.assertions.rebuild_compat();
    if let Some(traversal) = &pedge.traversal {
        let data = payload.traversal.get_or_insert_with(TraversalData::default);
        data.traversals = traversal
            .traversals
            .iter()
            .map(|record| Traversal {
                timestamp_ms: record.timestamp_ms,
                trigger: match record.trigger {
                    PersistedNavigationTrigger::Unknown => NavigationTrigger::Unknown,
                    PersistedNavigationTrigger::LinkClick => NavigationTrigger::LinkClick,
                    PersistedNavigationTrigger::Back => NavigationTrigger::Back,
                    PersistedNavigationTrigger::Forward => NavigationTrigger::Forward,
                    PersistedNavigationTrigger::AddressBarEntry => {
                        NavigationTrigger::AddressBarEntry
                    },
                    PersistedNavigationTrigger::PanePromotion => NavigationTrigger::PanePromotion,
                    PersistedNavigationTrigger::Programmatic => NavigationTrigger::Programmatic,
                    PersistedNavigationTrigger::Redirect => NavigationTrigger::Redirect,
                    PersistedNavigationTrigger::ReopenSession => NavigationTrigger::ReopenSession,
                    PersistedNavigationTrigger::JumpAnchor => NavigationTrigger::JumpAnchor,
                    PersistedNavigationTrigger::InPageSearchJump => {
                        NavigationTrigger::InPageSearchJump
                    },
                    PersistedNavigationTrigger::ImportedHistory => {
                        NavigationTrigger::ImportedHistory
                    },
                },
            })
            .collect();
        data.metrics = EdgeMetrics {
            total_navigations: traversal.metrics.total_navigations,
            forward_navigations: traversal.metrics.forward_navigations,
            backward_navigations: traversal.metrics.backward_navigations,
            last_navigated_at: traversal.metrics.last_navigated_at,
        };
    }
    structural_changes
}

/// Stable one-time legacy identity: UTF-8 JSON array of version/domain,
/// stratum, original directed endpoint strings, bucket ordinal and predicate;
/// RFC 9562 UUIDv5 in the URL namespace. No clock or platform hash enters it.
fn legacy_assertion_id(
    edge: &PersistedEdge,
    stratum: GraphStratum,
    ordinal: usize,
    predicate: &str,
) -> String {
    let bytes = serde_json::to_vec(&(
        "mere.legacy-relation-assertion",
        1u8,
        match stratum {
            GraphStratum::Surface => "surface",
            GraphStratum::Resource => "resource",
        },
        &edge.from_node_id,
        &edge.to_node_id,
        ordinal,
        predicate,
    ))
    .expect("string tuple JSON");
    format!(
        "urn:mere:legacy-assertion:v1:{}",
        Uuid::new_v5(&Uuid::NAMESPACE_URL, &bytes)
    )
}

fn runtime_assertion(
    statement: &crate::persistence::PersistedSemanticStatement,
) -> SemanticStatement {
    SemanticStatement {
        statement_id: statement.statement_id.clone(),
        predicate: statement.predicate.clone(),
        recognized_sub_kind: statement.recognized_sub_kind.clone().map(semantic_sub_kind),
        label: statement.label.clone(),
        basis: statement.basis.clone(),
        graph_scope: statement.graph_scope.clone(),
        provenance_iri: statement.provenance_iri.clone(),
        first_asserted_ms: statement.first_asserted_ms,
        asserted_at_ms: statement.asserted_at_ms,
        withdrawn: statement.withdrawn.clone(),
    }
}