mere-kernel 0.0.3

Portable identity, authority, and mutation kernel for the Mere browser. Renamed from graphshell-core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
// Copyright 2026 Mark Alan Boykin
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// SPDX-License-Identifier: MPL-2.0

//! Resource identity beneath browsing surfaces.

use super::{Graph, NodeKey};
use crate::persistence::{PersistedEdge, PersistedResourceFacet, PersistedResourceRecord};
use chartulary::{Address, Addressed, Identified};
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
use uuid::Uuid;

pub use super::resource_pair_bounds::ResourceEdgesBoundError;

/// A tagging assertion points from the tagged resource to its concept resource.
pub const TAGGED_WITH_IRI: &str = "https://mere.computer/ns/rel#taggedWith";

/// One resource identified by a canonical IRI.
///
/// Identity and address are immutable together. Content records will be
/// attached through the kernel's recorded write path.
#[derive(Debug, Clone, PartialEq)]
pub struct ResourceNode {
    container: chartulary::Container<Uuid>,
    pub(super) nested_selection: Option<super::FrozenSelection>,
    pub(super) nested_link: Option<super::FrozenLink>,
}

impl ResourceNode {
    /// Identify a resource using the common canonicalizer and UUID namespace.
    pub fn new(iri: &str) -> Self {
        let canonical = chartulary::canonical_url(iri);
        Self::from_canonical_iri(&canonical)
    }

    /// Identify a vocabulary term by its exact IRI, including fragment and case.
    /// Page resources use [`Self::new`] instead.
    pub fn for_term(iri: &str) -> Self {
        Self::from_canonical_iri(iri)
    }

    pub(crate) fn from_canonical_iri(canonical: &str) -> Self {
        Self {
            nested_selection: None,
            nested_link: None,
            container: chartulary::Container::with_identity(
                chartulary::resource_id_from_canonical_iri(canonical),
            )
            .with_address_record(Address::new(canonical)),
        }
    }

    /// Immutable nested selection borne by this Resource, when frozen.
    pub fn nested_selection(&self) -> Option<&super::FrozenSelection> {
        self.nested_selection.as_ref()
    }

    /// Immutable link reading borne by this Resource, when frozen.
    pub fn nested_link(&self) -> Option<&super::FrozenLink> {
        self.nested_link.as_ref()
    }

    /// The stable identity, shared by every surface showing this resource.
    pub fn id(&self) -> Uuid {
        self.container.id
    }

    /// The canonical IRI from which the stable identity was derived.
    pub fn canonical_iri(&self) -> &str {
        self.container.addresses[0].as_str()
    }
}

impl Graph {
    /// Read a resource by its stable identity.
    pub fn resource(&self, id: Uuid) -> Option<&ResourceNode> {
        self.resources.get(&id)
    }

    /// The resources currently held in this graph.
    pub fn resource_nodes(&self) -> impl Iterator<Item = &ResourceNode> {
        self.resources.nodes().map(|(_, resource)| resource)
    }

    /// Resource edges with their resource endpoints. Surface indices never cross this seam.
    pub fn resource_edges(
        &self,
    ) -> impl Iterator<Item = (&ResourceNode, &ResourceNode, &super::EdgePayload)> {
        self.resources.inner().edge_references().map(|edge| {
            (
                self.resources
                    .node(edge.source())
                    .expect("resource endpoint exists"),
                self.resources
                    .node(edge.target())
                    .expect("resource endpoint exists"),
                edge.weight(),
            )
        })
    }

    /// Resource metadata, separate from surface metadata.
    pub fn resource_facets(&self) -> &chartulary::FacetStore<Uuid> {
        &self.resource_facets
    }

    /// The resource explicitly shown by a surface, when recorded.
    pub fn shown_resource_id(&self, surface: NodeKey) -> Option<Uuid> {
        self.shown_resources
            .get(&self.get_node(surface)?.id)
            .copied()
    }

    /// Surface identities showing a resource, in stable order.
    pub fn surface_ids_showing_resource(&self, resource_id: Uuid) -> Vec<Uuid> {
        self.shown_resources
            .iter()
            .filter_map(|(surface, resource)| (*resource == resource_id).then_some(*surface))
            .collect()
    }

