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