Skip to main content

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            )
207            .map_err(|e| {
208                EngineError::Backend(crate::backend::BackendError::Other(format!(
209                    "export_mem_to_bytes: {e}"
210                )))
211            }),
212            MountStorage::Archive { .. } => {
213                Err(EngineError::Backend(crate::backend::BackendError::Sealed))
214            }
215            MountStorage::GitBranch { gitdir, branch } => {
216                let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
217                    EngineError::Backend(crate::backend::BackendError::Other(
218                        "git-branch export hook not installed (git-branch ops not wired)"
219                            .to_string(),
220                    ))
221                })?;
222                // Source per-entity provenance from the git-branch mutation
223                // log (commit trailers) via the mount's backend and hand the
224                // serialised payload to the hook to embed — the hook walks
225                // no history itself.
226                let (provenance, redactions) = mount
227                    .backend
228                    .read_provenance(None)
229                    .ok()
230                    .map(|records| crate::ops::export::build_redacted_archive_provenance(&records))
231                    .unwrap_or((None, Vec::new()));
232                let provenance_bytes = provenance.and_then(|prov| prov.to_archive_bytes().ok());
233                // Source the anchors sidecar from the branch tip so the
234                // git-branch `.mem` carries anchors like the other backends.
235                let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
236                (hook.export_to_bytes)(
237                    gitdir,
238                    branch,
239                    mem_name,
240                    config,
241                    workspace_root,
242                    workspace_schemas_dir,
243                    provenance_bytes.as_deref(),
244                    anchors_bytes.as_deref(),
245                )
246                .map(|mut out| {
247                    out.redactions = redactions;
248                    out
249                })
250                .map_err(EngineError::Backend)
251            }
252            // In-memory mems have no directory to walk: list the
253            // entities from the backend (RAM) and seal them through the
254            // same storage-agnostic archive builder the folder path uses,
255            // so a session mem exports to a `.mem` that mounts
256            // standalone identically.
257            MountStorage::InMemory => {
258                let backend = mount.backend.as_ref();
259                let rels = backend.list_entities().map_err(EngineError::Backend)?;
260                let mut md_entries: Vec<(std::path::PathBuf, Vec<u8>)> =
261                    Vec::with_capacity(rels.len());
262                for rel in rels {
263                    if let Some(bytes) = backend.read_entity(&rel).map_err(EngineError::Backend)? {
264                        md_entries.push((rel, bytes));
265                    }
266                }
267                // Source per-entity provenance from the backend's mutation
268                // log so an in-memory mem exports a provenance-bearing
269                // `.mem` identical in shape to the folder/git-branch paths.
270                let (provenance, redactions) = backend
271                    .read_provenance(None)
272                    .ok()
273                    .map(|records| crate::ops::export::build_redacted_archive_provenance(&records))
274                    .unwrap_or((None, Vec::new()));
275                // Source the anchors sidecar from the in-memory backend so a
276                // sketch-session mem exports a `.mem` carrying its anchors —
277                // the serve session-export → re-import round-trip.
278                let anchors_bytes = backend
279                    .read_anchors_sidecar()
280                    .map_err(EngineError::Backend)?;
281                crate::ops::export::export_entries_to_bytes(
282                    config,
283                    workspace_root,
284                    workspace_schemas_dir,
285                    mem_name,
286                    md_entries,
287                    provenance.as_ref(),
288                    anchors_bytes.as_deref(),
289                    self.ref_schema_source_for(config),
290                )
291                .map(|mut out| {
292                    out.redactions = redactions;
293                    out
294                })
295                .map_err(|e| {
296                    EngineError::Backend(crate::backend::BackendError::Other(format!(
297                        "export_mem_to_bytes: {e}"
298                    )))
299                })
300            }
301        }
302    }
303}
304
305/// Load the embedded `.memstead/schema/` package (if any) via
306/// `load_schema_from_memory`. Returns an empty vec when the archive
307/// carries no schema files — the boot resolver then falls back to the
308/// built-in catalogue for the schema pin. `pub(crate)` so the archive
309/// `SchemaSource` reads through the same loader.
310pub(crate) fn load_embedded_schemas(
311    schema_files: &[SchemaFile],
312) -> Result<Vec<Arc<Schema>>, FromArchiveBytesError> {
313    if schema_files.is_empty() {
314        return Ok(Vec::new());
315    }
316    let mut manifest: Option<&str> = None;
317    let mut types: Vec<(String, String)> = Vec::new();
318    for sf in schema_files {
319        if sf.archive_path == ".memstead/schema/schema.yaml" {
320            manifest = Some(&sf.content);
321        } else if let Some(rest) = sf.archive_path.strip_prefix(".memstead/schema/types/")
322            && let Some(stem) = rest.strip_suffix(".yaml")
323        {
324            types.push((stem.to_string(), sf.content.clone()));
325        }
326    }
327    let Some(manifest_yaml) = manifest else {
328        return Err(FromArchiveBytesError::EmbeddedSchemaInvalid(
329            "embedded schema package present but `.memstead/schema/schema.yaml` missing"
330                .to_string(),
331        ));
332    };
333    // The archive keeps its sealed generation: marker present ⇒
334    // current polarity; absent ⇒ legacy written meaning.
335    let marker_path = format!(
336        ".memstead/schema/{}",
337        memstead_schema::loader::SCHEMA_FORMAT_MARKER_FILE
338    );
339    let format = if schema_files.iter().any(|sf| sf.archive_path == marker_path) {
340        memstead_schema::MetadataPolarityFormat::RequiredOptIn
341    } else {
342        memstead_schema::MetadataPolarityFormat::Legacy
343    };
344    let schema =
345        memstead_schema::load_schema_from_memory_with_format(manifest_yaml, &types, format)
346            .map_err(|e| FromArchiveBytesError::EmbeddedSchemaInvalid(e.to_string()))?;
347    Ok(vec![Arc::new(schema)])
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353    use std::path::Path;
354    use tempfile::TempDir;
355
356    use crate::backend::{BackendError, MemBackend};
357    use crate::engine::test_helpers::{cli_actor, empty_create_args, folder_mount};
358    use crate::storage::FilesystemMemWriter;
359    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
360
361    /// Seed a folder-backed mem with `.memstead/config.json` and N
362    /// entities (zero allowed); return the running engine + mem dir.
363    fn folder_mem_with_entities(tmp: &TempDir, titles: &[&str]) -> (Engine, std::path::PathBuf) {
364        let mem_dir = tmp.path().join("specs");
365        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
366        let config_body = r#"{
367            "format": 1,
368            "schema": "default@1.0.0",
369            "version": "1.0.0"
370        }"#;
371        std::fs::write(mem_dir.join(".memstead").join("config.json"), config_body).unwrap();
372
373        let writer = FilesystemMemWriter::new(mem_dir.clone());
374        let mut engine = Engine::from_mounts(vec![(
375            folder_mount("specs", mem_dir.clone()),
376            Box::new(writer) as Box<dyn MemBackend>,
377        )])
378        .unwrap();
379        let (actor, client) = cli_actor();
380        for t in titles {
381            engine
382                .create_entity(empty_create_args("specs", t), actor, Some(&client), None)
383                .unwrap();
384        }
385        (engine, mem_dir)
386    }
387
388    #[test]
389    fn export_to_bytes_produces_bytes_that_extract_cleanly() {
390        let tmp = TempDir::new().unwrap();
391        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Alpha", "Beta"]);
392        let bytes = engine.export_mem_to_bytes("specs").unwrap();
393        assert!(!bytes.is_empty(), "export bytes must be non-empty");
394        // The bytes validate against the archive ingress validator
395        // standalone — any consumer of sealed archives accepts them.
396        let entries = extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
397        assert_eq!(entries.markdown_files.len(), 2);
398        let mut names: Vec<_> = entries
399            .markdown_files
400            .iter()
401            .map(|m| m.path.clone())
402            .collect();
403        names.sort();
404        assert_eq!(names, vec!["alpha.md".to_string(), "beta.md".to_string()]);
405    }
406
407    /// Export → validate/canonicalise (the install leg) → read
408    /// preserves title, scope, method, and exclusions exactly —
409    /// ordering and non-ASCII included, empty-exclusions included —
410    /// and a mem without either exports as today (format aside).
411    #[test]
412    fn export_round_trips_title_and_subject() {
413        let tmp = TempDir::new().unwrap();
414        let mem_dir = tmp.path().join("specs");
415        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
416        std::fs::write(
417            mem_dir.join(".memstead").join("config.json"),
418            serde_json::json!({
419                "format": 1,
420                "schema": "default@1.0.0",
421                "version": "1.0.0",
422                "title": "Einrichtungsbezogene Impfpflicht Deutschland",
423                "subject": {
424                    "scope": "Die einrichtungsbezogene Impfpflicht — Rechtslage und Vollzug",
425                    "method": "Primärquellen, händisch geprüft",
426                    "exclusions": ["Länderverordnungen nach 2023", "Presseberichte", "Άλλα θέματα"],
427                },
428            })
429            .to_string(),
430        )
431        .unwrap();
432        let writer = FilesystemMemWriter::new(mem_dir.clone());
433        let mut engine = Engine::from_mounts(vec![(
434            folder_mount("specs", mem_dir.clone()),
435            Box::new(writer) as Box<dyn MemBackend>,
436        )])
437        .unwrap();
438        let (actor, client) = cli_actor();
439        engine
440            .create_entity(
441                empty_create_args("specs", "Alpha"),
442                actor,
443                Some(&client),
444                None,
445            )
446            .unwrap();
447
448        let bytes = engine.export_mem_to_bytes("specs").unwrap();
449        // Install leg: validate + canonical repack, then read the config.
450        let validated =
451            crate::validator::validate_and_normalize_archive(&bytes).expect("archive re-validates");
452        let cfg = &validated.config;
453        assert_eq!(cfg.format, memstead_schema::PUBLISHED_MEM_FORMAT);
454        assert_eq!(
455            cfg.title.as_deref(),
456            Some("Einrichtungsbezogene Impfpflicht Deutschland")
457        );
458        let subject = cfg.subject.as_ref().expect("subject rides the archive");
459        assert_eq!(
460            subject.scope,
461            "Die einrichtungsbezogene Impfpflicht — Rechtslage und Vollzug"
462        );
463        assert_eq!(
464            subject.method.as_deref(),
465            Some("Primärquellen, händisch geprüft")
466        );
467        assert_eq!(
468            subject.exclusions,
469            vec![
470                "Länderverordnungen nach 2023",
471                "Presseberichte",
472                "Άλλα θέματα"
473            ],
474            "exclusions preserved in order, non-ASCII intact"
475        );
476
477        // Empty-exclusions case round-trips as an empty list, not a drop.
478        std::fs::write(
479            mem_dir.join(".memstead").join("config.json"),
480            serde_json::json!({
481                "format": 1,
482                "schema": "default@1.0.0",
483                "version": "1.0.0",
484                "subject": { "scope": "Nur der Rahmen", "exclusions": [] },
485            })
486            .to_string(),
487        )
488        .unwrap();
489        engine.reload_each_writable_mem().unwrap();
490        let bytes = engine.export_mem_to_bytes("specs").unwrap();
491        let validated =
492            crate::validator::validate_and_normalize_archive(&bytes).expect("re-validates");
493        let subject = validated.config.subject.as_ref().expect("subject present");
494        assert_eq!(subject.scope, "Nur der Rahmen");
495        assert_eq!(subject.method, None);
496        assert!(subject.exclusions.is_empty());
497        assert_eq!(validated.config.title, None, "unset title stays unset");
498    }
499
500    /// End-to-end producer → consumer round-trip: an entity created with
501    /// an authoring note exports per-entity provenance into the archive,
502    /// and a fresh engine that installs those bytes reads the rationale
503    /// back — matching the source. An entity created without a note is
504    /// absent from the payload (no fabricated provenance).
505    #[test]
506    fn export_carries_provenance_that_install_reads_back() {
507        let tmp = TempDir::new().unwrap();
508        let mem_dir = tmp.path().join("specs");
509        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
510        std::fs::write(
511            mem_dir.join(".memstead").join("config.json"),
512            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
513        )
514        .unwrap();
515        let writer = FilesystemMemWriter::new(mem_dir.clone());
516        let mut engine = Engine::from_mounts(vec![(
517            folder_mount("specs", mem_dir.clone()),
518            Box::new(writer) as Box<dyn MemBackend>,
519        )])
520        .unwrap();
521        let (actor, client) = cli_actor();
522        // Alpha carries a note; Beta deliberately does not.
523        engine
524            .create_entity(
525                empty_create_args("specs", "Alpha"),
526                actor,
527                Some(&client),
528                Some("why alpha exists"),
529            )
530            .unwrap();
531        engine
532            .create_entity(
533                empty_create_args("specs", "Beta"),
534                actor,
535                Some(&client),
536                None,
537            )
538            .unwrap();
539
540        let bytes = engine.export_mem_to_bytes("specs").unwrap();
541        // The archive carries the provenance payload.
542        let entries = extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
543        assert!(
544            entries.provenance_bytes.is_some(),
545            "export must embed the provenance payload"
546        );
547
548        // The publish/install store path persists the *canonical* (re-packed)
549        // bytes, not the raw upload — so normalize must preserve the
550        // provenance member or it would be dropped before serving.
551        let validated =
552            crate::validator::validate_and_normalize_archive(&bytes).expect("archive re-validates");
553        let canonical_entries =
554            extract_entries(&validated.canonical_bytes, &ValidatorLimits::DEFAULT).unwrap();
555        assert!(
556            canonical_entries.provenance_bytes.is_some(),
557            "normalize must preserve provenance through the canonical re-pack (publish store path)"
558        );
559
560        // Install the bytes into a fresh engine and read provenance back.
561        let installed = Engine::from_archive_bytes(bytes).unwrap();
562        let prov = installed
563            .archive_provenance_for("specs")
564            .expect("installed mem exposes provenance");
565        assert_eq!(
566            prov.entity("alpha").and_then(|r| r.rationale.as_deref()),
567            Some("why alpha exists"),
568            "noted entity's rationale matches the source"
569        );
570        assert_eq!(
571            prov.entity("alpha").and_then(|r| r.kind.as_deref()),
572            Some("create"),
573        );
574        assert!(
575            prov.entity("beta").is_none(),
576            "entity authored without a note is absent — no fabricated provenance"
577        );
578    }
579
580    /// Inject an extra member into a zip archive, returning fresh bytes.
581    /// Export now embeds anchors natively (see
582    /// [`export_embeds_anchors_that_install_reads_back`]); this helper still
583    /// synthesises the member in isolation so the canonical-repack survival
584    /// test exercises the registry path independent of the export producer.
585    fn inject_zip_member(archive: &[u8], name: &str, content: &[u8]) -> Vec<u8> {
586        use std::io::{Read, Write};
587        let mut src = zip::ZipArchive::new(std::io::Cursor::new(archive)).unwrap();
588        let mut out = Vec::new();
589        {
590            let mut w = zip::ZipWriter::new(std::io::Cursor::new(&mut out));
591            let opts = zip::write::SimpleFileOptions::default()
592                .compression_method(zip::CompressionMethod::Deflated);
593            for i in 0..src.len() {
594                let mut f = src.by_index(i).unwrap();
595                let fname = f.name().to_string();
596                let mut buf = Vec::new();
597                f.read_to_end(&mut buf).unwrap();
598                w.start_file(fname, opts).unwrap();
599                w.write_all(&buf).unwrap();
600            }
601            w.start_file(name, opts).unwrap();
602            w.write_all(content).unwrap();
603            w.finish().unwrap();
604        }
605        out
606    }
607
608    /// Replace one member's bytes in a zip archive, returning fresh
609    /// bytes — the tamper helper for negative format tests.
610    fn rewrite_zip_member(archive: &[u8], name: &str, content: &[u8]) -> Vec<u8> {
611        use std::io::{Read, Write};
612        let mut src = zip::ZipArchive::new(std::io::Cursor::new(archive)).unwrap();
613        let mut out = Vec::new();
614        {
615            let mut w = zip::ZipWriter::new(std::io::Cursor::new(&mut out));
616            let opts = zip::write::SimpleFileOptions::default()
617                .compression_method(zip::CompressionMethod::Deflated);
618            for i in 0..src.len() {
619                let mut f = src.by_index(i).unwrap();
620                let fname = f.name().to_string();
621                let mut buf = Vec::new();
622                f.read_to_end(&mut buf).unwrap();
623                w.start_file(fname.clone(), opts).unwrap();
624                if fname == name {
625                    w.write_all(content).unwrap();
626                } else {
627                    w.write_all(&buf).unwrap();
628                }
629            }
630            w.finish().unwrap();
631        }
632        out
633    }
634
635    /// The format gate has no reader path that bypasses it: an archive rewritten to `format: 99` used to
636    /// hydrate through the byte path (and hence the wasm package) and
637    /// serve every entity. It now refuses typed; the untampered archive
638    /// keeps hydrating.
639    #[test]
640    fn byte_hydration_refuses_unknown_archive_format() {
641        let tmp = TempDir::new().unwrap();
642        let (mut engine, _dir) = folder_mem_with_entities(&tmp, &["Alpha"]);
643        let _ = &mut engine;
644        let exported = engine.export_mem_to_bytes("specs").unwrap();
645
646        // Complement first: the untampered archive hydrates.
647        let ok = Engine::from_archive_bytes(exported.clone()).expect("valid archive hydrates");
648        assert!(
649            ok.get_entity(&crate::EntityId("specs--alpha".into()))
650                .is_some()
651        );
652
653        // Tamper: rewrite the declared format to an unknown value.
654        let entries = extract_entries(&exported, &ValidatorLimits::DEFAULT).unwrap();
655        let mut cfg: serde_json::Value = serde_json::from_slice(&entries.config_bytes).unwrap();
656        cfg["format"] = serde_json::json!(99);
657        let tampered = rewrite_zip_member(
658            &exported,
659            ".memstead/config.json",
660            serde_json::to_string(&cfg).unwrap().as_bytes(),
661        );
662
663        let err =
664            Engine::from_archive_bytes(tampered).expect_err("format 99 must refuse, never hydrate");
665        match err {
666            FromArchiveBytesError::UnsupportedFormat { declared, accepted } => {
667                assert_eq!(declared, 99);
668                assert!(!accepted.is_empty());
669            }
670            other => panic!("expected UnsupportedFormat, got {other:?}"),
671        }
672    }
673
674    /// Registry-leg survival: an anchors sidecar member threads verbatim
675    /// through `validate_and_normalize_archive`'s canonical re-pack (the
676    /// publish/install store path) rather than being silently stripped, and
677    /// the installed mem exposes the anchors.
678    #[test]
679    fn anchors_member_survives_canonical_repack_and_install() {
680        let tmp = TempDir::new().unwrap();
681        let (mut engine, _dir) = folder_mem_with_entities(&tmp, &["Alpha"]);
682        let _ = &mut engine;
683        let exported = engine.export_mem_to_bytes("specs").unwrap();
684
685        let anchors = br#"{"version":1,"entities":{"specs--alpha":[{"artifact":"src/lib.rs","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#;
686        let with_anchors = inject_zip_member(&exported, ".memstead/anchors.json", anchors);
687
688        // Recognised at extract time.
689        let entries = extract_entries(&with_anchors, &ValidatorLimits::DEFAULT).unwrap();
690        assert_eq!(entries.anchors_bytes.as_deref(), Some(&anchors[..]));
691
692        // Threaded through the canonical re-pack (what publish stores).
693        let validated = crate::validator::validate_and_normalize_archive(&with_anchors)
694            .expect("archive with anchors re-validates");
695        let canonical =
696            extract_entries(&validated.canonical_bytes, &ValidatorLimits::DEFAULT).unwrap();
697        assert_eq!(
698            canonical.anchors_bytes.as_deref(),
699            Some(&anchors[..]),
700            "normalize must preserve the anchors member through the canonical re-pack"
701        );
702
703        // Installing the canonical bytes exposes the anchors on the mem.
704        let installed = Engine::from_archive_bytes(validated.canonical_bytes).unwrap();
705        let ids = installed.entity_anchors(&crate::EntityId::new("specs", "alpha"));
706        assert_eq!(ids.len(), 1);
707        assert_eq!(ids[0].artifact, "src/lib.rs");
708    }
709
710    /// End-to-end export leg: an entity created with an
711    /// `anchors[]` payload exports the anchors sidecar *natively* inside the
712    /// `.mem` archive (no injection), the canonical re-pack preserves it, and
713    /// a fresh engine that installs the bytes reads the anchor back — matching
714    /// the source. A mem with no anchors embeds no member.
715    #[test]
716    fn export_embeds_anchors_that_install_reads_back() {
717        let tmp = TempDir::new().unwrap();
718        let mem_dir = tmp.path().join("specs");
719        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
720        std::fs::write(
721            mem_dir.join(".memstead").join("config.json"),
722            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
723        )
724        .unwrap();
725        let writer = FilesystemMemWriter::new(mem_dir.clone());
726        let mut engine = Engine::from_mounts(vec![(
727            folder_mount("specs", mem_dir.clone()),
728            Box::new(writer) as Box<dyn MemBackend>,
729        )])
730        .unwrap();
731        let (actor, client) = cli_actor();
732
733        // Alpha carries a file anchor; Beta carries none.
734        let mut alpha = empty_create_args("specs", "Alpha");
735        alpha.anchors = vec![crate::anchor::AnchorInput {
736            artifact: Some("src/lib.rs".to_string()),
737            grain: Some("file".to_string()),
738            class: Some("anchored".to_string()),
739            hash: Some("h1".to_string()),
740            hash_stability: Some("stable".to_string()),
741            ..Default::default()
742        }];
743        engine
744            .create_entity(alpha, actor, Some(&client), None)
745            .unwrap();
746        engine
747            .create_entity(
748                empty_create_args("specs", "Beta"),
749                actor,
750                Some(&client),
751                None,
752            )
753            .unwrap();
754
755        // Export embeds the anchors sidecar natively (producer half of the
756        // recognised-member contract).
757        let bytes = engine.export_mem_to_bytes("specs").unwrap();
758        let entries = extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
759        assert!(
760            entries.anchors_bytes.is_some(),
761            "export must embed the anchors sidecar when the mem has anchors"
762        );
763
764        // Canonical re-pack (publish store path) preserves it.
765        let validated =
766            crate::validator::validate_and_normalize_archive(&bytes).expect("archive re-validates");
767        let canonical =
768            extract_entries(&validated.canonical_bytes, &ValidatorLimits::DEFAULT).unwrap();
769        assert!(
770            canonical.anchors_bytes.is_some(),
771            "normalize must preserve the exported anchors member"
772        );
773
774        // Install into a fresh engine and read the anchor back.
775        let installed = Engine::from_archive_bytes(validated.canonical_bytes).unwrap();
776        let alpha_anchors = installed.entity_anchors(&crate::EntityId::new("specs", "alpha"));
777        assert_eq!(alpha_anchors.len(), 1);
778        assert_eq!(alpha_anchors[0].artifact, "src/lib.rs");
779        assert_eq!(alpha_anchors[0].hash.as_deref(), Some("h1"));
780        // Beta had no anchors — none fabricated.
781        assert!(
782            installed
783                .entity_anchors(&crate::EntityId::new("specs", "beta"))
784                .is_empty(),
785            "an entity with no anchors exposes none after install"
786        );
787    }
788
789    /// Publish-time redaction (W6/03): redacting an exported archive's
790    /// anchors passes validation, survives the canonical re-pack, and
791    /// installs with the redacted sidecar reading back intact — the
792    /// sentinel where the artifact reference was, the trust metadata
793    /// (class, hash) untouched, and the anchor count unchanged. The
794    /// unredacted bytes are not altered by the transform's existence:
795    /// an archive without the flag stays byte-identical, and a redacted
796    /// archive of a mem with NO anchors is byte-identical input too.
797    #[test]
798    fn redacted_archive_survives_repack_and_install() {
799        use crate::filesystem::publish::redact_archive_anchors;
800
801        let tmp = TempDir::new().unwrap();
802        let mem_dir = tmp.path().join("specs");
803        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
804        std::fs::write(
805            mem_dir.join(".memstead").join("config.json"),
806            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
807        )
808        .unwrap();
809        let writer = FilesystemMemWriter::new(mem_dir.clone());
810        let mut engine = Engine::from_mounts(vec![(
811            folder_mount("specs", mem_dir.clone()),
812            Box::new(writer) as Box<dyn MemBackend>,
813        )])
814        .unwrap();
815        let (actor, client) = cli_actor();
816        let mut alpha = empty_create_args("specs", "Alpha");
817        alpha.anchors = vec![crate::anchor::AnchorInput {
818            artifact: Some("src/secret/module.rs".to_string()),
819            grain: Some("file".to_string()),
820            class: Some("anchored".to_string()),
821            hash: Some("h1".to_string()),
822            hash_stability: Some("stable".to_string()),
823            ..Default::default()
824        }];
825        engine
826            .create_entity(alpha, actor, Some(&client), None)
827            .unwrap();
828
829        let bytes = engine.export_mem_to_bytes("specs").unwrap();
830        let redacted = redact_archive_anchors(&bytes).unwrap();
831        assert_ne!(redacted, bytes, "redaction changes the anchors member");
832
833        // Validation and the canonical re-pack accept the redacted package.
834        let validated = crate::validator::validate_and_normalize_archive(&redacted)
835            .expect("redacted archive validates");
836        let canonical =
837            extract_entries(&validated.canonical_bytes, &ValidatorLimits::DEFAULT).unwrap();
838        let sidecar = crate::anchor::AnchorSidecar::from_bytes(
839            canonical.anchors_bytes.as_deref().expect("member survives"),
840        )
841        .unwrap();
842        let anchors = sidecar.get("specs--alpha");
843        assert_eq!(anchors.len(), 1, "anchor count unchanged");
844        assert_eq!(
845            anchors[0].artifact,
846            crate::anchor::REDACTED_ARTIFACT_SENTINEL
847        );
848        assert_eq!(
849            anchors[0].hash.as_deref(),
850            Some("h1"),
851            "trust metadata kept"
852        );
853
854        // Install reads the redacted state back honestly.
855        let installed = Engine::from_archive_bytes(validated.canonical_bytes).unwrap();
856        let read_back = installed.entity_anchors(&crate::EntityId::new("specs", "alpha"));
857        assert_eq!(read_back.len(), 1);
858        assert_eq!(
859            read_back[0].artifact,
860            crate::anchor::REDACTED_ARTIFACT_SENTINEL
861        );
862        assert!(
863            !String::from_utf8_lossy(&redacted).contains("src/secret/module.rs"),
864            "the artifact path must not survive anywhere in the package"
865        );
866
867        // The workspace the author published from is unchanged: the local
868        // sidecar still carries the real reference, and local anchors
869        // rendering reads it — redaction happened on the staged copy only.
870        let local =
871            std::fs::read_to_string(mem_dir.join(".memstead").join("anchors.json")).unwrap();
872        assert!(
873            local.contains("src/secret/module.rs"),
874            "local sidecar bytes untouched by a redacted publish"
875        );
876        assert_eq!(
877            engine.entity_anchors(&crate::EntityId::new("specs", "alpha"))[0].artifact,
878            "src/secret/module.rs"
879        );
880
881        // A mem with no anchors: the transform is a byte-identical no-op.
882        let mem_dir2 = tmp.path().join("plain");
883        std::fs::create_dir_all(mem_dir2.join(".memstead")).unwrap();
884        std::fs::write(
885            mem_dir2.join(".memstead").join("config.json"),
886            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
887        )
888        .unwrap();
889        let writer2 = FilesystemMemWriter::new(mem_dir2.clone());
890        let mut engine2 = Engine::from_mounts(vec![(
891            folder_mount("plain", mem_dir2.clone()),
892            Box::new(writer2) as Box<dyn MemBackend>,
893        )])
894        .unwrap();
895        engine2
896            .create_entity(
897                empty_create_args("plain", "Only"),
898                actor,
899                Some(&client),
900                None,
901            )
902            .unwrap();
903        let plain_bytes = engine2.export_mem_to_bytes("plain").unwrap();
904        assert_eq!(
905            redact_archive_anchors(&plain_bytes).unwrap(),
906            plain_bytes,
907            "no anchors member ⇒ byte-identical passthrough"
908        );
909    }
910
911    /// Serve sketch-session leg: an anchored write into an
912    /// in-memory mem round-trips through session export → re-import. The
913    /// in-memory backend is exactly what serve mounts, so this proves the
914    /// serve session-export path carries anchors without a serve dependency.
915    #[test]
916    fn in_memory_mem_export_round_trips_anchors() {
917        use crate::storage::InMemoryBackend;
918        // A session-style in-memory mem is self-describing: a versioned config
919        // is written to the backend before boot so export can project it.
920        let backend = InMemoryBackend::new();
921        backend
922            .write_mem_config(br#"{"version":"0.1.0","schema":"default@1.0.0"}"#)
923            .unwrap();
924        let mount = Mount {
925            mem: "sketch".to_string(),
926            schema: Some("default@1.0.0".parse().unwrap()),
927            storage: MountStorage::InMemory,
928            capability: MountCapability::Write,
929            lifecycle: MountLifecycle::Eager,
930            cross_linkable: false,
931            migration_target: None,
932        };
933        let mut engine =
934            Engine::from_mounts(vec![(mount, Box::new(backend) as Box<dyn MemBackend>)]).unwrap();
935        let (actor, client) = cli_actor();
936
937        let mut args = empty_create_args("sketch", "Idea");
938        args.anchors = vec![crate::anchor::AnchorInput {
939            artifact: Some("notes/idea.md".to_string()),
940            grain: Some("file".to_string()),
941            class: Some("informed-by".to_string()),
942            ..Default::default()
943        }];
944        engine
945            .create_entity(args, actor, Some(&client), None)
946            .unwrap();
947
948        let bytes = engine.export_mem_to_bytes("sketch").unwrap();
949        let entries = extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
950        assert!(
951            entries.anchors_bytes.is_some(),
952            "in-memory session export must carry the anchors sidecar"
953        );
954
955        let reimported = Engine::from_archive_bytes(bytes).unwrap();
956        let anchors = reimported.entity_anchors(&crate::EntityId::new("sketch", "idea"));
957        assert_eq!(anchors.len(), 1);
958        assert_eq!(anchors[0].artifact, "notes/idea.md");
959        assert_eq!(
960            anchors[0].class,
961            crate::anchor::AnchorProvenanceClass::InformedBy
962        );
963    }
964
965    /// Size discipline: provenance scales with entity count (one current
966    /// rationale per entity, each ≤ the 280-char note cap), so for a
967    /// representative mem (~60 noted entities, larger than the live engine
968    /// seed's ~120 but with realistic notes) the provenance-bearing archive
969    /// stays well under the registry's 2 MB publish body limit, and the
970    /// provenance payload is a small fraction of the archive.
971    #[test]
972    fn provenance_bearing_archive_stays_within_publish_budget() {
973        const PUBLISH_BODY_LIMIT: usize = 2 * 1024 * 1024;
974        let tmp = TempDir::new().unwrap();
975        let mem_dir = tmp.path().join("specs");
976        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
977        std::fs::write(
978            mem_dir.join(".memstead").join("config.json"),
979            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
980        )
981        .unwrap();
982        let writer = FilesystemMemWriter::new(mem_dir.clone());
983        let mut engine = Engine::from_mounts(vec![(
984            folder_mount("specs", mem_dir.clone()),
985            Box::new(writer) as Box<dyn MemBackend>,
986        )])
987        .unwrap();
988        let (actor, client) = cli_actor();
989        // A realistic-length authoring note on every entity (near the
990        // 280-char cap) — the worst case for provenance size.
991        let note = "x".repeat(280);
992        for i in 0..60 {
993            engine
994                .create_entity(
995                    empty_create_args("specs", &format!("Entity {i}")),
996                    actor,
997                    Some(&client),
998                    Some(&note),
999                )
1000                .unwrap();
1001        }
1002        let bytes = engine.export_mem_to_bytes("specs").unwrap();
1003        assert!(
1004            bytes.len() < PUBLISH_BODY_LIMIT,
1005            "archive ({} B) must stay under the 2 MB publish limit",
1006            bytes.len()
1007        );
1008        let entries = extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
1009        let prov = entries.provenance_bytes.expect("provenance present");
1010        // Every entity's rationale travelled and the payload is a modest
1011        // fraction of the archive, not a budget threat.
1012        assert!(
1013            prov.len() < PUBLISH_BODY_LIMIT / 4,
1014            "provenance payload ({} B) is a small fraction of the budget",
1015            prov.len()
1016        );
1017        let parsed = memstead_schema::ArchiveProvenance::from_archive_bytes(&prov).unwrap();
1018        assert_eq!(
1019            parsed.entities.len(),
1020            60,
1021            "every noted entity has provenance"
1022        );
1023    }
1024
1025    /// A mem slice carrying a
1026    /// cross-mem edge (target lives in another mem, won't travel in
1027    /// this single-mem archive) exports successfully — the archive is
1028    /// still produced — and the export surfaces the dangling edge so the
1029    /// operator sees, before sharing, exactly what `install` will reject.
1030    /// AC1 (export warns, archive produced) + AC2 (export's condition ==
1031    /// install's refusal) tested against one set of bytes.
1032    #[test]
1033    fn export_warns_on_cross_mem_edge_that_install_refuses() {
1034        let tmp = TempDir::new().unwrap();
1035        let (engine, mem_dir) = folder_mem_with_entities(&tmp, &[]);
1036        // Hand-write a valid spec whose only blemish is a cross-mem
1037        // USES edge into mem `other` — the folder export reads `.md`
1038        // verbatim, so the edge lands in the archive.
1039        let md = "\
1040---
1041type: spec
1042created_date: 2026-01-15
1043last_modified: 2026-01-15
1044level: M0
1045---
1046# Broker
1047
1048## Identity
1049
1050A
1051
1052## Purpose
1053
1054B
1055
1056## Specifies
1057
1058C
1059
1060## Constraints
1061
1062D
1063
1064## Rationale
1065
1066E
1067
1068## Relationships
1069
1070- **USES**: [[other--thing]]
1071";
1072        std::fs::write(mem_dir.join("broker.md"), md).unwrap();
1073
1074        // The path-shaped export carries the dangling edge on its result
1075        // and still writes the archive (AC1).
1076        let out = tmp.path().join("specs.mem");
1077        let result = engine.export_mem("specs", &out).unwrap();
1078        assert!(out.is_file(), "archive must still be produced");
1079        assert_eq!(
1080            result.dangling_cross_mem_edges.len(),
1081            1,
1082            "export must surface the cross-mem edge: {:?}",
1083            result.dangling_cross_mem_edges
1084        );
1085        let edge = &result.dangling_cross_mem_edges[0];
1086        assert_eq!(edge.entity_path, "broker.md");
1087        assert_eq!(edge.target_id, "other--thing");
1088        assert_eq!(edge.target_mem, "other");
1089
1090        // AC2: the exact condition export warned on is what install
1091        // refuses on — the strict validator rejects these same bytes.
1092        let bytes = std::fs::read(&out).unwrap();
1093        let err = crate::validator::validate_and_normalize_archive(&bytes).unwrap_err();
1094        assert!(
1095            matches!(
1096                err,
1097                crate::validator::ValidationError::CrossMemRelationship { .. }
1098            ),
1099            "install-side strict validation must refuse the same edge: {err:?}",
1100        );
1101    }
1102
1103    /// `make_archive_self_contained` turns the archive `install` refuses
1104    /// into one it accepts: the cross-mem row is dropped and reported,
1105    /// the same-mem row and the body text survive, the result passes
1106    /// strict validation and hydrates. Complement: an already
1107    /// self-contained archive comes back with nothing dropped.
1108    #[test]
1109    fn self_contained_repack_drops_cross_mem_rows_and_passes_install_validation() {
1110        let tmp = TempDir::new().unwrap();
1111        let (engine, mem_dir) = folder_mem_with_entities(&tmp, &["Alpha"]);
1112        let md = "\
1113---
1114type: spec
1115created_date: 2026-01-15
1116last_modified: 2026-01-15
1117level: M0
1118---
1119# Broker
1120
1121## Identity
1122
1123Talks to [[other:thing]] over the wire.
1124
1125## Purpose
1126
1127B
1128
1129## Specifies
1130
1131C
1132
1133## Constraints
1134
1135D
1136
1137## Rationale
1138
1139E
1140
1141## Relationships
1142
1143- **USES**: [[other--thing]]
1144- **REFERENCES**: [[alpha]]
1145";
1146        std::fs::write(mem_dir.join("broker.md"), md).unwrap();
1147        let out = tmp.path().join("specs.mem");
1148        engine.export_mem("specs", &out).unwrap();
1149        let bytes = std::fs::read(&out).unwrap();
1150        assert!(
1151            crate::validator::validate_and_normalize_archive(&bytes).is_err(),
1152            "precondition: the raw export is refused"
1153        );
1154
1155        let sealed = crate::validator::make_archive_self_contained(&bytes).unwrap();
1156        assert_eq!(sealed.dropped.len(), 1, "{:?}", sealed.dropped);
1157        assert_eq!(sealed.dropped[0].entity_path, "broker.md");
1158        assert_eq!(sealed.dropped[0].target_id, "other--thing");
1159        assert_eq!(sealed.dropped[0].target_mem, "other");
1160        // The proof is the strict validator, the one `install` runs.
1161        let validated = crate::validator::validate_and_normalize_archive(&sealed.bytes)
1162            .expect("the self-contained archive passes strict validation");
1163        assert!(validated.dangling_cross_mem_edges.is_empty());
1164        let broker = validated
1165            .entities
1166            .iter()
1167            .find(|e| e.id.as_ref() == "specs--broker")
1168            .expect("broker travels");
1169        assert_eq!(
1170            broker
1171                .relationships
1172                .iter()
1173                .map(|r| r.target.as_ref())
1174                .collect::<Vec<_>>(),
1175            vec!["specs--alpha"],
1176            "only the same-mem row survives"
1177        );
1178        assert!(
1179            broker
1180                .sections
1181                .values()
1182                .any(|b| b.contains("[[other:thing]]")),
1183            "body wiki-links are never touched"
1184        );
1185        let hydrated = Engine::from_archive_bytes(sealed.bytes).unwrap();
1186        assert_eq!(
1187            hydrated.store().all_entities().filter(|e| !e.stub).count(),
1188            2
1189        );
1190
1191        // Complement: nothing to drop on an archive that is already clean.
1192        std::fs::remove_file(mem_dir.join("broker.md")).unwrap();
1193        let clean_engine = Engine::from_mounts(vec![(
1194            folder_mount("specs", mem_dir.clone()),
1195            Box::new(FilesystemMemWriter::new(mem_dir.clone())) as Box<dyn MemBackend>,
1196        )])
1197        .unwrap();
1198        let clean_out = tmp.path().join("clean.mem");
1199        clean_engine.export_mem("specs", &clean_out).unwrap();
1200        let clean =
1201            crate::validator::make_archive_self_contained(&std::fs::read(&clean_out).unwrap())
1202                .unwrap();
1203        assert!(clean.dropped.is_empty());
1204        assert!(crate::validator::validate_and_normalize_archive(&clean.bytes).is_ok());
1205    }
1206
1207    /// Complement: a self-contained export (no cross-mem edges) carries
1208    /// no dangling-edge warnings.
1209    #[test]
1210    fn export_self_contained_mem_warns_nothing() {
1211        let tmp = TempDir::new().unwrap();
1212        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Alpha", "Beta"]);
1213        let out = tmp.path().join("specs.mem");
1214        let result = engine.export_mem("specs", &out).unwrap();
1215        assert!(
1216            result.dangling_cross_mem_edges.is_empty(),
1217            "self-contained export must warn nothing: {:?}",
1218            result.dangling_cross_mem_edges
1219        );
1220    }
1221
1222    #[test]
1223    fn export_empty_mem_produces_valid_hydratable_archive() {
1224        let tmp = TempDir::new().unwrap();
1225        let (engine, _mem) = folder_mem_with_entities(&tmp, &[]);
1226        let bytes = engine.export_mem_to_bytes("specs").unwrap();
1227        // Validator accepts the empty case.
1228        let entries = extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
1229        assert!(entries.markdown_files.is_empty());
1230        // Hydrate path accepts it too.
1231        let hydrated = Engine::from_archive_bytes(bytes).unwrap();
1232        assert_eq!(hydrated.mem_names(), vec!["specs"]);
1233        assert!(hydrated.store().is_empty());
1234    }
1235
1236    #[test]
1237    fn export_unknown_mem_returns_unknown_mem_error() {
1238        let tmp = TempDir::new().unwrap();
1239        let (engine, _mem) = folder_mem_with_entities(&tmp, &[]);
1240        let err = engine.export_mem_to_bytes("missing").unwrap_err();
1241        match err {
1242            EngineError::UnknownMem(v) => assert_eq!(v, "missing"),
1243            other => panic!("expected UnknownMem, got {other:?}"),
1244        }
1245    }
1246
1247    #[test]
1248    fn export_archive_backend_returns_sealed() {
1249        // Seed by exporting a folder mem, then re-mount the produced
1250        // archive as a read-only archive. The byte-export path on the
1251        // archive mount refuses with the Sealed envelope — matches the
1252        // existing path-based `export_mem` posture.
1253        let tmp = TempDir::new().unwrap();
1254        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Alpha"]);
1255        let bytes = engine.export_mem_to_bytes("specs").unwrap();
1256
1257        let archive_path = tmp.path().join("ext.mem");
1258        std::fs::write(&archive_path, &bytes).unwrap();
1259        let archive_engine = Engine::from_mounts(vec![(
1260            Mount {
1261                mem: "ext".to_string(),
1262                schema: Some(memstead_schema::SchemaRef::new(
1263                    "default",
1264                    semver::Version::new(1, 0, 0),
1265                )),
1266                storage: MountStorage::Archive {
1267                    path: archive_path.clone(),
1268                },
1269                capability: MountCapability::ReadOnly,
1270                lifecycle: MountLifecycle::Lazy,
1271                cross_linkable: false,
1272                migration_target: None,
1273            },
1274            Box::new(crate::storage::ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
1275        )])
1276        .unwrap();
1277        let err = archive_engine.export_mem_to_bytes("ext").unwrap_err();
1278        assert!(matches!(err, EngineError::Backend(BackendError::Sealed)));
1279    }
1280
1281    #[test]
1282    fn from_archive_bytes_refuses_non_zip_with_validation_error() {
1283        let err = Engine::from_archive_bytes(b"not a zip at all".to_vec()).unwrap_err();
1284        match err {
1285            FromArchiveBytesError::Validation(crate::validator::ValidationError::Zip(_)) => {}
1286            other => panic!("expected Validation(Zip(_)), got {other:?}"),
1287        }
1288    }
1289
1290    #[test]
1291    fn from_archive_bytes_refuses_oversized_with_size_cap() {
1292        let tmp = TempDir::new().unwrap();
1293        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Alpha"]);
1294        let bytes = engine.export_mem_to_bytes("specs").unwrap();
1295
1296        let mut limits = ValidatorLimits::DEFAULT;
1297        limits.max_compressed_archive = 1;
1298        let err = Engine::from_archive_bytes_with_limits(bytes, &limits).unwrap_err();
1299        match err {
1300            FromArchiveBytesError::Validation(
1301                crate::validator::ValidationError::SizeCapExceeded { .. },
1302            ) => {}
1303            other => panic!("expected Validation(SizeCapExceeded), got {other:?}"),
1304        }
1305    }
1306
1307    #[test]
1308    fn hydrated_engine_answers_reads_and_refuses_writes() {
1309        let tmp = TempDir::new().unwrap();
1310        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Hello", "World"]);
1311        let bytes = engine.export_mem_to_bytes("specs").unwrap();
1312        let mut hydrated = Engine::from_archive_bytes(bytes).unwrap();
1313
1314        // Read surface — same titles surface from the hydrated state.
1315        let hello = hydrated
1316            .get_entity(&crate::EntityId::new("specs", "hello"))
1317            .expect("hello entity must round-trip");
1318        assert_eq!(hello.title, "Hello");
1319        let world = hydrated
1320            .get_entity(&crate::EntityId::new("specs", "world"))
1321            .expect("world entity must round-trip");
1322        assert_eq!(world.title, "World");
1323
1324        // Mutation surface — read-only mount refuses with the existing
1325        // typed envelope (no new error categories on the hydrate path).
1326        let (actor, client) = cli_actor();
1327        let err = hydrated
1328            .create_entity(
1329                empty_create_args("specs", "Forbidden"),
1330                actor,
1331                Some(&client),
1332                None,
1333            )
1334            .unwrap_err();
1335        assert!(matches!(err, EngineError::ReadOnlyMount(v) if v == "specs"));
1336    }
1337
1338    #[test]
1339    fn round_trip_preserves_entities_and_relations() {
1340        // Build a multi-entity mem with a relation, export → hydrate,
1341        // and confirm state equivalence: same ids, same content per
1342        // entity, same relations.
1343        let tmp = TempDir::new().unwrap();
1344        let mem_dir = tmp.path().join("specs");
1345        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
1346        std::fs::write(
1347            mem_dir.join(".memstead").join("config.json"),
1348            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
1349        )
1350        .unwrap();
1351        let writer = FilesystemMemWriter::new(mem_dir.clone());
1352        let mut source = Engine::from_mounts(vec![(
1353            folder_mount("specs", mem_dir),
1354            Box::new(writer) as Box<dyn MemBackend>,
1355        )])
1356        .unwrap();
1357        let (actor, client) = cli_actor();
1358        let src = source
1359            .create_entity(
1360                empty_create_args("specs", "Source"),
1361                actor,
1362                Some(&client),
1363                None,
1364            )
1365            .unwrap();
1366        let tgt = source
1367            .create_entity(
1368                empty_create_args("specs", "Target"),
1369                actor,
1370                Some(&client),
1371                None,
1372            )
1373            .unwrap();
1374        source
1375            .relate_entity(
1376                crate::engine::RelateEntityArgs {
1377                    source: src.id.clone(),
1378                    expected_hash: Some(src.content_hash.clone()),
1379                    rel_type: "USES".to_string(),
1380                    target: tgt.id.clone(),
1381                    remove: false,
1382                    description: None,
1383                    dry_run: false,
1384                },
1385                actor,
1386                Some(&client),
1387                None,
1388            )
1389            .unwrap();
1390
1391        let bytes = source.export_mem_to_bytes("specs").unwrap();
1392        let hydrated = Engine::from_archive_bytes(bytes).unwrap();
1393
1394        // Same id set.
1395        let mut src_ids: Vec<String> = source
1396            .store()
1397            .all_entities()
1398            .map(|e| e.id.to_string())
1399            .collect();
1400        let mut hyd_ids: Vec<String> = hydrated
1401            .store()
1402            .all_entities()
1403            .map(|e| e.id.to_string())
1404            .collect();
1405        src_ids.sort();
1406        hyd_ids.sort();
1407        assert_eq!(src_ids, hyd_ids);
1408
1409        // Same title + entity_type per id.
1410        for id_str in &src_ids {
1411            let (mem, slug) = id_str.split_once("--").expect("ids carry `<mem>--<slug>`");
1412            let id = crate::EntityId::new(mem, slug);
1413            let s = source.get_entity(&id).unwrap();
1414            let h = hydrated.get_entity(&id).unwrap();
1415            assert_eq!(s.title, h.title, "title differs for {id_str}");
1416            assert_eq!(s.entity_type, h.entity_type, "type differs for {id_str}");
1417        }
1418
1419        // Same outgoing relation set.
1420        let src_edges: Vec<_> = source
1421            .store()
1422            .outgoing(&src.id)
1423            .iter()
1424            .map(|e| (e.rel_type.clone(), e.target.clone()))
1425            .collect();
1426        let hyd_edges: Vec<_> = hydrated
1427            .store()
1428            .outgoing(&src.id)
1429            .iter()
1430            .map(|e| (e.rel_type.clone(), e.target.clone()))
1431            .collect();
1432        assert_eq!(src_edges, hyd_edges);
1433    }
1434
1435    #[test]
1436    fn export_then_hydrate_then_re_export_yields_byte_equivalent_archive() {
1437        // Determinism check — same source state must produce identical
1438        // archive bytes through the export path, and re-exporting from
1439        // the hydrated copy is not part of the contract (the hydrated
1440        // engine is read-only) but the produced bytes from the source
1441        // must be a fixpoint when re-fed.
1442        let tmp = TempDir::new().unwrap();
1443        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Alpha"]);
1444        let bytes1 = engine.export_mem_to_bytes("specs").unwrap();
1445        let bytes2 = engine.export_mem_to_bytes("specs").unwrap();
1446        assert_eq!(bytes1, bytes2, "export bytes must be deterministic");
1447    }
1448
1449    /// Compare two engines' state for the named mem. State
1450    /// equivalence at minimum (per the round-trip AC): same entity
1451    /// ids, same content per entity (title, type, metadata, sections,
1452    /// content_hash), same relations (rel_type + target per source).
1453    /// Shared by the fixture-sweep round-trip tests so they assert the
1454    /// same invariant regardless of the fixture shape under test.
1455    fn assert_state_equivalent(source: &Engine, hydrated: &Engine, mem: &str) {
1456        let mut src_ids: Vec<String> = source
1457            .store()
1458            .all_entities()
1459            .filter(|e| e.mem == mem)
1460            .map(|e| e.id.to_string())
1461            .collect();
1462        let mut hyd_ids: Vec<String> = hydrated
1463            .store()
1464            .all_entities()
1465            .filter(|e| e.mem == mem)
1466            .map(|e| e.id.to_string())
1467            .collect();
1468        src_ids.sort();
1469        hyd_ids.sort();
1470        assert_eq!(src_ids, hyd_ids, "entity id set differs for mem {mem}");
1471
1472        for id_str in &src_ids {
1473            let (v, slug) = id_str.split_once("--").expect("ids carry `<mem>--<slug>`");
1474            let id = crate::EntityId::new(v, slug);
1475            let s = source.get_entity(&id).expect("source entity present");
1476            let h = hydrated.get_entity(&id).expect("hydrated entity present");
1477            assert_eq!(s.title, h.title, "title differs for {id_str}");
1478            assert_eq!(s.entity_type, h.entity_type, "type differs for {id_str}");
1479            assert_eq!(s.metadata, h.metadata, "metadata differs for {id_str}");
1480            assert_eq!(s.sections, h.sections, "sections differ for {id_str}");
1481            assert_eq!(
1482                s.content_hash, h.content_hash,
1483                "content_hash differs for {id_str}",
1484            );
1485
1486            let mut src_edges: Vec<_> = source
1487                .store()
1488                .outgoing(&id)
1489                .iter()
1490                .map(|e| (e.rel_type.clone(), e.target.to_string()))
1491                .collect();
1492            let mut hyd_edges: Vec<_> = hydrated
1493                .store()
1494                .outgoing(&id)
1495                .iter()
1496                .map(|e| (e.rel_type.clone(), e.target.to_string()))
1497                .collect();
1498            src_edges.sort();
1499            hyd_edges.sort();
1500            assert_eq!(src_edges, hyd_edges, "edges differ for {id_str}");
1501        }
1502    }
1503
1504    /// Round-trip the engine state via export → hydrate, asserting
1505    /// state equivalence against the input. Returns the hydrated
1506    /// engine so individual tests can drive extra reads against it.
1507    fn round_trip(source: &Engine, mem: &str) -> Engine {
1508        let bytes = source.export_mem_to_bytes(mem).unwrap();
1509        // The bytes pass the validator standalone — same invariant the
1510        // bridge consumer relies on, asserted on every fixture so a
1511        // future export change can't silently break ingress.
1512        extract_entries(&bytes, &ValidatorLimits::DEFAULT).unwrap();
1513        let hydrated = Engine::from_archive_bytes(bytes).unwrap();
1514        assert_state_equivalent(source, &hydrated, mem);
1515        hydrated
1516    }
1517
1518    #[test]
1519    fn fixture_sweep_round_trip_empty() {
1520        let tmp = TempDir::new().unwrap();
1521        let (engine, _mem) = folder_mem_with_entities(&tmp, &[]);
1522        let hydrated = round_trip(&engine, "specs");
1523        assert!(hydrated.store().is_empty());
1524    }
1525
1526    #[test]
1527    fn fixture_sweep_round_trip_single_entity() {
1528        let tmp = TempDir::new().unwrap();
1529        let (engine, _mem) = folder_mem_with_entities(&tmp, &["Solo"]);
1530        round_trip(&engine, "specs");
1531    }
1532
1533    #[test]
1534    fn fixture_sweep_round_trip_multi_entity_no_relations() {
1535        let tmp = TempDir::new().unwrap();
1536        let (engine, _mem) = folder_mem_with_entities(&tmp, &["A One", "A Two", "A Three"]);
1537        round_trip(&engine, "specs");
1538    }
1539
1540    #[test]
1541    fn fixture_sweep_round_trip_entity_with_metadata_and_sections() {
1542        let tmp = TempDir::new().unwrap();
1543        let mem_dir = tmp.path().join("specs");
1544        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
1545        std::fs::write(
1546            mem_dir.join(".memstead").join("config.json"),
1547            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
1548        )
1549        .unwrap();
1550        let writer = FilesystemMemWriter::new(mem_dir.clone());
1551        let mut engine = Engine::from_mounts(vec![(
1552            folder_mount("specs", mem_dir),
1553            Box::new(writer) as Box<dyn MemBackend>,
1554        )])
1555        .unwrap();
1556        let (actor, client) = cli_actor();
1557
1558        let mut sections = indexmap::IndexMap::new();
1559        sections.insert("identity".to_string(), "A rich body.".to_string());
1560        sections.insert(
1561            "purpose".to_string(),
1562            "To exercise the archive round-trip.".to_string(),
1563        );
1564        sections.insert(
1565            "rationale".to_string(),
1566            "Because the spec said so.".to_string(),
1567        );
1568
1569        let mut metadata: indexmap::IndexMap<String, String> = indexmap::IndexMap::new();
1570        metadata.insert("level".to_string(), "M0".to_string());
1571
1572        engine
1573            .create_entity(
1574                crate::engine::CreateEntityArgs {
1575                    anchors: Vec::new(),
1576                    mem: "specs".to_string(),
1577                    title: "Rich".to_string(),
1578                    entity_type: "spec".to_string(),
1579                    sections,
1580                    metadata,
1581                    relations: Vec::new(),
1582                    dry_run: false,
1583                },
1584                actor,
1585                Some(&client),
1586                None,
1587            )
1588            .unwrap();
1589        round_trip(&engine, "specs");
1590    }
1591
1592    #[test]
1593    fn fixture_sweep_round_trip_multi_entity_with_relations() {
1594        let tmp = TempDir::new().unwrap();
1595        let mem_dir = tmp.path().join("specs");
1596        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
1597        std::fs::write(
1598            mem_dir.join(".memstead").join("config.json"),
1599            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
1600        )
1601        .unwrap();
1602        let writer = FilesystemMemWriter::new(mem_dir.clone());
1603        let mut engine = Engine::from_mounts(vec![(
1604            folder_mount("specs", mem_dir),
1605            Box::new(writer) as Box<dyn MemBackend>,
1606        )])
1607        .unwrap();
1608        let (actor, client) = cli_actor();
1609        let src = engine
1610            .create_entity(
1611                empty_create_args("specs", "Source"),
1612                actor,
1613                Some(&client),
1614                None,
1615            )
1616            .unwrap();
1617        let mid = engine
1618            .create_entity(
1619                empty_create_args("specs", "Middle"),
1620                actor,
1621                Some(&client),
1622                None,
1623            )
1624            .unwrap();
1625        let tgt = engine
1626            .create_entity(
1627                empty_create_args("specs", "Target"),
1628                actor,
1629                Some(&client),
1630                None,
1631            )
1632            .unwrap();
1633        // Two outgoing edges of different rel-types from the same
1634        // source — the round-trip must preserve both.
1635        engine
1636            .relate_entity(
1637                crate::engine::RelateEntityArgs {
1638                    source: src.id.clone(),
1639                    expected_hash: Some(src.content_hash.clone()),
1640                    rel_type: "USES".to_string(),
1641                    target: mid.id.clone(),
1642                    remove: false,
1643                    description: None,
1644                    dry_run: false,
1645                },
1646                actor,
1647                Some(&client),
1648                None,
1649            )
1650            .unwrap();
1651        let src_after = engine
1652            .get_entity(&src.id)
1653            .expect("source must still resolve");
1654        engine
1655            .relate_entity(
1656                crate::engine::RelateEntityArgs {
1657                    source: src.id.clone(),
1658                    expected_hash: Some(src_after.content_hash.clone()),
1659                    rel_type: "PART_OF".to_string(),
1660                    target: tgt.id.clone(),
1661                    remove: false,
1662                    description: None,
1663                    dry_run: false,
1664                },
1665                actor,
1666                Some(&client),
1667                None,
1668            )
1669            .unwrap();
1670        round_trip(&engine, "specs");
1671    }
1672
1673    #[test]
1674    fn read_entity_path_works_against_byte_backed_archive() {
1675        // Sanity: the byte-backed ArchiveBackend the hydrate path
1676        // constructs answers `read_entity` for every listed path.
1677        let tmp = TempDir::new().unwrap();
1678        let (engine, _mem) = folder_mem_with_entities(&tmp, &["First", "Second"]);
1679        let bytes = engine.export_mem_to_bytes("specs").unwrap();
1680        let hydrated = Engine::from_archive_bytes(bytes).unwrap();
1681        let first = hydrated
1682            .get_entity(&crate::EntityId::new("specs", "first"))
1683            .expect("first must hydrate");
1684        assert_eq!(first.title, "First");
1685        // Path-based archive_path() returns None for byte-backed
1686        // backends — compile-time check that the contract holds.
1687        let backend = ArchiveBackend::from_bytes(Vec::new());
1688        let _: Option<&Path> = backend.archive_path();
1689    }
1690}