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