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 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    // The export walks the mem's directory itself. While a commit of
409    // the mem is decided and not applied, part of it may be in place:
410    // such a mem is not exported, as it is not read anywhere else.
411    crate::storage::filesystem::refuse_cut_off_commit(mem_dir)
412        .map_err(|e| MemExportError::Io(std::io::Error::other(e.to_string())))?;
413
414    let mut md_files = Vec::new();
415    collect_markdown(mem_dir, &mut md_files)?;
416
417    let mut md_entries: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(md_files.len());
418    for abs in &md_files {
419        let rel = abs
420            .strip_prefix(mem_dir)
421            .expect("markdown file must live under mem_dir");
422        md_entries.push((rel.to_path_buf(), fs::read(abs)?));
423    }
424
425    // Source the per-entity authoring provenance from the folder mem's
426    // own mutation log (`.memstead/changes.jsonl`), read through the folder
427    // backend so the JSONL parsing has one home. A mem with no changelog
428    // yields no rationale, but every entity still gets its record.
429    use crate::backend::MemBackend;
430    let backend = crate::storage::FilesystemBackend::new(mem_dir.to_path_buf());
431    let entity_paths = entity_paths_of(
432        &md_entries
433            .iter()
434            .map(|(p, _)| p.clone())
435            .collect::<Vec<_>>(),
436    );
437    let records = backend.read_provenance(None).unwrap_or_default();
438    let (provenance, redactions) = build_redacted_archive_provenance(&records, &entity_paths);
439
440    // Source the engine-owned anchors sidecar (`.memstead/anchors.json`)
441    // through the same backend so it travels inside the `.mem` archive.
442    // Absent (a mem with no anchors) → no member, distinct from an empty
443    // sidecar. The recognised-member set + canonical re-pack already accept
444    // and thread it verbatim; export is the producer half of that contract.
445    let anchors_bytes = backend.read_anchors_sidecar().ok().flatten();
446
447    // Source the sealed check records from the workspace ledger (the
448    // engine's, never the mem's): the latest record per entity and kind
449    // for the entities this archive carries. No root, no ledger, no
450    // record: no member.
451    let (checks_bytes, check_redactions) =
452        sealed_checks_bytes_for(workspace_root, explicit_name, &entity_paths, rows);
453
454    export_entries_to_bytes(
455        config,
456        workspace_root,
457        workspace_schemas_dir,
458        explicit_name,
459        md_entries,
460        Some(&provenance),
461        anchors_bytes.as_deref(),
462        checks_bytes.as_deref(),
463        ref_schema_source,
464    )
465    .map(|mut r| {
466        r.redactions = merge_redactions(redactions, check_redactions);
467        r
468    })
469}
470
471/// Seal already-collected entity bytes into a portable `.mem` archive —
472/// the storage-agnostic core shared by the folder exporter
473/// ([`export_mem_to_bytes`], which walks a directory) and the
474/// in-memory exporter (which lists entities from a
475/// [`crate::backend::MemBackend`] holding them in RAM). Same wire
476/// format either way: whitelist config projection, embedded schema
477/// source, deterministic path-sorted entries, fixed mtime, and the same
478/// pre-write lenient validation pass.
479///
480/// `md_entries` are `(mem-relative path, bytes)` pairs; paths are
481/// posix-normalised for the archive. Entries need not be pre-sorted — the
482/// archive sort makes the output deterministic regardless of input order.
483/// The archive identity of a mem name: its LEAF segment. A hierarchical
484/// mem (`planning/plan-x`) publishes as `plan-x`: the path is workspace
485/// routing, not mem identity, and the archive format's name grammar
486/// admits no `/`. Flat names pass through unchanged. One definition for
487/// every export path, so an archive's name and the links inside it are
488/// derived by the same rule.
489pub fn archive_identity(mem_name: &str) -> &str {
490    mem_name.rsplit('/').next().unwrap_or(mem_name)
491}
492
493/// Retarget an entity file's mem-qualified wiki-links from the mem's
494/// workspace name to its archive identity: `[[<mem>--slug]]` and
495/// `[[<mem>:slug]]` become `[[<archive>--slug]]` / `[[<archive>:slug]]`.
496/// The archive is validated and installed under the leaf name, so a
497/// link that qualifies itself with the workspace path would read there
498/// as ambiguous (`a/b--slug`) or as a foreign mem (`a/b:slug`) — the
499/// write path accepted it as a self-reference, and the export must not
500/// write what install refuses. A no-op when the two names agree; bytes
501/// that are not UTF-8 pass through untouched (the validator judges them).
502pub fn retarget_mem_links(bytes: Vec<u8>, mem_name: &str, archive_name: &str) -> Vec<u8> {
503    if mem_name == archive_name {
504        return bytes;
505    }
506    match std::str::from_utf8(&bytes) {
507        Ok(text) => {
508            let (out, n) =
509                crate::entity::wikilink_rewrite::rewrite_mem_prefix(text, mem_name, archive_name);
510            if n == 0 { bytes } else { out.into_bytes() }
511        }
512        Err(_) => bytes,
513    }
514}
515
516/// The `content_hash` the loader will derive for an entity from these
517/// bytes, the store's one recipe ([`crate::entity::parser::compute_hash`]
518/// over the file text), so a sealed record is compared against exactly
519/// the hash the mount computes. `None` for bytes that are not UTF-8 (the
520/// validator judges those; no hash of theirs is ever keyed).
521pub fn archived_content_hash(bytes: &[u8]) -> Option<String> {
522    std::str::from_utf8(bytes)
523        .ok()
524        .map(crate::entity::parser::compute_hash)
525}
526
527/// Re-key the sealed check records to the archived entity bytes: for
528/// each `(entity path, pre-rewrite hash, post-rewrite hash)` the export
529/// changed, every record of that entity that was fresh at the
530/// pre-rewrite hash moves to the archived hash and is marked
531/// `carried_from: {hash, reason: "export"}` ([`crate::check::SealedChecks::rekey_entity`]);
532/// a record stale before the export keeps its hash and stays stale on
533/// the mount. The member bytes come back unchanged when nothing moved
534/// (or when they do not parse; the validator refuses those), so a
535/// mem whose bytes the export never rewrites exports byte-identically.
536pub fn rekey_sealed_checks(
537    checks_bytes: Option<Vec<u8>>,
538    rewrites: &[(String, String, String)],
539) -> Option<Vec<u8>> {
540    let bytes = checks_bytes?;
541    if rewrites.is_empty() {
542        return Some(bytes);
543    }
544    let Ok(mut sealed) = crate::check::SealedChecks::from_archive_bytes(&bytes) else {
545        return Some(bytes);
546    };
547    let mut moved = 0;
548    for (path, pre, post) in rewrites {
549        moved += sealed.rekey_entity(path, pre, post);
550    }
551    if moved == 0 {
552        return Some(bytes);
553    }
554    Some(sealed.to_archive_bytes().unwrap_or(bytes))
555}
556
557/// Carry an adopted body's origin marks across the link retarget an export
558/// applies, so a published archive keeps saying which of its bodies came
559/// from a contributor.
560///
561/// A hierarchical mem publishes under its leaf, so the export rewrites every
562/// self-qualified wiki-link in every entity, which moves the bytes a mark
563/// hashes. Unfollowed, the archive serves a contributor's untouched sentences
564/// as its owner's own the moment a consuming deployment vouches for the mem
565/// ([`crate::Engine::declare_mem_origin`]) — the third place this same
566/// rewrite had to be taught to carry the mark, after a rename and a mem
567/// rename.
568///
569/// Only a mark that still held over the pre-rewrite bytes is carried, and
570/// only for the keys the record names, so no schema and no load-bearing set
571/// enters here. Returns the bytes unchanged when there is nothing to carry.
572pub fn rekey_proposal_marks(
573    record_bytes: Option<Vec<u8>>,
574    rewrites: &[(String, ProposalMarkSections, ProposalMarkSections)],
575) -> Option<Vec<u8>> {
576    let bytes = record_bytes?;
577    if rewrites.is_empty() {
578        return Some(bytes);
579    }
580    let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
581        return Some(bytes);
582    };
583    if record.structural_defect().is_some() {
584        // A record the reader calls defective is left exactly as it is, the
585        // stance every write that follows a mark takes: the mem is quarantined
586        // on purpose, and an export that repaired the file would ship an
587        // archive claiming a record it can trust.
588        return Some(bytes);
589    }
590    let mut moved = false;
591    for (slug, was, now) in rewrites {
592        for proposal in &mut record.proposals {
593            let Some(entry) = proposal.entities.get_mut(slug) else {
594                continue;
595            };
596            let Some(marks) = entry.landed_sections.as_mut() else {
597                continue;
598            };
599            for (key, hash) in marks.iter_mut() {
600                let (Some(was), Some(now)) = (was.get(key), now.get(key)) else {
601                    continue;
602                };
603                if was == now || &crate::preparation::entity_section_prepared_hash(key, was) != hash
604                {
605                    continue;
606                }
607                *hash = crate::preparation::entity_section_prepared_hash(key, now);
608                moved = true;
609            }
610        }
611    }
612    if !moved {
613        return Some(bytes);
614    }
615    Some(record.to_bytes())
616}
617
618/// An entity's sections as the STORE holds them, which is the map the marks
619/// were computed over
620/// ([`crate::preparation::entity_load_bearing_section_marks`]).
621///
622/// The caller derives it, because only the caller has the schema: the store's
623/// map is schema-shaped (a catch-all section's value is the join of its own
624/// content and every undeclared heading re-emitted under it), so a
625/// schema-free re-parse disagrees on exactly those keys and would silently
626/// carry no mark for them, publishing an archive whose marks no longer hold
627/// over its own bytes.
628pub type ProposalMarkSections = indexmap::IndexMap<String, String>;
629
630/// The rewrite triple [`rekey_sealed_checks`] takes, for one entity file
631/// whose bytes the export changed: `None` when the archived bytes hash the
632/// same as the source bytes (nothing to re-key) or either side is not UTF-8.
633pub fn entity_rewrite(rel: &Path, before: &[u8], after: &[u8]) -> Option<(String, String, String)> {
634    let pre = archived_content_hash(before)?;
635    let post = archived_content_hash(after)?;
636    if pre == post {
637        return None;
638    }
639    let path = entity_paths_of(std::slice::from_ref(&rel.to_path_buf())).remove(0);
640    Some((path, pre, post))
641}
642
643#[allow(clippy::too_many_arguments)]
644pub fn export_entries_to_bytes(
645    config: &MemConfig,
646    workspace_root: Option<&Path>,
647    workspace_schemas_dir: Option<&Path>,
648    mem_name: &str,
649    md_entries: Vec<(PathBuf, Vec<u8>)>,
650    provenance: Option<&ArchiveProvenance>,
651    anchors_bytes: Option<&[u8]>,
652    checks_bytes: Option<&[u8]>,
653    ref_schema_source: Option<Vec<SchemaSourceFile>>,
654) -> Result<MemExportBytes, MemExportError> {
655    let explicit_name = archive_identity(mem_name);
656    let published = published_config_from(config, explicit_name)?;
657    let config_bytes = canonical_json(&published)
658        .map_err(|e| MemExportError::Canonical(e.to_string()))?
659        .into_bytes();
660
661    // The git-branch schema store wins where the caller resolved it —
662    // the same precedence the git-branch export path applies — so a
663    // schema sealed by `memstead schema install` on the `__MEMSTEAD`
664    // ref exports for folder mems too, not only for branch mems.
665    let schema_files = match ref_schema_source {
666        Some(files) => files,
667        None => collect_schema_source(workspace_root, workspace_schemas_dir, &published.schema)?,
668    };
669
670    let entity_count = md_entries.len();
671    // A hierarchical mem publishes under its leaf, so every link that
672    // qualifies itself with the workspace path follows the name into the
673    // archive. That rewrite moves the entity's content hash, and a sealed
674    // check record fresh against the source bytes is re-keyed to the
675    // archived bytes so it stays fresh on the mount (a stale one stays
676    // stale). Retargeted before the member is placed, so the member the
677    // archive carries already speaks of the archived bytes.
678    let mut rewrites: Vec<(String, String, String)> = Vec::new();
679    let md_entries: Vec<(PathBuf, Vec<u8>)> = md_entries
680        .into_iter()
681        .map(|(rel, bytes)| {
682            let retargeted = retarget_mem_links(bytes.clone(), mem_name, &published.name);
683            if let Some(rw) = entity_rewrite(&rel, &bytes, &retargeted) {
684                rewrites.push(rw);
685            }
686            (rel, retargeted)
687        })
688        .collect();
689    let checks_bytes = rekey_sealed_checks(checks_bytes.map(<[u8]>::to_vec), &rewrites);
690    let mut all_entries: Vec<(String, Vec<u8>)> =
691        Vec::with_capacity(2 + schema_files.len() + md_entries.len());
692    all_entries.push((ARCHIVE_CONFIG_PATH.to_string(), config_bytes));
693    // Embed the authoring-provenance payload when present. Serialised
694    // canonically; the validator tolerates it as a recognised meta member
695    // and the consumer reads it back via `read_archive_provenance`.
696    if let Some(prov) = provenance
697        && let Ok(bytes) = prov.to_archive_bytes()
698    {
699        all_entries.push((ARCHIVE_PROVENANCE_PATH.to_string(), bytes));
700    }
701    // Embed the engine-owned anchors sidecar verbatim when the mem carries
702    // one. A recognised `.memstead/` member: the archive validator strictly
703    // validates it and the canonical re-pack threads it through unchanged.
704    if let Some(anchors) = anchors_bytes {
705        all_entries.push((ARCHIVE_ANCHORS_PATH.to_string(), anchors.to_vec()));
706    }
707    // Embed the sealed check records when the mem has any. A recognised
708    // `.memstead/` member like the anchors: strictly validated by the
709    // archive validator, threaded verbatim through the canonical re-pack.
710    if let Some(checks) = checks_bytes {
711        all_entries.push((ARCHIVE_CHECKS_PATH.to_string(), checks));
712    }
713    for sf in &schema_files {
714        all_entries.push((
715            format!("{ARCHIVE_SCHEMA_PREFIX}{}", sf.archive_path),
716            sf.bytes.clone(),
717        ));
718    }
719    for (rel, bytes) in md_entries {
720        all_entries.push((posix_path(&rel), bytes));
721    }
722    all_entries.sort_by(|a, b| a.0.cmp(&b.0));
723
724    let mut buf: Vec<u8> = Vec::new();
725    {
726        let cursor = Cursor::new(&mut buf);
727        let mut zip = zip::ZipWriter::new(cursor);
728        let options = SimpleFileOptions::default()
729            .compression_method(CompressionMethod::Deflated)
730            .last_modified_time(fixed_mtime())
731            .unix_permissions(0o644);
732
733        for (archive_path, bytes) in &all_entries {
734            zip.start_file(archive_path, options)?;
735            zip.write_all(bytes)?;
736        }
737        zip.finish()?;
738    }
739
740    // Strict
741    // archive validation runs against the in-memory bytes before they
742    // leave this function. Export and install share one validator
743    // pass — the trust boundary fires at export rather than letting an
744    // invalid archive land on disk and refuse only at the next install
745    // attempt. If the produced archive doesn't validate (legacy
746    // on-disk drift, hand-edited markdown, archive-imports from
747    // non-canonical sources), surface the typed refusal; the
748    // disk-shaped wrapper (`export_mem`) never writes a broken
749    // archive because validation happens here, pre-write.
750    //
751    // The *lenient* variant collects cross-mem edges (whose target
752    // won't travel inside this single-mem archive) instead of
753    // refusing on them — export warns and still produces, where install
754    // refuses. Every other strict check still refuses, so a
755    // genuinely-broken archive never lands.
756    let validated = crate::validator::validate_and_normalize_archive_lenient(&buf)
757        .map_err(|e| MemExportError::ArchiveValidationFailed(e.to_string()))?;
758
759    Ok(MemExportBytes {
760        bytes: buf,
761        name: published.name.clone(),
762        version: published.version.to_string(),
763        entity_count,
764        dangling_cross_mem_edges: validated.dangling_cross_mem_edges,
765        redactions: Vec::new(),
766    })
767}
768
769/// Zip's minimum representable timestamp — 1980-01-01 00:00:00. Used
770/// as a fixed mtime so archives are byte-stable across exports.
771fn fixed_mtime() -> DateTime {
772    DateTime::default()
773}
774
775fn posix_path(path: &Path) -> String {
776    path.components()
777        .filter_map(|c| c.as_os_str().to_str())
778        .collect::<Vec<_>>()
779        .join("/")
780}
781
782/// Recursively collect `.md` files. Skips hidden directories and
783/// `README.md` (same policy as the entity loaders — a folder mem living
784/// visibly in a repository tree carries a human-facing README beside its
785/// entity files, and what load skips, export must skip too).
786fn collect_markdown(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), std::io::Error> {
787    let mut children: Vec<_> = fs::read_dir(dir)?.collect::<Result<_, _>>()?;
788    children.sort_by_key(|e| e.file_name());
789
790    for entry in children {
791        let path = entry.path();
792        let name = entry.file_name();
793        let name = name.to_string_lossy();
794
795        if path.is_dir() {
796            if name.starts_with('.') {
797                continue;
798            }
799            // A subdirectory with its own mem config is another mem, which
800            // load skips: its entities are never this mem's.
801            if crate::mem::is_nested_mem_root(&path) {
802                continue;
803            }
804            collect_markdown(&path, out)?;
805        } else if name.ends_with(".md") && name.as_ref() != "README.md" {
806            out.push(path);
807        }
808    }
809    Ok(())
810}