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