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    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) -> Result<MemExportResult, MemExportError> {
153    let basename = mem_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
154    let explicit_name = config.name.as_deref().unwrap_or(basename);
155    let out = export_mem_to_bytes(
156        mem_dir,
157        config,
158        workspace_root,
159        workspace_schemas_dir,
160        explicit_name,
161    )?;
162
163    if let Some(parent) = output_path.parent()
164        && !parent.as_os_str().is_empty()
165    {
166        fs::create_dir_all(parent)?;
167    }
168    fs::write(output_path, &out.bytes)?;
169
170    let size_bytes = fs::metadata(output_path)?.len();
171
172    Ok(MemExportResult {
173        unterminated_fence_entities: Vec::new(),
174        archive_path: output_path.display().to_string(),
175        name: out.name,
176        version: out.version,
177        entity_count: out.entity_count,
178        size_bytes,
179        dangling_cross_mem_edges: out.dangling_cross_mem_edges,
180    })
181}
182
183/// Produce a portable `.mem` archive **as bytes** for a folder-backed
184/// mem. Same wire format as [`export_mem`] — same whitelist
185/// projection, same embedded schema source, same deterministic sort
186/// order and fixed mtime — but the output stays in memory so the
187/// bridge / WASM consumers can return it directly over HTTP.
188///
189/// `explicit_name` is the mem name the publish whitelist receives.
190/// Callers reaching this through [`crate::Engine::export_mem_to_bytes`]
191/// pass the mount's mem name; callers reaching it directly choose
192/// the disk basename or a config-supplied alias.
193pub fn export_mem_to_bytes(
194    mem_dir: &Path,
195    config: &MemConfig,
196    workspace_root: Option<&Path>,
197    workspace_schemas_dir: Option<&Path>,
198    explicit_name: &str,
199) -> Result<MemExportBytes, MemExportError> {
200    if !mem_dir.is_dir() {
201        return Err(MemExportError::DirNotFound(mem_dir.display().to_string()));
202    }
203
204    let mut md_files = Vec::new();
205    collect_markdown(mem_dir, &mut md_files)?;
206
207    let mut md_entries: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(md_files.len());
208    for abs in &md_files {
209        let rel = abs
210            .strip_prefix(mem_dir)
211            .expect("markdown file must live under mem_dir");
212        md_entries.push((rel.to_path_buf(), fs::read(abs)?));
213    }
214
215    // Source the per-entity authoring provenance from the folder mem's
216    // own mutation log (`.memstead/changes.jsonl`), read through the folder
217    // backend so the JSONL parsing has one home. A mem with no changelog
218    // yields no records → no provenance member (absent, not empty).
219    use crate::backend::MemBackend;
220    let backend = crate::storage::FilesystemMemWriter::new(mem_dir.to_path_buf());
221    let provenance = backend
222        .read_provenance(None)
223        .ok()
224        .and_then(|records| build_archive_provenance(&records));
225
226    // Source the engine-owned anchors sidecar (`.memstead/anchors.json`)
227    // through the same backend so it travels inside the `.mem` archive.
228    // Absent (a mem with no anchors) → no member, distinct from an empty
229    // sidecar. The recognised-member set + canonical re-pack already accept
230    // and thread it verbatim; export is the producer half of that contract.
231    let anchors_bytes = backend.read_anchors_sidecar().ok().flatten();
232
233    export_entries_to_bytes(
234        config,
235        workspace_root,
236        workspace_schemas_dir,
237        explicit_name,
238        md_entries,
239        provenance.as_ref(),
240        anchors_bytes.as_deref(),
241    )
242}
243
244/// Seal already-collected entity bytes into a portable `.mem` archive —
245/// the storage-agnostic core shared by the folder exporter
246/// ([`export_mem_to_bytes`], which walks a directory) and the
247/// in-memory exporter (which lists entities from a
248/// [`crate::backend::MemBackend`] holding them in RAM). Same wire
249/// format either way: whitelist config projection, embedded schema
250/// source, deterministic path-sorted entries, fixed mtime, and the same
251/// pre-write lenient validation pass.
252///
253/// `md_entries` are `(mem-relative path, bytes)` pairs; paths are
254/// posix-normalised for the archive. Entries need not be pre-sorted — the
255/// archive sort makes the output deterministic regardless of input order.
256pub fn export_entries_to_bytes(
257    config: &MemConfig,
258    workspace_root: Option<&Path>,
259    workspace_schemas_dir: Option<&Path>,
260    explicit_name: &str,
261    md_entries: Vec<(PathBuf, Vec<u8>)>,
262    provenance: Option<&ArchiveProvenance>,
263    anchors_bytes: Option<&[u8]>,
264) -> Result<MemExportBytes, MemExportError> {
265    let published = published_config_from(config, explicit_name)?;
266    let config_bytes = canonical_json(&published)
267        .map_err(|e| MemExportError::Canonical(e.to_string()))?
268        .into_bytes();
269
270    let schema_files =
271        collect_schema_source(workspace_root, workspace_schemas_dir, &published.schema)?;
272
273    let entity_count = md_entries.len();
274    let mut all_entries: Vec<(String, Vec<u8>)> =
275        Vec::with_capacity(2 + schema_files.len() + md_entries.len());
276    all_entries.push((ARCHIVE_CONFIG_PATH.to_string(), config_bytes));
277    // Embed the authoring-provenance payload when present. Serialised
278    // canonically; the validator tolerates it as a recognised meta member
279    // and the consumer reads it back via `read_archive_provenance`.
280    if let Some(prov) = provenance
281        && let Ok(bytes) = prov.to_archive_bytes()
282    {
283        all_entries.push((ARCHIVE_PROVENANCE_PATH.to_string(), bytes));
284    }
285    // Embed the engine-owned anchors sidecar verbatim when the mem carries
286    // one. A recognised `.memstead/` member: the archive validator strictly
287    // validates it and the canonical re-pack threads it through unchanged.
288    if let Some(anchors) = anchors_bytes {
289        all_entries.push((ARCHIVE_ANCHORS_PATH.to_string(), anchors.to_vec()));
290    }
291    for sf in &schema_files {
292        all_entries.push((
293            format!("{ARCHIVE_SCHEMA_PREFIX}{}", sf.archive_path),
294            sf.bytes.clone(),
295        ));
296    }
297    for (rel, bytes) in md_entries {
298        all_entries.push((posix_path(&rel), bytes));
299    }
300    all_entries.sort_by(|a, b| a.0.cmp(&b.0));
301
302    let mut buf: Vec<u8> = Vec::new();
303    {
304        let cursor = Cursor::new(&mut buf);
305        let mut zip = zip::ZipWriter::new(cursor);
306        let options = SimpleFileOptions::default()
307            .compression_method(CompressionMethod::Deflated)
308            .last_modified_time(fixed_mtime())
309            .unix_permissions(0o644);
310
311        for (archive_path, bytes) in &all_entries {
312            zip.start_file(archive_path, options)?;
313            zip.write_all(bytes)?;
314        }
315        zip.finish()?;
316    }
317
318    // Strict
319    // archive validation runs against the in-memory bytes before they
320    // leave this function. Export and install share one validator
321    // pass — the trust boundary fires at export rather than letting an
322    // invalid archive land on disk and refuse only at the next install
323    // attempt. If the produced archive doesn't validate (legacy
324    // on-disk drift, hand-edited markdown, archive-imports from
325    // non-canonical sources), surface the typed refusal; the
326    // disk-shaped wrapper (`export_mem`) never writes a broken
327    // archive because validation happens here, pre-write.
328    //
329    // The *lenient* variant collects cross-mem edges (whose target
330    // won't travel inside this single-mem archive) instead of
331    // refusing on them — export warns and still produces, where install
332    // refuses. Every other strict check still refuses, so a
333    // genuinely-broken archive never lands.
334    let validated = crate::validator::validate_and_normalize_archive_lenient(&buf)
335        .map_err(|e| MemExportError::ArchiveValidationFailed(e.to_string()))?;
336
337    Ok(MemExportBytes {
338        bytes: buf,
339        name: published.name.clone(),
340        version: published.version.to_string(),
341        entity_count,
342        dangling_cross_mem_edges: validated.dangling_cross_mem_edges,
343    })
344}
345
346/// Zip's minimum representable timestamp — 1980-01-01 00:00:00. Used
347/// as a fixed mtime so archives are byte-stable across exports.
348fn fixed_mtime() -> DateTime {
349    DateTime::default()
350}
351
352fn posix_path(path: &Path) -> String {
353    path.components()
354        .filter_map(|c| c.as_os_str().to_str())
355        .collect::<Vec<_>>()
356        .join("/")
357}
358
359/// Recursively collect `.md` files. Skips hidden directories and
360/// `README.md` (same policy as the entity loaders — a folder mem living
361/// visibly in a repository tree carries a human-facing README beside its
362/// entity files, and what load skips, export must skip too).
363fn collect_markdown(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), std::io::Error> {
364    let mut children: Vec<_> = fs::read_dir(dir)?.collect::<Result<_, _>>()?;
365    children.sort_by_key(|e| e.file_name());
366
367    for entry in children {
368        let path = entry.path();
369        let name = entry.file_name();
370        let name = name.to_string_lossy();
371
372        if path.is_dir() {
373            if name.starts_with('.') {
374                continue;
375            }
376            collect_markdown(&path, out)?;
377        } else if name.ends_with(".md") && name.as_ref() != "README.md" {
378            out.push(path);
379        }
380    }
381    Ok(())
382}