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