Skip to main content

kernel/graph/
mod.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//! Graph data structures for the spatial browser.
8//!
9//! Core structures:
10//! - `Graph`: Main graph container backed by petgraph::StableGraph
11//! - `Node`: Webpage node with a transient projected position and metadata
12//! - `EdgePayload`: Edge semantics and traversal events between nodes
13//!
14//! This module is WASM-clean: it must compile to `wasm32-unknown-unknown`.
15
16use euclid::default::Point2D;
17// `MemoryEntryPrivacy` / `OwnerScopedMemory` / `GraphMemorySnapshot` /
18// `MemoryTransitionKind` were used by the node-history types that
19// moved to `history.rs` (2026-05-11 decomposition pass); `Graph` itself
20// doesn't reach into node-lineage directly.
21use petgraph::algo::{astar, dijkstra, has_path_connecting, kosaraju_scc};
22#[cfg(test)]
23use petgraph::stable_graph::NodeIndex;
24use petgraph::visit::{EdgeRef, IntoEdgeReferences};
25use rkyv::{Archive, Archived, Deserialize, Place, Resolver, Serialize, rancor::Fallible};
26use std::collections::{BTreeMap, HashMap, HashSet};
27use uuid::Uuid;
28
29pub use chartulary::stemma::TransitionKind as NodeHistoryTransitionKind;
30/// The stable address of a node's out-of-line representation.
31pub use muniment::Hash as ContentHash;
32
33use crate::address::{Address, AddressKind, address_from_url, cached_host_from_url, detect_mime};
34use crate::persistence::{
35    GraphSnapshot, PersistedAddress, PersistedArrangementEdgeData, PersistedArrangementSubKind,
36    PersistedContainmentEdgeData, PersistedContainmentSubKind, PersistedEdge, PersistedEdgeFamily,
37    PersistedImportedEdgeData, PersistedImportedSubKind, PersistedNavigationTrigger, PersistedNode,
38    PersistedNodeSessionState, PersistedProvenanceEdgeData, PersistedProvenanceSubKind,
39    PersistedSemanticEdgeData, PersistedSemanticSubKind, PersistedTraversalEdgeData,
40    PersistedTraversalMetrics, PersistedTraversalRecord,
41};
42#[allow(unused_imports)] // Some used only in #[cfg(test)]
43use crate::types::{
44    ClassificationProvenance, ClassificationScheme, ClassificationStatus, DominantEdge,
45    FrameLayoutHint, FrameLayoutNodeId, GraphScope, ImportRecord, ImportRecordMembership,
46    NodeClassification, NodeImportProvenance, NodeImportRecordSummary, NodeTagPresentationState,
47    SplitOrientation, format_imported_at_secs,
48};
49
50pub mod apply;
51pub mod assertion_handles;
52pub mod capture;
53/// Cross-graph node copy (tear-out fork): mints a node in this graph from a
54/// donor node in another graph, recording cross-graph derivation provenance.
55pub mod cross_graph;
56/// The edit spine: mere's captured-delta stream as a muniment journal, replayed into
57/// the graph (the substrate's append-only-log primitive over mere's own edit
58/// vocabulary). See `graph/journal.rs`.
59pub mod journal;
60pub mod legacy_content_migration;
61pub(crate) mod legacy_family_attribution;
62pub mod legacy_resource_migration;
63#[cfg(test)]
64mod legacy_resource_migration_copies_tests;
65#[cfg(test)]
66mod legacy_resource_migration_malformed_tests;
67#[cfg(test)]
68mod legacy_resource_migration_reason_tests;
69pub use cross_graph::ComponentCopy;
70mod assertion_write;
71pub mod pending_links;
72pub use pending_links::{PendingLink, PendingLinkRetention, PendingLinkRetry, PendingLinkState};
73pub mod frozen_selection;
74pub use frozen_selection::{FrozenSelection, OpenedFrozenSelection};
75pub mod frozen_link;
76pub use frozen_link::{
77    FROZEN_LINK, FrozenLink, FrozenLinkEndpoint, FrozenLinkSource, FrozenSourceBinding,
78    FrozenSourceRevision, OpenedFrozenLink,
79};
80#[cfg(test)]
81mod assertion_handles_tests;
82pub mod coverage;
83#[cfg(test)]
84mod frozen_link_tests;
85#[cfg(test)]
86mod frozen_selection_tests;
87mod residency;
88pub use coverage::{CoverageLayer, CoverageLimit, CoverageNote};
89mod edge_admission;
90pub mod edge_data;
91pub mod edge_payload;
92pub mod edge_taxonomy;
93pub mod facet_projection;
94pub mod filter;
95/// Test-fixture escape hatch over the `pub(crate)` mutators (write-path
96/// migration). Feature-gated: enable `fixtures` in dev-dependencies only.
97#[cfg(feature = "fixtures")]
98pub mod fixtures;
99pub mod history;
100pub mod identity;
101mod input_key;
102pub use input_key::GraphInputKey;
103mod membership;
104pub use membership::SurfaceNodeLifetime;
105pub mod import_records;
106pub mod merge;
107mod navigation_check;
108pub mod node;
109pub mod node_facets;
110pub mod node_props;
111pub mod predicate_declarations;
112pub mod predicate_registry;
113mod relation_read;
114pub mod resource;
115mod resource_pair_bounds;
116pub mod resource_classifications;
117pub mod resource_content;
118#[cfg(test)]
119mod resource_content_edge_tests;
120#[cfg(test)]
121mod resource_content_handle_tests;
122#[cfg(test)]
123mod resource_content_tests;
124pub mod resource_properties;
125pub mod resource_tags;
126/// Reverting one change: undo's edits and the parts it keeps (reservoir plan V2).
127pub mod revert;
128pub mod source_time;
129// chartulary capability-trait impls for `Node` (graph re-base, G5).
130mod chart;
131
132// Field system: the field-layer definition types (Field / Coupling / the field AST /
133// EdgePath) live in the portable `numen` crate, promoted out of the kernel so the
134// third graph primitive sits at the same portable tier as chartulary's nodes/edges.
135// The kernel keeps the parallel keyed store on `Graph` (fields/couplings are neither
136// petgraph node weights nor `EdgePayload` sidecars) and re-exports numen's types.
137/// Graph mutators + queries for the field layer (Phase 1): the parallel keyed store
138/// on `Graph` + selector evaluation. The field-layer *definition* types (Field /
139/// Coupling / the field AST / EdgePath) now live in the portable `numen` crate,
140/// re-exported below so `kernel::graph::` paths stay stable.
141mod field_ops;
142
143// Identity types and rkyv archive helpers extracted to `identity.rs`
144// per the 2026-04-30 renderer plan §6.4 decomposition target. Public
145// types are re-exported at this module path so external callers
146// (`kernel::graph::NodeKey`, etc.) continue to resolve;
147// the rkyv `with = ...` archive helpers are crate-internal and used
148// only by struct field annotations in this file.
149pub(crate) use identity::UuidAsBytes;
150pub use identity::{
151    EdgeKey, GraphDirection, GraphIndex, GraphViewId, NodeKey, RelationKey, ResourceEdgeKey,
152    SurfaceNodeKey,
153};
154
155// Node + NodeLifecycle extracted to `node.rs` per the same
156// decomposition target. Re-exported so `kernel::graph::Node`
157// continues to resolve.
158pub use assertion_write::StatementWriteError;
159pub use edge_ops::Retraction;
160pub use node::{Node, SurfaceNode};
161pub use node_facets::{NodeFacetStore, VisitHistoryFacet};
162pub use predicate_declarations::{
163    PredicateDeclaration, PredicateDeclarationError, PredicateDeclarations,
164};
165pub use predicate_registry::{
166    GraphStratum, built_in_predicate_stratum, built_in_relation_stratum, default_predicate_stratum,
167};
168pub use resource::ResourceNode;
169
170// Node navigation history extracted to `history.rs` (2026-05-11
171// kernel-mod decomposition pass). Re-exported so external callers
172// (`kernel::graph::NodeNavigationMemory`, etc.) keep resolving.
173pub use history::{
174    NodeHistoryBranchAlternative, NodeHistoryBranchProjection, NodeHistoryBranchVisit,
175    NodeHistoryOwner, NodeHistoryProjection, NodeHistorySemanticSummary, SharedNavigationMemory,
176};
177pub use navigation_check::NavigationIndexError;
178
179// Edge taxonomy (family/sub-kind enums) and per-family runtime data structs
180// extracted to their own modules. edge_taxonomy holds classifiers; edge_data
181// holds runtime payload types (Data structs, Traversal, EdgeMetrics, IRI fns).
182// Stage 4 of the 2026-05-11 relation-taxonomy plan removed `EdgeType` and
183// `EdgeKind`; reads go through [`RelationKind`] + [`RelationSelector`], writes
184// through [`EdgeAssertion`].
185pub use capture::{
186    CapturedDelta, DeltaRecorder, GraphTableStats, Malformed, Replay, ReplayRefused, Unwritable,
187    replay_captured_deltas, replay_captured_deltas_as_onto, replay_captured_deltas_onto,
188    replay_captured_deltas_onto_checked, set_captured_delta_hook, with_isolated_capture,
189};
190pub use journal::{
191    AttributedDelta, Author, AuthorKind, GraphJournal, USER_AUTHOR, journal_capture_hook,
192};
193pub use merge::import_edits;
194pub use revert::{
195    Part, Revert, Touched, part_edits, part_node, part_of, part_value, recreate_node_edits,
196    revert_change,
197};
198pub use source_time::{SourceExtent, SourceTime};
199// The borne-graph identity type (`Node.nested`): part of the node's public
200// surface, re-exported so consumers name it without a direct muniment dep.
201pub use edge_data::{
202    ArrangementData, AssertionData, ContainmentData, EdgeMetrics, ImportedData, ProvenanceData,
203    REL_VOCAB, RelationAssertion, RelationAssertionSpec, SemanticData, SemanticStatement,
204    SemanticStatementSpec, StatementAssert, Traversal, TraversalData, all_semantic_sub_kinds,
205    predicate_iri, sub_kind_from_iri,
206};
207pub use edge_payload::EdgePayload;
208pub use edge_taxonomy::{
209    ArrangementSubKind, ContainmentSubKind, EdgeAssertion, EdgeFamily, ImportedSubKind,
210    NavigationTrigger, ProvenanceSubKind, RelationDurability, RelationKind, RelationSelector,
211    SemanticSubKind,
212};
213pub use muniment::{LogId, Seq};
214
215// Field-system truth types (2026-05-31). Field/Coupling form a parallel field
216// layer beside the node/edge graph; numen reads them and evaluates.
217pub use numen::{
218    COUPLING_VOCAB, Coupling, CouplingId, CouplingResponse, EdgePath, EdgePathRule, Falloff, Field,
219    FieldDefinition, FieldExtent, FieldId, FieldLifecycle, NodeSelector, ScalarField, VectorField,
220};
221
222/// Traversal archive payload emitted when dissolving a node.
223#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
224pub struct DissolvedTraversalRecord {
225    #[rkyv(with = UuidAsBytes)]
226    pub from_node_id: Uuid,
227    #[rkyv(with = UuidAsBytes)]
228    pub to_node_id: Uuid,
229    pub traversals: Vec<Traversal>,
230}
231
232fn normalize_import_record_memberships(memberships: &mut Vec<ImportRecordMembership>) {
233    memberships.sort_by(|left, right| {
234        left.node_id
235            .cmp(&right.node_id)
236            .then_with(|| left.suppressed.cmp(&right.suppressed))
237    });
238    let mut deduped: Vec<ImportRecordMembership> = Vec::with_capacity(memberships.len());
239    for membership in memberships.drain(..) {
240        if let Some(existing) = deduped.last_mut()
241            && existing.node_id == membership.node_id
242        {
243            existing.suppressed &= membership.suppressed;
244            continue;
245        }
246        deduped.push(membership);
247    }
248    *memberships = deduped;
249}
250
251pub(crate) fn normalize_import_records(import_records: &mut Vec<ImportRecord>) {
252    let mut merged = BTreeMap::<String, ImportRecord>::new();
253    for mut record in import_records.drain(..) {
254        normalize_import_record_memberships(&mut record.memberships);
255        if record.record_id.trim().is_empty() {
256            continue;
257        }
258        let entry = merged
259            .entry(record.record_id.clone())
260            .or_insert_with(|| ImportRecord {
261                record_id: record.record_id.clone(),
262                source_id: record.source_id.clone(),
263                source_label: record.source_label.clone(),
264                imported_at_secs: record.imported_at_secs,
265                memberships: Vec::new(),
266            });
267        if entry.source_id.is_empty() {
268            entry.source_id = record.source_id.clone();
269        }
270        if entry.source_label.is_empty() {
271            entry.source_label = record.source_label.clone();
272        }
273        if entry.imported_at_secs == 0 {
274            entry.imported_at_secs = record.imported_at_secs;
275        } else if record.imported_at_secs != 0 {
276            entry.imported_at_secs = entry.imported_at_secs.min(record.imported_at_secs);
277        }
278        entry.memberships.extend(record.memberships);
279    }
280    *import_records = merged.into_values().collect();
281    for record in import_records.iter_mut() {
282        normalize_import_record_memberships(&mut record.memberships);
283    }
284    import_records.sort_by(|left, right| {
285        left.source_label
286            .cmp(&right.source_label)
287            .then_with(|| left.imported_at_secs.cmp(&right.imported_at_secs))
288            .then_with(|| left.record_id.cmp(&right.record_id))
289    });
290}
291
292pub(crate) fn current_unix_timestamp_secs() -> u64 {
293    crate::time::unix_epoch_seconds()
294}
295
296// Node, NodeLifecycle, and impl Node moved to `node.rs` per the
297// 2026-04-30 renderer plan §6.4 decomposition target. Re-exported
298// here so external paths (`kernel::graph::Node`, etc.)
299// resolve unchanged.
300
301/// Canonical read-side relation view. One row per (from, to,
302/// [`RelationKind`]) — a multi-relation node pair yields multiple
303/// rows. Replaces the `EdgeType`-flavoured `EdgeView` removed in
304/// stage 4 of the 2026-05-11 relation-taxonomy plan.
305///
306/// This is the **classifier shape** — it carries no per-relation
307/// payload (labels, decay, traversal events). Callers needing
308/// payload reach for the typed `EdgePayload` sidecar via the
309/// kernel's per-family query methods.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub struct RelationView {
312    pub from: NodeKey,
313    pub to: NodeKey,
314    pub kind: RelationKind,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct SemanticEdgeView {
319    pub from: NodeKey,
320    pub to: NodeKey,
321    pub sub_kind: SemanticSubKind,
322    pub label: Option<String>,
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub struct ArrangementEdgeView {
327    pub from: NodeKey,
328    pub to: NodeKey,
329    pub sub_kind: ArrangementSubKind,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333pub struct ContainmentEdgeView {
334    pub from: NodeKey,
335    pub to: NodeKey,
336    pub sub_kind: ContainmentSubKind,
337}
338
339/// Main graph structure backed by petgraph::StableGraph
340#[derive(Clone)]
341pub struct Graph {
342    /// Runtime-only model input versions, preserved by clones and advanced at
343    /// the existing structural/content/site/visit mutation boundaries.
344    runtime_input_keys: [GraphInputKey; 4],
345    /// The substrate graph: a [`chartulary::Graph`] over mere's [`Node`] and
346    /// [`EdgePayload`] (the G5 re-base — mere's graph *is* a chartulary graph).
347    /// It owns the petgraph topology and the stable id-to-key index (mere's old
348    /// hand-rolled `id_to_node` is retired in its favor). `pub(crate)` to enforce
349    /// the single-write-path boundary at the type level: every topology mutation
350    /// goes through a `Graph` method so it advances [`revision`](Self::revision);
351    /// direct mutation from outside the kernel would bypass the bump and stale the
352    /// structural caches. Reads reach petgraph algorithms through
353    /// [`chartulary::Graph::inner`]. (Graph signals.)
354    pub(crate) inner: chartulary::Graph<Node, EdgePayload>,
355    /// Runtime membership witnesses; cloned with candidates, never snapshotted.
356    surface_node_lifetimes: HashMap<Uuid, SurfaceNodeLifetime>,
357
358    /// Resource truth beneath surfaces, indexed by the prepared identity IRI.
359    pub(crate) resources: chartulary::Graph<ResourceNode, EdgePayload>,
360    /// The one live authority for ordinary resource metadata.
361    pub(crate) resource_facets: chartulary::FacetStore<Uuid>,
362    /// Explicit surface UUID to resource UUID associations.
363    pub(crate) shown_resources: BTreeMap<Uuid, Uuid>,
364
365    /// Atomic optional metadata keyed by stable node id. This is the single
366    /// live authority persisted by the host as `facets.json`; snapshot columns
367    /// are legacy import inputs only.
368    pub(crate) facets: chartulary::FacetStore<Uuid>,
369
370    /// URL to node mapping for lookup (supports duplicate URLs).
371    pub(crate) url_to_nodes: HashMap<String, Vec<NodeKey>>,
372
373    /// Durable imported relation truth; node provenance is derived from this.
374    pub(crate) import_records: Vec<ImportRecord>,
375
376    /// Field-layer truth (field-system step 3, Phase 1): a parallel keyed store
377    /// beside the node/edge petgraph. A coupling targets a *selector* over nodes,
378    /// not a node→node edge, so fields/couplings cannot ride the petgraph; they
379    /// are content truth that numen reads and evaluates (derived).
380    ///
381    /// Ordered by id (the inner UUID, which orders as its canonical string
382    /// does; `FieldId` and `CouplingId` carry no `Ord`), so every read and
383    /// every snapshot sees one order.
384    pub(crate) fields: BTreeMap<Uuid, Field>,
385    pub(crate) couplings: BTreeMap<Uuid, Coupling>,
386
387    /// The graph's whole navigation history: one shared visit space, one owner
388    /// per node (the (b) anchor design). In-place navigation extends a node's own
389    /// path; a branch node is spawned anchored under its origin's current visit.
390    pub(crate) nav: SharedNavigationMemory,
391
392    /// A monotonic **structural revision**, bumped by [`bump_revision`](Self::bump_revision)
393    /// whenever the node/edge structure or a pair's relation set changes (add/remove node, add/
394    /// remove edge, assert/retract a relation). It does NOT bump on a re-visit's traversal append
395    /// or on pure content edits (title/url/tags), since those leave the structure a derived signal
396    /// reads unchanged. The single source of truth any consumer gates a cache on — community,
397    /// arrangements, importance — so a recompute happens once per real change, not per frame.
398    /// (Graph signals — the local counter; cross-owner caches use structural_input_key.)
399    revision: u64,
400
401    /// A monotonic revision for the URL-authority partition used by views such
402    /// as site kanban. URL edits do not change topology, so they deliberately
403    /// do not advance [`revision`](Self::revision); a consumer that groups
404    /// nodes by authority must depend on this narrower signal instead.
405    url_grouping_revision: u64,
406
407    /// A monotonic **content revision**: bumped when a node's text may have
408    /// changed (a node added, copied in or removed, its title set, its
409    /// primary URL moved). Structure, visits, tags, images and facets leave it
410    /// alone. A consumer keyed to node text, such as the canvas's Meaning
411    /// channel, recomputes only when it moves. Not persisted, like
412    /// [`revision`](Self::revision). (Dynamics grammar plan, G2, F33.)
413    content_revision: u64,
414
415    /// A monotonic **visit revision**: bumped whenever a node's visit history
416    /// (`visit.history`) may have changed, through any kernel writer of it, a
417    /// generic facet delta naming it, a sidecar overlay, or mutable facet
418    /// access. Structure and text leave it alone. A consumer keyed to recency,
419    /// such as the channel registry's recency order, recomputes only when it or
420    /// the structural revision moves. Not persisted. (Dynamics grammar plan,
421    /// G2b, F54.)
422    visit_revision: u64,
423
424    /// The current app-launch session number, set once by the host via
425    /// [`set_current_session`](Self::set_current_session) right after construction/
426    /// restore. `0` (the default) means "not wired" — [`navigate_node`](Self::navigate_node)
427    /// then stamps nothing, so by-sessions eviction sees every node as undated until the
428    /// host opts in. Not part of the persisted snapshot: it is per-launch host state, not
429    /// graph truth. (Alembic B5 — by-sessions eviction.)
430    current_session: u64,
431
432    /// Attribution context supplied by the session performing a write.
433    write_author: Author,
434
435    /// Where this graph sends its own captured deltas, once a host opts it in
436    /// with [`set_recorder`](Self::set_recorder). Not graph truth, and not
437    /// carried by a clone.
438    pub(crate) recorder: capture::Recorder,
439    pub(crate) pending_link_state: PendingLinkState,
440    pub(crate) pending_derivation_suppressed: pending_links::Suppression,
441    pub(crate) semantic_observation_revision: u64,
442    pub(crate) appearance_admission_revision: u64,
443    pub(crate) known_coverage: CoverageNote,
444    /// Set only inside a legacy migration's staged scope; see `edge_admission`.
445    pub(crate) staged_edges: edge_admission::StagedEdges,
446}
447
448impl Graph {
449    /// Create a new empty graph
450    pub fn new() -> Self {
451        Self {
452            runtime_input_keys: [GraphInputKey::new_source(); 4],
453            inner: chartulary::Graph::new(),
454            surface_node_lifetimes: HashMap::new(),
455            resources: chartulary::Graph::new(),
456            resource_facets: chartulary::FacetStore::new(),
457            shown_resources: BTreeMap::new(),
458            facets: chartulary::FacetStore::new(),
459            url_to_nodes: HashMap::new(),
460            import_records: Vec::new(),
461            fields: BTreeMap::new(),
462            couplings: BTreeMap::new(),
463            nav: SharedNavigationMemory::empty(),
464            revision: 0,
465            url_grouping_revision: 0,
466            content_revision: 0,
467            visit_revision: 0,
468            current_session: 0,
469            write_author: Author::user(),
470            recorder: capture::Recorder::default(),
471            pending_link_state: PendingLinkState::default(),
472            pending_derivation_suppressed: pending_links::Suppression::default(),
473            semantic_observation_revision: 0,
474            appearance_admission_revision: 0,
475            known_coverage: CoverageNote::default(),
476            staged_edges: Default::default(),
477        }
478    }
479
480    /// Send every delta this graph applies through `apply_graph_delta` to
481    /// `recorder`, or stop with `None`. The per-graph twin of the thread's
482    /// capture hook: a host holding many session graphs records each into its
483    /// own journal. A clone of this graph, and a replay onto it, record nothing.
484    pub fn set_recorder(&mut self, recorder: Option<DeltaRecorder>) {
485        self.recorder.0 = recorder;
486    }
487
488    /// Whether this graph records its deltas.
489    pub fn is_recording(&self) -> bool {
490        self.recorder.0.is_some()
491    }
492
493    /// The recorder identity used when a writer has no attributed source.
494    pub fn write_author(&self) -> &Author {
495        &self.write_author
496    }
497
498    /// Run a write under the same author its journal will record.
499    pub fn write_as<R>(&mut self, author: Author, write: impl FnOnce(&mut Self) -> R) -> R {
500        let previous = std::mem::replace(&mut self.write_author, author);
501        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| write(self)));
502        self.write_author = previous;
503        match result {
504            Ok(value) => value,
505            Err(panic) => std::panic::resume_unwind(panic),
506        }
507    }
508
509    /// Set the current app-launch session number (Alembic B5). The host calls this once,
510    /// right after construction or snapshot-restore, with its persisted-and-incremented
511    /// session counter; every [`navigate_node`](Self::navigate_node) call afterwards stamps
512    /// the visited node's [`Node::last_session_visited`] with this value.
513    pub fn set_current_session(&mut self, session: u64) {
514        self.current_session = session;
515    }
516
517    /// The launch number [`set_current_session`](Self::set_current_session) installed.
518    pub fn current_session(&self) -> u64 {
519        self.current_session
520    }
521
522    /// The current structural revision (see [`revision`](Self::revision)). A consumer captures it
523    /// alongside a derived result and recomputes only when it has advanced. (Graph signals.)
524    pub fn revision(&self) -> u64 {
525        self.revision
526    }
527
528    /// The current URL-authority grouping revision. This advances only when a
529    /// node's primary URL moves between site groups, letting site-grouped
530    /// projections refresh without invalidating structural caches for an
531    /// ordinary same-site navigation.
532    pub fn url_grouping_revision(&self) -> u64 {
533        self.url_grouping_revision
534    }
535
536    /// The current content revision (see the field's doc): it advances on a
537    /// node's title or primary URL changing and on a node joining or leaving,
538    /// never on an edge or relation change.
539    pub fn content_revision(&self) -> u64 {
540        self.content_revision
541    }
542
543    /// The current visit revision (see the field's doc): it advances when a
544    /// node's visit history may have changed, never on structure or text.
545    pub fn visit_revision(&self) -> u64 {
546        self.visit_revision
547    }
548
549    /// The categorical site key used by URL-grouped projections: the authority
550    /// after `://` and before a path, query, or fragment, or the whole hostless
551    /// input. It deliberately retains ports and opaque values.
552    pub fn url_grouping_key(url: &str) -> &str {
553        let after_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
554        after_scheme
555            .split(['/', '?', '#'])
556            .next()
557            .unwrap_or(after_scheme)
558    }
559
560    /// Advance the structural revision. Called by the topology/relation mutators on a real change.
561    /// (Graph signals — the local counter; cross-owner caches use structural_input_key.)
562    fn bump_revision(&mut self) {
563        self.revision = self.revision.wrapping_add(1);
564        self.runtime_input_keys[0].advance();
565    }
566
567    fn bump_url_grouping_revision(&mut self) {
568        self.url_grouping_revision = self.url_grouping_revision.wrapping_add(1);
569        self.runtime_input_keys[2].advance();
570    }
571
572    pub(crate) fn bump_content_revision(&mut self) {
573        self.content_revision = self.content_revision.wrapping_add(1);
574        self.runtime_input_keys[1].advance();
575    }
576
577    pub(crate) fn bump_visit_revision(&mut self) {
578        self.visit_revision = self.visit_revision.wrapping_add(1);
579        self.runtime_input_keys[3].advance();
580    }
581
582    // Durable write boundaries. The Phase 6.5 GraphDelta migration covers
583    // ordinary primitive mutations; assertion lifecycle and predicate
584    // declaration APIs also expose public durable writes and emit captures
585    // directly. A host must install a recorder and apply its admission policy
586    // around either entry point; GraphDelta is not the sole public writer.
587    // The writer classes:
588    //   1. Ordinary primitive mutations (topology, relations, nav history, tags,
589    //      titles, body, media, classifications, properties, predicates,
590    //      fields/couplings, frame hints, import records) — `pub(crate)`,
591    //      reached externally only via `GraphDelta`. Navigation has one primitive
592    //      per operation (`navigate_node`, `branch_history`, `node_history_back`,
593    //      `node_history_forward`) under both the live and the replay arm.
594    //   2. Public native assertion/declaration writes: `assertion_write` and
595    //      `predicate_declarations`, with their own capture emission.
596    //   3. Compound kernel operations stay `pub`: `from_snapshot`,
597    //      `cross_graph::copy_*` — kernel-authored multi-step ops over
598    //      non-delta-able inputs (`&Graph` donors); the "trusted writers".
599    //   4. Transient/runtime state stays `pub`, exempt by design:
600    //      `set_node_position` / `set_node_projected_position` (physics/view —
601    //      positions are not graph truth), `set_current_session` (per-launch
602    //      host wiring). Webview runtime state left the kernel entirely
603    //      (`BrowserNodeState` sidecar, boundary pass slice C).
604    //   5. Test fixtures: the `fixtures` cargo feature re-exposes the raw
605    //      structural mutators via `graph::fixtures::GraphFixtures` —
606    //      dev-dependencies only, never a production enable. Navigation is not
607    //      among them: a fixture graph navigates through `GraphDelta`, so it
608    //      carries what a live navigation leaves.
609
610    /// The fixed namespace for the deterministic node id (see
611    /// [`node_namespace_id`](Self::node_namespace_id)). Fixed forever: changing it
612    /// would renumber every node derived from it.
613    const NODE_NAMESPACE: Uuid = Uuid::from_u128(0x6D65_7265_4E4F_4445_6E61_6D65_7370_6163);
614
615    /// The deterministic node UUID for `url`: a name-based UUIDv5 under
616    /// [`NODE_NAMESPACE`](Self::NODE_NAMESPACE). Two hosts that materialize the
617    /// same `url` mint the same id, so a federated merge needs no identity
618    /// reconciliation. The linked-data ingest layer uses this for a document's
619    /// `@id`, where the URL *is* the identity. Raw [`add_node`] keeps a fresh
620    /// random id, because the kernel treats a node's address as a property and
621    /// lets several nodes share one (see `get_nodes_by_url`).
622    pub fn node_namespace_id(url: &str) -> Uuid {
623        Uuid::new_v5(&Self::NODE_NAMESPACE, url.as_bytes())
624    }
625
626    /// Add a new node to the graph.
627    ///
628    /// Not available on `wasm32`; use [`add_node_with_id`] with a host-provided
629    /// UUID (e.g. from [`node_namespace_id`](Self::node_namespace_id)) instead.
630    #[cfg(not(target_arch = "wasm32"))]
631    pub(crate) fn add_node(&mut self, url: String, position: Point2D<f32>) -> NodeKey {
632        self.add_node_with_id(Uuid::new_v4(), url, position)
633    }
634
635    /// Add a node with a pre-existing UUID, or return the key of the node that
636    /// already holds it ([`insert_node_if_missing`](Self::insert_node_if_missing)).
637    pub(crate) fn add_node_with_id(
638        &mut self,
639        id: Uuid,
640        url: String,
641        position: Point2D<f32>,
642    ) -> NodeKey {
643        self.insert_node_if_missing(id, url, position).0
644    }
645
646    /// The insertion contract shared by live `AddNode` and replay: insert if
647    /// the id is missing, else leave the existing node, its address and its URL
648    /// index entries as they are. The flag reports whether a node was inserted.
649    /// `_position` is the caller's initial placement hint; it is no longer
650    /// stored on the node (position is not graph truth), so the host applies it
651    /// to seiche / the cartography sidecar.
652    pub(crate) fn insert_node_if_missing(
653        &mut self,
654        id: Uuid,
655        url: String,
656        _position: Point2D<f32>,
657    ) -> (NodeKey, bool) {
658        let primary_address = address_from_url(&url);
659        let mut container = chartulary::Container::with_identity(id)
660            .with_address_record(primary_address)
661            .with_title(url.clone());
662        container.media_type = detect_mime(&url, None);
663        let (key, inserted) = self.insert_surface_node(Node {
664            container,
665            images: std::collections::BTreeMap::new(),
666        });
667        if inserted {
668            self.set_node_last_visited_at_ms(key, Self::epoch_ms());
669            self.url_to_nodes.entry(url).or_default().push(key);
670            self.bump_revision();
671            self.bump_content_revision();
672        }
673        (key, inserted)
674    }
675
676    /// Remove a node and all its connected edges
677    pub(crate) fn remove_node(&mut self, key: NodeKey) -> bool {
678        if let Some(node) = self.inner.remove(key) {
679            // The node's navigation owner is intentionally *kept* in the shared
680            // visit space: a node branched from it still anchors to its visits, so
681            // erasing the lineage on node removal would orphan those anchors. The
682            // owner is simply never queried once the node is gone (pruning belongs
683            // to a future GC / `eidetic` scope, not graph removal).
684            // Deregister every URL claim this node carried — Primary plus
685            // any aliases. (Aliases are not yet wired into add paths but the
686            // index handles them when they land.)
687            for address in &node.addresses {
688                self.remove_url_mapping(address.as_url_str(), key);
689            }
690            let node_id = node.id;
691            self.surface_node_lifetimes.remove(&node_id);
692            self.shown_resources.remove(&node_id);
693            self.remove_facets_for_node(node_id);
694            let removed_id = node_id.to_string();
695            for record in &mut self.import_records {
696                record
697                    .memberships
698                    .retain(|membership| membership.node_id != removed_id);
699            }
700            self.import_records
701                .retain(|record| !record.memberships.is_empty());
702            self.bump_revision();
703            self.bump_content_revision();
704            true
705        } else {
706            false
707        }
708    }
709
710    /// Write a node's primary address, maintaining the url_to_nodes index.
711    /// Returns the old URL, or None if the node doesn't exist.
712    ///
713    /// The one writer of the address. `SetNodeUrl` calls it alone, changing the
714    /// address with no visit; [`navigate_node`](Self::navigate_node) calls it
715    /// after recording the visit, and a history step after moving the cursor
716    /// (`land_history_step`). The Stemma cursor is the browse trail's position,
717    /// not the address; see the `history` module.
718    ///
719    /// Operates on the Primary claim only; aliases (when supported) stay
720    /// attached. To mutate aliases, use dedicated alias methods (future).
721    pub(crate) fn update_node_url(&mut self, key: NodeKey, new_url: String) -> Option<String> {
722        let node = self.inner.node_mut(key)?;
723        let old_url = node.primary_address().as_url_str().to_string();
724        let host_changed = cached_host_from_url(&old_url) != cached_host_from_url(&new_url);
725        let site_group_changed =
726            Self::url_grouping_key(&old_url) != Self::url_grouping_key(&new_url);
727        // A navigation to a different host invalidates the favicon (it was the old
728        // site's icon); clear it so a stale favicon does not linger on the tile until
729        // the new one loads. A same-host path change keeps it. (Favicon-on-tile.)
730        if host_changed {
731            node.clear_image(crate::types::ImageRole::Favicon);
732        }
733        // Primary-first is Container's address-role mapping. Replace index 0;
734        // aliases (the rest) stay attached.
735        let new_primary_address = address_from_url(&new_url);
736        if let Some(primary) = node.addresses.first_mut() {
737            *primary = new_primary_address;
738        }
739        let url_changed = old_url != new_url;
740        self.remove_url_mapping(&old_url, key);
741        self.url_to_nodes.entry(new_url).or_default().push(key);
742        if site_group_changed {
743            self.bump_url_grouping_revision();
744        }
745        if url_changed {
746            self.bump_content_revision();
747        }
748        Some(old_url)
749    }
750
751    /// Establish the current page binding for a live write, retaining an
752    /// already recorded binding. Legacy replay does not call this helper.
753    pub(crate) fn ensure_surface_resource(&mut self, key: NodeKey) -> Option<Uuid> {
754        self.shown_resource_id(key)
755            .or_else(|| self.refresh_surface_resource(key))
756    }
757
758    /// Refresh a live surface's page binding after its surface mutation has
759    /// been captured. The resource record precedes the shown association.
760    pub(crate) fn refresh_surface_resource(&mut self, key: NodeKey) -> Option<Uuid> {
761        let node = self.get_node(key)?;
762        let surface_id = node.id;
763        let resource = ResourceNode::new(node.primary_address().as_url_str());
764        let resource_id = resource.id();
765        if self.resource(resource_id).is_none() {
766            let record = crate::persistence::PersistedResourceRecord {
767                canonical_iri: resource.canonical_iri().to_string(),
768                facets: Vec::new(),
769            };
770            if !self.set_resource_record(resource_id, Some(record.clone())) {
771                return None;
772            }
773            self.record_delta(&CapturedDelta::ReplaySetResourceRecordById {
774                resource_id: resource_id.to_string(),
775                record: Some(record),
776            });
777        }
778        if self.set_shown_resource(surface_id, Some(resource_id)) {
779            self.record_delta(&CapturedDelta::ReplaySetShownResourceById {
780                surface_id: surface_id.to_string(),
781                resource_id: Some(resource_id.to_string()),
782            });
783        }
784        Some(resource_id)
785    }
786
787    /// Navigate `key` in place to `url`: record the visit in the node's own
788    /// browse history (a forward-fork if the cursor had stepped back), write
789    /// `url` as its primary address, and stamp its recency at `at_ms` and its
790    /// session. A visit moves the trail and the address together; `SetNodeUrl`
791    /// moves the address alone. No new node and no edge: the node is a browsing
792    /// surface whose content changes; the graph shape does not. Cross-node
793    /// lineage (the navigated-from relation) is a separate, explicit edge.
794    ///
795    /// The one mutation under both the live and the replayed arm, which differ
796    /// only in the stamp they pass. Returns the node's id, or `None` if absent.
797    pub(crate) fn navigate_node(
798        &mut self,
799        key: NodeKey,
800        url: &str,
801        transition: NodeHistoryTransitionKind,
802        at_ms: u64,
803        last_session_visited: u64,
804    ) -> Option<Uuid> {
805        let id = self.inner.node(key)?.id;
806        self.nav.record_visit(id, url, transition, at_ms);
807        self.set_node_last_session_visited(key, last_session_visited);
808        self.update_node_url(key, url.to_string());
809        self.set_node_last_visited_at_ms(key, at_ms);
810        Some(id)
811    }
812
813    /// Anchor a freshly-minted `child` node's history under `parent`'s current
814    /// visit, the navigated-from anchor. Do this **before** the child's first
815    /// [`navigate_node`](Self::navigate_node) so that first visit attaches there
816    /// in the shared lineage tree (the (b) cross-node anchor; the branch-mint
817    /// path). Returns the `(child, parent)` ids, or `None` if either is absent.
818    pub(crate) fn branch_history(
819        &mut self,
820        child: NodeKey,
821        parent: NodeKey,
822    ) -> Option<(Uuid, Uuid)> {
823        let child_id = self.inner.node(child)?.id;
824        let parent_id = self.inner.node(parent)?.id;
825        self.nav.spawn(child_id, parent_id);
826        Some((child_id, parent_id))
827    }
828
829    /// Step `key` back one visit in its own history, updating its Primary URL to
830    /// the revealed page. Returns the new URL, or `None` if already at the root.
831    pub(crate) fn node_history_back(&mut self, key: NodeKey, at_ms: u64) -> Option<String> {
832        let id = self.inner.node(key)?.id;
833        let url = self.nav.back(id, at_ms)?;
834        self.land_history_step(key, &url, at_ms);
835        Some(url)
836    }
837
838    /// Step `key` forward one visit in its own history. Returns the new URL, or
839    /// `None` if already at the tip.
840    pub(crate) fn node_history_forward(&mut self, key: NodeKey, at_ms: u64) -> Option<String> {
841        let id = self.inner.node(key)?.id;
842        let url = self.nav.forward(id, at_ms)?;
843        self.land_history_step(key, &url, at_ms);
844        Some(url)
845    }
846
847    /// What a moved history cursor leaves on the node: the revealed page as its
848    /// primary address, and the step as its latest visit. The one place history
849    /// writes the address: the cursor is the trail's position, and a step lands
850    /// its page on the address even where a `SetNodeUrl` has moved it since.
851    fn land_history_step(&mut self, key: NodeKey, url: &str, at_ms: u64) {
852        self.update_node_url(key, url.to_string());
853        self.set_node_last_visited_at_ms(key, at_ms);
854    }
855
856    /// Whether `key`'s within-node history can step back (toolbar gating).
857    pub fn node_can_back(&self, key: NodeKey) -> bool {
858        self.inner
859            .node(key)
860            .is_some_and(|n| self.nav.can_back(n.id))
861    }
862
863    /// Whether `key`'s within-node history can step forward (toolbar gating).
864    pub fn node_can_forward(&self, key: NodeKey) -> bool {
865        self.inner
866            .node(key)
867            .is_some_and(|n| self.nav.can_forward(n.id))
868    }
869
870    /// `key`'s linear-history projection (active path + cursor).
871    pub fn node_history_projection(&self, key: NodeKey) -> NodeHistoryProjection {
872        match self.inner.node(key) {
873            Some(node) => self.nav.projection(node.id),
874            None => NodeHistoryProjection {
875                entries: Vec::new(),
876                current_index: 0,
877            },
878        }
879    }
880
881    /// `key`'s branching-history projection (visit tree with alternates).
882    pub fn node_history_branch_projection(&self, key: NodeKey) -> NodeHistoryBranchProjection {
883        self.inner
884            .node(key)
885            .map(|node| self.nav.branch_projection(node.id))
886            .unwrap_or_default()
887    }
888
889    /// A coarse semantic summary of `key`'s history.
890    pub fn node_history_semantic_summary(&self, key: NodeKey) -> NodeHistorySemanticSummary {
891        self.inner
892            .node(key)
893            .map(|node| self.nav.semantic_summary(node.id))
894            .unwrap_or_default()
895    }
896
897    /// Milliseconds since the Unix epoch, for visit timestamps (live-app clock).
898    fn epoch_ms() -> u64 {
899        crate::time::unix_epoch_millis()
900    }
901}
902
903// Edge mutators (add_edge, assert_relation, replay_*, dissolve_*,
904// remove_edges, retract_relations, get_edge*, push_traversal) live in
905// `graph/edge_ops.rs` (2026-05-11 decomposition pass).
906pub mod edge_ops;
907
908// Query + traversal (node/edge lookups, neighbor iteration, BFS /
909// shortest-path / connected-components / SCC, derived-edge views)
910// live in `graph/query.rs` (2026-05-11 decomposition pass).
911pub mod query;
912
913// `node_display_label`: a human-meaningful label derived from a node's title /
914// linked-data role / @type / address, for the canvas tiles + roster (so an
915// anonymous ingested entity reads as "publisher" / "Organization", not a raw
916// `urn:mere:bnode:` string).
917pub mod display;
918
919// Snapshot serialization (`to_snapshot` / `from_snapshot`), the rkyv
920// trait impls that delegate through them, `containment_parent_url`,
921// and `impl Default for Graph` live in `graph/snapshot.rs`
922// (2026-05-11 decomposition pass).
923pub mod snapshot;
924
925// Tests live in `graph/tests.rs` to keep this file under the
926// 600-LOC ceiling (kernel decomposition pass 2026-05-11).
927#[cfg(test)]
928mod tests;
929
930#[cfg(test)]
931#[path = "tests/resource_lifecycle.rs"]
932mod resource_lifecycle_tests;