    pub fn resource_record(&self, id: Uuid) -> Option<PersistedResourceRecord> {
        let resource = self.resource(id)?;
        let facets = self
            .resource_facets
            .facets_of(&id)
            .into_iter()
            .flat_map(|facets| facets.iter())
            .map(|(facet, value)| PersistedResourceFacet {
                facet: facet.as_str().to_string(),
                value_json: serde_json::to_string(value).expect("JSON value serializes"),
            })
            .collect();
        Some(PersistedResourceRecord {
            canonical_iri: resource.canonical_iri().to_string(),
            facets,
        })
    }

    pub(crate) fn set_resource_record(
        &mut self,
        id: Uuid,
        record: Option<PersistedResourceRecord>,
    ) -> bool {
        let Some(record) = record else {
            let Some(key) = self.resources.key_of(&id) else {
                return false;
            };
            if self
                .shown_resources
                .values()
                .any(|resource| *resource == id)
                || self
                    .resources
                    .inner()
                    .edge_references()
                    .any(|edge| edge.source() == key || edge.target() == key)
            {
                return false;
            }
            self.resources.remove(key);
            self.resource_facets.remove_node(&id);
            self.bump_revision();
            return true;
        };
        let mut resource = ResourceNode::from_canonical_iri(&record.canonical_iri);
        let Ok(selection) = super::frozen_selection::selection_from_record(&record) else {
            return false;
        };
        let Ok(link) = super::frozen_link::validate_frozen_link_record(&record) else {
            return false;
        };
        if let Some(existing) = self
            .resource(id)
            .and_then(|resource| resource.nested_selection())
            && selection.as_ref() != Some(existing)
        {
            return false;
        }
        if self
            .resource(id)
            .is_some_and(|resource| resource.nested_selection().is_some())
        {
            let stored = self.resource_facets.get(
                &id,
                &chartulary::FacetId::new(super::frozen_selection::FROZEN_SELECTION),
            );
            let incoming = record
                .facets
                .iter()
                .find(|facet| facet.facet == super::frozen_selection::FROZEN_SELECTION)
                .and_then(|facet| {
                    serde_json::from_str::<serde_json::Value>(&facet.value_json).ok()
                });
            if stored != incoming.as_ref() {
                return false;
            }
        }
        if let Some(existing) = self
            .resource(id)
            .and_then(|resource| resource.nested_link())
            && link.as_ref() != Some(existing)
        {
            return false;
        }
        if self
            .resource(id)
            .is_some_and(|resource| resource.nested_link().is_some())
        {
            let stored = self.resource_facets.get(
                &id,
                &chartulary::FacetId::new(super::frozen_link::FROZEN_LINK),
            );
            let incoming = record
                .facets
                .iter()
                .find(|facet| facet.facet == super::frozen_link::FROZEN_LINK)
                .and_then(|facet| {
                    serde_json::from_str::<serde_json::Value>(&facet.value_json).ok()
                });
            if stored != incoming.as_ref() {
                return false;
            }
        }
        resource.nested_selection = selection;
        resource.nested_link = link;
        if resource.id() != id {
            return false;
        }
        if super::predicate_declarations::predicate_declarations_from_record(&record).is_err() {
            return false;
        }
        if super::resource_content::validate_content_record(&record).is_err() {
            return false;
        }
        let mut facets = std::collections::BTreeMap::new();
        for facet in record.facets {
            let Ok(value) = serde_json::from_str::<serde_json::Value>(&facet.value_json) else {
                return false;
            };
            if facets
                .insert(chartulary::FacetId::new(facet.facet), value)
                .is_some()
            {
                return false;
            }
        }
        if self
            .resource(id)
            .is_some_and(|existing| existing == &resource)
            && self
                .resource_facets
                .facets_of(&id)
                .map(|values| {
                    values
                        .iter()
                        .map(|(key, value)| (key.clone(), value.clone()))
                        .collect::<std::collections::BTreeMap<_, _>>()
                })
                .unwrap_or_default()
                == facets
        {
            return false;
        }
        self.resources.insert(resource);
        self.resource_facets.remove_node(&id);
        for (facet, value) in facets {
            self.resource_facets
                .set(id, facet, value, &chartulary::AcceptAll)
                .expect("permissive facet validator");
        }
        self.bump_revision();
        true
    }

