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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
// 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

//! Graph data structures for the spatial browser.
//!
//! Core structures:
//! - `Graph`: Main graph container backed by petgraph::StableGraph
//! - `Node`: Webpage node with a transient projected position and metadata
//! - `EdgePayload`: Edge semantics and traversal events between nodes
//!
//! This module is WASM-clean: it must compile to `wasm32-unknown-unknown`.

use euclid::default::Point2D;
// `MemoryEntryPrivacy` / `OwnerScopedMemory` / `GraphMemorySnapshot` /
// `MemoryTransitionKind` were used by the node-history types that
// moved to `history.rs` (2026-05-11 decomposition pass); `Graph` itself
// doesn't reach into node-lineage directly.
use petgraph::algo::{astar, dijkstra, has_path_connecting, kosaraju_scc};
#[cfg(test)]
use petgraph::stable_graph::NodeIndex;
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
use rkyv::{Archive, Archived, Deserialize, Place, Resolver, Serialize, rancor::Fallible};
use std::collections::{BTreeMap, HashMap, HashSet};
use uuid::Uuid;

pub use chartulary::stemma::TransitionKind as NodeHistoryTransitionKind;
/// The stable address of a node's out-of-line representation.
pub use muniment::Hash as ContentHash;

use crate::address::{Address, AddressKind, address_from_url, cached_host_from_url, detect_mime};
use crate::persistence::{
    GraphSnapshot, PersistedAddress, PersistedArrangementEdgeData, PersistedArrangementSubKind,
    PersistedContainmentEdgeData, PersistedContainmentSubKind, PersistedEdge, PersistedEdgeFamily,
    PersistedImportedEdgeData, PersistedImportedSubKind, PersistedNavigationTrigger, PersistedNode,
    PersistedNodeSessionState, PersistedProvenanceEdgeData, PersistedProvenanceSubKind,
    PersistedSemanticEdgeData, PersistedSemanticSubKind, PersistedTraversalEdgeData,
    PersistedTraversalMetrics, PersistedTraversalRecord,
};
#[allow(unused_imports)] // Some used only in #[cfg(test)]
use crate::types::{
    ClassificationProvenance, ClassificationScheme, ClassificationStatus, DominantEdge,
    FrameLayoutHint, FrameLayoutNodeId, GraphScope, ImportRecord, ImportRecordMembership,
    NodeClassification, NodeImportProvenance, NodeImportRecordSummary, NodeTagPresentationState,
    SplitOrientation, format_imported_at_secs,
};

pub mod apply;
pub mod assertion_handles;
pub mod capture;
/// Cross-graph node copy (tear-out fork): mints a node in this graph from a
/// donor node in another graph, recording cross-graph derivation provenance.
pub mod cross_graph;
/// The edit spine: mere's captured-delta stream as a muniment journal, replayed into
/// the graph (the substrate's append-only-log primitive over mere's own edit
/// vocabulary). See `graph/journal.rs`.
pub mod journal;
pub mod legacy_content_migration;
pub(crate) mod legacy_family_attribution;
pub mod legacy_resource_migration;
#[cfg(test)]
mod legacy_resource_migration_copies_tests;
#[cfg(test)]
mod legacy_resource_migration_malformed_tests;
#[cfg(test)]
mod legacy_resource_migration_reason_tests;
pub use cross_graph::ComponentCopy;
mod assertion_write;
pub mod pending_links;
pub use pending_links::{PendingLink, PendingLinkRetention, PendingLinkRetry, PendingLinkState};
pub mod frozen_selection;
pub use frozen_selection::{FrozenSelection, OpenedFrozenSelection};
pub mod frozen_link;
pub use frozen_link::{
    FROZEN_LINK, FrozenLink, FrozenLinkEndpoint, FrozenLinkSource, FrozenSourceBinding,
    FrozenSourceRevision, OpenedFrozenLink,
};
#[cfg(test)]
mod assertion_handles_tests;
pub mod coverage;
#[cfg(test)]
mod frozen_link_tests;
#[cfg(test)]
mod frozen_selection_tests;
mod residency;
pub use coverage::{CoverageLayer, CoverageLimit, CoverageNote};
mod edge_admission;
pub mod edge_data;
pub mod edge_payload;
pub mod edge_taxonomy;
pub mod facet_projection;
pub mod filter;
/// Test-fixture escape hatch over the `pub(crate)` mutators (write-path
/// migration). Feature-gated: enable `fixtures` in dev-dependencies only.
#[cfg(feature = "fixtures")]
pub mod fixtures;
pub mod history;
pub mod identity;
mod input_key;
pub use input_key::GraphInputKey;
mod membership;
pub use membership::SurfaceNodeLifetime;
pub mod import_records;
pub mod merge;
mod navigation_check;
pub mod node;
pub mod node_facets;
pub mod node_props;
pub mod predicate_declarations;
pub mod predicate_registry;
mod relation_read;
pub mod resource;
mod resource_pair_bounds;
pub mod resource_classifications;
pub mod resource_content;
#[cfg(test)]
mod resource_content_edge_tests;
#[cfg(test)]
mod resource_content_handle_tests;
#[cfg(test)]
mod resource_content_tests;
pub mod resource_properties;
pub mod resource_tags;
/// Reverting one change: undo's edits and the parts it keeps (reservoir plan V2).
pub mod revert;
pub mod source_time;
// chartulary capability-trait impls for `Node` (graph re-base, G5).
mod chart;

