memstead_base/engine/archive.rs
1//! Byte-based snapshot API: hydrate an engine from sealed `.mem`
2//! archive bytes, and export a mem's current state back to archive
3//! bytes.
4//!
5//! Bridge consumers and future browser-WASM replicas consume
6//! these two methods to ship the current state of a mem over HTTP
7//! without materialising a temp file. Both methods go through the
8//! existing validator + storage stack — same wire format, same caps,
9//! same refusal envelopes — but expose a single-call API that hides
10//! `ArchiveBackend` / `Mount` from the caller.
11//!
12//! Symmetric contract: bytes produced by [`Engine::export_mem_to_bytes`]
13//! hydrate cleanly into another [`Engine`] via
14//! [`Engine::from_archive_bytes`], and the resulting engine answers the
15//! read surface (`memstead_overview`, `memstead_search`, `memstead_entity`,
16//! `memstead_health`) with results indistinguishable from the source for
17//! the exported mem. Mutation methods refuse via the existing
18//! sealed-backend / read-only-mount envelope — no new error categories
19//! enter the surface here.
20
21use std::path::PathBuf;
22use std::sync::Arc;
23
24use memstead_schema::Schema;
25
26use crate::backend::MemBackend;
27use crate::storage::ArchiveBackend;
28use crate::validator::ValidatorLimits;
29use crate::validator::archive::{ArchiveEntries, SchemaFile, extract_entries};
30use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
31
32use super::{Engine, EngineError};
33
34/// Errors surfaced by [`Engine::from_archive_bytes`].
35///
36/// The archive ingress validator's typed payload rides through as
37/// [`Self::Validation`] so the caller pattern-matches on the same
38/// variant `extract_entries` would surface standalone — the new API
39/// does not collapse validation failures into a generic error. The
40/// remaining variants cover the small ladder of engine-side failures
41/// (config parse, embedded schema load, downstream construction).
42// The `Validation` variant carries the lower-layer error verbatim, which is
43// what makes `#[from]` lifting possible; boxing it to equalise variant sizes
44// would trade a cold-path allocation for a colder-path byte count.
45#[allow(clippy::large_enum_variant)]
46#[derive(Debug, thiserror::Error)]
47pub enum FromArchiveBytesError {
48 /// Archive bytes failed validation by `extract_entries`. Carries
49 /// the typed [`crate::validator::ValidationError`] verbatim.
50 #[error("archive validation: {0}")]
51 Validation(#[from] crate::validator::ValidationError),
52 /// `.memstead/config.json` inside the archive could not be parsed as a
53 /// `PublishedMemConfig`. The archive bytes passed the
54 /// archive-level whitelist but the JSON shape failed.
55 #[error("invalid published config: {0}")]
56 InvalidConfig(String),
57 /// The archive declares a `format` this engine does not accept
58 /// (`published_format_accepted` refused it). A reader that proceeds
59 /// past an unknown format would reinterpret bytes written under a
60 /// contract it does not know — refuse, never guess.
61 #[error(
62 "unsupported archive format {declared} — this engine accepts formats {accepted:?}; \
63 re-export the mem with a current engine or upgrade this one"
64 )]
65 UnsupportedFormat {
66 /// The `format` the archive's config declares.
67 declared: u32,
68 /// The formats this engine accepts.
69 accepted: &'static [u32],
70 },
71 /// The embedded `.memstead/schema/` package failed to load via
72 /// `load_schema_from_memory`.
73 #[error("embedded schema failed to load: {0}")]
74 EmbeddedSchemaInvalid(String),
75 /// Downstream engine construction failed (e.g., schema pin not
76 /// resolved against builtins + embedded schemas).
77 #[error(transparent)]
78 Engine(#[from] EngineError),
79}
80
81impl Engine {
82 /// Hydrate an engine from sealed archive bytes (`.mem`).
83 ///
84 /// Validates the bytes through the archive ingress validator
85 /// (`extract_entries`), reads the embedded `.memstead/config.json` for
86 /// mem name + schema pin, loads any embedded schema package
87 /// (`.memstead/schema/`) into the engine's schema catalogue, and
88 /// constructs a single-mount read-only engine backed by the bytes.
89 /// No temp file, no on-disk artifact — the bytes are the storage.
90 ///
91 /// The resulting engine refuses mutations (`memstead_create`,
92 /// `memstead_update`, `memstead_delete`, `memstead_relate`, `memstead_rename`) via
93 /// the existing read-only-mount / sealed-backend envelope. Read
94 /// operations work for the embedded mem.
95 pub fn from_archive_bytes(bytes: Vec<u8>) -> Result<Self, FromArchiveBytesError> {
96 Self::from_archive_bytes_with_limits(bytes, &ValidatorLimits::DEFAULT)
97 }
98
99 /// Variant of [`Self::from_archive_bytes`] with caller-supplied
100 /// limits. Bridge / registry deployments tune the caps; the
101 /// default ladder ([`ValidatorLimits::DEFAULT`]) is what
102 /// `from_archive_bytes` picks.
103 pub fn from_archive_bytes_with_limits(
104 bytes: Vec<u8>,
105 limits: &ValidatorLimits,
106 ) -> Result<Self, FromArchiveBytesError> {
107 let entries = extract_entries(&bytes, limits)?;
108 let ArchiveEntries {
109 config_bytes,
110 schema_files,
111 ..
112 } = &entries;
113
114 let published: memstead_schema::PublishedMemConfig =
115 serde_json::from_slice(config_bytes)
116 .map_err(|e| FromArchiveBytesError::InvalidConfig(e.to_string()))?;
117
118 // The format gate: every reader path consults the one predicate
119 // (`published_format_accepted`) — this byte-hydration path used to
120 // skip it, so an archive rewritten to `format: 99` hydrated and
121 // served entities through the wasm package. Refuse typed instead.
122 if !memstead_schema::published_format_accepted(published.format) {
123 return Err(FromArchiveBytesError::UnsupportedFormat {
124 declared: published.format,
125 accepted: memstead_schema::PUBLISHED_MEM_FORMATS_ACCEPTED,
126 });
127 }
128
129 let extra_schemas = load_embedded_schemas(schema_files)?;
130
131 let mount = Mount {
132 mem: published.name.clone(),
133 schema: Some(published.schema.clone()),
134 storage: MountStorage::Archive {
135 path: PathBuf::new(),
136 },
137 capability: MountCapability::ReadOnly,
138 lifecycle: MountLifecycle::Eager,
139 cross_linkable: false,
140 migration_target: None,
141 };
142 let backend: Box<dyn MemBackend> = Box::new(ArchiveBackend::from_bytes(bytes));
143
144 let engine = Self::from_mounts_inner(vec![(mount, backend)], extra_schemas, Vec::new())?;
145 Ok(engine)
146 }
147
148 /// Export the named mem's current state as `.mem` archive bytes.
149 ///
150 /// Symmetric to [`Self::from_archive_bytes`]: a mem name in, a
151 /// self-contained byte buffer out. The bytes validate against
152 /// `extract_entries` standalone — any consumer of sealed archives
153 /// accepts them. Feeding the bytes back into
154 /// `Engine::from_archive_bytes` yields an engine that returns
155 /// identical reads against the exported mem.
156 ///
157 /// Returns [`EngineError::UnknownMem`] when the name resolves to
158 /// no mount; [`EngineError::Backend`] wrapping
159 /// [`crate::backend::BackendError::Sealed`] when the mem is
160 /// archive-mounted (already-an-archive, no meaningful re-export);
161 /// [`EngineError::InvalidInput`] when the mem has no loaded
162 /// `MemConfig`; [`EngineError::MemConfigIncomplete`] when the
163 /// loaded config is missing `version`. The git-branch byte-export
164 /// path lifts in a follow-up; today it surfaces as
165 /// [`EngineError::Backend`] wrapping the unmounted-hook message.
166 pub fn export_mem_to_bytes(&self, mem_name: &str) -> Result<Vec<u8>, EngineError> {
167 self.export_mem_bytes_report(mem_name).map(|out| out.bytes)
168 }
169
170 /// The bytes export with its report: the archive bytes plus the
171 /// counts the disk export reports (entities, dangling cross-mem
172 /// edges, per-class provenance redactions), so a caller that never
173 /// touches disk can still say what the archive carries.
174 pub fn export_mem_bytes_report(
175 &self,
176 mem_name: &str,
177 ) -> Result<crate::ops::export::MemExportBytes, EngineError> {
178 let mount = self
179 .mounts
180 .iter()
181 .find(|m| m.mount.mem == mem_name)
182 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
183 let config = self.mem_config_for(mem_name).ok_or_else(|| {
184 EngineError::InvalidInput(format!(
185 "mem '{mem_name}' has no loaded MemConfig — cannot export"
186 ))
187 })?;
188 if config.version.is_none() {
189 return Err(EngineError::MemConfigIncomplete {
190 mem: mem_name.to_string(),
191 missing_fields: vec!["version".to_string()],
192 });
193 }
194 let workspace_root = self.workspace_root.as_deref();
195 // Fixed authored-schema location (the `schemas_dir` key is retired).
196 let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
197 let workspace_schemas_dir = fixed_schemas_dir.as_deref();
198 match &mount.mount.storage {
199 MountStorage::Folder { path } => crate::ops::export::export_mem_to_bytes(
200 path,
201 config,
202 workspace_root,
203 workspace_schemas_dir,
204 mem_name,
205 self.ref_schema_source_for(config),
206 Some(&self.sealed_row_reader(mem_name)),
207 )
208 .map_err(|e| {
209 EngineError::Backend(crate::backend::BackendError::Other(format!(
210 "export_mem_to_bytes: {e}"
211 )))
212 }),
213 MountStorage::Archive { .. } => {
214 Err(EngineError::Backend(crate::backend::BackendError::Sealed))
215 }
216 MountStorage::GitBranch { gitdir, branch } => {
217 let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
218 EngineError::Backend(crate::backend::BackendError::Other(
219 "git-branch export hook not installed (git-branch ops not wired)"
220 .to_string(),
221 ))
222 })?;
223 // Source per-entity provenance from the git-branch mutation
224 // log (commit trailers) via the mount's backend and hand the
225 // serialised payload to the hook to embed — the hook walks
226 // no history itself.
227 let entity_paths = crate::ops::export::entity_paths_of(
228 &mount
229 .backend
230 .list_entities()
231 .map_err(EngineError::Backend)?,
232 );
233 let records = mount.backend.read_provenance(None).unwrap_or_default();
234 let (provenance, redactions) =
235 crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
236 let provenance_bytes = provenance.to_archive_bytes().ok();
237 // Source the anchors sidecar from the branch tip so the
238 // git-branch `.mem` carries anchors like the other backends.
239 let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
240 // The sealed check records come from the workspace ledger
241 // the engine holds, each with the independence reading the
242 // engine derives; the hook only places the member.
243 let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
244 workspace_root,
245 mem_name,
246 &entity_paths,
247 Some(&self.sealed_row_reader(mem_name)),
248 );
249 (hook.export_to_bytes)(
250 gitdir,
251 branch,
252 mem_name,
253 config,
254 workspace_root,
255 workspace_schemas_dir,
256 provenance_bytes.as_deref(),
257 anchors_bytes.as_deref(),
258 checks_bytes.as_deref(),
259 )
260 .map(|mut out| {
261 out.redactions =
262 crate::ops::export::merge_redactions(redactions, check_redactions);
263 out
264 })
265 .map_err(EngineError::Backend)
266 }
267 // In-memory mems have no directory to walk: list the
268 // entities from the backend (RAM) and seal them through the
269 // same storage-agnostic archive builder the folder path uses,
270 // so a session mem exports to a `.mem` that mounts
271 // standalone identically.
272 MountStorage::InMemory => {
273 let backend = mount.backend.as_ref();
274 let rels = backend.list_entities().map_err(EngineError::Backend)?;
275 let entity_paths = crate::ops::export::entity_paths_of(&rels);
276 let mut md_entries: Vec<(std::path::PathBuf, Vec<u8>)> =
277 Vec::with_capacity(rels.len());
278 for rel in rels {
279 if let Some(bytes) = backend.read_entity(&rel).map_err(EngineError::Backend)? {
280 md_entries.push((rel, bytes));
281 }
282 }
283 // Source per-entity provenance from the backend's mutation
284 // log so an in-memory mem exports a provenance-bearing
285 // `.mem` identical in shape to the folder/git-branch paths.
286 let records = backend.read_provenance(None).unwrap_or_default();
287 let (provenance, redactions) =
288 crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
289 // Source the anchors sidecar from the in-memory backend so a
290 // sketch-session mem exports a `.mem` carrying its anchors —
291 // the serve session-export → re-import round-trip.
292 let anchors_bytes = backend
293 .read_anchors_sidecar()
294 .map_err(EngineError::Backend)?;
295 // The sealed check records, from the workspace ledger, each
296 // with the independence reading the engine derives.
297 let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
298 workspace_root,
299 mem_name,
300 &entity_paths,
301 Some(&self.sealed_row_reader(mem_name)),
302 );
303 crate::ops::export::export_entries_to_bytes(
304 config,
305 workspace_root,
306 workspace_schemas_dir,
307 mem_name,
308 md_entries,
309 Some(&provenance),
310 anchors_bytes.as_deref(),
311 checks_bytes.as_deref(),
312 self.ref_schema_source_for(config),
313 )
314 .map(|mut out| {
315 out.redactions =
316 crate::ops::export::merge_redactions(redactions, check_redactions);
317 out
318 })
319 .map_err(|e| {
320 EngineError::Backend(crate::backend::BackendError::Other(format!(
321 "export_mem_to_bytes: {e}"
322 )))
323 })
324 }
325 }
326 }
327}
328
329/// Load the embedded `.memstead/schema/` package (if any) via
330/// `load_schema_from_memory`. Returns an empty vec when the archive
331/// carries no schema files — the boot resolver then falls back to the
332/// built-in catalogue for the schema pin. `pub(crate)` so the archive
333/// `SchemaSource` reads through the same loader.
334pub(crate) fn load_embedded_schemas(
335 schema_files: &[SchemaFile],
336) -> Result<Vec<Arc<Schema>>, FromArchiveBytesError> {
337 if schema_files.is_empty() {
338 return Ok(Vec::new());
339 }
340 let mut manifest: Option<&str> = None;
341 let mut types: Vec<(String, String)> = Vec::new();
342 for sf in schema_files {
343 if sf.archive_path == ".memstead/schema/schema.yaml" {
344 manifest = Some(&sf.content);
345 } else if let Some(rest) = sf.archive_path.strip_prefix(".memstead/schema/types/")
346 && let Some(stem) = rest.strip_suffix(".yaml")
347 {
348 types.push((stem.to_string(), sf.content.clone()));
349 }
350 }
351 let Some(manifest_yaml) = manifest else {
352 return Err(FromArchiveBytesError::EmbeddedSchemaInvalid(
353 "embedded schema package present but `.memstead/schema/schema.yaml` missing"
354 .to_string(),
355 ));
356 };
357 // The archive keeps its sealed generation: marker present ⇒
358 // current polarity; absent ⇒ legacy written meaning.
359 let marker_path = format!(
360 ".memstead/schema/{}",
361 memstead_schema::loader::SCHEMA_FORMAT_MARKER_FILE
362 );
363 let format = if schema_files.iter().any(|sf| sf.archive_path == marker_path) {
364 memstead_schema::MetadataPolarityFormat::RequiredOptIn
365 } else {
366 memstead_schema::MetadataPolarityFormat::Legacy
367 };
368 let schema =
369 memstead_schema::load_schema_from_memory_with_format(manifest_yaml, &types, format)
370 .map_err(|e| FromArchiveBytesError::EmbeddedSchemaInvalid(e.to_string()))?;
371 Ok(vec![Arc::new(schema)])
372}
373
374#[cfg(test)]
375mod tests;