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