Skip to main content

memstead_base/ops/
export.rs

1//! Mem-archive export.
2//!
3//! The folder-shaped export (the gix-free path) lives here so the
4//! unified `Engine::export_mem` can call it without crossing into
5//! `memstead-git-branch`. The git-branch-shaped variant
6//! (`export_mem_from_branch`) stays in `memstead-git-branch::ops::export`
7//! because it walks a gitdir.
8//!
9//! Output wire shape is deterministic and matches the git-branch
10//! variant byte-for-byte for equivalent input: `.memstead/config.json`
11//! carries the whitelist-projection of the author's `MemConfig`,
12//! `.memstead/schema/` embeds the pinned schema's source files, and the
13//! mem's `.md` blobs land at their mem-relative paths. Entries are
14//! sorted by path and zip-stamped with a fixed mtime so identical
15//! input produces byte-identical archives.
16
17use std::fs;
18use std::io::{Cursor, Write};
19use std::path::{Path, PathBuf};
20
21use memstead_schema::{
22    ARCHIVE_ANCHORS_PATH, ARCHIVE_CONFIG_PATH, ARCHIVE_PROVENANCE_PATH, ARCHIVE_SCHEMA_PREFIX,
23    ArchiveProvenance, EntityProvenance, MemConfig, PublishConversionError, SchemaSourceError,
24    SchemaSourceFile, collect_schema_source, published_config_from,
25};
26use zip::{CompressionMethod, DateTime, write::SimpleFileOptions};
27
28use crate::entity::EntityId;
29use crate::ops::MemExportResult;
30use crate::provenance::Provenance;
31use crate::validator::canonical::canonical_json;
32
33/// Build the per-entity authoring-provenance payload from a backend's
34/// mutation log (`read_provenance`). Keys by each entity's mem-relative
35/// path ([`EntityId::path`]) so the payload survives a remount under a
36/// different mem name. For each entity, keeps the most recent record
37/// that carries a non-empty note — the entity's *current* rationale.
38///
39/// No-fabrication: records with no entity (batch) or no note are skipped,
40/// so an entity authored without rationale is simply absent from the
41/// payload (the read path reports it absent). Returns `None` when no
42/// entity carried a note — the export then ships no provenance member,
43/// distinct from an empty payload.
44pub fn build_archive_provenance(records: &[Provenance]) -> Option<ArchiveProvenance> {
45    use std::collections::BTreeMap;
46    use std::time::SystemTime;
47
48    let mut by_path: BTreeMap<String, (SystemTime, EntityProvenance)> = BTreeMap::new();
49    for r in records {
50        let Some(entity) = r.entity.as_deref() else {
51            continue;
52        };
53        let Some(note) = r.note.as_deref().map(str::trim).filter(|n| !n.is_empty()) else {
54            continue;
55        };
56        let path = EntityId(entity.to_string()).path().to_string();
57        if path.is_empty() {
58            continue;
59        }
60        let candidate = EntityProvenance {
61            rationale: Some(note.to_string()),
62            kind: Some(r.kind.as_str().to_string()),
63            timestamp: Some(crate::filesystem::changelog::format_rfc3339_utc(
64                r.timestamp,
65            )),
66            actor: Some(r.actor.as_trailer().to_string()),
67        };
68        match by_path.get(&path) {
69            // Keep the existing entry when it is at least as recent.
70            Some((ts, _)) if *ts >= r.timestamp => {}
71            _ => {
72                by_path.insert(path, (r.timestamp, candidate));
73            }
74        }
75    }
76    if by_path.is_empty() {
77        return None;
78    }
79    Some(ArchiveProvenance::summarised(
80        by_path.into_iter().map(|(k, (_, v))| (k, v)).collect(),
81    ))
82}
83
84/// Byte-shaped output of [`export_mem_to_bytes`]. Bundles the
85/// produced archive bytes with the same metadata
86/// [`MemExportResult`] reports for path-based exports.
87#[derive(Debug, Clone)]
88pub struct MemExportBytes {
89    /// The `.mem` archive bytes — self-contained, ready to validate
90    /// via `extract_entries` and hydrate via `Engine::from_archive_bytes`.
91    pub bytes: Vec<u8>,
92    /// Mem name (mirrors `MemExportResult.name`).
93    pub name: String,
94    /// Mem version (mirrors `MemExportResult.version`).
95    pub version: String,
96    /// `.md` entity count in the produced archive.
97    pub entity_count: usize,
98    /// Cross-mem edges whose target won't travel inside this archive —
99    /// `install` will reject each. Mirrors
100    /// `MemExportResult.dangling_cross_mem_edges`; empty for a
101    /// self-contained export.
102    pub dangling_cross_mem_edges: Vec<crate::validator::DanglingCrossMemEdge>,
103}
104
105#[derive(Debug, thiserror::Error)]
106pub enum MemExportError {
107    #[error("mem directory not found: {0}")]
108    DirNotFound(String),
109    #[error(transparent)]
110    Convert(#[from] PublishConversionError),
111    #[error("io error: {0}")]
112    Io(#[from] std::io::Error),
113    #[error("zip error: {0}")]
114    Zip(#[from] zip::result::ZipError),
115    #[error("config serialization error: {0}")]
116    Canonical(String),
117    #[error(transparent)]
118    SchemaSource(#[from] SchemaSourceError),
119    #[error("branch read error: {0}")]
120    BranchRead(String),
121    /// The
122    /// produced archive failed strict validation. Reaches this state
123    /// when the mem carries on-disk drift from a pre-fix engine —
124    /// entities created when `MISSING_REQUIRED_SECTION` was a
125    /// warning, hand-edited markdown, or archive-imports from
126    /// non-canonical sources. Export and install share one strict
127    /// validator pass; the trust boundary now fires at export rather
128    /// than letting an invalid archive land on disk and refuse only
129    /// at the next install attempt.
130    #[error("export archive failed strict validation: {0}")]
131    ArchiveValidationFailed(String),
132}
133
134/// Export a mem directory as a portable `.mem` archive.
135///
136/// The archive contains `.memstead/config.json` (a **whitelist projection**
137/// of the author's `MemConfig` — author-only fields like
138/// `writeGuidance`, `mediums`, `projections`, `readMems` never enter
139/// the archive), every `.md` file under the mem root, and the pinned
140/// schema's source YAML under `schema/`.
141///
142/// Output is deterministic — entries are sorted by path and written
143/// with a fixed modification time — so identical input produces
144/// byte-identical archives, and archives produced here round-trip
145/// through `validate_and_normalize_archive` without rewriting.
146pub fn export_mem(
147    mem_dir: &Path,
148    config: &MemConfig,
149    output_path: &Path,
150    workspace_root: Option<&Path>,
151    workspace_schemas_dir: Option<&Path>,
152    ref_schema_source: Option<Vec<SchemaSourceFile>>,
153) -> Result<MemExportResult, MemExportError> {
154    let basename = mem_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
155    let explicit_name = config.name.as_deref().unwrap_or(basename);
156    let out = export_mem_to_bytes(
157        mem_dir,
158        config,
159        workspace_root,
160        workspace_schemas_dir,
161        explicit_name,
162        ref_schema_source,
163    )?;
164
165    if let Some(parent) = output_path.parent()
166        && !parent.as_os_str().is_empty()
167    {
168        fs::create_dir_all(parent)?;
169    }
170    fs::write(output_path, &out.bytes)?;
171
172    let size_bytes = fs::metadata(output_path)?.len();
173
174    Ok(MemExportResult {
175        unterminated_fence_entities: Vec::new(),
176        archive_path: output_path.display().to_string(),
177        name: out.name,
178        version: out.version,
179        entity_count: out.entity_count,
180        size_bytes,
181        dangling_cross_mem_edges: out.dangling_cross_mem_edges,
182    })
183}
184
185/// Produce a portable `.mem` archive **as bytes** for a folder-backed
186/// mem. Same wire format as [`export_mem`] — same whitelist
187/// projection, same embedded schema source, same deterministic sort
188/// order and fixed mtime — but the output stays in memory so the
189/// bridge / WASM consumers can return it directly over HTTP.
190///
191/// `explicit_name` is the mem name the publish whitelist receives.
192/// Callers reaching this through [`crate::Engine::export_mem_to_bytes`]
193/// pass the mount's mem name; callers reaching it directly choose
194/// the disk basename or a config-supplied alias.
195///
196/// `ref_schema_source`: pre-collected schema source files from the
197/// workspace's `__MEMSTEAD:schemas/` ref (git-branch schema store).
198/// `Some` takes precedence over the disk/builtin chain — the same
199/// precedence the git-branch export path applies — so a folder mem in
200/// a mem-repo workspace seals the schema the loader resolved. `None`
201/// keeps the historical disk/builtin chain unchanged.
202pub fn export_mem_to_bytes(
203    mem_dir: &Path,
204    config: &MemConfig,
205    workspace_root: Option<&Path>,
206    workspace_schemas_dir: Option<&Path>,
207    explicit_name: &str,
208    ref_schema_source: Option<Vec<SchemaSourceFile>>,
209) -> Result<MemExportBytes, MemExportError> {
210    if !mem_dir.is_dir() {
211        return Err(MemExportError::DirNotFound(mem_dir.display().to_string()));
212    }
213
214    let mut md_files = Vec::new();
215    collect_markdown(mem_dir, &mut md_files)?;
216
217    let mut md_entries: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(md_files.len());
218    for abs in &md_files {
219        let rel = abs
220            .strip_prefix(mem_dir)
221            .expect("markdown file must live under mem_dir");
222        md_entries.push((rel.to_path_buf(), fs::read(abs)?));
223    }
224
225    // Source the per-entity authoring provenance from the folder mem's
226    // own mutation log (`.memstead/changes.jsonl`), read through the folder
227    // backend so the JSONL parsing has one home. A mem with no changelog
228    // yields no records → no provenance member (absent, not empty).
229    use crate::backend::MemBackend;
230    let backend = crate::storage::FilesystemMemWriter::new(mem_dir.to_path_buf());
231    let provenance = backend
232        .read_provenance(None)
233        .ok()
234        .and_then(|records| build_archive_provenance(&records));
235
236    // Source the engine-owned anchors sidecar (`.memstead/anchors.json`)
237    // through the same backend so it travels inside the `.mem` archive.
238    // Absent (a mem with no anchors) → no member, distinct from an empty
239    // sidecar. The recognised-member set + canonical re-pack already accept
240    // and thread it verbatim; export is the producer half of that contract.
241    let anchors_bytes = backend.read_anchors_sidecar().ok().flatten();
242
243    export_entries_to_bytes(
244        config,
245        workspace_root,
246        workspace_schemas_dir,
247        explicit_name,
248        md_entries,
249        provenance.as_ref(),
250        anchors_bytes.as_deref(),
251        ref_schema_source,
252    )
253}
254
255/// Seal already-collected entity bytes into a portable `.mem` archive —
256/// the storage-agnostic core shared by the folder exporter
257/// ([`export_mem_to_bytes`], which walks a directory) and the
258/// in-memory exporter (which lists entities from a
259/// [`crate::backend::MemBackend`] holding them in RAM). Same wire
260/// format either way: whitelist config projection, embedded schema
261/// source, deterministic path-sorted entries, fixed mtime, and the same
262/// pre-write lenient validation pass.
263///
264/// `md_entries` are `(mem-relative path, bytes)` pairs; paths are
265/// posix-normalised for the archive. Entries need not be pre-sorted — the
266/// archive sort makes the output deterministic regardless of input order.
267#[allow(clippy::too_many_arguments)]
268pub fn export_entries_to_bytes(
269    config: &MemConfig,
270    workspace_root: Option<&Path>,
271    workspace_schemas_dir: Option<&Path>,
272    explicit_name: &str,
273    md_entries: Vec<(PathBuf, Vec<u8>)>,
274    provenance: Option<&ArchiveProvenance>,
275    anchors_bytes: Option<&[u8]>,
276    ref_schema_source: Option<Vec<SchemaSourceFile>>,
277) -> Result<MemExportBytes, MemExportError> {
278    let published = published_config_from(config, explicit_name)?;
279    let config_bytes = canonical_json(&published)
280        .map_err(|e| MemExportError::Canonical(e.to_string()))?
281        .into_bytes();
282
283    // The git-branch schema store wins where the caller resolved it —
284    // the same precedence the git-branch export path applies — so a
285    // schema sealed by `memstead schema install` on the `__MEMSTEAD`
286    // ref exports for folder mems too, not only for branch mems.
287    let schema_files = match ref_schema_source {
288        Some(files) => files,
289        None => collect_schema_source(workspace_root, workspace_schemas_dir, &published.schema)?,
290    };
291
292    let entity_count = md_entries.len();
293    let mut all_entries: Vec<(String, Vec<u8>)> =
294        Vec::with_capacity(2 + schema_files.len() + md_entries.len());
295    all_entries.push((ARCHIVE_CONFIG_PATH.to_string(), config_bytes));
296    // Embed the authoring-provenance payload when present. Serialised
297    // canonically; the validator tolerates it as a recognised meta member
298    // and the consumer reads it back via `read_archive_provenance`.
299    if let Some(prov) = provenance
300        && let Ok(bytes) = prov.to_archive_bytes()
301    {
302        all_entries.push((ARCHIVE_PROVENANCE_PATH.to_string(), bytes));
303    }
304    // Embed the engine-owned anchors sidecar verbatim when the mem carries
305    // one. A recognised `.memstead/` member: the archive validator strictly
306    // validates it and the canonical re-pack threads it through unchanged.
307    if let Some(anchors) = anchors_bytes {
308        all_entries.push((ARCHIVE_ANCHORS_PATH.to_string(), anchors.to_vec()));
309    }
310    for sf in &schema_files {
311        all_entries.push((
312            format!("{ARCHIVE_SCHEMA_PREFIX}{}", sf.archive_path),
313            sf.bytes.clone(),
314        ));
315    }
316    for (rel, bytes) in md_entries {
317        all_entries.push((posix_path(&rel), bytes));
318    }
319    all_entries.sort_by(|a, b| a.0.cmp(&b.0));
320
321    let mut buf: Vec<u8> = Vec::new();
322    {
323        let cursor = Cursor::new(&mut buf);
324        let mut zip = zip::ZipWriter::new(cursor);
325        let options = SimpleFileOptions::default()
326            .compression_method(CompressionMethod::Deflated)
327            .last_modified_time(fixed_mtime())
328            .unix_permissions(0o644);
329
330        for (archive_path, bytes) in &all_entries {
331            zip.start_file(archive_path, options)?;
332            zip.write_all(bytes)?;
333        }
334        zip.finish()?;
335    }
336
337    // Strict
338    // archive validation runs against the in-memory bytes before they
339    // leave this function. Export and install share one validator
340    // pass — the trust boundary fires at export rather than letting an
341    // invalid archive land on disk and refuse only at the next install
342    // attempt. If the produced archive doesn't validate (legacy
343    // on-disk drift, hand-edited markdown, archive-imports from
344    // non-canonical sources), surface the typed refusal; the
345    // disk-shaped wrapper (`export_mem`) never writes a broken
346    // archive because validation happens here, pre-write.
347    //
348    // The *lenient* variant collects cross-mem edges (whose target
349    // won't travel inside this single-mem archive) instead of
350    // refusing on them — export warns and still produces, where install
351    // refuses. Every other strict check still refuses, so a
352    // genuinely-broken archive never lands.
353    let validated = crate::validator::validate_and_normalize_archive_lenient(&buf)
354        .map_err(|e| MemExportError::ArchiveValidationFailed(e.to_string()))?;
355
356    Ok(MemExportBytes {
357        bytes: buf,
358        name: published.name.clone(),
359        version: published.version.to_string(),
360        entity_count,
361        dangling_cross_mem_edges: validated.dangling_cross_mem_edges,
362    })
363}
364
365/// Zip's minimum representable timestamp — 1980-01-01 00:00:00. Used
366/// as a fixed mtime so archives are byte-stable across exports.
367fn fixed_mtime() -> DateTime {
368    DateTime::default()
369}
370
371fn posix_path(path: &Path) -> String {
372    path.components()
373        .filter_map(|c| c.as_os_str().to_str())
374        .collect::<Vec<_>>()
375        .join("/")
376}
377
378/// Recursively collect `.md` files. Skips hidden directories and
379/// `README.md` (same policy as the entity loaders — a folder mem living
380/// visibly in a repository tree carries a human-facing README beside its
381/// entity files, and what load skips, export must skip too).
382fn collect_markdown(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), std::io::Error> {
383    let mut children: Vec<_> = fs::read_dir(dir)?.collect::<Result<_, _>>()?;
384    children.sort_by_key(|e| e.file_name());
385
386    for entry in children {
387        let path = entry.path();
388        let name = entry.file_name();
389        let name = name.to_string_lossy();
390
391        if path.is_dir() {
392            if name.starts_with('.') {
393                continue;
394            }
395            collect_markdown(&path, out)?;
396        } else if name.ends_with(".md") && name.as_ref() != "README.md" {
397            out.push(path);
398        }
399    }
400    Ok(())
401}