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