1use std::cell::RefCell;
18use std::collections::BTreeMap;
19use std::sync::Arc;
20
21use chartulary::stemma::TransitionKind;
22use euclid::default::Point2D;
23use rkyv::{Archive, Deserialize, Serialize};
24use uuid::Uuid;
25
26use super::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
27use super::{
28 Coupling, CouplingResponse, EdgeAssertion, Field, FieldDefinition, FieldExtent, FieldId,
29 FieldLifecycle, FrameLayoutHint, Graph, NavigationTrigger, NodeSelector, RelationSelector,
30};
31use crate::persistence::{
32 PersistedCoupling, PersistedCouplingResponse, PersistedEdge, PersistedField,
33 PersistedFieldExtent, PersistedFieldLifecycle, PersistedNodeSelector, PersistedResourceRecord,
34};
35use crate::types::{
36 BadgeIcon, ClassificationScheme, ClassificationStatus, ImageRef, ImageRole, ImportRecord,
37 NodeClassification, NodeDerivation, NodeProperty,
38};
39
40mod edge_assertion_compat;
41mod replay_outcome;
42pub(crate) use replay_outcome::replay_outcomes_onto;
43pub use replay_outcome::{Malformed, Replay, Unwritable};
44
45#[cfg(test)]
46mod decay_compat_tests;
47#[cfg(test)]
48mod replay_outcome_tests;
49
50#[derive(
52 Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
53)]
54pub enum CapturedDelta {
55 ReplayAddNodeWithIdIfMissing {
56 id: String,
57 url: String,
58 position: [f32; 2],
59 },
60 ReplayAssertRelationByIds {
61 from_id: String,
62 to_id: String,
63 #[serde(with = "edge_assertion_compat")]
64 #[rkyv(with = edge_assertion_compat::Rkyv)]
65 assertion: EdgeAssertion,
66 },
67 ReplayRemoveNodeById {
68 node_id: String,
69 },
70 ReplayRetractRelationsByIds {
71 from_id: String,
72 to_id: String,
73 selector: RelationSelector,
74 },
75 ReplayAppendTraversalByIds {
76 from_id: String,
77 to_id: String,
78 trigger: NavigationTrigger,
79 timestamp_ms: u64,
80 },
81 ReplaySetNodeTitleById {
82 node_id: String,
83 title: String,
84 },
85 ReplaySetNodeUrlById {
86 node_id: String,
87 new_url: String,
88 },
89 ReplaySetNodeImageById {
90 node_id: String,
91 role: ImageRole,
92 image: ImageRef,
93 },
94 ReplaySetNodeThumbnailById {
103 node_id: String,
104 png_bytes: Vec<u8>,
105 width: u32,
106 height: u32,
107 },
108 ReplaySetNodeFaviconById {
109 node_id: String,
110 rgba: Vec<u8>,
111 width: u32,
112 height: u32,
113 },
114 ReplaySetNodeMimeHintById {
115 node_id: String,
116 mime_hint: Option<String>,
117 },
118 ReplaySetNodeNestedById {
119 node_id: String,
120 nested: Option<String>,
121 },
122 ReplaySetNodePinnedById {
123 node_id: String,
124 is_pinned: bool,
125 },
126 ReplaySetNodeFacetById {
127 node_id: String,
128 facet: String,
129 value_json: String,
130 },
131 ReplayRemoveNodeFacetById {
132 node_id: String,
133 facet: String,
134 },
135 ReplayInsertNodeTagById {
136 node_id: String,
137 tag: String,
138 },
139 ReplayRemoveNodeTagById {
140 node_id: String,
141 tag: String,
142 },
143 ReplaySetNodeBodyById {
144 node_id: String,
145 body: Option<String>,
146 },
147 ReplayNavigateNodeById {
148 node_id: String,
149 url: String,
150 transition: TransitionKind,
151 timestamp_ms: u64,
152 last_session_visited: u64,
153 },
154 ReplayBranchHistoryByIds {
155 child_id: String,
156 parent_id: String,
157 },
158 ReplayNodeHistoryBackById {
159 node_id: String,
160 timestamp_ms: u64,
161 },
162 ReplayNodeHistoryForwardById {
163 node_id: String,
164 timestamp_ms: u64,
165 },
166 ReplayAppendNodePropertyById {
167 node_id: String,
168 property: NodeProperty,
169 },
170 ReplayAddNodeClassificationById {
171 node_id: String,
172 classification: NodeClassification,
173 },
174 ReplayRemoveNodeClassificationById {
175 node_id: String,
176 scheme: ClassificationScheme,
177 value: String,
178 },
179 ReplaySetNodeClassificationStatusById {
180 node_id: String,
181 scheme: ClassificationScheme,
182 value: String,
183 status: ClassificationStatus,
184 },
185 ReplaySetNodePrimaryClassificationById {
186 node_id: String,
187 scheme: ClassificationScheme,
188 value: String,
189 },
190 ReplayRecordNodeDerivationById {
191 node_id: String,
192 derivation: NodeDerivation,
193 },
194 ReplaySetNodeTagIconOverrideById {
195 node_id: String,
196 tag: String,
197 icon: Option<BadgeIcon>,
198 },
199 ReplaySetEdgeSemanticPredicateByIds {
200 from_id: String,
201 to_id: String,
202 predicate: Option<String>,
203 },
204 ReplayAssertSemanticPredicateByIds {
205 from_id: String,
206 to_id: String,
207 predicate: String,
208 },
209 ReplayAppendFrameLayoutHintById {
210 node_id: String,
211 hint: FrameLayoutHint,
212 },
213 ReplayRemoveFrameLayoutHintById {
214 node_id: String,
215 hint_index: usize,
216 },
217 ReplayMoveFrameLayoutHintById {
218 node_id: String,
219 from_index: usize,
220 to_index: usize,
221 },
222 ReplaySetFrameSplitOfferSuppressedById {
223 node_id: String,
224 suppressed: bool,
225 },
226 ReplayUpdateNodeHistoryById {
227 node_id: String,
228 entries: Vec<String>,
229 current_index: usize,
230 },
231 ReplaySetImportRecords {
232 import_records: Vec<ImportRecord>,
233 },
234 ReplaySetEdgesByIds {
237 from_id: String,
238 to_id: String,
239 edges: Vec<PersistedEdge>,
240 },
241 ReplayTouchNodeLastVisitedById {
242 node_id: String,
243 timestamp_ms: u64,
244 },
245 ReplayAddField {
246 field: PersistedField,
247 },
248 ReplayRetireFieldById {
249 field_id: String,
250 },
251 ReplayRemoveFieldById {
253 field_id: String,
254 },
255 ReplayAddCoupling {
256 coupling: PersistedCoupling,
257 },
258 ReplaySetFieldCouplingStrengthByFieldId {
259 field_id: String,
260 strength: f32,
261 },
262 ReplayActivateFieldById {
263 field_id: String,
264 },
265 ReplayRetractCouplingById {
266 coupling_id: String,
267 },
268 ReplaySetNodeContentById {
270 node_id: String,
271 content: Option<[u8; 32]>,
272 },
273 ReplaySetResourceRecordById {
274 resource_id: String,
275 record: Option<PersistedResourceRecord>,
276 },
277 ReplaySetResourceEdgesByIds {
278 from_resource_id: String,
279 to_resource_id: String,
280 edges: Vec<PersistedEdge>,
281 },
282 ReplaySetShownResourceById {
283 surface_id: String,
284 resource_id: Option<String>,
285 },
286}
287
288impl CapturedDelta {
289 pub fn replay(&self) -> Replay {
293 Replay::Apply(match self {
294 Self::ReplayAddNodeWithIdIfMissing { id, url, position } => {
295 GraphDelta::ReplayAddNodeWithIdIfMissing {
296 id: parse_uuid(id),
297 url: url.clone(),
298 position: Point2D::new(position[0], position[1]),
299 }
300 },
301 Self::ReplayAssertRelationByIds {
302 from_id,
303 to_id,
304 assertion,
305 } => GraphDelta::ReplayAssertRelationByIds {
306 from_id: parse_uuid(from_id),
307 to_id: parse_uuid(to_id),
308 assertion: assertion.clone(),
309 asserter_iri: super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into(),
310 },
311 Self::ReplayRemoveNodeById { node_id } => GraphDelta::ReplayRemoveNodeById {
312 node_id: parse_uuid(node_id),
313 },
314 Self::ReplayRetractRelationsByIds {
315 from_id,
316 to_id,
317 selector,
318 } => GraphDelta::ReplayRetractRelationsByIds {
319 from_id: parse_uuid(from_id),
320 to_id: parse_uuid(to_id),
321 selector: *selector,
322 },
323 Self::ReplayAppendTraversalByIds {
324 from_id,
325 to_id,
326 trigger,
327 timestamp_ms,
328 } => GraphDelta::ReplayAppendTraversalByIds {
329 from_id: parse_uuid(from_id),
330 to_id: parse_uuid(to_id),
331 trigger: *trigger,
332 timestamp_ms: *timestamp_ms,
333 },
334 Self::ReplaySetNodeTitleById { node_id, title } => GraphDelta::ReplaySetNodeTitleById {
335 node_id: parse_uuid(node_id),
336 title: title.clone(),
337 },
338 Self::ReplaySetNodeUrlById { node_id, new_url } => GraphDelta::ReplaySetNodeUrlById {
339 node_id: parse_uuid(node_id),
340 new_url: new_url.clone(),
341 },
342 Self::ReplaySetNodeImageById {
343 node_id,
344 role,
345 image,
346 } => GraphDelta::ReplaySetNodeImageById {
347 node_id: parse_uuid(node_id),
348 role: *role,
349 image: *image,
350 },
351 Self::ReplaySetNodeThumbnailById { .. } | Self::ReplaySetNodeFaviconById { .. } => {
355 return Replay::Skip;
356 },
357 Self::ReplaySetNodeMimeHintById { node_id, mime_hint } => {
358 GraphDelta::ReplaySetNodeMimeHintById {
359 node_id: parse_uuid(node_id),
360 mime_hint: mime_hint.clone(),
361 }
362 },
363 Self::ReplaySetNodeContentById { node_id, content } => {
364 GraphDelta::ReplaySetNodeContentById {
365 node_id: parse_uuid(node_id),
366 content: content.map(muniment::Hash::from_bytes),
367 }
368 },
369 Self::ReplaySetNodeNestedById { node_id, nested } => {
370 GraphDelta::ReplaySetNodeNestedById {
371 node_id: parse_uuid(node_id),
372 nested: nested.clone(),
373 }
374 },
375 Self::ReplaySetNodePinnedById { node_id, is_pinned } => {
376 GraphDelta::ReplaySetNodePinnedById {
377 node_id: parse_uuid(node_id),
378 is_pinned: *is_pinned,
379 }
380 },
381 Self::ReplaySetNodeFacetById {
382 node_id,
383 facet,
384 value_json,
385 } => {
386 let value = match serde_json::from_str(value_json) {
387 Ok(value) => value,
388 Err(error) => return Replay::Malformed(Malformed::new(node_id, facet, error)),
389 };
390 GraphDelta::ReplaySetNodeFacetById {
391 node_id: parse_uuid(node_id),
392 facet: facet.clone(),
393 value,
394 }
395 },
396 Self::ReplayRemoveNodeFacetById { node_id, facet } => {
397 GraphDelta::ReplayRemoveNodeFacetById {
398 node_id: parse_uuid(node_id),
399 facet: facet.clone(),
400 }
401 },
402 Self::ReplayInsertNodeTagById { node_id, tag } => GraphDelta::ReplayInsertNodeTagById {
403 node_id: parse_uuid(node_id),
404 tag: tag.clone(),
405 },
406 Self::ReplayRemoveNodeTagById { node_id, tag } => GraphDelta::ReplayRemoveNodeTagById {
407 node_id: parse_uuid(node_id),
408 tag: tag.clone(),
409 },
410 Self::ReplaySetNodeBodyById { node_id, body } => GraphDelta::ReplaySetNodeBodyById {
411 node_id: parse_uuid(node_id),
412 body: body.clone(),
413 },
414 Self::ReplayNavigateNodeById {
415 node_id,
416 url,
417 transition,
418 timestamp_ms,
419 last_session_visited,
420 } => GraphDelta::ReplayNavigateNodeById {
421 node_id: parse_uuid(node_id),
422 url: url.clone(),
423 transition: *transition,
424 timestamp_ms: *timestamp_ms,
425 last_session_visited: *last_session_visited,
426 },
427 Self::ReplayBranchHistoryByIds {
428 child_id,
429 parent_id,
430 } => GraphDelta::ReplayBranchHistoryByIds {
431 child_id: parse_uuid(child_id),
432 parent_id: parse_uuid(parent_id),
433 },
434 Self::ReplayNodeHistoryBackById {
435 node_id,
436 timestamp_ms,
437 } => GraphDelta::ReplayNodeHistoryBackById {
438 node_id: parse_uuid(node_id),
439 timestamp_ms: *timestamp_ms,
440 },
441 Self::ReplayNodeHistoryForwardById {
442 node_id,
443 timestamp_ms,
444 } => GraphDelta::ReplayNodeHistoryForwardById {
445 node_id: parse_uuid(node_id),
446 timestamp_ms: *timestamp_ms,
447 },
448 Self::ReplayAppendNodePropertyById { node_id, property } => {
449 GraphDelta::ReplayAppendNodePropertyById {
450 node_id: parse_uuid(node_id),
451 property: property.clone(),
452 }
453 },
454 Self::ReplayAddNodeClassificationById {
455 node_id,
456 classification,
457 } => GraphDelta::ReplayAddNodeClassificationById {
458 node_id: parse_uuid(node_id),
459 classification: classification.clone(),
460 },
461 Self::ReplayRemoveNodeClassificationById {
462 node_id,
463 scheme,
464 value,
465 } => GraphDelta::ReplayRemoveNodeClassificationById {
466 node_id: parse_uuid(node_id),
467 scheme: scheme.clone(),
468 value: value.clone(),
469 },
470 Self::ReplaySetNodeClassificationStatusById {
471 node_id,
472 scheme,
473 value,
474 status,
475 } => GraphDelta::ReplaySetNodeClassificationStatusById {
476 node_id: parse_uuid(node_id),
477 scheme: scheme.clone(),
478 value: value.clone(),
479 status: status.clone(),
480 },
481 Self::ReplaySetNodePrimaryClassificationById {
482 node_id,
483 scheme,
484 value,
485 } => GraphDelta::ReplaySetNodePrimaryClassificationById {
486 node_id: parse_uuid(node_id),
487 scheme: scheme.clone(),
488 value: value.clone(),
489 },
490 Self::ReplayRecordNodeDerivationById {
491 node_id,
492 derivation,
493 } => GraphDelta::ReplayRecordNodeDerivationById {
494 node_id: parse_uuid(node_id),
495 derivation: derivation.clone(),
496 },
497 Self::ReplaySetNodeTagIconOverrideById { node_id, tag, icon } => {
498 GraphDelta::ReplaySetNodeTagIconOverrideById {
499 node_id: parse_uuid(node_id),
500 tag: tag.clone(),
501 icon: icon.clone(),
502 }
503 },
504 Self::ReplaySetEdgeSemanticPredicateByIds {
505 from_id,
506 to_id,
507 predicate,
508 } => GraphDelta::ReplaySetEdgeSemanticPredicateByIds {
509 from_id: parse_uuid(from_id),
510 to_id: parse_uuid(to_id),
511 predicate: predicate.clone(),
512 asserter_iri: super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into(),
513 },
514 Self::ReplayAssertSemanticPredicateByIds {
515 from_id,
516 to_id,
517 predicate,
518 } => GraphDelta::ReplayAssertSemanticPredicateByIds {
519 from_id: parse_uuid(from_id),
520 to_id: parse_uuid(to_id),
521 predicate: predicate.clone(),
522 asserter_iri: super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into(),
523 },
524 Self::ReplayAppendFrameLayoutHintById { node_id, hint } => {
525 GraphDelta::ReplayAppendFrameLayoutHintById {
526 node_id: parse_uuid(node_id),
527 hint: hint.clone(),
528 }
529 },
530 Self::ReplayRemoveFrameLayoutHintById {
531 node_id,
532 hint_index,
533 } => GraphDelta::ReplayRemoveFrameLayoutHintById {
534 node_id: parse_uuid(node_id),
535 hint_index: *hint_index,
536 },
537 Self::ReplayMoveFrameLayoutHintById {
538 node_id,
539 from_index,
540 to_index,
541 } => GraphDelta::ReplayMoveFrameLayoutHintById {
542 node_id: parse_uuid(node_id),
543 from_index: *from_index,
544 to_index: *to_index,
545 },
546 Self::ReplaySetFrameSplitOfferSuppressedById {
547 node_id,
548 suppressed,
549 } => GraphDelta::ReplaySetFrameSplitOfferSuppressedById {
550 node_id: parse_uuid(node_id),
551 suppressed: *suppressed,
552 },
553 Self::ReplayUpdateNodeHistoryById {
554 node_id,
555 entries,
556 current_index,
557 } => GraphDelta::ReplayUpdateNodeHistoryById {
558 node_id: parse_uuid(node_id),
559 entries: entries.clone(),
560 current_index: *current_index,
561 },
562 Self::ReplaySetImportRecords { import_records } => GraphDelta::ReplaySetImportRecords {
563 import_records: import_records.clone(),
564 },
565 Self::ReplaySetEdgesByIds {
566 from_id,
567 to_id,
568 edges,
569 } => GraphDelta::ReplaySetEdgesByIds {
570 from_id: parse_uuid(from_id),
571 to_id: parse_uuid(to_id),
572 edges: edges.clone(),
573 },
574 Self::ReplaySetResourceRecordById {
575 resource_id,
576 record,
577 } => GraphDelta::ReplaySetResourceRecordById {
578 resource_id: parse_uuid(resource_id),
579 record: record.clone(),
580 },
581 Self::ReplaySetResourceEdgesByIds {
582 from_resource_id,
583 to_resource_id,
584 edges,
585 } => GraphDelta::ReplaySetResourceEdgesByIds {
586 from_resource_id: parse_uuid(from_resource_id),
587 to_resource_id: parse_uuid(to_resource_id),
588 edges: edges.clone(),
589 },
590 Self::ReplaySetShownResourceById {
591 surface_id,
592 resource_id,
593 } => GraphDelta::ReplaySetShownResourceById {
594 surface_id: parse_uuid(surface_id),
595 resource_id: resource_id.as_deref().map(parse_uuid),
596 },
597 Self::ReplayTouchNodeLastVisitedById {
598 node_id,
599 timestamp_ms,
600 } => GraphDelta::ReplayTouchNodeLastVisitedById {
601 node_id: parse_uuid(node_id),
602 timestamp_ms: *timestamp_ms,
603 },
604 Self::ReplayAddField { field } => GraphDelta::ReplayAddField {
605 field: field.clone(),
606 },
607 Self::ReplayRetireFieldById { field_id } => GraphDelta::ReplayRetireFieldById {
608 field_id: field_id.clone(),
609 },
610 Self::ReplayRemoveFieldById { field_id } => GraphDelta::ReplayRemoveFieldById {
611 field_id: field_id.clone(),
612 },
613 Self::ReplayAddCoupling { coupling } => GraphDelta::ReplayAddCoupling {
614 coupling: coupling.clone(),
615 },
616 Self::ReplaySetFieldCouplingStrengthByFieldId { field_id, strength } => {
617 GraphDelta::ReplaySetFieldCouplingStrengthByFieldId {
618 field_id: field_id.clone(),
619 strength: *strength,
620 }
621 },
622 Self::ReplayActivateFieldById { field_id } => GraphDelta::ReplayActivateFieldById {
623 field_id: field_id.clone(),
624 },
625 Self::ReplayRetractCouplingById { coupling_id } => {
626 GraphDelta::ReplayRetractCouplingById {
627 coupling_id: coupling_id.clone(),
628 }
629 },
630 })
631 }
632 pub fn replay_as(&self, author: &super::Author) -> Replay {
635 let mut replay = self.replay();
636 if let Replay::Apply(
637 GraphDelta::ReplayAssertRelationByIds { asserter_iri, .. }
638 | GraphDelta::ReplayAssertSemanticPredicateByIds { asserter_iri, .. }
639 | GraphDelta::ReplaySetEdgeSemanticPredicateByIds { asserter_iri, .. },
640 ) = &mut replay
641 {
642 *asserter_iri = author.asserter_iri();
643 }
644 replay
645 }
646}
647
648fn parse_uuid(id: &str) -> Uuid {
649 Uuid::parse_str(id).expect("captured stable ids should always parse")
650}
651
652pub(crate) fn persisted_field_from_field(field: &Field) -> PersistedField {
653 PersistedField {
654 id: field.id.as_uuid().to_string(),
655 name: field.name.clone(),
656 definition_json: serde_json::to_string(&field.definition).unwrap_or_default(),
657 extent: match &field.extent {
658 FieldExtent::Global => PersistedFieldExtent::Global,
659 FieldExtent::Region {
660 min_x,
661 min_y,
662 max_x,
663 max_y,
664 } => PersistedFieldExtent::Region {
665 min_x: *min_x,
666 min_y: *min_y,
667 max_x: *max_x,
668 max_y: *max_y,
669 },
670 FieldExtent::AttachedToNode(id) => PersistedFieldExtent::AttachedToNode(id.to_string()),
671 FieldExtent::Polygon { points } => PersistedFieldExtent::Polygon {
672 points: points.clone(),
673 },
674 },
675 lifecycle: match field.lifecycle {
676 FieldLifecycle::Active => PersistedFieldLifecycle::Active,
677 FieldLifecycle::Retired => PersistedFieldLifecycle::Retired,
678 },
679 }
680}
681
682pub(crate) fn field_from_persisted(pfield: &PersistedField) -> Option<Field> {
683 let id = Uuid::parse_str(&pfield.id).ok()?;
684 let definition = serde_json::from_str::<FieldDefinition>(&pfield.definition_json).ok()?;
685 let extent = match &pfield.extent {
686 PersistedFieldExtent::Global => FieldExtent::Global,
687 PersistedFieldExtent::Region {
688 min_x,
689 min_y,
690 max_x,
691 max_y,
692 } => FieldExtent::Region {
693 min_x: *min_x,
694 min_y: *min_y,
695 max_x: *max_x,
696 max_y: *max_y,
697 },
698 PersistedFieldExtent::AttachedToNode(s) => Uuid::parse_str(s)
699 .map(FieldExtent::AttachedToNode)
700 .unwrap_or(FieldExtent::Global),
701 PersistedFieldExtent::Polygon { points } => FieldExtent::Polygon {
702 points: points.clone(),
703 },
704 };
705 let mut field = Field::new(FieldId::from_uuid(id), definition).with_extent(extent);
706 if let Some(name) = &pfield.name {
707 field = field.with_name(name.clone());
708 }
709 field.lifecycle = match pfield.lifecycle {
710 PersistedFieldLifecycle::Active => FieldLifecycle::Active,
711 PersistedFieldLifecycle::Retired => FieldLifecycle::Retired,
712 };
713 Some(field)
714}
715
716pub(crate) fn persisted_coupling_from_coupling(coupling: &Coupling) -> PersistedCoupling {
717 PersistedCoupling {
718 id: coupling.id.as_uuid().to_string(),
719 field_id: coupling.field.as_uuid().to_string(),
720 selector: match &coupling.selector {
721 NodeSelector::All => PersistedNodeSelector::All,
722 NodeSelector::Tagged(tag) => PersistedNodeSelector::Tagged(tag.clone()),
723 NodeSelector::Kind(kind) => PersistedNodeSelector::Kind(kind.clone()),
724 NodeSelector::NotTagged(tag) => PersistedNodeSelector::NotTagged(tag.clone()),
725 },
726 response: match &coupling.response {
727 CouplingResponse::AttractToMin => PersistedCouplingResponse::AttractToMin,
728 CouplingResponse::RepelFromMax => PersistedCouplingResponse::RepelFromMax,
729 CouplingResponse::AlignVelocity => PersistedCouplingResponse::AlignVelocity,
730 CouplingResponse::FlowAdvect => PersistedCouplingResponse::FlowAdvect,
731 CouplingResponse::DampenInside { factor } => {
732 PersistedCouplingResponse::DampenInside { factor: *factor }
733 },
734 CouplingResponse::ContainmentWall => PersistedCouplingResponse::ContainmentWall,
735 CouplingResponse::Open { predicate } => PersistedCouplingResponse::Open {
736 predicate: predicate.clone(),
737 },
738 },
739 strength: coupling.strength,
740 }
741}
742
743pub(crate) fn coupling_from_persisted(pcoupling: &PersistedCoupling) -> Option<Coupling> {
744 let cid = Uuid::parse_str(&pcoupling.id).ok()?;
745 let fid = Uuid::parse_str(&pcoupling.field_id).ok()?;
746 let selector = match &pcoupling.selector {
747 PersistedNodeSelector::All => NodeSelector::All,
748 PersistedNodeSelector::Tagged(tag) => NodeSelector::Tagged(tag.clone()),
749 PersistedNodeSelector::Kind(kind) => NodeSelector::Kind(kind.clone()),
750 PersistedNodeSelector::NotTagged(tag) => NodeSelector::NotTagged(tag.clone()),
751 };
752 let response = match &pcoupling.response {
753 PersistedCouplingResponse::AttractToMin => CouplingResponse::AttractToMin,
754 PersistedCouplingResponse::RepelFromMax => CouplingResponse::RepelFromMax,
755 PersistedCouplingResponse::AlignVelocity => CouplingResponse::AlignVelocity,
756 PersistedCouplingResponse::FlowAdvect => CouplingResponse::FlowAdvect,
757 PersistedCouplingResponse::DampenInside { factor } => {
758 CouplingResponse::DampenInside { factor: *factor }
759 },
760 PersistedCouplingResponse::ContainmentWall => CouplingResponse::ContainmentWall,
761 PersistedCouplingResponse::Open { predicate } => CouplingResponse::Open {
762 predicate: predicate.clone(),
763 },
764 };
765 Some(Coupling::new(
766 super::CouplingId::from_uuid(cid),
767 FieldId::from_uuid(fid),
768 selector,
769 response,
770 pcoupling.strength,
771 ))
772}
773
774#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
776pub struct GraphTableStats {
777 pub node_count: usize,
778 pub edge_count: usize,
779 pub relation_count: usize,
780 pub field_count: usize,
781 pub coupling_count: usize,
782 pub history_owner_count: usize,
783 pub history_entry_count: usize,
784 pub history_visit_count: usize,
785}
786
787impl Graph {
788 pub fn table_stats(&self) -> GraphTableStats {
790 GraphTableStats {
791 node_count: self.node_count(),
792 edge_count: self.edge_count(),
793 relation_count: self.relations().count(),
794 field_count: self.fields().count(),
795 coupling_count: self.couplings().count(),
796 history_owner_count: self.nav.owner_count(),
797 history_entry_count: self.nav.entry_count(),
798 history_visit_count: self.nav.visit_count(),
799 }
800 }
801}
802
803pub fn replay_captured_deltas<I>(deltas: I) -> Graph
805where
806 I: IntoIterator<Item = CapturedDelta>,
807{
808 let mut graph = Graph::new();
809 replay_captured_deltas_onto(&mut graph, deltas);
810 graph
811}
812
813pub fn replay_captured_deltas_onto<I>(graph: &mut Graph, deltas: I)
823where
824 I: IntoIterator<Item = CapturedDelta>,
825{
826 let _ = replay_outcomes_onto(
830 graph,
831 deltas.into_iter().map(|delta| delta.replay()),
832 OnRefusal::Drop,
833 );
834}
835
836pub fn replay_captured_deltas_onto_checked<I>(
840 graph: &mut Graph,
841 deltas: I,
842) -> Result<(), ReplayRefused>
843where
844 I: IntoIterator<Item = CapturedDelta>,
845{
846 replay_outcomes_onto(
847 graph,
848 deltas.into_iter().map(|delta| delta.replay()),
849 OnRefusal::Stop,
850 )
851}
852
853pub fn replay_captured_deltas_as_onto<I>(graph: &mut Graph, author: &super::Author, deltas: I)
856where
857 I: IntoIterator<Item = CapturedDelta>,
858{
859 let _ = replay_outcomes_onto(
860 graph,
861 deltas.into_iter().map(|delta| delta.replay_as(author)),
862 OnRefusal::Drop,
863 );
864}
865
866pub(crate) struct ReplayAttribution(
868 BTreeMap<String, String>,
869 super::legacy_family_attribution::LegacyFamilyAttribution,
870);
871
872impl ReplayAttribution {
873 pub(crate) fn from_baseline(graph: &Graph) -> Self {
874 let mut attribution = Self(
875 BTreeMap::new(),
876 super::legacy_family_attribution::LegacyFamilyAttribution::from_baseline(graph),
877 );
878 attribution.observe_graph(graph);
879 attribution
880 }
881
882 fn observe_graph(&mut self, graph: &Graph) {
883 for edge in graph
884 .inner
885 .inner()
886 .edge_weights()
887 .chain(graph.resources.inner().edge_weights())
888 {
889 for statement in edge.assertions() {
890 if statement.statement_id.starts_with(
891 super::legacy_family_attribution::LEGACY_FAMILY_ASSERTION_ID_PREFIX,
892 ) {
893 continue;
894 }
895 self.0
896 .entry(statement.statement_id.clone())
897 .or_insert_with(|| {
898 statement
899 .provenance_iri
900 .clone()
901 .unwrap_or_else(|| super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into())
902 });
903 }
904 }
905 }
906
907 pub(crate) fn repair_checkpoint(&self, graph: &mut Graph) {
908 let changed = self.repair_edges(&mut graph.inner) | self.repair_edges(&mut graph.resources);
909 if changed {
910 graph.bump_revision();
911 }
912 self.1.repair_checkpoint(graph);
913 }
914
915 fn repair_edges<N: chartulary::Identified>(
916 &self,
917 graph: &mut chartulary::Graph<N, super::EdgePayload>,
918 ) -> bool {
919 let unknown = super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI;
920 let keys: Vec<_> = graph.inner().edge_indices().collect();
921 let mut changed = false;
922 for key in keys {
923 if let Some(payload) = graph.edge_mut(key) {
924 let semantic = &mut payload.assertions;
925 for statement in &mut semantic.statements {
926 if statement.statement_id.starts_with(
927 super::legacy_family_attribution::LEGACY_FAMILY_ASSERTION_ID_PREFIX,
928 ) {
929 continue;
930 }
931 if statement
932 .provenance_iri
933 .as_deref()
934 .is_none_or(|source| source == unknown)
935 && let Some(source) = self.0.get(&statement.statement_id)
936 && statement.provenance_iri.as_deref() != Some(source.as_str())
937 {
938 statement.provenance_iri = Some(source.clone());
939 changed = true;
940 }
941 }
942 }
943 }
944 changed
945 }
946
947 pub(crate) fn replay(&mut self, delta: &CapturedDelta, author: &super::Author) -> Replay {
948 let mut delta = match delta.replay_as(author) {
949 Replay::Apply(delta) => delta,
950 other => return other,
951 };
952 if let GraphDelta::ReplaySetEdgesByIds { edges, .. }
953 | GraphDelta::ReplaySetResourceEdgesByIds { edges, .. } = &mut delta
954 {
955 for edge in edges {
956 for statement in edge.retained_assertions_mut() {
957 if statement.statement_id.starts_with(
958 super::legacy_family_attribution::LEGACY_FAMILY_ASSERTION_ID_PREFIX,
959 ) {
960 continue;
964 }
965 let original =
966 self.0
967 .entry(statement.statement_id.clone())
968 .or_insert_with(|| {
969 statement
970 .provenance_iri
971 .clone()
972 .unwrap_or_else(|| author.asserter_iri())
973 });
974 if statement.provenance_iri.is_none() {
975 statement.provenance_iri = Some(original.clone());
976 }
977 }
978 }
979 }
980 Replay::Apply(delta)
981 }
982}
983
984#[derive(Debug, Clone, PartialEq, Eq)]
987pub struct ReplayRefused {
988 pub position: usize,
989 pub reason: super::resource_content::ContentError,
990}
991
992impl std::fmt::Display for ReplayRefused {
993 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
994 write!(
995 f,
996 "replayed entry {} refused: {}",
997 self.position, self.reason
998 )
999 }
1000}
1001
1002impl std::error::Error for ReplayRefused {}
1003
1004#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1007pub(crate) enum OnRefusal {
1008 Stop,
1009 Drop,
1010}
1011
1012pub(crate) fn replay_attributed_deltas_onto<'a, I>(
1013 graph: &mut Graph,
1014 attribution: &mut ReplayAttribution,
1015 entries: I,
1016 on_refusal: OnRefusal,
1017) -> Result<(), ReplayRefused>
1018where
1019 I: IntoIterator<Item = &'a super::journal::AttributedDelta>,
1020{
1021 replay_quietly(graph, |graph| {
1022 for (position, entry) in entries.into_iter().enumerate() {
1023 let delta = match attribution.replay(&entry.delta, &entry.author) {
1024 Replay::Apply(delta) => delta,
1025 Replay::Skip => continue,
1026 Replay::Malformed(bad) if on_refusal == OnRefusal::Stop => {
1027 return Err(bad.refused_at(position));
1028 },
1029 Replay::Malformed(_) => continue,
1030 };
1031 let legacy_assertion = matches!(
1032 delta,
1033 GraphDelta::ReplayAssertRelationByIds { .. }
1034 | GraphDelta::ReplayAssertSemanticPredicateByIds { .. }
1035 | GraphDelta::ReplaySetEdgeSemanticPredicateByIds { .. }
1036 );
1037 if let GraphDeltaResult::Refused(reason) = apply_graph_delta(graph, delta)
1038 && on_refusal == OnRefusal::Stop
1039 {
1040 return Err(ReplayRefused { position, reason });
1041 }
1042 attribution.1.observe_delta(graph, entry);
1043 if legacy_assertion {
1044 attribution.observe_graph(graph);
1045 }
1046 }
1047 Ok(())
1048 })
1049}
1050
1051pub(crate) fn replay_graph_deltas_onto<I>(
1052 graph: &mut Graph,
1053 deltas: I,
1054 on_refusal: OnRefusal,
1055) -> Result<(), ReplayRefused>
1056where
1057 I: IntoIterator<Item = GraphDelta>,
1058{
1059 replay_outcomes_onto(graph, deltas.into_iter().map(Replay::Apply), on_refusal)
1060}
1061
1062fn replay_quietly<R>(graph: &mut Graph, edit: impl FnOnce(&mut Graph) -> R) -> R {
1063 let _quiet = QuietThread::begin();
1064 let recorder = graph.recorder.0.take();
1065 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1066 graph.without_pending_derivation(edit)
1067 }));
1068 graph.recorder.0 = recorder;
1069 match result {
1070 Ok(result) => result,
1071 Err(panic) => std::panic::resume_unwind(panic),
1072 }
1073}
1074
1075type CaptureHook = dyn Fn(&CapturedDelta) + Send + Sync + 'static;
1076
1077pub type DeltaRecorder = Arc<CaptureHook>;
1080
1081#[derive(Default)]
1084pub(crate) struct Recorder(pub(crate) Option<DeltaRecorder>);
1085
1086impl Clone for Recorder {
1087 fn clone(&self) -> Self {
1088 Self(None)
1089 }
1090}
1091
1092thread_local! {
1093 static CAPTURE_HOOK: RefCell<Option<Arc<CaptureHook>>> = RefCell::new(None);
1094}
1095
1096pub fn set_captured_delta_hook(hook: Option<Arc<CaptureHook>>) {
1098 CAPTURE_HOOK.with(|slot| *slot.borrow_mut() = hook);
1099}
1100
1101struct QuietThread(Option<Arc<CaptureHook>>);
1104
1105impl QuietThread {
1106 fn begin() -> Self {
1107 Self(CAPTURE_HOOK.with(|slot| slot.borrow_mut().take()))
1108 }
1109}
1110
1111impl Drop for QuietThread {
1112 fn drop(&mut self) {
1113 let hook = self.0.take();
1114 CAPTURE_HOOK.with(|slot| *slot.borrow_mut() = hook);
1115 }
1116}
1117
1118pub fn with_isolated_capture<R>(edit: impl FnOnce() -> R) -> R {
1121 let _quiet = QuietThread::begin();
1122 edit()
1123}
1124
1125impl Graph {
1126 pub(crate) fn record_delta(&self, delta: &CapturedDelta) {
1129 if let Some(recorder) = &self.recorder.0 {
1130 recorder(delta);
1131 }
1132 CAPTURE_HOOK.with(|slot| {
1133 if let Some(hook) = slot.borrow().as_ref() {
1134 hook(delta);
1135 }
1136 });
1137 }
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142 use super::*;
1143 use std::sync::Mutex;
1144
1145 use crate::graph::{
1146 ContainmentSubKind, Coupling, CouplingId, CouplingResponse, EdgeAssertion, Field,
1147 FieldDefinition, FieldExtent, FieldId, Graph, NavigationTrigger, NodeSelector,
1148 ProvenanceSubKind, RelationKind, ScalarField, SemanticSubKind, SharedNavigationMemory,
1149 };
1150 use crate::types::{
1151 BadgeIcon, ClassificationProvenance, ClassificationScheme, ClassificationStatus,
1152 FrameLayoutHint, ImportRecordMembership, NodeClassification, NodeDerivation,
1153 NodeImportProvenance, NodeProperty, SplitOrientation,
1154 };
1155
1156 fn point(x: f32, y: f32) -> Point2D<f32> {
1157 Point2D::new(x, y)
1158 }
1159
1160 fn sample_field(id: FieldId) -> Field {
1161 Field::new(id, FieldDefinition::Scalar(ScalarField::Const(1.0)))
1162 .with_name("focus")
1163 .with_extent(FieldExtent::Region {
1164 min_x: -10.0,
1165 min_y: -20.0,
1166 max_x: 30.0,
1167 max_y: 40.0,
1168 })
1169 }
1170
1171 fn sample_coupling(id: CouplingId, field: FieldId) -> Coupling {
1172 Coupling::new(
1173 id,
1174 field,
1175 NodeSelector::Kind("paper".into()),
1176 CouplingResponse::DampenInside { factor: 0.3 },
1177 1.5,
1178 )
1179 }
1180
1181 #[test]
1182 fn structural_captured_delta_round_trips_through_postcard() {
1183 let delta = CapturedDelta::ReplayAssertRelationByIds {
1184 from_id: Uuid::from_u128(1).to_string(),
1185 to_id: Uuid::from_u128(2).to_string(),
1186 assertion: EdgeAssertion::Semantic {
1187 sub_kind: SemanticSubKind::Hyperlink,
1188 label: Some("next".into()),
1189 },
1190 };
1191 let bytes = postcard::to_allocvec(&delta).expect("encode");
1192 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1193 assert_eq!(restored, delta);
1194 }
1195
1196 #[test]
1197 fn arbitrary_facets_use_the_same_capture_and_replay_spine() {
1198 let captured = Arc::new(Mutex::new(Vec::<CapturedDelta>::new()));
1199 let sink = captured.clone();
1200 set_captured_delta_hook(Some(Arc::new(move |delta| {
1201 sink.lock().expect("capture sink").push(delta.clone());
1202 })));
1203
1204 let id = Uuid::from_u128(0xfac7);
1205 let mut graph = Graph::new();
1206 let key = crate::graph::apply::add_node(
1207 &mut graph,
1208 Some(id),
1209 "mere://facet-test".into(),
1210 point(0.0, 0.0),
1211 );
1212 let value = serde_json::json!({"portable": true});
1213 let _ = apply_graph_delta(
1214 &mut graph,
1215 GraphDelta::SetNodeFacet {
1216 key,
1217 facet: "example.portable/v1".into(),
1218 value: value.clone(),
1219 },
1220 );
1221 let _ = apply_graph_delta(
1222 &mut graph,
1223 GraphDelta::SetNodeFacet {
1224 key,
1225 facet: "example.portable/v1".into(),
1226 value: value.clone(),
1227 },
1228 );
1229 let _ = apply_graph_delta(
1230 &mut graph,
1231 GraphDelta::RemoveNodeFacet {
1232 key,
1233 facet: "example.portable/v1".into(),
1234 },
1235 );
1236 set_captured_delta_hook(None);
1237
1238 let captured = captured.lock().expect("capture sink");
1239 let [added, stamp, resource, shown, set, removed] = captured.as_slice() else {
1240 panic!("expected add, visit, resource, shown, one facet set and remove: {captured:?}");
1241 };
1242 let resource_id = chartulary::resource_id("mere://facet-test").to_string();
1243 assert!(
1244 matches!(added, CapturedDelta::ReplayAddNodeWithIdIfMissing {
1245 id: node_id, .. } if node_id == &id.to_string())
1246 );
1247 assert!(
1248 matches!(stamp, CapturedDelta::ReplayTouchNodeLastVisitedById {
1249 node_id, .. } if node_id == &id.to_string())
1250 );
1251 assert!(
1252 matches!(resource, CapturedDelta::ReplaySetResourceRecordById {
1253 resource_id: captured_id, record: Some(record) }
1254 if captured_id == &resource_id && record.canonical_iri == "mere://facet-test"
1255 && record.facets.is_empty())
1256 );
1257 assert!(matches!(shown, CapturedDelta::ReplaySetShownResourceById {
1258 surface_id, resource_id: Some(captured_id) }
1259 if surface_id == &id.to_string() && captured_id == &resource_id));
1260 assert!(matches!(set, CapturedDelta::ReplaySetNodeFacetById {
1261 node_id, facet, value_json } if node_id == &id.to_string()
1262 && facet == "example.portable/v1"
1263 && serde_json::from_str::<serde_json::Value>(value_json).unwrap() == value));
1264 assert!(matches!(removed, CapturedDelta::ReplayRemoveNodeFacetById {
1265 node_id, facet } if node_id == &id.to_string() && facet == "example.portable/v1"));
1266 let set_projection = replay_captured_deltas(captured[..captured.len() - 1].iter().cloned());
1267 assert_eq!(
1268 set_projection
1269 .facets()
1270 .get(&id, &chartulary::FacetId::new("example.portable/v1"),),
1271 Some(&value)
1272 );
1273 let removed_projection = replay_captured_deltas(captured.iter().cloned());
1274 assert!(
1275 removed_projection
1276 .facets()
1277 .get(&id, &chartulary::FacetId::new("example.portable/v1"),)
1278 .is_none()
1279 );
1280 assert_eq!(
1281 set_projection.to_snapshot().resources,
1282 graph.to_snapshot().resources
1283 );
1284 assert_eq!(
1285 set_projection.to_snapshot().shown_resources,
1286 graph.to_snapshot().shown_resources
1287 );
1288 assert_eq!(
1289 removed_projection.to_snapshot().resources,
1290 graph.to_snapshot().resources
1291 );
1292 assert_eq!(
1293 removed_projection.to_snapshot().shown_resources,
1294 graph.to_snapshot().shown_resources
1295 );
1296 }
1297
1298 #[test]
1299 fn traversal_captured_delta_round_trips_through_postcard() {
1300 let delta = CapturedDelta::ReplayAppendTraversalByIds {
1301 from_id: Uuid::from_u128(3).to_string(),
1302 to_id: Uuid::from_u128(4).to_string(),
1303 trigger: NavigationTrigger::Redirect,
1304 timestamp_ms: 12_345,
1305 };
1306 let bytes = postcard::to_allocvec(&delta).expect("encode");
1307 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1308 assert_eq!(restored, delta);
1309 }
1310
1311 #[test]
1312 fn node_content_captured_delta_round_trips_through_postcard() {
1313 let delta = CapturedDelta::ReplaySetNodeContentById {
1314 node_id: Uuid::from_u128(5).to_string(),
1315 content: Some([7; 32]),
1316 };
1317 let bytes = postcard::to_allocvec(&delta).expect("encode");
1318 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1319 assert_eq!(restored, delta);
1320 }
1321
1322 #[test]
1323 fn node_enrichment_captured_delta_round_trips_through_postcard() {
1324 let delta = CapturedDelta::ReplayAddNodeClassificationById {
1325 node_id: Uuid::from_u128(6).to_string(),
1326 classification: NodeClassification {
1327 scheme: ClassificationScheme::ContentKind,
1328 value: "article".into(),
1329 label: Some("Article".into()),
1330 confidence: 1.0,
1331 provenance: ClassificationProvenance::UserAuthored,
1332 status: ClassificationStatus::Accepted,
1333 primary: true,
1334 },
1335 };
1336 let bytes = postcard::to_allocvec(&delta).expect("encode");
1337 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1338 assert_eq!(restored, delta);
1339 }
1340
1341 #[test]
1342 fn classification_admin_captured_delta_round_trips_through_postcard() {
1343 let delta = CapturedDelta::ReplaySetNodeClassificationStatusById {
1344 node_id: Uuid::from_u128(61).to_string(),
1345 scheme: ClassificationScheme::ContentKind,
1346 value: "article".into(),
1347 status: ClassificationStatus::Verified,
1348 };
1349 let bytes = postcard::to_allocvec(&delta).expect("encode");
1350 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1351 assert_eq!(restored, delta);
1352 }
1353
1354 #[test]
1355 fn tag_presentation_captured_delta_round_trips_through_postcard() {
1356 let delta = CapturedDelta::ReplaySetNodeTagIconOverrideById {
1357 node_id: Uuid::from_u128(62).to_string(),
1358 tag: "paper".into(),
1359 icon: Some(BadgeIcon::Lucide("file-text".into())),
1360 };
1361 let bytes = postcard::to_allocvec(&delta).expect("encode");
1362 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1363 assert_eq!(restored, delta);
1364 }
1365
1366 #[test]
1367 fn node_media_captured_delta_round_trips_through_postcard() {
1368 let delta = CapturedDelta::ReplaySetNodeImageById {
1369 node_id: Uuid::from_u128(7).to_string(),
1370 role: ImageRole::Preview,
1371 image: ImageRef::new([4u8; 32], 2, 2),
1372 };
1373 let bytes = postcard::to_allocvec(&delta).expect("encode");
1374 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1375 assert_eq!(restored, delta);
1376 }
1377
1378 #[test]
1382 fn a_legacy_inline_image_record_still_decodes_and_is_skipped_on_replay() {
1383 let delta = CapturedDelta::ReplaySetNodeThumbnailById {
1384 node_id: Uuid::from_u128(7).to_string(),
1385 png_bytes: vec![1, 2, 3, 4],
1386 width: 2,
1387 height: 2,
1388 };
1389 let bytes = postcard::to_allocvec(&delta).expect("encode");
1390 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1391 assert_eq!(restored, delta, "an old journal entry still reads");
1392 assert!(
1393 matches!(restored.replay(), Replay::Skip),
1394 "it has no live delta: the pixels are dropped, not restored"
1395 );
1396 }
1397
1398 #[test]
1399 fn navigation_captured_delta_round_trips_through_postcard() {
1400 let delta = CapturedDelta::ReplayNavigateNodeById {
1401 node_id: Uuid::from_u128(8).to_string(),
1402 url: "https://example.test/two".into(),
1403 transition: TransitionKind::UrlTyped,
1404 timestamp_ms: 123,
1405 last_session_visited: 77,
1406 };
1407 let bytes = postcard::to_allocvec(&delta).expect("encode");
1408 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1409 assert_eq!(restored, delta);
1410 }
1411
1412 #[test]
1413 fn semantic_edge_captured_delta_round_trips_through_postcard() {
1414 let delta = CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
1415 from_id: Uuid::from_u128(81).to_string(),
1416 to_id: Uuid::from_u128(82).to_string(),
1417 predicate: Some("https://schema.org/author".into()),
1418 };
1419 let bytes = postcard::to_allocvec(&delta).expect("encode");
1420 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1421 assert_eq!(restored, delta);
1422 }
1423
1424 #[test]
1425 fn field_layer_captured_delta_round_trips_through_postcard() {
1426 let delta = CapturedDelta::ReplayAddField {
1427 field: persisted_field_from_field(&sample_field(FieldId::from_uuid(Uuid::from_u128(
1428 9,
1429 )))),
1430 };
1431 let bytes = postcard::to_allocvec(&delta).expect("encode");
1432 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1433 assert_eq!(restored, delta);
1434 }
1435
1436 #[test]
1437 fn field_admin_captured_delta_round_trips_through_postcard() {
1438 let delta = CapturedDelta::ReplayRetractCouplingById {
1439 coupling_id: Uuid::from_u128(91).to_string(),
1440 };
1441 let bytes = postcard::to_allocvec(&delta).expect("encode");
1442 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1443 assert_eq!(restored, delta);
1444 }
1445
1446 #[test]
1447 fn last_visited_captured_delta_round_trips_through_postcard() {
1448 let delta = CapturedDelta::ReplayTouchNodeLastVisitedById {
1449 node_id: Uuid::from_u128(93).to_string(),
1450 timestamp_ms: 1_763_573_400_123,
1451 };
1452 let bytes = postcard::to_allocvec(&delta).expect("encode");
1453 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1454 assert_eq!(restored, delta);
1455 }
1456
1457 #[test]
1458 fn frame_history_captured_delta_round_trips_through_postcard() {
1459 let delta = CapturedDelta::ReplayUpdateNodeHistoryById {
1460 node_id: Uuid::from_u128(10).to_string(),
1461 entries: vec!["https://a.test".into(), "https://b.test".into()],
1462 current_index: 1,
1463 };
1464 let bytes = postcard::to_allocvec(&delta).expect("encode");
1465 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1466 assert_eq!(restored, delta);
1467 }
1468
1469 #[test]
1470 fn import_records_captured_delta_round_trips_through_postcard() {
1471 let delta = CapturedDelta::ReplaySetImportRecords {
1472 import_records: vec![ImportRecord {
1473 record_id: "import-record:seed".into(),
1474 source_id: "import:seed".into(),
1475 source_label: "Seed import".into(),
1476 imported_at_secs: 1_763_500_800,
1477 memberships: vec![ImportRecordMembership {
1478 node_id: Uuid::from_u128(10).to_string(),
1479 suppressed: false,
1480 }],
1481 }],
1482 };
1483 let bytes = postcard::to_allocvec(&delta).expect("encode");
1484 let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
1485 assert_eq!(restored, delta);
1486 }
1487
1488 #[test]
1489 fn replay_captured_deltas_rebuilds_relation_traversal_media_navigation_field_enrichment_and_frame_history_state()
1490 {
1491 let a_id = Uuid::from_u128(11);
1492 let b_id = Uuid::from_u128(12);
1493 let c_id = Uuid::from_u128(13);
1494 let field_id = FieldId::from_uuid(Uuid::from_u128(14));
1495 let coupling_id = CouplingId::from_uuid(Uuid::from_u128(15));
1496 let deltas = vec![
1497 CapturedDelta::ReplayAddNodeWithIdIfMissing {
1498 id: a_id.to_string(),
1499 url: "https://a.test".into(),
1500 position: [1.0, 2.0],
1501 },
1502 CapturedDelta::ReplayAddNodeWithIdIfMissing {
1503 id: b_id.to_string(),
1504 url: "https://b.test".into(),
1505 position: [3.0, 4.0],
1506 },
1507 CapturedDelta::ReplayAddNodeWithIdIfMissing {
1508 id: c_id.to_string(),
1509 url: "https://c.test".into(),
1510 position: [5.0, 6.0],
1511 },
1512 CapturedDelta::ReplayAssertRelationByIds {
1513 from_id: a_id.to_string(),
1514 to_id: b_id.to_string(),
1515 assertion: EdgeAssertion::Containment {
1516 sub_kind: ContainmentSubKind::CollectionMember,
1517 },
1518 },
1519 CapturedDelta::ReplayAppendTraversalByIds {
1520 from_id: a_id.to_string(),
1521 to_id: b_id.to_string(),
1522 trigger: NavigationTrigger::LinkClick,
1523 timestamp_ms: 6_789,
1524 },
1525 CapturedDelta::ReplaySetNodeTitleById {
1526 node_id: a_id.to_string(),
1527 title: "Alpha".into(),
1528 },
1529 CapturedDelta::ReplaySetNodeUrlById {
1530 node_id: a_id.to_string(),
1531 new_url: "https://a.test/next".into(),
1532 },
1533 CapturedDelta::ReplaySetNodeImageById {
1534 node_id: a_id.to_string(),
1535 role: ImageRole::Preview,
1536 image: ImageRef::new([7u8; 32], 1, 1),
1537 },
1538 CapturedDelta::ReplaySetNodeImageById {
1539 node_id: a_id.to_string(),
1540 role: ImageRole::Favicon,
1541 image: ImageRef::new([9u8; 32], 1, 1),
1542 },
1543 CapturedDelta::ReplaySetNodeMimeHintById {
1544 node_id: a_id.to_string(),
1545 mime_hint: Some("text/html".into()),
1546 },
1547 CapturedDelta::ReplaySetNodePinnedById {
1548 node_id: a_id.to_string(),
1549 is_pinned: true,
1550 },
1551 CapturedDelta::ReplayInsertNodeTagById {
1552 node_id: a_id.to_string(),
1553 tag: "research".into(),
1554 },
1555 CapturedDelta::ReplayRemoveNodeTagById {
1556 node_id: a_id.to_string(),
1557 tag: "research".into(),
1558 },
1559 CapturedDelta::ReplaySetNodeBodyById {
1560 node_id: a_id.to_string(),
1561 body: Some("body".into()),
1562 },
1563 CapturedDelta::ReplayTouchNodeLastVisitedById {
1564 node_id: a_id.to_string(),
1565 timestamp_ms: 1_763_573_400_123,
1566 },
1567 CapturedDelta::ReplayInsertNodeTagById {
1568 node_id: a_id.to_string(),
1569 tag: "paper".into(),
1570 },
1571 CapturedDelta::ReplaySetNodeTagIconOverrideById {
1572 node_id: a_id.to_string(),
1573 tag: "paper".into(),
1574 icon: Some(BadgeIcon::Lucide("file-text".into())),
1575 },
1576 CapturedDelta::ReplayNavigateNodeById {
1577 node_id: b_id.to_string(),
1578 url: "https://b.test/one".into(),
1579 transition: TransitionKind::UrlTyped,
1580 timestamp_ms: 111,
1581 last_session_visited: 77,
1582 },
1583 CapturedDelta::ReplayNavigateNodeById {
1584 node_id: b_id.to_string(),
1585 url: "https://b.test/two".into(),
1586 transition: TransitionKind::UrlTyped,
1587 timestamp_ms: 222,
1588 last_session_visited: 77,
1589 },
1590 CapturedDelta::ReplayNodeHistoryBackById {
1591 node_id: b_id.to_string(),
1592 timestamp_ms: 333,
1593 },
1594 CapturedDelta::ReplayNodeHistoryForwardById {
1595 node_id: b_id.to_string(),
1596 timestamp_ms: 444,
1597 },
1598 CapturedDelta::ReplayBranchHistoryByIds {
1599 child_id: c_id.to_string(),
1600 parent_id: b_id.to_string(),
1601 },
1602 CapturedDelta::ReplayNavigateNodeById {
1603 node_id: c_id.to_string(),
1604 url: "https://c.test/branched".into(),
1605 transition: TransitionKind::UrlTyped,
1606 timestamp_ms: 555,
1607 last_session_visited: 77,
1608 },
1609 CapturedDelta::ReplayAddField {
1610 field: persisted_field_from_field(&sample_field(field_id)),
1611 },
1612 CapturedDelta::ReplayAddCoupling {
1613 coupling: persisted_coupling_from_coupling(&sample_coupling(coupling_id, field_id)),
1614 },
1615 CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
1616 field_id: field_id.as_uuid().to_string(),
1617 strength: 2.0,
1618 },
1619 CapturedDelta::ReplayRetireFieldById {
1620 field_id: field_id.as_uuid().to_string(),
1621 },
1622 CapturedDelta::ReplayActivateFieldById {
1623 field_id: field_id.as_uuid().to_string(),
1624 },
1625 CapturedDelta::ReplayRetractCouplingById {
1626 coupling_id: coupling_id.as_uuid().to_string(),
1627 },
1628 CapturedDelta::ReplayAddCoupling {
1629 coupling: persisted_coupling_from_coupling(&sample_coupling(coupling_id, field_id)),
1630 },
1631 CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
1632 field_id: field_id.as_uuid().to_string(),
1633 strength: 2.0,
1634 },
1635 CapturedDelta::ReplayAppendNodePropertyById {
1636 node_id: a_id.to_string(),
1637 property: NodeProperty::new(
1638 "https://schema.org/datePublished".into(),
1639 "2026-07-02".into(),
1640 ),
1641 },
1642 CapturedDelta::ReplayAddNodeClassificationById {
1643 node_id: a_id.to_string(),
1644 classification: NodeClassification {
1645 scheme: ClassificationScheme::ContentKind,
1646 value: "article".into(),
1647 label: Some("Article".into()),
1648 confidence: 1.0,
1649 provenance: ClassificationProvenance::UserAuthored,
1650 status: ClassificationStatus::Accepted,
1651 primary: true,
1652 },
1653 },
1654 CapturedDelta::ReplayAddNodeClassificationById {
1655 node_id: a_id.to_string(),
1656 classification: NodeClassification {
1657 scheme: ClassificationScheme::ContentKind,
1658 value: "essay".into(),
1659 label: Some("Essay".into()),
1660 confidence: 0.6,
1661 provenance: ClassificationProvenance::AgentSuggested,
1662 status: ClassificationStatus::Suggested,
1663 primary: false,
1664 },
1665 },
1666 CapturedDelta::ReplayAddNodeClassificationById {
1667 node_id: a_id.to_string(),
1668 classification: NodeClassification {
1669 scheme: ClassificationScheme::ContentKind,
1670 value: "draft".into(),
1671 label: Some("Draft".into()),
1672 confidence: 0.3,
1673 provenance: ClassificationProvenance::AgentSuggested,
1674 status: ClassificationStatus::Suggested,
1675 primary: false,
1676 },
1677 },
1678 CapturedDelta::ReplaySetNodeClassificationStatusById {
1679 node_id: a_id.to_string(),
1680 scheme: ClassificationScheme::ContentKind,
1681 value: "article".into(),
1682 status: ClassificationStatus::Verified,
1683 },
1684 CapturedDelta::ReplaySetNodePrimaryClassificationById {
1685 node_id: a_id.to_string(),
1686 scheme: ClassificationScheme::ContentKind,
1687 value: "essay".into(),
1688 },
1689 CapturedDelta::ReplayRemoveNodeClassificationById {
1690 node_id: a_id.to_string(),
1691 scheme: ClassificationScheme::ContentKind,
1692 value: "draft".into(),
1693 },
1694 CapturedDelta::ReplayRecordNodeDerivationById {
1695 node_id: a_id.to_string(),
1696 derivation: NodeDerivation {
1697 sub_kind: ProvenanceSubKind::ExtractedFrom,
1698 source_node: Uuid::from_u128(99).to_string(),
1699 source_graph: Some("graph:test".into()),
1700 },
1701 },
1702 CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
1703 from_id: a_id.to_string(),
1704 to_id: b_id.to_string(),
1705 predicate: Some("https://schema.org/author".into()),
1706 },
1707 CapturedDelta::ReplayAssertSemanticPredicateByIds {
1708 from_id: b_id.to_string(),
1709 to_id: c_id.to_string(),
1710 predicate: "https://schema.org/citation".into(),
1711 },
1712 CapturedDelta::ReplayAppendFrameLayoutHintById {
1713 node_id: a_id.to_string(),
1714 hint: FrameLayoutHint::SplitHalf {
1715 first: b_id.to_string(),
1716 second: c_id.to_string(),
1717 orientation: SplitOrientation::Vertical,
1718 },
1719 },
1720 CapturedDelta::ReplayAppendFrameLayoutHintById {
1721 node_id: a_id.to_string(),
1722 hint: FrameLayoutHint::SplitHalf {
1723 first: c_id.to_string(),
1724 second: b_id.to_string(),
1725 orientation: SplitOrientation::Horizontal,
1726 },
1727 },
1728 CapturedDelta::ReplayMoveFrameLayoutHintById {
1729 node_id: a_id.to_string(),
1730 from_index: 0,
1731 to_index: 1,
1732 },
1733 CapturedDelta::ReplayRemoveFrameLayoutHintById {
1734 node_id: a_id.to_string(),
1735 hint_index: 1,
1736 },
1737 CapturedDelta::ReplaySetFrameSplitOfferSuppressedById {
1738 node_id: a_id.to_string(),
1739 suppressed: true,
1740 },
1741 CapturedDelta::ReplayUpdateNodeHistoryById {
1742 node_id: a_id.to_string(),
1743 entries: vec![
1744 "https://a.test/one".into(),
1745 "https://a.test/two".into(),
1746 "https://a.test/three".into(),
1747 ],
1748 current_index: 9,
1749 },
1750 CapturedDelta::ReplaySetImportRecords {
1751 import_records: vec![ImportRecord {
1752 record_id: "import-record:seed".into(),
1753 source_id: "import:seed".into(),
1754 source_label: "Seed import".into(),
1755 imported_at_secs: 1_763_500_800,
1756 memberships: vec![
1757 ImportRecordMembership {
1758 node_id: a_id.to_string(),
1759 suppressed: false,
1760 },
1761 ImportRecordMembership {
1762 node_id: c_id.to_string(),
1763 suppressed: true,
1764 },
1765 ],
1766 }],
1767 },
1768 ];
1769
1770 let graph = replay_captured_deltas(deltas);
1771 assert_eq!(graph.node_count(), 3);
1772 assert_eq!(graph.edge_count(), 2);
1773 assert!(graph.get_node_by_id(a_id).is_some());
1774 assert!(graph.get_node_by_id(b_id).is_some());
1775 assert!(graph.get_node_by_id(c_id).is_some());
1776 assert_eq!(graph.relations().count(), 4);
1782 assert_eq!(
1783 graph
1784 .relations()
1785 .filter(|r| r.kind == RelationKind::OpenPredicate)
1786 .count(),
1787 2
1788 );
1789 let from = graph.get_node_key_by_id(a_id).expect("from key");
1790 let to = graph.get_node_key_by_id(b_id).expect("to key");
1791 let edge = graph.find_edge_key(from, to).expect("edge key");
1792 let payload = graph.get_edge(edge).expect("edge payload");
1793 assert_eq!(payload.traversals().len(), 1);
1794 assert_eq!(payload.metrics().total_navigations, 1);
1795 assert_eq!(payload.metrics().last_navigated_at, Some(6_789));
1796 let node = graph.get_node(from).expect("node payload");
1797 assert_eq!(node.title, "Alpha");
1798 assert_eq!(node.url(), "https://a.test/next");
1799 assert_eq!(node.preview(), Some(&ImageRef::new([7u8; 32], 1, 1)));
1800 assert_eq!(node.favicon(), Some(&ImageRef::new([9u8; 32], 1, 1)));
1801 assert_eq!(node.media_type.as_deref(), Some("text/html"));
1802 assert_eq!(graph.node_is_pinned(from), Some(true));
1803 assert_eq!(node.body.as_deref(), Some("body"));
1804 assert_eq!(
1805 graph
1806 .node_last_visited(from)
1807 .expect("last visited facet")
1808 .duration_since(std::time::UNIX_EPOCH)
1809 .expect("last visited since epoch")
1810 .as_millis() as u64,
1811 1_763_573_400_123
1812 );
1813 assert!(!node.tags.contains("research"));
1814 assert!(node.tags.contains("paper"));
1815 assert_eq!(
1816 graph
1817 .node_tag_presentation(from)
1818 .unwrap()
1819 .icon_overrides
1820 .get("paper"),
1821 Some(&BadgeIcon::Lucide("file-text".into()))
1822 );
1823 let properties = graph.node_properties(from).unwrap();
1824 assert_eq!(properties.len(), 1);
1825 assert_eq!(properties[0].predicate, "https://schema.org/datePublished");
1826 assert_eq!(properties[0].value, "2026-07-02");
1827 let classifications = graph.node_classifications(from).unwrap();
1828 assert_eq!(classifications.len(), 2);
1829 assert!(classifications.iter().any(|classification| {
1830 classification.value == "article"
1831 && classification.status == ClassificationStatus::Verified
1832 && !classification.primary
1833 }));
1834 assert!(classifications.iter().any(|classification| {
1835 classification.value == "essay"
1836 && classification.status == ClassificationStatus::Suggested
1837 && classification.primary
1838 }));
1839 assert!(
1840 classifications
1841 .iter()
1842 .all(|classification| classification.value != "draft")
1843 );
1844 let derivations = graph.node_derivations(from).unwrap();
1845 assert_eq!(derivations.len(), 1);
1846 assert_eq!(derivations[0].sub_kind, ProvenanceSubKind::ExtractedFrom);
1847 assert_eq!(
1848 payload
1849 .semantic_data()
1850 .and_then(|data| data.predicate.as_deref()),
1851 Some("https://schema.org/author")
1852 );
1853 let history_node_key = graph.get_node_key_by_id(b_id).expect("history node key");
1854 let history_node = graph.get_node(history_node_key).expect("history node");
1855 assert_eq!(history_node.url(), "https://b.test/two");
1856 assert_eq!(graph.node_last_session_visited(history_node_key), Some(77));
1857 let history_projection = graph.node_history_projection(history_node_key);
1858 assert_eq!(
1859 history_projection.entries,
1860 vec![
1861 "https://b.test/one".to_string(),
1862 "https://b.test/two".to_string(),
1863 ]
1864 );
1865 assert_eq!(history_projection.current_index, 1);
1866 let branched_node_key = graph.get_node_key_by_id(c_id).expect("branched node key");
1867 let branched_node = graph.get_node(branched_node_key).expect("branched node");
1868 assert_eq!(branched_node.url(), "https://c.test/branched");
1869 assert_eq!(graph.node_last_session_visited(branched_node_key), Some(77));
1870 let semantic_edge = graph
1871 .find_edge_key(history_node_key, branched_node_key)
1872 .expect("semantic edge key");
1873 let semantic_payload = graph
1874 .get_edge(semantic_edge)
1875 .expect("semantic edge payload");
1876 assert_eq!(
1877 semantic_payload
1878 .semantic_data()
1879 .and_then(|data| data.predicate.as_deref()),
1880 Some("https://schema.org/citation")
1881 );
1882 let field = graph.field(field_id).expect("field payload");
1883 assert_eq!(field.name.as_deref(), Some("focus"));
1884 assert!(field.is_active());
1885 assert_eq!(
1886 field.extent,
1887 FieldExtent::Region {
1888 min_x: -10.0,
1889 min_y: -20.0,
1890 max_x: 30.0,
1891 max_y: 40.0,
1892 }
1893 );
1894 let coupling = graph
1895 .couplings_for_field(field_id)
1896 .next()
1897 .expect("field coupling");
1898 assert_eq!(coupling.id, coupling_id);
1899 assert_eq!(coupling.selector, NodeSelector::Kind("paper".into()));
1900 assert_eq!(
1901 coupling.response,
1902 CouplingResponse::DampenInside { factor: 0.3 }
1903 );
1904 assert_eq!(coupling.strength, 2.0);
1905 let hints = graph.frame_layout_hints(from).expect("frame layout hints");
1906 assert_eq!(hints.len(), 1);
1907 assert_eq!(
1908 hints[0],
1909 FrameLayoutHint::SplitHalf {
1910 first: c_id.to_string(),
1911 second: b_id.to_string(),
1912 orientation: SplitOrientation::Horizontal,
1913 }
1914 );
1915 assert_eq!(graph.frame_split_offer_suppressed(from), Some(true));
1916 let history = graph.node_history_projection(from);
1917 assert_eq!(
1918 history.entries,
1919 vec![
1920 "https://a.test/one".to_string(),
1921 "https://a.test/two".to_string(),
1922 "https://a.test/three".to_string(),
1923 ]
1924 );
1925 assert_eq!(history.current_index, 2);
1926 let import_records = graph.import_records();
1927 assert_eq!(import_records.len(), 1);
1928 assert_eq!(import_records[0].record_id, "import-record:seed");
1929 assert_eq!(
1930 graph.import_record_member_keys("import-record:seed"),
1931 vec![from]
1932 );
1933 assert_eq!(
1934 graph
1935 .node_import_provenance(from)
1936 .expect("import provenance"),
1937 [NodeImportProvenance {
1938 source_id: "import:seed".into(),
1939 source_label: "Seed import".into(),
1940 }]
1941 );
1942 assert!(
1943 graph
1944 .node_import_provenance(branched_node_key)
1945 .expect("suppressed provenance")
1946 .is_empty()
1947 );
1948 let mut expected_nav = SharedNavigationMemory::empty();
1949 expected_nav.record_visit(b_id, "https://b.test/one", TransitionKind::UrlTyped, 111);
1950 expected_nav.record_visit(b_id, "https://b.test/two", TransitionKind::UrlTyped, 222);
1951 assert_eq!(
1952 expected_nav.back(b_id, 333).as_deref(),
1953 Some("https://b.test/one")
1954 );
1955 assert_eq!(
1956 expected_nav.forward(b_id, 444).as_deref(),
1957 Some("https://b.test/two")
1958 );
1959 expected_nav.spawn(c_id, b_id);
1960 expected_nav.record_visit(
1961 c_id,
1962 "https://c.test/branched",
1963 TransitionKind::UrlTyped,
1964 555,
1965 );
1966 expected_nav.seed_linear(
1967 a_id,
1968 vec![
1969 "https://a.test/one".to_string(),
1970 "https://a.test/two".to_string(),
1971 "https://a.test/three".to_string(),
1972 ],
1973 9,
1974 );
1975 let mut actual_snapshot = graph.to_snapshot().navigation.snapshot().clone();
1976 for owner in &mut actual_snapshot.owners {
1977 owner.owned_visits.sort_unstable();
1978 }
1979 for visit in &mut actual_snapshot.visits {
1980 visit.bindings.sort_by_key(|binding| {
1981 (
1982 binding.owner,
1983 binding.forward_child.unwrap_or(usize::MAX),
1984 binding.last_accessed_at_ms,
1985 )
1986 });
1987 }
1988 let mut expected_snapshot = expected_nav.snapshot().clone();
1989 for owner in &mut expected_snapshot.owners {
1990 owner.owned_visits.sort_unstable();
1991 }
1992 for visit in &mut expected_snapshot.visits {
1993 visit.bindings.sort_by_key(|binding| {
1994 (
1995 binding.owner,
1996 binding.forward_child.unwrap_or(usize::MAX),
1997 binding.last_accessed_at_ms,
1998 )
1999 });
2000 }
2001 assert_eq!(actual_snapshot, expected_snapshot);
2002 }
2003
2004 #[test]
2005 fn capture_hook_receives_replayable_apply_events() {
2006 let captured = Arc::new(Mutex::new(Vec::<CapturedDelta>::new()));
2007 let sink = captured.clone();
2008 set_captured_delta_hook(Some(Arc::new(move |delta| {
2009 sink.lock().expect("capture sink").push(delta.clone());
2010 })));
2011
2012 let mut graph = Graph::new();
2013 graph.set_current_session(77);
2014 let a = crate::graph::apply::add_node(
2015 &mut graph,
2016 Some(Uuid::from_u128(21)),
2017 "https://a.test".into(),
2018 point(0.0, 0.0),
2019 );
2020 let b = crate::graph::apply::add_node(
2021 &mut graph,
2022 Some(Uuid::from_u128(22)),
2023 "https://b.test".into(),
2024 point(1.0, 0.0),
2025 );
2026 let c = crate::graph::apply::add_node(
2027 &mut graph,
2028 Some(Uuid::from_u128(23)),
2029 "https://c.test".into(),
2030 point(2.0, 0.0),
2031 );
2032 let field_id = FieldId::from_uuid(Uuid::from_u128(24));
2033 let coupling_id = CouplingId::from_uuid(Uuid::from_u128(25));
2034 graph.assert_semantic_statement(
2035 a,
2036 b,
2037 crate::graph::SemanticStatementSpec {
2038 predicate: "https://schema.org/author".into(),
2039 recognized_sub_kind: Some(SemanticSubKind::Hyperlink),
2040 provenance_iri: Some(crate::graph::journal::Author::user().asserter_iri()),
2041 ..Default::default()
2042 },
2043 );
2044 let historical_statement = graph
2045 .resource_relations()
2046 .flat_map(|(_, _, _, payload)| payload.semantic_statements())
2047 .find(|statement| statement.predicate == "https://schema.org/author")
2048 .unwrap()
2049 .clone();
2050 let _ = crate::graph::apply::apply_graph_delta(
2051 &mut graph,
2052 GraphDelta::AppendTraversal {
2053 from: a,
2054 to: b,
2055 trigger: NavigationTrigger::Programmatic,
2056 timestamp_ms: Some(4_321),
2057 },
2058 );
2059 let _ = crate::graph::apply::apply_graph_delta(
2060 &mut graph,
2061 GraphDelta::SetNodeTitle {
2062 key: a,
2063 title: "Alpha".into(),
2064 },
2065 );
2066 let _ = crate::graph::apply::apply_graph_delta(
2067 &mut graph,
2068 GraphDelta::SetNodeUrl {
2069 key: a,
2070 new_url: "https://a.test/next".into(),
2071 },
2072 );
2073 let _ = crate::graph::apply::apply_graph_delta(
2074 &mut graph,
2075 GraphDelta::SetNodeImage {
2076 key: a,
2077 role: ImageRole::Preview,
2078 image: ImageRef::new([7u8; 32], 1, 1),
2079 },
2080 );
2081 let _ = crate::graph::apply::apply_graph_delta(
2082 &mut graph,
2083 GraphDelta::SetNodeImage {
2084 key: a,
2085 role: ImageRole::Favicon,
2086 image: ImageRef::new([9u8; 32], 1, 1),
2087 },
2088 );
2089 let _ = crate::graph::apply::apply_graph_delta(
2090 &mut graph,
2091 GraphDelta::SetNodeMimeHint {
2092 key: a,
2093 mime_hint: Some("text/html".into()),
2094 },
2095 );
2096 let _ = crate::graph::apply::apply_graph_delta(
2097 &mut graph,
2098 GraphDelta::SetNodePinned {
2099 key: a,
2100 is_pinned: true,
2101 },
2102 );
2103 let _ = crate::graph::apply::apply_graph_delta(
2104 &mut graph,
2105 GraphDelta::InsertNodeTag {
2106 key: a,
2107 tag: "research".into(),
2108 },
2109 );
2110 let _ = crate::graph::apply::apply_graph_delta(
2111 &mut graph,
2112 GraphDelta::RemoveNodeTag {
2113 key: a,
2114 tag: "research".into(),
2115 },
2116 );
2117 let _ = crate::graph::apply::apply_graph_delta(
2118 &mut graph,
2119 GraphDelta::SetNodeBody {
2120 key: a,
2121 body: Some("body".into()),
2122 },
2123 );
2124 std::thread::sleep(std::time::Duration::from_millis(2));
2127 let _ = crate::graph::apply::apply_graph_delta(
2128 &mut graph,
2129 GraphDelta::TouchNodeLastVisited { key: a },
2130 );
2131 let _ = crate::graph::apply::apply_graph_delta(
2132 &mut graph,
2133 GraphDelta::InsertNodeTag {
2134 key: a,
2135 tag: "paper".into(),
2136 },
2137 );
2138 let _ = crate::graph::apply::apply_graph_delta(
2139 &mut graph,
2140 GraphDelta::SetNodeTagIconOverride {
2141 key: a,
2142 tag: "paper".into(),
2143 icon: Some(BadgeIcon::Lucide("file-text".into())),
2144 },
2145 );
2146 let _ = crate::graph::apply::apply_graph_delta(
2147 &mut graph,
2148 GraphDelta::NavigateNode {
2149 key: b,
2150 url: "https://b.test/one".into(),
2151 },
2152 );
2153 let _ = crate::graph::apply::apply_graph_delta(
2154 &mut graph,
2155 GraphDelta::NavigateNode {
2156 key: b,
2157 url: "https://b.test/two".into(),
2158 },
2159 );
2160 let _ = crate::graph::apply::apply_graph_delta(
2161 &mut graph,
2162 GraphDelta::NodeHistoryBack { key: b },
2163 );
2164 let _ = crate::graph::apply::apply_graph_delta(
2165 &mut graph,
2166 GraphDelta::NodeHistoryForward { key: b },
2167 );
2168 let _ = crate::graph::apply::apply_graph_delta(
2169 &mut graph,
2170 GraphDelta::BranchHistory {
2171 child: c,
2172 parent: b,
2173 },
2174 );
2175 let _ = crate::graph::apply::apply_graph_delta(
2176 &mut graph,
2177 GraphDelta::NavigateNode {
2178 key: c,
2179 url: "https://c.test/branched".into(),
2180 },
2181 );
2182 let _ = crate::graph::apply::apply_graph_delta(
2183 &mut graph,
2184 GraphDelta::AddField {
2185 field: sample_field(field_id),
2186 },
2187 );
2188 let _ = crate::graph::apply::apply_graph_delta(
2189 &mut graph,
2190 GraphDelta::AddCoupling {
2191 coupling: sample_coupling(coupling_id, field_id),
2192 },
2193 );
2194 let _ = crate::graph::apply::apply_graph_delta(
2195 &mut graph,
2196 GraphDelta::SetFieldCouplingStrength {
2197 field: field_id,
2198 strength: 2.0,
2199 },
2200 );
2201 let _ = crate::graph::apply::apply_graph_delta(
2202 &mut graph,
2203 GraphDelta::RetireField { id: field_id },
2204 );
2205 let _ = crate::graph::apply::apply_graph_delta(
2206 &mut graph,
2207 GraphDelta::ActivateField { id: field_id },
2208 );
2209 let _ = crate::graph::apply::apply_graph_delta(
2210 &mut graph,
2211 GraphDelta::RetractCoupling { id: coupling_id },
2212 );
2213 let _ = crate::graph::apply::apply_graph_delta(
2214 &mut graph,
2215 GraphDelta::AddCoupling {
2216 coupling: sample_coupling(coupling_id, field_id),
2217 },
2218 );
2219 let _ = crate::graph::apply::apply_graph_delta(
2220 &mut graph,
2221 GraphDelta::SetFieldCouplingStrength {
2222 field: field_id,
2223 strength: 2.0,
2224 },
2225 );
2226 let _ = crate::graph::apply::apply_graph_delta(
2227 &mut graph,
2228 GraphDelta::AppendNodeProperty {
2229 key: a,
2230 property: NodeProperty::new(
2231 "https://schema.org/datePublished".into(),
2232 "2026-07-02".into(),
2233 ),
2234 },
2235 );
2236 let _ = crate::graph::apply::apply_graph_delta(
2237 &mut graph,
2238 GraphDelta::AddNodeClassification {
2239 key: a,
2240 classification: NodeClassification {
2241 scheme: ClassificationScheme::ContentKind,
2242 value: "article".into(),
2243 label: Some("Article".into()),
2244 confidence: 1.0,
2245 provenance: ClassificationProvenance::UserAuthored,
2246 status: ClassificationStatus::Accepted,
2247 primary: true,
2248 },
2249 },
2250 );
2251 let _ = crate::graph::apply::apply_graph_delta(
2252 &mut graph,
2253 GraphDelta::AddNodeClassification {
2254 key: a,
2255 classification: NodeClassification {
2256 scheme: ClassificationScheme::ContentKind,
2257 value: "essay".into(),
2258 label: Some("Essay".into()),
2259 confidence: 0.6,
2260 provenance: ClassificationProvenance::AgentSuggested,
2261 status: ClassificationStatus::Suggested,
2262 primary: false,
2263 },
2264 },
2265 );
2266 let _ = crate::graph::apply::apply_graph_delta(
2267 &mut graph,
2268 GraphDelta::AddNodeClassification {
2269 key: a,
2270 classification: NodeClassification {
2271 scheme: ClassificationScheme::ContentKind,
2272 value: "draft".into(),
2273 label: Some("Draft".into()),
2274 confidence: 0.3,
2275 provenance: ClassificationProvenance::AgentSuggested,
2276 status: ClassificationStatus::Suggested,
2277 primary: false,
2278 },
2279 },
2280 );
2281 let _ = crate::graph::apply::apply_graph_delta(
2282 &mut graph,
2283 GraphDelta::SetNodeClassificationStatus {
2284 key: a,
2285 scheme: ClassificationScheme::ContentKind,
2286 value: "article".into(),
2287 status: ClassificationStatus::Verified,
2288 },
2289 );
2290 let _ = crate::graph::apply::apply_graph_delta(
2291 &mut graph,
2292 GraphDelta::SetNodePrimaryClassification {
2293 key: a,
2294 scheme: ClassificationScheme::ContentKind,
2295 value: "essay".into(),
2296 },
2297 );
2298 let _ = crate::graph::apply::apply_graph_delta(
2299 &mut graph,
2300 GraphDelta::RemoveNodeClassification {
2301 key: a,
2302 scheme: ClassificationScheme::ContentKind,
2303 value: "draft".into(),
2304 },
2305 );
2306 let _ = crate::graph::apply::apply_graph_delta(
2307 &mut graph,
2308 GraphDelta::RecordNodeDerivation {
2309 key: a,
2310 derivation: NodeDerivation {
2311 sub_kind: ProvenanceSubKind::ExtractedFrom,
2312 source_node: Uuid::from_u128(99).to_string(),
2313 source_graph: Some("graph:test".into()),
2314 },
2315 },
2316 );
2317 let _ = crate::graph::apply::apply_graph_delta(
2318 &mut graph,
2319 GraphDelta::AssertSemanticPredicate {
2320 asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
2321 from: b,
2322 to: c,
2323 predicate: "https://schema.org/citation".into(),
2324 },
2325 );
2326 let _ = crate::graph::apply::apply_graph_delta(
2327 &mut graph,
2328 GraphDelta::AppendFrameLayoutHint {
2329 key: a,
2330 hint: FrameLayoutHint::SplitHalf {
2331 first: Uuid::from_u128(22).to_string(),
2332 second: Uuid::from_u128(23).to_string(),
2333 orientation: SplitOrientation::Vertical,
2334 },
2335 },
2336 );
2337 let _ = crate::graph::apply::apply_graph_delta(
2338 &mut graph,
2339 GraphDelta::AppendFrameLayoutHint {
2340 key: a,
2341 hint: FrameLayoutHint::SplitHalf {
2342 first: Uuid::from_u128(23).to_string(),
2343 second: Uuid::from_u128(22).to_string(),
2344 orientation: SplitOrientation::Horizontal,
2345 },
2346 },
2347 );
2348 let _ = crate::graph::apply::apply_graph_delta(
2349 &mut graph,
2350 GraphDelta::MoveFrameLayoutHint {
2351 key: a,
2352 from_index: 0,
2353 to_index: 1,
2354 },
2355 );
2356 let _ = crate::graph::apply::apply_graph_delta(
2357 &mut graph,
2358 GraphDelta::RemoveFrameLayoutHint {
2359 key: a,
2360 hint_index: 1,
2361 },
2362 );
2363 let _ = crate::graph::apply::apply_graph_delta(
2364 &mut graph,
2365 GraphDelta::SetFrameSplitOfferSuppressed {
2366 key: a,
2367 suppressed: true,
2368 },
2369 );
2370 let _ = crate::graph::apply::apply_graph_delta(
2371 &mut graph,
2372 GraphDelta::UpdateNodeHistory {
2373 key: a,
2374 entries: vec![
2375 "https://a.test/one".into(),
2376 "https://a.test/two".into(),
2377 "https://a.test/three".into(),
2378 ],
2379 current_index: 9,
2380 },
2381 );
2382 let _ = crate::graph::apply::apply_graph_delta(
2383 &mut graph,
2384 GraphDelta::SetNodeImportProvenance {
2385 key: a,
2386 import_provenance: vec![NodeImportProvenance {
2387 source_id: "import:seed".into(),
2388 source_label: "Seed import".into(),
2389 }],
2390 },
2391 );
2392 let _ = crate::graph::apply::apply_graph_delta(
2393 &mut graph,
2394 GraphDelta::SetImportRecordMembershipSuppressed {
2395 record_id: "import-record:import:seed".into(),
2396 key: a,
2397 suppressed: true,
2398 },
2399 );
2400 let c_node_id = graph.get_node(c).expect("node c").id.to_string();
2401 let _ = crate::graph::apply::apply_graph_delta(
2402 &mut graph,
2403 GraphDelta::SetImportRecords {
2404 import_records: vec![ImportRecord {
2405 record_id: "import-record:seed-two".into(),
2406 source_id: "import:seed-two".into(),
2407 source_label: "Seed import two".into(),
2408 imported_at_secs: 1_763_500_801,
2409 memberships: vec![ImportRecordMembership {
2410 node_id: c_node_id,
2411 suppressed: false,
2412 }],
2413 }],
2414 },
2415 );
2416 let _ = crate::graph::apply::apply_graph_delta(
2417 &mut graph,
2418 GraphDelta::RetractRelations {
2419 from: a,
2420 to: b,
2421 selector: RelationSelector::Semantic(SemanticSubKind::Hyperlink),
2422 },
2423 );
2424 let _ =
2425 crate::graph::apply::apply_graph_delta(&mut graph, GraphDelta::RemoveNode { key: b });
2426
2427 set_captured_delta_hook(None);
2428
2429 let captured = captured.lock().expect("capture sink");
2430 let stamps = captured
2434 .windows(2)
2435 .filter(|pair| {
2436 matches!(pair[0], CapturedDelta::ReplayAddNodeWithIdIfMissing { .. })
2437 && matches!(
2438 pair[1],
2439 CapturedDelta::ReplayTouchNodeLastVisitedById { .. }
2440 )
2441 })
2442 .count();
2443 let minted = captured
2444 .iter()
2445 .filter(|delta| matches!(delta, CapturedDelta::ReplaySetResourceEdgesByIds { edges, .. }
2446 if edges.iter().flat_map(|edge| edge.retained_assertions())
2447 .any(|statement| statement.predicate != crate::graph::resource::TAGGED_WITH_IRI)))
2448 .count();
2449 assert_eq!(
2450 (stamps, minted),
2451 (3, 2),
2452 "three new nodes; hyperlink assertion with its predicate and open assertion captured"
2453 );
2454 let expected_bindings = [
2455 (21, "https://a.test"),
2456 (22, "https://b.test"),
2457 (23, "https://c.test"),
2458 (21, "https://a.test/next"),
2459 (22, "https://b.test/one"),
2460 (22, "https://b.test/two"),
2461 (22, "https://b.test/one"),
2462 (22, "https://b.test/two"),
2463 (23, "https://c.test/branched"),
2464 ]
2465 .map(|(surface, iri)| {
2466 (
2467 Uuid::from_u128(surface).to_string(),
2468 chartulary::resource_id(iri).to_string(),
2469 )
2470 });
2471 let actual_bindings = captured
2472 .iter()
2473 .filter_map(|delta| match delta {
2474 CapturedDelta::ReplaySetShownResourceById {
2475 surface_id,
2476 resource_id: Some(resource_id),
2477 } => Some((surface_id.clone(), resource_id.clone())),
2478 _ => None,
2479 })
2480 .collect::<Vec<_>>();
2481 assert_eq!(actual_bindings, expected_bindings);
2482 let expected_records = [
2483 "https://a.test",
2484 "https://b.test",
2485 "https://c.test",
2486 "https://a.test/next",
2487 "https://b.test/one",
2488 "https://b.test/two",
2489 "https://c.test/branched",
2490 ]
2491 .map(|iri| {
2492 (
2493 chartulary::resource_id(iri).to_string(),
2494 chartulary::canonical_url(iri),
2495 )
2496 });
2497 let actual_records = captured.iter().enumerate().filter_map(|(index, delta)| match delta {
2498 CapturedDelta::ReplaySetResourceRecordById { resource_id, record: Some(record) }
2499 if record.facets.is_empty() && expected_records.iter().any(|(id, _)| id == resource_id) => {
2500 assert!(record.facets.is_empty());
2501 let shown = captured.iter().position(|delta| matches!(delta,
2502 CapturedDelta::ReplaySetShownResourceById { resource_id: Some(id), .. } if id == resource_id)).unwrap();
2503 assert!(index < shown, "resource exists before the first shown binding");
2504 assert!(captured[..index].iter().any(|delta| match delta {
2505 CapturedDelta::ReplayAddNodeWithIdIfMissing { url, .. }
2506 | CapturedDelta::ReplayNavigateNodeById { url, .. }
2507 | CapturedDelta::ReplaySetNodeUrlById { new_url: url, .. } => {
2508 chartulary::resource_id(url).to_string() == *resource_id
2509 },
2510 _ => false,
2511 }));
2512 Some((resource_id.clone(), record.canonical_iri.clone()))
2513 },
2514 _ => None,
2515 }).collect::<Vec<_>>();
2516 assert_eq!(
2517 actual_records, expected_records,
2518 "history revisits retain existing records"
2519 );
2520 let replayed = replay_captured_deltas(captured.iter().cloned());
2521 let expected = graph.to_snapshot();
2522 let mut actual = replayed.to_snapshot();
2523 actual.timestamp_secs = expected.timestamp_secs;
2524 let canonical = |snapshot: &crate::persistence::GraphSnapshot| {
2525 let mut value = serde_json::to_value(snapshot).unwrap();
2526 let navigation = &mut value["navigation"]["snapshot"];
2527 for owner in navigation["owners"].as_array_mut().unwrap() {
2528 owner["owned_visits"]
2529 .as_array_mut()
2530 .unwrap()
2531 .sort_by_key(|id| id.as_u64().unwrap());
2532 }
2533 for visit in navigation["visits"].as_array_mut().unwrap() {
2534 visit["bindings"]
2535 .as_array_mut()
2536 .unwrap()
2537 .sort_by_key(|binding| binding["owner"].as_u64().unwrap());
2538 }
2539 value
2540 };
2541 assert_eq!(canonical(&actual), canonical(&expected));
2542 assert_eq!(replayed.facets(), graph.facets());
2543 assert_eq!(actual.resources, expected.resources);
2544 assert_eq!(actual.resource_edges, expected.resource_edges);
2545 assert_eq!(actual.shown_resources, expected.shown_resources);
2546 assert!(replayed.get_node_key_by_id(Uuid::from_u128(22)).is_none());
2547 assert_eq!(
2548 graph
2549 .find_semantic_statement(&historical_statement.statement_id)
2550 .unwrap()
2551 .1,
2552 &historical_statement,
2553 "navigation and Surface removal leave the original Resource assertion held"
2554 );
2555 assert!(graph.node_content_tags(a).unwrap().contains("paper"));
2556 assert!(!graph.node_content_tags(a).unwrap().contains("research"));
2557 assert_eq!(graph.node_properties(a).unwrap().len(), 1);
2558 let classes = graph.node_classifications(a).unwrap();
2559 assert_eq!(classes.len(), 2);
2560 assert!(
2561 classes
2562 .iter()
2563 .any(|classification| classification.value == "article"
2564 && classification.status == ClassificationStatus::Verified)
2565 );
2566 assert!(
2567 classes
2568 .iter()
2569 .any(|classification| classification.value == "essay"
2570 && classification.primary
2571 && classification.status == ClassificationStatus::Suggested)
2572 );
2573 let content_records: Vec<_> = captured
2574 .iter()
2575 .filter_map(|delta| match delta {
2576 CapturedDelta::ReplaySetResourceRecordById {
2577 record: Some(record),
2578 ..
2579 } if !record.facets.is_empty() => Some(record),
2580 _ => None,
2581 })
2582 .collect();
2583 for facet in [
2584 crate::graph::resource_content::TAG_CONCEPT,
2585 crate::graph::resource_content::RESOURCE_PROPERTIES,
2586 crate::graph::resource_content::RESOURCE_CLASSIFICATIONS,
2587 ] {
2588 assert!(
2589 content_records
2590 .iter()
2591 .any(|record| record.facets.iter().any(|entry| entry.facet == facet)),
2592 "{facet} is captured exactly"
2593 );
2594 }
2595 let mut out = Vec::new();
2596 for (index, delta) in captured.iter().enumerate() {
2597 let stamp = index > 0
2598 && matches!(delta, CapturedDelta::ReplayTouchNodeLastVisitedById { .. })
2599 && matches!(
2600 captured[index - 1],
2601 CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
2602 );
2603 if !stamp
2604 && !matches!(
2605 delta,
2606 CapturedDelta::ReplaySetEdgesByIds { .. }
2607 | CapturedDelta::ReplaySetResourceEdgesByIds { .. }
2608 | CapturedDelta::ReplaySetResourceRecordById { .. }
2609 | CapturedDelta::ReplaySetShownResourceById { .. }
2610 )
2611 {
2612 out.push(delta.clone());
2613 }
2614 }
2615 assert_eq!(out.len(), 38);
2616 assert!(matches!(
2617 out[0],
2618 CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
2619 ));
2620 assert!(matches!(
2621 out[1],
2622 CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
2623 ));
2624 assert!(matches!(
2625 out[2],
2626 CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
2627 ));
2628 assert!(matches!(
2629 out[3],
2630 CapturedDelta::ReplayAppendTraversalByIds { .. }
2631 ));
2632 assert!(matches!(
2633 out[4],
2634 CapturedDelta::ReplaySetNodeTitleById { .. }
2635 ));
2636 assert!(matches!(out[5], CapturedDelta::ReplaySetNodeUrlById { .. }));
2637 assert!(matches!(
2638 out[6],
2639 CapturedDelta::ReplaySetNodeImageById { .. }
2640 ));
2641 assert!(matches!(
2642 out[7],
2643 CapturedDelta::ReplaySetNodeImageById { .. }
2644 ));
2645 assert!(matches!(
2646 out[8],
2647 CapturedDelta::ReplaySetNodeMimeHintById { .. }
2648 ));
2649 assert!(matches!(
2650 out[9],
2651 CapturedDelta::ReplaySetNodePinnedById { .. }
2652 ));
2653 assert!(matches!(
2654 out[10],
2655 CapturedDelta::ReplaySetNodeBodyById { .. }
2656 ));
2657 assert!(matches!(
2658 out[11],
2659 CapturedDelta::ReplayTouchNodeLastVisitedById { .. }
2660 ));
2661 assert!(matches!(
2662 out[12],
2663 CapturedDelta::ReplaySetNodeTagIconOverrideById { .. }
2664 ));
2665 assert!(matches!(
2666 out[13],
2667 CapturedDelta::ReplayNavigateNodeById { .. }
2668 ));
2669 assert!(matches!(
2670 out[14],
2671 CapturedDelta::ReplayNavigateNodeById { .. }
2672 ));
2673 assert!(matches!(
2674 out[15],
2675 CapturedDelta::ReplayNodeHistoryBackById { .. }
2676 ));
2677 assert!(matches!(
2678 out[16],
2679 CapturedDelta::ReplayNodeHistoryForwardById { .. }
2680 ));
2681 assert!(matches!(
2682 out[17],
2683 CapturedDelta::ReplayBranchHistoryByIds { .. }
2684 ));
2685 assert!(matches!(
2686 out[18],
2687 CapturedDelta::ReplayNavigateNodeById { .. }
2688 ));
2689 assert!(matches!(out[19], CapturedDelta::ReplayAddField { .. }));
2690 assert!(matches!(out[20], CapturedDelta::ReplayAddCoupling { .. }));
2691 assert!(matches!(
2692 out[21],
2693 CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId { .. }
2694 ));
2695 assert!(matches!(
2696 out[22],
2697 CapturedDelta::ReplayRetireFieldById { .. }
2698 ));
2699 assert!(matches!(
2700 out[23],
2701 CapturedDelta::ReplayActivateFieldById { .. }
2702 ));
2703 assert!(matches!(
2704 out[24],
2705 CapturedDelta::ReplayRetractCouplingById { .. }
2706 ));
2707 assert!(matches!(out[25], CapturedDelta::ReplayAddCoupling { .. }));
2708 assert!(matches!(
2709 out[26],
2710 CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId { .. }
2711 ));
2712 assert!(matches!(
2713 out[27],
2714 CapturedDelta::ReplayRecordNodeDerivationById { .. }
2715 ));
2716 assert!(matches!(
2717 out[28],
2718 CapturedDelta::ReplayAppendFrameLayoutHintById { .. }
2719 ));
2720 assert!(matches!(
2721 out[29],
2722 CapturedDelta::ReplayAppendFrameLayoutHintById { .. }
2723 ));
2724 assert!(matches!(
2725 out[30],
2726 CapturedDelta::ReplayMoveFrameLayoutHintById { .. }
2727 ));
2728 assert!(matches!(
2729 out[31],
2730 CapturedDelta::ReplayRemoveFrameLayoutHintById { .. }
2731 ));
2732 assert!(matches!(
2733 out[32],
2734 CapturedDelta::ReplaySetFrameSplitOfferSuppressedById { .. }
2735 ));
2736 assert!(matches!(
2737 out[33],
2738 CapturedDelta::ReplayUpdateNodeHistoryById { .. }
2739 ));
2740 assert!(matches!(
2741 out[34],
2742 CapturedDelta::ReplaySetImportRecords { .. }
2743 ));
2744 assert!(matches!(
2745 out[35],
2746 CapturedDelta::ReplaySetImportRecords { .. }
2747 ));
2748 assert!(matches!(
2749 out[36],
2750 CapturedDelta::ReplaySetImportRecords { .. }
2751 ));
2752 assert!(matches!(
2753 out[37],
2754 CapturedDelta::ReplayRemoveNodeById { .. }
2755 ));
2756 }
2757}
2758
2759#[cfg(test)]
2760mod resource_capture_tests {
2761 use std::sync::{Arc, Mutex};
2762
2763 use super::*;
2764 use crate::graph::{Author, GraphJournal, SemanticStatement};
2765 use crate::persistence::PersistedResourceFacet;
2766
2767 fn record(iri: &str) -> CapturedDelta {
2768 CapturedDelta::ReplaySetResourceRecordById {
2769 resource_id: chartulary::resource_id(iri).to_string(),
2770 record: Some(PersistedResourceRecord {
2771 canonical_iri: chartulary::canonical_url(iri),
2772 facets: vec![PersistedResourceFacet {
2773 facet: "foreign.metadata".into(),
2774 value_json: r#"{"nested":[null,{"future":"kept"}]}"#.into(),
2775 }],
2776 }),
2777 }
2778 }
2779
2780 fn edges(from: Uuid, to: Uuid) -> Vec<PersistedEdge> {
2781 let mut persisted = Vec::new();
2782 for (statement_id, source_iri, time) in [
2783 ("minted-handle", "https://people.test/minter", 10),
2784 ("explicit-handle", "https://people.test/explicit", 20),
2785 ] {
2786 let mut graph = Graph::new();
2787 let source =
2788 graph.add_node_with_id(from, "https://surface-a.test".into(), Default::default());
2789 let target =
2790 graph.add_node_with_id(to, "https://surface-b.test".into(), Default::default());
2791 graph.assert_surface_persisted_semantic_statement(
2792 source,
2793 target,
2794 SemanticStatement {
2795 statement_id: statement_id.into(),
2796 predicate: "https://vocab.test/relation".into(),
2797 recognized_sub_kind: None,
2798 label: None,
2799 graph_scope: crate::types::GraphScope::User,
2800 provenance_iri: Some(source_iri.into()),
2801 asserted_at_ms: Some(time),
2802 first_asserted_ms: Some(time),
2803 withdrawn: None,
2804 basis: Default::default(),
2805 },
2806 );
2807 persisted.extend(graph.persisted_edges_between(source, target));
2808 }
2809 persisted
2810 }
2811
2812 #[test]
2813 fn resource_capture_codecs_preserve_old_ordinals_and_new_payloads() {
2814 let old_pair = CapturedDelta::ReplaySetEdgesByIds {
2815 from_id: "a".into(),
2816 to_id: "b".into(),
2817 edges: Vec::new(),
2818 };
2819 assert_eq!(
2820 postcard::to_allocvec(&old_pair).unwrap(),
2821 [37, 1, b'a', 1, b'b', 0]
2822 );
2823 let old_content = CapturedDelta::ReplaySetNodeContentById {
2824 node_id: "a".into(),
2825 content: None,
2826 };
2827 assert_eq!(
2828 postcard::to_allocvec(&old_content).unwrap(),
2829 [46, 1, b'a', 0]
2830 );
2831 let iri = "https://resource.test/a";
2832 let resource = chartulary::resource_id(iri);
2833 let other = chartulary::resource_id("https://resource.test/b");
2834 let variants = [
2835 record(iri),
2836 CapturedDelta::ReplaySetResourceEdgesByIds {
2837 from_resource_id: resource.to_string(),
2838 to_resource_id: other.to_string(),
2839 edges: edges(resource, other),
2840 },
2841 CapturedDelta::ReplaySetShownResourceById {
2842 surface_id: Uuid::from_u128(1).to_string(),
2843 resource_id: Some(resource.to_string()),
2844 },
2845 ];
2846 for (ordinal, delta) in (47u8..).zip(variants) {
2847 let bytes = postcard::to_allocvec(&delta).unwrap();
2848 assert_eq!(bytes[0], ordinal);
2849 assert_eq!(
2850 postcard::from_bytes::<CapturedDelta>(&bytes).unwrap(),
2851 delta
2852 );
2853 let json = serde_json::to_string(&delta).unwrap();
2854 assert_eq!(serde_json::from_str::<CapturedDelta>(&json).unwrap(), delta);
2855 }
2856 }
2857
2858 #[test]
2859 fn resource_capture_replay_preserves_strata_exact_data_and_noops() {
2860 let from = chartulary::resource_id("https://resource.test/a");
2861 let to = chartulary::resource_id("https://resource.test/b");
2862 let mut graph = Graph::new();
2863 let source =
2864 graph.add_node_with_id(from, "https://surface.test/a".into(), Default::default());
2865 let target =
2866 graph.add_node_with_id(to, "https://surface.test/b".into(), Default::default());
2867 graph.assert_surface_persisted_semantic_statement(
2868 source,
2869 target,
2870 SemanticStatement {
2871 statement_id: "surface-control".into(),
2872 predicate: "https://vocab.test/surface".into(),
2873 recognized_sub_kind: None,
2874 label: None,
2875 graph_scope: crate::types::GraphScope::User,
2876 provenance_iri: Some("https://people.test/surface".into()),
2877 asserted_at_ms: Some(30),
2878 first_asserted_ms: Some(30),
2879 withdrawn: None,
2880 basis: Default::default(),
2881 },
2882 );
2883 let baseline = graph.clone();
2884 let seen = Arc::new(Mutex::new(Vec::new()));
2885 let sink = seen.clone();
2886 graph.set_recorder(Some(Arc::new(move |delta: &CapturedDelta| {
2887 sink.lock().unwrap().push(delta.clone())
2888 })));
2889 let writes = [
2890 record("https://resource.test/a"),
2891 record("https://resource.test/b"),
2892 CapturedDelta::ReplaySetResourceEdgesByIds {
2893 from_resource_id: from.to_string(),
2894 to_resource_id: to.to_string(),
2895 edges: edges(from, to),
2896 },
2897 CapturedDelta::ReplaySetShownResourceById {
2898 surface_id: from.to_string(),
2899 resource_id: Some(from.to_string()),
2900 },
2901 ];
2902 for delta in &writes {
2903 apply_graph_delta(&mut graph, delta.replay().into_write().unwrap());
2904 }
2905 let recorded = seen.lock().unwrap().clone();
2906 assert_eq!(recorded.len(), 4);
2907 let revision = graph.revision();
2908 for delta in &recorded {
2909 apply_graph_delta(&mut graph, delta.replay().into_write().unwrap());
2910 }
2911 assert_eq!(
2912 seen.lock().unwrap().len(),
2913 4,
2914 "identical writes capture nothing"
2915 );
2916 assert_eq!(graph.revision(), revision);
2917 assert_eq!(
2918 graph.persisted_edges_between(source, target),
2919 baseline.persisted_edges_between(source, target)
2920 );
2921 assert_eq!(
2922 graph.persisted_resource_edges_between(from, to),
2923 edges(from, to)
2924 );
2925 let mut restored = baseline;
2926 replay_captured_deltas_onto(&mut restored, recorded);
2927 assert_eq!(restored.resource_record(from), graph.resource_record(from));
2928 assert_eq!(
2929 restored.persisted_resource_edges_between(from, to),
2930 graph.persisted_resource_edges_between(from, to)
2931 );
2932 assert_eq!(restored.shown_resource_id(source), Some(from));
2933 assert_eq!(restored.surface_ids_showing_resource(from), [from]);
2934 }
2935
2936 #[test]
2937 fn resource_capture_journal_preserves_mint_source_across_withdrawal() {
2938 let from = chartulary::resource_id("https://resource.test/a");
2939 let to = chartulary::resource_id("https://resource.test/b");
2940 let mut captured = edges(from, to);
2941 captured[0].retained_assertions_mut()[0].provenance_iri = None;
2942 let pair = |edges| CapturedDelta::ReplaySetResourceEdgesByIds {
2943 from_resource_id: from.to_string(),
2944 to_resource_id: to.to_string(),
2945 edges,
2946 };
2947 let minter = Author::engine("mint-engine", "v1");
2948 let restorer = Author::person("restoring-person");
2949 let mut journal = GraphJournal::new();
2950 journal.record(record("https://resource.test/a"));
2951 journal.record(record("https://resource.test/b"));
2952 journal.record_as(minter.clone(), pair(captured.clone()));
2953 let before_withdrawal = journal.replay();
2954 journal.record_as(restorer.clone(), pair(Vec::new()));
2955 let absent = journal.replay();
2956 assert!(absent.persisted_resource_edges_between(from, to).is_empty());
2957 assert!(
2958 absent.resource_record(from).is_some(),
2959 "withdrawal keeps resource identity"
2960 );
2961 journal.record_as(restorer, pair(captured));
2962 let restored = journal.replay();
2963 assert_eq!(
2964 restored.persisted_resource_edges_between(from, to),
2965 before_withdrawal.persisted_resource_edges_between(from, to)
2966 );
2967 let persisted = restored.persisted_resource_edges_between(from, to);
2968 assert_eq!(persisted.len(), 2, "parallel exact records remain separate");
2969 let minted = &persisted[0].retained_assertions()[0];
2970 let explicit = &persisted[1].retained_assertions()[0];
2971 assert_eq!(minted.statement_id, "minted-handle");
2972 assert_eq!(minted.asserted_at_ms, Some(10));
2973 assert_eq!(minted.provenance_iri, Some(minter.asserter_iri()));
2974 assert_eq!(explicit.statement_id, "explicit-handle");
2975 assert_eq!(explicit.asserted_at_ms, Some(20));
2976 assert_eq!(
2977 explicit.provenance_iri.as_deref(),
2978 Some("https://people.test/explicit")
2979 );
2980 }
2981}