    /// Runtime receipt for completed new shown-Resource associations.
    /// This advances on admission, including navigation to an already held Resource.
    pub fn appearance_admission_revision(&self) -> u64 {
        self.appearance_admission_revision
    }

    pub(crate) fn set_shown_resource(&mut self, surface: Uuid, resource: Option<Uuid>) -> bool {
        if self.inner.key_of(&surface).is_none()
            || resource.is_some_and(|id| self.resource(id).is_none())
        {
            return false;
        }
        if self.shown_resources.get(&surface).copied() == resource {
            return false;
        }
        if let Some(resource) = resource {
            self.shown_resources.insert(surface, resource);
            self.appearance_admission_revision = self.appearance_admission_revision.wrapping_add(1);
        } else {
            self.shown_resources.remove(&surface);
        }
        self.bump_revision();
        true
    }

    pub(crate) fn persisted_resource_edges_between(
        &self,
        from: Uuid,
        to: Uuid,
    ) -> Vec<PersistedEdge> {
        let (Some(source), Some(target)) =
            (self.resources.key_of(&from), self.resources.key_of(&to))
        else {
            return Vec::new();
        };
        self.resources
            .inner()
            .edges_connecting(source, target)
            .map(|edge| super::snapshot::persisted_edge_for_ids(from, to, edge.weight()))
            .collect()
    }

    pub(crate) fn set_resource_edges_between(
        &mut self,
        from: Uuid,
        to: Uuid,
        edges: &[PersistedEdge],
    ) -> bool {
        let (Some(source), Some(target)) =
            (self.resources.key_of(&from), self.resources.key_of(&to))
        else {
            return false;
        };
        if !super::edge_admission::resource_rows_wellformed(from, to, edges) {
            return false;
        }
        let mut statements = std::collections::BTreeMap::new();
        for statement in edges.iter().flat_map(|edge| edge.retained_assertions()) {
            if let Some(previous) = statements.insert(&statement.statement_id, statement)
                && previous != statement
            {
                return false;
            }
        }
        for edge in self.resources.inner().edge_references() {
            if edge.source() == source && edge.target() == target {
                continue;
            }
            if edge
                .weight()
                .assertions()
                .iter()
                .any(|statement| statements.contains_key(&statement.statement_id))
            {
                return false;
            }
        }
        if self.inner.inner().edge_weights().any(|edge| {
            edge.assertions()
                .iter()
                .any(|statement| statements.contains_key(&statement.statement_id))
        }) {
            return false;
        }
        let payloads: Vec<_> = edges
            .iter()
            .enumerate()
            .map(|(ordinal, edge)| {
                super::snapshot::payload_from_persisted_at(
                    edge,
                    super::GraphStratum::Resource,
                    ordinal,
                )
            })
            .collect();
        let current: Vec<_> = self
            .resources
            .inner()
            .edges_connecting(source, target)
            .map(|edge| edge.weight())
            .collect();
        if current.len() == payloads.len()
            && current.iter().zip(&payloads).all(|(old, new)| *old == new)
        {
            return false;
        }
        let old: Vec<_> = self
            .resources
            .inner()
            .edges_connecting(source, target)
            .map(|edge| edge.id())
            .collect();
        for edge in old {
            self.resources.disconnect(edge);
        }
        for payload in payloads.into_iter().rev() {
            self.resources.connect(source, target, payload);
        }
        self.bump_revision();
        true
    }
}

impl Identified for ResourceNode {
    type Id = Uuid;

    fn id(&self) -> &Uuid {
        &self.container.id
    }
}

