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_CHECKS_PATH, ARCHIVE_CONFIG_PATH, ARCHIVE_PROVENANCE_PATH,
23 ARCHIVE_SCHEMA_PREFIX, ArchiveProvenance, EntityProvenance, MemConfig, PublishConversionError,
24 SchemaSourceError, 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 only when it is strictly more recent:
106 // the records arrive oldest first and commit times have
107 // one-second resolution, so of two notes in the same second the
108 // later one is the newer and replaces the earlier.
109 Some((ts, _)) if *ts > r.timestamp => {}
110 _ => {
111 by_path.insert(path, (r.timestamp, (candidate, counts)));
112 }
113 }
114 }
115 // Every carried entity gets a record: no rationale where none was
116 // noted, never an absent key that a reader could mistake for a lost
117 // member.
118 for path in entity_paths {
119 by_path.entry(path.clone()).or_insert_with(|| {
120 (
121 SystemTime::UNIX_EPOCH,
122 (EntityProvenance::default(), BTreeMap::new()),
123 )
124 });
125 }
126 let mut redacted_total: BTreeMap<&'static str, usize> = BTreeMap::new();
127 let mut entities = BTreeMap::new();
128 for (k, (_, (v, counts))) in by_path {
129 crate::ops::redaction::tally(&mut redacted_total, counts);
130 entities.insert(k, v);
131 }
132 (
133 ArchiveProvenance::summarised(entities),
134 crate::ops::redaction::counts_to_list(&redacted_total),
135 )
136}
137
138/// What the source engine derives for one ledger record at export time,
139/// for the archive to carry: facts the mount cannot re-derive because it
140/// holds neither the mem's history nor the deployment's identity roster.
141#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
142pub struct SealedRowFacts {
143 /// The author≠checker reading
144 /// ([`crate::Engine::independence_of`]). `None` seals none.
145 pub independence: Option<crate::engine::independence::Independence>,
146 /// The trust class of the row's prose
147 /// ([`crate::Engine::check_row_origin_class`]). `None` seals none,
148 /// which is the undeclared case: every reader then inherits the mem's
149 /// class, as it did before the field existed.
150 pub origin: Option<crate::render::OriginClass>,
151}
152
153/// The export's one source for both ([`crate::Engine::sealed_row_reader`]).
154pub type SealedRowReader<'a> = &'a dyn Fn(&crate::check::CheckRecord) -> SealedRowFacts;
155
156/// Build the sealed check-records member from a workspace ledger: for
157/// every entity the archive carries (`entity_paths`, the mem-relative
158/// paths), the latest ledger record per kind, as [`crate::check::SealedChecks`].
159/// Records of other mems, and records of entities the archive does not
160/// carry (deleted since the check), are not sealed; the method note
161/// passes through the same private-pattern redaction the provenance
162/// member applies, and identities travel verbatim. Each sealed record
163/// carries the author≠checker independence reading `independence`
164/// derives for it (the archive mount serves that reading, having no
165/// history to derive one from); without a reader, none. `None` when no
166/// record qualifies, so a mem with no record exports byte-identically
167/// to one exported by an engine without this member.
168pub fn build_redacted_sealed_checks(
169 records: &[crate::check::CheckRecord],
170 mem_name: &str,
171 entity_paths: &[String],
172 rows: Option<SealedRowReader<'_>>,
173) -> (
174 Option<crate::check::SealedChecks>,
175 Vec<crate::ops::redaction::RedactionCount>,
176) {
177 use std::collections::BTreeMap;
178
179 let carried: std::collections::BTreeSet<&str> =
180 entity_paths.iter().map(String::as_str).collect();
181 // `records` arrive in standing order
182 // ([`crate::check::CheckLedger::in_standing_order`]): a later row of
183 // the same (entity, kind) supersedes an earlier one, exactly as
184 // `latest_for_wire_kind` reads the ledger.
185 let mut latest: BTreeMap<String, BTreeMap<String, crate::check::CheckRecord>> = BTreeMap::new();
186 for rec in records {
187 let id = EntityId(rec.entity.clone());
188 if id.mem() != mem_name || !carried.contains(id.path()) {
189 continue;
190 }
191 let kind = crate::check::sealed_kind_of(rec);
192 if kind.is_empty() {
193 continue;
194 }
195 latest
196 .entry(id.path().to_string())
197 .or_default()
198 .insert(kind, rec.clone());
199 }
200 if latest.is_empty() {
201 return (None, Vec::new());
202 }
203 let mut redacted_total: BTreeMap<&'static str, usize> = BTreeMap::new();
204 let mut sealed = crate::check::SealedChecks::new();
205 for (path, kinds) in latest {
206 let mut out = BTreeMap::new();
207 for (kind, rec) in kinds {
208 let mut sc = crate::check::SealedCheck::from_record(&rec);
209 let facts = rows.map(|read| read(&rec)).unwrap_or_default();
210 sc.independence = facts.independence.map(|r| r.as_str().to_string());
211 sc.origin = facts.origin.map(|c| c.as_wire().to_string());
212 if let Some(m) = sc.method.take() {
213 let (m, counts) = crate::ops::redaction::redact(&m);
214 crate::ops::redaction::tally(&mut redacted_total, counts);
215 sc.method = Some(m);
216 }
217 out.insert(kind, sc);
218 }
219 sealed.entities.insert(path, out);
220 }
221 (
222 Some(sealed),
223 crate::ops::redaction::counts_to_list(&redacted_total),
224 )
225}
226
227/// The sealed check-records member bytes for a mem, read from the
228/// workspace ledger when the engine has a workspace root: `None` (no
229/// member) without a root, without a ledger, or without a qualifying
230/// record. One reader for every export path, so the three storage arms
231/// seal the same bytes for the same ledger. `independence` is the
232/// engine's reader of the reading each record is sealed with
233/// ([`build_redacted_sealed_checks`]).
234pub fn sealed_checks_bytes_for(
235 workspace_root: Option<&Path>,
236 mem_name: &str,
237 entity_paths: &[String],
238 rows: Option<SealedRowReader<'_>>,
239) -> (Option<Vec<u8>>, Vec<crate::ops::redaction::RedactionCount>) {
240 let Some(root) = workspace_root else {
241 return (None, Vec::new());
242 };
243 let records = crate::check::CheckLedger::for_workspace(root).in_standing_order();
244 let (sealed, redactions) = build_redacted_sealed_checks(&records, mem_name, entity_paths, rows);
245 (sealed.and_then(|s| s.to_archive_bytes().ok()), redactions)
246}
247
248/// Fold two export paths' redaction counts into one list, in vocabulary
249/// order (the provenance member's and the checks member's).
250pub fn merge_redactions(
251 a: Vec<crate::ops::redaction::RedactionCount>,
252 b: Vec<crate::ops::redaction::RedactionCount>,
253) -> Vec<crate::ops::redaction::RedactionCount> {
254 use std::collections::BTreeMap;
255 let mut total: BTreeMap<&'static str, usize> = BTreeMap::new();
256 for rc in a.iter().chain(b.iter()) {
257 if let Some(class) = crate::ops::redaction::REDACTION_CLASSES
258 .iter()
259 .find(|c| c.name == rc.class)
260 {
261 *total.entry(class.name).or_insert(0) += rc.count;
262 }
263 }
264 crate::ops::redaction::counts_to_list(&total)
265}
266
267/// Byte-shaped output of [`export_mem_to_bytes`]. Bundles the
268/// produced archive bytes with the same metadata
269/// [`MemExportResult`] reports for path-based exports.
270#[derive(Debug, Clone)]
271pub struct MemExportBytes {
272 /// The `.mem` archive bytes — self-contained, ready to validate
273 /// via `extract_entries` and hydrate via `Engine::from_archive_bytes`.
274 pub bytes: Vec<u8>,
275 /// Mem name (mirrors `MemExportResult.name`).
276 pub name: String,
277 /// Mem version (mirrors `MemExportResult.version`).
278 pub version: String,
279 /// `.md` entity count in the produced archive.
280 pub entity_count: usize,
281 /// Per-class private-pattern redactions in the provenance and the
282 /// sealed-checks members (mirrors `MemExportResult.redactions`);
283 /// empty when none.
284 pub redactions: Vec<crate::ops::redaction::RedactionCount>,
285 /// Cross-mem edges whose target won't travel inside this archive —
286 /// `install` will reject each. Mirrors
287 /// `MemExportResult.dangling_cross_mem_edges`; empty for a
288 /// self-contained export.
289 pub dangling_cross_mem_edges: Vec<crate::validator::DanglingCrossMemEdge>,
290}
291
292#[derive(Debug, thiserror::Error)]
293pub enum MemExportError {
294 #[error("mem directory not found: {0}")]
295 DirNotFound(String),
296 #[error(transparent)]
297 Convert(#[from] PublishConversionError),
298 #[error("io error: {0}")]
299 Io(#[from] std::io::Error),
300 #[error("zip error: {0}")]
301 Zip(#[from] zip::result::ZipError),
302 #[error("config serialization error: {0}")]
303 Canonical(String),
304 #[error(transparent)]
305 SchemaSource(#[from] SchemaSourceError),
306 #[error("branch read error: {0}")]
307 BranchRead(String),
308 /// The
309 /// produced archive failed strict validation. Reaches this state
310 /// when the mem carries on-disk drift from a pre-fix engine —
311 /// entities created when `MISSING_REQUIRED_SECTION` was a
312 /// warning, hand-edited markdown, or archive-imports from
313 /// non-canonical sources. Export and install share one strict
314 /// validator pass; the trust boundary now fires at export rather
315 /// than letting an invalid archive land on disk and refuse only
316 /// at the next install attempt.
317 #[error("export archive failed strict validation: {0}")]
318 ArchiveValidationFailed(String),
319}
320
321/// Export a mem directory as a portable `.mem` archive.
322///
323/// The archive contains `.memstead/config.json` (a **whitelist projection**
324/// of the author's `MemConfig` — author-only fields like
325/// `writeGuidance`, `mediums`, `projections`, `readMems` never enter
326/// the archive), every `.md` file under the mem root, and the pinned
327/// schema's source YAML under `schema/`.
328///
329/// Output is deterministic — entries are sorted by path and written
330/// with a fixed modification time — so identical input produces
331/// byte-identical archives, and archives produced here round-trip
332/// through `validate_and_normalize_archive` without rewriting.
333pub fn export_mem(
334 mem_dir: &Path,
335 config: &MemConfig,
336 output_path: &Path,
337 workspace_root: Option<&Path>,
338 workspace_schemas_dir: Option<&Path>,
339 ref_schema_source: Option<Vec<SchemaSourceFile>>,
340 rows: Option<SealedRowReader<'_>>,
341) -> Result<MemExportResult, MemExportError> {
342 let basename = mem_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
343 let explicit_name = config.name.as_deref().unwrap_or(basename);
344 let out = export_mem_to_bytes(
345 mem_dir,
346 config,
347 workspace_root,
348 workspace_schemas_dir,
349 explicit_name,
350 ref_schema_source,
351 rows,
352 )?;
353
354 if let Some(parent) = output_path.parent()
355 && !parent.as_os_str().is_empty()
356 {
357 fs::create_dir_all(parent)?;
358 }
359 fs::write(output_path, &out.bytes)?;
360
361 let size_bytes = fs::metadata(output_path)?.len();
362
363 Ok(MemExportResult {
364 unterminated_fence_entities: Vec::new(),
365 archive_path: output_path.display().to_string(),
366 name: out.name,
367 version: out.version,
368 entity_count: out.entity_count,
369 size_bytes,
370 dangling_cross_mem_edges: out.dangling_cross_mem_edges,
371 redactions: out.redactions,
372 })
373}
374
375/// Produce a portable `.mem` archive **as bytes** for a folder-backed
376/// mem. Same wire format as [`export_mem`] — same whitelist
377/// projection, same embedded schema source, same deterministic sort
378/// order and fixed mtime — but the output stays in memory so the
379/// bridge / WASM consumers can return it directly over HTTP.
380///
381/// `explicit_name` is the mem name the publish whitelist receives.
382/// Callers reaching this through [`crate::Engine::export_mem_to_bytes`]
383/// pass the mount's mem name; callers reaching it directly choose
384/// the disk basename or a config-supplied alias.
385///
386/// `ref_schema_source`: pre-collected schema source files from the
387/// workspace's `__MEMSTEAD:schemas/` ref (git-branch schema store).
388/// `Some` takes precedence over the disk/builtin chain — the same
389/// precedence the git-branch export path applies — so a folder mem in
390/// a mem-repo workspace seals the schema the loader resolved. `None`
391/// keeps the historical disk/builtin chain unchanged.
392///
393/// `independence`: the engine's reader of the independence reading each
394/// sealed check record carries ([`sealed_checks_bytes_for`]); a caller
395/// without an engine passes `None` and seals records without one.
396pub fn export_mem_to_bytes(
397 mem_dir: &Path,
398 config: &MemConfig,
399 workspace_root: Option<&Path>,
400 workspace_schemas_dir: Option<&Path>,
401 explicit_name: &str,
402 ref_schema_source: Option<Vec<SchemaSourceFile>>,
403 rows: Option<SealedRowReader<'_>>,
404) -> Result<MemExportBytes, MemExportError> {
405 if !mem_dir.is_dir() {
406 return Err(MemExportError::DirNotFound(mem_dir.display().to_string()));
407 }
408
409 let mut md_files = Vec::new();
410 collect_markdown(mem_dir, &mut md_files)?;
411
412 let mut md_entries: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(md_files.len());
413 for abs in &md_files {
414 let rel = abs
415 .strip_prefix(mem_dir)
416 .expect("markdown file must live under mem_dir");
417 md_entries.push((rel.to_path_buf(), fs::read(abs)?));
418 }
419
420 // Source the per-entity authoring provenance from the folder mem's
421 // own mutation log (`.memstead/changes.jsonl`), read through the folder
422 // backend so the JSONL parsing has one home. A mem with no changelog
423 // yields no rationale, but every entity still gets its record.
424 use crate::backend::MemBackend;
425 let backend = crate::storage::FilesystemBackend::new(mem_dir.to_path_buf());
426 let entity_paths = entity_paths_of(
427 &md_entries
428 .iter()
429 .map(|(p, _)| p.clone())
430 .collect::<Vec<_>>(),
431 );
432 let records = backend.read_provenance(None).unwrap_or_default();
433 let (provenance, redactions) = build_redacted_archive_provenance(&records, &entity_paths);
434
435 // Source the engine-owned anchors sidecar (`.memstead/anchors.json`)
436 // through the same backend so it travels inside the `.mem` archive.
437 // Absent (a mem with no anchors) → no member, distinct from an empty
438 // sidecar. The recognised-member set + canonical re-pack already accept
439 // and thread it verbatim; export is the producer half of that contract.
440 let anchors_bytes = backend.read_anchors_sidecar().ok().flatten();
441
442 // Source the sealed check records from the workspace ledger (the
443 // engine's, never the mem's): the latest record per entity and kind
444 // for the entities this archive carries. No root, no ledger, no
445 // record: no member.
446 let (checks_bytes, check_redactions) =
447 sealed_checks_bytes_for(workspace_root, explicit_name, &entity_paths, rows);
448
449 export_entries_to_bytes(
450 config,
451 workspace_root,
452 workspace_schemas_dir,
453 explicit_name,
454 md_entries,
455 Some(&provenance),
456 anchors_bytes.as_deref(),
457 checks_bytes.as_deref(),
458 ref_schema_source,
459 )
460 .map(|mut r| {
461 r.redactions = merge_redactions(redactions, check_redactions);
462 r
463 })
464}
465
466/// Seal already-collected entity bytes into a portable `.mem` archive —
467/// the storage-agnostic core shared by the folder exporter
468/// ([`export_mem_to_bytes`], which walks a directory) and the
469/// in-memory exporter (which lists entities from a
470/// [`crate::backend::MemBackend`] holding them in RAM). Same wire
471/// format either way: whitelist config projection, embedded schema
472/// source, deterministic path-sorted entries, fixed mtime, and the same
473/// pre-write lenient validation pass.
474///
475/// `md_entries` are `(mem-relative path, bytes)` pairs; paths are
476/// posix-normalised for the archive. Entries need not be pre-sorted — the
477/// archive sort makes the output deterministic regardless of input order.
478/// The archive identity of a mem name: its LEAF segment. A hierarchical
479/// mem (`planning/plan-x`) publishes as `plan-x`: the path is workspace
480/// routing, not mem identity, and the archive format's name grammar
481/// admits no `/`. Flat names pass through unchanged. One definition for
482/// every export path, so an archive's name and the links inside it are
483/// derived by the same rule.
484pub fn archive_identity(mem_name: &str) -> &str {
485 mem_name.rsplit('/').next().unwrap_or(mem_name)
486}
487
488/// Retarget an entity file's mem-qualified wiki-links from the mem's
489/// workspace name to its archive identity: `[[<mem>--slug]]` and
490/// `[[<mem>:slug]]` become `[[<archive>--slug]]` / `[[<archive>:slug]]`.
491/// The archive is validated and installed under the leaf name, so a
492/// link that qualifies itself with the workspace path would read there
493/// as ambiguous (`a/b--slug`) or as a foreign mem (`a/b:slug`) — the
494/// write path accepted it as a self-reference, and the export must not
495/// write what install refuses. A no-op when the two names agree; bytes
496/// that are not UTF-8 pass through untouched (the validator judges them).
497pub fn retarget_mem_links(bytes: Vec<u8>, mem_name: &str, archive_name: &str) -> Vec<u8> {
498 if mem_name == archive_name {
499 return bytes;
500 }
501 match std::str::from_utf8(&bytes) {
502 Ok(text) => {
503 let (out, n) =
504 crate::entity::wikilink_rewrite::rewrite_mem_prefix(text, mem_name, archive_name);
505 if n == 0 { bytes } else { out.into_bytes() }
506 }
507 Err(_) => bytes,
508 }
509}
510
511/// The `content_hash` the loader will derive for an entity from these
512/// bytes, the store's one recipe ([`crate::entity::parser::compute_hash`]
513/// over the file text), so a sealed record is compared against exactly
514/// the hash the mount computes. `None` for bytes that are not UTF-8 (the
515/// validator judges those; no hash of theirs is ever keyed).
516pub fn archived_content_hash(bytes: &[u8]) -> Option<String> {
517 std::str::from_utf8(bytes)
518 .ok()
519 .map(crate::entity::parser::compute_hash)
520}
521
522/// Re-key the sealed check records to the archived entity bytes: for
523/// each `(entity path, pre-rewrite hash, post-rewrite hash)` the export
524/// changed, every record of that entity that was fresh at the
525/// pre-rewrite hash moves to the archived hash and is marked
526/// `carried_from: {hash, reason: "export"}` ([`crate::check::SealedChecks::rekey_entity`]);
527/// a record stale before the export keeps its hash and stays stale on
528/// the mount. The member bytes come back unchanged when nothing moved
529/// (or when they do not parse; the validator refuses those), so a
530/// mem whose bytes the export never rewrites exports byte-identically.
531pub fn rekey_sealed_checks(
532 checks_bytes: Option<Vec<u8>>,
533 rewrites: &[(String, String, String)],
534) -> Option<Vec<u8>> {
535 let bytes = checks_bytes?;
536 if rewrites.is_empty() {
537 return Some(bytes);
538 }
539 let Ok(mut sealed) = crate::check::SealedChecks::from_archive_bytes(&bytes) else {
540 return Some(bytes);
541 };
542 let mut moved = 0;
543 for (path, pre, post) in rewrites {
544 moved += sealed.rekey_entity(path, pre, post);
545 }
546 if moved == 0 {
547 return Some(bytes);
548 }
549 Some(sealed.to_archive_bytes().unwrap_or(bytes))
550}
551
552/// Carry an adopted body's origin marks across the link retarget an export
553/// applies, so a published archive keeps saying which of its bodies came
554/// from a contributor.
555///
556/// A hierarchical mem publishes under its leaf, so the export rewrites every
557/// self-qualified wiki-link in every entity, which moves the bytes a mark
558/// hashes. Unfollowed, the archive serves a contributor's untouched sentences
559/// as its owner's own the moment a consuming deployment vouches for the mem
560/// ([`crate::Engine::declare_mem_origin`]) — the third place this same
561/// rewrite had to be taught to carry the mark, after a rename and a mem
562/// rename.
563///
564/// Only a mark that still held over the pre-rewrite bytes is carried, and
565/// only for the keys the record names, so no schema and no load-bearing set
566/// enters here. Returns the bytes unchanged when there is nothing to carry.
567pub fn rekey_proposal_marks(
568 record_bytes: Option<Vec<u8>>,
569 rewrites: &[(String, ProposalMarkSections, ProposalMarkSections)],
570) -> Option<Vec<u8>> {
571 let bytes = record_bytes?;
572 if rewrites.is_empty() {
573 return Some(bytes);
574 }
575 let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
576 return Some(bytes);
577 };
578 if record.structural_defect().is_some() {
579 // A record the reader calls defective is left exactly as it is, the
580 // stance every write that follows a mark takes: the mem is quarantined
581 // on purpose, and an export that repaired the file would ship an
582 // archive claiming a record it can trust.
583 return Some(bytes);
584 }
585 let mut moved = false;
586 for (slug, was, now) in rewrites {
587 for proposal in &mut record.proposals {
588 let Some(entry) = proposal.entities.get_mut(slug) else {
589 continue;
590 };
591 let Some(marks) = entry.landed_sections.as_mut() else {
592 continue;
593 };
594 for (key, hash) in marks.iter_mut() {
595 let (Some(was), Some(now)) = (was.get(key), now.get(key)) else {
596 continue;
597 };
598 if was == now || &crate::preparation::entity_section_prepared_hash(key, was) != hash
599 {
600 continue;
601 }
602 *hash = crate::preparation::entity_section_prepared_hash(key, now);
603 moved = true;
604 }
605 }
606 }
607 if !moved {
608 return Some(bytes);
609 }
610 Some(record.to_bytes())
611}
612
613/// An entity's sections as the STORE holds them, which is the map the marks
614/// were computed over
615/// ([`crate::preparation::entity_load_bearing_section_marks`]).
616///
617/// The caller derives it, because only the caller has the schema: the store's
618/// map is schema-shaped (a catch-all section's value is the join of its own
619/// content and every undeclared heading re-emitted under it), so a
620/// schema-free re-parse disagrees on exactly those keys and would silently
621/// carry no mark for them, publishing an archive whose marks no longer hold
622/// over its own bytes.
623pub type ProposalMarkSections = indexmap::IndexMap<String, String>;
624
625/// The rewrite triple [`rekey_sealed_checks`] takes, for one entity file
626/// whose bytes the export changed: `None` when the archived bytes hash the
627/// same as the source bytes (nothing to re-key) or either side is not UTF-8.
628pub fn entity_rewrite(rel: &Path, before: &[u8], after: &[u8]) -> Option<(String, String, String)> {
629 let pre = archived_content_hash(before)?;
630 let post = archived_content_hash(after)?;
631 if pre == post {
632 return None;
633 }
634 let path = entity_paths_of(std::slice::from_ref(&rel.to_path_buf())).remove(0);
635 Some((path, pre, post))
636}
637
638#[allow(clippy::too_many_arguments)]
639pub fn export_entries_to_bytes(
640 config: &MemConfig,
641 workspace_root: Option<&Path>,
642 workspace_schemas_dir: Option<&Path>,
643 mem_name: &str,
644 md_entries: Vec<(PathBuf, Vec<u8>)>,
645 provenance: Option<&ArchiveProvenance>,
646 anchors_bytes: Option<&[u8]>,
647 checks_bytes: Option<&[u8]>,
648 ref_schema_source: Option<Vec<SchemaSourceFile>>,
649) -> Result<MemExportBytes, MemExportError> {
650 let explicit_name = archive_identity(mem_name);
651 let published = published_config_from(config, explicit_name)?;
652 let config_bytes = canonical_json(&published)
653 .map_err(|e| MemExportError::Canonical(e.to_string()))?
654 .into_bytes();
655
656 // The git-branch schema store wins where the caller resolved it —
657 // the same precedence the git-branch export path applies — so a
658 // schema sealed by `memstead schema install` on the `__MEMSTEAD`
659 // ref exports for folder mems too, not only for branch mems.
660 let schema_files = match ref_schema_source {
661 Some(files) => files,
662 None => collect_schema_source(workspace_root, workspace_schemas_dir, &published.schema)?,
663 };
664
665 let entity_count = md_entries.len();
666 // A hierarchical mem publishes under its leaf, so every link that
667 // qualifies itself with the workspace path follows the name into the
668 // archive. That rewrite moves the entity's content hash, and a sealed
669 // check record fresh against the source bytes is re-keyed to the
670 // archived bytes so it stays fresh on the mount (a stale one stays
671 // stale). Retargeted before the member is placed, so the member the
672 // archive carries already speaks of the archived bytes.
673 let mut rewrites: Vec<(String, String, String)> = Vec::new();
674 let md_entries: Vec<(PathBuf, Vec<u8>)> = md_entries
675 .into_iter()
676 .map(|(rel, bytes)| {
677 let retargeted = retarget_mem_links(bytes.clone(), mem_name, &published.name);
678 if let Some(rw) = entity_rewrite(&rel, &bytes, &retargeted) {
679 rewrites.push(rw);
680 }
681 (rel, retargeted)
682 })
683 .collect();
684 let checks_bytes = rekey_sealed_checks(checks_bytes.map(<[u8]>::to_vec), &rewrites);
685 let mut all_entries: Vec<(String, Vec<u8>)> =
686 Vec::with_capacity(2 + schema_files.len() + md_entries.len());
687 all_entries.push((ARCHIVE_CONFIG_PATH.to_string(), config_bytes));
688 // Embed the authoring-provenance payload when present. Serialised
689 // canonically; the validator tolerates it as a recognised meta member
690 // and the consumer reads it back via `read_archive_provenance`.
691 if let Some(prov) = provenance
692 && let Ok(bytes) = prov.to_archive_bytes()
693 {
694 all_entries.push((ARCHIVE_PROVENANCE_PATH.to_string(), bytes));
695 }
696 // Embed the engine-owned anchors sidecar verbatim when the mem carries
697 // one. A recognised `.memstead/` member: the archive validator strictly
698 // validates it and the canonical re-pack threads it through unchanged.
699 if let Some(anchors) = anchors_bytes {
700 all_entries.push((ARCHIVE_ANCHORS_PATH.to_string(), anchors.to_vec()));
701 }
702 // Embed the sealed check records when the mem has any. A recognised
703 // `.memstead/` member like the anchors: strictly validated by the
704 // archive validator, threaded verbatim through the canonical re-pack.
705 if let Some(checks) = checks_bytes {
706 all_entries.push((ARCHIVE_CHECKS_PATH.to_string(), checks));
707 }
708 for sf in &schema_files {
709 all_entries.push((
710 format!("{ARCHIVE_SCHEMA_PREFIX}{}", sf.archive_path),
711 sf.bytes.clone(),
712 ));
713 }
714 for (rel, bytes) in md_entries {
715 all_entries.push((posix_path(&rel), bytes));
716 }
717 all_entries.sort_by(|a, b| a.0.cmp(&b.0));
718
719 let mut buf: Vec<u8> = Vec::new();
720 {
721 let cursor = Cursor::new(&mut buf);
722 let mut zip = zip::ZipWriter::new(cursor);
723 let options = SimpleFileOptions::default()
724 .compression_method(CompressionMethod::Deflated)
725 .last_modified_time(fixed_mtime())
726 .unix_permissions(0o644);
727
728 for (archive_path, bytes) in &all_entries {
729 zip.start_file(archive_path, options)?;
730 zip.write_all(bytes)?;
731 }
732 zip.finish()?;
733 }
734
735 // Strict
736 // archive validation runs against the in-memory bytes before they
737 // leave this function. Export and install share one validator
738 // pass — the trust boundary fires at export rather than letting an
739 // invalid archive land on disk and refuse only at the next install
740 // attempt. If the produced archive doesn't validate (legacy
741 // on-disk drift, hand-edited markdown, archive-imports from
742 // non-canonical sources), surface the typed refusal; the
743 // disk-shaped wrapper (`export_mem`) never writes a broken
744 // archive because validation happens here, pre-write.
745 //
746 // The *lenient* variant collects cross-mem edges (whose target
747 // won't travel inside this single-mem archive) instead of
748 // refusing on them — export warns and still produces, where install
749 // refuses. Every other strict check still refuses, so a
750 // genuinely-broken archive never lands.
751 let validated = crate::validator::validate_and_normalize_archive_lenient(&buf)
752 .map_err(|e| MemExportError::ArchiveValidationFailed(e.to_string()))?;
753
754 Ok(MemExportBytes {
755 bytes: buf,
756 name: published.name.clone(),
757 version: published.version.to_string(),
758 entity_count,
759 dangling_cross_mem_edges: validated.dangling_cross_mem_edges,
760 redactions: Vec::new(),
761 })
762}
763
764/// Zip's minimum representable timestamp — 1980-01-01 00:00:00. Used
765/// as a fixed mtime so archives are byte-stable across exports.
766fn fixed_mtime() -> DateTime {
767 DateTime::default()
768}
769
770fn posix_path(path: &Path) -> String {
771 path.components()
772 .filter_map(|c| c.as_os_str().to_str())
773 .collect::<Vec<_>>()
774 .join("/")
775}
776
777/// Recursively collect `.md` files. Skips hidden directories and
778/// `README.md` (same policy as the entity loaders — a folder mem living
779/// visibly in a repository tree carries a human-facing README beside its
780/// entity files, and what load skips, export must skip too).
781fn collect_markdown(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), std::io::Error> {
782 let mut children: Vec<_> = fs::read_dir(dir)?.collect::<Result<_, _>>()?;
783 children.sort_by_key(|e| e.file_name());
784
785 for entry in children {
786 let path = entry.path();
787 let name = entry.file_name();
788 let name = name.to_string_lossy();
789
790 if path.is_dir() {
791 if name.starts_with('.') {
792 continue;
793 }
794 // A subdirectory with its own mem config is another mem, which
795 // load skips: its entities are never this mem's.
796 if crate::mem::is_nested_mem_root(&path) {
797 continue;
798 }
799 collect_markdown(&path, out)?;
800 } else if name.ends_with(".md") && name.as_ref() != "README.md" {
801 out.push(path);
802 }
803 }
804 Ok(())
805}