Skip to main content

kernel/graph/snapshot/
from.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//! `Graph::from_snapshot` — reconstruct the runtime graph from a
8//! persisted [`GraphSnapshot`].
9//!
10//! Extracted from `graph/snapshot.rs` per the 2026-05-11 kernel
11//! decomposition pass.
12
13use euclid::default::Point2D;
14use std::collections::BTreeMap;
15use uuid::Uuid;
16
17use super::super::import_records::import_records_from_legacy_provenance;
18use super::super::*;
19use crate::address::{address_from_url, detect_mime};
20use crate::persistence::{
21    GraphSnapshot, PersistedArrangementSubKind, PersistedContainmentSubKind,
22    PersistedCouplingResponse, PersistedEdge, PersistedFieldExtent, PersistedFieldLifecycle,
23    PersistedImportedSubKind, PersistedNavigationTrigger, PersistedNodeSelector,
24    PersistedProvenanceSubKind, PersistedSemanticSubKind,
25};
26
27fn semantic_sub_kind(sub_kind: PersistedSemanticSubKind) -> SemanticSubKind {
28    match sub_kind {
29        PersistedSemanticSubKind::Hyperlink => SemanticSubKind::Hyperlink,
30        PersistedSemanticSubKind::UserGrouped => SemanticSubKind::UserGrouped,
31        PersistedSemanticSubKind::AgentDerived => SemanticSubKind::AgentDerived,
32        PersistedSemanticSubKind::Cites => SemanticSubKind::Cites,
33        PersistedSemanticSubKind::Quotes => SemanticSubKind::Quotes,
34        PersistedSemanticSubKind::Summarizes => SemanticSubKind::Summarizes,
35        PersistedSemanticSubKind::Elaborates => SemanticSubKind::Elaborates,
36        PersistedSemanticSubKind::ExampleOf => SemanticSubKind::ExampleOf,
37        PersistedSemanticSubKind::Supports => SemanticSubKind::Supports,
38        PersistedSemanticSubKind::Contradicts => SemanticSubKind::Contradicts,
39        PersistedSemanticSubKind::Questions => SemanticSubKind::Questions,
40        PersistedSemanticSubKind::SameEntityAs => SemanticSubKind::SameEntityAs,
41        PersistedSemanticSubKind::DuplicateOf => SemanticSubKind::DuplicateOf,
42        PersistedSemanticSubKind::CanonicalMirrorOf => SemanticSubKind::CanonicalMirrorOf,
43        PersistedSemanticSubKind::DependsOn => SemanticSubKind::DependsOn,
44        PersistedSemanticSubKind::Blocks => SemanticSubKind::Blocks,
45        PersistedSemanticSubKind::NextStep => SemanticSubKind::NextStep,
46    }
47}
48
49impl Graph {
50    /// Load a snapshot, stopping on invalid explicit resource data or
51    /// navigation indices. Fallible load boundaries should use
52    /// [`Self::try_from_snapshot`].
53    pub fn from_snapshot(snapshot: &GraphSnapshot) -> Self {
54        Self::try_from_snapshot(snapshot)
55            .unwrap_or_else(|error| panic!("invalid graph snapshot: {error}"))
56    }
57
58    pub(super) fn from_snapshot_unchecked(snapshot: &GraphSnapshot) -> Self {
59        Self::materialize_snapshot(snapshot, true)
60    }
61
62    pub(super) fn from_recorded_snapshot_unchecked(snapshot: &GraphSnapshot) -> Self {
63        Self::materialize_snapshot(snapshot, false)
64    }
65
66    fn materialize_snapshot(snapshot: &GraphSnapshot, legacy_derived_containment: bool) -> Self {
67        let mut graph = Graph::new();
68        // Restore the shared navigation history (one visit space, owner per node)
69        // before the node loop, so each node's restored current page reads from it.
70        graph.nav = snapshot.navigation.clone();
71
72        // Checked load has already refused an unparseable or repeated Surface id.
73        for pnode in &snapshot.nodes {
74            let Ok(node_id) = Uuid::parse_str(&pnode.node_id) else {
75                continue;
76            };
77            // Prefer the typed address field (Stage C.2+); fall back to the legacy
78            // `url` string field for snapshots written before Stage C.2.
79            let node_url = {
80                let from_address = pnode.address.as_url_str();
81                if from_address.is_empty() {
82                    pnode.url.clone()
83                } else {
84                    from_address.to_string()
85                }
86            };
87            // Positions are no longer graph truth; they live in the cartography
88            // sidecar (the Cartography projection's geometry). Seed at the origin and
89            // let the sidecar override on load. (Position gut.)
90            let (key, inserted) =
91                graph.insert_node_if_missing(node_id, node_url, Point2D::new(0.0, 0.0));
92            if !inserted {
93                continue;
94            }
95            if let Some(node) = graph.inner.node_mut(key) {
96                if node.title != pnode.title {
97                    graph.content_revision = graph.content_revision.wrapping_add(1);
98                }
99                node.title = pnode.title.clone();
100                node.tags = pnode.tags.iter().cloned().collect();
101                // References only. Legacy inline bytes are externalized by the
102                // host before conversion (`pandect::image_store::
103                // migrate_legacy_images`), because hashing and blob storage
104                // are the store's job, not the kernel's. A snapshot that still
105                // carries them here has skipped that pass — see
106                // `GraphSnapshot::legacy_image_count`.
107                node.images = pnode.images.clone();
108                node.media_type = pnode.mime_hint.clone();
109                // address was already set by add_node_with_id from pnode.url; no re-derivation needed.
110                node.body = pnode.body.clone();
111                node.nested = pnode.nested.clone().map(muniment::LogId::new);
112                node.content = pnode
113                    .content_hash
114                    .as_deref()
115                    .and_then(muniment::Hash::from_hex);
116                if node.content.is_some() {
117                    node.body = None;
118                }
119            }
120            // One-time legacy-column import. Canonical saves put these records
121            // in `facets.json`; the old graph fields are written empty.
122            graph.set_node_facet(
123                key,
124                super::super::node_facets::PRESENTATION_TAGS,
125                &pnode.tag_presentation,
126            );
127            graph.set_node_facet(
128                key,
129                super::super::node_facets::PROVENANCE_IMPORT,
130                &pnode.import_provenance,
131            );
132            graph.set_node_facet(
133                key,
134                super::super::node_facets::SEMANTIC_CLASSIFICATIONS,
135                &pnode.classifications,
136            );
137            graph.set_node_facet(
138                key,
139                super::super::node_facets::SEMANTIC_PROPERTIES,
140                &pnode.properties,
141            );
142            graph.set_node_facet(
143                key,
144                super::super::node_facets::PROVENANCE_DERIVATIONS,
145                &pnode.derivations,
146            );
147            graph.set_node_facet(
148                key,
149                super::super::node_facets::ARRANGEMENT_PIN,
150                &pnode.is_pinned,
151            );
152            graph.set_node_facet(
153                key,
154                super::super::node_facets::ARRANGEMENT_FRAME_LAYOUT,
155                &pnode.frame_layout_hints,
156            );
157            graph.set_node_facet(
158                key,
159                super::super::node_facets::ARRANGEMENT_SPLIT_OFFER_SUPPRESSED,
160                &pnode.frame_split_offer_suppressed,
161            );
162            let last_visited_ms = pnode
163                .session_state
164                .as_ref()
165                .and_then(|session| session.last_visited_ms);
166            if let Some(last_visited_ms) = last_visited_ms {
167                graph.set_node_facet(
168                    key,
169                    super::super::node_facets::VISIT_HISTORY,
170                    &super::super::node_facets::VisitHistoryFacet {
171                        last_visited_ms: Some(last_visited_ms),
172                        last_session_visited: pnode.last_session_visited,
173                    },
174                );
175            } else if pnode.last_session_visited != 0 {
176                // Old snapshots could carry a session ordinal without an
177                // explicit visit timestamp. Preserve the creation-time visit
178                // installed by `add_node_with_id` while importing that ordinal.
179                graph.set_node_last_session_visited(key, pnode.last_session_visited);
180            }
181            // The saved node address is the owner of the current address. The
182            // navigation cursor is only a history position and never rewrites it
183            // (SetNodeUrl changes the address without a visit).
184        }
185
186        let mut surface_pair_ordinals = BTreeMap::new();
187        for pedge in &snapshot.edges {
188            let from_id = Uuid::parse_str(&pedge.from_node_id).ok();
189            let to_id = Uuid::parse_str(&pedge.to_node_id).ok();
190            let from_key = from_id.and_then(|id| graph.get_node_key_by_id(id));
191            let to_key = to_id.and_then(|id| graph.get_node_key_by_id(id));
192            if let (Some(from), Some(to), Some(from_id), Some(to_id)) =
193                (from_key, to_key, from_id, to_id)
194            {
195                // Legacy assertion identities are scoped to their ordered
196                // endpoint pair and bucket position. Replay uses this same
197                // pair-local ordinal in `set_edges_between`; an unrelated
198                // earlier pair must not change the synthesized identity.
199                let ordinal = surface_pair_ordinals.entry((from_id, to_id)).or_insert(0);
200                let pair_ordinal = *ordinal;
201                *ordinal += 1;
202                let mut payload =
203                    payload_from_persisted_at(pedge, GraphStratum::Surface, pair_ordinal);
204                if legacy_derived_containment
205                    && snapshot.assertion_schema == 0
206                    && pedge.assertions.is_none()
207                {
208                    mark_legacy_containment_sidecars_as_derived(&mut payload, pedge);
209                }
210                for statement in &mut payload.assertions.statements {
211                    statement.normalize_legacy_asserter();
212                }
213                if !payload.is_empty() || pedge.semantic.is_some() || pedge.traversal.is_some() {
214                    graph.inner.connect(from, to, payload);
215                    graph.bump_revision();
216                }
217            }
218        }
219
220        for record in &snapshot.resources {
221            let id = chartulary::resource_id_from_canonical_iri(&record.canonical_iri);
222            graph.set_resource_record(id, Some(record.clone()));
223        }
224        let mut resource_pairs: BTreeMap<(Uuid, Uuid), Vec<PersistedEdge>> = BTreeMap::new();
225        for edge in &snapshot.resource_edges {
226            let (Ok(from), Ok(to)) = (
227                Uuid::parse_str(&edge.from_node_id),
228                Uuid::parse_str(&edge.to_node_id),
229            ) else {
230                continue;
231            };
232            let mut edge = edge.clone();
233            if let Some(semantic) = &mut edge.semantic {
234                for statement in &mut semantic.statements {
235                    statement
236                        .provenance_iri
237                        .get_or_insert_with(|| edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.to_owned());
238                }
239            }
240            resource_pairs.entry((from, to)).or_default().push(edge);
241        }
242        for ((from, to), edges) in resource_pairs {
243            graph.set_resource_edges_between(from, to, &edges);
244        }
245        for shown in &snapshot.shown_resources {
246            if let (Ok(surface), Ok(resource)) = (
247                Uuid::parse_str(&shown.surface_id),
248                Uuid::parse_str(&shown.resource_id),
249            ) {
250                graph.set_shown_resource(surface, Some(resource));
251            }
252        }
253
254        // Field layer (field-system Phase 2). Malformed ids / definitions skip the
255        // entry rather than failing the whole load, matching the node/edge loops.
256        for pfield in &snapshot.fields {
257            let Ok(id) = Uuid::parse_str(&pfield.id) else {
258                continue;
259            };
260            let Ok(definition) = serde_json::from_str::<FieldDefinition>(&pfield.definition_json)
261            else {
262                continue;
263            };
264            let extent = match &pfield.extent {
265                PersistedFieldExtent::Global => FieldExtent::Global,
266                PersistedFieldExtent::Region {
267                    min_x,
268                    min_y,
269                    max_x,
270                    max_y,
271                } => FieldExtent::Region {
272                    min_x: *min_x,
273                    min_y: *min_y,
274                    max_x: *max_x,
275                    max_y: *max_y,
276                },
277                PersistedFieldExtent::AttachedToNode(s) => match Uuid::parse_str(s) {
278                    Ok(node_id) => FieldExtent::AttachedToNode(node_id),
279                    Err(_) => FieldExtent::Global,
280                },
281                PersistedFieldExtent::Polygon { points } => FieldExtent::Polygon {
282                    points: points.clone(),
283                },
284            };
285            let mut field = Field::new(FieldId::from_uuid(id), definition).with_extent(extent);
286            if let Some(name) = &pfield.name {
287                field = field.with_name(name.clone());
288            }
289            field.lifecycle = match pfield.lifecycle {
290                PersistedFieldLifecycle::Active => FieldLifecycle::Active,
291                PersistedFieldLifecycle::Retired => FieldLifecycle::Retired,
292            };
293            graph.add_field(field);
294        }
295
296        for pcoupling in &snapshot.couplings {
297            let Ok(cid) = Uuid::parse_str(&pcoupling.id) else {
298                continue;
299            };
300            let Ok(fid) = Uuid::parse_str(&pcoupling.field_id) else {
301                continue;
302            };
303            let selector = match &pcoupling.selector {
304                PersistedNodeSelector::All => NodeSelector::All,
305                PersistedNodeSelector::Tagged(t) => NodeSelector::Tagged(t.clone()),
306                PersistedNodeSelector::Kind(k) => NodeSelector::Kind(k.clone()),
307                PersistedNodeSelector::NotTagged(t) => NodeSelector::NotTagged(t.clone()),
308            };
309            let response = match &pcoupling.response {
310                PersistedCouplingResponse::AttractToMin => CouplingResponse::AttractToMin,
311                PersistedCouplingResponse::RepelFromMax => CouplingResponse::RepelFromMax,
312                PersistedCouplingResponse::AlignVelocity => CouplingResponse::AlignVelocity,
313                PersistedCouplingResponse::FlowAdvect => CouplingResponse::FlowAdvect,
314                PersistedCouplingResponse::DampenInside { factor } => {
315                    CouplingResponse::DampenInside { factor: *factor }
316                },
317                PersistedCouplingResponse::ContainmentWall => CouplingResponse::ContainmentWall,
318                PersistedCouplingResponse::Open { predicate } => CouplingResponse::Open {
319                    predicate: predicate.clone(),
320                },
321            };
322            graph.add_coupling(Coupling::new(
323                CouplingId::from_uuid(cid),
324                FieldId::from_uuid(fid),
325                selector,
326                response,
327                pcoupling.strength,
328            ));
329        }
330
331        graph.import_records = if snapshot.import_records.is_empty() {
332            // Predates the table: the legacy per-node column is the only source.
333            import_records_from_legacy_provenance(
334                snapshot.nodes.iter().filter_map(|pnode| {
335                    let node_id = Uuid::parse_str(&pnode.node_id).ok()?;
336                    Some((node_id, pnode.import_provenance.as_slice()))
337                }),
338                snapshot.timestamp_secs,
339            )
340        } else {
341            snapshot.import_records.clone()
342        };
343        normalize_import_records(&mut graph.import_records);
344        graph.sync_node_import_provenance_from_records();
345
346        if legacy_derived_containment {
347            graph.rebuild_derived_containment_relations();
348        }
349
350        graph
351    }
352}
353
354/// Before canonical assertion records existed, Surface UrlPath and Domain
355/// sidecars were compatibility projections of current URLs, not authored
356/// claims. Mark just those legacy Surface rows so the ordinary session loader
357/// can replace them from current source data without treating canonical or
358/// unknown Resource assertions as rule output.
359fn mark_legacy_containment_sidecars_as_derived(payload: &mut EdgePayload, edge: &PersistedEdge) {
360    let Some(containment) = &edge.containment else {
361        return;
362    };
363    let has_derived_sidecar = containment.sub_kinds.iter().any(|kind| {
364        matches!(
365            kind,
366            PersistedContainmentSubKind::UrlPath | PersistedContainmentSubKind::Domain
367        )
368    });
369    if !has_derived_sidecar {
370        return;
371    }
372    for statement in &mut payload.assertions.statements {
373        if statement.provenance_iri.as_deref() != Some(edge_data::UNKNOWN_LEGACY_ASSERTER_IRI)
374            || statement.basis.method.is_some()
375            || !matches!(
376                statement.relation_kind(),
377                RelationKind::Containment(ContainmentSubKind::UrlPath | ContainmentSubKind::Domain)
378            )
379        {
380            continue;
381        }
382        statement.basis.method = Some(crate::types::AssertionMethod {
383            iri: "urn:mere:method:derived-containment".into(),
384            version: Some("1".into()),
385        });
386    }
387    payload.assertions.rebuild_compat();
388}
389
390impl Graph {
391    /// Merge one persisted edge into a surface pair, retaining revision behavior.
392    pub(crate) fn restore_persisted_edge(
393        &mut self,
394        from: NodeKey,
395        to: NodeKey,
396        pedge: &PersistedEdge,
397    ) {
398        let existing = self.find_edge_key(from, to);
399        let mut payload = existing
400            .and_then(|key| self.inner.edge(key))
401            .cloned()
402            .unwrap_or_else(EdgePayload::new);
403        let structural_changes = restore_persisted_payload(&mut payload, pedge);
404        if pedge.semantic.is_some() || pedge.traversal.is_some() || !payload.is_empty() {
405            match existing {
406                Some(key) => *self.inner.edge_mut(key).expect("existing edge") = payload,
407                None => {
408                    self.inner.connect(from, to, payload);
409                },
410            }
411        }
412        for _ in 0..structural_changes {
413            self.bump_revision();
414        }
415    }
416}
417
418/// Decode a standalone pair without changing carried assertion metadata.
419pub(crate) fn payload_from_persisted(pedge: &PersistedEdge) -> EdgePayload {
420    payload_from_persisted_at(pedge, GraphStratum::Surface, 0)
421}
422
423pub(crate) fn payload_from_persisted_at(
424    pedge: &PersistedEdge,
425    stratum: GraphStratum,
426    ordinal: usize,
427) -> EdgePayload {
428    let mut payload = EdgePayload::new();
429    restore_payload_at(&mut payload, pedge, stratum, ordinal);
430    payload
431}
432
433/// Merge persisted sidecars; report structural insertions for surface revisions.
434pub(crate) fn restore_persisted_payload(payload: &mut EdgePayload, pedge: &PersistedEdge) -> usize {
435    restore_payload_at(payload, pedge, GraphStratum::Surface, 0)
436}
437
438fn restore_payload_at(
439    payload: &mut EdgePayload,
440    pedge: &PersistedEdge,
441    stratum: GraphStratum,
442    ordinal: usize,
443) -> usize {
444    let mut structural_changes = 0;
445    if let Some(records) = &pedge.assertions {
446        let mut ids: std::collections::BTreeSet<_> = payload
447            .assertions()
448            .iter()
449            .map(|s| s.statement_id.clone())
450            .collect();
451        for record in records {
452            if ids.insert(record.statement_id.clone()) {
453                let mut record = runtime_assertion(record);
454                record.normalize_basis_compat();
455                payload.assertions.statements.push(record);
456                structural_changes += 1;
457            }
458        }
459    }
460    let preserved_ids: std::collections::BTreeSet<_> = payload
461        .assertions()
462        .iter()
463        .map(|s| s.statement_id.clone())
464        .chain(
465            pedge
466                .semantic
467                .as_ref()
468                .into_iter()
469                .flat_map(|data| &data.statements)
470                .map(|s| s.statement_id.clone()),
471        )
472        .collect();
473    // Canonical records are authoritative. Checked load refuses a nonempty
474    // legacy sidecar alongside them instead of inventing a merge precedence.
475    if pedge.assertions.is_none() {
476        if let Some(semantic) = &pedge.semantic {
477            if !semantic.statements.is_empty() {
478                for statement in &semantic.statements {
479                    let _ = payload.push_persisted_semantic_statement(SemanticStatement {
480                        statement_id: statement.statement_id.clone(),
481                        predicate: statement.predicate.clone(),
482                        recognized_sub_kind: statement.recognized_sub_kind.map(semantic_sub_kind),
483                        label: statement.label.clone(),
484                        basis: statement.basis.clone(),
485                        graph_scope: statement.graph_scope.clone(),
486                        provenance_iri: statement.provenance_iri.clone(),
487                        first_asserted_ms: statement.first_asserted_ms,
488                        asserted_at_ms: statement.asserted_at_ms,
489                        withdrawn: statement.withdrawn.clone(),
490                    });
491                }
492            } else {
493                for sub_kind in &semantic.sub_kinds {
494                    payload.assert_semantic_statement(SemanticStatementSpec {
495                        predicate: predicate_iri(semantic_sub_kind(sub_kind.clone())).into(),
496                        recognized_sub_kind: Some(semantic_sub_kind(sub_kind.clone())),
497                        label: semantic.label.clone(),
498                        graph_scope: crate::types::GraphScope::Default,
499                        provenance_iri: Some(edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into()),
500                        asserted_at_ms: None,
501                        basis: Default::default(),
502                    });
503                }
504                if semantic.predicate.is_some() {
505                    payload.set_semantic_predicate(semantic.predicate.clone());
506                }
507            }
508        }
509        if let Some(arrangement) = &pedge.arrangement {
510            for sub_kind in &arrangement.sub_kinds {
511                let assertion = match sub_kind {
512                    PersistedArrangementSubKind::FrameMember => EdgeAssertion::Arrangement {
513                        sub_kind: ArrangementSubKind::FrameMember,
514                    },
515                    PersistedArrangementSubKind::TileGroup => EdgeAssertion::Arrangement {
516                        sub_kind: ArrangementSubKind::TileGroup,
517                    },
518                    PersistedArrangementSubKind::SplitPair => EdgeAssertion::Arrangement {
519                        sub_kind: ArrangementSubKind::SplitPair,
520                    },
521                    PersistedArrangementSubKind::TabNeighbor
522                    | PersistedArrangementSubKind::ActiveTab
523                    | PersistedArrangementSubKind::PinnedInFrame => continue,
524                };
525                structural_changes += usize::from(payload.assert_relation(assertion));
526            }
527        }
528        if let Some(containment) = &pedge.containment {
529            for sub_kind in &containment.sub_kinds {
530                // Every persisted sub-kind is restored. `UrlPath` and
531                // `Domain` are re-derived below by
532                // `rebuild_derived_containment_relations`, but the
533                // authored ones exist only here: dropping any of them
534                // loses user data. Matched exhaustively so a new
535                // variant is a compile error rather than a silent
536                // omission.
537                let sub_kind = match sub_kind {
538                    PersistedContainmentSubKind::UrlPath => ContainmentSubKind::UrlPath,
539                    PersistedContainmentSubKind::Domain => ContainmentSubKind::Domain,
540                    PersistedContainmentSubKind::FileSystem => ContainmentSubKind::FileSystem,
541                    PersistedContainmentSubKind::UserFolder => ContainmentSubKind::UserFolder,
542                    PersistedContainmentSubKind::ClipSource => ContainmentSubKind::ClipSource,
543                    PersistedContainmentSubKind::NotebookSection => {
544                        ContainmentSubKind::NotebookSection
545                    },
546                    PersistedContainmentSubKind::CollectionMember => {
547                        ContainmentSubKind::CollectionMember
548                    },
549                };
550                structural_changes +=
551                    usize::from(payload.assert_relation(EdgeAssertion::Containment { sub_kind }));
552            }
553        }
554        if let Some(imported) = &pedge.imported {
555            for sub_kind in &imported.sub_kinds {
556                let assertion = match sub_kind {
557                    PersistedImportedSubKind::BookmarkFolder => EdgeAssertion::Imported {
558                        sub_kind: ImportedSubKind::BookmarkFolder,
559                    },
560                    PersistedImportedSubKind::HistoryImport => EdgeAssertion::Imported {
561                        sub_kind: ImportedSubKind::HistoryImport,
562                    },
563                    PersistedImportedSubKind::SessionImport => EdgeAssertion::Imported {
564                        sub_kind: ImportedSubKind::SessionImport,
565                    },
566                    PersistedImportedSubKind::RssMembership => EdgeAssertion::Imported {
567                        sub_kind: ImportedSubKind::RssMembership,
568                    },
569                    PersistedImportedSubKind::FileSystemImport => EdgeAssertion::Imported {
570                        sub_kind: ImportedSubKind::FileSystemImport,
571                    },
572                    PersistedImportedSubKind::ArchiveMembership => EdgeAssertion::Imported {
573                        sub_kind: ImportedSubKind::ArchiveMembership,
574                    },
575                    PersistedImportedSubKind::SharedCollection => EdgeAssertion::Imported {
576                        sub_kind: ImportedSubKind::SharedCollection,
577                    },
578                };
579                structural_changes += usize::from(payload.assert_relation(assertion));
580            }
581        }
582        if let Some(provenance) = &pedge.provenance {
583            for sub_kind in &provenance.sub_kinds {
584                let assertion = match sub_kind {
585                    PersistedProvenanceSubKind::ClippedFrom => EdgeAssertion::Provenance {
586                        sub_kind: ProvenanceSubKind::ClippedFrom,
587                    },
588                    PersistedProvenanceSubKind::ExcerptedFrom => EdgeAssertion::Provenance {
589                        sub_kind: ProvenanceSubKind::ExcerptedFrom,
590                    },
591                    PersistedProvenanceSubKind::SummarizedFrom => EdgeAssertion::Provenance {
592                        sub_kind: ProvenanceSubKind::SummarizedFrom,
593                    },
594                    PersistedProvenanceSubKind::TranslatedFrom => EdgeAssertion::Provenance {
595                        sub_kind: ProvenanceSubKind::TranslatedFrom,
596                    },
597                    PersistedProvenanceSubKind::RewrittenFrom => EdgeAssertion::Provenance {
598                        sub_kind: ProvenanceSubKind::RewrittenFrom,
599                    },
600                    PersistedProvenanceSubKind::GeneratedFrom => EdgeAssertion::Provenance {
601                        sub_kind: ProvenanceSubKind::GeneratedFrom,
602                    },
603                    PersistedProvenanceSubKind::ExtractedFrom => EdgeAssertion::Provenance {
604                        sub_kind: ProvenanceSubKind::ExtractedFrom,
605                    },
606                    PersistedProvenanceSubKind::ImportedFromSource => EdgeAssertion::Provenance {
607                        sub_kind: ProvenanceSubKind::ImportedFromSource,
608                    },
609                    PersistedProvenanceSubKind::CopiedFrom => EdgeAssertion::Provenance {
610                        sub_kind: ProvenanceSubKind::CopiedFrom,
611                    },
612                    PersistedProvenanceSubKind::MergedFrom => EdgeAssertion::Provenance {
613                        sub_kind: ProvenanceSubKind::MergedFrom,
614                    },
615                };
616                structural_changes += usize::from(payload.assert_relation(assertion));
617            }
618        }
619    }
620    for statement in &mut payload.assertions.statements {
621        if !preserved_ids.contains(&statement.statement_id) {
622            statement.statement_id =
623                legacy_assertion_id(pedge, stratum, ordinal, &statement.predicate);
624            statement.normalize_legacy_asserter();
625        }
626    }
627    payload.assertions.rebuild_compat();
628    if let Some(traversal) = &pedge.traversal {
629        let data = payload.traversal.get_or_insert_with(TraversalData::default);
630        data.traversals = traversal
631            .traversals
632            .iter()
633            .map(|record| Traversal {
634                timestamp_ms: record.timestamp_ms,
635                trigger: match record.trigger {
636                    PersistedNavigationTrigger::Unknown => NavigationTrigger::Unknown,
637                    PersistedNavigationTrigger::LinkClick => NavigationTrigger::LinkClick,
638                    PersistedNavigationTrigger::Back => NavigationTrigger::Back,
639                    PersistedNavigationTrigger::Forward => NavigationTrigger::Forward,
640                    PersistedNavigationTrigger::AddressBarEntry => {
641                        NavigationTrigger::AddressBarEntry
642                    },
643                    PersistedNavigationTrigger::PanePromotion => NavigationTrigger::PanePromotion,
644                    PersistedNavigationTrigger::Programmatic => NavigationTrigger::Programmatic,
645                    PersistedNavigationTrigger::Redirect => NavigationTrigger::Redirect,
646                    PersistedNavigationTrigger::ReopenSession => NavigationTrigger::ReopenSession,
647                    PersistedNavigationTrigger::JumpAnchor => NavigationTrigger::JumpAnchor,
648                    PersistedNavigationTrigger::InPageSearchJump => {
649                        NavigationTrigger::InPageSearchJump
650                    },
651                    PersistedNavigationTrigger::ImportedHistory => {
652                        NavigationTrigger::ImportedHistory
653                    },
654                },
655            })
656            .collect();
657        data.metrics = EdgeMetrics {
658            total_navigations: traversal.metrics.total_navigations,
659            forward_navigations: traversal.metrics.forward_navigations,
660            backward_navigations: traversal.metrics.backward_navigations,
661            last_navigated_at: traversal.metrics.last_navigated_at,
662        };
663    }
664    structural_changes
665}
666
667/// Stable one-time legacy identity: UTF-8 JSON array of version/domain,
668/// stratum, original directed endpoint strings, bucket ordinal and predicate;
669/// RFC 9562 UUIDv5 in the URL namespace. No clock or platform hash enters it.
670fn legacy_assertion_id(
671    edge: &PersistedEdge,
672    stratum: GraphStratum,
673    ordinal: usize,
674    predicate: &str,
675) -> String {
676    let bytes = serde_json::to_vec(&(
677        "mere.legacy-relation-assertion",
678        1u8,
679        match stratum {
680            GraphStratum::Surface => "surface",
681            GraphStratum::Resource => "resource",
682        },
683        &edge.from_node_id,
684        &edge.to_node_id,
685        ordinal,
686        predicate,
687    ))
688    .expect("string tuple JSON");
689    format!(
690        "urn:mere:legacy-assertion:v1:{}",
691        Uuid::new_v5(&Uuid::NAMESPACE_URL, &bytes)
692    )
693}
694
695fn runtime_assertion(
696    statement: &crate::persistence::PersistedSemanticStatement,
697) -> SemanticStatement {
698    SemanticStatement {
699        statement_id: statement.statement_id.clone(),
700        predicate: statement.predicate.clone(),
701        recognized_sub_kind: statement.recognized_sub_kind.clone().map(semantic_sub_kind),
702        label: statement.label.clone(),
703        basis: statement.basis.clone(),
704        graph_scope: statement.graph_scope.clone(),
705        provenance_iri: statement.provenance_iri.clone(),
706        first_asserted_ms: statement.first_asserted_ms,
707        asserted_at_ms: statement.asserted_at_ms,
708        withdrawn: statement.withdrawn.clone(),
709    }
710}