Skip to main content

kernel/graph/
mod.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Graph data structures for the spatial browser.
5//!
6//! Core structures:
7//! - `Graph`: Main graph container backed by petgraph::StableGraph
8//! - `Node`: Webpage node with a transient projected position and metadata
9//! - `EdgePayload`: Edge semantics and traversal events between nodes
10//!
11//! This module is WASM-clean: it must compile to `wasm32-unknown-unknown`.
12
13use euclid::default::Point2D;
14// `MemoryEntryPrivacy` / `OwnerScopedMemory` / `GraphMemorySnapshot` /
15// `MemoryTransitionKind` were used by the node-history types that
16// moved to `history.rs` (2026-05-11 decomposition pass); `Graph` itself
17// doesn't reach into node-lineage directly.
18use petgraph::algo::{astar, dijkstra, has_path_connecting, kosaraju_scc};
19#[cfg(test)]
20use petgraph::stable_graph::NodeIndex;
21use petgraph::visit::{EdgeRef, IntoEdgeReferences};
22use rkyv::{Archive, Archived, Deserialize, Place, Resolver, Serialize, rancor::Fallible};
23use std::collections::{BTreeMap, HashMap, HashSet};
24use uuid::Uuid;
25
26pub use chartulary::stemma::TransitionKind as NodeHistoryTransitionKind;
27/// The stable address of a node's out-of-line representation.
28pub use muniment::Hash as ContentHash;
29
30use crate::address::{Address, AddressKind, address_from_url, cached_host_from_url, detect_mime};
31use crate::persistence::{
32    GraphSnapshot, PersistedAddress, PersistedArrangementEdgeData, PersistedArrangementSubKind,
33    PersistedContainmentEdgeData, PersistedContainmentSubKind, PersistedEdge, PersistedEdgeFamily,
34    PersistedImportedEdgeData, PersistedImportedSubKind, PersistedNavigationTrigger, PersistedNode,
35    PersistedNodeSessionState, PersistedProvenanceEdgeData, PersistedProvenanceSubKind,
36    PersistedSemanticEdgeData, PersistedSemanticSubKind, PersistedTraversalEdgeData,
37    PersistedTraversalMetrics, PersistedTraversalRecord,
38};
39#[allow(unused_imports)] // Some used only in #[cfg(test)]
40use crate::types::{
41    ClassificationProvenance, ClassificationScheme, ClassificationStatus, DominantEdge,
42    FrameLayoutHint, FrameLayoutNodeId, GraphScope, ImportRecord, ImportRecordMembership,
43    NodeClassification, NodeImportProvenance, NodeImportRecordSummary, NodeTagPresentationState,
44    SplitOrientation, format_imported_at_secs,
45};
46
47pub mod apply;
48pub mod capture;
49/// Cross-graph node copy (tear-out fork): mints a node in this graph from a
50/// donor node in another graph, recording cross-graph derivation provenance.
51pub mod cross_graph;
52/// The edit spine: mere's captured-delta stream as a `codicil` log, replayed into
53/// the graph (the substrate's append-only-log primitive over mere's own edit
54/// vocabulary). See `graph/journal.rs`.
55pub mod journal;
56pub use cross_graph::ComponentCopy;
57pub mod edge_data;
58pub mod edge_payload;
59pub mod edge_taxonomy;
60pub mod facet_projection;
61pub mod filter;
62/// Test-fixture escape hatch over the `pub(crate)` mutators (write-path
63/// migration). Feature-gated: enable `fixtures` in dev-dependencies only.
64#[cfg(feature = "fixtures")]
65pub mod fixtures;
66pub mod history;
67pub mod identity;
68pub mod import_records;
69pub mod node;
70pub mod node_facets;
71pub mod node_props;
72pub mod source_time;
73// chartulary capability-trait impls for `Node` (graph re-base, G5).
74mod chart;
75
76// Field system: the field-layer definition types (Field / Coupling / the field AST /
77// EdgePath) live in the portable `numen` crate, promoted out of the kernel so the
78// third graph primitive sits at the same portable tier as chartulary's nodes/edges.
79// The kernel keeps the parallel keyed store on `Graph` (fields/couplings are neither
80// petgraph node weights nor `EdgePayload` sidecars) and re-exports numen's types.
81/// Graph mutators + queries for the field layer (Phase 1): the parallel keyed store
82/// on `Graph` + selector evaluation. The field-layer *definition* types (Field /
83/// Coupling / the field AST / EdgePath) now live in the portable `numen` crate,
84/// re-exported below so `kernel::graph::` paths stay stable.
85mod field_ops;
86
87// Identity types and rkyv archive helpers extracted to `identity.rs`
88// per the 2026-04-30 renderer plan §6.4 decomposition target. Public
89// types are re-exported at this module path so external callers
90// (`kernel::graph::NodeKey`, etc.) continue to resolve;
91// the rkyv `with = ...` archive helpers are crate-internal and used
92// only by struct field annotations in this file.
93pub(crate) use identity::UuidAsBytes;
94pub use identity::{EdgeKey, GraphDirection, GraphIndex, GraphViewId, NodeKey};
95
96// Node + NodeLifecycle extracted to `node.rs` per the same
97// decomposition target. Re-exported so `kernel::graph::Node`
98// continues to resolve.
99pub use node::Node;
100pub use node_facets::{NodeFacetStore, VisitHistoryFacet};
101
102// Node navigation history extracted to `history.rs` (2026-05-11
103// kernel-mod decomposition pass). Re-exported so external callers
104// (`kernel::graph::NodeNavigationMemory`, etc.) keep resolving.
105pub use history::{
106    NodeHistoryBranchAlternative, NodeHistoryBranchProjection, NodeHistoryBranchVisit,
107    NodeHistoryOwner, NodeHistoryProjection, NodeHistorySemanticSummary, RecentVisit,
108    SharedNavigationMemory,
109};
110
111// Edge taxonomy (family/sub-kind enums) and per-family runtime data structs
112// extracted to their own modules. edge_taxonomy holds classifiers; edge_data
113// holds runtime payload types (Data structs, Traversal, EdgeMetrics, IRI fns).
114// Stage 4 of the 2026-05-11 relation-taxonomy plan removed `EdgeType` and
115// `EdgeKind`; reads go through [`RelationKind`] + [`RelationSelector`], writes
116// through [`EdgeAssertion`].
117pub use capture::{
118    CapturedDelta, GraphTableStats, replay_captured_deltas, replay_captured_deltas_onto,
119    set_captured_delta_hook,
120};
121pub use journal::{AttributedDelta, GraphJournal, USER_AUTHOR, journal_capture_hook};
122pub use source_time::{SourceExtent, SourceTime};
123// The borne-graph identity type (`Node.nested`): part of the node's public
124// surface, re-exported so consumers name it without a direct codicil dep.
125pub use codicil::{LogId, Seq};
126pub use edge_data::{
127    ArrangementData, ContainmentData, EdgeMetrics, ImportedData, ProvenanceData, REL_VOCAB,
128    SemanticData, SemanticStatement, SemanticStatementSpec, StatementAssert, Traversal,
129    TraversalData, all_semantic_sub_kinds, predicate_iri, sub_kind_from_iri,
130};
131pub use edge_payload::EdgePayload;
132pub use edge_taxonomy::{
133    ArrangementSubKind, ContainmentSubKind, EdgeAssertion, EdgeFamily, ImportedSubKind,
134    NavigationTrigger, ProvenanceSubKind, RelationDurability, RelationKind, RelationSelector,
135    SemanticSubKind,
136};
137
138// Field-system truth types (2026-05-31). Field/Coupling form a parallel field
139// layer beside the node/edge graph; quint reads them and evaluates.
140pub use numen::{
141    COUPLING_VOCAB, Coupling, CouplingId, CouplingResponse, EdgePath, EdgePathRule, Falloff, Field,
142    FieldDefinition, FieldExtent, FieldId, FieldLifecycle, NodeSelector, ScalarField, VectorField,
143};
144
145/// Traversal archive payload emitted when dissolving a node.
146#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
147pub struct DissolvedTraversalRecord {
148    #[rkyv(with = UuidAsBytes)]
149    pub from_node_id: Uuid,
150    #[rkyv(with = UuidAsBytes)]
151    pub to_node_id: Uuid,
152    pub traversals: Vec<Traversal>,
153}
154
155fn normalize_import_record_memberships(memberships: &mut Vec<ImportRecordMembership>) {
156    memberships.sort_by(|left, right| {
157        left.node_id
158            .cmp(&right.node_id)
159            .then_with(|| left.suppressed.cmp(&right.suppressed))
160    });
161    let mut deduped: Vec<ImportRecordMembership> = Vec::with_capacity(memberships.len());
162    for membership in memberships.drain(..) {
163        if let Some(existing) = deduped.last_mut()
164            && existing.node_id == membership.node_id
165        {
166            existing.suppressed &= membership.suppressed;
167            continue;
168        }
169        deduped.push(membership);
170    }
171    *memberships = deduped;
172}
173
174pub(crate) fn normalize_import_records(import_records: &mut Vec<ImportRecord>) {
175    let mut merged = BTreeMap::<String, ImportRecord>::new();
176    for mut record in import_records.drain(..) {
177        normalize_import_record_memberships(&mut record.memberships);
178        if record.record_id.trim().is_empty() {
179            continue;
180        }
181        let entry = merged
182            .entry(record.record_id.clone())
183            .or_insert_with(|| ImportRecord {
184                record_id: record.record_id.clone(),
185                source_id: record.source_id.clone(),
186                source_label: record.source_label.clone(),
187                imported_at_secs: record.imported_at_secs,
188                memberships: Vec::new(),
189            });
190        if entry.source_id.is_empty() {
191            entry.source_id = record.source_id.clone();
192        }
193        if entry.source_label.is_empty() {
194            entry.source_label = record.source_label.clone();
195        }
196        if entry.imported_at_secs == 0 {
197            entry.imported_at_secs = record.imported_at_secs;
198        } else if record.imported_at_secs != 0 {
199            entry.imported_at_secs = entry.imported_at_secs.min(record.imported_at_secs);
200        }
201        entry.memberships.extend(record.memberships);
202    }
203    *import_records = merged.into_values().collect();
204    for record in import_records.iter_mut() {
205        normalize_import_record_memberships(&mut record.memberships);
206    }
207    import_records.sort_by(|left, right| {
208        left.source_label
209            .cmp(&right.source_label)
210            .then_with(|| left.imported_at_secs.cmp(&right.imported_at_secs))
211            .then_with(|| left.record_id.cmp(&right.record_id))
212    });
213}
214
215pub(crate) fn current_unix_timestamp_secs() -> u64 {
216    crate::time::unix_epoch_seconds()
217}
218
219// Node, NodeLifecycle, and impl Node moved to `node.rs` per the
220// 2026-04-30 renderer plan §6.4 decomposition target. Re-exported
221// here so external paths (`kernel::graph::Node`, etc.)
222// resolve unchanged.
223
224/// Canonical read-side relation view. One row per (from, to,
225/// [`RelationKind`]) — a multi-relation node pair yields multiple
226/// rows. Replaces the `EdgeType`-flavoured `EdgeView` removed in
227/// stage 4 of the 2026-05-11 relation-taxonomy plan.
228///
229/// This is the **classifier shape** — it carries no per-relation
230/// payload (labels, decay, traversal events). Callers needing
231/// payload reach for the typed `EdgePayload` sidecar via the
232/// kernel's per-family query methods.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
234pub struct RelationView {
235    pub from: NodeKey,
236    pub to: NodeKey,
237    pub kind: RelationKind,
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct SemanticEdgeView {
242    pub from: NodeKey,
243    pub to: NodeKey,
244    pub sub_kind: SemanticSubKind,
245    pub label: Option<String>,
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub struct ArrangementEdgeView {
250    pub from: NodeKey,
251    pub to: NodeKey,
252    pub sub_kind: ArrangementSubKind,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub struct ContainmentEdgeView {
257    pub from: NodeKey,
258    pub to: NodeKey,
259    pub sub_kind: ContainmentSubKind,
260}
261
262/// Main graph structure backed by petgraph::StableGraph
263#[derive(Clone)]
264pub struct Graph {
265    /// The substrate graph: a [`chartulary::Graph`] over mere's [`Node`] and
266    /// [`EdgePayload`] (the G5 re-base — mere's graph *is* a chartulary graph).
267    /// It owns the petgraph topology and the stable id-to-key index (mere's old
268    /// hand-rolled `id_to_node` is retired in its favor). `pub(crate)` to enforce
269    /// the single-write-path boundary at the type level: every topology mutation
270    /// goes through a `Graph` method so it advances [`revision`](Self::revision);
271    /// direct mutation from outside the kernel would bypass the bump and stale the
272    /// structural caches. Reads reach petgraph algorithms through
273    /// [`chartulary::Graph::inner`]. (Graph signals.)
274    pub(crate) inner: chartulary::Graph<Node, EdgePayload>,
275
276    /// Atomic optional metadata keyed by stable node id. This is the single
277    /// live authority persisted by the host as `facets.json`; snapshot columns
278    /// are legacy import inputs only.
279    pub(crate) facets: chartulary::FacetStore<Uuid>,
280
281    /// URL to node mapping for lookup (supports duplicate URLs).
282    pub(crate) url_to_nodes: HashMap<String, Vec<NodeKey>>,
283
284    /// Durable imported relation truth; node provenance is derived from this.
285    pub(crate) import_records: Vec<ImportRecord>,
286
287    /// Field-layer truth (field-system step 3, Phase 1): a parallel keyed store
288    /// beside the node/edge petgraph. A coupling targets a *selector* over nodes,
289    /// not a node→node edge, so fields/couplings cannot ride the petgraph; they
290    /// are content truth that `quint` reads and evaluates (derived).
291    pub(crate) fields: HashMap<FieldId, Field>,
292    pub(crate) couplings: HashMap<CouplingId, Coupling>,
293
294    /// The graph's whole navigation history: one shared visit space, one owner
295    /// per node (the (b) anchor design). In-place navigation extends a node's own
296    /// path; a branch node is spawned anchored under its origin's current visit.
297    pub(crate) nav: SharedNavigationMemory,
298
299    /// A monotonic **structural revision**, bumped by [`bump_revision`](Self::bump_revision)
300    /// whenever the node/edge structure or a pair's relation set changes (add/remove node, add/
301    /// remove edge, assert/retract a relation). It does NOT bump on a re-visit's traversal append
302    /// or on pure content edits (title/url/tags), since those leave the structure a derived signal
303    /// reads unchanged. The single source of truth any consumer gates a cache on — community,
304    /// arrangements, importance — so a recompute happens once per real change, not per frame.
305    /// (Graph signals — the universal cache key.)
306    revision: u64,
307
308    /// The current app-launch session number, set once by the host via
309    /// [`set_current_session`](Self::set_current_session) right after construction/
310    /// restore. `0` (the default) means "not wired" — [`navigate_node`](Self::navigate_node)
311    /// then stamps nothing, so by-sessions eviction sees every node as undated until the
312    /// host opts in. Not part of the persisted snapshot: it is per-launch host state, not
313    /// graph truth. (Alembic B5 — by-sessions eviction.)
314    current_session: u64,
315}
316
317impl Graph {
318    /// Create a new empty graph
319    pub fn new() -> Self {
320        Self {
321            inner: chartulary::Graph::new(),
322            facets: chartulary::FacetStore::new(),
323            url_to_nodes: HashMap::new(),
324            import_records: Vec::new(),
325            fields: HashMap::new(),
326            couplings: HashMap::new(),
327            nav: SharedNavigationMemory::empty(),
328            revision: 0,
329            current_session: 0,
330        }
331    }
332
333    /// Set the current app-launch session number (Alembic B5). The host calls this once,
334    /// right after construction or snapshot-restore, with its persisted-and-incremented
335    /// session counter; every [`navigate_node`](Self::navigate_node) call afterwards stamps
336    /// the visited node's [`Node::last_session_visited`] with this value.
337    pub fn set_current_session(&mut self, session: u64) {
338        self.current_session = session;
339    }
340
341    /// The current structural revision (see [`revision`](Self::revision)). A consumer captures it
342    /// alongside a derived result and recomputes only when it has advanced. (Graph signals.)
343    pub fn revision(&self) -> u64 {
344        self.revision
345    }
346
347    /// Advance the structural revision. Called by the topology/relation mutators on a real change.
348    /// (Graph signals — the universal cache key.)
349    fn bump_revision(&mut self) {
350        self.revision = self.revision.wrapping_add(1);
351    }
352
353    // Single-write-path boundary (Phase 6.5 — ENFORCED as of the 2026-07-01
354    // write-path migration). Every primitive durable mutator on `Graph` is
355    // `pub(crate)`; external code routes through `apply::apply_graph_delta`
356    // (the one funnel a future recording hook — the event log — instruments).
357    // The four writer classes:
358    //   1. Primitive durable mutations (topology, relations, nav history, tags,
359    //      titles, body, media, classifications, properties, predicates,
360    //      fields/couplings, frame hints, import records) — `pub(crate)`,
361    //      reached externally only via `GraphDelta`.
362    //   2. Compound kernel operations stay `pub`: `from_snapshot`,
363    //      `cross_graph::copy_*` — kernel-authored multi-step ops over
364    //      non-delta-able inputs (`&Graph` donors); the "trusted writers".
365    //   3. Transient/runtime state stays `pub`, exempt by design:
366    //      `set_node_position` / `set_node_projected_position` (physics/view —
367    //      positions are not graph truth), `set_current_session` (per-launch
368    //      host wiring). Webview runtime state left the kernel entirely
369    //      (`BrowserNodeState` sidecar, boundary pass slice C).
370    //   4. Test fixtures: the `fixtures` cargo feature re-exposes the raw
371    //      mutators via `graph::fixtures::GraphFixtures` — dev-dependencies
372    //      only, never a production enable.
373
374    /// The fixed namespace for the deterministic node id (see
375    /// [`node_namespace_id`](Self::node_namespace_id)). Fixed forever: changing it
376    /// would renumber every node derived from it.
377    const NODE_NAMESPACE: Uuid = Uuid::from_u128(0x6D65_7265_4E4F_4445_6E61_6D65_7370_6163);
378
379    /// The deterministic node UUID for `url`: a name-based UUIDv5 under
380    /// [`NODE_NAMESPACE`](Self::NODE_NAMESPACE). Two hosts that materialize the
381    /// same `url` mint the same id, so a federated merge needs no identity
382    /// reconciliation. The linked-data ingest layer uses this for a document's
383    /// `@id`, where the URL *is* the identity. Raw [`add_node`] keeps a fresh
384    /// random id, because the kernel treats a node's address as a property and
385    /// lets several nodes share one (see `get_nodes_by_url`).
386    pub fn node_namespace_id(url: &str) -> Uuid {
387        Uuid::new_v5(&Self::NODE_NAMESPACE, url.as_bytes())
388    }
389
390    /// Add a new node to the graph.
391    ///
392    /// Not available on `wasm32`; use [`add_node_with_id`] with a host-provided
393    /// UUID (e.g. from [`node_namespace_id`](Self::node_namespace_id)) instead.
394    #[cfg(not(target_arch = "wasm32"))]
395    pub(crate) fn add_node(&mut self, url: String, position: Point2D<f32>) -> NodeKey {
396        self.add_node_with_id(Uuid::new_v4(), url, position)
397    }
398
399    /// Add a node with a pre-existing UUID. `_position` is the caller's initial
400    /// placement hint; it is no longer stored on the node (position is not graph
401    /// truth), so the host applies it to seiche / the cartography sidecar.
402    pub(crate) fn add_node_with_id(
403        &mut self,
404        id: Uuid,
405        url: String,
406        _position: Point2D<f32>,
407    ) -> NodeKey {
408        let primary_address = address_from_url(&url);
409        let mut container = chartulary::Container::with_identity(id)
410            .with_address_record(primary_address)
411            .with_title(url.clone());
412        container.media_type = detect_mime(&url, None);
413        let key = self.inner.insert(Node {
414            container,
415            images: std::collections::BTreeMap::new(),
416        });
417        self.set_node_last_visited_at_ms(key, Self::epoch_ms());
418
419        self.url_to_nodes.entry(url).or_default().push(key);
420        self.bump_revision();
421        key
422    }
423
424    /// Remove a node and all its connected edges
425    pub(crate) fn remove_node(&mut self, key: NodeKey) -> bool {
426        if let Some(node) = self.inner.remove(key) {
427            // The node's navigation owner is intentionally *kept* in the shared
428            // visit space: a node branched from it still anchors to its visits, so
429            // erasing the lineage on node removal would orphan those anchors. The
430            // owner is simply never queried once the node is gone (pruning belongs
431            // to a future GC / `eidetic` scope, not graph removal).
432            // Deregister every URL claim this node carried — Primary plus
433            // any aliases. (Aliases are not yet wired into add paths but the
434            // index handles them when they land.)
435            for address in &node.addresses {
436                self.remove_url_mapping(address.as_url_str(), key);
437            }
438            let node_id = node.id;
439            self.remove_facets_for_node(node_id);
440            let removed_id = node_id.to_string();
441            for record in &mut self.import_records {
442                record
443                    .memberships
444                    .retain(|membership| membership.node_id != removed_id);
445            }
446            self.import_records
447                .retain(|record| !record.memberships.is_empty());
448            self.bump_revision();
449            true
450        } else {
451            false
452        }
453    }
454
455    /// Update a node's Primary URL, maintaining the url_to_nodes index.
456    /// Returns the old URL, or None if the node doesn't exist.
457    ///
458    /// Operates on the Primary claim only; aliases (when supported) stay
459    /// attached. To mutate aliases, use dedicated alias methods (future).
460    pub(crate) fn update_node_url(&mut self, key: NodeKey, new_url: String) -> Option<String> {
461        let node = self.inner.node_mut(key)?;
462        let old_url = node.primary_address().as_url_str().to_string();
463        // A navigation to a different host invalidates the favicon (it was the old
464        // site's icon); clear it so a stale favicon does not linger on the tile until
465        // the new one loads. A same-host path change keeps it. (Favicon-on-tile.)
466        if cached_host_from_url(&old_url) != cached_host_from_url(&new_url) {
467            node.clear_image(crate::types::ImageRole::Favicon);
468        }
469        // Primary-first is Container's address-role mapping. Replace index 0;
470        // aliases (the rest) stay attached.
471        let new_primary_address = address_from_url(&new_url);
472        if let Some(primary) = node.addresses.first_mut() {
473            *primary = new_primary_address;
474        }
475        self.remove_url_mapping(&old_url, key);
476        self.url_to_nodes.entry(new_url).or_default().push(key);
477        Some(old_url)
478    }
479
480    /// Navigate `key` in place to `url`: record the visit in the node's own
481    /// browse history (a forward-fork if the cursor had stepped back) and update
482    /// its Primary URL. No new node and no edge — the node is a browsing surface
483    /// whose content changes; the graph shape does not. Cross-node lineage
484    /// (the navigated-from relation) is a separate, explicit edge.
485    pub(crate) fn navigate_node(&mut self, key: NodeKey, url: &str) {
486        let at_ms = Self::epoch_ms();
487        if let Some(id) = self.inner.node(key).map(|n| n.id) {
488            self.nav
489                .record_visit(id, url, chartulary::stemma::TransitionKind::UrlTyped, at_ms);
490        }
491        self.set_node_last_session_visited(key, self.current_session);
492        self.update_node_url(key, url.to_string());
493    }
494
495    /// Anchor a freshly-minted `child` node's history under `parent`'s current
496    /// visit — the navigated-from anchor. Call **before** the child's first
497    /// [`navigate_node`](Self::navigate_node) so that first visit attaches there in
498    /// the shared lineage tree (the (b) cross-node anchor; the branch-mint path).
499    pub(crate) fn branch_history(&mut self, child: NodeKey, parent: NodeKey) {
500        let (Some(child_id), Some(parent_id)) = (
501            self.inner.node(child).map(|n| n.id),
502            self.inner.node(parent).map(|n| n.id),
503        ) else {
504            return;
505        };
506        self.nav.spawn(child_id, parent_id);
507    }
508
509    /// Step `key` back one visit in its own history, updating its Primary URL to
510    /// the revealed page. Returns the new URL, or `None` if already at the root.
511    pub(crate) fn node_history_back(&mut self, key: NodeKey) -> Option<String> {
512        let at_ms = Self::epoch_ms();
513        let id = self.inner.node(key)?.id;
514        let url = self.nav.back(id, at_ms)?;
515        self.update_node_url(key, url.clone());
516        Some(url)
517    }
518
519    /// Step `key` forward one visit in its own history. Returns the new URL, or
520    /// `None` if already at the tip.
521    pub(crate) fn node_history_forward(&mut self, key: NodeKey) -> Option<String> {
522        let at_ms = Self::epoch_ms();
523        let id = self.inner.node(key)?.id;
524        let url = self.nav.forward(id, at_ms)?;
525        self.update_node_url(key, url.clone());
526        Some(url)
527    }
528
529    /// Whether `key`'s within-node history can step back (toolbar gating).
530    pub fn node_can_back(&self, key: NodeKey) -> bool {
531        self.inner
532            .node(key)
533            .is_some_and(|n| self.nav.can_back(n.id))
534    }
535
536    /// Whether `key`'s within-node history can step forward (toolbar gating).
537    pub fn node_can_forward(&self, key: NodeKey) -> bool {
538        self.inner
539            .node(key)
540            .is_some_and(|n| self.nav.can_forward(n.id))
541    }
542
543    /// `key`'s current page (its history cursor's URL), if any.
544    pub fn node_current_url(&self, key: NodeKey) -> Option<String> {
545        let id = self.inner.node(key)?.id;
546        self.nav.current_url(id)
547    }
548
549    /// `key`'s linear-history projection (active path + cursor).
550    pub fn node_history_projection(&self, key: NodeKey) -> NodeHistoryProjection {
551        match self.inner.node(key) {
552            Some(node) => self.nav.projection(node.id),
553            None => NodeHistoryProjection {
554                entries: Vec::new(),
555                current_index: 0,
556            },
557        }
558    }
559
560    /// `key`'s branching-history projection (visit tree with alternates).
561    pub fn node_history_branch_projection(&self, key: NodeKey) -> NodeHistoryBranchProjection {
562        self.inner
563            .node(key)
564            .map(|node| self.nav.branch_projection(node.id))
565            .unwrap_or_default()
566    }
567
568    /// A coarse semantic summary of `key`'s history.
569    pub fn node_history_semantic_summary(&self, key: NodeKey) -> NodeHistorySemanticSummary {
570        self.inner
571            .node(key)
572            .map(|node| self.nav.semantic_summary(node.id))
573            .unwrap_or_default()
574    }
575
576    /// The graph's recently-visited nodes, newest first, capped at `limit` — the
577    /// graph-wide "recent" projection over the shared visit space (gloss; the
578    /// lineage pane). Delegates to [`SharedNavigationMemory::recent_visited`].
579    pub fn recent_visited(&self, limit: usize) -> Vec<RecentVisit> {
580        self.nav.recent_visited(limit)
581    }
582
583    /// Milliseconds since the Unix epoch, for visit timestamps (live-app clock).
584    fn epoch_ms() -> u64 {
585        crate::time::unix_epoch_millis()
586    }
587}
588
589// Edge mutators (add_edge, assert_relation, replay_*, dissolve_*,
590// remove_edges, retract_relations, get_edge*, push_traversal) live in
591// `graph/edge_ops.rs` (2026-05-11 decomposition pass).
592pub mod edge_ops;
593
594// Query + traversal (node/edge lookups, neighbor iteration, BFS /
595// shortest-path / connected-components / SCC, derived-edge views)
596// live in `graph/query.rs` (2026-05-11 decomposition pass).
597pub mod query;
598
599// `node_display_label`: a human-meaningful label derived from a node's title /
600// linked-data role / @type / address, for the canvas tiles + roster (so an
601// anonymous ingested entity reads as "publisher" / "Organization", not a raw
602// `urn:mere:bnode:` string).
603pub mod display;
604
605// Snapshot serialization (`to_snapshot` / `from_snapshot`), the rkyv
606// trait impls that delegate through them, `containment_parent_url`,
607// and `impl Default for Graph` live in `graph/snapshot.rs`
608// (2026-05-11 decomposition pass).
609pub mod snapshot;
610
611// Tests live in `graph/tests.rs` to keep this file under the
612// 600-LOC ceiling (kernel decomposition pass 2026-05-11).
613#[cfg(test)]
614mod tests;