// Field system: the field-layer definition types (Field / Coupling / the field AST /
// EdgePath) live in the portable `numen` crate, promoted out of the kernel so the
// third graph primitive sits at the same portable tier as chartulary's nodes/edges.
// The kernel keeps the parallel keyed store on `Graph` (fields/couplings are neither
// petgraph node weights nor `EdgePayload` sidecars) and re-exports numen's types.
/// Graph mutators + queries for the field layer (Phase 1): the parallel keyed store
/// on `Graph` + selector evaluation. The field-layer *definition* types (Field /
/// Coupling / the field AST / EdgePath) now live in the portable `numen` crate,
/// re-exported below so `kernel::graph::` paths stay stable.
mod field_ops;

// Identity types and rkyv archive helpers extracted to `identity.rs`
// per the 2026-04-30 renderer plan §6.4 decomposition target. Public
// types are re-exported at this module path so external callers
// (`kernel::graph::NodeKey`, etc.) continue to resolve;
// the rkyv `with = ...` archive helpers are crate-internal and used
// only by struct field annotations in this file.
pub(crate) use identity::UuidAsBytes;
pub use identity::{
    EdgeKey, GraphDirection, GraphIndex, GraphViewId, NodeKey, RelationKey, ResourceEdgeKey,
    SurfaceNodeKey,
};

// Node + NodeLifecycle extracted to `node.rs` per the same
// decomposition target. Re-exported so `kernel::graph::Node`
// continues to resolve.
pub use assertion_write::StatementWriteError;
pub use edge_ops::Retraction;
pub use node::{Node, SurfaceNode};
pub use node_facets::{NodeFacetStore, VisitHistoryFacet};
pub use predicate_declarations::{
    PredicateDeclaration, PredicateDeclarationError, PredicateDeclarations,
};
pub use predicate_registry::{
    GraphStratum, built_in_predicate_stratum, built_in_relation_stratum, default_predicate_stratum,
};
pub use resource::ResourceNode;

// Node navigation history extracted to `history.rs` (2026-05-11
// kernel-mod decomposition pass). Re-exported so external callers
// (`kernel::graph::NodeNavigationMemory`, etc.) keep resolving.
pub use history::{
    NodeHistoryBranchAlternative, NodeHistoryBranchProjection, NodeHistoryBranchVisit,
    NodeHistoryOwner, NodeHistoryProjection, NodeHistorySemanticSummary, SharedNavigationMemory,
};
pub use navigation_check::NavigationIndexError;

// Edge taxonomy (family/sub-kind enums) and per-family runtime data structs
// extracted to their own modules. edge_taxonomy holds classifiers; edge_data
// holds runtime payload types (Data structs, Traversal, EdgeMetrics, IRI fns).
// Stage 4 of the 2026-05-11 relation-taxonomy plan removed `EdgeType` and
// `EdgeKind`; reads go through [`RelationKind`] + [`RelationSelector`], writes
// through [`EdgeAssertion`].
pub use capture::{
    CapturedDelta, DeltaRecorder, GraphTableStats, Malformed, Replay, ReplayRefused, Unwritable,
    replay_captured_deltas, replay_captured_deltas_as_onto, replay_captured_deltas_onto,
    replay_captured_deltas_onto_checked, set_captured_delta_hook, with_isolated_capture,
};
pub use journal::{
    AttributedDelta, Author, AuthorKind, GraphJournal, USER_AUTHOR, journal_capture_hook,
};
pub use merge::import_edits;
pub use revert::{
    Part, Revert, Touched, part_edits, part_node, part_of, part_value, recreate_node_edits,
    revert_change,
};
pub use source_time::{SourceExtent, SourceTime};
// The borne-graph identity type (`Node.nested`): part of the node's public
// surface, re-exported so consumers name it without a direct muniment dep.
pub use edge_data::{
    ArrangementData, AssertionData, ContainmentData, EdgeMetrics, ImportedData, ProvenanceData,
    REL_VOCAB, RelationAssertion, RelationAssertionSpec, SemanticData, SemanticStatement,
    SemanticStatementSpec, StatementAssert, Traversal, TraversalData, all_semantic_sub_kinds,
    predicate_iri, sub_kind_from_iri,
};
pub use edge_payload::EdgePayload;
pub use edge_taxonomy::{
    ArrangementSubKind, ContainmentSubKind, EdgeAssertion, EdgeFamily, ImportedSubKind,
    NavigationTrigger, ProvenanceSubKind, RelationDurability, RelationKind, RelationSelector,
    SemanticSubKind,
};
pub use muniment::{LogId, Seq};

