Skip to main content

kernel/graph/
apply.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use chartulary::stemma::TransitionKind;
5use euclid::default::Point2D;
6use uuid::Uuid;
7
8use super::{
9    Coupling, CouplingId, EdgeAssertion, EdgeKey, Field, FieldId, FrameLayoutHint, Graph,
10    NavigationTrigger, NodeKey, RelationSelector, SemanticSubKind,
11    capture::{
12        CapturedDelta, coupling_from_persisted, field_from_persisted,
13        persisted_coupling_from_coupling, persisted_field_from_field, record_captured_delta,
14    },
15};
16use crate::persistence::{PersistedCoupling, PersistedField};
17use crate::types::{
18    BadgeIcon, ClassificationScheme, ClassificationStatus, GraphScope, ImageRef, ImageRole,
19    ImportRecord, NodeClassification, NodeDerivation, NodeImportProvenance, NodeProperty,
20};
21
22#[derive(Debug, Clone)]
23pub enum GraphDelta {
24    AddNode {
25        id: Option<Uuid>,
26        url: String,
27        position: Point2D<f32>,
28    },
29    AssertRelation {
30        from: NodeKey,
31        to: NodeKey,
32        assertion: EdgeAssertion,
33    },
34    RemoveNode {
35        key: NodeKey,
36    },
37    ReplayAddNodeWithIdIfMissing {
38        id: Uuid,
39        url: String,
40        position: Point2D<f32>,
41    },
42    ReplayAssertRelationByIds {
43        from_id: Uuid,
44        to_id: Uuid,
45        assertion: EdgeAssertion,
46    },
47    ReplayRemoveNodeById {
48        node_id: Uuid,
49    },
50    ReplayRetractRelationsByIds {
51        from_id: Uuid,
52        to_id: Uuid,
53        selector: RelationSelector,
54    },
55    ReplayAppendTraversalByIds {
56        from_id: Uuid,
57        to_id: Uuid,
58        trigger: NavigationTrigger,
59        timestamp_ms: u64,
60    },
61    ReplaySetNodeTitleById {
62        node_id: Uuid,
63        title: String,
64    },
65    ReplaySetNodeUrlById {
66        node_id: Uuid,
67        new_url: String,
68    },
69    ReplaySetNodeImageById {
70        node_id: Uuid,
71        role: ImageRole,
72        image: ImageRef,
73    },
74    ReplaySetNodeMimeHintById {
75        node_id: Uuid,
76        mime_hint: Option<String>,
77    },
78    ReplaySetNodeNestedById {
79        node_id: Uuid,
80        nested: Option<String>,
81    },
82    ReplaySetNodePinnedById {
83        node_id: Uuid,
84        is_pinned: bool,
85    },
86    ReplaySetNodeFacetById {
87        node_id: Uuid,
88        facet: String,
89        value: serde_json::Value,
90    },
91    ReplayRemoveNodeFacetById {
92        node_id: Uuid,
93        facet: String,
94    },
95    ReplayInsertNodeTagById {
96        node_id: Uuid,
97        tag: String,
98    },
99    ReplayRemoveNodeTagById {
100        node_id: Uuid,
101        tag: String,
102    },
103    ReplaySetNodeBodyById {
104        node_id: Uuid,
105        body: Option<String>,
106    },
107    ReplayNavigateNodeById {
108        node_id: Uuid,
109        url: String,
110        transition: TransitionKind,
111        timestamp_ms: u64,
112        last_session_visited: u64,
113    },
114    ReplayBranchHistoryByIds {
115        child_id: Uuid,
116        parent_id: Uuid,
117    },
118    ReplayNodeHistoryBackById {
119        node_id: Uuid,
120        timestamp_ms: u64,
121    },
122    ReplayNodeHistoryForwardById {
123        node_id: Uuid,
124        timestamp_ms: u64,
125    },
126    ReplayAppendNodePropertyById {
127        node_id: Uuid,
128        property: NodeProperty,
129    },
130    ReplayAddNodeClassificationById {
131        node_id: Uuid,
132        classification: NodeClassification,
133    },
134    ReplayRemoveNodeClassificationById {
135        node_id: Uuid,
136        scheme: ClassificationScheme,
137        value: String,
138    },
139    ReplaySetNodeClassificationStatusById {
140        node_id: Uuid,
141        scheme: ClassificationScheme,
142        value: String,
143        status: ClassificationStatus,
144    },
145    ReplaySetNodePrimaryClassificationById {
146        node_id: Uuid,
147        scheme: ClassificationScheme,
148        value: String,
149    },
150    ReplayRecordNodeDerivationById {
151        node_id: Uuid,
152        derivation: NodeDerivation,
153    },
154    ReplaySetNodeTagIconOverrideById {
155        node_id: Uuid,
156        tag: String,
157        icon: Option<BadgeIcon>,
158    },
159    ReplaySetEdgeSemanticPredicateByIds {
160        from_id: Uuid,
161        to_id: Uuid,
162        predicate: Option<String>,
163    },
164    ReplayAssertSemanticPredicateByIds {
165        from_id: Uuid,
166        to_id: Uuid,
167        predicate: String,
168    },
169    ReplayAppendFrameLayoutHintById {
170        node_id: Uuid,
171        hint: FrameLayoutHint,
172    },
173    ReplayRemoveFrameLayoutHintById {
174        node_id: Uuid,
175        hint_index: usize,
176    },
177    ReplayMoveFrameLayoutHintById {
178        node_id: Uuid,
179        from_index: usize,
180        to_index: usize,
181    },
182    ReplaySetFrameSplitOfferSuppressedById {
183        node_id: Uuid,
184        suppressed: bool,
185    },
186    ReplayUpdateNodeHistoryById {
187        node_id: Uuid,
188        entries: Vec<String>,
189        current_index: usize,
190    },
191    ReplaySetImportRecords {
192        import_records: Vec<ImportRecord>,
193    },
194    ReplayTouchNodeLastVisitedById {
195        node_id: Uuid,
196        timestamp_ms: u64,
197    },
198    RetractRelations {
199        from: NodeKey,
200        to: NodeKey,
201        selector: RelationSelector,
202    },
203    /// Append a traversal event to the `from → to` edge (creating the
204    /// edge if absent). `timestamp_ms = None` stamps now-via-the-kernel;
205    /// `Some(t)` uses the supplied timestamp (importers, replay).
206    AppendTraversal {
207        from: NodeKey,
208        to: NodeKey,
209        trigger: NavigationTrigger,
210        timestamp_ms: Option<u64>,
211    },
212    SetNodeTitle {
213        key: NodeKey,
214        title: String,
215    },
216    SetNodeUrl {
217        key: NodeKey,
218        new_url: String,
219    },
220    /// Attach a stored image reference under a role. The host stores the blob
221    /// first and passes the handle; no pixels travel through the delta spine
222    /// (node-image externalization, phase 3).
223    SetNodeImage {
224        key: NodeKey,
225        role: ImageRole,
226        image: ImageRef,
227    },
228    SetNodeMimeHint {
229        key: NodeKey,
230        mime_hint: Option<String>,
231    },
232    SetNodeNested {
233        key: NodeKey,
234        nested: Option<codicil::LogId>,
235    },
236    SetNodePinned {
237        key: NodeKey,
238        is_pinned: bool,
239    },
240    /// Set one arbitrary, namespaced facet through the durable delta spine.
241    SetNodeFacet {
242        key: NodeKey,
243        facet: String,
244        value: serde_json::Value,
245    },
246    /// Remove one arbitrary, namespaced facet through the durable delta spine.
247    RemoveNodeFacet {
248        key: NodeKey,
249        facet: String,
250    },
251    AppendFrameLayoutHint {
252        key: NodeKey,
253        hint: FrameLayoutHint,
254    },
255    RemoveFrameLayoutHint {
256        key: NodeKey,
257        hint_index: usize,
258    },
259    MoveFrameLayoutHint {
260        key: NodeKey,
261        from_index: usize,
262        to_index: usize,
263    },
264    SetFrameSplitOfferSuppressed {
265        key: NodeKey,
266        suppressed: bool,
267    },
268    /// Replace a node's persisted navigation history (entries + current
269    /// index). The clamping rule is: `current_index` is treated as `0` when
270    /// `entries` is empty, otherwise it is clamped to `entries.len() - 1`.
271    /// Sole sanctioned write surface for `Node::history`; the underlying
272    /// `Graph` setter is `pub(crate)` so this delta is the only way to
273    /// mutate the field from outside `kernel`.
274    UpdateNodeHistory {
275        key: NodeKey,
276        entries: Vec<String>,
277        current_index: usize,
278    },
279    /// Replace the durable import-record table with a normalized whole-table snapshot.
280    SetImportRecords {
281        import_records: Vec<ImportRecord>,
282    },
283    /// Delete one durable import record by id.
284    DeleteImportRecord {
285        record_id: String,
286    },
287    /// Suppress or unsuppress one node membership within an import record.
288    SetImportRecordMembershipSuppressed {
289        record_id: String,
290        key: NodeKey,
291        suppressed: bool,
292    },
293    /// Replace one node's import provenance; the kernel rebuilds import records from it.
294    SetNodeImportProvenance {
295        key: NodeKey,
296        import_provenance: Vec<NodeImportProvenance>,
297    },
298    /// Stamp one node's last-visited clock from the kernel clock.
299    TouchNodeLastVisited {
300        key: NodeKey,
301    },
302    // --- Write-path migration (2026-07-01): the variants below complete the
303    // Phase 6.5 boundary. Every primitive durable mutation shell/runtime code
304    // performs now has a delta; the raw mutators are `pub(crate)`. ---
305    /// Navigate a node in place: record the visit in its own browse history and
306    /// update its Primary URL. No new node, no edge.
307    NavigateNode {
308        key: NodeKey,
309        url: String,
310    },
311    /// Anchor a freshly-minted `child` node's history under `parent`'s current
312    /// visit (the navigated-from anchor; call before the child's first navigate).
313    BranchHistory {
314        child: NodeKey,
315        parent: NodeKey,
316    },
317    /// Step a node back one visit in its own history (result:
318    /// [`GraphDeltaResult::HistoryStepped`] carries the revealed URL).
319    NodeHistoryBack {
320        key: NodeKey,
321    },
322    /// Step a node forward one visit in its own history.
323    NodeHistoryForward {
324        key: NodeKey,
325    },
326    /// Add a durable semantic tag (also appends to the presentation order).
327    InsertNodeTag {
328        key: NodeKey,
329        tag: String,
330    },
331    /// Remove a durable semantic tag (also drops its presentation entries).
332    RemoveNodeTag {
333        key: NodeKey,
334        tag: String,
335    },
336    /// Set (or clear) a node's inline authored content body (knot note source).
337    SetNodeBody {
338        key: NodeKey,
339        body: Option<String>,
340    },
341    /// Append an open literal property (dedup by exact predicate+value pair).
342    AppendNodeProperty {
343        key: NodeKey,
344        property: NodeProperty,
345    },
346    /// Add a provenance-bearing classification record (dedup by scheme+value).
347    AddNodeClassification {
348        key: NodeKey,
349        classification: NodeClassification,
350    },
351    /// Remove a classification record identified by `(scheme, value)`.
352    RemoveNodeClassification {
353        key: NodeKey,
354        scheme: ClassificationScheme,
355        value: String,
356    },
357    /// Update the status of a classification record identified by `(scheme, value)`.
358    SetNodeClassificationStatus {
359        key: NodeKey,
360        scheme: ClassificationScheme,
361        value: String,
362        status: ClassificationStatus,
363    },
364    /// Promote one classification record to primary within its scheme.
365    SetNodePrimaryClassification {
366        key: NodeKey,
367        scheme: ClassificationScheme,
368        value: String,
369    },
370    /// Record cross-graph / extraction derivation provenance on a node.
371    RecordNodeDerivation {
372        key: NodeKey,
373        derivation: NodeDerivation,
374    },
375    /// Set or clear a tag-icon override for a durable user tag.
376    SetNodeTagIconOverride {
377        key: NodeKey,
378        tag: String,
379        icon: Option<BadgeIcon>,
380    },
381    /// Set (or clear) the canonical semantic-predicate IRI on an existing edge.
382    SetEdgeSemanticPredicate {
383        edge: EdgeKey,
384        predicate: Option<String>,
385    },
386    /// Assert a plain semantic edge carrying a raw predicate IRI (the
387    /// unrecognized-predicate ingest path), creating the edge if absent.
388    AssertSemanticPredicate {
389        from: NodeKey,
390        to: NodeKey,
391        predicate: String,
392    },
393    ReplayAddField {
394        field: PersistedField,
395    },
396    ReplayRetireFieldById {
397        field_id: String,
398    },
399    ReplayAddCoupling {
400        coupling: PersistedCoupling,
401    },
402    ReplaySetFieldCouplingStrengthByFieldId {
403        field_id: String,
404        strength: f32,
405    },
406    ReplayActivateFieldById {
407        field_id: String,
408    },
409    ReplayRetractCouplingById {
410        coupling_id: String,
411    },
412    /// Add (or replace by id) a field — field-layer truth.
413    AddField {
414        field: Field,
415    },
416    /// Retire a field (lifecycle to Retired; couplings stop evaluating).
417    RetireField {
418        id: FieldId,
419    },
420    /// Add (or replace by id) a coupling binding a field to a node selector.
421    AddCoupling {
422        coupling: Coupling,
423    },
424    /// Set the strength of every coupling bound to `field`.
425    SetFieldCouplingStrength {
426        field: FieldId,
427        strength: f32,
428    },
429    /// Reactivate a retired field.
430    ActivateField {
431        id: FieldId,
432    },
433    /// Remove one coupling binding by id.
434    RetractCoupling {
435        id: CouplingId,
436    },
437}
438
439#[derive(Debug, Clone, PartialEq, Eq)]
440pub enum GraphDeltaResult {
441    NodeAdded(NodeKey),
442    NodeMaybeAdded(Option<NodeKey>),
443    EdgeAdded(Option<EdgeKey>),
444    NodeRemoved(bool),
445    EdgesRemoved(usize),
446    TraversalAppended(bool),
447    NodeMetadataUpdated(bool),
448    NodeUrlUpdated(Option<String>),
449    /// A history back/forward step: the revealed URL, or `None` at the
450    /// root/tip (the cursor did not move).
451    HistoryStepped(Option<String>),
452    /// A field-layer mutation: whether anything actually changed.
453    FieldChanged(bool),
454    /// An import-record mutation: whether anything actually changed.
455    ImportRecordsUpdated(bool),
456    /// A mutation with no observable result (e.g. navigate, branch-history).
457    Applied,
458}
459
460fn capture_resolved_import_records(graph: &Graph) {
461    record_captured_delta(&CapturedDelta::ReplaySetImportRecords {
462        import_records: graph.import_records().to_vec(),
463    });
464}
465
466fn set_node_facet(graph: &mut Graph, key: NodeKey, facet: &str, value: serde_json::Value) -> bool {
467    let Some(node_id) = graph.get_node(key).map(|node| node.id) else {
468        return false;
469    };
470    let facet = chartulary::FacetId::new(facet);
471    if graph.facets().get(&node_id, &facet) == Some(&value) {
472        return false;
473    }
474    graph
475        .facets
476        .set(node_id, facet, value, &chartulary::AcceptAll)
477        .expect("AcceptAll cannot reject a graph facet");
478    true
479}
480
481fn remove_node_facet(graph: &mut Graph, key: NodeKey, facet: &str) -> bool {
482    let Some(node_id) = graph.get_node(key).map(|node| node.id) else {
483        return false;
484    };
485    graph
486        .facets
487        .remove(&node_id, &chartulary::FacetId::new(facet))
488        .is_some()
489}
490
491pub fn apply_graph_delta(graph: &mut Graph, delta: GraphDelta) -> GraphDeltaResult {
492    match delta {
493        GraphDelta::AddNode { id, url, position } => {
494            let capture_url = url.clone();
495            let capture_position = [position.x, position.y];
496            let key = match id {
497                Some(id) => graph.add_node_with_id(id, url, position),
498                #[cfg(not(target_arch = "wasm32"))]
499                None => graph.add_node(url, position),
500                #[cfg(target_arch = "wasm32")]
501                None => panic!("AddNode without an explicit id is not supported on WASM"),
502            };
503            if let Some(node) = graph.get_node(key) {
504                record_captured_delta(&CapturedDelta::ReplayAddNodeWithIdIfMissing {
505                    id: node.id.to_string(),
506                    url: capture_url,
507                    position: capture_position,
508                });
509            }
510            GraphDeltaResult::NodeAdded(key)
511        }
512        GraphDelta::AssertRelation {
513            from,
514            to,
515            assertion,
516        } => {
517            let from_id = graph.get_node(from).map(|node| node.id);
518            let to_id = graph.get_node(to).map(|node| node.id);
519            let capture_assertion = assertion.clone();
520            let edge = graph.assert_relation(from, to, assertion);
521            if edge.is_some()
522                && let (Some(from_id), Some(to_id)) = (from_id, to_id)
523            {
524                record_captured_delta(&CapturedDelta::ReplayAssertRelationByIds {
525                    from_id: from_id.to_string(),
526                    to_id: to_id.to_string(),
527                    assertion: capture_assertion,
528                });
529            }
530            GraphDeltaResult::EdgeAdded(edge)
531        }
532        GraphDelta::RemoveNode { key } => {
533            let node_id = graph.get_node(key).map(|node| node.id);
534            let removed = graph.remove_node(key);
535            if removed && let Some(node_id) = node_id {
536                record_captured_delta(&CapturedDelta::ReplayRemoveNodeById {
537                    node_id: node_id.to_string(),
538                });
539            }
540            GraphDeltaResult::NodeRemoved(removed)
541        }
542        GraphDelta::ReplayAddNodeWithIdIfMissing { id, url, position } => {
543            let capture_url = url.clone();
544            let capture_position = [position.x, position.y];
545            let added = graph.replay_add_node_with_id_if_missing(id, url, position);
546            if added.is_some() {
547                record_captured_delta(&CapturedDelta::ReplayAddNodeWithIdIfMissing {
548                    id: id.to_string(),
549                    url: capture_url,
550                    position: capture_position,
551                });
552            }
553            GraphDeltaResult::NodeMaybeAdded(added)
554        }
555        GraphDelta::ReplayAssertRelationByIds {
556            from_id,
557            to_id,
558            assertion,
559        } => {
560            let capture_assertion = assertion.clone();
561            let edge = graph.replay_assert_relation_by_ids(from_id, to_id, assertion);
562            if edge.is_some() {
563                record_captured_delta(&CapturedDelta::ReplayAssertRelationByIds {
564                    from_id: from_id.to_string(),
565                    to_id: to_id.to_string(),
566                    assertion: capture_assertion,
567                });
568            }
569            GraphDeltaResult::EdgeAdded(edge)
570        }
571        GraphDelta::ReplayRemoveNodeById { node_id } => {
572            let removed = graph.replay_remove_node_by_id(node_id);
573            if removed {
574                record_captured_delta(&CapturedDelta::ReplayRemoveNodeById {
575                    node_id: node_id.to_string(),
576                });
577            }
578            GraphDeltaResult::NodeRemoved(removed)
579        }
580        GraphDelta::ReplayRetractRelationsByIds {
581            from_id,
582            to_id,
583            selector,
584        } => {
585            let removed = graph.replay_retract_relations_by_ids(from_id, to_id, selector);
586            if removed > 0 {
587                record_captured_delta(&CapturedDelta::ReplayRetractRelationsByIds {
588                    from_id: from_id.to_string(),
589                    to_id: to_id.to_string(),
590                    selector,
591                });
592            }
593            GraphDeltaResult::EdgesRemoved(removed)
594        }
595        GraphDelta::ReplayAppendTraversalByIds {
596            from_id,
597            to_id,
598            trigger,
599            timestamp_ms,
600        } => {
601            let appended =
602                graph.replay_append_traversal_by_ids(from_id, to_id, trigger, timestamp_ms);
603            if appended {
604                record_captured_delta(&CapturedDelta::ReplayAppendTraversalByIds {
605                    from_id: from_id.to_string(),
606                    to_id: to_id.to_string(),
607                    trigger,
608                    timestamp_ms,
609                });
610            }
611            GraphDeltaResult::TraversalAppended(appended)
612        }
613        GraphDelta::RetractRelations { from, to, selector } => {
614            let from_id = graph.get_node(from).map(|node| node.id);
615            let to_id = graph.get_node(to).map(|node| node.id);
616            let removed = graph.retract_relations(from, to, selector);
617            if removed > 0
618                && let (Some(from_id), Some(to_id)) = (from_id, to_id)
619            {
620                record_captured_delta(&CapturedDelta::ReplayRetractRelationsByIds {
621                    from_id: from_id.to_string(),
622                    to_id: to_id.to_string(),
623                    selector,
624                });
625            }
626            GraphDeltaResult::EdgesRemoved(removed)
627        }
628        GraphDelta::AppendTraversal {
629            from,
630            to,
631            trigger,
632            timestamp_ms,
633        } => {
634            let from_id = graph.get_node(from).map(|node| node.id);
635            let to_id = graph.get_node(to).map(|node| node.id);
636            let appended = graph.append_traversal(from, to, trigger, timestamp_ms);
637            if appended
638                && let (Some(from_id), Some(to_id)) = (from_id, to_id)
639                && let Some(traversal) = graph
640                    .find_edge_key(from, to)
641                    .and_then(|edge| graph.get_edge(edge))
642                    .and_then(|payload| payload.traversals().last())
643                    .copied()
644            {
645                record_captured_delta(&CapturedDelta::ReplayAppendTraversalByIds {
646                    from_id: from_id.to_string(),
647                    to_id: to_id.to_string(),
648                    trigger: traversal.trigger,
649                    timestamp_ms: traversal.timestamp_ms,
650                });
651            }
652            GraphDeltaResult::TraversalAppended(appended)
653        }
654        GraphDelta::ReplaySetNodeTitleById { node_id, title } => {
655            let updated = graph
656                .get_node_key_by_id(node_id)
657                .is_some_and(|key| graph.set_node_title(key, title.clone()));
658            if updated {
659                record_captured_delta(&CapturedDelta::ReplaySetNodeTitleById {
660                    node_id: node_id.to_string(),
661                    title,
662                });
663            }
664            GraphDeltaResult::NodeMetadataUpdated(updated)
665        }
666        GraphDelta::SetNodeTitle { key, title } => {
667            let node_id = graph.get_node(key).map(|node| node.id);
668            let capture_title = title.clone();
669            let updated = graph.set_node_title(key, title);
670            if updated && let Some(node_id) = node_id {
671                record_captured_delta(&CapturedDelta::ReplaySetNodeTitleById {
672                    node_id: node_id.to_string(),
673                    title: capture_title,
674                });
675            }
676            GraphDeltaResult::NodeMetadataUpdated(updated)
677        }
678        GraphDelta::ReplaySetNodeUrlById { node_id, new_url } => {
679            let updated = graph
680                .get_node_key_by_id(node_id)
681                .and_then(|key| graph.update_node_url(key, new_url.clone()));
682            if updated.is_some() {
683                record_captured_delta(&CapturedDelta::ReplaySetNodeUrlById {
684                    node_id: node_id.to_string(),
685                    new_url,
686                });
687            }
688            GraphDeltaResult::NodeUrlUpdated(updated)
689        }
690        GraphDelta::SetNodeUrl { key, new_url } => {
691            let node_id = graph.get_node(key).map(|node| node.id);
692            let capture_url = new_url.clone();
693            let updated = graph.update_node_url(key, new_url);
694            if updated.is_some()
695                && let Some(node_id) = node_id
696            {
697                record_captured_delta(&CapturedDelta::ReplaySetNodeUrlById {
698                    node_id: node_id.to_string(),
699                    new_url: capture_url,
700                });
701            }
702            GraphDeltaResult::NodeUrlUpdated(updated)
703        }
704        GraphDelta::ReplaySetNodeImageById {
705            node_id,
706            role,
707            image,
708        } => {
709            let updated = graph
710                .get_node_key_by_id(node_id)
711                .is_some_and(|key| graph.set_node_image(key, role, image));
712            if updated {
713                record_captured_delta(&CapturedDelta::ReplaySetNodeImageById {
714                    node_id: node_id.to_string(),
715                    role,
716                    image,
717                });
718            }
719            GraphDeltaResult::NodeMetadataUpdated(updated)
720        }
721        GraphDelta::SetNodeImage { key, role, image } => {
722            let node_id = graph.get_node(key).map(|node| node.id);
723            let updated = graph.set_node_image(key, role, image);
724            if updated && let Some(node_id) = node_id {
725                record_captured_delta(&CapturedDelta::ReplaySetNodeImageById {
726                    node_id: node_id.to_string(),
727                    role,
728                    image,
729                });
730            }
731            GraphDeltaResult::NodeMetadataUpdated(updated)
732        }
733        GraphDelta::ReplaySetNodeMimeHintById { node_id, mime_hint } => {
734            let updated = graph
735                .get_node_key_by_id(node_id)
736                .is_some_and(|key| graph.set_node_mime_hint(key, mime_hint.clone()));
737            if updated {
738                record_captured_delta(&CapturedDelta::ReplaySetNodeMimeHintById {
739                    node_id: node_id.to_string(),
740                    mime_hint,
741                });
742            }
743            GraphDeltaResult::NodeMetadataUpdated(updated)
744        }
745        GraphDelta::SetNodeMimeHint { key, mime_hint } => {
746            let node_id = graph.get_node(key).map(|node| node.id);
747            let capture_mime_hint = mime_hint.clone();
748            let updated = graph.set_node_mime_hint(key, mime_hint);
749            if updated && let Some(node_id) = node_id {
750                record_captured_delta(&CapturedDelta::ReplaySetNodeMimeHintById {
751                    node_id: node_id.to_string(),
752                    mime_hint: capture_mime_hint,
753                });
754            }
755            GraphDeltaResult::NodeMetadataUpdated(updated)
756        }
757        GraphDelta::ReplaySetNodeNestedById { node_id, nested } => {
758            let log = nested.clone().map(codicil::LogId::new);
759            let updated = graph
760                .get_node_key_by_id(node_id)
761                .is_some_and(|key| graph.set_node_nested(key, log.clone()));
762            if updated {
763                record_captured_delta(&CapturedDelta::ReplaySetNodeNestedById {
764                    node_id: node_id.to_string(),
765                    nested,
766                });
767            }
768            GraphDeltaResult::NodeMetadataUpdated(updated)
769        }
770        GraphDelta::SetNodeNested { key, nested } => {
771            let node_id = graph.get_node(key).map(|node| node.id);
772            let capture_nested = nested.as_ref().map(|log| log.as_str().to_string());
773            let updated = graph.set_node_nested(key, nested);
774            if updated && let Some(node_id) = node_id {
775                record_captured_delta(&CapturedDelta::ReplaySetNodeNestedById {
776                    node_id: node_id.to_string(),
777                    nested: capture_nested,
778                });
779            }
780            GraphDeltaResult::NodeMetadataUpdated(updated)
781        }
782        GraphDelta::ReplaySetNodePinnedById { node_id, is_pinned } => {
783            let updated = graph
784                .get_node_key_by_id(node_id)
785                .is_some_and(|key| graph.set_node_pinned(key, is_pinned));
786            if updated {
787                record_captured_delta(&CapturedDelta::ReplaySetNodePinnedById {
788                    node_id: node_id.to_string(),
789                    is_pinned,
790                });
791            }
792            GraphDeltaResult::NodeMetadataUpdated(updated)
793        }
794        GraphDelta::SetNodePinned { key, is_pinned } => {
795            let node_id = graph.get_node(key).map(|node| node.id);
796            let updated = graph.set_node_pinned(key, is_pinned);
797            if updated && let Some(node_id) = node_id {
798                record_captured_delta(&CapturedDelta::ReplaySetNodePinnedById {
799                    node_id: node_id.to_string(),
800                    is_pinned,
801                });
802            }
803            GraphDeltaResult::NodeMetadataUpdated(updated)
804        }
805        GraphDelta::ReplaySetNodeFacetById {
806            node_id,
807            facet,
808            value,
809        } => {
810            let updated = graph
811                .get_node_key_by_id(node_id)
812                .is_some_and(|key| set_node_facet(graph, key, &facet, value.clone()));
813            if updated {
814                record_captured_delta(&CapturedDelta::ReplaySetNodeFacetById {
815                    node_id: node_id.to_string(),
816                    facet,
817                    value_json: serde_json::to_string(&value)
818                        .expect("a graph facet value always serializes"),
819                });
820            }
821            GraphDeltaResult::NodeMetadataUpdated(updated)
822        }
823        GraphDelta::SetNodeFacet { key, facet, value } => {
824            let node_id = graph.get_node(key).map(|node| node.id);
825            let capture_value = value.clone();
826            let updated = set_node_facet(graph, key, &facet, value);
827            if updated && let Some(node_id) = node_id {
828                record_captured_delta(&CapturedDelta::ReplaySetNodeFacetById {
829                    node_id: node_id.to_string(),
830                    facet,
831                    value_json: serde_json::to_string(&capture_value)
832                        .expect("a graph facet value always serializes"),
833                });
834            }
835            GraphDeltaResult::NodeMetadataUpdated(updated)
836        }
837        GraphDelta::ReplayRemoveNodeFacetById { node_id, facet } => {
838            let updated = graph
839                .get_node_key_by_id(node_id)
840                .is_some_and(|key| remove_node_facet(graph, key, &facet));
841            if updated {
842                record_captured_delta(&CapturedDelta::ReplayRemoveNodeFacetById {
843                    node_id: node_id.to_string(),
844                    facet,
845                });
846            }
847            GraphDeltaResult::NodeMetadataUpdated(updated)
848        }
849        GraphDelta::RemoveNodeFacet { key, facet } => {
850            let node_id = graph.get_node(key).map(|node| node.id);
851            let updated = remove_node_facet(graph, key, &facet);
852            if updated && let Some(node_id) = node_id {
853                record_captured_delta(&CapturedDelta::ReplayRemoveNodeFacetById {
854                    node_id: node_id.to_string(),
855                    facet,
856                });
857            }
858            GraphDeltaResult::NodeMetadataUpdated(updated)
859        }
860        GraphDelta::ReplayAppendFrameLayoutHintById { node_id, hint } => {
861            let updated = graph
862                .get_node_key_by_id(node_id)
863                .is_some_and(|key| graph.append_frame_layout_hint(key, hint.clone()));
864            if updated {
865                record_captured_delta(&CapturedDelta::ReplayAppendFrameLayoutHintById {
866                    node_id: node_id.to_string(),
867                    hint,
868                });
869            }
870            GraphDeltaResult::NodeMetadataUpdated(updated)
871        }
872        GraphDelta::AppendFrameLayoutHint { key, hint } => {
873            let node_id = graph.get_node(key).map(|node| node.id);
874            let capture_hint = hint.clone();
875            let updated = graph.append_frame_layout_hint(key, hint);
876            if updated && let Some(node_id) = node_id {
877                record_captured_delta(&CapturedDelta::ReplayAppendFrameLayoutHintById {
878                    node_id: node_id.to_string(),
879                    hint: capture_hint,
880                });
881            }
882            GraphDeltaResult::NodeMetadataUpdated(updated)
883        }
884        GraphDelta::ReplayRemoveFrameLayoutHintById {
885            node_id,
886            hint_index,
887        } => {
888            let updated = graph
889                .get_node_key_by_id(node_id)
890                .is_some_and(|key| graph.remove_frame_layout_hint_at(key, hint_index));
891            if updated {
892                record_captured_delta(&CapturedDelta::ReplayRemoveFrameLayoutHintById {
893                    node_id: node_id.to_string(),
894                    hint_index,
895                });
896            }
897            GraphDeltaResult::NodeMetadataUpdated(updated)
898        }
899        GraphDelta::RemoveFrameLayoutHint { key, hint_index } => {
900            let node_id = graph.get_node(key).map(|node| node.id);
901            let updated = graph.remove_frame_layout_hint_at(key, hint_index);
902            if updated && let Some(node_id) = node_id {
903                record_captured_delta(&CapturedDelta::ReplayRemoveFrameLayoutHintById {
904                    node_id: node_id.to_string(),
905                    hint_index,
906                });
907            }
908            GraphDeltaResult::NodeMetadataUpdated(updated)
909        }
910        GraphDelta::ReplayMoveFrameLayoutHintById {
911            node_id,
912            from_index,
913            to_index,
914        } => {
915            let updated = graph
916                .get_node_key_by_id(node_id)
917                .is_some_and(|key| graph.move_frame_layout_hint(key, from_index, to_index));
918            if updated {
919                record_captured_delta(&CapturedDelta::ReplayMoveFrameLayoutHintById {
920                    node_id: node_id.to_string(),
921                    from_index,
922                    to_index,
923                });
924            }
925            GraphDeltaResult::NodeMetadataUpdated(updated)
926        }
927        GraphDelta::MoveFrameLayoutHint {
928            key,
929            from_index,
930            to_index,
931        } => {
932            let node_id = graph.get_node(key).map(|node| node.id);
933            let updated = graph.move_frame_layout_hint(key, from_index, to_index);
934            if updated && let Some(node_id) = node_id {
935                record_captured_delta(&CapturedDelta::ReplayMoveFrameLayoutHintById {
936                    node_id: node_id.to_string(),
937                    from_index,
938                    to_index,
939                });
940            }
941            GraphDeltaResult::NodeMetadataUpdated(updated)
942        }
943        GraphDelta::ReplaySetFrameSplitOfferSuppressedById {
944            node_id,
945            suppressed,
946        } => {
947            let updated = graph
948                .get_node_key_by_id(node_id)
949                .is_some_and(|key| graph.set_frame_split_offer_suppressed(key, suppressed));
950            if updated {
951                record_captured_delta(&CapturedDelta::ReplaySetFrameSplitOfferSuppressedById {
952                    node_id: node_id.to_string(),
953                    suppressed,
954                });
955            }
956            GraphDeltaResult::NodeMetadataUpdated(updated)
957        }
958        GraphDelta::SetFrameSplitOfferSuppressed { key, suppressed } => {
959            let node_id = graph.get_node(key).map(|node| node.id);
960            let updated = graph.set_frame_split_offer_suppressed(key, suppressed);
961            if updated && let Some(node_id) = node_id {
962                record_captured_delta(&CapturedDelta::ReplaySetFrameSplitOfferSuppressedById {
963                    node_id: node_id.to_string(),
964                    suppressed,
965                });
966            }
967            GraphDeltaResult::NodeMetadataUpdated(updated)
968        }
969        GraphDelta::ReplayUpdateNodeHistoryById {
970            node_id,
971            entries,
972            current_index,
973        } => {
974            let updated = graph.get_node_key_by_id(node_id).is_some_and(|key| {
975                graph.set_node_history_state(key, entries.clone(), current_index)
976            });
977            if updated {
978                record_captured_delta(&CapturedDelta::ReplayUpdateNodeHistoryById {
979                    node_id: node_id.to_string(),
980                    entries,
981                    current_index,
982                });
983            }
984            GraphDeltaResult::NodeMetadataUpdated(updated)
985        }
986        GraphDelta::UpdateNodeHistory {
987            key,
988            entries,
989            current_index,
990        } => {
991            let node_id = graph.get_node(key).map(|node| node.id);
992            let capture_entries = entries.clone();
993            let updated = graph.set_node_history_state(key, entries, current_index);
994            if updated && let Some(node_id) = node_id {
995                record_captured_delta(&CapturedDelta::ReplayUpdateNodeHistoryById {
996                    node_id: node_id.to_string(),
997                    entries: capture_entries,
998                    current_index,
999                });
1000            }
1001            GraphDeltaResult::NodeMetadataUpdated(updated)
1002        }
1003        GraphDelta::ReplaySetImportRecords { import_records } => {
1004            let changed = graph.set_import_records(import_records);
1005            if changed {
1006                capture_resolved_import_records(graph);
1007            }
1008            GraphDeltaResult::ImportRecordsUpdated(changed)
1009        }
1010        GraphDelta::ReplayTouchNodeLastVisitedById {
1011            node_id,
1012            timestamp_ms,
1013        } => {
1014            let updated = graph
1015                .get_node_key_by_id(node_id)
1016                .is_some_and(|key| graph.set_node_last_visited_at_ms(key, timestamp_ms));
1017            if updated {
1018                record_captured_delta(&CapturedDelta::ReplayTouchNodeLastVisitedById {
1019                    node_id: node_id.to_string(),
1020                    timestamp_ms,
1021                });
1022            }
1023            GraphDeltaResult::NodeMetadataUpdated(updated)
1024        }
1025        GraphDelta::NavigateNode { key, url } => {
1026            let Some(node_id) = graph.get_node(key).map(|node| node.id) else {
1027                return GraphDeltaResult::Applied;
1028            };
1029            let timestamp_ms = Graph::epoch_ms();
1030            graph
1031                .nav
1032                .record_visit(node_id, &url, TransitionKind::UrlTyped, timestamp_ms);
1033            let last_session_visited = graph.current_session;
1034            graph.set_node_last_session_visited(key, last_session_visited);
1035            let _ = graph.update_node_url(key, url.clone());
1036            record_captured_delta(&CapturedDelta::ReplayNavigateNodeById {
1037                node_id: node_id.to_string(),
1038                url,
1039                transition: TransitionKind::UrlTyped,
1040                timestamp_ms,
1041                last_session_visited,
1042            });
1043            GraphDeltaResult::Applied
1044        }
1045        GraphDelta::BranchHistory { child, parent } => {
1046            if let (Some(child_id), Some(parent_id)) = (
1047                graph.get_node(child).map(|node| node.id),
1048                graph.get_node(parent).map(|node| node.id),
1049            ) {
1050                graph.nav.spawn(child_id, parent_id);
1051                record_captured_delta(&CapturedDelta::ReplayBranchHistoryByIds {
1052                    child_id: child_id.to_string(),
1053                    parent_id: parent_id.to_string(),
1054                });
1055            }
1056            GraphDeltaResult::Applied
1057        }
1058        GraphDelta::NodeHistoryBack { key } => {
1059            let Some(node_id) = graph.get_node(key).map(|node| node.id) else {
1060                return GraphDeltaResult::HistoryStepped(None);
1061            };
1062            let timestamp_ms = Graph::epoch_ms();
1063            let stepped = graph.nav.back(node_id, timestamp_ms);
1064            if let Some(url) = stepped.clone() {
1065                let _ = graph.update_node_url(key, url);
1066                record_captured_delta(&CapturedDelta::ReplayNodeHistoryBackById {
1067                    node_id: node_id.to_string(),
1068                    timestamp_ms,
1069                });
1070            }
1071            GraphDeltaResult::HistoryStepped(stepped)
1072        }
1073        GraphDelta::NodeHistoryForward { key } => {
1074            let Some(node_id) = graph.get_node(key).map(|node| node.id) else {
1075                return GraphDeltaResult::HistoryStepped(None);
1076            };
1077            let timestamp_ms = Graph::epoch_ms();
1078            let stepped = graph.nav.forward(node_id, timestamp_ms);
1079            if let Some(url) = stepped.clone() {
1080                let _ = graph.update_node_url(key, url);
1081                record_captured_delta(&CapturedDelta::ReplayNodeHistoryForwardById {
1082                    node_id: node_id.to_string(),
1083                    timestamp_ms,
1084                });
1085            }
1086            GraphDeltaResult::HistoryStepped(stepped)
1087        }
1088        GraphDelta::ReplayInsertNodeTagById { node_id, tag } => {
1089            let updated = graph
1090                .get_node_key_by_id(node_id)
1091                .is_some_and(|key| graph.insert_node_tag(key, tag.clone()));
1092            if updated {
1093                record_captured_delta(&CapturedDelta::ReplayInsertNodeTagById {
1094                    node_id: node_id.to_string(),
1095                    tag,
1096                });
1097            }
1098            GraphDeltaResult::NodeMetadataUpdated(updated)
1099        }
1100        GraphDelta::InsertNodeTag { key, tag } => {
1101            let node_id = graph.get_node(key).map(|node| node.id);
1102            let capture_tag = tag.clone();
1103            let updated = graph.insert_node_tag(key, tag);
1104            if updated && let Some(node_id) = node_id {
1105                record_captured_delta(&CapturedDelta::ReplayInsertNodeTagById {
1106                    node_id: node_id.to_string(),
1107                    tag: capture_tag,
1108                });
1109            }
1110            GraphDeltaResult::NodeMetadataUpdated(updated)
1111        }
1112        GraphDelta::ReplayRemoveNodeTagById { node_id, tag } => {
1113            let updated = graph
1114                .get_node_key_by_id(node_id)
1115                .is_some_and(|key| graph.remove_node_tag(key, &tag));
1116            if updated {
1117                record_captured_delta(&CapturedDelta::ReplayRemoveNodeTagById {
1118                    node_id: node_id.to_string(),
1119                    tag,
1120                });
1121            }
1122            GraphDeltaResult::NodeMetadataUpdated(updated)
1123        }
1124        GraphDelta::RemoveNodeTag { key, tag } => {
1125            let node_id = graph.get_node(key).map(|node| node.id);
1126            let updated = graph.remove_node_tag(key, &tag);
1127            if updated && let Some(node_id) = node_id {
1128                record_captured_delta(&CapturedDelta::ReplayRemoveNodeTagById {
1129                    node_id: node_id.to_string(),
1130                    tag,
1131                });
1132            }
1133            GraphDeltaResult::NodeMetadataUpdated(updated)
1134        }
1135        GraphDelta::ReplaySetNodeBodyById { node_id, body } => {
1136            let updated = graph
1137                .get_node_key_by_id(node_id)
1138                .is_some_and(|key| graph.set_node_body(key, body.clone()));
1139            if updated {
1140                record_captured_delta(&CapturedDelta::ReplaySetNodeBodyById {
1141                    node_id: node_id.to_string(),
1142                    body,
1143                });
1144            }
1145            GraphDeltaResult::NodeMetadataUpdated(updated)
1146        }
1147        GraphDelta::SetNodeBody { key, body } => {
1148            let node_id = graph.get_node(key).map(|node| node.id);
1149            let capture_body = body.clone();
1150            let updated = graph.set_node_body(key, body);
1151            if updated && let Some(node_id) = node_id {
1152                record_captured_delta(&CapturedDelta::ReplaySetNodeBodyById {
1153                    node_id: node_id.to_string(),
1154                    body: capture_body,
1155                });
1156            }
1157            GraphDeltaResult::NodeMetadataUpdated(updated)
1158        }
1159        GraphDelta::ReplayNavigateNodeById {
1160            node_id,
1161            url,
1162            transition,
1163            timestamp_ms,
1164            last_session_visited,
1165        } => {
1166            let applied = graph.get_node_key_by_id(node_id).is_some_and(|key| {
1167                graph
1168                    .nav
1169                    .record_visit(node_id, &url, transition, timestamp_ms);
1170                graph.set_node_last_session_visited(key, last_session_visited);
1171                let _ = graph.update_node_url(key, url.clone());
1172                true
1173            });
1174            if applied {
1175                record_captured_delta(&CapturedDelta::ReplayNavigateNodeById {
1176                    node_id: node_id.to_string(),
1177                    url,
1178                    transition,
1179                    timestamp_ms,
1180                    last_session_visited,
1181                });
1182            }
1183            GraphDeltaResult::Applied
1184        }
1185        GraphDelta::ReplayBranchHistoryByIds {
1186            child_id,
1187            parent_id,
1188        } => {
1189            let applied = match (
1190                graph.get_node_key_by_id(child_id),
1191                graph.get_node_key_by_id(parent_id),
1192            ) {
1193                (Some(_child), Some(_parent)) => {
1194                    graph.nav.spawn(child_id, parent_id);
1195                    true
1196                }
1197                _ => false,
1198            };
1199            if applied {
1200                record_captured_delta(&CapturedDelta::ReplayBranchHistoryByIds {
1201                    child_id: child_id.to_string(),
1202                    parent_id: parent_id.to_string(),
1203                });
1204            }
1205            GraphDeltaResult::Applied
1206        }
1207        GraphDelta::ReplayNodeHistoryBackById {
1208            node_id,
1209            timestamp_ms,
1210        } => {
1211            let stepped = graph.get_node_key_by_id(node_id).and_then(|key| {
1212                let url = graph.nav.back(node_id, timestamp_ms)?;
1213                let _ = graph.update_node_url(key, url.clone());
1214                Some(url)
1215            });
1216            if stepped.is_some() {
1217                record_captured_delta(&CapturedDelta::ReplayNodeHistoryBackById {
1218                    node_id: node_id.to_string(),
1219                    timestamp_ms,
1220                });
1221            }
1222            GraphDeltaResult::HistoryStepped(stepped)
1223        }
1224        GraphDelta::ReplayNodeHistoryForwardById {
1225            node_id,
1226            timestamp_ms,
1227        } => {
1228            let stepped = graph.get_node_key_by_id(node_id).and_then(|key| {
1229                let url = graph.nav.forward(node_id, timestamp_ms)?;
1230                let _ = graph.update_node_url(key, url.clone());
1231                Some(url)
1232            });
1233            if stepped.is_some() {
1234                record_captured_delta(&CapturedDelta::ReplayNodeHistoryForwardById {
1235                    node_id: node_id.to_string(),
1236                    timestamp_ms,
1237                });
1238            }
1239            GraphDeltaResult::HistoryStepped(stepped)
1240        }
1241        GraphDelta::ReplayAppendNodePropertyById { node_id, property } => {
1242            let updated = graph
1243                .get_node_key_by_id(node_id)
1244                .is_some_and(|key| graph.append_node_property(key, property.clone()));
1245            if updated {
1246                record_captured_delta(&CapturedDelta::ReplayAppendNodePropertyById {
1247                    node_id: node_id.to_string(),
1248                    property,
1249                });
1250            }
1251            GraphDeltaResult::NodeMetadataUpdated(updated)
1252        }
1253        GraphDelta::AppendNodeProperty { key, property } => {
1254            let node_id = graph.get_node(key).map(|node| node.id);
1255            let capture_property = property.clone();
1256            let updated = graph.append_node_property(key, property);
1257            if updated && let Some(node_id) = node_id {
1258                record_captured_delta(&CapturedDelta::ReplayAppendNodePropertyById {
1259                    node_id: node_id.to_string(),
1260                    property: capture_property,
1261                });
1262            }
1263            GraphDeltaResult::NodeMetadataUpdated(updated)
1264        }
1265        GraphDelta::ReplayAddNodeClassificationById {
1266            node_id,
1267            classification,
1268        } => {
1269            let updated = graph
1270                .get_node_key_by_id(node_id)
1271                .is_some_and(|key| graph.add_node_classification(key, classification.clone()));
1272            if updated {
1273                record_captured_delta(&CapturedDelta::ReplayAddNodeClassificationById {
1274                    node_id: node_id.to_string(),
1275                    classification,
1276                });
1277            }
1278            GraphDeltaResult::NodeMetadataUpdated(updated)
1279        }
1280        GraphDelta::AddNodeClassification {
1281            key,
1282            classification,
1283        } => {
1284            let node_id = graph.get_node(key).map(|node| node.id);
1285            let capture_classification = classification.clone();
1286            let updated = graph.add_node_classification(key, classification);
1287            if updated && let Some(node_id) = node_id {
1288                record_captured_delta(&CapturedDelta::ReplayAddNodeClassificationById {
1289                    node_id: node_id.to_string(),
1290                    classification: capture_classification,
1291                });
1292            }
1293            GraphDeltaResult::NodeMetadataUpdated(updated)
1294        }
1295        GraphDelta::ReplayRemoveNodeClassificationById {
1296            node_id,
1297            scheme,
1298            value,
1299        } => {
1300            let updated = graph
1301                .get_node_key_by_id(node_id)
1302                .is_some_and(|key| graph.remove_node_classification(key, &scheme, &value));
1303            if updated {
1304                record_captured_delta(&CapturedDelta::ReplayRemoveNodeClassificationById {
1305                    node_id: node_id.to_string(),
1306                    scheme,
1307                    value,
1308                });
1309            }
1310            GraphDeltaResult::NodeMetadataUpdated(updated)
1311        }
1312        GraphDelta::RemoveNodeClassification { key, scheme, value } => {
1313            let node_id = graph.get_node(key).map(|node| node.id);
1314            let capture_scheme = scheme.clone();
1315            let capture_value = value.clone();
1316            let updated = graph.remove_node_classification(key, &scheme, &value);
1317            if updated && let Some(node_id) = node_id {
1318                record_captured_delta(&CapturedDelta::ReplayRemoveNodeClassificationById {
1319                    node_id: node_id.to_string(),
1320                    scheme: capture_scheme,
1321                    value: capture_value,
1322                });
1323            }
1324            GraphDeltaResult::NodeMetadataUpdated(updated)
1325        }
1326        GraphDelta::ReplaySetNodeClassificationStatusById {
1327            node_id,
1328            scheme,
1329            value,
1330            status,
1331        } => {
1332            let updated = graph.get_node_key_by_id(node_id).is_some_and(|key| {
1333                graph.set_node_classification_status(key, &scheme, &value, status.clone())
1334            });
1335            if updated {
1336                record_captured_delta(&CapturedDelta::ReplaySetNodeClassificationStatusById {
1337                    node_id: node_id.to_string(),
1338                    scheme,
1339                    value,
1340                    status,
1341                });
1342            }
1343            GraphDeltaResult::NodeMetadataUpdated(updated)
1344        }
1345        GraphDelta::SetNodeClassificationStatus {
1346            key,
1347            scheme,
1348            value,
1349            status,
1350        } => {
1351            let node_id = graph.get_node(key).map(|node| node.id);
1352            let capture_scheme = scheme.clone();
1353            let capture_value = value.clone();
1354            let capture_status = status.clone();
1355            let updated = graph.set_node_classification_status(key, &scheme, &value, status);
1356            if updated && let Some(node_id) = node_id {
1357                record_captured_delta(&CapturedDelta::ReplaySetNodeClassificationStatusById {
1358                    node_id: node_id.to_string(),
1359                    scheme: capture_scheme,
1360                    value: capture_value,
1361                    status: capture_status,
1362                });
1363            }
1364            GraphDeltaResult::NodeMetadataUpdated(updated)
1365        }
1366        GraphDelta::ReplaySetNodePrimaryClassificationById {
1367            node_id,
1368            scheme,
1369            value,
1370        } => {
1371            let updated = graph
1372                .get_node_key_by_id(node_id)
1373                .is_some_and(|key| graph.set_node_primary_classification(key, &scheme, &value));
1374            if updated {
1375                record_captured_delta(&CapturedDelta::ReplaySetNodePrimaryClassificationById {
1376                    node_id: node_id.to_string(),
1377                    scheme,
1378                    value,
1379                });
1380            }
1381            GraphDeltaResult::NodeMetadataUpdated(updated)
1382        }
1383        GraphDelta::SetNodePrimaryClassification { key, scheme, value } => {
1384            let node_id = graph.get_node(key).map(|node| node.id);
1385            let capture_scheme = scheme.clone();
1386            let capture_value = value.clone();
1387            let updated = graph.set_node_primary_classification(key, &scheme, &value);
1388            if updated && let Some(node_id) = node_id {
1389                record_captured_delta(&CapturedDelta::ReplaySetNodePrimaryClassificationById {
1390                    node_id: node_id.to_string(),
1391                    scheme: capture_scheme,
1392                    value: capture_value,
1393                });
1394            }
1395            GraphDeltaResult::NodeMetadataUpdated(updated)
1396        }
1397        GraphDelta::ReplayRecordNodeDerivationById {
1398            node_id,
1399            derivation,
1400        } => {
1401            let updated = graph
1402                .get_node_key_by_id(node_id)
1403                .is_some_and(|key| graph.record_derivation(key, derivation.clone()));
1404            if updated {
1405                record_captured_delta(&CapturedDelta::ReplayRecordNodeDerivationById {
1406                    node_id: node_id.to_string(),
1407                    derivation,
1408                });
1409            }
1410            GraphDeltaResult::NodeMetadataUpdated(updated)
1411        }
1412        GraphDelta::RecordNodeDerivation { key, derivation } => {
1413            let node_id = graph.get_node(key).map(|node| node.id);
1414            let capture_derivation = derivation.clone();
1415            let updated = graph.record_derivation(key, derivation);
1416            if updated && let Some(node_id) = node_id {
1417                record_captured_delta(&CapturedDelta::ReplayRecordNodeDerivationById {
1418                    node_id: node_id.to_string(),
1419                    derivation: capture_derivation,
1420                });
1421            }
1422            GraphDeltaResult::NodeMetadataUpdated(updated)
1423        }
1424        GraphDelta::ReplaySetNodeTagIconOverrideById { node_id, tag, icon } => {
1425            let updated = graph
1426                .get_node_key_by_id(node_id)
1427                .is_some_and(|key| graph.set_node_tag_icon_override(key, &tag, icon.clone()));
1428            if updated {
1429                record_captured_delta(&CapturedDelta::ReplaySetNodeTagIconOverrideById {
1430                    node_id: node_id.to_string(),
1431                    tag,
1432                    icon,
1433                });
1434            }
1435            GraphDeltaResult::NodeMetadataUpdated(updated)
1436        }
1437        GraphDelta::SetNodeTagIconOverride { key, tag, icon } => {
1438            let node_id = graph.get_node(key).map(|node| node.id);
1439            let capture_tag = tag.clone();
1440            let capture_icon = icon.clone();
1441            let updated = graph.set_node_tag_icon_override(key, &tag, icon);
1442            if updated && let Some(node_id) = node_id {
1443                record_captured_delta(&CapturedDelta::ReplaySetNodeTagIconOverrideById {
1444                    node_id: node_id.to_string(),
1445                    tag: capture_tag,
1446                    icon: capture_icon,
1447                });
1448            }
1449            GraphDeltaResult::NodeMetadataUpdated(updated)
1450        }
1451        GraphDelta::ReplaySetEdgeSemanticPredicateByIds {
1452            from_id,
1453            to_id,
1454            predicate,
1455        } => {
1456            let updated =
1457                graph.replay_set_edge_semantic_predicate_by_ids(from_id, to_id, predicate.clone());
1458            if updated {
1459                record_captured_delta(&CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
1460                    from_id: from_id.to_string(),
1461                    to_id: to_id.to_string(),
1462                    predicate,
1463                });
1464            }
1465            GraphDeltaResult::NodeMetadataUpdated(updated)
1466        }
1467        GraphDelta::ReplayAssertSemanticPredicateByIds {
1468            from_id,
1469            to_id,
1470            predicate,
1471        } => {
1472            let edge =
1473                graph.replay_assert_semantic_predicate_by_ids(from_id, to_id, predicate.clone());
1474            if edge.is_some() {
1475                record_captured_delta(&CapturedDelta::ReplayAssertSemanticPredicateByIds {
1476                    from_id: from_id.to_string(),
1477                    to_id: to_id.to_string(),
1478                    predicate,
1479                });
1480            }
1481            GraphDeltaResult::EdgeAdded(edge)
1482        }
1483        GraphDelta::SetEdgeSemanticPredicate { edge, predicate } => {
1484            let endpoints = graph
1485                .inner
1486                .inner()
1487                .edge_endpoints(edge)
1488                .and_then(|(from, to)| Some((graph.get_node(from)?.id, graph.get_node(to)?.id)));
1489            let capture_predicate = predicate.clone();
1490            let updated = graph.set_edge_semantic_predicate(edge, predicate);
1491            if updated && let Some((from_id, to_id)) = endpoints {
1492                record_captured_delta(&CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
1493                    from_id: from_id.to_string(),
1494                    to_id: to_id.to_string(),
1495                    predicate: capture_predicate,
1496                });
1497            }
1498            GraphDeltaResult::NodeMetadataUpdated(updated)
1499        }
1500        GraphDelta::AssertSemanticPredicate {
1501            from,
1502            to,
1503            predicate,
1504        } => {
1505            let from_id = graph.get_node(from).map(|node| node.id);
1506            let to_id = graph.get_node(to).map(|node| node.id);
1507            let capture_predicate = predicate.clone();
1508            let edge = graph.assert_semantic_predicate(from, to, predicate);
1509            if edge.is_some()
1510                && let (Some(from_id), Some(to_id)) = (from_id, to_id)
1511            {
1512                record_captured_delta(&CapturedDelta::ReplayAssertSemanticPredicateByIds {
1513                    from_id: from_id.to_string(),
1514                    to_id: to_id.to_string(),
1515                    predicate: capture_predicate,
1516                });
1517            }
1518            GraphDeltaResult::EdgeAdded(edge)
1519        }
1520        GraphDelta::ReplayAddField { field } => {
1521            let changed = if let Some(field) = field_from_persisted(&field) {
1522                graph.add_field(field);
1523                true
1524            } else {
1525                false
1526            };
1527            if changed {
1528                record_captured_delta(&CapturedDelta::ReplayAddField { field });
1529            }
1530            GraphDeltaResult::FieldChanged(changed)
1531        }
1532        GraphDelta::ReplayRetireFieldById { field_id } => {
1533            let changed = Uuid::parse_str(&field_id)
1534                .ok()
1535                .map(FieldId::from_uuid)
1536                .is_some_and(|id| graph.retire_field(id));
1537            if changed {
1538                record_captured_delta(&CapturedDelta::ReplayRetireFieldById { field_id });
1539            }
1540            GraphDeltaResult::FieldChanged(changed)
1541        }
1542        GraphDelta::ReplayAddCoupling { coupling } => {
1543            let changed = if let Some(coupling_model) = coupling_from_persisted(&coupling) {
1544                graph.add_coupling(coupling_model);
1545                true
1546            } else {
1547                false
1548            };
1549            if changed {
1550                record_captured_delta(&CapturedDelta::ReplayAddCoupling { coupling });
1551            }
1552            GraphDeltaResult::FieldChanged(changed)
1553        }
1554        GraphDelta::ReplaySetFieldCouplingStrengthByFieldId { field_id, strength } => {
1555            let changed = Uuid::parse_str(&field_id)
1556                .ok()
1557                .map(FieldId::from_uuid)
1558                .is_some_and(|field| graph.set_field_coupling_strength(field, strength));
1559            if changed {
1560                record_captured_delta(&CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
1561                    field_id,
1562                    strength,
1563                });
1564            }
1565            GraphDeltaResult::FieldChanged(changed)
1566        }
1567        GraphDelta::ReplayActivateFieldById { field_id } => {
1568            let changed = Uuid::parse_str(&field_id)
1569                .ok()
1570                .map(FieldId::from_uuid)
1571                .is_some_and(|id| graph.activate_field(id));
1572            if changed {
1573                record_captured_delta(&CapturedDelta::ReplayActivateFieldById { field_id });
1574            }
1575            GraphDeltaResult::FieldChanged(changed)
1576        }
1577        GraphDelta::ReplayRetractCouplingById { coupling_id } => {
1578            let changed = Uuid::parse_str(&coupling_id)
1579                .ok()
1580                .map(CouplingId::from_uuid)
1581                .is_some_and(|id| graph.retract_coupling(id));
1582            if changed {
1583                record_captured_delta(&CapturedDelta::ReplayRetractCouplingById { coupling_id });
1584            }
1585            GraphDeltaResult::FieldChanged(changed)
1586        }
1587        GraphDelta::AddField { field } => {
1588            let capture_field = persisted_field_from_field(&field);
1589            graph.add_field(field);
1590            record_captured_delta(&CapturedDelta::ReplayAddField {
1591                field: capture_field,
1592            });
1593            GraphDeltaResult::FieldChanged(true)
1594        }
1595        GraphDelta::RetireField { id } => {
1596            let changed = graph.retire_field(id);
1597            if changed {
1598                record_captured_delta(&CapturedDelta::ReplayRetireFieldById {
1599                    field_id: id.as_uuid().to_string(),
1600                });
1601            }
1602            GraphDeltaResult::FieldChanged(changed)
1603        }
1604        GraphDelta::AddCoupling { coupling } => {
1605            let capture_coupling = persisted_coupling_from_coupling(&coupling);
1606            graph.add_coupling(coupling);
1607            record_captured_delta(&CapturedDelta::ReplayAddCoupling {
1608                coupling: capture_coupling,
1609            });
1610            GraphDeltaResult::FieldChanged(true)
1611        }
1612        GraphDelta::SetFieldCouplingStrength { field, strength } => {
1613            let changed = graph.set_field_coupling_strength(field, strength);
1614            if changed {
1615                record_captured_delta(&CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
1616                    field_id: field.as_uuid().to_string(),
1617                    strength,
1618                });
1619            }
1620            GraphDeltaResult::FieldChanged(changed)
1621        }
1622        GraphDelta::ActivateField { id } => {
1623            let changed = graph.activate_field(id);
1624            if changed {
1625                record_captured_delta(&CapturedDelta::ReplayActivateFieldById {
1626                    field_id: id.as_uuid().to_string(),
1627                });
1628            }
1629            GraphDeltaResult::FieldChanged(changed)
1630        }
1631        GraphDelta::RetractCoupling { id } => {
1632            let changed = graph.retract_coupling(id);
1633            if changed {
1634                record_captured_delta(&CapturedDelta::ReplayRetractCouplingById {
1635                    coupling_id: id.as_uuid().to_string(),
1636                });
1637            }
1638            GraphDeltaResult::FieldChanged(changed)
1639        }
1640        GraphDelta::SetImportRecords { import_records } => {
1641            let changed = graph.set_import_records(import_records);
1642            if changed {
1643                capture_resolved_import_records(graph);
1644            }
1645            GraphDeltaResult::ImportRecordsUpdated(changed)
1646        }
1647        GraphDelta::DeleteImportRecord { record_id } => {
1648            let changed = graph.delete_import_record(&record_id);
1649            if changed {
1650                capture_resolved_import_records(graph);
1651            }
1652            GraphDeltaResult::ImportRecordsUpdated(changed)
1653        }
1654        GraphDelta::SetImportRecordMembershipSuppressed {
1655            record_id,
1656            key,
1657            suppressed,
1658        } => {
1659            let changed =
1660                graph.set_import_record_membership_suppressed(&record_id, key, suppressed);
1661            if changed {
1662                capture_resolved_import_records(graph);
1663            }
1664            GraphDeltaResult::ImportRecordsUpdated(changed)
1665        }
1666        GraphDelta::SetNodeImportProvenance {
1667            key,
1668            import_provenance,
1669        } => {
1670            let changed = graph.set_node_import_provenance(key, import_provenance);
1671            if changed {
1672                capture_resolved_import_records(graph);
1673            }
1674            GraphDeltaResult::ImportRecordsUpdated(changed)
1675        }
1676        GraphDelta::TouchNodeLastVisited { key } => {
1677            let node_id = graph.get_node(key).map(|node| node.id);
1678            let updated = graph.touch_node_last_visited_now(key);
1679            if updated
1680                && let Some(node_id) = node_id
1681                && let Some(timestamp_ms) = graph
1682                    .node_last_visited(key)
1683                    .and_then(|visited| visited.duration_since(std::time::UNIX_EPOCH).ok())
1684                    .map(|duration| duration.as_millis() as u64)
1685            {
1686                record_captured_delta(&CapturedDelta::ReplayTouchNodeLastVisitedById {
1687                    node_id: node_id.to_string(),
1688                    timestamp_ms,
1689                });
1690            }
1691            GraphDeltaResult::NodeMetadataUpdated(updated)
1692        }
1693    }
1694}
1695
1696// --- Ergonomic wrappers (write-path migration, 2026-07-01) ---
1697//
1698// Thin constructors over [`apply_graph_delta`] for the deltas whose result the
1699// caller almost always unwraps. They keep the funnel — every one routes through
1700// `apply_graph_delta`, so a future recording hook (the event log) instruments
1701// exactly one function — while sparing hot call sites the enum-unwrap noise.
1702
1703/// Add a node (fresh random id when `id` is `None`; not available on wasm
1704/// without an explicit id) and return its key.
1705pub fn add_node(
1706    graph: &mut Graph,
1707    id: Option<Uuid>,
1708    url: String,
1709    position: Point2D<f32>,
1710) -> NodeKey {
1711    match apply_graph_delta(graph, GraphDelta::AddNode { id, url, position }) {
1712        GraphDeltaResult::NodeAdded(key) => key,
1713        other => unreachable!("AddNode returned {other:?}"),
1714    }
1715}
1716
1717/// Assert a relation between two nodes, returning the edge key (or `None` when
1718/// either endpoint is gone).
1719pub fn assert_relation(
1720    graph: &mut Graph,
1721    from: NodeKey,
1722    to: NodeKey,
1723    assertion: EdgeAssertion,
1724) -> Option<EdgeKey> {
1725    match apply_graph_delta(
1726        graph,
1727        GraphDelta::AssertRelation {
1728            from,
1729            to,
1730            assertion,
1731        },
1732    ) {
1733        GraphDeltaResult::EdgeAdded(key) => key,
1734        other => unreachable!("AssertRelation returned {other:?}"),
1735    }
1736}
1737
1738/// Assert a recognized semantic statement in a specific named-graph scope.
1739pub fn assert_semantic_relation_in_scope(
1740    graph: &mut Graph,
1741    from: NodeKey,
1742    to: NodeKey,
1743    sub_kind: SemanticSubKind,
1744    label: Option<String>,
1745    graph_scope: GraphScope,
1746) -> Option<EdgeKey> {
1747    graph.assert_semantic_relation_in_scope(from, to, sub_kind, label, graph_scope)
1748}
1749
1750/// Assert an open-predicate semantic statement in a specific named-graph scope.
1751pub fn assert_semantic_predicate_in_scope(
1752    graph: &mut Graph,
1753    from: NodeKey,
1754    to: NodeKey,
1755    predicate: String,
1756    graph_scope: GraphScope,
1757) -> Option<EdgeKey> {
1758    graph.assert_semantic_predicate_in_scope(from, to, predicate, graph_scope)
1759}
1760
1761/// Step a node back one visit in its own browse history, returning the
1762/// revealed URL (`None` at the root).
1763pub fn node_history_back(graph: &mut Graph, key: NodeKey) -> Option<String> {
1764    match apply_graph_delta(graph, GraphDelta::NodeHistoryBack { key }) {
1765        GraphDeltaResult::HistoryStepped(url) => url,
1766        other => unreachable!("NodeHistoryBack returned {other:?}"),
1767    }
1768}
1769
1770/// Step a node forward one visit in its own browse history, returning the
1771/// revealed URL (`None` at the tip).
1772pub fn node_history_forward(graph: &mut Graph, key: NodeKey) -> Option<String> {
1773    match apply_graph_delta(graph, GraphDelta::NodeHistoryForward { key }) {
1774        GraphDeltaResult::HistoryStepped(url) => url,
1775        other => unreachable!("NodeHistoryForward returned {other:?}"),
1776    }
1777}