impl Addressed for ResourceNode {
    fn addresses(&self) -> Vec<Address> {
        self.container.addresses.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{Graph, SurfaceNode};

    fn record(iri: &str, value_json: &str) -> PersistedResourceRecord {
        PersistedResourceRecord {
            canonical_iri: chartulary::canonical_url(iri),
            facets: vec![PersistedResourceFacet {
                facet: "test.content".into(),
                value_json: value_json.into(),
            }],
        }
    }

    #[test]
    fn resource_record_validation_is_atomic_and_replacement_clears_old_facets() {
        let mut graph = Graph::new();
        let iri = "https://example.com/resource";
        let id = chartulary::resource_id(iri);
        let original = record(iri, "{\"title\":\"original\"}");
        assert!(graph.set_resource_record(id, Some(original.clone())));
        assert_eq!(graph.resource_record(id), Some(original.clone()));
        assert!(!graph.set_resource_record(id, Some(original.clone())));
        assert!(!graph.set_resource_record(Uuid::nil(), Some(original.clone())));
        assert!(!graph.set_resource_record(id, Some(record(iri, "invalid JSON"))));
        let mut duplicate = original.clone();
        duplicate.facets.push(duplicate.facets[0].clone());
        assert!(!graph.set_resource_record(id, Some(duplicate)));
        assert_eq!(graph.resource_record(id), Some(original));
        assert!(graph.set_resource_record(
            id,
            Some(PersistedResourceRecord {
                canonical_iri: iri.into(),
                facets: vec![]
            })
        ));
        assert!(graph.resource_record(id).unwrap().facets.is_empty());
        assert!(graph.set_resource_record(id, None));
        assert!(graph.resource(id).is_none());
        assert!(graph.resource_facets.facets_of(&id).is_none());
    }

    #[test]
    fn shown_resource_is_explicit_and_references_guard_inverse_creation() {
        let mut graph = Graph::new();
        let first = graph.add_node(
            "https://example.com/page".into(),
            euclid::default::Point2D::new(0.0, 0.0),
        );
        let second = graph.add_node(
            "https://example.com/page#part".into(),
            euclid::default::Point2D::new(1.0, 0.0),
        );
        let surface = graph.get_node(first).unwrap().id;
        let alias = graph.get_node(second).unwrap().id;
        let id = chartulary::resource_id("https://example.com/page");
        assert!(graph.shown_resource_id(first).is_none());
        assert!(!graph.set_shown_resource(surface, Some(id)));
        assert!(graph.set_resource_record(id, Some(record("https://example.com/page", "null"))));
        assert!(graph.set_shown_resource(surface, Some(id)));
        assert!(graph.set_shown_resource(alias, Some(id)));
        let mut expected = vec![surface, alias];
        expected.sort();
        assert_eq!(graph.surface_ids_showing_resource(id), expected);
        assert!(!graph.set_shown_resource(surface, Some(id)));
        assert!(!graph.set_resource_record(id, None));
        assert!(graph.remove_node(first));
        assert_eq!(graph.surface_ids_showing_resource(id), vec![alias]);
        assert!(graph.set_shown_resource(alias, None));
        assert!(graph.set_resource_record(id, None));
    }

    #[test]
    fn resource_pair_rejects_conflicting_handles_before_replacing_truth() {
        use crate::graph::{EdgePayload, SemanticStatement, SemanticSubKind};
        let mut graph = Graph::new();
        let ids: Vec<_> = ["https://a.test/", "https://b.test/", "https://c.test/"]
            .into_iter()
            .map(|iri| {
                let id = chartulary::resource_id(iri);
                assert!(graph.set_resource_record(id, Some(record(iri, "null"))));
                id
            })
            .collect();
        let mut payload = EdgePayload::new();
        payload.push_persisted_semantic_statement(SemanticStatement {
            statement_id: "stable-handle".into(),
            predicate: crate::graph::predicate_iri(SemanticSubKind::Cites).into(),
            recognized_sub_kind: Some(SemanticSubKind::Cites),
            label: Some("original".into()),
            graph_scope: crate::types::GraphScope::Default,
            provenance_iri: Some("https://alice.test/".into()),
            asserted_at_ms: Some(17),
            first_asserted_ms: Some(17),
            withdrawn: None,
            basis: Default::default(),
        });
        let original = super::super::snapshot::persisted_edge_for_ids(ids[0], ids[1], &payload);
        let mut aggregate_only = original.clone();
        aggregate_only.assertions = None;
        aggregate_only.semantic = Some(Default::default());
        aggregate_only.semantic.as_mut().unwrap().sub_kinds =
            vec![crate::persistence::PersistedSemanticSubKind::Cites];
        assert!(!graph.set_resource_edges_between(ids[0], ids[1], &[aggregate_only.clone()]));
        assert!(!graph.set_resource_edges_between(ids[0], ids[1], &[aggregate_only]));
        assert!(
            graph
                .persisted_resource_edges_between(ids[0], ids[1])
                .is_empty()
        );
        assert!(graph.set_resource_edges_between(ids[0], ids[1], &[original.clone()]));
        assert!(!graph.set_resource_edges_between(ids[0], ids[1], &[original.clone()]));
        let mut conflicting = original.clone();
        conflicting.retained_assertions_mut()[0].label = Some("conflict".into());
        assert!(!graph.set_resource_edges_between(
            ids[0],
            ids[1],
            &[original.clone(), conflicting]
        ));
        assert_eq!(
            graph.persisted_resource_edges_between(ids[0], ids[1]),
            vec![original.clone()]
        );
        let mut other_pair = original.clone();
        other_pair.to_node_id = ids[2].to_string();
        assert!(!graph.set_resource_edges_between(ids[0], ids[2], &[other_pair.clone()]));
        assert!(
            graph
                .persisted_resource_edges_between(ids[0], ids[2])
                .is_empty()
        );
        other_pair.retained_assertions_mut()[0].statement_id = "other-handle".into();
        assert!(graph.set_resource_edges_between(ids[0], ids[2], &[other_pair.clone()]));
        assert_eq!(
            graph.persisted_resource_edges_between(ids[0], ids[2]),
            vec![other_pair.clone()]
        );
        let first = graph.add_node(
            "https://surface.test/a".into(),
            euclid::default::Point2D::new(0.0, 0.0),
        );
        let second = graph.add_node(
            "https://surface.test/b".into(),
            euclid::default::Point2D::new(1.0, 0.0),
        );
        let mut collision = other_pair.clone();
        collision.retained_assertions_mut()[0].statement_id = "surface-handle".into();
        graph.inner.connect(
            first,
            second,
            super::super::snapshot::payload_from_persisted(&collision),
        );
        assert!(!graph.set_resource_edges_between(ids[0], ids[2], &[collision.clone()]));
        assert_eq!(
            graph.persisted_resource_edges_between(ids[0], ids[2]),
            vec![other_pair]
        );
        collision.retained_assertions_mut()[0].statement_id = "fresh-resource-handle".into();
        assert!(graph.set_resource_edges_between(ids[0], ids[2], &[collision.clone()]));
        assert_eq!(
            graph.persisted_resource_edges_between(ids[0], ids[2]),
            vec![collision]
        );
        assert!(!graph.set_resource_record(ids[0], None));
        assert!(graph.set_resource_edges_between(ids[0], ids[1], &[]));
        assert!(graph.set_resource_edges_between(ids[0], ids[2], &[]));
        assert!(graph.set_resource_record(ids[0], None));
    }

    #[test]
    fn resource_identity_is_common_and_canonical_without_renumbering_surfaces() {
        let iri = "https://example.com/page?id=7";
        let alias = "https://EXAMPLE.COM:443/page?utm_source=news&id=7#part";
        let resource = ResourceNode::new(alias);
        assert_eq!(resource.canonical_iri(), iri);
        assert_eq!(resource.id(), chartulary::resource_id(iri));
        assert_eq!(*Identified::id(&resource), resource.id());
        assert_eq!(resource.primary_address(), Some(Address::new(iri)));
        assert_eq!(resource, ResourceNode::new(iri));
        assert_ne!(
            resource.id(),
            ResourceNode::new("https://example.com/page?id=8").id()
        );
        assert_ne!(resource.id(), Graph::node_namespace_id(iri));

        let first = SurfaceNode::test_stub(iri);
        let second = SurfaceNode::test_stub(alias);
        assert_ne!(first.id, second.id);
        assert_eq!(
            ResourceNode::new(first.url()),
            ResourceNode::new(second.url())
        );
    }

    #[test]
    fn vocabulary_term_identity_preserves_fragments_query_and_case() {
        let cat = ResourceNode::for_term("https://vocab.test/concepts#Cat");
        for iri in [
            "https://vocab.test/concepts#Dog",
            "https://vocab.test/concepts#cat",
            "https://VOCAB.test/concepts#Cat",
            "https://vocab.test/concepts?edition=1#Cat",
        ] {
            let term = ResourceNode::for_term(iri);
            assert_eq!(term.canonical_iri(), iri);
            assert_eq!(term.id(), chartulary::resource_id_from_canonical_iri(iri));
            assert_ne!(term.id(), cat.id());
        }
        assert_eq!(cat, ResourceNode::for_term(cat.canonical_iri()));
        assert_eq!(
            ResourceNode::new("https://vocab.test/concepts#Cat"),
            ResourceNode::new("https://VOCAB.test:443/concepts#Dog")
        );
        assert_ne!(cat.id(), ResourceNode::new(cat.canonical_iri()).id());
    }

    #[test]
    fn exact_term_records_and_resource_edge_endpoints_survive_checked_load() {
        use crate::graph::{EdgePayload, SemanticStatement, SemanticSubKind};
        let mut graph = Graph::new();
        let terms = [
            ResourceNode::for_term("https://vocab.test/concepts#Cat"),
            ResourceNode::for_term("https://vocab.test/concepts#Dog"),
        ];
        for term in &terms {
            assert!(graph.set_resource_record(
                term.id(),
                Some(PersistedResourceRecord {
                    canonical_iri: term.canonical_iri().into(),
                    facets: vec![],
                })
            ));
        }
        let mut payload = EdgePayload::new();
        payload.push_persisted_semantic_statement(SemanticStatement {
            statement_id: "exact-vocabulary-assertion".into(),
            predicate: crate::graph::predicate_iri(SemanticSubKind::SameEntityAs).into(),
            recognized_sub_kind: Some(SemanticSubKind::SameEntityAs),
            label: None,
            graph_scope: crate::types::GraphScope::Default,
            provenance_iri: Some("https://author.test/".into()),
            asserted_at_ms: Some(19),
            first_asserted_ms: Some(19),
            withdrawn: None,
            basis: Default::default(),
        });
        let edge =
            super::super::snapshot::persisted_edge_for_ids(terms[0].id(), terms[1].id(), &payload);
        assert!(graph.set_resource_edges_between(terms[0].id(), terms[1].id(), &[edge]));
        let restored = Graph::try_from_snapshot(&graph.to_snapshot()).unwrap();
        for term in &terms {
            assert_eq!(restored.resource(term.id()), Some(term));
        }
        let edges: Vec<_> = restored.resource_edges().collect();
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].0, &terms[0]);
        assert_eq!(edges[0].1, &terms[1]);
        assert_eq!(edges[0].2, &payload);
        assert_eq!(
            restored.edge_count(),
            0,
            "resource edges do not create surface edges"
        );
    }

    #[test]
    fn chartulary_indexes_resources_by_the_shared_identity() {
        let mut graph = chartulary::Graph::<ResourceNode, ()>::new();
        let first = graph.insert(ResourceNode::new("https://example.com/page"));
        let alias = graph.insert(ResourceNode::new("https://EXAMPLE.COM/page#part"));
        assert_eq!(first, alias);
        assert_eq!(graph.node_count(), 1);
        let other = graph.insert(ResourceNode::new("https://example.com/other"));
        assert_ne!(first, other);
        assert_eq!(graph.node_count(), 2);
        let clone = graph.clone();
        assert_eq!(
            clone.get(&chartulary::resource_id("https://example.com/page")),
            graph.node(first)
        );
        assert_eq!(
            clone.get(&chartulary::resource_id("https://example.com/other")),
            graph.node(other)
        );
    }
}