Skip to main content

kernel/graph/
capture.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Stable-id graph-delta capture/replay helpers.
5//!
6//! This records the graph mutations that already have stable-id replay forms in
7//! [`super::apply::GraphDelta`]: add/remove node, assert/retract relation,
8//! traversal append, media writes, navigation chronology/history mutations, the
9//! lighter per-node content/presentation setters, semantic-predicate edge
10//! writes, the node-enrichment setters, import-record truth, and deterministic
11//! frame/history state setters. The broader content-mutation lane still stays
12//! separate until those writes grow stable-id replay forms of their own.
13
14use std::cell::RefCell;
15use std::sync::Arc;
16
17use chartulary::stemma::TransitionKind;
18use euclid::default::Point2D;
19use rkyv::{Archive, Deserialize, Serialize};
20use uuid::Uuid;
21
22use super::apply::{GraphDelta, apply_graph_delta};
23use super::{
24    Coupling, CouplingResponse, EdgeAssertion, Field, FieldDefinition, FieldExtent, FieldId,
25    FieldLifecycle, FrameLayoutHint, Graph, NavigationTrigger, NodeSelector, RelationSelector,
26};
27use crate::persistence::{
28    PersistedCoupling, PersistedCouplingResponse, PersistedField, PersistedFieldExtent,
29    PersistedFieldLifecycle, PersistedNodeSelector,
30};
31use crate::types::{
32    BadgeIcon, ClassificationScheme, ClassificationStatus, ImageRef, ImageRole, ImportRecord,
33    NodeClassification, NodeDerivation, NodeProperty,
34};
35
36/// The stable-id, serializable mirror of the replayable graph deltas.
37#[derive(
38    Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
39)]
40pub enum CapturedDelta {
41    ReplayAddNodeWithIdIfMissing {
42        id: String,
43        url: String,
44        position: [f32; 2],
45    },
46    ReplayAssertRelationByIds {
47        from_id: String,
48        to_id: String,
49        assertion: EdgeAssertion,
50    },
51    ReplayRemoveNodeById {
52        node_id: String,
53    },
54    ReplayRetractRelationsByIds {
55        from_id: String,
56        to_id: String,
57        selector: RelationSelector,
58    },
59    ReplayAppendTraversalByIds {
60        from_id: String,
61        to_id: String,
62        trigger: NavigationTrigger,
63        timestamp_ms: u64,
64    },
65    ReplaySetNodeTitleById {
66        node_id: String,
67        title: String,
68    },
69    ReplaySetNodeUrlById {
70        node_id: String,
71        new_url: String,
72    },
73    ReplaySetNodeImageById {
74        node_id: String,
75        role: ImageRole,
76        image: ImageRef,
77    },
78    // --- Pre-phase-2 inline imagery: readable, never written ---------------
79    //
80    // Journals recorded before the node-image externalization carry raw bytes
81    // in these. They are kept so an existing journal still deserializes and
82    // replays; `replay_delta` returns `None` for them, so the pixels are
83    // dropped rather than restored. That is deliberate: a preview is
84    // experience, not truth, and the next capture re-deposits it. Nothing
85    // emits these variants any more.
86    ReplaySetNodeThumbnailById {
87        node_id: String,
88        png_bytes: Vec<u8>,
89        width: u32,
90        height: u32,
91    },
92    ReplaySetNodeFaviconById {
93        node_id: String,
94        rgba: Vec<u8>,
95        width: u32,
96        height: u32,
97    },
98    ReplaySetNodeMimeHintById {
99        node_id: String,
100        mime_hint: Option<String>,
101    },
102    ReplaySetNodeNestedById {
103        node_id: String,
104        nested: Option<String>,
105    },
106    ReplaySetNodePinnedById {
107        node_id: String,
108        is_pinned: bool,
109    },
110    ReplaySetNodeFacetById {
111        node_id: String,
112        facet: String,
113        value_json: String,
114    },
115    ReplayRemoveNodeFacetById {
116        node_id: String,
117        facet: String,
118    },
119    ReplayInsertNodeTagById {
120        node_id: String,
121        tag: String,
122    },
123    ReplayRemoveNodeTagById {
124        node_id: String,
125        tag: String,
126    },
127    ReplaySetNodeBodyById {
128        node_id: String,
129        body: Option<String>,
130    },
131    ReplayNavigateNodeById {
132        node_id: String,
133        url: String,
134        transition: TransitionKind,
135        timestamp_ms: u64,
136        last_session_visited: u64,
137    },
138    ReplayBranchHistoryByIds {
139        child_id: String,
140        parent_id: String,
141    },
142    ReplayNodeHistoryBackById {
143        node_id: String,
144        timestamp_ms: u64,
145    },
146    ReplayNodeHistoryForwardById {
147        node_id: String,
148        timestamp_ms: u64,
149    },
150    ReplayAppendNodePropertyById {
151        node_id: String,
152        property: NodeProperty,
153    },
154    ReplayAddNodeClassificationById {
155        node_id: String,
156        classification: NodeClassification,
157    },
158    ReplayRemoveNodeClassificationById {
159        node_id: String,
160        scheme: ClassificationScheme,
161        value: String,
162    },
163    ReplaySetNodeClassificationStatusById {
164        node_id: String,
165        scheme: ClassificationScheme,
166        value: String,
167        status: ClassificationStatus,
168    },
169    ReplaySetNodePrimaryClassificationById {
170        node_id: String,
171        scheme: ClassificationScheme,
172        value: String,
173    },
174    ReplayRecordNodeDerivationById {
175        node_id: String,
176        derivation: NodeDerivation,
177    },
178    ReplaySetNodeTagIconOverrideById {
179        node_id: String,
180        tag: String,
181        icon: Option<BadgeIcon>,
182    },
183    ReplaySetEdgeSemanticPredicateByIds {
184        from_id: String,
185        to_id: String,
186        predicate: Option<String>,
187    },
188    ReplayAssertSemanticPredicateByIds {
189        from_id: String,
190        to_id: String,
191        predicate: String,
192    },
193    ReplayAppendFrameLayoutHintById {
194        node_id: String,
195        hint: FrameLayoutHint,
196    },
197    ReplayRemoveFrameLayoutHintById {
198        node_id: String,
199        hint_index: usize,
200    },
201    ReplayMoveFrameLayoutHintById {
202        node_id: String,
203        from_index: usize,
204        to_index: usize,
205    },
206    ReplaySetFrameSplitOfferSuppressedById {
207        node_id: String,
208        suppressed: bool,
209    },
210    ReplayUpdateNodeHistoryById {
211        node_id: String,
212        entries: Vec<String>,
213        current_index: usize,
214    },
215    ReplaySetImportRecords {
216        import_records: Vec<ImportRecord>,
217    },
218    ReplayTouchNodeLastVisitedById {
219        node_id: String,
220        timestamp_ms: u64,
221    },
222    ReplayAddField {
223        field: PersistedField,
224    },
225    ReplayRetireFieldById {
226        field_id: String,
227    },
228    ReplayAddCoupling {
229        coupling: PersistedCoupling,
230    },
231    ReplaySetFieldCouplingStrengthByFieldId {
232        field_id: String,
233        strength: f32,
234    },
235    ReplayActivateFieldById {
236        field_id: String,
237    },
238    ReplayRetractCouplingById {
239        coupling_id: String,
240    },
241}
242
243impl CapturedDelta {
244    /// The graph-kernel replay delta this captured record folds back into.
245    ///
246    /// `None` for records with no live equivalent (pre-phase-2 inline
247    /// imagery), which a replay skips.
248    pub fn replay_delta(&self) -> Option<GraphDelta> {
249        Some(match self {
250            Self::ReplayAddNodeWithIdIfMissing { id, url, position } => {
251                GraphDelta::ReplayAddNodeWithIdIfMissing {
252                    id: parse_uuid(id),
253                    url: url.clone(),
254                    position: Point2D::new(position[0], position[1]),
255                }
256            }
257            Self::ReplayAssertRelationByIds {
258                from_id,
259                to_id,
260                assertion,
261            } => GraphDelta::ReplayAssertRelationByIds {
262                from_id: parse_uuid(from_id),
263                to_id: parse_uuid(to_id),
264                assertion: assertion.clone(),
265            },
266            Self::ReplayRemoveNodeById { node_id } => GraphDelta::ReplayRemoveNodeById {
267                node_id: parse_uuid(node_id),
268            },
269            Self::ReplayRetractRelationsByIds {
270                from_id,
271                to_id,
272                selector,
273            } => GraphDelta::ReplayRetractRelationsByIds {
274                from_id: parse_uuid(from_id),
275                to_id: parse_uuid(to_id),
276                selector: *selector,
277            },
278            Self::ReplayAppendTraversalByIds {
279                from_id,
280                to_id,
281                trigger,
282                timestamp_ms,
283            } => GraphDelta::ReplayAppendTraversalByIds {
284                from_id: parse_uuid(from_id),
285                to_id: parse_uuid(to_id),
286                trigger: *trigger,
287                timestamp_ms: *timestamp_ms,
288            },
289            Self::ReplaySetNodeTitleById { node_id, title } => GraphDelta::ReplaySetNodeTitleById {
290                node_id: parse_uuid(node_id),
291                title: title.clone(),
292            },
293            Self::ReplaySetNodeUrlById { node_id, new_url } => GraphDelta::ReplaySetNodeUrlById {
294                node_id: parse_uuid(node_id),
295                new_url: new_url.clone(),
296            },
297            Self::ReplaySetNodeImageById {
298                node_id,
299                role,
300                image,
301            } => GraphDelta::ReplaySetNodeImageById {
302                node_id: parse_uuid(node_id),
303                role: *role,
304                image: *image,
305            },
306            // Legacy inline imagery has no live delta to fold into: the kernel
307            // cannot store a blob (that is async, and the store's job), so the
308            // bytes are dropped and the preview regenerates on next capture.
309            Self::ReplaySetNodeThumbnailById { .. } | Self::ReplaySetNodeFaviconById { .. } => {
310                return None;
311            }
312            Self::ReplaySetNodeMimeHintById { node_id, mime_hint } => {
313                GraphDelta::ReplaySetNodeMimeHintById {
314                    node_id: parse_uuid(node_id),
315                    mime_hint: mime_hint.clone(),
316                }
317            }
318            Self::ReplaySetNodeNestedById { node_id, nested } => {
319                GraphDelta::ReplaySetNodeNestedById {
320                    node_id: parse_uuid(node_id),
321                    nested: nested.clone(),
322                }
323            }
324            Self::ReplaySetNodePinnedById { node_id, is_pinned } => {
325                GraphDelta::ReplaySetNodePinnedById {
326                    node_id: parse_uuid(node_id),
327                    is_pinned: *is_pinned,
328                }
329            }
330            Self::ReplaySetNodeFacetById {
331                node_id,
332                facet,
333                value_json,
334            } => {
335                let value = serde_json::from_str(value_json).ok()?;
336                GraphDelta::ReplaySetNodeFacetById {
337                    node_id: parse_uuid(node_id),
338                    facet: facet.clone(),
339                    value,
340                }
341            }
342            Self::ReplayRemoveNodeFacetById { node_id, facet } => {
343                GraphDelta::ReplayRemoveNodeFacetById {
344                    node_id: parse_uuid(node_id),
345                    facet: facet.clone(),
346                }
347            }
348            Self::ReplayInsertNodeTagById { node_id, tag } => GraphDelta::ReplayInsertNodeTagById {
349                node_id: parse_uuid(node_id),
350                tag: tag.clone(),
351            },
352            Self::ReplayRemoveNodeTagById { node_id, tag } => GraphDelta::ReplayRemoveNodeTagById {
353                node_id: parse_uuid(node_id),
354                tag: tag.clone(),
355            },
356            Self::ReplaySetNodeBodyById { node_id, body } => GraphDelta::ReplaySetNodeBodyById {
357                node_id: parse_uuid(node_id),
358                body: body.clone(),
359            },
360            Self::ReplayNavigateNodeById {
361                node_id,
362                url,
363                transition,
364                timestamp_ms,
365                last_session_visited,
366            } => GraphDelta::ReplayNavigateNodeById {
367                node_id: parse_uuid(node_id),
368                url: url.clone(),
369                transition: *transition,
370                timestamp_ms: *timestamp_ms,
371                last_session_visited: *last_session_visited,
372            },
373            Self::ReplayBranchHistoryByIds {
374                child_id,
375                parent_id,
376            } => GraphDelta::ReplayBranchHistoryByIds {
377                child_id: parse_uuid(child_id),
378                parent_id: parse_uuid(parent_id),
379            },
380            Self::ReplayNodeHistoryBackById {
381                node_id,
382                timestamp_ms,
383            } => GraphDelta::ReplayNodeHistoryBackById {
384                node_id: parse_uuid(node_id),
385                timestamp_ms: *timestamp_ms,
386            },
387            Self::ReplayNodeHistoryForwardById {
388                node_id,
389                timestamp_ms,
390            } => GraphDelta::ReplayNodeHistoryForwardById {
391                node_id: parse_uuid(node_id),
392                timestamp_ms: *timestamp_ms,
393            },
394            Self::ReplayAppendNodePropertyById { node_id, property } => {
395                GraphDelta::ReplayAppendNodePropertyById {
396                    node_id: parse_uuid(node_id),
397                    property: property.clone(),
398                }
399            }
400            Self::ReplayAddNodeClassificationById {
401                node_id,
402                classification,
403            } => GraphDelta::ReplayAddNodeClassificationById {
404                node_id: parse_uuid(node_id),
405                classification: classification.clone(),
406            },
407            Self::ReplayRemoveNodeClassificationById {
408                node_id,
409                scheme,
410                value,
411            } => GraphDelta::ReplayRemoveNodeClassificationById {
412                node_id: parse_uuid(node_id),
413                scheme: scheme.clone(),
414                value: value.clone(),
415            },
416            Self::ReplaySetNodeClassificationStatusById {
417                node_id,
418                scheme,
419                value,
420                status,
421            } => GraphDelta::ReplaySetNodeClassificationStatusById {
422                node_id: parse_uuid(node_id),
423                scheme: scheme.clone(),
424                value: value.clone(),
425                status: status.clone(),
426            },
427            Self::ReplaySetNodePrimaryClassificationById {
428                node_id,
429                scheme,
430                value,
431            } => GraphDelta::ReplaySetNodePrimaryClassificationById {
432                node_id: parse_uuid(node_id),
433                scheme: scheme.clone(),
434                value: value.clone(),
435            },
436            Self::ReplayRecordNodeDerivationById {
437                node_id,
438                derivation,
439            } => GraphDelta::ReplayRecordNodeDerivationById {
440                node_id: parse_uuid(node_id),
441                derivation: derivation.clone(),
442            },
443            Self::ReplaySetNodeTagIconOverrideById { node_id, tag, icon } => {
444                GraphDelta::ReplaySetNodeTagIconOverrideById {
445                    node_id: parse_uuid(node_id),
446                    tag: tag.clone(),
447                    icon: icon.clone(),
448                }
449            }
450            Self::ReplaySetEdgeSemanticPredicateByIds {
451                from_id,
452                to_id,
453                predicate,
454            } => GraphDelta::ReplaySetEdgeSemanticPredicateByIds {
455                from_id: parse_uuid(from_id),
456                to_id: parse_uuid(to_id),
457                predicate: predicate.clone(),
458            },
459            Self::ReplayAssertSemanticPredicateByIds {
460                from_id,
461                to_id,
462                predicate,
463            } => GraphDelta::ReplayAssertSemanticPredicateByIds {
464                from_id: parse_uuid(from_id),
465                to_id: parse_uuid(to_id),
466                predicate: predicate.clone(),
467            },
468            Self::ReplayAppendFrameLayoutHintById { node_id, hint } => {
469                GraphDelta::ReplayAppendFrameLayoutHintById {
470                    node_id: parse_uuid(node_id),
471                    hint: hint.clone(),
472                }
473            }
474            Self::ReplayRemoveFrameLayoutHintById {
475                node_id,
476                hint_index,
477            } => GraphDelta::ReplayRemoveFrameLayoutHintById {
478                node_id: parse_uuid(node_id),
479                hint_index: *hint_index,
480            },
481            Self::ReplayMoveFrameLayoutHintById {
482                node_id,
483                from_index,
484                to_index,
485            } => GraphDelta::ReplayMoveFrameLayoutHintById {
486                node_id: parse_uuid(node_id),
487                from_index: *from_index,
488                to_index: *to_index,
489            },
490            Self::ReplaySetFrameSplitOfferSuppressedById {
491                node_id,
492                suppressed,
493            } => GraphDelta::ReplaySetFrameSplitOfferSuppressedById {
494                node_id: parse_uuid(node_id),
495                suppressed: *suppressed,
496            },
497            Self::ReplayUpdateNodeHistoryById {
498                node_id,
499                entries,
500                current_index,
501            } => GraphDelta::ReplayUpdateNodeHistoryById {
502                node_id: parse_uuid(node_id),
503                entries: entries.clone(),
504                current_index: *current_index,
505            },
506            Self::ReplaySetImportRecords { import_records } => GraphDelta::ReplaySetImportRecords {
507                import_records: import_records.clone(),
508            },
509            Self::ReplayTouchNodeLastVisitedById {
510                node_id,
511                timestamp_ms,
512            } => GraphDelta::ReplayTouchNodeLastVisitedById {
513                node_id: parse_uuid(node_id),
514                timestamp_ms: *timestamp_ms,
515            },
516            Self::ReplayAddField { field } => GraphDelta::ReplayAddField {
517                field: field.clone(),
518            },
519            Self::ReplayRetireFieldById { field_id } => GraphDelta::ReplayRetireFieldById {
520                field_id: field_id.clone(),
521            },
522            Self::ReplayAddCoupling { coupling } => GraphDelta::ReplayAddCoupling {
523                coupling: coupling.clone(),
524            },
525            Self::ReplaySetFieldCouplingStrengthByFieldId { field_id, strength } => {
526                GraphDelta::ReplaySetFieldCouplingStrengthByFieldId {
527                    field_id: field_id.clone(),
528                    strength: *strength,
529                }
530            }
531            Self::ReplayActivateFieldById { field_id } => GraphDelta::ReplayActivateFieldById {
532                field_id: field_id.clone(),
533            },
534            Self::ReplayRetractCouplingById { coupling_id } => {
535                GraphDelta::ReplayRetractCouplingById {
536                    coupling_id: coupling_id.clone(),
537                }
538            }
539        })
540    }
541}
542
543fn parse_uuid(id: &str) -> Uuid {
544    Uuid::parse_str(id).expect("captured stable ids should always parse")
545}
546
547pub(crate) fn persisted_field_from_field(field: &Field) -> PersistedField {
548    PersistedField {
549        id: field.id.as_uuid().to_string(),
550        name: field.name.clone(),
551        definition_json: serde_json::to_string(&field.definition).unwrap_or_default(),
552        extent: match &field.extent {
553            FieldExtent::Global => PersistedFieldExtent::Global,
554            FieldExtent::Region {
555                min_x,
556                min_y,
557                max_x,
558                max_y,
559            } => PersistedFieldExtent::Region {
560                min_x: *min_x,
561                min_y: *min_y,
562                max_x: *max_x,
563                max_y: *max_y,
564            },
565            FieldExtent::AttachedToNode(id) => PersistedFieldExtent::AttachedToNode(id.to_string()),
566            FieldExtent::Polygon { points } => PersistedFieldExtent::Polygon {
567                points: points.clone(),
568            },
569        },
570        lifecycle: match field.lifecycle {
571            FieldLifecycle::Active => PersistedFieldLifecycle::Active,
572            FieldLifecycle::Retired => PersistedFieldLifecycle::Retired,
573        },
574    }
575}
576
577pub(crate) fn field_from_persisted(pfield: &PersistedField) -> Option<Field> {
578    let id = Uuid::parse_str(&pfield.id).ok()?;
579    let definition = serde_json::from_str::<FieldDefinition>(&pfield.definition_json).ok()?;
580    let extent = match &pfield.extent {
581        PersistedFieldExtent::Global => FieldExtent::Global,
582        PersistedFieldExtent::Region {
583            min_x,
584            min_y,
585            max_x,
586            max_y,
587        } => FieldExtent::Region {
588            min_x: *min_x,
589            min_y: *min_y,
590            max_x: *max_x,
591            max_y: *max_y,
592        },
593        PersistedFieldExtent::AttachedToNode(s) => Uuid::parse_str(s)
594            .map(FieldExtent::AttachedToNode)
595            .unwrap_or(FieldExtent::Global),
596        PersistedFieldExtent::Polygon { points } => FieldExtent::Polygon {
597            points: points.clone(),
598        },
599    };
600    let mut field = Field::new(FieldId::from_uuid(id), definition).with_extent(extent);
601    if let Some(name) = &pfield.name {
602        field = field.with_name(name.clone());
603    }
604    field.lifecycle = match pfield.lifecycle {
605        PersistedFieldLifecycle::Active => FieldLifecycle::Active,
606        PersistedFieldLifecycle::Retired => FieldLifecycle::Retired,
607    };
608    Some(field)
609}
610
611pub(crate) fn persisted_coupling_from_coupling(coupling: &Coupling) -> PersistedCoupling {
612    PersistedCoupling {
613        id: coupling.id.as_uuid().to_string(),
614        field_id: coupling.field.as_uuid().to_string(),
615        selector: match &coupling.selector {
616            NodeSelector::All => PersistedNodeSelector::All,
617            NodeSelector::Tagged(tag) => PersistedNodeSelector::Tagged(tag.clone()),
618            NodeSelector::Kind(kind) => PersistedNodeSelector::Kind(kind.clone()),
619            NodeSelector::NotTagged(tag) => PersistedNodeSelector::NotTagged(tag.clone()),
620        },
621        response: match &coupling.response {
622            CouplingResponse::AttractToMin => PersistedCouplingResponse::AttractToMin,
623            CouplingResponse::RepelFromMax => PersistedCouplingResponse::RepelFromMax,
624            CouplingResponse::AlignVelocity => PersistedCouplingResponse::AlignVelocity,
625            CouplingResponse::FlowAdvect => PersistedCouplingResponse::FlowAdvect,
626            CouplingResponse::DampenInside { factor } => {
627                PersistedCouplingResponse::DampenInside { factor: *factor }
628            }
629            CouplingResponse::ContainmentWall => PersistedCouplingResponse::ContainmentWall,
630            CouplingResponse::Open { predicate } => PersistedCouplingResponse::Open {
631                predicate: predicate.clone(),
632            },
633        },
634        strength: coupling.strength,
635    }
636}
637
638pub(crate) fn coupling_from_persisted(pcoupling: &PersistedCoupling) -> Option<Coupling> {
639    let cid = Uuid::parse_str(&pcoupling.id).ok()?;
640    let fid = Uuid::parse_str(&pcoupling.field_id).ok()?;
641    let selector = match &pcoupling.selector {
642        PersistedNodeSelector::All => NodeSelector::All,
643        PersistedNodeSelector::Tagged(tag) => NodeSelector::Tagged(tag.clone()),
644        PersistedNodeSelector::Kind(kind) => NodeSelector::Kind(kind.clone()),
645        PersistedNodeSelector::NotTagged(tag) => NodeSelector::NotTagged(tag.clone()),
646    };
647    let response = match &pcoupling.response {
648        PersistedCouplingResponse::AttractToMin => CouplingResponse::AttractToMin,
649        PersistedCouplingResponse::RepelFromMax => CouplingResponse::RepelFromMax,
650        PersistedCouplingResponse::AlignVelocity => CouplingResponse::AlignVelocity,
651        PersistedCouplingResponse::FlowAdvect => CouplingResponse::FlowAdvect,
652        PersistedCouplingResponse::DampenInside { factor } => {
653            CouplingResponse::DampenInside { factor: *factor }
654        }
655        PersistedCouplingResponse::ContainmentWall => CouplingResponse::ContainmentWall,
656        PersistedCouplingResponse::Open { predicate } => CouplingResponse::Open {
657            predicate: predicate.clone(),
658        },
659    };
660    Some(Coupling::new(
661        super::CouplingId::from_uuid(cid),
662        FieldId::from_uuid(fid),
663        selector,
664        response,
665        pcoupling.strength,
666    ))
667}
668
669/// Cheap live counts for the graph's arena-like tables, surfaced in Apparatus.
670#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
671pub struct GraphTableStats {
672    pub node_count: usize,
673    pub edge_count: usize,
674    pub relation_count: usize,
675    pub field_count: usize,
676    pub coupling_count: usize,
677    pub history_owner_count: usize,
678    pub history_entry_count: usize,
679    pub history_visit_count: usize,
680}
681
682impl Graph {
683    /// Cheap live counts for the graph's kernel-owned tables.
684    pub fn table_stats(&self) -> GraphTableStats {
685        GraphTableStats {
686            node_count: self.node_count(),
687            edge_count: self.edge_count(),
688            relation_count: self.relations().count(),
689            field_count: self.fields().count(),
690            coupling_count: self.couplings().count(),
691            history_owner_count: self.nav.owner_count(),
692            history_entry_count: self.nav.entry_count(),
693            history_visit_count: self.nav.visit_count(),
694        }
695    }
696}
697
698/// Replay a captured-delta stream against an empty graph.
699pub fn replay_captured_deltas<I>(deltas: I) -> Graph
700where
701    I: IntoIterator<Item = CapturedDelta>,
702{
703    let mut graph = Graph::new();
704    replay_captured_deltas_onto(&mut graph, deltas);
705    graph
706}
707
708/// Replay a captured-delta stream against an existing graph, advancing it in
709/// place. The incremental twin of [`replay_captured_deltas`]: materialize a
710/// checkpoint (a `GraphSnapshot`), then apply only the journal entries recorded
711/// after it. Live editing and replay both funnel through `apply_graph_delta`, so a
712/// replayed graph cannot diverge from the one the edits were captured from — the
713/// edit-spine invariant. (See `graph/journal.rs`.)
714pub fn replay_captured_deltas_onto<I>(graph: &mut Graph, deltas: I)
715where
716    I: IntoIterator<Item = CapturedDelta>,
717{
718    for delta in deltas {
719        if let Some(delta) = delta.replay_delta() {
720            let _ = apply_graph_delta(graph, delta);
721        }
722    }
723}
724
725type CaptureHook = dyn Fn(&CapturedDelta) + Send + Sync + 'static;
726
727thread_local! {
728    static CAPTURE_HOOK: RefCell<Option<Arc<CaptureHook>>> = RefCell::new(None);
729}
730
731/// Install or clear the current thread's graph-delta capture hook.
732pub fn set_captured_delta_hook(hook: Option<Arc<CaptureHook>>) {
733    CAPTURE_HOOK.with(|slot| *slot.borrow_mut() = hook);
734}
735
736pub(crate) fn record_captured_delta(delta: &CapturedDelta) {
737    CAPTURE_HOOK.with(|slot| {
738        if let Some(hook) = slot.borrow().as_ref() {
739            hook(delta);
740        }
741    });
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747    use std::sync::Mutex;
748
749    use crate::graph::{
750        ContainmentSubKind, Coupling, CouplingId, CouplingResponse, EdgeAssertion, Field,
751        FieldDefinition, FieldExtent, FieldId, Graph, NavigationTrigger, NodeSelector,
752        ProvenanceSubKind, ScalarField, SemanticSubKind, SharedNavigationMemory,
753    };
754    use crate::types::{
755        BadgeIcon, ClassificationProvenance, ClassificationScheme, ClassificationStatus,
756        FrameLayoutHint, ImportRecordMembership, NodeClassification, NodeDerivation,
757        NodeImportProvenance, NodeProperty, SplitOrientation,
758    };
759
760    fn point(x: f32, y: f32) -> Point2D<f32> {
761        Point2D::new(x, y)
762    }
763
764    fn sample_field(id: FieldId) -> Field {
765        Field::new(id, FieldDefinition::Scalar(ScalarField::Const(1.0)))
766            .with_name("focus")
767            .with_extent(FieldExtent::Region {
768                min_x: -10.0,
769                min_y: -20.0,
770                max_x: 30.0,
771                max_y: 40.0,
772            })
773    }
774
775    fn sample_coupling(id: CouplingId, field: FieldId) -> Coupling {
776        Coupling::new(
777            id,
778            field,
779            NodeSelector::Kind("paper".into()),
780            CouplingResponse::DampenInside { factor: 0.3 },
781            1.5,
782        )
783    }
784
785    #[test]
786    fn structural_captured_delta_round_trips_through_postcard() {
787        let delta = CapturedDelta::ReplayAssertRelationByIds {
788            from_id: Uuid::from_u128(1).to_string(),
789            to_id: Uuid::from_u128(2).to_string(),
790            assertion: EdgeAssertion::Semantic {
791                sub_kind: SemanticSubKind::Hyperlink,
792                label: Some("next".into()),
793                decay_progress: Some(0.25),
794            },
795        };
796        let bytes = postcard::to_allocvec(&delta).expect("encode");
797        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
798        assert_eq!(restored, delta);
799    }
800
801    #[test]
802    fn arbitrary_facets_use_the_same_capture_and_replay_spine() {
803        let captured = Arc::new(Mutex::new(Vec::<CapturedDelta>::new()));
804        let sink = captured.clone();
805        set_captured_delta_hook(Some(Arc::new(move |delta| {
806            sink.lock().expect("capture sink").push(delta.clone());
807        })));
808
809        let id = Uuid::from_u128(0xfac7);
810        let mut graph = Graph::new();
811        let key = crate::graph::apply::add_node(
812            &mut graph,
813            Some(id),
814            "mere://facet-test".into(),
815            point(0.0, 0.0),
816        );
817        let value = serde_json::json!({"portable": true});
818        let _ = apply_graph_delta(
819            &mut graph,
820            GraphDelta::SetNodeFacet {
821                key,
822                facet: "example.portable/v1".into(),
823                value: value.clone(),
824            },
825        );
826        let _ = apply_graph_delta(
827            &mut graph,
828            GraphDelta::SetNodeFacet {
829                key,
830                facet: "example.portable/v1".into(),
831                value: value.clone(),
832            },
833        );
834        let _ = apply_graph_delta(
835            &mut graph,
836            GraphDelta::RemoveNodeFacet {
837                key,
838                facet: "example.portable/v1".into(),
839            },
840        );
841        set_captured_delta_hook(None);
842
843        let captured = captured.lock().expect("capture sink");
844        assert_eq!(
845            captured.len(),
846            3,
847            "add, first set, and remove are captured; an identical set is not"
848        );
849        let set_projection = replay_captured_deltas(captured[..2].iter().cloned());
850        assert_eq!(
851            set_projection
852                .facets()
853                .get(&id, &chartulary::FacetId::new("example.portable/v1"),),
854            Some(&value)
855        );
856        let removed_projection = replay_captured_deltas(captured.iter().cloned());
857        assert!(
858            removed_projection
859                .facets()
860                .get(&id, &chartulary::FacetId::new("example.portable/v1"),)
861                .is_none()
862        );
863    }
864
865    #[test]
866    fn traversal_captured_delta_round_trips_through_postcard() {
867        let delta = CapturedDelta::ReplayAppendTraversalByIds {
868            from_id: Uuid::from_u128(3).to_string(),
869            to_id: Uuid::from_u128(4).to_string(),
870            trigger: NavigationTrigger::Redirect,
871            timestamp_ms: 12_345,
872        };
873        let bytes = postcard::to_allocvec(&delta).expect("encode");
874        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
875        assert_eq!(restored, delta);
876    }
877
878    #[test]
879    fn node_content_captured_delta_round_trips_through_postcard() {
880        let delta = CapturedDelta::ReplaySetNodeBodyById {
881            node_id: Uuid::from_u128(5).to_string(),
882            body: Some("hello".into()),
883        };
884        let bytes = postcard::to_allocvec(&delta).expect("encode");
885        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
886        assert_eq!(restored, delta);
887    }
888
889    #[test]
890    fn node_enrichment_captured_delta_round_trips_through_postcard() {
891        let delta = CapturedDelta::ReplayAddNodeClassificationById {
892            node_id: Uuid::from_u128(6).to_string(),
893            classification: NodeClassification {
894                scheme: ClassificationScheme::ContentKind,
895                value: "article".into(),
896                label: Some("Article".into()),
897                confidence: 1.0,
898                provenance: ClassificationProvenance::UserAuthored,
899                status: ClassificationStatus::Accepted,
900                primary: true,
901            },
902        };
903        let bytes = postcard::to_allocvec(&delta).expect("encode");
904        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
905        assert_eq!(restored, delta);
906    }
907
908    #[test]
909    fn classification_admin_captured_delta_round_trips_through_postcard() {
910        let delta = CapturedDelta::ReplaySetNodeClassificationStatusById {
911            node_id: Uuid::from_u128(61).to_string(),
912            scheme: ClassificationScheme::ContentKind,
913            value: "article".into(),
914            status: ClassificationStatus::Verified,
915        };
916        let bytes = postcard::to_allocvec(&delta).expect("encode");
917        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
918        assert_eq!(restored, delta);
919    }
920
921    #[test]
922    fn tag_presentation_captured_delta_round_trips_through_postcard() {
923        let delta = CapturedDelta::ReplaySetNodeTagIconOverrideById {
924            node_id: Uuid::from_u128(62).to_string(),
925            tag: "paper".into(),
926            icon: Some(BadgeIcon::Lucide("file-text".into())),
927        };
928        let bytes = postcard::to_allocvec(&delta).expect("encode");
929        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
930        assert_eq!(restored, delta);
931    }
932
933    #[test]
934    fn node_media_captured_delta_round_trips_through_postcard() {
935        let delta = CapturedDelta::ReplaySetNodeImageById {
936            node_id: Uuid::from_u128(7).to_string(),
937            role: ImageRole::Preview,
938            image: ImageRef::new([4u8; 32], 2, 2),
939        };
940        let bytes = postcard::to_allocvec(&delta).expect("encode");
941        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
942        assert_eq!(restored, delta);
943    }
944
945    /// A journal written before the node-image externalization must still
946    /// decode — losing the ability to read an existing journal would be a
947    /// far worse failure than losing a regenerable preview.
948    #[test]
949    fn a_legacy_inline_image_record_still_decodes_and_is_skipped_on_replay() {
950        let delta = CapturedDelta::ReplaySetNodeThumbnailById {
951            node_id: Uuid::from_u128(7).to_string(),
952            png_bytes: vec![1, 2, 3, 4],
953            width: 2,
954            height: 2,
955        };
956        let bytes = postcard::to_allocvec(&delta).expect("encode");
957        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
958        assert_eq!(restored, delta, "an old journal entry still reads");
959        assert!(
960            restored.replay_delta().is_none(),
961            "it has no live delta: the pixels are dropped, not restored"
962        );
963    }
964
965    #[test]
966    fn navigation_captured_delta_round_trips_through_postcard() {
967        let delta = CapturedDelta::ReplayNavigateNodeById {
968            node_id: Uuid::from_u128(8).to_string(),
969            url: "https://example.test/two".into(),
970            transition: TransitionKind::UrlTyped,
971            timestamp_ms: 123,
972            last_session_visited: 77,
973        };
974        let bytes = postcard::to_allocvec(&delta).expect("encode");
975        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
976        assert_eq!(restored, delta);
977    }
978
979    #[test]
980    fn semantic_edge_captured_delta_round_trips_through_postcard() {
981        let delta = CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
982            from_id: Uuid::from_u128(81).to_string(),
983            to_id: Uuid::from_u128(82).to_string(),
984            predicate: Some("https://schema.org/author".into()),
985        };
986        let bytes = postcard::to_allocvec(&delta).expect("encode");
987        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
988        assert_eq!(restored, delta);
989    }
990
991    #[test]
992    fn field_layer_captured_delta_round_trips_through_postcard() {
993        let delta = CapturedDelta::ReplayAddField {
994            field: persisted_field_from_field(&sample_field(FieldId::from_uuid(Uuid::from_u128(
995                9,
996            )))),
997        };
998        let bytes = postcard::to_allocvec(&delta).expect("encode");
999        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1000        assert_eq!(restored, delta);
1001    }
1002
1003    #[test]
1004    fn field_admin_captured_delta_round_trips_through_postcard() {
1005        let delta = CapturedDelta::ReplayRetractCouplingById {
1006            coupling_id: Uuid::from_u128(91).to_string(),
1007        };
1008        let bytes = postcard::to_allocvec(&delta).expect("encode");
1009        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1010        assert_eq!(restored, delta);
1011    }
1012
1013    #[test]
1014    fn last_visited_captured_delta_round_trips_through_postcard() {
1015        let delta = CapturedDelta::ReplayTouchNodeLastVisitedById {
1016            node_id: Uuid::from_u128(93).to_string(),
1017            timestamp_ms: 1_763_573_400_123,
1018        };
1019        let bytes = postcard::to_allocvec(&delta).expect("encode");
1020        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1021        assert_eq!(restored, delta);
1022    }
1023
1024    #[test]
1025    fn frame_history_captured_delta_round_trips_through_postcard() {
1026        let delta = CapturedDelta::ReplayUpdateNodeHistoryById {
1027            node_id: Uuid::from_u128(10).to_string(),
1028            entries: vec!["https://a.test".into(), "https://b.test".into()],
1029            current_index: 1,
1030        };
1031        let bytes = postcard::to_allocvec(&delta).expect("encode");
1032        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1033        assert_eq!(restored, delta);
1034    }
1035
1036    #[test]
1037    fn import_records_captured_delta_round_trips_through_postcard() {
1038        let delta = CapturedDelta::ReplaySetImportRecords {
1039            import_records: vec![ImportRecord {
1040                record_id: "import-record:seed".into(),
1041                source_id: "import:seed".into(),
1042                source_label: "Seed import".into(),
1043                imported_at_secs: 1_763_500_800,
1044                memberships: vec![ImportRecordMembership {
1045                    node_id: Uuid::from_u128(10).to_string(),
1046                    suppressed: false,
1047                }],
1048            }],
1049        };
1050        let bytes = postcard::to_allocvec(&delta).expect("encode");
1051        let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1052        assert_eq!(restored, delta);
1053    }
1054
1055    #[test]
1056    fn replay_captured_deltas_rebuilds_relation_traversal_media_navigation_field_enrichment_and_frame_history_state()
1057     {
1058        let a_id = Uuid::from_u128(11);
1059        let b_id = Uuid::from_u128(12);
1060        let c_id = Uuid::from_u128(13);
1061        let field_id = FieldId::from_uuid(Uuid::from_u128(14));
1062        let coupling_id = CouplingId::from_uuid(Uuid::from_u128(15));
1063        let deltas = vec![
1064            CapturedDelta::ReplayAddNodeWithIdIfMissing {
1065                id: a_id.to_string(),
1066                url: "https://a.test".into(),
1067                position: [1.0, 2.0],
1068            },
1069            CapturedDelta::ReplayAddNodeWithIdIfMissing {
1070                id: b_id.to_string(),
1071                url: "https://b.test".into(),
1072                position: [3.0, 4.0],
1073            },
1074            CapturedDelta::ReplayAddNodeWithIdIfMissing {
1075                id: c_id.to_string(),
1076                url: "https://c.test".into(),
1077                position: [5.0, 6.0],
1078            },
1079            CapturedDelta::ReplayAssertRelationByIds {
1080                from_id: a_id.to_string(),
1081                to_id: b_id.to_string(),
1082                assertion: EdgeAssertion::Containment {
1083                    sub_kind: ContainmentSubKind::CollectionMember,
1084                },
1085            },
1086            CapturedDelta::ReplayAppendTraversalByIds {
1087                from_id: a_id.to_string(),
1088                to_id: b_id.to_string(),
1089                trigger: NavigationTrigger::LinkClick,
1090                timestamp_ms: 6_789,
1091            },
1092            CapturedDelta::ReplaySetNodeTitleById {
1093                node_id: a_id.to_string(),
1094                title: "Alpha".into(),
1095            },
1096            CapturedDelta::ReplaySetNodeUrlById {
1097                node_id: a_id.to_string(),
1098                new_url: "https://a.test/next".into(),
1099            },
1100            CapturedDelta::ReplaySetNodeImageById {
1101                node_id: a_id.to_string(),
1102                role: ImageRole::Preview,
1103                image: ImageRef::new([7u8; 32], 1, 1),
1104            },
1105            CapturedDelta::ReplaySetNodeImageById {
1106                node_id: a_id.to_string(),
1107                role: ImageRole::Favicon,
1108                image: ImageRef::new([9u8; 32], 1, 1),
1109            },
1110            CapturedDelta::ReplaySetNodeMimeHintById {
1111                node_id: a_id.to_string(),
1112                mime_hint: Some("text/html".into()),
1113            },
1114            CapturedDelta::ReplaySetNodePinnedById {
1115                node_id: a_id.to_string(),
1116                is_pinned: true,
1117            },
1118            CapturedDelta::ReplayInsertNodeTagById {
1119                node_id: a_id.to_string(),
1120                tag: "research".into(),
1121            },
1122            CapturedDelta::ReplayRemoveNodeTagById {
1123                node_id: a_id.to_string(),
1124                tag: "research".into(),
1125            },
1126            CapturedDelta::ReplaySetNodeBodyById {
1127                node_id: a_id.to_string(),
1128                body: Some("body".into()),
1129            },
1130            CapturedDelta::ReplayTouchNodeLastVisitedById {
1131                node_id: a_id.to_string(),
1132                timestamp_ms: 1_763_573_400_123,
1133            },
1134            CapturedDelta::ReplayInsertNodeTagById {
1135                node_id: a_id.to_string(),
1136                tag: "paper".into(),
1137            },
1138            CapturedDelta::ReplaySetNodeTagIconOverrideById {
1139                node_id: a_id.to_string(),
1140                tag: "paper".into(),
1141                icon: Some(BadgeIcon::Lucide("file-text".into())),
1142            },
1143            CapturedDelta::ReplayNavigateNodeById {
1144                node_id: b_id.to_string(),
1145                url: "https://b.test/one".into(),
1146                transition: TransitionKind::UrlTyped,
1147                timestamp_ms: 111,
1148                last_session_visited: 77,
1149            },
1150            CapturedDelta::ReplayNavigateNodeById {
1151                node_id: b_id.to_string(),
1152                url: "https://b.test/two".into(),
1153                transition: TransitionKind::UrlTyped,
1154                timestamp_ms: 222,
1155                last_session_visited: 77,
1156            },
1157            CapturedDelta::ReplayNodeHistoryBackById {
1158                node_id: b_id.to_string(),
1159                timestamp_ms: 333,
1160            },
1161            CapturedDelta::ReplayNodeHistoryForwardById {
1162                node_id: b_id.to_string(),
1163                timestamp_ms: 444,
1164            },
1165            CapturedDelta::ReplayBranchHistoryByIds {
1166                child_id: c_id.to_string(),
1167                parent_id: b_id.to_string(),
1168            },
1169            CapturedDelta::ReplayNavigateNodeById {
1170                node_id: c_id.to_string(),
1171                url: "https://c.test/branched".into(),
1172                transition: TransitionKind::UrlTyped,
1173                timestamp_ms: 555,
1174                last_session_visited: 77,
1175            },
1176            CapturedDelta::ReplayAddField {
1177                field: persisted_field_from_field(&sample_field(field_id)),
1178            },
1179            CapturedDelta::ReplayAddCoupling {
1180                coupling: persisted_coupling_from_coupling(&sample_coupling(coupling_id, field_id)),
1181            },
1182            CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
1183                field_id: field_id.as_uuid().to_string(),
1184                strength: 2.0,
1185            },
1186            CapturedDelta::ReplayRetireFieldById {
1187                field_id: field_id.as_uuid().to_string(),
1188            },
1189            CapturedDelta::ReplayActivateFieldById {
1190                field_id: field_id.as_uuid().to_string(),
1191            },
1192            CapturedDelta::ReplayRetractCouplingById {
1193                coupling_id: coupling_id.as_uuid().to_string(),
1194            },
1195            CapturedDelta::ReplayAddCoupling {
1196                coupling: persisted_coupling_from_coupling(&sample_coupling(coupling_id, field_id)),
1197            },
1198            CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
1199                field_id: field_id.as_uuid().to_string(),
1200                strength: 2.0,
1201            },
1202            CapturedDelta::ReplayAppendNodePropertyById {
1203                node_id: a_id.to_string(),
1204                property: NodeProperty::new(
1205                    "https://schema.org/datePublished".into(),
1206                    "2026-07-02".into(),
1207                ),
1208            },
1209            CapturedDelta::ReplayAddNodeClassificationById {
1210                node_id: a_id.to_string(),
1211                classification: NodeClassification {
1212                    scheme: ClassificationScheme::ContentKind,
1213                    value: "article".into(),
1214                    label: Some("Article".into()),
1215                    confidence: 1.0,
1216                    provenance: ClassificationProvenance::UserAuthored,
1217                    status: ClassificationStatus::Accepted,
1218                    primary: true,
1219                },
1220            },
1221            CapturedDelta::ReplayAddNodeClassificationById {
1222                node_id: a_id.to_string(),
1223                classification: NodeClassification {
1224                    scheme: ClassificationScheme::ContentKind,
1225                    value: "essay".into(),
1226                    label: Some("Essay".into()),
1227                    confidence: 0.6,
1228                    provenance: ClassificationProvenance::AgentSuggested,
1229                    status: ClassificationStatus::Suggested,
1230                    primary: false,
1231                },
1232            },
1233            CapturedDelta::ReplayAddNodeClassificationById {
1234                node_id: a_id.to_string(),
1235                classification: NodeClassification {
1236                    scheme: ClassificationScheme::ContentKind,
1237                    value: "draft".into(),
1238                    label: Some("Draft".into()),
1239                    confidence: 0.3,
1240                    provenance: ClassificationProvenance::AgentSuggested,
1241                    status: ClassificationStatus::Suggested,
1242                    primary: false,
1243                },
1244            },
1245            CapturedDelta::ReplaySetNodeClassificationStatusById {
1246                node_id: a_id.to_string(),
1247                scheme: ClassificationScheme::ContentKind,
1248                value: "article".into(),
1249                status: ClassificationStatus::Verified,
1250            },
1251            CapturedDelta::ReplaySetNodePrimaryClassificationById {
1252                node_id: a_id.to_string(),
1253                scheme: ClassificationScheme::ContentKind,
1254                value: "essay".into(),
1255            },
1256            CapturedDelta::ReplayRemoveNodeClassificationById {
1257                node_id: a_id.to_string(),
1258                scheme: ClassificationScheme::ContentKind,
1259                value: "draft".into(),
1260            },
1261            CapturedDelta::ReplayRecordNodeDerivationById {
1262                node_id: a_id.to_string(),
1263                derivation: NodeDerivation {
1264                    sub_kind: ProvenanceSubKind::ExtractedFrom,
1265                    source_node: Uuid::from_u128(99).to_string(),
1266                    source_graph: Some("graph:test".into()),
1267                },
1268            },
1269            CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
1270                from_id: a_id.to_string(),
1271                to_id: b_id.to_string(),
1272                predicate: Some("https://schema.org/author".into()),
1273            },
1274            CapturedDelta::ReplayAssertSemanticPredicateByIds {
1275                from_id: b_id.to_string(),
1276                to_id: c_id.to_string(),
1277                predicate: "https://schema.org/citation".into(),
1278            },
1279            CapturedDelta::ReplayAppendFrameLayoutHintById {
1280                node_id: a_id.to_string(),
1281                hint: FrameLayoutHint::SplitHalf {
1282                    first: b_id.to_string(),
1283                    second: c_id.to_string(),
1284                    orientation: SplitOrientation::Vertical,
1285                },
1286            },
1287            CapturedDelta::ReplayAppendFrameLayoutHintById {
1288                node_id: a_id.to_string(),
1289                hint: FrameLayoutHint::SplitHalf {
1290                    first: c_id.to_string(),
1291                    second: b_id.to_string(),
1292                    orientation: SplitOrientation::Horizontal,
1293                },
1294            },
1295            CapturedDelta::ReplayMoveFrameLayoutHintById {
1296                node_id: a_id.to_string(),
1297                from_index: 0,
1298                to_index: 1,
1299            },
1300            CapturedDelta::ReplayRemoveFrameLayoutHintById {
1301                node_id: a_id.to_string(),
1302                hint_index: 1,
1303            },
1304            CapturedDelta::ReplaySetFrameSplitOfferSuppressedById {
1305                node_id: a_id.to_string(),
1306                suppressed: true,
1307            },
1308            CapturedDelta::ReplayUpdateNodeHistoryById {
1309                node_id: a_id.to_string(),
1310                entries: vec![
1311                    "https://a.test/one".into(),
1312                    "https://a.test/two".into(),
1313                    "https://a.test/three".into(),
1314                ],
1315                current_index: 9,
1316            },
1317            CapturedDelta::ReplaySetImportRecords {
1318                import_records: vec![ImportRecord {
1319                    record_id: "import-record:seed".into(),
1320                    source_id: "import:seed".into(),
1321                    source_label: "Seed import".into(),
1322                    imported_at_secs: 1_763_500_800,
1323                    memberships: vec![
1324                        ImportRecordMembership {
1325                            node_id: a_id.to_string(),
1326                            suppressed: false,
1327                        },
1328                        ImportRecordMembership {
1329                            node_id: c_id.to_string(),
1330                            suppressed: true,
1331                        },
1332                    ],
1333                }],
1334            },
1335        ];
1336
1337        let graph = replay_captured_deltas(deltas);
1338        assert_eq!(graph.node_count(), 3);
1339        assert_eq!(graph.edge_count(), 2);
1340        assert!(graph.get_node_by_id(a_id).is_some());
1341        assert!(graph.get_node_by_id(b_id).is_some());
1342        assert!(graph.get_node_by_id(c_id).is_some());
1343        assert_eq!(graph.relations().count(), 2);
1344        let from = graph.get_node_key_by_id(a_id).expect("from key");
1345        let to = graph.get_node_key_by_id(b_id).expect("to key");
1346        let edge = graph.find_edge_key(from, to).expect("edge key");
1347        let payload = graph.get_edge(edge).expect("edge payload");
1348        assert_eq!(payload.traversals().len(), 1);
1349        assert_eq!(payload.metrics().total_navigations, 1);
1350        assert_eq!(payload.metrics().last_navigated_at, Some(6_789));
1351        let node = graph.get_node(from).expect("node payload");
1352        assert_eq!(node.title, "Alpha");
1353        assert_eq!(node.url(), "https://a.test/next");
1354        assert_eq!(node.preview(), Some(&ImageRef::new([7u8; 32], 1, 1)));
1355        assert_eq!(node.favicon(), Some(&ImageRef::new([9u8; 32], 1, 1)));
1356        assert_eq!(node.media_type.as_deref(), Some("text/html"));
1357        assert_eq!(graph.node_is_pinned(from), Some(true));
1358        assert_eq!(node.body.as_deref(), Some("body"));
1359        assert_eq!(
1360            graph
1361                .node_last_visited(from)
1362                .expect("last visited facet")
1363                .duration_since(std::time::UNIX_EPOCH)
1364                .expect("last visited since epoch")
1365                .as_millis() as u64,
1366            1_763_573_400_123
1367        );
1368        assert!(!node.tags.contains("research"));
1369        assert!(node.tags.contains("paper"));
1370        assert_eq!(
1371            graph
1372                .node_tag_presentation(from)
1373                .unwrap()
1374                .icon_overrides
1375                .get("paper"),
1376            Some(&BadgeIcon::Lucide("file-text".into()))
1377        );
1378        let properties = graph.node_properties(from).unwrap();
1379        assert_eq!(properties.len(), 1);
1380        assert_eq!(properties[0].predicate, "https://schema.org/datePublished");
1381        assert_eq!(properties[0].value, "2026-07-02");
1382        let classifications = graph.node_classifications(from).unwrap();
1383        assert_eq!(classifications.len(), 2);
1384        assert!(classifications.iter().any(|classification| {
1385            classification.value == "article"
1386                && classification.status == ClassificationStatus::Verified
1387                && !classification.primary
1388        }));
1389        assert!(classifications.iter().any(|classification| {
1390            classification.value == "essay"
1391                && classification.status == ClassificationStatus::Suggested
1392                && classification.primary
1393        }));
1394        assert!(
1395            classifications
1396                .iter()
1397                .all(|classification| classification.value != "draft")
1398        );
1399        let derivations = graph.node_derivations(from).unwrap();
1400        assert_eq!(derivations.len(), 1);
1401        assert_eq!(derivations[0].sub_kind, ProvenanceSubKind::ExtractedFrom);
1402        assert_eq!(
1403            payload
1404                .semantic_data()
1405                .and_then(|data| data.predicate.as_deref()),
1406            Some("https://schema.org/author")
1407        );
1408        let history_node_key = graph.get_node_key_by_id(b_id).expect("history node key");
1409        let history_node = graph.get_node(history_node_key).expect("history node");
1410        assert_eq!(history_node.url(), "https://b.test/two");
1411        assert_eq!(graph.node_last_session_visited(history_node_key), Some(77));
1412        let history_projection = graph.node_history_projection(history_node_key);
1413        assert_eq!(
1414            history_projection.entries,
1415            vec![
1416                "https://b.test/one".to_string(),
1417                "https://b.test/two".to_string(),
1418            ]
1419        );
1420        assert_eq!(history_projection.current_index, 1);
1421        let branched_node_key = graph.get_node_key_by_id(c_id).expect("branched node key");
1422        let branched_node = graph.get_node(branched_node_key).expect("branched node");
1423        assert_eq!(branched_node.url(), "https://c.test/branched");
1424        assert_eq!(graph.node_last_session_visited(branched_node_key), Some(77));
1425        let semantic_edge = graph
1426            .find_edge_key(history_node_key, branched_node_key)
1427            .expect("semantic edge key");
1428        let semantic_payload = graph
1429            .get_edge(semantic_edge)
1430            .expect("semantic edge payload");
1431        assert_eq!(
1432            semantic_payload
1433                .semantic_data()
1434                .and_then(|data| data.predicate.as_deref()),
1435            Some("https://schema.org/citation")
1436        );
1437        let field = graph.field(field_id).expect("field payload");
1438        assert_eq!(field.name.as_deref(), Some("focus"));
1439        assert!(field.is_active());
1440        assert_eq!(
1441            field.extent,
1442            FieldExtent::Region {
1443                min_x: -10.0,
1444                min_y: -20.0,
1445                max_x: 30.0,
1446                max_y: 40.0,
1447            }
1448        );
1449        let coupling = graph
1450            .couplings_for_field(field_id)
1451            .next()
1452            .expect("field coupling");
1453        assert_eq!(coupling.id, coupling_id);
1454        assert_eq!(coupling.selector, NodeSelector::Kind("paper".into()));
1455        assert_eq!(
1456            coupling.response,
1457            CouplingResponse::DampenInside { factor: 0.3 }
1458        );
1459        assert_eq!(coupling.strength, 2.0);
1460        let hints = graph.frame_layout_hints(from).expect("frame layout hints");
1461        assert_eq!(hints.len(), 1);
1462        assert_eq!(
1463            hints[0],
1464            FrameLayoutHint::SplitHalf {
1465                first: c_id.to_string(),
1466                second: b_id.to_string(),
1467                orientation: SplitOrientation::Horizontal,
1468            }
1469        );
1470        assert_eq!(graph.frame_split_offer_suppressed(from), Some(true));
1471        let history = graph.node_history_projection(from);
1472        assert_eq!(
1473            history.entries,
1474            vec![
1475                "https://a.test/one".to_string(),
1476                "https://a.test/two".to_string(),
1477                "https://a.test/three".to_string(),
1478            ]
1479        );
1480        assert_eq!(history.current_index, 2);
1481        let import_records = graph.import_records();
1482        assert_eq!(import_records.len(), 1);
1483        assert_eq!(import_records[0].record_id, "import-record:seed");
1484        assert_eq!(
1485            graph.import_record_member_keys("import-record:seed"),
1486            vec![from]
1487        );
1488        assert_eq!(
1489            graph
1490                .node_import_provenance(from)
1491                .expect("import provenance"),
1492            [NodeImportProvenance {
1493                source_id: "import:seed".into(),
1494                source_label: "Seed import".into(),
1495            }]
1496        );
1497        assert!(
1498            graph
1499                .node_import_provenance(branched_node_key)
1500                .expect("suppressed provenance")
1501                .is_empty()
1502        );
1503        let mut expected_nav = SharedNavigationMemory::empty();
1504        expected_nav.record_visit(b_id, "https://b.test/one", TransitionKind::UrlTyped, 111);
1505        expected_nav.record_visit(b_id, "https://b.test/two", TransitionKind::UrlTyped, 222);
1506        assert_eq!(
1507            expected_nav.back(b_id, 333).as_deref(),
1508            Some("https://b.test/one")
1509        );
1510        assert_eq!(
1511            expected_nav.forward(b_id, 444).as_deref(),
1512            Some("https://b.test/two")
1513        );
1514        expected_nav.spawn(c_id, b_id);
1515        expected_nav.record_visit(
1516            c_id,
1517            "https://c.test/branched",
1518            TransitionKind::UrlTyped,
1519            555,
1520        );
1521        expected_nav.seed_linear(
1522            a_id,
1523            vec![
1524                "https://a.test/one".to_string(),
1525                "https://a.test/two".to_string(),
1526                "https://a.test/three".to_string(),
1527            ],
1528            9,
1529        );
1530        let mut actual_snapshot = graph.to_snapshot().navigation.snapshot().clone();
1531        for owner in &mut actual_snapshot.owners {
1532            owner.owned_visits.sort_unstable();
1533        }
1534        for visit in &mut actual_snapshot.visits {
1535            visit.bindings.sort_by_key(|binding| {
1536                (
1537                    binding.owner,
1538                    binding.forward_child.unwrap_or(usize::MAX),
1539                    binding.last_accessed_at_ms,
1540                )
1541            });
1542        }
1543        let mut expected_snapshot = expected_nav.snapshot().clone();
1544        for owner in &mut expected_snapshot.owners {
1545            owner.owned_visits.sort_unstable();
1546        }
1547        for visit in &mut expected_snapshot.visits {
1548            visit.bindings.sort_by_key(|binding| {
1549                (
1550                    binding.owner,
1551                    binding.forward_child.unwrap_or(usize::MAX),
1552                    binding.last_accessed_at_ms,
1553                )
1554            });
1555        }
1556        assert_eq!(actual_snapshot, expected_snapshot);
1557    }
1558
1559    #[test]
1560    fn capture_hook_receives_replayable_apply_events() {
1561        let captured = Arc::new(Mutex::new(Vec::<CapturedDelta>::new()));
1562        let sink = captured.clone();
1563        set_captured_delta_hook(Some(Arc::new(move |delta| {
1564            sink.lock().expect("capture sink").push(delta.clone());
1565        })));
1566
1567        let mut graph = Graph::new();
1568        graph.set_current_session(77);
1569        let a = crate::graph::apply::add_node(
1570            &mut graph,
1571            Some(Uuid::from_u128(21)),
1572            "https://a.test".into(),
1573            point(0.0, 0.0),
1574        );
1575        let b = crate::graph::apply::add_node(
1576            &mut graph,
1577            Some(Uuid::from_u128(22)),
1578            "https://b.test".into(),
1579            point(1.0, 0.0),
1580        );
1581        let c = crate::graph::apply::add_node(
1582            &mut graph,
1583            Some(Uuid::from_u128(23)),
1584            "https://c.test".into(),
1585            point(2.0, 0.0),
1586        );
1587        let field_id = FieldId::from_uuid(Uuid::from_u128(24));
1588        let coupling_id = CouplingId::from_uuid(Uuid::from_u128(25));
1589        crate::graph::apply::assert_relation(
1590            &mut graph,
1591            a,
1592            b,
1593            EdgeAssertion::Semantic {
1594                sub_kind: SemanticSubKind::Hyperlink,
1595                label: None,
1596                decay_progress: None,
1597            },
1598        );
1599        let _ = crate::graph::apply::apply_graph_delta(
1600            &mut graph,
1601            GraphDelta::AppendTraversal {
1602                from: a,
1603                to: b,
1604                trigger: NavigationTrigger::Programmatic,
1605                timestamp_ms: Some(4_321),
1606            },
1607        );
1608        let _ = crate::graph::apply::apply_graph_delta(
1609            &mut graph,
1610            GraphDelta::SetNodeTitle {
1611                key: a,
1612                title: "Alpha".into(),
1613            },
1614        );
1615        let _ = crate::graph::apply::apply_graph_delta(
1616            &mut graph,
1617            GraphDelta::SetNodeUrl {
1618                key: a,
1619                new_url: "https://a.test/next".into(),
1620            },
1621        );
1622        let _ = crate::graph::apply::apply_graph_delta(
1623            &mut graph,
1624            GraphDelta::SetNodeImage {
1625                key: a,
1626                role: ImageRole::Preview,
1627                image: ImageRef::new([7u8; 32], 1, 1),
1628            },
1629        );
1630        let _ = crate::graph::apply::apply_graph_delta(
1631            &mut graph,
1632            GraphDelta::SetNodeImage {
1633                key: a,
1634                role: ImageRole::Favicon,
1635                image: ImageRef::new([9u8; 32], 1, 1),
1636            },
1637        );
1638        let _ = crate::graph::apply::apply_graph_delta(
1639            &mut graph,
1640            GraphDelta::SetNodeMimeHint {
1641                key: a,
1642                mime_hint: Some("text/html".into()),
1643            },
1644        );
1645        let _ = crate::graph::apply::apply_graph_delta(
1646            &mut graph,
1647            GraphDelta::SetNodePinned {
1648                key: a,
1649                is_pinned: true,
1650            },
1651        );
1652        let _ = crate::graph::apply::apply_graph_delta(
1653            &mut graph,
1654            GraphDelta::InsertNodeTag {
1655                key: a,
1656                tag: "research".into(),
1657            },
1658        );
1659        let _ = crate::graph::apply::apply_graph_delta(
1660            &mut graph,
1661            GraphDelta::RemoveNodeTag {
1662                key: a,
1663                tag: "research".into(),
1664            },
1665        );
1666        let _ = crate::graph::apply::apply_graph_delta(
1667            &mut graph,
1668            GraphDelta::SetNodeBody {
1669                key: a,
1670                body: Some("body".into()),
1671            },
1672        );
1673        let _ = crate::graph::apply::apply_graph_delta(
1674            &mut graph,
1675            GraphDelta::TouchNodeLastVisited { key: a },
1676        );
1677        let _ = crate::graph::apply::apply_graph_delta(
1678            &mut graph,
1679            GraphDelta::InsertNodeTag {
1680                key: a,
1681                tag: "paper".into(),
1682            },
1683        );
1684        let _ = crate::graph::apply::apply_graph_delta(
1685            &mut graph,
1686            GraphDelta::SetNodeTagIconOverride {
1687                key: a,
1688                tag: "paper".into(),
1689                icon: Some(BadgeIcon::Lucide("file-text".into())),
1690            },
1691        );
1692        let _ = crate::graph::apply::apply_graph_delta(
1693            &mut graph,
1694            GraphDelta::NavigateNode {
1695                key: b,
1696                url: "https://b.test/one".into(),
1697            },
1698        );
1699        let _ = crate::graph::apply::apply_graph_delta(
1700            &mut graph,
1701            GraphDelta::NavigateNode {
1702                key: b,
1703                url: "https://b.test/two".into(),
1704            },
1705        );
1706        let _ = crate::graph::apply::apply_graph_delta(
1707            &mut graph,
1708            GraphDelta::NodeHistoryBack { key: b },
1709        );
1710        let _ = crate::graph::apply::apply_graph_delta(
1711            &mut graph,
1712            GraphDelta::NodeHistoryForward { key: b },
1713        );
1714        let _ = crate::graph::apply::apply_graph_delta(
1715            &mut graph,
1716            GraphDelta::BranchHistory {
1717                child: c,
1718                parent: b,
1719            },
1720        );
1721        let _ = crate::graph::apply::apply_graph_delta(
1722            &mut graph,
1723            GraphDelta::NavigateNode {
1724                key: c,
1725                url: "https://c.test/branched".into(),
1726            },
1727        );
1728        let _ = crate::graph::apply::apply_graph_delta(
1729            &mut graph,
1730            GraphDelta::AddField {
1731                field: sample_field(field_id),
1732            },
1733        );
1734        let _ = crate::graph::apply::apply_graph_delta(
1735            &mut graph,
1736            GraphDelta::AddCoupling {
1737                coupling: sample_coupling(coupling_id, field_id),
1738            },
1739        );
1740        let _ = crate::graph::apply::apply_graph_delta(
1741            &mut graph,
1742            GraphDelta::SetFieldCouplingStrength {
1743                field: field_id,
1744                strength: 2.0,
1745            },
1746        );
1747        let _ = crate::graph::apply::apply_graph_delta(
1748            &mut graph,
1749            GraphDelta::RetireField { id: field_id },
1750        );
1751        let _ = crate::graph::apply::apply_graph_delta(
1752            &mut graph,
1753            GraphDelta::ActivateField { id: field_id },
1754        );
1755        let _ = crate::graph::apply::apply_graph_delta(
1756            &mut graph,
1757            GraphDelta::RetractCoupling { id: coupling_id },
1758        );
1759        let _ = crate::graph::apply::apply_graph_delta(
1760            &mut graph,
1761            GraphDelta::AddCoupling {
1762                coupling: sample_coupling(coupling_id, field_id),
1763            },
1764        );
1765        let _ = crate::graph::apply::apply_graph_delta(
1766            &mut graph,
1767            GraphDelta::SetFieldCouplingStrength {
1768                field: field_id,
1769                strength: 2.0,
1770            },
1771        );
1772        let _ = crate::graph::apply::apply_graph_delta(
1773            &mut graph,
1774            GraphDelta::AppendNodeProperty {
1775                key: a,
1776                property: NodeProperty::new(
1777                    "https://schema.org/datePublished".into(),
1778                    "2026-07-02".into(),
1779                ),
1780            },
1781        );
1782        let _ = crate::graph::apply::apply_graph_delta(
1783            &mut graph,
1784            GraphDelta::AddNodeClassification {
1785                key: a,
1786                classification: NodeClassification {
1787                    scheme: ClassificationScheme::ContentKind,
1788                    value: "article".into(),
1789                    label: Some("Article".into()),
1790                    confidence: 1.0,
1791                    provenance: ClassificationProvenance::UserAuthored,
1792                    status: ClassificationStatus::Accepted,
1793                    primary: true,
1794                },
1795            },
1796        );
1797        let _ = crate::graph::apply::apply_graph_delta(
1798            &mut graph,
1799            GraphDelta::AddNodeClassification {
1800                key: a,
1801                classification: NodeClassification {
1802                    scheme: ClassificationScheme::ContentKind,
1803                    value: "essay".into(),
1804                    label: Some("Essay".into()),
1805                    confidence: 0.6,
1806                    provenance: ClassificationProvenance::AgentSuggested,
1807                    status: ClassificationStatus::Suggested,
1808                    primary: false,
1809                },
1810            },
1811        );
1812        let _ = crate::graph::apply::apply_graph_delta(
1813            &mut graph,
1814            GraphDelta::AddNodeClassification {
1815                key: a,
1816                classification: NodeClassification {
1817                    scheme: ClassificationScheme::ContentKind,
1818                    value: "draft".into(),
1819                    label: Some("Draft".into()),
1820                    confidence: 0.3,
1821                    provenance: ClassificationProvenance::AgentSuggested,
1822                    status: ClassificationStatus::Suggested,
1823                    primary: false,
1824                },
1825            },
1826        );
1827        let _ = crate::graph::apply::apply_graph_delta(
1828            &mut graph,
1829            GraphDelta::SetNodeClassificationStatus {
1830                key: a,
1831                scheme: ClassificationScheme::ContentKind,
1832                value: "article".into(),
1833                status: ClassificationStatus::Verified,
1834            },
1835        );
1836        let _ = crate::graph::apply::apply_graph_delta(
1837            &mut graph,
1838            GraphDelta::SetNodePrimaryClassification {
1839                key: a,
1840                scheme: ClassificationScheme::ContentKind,
1841                value: "essay".into(),
1842            },
1843        );
1844        let _ = crate::graph::apply::apply_graph_delta(
1845            &mut graph,
1846            GraphDelta::RemoveNodeClassification {
1847                key: a,
1848                scheme: ClassificationScheme::ContentKind,
1849                value: "draft".into(),
1850            },
1851        );
1852        let _ = crate::graph::apply::apply_graph_delta(
1853            &mut graph,
1854            GraphDelta::RecordNodeDerivation {
1855                key: a,
1856                derivation: NodeDerivation {
1857                    sub_kind: ProvenanceSubKind::ExtractedFrom,
1858                    source_node: Uuid::from_u128(99).to_string(),
1859                    source_graph: Some("graph:test".into()),
1860                },
1861            },
1862        );
1863        let ab_edge = graph.find_edge_key(a, b).expect("a->b edge");
1864        let _ = crate::graph::apply::apply_graph_delta(
1865            &mut graph,
1866            GraphDelta::SetEdgeSemanticPredicate {
1867                edge: ab_edge,
1868                predicate: Some("https://schema.org/author".into()),
1869            },
1870        );
1871        let _ = crate::graph::apply::apply_graph_delta(
1872            &mut graph,
1873            GraphDelta::AssertSemanticPredicate {
1874                from: b,
1875                to: c,
1876                predicate: "https://schema.org/citation".into(),
1877            },
1878        );
1879        let _ = crate::graph::apply::apply_graph_delta(
1880            &mut graph,
1881            GraphDelta::AppendFrameLayoutHint {
1882                key: a,
1883                hint: FrameLayoutHint::SplitHalf {
1884                    first: Uuid::from_u128(22).to_string(),
1885                    second: Uuid::from_u128(23).to_string(),
1886                    orientation: SplitOrientation::Vertical,
1887                },
1888            },
1889        );
1890        let _ = crate::graph::apply::apply_graph_delta(
1891            &mut graph,
1892            GraphDelta::AppendFrameLayoutHint {
1893                key: a,
1894                hint: FrameLayoutHint::SplitHalf {
1895                    first: Uuid::from_u128(23).to_string(),
1896                    second: Uuid::from_u128(22).to_string(),
1897                    orientation: SplitOrientation::Horizontal,
1898                },
1899            },
1900        );
1901        let _ = crate::graph::apply::apply_graph_delta(
1902            &mut graph,
1903            GraphDelta::MoveFrameLayoutHint {
1904                key: a,
1905                from_index: 0,
1906                to_index: 1,
1907            },
1908        );
1909        let _ = crate::graph::apply::apply_graph_delta(
1910            &mut graph,
1911            GraphDelta::RemoveFrameLayoutHint {
1912                key: a,
1913                hint_index: 1,
1914            },
1915        );
1916        let _ = crate::graph::apply::apply_graph_delta(
1917            &mut graph,
1918            GraphDelta::SetFrameSplitOfferSuppressed {
1919                key: a,
1920                suppressed: true,
1921            },
1922        );
1923        let _ = crate::graph::apply::apply_graph_delta(
1924            &mut graph,
1925            GraphDelta::UpdateNodeHistory {
1926                key: a,
1927                entries: vec![
1928                    "https://a.test/one".into(),
1929                    "https://a.test/two".into(),
1930                    "https://a.test/three".into(),
1931                ],
1932                current_index: 9,
1933            },
1934        );
1935        let _ = crate::graph::apply::apply_graph_delta(
1936            &mut graph,
1937            GraphDelta::SetNodeImportProvenance {
1938                key: a,
1939                import_provenance: vec![NodeImportProvenance {
1940                    source_id: "import:seed".into(),
1941                    source_label: "Seed import".into(),
1942                }],
1943            },
1944        );
1945        let _ = crate::graph::apply::apply_graph_delta(
1946            &mut graph,
1947            GraphDelta::SetImportRecordMembershipSuppressed {
1948                record_id: "import-record:import:seed".into(),
1949                key: a,
1950                suppressed: true,
1951            },
1952        );
1953        let c_node_id = graph.get_node(c).expect("node c").id.to_string();
1954        let _ = crate::graph::apply::apply_graph_delta(
1955            &mut graph,
1956            GraphDelta::SetImportRecords {
1957                import_records: vec![ImportRecord {
1958                    record_id: "import-record:seed-two".into(),
1959                    source_id: "import:seed-two".into(),
1960                    source_label: "Seed import two".into(),
1961                    imported_at_secs: 1_763_500_801,
1962                    memberships: vec![ImportRecordMembership {
1963                        node_id: c_node_id,
1964                        suppressed: false,
1965                    }],
1966                }],
1967            },
1968        );
1969        let _ = crate::graph::apply::apply_graph_delta(
1970            &mut graph,
1971            GraphDelta::RetractRelations {
1972                from: a,
1973                to: b,
1974                selector: RelationSelector::Semantic(SemanticSubKind::Hyperlink),
1975            },
1976        );
1977        let _ =
1978            crate::graph::apply::apply_graph_delta(&mut graph, GraphDelta::RemoveNode { key: b });
1979
1980        set_captured_delta_hook(None);
1981
1982        let out = captured.lock().expect("capture sink");
1983        assert_eq!(out.len(), 52);
1984        assert!(matches!(
1985            out[0],
1986            CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
1987        ));
1988        assert!(matches!(
1989            out[1],
1990            CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
1991        ));
1992        assert!(matches!(
1993            out[2],
1994            CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
1995        ));
1996        assert!(matches!(
1997            out[3],
1998            CapturedDelta::ReplayAssertRelationByIds { .. }
1999        ));
2000        assert!(matches!(
2001            out[4],
2002            CapturedDelta::ReplayAppendTraversalByIds { .. }
2003        ));
2004        assert!(matches!(
2005            out[5],
2006            CapturedDelta::ReplaySetNodeTitleById { .. }
2007        ));
2008        assert!(matches!(out[6], CapturedDelta::ReplaySetNodeUrlById { .. }));
2009        assert!(matches!(
2010            out[7],
2011            CapturedDelta::ReplaySetNodeImageById { .. }
2012        ));
2013        assert!(matches!(
2014            out[8],
2015            CapturedDelta::ReplaySetNodeImageById { .. }
2016        ));
2017        assert!(matches!(
2018            out[9],
2019            CapturedDelta::ReplaySetNodeMimeHintById { .. }
2020        ));
2021        assert!(matches!(
2022            out[10],
2023            CapturedDelta::ReplaySetNodePinnedById { .. }
2024        ));
2025        assert!(matches!(
2026            out[11],
2027            CapturedDelta::ReplayInsertNodeTagById { .. }
2028        ));
2029        assert!(matches!(
2030            out[12],
2031            CapturedDelta::ReplayRemoveNodeTagById { .. }
2032        ));
2033        assert!(matches!(
2034            out[13],
2035            CapturedDelta::ReplaySetNodeBodyById { .. }
2036        ));
2037        assert!(matches!(
2038            out[14],
2039            CapturedDelta::ReplayTouchNodeLastVisitedById { .. }
2040        ));
2041        assert!(matches!(
2042            out[15],
2043            CapturedDelta::ReplayInsertNodeTagById { .. }
2044        ));
2045        assert!(matches!(
2046            out[16],
2047            CapturedDelta::ReplaySetNodeTagIconOverrideById { .. }
2048        ));
2049        assert!(matches!(
2050            out[17],
2051            CapturedDelta::ReplayNavigateNodeById { .. }
2052        ));
2053        assert!(matches!(
2054            out[18],
2055            CapturedDelta::ReplayNavigateNodeById { .. }
2056        ));
2057        assert!(matches!(
2058            out[19],
2059            CapturedDelta::ReplayNodeHistoryBackById { .. }
2060        ));
2061        assert!(matches!(
2062            out[20],
2063            CapturedDelta::ReplayNodeHistoryForwardById { .. }
2064        ));
2065        assert!(matches!(
2066            out[21],
2067            CapturedDelta::ReplayBranchHistoryByIds { .. }
2068        ));
2069        assert!(matches!(
2070            out[22],
2071            CapturedDelta::ReplayNavigateNodeById { .. }
2072        ));
2073        assert!(matches!(out[23], CapturedDelta::ReplayAddField { .. }));
2074        assert!(matches!(out[24], CapturedDelta::ReplayAddCoupling { .. }));
2075        assert!(matches!(
2076            out[25],
2077            CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId { .. }
2078        ));
2079        assert!(matches!(
2080            out[26],
2081            CapturedDelta::ReplayRetireFieldById { .. }
2082        ));
2083        assert!(matches!(
2084            out[27],
2085            CapturedDelta::ReplayActivateFieldById { .. }
2086        ));
2087        assert!(matches!(
2088            out[28],
2089            CapturedDelta::ReplayRetractCouplingById { .. }
2090        ));
2091        assert!(matches!(out[29], CapturedDelta::ReplayAddCoupling { .. }));
2092        assert!(matches!(
2093            out[30],
2094            CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId { .. }
2095        ));
2096        assert!(matches!(
2097            out[31],
2098            CapturedDelta::ReplayAppendNodePropertyById { .. }
2099        ));
2100        assert!(matches!(
2101            out[32],
2102            CapturedDelta::ReplayAddNodeClassificationById { .. }
2103        ));
2104        assert!(matches!(
2105            out[33],
2106            CapturedDelta::ReplayAddNodeClassificationById { .. }
2107        ));
2108        assert!(matches!(
2109            out[34],
2110            CapturedDelta::ReplayAddNodeClassificationById { .. }
2111        ));
2112        assert!(matches!(
2113            out[35],
2114            CapturedDelta::ReplaySetNodeClassificationStatusById { .. }
2115        ));
2116        assert!(matches!(
2117            out[36],
2118            CapturedDelta::ReplaySetNodePrimaryClassificationById { .. }
2119        ));
2120        assert!(matches!(
2121            out[37],
2122            CapturedDelta::ReplayRemoveNodeClassificationById { .. }
2123        ));
2124        assert!(matches!(
2125            out[38],
2126            CapturedDelta::ReplayRecordNodeDerivationById { .. }
2127        ));
2128        assert!(matches!(
2129            out[39],
2130            CapturedDelta::ReplaySetEdgeSemanticPredicateByIds { .. }
2131        ));
2132        assert!(matches!(
2133            out[40],
2134            CapturedDelta::ReplayAssertSemanticPredicateByIds { .. }
2135        ));
2136        assert!(matches!(
2137            out[41],
2138            CapturedDelta::ReplayAppendFrameLayoutHintById { .. }
2139        ));
2140        assert!(matches!(
2141            out[42],
2142            CapturedDelta::ReplayAppendFrameLayoutHintById { .. }
2143        ));
2144        assert!(matches!(
2145            out[43],
2146            CapturedDelta::ReplayMoveFrameLayoutHintById { .. }
2147        ));
2148        assert!(matches!(
2149            out[44],
2150            CapturedDelta::ReplayRemoveFrameLayoutHintById { .. }
2151        ));
2152        assert!(matches!(
2153            out[45],
2154            CapturedDelta::ReplaySetFrameSplitOfferSuppressedById { .. }
2155        ));
2156        assert!(matches!(
2157            out[46],
2158            CapturedDelta::ReplayUpdateNodeHistoryById { .. }
2159        ));
2160        assert!(matches!(
2161            out[47],
2162            CapturedDelta::ReplaySetImportRecords { .. }
2163        ));
2164        assert!(matches!(
2165            out[48],
2166            CapturedDelta::ReplaySetImportRecords { .. }
2167        ));
2168        assert!(matches!(
2169            out[49],
2170            CapturedDelta::ReplaySetImportRecords { .. }
2171        ));
2172        assert!(matches!(
2173            out[50],
2174            CapturedDelta::ReplayRetractRelationsByIds { .. }
2175        ));
2176        assert!(matches!(
2177            out[51],
2178            CapturedDelta::ReplayRemoveNodeById { .. }
2179        ));
2180    }
2181}