Skip to main content

memstead_base/filesystem/
publish.rs

1//! Filesystem-mem → `.mem` archive assembler.
2//!
3//! Walks a workspace root on disk, reads the workspace config,
4//! projects it to the strict archive shape, embeds the resolved schema
5//! source under `.memstead/schema/`, and packs every entity `.md` file
6//! into a deterministic zip.
7//!
8//! Engine-agnostic: the caller passes a path. Used by both
9//! `memstead publish` and `memstead export --format mem`, neither of which
10//! needs a live engine for the archive build (the workspace config
11//! and the entity walker both read from disk directly).
12//!
13//! ## Archive layout (matches `memstead-base::validator::archive`)
14//!
15//! ```text
16//! .memstead/config.json               # archive shape (PublishedMemConfig)
17//! .memstead/schema/schema.yaml        # schema manifest
18//! .memstead/schema/types/<name>.yaml  # per-type definitions
19//! <mem-relative entity path>.md     # one per entity in the workspace
20//! ```
21//!
22//! ## Determinism
23//!
24//! - Entity `.md` files are emitted in mem-relative path order — the
25//!   same order [`crate::entity::source::EntitySource::Directory`]
26//!   yields them on read.
27//! - Schema files come from
28//!   [`memstead_schema::collect_schema_source`], which already sorts by
29//!   `archive_path`.
30//! - The `.memstead/config.json` is serialised pretty-printed for human
31//!   inspection but with deterministic key order via
32//!   [`memstead_schema::PublishedMemConfig`]'s `Serialize` impl.
33//! - Compression is fixed at `Stored` so repeated assembly of the same
34//!   workspace yields byte-identical archive bytes (modulo zip-level
35//!   timestamps, which the writer leaves at zero by default).
36//!
37//! ## What this does NOT do
38//!
39//! - HTTP. The CLI's `commands::publish` posts the bytes; this module
40//!   stops at "build the byte buffer". Same separation as the
41//!   mem-repo `export_mem` → `commands::publish` flow.
42//! - Validate. The bytes go through `validator::archive::extract_entries`
43//!   on the registry side; doing it here too would double the work for
44//!   the same answer. Tests in this module *do* re-validate so future
45//!   layout changes surface as test failures rather than registry
46//!   rejections.
47
48use std::io::{Cursor, Write as _};
49use std::path::Path;
50
51use memstead_schema::{
52    ARCHIVE_CONFIG_PATH, ARCHIVE_SCHEMA_PREFIX, PublishConversionError, SchemaRef,
53    SchemaSourceError, collect_schema_source,
54};
55use zip::CompressionMethod;
56use zip::result::ZipError;
57use zip::write::SimpleFileOptions;
58
59use super::config::{WorkspaceConfigError, read_workspace_config};
60use crate::entity::source::EntitySource;
61
62/// Errors surfaced by [`assemble_archive`].
63#[derive(Debug, thiserror::Error)]
64pub enum AssembleError {
65    /// The workspace config could not be read
66    /// or parsed (missing file, malformed JSON, format mismatch).
67    #[error("workspace config: {0}")]
68    WorkspaceConfig(#[from] WorkspaceConfigError),
69    /// The workspace config does not project cleanly to the archive
70    /// shape — typically because `version` is unset on the workspace
71    /// config.
72    #[error("config projection: {0}")]
73    Config(#[from] PublishConversionError),
74    /// Resolving the schema's source files failed — either the
75    /// `name@version` pin does not match any builtin (and there's no
76    /// workspace-local schema dir) or the on-disk schema directory is
77    /// malformed.
78    #[error("schema source: {0}")]
79    Schema(#[from] SchemaSourceError),
80    /// I/O while reading entity `.md` files from the workspace.
81    #[error("workspace io: {0}")]
82    Io(String),
83    /// Zip-level error while writing into the in-memory buffer.
84    /// Should not happen in practice — the buffer is unbounded — but
85    /// surfaces cleanly if a future zip version starts failing earlier.
86    #[error("zip writer: {0}")]
87    Zip(#[from] ZipError),
88    /// Serialising the archive's `.memstead/config.json`.
89    #[error("config serialisation: {0}")]
90    Serialise(#[from] serde_json::Error),
91    /// The workspace's anchors sidecar (or an archive's anchors member)
92    /// is unreadable or malformed. A refusal, never a silent drop — an
93    /// archive shipping without the anchors its workspace carries is
94    /// exactly the publish-strip failure the anchors contract closes.
95    #[error("anchors sidecar: {0}")]
96    Anchors(String),
97}
98
99impl AssembleError {
100    /// The wire code: a schema source or anchors refusal keeps its own,
101    /// every other stage is the assembly failing.
102    pub fn code(&self) -> &'static str {
103        match self {
104            AssembleError::Schema(e) => e.code(),
105            AssembleError::Anchors(_) => "ANCHORS_SIDECAR_UNREADABLE",
106            AssembleError::WorkspaceConfig(_)
107            | AssembleError::Config(_)
108            | AssembleError::Io(_)
109            | AssembleError::Zip(_)
110            | AssembleError::Serialise(_) => "ARCHIVE_ASSEMBLY_FAILED",
111        }
112    }
113
114    /// The recovery payload: the stage that failed and why, with the
115    /// path where the stage names one.
116    pub fn details(&self) -> serde_json::Value {
117        match self {
118            AssembleError::Schema(e) => e.details(),
119            AssembleError::WorkspaceConfig(WorkspaceConfigError::NotFound(path))
120            | AssembleError::WorkspaceConfig(WorkspaceConfigError::Io { path, .. }) => {
121                serde_json::json!({
122                    "stage": "workspace_config",
123                    "path": path,
124                    "reason": self.to_string(),
125                })
126            }
127            AssembleError::WorkspaceConfig(_) => serde_json::json!({
128                "stage": "workspace_config",
129                "reason": self.to_string(),
130            }),
131            AssembleError::Config(_) => serde_json::json!({
132                "stage": "config_projection",
133                "reason": self.to_string(),
134            }),
135            AssembleError::Io(reason) => serde_json::json!({ "stage": "io", "reason": reason }),
136            AssembleError::Zip(_) | AssembleError::Serialise(_) => serde_json::json!({
137                "stage": "write",
138                "reason": self.to_string(),
139            }),
140            AssembleError::Anchors(reason) => serde_json::json!({ "reason": reason }),
141        }
142    }
143}
144
145/// Build the archive bytes for the workspace at `workspace_root`.
146///
147/// The caller writes the bytes to a tempfile and POSTs them to the
148/// registry — this function does not touch the network. It reads
149/// the workspace config and walks every `.md` file
150/// under `workspace_root`; both reads are direct (no engine
151/// involvement).
152pub fn assemble_archive(workspace_root: &Path) -> Result<Vec<u8>, AssembleError> {
153    // 1. Read the workspace config and project it to the strict
154    //    archive shape.
155    let config = read_workspace_config(workspace_root)?;
156    let published = config.to_published()?;
157    // The projection guarantees a versioned schema pin; reuse it for
158    // the schema-source resolver.
159    let schema_ref: SchemaRef = published.schema.clone();
160
161    // 2. Resolve the schema source files. Installed packages live under
162    //    `.memstead/schemas/` (the fixed `memstead schema install`
163    //    destination — same wiring as `Engine::export_mem_to_bytes`);
164    //    builtins remain the final fallback. (The former
165    //    `.memstead.cache/schemas/` layer is retired — see
166    //    memstead-schema/src/source.rs — nothing ever wrote it.)
167    let schemas_dir = workspace_root.join(".memstead").join("schemas");
168    let schema_files =
169        collect_schema_source(Some(workspace_root), Some(&schemas_dir), &schema_ref)?;
170
171    // 3. Walk every entity `.md` under the workspace.
172    let source = EntitySource::Directory {
173        root: workspace_root.to_path_buf(),
174    };
175    let (source_entries, read_errors) = source
176        .read_all()
177        .map_err(|e| AssembleError::Io(e.to_string()))?;
178    if let Some(first) = read_errors.first() {
179        return Err(AssembleError::Io(format!(
180            "{}: {}",
181            first.source_path.display(),
182            first.error
183        )));
184    }
185
186    // 4. Pack into a zip. Sort entries by archive path for
187    //    determinism — the directory walker already sorts but
188    //    re-sorting here makes the contract explicit (a future change
189    //    in the walker won't break archive determinism).
190    let mut buf: Vec<u8> = Vec::new();
191    {
192        let cursor = Cursor::new(&mut buf);
193        let mut zip = zip::ZipWriter::new(cursor);
194        let opts = SimpleFileOptions::default()
195            .compression_method(CompressionMethod::Stored)
196            .last_modified_time(zip::DateTime::default());
197
198        // .memstead/config.json (archive shape — `deps` and other
199        // workspace-local fields are dropped by `to_published`).
200        let config_bytes = serde_json::to_vec_pretty(&published)?;
201        zip.start_file(ARCHIVE_CONFIG_PATH, opts)?;
202        zip.write_all(&config_bytes)
203            .map_err(|e| AssembleError::Io(format!("write config: {e}")))?;
204
205        // .memstead/anchors.json — the engine-owned anchors sidecar,
206        // when the mem carries one. The engine exporters have always
207        // threaded it (anchors travel in published archives, by
208        // contract); this walker previously did not, so a bare
209        // `memstead publish` of a folder mem silently shipped without
210        // its anchors — the publish-strip failure the contract exists
211        // to close. A present-but-malformed sidecar refuses rather than
212        // drops.
213        let anchors_path = workspace_root.join(crate::anchor::ANCHOR_SIDECAR_PATH);
214        if anchors_path.exists() {
215            let bytes = std::fs::read(&anchors_path)
216                .map_err(|e| AssembleError::Anchors(format!("read: {e}")))?;
217            let sidecar = crate::anchor::AnchorSidecar::from_bytes(&bytes)
218                .map_err(|e| AssembleError::Anchors(e.to_string()))?;
219            // An anchorless sidecar file embeds nothing — the archive
220            // contract is "no anchors ⇒ no member".
221            if !sidecar.entities.is_empty() {
222                zip.start_file(crate::anchor::ANCHOR_SIDECAR_PATH, opts)?;
223                zip.write_all(&bytes)
224                    .map_err(|e| AssembleError::Io(format!("write anchors: {e}")))?;
225            }
226        }
227
228        // .memstead/schema/* — `collect_schema_source` returns paths
229        // rooted at the schema dir (`schema.yaml`, `types/<name>.yaml`).
230        // Prepend the archive's `.memstead/schema/` root so the validator
231        // picks them up under the right path.
232        for sf in &schema_files {
233            let archive_path = format!("{ARCHIVE_SCHEMA_PREFIX}{}", sf.archive_path);
234            zip.start_file(&archive_path, opts)?;
235            zip.write_all(&sf.bytes)
236                .map_err(|e| AssembleError::Io(format!("write schema: {e}")))?;
237        }
238
239        // Entity .md files. Source-walked paths use the platform
240        // separator on Directory; normalise to forward-slash so the
241        // archive is portable across OSes.
242        let mut entries = source_entries;
243        entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
244        for entry in &entries {
245            let archive_path = entry.relative_path.replace('\\', "/");
246            zip.start_file(&archive_path, opts)?;
247            zip.write_all(entry.content.as_bytes())
248                .map_err(|e| AssembleError::Io(format!("write entity {archive_path}: {e}")))?;
249        }
250
251        zip.finish()?;
252    }
253    Ok(buf)
254}
255
256/// Redact the anchors sidecar inside assembled `.mem` archive bytes:
257/// every `artifact` and every `derived_from` entry becomes
258/// [`crate::anchor::REDACTED_ARTIFACT_SENTINEL`]; class, grain,
259/// `at_version`, hash, hash-stability, binding, source, and the
260/// per-entity anchor counts survive — redact, not strip, so the trust
261/// grade stays readable without the source's identity.
262///
263/// Operates on finished archive bytes so ANY packaging caller can apply
264/// it, whichever assembler produced them (the engine's
265/// `export_mem_to_bytes`, this module's [`assemble_archive`]). An archive
266/// with no anchors member returns byte-identical input. Every member is
267/// rewritten with the same deterministic options the assembler uses; the
268/// registry's canonical re-pack normalises the bytes again regardless.
269pub fn redact_archive_anchors(archive: &[u8]) -> Result<Vec<u8>, AssembleError> {
270    use crate::anchor::{ANCHOR_SIDECAR_PATH, AnchorSidecar};
271    use std::io::Read as _;
272
273    let mut zip = zip::ZipArchive::new(Cursor::new(archive))
274        .map_err(|e| AssembleError::Anchors(format!("read archive: {e}")))?;
275    let names: Vec<String> = zip
276        .file_names()
277        .map(|n| n.map(|c| c.into_owned()))
278        .collect::<Result<_, _>>()
279        .map_err(|e| AssembleError::Anchors(format!("read member name: {e}")))?;
280    if !names.iter().any(|n| n == ANCHOR_SIDECAR_PATH) {
281        return Ok(archive.to_vec());
282    }
283
284    let mut buf: Vec<u8> = Vec::new();
285    {
286        let cursor = Cursor::new(&mut buf);
287        let mut out = zip::ZipWriter::new(cursor);
288        let opts = SimpleFileOptions::default()
289            .compression_method(CompressionMethod::Stored)
290            .last_modified_time(zip::DateTime::default());
291        for index in 0..zip.len() {
292            let mut member = zip
293                .by_index(index)
294                .map_err(|e| AssembleError::Anchors(format!("read member: {e}")))?;
295            let name = member
296                .name()
297                .map_err(|e| AssembleError::Anchors(format!("read member name: {e}")))?
298                .into_owned();
299            let mut bytes = Vec::new();
300            member
301                .read_to_end(&mut bytes)
302                .map_err(|e| AssembleError::Io(format!("read member {name}: {e}")))?;
303            if name == ANCHOR_SIDECAR_PATH {
304                let mut sidecar = AnchorSidecar::from_bytes(&bytes)
305                    .map_err(|e| AssembleError::Anchors(e.to_string()))?;
306                sidecar.redact_artifact_references();
307                bytes = sidecar.to_bytes();
308            }
309            out.start_file(&name, opts)?;
310            out.write_all(&bytes)
311                .map_err(|e| AssembleError::Io(format!("write member {name}: {e}")))?;
312        }
313        out.finish()?;
314    }
315    Ok(buf)
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::filesystem::config::{WorkspaceConfig, write_workspace_config};
322    use crate::validator::ValidatorLimits;
323    use crate::validator::archive::extract_entries;
324    use memstead_schema::SchemaRef;
325    use std::path::PathBuf;
326    use tempfile::TempDir;
327
328    fn versioned(name: &str, version: &str) -> SchemaRef {
329        SchemaRef::new(name, semver::Version::parse(version).unwrap())
330    }
331
332    /// Create the mem in a folder *named after it* (identity is path-derived
333    /// under the unified layout) and return the mem root.
334    fn write_workspace(tmp: &TempDir, name: &str, with_version: bool) -> PathBuf {
335        let root = tmp.path().join(name);
336        std::fs::create_dir_all(&root).unwrap();
337        // `WorkspaceConfig::new` now seeds `version = Some(0.1.0)`
338        // by default. To simulate the pre-gate / externally-imported
339        // config in the no-version test path, clear it explicitly.
340        let mut cfg = WorkspaceConfig::new(name, versioned("default", "1.0.0"));
341        if with_version {
342            cfg.description = Some("test mem".into());
343        } else {
344            cfg.version = None;
345        }
346        write_workspace_config(&root, &cfg).unwrap();
347        root
348    }
349
350    /// Write a minimal valid spec entity directly to disk.
351    /// `assemble_archive` walks the directory itself so the entity
352    /// just needs to exist on disk in canonical markdown form.
353    fn write_spec(root: &Path, slug: &str, title: &str) {
354        std::fs::write(
355            root.join(format!("{slug}.md")),
356            format!("---\ntype: spec\n---\n# {title}\n"),
357        )
358        .unwrap();
359    }
360
361    #[test]
362    fn assemble_archive_round_trips_through_validator() {
363        let tmp = TempDir::new().unwrap();
364        let root = write_workspace(&tmp, "demo", true);
365
366        // Two entities so the archive has a non-empty markdown set.
367        write_spec(&root, "first", "First");
368        write_spec(&root, "second", "Second");
369
370        let bytes = assemble_archive(&root).expect("archive must build");
371        assert!(!bytes.is_empty());
372
373        // Round-trip through the same validator the registry uses.
374        let limits = ValidatorLimits::default();
375        let entries = extract_entries(&bytes, &limits).expect("validator must accept");
376
377        // Config: present and projects to the archive shape (no `deps`).
378        let cfg_text = String::from_utf8_lossy(&entries.config_bytes);
379        assert!(cfg_text.contains("\"name\": \"demo\""));
380        assert!(cfg_text.contains("\"version\": \"0.1.0\""));
381        assert!(!cfg_text.contains("\"deps\""), "deps must drop on publish");
382
383        // Schema: at least the manifest is present.
384        let schema_paths: Vec<_> = entries
385            .schema_files
386            .iter()
387            .map(|s| s.archive_path.as_str())
388            .collect();
389        assert!(schema_paths.contains(&".memstead/schema/schema.yaml"));
390
391        // Entities: both markdown files made it in.
392        let md_paths: Vec<_> = entries
393            .markdown_files
394            .iter()
395            .map(|m| m.path.as_str())
396            .collect();
397        assert!(md_paths.contains(&"first.md"));
398        assert!(md_paths.contains(&"second.md"));
399    }
400
401    /// The engine-agnostic assembler embeds the mem's anchors sidecar —
402    /// closing the gap where a bare `memstead publish` of a folder mem
403    /// silently shipped without the anchors its engine-exported sibling
404    /// carries. A malformed sidecar refuses (never a silent drop); an
405    /// anchorless (empty-entities) sidecar file embeds no member; and
406    /// [`redact_archive_anchors`] over the assembled bytes blanks the
407    /// references while the package keeps validating.
408    #[test]
409    fn assemble_archive_embeds_and_redacts_anchors() {
410        let tmp = TempDir::new().unwrap();
411        let root = write_workspace(&tmp, "demo", true);
412        write_spec(&root, "first", "First");
413        std::fs::write(
414            root.join(".memstead").join("anchors.json"),
415            br#"{"version":1,"entities":{"demo--first":[{"artifact":"src/private.rs","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#,
416        )
417        .unwrap();
418
419        let bytes = assemble_archive(&root).expect("archive must build");
420        let limits = ValidatorLimits::default();
421        let entries = extract_entries(&bytes, &limits).expect("validator must accept");
422        let sidecar_bytes = entries.anchors_bytes.expect("anchors member embedded");
423        assert!(String::from_utf8_lossy(&sidecar_bytes).contains("src/private.rs"));
424
425        // Redaction over the assembled bytes: sentinel in, identity out,
426        // and the package still validates.
427        let redacted = redact_archive_anchors(&bytes).unwrap();
428        let entries = extract_entries(&redacted, &limits).expect("redacted archive validates");
429        let sidecar =
430            crate::anchor::AnchorSidecar::from_bytes(&entries.anchors_bytes.unwrap()).unwrap();
431        assert_eq!(
432            sidecar.get("demo--first")[0].artifact,
433            crate::anchor::REDACTED_ARTIFACT_SENTINEL
434        );
435        assert!(!String::from_utf8_lossy(&redacted).contains("src/private.rs"));
436
437        // An empty-entities sidecar embeds no member.
438        std::fs::write(
439            root.join(".memstead").join("anchors.json"),
440            br#"{"version":1,"entities":{}}"#,
441        )
442        .unwrap();
443        let bytes = assemble_archive(&root).unwrap();
444        assert!(
445            extract_entries(&bytes, &limits)
446                .unwrap()
447                .anchors_bytes
448                .is_none(),
449            "no anchors ⇒ no member"
450        );
451
452        // A malformed sidecar refuses the assembly.
453        std::fs::write(root.join(".memstead").join("anchors.json"), b"{ nope").unwrap();
454        assert!(matches!(
455            assemble_archive(&root),
456            Err(AssembleError::Anchors(_))
457        ));
458    }
459
460    #[test]
461    fn assemble_archive_resolves_installed_workspace_schema() {
462        // Regression: bare `memstead publish` / `memstead export --format
463        // mem` on a folder workspace pinned to an INSTALLED custom schema
464        // used to fail with "schema <ref> not found — candidate paths
465        // tried: []" because the resolver ran built-in-only. The archive
466        // assembler must consult `.memstead/schemas/<name>@<version>/` —
467        // the `memstead schema install` destination.
468        let tmp = TempDir::new().unwrap();
469        let root = tmp.path().join("demo");
470        std::fs::create_dir_all(&root).unwrap();
471        let mut cfg = WorkspaceConfig::new("demo", versioned("cookbook", "0.1.0"));
472        cfg.description = Some("custom-schema mem".into());
473        write_workspace_config(&root, &cfg).unwrap();
474
475        // Install-shaped package dir, as `memstead schema install` writes it.
476        let schema_dir = root
477            .join(".memstead")
478            .join("schemas")
479            .join("cookbook@0.1.0");
480        std::fs::create_dir_all(schema_dir.join("types")).unwrap();
481        std::fs::write(
482            schema_dir.join("schema.yaml"),
483            "name: cookbook\nversion: 0.1.0\ndescription: installed-cookbook-manifest\ntypes:\n  - note\n",
484        )
485        .unwrap();
486        std::fs::write(
487            schema_dir.join("types").join("note.yaml"),
488            "name: note\ndescription: test\n",
489        )
490        .unwrap();
491
492        write_spec(&root, "only", "Only");
493
494        let bytes = assemble_archive(&root).expect("installed schema must resolve");
495        let limits = ValidatorLimits::default();
496        let entries = extract_entries(&bytes, &limits).expect("validator must accept");
497
498        // The embedded schema is the *installed* package, not a builtin.
499        let manifest = entries
500            .schema_files
501            .iter()
502            .find(|s| s.archive_path == ".memstead/schema/schema.yaml")
503            .expect("manifest must embed");
504        assert!(
505            manifest.content.contains("installed-cookbook-manifest"),
506            "embedded manifest must come from .memstead/schemas/cookbook@0.1.0"
507        );
508        assert!(
509            entries
510                .schema_files
511                .iter()
512                .any(|s| s.archive_path == ".memstead/schema/types/note.yaml"),
513            "installed type definitions must embed too"
514        );
515    }
516
517    #[test]
518    fn assemble_archive_rejects_workspace_without_version() {
519        let tmp = TempDir::new().unwrap();
520        // Skip `version` on the workspace config — `to_published`
521        // surfaces `MissingVersion`.
522        let root = write_workspace(&tmp, "demo", false);
523
524        let err = assemble_archive(&root).expect_err("missing version must fail");
525        assert!(matches!(
526            err,
527            AssembleError::Config(PublishConversionError::MissingVersion)
528        ));
529    }
530
531    #[test]
532    fn assemble_archive_excludes_engine_internal_dirs() {
533        // The walker already skips `.git/` and `.memstead/`; this is the
534        // contract test that the publish path inherits that behaviour. A
535        // stray markdown file inside the meta dir must NOT land in the
536        // archive's markdown set.
537        let tmp = TempDir::new().unwrap();
538        let root = write_workspace(&tmp, "demo", true);
539        std::fs::write(
540            root.join(".memstead").join("rogue.md"),
541            "---\ntype: spec\n---\n# Rogue\n\n## Identity\n\nNo.\n",
542        )
543        .unwrap();
544
545        write_spec(&root, "visible", "Visible");
546
547        let bytes = assemble_archive(&root).unwrap();
548        let limits = ValidatorLimits::default();
549        let entries = extract_entries(&bytes, &limits).unwrap();
550        let md_paths: Vec<_> = entries
551            .markdown_files
552            .iter()
553            .map(|m| m.path.as_str())
554            .collect();
555        assert!(md_paths.contains(&"visible.md"));
556        assert!(!md_paths.iter().any(|p| p.contains("rogue")));
557    }
558
559    #[test]
560    fn assemble_archive_is_deterministic_across_calls() {
561        let tmp = TempDir::new().unwrap();
562        let root = write_workspace(&tmp, "demo", true);
563        for (slug, title) in [("a", "A"), ("b", "B"), ("c", "C")] {
564            write_spec(&root, slug, title);
565        }
566
567        let bytes1 = assemble_archive(&root).unwrap();
568        let bytes2 = assemble_archive(&root).unwrap();
569        assert_eq!(
570            bytes1, bytes2,
571            "two assemble calls on the same workspace must yield byte-identical archives"
572        );
573    }
574}