Skip to main content

kernel/graph/
revert.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Reverting one change: the edits that put back what a change altered,
8//! leaving alone whatever changed after it.
9//!
10//! Reservoir plan V2, ยง7 items 17 and 18. A change's own edits name what it
11//! touched: nodes, the relations from one node to another, the field layer and
12//! the import records. For each such part, the graph just before the change,
13//! just after it, and now are compared. A part that still reads as the change
14//! left it goes back to how it stood before; a part changed since is kept and
15//! reported. The edits are ordinary ones (a retitle, a relation set back), so a
16//! Timeline reads an undo like any other change. Previews (node images) are
17//! experience, not truth, and are left alone.
18
19use std::collections::{BTreeMap, BTreeSet};
20
21use euclid::default::Point2D;
22use serde_json::Value;
23use uuid::Uuid;
24
25use super::apply::{GraphDelta, apply_graph_delta};
26use super::capture::{CapturedDelta, persisted_coupling_from_coupling, persisted_field_from_field};
27use super::node_facets::ARRANGEMENT_FRAME_LAYOUT;
28use super::{CouplingId, FieldId, FrameLayoutHint, Graph, NodeKey};
29use crate::persistence::{
30    PersistedEdge, PersistedFieldExtent, PersistedResourceFacet, PersistedResourceRecord,
31};
32
33/// One part of the graph a change can alter.
34#[derive(
35    Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
36)]
37#[serde(rename_all = "snake_case")]
38pub enum Part {
39    /// A node as a whole: made or removed by the change.
40    Node(Uuid),
41    Title(Uuid),
42    Url(Uuid),
43    Tag(Uuid, String),
44    Body(Uuid),
45    Content(Uuid),
46    MediaType(Uuid),
47    Nested(Uuid),
48    Facet(Uuid, String),
49    History(Uuid),
50    /// Every relation from the first node to the second.
51    Edges(Uuid, Uuid),
52    Field(Uuid),
53    Coupling(Uuid),
54    ImportRecords,
55    Resource(Uuid),
56    ResourceFacet(Uuid, String),
57    ResourceEdges(Uuid, Uuid),
58    ShownResource(Uuid),
59}
60
61/// The edits that revert a change, and the parts left as they are.
62#[derive(Clone, Debug, Default, PartialEq)]
63pub struct Revert {
64    pub edits: Vec<CapturedDelta>,
65    /// Parts changed after the change, kept rather than reverted.
66    pub kept: Vec<Part>,
67}
68
69/// What a set of edits names: nodes, node pairs, and the graph-level stores.
70#[derive(Clone, Debug, Default, PartialEq, Eq)]
71pub struct Touched {
72    pub nodes: BTreeSet<Uuid>,
73    pub edges: BTreeSet<(Uuid, Uuid)>,
74    pub fields: BTreeSet<Uuid>,
75    pub couplings: BTreeSet<Uuid>,
76    /// Fields whose couplings were retuned as a group.
77    pub coupled_fields: BTreeSet<Uuid>,
78    pub import_records: bool,
79    pub resources: BTreeSet<Uuid>,
80    pub resource_edges: BTreeSet<(Uuid, Uuid)>,
81    pub shown_surfaces: BTreeSet<Uuid>,
82}
83
84fn uuid(text: &str) -> Option<Uuid> {
85    Uuid::parse_str(text).ok()
86}
87
88impl Touched {
89    /// What `edits` name.
90    pub fn of<'a>(edits: impl IntoIterator<Item = &'a CapturedDelta>) -> Self {
91        let mut touched = Self::default();
92        for edit in edits {
93            touched.add(edit);
94        }
95        touched
96    }
97
98    fn node(&mut self, id: &str) {
99        self.nodes.extend(uuid(id));
100    }
101
102    fn edge(&mut self, from: &str, to: &str) {
103        if let (Some(from), Some(to)) = (uuid(from), uuid(to)) {
104            self.edges.insert((from, to));
105        }
106    }
107
108    // Exhaustive on purpose: a new edit kind must say what it touches.
109    fn add(&mut self, edit: &CapturedDelta) {
110        use CapturedDelta as D;
111        match edit {
112            D::ReplayAddNodeWithIdIfMissing { id, .. } => self.node(id),
113            D::ReplayRemoveNodeById { node_id }
114            | D::ReplaySetNodeTitleById { node_id, .. }
115            | D::ReplaySetNodeUrlById { node_id, .. }
116            | D::ReplaySetNodeImageById { node_id, .. }
117            | D::ReplaySetNodeThumbnailById { node_id, .. }
118            | D::ReplaySetNodeFaviconById { node_id, .. }
119            | D::ReplaySetNodeMimeHintById { node_id, .. }
120            | D::ReplaySetNodeNestedById { node_id, .. }
121            | D::ReplaySetNodePinnedById { node_id, .. }
122            | D::ReplaySetNodeFacetById { node_id, .. }
123            | D::ReplayRemoveNodeFacetById { node_id, .. }
124            | D::ReplayInsertNodeTagById { node_id, .. }
125            | D::ReplayRemoveNodeTagById { node_id, .. }
126            | D::ReplaySetNodeBodyById { node_id, .. }
127            | D::ReplayNavigateNodeById { node_id, .. }
128            | D::ReplayNodeHistoryBackById { node_id, .. }
129            | D::ReplayNodeHistoryForwardById { node_id, .. }
130            | D::ReplayAppendNodePropertyById { node_id, .. }
131            | D::ReplayAddNodeClassificationById { node_id, .. }
132            | D::ReplayRemoveNodeClassificationById { node_id, .. }
133            | D::ReplaySetNodeClassificationStatusById { node_id, .. }
134            | D::ReplaySetNodePrimaryClassificationById { node_id, .. }
135            | D::ReplayRecordNodeDerivationById { node_id, .. }
136            | D::ReplaySetNodeTagIconOverrideById { node_id, .. }
137            | D::ReplayAppendFrameLayoutHintById { node_id, .. }
138            | D::ReplayRemoveFrameLayoutHintById { node_id, .. }
139            | D::ReplayMoveFrameLayoutHintById { node_id, .. }
140            | D::ReplaySetFrameSplitOfferSuppressedById { node_id, .. }
141            | D::ReplayUpdateNodeHistoryById { node_id, .. }
142            | D::ReplayTouchNodeLastVisitedById { node_id, .. }
143            | D::ReplaySetNodeContentById { node_id, .. } => self.node(node_id),
144            D::ReplayBranchHistoryByIds {
145                child_id,
146                parent_id,
147            } => {
148                self.node(child_id);
149                self.node(parent_id);
150            },
151            D::ReplayAssertRelationByIds { from_id, to_id, .. }
152            | D::ReplayRetractRelationsByIds { from_id, to_id, .. }
153            | D::ReplayAppendTraversalByIds { from_id, to_id, .. }
154            | D::ReplaySetEdgeSemanticPredicateByIds { from_id, to_id, .. }
155            | D::ReplayAssertSemanticPredicateByIds { from_id, to_id, .. }
156            | D::ReplaySetEdgesByIds { from_id, to_id, .. } => self.edge(from_id, to_id),
157            D::ReplaySetImportRecords { .. } => self.import_records = true,
158            D::ReplayAddField { field } => self.fields.extend(uuid(&field.id)),
159            D::ReplayRetireFieldById { field_id }
160            | D::ReplayActivateFieldById { field_id }
161            | D::ReplayRemoveFieldById { field_id } => self.fields.extend(uuid(field_id)),
162            D::ReplaySetFieldCouplingStrengthByFieldId { field_id, .. } => {
163                self.coupled_fields.extend(uuid(field_id));
164            },
165            D::ReplayAddCoupling { coupling } => self.couplings.extend(uuid(&coupling.id)),
166            D::ReplayRetractCouplingById { coupling_id } => {
167                self.couplings.extend(uuid(coupling_id));
168            },
169            D::ReplaySetResourceRecordById { resource_id, .. } => {
170                self.resources.extend(uuid(resource_id));
171            },
172            D::ReplaySetResourceEdgesByIds {
173                from_resource_id,
174                to_resource_id,
175                ..
176            } => {
177                if let (Some(from), Some(to)) = (uuid(from_resource_id), uuid(to_resource_id)) {
178                    self.resource_edges.insert((from, to));
179                }
180            },
181            D::ReplaySetShownResourceById {
182                surface_id,
183                resource_id,
184            } => {
185                self.shown_surfaces.extend(uuid(surface_id));
186                self.resources.extend(resource_id.as_deref().and_then(uuid));
187            },
188        }
189    }
190
191    /// Whether these edits reach `part`: how a caller learns who changed a
192    /// part that undo kept.
193    pub fn reaches(&self, part: &Part) -> bool {
194        match part {
195            Part::Node(id)
196            | Part::Title(id)
197            | Part::Url(id)
198            | Part::Tag(id, _)
199            | Part::Body(id)
200            | Part::Content(id)
201            | Part::MediaType(id)
202            | Part::Nested(id)
203            | Part::Facet(id, _)
204            | Part::History(id) => {
205                self.nodes.contains(id)
206                    || self.shown_surfaces.contains(id)
207                    || self.edges.iter().any(|(from, to)| from == id || to == id)
208            },
209            Part::Edges(from, to) => {
210                self.edges.contains(&(*from, *to))
211                    || self.nodes.contains(from)
212                    || self.nodes.contains(to)
213            },
214            Part::Field(id) => self.fields.contains(id),
215            Part::Coupling(id) => self.couplings.contains(id) || !self.coupled_fields.is_empty(),
216            Part::ImportRecords => self.import_records,
217            Part::Resource(id) | Part::ResourceFacet(id, _) => {
218                self.resources.contains(id)
219                    || self
220                        .resource_edges
221                        .iter()
222                        .any(|(from, to)| from == id || to == id)
223            },
224            Part::ResourceEdges(from, to) => {
225                self.resource_edges.contains(&(*from, *to))
226                    || self.resources.contains(from)
227                    || self.resources.contains(to)
228            },
229            Part::ShownResource(id) => self.shown_surfaces.contains(id) || self.nodes.contains(id),
230        }
231    }
232}
233
234/// Rewrites an id in place when the map names it.
235type Swap<'a> = &'a dyn Fn(&mut String);
236
237impl CapturedDelta {
238    /// This edit with each id in `ids` (old to new, as canonical UUID text)
239    /// rewritten where the edit holds an id, and every other string as it was:
240    /// a title, tag, url or body that reads like an id is text.
241    ///
242    /// The id fields are those [`Touched`] reads, and the ids those edits carry
243    /// in their payloads: the ends of a relation, an import membership, a
244    /// field's attached node and a frame-layout member. A node facet's value is
245    /// rewritten through [`remap_facet_value`]; a resource record and a
246    /// derivation are carried as written.
247    ///
248    /// Exhaustive on purpose, as `Touched::add` is: a new edit kind must say
249    /// which of its fields are ids.
250    pub fn remap_ids(&self, ids: &BTreeMap<String, String>) -> CapturedDelta {
251        use CapturedDelta as D;
252        let swap = |id: &mut String| {
253            if let Some(mapped) = ids.get(id.as_str()) {
254                id.clone_from(mapped);
255            }
256        };
257        let mut edit = self.clone();
258        match &mut edit {
259            D::ReplayAddNodeWithIdIfMissing { id, .. } => swap(id),
260            D::ReplayRemoveNodeById { node_id }
261            | D::ReplaySetNodeTitleById { node_id, .. }
262            | D::ReplaySetNodeUrlById { node_id, .. }
263            | D::ReplaySetNodeImageById { node_id, .. }
264            | D::ReplaySetNodeThumbnailById { node_id, .. }
265            | D::ReplaySetNodeFaviconById { node_id, .. }
266            | D::ReplaySetNodeMimeHintById { node_id, .. }
267            | D::ReplaySetNodeNestedById { node_id, .. }
268            | D::ReplaySetNodePinnedById { node_id, .. }
269            | D::ReplayRemoveNodeFacetById { node_id, .. }
270            | D::ReplayInsertNodeTagById { node_id, .. }
271            | D::ReplayRemoveNodeTagById { node_id, .. }
272            | D::ReplaySetNodeBodyById { node_id, .. }
273            | D::ReplayNavigateNodeById { node_id, .. }
274            | D::ReplayNodeHistoryBackById { node_id, .. }
275            | D::ReplayNodeHistoryForwardById { node_id, .. }
276            | D::ReplayAppendNodePropertyById { node_id, .. }
277            | D::ReplayAddNodeClassificationById { node_id, .. }
278            | D::ReplayRemoveNodeClassificationById { node_id, .. }
279            | D::ReplaySetNodeClassificationStatusById { node_id, .. }
280            | D::ReplaySetNodePrimaryClassificationById { node_id, .. }
281            // A derivation's `source_node` names a node of another graph: kept.
282            | D::ReplayRecordNodeDerivationById { node_id, .. }
283            | D::ReplaySetNodeTagIconOverrideById { node_id, .. }
284            | D::ReplayRemoveFrameLayoutHintById { node_id, .. }
285            | D::ReplayMoveFrameLayoutHintById { node_id, .. }
286            | D::ReplaySetFrameSplitOfferSuppressedById { node_id, .. }
287            | D::ReplayUpdateNodeHistoryById { node_id, .. }
288            | D::ReplayTouchNodeLastVisitedById { node_id, .. }
289            | D::ReplaySetNodeContentById { node_id, .. } => swap(node_id),
290            D::ReplaySetNodeFacetById {
291                node_id,
292                facet,
293                value_json,
294            } => {
295                swap(node_id);
296                *value_json = remap_facet_value(facet, value_json, &swap);
297            },
298            D::ReplayAppendFrameLayoutHintById { node_id, hint } => {
299                swap(node_id);
300                remap_hint(hint, &swap);
301            },
302            D::ReplayBranchHistoryByIds {
303                child_id,
304                parent_id,
305            } => {
306                swap(child_id);
307                swap(parent_id);
308            },
309            D::ReplayAssertRelationByIds { from_id, to_id, .. }
310            | D::ReplayRetractRelationsByIds { from_id, to_id, .. }
311            | D::ReplayAppendTraversalByIds { from_id, to_id, .. }
312            | D::ReplaySetEdgeSemanticPredicateByIds { from_id, to_id, .. }
313            | D::ReplayAssertSemanticPredicateByIds { from_id, to_id, .. } => {
314                swap(from_id);
315                swap(to_id);
316            },
317            D::ReplaySetEdgesByIds {
318                from_id,
319                to_id,
320                edges,
321            } => {
322                swap(from_id);
323                swap(to_id);
324                remap_ends(edges, &swap);
325            },
326            D::ReplaySetImportRecords { import_records } => {
327                for member in import_records.iter_mut().flat_map(|r| &mut r.memberships) {
328                    swap(&mut member.node_id);
329                }
330            },
331            D::ReplayAddField { field } => {
332                swap(&mut field.id);
333                if let PersistedFieldExtent::AttachedToNode(node) = &mut field.extent {
334                    swap(node);
335                }
336            },
337            D::ReplayRetireFieldById { field_id }
338            | D::ReplayActivateFieldById { field_id }
339            | D::ReplayRemoveFieldById { field_id }
340            | D::ReplaySetFieldCouplingStrengthByFieldId { field_id, .. } => swap(field_id),
341            D::ReplayAddCoupling { coupling } => {
342                swap(&mut coupling.id);
343                swap(&mut coupling.field_id);
344            },
345            D::ReplayRetractCouplingById { coupling_id } => swap(coupling_id),
346            D::ReplaySetResourceRecordById { resource_id, .. } => swap(resource_id),
347            D::ReplaySetResourceEdgesByIds {
348                from_resource_id,
349                to_resource_id,
350                edges,
351            } => {
352                swap(from_resource_id);
353                swap(to_resource_id);
354                remap_ends(edges, &swap);
355            },
356            D::ReplaySetShownResourceById {
357                surface_id,
358                resource_id,
359            } => {
360                swap(surface_id);
361                if let Some(resource) = resource_id {
362                    swap(resource);
363                }
364            },
365        }
366        edit
367    }
368}
369
370fn remap_ends(edges: &mut [PersistedEdge], swap: Swap) {
371    for edge in edges {
372        swap(&mut edge.from_node_id);
373        swap(&mut edge.to_node_id);
374    }
375}
376
377fn remap_hint(hint: &mut FrameLayoutHint, swap: Swap) {
378    use FrameLayoutHint as H;
379    match hint {
380        H::SplitHalf { first, second, .. } => [first, second].into_iter().for_each(swap),
381        H::SplitPamphlet { members, .. } => members.iter_mut().for_each(swap),
382        H::SplitTriptych {
383            dominant, wings, ..
384        } => {
385            swap(dominant);
386            wings.iter_mut().for_each(swap);
387        },
388        H::SplitQuartered {
389            top_left,
390            top_right,
391            bottom_left,
392            bottom_right,
393        } => [top_left, top_right, bottom_left, bottom_right]
394            .into_iter()
395            .for_each(swap),
396    }
397}
398
399/// The value of node facet `facet` with the ids it declares rewritten, and
400/// the text unchanged for every other facet: facets are open JSON, so a facet
401/// names ids only by declaring them here. The kernel's own:
402///
403/// - `arrangement.frame-layout` holds hints whose members are node ids of the
404///   graph itself: rewritten.
405/// - `provenance.derivations` holds `source_node`, a node of the source
406///   graph, which is what a pick merge matches on: kept.
407/// - `arrangement.pin` and `arrangement.split-offer-suppressed` are flags,
408///   `visit.history` clocks, `presentation.tags` tag names and icons,
409///   `provenance.import` an import source's id and label,
410///   `semantic.classifications` and `semantic.properties` scheme values and
411///   literals: none holds a node id.
412fn remap_facet_value(facet: &str, value_json: &str, swap: Swap) -> String {
413    match facet {
414        ARRANGEMENT_FRAME_LAYOUT => serde_json::from_str::<Vec<FrameLayoutHint>>(value_json)
415            .ok()
416            .and_then(|mut hints| {
417                hints.iter_mut().for_each(|hint| remap_hint(hint, swap));
418                serde_json::to_string(&hints).ok()
419            })
420            .unwrap_or_else(|| value_json.to_string()),
421        _ => value_json.to_string(),
422    }
423}
424
425/// A node's revertible state, part by part.
426#[derive(Clone, Debug, PartialEq)]
427pub(super) struct NodeState {
428    pub(super) title: String,
429    pub(super) url: String,
430    pub(super) tags: BTreeSet<String>,
431    pub(super) body: Option<String>,
432    pub(super) content: Option<[u8; 32]>,
433    pub(super) media_type: Option<String>,
434    pub(super) nested: Option<String>,
435    pub(super) facets: BTreeMap<String, Value>,
436    pub(super) history: (Vec<String>, usize),
437}
438
439pub(super) fn node_state(graph: &Graph, id: Uuid) -> Option<NodeState> {
440    let (key, node) = graph.get_node_by_id(id)?;
441    let history = graph.node_history_projection(key);
442    Some(NodeState {
443        title: node.title.clone(),
444        url: node.primary_address().as_url_str().to_string(),
445        tags: node.tags.iter().cloned().collect(),
446        body: node.body.clone(),
447        content: node.content.map(|hash| *hash.as_bytes()),
448        media_type: node.media_type.clone(),
449        nested: node.nested.as_ref().map(|log| log.as_str().to_string()),
450        facets: graph
451            .facets()
452            .facets_of(&id)
453            .map(|facets| {
454                facets
455                    .iter()
456                    .map(|(facet, value)| (facet.as_str().to_string(), value.clone()))
457                    .collect()
458            })
459            .unwrap_or_default(),
460        history: (history.entries, history.current_index),
461    })
462}
463
464/// Every relation from `from` to `to`, in persisted form: compared as a
465/// whole and written back as a whole.
466pub(super) fn edges_between(graph: &Graph, from: Uuid, to: Uuid) -> Vec<PersistedEdge> {
467    match (graph.get_node_by_id(from), graph.get_node_by_id(to)) {
468        (Some((from, _)), Some((to, _))) => graph.persisted_edges_between(from, to),
469        _ => Vec::new(),
470    }
471}
472
473/// The pairs of nodes `id` has relations with, either way round.
474fn incident_pairs(graph: &Graph, id: Uuid) -> Vec<(Uuid, Uuid)> {
475    let Some((key, _)) = graph.get_node_by_id(id) else {
476        return Vec::new();
477    };
478    let id_of = |key: NodeKey| graph.get_node(key).map(|node| node.id);
479    graph
480        .outgoing_relations(key)
481        .chain(graph.incoming_relations(key))
482        .filter_map(|relation| Some((id_of(relation.from)?, id_of(relation.to)?)))
483        .collect()
484}
485
486fn shown_resource(graph: &Graph, surface: Uuid) -> Option<Uuid> {
487    graph
488        .get_node_by_id(surface)
489        .and_then(|(key, _)| graph.shown_resource_id(key))
490}
491
492fn resource_incident_pairs(graph: &Graph, id: Uuid) -> Vec<(Uuid, Uuid)> {
493    use petgraph::visit::EdgeRef;
494    let Some(key) = graph.resources.key_of(&id) else {
495        return Vec::new();
496    };
497    graph
498        .resources
499        .inner()
500        .edges_directed(key, petgraph::Direction::Outgoing)
501        .chain(
502            graph
503                .resources
504                .inner()
505                .edges_directed(key, petgraph::Direction::Incoming),
506        )
507        .filter_map(|edge| {
508            Some((
509                graph.resources.node(edge.source())?.id(),
510                graph.resources.node(edge.target())?.id(),
511            ))
512        })
513        .collect()
514}
515
516fn resource_facets(record: &PersistedResourceRecord) -> BTreeMap<String, Value> {
517    record
518        .facets
519        .iter()
520        .map(|facet| {
521            (
522                facet.facet.clone(),
523                serde_json::from_str(&facet.value_json)
524                    .expect("stored resource facets are valid JSON"),
525            )
526        })
527        .collect()
528}
529
530impl Revert {
531    fn keep(&mut self, part: Part) {
532        self.kept.push(part);
533    }
534
535    fn resource_parts(
536        &mut self,
537        id: Uuid,
538        before: &PersistedResourceRecord,
539        after: &PersistedResourceRecord,
540        live: &PersistedResourceRecord,
541    ) {
542        let was = resource_facets(before);
543        let became = resource_facets(after);
544        let mut now = resource_facets(live);
545        let keys: BTreeSet<_> = was.keys().chain(became.keys()).collect();
546        let mut changed = false;
547        for key in keys {
548            if was.get(key) == became.get(key) {
549                continue;
550            }
551            if now.get(key) != became.get(key) {
552                self.keep(Part::ResourceFacet(id, key.clone()));
553                continue;
554            }
555            match was.get(key) {
556                Some(value) => {
557                    now.insert(key.clone(), value.clone());
558                },
559                None => {
560                    now.remove(key);
561                },
562            }
563            changed = true;
564        }
565        if changed {
566            self.edits.push(CapturedDelta::ReplaySetResourceRecordById {
567                resource_id: id.to_string(),
568                record: Some(PersistedResourceRecord {
569                    canonical_iri: live.canonical_iri.clone(),
570                    facets: now
571                        .into_iter()
572                        .map(|(facet, value)| PersistedResourceFacet {
573                            facet,
574                            value_json: value.to_string(),
575                        })
576                        .collect(),
577                }),
578            });
579        }
580    }
581
582    /// Revert one part: `changed` if the change altered it, `untouched` if it
583    /// still reads as the change left it.
584    fn part(&mut self, part: Part, changed: bool, untouched: bool, edit: CapturedDelta) {
585        if !changed {
586            return;
587        }
588        if untouched {
589            self.edits.push(edit);
590        } else {
591            self.keep(part);
592        }
593    }
594
595    /// Put back each node part the change altered and nobody touched since.
596    fn node_parts(
597        &mut self,
598        id: Uuid,
599        before: &NodeState,
600        after: &NodeState,
601        live: &NodeState,
602        recreating: bool,
603    ) {
604        let node_id = id.to_string();
605        self.part(
606            Part::Title(id),
607            before.title != after.title,
608            live.title == after.title,
609            CapturedDelta::ReplaySetNodeTitleById {
610                node_id: node_id.clone(),
611                title: before.title.clone(),
612            },
613        );
614        self.part(
615            Part::Url(id),
616            before.url != after.url,
617            live.url == after.url,
618            CapturedDelta::ReplaySetNodeUrlById {
619                node_id: node_id.clone(),
620                new_url: before.url.clone(),
621            },
622        );
623        self.part(
624            Part::Body(id),
625            before.body != after.body,
626            live.body == after.body,
627            CapturedDelta::ReplaySetNodeBodyById {
628                node_id: node_id.clone(),
629                body: before.body.clone(),
630            },
631        );
632        self.part(
633            Part::Content(id),
634            before.content != after.content,
635            live.content == after.content,
636            CapturedDelta::ReplaySetNodeContentById {
637                node_id: node_id.clone(),
638                content: before.content,
639            },
640        );
641        self.part(
642            Part::MediaType(id),
643            before.media_type != after.media_type,
644            live.media_type == after.media_type,
645            CapturedDelta::ReplaySetNodeMimeHintById {
646                node_id: node_id.clone(),
647                mime_hint: before.media_type.clone(),
648            },
649        );
650        self.part(
651            Part::Nested(id),
652            before.nested != after.nested,
653            live.nested == after.nested,
654            CapturedDelta::ReplaySetNodeNestedById {
655                node_id: node_id.clone(),
656                nested: before.nested.clone(),
657            },
658        );
659        for tag in before.tags.symmetric_difference(&after.tags) {
660            let untouched = live.tags.contains(tag) == after.tags.contains(tag);
661            let edit = if before.tags.contains(tag) {
662                CapturedDelta::ReplayInsertNodeTagById {
663                    node_id: node_id.clone(),
664                    tag: tag.clone(),
665                }
666            } else {
667                CapturedDelta::ReplayRemoveNodeTagById {
668                    node_id: node_id.clone(),
669                    tag: tag.clone(),
670                }
671            };
672            self.part(Part::Tag(id, tag.clone()), true, untouched, edit);
673        }
674        let facet_ids: BTreeSet<&String> =
675            before.facets.keys().chain(after.facets.keys()).collect();
676        for facet in facet_ids {
677            let (was, became) = (before.facets.get(facet), after.facets.get(facet));
678            let edit = match was {
679                Some(value) => CapturedDelta::ReplaySetNodeFacetById {
680                    node_id: node_id.clone(),
681                    facet: facet.clone(),
682                    value_json: value.to_string(),
683                },
684                None => CapturedDelta::ReplayRemoveNodeFacetById {
685                    node_id: node_id.clone(),
686                    facet: facet.clone(),
687                },
688            };
689            self.part(
690                Part::Facet(id, facet.clone()),
691                recreating || was != became,
692                live.facets.get(facet) == became,
693                edit,
694            );
695        }
696        self.part(
697            Part::History(id),
698            before.history != after.history,
699            live.history == after.history,
700            CapturedDelta::ReplayUpdateNodeHistoryById {
701                node_id,
702                entries: before.history.0.clone(),
703                current_index: before.history.1,
704            },
705        );
706    }
707
708    /// Make a node the change removed again, as it stood before.
709    pub(super) fn recreate(&mut self, id: Uuid, before: &NodeState) {
710        // What a node is born with, so every part below lands as it stood.
711        let mut scratch = Graph::new();
712        let _ = apply_graph_delta(
713            &mut scratch,
714            GraphDelta::ReplayAddNodeWithIdIfMissing {
715                id,
716                url: before.url.clone(),
717                position: Point2D::new(0.0, 0.0),
718            },
719        );
720        let born = node_state(&scratch, id).expect("the scratch node exists");
721        self.recreate_from_birth_state(id, before, &born);
722    }
723
724    fn recreate_from_birth_state(&mut self, id: Uuid, before: &NodeState, born: &NodeState) {
725        self.edits
726            .push(CapturedDelta::ReplayAddNodeWithIdIfMissing {
727                id: id.to_string(),
728                url: before.url.clone(),
729                position: [0.0, 0.0],
730            });
731        // Replay's birth clock can differ from the planner's; restore every facet.
732        self.node_parts(id, before, born, born, true);
733    }
734}
735
736/// The edits that revert `change`, given the graph just before it (`before`),
737/// just after it (`after`) and now (`live`), and the parts kept because they
738/// changed since.
739pub fn revert_change(
740    change: &[CapturedDelta],
741    before: &Graph,
742    after: &Graph,
743    live: &Graph,
744) -> Revert {
745    let touched = Touched::of(change);
746    let mut out = Revert::default();
747    let mut resource_coming = BTreeSet::new();
748    let mut resource_removals = BTreeSet::new();
749    let mut resource_pairs = touched.resource_edges.clone();
750    for id in &touched.resources {
751        resource_pairs.extend(resource_incident_pairs(before, *id));
752        resource_pairs.extend(resource_incident_pairs(after, *id));
753        match (
754            before.resource_record(*id),
755            after.resource_record(*id),
756            live.resource_record(*id),
757        ) {
758            (None, Some(became), Some(now)) => {
759                if now == became {
760                    resource_removals.insert(*id);
761                } else {
762                    out.keep(Part::Resource(*id));
763                }
764            },
765            (Some(was), None, None) => {
766                resource_coming.insert(*id);
767                out.edits.push(CapturedDelta::ReplaySetResourceRecordById {
768                    resource_id: id.to_string(),
769                    record: Some(was),
770                });
771            },
772            (Some(_), None, Some(_)) => out.keep(Part::Resource(*id)),
773            (Some(was), Some(became), Some(now)) => out.resource_parts(*id, &was, &became, &now),
774            (Some(was), Some(became), None) if was != became => out.keep(Part::Resource(*id)),
775            _ => {},
776        }
777    }
778    let mut pairs = touched.edges.clone();
779    // A node made or removed takes its relations with it.
780    for id in &touched.nodes {
781        pairs.extend(incident_pairs(before, *id));
782        pairs.extend(incident_pairs(after, *id));
783    }
784
785    let mut going = BTreeSet::new();
786    let mut coming = BTreeSet::new();
787    let mut removals = Vec::new();
788    for id in &touched.nodes {
789        match (
790            node_state(before, *id),
791            node_state(after, *id),
792            node_state(live, *id),
793        ) {
794            // Made by the change: it goes, unless changed or linked since.
795            (None, Some(became), Some(now)) => {
796                let unlinked_since = incident_pairs(live, *id).into_iter().all(|(from, to)| {
797                    edges_between(live, from, to) == edges_between(after, from, to)
798                });
799                if now == became
800                    && unlinked_since
801                    && shown_resource(live, *id) == shown_resource(after, *id)
802                {
803                    going.insert(*id);
804                    removals.push(CapturedDelta::ReplayRemoveNodeById {
805                        node_id: id.to_string(),
806                    });
807                } else {
808                    out.keep(Part::Node(*id));
809                }
810            },
811            // Removed by the change: it comes back, unless made again since.
812            (Some(was), None, None) => {
813                coming.insert(*id);
814                out.recreate(*id, &was);
815            },
816            (Some(_), None, Some(_)) => out.keep(Part::Node(*id)),
817            (Some(was), Some(became), Some(now)) => out.node_parts(*id, &was, &became, &now, false),
818            // Removed by someone since the change.
819            (Some(was), Some(became), None) => {
820                if was != became {
821                    out.keep(Part::Node(*id));
822                }
823            },
824            (None, _, None) | (None, None, Some(_)) => {},
825        }
826    }
827
828    let present = |id: &Uuid| {
829        !going.contains(id) && (coming.contains(id) || live.get_node_by_id(*id).is_some())
830    };
831    for (from, to) in pairs {
832        let (was, became) = (
833            edges_between(before, from, to),
834            edges_between(after, from, to),
835        );
836        if was == became || going.contains(&from) || going.contains(&to) {
837            continue;
838        }
839        let untouched = edges_between(live, from, to) == became;
840        if !untouched || !present(&from) || !present(&to) {
841            out.keep(Part::Edges(from, to));
842            continue;
843        }
844        out.edits.push(CapturedDelta::ReplaySetEdgesByIds {
845            from_id: from.to_string(),
846            to_id: to.to_string(),
847            edges: was,
848        });
849    }
850    for (from, to) in resource_pairs {
851        let was = before.persisted_resource_edges_between(from, to);
852        let became = after.persisted_resource_edges_between(from, to);
853        if was == became {
854            continue;
855        }
856        let present = |id| resource_coming.contains(&id) || live.resource_record(id).is_some();
857        if live.persisted_resource_edges_between(from, to) != became
858            || !present(from)
859            || !present(to)
860        {
861            out.keep(Part::ResourceEdges(from, to));
862            continue;
863        }
864        out.edits.push(CapturedDelta::ReplaySetResourceEdgesByIds {
865            from_resource_id: from.to_string(),
866            to_resource_id: to.to_string(),
867            edges: was,
868        });
869    }
870    let shown_surfaces: BTreeSet<_> = touched
871        .shown_surfaces
872        .union(&touched.nodes)
873        .copied()
874        .collect();
875    for id in shown_surfaces {
876        let was = shown_resource(before, id);
877        let became = shown_resource(after, id);
878        if was == became {
879            continue;
880        }
881        let surface_present = coming.contains(&id) || live.get_node_by_id(id).is_some();
882        let resource_present = was.is_none_or(|resource| {
883            resource_coming.contains(&resource) || live.resource_record(resource).is_some()
884        });
885        if shown_resource(live, id) != became || !surface_present || !resource_present {
886            out.keep(Part::ShownResource(id));
887            continue;
888        }
889        out.edits.push(CapturedDelta::ReplaySetShownResourceById {
890            surface_id: id.to_string(),
891            resource_id: was.map(|resource| resource.to_string()),
892        });
893    }
894    out.edits.extend(removals);
895
896    if touched.import_records {
897        let (was, became) = (before.import_records(), after.import_records());
898        if was != became {
899            if live.import_records() == became {
900                out.edits.push(CapturedDelta::ReplaySetImportRecords {
901                    import_records: was.to_vec(),
902                });
903            } else {
904                out.keep(Part::ImportRecords);
905            }
906        }
907    }
908
909    for id in &touched.fields {
910        let state = |graph: &Graph| {
911            graph
912                .field(FieldId::from_uuid(*id))
913                .map(persisted_field_from_field)
914        };
915        let (was, became) = (state(before), state(after));
916        if was == became {
917            continue;
918        }
919        if state(live) != became {
920            out.keep(Part::Field(*id));
921            continue;
922        }
923        out.edits.push(match was {
924            Some(field) => CapturedDelta::ReplayAddField { field },
925            None => CapturedDelta::ReplayRemoveFieldById {
926                field_id: id.to_string(),
927            },
928        });
929    }
930
931    let mut couplings = touched.couplings.clone();
932    for graph in [before, after] {
933        couplings.extend(
934            graph
935                .couplings()
936                .filter(|coupling| touched.coupled_fields.contains(&coupling.field.as_uuid()))
937                .map(|coupling| coupling.id.as_uuid()),
938        );
939    }
940    for id in &couplings {
941        let state = |graph: &Graph| {
942            graph
943                .couplings()
944                .find(|coupling| coupling.id == CouplingId::from_uuid(*id))
945                .map(persisted_coupling_from_coupling)
946        };
947        let (was, became) = (state(before), state(after));
948        if was == became {
949            continue;
950        }
951        if state(live) != became {
952            out.keep(Part::Coupling(*id));
953            continue;
954        }
955        out.edits.push(match was {
956            Some(coupling) => CapturedDelta::ReplayAddCoupling { coupling },
957            None => CapturedDelta::ReplayRetractCouplingById {
958                coupling_id: id.to_string(),
959            },
960        });
961    }
962    if !resource_removals.is_empty() {
963        let mut scratch = live.clone();
964        super::capture::replay_captured_deltas_onto(&mut scratch, out.edits.iter().cloned());
965        for resource in resource_removals {
966            if scratch.set_resource_record(resource, None) {
967                out.edits.push(CapturedDelta::ReplaySetResourceRecordById {
968                    resource_id: resource.to_string(),
969                    record: None,
970                });
971            } else {
972                out.keep(Part::Resource(resource));
973            }
974        }
975    }
976    out
977}
978
979/// The part one revert or merge edit sets: what a caller picking edits by
980/// part (a merge-in applying one side of a conflict) filters on. An edit that
981/// recreates or removes a node is [`Part::Node`]; a whole resource record is
982/// [`Part::Resource`]. `None` for edits revert never writes (traversals,
983/// previews, layout hints and the like).
984pub fn part_of(edit: &CapturedDelta) -> Option<Part> {
985    use CapturedDelta as D;
986    let id = |text: &str| uuid(text);
987    Some(match edit {
988        D::ReplayAddNodeWithIdIfMissing { id: node, .. }
989        | D::ReplayRemoveNodeById { node_id: node } => Part::Node(id(node)?),
990        D::ReplaySetNodeTitleById { node_id, .. } => Part::Title(id(node_id)?),
991        D::ReplaySetNodeUrlById { node_id, .. } => Part::Url(id(node_id)?),
992        D::ReplayInsertNodeTagById { node_id, tag }
993        | D::ReplayRemoveNodeTagById { node_id, tag } => Part::Tag(id(node_id)?, tag.clone()),
994        D::ReplaySetNodeBodyById { node_id, .. } => Part::Body(id(node_id)?),
995        D::ReplaySetNodeContentById { node_id, .. } => Part::Content(id(node_id)?),
996        D::ReplaySetNodeMimeHintById { node_id, .. } => Part::MediaType(id(node_id)?),
997        D::ReplaySetNodeNestedById { node_id, .. } => Part::Nested(id(node_id)?),
998        D::ReplaySetNodeFacetById { node_id, facet, .. }
999        | D::ReplayRemoveNodeFacetById { node_id, facet } => {
1000            Part::Facet(id(node_id)?, facet.clone())
1001        },
1002        D::ReplayUpdateNodeHistoryById { node_id, .. } => Part::History(id(node_id)?),
1003        D::ReplaySetEdgesByIds { from_id, to_id, .. } => Part::Edges(id(from_id)?, id(to_id)?),
1004        D::ReplaySetImportRecords { .. } => Part::ImportRecords,
1005        D::ReplayAddField { field } => Part::Field(id(&field.id)?),
1006        D::ReplayRemoveFieldById { field_id } => Part::Field(id(field_id)?),
1007        D::ReplayAddCoupling { coupling } => Part::Coupling(id(&coupling.id)?),
1008        D::ReplayRetractCouplingById { coupling_id } => Part::Coupling(id(coupling_id)?),
1009        D::ReplaySetResourceRecordById { resource_id, .. } => Part::Resource(id(resource_id)?),
1010        D::ReplaySetResourceEdgesByIds {
1011            from_resource_id,
1012            to_resource_id,
1013            ..
1014        } => Part::ResourceEdges(id(from_resource_id)?, id(to_resource_id)?),
1015        D::ReplaySetShownResourceById { surface_id, .. } => Part::ShownResource(id(surface_id)?),
1016        _ => return None,
1017    })
1018}
1019
1020/// The node a node-scoped part belongs to, if it is one.
1021pub fn part_node(part: &Part) -> Option<Uuid> {
1022    match part {
1023        Part::Node(id)
1024        | Part::Title(id)
1025        | Part::Url(id)
1026        | Part::Tag(id, _)
1027        | Part::Body(id)
1028        | Part::Content(id)
1029        | Part::MediaType(id)
1030        | Part::Nested(id)
1031        | Part::Facet(id, _)
1032        | Part::History(id) => Some(*id),
1033        _ => None,
1034    }
1035}
1036
1037/// What `part` holds in `graph`, as JSON, or `None` when the graph does not
1038/// hold it (a missing node, an absent tag or facet, no relations between two
1039/// nodes). Two graphs agree on a part exactly when these are equal: how a
1040/// merge-in tells a conflict from two sides making the same change.
1041pub fn part_value(graph: &Graph, part: &Part) -> Option<Value> {
1042    let node = |id: &Uuid| node_state(graph, *id);
1043    match part {
1044        Part::Node(id) => node(id).map(|state| {
1045            serde_json::json!({
1046                "title": state.title,
1047                "url": state.url,
1048                "tags": state.tags,
1049                "body": state.body,
1050                "content": state.content.map(|hash| hash.to_vec()),
1051                "media_type": state.media_type,
1052                "nested": state.nested,
1053                "facets": state.facets,
1054                "history": state.history,
1055            })
1056        }),
1057        Part::Title(id) => node(id).map(|state| Value::from(state.title)),
1058        Part::Url(id) => node(id).map(|state| Value::from(state.url)),
1059        Part::Tag(id, tag) => node(id)
1060            .filter(|state| state.tags.contains(tag))
1061            .map(|_| Value::Bool(true)),
1062        Part::Body(id) => node(id).and_then(|state| state.body.map(Value::from)),
1063        Part::Content(id) => node(id)
1064            .and_then(|state| state.content)
1065            .map(|hash| Value::from(hash.to_vec())),
1066        Part::MediaType(id) => node(id).and_then(|state| state.media_type.map(Value::from)),
1067        Part::Nested(id) => node(id).and_then(|state| state.nested.map(Value::from)),
1068        Part::Facet(id, facet) => node(id).and_then(|mut state| state.facets.remove(facet)),
1069        Part::History(id) => node(id).map(|state| serde_json::json!(state.history)),
1070        Part::Edges(from, to) => {
1071            let edges = edges_between(graph, *from, *to);
1072            (!edges.is_empty()).then(|| serde_json::to_value(edges).expect("edges encode"))
1073        },
1074        Part::Field(id) => graph.field(FieldId::from_uuid(*id)).map(|field| {
1075            serde_json::to_value(persisted_field_from_field(field)).expect("field encodes")
1076        }),
1077        Part::Coupling(id) => graph
1078            .couplings()
1079            .find(|coupling| coupling.id == CouplingId::from_uuid(*id))
1080            .map(|coupling| {
1081                serde_json::to_value(persisted_coupling_from_coupling(coupling))
1082                    .expect("coupling encodes")
1083            }),
1084        Part::ImportRecords => {
1085            let records = graph.import_records();
1086            (!records.is_empty()).then(|| serde_json::to_value(records).expect("records encode"))
1087        },
1088        Part::Resource(id) => graph
1089            .resource_record(*id)
1090            .map(|record| serde_json::to_value(record).expect("record encodes")),
1091        Part::ResourceFacet(id, facet) => graph
1092            .resource_record(*id)
1093            .and_then(|record| resource_facets(&record).remove(facet)),
1094        Part::ResourceEdges(from, to) => {
1095            let edges = graph.persisted_resource_edges_between(*from, *to);
1096            (!edges.is_empty()).then(|| serde_json::to_value(edges).expect("edges encode"))
1097        },
1098        Part::ShownResource(id) => {
1099            shown_resource(graph, *id).map(|resource| Value::from(resource.to_string()))
1100        },
1101    }
1102}
1103
1104/// The edits that make node `id` again, whole, as it stands in `graph`: what
1105/// a merge-in uses to bring a node across that its target never held. `None`
1106/// when `graph` has no such node. Relations are not included.
1107pub fn recreate_node_edits(graph: &Graph, id: Uuid) -> Option<Vec<CapturedDelta>> {
1108    let state = node_state(graph, id)?;
1109    let mut made = Revert::default();
1110    made.recreate(id, &state);
1111    Some(made.edits)
1112}
1113
1114/// A node state read back from [`part_value`]'s `Part::Node` form.
1115fn node_state_from(value: &Value) -> Option<NodeState> {
1116    let text = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
1117    let content = match value.get("content") {
1118        None | Some(Value::Null) => None,
1119        Some(bytes) => Some(
1120            serde_json::from_value::<Vec<u8>>(bytes.clone())
1121                .ok()?
1122                .try_into()
1123                .ok()?,
1124        ),
1125    };
1126    Some(NodeState {
1127        title: text("title")?,
1128        url: text("url")?,
1129        tags: serde_json::from_value(value.get("tags")?.clone()).ok()?,
1130        body: text("body"),
1131        content,
1132        media_type: text("media_type"),
1133        nested: text("nested"),
1134        facets: serde_json::from_value(value.get("facets")?.clone()).ok()?,
1135        history: serde_json::from_value(value.get("history")?.clone()).ok()?,
1136    })
1137}
1138
1139/// The edits that make `part` in `graph` read as `value`, given in
1140/// [`part_value`]'s form, `None` for absent: how a merge-in applies a value
1141/// someone supplied by hand. An error names a value that does not fit the
1142/// part.
1143pub fn part_edits(
1144    graph: &Graph,
1145    part: &Part,
1146    value: Option<&Value>,
1147) -> Result<Vec<CapturedDelta>, String> {
1148    use CapturedDelta as D;
1149    let unfit = || format!("{value:?} does not fit {part:?}");
1150    fn decode<T: serde::de::DeserializeOwned>(value: &Value) -> Result<T, String> {
1151        serde_json::from_value(value.clone()).map_err(|error| error.to_string())
1152    }
1153    let text = || value.and_then(Value::as_str).map(str::to_string);
1154    Ok(match part {
1155        Part::Node(id) => match value {
1156            None => graph
1157                .get_node_by_id(*id)
1158                .map(|_| D::ReplayRemoveNodeById {
1159                    node_id: id.to_string(),
1160                })
1161                .into_iter()
1162                .collect(),
1163            Some(value) => {
1164                let wanted = node_state_from(value).ok_or_else(unfit)?;
1165                let mut out = Revert::default();
1166                match node_state(graph, *id) {
1167                    Some(now) => out.node_parts(*id, &wanted, &now, &now, false),
1168                    None => out.recreate(*id, &wanted),
1169                }
1170                out.edits
1171            },
1172        },
1173        Part::Title(id) => vec![D::ReplaySetNodeTitleById {
1174            node_id: id.to_string(),
1175            title: text().ok_or_else(unfit)?,
1176        }],
1177        Part::Url(id) => vec![D::ReplaySetNodeUrlById {
1178            node_id: id.to_string(),
1179            new_url: text().ok_or_else(unfit)?,
1180        }],
1181        Part::Tag(id, tag) => {
1182            let node_id = id.to_string();
1183            let tag = tag.clone();
1184            if value.is_some_and(|value| value != &Value::Bool(false)) {
1185                vec![D::ReplayInsertNodeTagById { node_id, tag }]
1186            } else {
1187                vec![D::ReplayRemoveNodeTagById { node_id, tag }]
1188            }
1189        },
1190        Part::Body(id) => vec![D::ReplaySetNodeBodyById {
1191            node_id: id.to_string(),
1192            body: text(),
1193        }],
1194        Part::Content(id) => vec![D::ReplaySetNodeContentById {
1195            node_id: id.to_string(),
1196            content: match value {
1197                None => None,
1198                Some(bytes) => Some(decode::<Vec<u8>>(bytes)?.try_into().map_err(|_| unfit())?),
1199            },
1200        }],
1201        Part::MediaType(id) => vec![D::ReplaySetNodeMimeHintById {
1202            node_id: id.to_string(),
1203            mime_hint: text(),
1204        }],
1205        Part::Nested(id) => vec![D::ReplaySetNodeNestedById {
1206            node_id: id.to_string(),
1207            nested: text(),
1208        }],
1209        Part::Facet(id, facet) => vec![match value {
1210            Some(value) => D::ReplaySetNodeFacetById {
1211                node_id: id.to_string(),
1212                facet: facet.clone(),
1213                value_json: value.to_string(),
1214            },
1215            None => D::ReplayRemoveNodeFacetById {
1216                node_id: id.to_string(),
1217                facet: facet.clone(),
1218            },
1219        }],
1220        Part::History(id) => {
1221            let (entries, current_index): (Vec<String>, usize) = decode(value.ok_or_else(unfit)?)?;
1222            vec![D::ReplayUpdateNodeHistoryById {
1223                node_id: id.to_string(),
1224                entries,
1225                current_index,
1226            }]
1227        },
1228        Part::Edges(from, to) => vec![D::ReplaySetEdgesByIds {
1229            from_id: from.to_string(),
1230            to_id: to.to_string(),
1231            edges: value.map(decode).transpose()?.unwrap_or_default(),
1232        }],
1233        Part::Field(id) => vec![match value {
1234            Some(value) => D::ReplayAddField {
1235                field: decode(value)?,
1236            },
1237            None => D::ReplayRemoveFieldById {
1238                field_id: id.to_string(),
1239            },
1240        }],
1241        Part::Coupling(id) => vec![match value {
1242            Some(value) => D::ReplayAddCoupling {
1243                coupling: decode(value)?,
1244            },
1245            None => D::ReplayRetractCouplingById {
1246                coupling_id: id.to_string(),
1247            },
1248        }],
1249        Part::ImportRecords => vec![D::ReplaySetImportRecords {
1250            import_records: value.map(decode).transpose()?.unwrap_or_default(),
1251        }],
1252        Part::Resource(id) => vec![D::ReplaySetResourceRecordById {
1253            resource_id: id.to_string(),
1254            record: value.map(decode).transpose()?,
1255        }],
1256        Part::ResourceFacet(id, facet) => {
1257            let mut record = graph.resource_record(*id).ok_or_else(unfit)?;
1258            record.facets.retain(|held| &held.facet != facet);
1259            if let Some(value) = value {
1260                record.facets.push(PersistedResourceFacet {
1261                    facet: facet.clone(),
1262                    value_json: value.to_string(),
1263                });
1264            }
1265            vec![D::ReplaySetResourceRecordById {
1266                resource_id: id.to_string(),
1267                record: Some(record),
1268            }]
1269        },
1270        Part::ResourceEdges(from, to) => vec![D::ReplaySetResourceEdgesByIds {
1271            from_resource_id: from.to_string(),
1272            to_resource_id: to.to_string(),
1273            edges: value.map(decode).transpose()?.unwrap_or_default(),
1274        }],
1275        Part::ShownResource(id) => vec![D::ReplaySetShownResourceById {
1276            surface_id: id.to_string(),
1277            resource_id: text(),
1278        }],
1279    })
1280}
1281
1282#[cfg(test)]
1283pub(super) mod tests {
1284    use std::sync::{Arc, Mutex};
1285
1286    use super::*;
1287    use crate::graph::{
1288        Coupling, CouplingResponse, EdgeAssertion, Field, FieldDefinition, NavigationTrigger,
1289        NodeSelector, ScalarField, SemanticSubKind,
1290    };
1291    use crate::types::{ImportRecord, ImportRecordMembership};
1292
1293    pub(in crate::graph) fn id(n: u128) -> Uuid {
1294        Uuid::from_u128(n)
1295    }
1296
1297    pub(in crate::graph) fn add(n: u128) -> CapturedDelta {
1298        CapturedDelta::ReplayAddNodeWithIdIfMissing {
1299            id: id(n).to_string(),
1300            url: format!("https://{n}.test/"),
1301            position: [0.0, 0.0],
1302        }
1303    }
1304
1305    pub(in crate::graph) fn title(n: u128, title: &str) -> CapturedDelta {
1306        CapturedDelta::ReplaySetNodeTitleById {
1307            node_id: id(n).to_string(),
1308            title: title.to_string(),
1309        }
1310    }
1311
1312    pub(in crate::graph) fn tag(n: u128, tag: &str) -> CapturedDelta {
1313        CapturedDelta::ReplayInsertNodeTagById {
1314            node_id: id(n).to_string(),
1315            tag: tag.to_string(),
1316        }
1317    }
1318
1319    pub(in crate::graph) fn facet(n: u128, facet: &str, value: &str) -> CapturedDelta {
1320        CapturedDelta::ReplaySetNodeFacetById {
1321            node_id: id(n).to_string(),
1322            facet: facet.to_string(),
1323            value_json: value.to_string(),
1324        }
1325    }
1326
1327    pub(in crate::graph) fn relate(from: u128, to: u128) -> CapturedDelta {
1328        CapturedDelta::ReplayAssertRelationByIds {
1329            from_id: id(from).to_string(),
1330            to_id: id(to).to_string(),
1331            assertion: EdgeAssertion::Semantic {
1332                sub_kind: SemanticSubKind::Cites,
1333                label: Some("cites".into()),
1334            },
1335        }
1336    }
1337
1338    fn remove(n: u128) -> CapturedDelta {
1339        CapturedDelta::ReplayRemoveNodeById {
1340            node_id: id(n).to_string(),
1341        }
1342    }
1343
1344    /// Run `edit` with a recorder on, and return what the graph recorded:
1345    /// the change as a journal would hold it.
1346    fn recorded(graph: &mut Graph, edit: impl FnOnce(&mut Graph)) -> Vec<CapturedDelta> {
1347        let seen = Arc::new(Mutex::new(Vec::new()));
1348        let sink = Arc::clone(&seen);
1349        graph.set_recorder(Some(Arc::new(move |delta: &CapturedDelta| {
1350            sink.lock().unwrap().push(delta.clone());
1351        })));
1352        edit(graph);
1353        graph.set_recorder(None);
1354        seen.lock().unwrap().clone()
1355    }
1356
1357    pub(in crate::graph) fn apply_all(graph: &mut Graph, edits: &[CapturedDelta]) {
1358        for edit in edits {
1359            let _ = apply_graph_delta(graph, edit.replay().into_write().expect("replayable"));
1360        }
1361    }
1362
1363    type Nodes = Vec<(Uuid, Option<NodeState>)>;
1364
1365    /// Every node's state and every relation, so two graphs compare whole.
1366    fn fingerprint(graph: &Graph) -> (Nodes, Vec<PersistedEdge>) {
1367        let mut ids: Vec<Uuid> = graph.nodes().map(|(_, node)| node.id).collect();
1368        ids.sort();
1369        let nodes = ids.iter().map(|n| (*n, node_state(graph, *n))).collect();
1370        let mut edges = Vec::new();
1371        for from in &ids {
1372            for to in &ids {
1373                edges.extend(edges_between(graph, *from, *to));
1374            }
1375        }
1376        (nodes, edges)
1377    }
1378
1379    /// The graph before a change, the change as recorded, and the graph after.
1380    fn scene(
1381        base: &[CapturedDelta],
1382        edits: &[CapturedDelta],
1383    ) -> (Graph, Vec<CapturedDelta>, Graph) {
1384        let mut graph = Graph::new();
1385        apply_all(&mut graph, base);
1386        let before = graph.clone();
1387        let made = recorded(&mut graph, |graph| apply_all(graph, edits));
1388        (before, made, graph)
1389    }
1390
1391    #[test]
1392    fn a_retitle_reverts_unless_someone_retitled_since() {
1393        let (before, made, after) = scene(&[add(1), title(1, "A")], &[title(1, "B")]);
1394        let mut live = after.clone();
1395        let revert = revert_change(&made, &before, &after, &live);
1396        assert_eq!(revert.edits, [title(1, "A")]);
1397        assert!(revert.kept.is_empty());
1398        apply_all(&mut live, &revert.edits);
1399        assert_eq!(fingerprint(&live), fingerprint(&before));
1400
1401        let mut retitled = after.clone();
1402        apply_all(&mut retitled, &[title(1, "C")]);
1403        let revert = revert_change(&made, &before, &after, &retitled);
1404        assert!(revert.edits.is_empty());
1405        assert_eq!(revert.kept, [Part::Title(id(1))]);
1406    }
1407
1408    #[test]
1409    fn a_made_node_goes_with_its_relations_unless_linked_since() {
1410        let (before, made, after) = scene(&[add(1)], &[add(2), title(2, "Two"), relate(1, 2)]);
1411        let mut live = after.clone();
1412        let revert = revert_change(&made, &before, &after, &live);
1413        assert_eq!(
1414            revert.edits,
1415            [remove(2)],
1416            "the node takes its relation with it"
1417        );
1418        apply_all(&mut live, &revert.edits);
1419        assert_eq!(fingerprint(&live), fingerprint(&before));
1420
1421        let mut linked = after.clone();
1422        apply_all(&mut linked, &[add(3), relate(3, 2)]);
1423        let revert = revert_change(&made, &before, &after, &linked);
1424        assert!(
1425            revert.kept.contains(&Part::Node(id(2))),
1426            "{:?}",
1427            revert.kept
1428        );
1429        assert!(!revert.edits.contains(&remove(2)));
1430    }
1431
1432    #[test]
1433    fn a_removed_node_comes_back_whole() {
1434        let base = [
1435            add(1),
1436            add(2),
1437            title(2, "Two"),
1438            tag(2, "kept"),
1439            facet(2, "custom.note", r#"{"text":"hello"}"#),
1440            relate(1, 2),
1441        ];
1442        let (before, made, after) = scene(&base, &[remove(2)]);
1443        let mut live = after.clone();
1444        let revert = revert_change(&made, &before, &after, &live);
1445        assert!(revert.kept.is_empty(), "{:?}", revert.kept);
1446        apply_all(&mut live, &revert.edits);
1447        assert_eq!(fingerprint(&live), fingerprint(&before));
1448    }
1449
1450    #[test]
1451    fn a_restored_node_keeps_its_visit_stamp_across_a_clock_tick() {
1452        // Birth stamps visits with the clock. Make the node and the revert in
1453        // one millisecond and apply it in the next: the stamp must still be the
1454        // original, not the moment of the restore.
1455        let tick = |from: u64| while crate::time::unix_epoch_millis() == from {};
1456        let (before, after, revert, at) = (0..100)
1457            .find_map(|_| {
1458                tick(crate::time::unix_epoch_millis());
1459                let at = crate::time::unix_epoch_millis();
1460                let (before, made, after) = scene(&[add(1), add(2), relate(1, 2)], &[remove(2)]);
1461                let revert = revert_change(&made, &before, &after, &after);
1462                (crate::time::unix_epoch_millis() == at).then_some((before, after, revert, at))
1463            })
1464            .expect("a scene and its revert fit in one millisecond");
1465        tick(at);
1466        let mut live = after;
1467        apply_all(&mut live, &revert.edits);
1468        assert_eq!(fingerprint(&live), fingerprint(&before));
1469    }
1470
1471    #[test]
1472    fn recreation_restores_facets_when_the_birth_clock_changes() {
1473        for original_visit in [Some(90), None, Some(100)] {
1474            let mut before = Graph::new();
1475            apply_all(&mut before, &[add(1), add(2)]);
1476            let visit_facet = super::super::node_facets::VISIT_HISTORY;
1477            apply_all(
1478                &mut before,
1479                &[
1480                    facet(
1481                        1,
1482                        visit_facet,
1483                        r#"{"last_visited_ms":42,"last_session_visited":0}"#,
1484                    ),
1485                    facet(2, "custom.note", r#"{"text":"original"}"#),
1486                ],
1487            );
1488            let original = match original_visit {
1489                Some(timestamp) => facet(
1490                    2,
1491                    visit_facet,
1492                    &serde_json::json!({
1493                        "last_visited_ms": timestamp,
1494                        "last_session_visited": 0,
1495                    })
1496                    .to_string(),
1497                ),
1498                None => CapturedDelta::ReplayRemoveNodeFacetById {
1499                    node_id: id(2).to_string(),
1500                    facet: visit_facet.into(),
1501                },
1502            };
1503            apply_all(&mut before, &[original]);
1504            let was = node_state(&before, id(2)).unwrap();
1505            let mut scratch = Graph::new();
1506            apply_all(&mut scratch, &[add(2)]);
1507            let mut born = node_state(&scratch, id(2)).unwrap();
1508            born.facets.insert(
1509                visit_facet.into(),
1510                serde_json::json!({"last_visited_ms":100,"last_session_visited":0}),
1511            );
1512            let mut revert = Revert::default();
1513            revert.recreate_from_birth_state(id(2), &was, &born);
1514
1515            let mut live = before.clone();
1516            apply_all(&mut live, &[remove(2)]);
1517            apply_all(&mut live, &revert.edits[..1]);
1518            // A later replay birth, even when original and planner both read 100.
1519            apply_all(
1520                &mut live,
1521                &[CapturedDelta::ReplayTouchNodeLastVisitedById {
1522                    node_id: id(2).to_string(),
1523                    timestamp_ms: 101,
1524                }],
1525            );
1526            apply_all(&mut live, &revert.edits[1..]);
1527            assert_eq!(
1528                fingerprint(&live),
1529                fingerprint(&before),
1530                "{original_visit:?}"
1531            );
1532            assert_eq!(
1533                node_state(&live, id(1)).unwrap().facets[visit_facet]["last_visited_ms"],
1534                42,
1535                "the untouched node keeps its own timestamp"
1536            );
1537        }
1538    }
1539
1540    #[test]
1541    fn tags_and_facets_revert_part_by_part() {
1542        let (before, made, after) = scene(
1543            &[add(1), facet(1, "custom.a", "1")],
1544            &[
1545                tag(1, "new"),
1546                facet(1, "custom.a", "2"),
1547                facet(1, "custom.b", "true"),
1548            ],
1549        );
1550        let mut live = after.clone();
1551        // Another author changes custom.b afterwards; the rest still reverts.
1552        apply_all(&mut live, &[facet(1, "custom.b", "false")]);
1553        let revert = revert_change(&made, &before, &after, &live);
1554        assert_eq!(revert.kept, [Part::Facet(id(1), "custom.b".into())]);
1555        apply_all(&mut live, &revert.edits);
1556        let state = node_state(&live, id(1)).unwrap();
1557        assert!(!state.tags.contains("new"));
1558        assert_eq!(state.facets.get("custom.a"), Some(&serde_json::json!(1)));
1559        assert_eq!(
1560            state.facets.get("custom.b"),
1561            Some(&serde_json::json!(false))
1562        );
1563        assert!(before.get_node_by_id(id(1)).is_some());
1564    }
1565
1566    #[test]
1567    fn an_undo_reverts_exactly_and_reverting_the_undo_redoes() {
1568        let traverse = CapturedDelta::ReplayAppendTraversalByIds {
1569            from_id: id(1).to_string(),
1570            to_id: id(2).to_string(),
1571            trigger: NavigationTrigger::LinkClick,
1572            timestamp_ms: 1_700_000_000_000,
1573        };
1574        let (before, made, after) = scene(&[add(1), add(2)], &[relate(1, 2), traverse]);
1575        let mut live = after.clone();
1576        let undo = revert_change(&made, &before, &after, &live);
1577        let undone = recorded(&mut live, |graph| apply_all(graph, &undo.edits));
1578        assert_eq!(fingerprint(&live), fingerprint(&before), "undo");
1579
1580        // Redo is the undo reverted, with the undo's own before and after.
1581        let after_undo = live.clone();
1582        let redo = revert_change(&undone, &after, &after_undo, &live);
1583        assert!(redo.kept.is_empty(), "{:?}", redo.kept);
1584        apply_all(&mut live, &redo.edits);
1585        assert_eq!(fingerprint(&live), fingerprint(&after), "redo");
1586    }
1587
1588    #[test]
1589    fn the_field_layer_and_import_records_revert() {
1590        let field_id = FieldId::from_uuid(id(40));
1591        let coupling_id = CouplingId::from_uuid(id(41));
1592        let field = Field::new(field_id, FieldDefinition::Scalar(ScalarField::Const(1.0)));
1593        let coupling = Coupling::new(
1594            coupling_id,
1595            field_id,
1596            NodeSelector::Kind("paper".into()),
1597            CouplingResponse::DampenInside { factor: 0.3 },
1598            1.5,
1599        );
1600        let records = vec![ImportRecord {
1601            record_id: "import-record:one".into(),
1602            source_id: "import:one".into(),
1603            source_label: "One".into(),
1604            imported_at_secs: 1_763_500_800,
1605            memberships: vec![ImportRecordMembership {
1606                node_id: id(1).to_string(),
1607                suppressed: false,
1608            }],
1609        }];
1610        let mut graph = Graph::new();
1611        apply_all(&mut graph, &[add(1)]);
1612        let before = graph.clone();
1613        let made = recorded(&mut graph, |graph| {
1614            let _ = apply_graph_delta(graph, GraphDelta::AddField { field });
1615            let _ = apply_graph_delta(graph, GraphDelta::AddCoupling { coupling });
1616            let _ = apply_graph_delta(
1617                graph,
1618                GraphDelta::SetImportRecords {
1619                    import_records: records,
1620                },
1621            );
1622        });
1623        let after = graph.clone();
1624        let revert = revert_change(&made, &before, &after, &graph);
1625        assert!(revert.kept.is_empty(), "{:?}", revert.kept);
1626        apply_all(&mut graph, &revert.edits);
1627        assert!(
1628            graph.field(field_id).is_none(),
1629            "the added field is gone, not retired"
1630        );
1631        assert_eq!(graph.couplings().count(), 0);
1632        assert!(graph.import_records().is_empty());
1633    }
1634
1635    #[test]
1636    fn touched_parts_reach_the_edits_that_name_them() {
1637        let touched = Touched::of(&[title(1, "A"), relate(2, 3)]);
1638        assert!(touched.reaches(&Part::Title(id(1))));
1639        assert!(touched.reaches(&Part::Edges(id(2), id(3))));
1640        assert!(
1641            touched.reaches(&Part::Node(id(2))),
1642            "a relation touches its ends"
1643        );
1644        assert!(!touched.reaches(&Part::Title(id(4))));
1645        assert!(!touched.reaches(&Part::ImportRecords));
1646    }
1647}
1648
1649#[cfg(test)]
1650mod resource_revert_tests {
1651    use super::*;
1652    use crate::graph::SemanticStatement;
1653
1654    fn record(iri: &str, facets: &[(&str, Value)]) -> CapturedDelta {
1655        CapturedDelta::ReplaySetResourceRecordById {
1656            resource_id: chartulary::resource_id(iri).to_string(),
1657            record: Some(PersistedResourceRecord {
1658                canonical_iri: chartulary::canonical_url(iri),
1659                facets: facets
1660                    .iter()
1661                    .map(|(facet, value)| PersistedResourceFacet {
1662                        facet: (*facet).into(),
1663                        value_json: value.to_string(),
1664                    })
1665                    .collect(),
1666            }),
1667        }
1668    }
1669
1670    fn shown(surface: Uuid, resource: Uuid) -> CapturedDelta {
1671        CapturedDelta::ReplaySetShownResourceById {
1672            surface_id: surface.to_string(),
1673            resource_id: Some(resource.to_string()),
1674        }
1675    }
1676
1677    fn pair(from: Uuid, to: Uuid, handle: &str) -> CapturedDelta {
1678        let mut source = Graph::new();
1679        let a = source.add_node_with_id(from, "https://a.test".into(), Default::default());
1680        let b = source.add_node_with_id(to, "https://b.test".into(), Default::default());
1681        source.assert_surface_persisted_semantic_statement(
1682            a,
1683            b,
1684            SemanticStatement {
1685                statement_id: handle.into(),
1686                predicate: "https://vocab.test/relation".into(),
1687                recognized_sub_kind: None,
1688                label: None,
1689                graph_scope: crate::types::GraphScope::User,
1690                provenance_iri: Some("https://people.test/source".into()),
1691                asserted_at_ms: Some(100),
1692                first_asserted_ms: Some(100),
1693                withdrawn: None,
1694                basis: Default::default(),
1695            },
1696        );
1697        CapturedDelta::ReplaySetResourceEdgesByIds {
1698            from_resource_id: from.to_string(),
1699            to_resource_id: to.to_string(),
1700            edges: source.persisted_edges_between(a, b),
1701        }
1702    }
1703
1704    fn apply(graph: &mut Graph, edits: &[CapturedDelta]) {
1705        super::tests::apply_all(graph, edits);
1706    }
1707
1708    #[test]
1709    fn resource_undo_keeps_later_facet_keys_and_reports_same_key_conflicts() {
1710        let iri = "https://resource.test/a";
1711        let resource = chartulary::resource_id(iri);
1712        let mut before = Graph::new();
1713        apply(
1714            &mut before,
1715            &[record(iri, &[("a", Value::from(1)), ("b", Value::from(1))])],
1716        );
1717        let change = [record(iri, &[("a", Value::from(2)), ("b", Value::from(1))])];
1718        let mut after = before.clone();
1719        apply(&mut after, &change);
1720        let mut live = after.clone();
1721        apply(
1722            &mut live,
1723            &[record(
1724                iri,
1725                &[
1726                    ("a", Value::from(2)),
1727                    ("b", Value::from(3)),
1728                    ("foreign", serde_json::json!({"kept":true})),
1729                ],
1730            )],
1731        );
1732        let undo = revert_change(&change, &before, &after, &live);
1733        assert!(undo.kept.is_empty());
1734        apply(&mut live, &undo.edits);
1735        let facets = resource_facets(&live.resource_record(resource).unwrap());
1736        assert_eq!(facets["a"], Value::from(1));
1737        assert_eq!(facets["b"], Value::from(3));
1738        assert_eq!(facets["foreign"], serde_json::json!({"kept":true}));
1739
1740        let mut conflict = after.clone();
1741        apply(
1742            &mut conflict,
1743            &[record(iri, &[("a", Value::from(4)), ("b", Value::from(3))])],
1744        );
1745        let undo = revert_change(&change, &before, &after, &conflict);
1746        assert_eq!(undo.kept, [Part::ResourceFacet(resource, "a".into())]);
1747        assert!(undo.edits.is_empty());
1748        assert_eq!(
1749            resource_facets(&conflict.resource_record(resource).unwrap())["a"],
1750            Value::from(4)
1751        );
1752    }
1753
1754    fn creation_fixture() -> (Graph, Graph, Vec<CapturedDelta>, Uuid, Uuid, Uuid, Uuid) {
1755        let surface_a = Uuid::from_u128(1);
1756        let surface_b = Uuid::from_u128(2);
1757        let resource_a = chartulary::resource_id("https://resource.test/a");
1758        let resource_b = chartulary::resource_id("https://resource.test/b");
1759        let mut before = Graph::new();
1760        before.add_node_with_id(
1761            surface_a,
1762            "https://surface.test/a".into(),
1763            Default::default(),
1764        );
1765        before.add_node_with_id(
1766            surface_b,
1767            "https://surface.test/b".into(),
1768            Default::default(),
1769        );
1770        apply(
1771            &mut before,
1772            &[
1773                record("https://resource.test/b", &[]),
1774                shown(surface_b, resource_b),
1775            ],
1776        );
1777        let change = vec![
1778            record("https://resource.test/a", &[]),
1779            pair(resource_a, resource_b, "owned-handle"),
1780            shown(surface_a, resource_a),
1781        ];
1782        let mut after = before.clone();
1783        apply(&mut after, &change);
1784        (
1785            before, after, change, surface_a, surface_b, resource_a, resource_b,
1786        )
1787    }
1788
1789    #[test]
1790    fn resource_undo_creation_clears_pairs_and_bindings_before_record() {
1791        let (before, after, change, surface_a, surface_b, resource_a, resource_b) =
1792            creation_fixture();
1793        let undo = revert_change(&change, &before, &after, &after);
1794        assert!(undo.kept.is_empty());
1795        let removal = undo
1796            .edits
1797            .iter()
1798            .position(|edit| {
1799                matches!(
1800                    edit,
1801                    CapturedDelta::ReplaySetResourceRecordById { record: None, .. }
1802                )
1803            })
1804            .unwrap();
1805        let pair = undo.edits.iter().position(|edit| matches!(edit, CapturedDelta::ReplaySetResourceEdgesByIds { edges, .. } if edges.is_empty())).unwrap();
1806        let binding = undo
1807            .edits
1808            .iter()
1809            .position(|edit| {
1810                matches!(
1811                    edit,
1812                    CapturedDelta::ReplaySetShownResourceById {
1813                        resource_id: None,
1814                        ..
1815                    }
1816                )
1817            })
1818            .unwrap();
1819        assert!(pair < removal && binding < removal);
1820        let mut restored = after.clone();
1821        apply(&mut restored, &undo.edits);
1822        assert!(restored.resource_record(resource_a).is_none());
1823        assert!(
1824            restored
1825                .persisted_resource_edges_between(resource_a, resource_b)
1826                .is_empty()
1827        );
1828        assert_eq!(shown_resource(&restored, surface_a), None);
1829        assert_eq!(shown_resource(&restored, surface_b), Some(resource_b));
1830        assert_eq!(
1831            restored.resource_record(resource_b),
1832            before.resource_record(resource_b)
1833        );
1834        assert!(restored.get_node_by_id(surface_a).is_some());
1835    }
1836
1837    #[test]
1838    fn resource_undo_creation_keeps_later_surface_and_pair_references() {
1839        let (before, after, change, surface_a, surface_b, resource_a, resource_b) =
1840            creation_fixture();
1841        for later_surface in [true, false] {
1842            let mut live = after.clone();
1843            let resource_c = chartulary::resource_id("https://resource.test/c");
1844            if later_surface {
1845                apply(&mut live, &[shown(surface_b, resource_a)]);
1846            } else {
1847                apply(
1848                    &mut live,
1849                    &[
1850                        record("https://resource.test/c", &[]),
1851                        pair(resource_a, resource_c, "later-handle"),
1852                    ],
1853                );
1854            }
1855            let undo = revert_change(&change, &before, &after, &live);
1856            assert!(undo.kept.contains(&Part::Resource(resource_a)));
1857            apply(&mut live, &undo.edits);
1858            assert!(live.resource_record(resource_a).is_some());
1859            assert!(
1860                live.persisted_resource_edges_between(resource_a, resource_b)
1861                    .is_empty(),
1862                "owned pair still reverts"
1863            );
1864            assert_eq!(
1865                shown_resource(&live, surface_a),
1866                None,
1867                "owned binding still reverts"
1868            );
1869            assert!(live.resource_record(resource_b).is_some());
1870            if later_surface {
1871                assert_eq!(shown_resource(&live, surface_b), Some(resource_a));
1872            } else {
1873                let surviving = live.persisted_resource_edges_between(resource_a, resource_c);
1874                assert_eq!(
1875                    surviving[0].retained_assertions()[0].statement_id,
1876                    "later-handle"
1877                );
1878                assert_eq!(shown_resource(&live, surface_b), Some(resource_b));
1879            }
1880        }
1881    }
1882
1883    #[test]
1884    fn surface_creation_undo_preserves_later_shown_binding() {
1885        let resource_a = chartulary::resource_id("https://resource.test/a");
1886        let resource_b = chartulary::resource_id("https://resource.test/b");
1887        let surface = Uuid::from_u128(99);
1888        let mut before = Graph::new();
1889        apply(
1890            &mut before,
1891            &[
1892                record("https://resource.test/a", &[]),
1893                record("https://resource.test/b", &[]),
1894            ],
1895        );
1896        for initial_binding in [None, Some(resource_a)] {
1897            let mut change = vec![CapturedDelta::ReplayAddNodeWithIdIfMissing {
1898                id: surface.to_string(),
1899                url: "https://surface.test".into(),
1900                position: [0.0, 0.0],
1901            }];
1902            if let Some(resource) = initial_binding {
1903                change.push(shown(surface, resource));
1904            }
1905            let mut after = before.clone();
1906            apply(&mut after, &change);
1907            let undo = revert_change(&change, &before, &after, &after);
1908            assert!(undo.kept.is_empty());
1909            let mut original = after.clone();
1910            apply(&mut original, &undo.edits);
1911            assert!(original.get_node_by_id(surface).is_none());
1912            assert!(original.surface_ids_showing_resource(resource_a).is_empty());
1913            assert!(original.resource_record(resource_a).is_some());
1914            assert!(original.resource_record(resource_b).is_some());
1915
1916            let mut later = after.clone();
1917            apply(&mut later, &[shown(surface, resource_b)]);
1918            let undo = revert_change(&change, &before, &after, &later);
1919            assert!(undo.kept.contains(&Part::Node(surface)));
1920            if initial_binding.is_some() {
1921                assert!(undo.kept.contains(&Part::ShownResource(surface)));
1922            }
1923            apply(&mut later, &undo.edits);
1924            assert!(later.get_node_by_id(surface).is_some());
1925            assert_eq!(shown_resource(&later, surface), Some(resource_b));
1926            assert_eq!(later.surface_ids_showing_resource(resource_b), [surface]);
1927            assert!(later.resource_record(resource_a).is_some());
1928        }
1929    }
1930
1931    #[test]
1932    fn surface_removal_undo_restores_shown_binding_and_keeps_later_recreation() {
1933        let (_, before, _, surface_a, surface_b, resource_a, resource_b) = creation_fixture();
1934        let change = [CapturedDelta::ReplayRemoveNodeById {
1935            node_id: surface_a.to_string(),
1936        }];
1937        let mut after = before.clone();
1938        apply(&mut after, &change);
1939        assert!(after.get_node_by_id(surface_a).is_none());
1940        assert!(after.surface_ids_showing_resource(resource_a).is_empty());
1941        let undo = revert_change(&change, &before, &after, &after);
1942        assert!(undo.kept.is_empty());
1943        let mut restored = after.clone();
1944        apply(&mut restored, &undo.edits);
1945        assert_eq!(shown_resource(&restored, surface_a), Some(resource_a));
1946        assert_eq!(shown_resource(&restored, surface_b), Some(resource_b));
1947        assert_eq!(
1948            restored.resource_record(resource_a),
1949            before.resource_record(resource_a)
1950        );
1951
1952        let mut later = after.clone();
1953        later.add_node_with_id(surface_a, "https://later.test".into(), Default::default());
1954        apply(&mut later, &[shown(surface_a, resource_b)]);
1955        let undo = revert_change(&change, &before, &after, &later);
1956        assert!(undo.kept.contains(&Part::Node(surface_a)));
1957        assert!(undo.kept.contains(&Part::ShownResource(surface_a)));
1958        apply(&mut later, &undo.edits);
1959        assert_eq!(shown_resource(&later, surface_a), Some(resource_b));
1960        assert_eq!(
1961            later.get_node_by_id(surface_a).unwrap().1.url(),
1962            "https://later.test"
1963        );
1964        assert_eq!(shown_resource(&later, surface_b), Some(resource_b));
1965    }
1966
1967    #[test]
1968    fn resource_touched_parts_keep_equal_surface_ids_separate() {
1969        let from = Uuid::from_u128(1);
1970        let to = Uuid::from_u128(2);
1971        let touched = Touched::of(&[CapturedDelta::ReplaySetResourceEdgesByIds {
1972            from_resource_id: from.to_string(),
1973            to_resource_id: to.to_string(),
1974            edges: Vec::new(),
1975        }]);
1976        assert!(touched.reaches(&Part::ResourceEdges(from, to)));
1977        assert!(touched.reaches(&Part::Resource(from)));
1978        assert!(!touched.reaches(&Part::Edges(from, to)));
1979        assert!(!touched.reaches(&Part::Node(from)));
1980        let touched = Touched::of(&[shown(from, to)]);
1981        assert!(touched.reaches(&Part::ShownResource(from)));
1982        assert!(touched.reaches(&Part::Resource(to)));
1983        assert!(!touched.reaches(&Part::Resource(from)));
1984    }
1985}
1986
1987#[cfg(test)]
1988mod remap_tests {
1989    use serde_json::json;
1990
1991    use super::tests::{facet, id};
1992    use super::*;
1993    use crate::graph::node_facets::{PROVENANCE_DERIVATIONS, SEMANTIC_PROPERTIES};
1994    use crate::graph::{EdgeAssertion, ProvenanceSubKind, SemanticSubKind, SplitOrientation};
1995    use crate::persistence::{
1996        PersistedCoupling, PersistedCouplingResponse, PersistedField, PersistedFieldLifecycle,
1997        PersistedNodeSelector,
1998    };
1999    use crate::types::{ImportRecord, ImportRecordMembership, NodeDerivation, NodeProperty};
2000
2001    fn node(n: u128) -> String {
2002        id(n).to_string()
2003    }
2004
2005    /// Ids 1 to 8, the ones the edits below hold, each mapped to itself plus 100.
2006    fn ids() -> BTreeMap<String, String> {
2007        (1..=8).map(|n| (node(n), node(n + 100))).collect()
2008    }
2009
2010    fn edge(from: u128, to: u128) -> PersistedEdge {
2011        serde_json::from_value(json!({ "from_node_id": node(from), "to_node_id": node(to) }))
2012            .unwrap()
2013    }
2014
2015    fn hint(first: u128, second: u128) -> FrameLayoutHint {
2016        FrameLayoutHint::SplitHalf {
2017            first: node(first),
2018            second: node(second),
2019            orientation: SplitOrientation::Vertical,
2020        }
2021    }
2022
2023    /// Edits whose other strings read as the id of node 1, with the leaves of
2024    /// each that are ids.
2025    fn cases() -> Vec<(CapturedDelta, Vec<&'static str>)> {
2026        use CapturedDelta as D;
2027        let text = node(1);
2028        let record = ImportRecord {
2029            record_id: text.clone(),
2030            source_id: text.clone(),
2031            source_label: text.clone(),
2032            imported_at_secs: 0,
2033            memberships: vec![
2034                ImportRecordMembership {
2035                    node_id: node(1),
2036                    suppressed: false,
2037                },
2038                ImportRecordMembership {
2039                    node_id: node(2),
2040                    suppressed: true,
2041                },
2042            ],
2043        };
2044        let derivation = NodeDerivation {
2045            sub_kind: ProvenanceSubKind::CopiedFrom,
2046            source_node: node(2),
2047            source_graph: Some(text.clone()),
2048        };
2049        let field = PersistedField {
2050            id: node(5),
2051            name: Some(text.clone()),
2052            definition_json: text.clone(),
2053            extent: PersistedFieldExtent::AttachedToNode(node(1)),
2054            lifecycle: PersistedFieldLifecycle::Active,
2055        };
2056        let coupling = PersistedCoupling {
2057            id: node(6),
2058            field_id: node(5),
2059            selector: PersistedNodeSelector::Tagged(text.clone()),
2060            response: PersistedCouplingResponse::AttractToMin,
2061            strength: 1.0,
2062        };
2063        let resource = PersistedResourceRecord {
2064            canonical_iri: text.clone(),
2065            facets: vec![PersistedResourceFacet {
2066                facet: text.clone(),
2067                value_json: format!("\"{text}\""),
2068            }],
2069        };
2070        vec![
2071            (
2072                D::ReplayAddNodeWithIdIfMissing {
2073                    id: node(1),
2074                    url: text.clone(),
2075                    position: [0.0, 0.0],
2076                },
2077                vec!["/id"],
2078            ),
2079            (
2080                D::ReplaySetNodeTitleById {
2081                    node_id: node(1),
2082                    title: text.clone(),
2083                },
2084                vec!["/node_id"],
2085            ),
2086            (
2087                D::ReplaySetNodeUrlById {
2088                    node_id: node(1),
2089                    new_url: text.clone(),
2090                },
2091                vec!["/node_id"],
2092            ),
2093            (
2094                D::ReplayInsertNodeTagById {
2095                    node_id: node(1),
2096                    tag: text.clone(),
2097                },
2098                vec!["/node_id"],
2099            ),
2100            (
2101                D::ReplaySetNodeBodyById {
2102                    node_id: node(1),
2103                    body: Some(text.clone()),
2104                },
2105                vec!["/node_id"],
2106            ),
2107            (
2108                D::ReplaySetNodeNestedById {
2109                    node_id: node(1),
2110                    nested: Some(text.clone()),
2111                },
2112                vec!["/node_id"],
2113            ),
2114            (
2115                D::ReplayUpdateNodeHistoryById {
2116                    node_id: node(1),
2117                    entries: vec![text.clone()],
2118                    current_index: 0,
2119                },
2120                vec!["/node_id"],
2121            ),
2122            (
2123                D::ReplayAppendNodePropertyById {
2124                    node_id: node(1),
2125                    property: NodeProperty::new(text.clone(), text.clone()),
2126                },
2127                vec!["/node_id"],
2128            ),
2129            (
2130                D::ReplayRecordNodeDerivationById {
2131                    node_id: node(1),
2132                    derivation,
2133                },
2134                vec!["/node_id"],
2135            ),
2136            (
2137                D::ReplaySetNodeFacetById {
2138                    node_id: node(1),
2139                    facet: text.clone(),
2140                    value_json: format!("\"{text}\""),
2141                },
2142                vec!["/node_id"],
2143            ),
2144            (
2145                D::ReplayAppendFrameLayoutHintById {
2146                    node_id: node(1),
2147                    hint: hint(2, 3),
2148                },
2149                vec![
2150                    "/node_id",
2151                    "/hint/SplitHalf/first",
2152                    "/hint/SplitHalf/second",
2153                ],
2154            ),
2155            (
2156                D::ReplayBranchHistoryByIds {
2157                    child_id: node(1),
2158                    parent_id: node(2),
2159                },
2160                vec!["/child_id", "/parent_id"],
2161            ),
2162            (
2163                D::ReplayAssertSemanticPredicateByIds {
2164                    from_id: node(1),
2165                    to_id: node(2),
2166                    predicate: text.clone(),
2167                },
2168                vec!["/from_id", "/to_id"],
2169            ),
2170            (
2171                D::ReplayAssertRelationByIds {
2172                    from_id: node(1),
2173                    to_id: node(2),
2174                    assertion: EdgeAssertion::Semantic {
2175                        sub_kind: SemanticSubKind::Cites,
2176                        label: Some(text.clone()),
2177                    },
2178                },
2179                vec!["/from_id", "/to_id"],
2180            ),
2181            (
2182                D::ReplaySetEdgesByIds {
2183                    from_id: node(1),
2184                    to_id: node(2),
2185                    edges: vec![edge(1, 2)],
2186                },
2187                vec![
2188                    "/from_id",
2189                    "/to_id",
2190                    "/edges/0/from_node_id",
2191                    "/edges/0/to_node_id",
2192                ],
2193            ),
2194            (
2195                D::ReplaySetImportRecords {
2196                    import_records: vec![record],
2197                },
2198                vec![
2199                    "/import_records/0/memberships/0/node_id",
2200                    "/import_records/0/memberships/1/node_id",
2201                ],
2202            ),
2203            (
2204                D::ReplayAddField { field },
2205                vec!["/field/id", "/field/extent/AttachedToNode"],
2206            ),
2207            (
2208                D::ReplaySetFieldCouplingStrengthByFieldId {
2209                    field_id: node(5),
2210                    strength: 0.5,
2211                },
2212                vec!["/field_id"],
2213            ),
2214            (
2215                D::ReplayAddCoupling { coupling },
2216                vec!["/coupling/id", "/coupling/field_id"],
2217            ),
2218            (
2219                D::ReplayRetractCouplingById {
2220                    coupling_id: node(6),
2221                },
2222                vec!["/coupling_id"],
2223            ),
2224            (
2225                D::ReplaySetResourceRecordById {
2226                    resource_id: node(7),
2227                    record: Some(resource),
2228                },
2229                vec!["/resource_id"],
2230            ),
2231            (
2232                D::ReplaySetResourceEdgesByIds {
2233                    from_resource_id: node(7),
2234                    to_resource_id: node(8),
2235                    edges: vec![edge(7, 8)],
2236                },
2237                vec![
2238                    "/from_resource_id",
2239                    "/to_resource_id",
2240                    "/edges/0/from_node_id",
2241                    "/edges/0/to_node_id",
2242                ],
2243            ),
2244            (
2245                D::ReplaySetShownResourceById {
2246                    surface_id: node(1),
2247                    resource_id: Some(node(7)),
2248                },
2249                vec!["/surface_id", "/resource_id"],
2250            ),
2251        ]
2252    }
2253
2254    /// The variant's fields, without its name.
2255    fn body(edit: &CapturedDelta) -> Value {
2256        let value = serde_json::to_value(edit).unwrap();
2257        value.as_object().unwrap().values().next().unwrap().clone()
2258    }
2259
2260    /// The paths of the leaves that differ.
2261    fn changed(before: &Value, after: &Value, at: String, out: &mut Vec<String>) {
2262        match (before, after) {
2263            (Value::Object(a), Value::Object(b)) if a.len() == b.len() => {
2264                for (key, value) in a {
2265                    changed(value, &b[key], format!("{at}/{key}"), out);
2266                }
2267            },
2268            (Value::Array(a), Value::Array(b)) if a.len() == b.len() => {
2269                for (n, (x, y)) in a.iter().zip(b).enumerate() {
2270                    changed(x, y, format!("{at}/{n}"), out);
2271                }
2272            },
2273            _ if before != after => out.push(at),
2274            _ => {},
2275        }
2276    }
2277
2278    /// What `Touched` reports, with each id it names taken through `ids`.
2279    fn renamed(touched: &Touched, ids: &BTreeMap<String, String>) -> Touched {
2280        let swap = |id: &Uuid| {
2281            ids.get(&id.to_string())
2282                .map_or(*id, |new| Uuid::parse_str(new).unwrap())
2283        };
2284        let set = |set: &BTreeSet<Uuid>| set.iter().map(swap).collect::<BTreeSet<_>>();
2285        let pairs = |pairs: &BTreeSet<(Uuid, Uuid)>| {
2286            pairs
2287                .iter()
2288                .map(|(a, b)| (swap(a), swap(b)))
2289                .collect::<BTreeSet<_>>()
2290        };
2291        Touched {
2292            nodes: set(&touched.nodes),
2293            edges: pairs(&touched.edges),
2294            fields: set(&touched.fields),
2295            couplings: set(&touched.couplings),
2296            coupled_fields: set(&touched.coupled_fields),
2297            import_records: touched.import_records,
2298            resources: set(&touched.resources),
2299            resource_edges: pairs(&touched.resource_edges),
2300            shown_surfaces: set(&touched.shown_surfaces),
2301        }
2302    }
2303
2304    #[test]
2305    fn remap_ids_rewrites_what_touched_names_and_nothing_else() {
2306        let ids = ids();
2307        for (edit, expected) in cases() {
2308            let remapped = edit.remap_ids(&ids);
2309            let mut moved = Vec::new();
2310            changed(&body(&edit), &body(&remapped), String::new(), &mut moved);
2311            moved.sort();
2312            let mut expected = expected;
2313            expected.sort();
2314            assert_eq!(moved, expected, "{edit:?}");
2315            assert_eq!(
2316                Touched::of([&remapped]),
2317                renamed(&Touched::of([&edit]), &ids),
2318                "{edit:?}"
2319            );
2320        }
2321    }
2322
2323    #[test]
2324    fn remap_ids_leaves_an_id_the_map_does_not_name() {
2325        let ids = BTreeMap::from([(node(1), node(101))]);
2326        let edit = CapturedDelta::ReplayBranchHistoryByIds {
2327            child_id: node(1),
2328            parent_id: node(2),
2329        };
2330        assert_eq!(
2331            edit.remap_ids(&ids),
2332            CapturedDelta::ReplayBranchHistoryByIds {
2333                child_id: node(101),
2334                parent_id: node(2),
2335            }
2336        );
2337    }
2338
2339    fn text_of(value: &impl serde::Serialize) -> String {
2340        serde_json::to_string(value).unwrap()
2341    }
2342
2343    #[test]
2344    fn a_facet_value_is_remapped_only_through_the_ids_it_declares() {
2345        let ids = ids();
2346        let remapped = |name: &str, value: &str| match facet(1, name, value).remap_ids(&ids) {
2347            CapturedDelta::ReplaySetNodeFacetById {
2348                node_id,
2349                value_json,
2350                ..
2351            } => {
2352                assert_eq!(node_id, node(101), "the node key moves with the edit");
2353                value_json
2354            },
2355            other => panic!("{other:?}"),
2356        };
2357        // Frame-layout members are node ids.
2358        assert_eq!(
2359            remapped(ARRANGEMENT_FRAME_LAYOUT, &text_of(&[hint(2, 3)])),
2360            text_of(&[hint(102, 103)])
2361        );
2362        // Everything else the kernel defines, and anything it does not, carries as written.
2363        let derivation = vec![NodeDerivation {
2364            sub_kind: ProvenanceSubKind::CopiedFrom,
2365            source_node: node(2),
2366            source_graph: Some(node(3)),
2367        }];
2368        let property = vec![NodeProperty::new(node(1), node(2))];
2369        for (name, value) in [
2370            (PROVENANCE_DERIVATIONS, text_of(&derivation)),
2371            (SEMANTIC_PROPERTIES, text_of(&property)),
2372            ("extension.note", json!({ "about": node(2) }).to_string()),
2373            (ARRANGEMENT_FRAME_LAYOUT, "not a list of hints".to_string()),
2374            (
2375                ARRANGEMENT_FRAME_LAYOUT,
2376                json!([{ "Unknown": node(2) }]).to_string(),
2377            ),
2378        ] {
2379            assert_eq!(remapped(name, &value), value, "{name}");
2380        }
2381    }
2382}