// Field-system truth types (2026-05-31). Field/Coupling form a parallel field
// layer beside the node/edge graph; numen reads them and evaluates.
pub use numen::{
    COUPLING_VOCAB, Coupling, CouplingId, CouplingResponse, EdgePath, EdgePathRule, Falloff, Field,
    FieldDefinition, FieldExtent, FieldId, FieldLifecycle, NodeSelector, ScalarField, VectorField,
};

/// Traversal archive payload emitted when dissolving a node.
#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub struct DissolvedTraversalRecord {
    #[rkyv(with = UuidAsBytes)]
    pub from_node_id: Uuid,
    #[rkyv(with = UuidAsBytes)]
    pub to_node_id: Uuid,
    pub traversals: Vec<Traversal>,
}

fn normalize_import_record_memberships(memberships: &mut Vec<ImportRecordMembership>) {
    memberships.sort_by(|left, right| {
        left.node_id
            .cmp(&right.node_id)
            .then_with(|| left.suppressed.cmp(&right.suppressed))
    });
    let mut deduped: Vec<ImportRecordMembership> = Vec::with_capacity(memberships.len());
    for membership in memberships.drain(..) {
        if let Some(existing) = deduped.last_mut()
            && existing.node_id == membership.node_id
        {
            existing.suppressed &= membership.suppressed;
            continue;
        }
        deduped.push(membership);
    }
    *memberships = deduped;
}

pub(crate) fn normalize_import_records(import_records: &mut Vec<ImportRecord>) {
    let mut merged = BTreeMap::<String, ImportRecord>::new();
    for mut record in import_records.drain(..) {
        normalize_import_record_memberships(&mut record.memberships);
        if record.record_id.trim().is_empty() {
            continue;
        }
        let entry = merged
            .entry(record.record_id.clone())
            .or_insert_with(|| ImportRecord {
                record_id: record.record_id.clone(),
                source_id: record.source_id.clone(),
                source_label: record.source_label.clone(),
                imported_at_secs: record.imported_at_secs,
                memberships: Vec::new(),
            });
        if entry.source_id.is_empty() {
            entry.source_id = record.source_id.clone();
        }
        if entry.source_label.is_empty() {
            entry.source_label = record.source_label.clone();
        }
        if entry.imported_at_secs == 0 {
            entry.imported_at_secs = record.imported_at_secs;
        } else if record.imported_at_secs != 0 {
            entry.imported_at_secs = entry.imported_at_secs.min(record.imported_at_secs);
        }
        entry.memberships.extend(record.memberships);
    }
    *import_records = merged.into_values().collect();
    for record in import_records.iter_mut() {
        normalize_import_record_memberships(&mut record.memberships);
    }
    import_records.sort_by(|left, right| {
        left.source_label
            .cmp(&right.source_label)
            .then_with(|| left.imported_at_secs.cmp(&right.imported_at_secs))
            .then_with(|| left.record_id.cmp(&right.record_id))
    });
}

pub(crate) fn current_unix_timestamp_secs() -> u64 {
    crate::time::unix_epoch_seconds()
}

// Node, NodeLifecycle, and impl Node moved to `node.rs` per the
// 2026-04-30 renderer plan §6.4 decomposition target. Re-exported
// here so external paths (`kernel::graph::Node`, etc.)
// resolve unchanged.

