kernel/persistence.rs
1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Serializable types for graph persistence.
5//!
6//! These types define the portable snapshot and edge schema shared by all hosts.
7//! Storage adapters (fjall, IndexedDB, etc.) live in the host, not here.
8
9use std::collections::BTreeMap;
10
11use rkyv::{Archive, Deserialize, Serialize};
12
13use crate::types::{ImageRef, ImageRole};
14
15// Field-layer DTOs live in their own file (per-file ceiling) but belong to this
16// module's vocabulary; re-export so `crate::persistence::PersistedField` resolves.
17pub use crate::persistence_fields::{
18 PersistedCoupling, PersistedCouplingResponse, PersistedField, PersistedFieldExtent,
19 PersistedFieldLifecycle, PersistedNodeSelector,
20};
21
22// Edge persistence types live in their own file (per-file ceiling); re-exported
23// here so `crate::persistence::PersistedEdge` etc. continue to resolve.
24pub use crate::persistence_edge::{
25 PersistedArrangementEdgeData, PersistedArrangementSubKind, PersistedContainmentEdgeData,
26 PersistedContainmentSubKind, PersistedEdge, PersistedEdgeAssertion, PersistedEdgeFamily,
27 PersistedImportedEdgeData, PersistedImportedSubKind, PersistedNavigationTrigger,
28 PersistedProvenanceEdgeData, PersistedProvenanceSubKind, PersistedRelationSelector,
29 PersistedSemanticEdgeData, PersistedSemanticStatement, PersistedSemanticSubKind,
30 PersistedTraversalEdgeData, PersistedTraversalMetrics, PersistedTraversalRecord,
31};
32
33use crate::graph::SharedNavigationMemory;
34use crate::types::{
35 FrameLayoutHint, ImportRecord, NodeClassification, NodeDerivation, NodeImportProvenance,
36 NodeProperty, NodeTagPresentationState,
37};
38
39// ---------------------------------------------------------------------------
40// Address persistence types
41// ---------------------------------------------------------------------------
42
43/// Address type hint for persistence (mirrors `AddressKind` in the graph model).
44///
45/// Deprecated: superseded by [`PersistedAddress`]. Kept for rkyv backward compatibility
46/// with old snapshots. No new values are written.
47#[derive(
48 Archive,
49 Serialize,
50 Deserialize,
51 Clone,
52 Copy,
53 Debug,
54 PartialEq,
55 Default,
56 serde::Serialize,
57 serde::Deserialize,
58)]
59#[rkyv(derive(Debug, PartialEq))]
60pub enum PersistedAddressKind {
61 #[default]
62 Http,
63 File,
64 Data,
65 GraphshellClip,
66 Directory,
67 Unknown,
68}
69
70/// Typed address for persistence — carries both the URL scheme classification
71/// and the raw URL string.
72///
73/// All variants store the full URL string so that [`PersistedAddress::as_url_str`]
74/// is always a round-trip identity.
75#[derive(
76 Archive, Serialize, Deserialize, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize,
77)]
78#[rkyv(derive(Debug, PartialEq))]
79pub enum PersistedAddress {
80 Http(String),
81 File(String),
82 Data(String),
83 /// Clip route (`verso://clip/<id>` or `graphshell://clip/<id>`). Stores the full URL.
84 Clip(String),
85 Directory(String),
86 Custom(String),
87}
88
89impl Default for PersistedAddress {
90 /// Fallback used when deserializing old snapshots that lack the `address` field.
91 /// The load path detects the empty URL and uses the legacy `url` field instead.
92 fn default() -> Self {
93 PersistedAddress::Custom(String::new())
94 }
95}
96
97impl PersistedAddress {
98 /// Return the raw URL string for this address.
99 pub fn as_url_str(&self) -> &str {
100 match self {
101 PersistedAddress::Http(s)
102 | PersistedAddress::File(s)
103 | PersistedAddress::Data(s)
104 | PersistedAddress::Clip(s)
105 | PersistedAddress::Directory(s)
106 | PersistedAddress::Custom(s) => s.as_str(),
107 }
108 }
109}
110
111impl ArchivedPersistedAddress {
112 /// Return the raw URL string from the archived address.
113 pub fn as_url_str(&self) -> &str {
114 match self {
115 ArchivedPersistedAddress::Http(s)
116 | ArchivedPersistedAddress::File(s)
117 | ArchivedPersistedAddress::Data(s)
118 | ArchivedPersistedAddress::Clip(s)
119 | ArchivedPersistedAddress::Directory(s)
120 | ArchivedPersistedAddress::Custom(s) => s.as_str(),
121 }
122 }
123}
124
125// ---------------------------------------------------------------------------
126// Node persistence types
127// ---------------------------------------------------------------------------
128
129/// Persisted per-node session fidelity state.
130#[derive(Archive, Serialize, Deserialize, Clone, Debug, serde::Serialize, serde::Deserialize)]
131pub struct PersistedNodeSessionState {
132 pub scroll_x: Option<f32>,
133 pub scroll_y: Option<f32>,
134 pub form_draft: Option<String>,
135 #[serde(default)]
136 pub last_visited_ms: Option<u64>,
137}
138
139/// Persisted node.
140#[derive(Archive, Serialize, Deserialize, Clone, Debug, serde::Serialize, serde::Deserialize)]
141pub struct PersistedNode {
142 /// Stable node identity.
143 pub node_id: String,
144
145 /// Typed address — canonical source of the node URL since Stage C.2.
146 #[serde(default)]
147 pub address: PersistedAddress,
148
149 /// Legacy URL field — written alongside `address` for backward compatibility.
150 #[serde(default)]
151 pub url: String,
152
153 #[serde(default)]
154 pub cached_host: Option<String>,
155 pub title: String,
156 #[serde(default)]
157 pub tags: Vec<String>,
158 #[serde(default)]
159 pub tag_presentation: NodeTagPresentationState,
160 #[serde(default)]
161 pub import_provenance: Vec<NodeImportProvenance>,
162 pub is_pinned: bool,
163 /// Content-addressed preview imagery by role. Snapshots carry handles,
164 /// never pixels (node-image externalization, phase 2).
165 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
166 pub images: BTreeMap<ImageRole, ImageRef>,
167
168 // --- Legacy inline imagery: deserialize-only migration shadows ---------
169 //
170 // Snapshots written before phase 2 carry raw PNG/RGBA bytes here. They
171 // load, get externalized into the blob store, and are never written back:
172 // `skip_serializing` means a re-saved snapshot emits references only. Once
173 // no snapshot in the wild carries them these can go.
174 #[serde(default, skip_serializing, rename = "thumbnail_png")]
175 pub legacy_thumbnail_png: Option<Vec<u8>>,
176 #[serde(default, skip_serializing, rename = "thumbnail_width")]
177 pub legacy_thumbnail_width: u32,
178 #[serde(default, skip_serializing, rename = "thumbnail_height")]
179 pub legacy_thumbnail_height: u32,
180 #[serde(default, skip_serializing, rename = "favicon_rgba")]
181 pub legacy_favicon_rgba: Option<Vec<u8>>,
182 #[serde(default, skip_serializing, rename = "favicon_width")]
183 pub legacy_favicon_width: u32,
184 #[serde(default, skip_serializing, rename = "favicon_height")]
185 pub legacy_favicon_height: u32,
186 pub session_state: Option<PersistedNodeSessionState>,
187 /// Optional MIME type hint; drives renderer selection.
188 pub mime_hint: Option<String>,
189 /// Durable provenance-bearing classification records (Stage A enrichment).
190 #[serde(default)]
191 pub classifications: Vec<NodeClassification>,
192 /// Durable split arrangement annotations for frame-anchor nodes.
193 #[serde(default)]
194 pub frame_layout_hints: Vec<FrameLayoutHint>,
195 /// Durable split-offer suppression for frame-anchor nodes.
196 #[serde(default)]
197 pub frame_split_offer_suppressed: bool,
198 /// Open literal properties (non-curated literals preserved on ingest).
199 #[serde(default)]
200 pub properties: Vec<NodeProperty>,
201 /// Cross-graph derivation provenance (copied/forked from another graph).
202 #[serde(default)]
203 pub derivations: Vec<NodeDerivation>,
204 /// Inline authored content body — a knot note's djot source. `#[serde(default)]`
205 /// so snapshots written before the inline body load with `None`. (Djot editor
206 /// reframe, slice 3.)
207 #[serde(default)]
208 pub body: Option<String>,
209 /// The app-launch session number this node was last navigated in. `0` (the
210 /// `#[serde(default)]` for snapshots written before this field existed) means
211 /// "never stamped" — by-sessions eviction treats that as undated, never evicted.
212 /// (Alembic B5.)
213 #[serde(default)]
214 pub last_session_visited: u64,
215 /// The nested graph this node bears, as a log-id string (`Node.nested`;
216 /// the one-node containment ruling). `#[serde(default)]` so snapshots
217 /// written before containment load with `None`.
218 #[serde(default)]
219 pub nested: Option<String>,
220}
221
222/// Full graph snapshot for periodic saves.
223///
224/// Carries both `rkyv` derives (for compact binary persistence —
225/// the original intent) and `serde` derives (added 2026-05-11 so
226/// `host-runtime::session_graph_store` can persist sessions
227/// as hand-inspectable JSON). All sub-types (`PersistedNode`,
228/// `PersistedEdge`, `ImportRecord`) already carry both.
229#[derive(Archive, Serialize, Deserialize, Clone, Debug, serde::Serialize, serde::Deserialize)]
230pub struct GraphSnapshot {
231 pub nodes: Vec<PersistedNode>,
232 pub edges: Vec<PersistedEdge>,
233 pub import_records: Vec<ImportRecord>,
234 pub timestamp_secs: u64,
235 /// Field-layer truth (field-system Phase 2). `#[serde(default)]` so snapshots
236 /// written before the field layer load with an empty one.
237 #[serde(default)]
238 pub fields: Vec<PersistedField>,
239 #[serde(default)]
240 pub couplings: Vec<PersistedCoupling>,
241 /// The graph's shared navigation history (one visit space, owner per node —
242 /// the (b) anchor design). `#[serde(default)]` so snapshots written before the
243 /// shared-history migration (per-node `navigation_memory`, now ignored) load
244 /// with an empty history rather than failing.
245 #[serde(default)]
246 pub navigation: SharedNavigationMemory,
247}
248
249impl GraphSnapshot {
250 /// How many nodes still carry pre-phase-2 inline image bytes.
251 ///
252 /// Conversion into a `Graph` keeps references only, so a non-zero count
253 /// here means the host has not run its externalization pass yet and those
254 /// pixels are about to be dropped. Assert it is zero after migrating; a
255 /// silent loss is the failure mode this exists to make loud.
256 pub fn legacy_image_count(&self) -> usize {
257 self.nodes
258 .iter()
259 .filter(|n| n.legacy_thumbnail_png.is_some() || n.legacy_favicon_rgba.is_some())
260 .count()
261 }
262
263 /// How many nodes still carry optional metadata in the pre-facet columns.
264 ///
265 /// A non-zero count asks the host to persist the imported facet store and
266 /// re-save the graph immediately. Canonical snapshots keep these columns
267 /// empty; the values survive only in `facets.json`.
268 pub fn legacy_node_facet_count(&self) -> usize {
269 self.nodes
270 .iter()
271 .filter(|node| {
272 node.is_pinned
273 || !node.frame_layout_hints.is_empty()
274 || node.frame_split_offer_suppressed
275 || node.tag_presentation != NodeTagPresentationState::default()
276 || !node.import_provenance.is_empty()
277 || !node.classifications.is_empty()
278 || !node.properties.is_empty()
279 || !node.derivations.is_empty()
280 || node.last_session_visited != 0
281 || node
282 .session_state
283 .as_ref()
284 .is_some_and(|state| state.last_visited_ms.is_some())
285 })
286 .count()
287 }
288}
289
290// ---------------------------------------------------------------------------
291// Node audit event taxonomy (Slice 63 — promoted from
292// `services/persistence/types.rs`)
293// ---------------------------------------------------------------------------
294
295/// The kind of node metadata or lifecycle event recorded in an audit log entry.
296///
297/// Each variant carries only the new value (not the old one). The sequence of
298/// audit events in the WAL provides the full history; diffing adjacent entries
299/// to recover the "from" value is a query-time operation.
300///
301/// Promoted to kernel in Slice 63 so it can travel with the rest
302/// of the persistence type taxonomy and be referenced by the (eventually
303/// portable) `GraphMutation` / `GraphIntent` enums without needing the
304/// shell-side `services/persistence` module in scope.
305#[derive(
306 Archive,
307 Serialize,
308 Deserialize,
309 Clone,
310 Debug,
311 PartialEq,
312 Eq,
313 serde::Serialize,
314 serde::Deserialize,
315)]
316#[rkyv(derive(Debug))]
317pub enum NodeAuditEventKind {
318 /// Node title was changed. Records the new title.
319 TitleChanged { new_title: String },
320 /// A tag was added to the node.
321 Tagged { tag: String },
322 /// A tag was removed from the node.
323 Untagged { tag: String },
324 /// Node was pinned.
325 Pinned,
326 /// Node was unpinned.
327 Unpinned,
328 /// Node URL was changed out-of-band (not via NavigateNode navigation).
329 /// Used when a node's URL is set directly rather than through navigation.
330 UrlChanged { new_url: String },
331 /// A viewer or workflow recorded a notable node-scoped action.
332 ActionRecorded { action: String, detail: String },
333 /// Node was tombstoned (soft-deleted).
334 Tombstoned,
335 /// Node was restored from tombstone state.
336 Restored,
337}