/// Canonical read-side relation view. One row per (from, to,
/// [`RelationKind`]) — a multi-relation node pair yields multiple
/// rows. Replaces the `EdgeType`-flavoured `EdgeView` removed in
/// stage 4 of the 2026-05-11 relation-taxonomy plan.
///
/// This is the **classifier shape** — it carries no per-relation
/// payload (labels, decay, traversal events). Callers needing
/// payload reach for the typed `EdgePayload` sidecar via the
/// kernel's per-family query methods.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RelationView {
    pub from: NodeKey,
    pub to: NodeKey,
    pub kind: RelationKind,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticEdgeView {
    pub from: NodeKey,
    pub to: NodeKey,
    pub sub_kind: SemanticSubKind,
    pub label: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArrangementEdgeView {
    pub from: NodeKey,
    pub to: NodeKey,
    pub sub_kind: ArrangementSubKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContainmentEdgeView {
    pub from: NodeKey,
    pub to: NodeKey,
    pub sub_kind: ContainmentSubKind,
}

/// Main graph structure backed by petgraph::StableGraph
#[derive(Clone)]
pub struct Graph {
    /// Runtime-only model input versions, preserved by clones and advanced at
    /// the existing structural/content/site/visit mutation boundaries.
    runtime_input_keys: [GraphInputKey; 4],
    /// The substrate graph: a [`chartulary::Graph`] over mere's [`Node`] and
    /// [`EdgePayload`] (the G5 re-base — mere's graph *is* a chartulary graph).
    /// It owns the petgraph topology and the stable id-to-key index (mere's old
    /// hand-rolled `id_to_node` is retired in its favor). `pub(crate)` to enforce
    /// the single-write-path boundary at the type level: every topology mutation
    /// goes through a `Graph` method so it advances [`revision`](Self::revision);
    /// direct mutation from outside the kernel would bypass the bump and stale the
    /// structural caches. Reads reach petgraph algorithms through
    /// [`chartulary::Graph::inner`]. (Graph signals.)
    pub(crate) inner: chartulary::Graph<Node, EdgePayload>,
    /// Runtime membership witnesses; cloned with candidates, never snapshotted.
    surface_node_lifetimes: HashMap<Uuid, SurfaceNodeLifetime>,

    /// Resource truth beneath surfaces, indexed by the prepared identity IRI.
    pub(crate) resources: chartulary::Graph<ResourceNode, EdgePayload>,
    /// The one live authority for ordinary resource metadata.
    pub(crate) resource_facets: chartulary::FacetStore<Uuid>,
    /// Explicit surface UUID to resource UUID associations.
    pub(crate) shown_resources: BTreeMap<Uuid, Uuid>,

    /// Atomic optional metadata keyed by stable node id. This is the single
    /// live authority persisted by the host as `facets.json`; snapshot columns
    /// are legacy import inputs only.
    pub(crate) facets: chartulary::FacetStore<Uuid>,

    /// URL to node mapping for lookup (supports duplicate URLs).
    pub(crate) url_to_nodes: HashMap<String, Vec<NodeKey>>,

    /// Durable imported relation truth; node provenance is derived from this.
    pub(crate) import_records: Vec<ImportRecord>,

    /// Field-layer truth (field-system step 3, Phase 1): a parallel keyed store
    /// beside the node/edge petgraph. A coupling targets a *selector* over nodes,
    /// not a node→node edge, so fields/couplings cannot ride the petgraph; they
    /// are content truth that numen reads and evaluates (derived).
    ///
    /// Ordered by id (the inner UUID, which orders as its canonical string
    /// does; `FieldId` and `CouplingId` carry no `Ord`), so every read and
    /// every snapshot sees one order.
    pub(crate) fields: BTreeMap<Uuid, Field>,
    pub(crate) couplings: BTreeMap<Uuid, Coupling>,

    /// The graph's whole navigation history: one shared visit space, one owner
    /// per node (the (b) anchor design). In-place navigation extends a node's own
    /// path; a branch node is spawned anchored under its origin's current visit.
    pub(crate) nav: SharedNavigationMemory,

    /// A monotonic **structural revision**, bumped by [`bump_revision`](Self::bump_revision)
    /// whenever the node/edge structure or a pair's relation set changes (add/remove node, add/
    /// remove edge, assert/retract a relation). It does NOT bump on a re-visit's traversal append
    /// or on pure content edits (title/url/tags), since those leave the structure a derived signal
    /// reads unchanged. The single source of truth any consumer gates a cache on — community,
    /// arrangements, importance — so a recompute happens once per real change, not per frame.
    /// (Graph signals — the local counter; cross-owner caches use structural_input_key.)
    revision: u64,

    /// A monotonic revision for the URL-authority partition used by views such
    /// as site kanban. URL edits do not change topology, so they deliberately
    /// do not advance [`revision`](Self::revision); a consumer that groups
    /// nodes by authority must depend on this narrower signal instead.
    url_grouping_revision: u64,

    /// A monotonic **content revision**: bumped when a node's text may have
    /// changed (a node added, copied in or removed, its title set, its
    /// primary URL moved). Structure, visits, tags, images and facets leave it
    /// alone. A consumer keyed to node text, such as the canvas's Meaning
    /// channel, recomputes only when it moves. Not persisted, like
    /// [`revision`](Self::revision). (Dynamics grammar plan, G2, F33.)
    content_revision: u64,

    /// A monotonic **visit revision**: bumped whenever a node's visit history
    /// (`visit.history`) may have changed, through any kernel writer of it, a
    /// generic facet delta naming it, a sidecar overlay, or mutable facet
    /// access. Structure and text leave it alone. A consumer keyed to recency,
    /// such as the channel registry's recency order, recomputes only when it or
    /// the structural revision moves. Not persisted. (Dynamics grammar plan,
    /// G2b, F54.)
    visit_revision: u64,

    /// The current app-launch session number, set once by the host via
    /// [`set_current_session`](Self::set_current_session) right after construction/
    /// restore. `0` (the default) means "not wired" — [`navigate_node`](Self::navigate_node)
    /// then stamps nothing, so by-sessions eviction sees every node as undated until the
    /// host opts in. Not part of the persisted snapshot: it is per-launch host state, not
    /// graph truth. (Alembic B5 — by-sessions eviction.)
    current_session: u64,

    /// Attribution context supplied by the session performing a write.
    write_author: Author,

    /// Where this graph sends its own captured deltas, once a host opts it in
    /// with [`set_recorder`](Self::set_recorder). Not graph truth, and not
    /// carried by a clone.
    pub(crate) recorder: capture::Recorder,
    pub(crate) pending_link_state: PendingLinkState,
    pub(crate) pending_derivation_suppressed: pending_links::Suppression,
    pub(crate) semantic_observation_revision: u64,
    pub(crate) appearance_admission_revision: u64,
    pub(crate) known_coverage: CoverageNote,
    /// Set only inside a legacy migration's staged scope; see `edge_admission`.
    pub(crate) staged_edges: edge_admission::StagedEdges,
}

impl Graph {
    /// Create a new empty graph
    pub fn new() -> Self {
        Self {
            runtime_input_keys: [GraphInputKey::new_source(); 4],
            inner: chartulary::Graph::new(),
            surface_node_lifetimes: HashMap::new(),
            resources: chartulary::Graph::new(),
            resource_facets: chartulary::FacetStore::new(),
            shown_resources: BTreeMap::new(),
            facets: chartulary::FacetStore::new(),
            url_to_nodes: HashMap::new(),
            import_records: Vec::new(),
            fields: BTreeMap::new(),
            couplings: BTreeMap::new(),
            nav: SharedNavigationMemory::empty(),
            revision: 0,
            url_grouping_revision: 0,
            content_revision: 0,
            visit_revision: 0,
            current_session: 0,
            write_author: Author::user(),
            recorder: capture::Recorder::default(),
            pending_link_state: PendingLinkState::default(),
            pending_derivation_suppressed: pending_links::Suppression::default(),
            semantic_observation_revision: 0,
            appearance_admission_revision: 0,
            known_coverage: CoverageNote::default(),
            staged_edges: Default::default(),
        }
    }

    /// Send every delta this graph applies through `apply_graph_delta` to
    /// `recorder`, or stop with `None`. The per-graph twin of the thread's
    /// capture hook: a host holding many session graphs records each into its
    /// own journal. A clone of this graph, and a replay onto it, record nothing.
    pub fn set_recorder(&mut self, recorder: Option<DeltaRecorder>) {
        self.recorder.0 = recorder;
    }

    /// Whether this graph records its deltas.
    pub fn is_recording(&self) -> bool {
        self.recorder.0.is_some()
    }

    /// The recorder identity used when a writer has no attributed source.
    pub fn write_author(&self) -> &Author {
        &self.write_author
    }

    /// Run a write under the same author its journal will record.
    pub fn write_as<R>(&mut self, author: Author, write: impl FnOnce(&mut Self) -> R) -> R {
        let previous = std::mem::replace(&mut self.write_author, author);
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| write(self)));
        self.write_author = previous;
        match result {
            Ok(value) => value,
            Err(panic) => std::panic::resume_unwind(panic),
        }
    }

    /// Set the current app-launch session number (Alembic B5). The host calls this once,
    /// right after construction or snapshot-restore, with its persisted-and-incremented
    /// session counter; every [`navigate_node`](Self::navigate_node) call afterwards stamps
    /// the visited node's [`Node::last_session_visited`] with this value.
    pub fn set_current_session(&mut self, session: u64) {
        self.current_session = session;
    }

    /// The launch number [`set_current_session`](Self::set_current_session) installed.
    pub fn current_session(&self) -> u64 {
        self.current_session
    }

    /// The current structural revision (see [`revision`](Self::revision)). A consumer captures it
    /// alongside a derived result and recomputes only when it has advanced. (Graph signals.)
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// The current URL-authority grouping revision. This advances only when a
    /// node's primary URL moves between site groups, letting site-grouped
    /// projections refresh without invalidating structural caches for an
    /// ordinary same-site navigation.
    pub fn url_grouping_revision(&self) -> u64 {
        self.url_grouping_revision
    }

    /// The current content revision (see the field's doc): it advances on a
    /// node's title or primary URL changing and on a node joining or leaving,
    /// never on an edge or relation change.
    pub fn content_revision(&self) -> u64 {
        self.content_revision
    }

    /// The current visit revision (see the field's doc): it advances when a
    /// node's visit history may have changed, never on structure or text.
    pub fn visit_revision(&self) -> u64 {
        self.visit_revision
    }

    /// The categorical site key used by URL-grouped projections: the authority
    /// after `://` and before a path, query, or fragment, or the whole hostless
    /// input. It deliberately retains ports and opaque values.
    pub fn url_grouping_key(url: &str) -> &str {
        let after_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
        after_scheme
            .split(['/', '?', '#'])
            .next()
            .unwrap_or(after_scheme)
    }

    /// Advance the structural revision. Called by the topology/relation mutators on a real change.
    /// (Graph signals — the local counter; cross-owner caches use structural_input_key.)
    fn bump_revision(&mut self) {
        self.revision = self.revision.wrapping_add(1);
        self.runtime_input_keys[0].advance();
    }

    fn bump_url_grouping_revision(&mut self) {
        self.url_grouping_revision = self.url_grouping_revision.wrapping_add(1);
        self.runtime_input_keys[2].advance();
    }

    pub(crate) fn bump_content_revision(&mut self) {
        self.content_revision = self.content_revision.wrapping_add(1);
        self.runtime_input_keys[1].advance();
    }

    pub(crate) fn bump_visit_revision(&mut self) {
        self.visit_revision = self.visit_revision.wrapping_add(1);
        self.runtime_input_keys[3].advance();
    }

    // Durable write boundaries. The Phase 6.5 GraphDelta migration covers
    // ordinary primitive mutations; assertion lifecycle and predicate
    // declaration APIs also expose public durable writes and emit captures
    // directly. A host must install a recorder and apply its admission policy
    // around either entry point; GraphDelta is not the sole public writer.
    // The writer classes:
    //   1. Ordinary primitive mutations (topology, relations, nav history, tags,
    //      titles, body, media, classifications, properties, predicates,
    //      fields/couplings, frame hints, import records) — `pub(crate)`,
    //      reached externally only via `GraphDelta`. Navigation has one primitive
    //      per operation (`navigate_node`, `branch_history`, `node_history_back`,
    //      `node_history_forward`) under both the live and the replay arm.
    //   2. Public native assertion/declaration writes: `assertion_write` and
    //      `predicate_declarations`, with their own capture emission.
    //   3. Compound kernel operations stay `pub`: `from_snapshot`,
    //      `cross_graph::copy_*` — kernel-authored multi-step ops over
    //      non-delta-able inputs (`&Graph` donors); the "trusted writers".
    //   4. Transient/runtime state stays `pub`, exempt by design:
    //      `set_node_position` / `set_node_projected_position` (physics/view —
    //      positions are not graph truth), `set_current_session` (per-launch
    //      host wiring). Webview runtime state left the kernel entirely
    //      (`BrowserNodeState` sidecar, boundary pass slice C).
    //   5. Test fixtures: the `fixtures` cargo feature re-exposes the raw
    //      structural mutators via `graph::fixtures::GraphFixtures` —
    //      dev-dependencies only, never a production enable. Navigation is not
    //      among them: a fixture graph navigates through `GraphDelta`, so it
    //      carries what a live navigation leaves.

    /// The fixed namespace for the deterministic node id (see
    /// [`node_namespace_id`](Self::node_namespace_id)). Fixed forever: changing it
    /// would renumber every node derived from it.
    const NODE_NAMESPACE: Uuid = Uuid::from_u128(0x6D65_7265_4E4F_4445_6E61_6D65_7370_6163);

    /// The deterministic node UUID for `url`: a name-based UUIDv5 under
    /// [`NODE_NAMESPACE`](Self::NODE_NAMESPACE). Two hosts that materialize the
    /// same `url` mint the same id, so a federated merge needs no identity
    /// reconciliation. The linked-data ingest layer uses this for a document's
    /// `@id`, where the URL *is* the identity. Raw [`add_node`] keeps a fresh
    /// random id, because the kernel treats a node's address as a property and
    /// lets several nodes share one (see `get_nodes_by_url`).
    pub fn node_namespace_id(url: &str) -> Uuid {
        Uuid::new_v5(&Self::NODE_NAMESPACE, url.as_bytes())
    }

    /// Add a new node to the graph.
    ///
    /// Not available on `wasm32`; use [`add_node_with_id`] with a host-provided
    /// UUID (e.g. from [`node_namespace_id`](Self::node_namespace_id)) instead.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn add_node(&mut self, url: String, position: Point2D<f32>) -> NodeKey {
        self.add_node_with_id(Uuid::new_v4(), url, position)
    }

    /// Add a node with a pre-existing UUID, or return the key of the node that
    /// already holds it ([`insert_node_if_missing`](Self::insert_node_if_missing)).
    pub(crate) fn add_node_with_id(
        &mut self,
        id: Uuid,
        url: String,
        position: Point2D<f32>,
    ) -> NodeKey {
        self.insert_node_if_missing(id, url, position).0
    }

    /// The insertion contract shared by live `AddNode` and replay: insert if
    /// the id is missing, else leave the existing node, its address and its URL
    /// index entries as they are. The flag reports whether a node was inserted.
    /// `_position` is the caller's initial placement hint; it is no longer
    /// stored on the node (position is not graph truth), so the host applies it
    /// to seiche / the cartography sidecar.
    pub(crate) fn insert_node_if_missing(
        &mut self,
        id: Uuid,
        url: String,
        _position: Point2D<f32>,
    ) -> (NodeKey, bool) {
        let primary_address = address_from_url(&url);
        let mut container = chartulary::Container::with_identity(id)
            .with_address_record(primary_address)
            .with_title(url.clone());
        container.media_type = detect_mime(&url, None);
        let (key, inserted) = self.insert_surface_node(Node {
            container,
            images: std::collections::BTreeMap::new(),
        });
        if inserted {
            self.set_node_last_visited_at_ms(key, Self::epoch_ms());
            self.url_to_nodes.entry(url).or_default().push(key);
            self.bump_revision();
            self.bump_content_revision();
        }
        (key, inserted)
    }

    /// Remove a node and all its connected edges
    pub(crate) fn remove_node(&mut self, key: NodeKey) -> bool {
        if let Some(node) = self.inner.remove(key) {
            // The node's navigation owner is intentionally *kept* in the shared
            // visit space: a node branched from it still anchors to its visits, so
            // erasing the lineage on node removal would orphan those anchors. The
            // owner is simply never queried once the node is gone (pruning belongs
            // to a future GC / `eidetic` scope, not graph removal).
            // Deregister every URL claim this node carried — Primary plus
            // any aliases. (Aliases are not yet wired into add paths but the
            // index handles them when they land.)
            for address in &node.addresses {
                self.remove_url_mapping(address.as_url_str(), key);
            }
            let node_id = node.id;
            self.surface_node_lifetimes.remove(&node_id);
            self.shown_resources.remove(&node_id);
            self.remove_facets_for_node(node_id);
            let removed_id = node_id.to_string();
            for record in &mut self.import_records {
                record
                    .memberships
                    .retain(|membership| membership.node_id != removed_id);
            }
            self.import_records
                .retain(|record| !record.memberships.is_empty());
            self.bump_revision();
            self.bump_content_revision();
            true
        } else {
            false
        }
    }

    /// Write a node's primary address, maintaining the url_to_nodes index.
    /// Returns the old URL, or None if the node doesn't exist.
    ///
    /// The one writer of the address. `SetNodeUrl` calls it alone, changing the
    /// address with no visit; [`navigate_node`](Self::navigate_node) calls it
    /// after recording the visit, and a history step after moving the cursor
    /// (`land_history_step`). The Stemma cursor is the browse trail's position,
    /// not the address; see the `history` module.
    ///
    /// Operates on the Primary claim only; aliases (when supported) stay
    /// attached. To mutate aliases, use dedicated alias methods (future).
    pub(crate) fn update_node_url(&mut self, key: NodeKey, new_url: String) -> Option<String> {
        let node = self.inner.node_mut(key)?;
        let old_url = node.primary_address().as_url_str().to_string();
        let host_changed = cached_host_from_url(&old_url) != cached_host_from_url(&new_url);
        let site_group_changed =
            Self::url_grouping_key(&old_url) != Self::url_grouping_key(&new_url);
        // A navigation to a different host invalidates the favicon (it was the old
        // site's icon); clear it so a stale favicon does not linger on the tile until
        // the new one loads. A same-host path change keeps it. (Favicon-on-tile.)
        if host_changed {
            node.clear_image(crate::types::ImageRole::Favicon);
        }
        // Primary-first is Container's address-role mapping. Replace index 0;
        // aliases (the rest) stay attached.
        let new_primary_address = address_from_url(&new_url);
        if let Some(primary) = node.addresses.first_mut() {
            *primary = new_primary_address;
        }
        let url_changed = old_url != new_url;
        self.remove_url_mapping(&old_url, key);
        self.url_to_nodes.entry(new_url).or_default().push(key);
        if site_group_changed {
            self.bump_url_grouping_revision();
        }
        if url_changed {
            self.bump_content_revision();
        }
        Some(old_url)
    }

    /// Establish the current page binding for a live write, retaining an
    /// already recorded binding. Legacy replay does not call this helper.
    pub(crate) fn ensure_surface_resource(&mut self, key: NodeKey) -> Option<Uuid> {
        self.shown_resource_id(key)
            .or_else(|| self.refresh_surface_resource(key))
    }

    /// Refresh a live surface's page binding after its surface mutation has
    /// been captured. The resource record precedes the shown association.
    pub(crate) fn refresh_surface_resource(&mut self, key: NodeKey) -> Option<Uuid> {
        let node = self.get_node(key)?;
        let surface_id = node.id;
        let resource = ResourceNode::new(node.primary_address().as_url_str());
        let resource_id = resource.id();
        if self.resource(resource_id).is_none() {
            let record = crate::persistence::PersistedResourceRecord {
                canonical_iri: resource.canonical_iri().to_string(),
                facets: Vec::new(),
            };
            if !self.set_resource_record(resource_id, Some(record.clone())) {
                return None;
            }
            self.record_delta(&CapturedDelta::ReplaySetResourceRecordById {
                resource_id: resource_id.to_string(),
                record: Some(record),
            });
        }
        if self.set_shown_resource(surface_id, Some(resource_id)) {
            self.record_delta(&CapturedDelta::ReplaySetShownResourceById {
                surface_id: surface_id.to_string(),
                resource_id: Some(resource_id.to_string()),
            });
        }
        Some(resource_id)
    }

    /// Navigate `key` in place to `url`: record the visit in the node's own
    /// browse history (a forward-fork if the cursor had stepped back), write
    /// `url` as its primary address, and stamp its recency at `at_ms` and its
    /// session. A visit moves the trail and the address together; `SetNodeUrl`
    /// moves the address alone. No new node and no edge: the node is a browsing
    /// surface whose content changes; the graph shape does not. Cross-node
    /// lineage (the navigated-from relation) is a separate, explicit edge.
    ///
    /// The one mutation under both the live and the replayed arm, which differ
    /// only in the stamp they pass. Returns the node's id, or `None` if absent.
    pub(crate) fn navigate_node(
        &mut self,
        key: NodeKey,
        url: &str,
        transition: NodeHistoryTransitionKind,
        at_ms: u64,
        last_session_visited: u64,
    ) -> Option<Uuid> {
        let id = self.inner.node(key)?.id;
        self.nav.record_visit(id, url, transition, at_ms);
        self.set_node_last_session_visited(key, last_session_visited);
        self.update_node_url(key, url.to_string());
        self.set_node_last_visited_at_ms(key, at_ms);
        Some(id)
    }

    /// Anchor a freshly-minted `child` node's history under `parent`'s current
    /// visit, the navigated-from anchor. Do this **before** the child's first
    /// [`navigate_node`](Self::navigate_node) so that first visit attaches there
    /// in the shared lineage tree (the (b) cross-node anchor; the branch-mint
    /// path). Returns the `(child, parent)` ids, or `None` if either is absent.
    pub(crate) fn branch_history(
        &mut self,
        child: NodeKey,
        parent: NodeKey,
    ) -> Option<(Uuid, Uuid)> {
        let child_id = self.inner.node(child)?.id;
        let parent_id = self.inner.node(parent)?.id;
        self.nav.spawn(child_id, parent_id);
        Some((child_id, parent_id))
    }

    /// Step `key` back one visit in its own history, updating its Primary URL to
    /// the revealed page. Returns the new URL, or `None` if already at the root.
    pub(crate) fn node_history_back(&mut self, key: NodeKey, at_ms: u64) -> Option<String> {
        let id = self.inner.node(key)?.id;
        let url = self.nav.back(id, at_ms)?;
        self.land_history_step(key, &url, at_ms);
        Some(url)
    }

    /// Step `key` forward one visit in its own history. Returns the new URL, or
    /// `None` if already at the tip.
    pub(crate) fn node_history_forward(&mut self, key: NodeKey, at_ms: u64) -> Option<String> {
        let id = self.inner.node(key)?.id;
        let url = self.nav.forward(id, at_ms)?;
        self.land_history_step(key, &url, at_ms);
        Some(url)
    }

    /// What a moved history cursor leaves on the node: the revealed page as its
    /// primary address, and the step as its latest visit. The one place history
    /// writes the address: the cursor is the trail's position, and a step lands
    /// its page on the address even where a `SetNodeUrl` has moved it since.
    fn land_history_step(&mut self, key: NodeKey, url: &str, at_ms: u64) {
        self.update_node_url(key, url.to_string());
        self.set_node_last_visited_at_ms(key, at_ms);
    }

    /// Whether `key`'s within-node history can step back (toolbar gating).
    pub fn node_can_back(&self, key: NodeKey) -> bool {
        self.inner
            .node(key)
            .is_some_and(|n| self.nav.can_back(n.id))
    }

    /// Whether `key`'s within-node history can step forward (toolbar gating).
    pub fn node_can_forward(&self, key: NodeKey) -> bool {
        self.inner
            .node(key)
            .is_some_and(|n| self.nav.can_forward(n.id))
    }

    /// `key`'s linear-history projection (active path + cursor).
    pub fn node_history_projection(&self, key: NodeKey) -> NodeHistoryProjection {
        match self.inner.node(key) {
            Some(node) => self.nav.projection(node.id),
            None => NodeHistoryProjection {
                entries: Vec::new(),
                current_index: 0,
            },
        }
    }

    /// `key`'s branching-history projection (visit tree with alternates).
    pub fn node_history_branch_projection(&self, key: NodeKey) -> NodeHistoryBranchProjection {
        self.inner
            .node(key)
            .map(|node| self.nav.branch_projection(node.id))
            .unwrap_or_default()
    }

    /// A coarse semantic summary of `key`'s history.
    pub fn node_history_semantic_summary(&self, key: NodeKey) -> NodeHistorySemanticSummary {
        self.inner
            .node(key)
            .map(|node| self.nav.semantic_summary(node.id))
            .unwrap_or_default()
    }

    /// Milliseconds since the Unix epoch, for visit timestamps (live-app clock).
    fn epoch_ms() -> u64 {
        crate::time::unix_epoch_millis()
    }
}

// Edge mutators (add_edge, assert_relation, replay_*, dissolve_*,
// remove_edges, retract_relations, get_edge*, push_traversal) live in
// `graph/edge_ops.rs` (2026-05-11 decomposition pass).
pub mod edge_ops;

// Query + traversal (node/edge lookups, neighbor iteration, BFS /
// shortest-path / connected-components / SCC, derived-edge views)
// live in `graph/query.rs` (2026-05-11 decomposition pass).
pub mod query;

// `node_display_label`: a human-meaningful label derived from a node's title /
// linked-data role / @type / address, for the canvas tiles + roster (so an
// anonymous ingested entity reads as "publisher" / "Organization", not a raw
// `urn:mere:bnode:` string).
pub mod display;

// Snapshot serialization (`to_snapshot` / `from_snapshot`), the rkyv
// trait impls that delegate through them, `containment_parent_url`,
// and `impl Default for Graph` live in `graph/snapshot.rs`
// (2026-05-11 decomposition pass).
pub mod snapshot;

// Tests live in `graph/tests.rs` to keep this file under the
// 600-LOC ceiling (kernel decomposition pass 2026-05-11).
#[cfg(test)]
mod tests;

#[cfg(test)]
#[path = "tests/resource_lifecycle.rs"]
mod resource_lifecycle_tests;