memstead-base 0.21.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Mem-archive export.
//!
//! The folder-shaped export (the gix-free path) lives here so the
//! unified `Engine::export_mem` can call it without crossing into
//! `memstead-git-branch`. The git-branch-shaped variant
//! (`export_mem_from_branch`) stays in `memstead-git-branch::ops::export`
//! because it walks a gitdir.
//!
//! Output wire shape is deterministic and matches the git-branch
//! variant byte-for-byte for equivalent input: `.memstead/config.json`
//! carries the whitelist-projection of the author's `MemConfig`,
//! `.memstead/schema/` embeds the pinned schema's source files, and the
//! mem's `.md` blobs land at their mem-relative paths. Entries are
//! sorted by path and zip-stamped with a fixed mtime so identical
//! input produces byte-identical archives.

use std::fs;
use std::io::{Cursor, Write};
use std::path::{Path, PathBuf};

use memstead_schema::{
    ARCHIVE_ANCHORS_PATH, ARCHIVE_CHECKS_PATH, ARCHIVE_CONFIG_PATH, ARCHIVE_PROVENANCE_PATH,
    ARCHIVE_SCHEMA_PREFIX, ArchiveProvenance, EntityProvenance, MemConfig, PublishConversionError,
    SchemaSourceError, SchemaSourceFile, collect_schema_source, published_config_from,
};
use zip::{CompressionMethod, DateTime, write::SimpleFileOptions};

use crate::entity::EntityId;
use crate::ops::MemExportResult;
use crate::provenance::Provenance;
use crate::validator::canonical::canonical_json;

/// Build the per-entity authoring-provenance payload from a backend's
/// mutation log (`read_provenance`). Keys by each entity's mem-relative
/// path ([`EntityId::path`]) so the payload survives a remount under a
/// different mem name. For each entity, keeps the most recent record
/// that carries a non-empty note — the entity's *current* rationale.
///
/// No-fabrication: records with no entity (batch) or no note contribute no
/// rationale. Every path in `entity_paths` (the entities the archive
/// carries) gets a record regardless: one with the rationale where a noted
/// mutation exists, an explicit no-rationale record otherwise. The member
/// therefore always ships, and a reader tells "never noted" apart from
/// "member missing" (an archive from an earlier engine).
pub fn build_archive_provenance(
    records: &[Provenance],
    entity_paths: &[String],
) -> ArchiveProvenance {
    build_redacted_archive_provenance(records, entity_paths).0
}

/// The mem-relative entity paths (`EntityId::path` form, the provenance
/// payload's key) of a set of entity-bearing file paths, in one place so
/// every export site keys the payload the way the sealed read looks it up.
pub fn entity_paths_of(rels: &[PathBuf]) -> Vec<String> {
    rels.iter()
        .map(|rel| {
            let s = rel.to_string_lossy().replace('\\', "/");
            crate::entity::id::file_path_to_id(&s, "m")
                .path()
                .to_string()
        })
        .collect()
}

/// The builder proper: every rationale passes through the private-pattern
/// redaction (`ops::redaction`, the leak scan's classes) before it is
/// summarised, so an archive never carries a span the public tree refuses;
/// the per-class counts of the rationales that ship travel to the export
/// result (a superseded note's redactions never reach the archive and are
/// not counted).
pub fn build_redacted_archive_provenance(
    records: &[Provenance],
    entity_paths: &[String],
) -> (
    ArchiveProvenance,
    Vec<crate::ops::redaction::RedactionCount>,
) {
    use std::collections::BTreeMap;
    use std::time::SystemTime;

    type Counted = (EntityProvenance, BTreeMap<&'static str, usize>);
    let mut by_path: BTreeMap<String, (SystemTime, Counted)> = BTreeMap::new();
    for r in records {
        let Some(entity) = r.entity.as_deref() else {
            continue;
        };
        let Some(note) = r.note.as_deref().map(str::trim).filter(|n| !n.is_empty()) else {
            continue;
        };
        let path = EntityId(entity.to_string()).path().to_string();
        if path.is_empty() {
            continue;
        }
        let (note, counts) = crate::ops::redaction::redact(note);
        let candidate = EntityProvenance {
            rationale: Some(note),
            kind: Some(r.kind.as_str().to_string()),
            timestamp: Some(crate::filesystem::changelog::format_rfc3339_utc(
                r.timestamp,
            )),
            actor: Some(r.actor.as_trailer().to_string()),
        };
        match by_path.get(&path) {
            // Keep the existing entry when it is at least as recent.
            Some((ts, _)) if *ts >= r.timestamp => {}
            _ => {
                by_path.insert(path, (r.timestamp, (candidate, counts)));
            }
        }
    }
    // Every carried entity gets a record: no rationale where none was
    // noted, never an absent key that a reader could mistake for a lost
    // member.
    for path in entity_paths {
        by_path.entry(path.clone()).or_insert_with(|| {
            (
                SystemTime::UNIX_EPOCH,
                (EntityProvenance::default(), BTreeMap::new()),
            )
        });
    }
    let mut redacted_total: BTreeMap<&'static str, usize> = BTreeMap::new();
    let mut entities = BTreeMap::new();
    for (k, (_, (v, counts))) in by_path {
        crate::ops::redaction::tally(&mut redacted_total, counts);
        entities.insert(k, v);
    }
    (
        ArchiveProvenance::summarised(entities),
        crate::ops::redaction::counts_to_list(&redacted_total),
    )
}

/// What the source engine derives for one ledger record at export time,
/// for the archive to carry: facts the mount cannot re-derive because it
/// holds neither the mem's history nor the deployment's identity roster.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SealedRowFacts {
    /// The author≠checker reading
    /// ([`crate::Engine::independence_of`]). `None` seals none.
    pub independence: Option<crate::engine::independence::Independence>,
    /// The trust class of the row's prose
    /// ([`crate::Engine::check_row_origin_class`]). `None` seals none,
    /// which is the undeclared case: every reader then inherits the mem's
    /// class, as it did before the field existed.
    pub origin: Option<crate::render::OriginClass>,
}

/// The export's one source for both ([`crate::Engine::sealed_row_reader`]).
pub type SealedRowReader<'a> = &'a dyn Fn(&crate::check::CheckRecord) -> SealedRowFacts;

/// Build the sealed check-records member from a workspace ledger: for
/// every entity the archive carries (`entity_paths`, the mem-relative
/// paths), the latest ledger record per kind, as [`crate::check::SealedChecks`].
/// Records of other mems, and records of entities the archive does not
/// carry (deleted since the check), are not sealed; the method note
/// passes through the same private-pattern redaction the provenance
/// member applies, and identities travel verbatim. Each sealed record
/// carries the author≠checker independence reading `independence`
/// derives for it (the archive mount serves that reading, having no
/// history to derive one from); without a reader, none. `None` when no
/// record qualifies, so a mem with no record exports byte-identically
/// to one exported by an engine without this member.
pub fn build_redacted_sealed_checks(
    records: &[crate::check::CheckRecord],
    mem_name: &str,
    entity_paths: &[String],
    rows: Option<SealedRowReader<'_>>,
) -> (
    Option<crate::check::SealedChecks>,
    Vec<crate::ops::redaction::RedactionCount>,
) {
    use std::collections::BTreeMap;

    let carried: std::collections::BTreeSet<&str> =
        entity_paths.iter().map(String::as_str).collect();
    // Ledger order is record order: a later line of the same (entity,
    // kind) supersedes an earlier one, exactly as `latest_for_wire_kind`
    // reads the ledger.
    let mut latest: BTreeMap<String, BTreeMap<String, crate::check::CheckRecord>> = BTreeMap::new();
    for rec in records {
        let id = EntityId(rec.entity.clone());
        if id.mem() != mem_name || !carried.contains(id.path()) {
            continue;
        }
        let kind = crate::check::sealed_kind_of(rec);
        if kind.is_empty() {
            continue;
        }
        latest
            .entry(id.path().to_string())
            .or_default()
            .insert(kind, rec.clone());
    }
    if latest.is_empty() {
        return (None, Vec::new());
    }
    let mut redacted_total: BTreeMap<&'static str, usize> = BTreeMap::new();
    let mut sealed = crate::check::SealedChecks::new();
    for (path, kinds) in latest {
        let mut out = BTreeMap::new();
        for (kind, rec) in kinds {
            let mut sc = crate::check::SealedCheck::from_record(&rec);
            let facts = rows.map(|read| read(&rec)).unwrap_or_default();
            sc.independence = facts.independence.map(|r| r.as_str().to_string());
            sc.origin = facts.origin.map(|c| c.as_wire().to_string());
            if let Some(m) = sc.method.take() {
                let (m, counts) = crate::ops::redaction::redact(&m);
                crate::ops::redaction::tally(&mut redacted_total, counts);
                sc.method = Some(m);
            }
            out.insert(kind, sc);
        }
        sealed.entities.insert(path, out);
    }
    (
        Some(sealed),
        crate::ops::redaction::counts_to_list(&redacted_total),
    )
}

/// The sealed check-records member bytes for a mem, read from the
/// workspace ledger when the engine has a workspace root: `None` (no
/// member) without a root, without a ledger, or without a qualifying
/// record. One reader for every export path, so the three storage arms
/// seal the same bytes for the same ledger. `independence` is the
/// engine's reader of the reading each record is sealed with
/// ([`build_redacted_sealed_checks`]).
pub fn sealed_checks_bytes_for(
    workspace_root: Option<&Path>,
    mem_name: &str,
    entity_paths: &[String],
    rows: Option<SealedRowReader<'_>>,
) -> (Option<Vec<u8>>, Vec<crate::ops::redaction::RedactionCount>) {
    let Some(root) = workspace_root else {
        return (None, Vec::new());
    };
    let records = crate::check::CheckLedger::for_workspace(root).all();
    let (sealed, redactions) = build_redacted_sealed_checks(&records, mem_name, entity_paths, rows);
    (sealed.and_then(|s| s.to_archive_bytes().ok()), redactions)
}

/// Fold two export paths' redaction counts into one list, in vocabulary
/// order (the provenance member's and the checks member's).
pub fn merge_redactions(
    a: Vec<crate::ops::redaction::RedactionCount>,
    b: Vec<crate::ops::redaction::RedactionCount>,
) -> Vec<crate::ops::redaction::RedactionCount> {
    use std::collections::BTreeMap;
    let mut total: BTreeMap<&'static str, usize> = BTreeMap::new();
    for rc in a.iter().chain(b.iter()) {
        if let Some(class) = crate::ops::redaction::REDACTION_CLASSES
            .iter()
            .find(|c| c.name == rc.class)
        {
            *total.entry(class.name).or_insert(0) += rc.count;
        }
    }
    crate::ops::redaction::counts_to_list(&total)
}

/// Byte-shaped output of [`export_mem_to_bytes`]. Bundles the
/// produced archive bytes with the same metadata
/// [`MemExportResult`] reports for path-based exports.
#[derive(Debug, Clone)]
pub struct MemExportBytes {
    /// The `.mem` archive bytes — self-contained, ready to validate
    /// via `extract_entries` and hydrate via `Engine::from_archive_bytes`.
    pub bytes: Vec<u8>,
    /// Mem name (mirrors `MemExportResult.name`).
    pub name: String,
    /// Mem version (mirrors `MemExportResult.version`).
    pub version: String,
    /// `.md` entity count in the produced archive.
    pub entity_count: usize,
    /// Per-class private-pattern redactions in the provenance and the
    /// sealed-checks members (mirrors `MemExportResult.redactions`);
    /// empty when none.
    pub redactions: Vec<crate::ops::redaction::RedactionCount>,
    /// Cross-mem edges whose target won't travel inside this archive —
    /// `install` will reject each. Mirrors
    /// `MemExportResult.dangling_cross_mem_edges`; empty for a
    /// self-contained export.
    pub dangling_cross_mem_edges: Vec<crate::validator::DanglingCrossMemEdge>,
}

#[derive(Debug, thiserror::Error)]
pub enum MemExportError {
    #[error("mem directory not found: {0}")]
    DirNotFound(String),
    #[error(transparent)]
    Convert(#[from] PublishConversionError),
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("zip error: {0}")]
    Zip(#[from] zip::result::ZipError),
    #[error("config serialization error: {0}")]
    Canonical(String),
    #[error(transparent)]
    SchemaSource(#[from] SchemaSourceError),
    #[error("branch read error: {0}")]
    BranchRead(String),
    /// The
    /// produced archive failed strict validation. Reaches this state
    /// when the mem carries on-disk drift from a pre-fix engine —
    /// entities created when `MISSING_REQUIRED_SECTION` was a
    /// warning, hand-edited markdown, or archive-imports from
    /// non-canonical sources. Export and install share one strict
    /// validator pass; the trust boundary now fires at export rather
    /// than letting an invalid archive land on disk and refuse only
    /// at the next install attempt.
    #[error("export archive failed strict validation: {0}")]
    ArchiveValidationFailed(String),
}

/// Export a mem directory as a portable `.mem` archive.
///
/// The archive contains `.memstead/config.json` (a **whitelist projection**
/// of the author's `MemConfig` — author-only fields like
/// `writeGuidance`, `mediums`, `projections`, `readMems` never enter
/// the archive), every `.md` file under the mem root, and the pinned
/// schema's source YAML under `schema/`.
///
/// Output is deterministic — entries are sorted by path and written
/// with a fixed modification time — so identical input produces
/// byte-identical archives, and archives produced here round-trip
/// through `validate_and_normalize_archive` without rewriting.
pub fn export_mem(
    mem_dir: &Path,
    config: &MemConfig,
    output_path: &Path,
    workspace_root: Option<&Path>,
    workspace_schemas_dir: Option<&Path>,
    ref_schema_source: Option<Vec<SchemaSourceFile>>,
    rows: Option<SealedRowReader<'_>>,
) -> Result<MemExportResult, MemExportError> {
    let basename = mem_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
    let explicit_name = config.name.as_deref().unwrap_or(basename);
    let out = export_mem_to_bytes(
        mem_dir,
        config,
        workspace_root,
        workspace_schemas_dir,
        explicit_name,
        ref_schema_source,
        rows,
    )?;

    if let Some(parent) = output_path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent)?;
    }
    fs::write(output_path, &out.bytes)?;

    let size_bytes = fs::metadata(output_path)?.len();

    Ok(MemExportResult {
        unterminated_fence_entities: Vec::new(),
        archive_path: output_path.display().to_string(),
        name: out.name,
        version: out.version,
        entity_count: out.entity_count,
        size_bytes,
        dangling_cross_mem_edges: out.dangling_cross_mem_edges,
        redactions: out.redactions,
    })
}

/// Produce a portable `.mem` archive **as bytes** for a folder-backed
/// mem. Same wire format as [`export_mem`] — same whitelist
/// projection, same embedded schema source, same deterministic sort
/// order and fixed mtime — but the output stays in memory so the
/// bridge / WASM consumers can return it directly over HTTP.
///
/// `explicit_name` is the mem name the publish whitelist receives.
/// Callers reaching this through [`crate::Engine::export_mem_to_bytes`]
/// pass the mount's mem name; callers reaching it directly choose
/// the disk basename or a config-supplied alias.
///
/// `ref_schema_source`: pre-collected schema source files from the
/// workspace's `__MEMSTEAD:schemas/` ref (git-branch schema store).
/// `Some` takes precedence over the disk/builtin chain — the same
/// precedence the git-branch export path applies — so a folder mem in
/// a mem-repo workspace seals the schema the loader resolved. `None`
/// keeps the historical disk/builtin chain unchanged.
///
/// `independence`: the engine's reader of the independence reading each
/// sealed check record carries ([`sealed_checks_bytes_for`]); a caller
/// without an engine passes `None` and seals records without one.
pub fn export_mem_to_bytes(
    mem_dir: &Path,
    config: &MemConfig,
    workspace_root: Option<&Path>,
    workspace_schemas_dir: Option<&Path>,
    explicit_name: &str,
    ref_schema_source: Option<Vec<SchemaSourceFile>>,
    rows: Option<SealedRowReader<'_>>,
) -> Result<MemExportBytes, MemExportError> {
    if !mem_dir.is_dir() {
        return Err(MemExportError::DirNotFound(mem_dir.display().to_string()));
    }

    let mut md_files = Vec::new();
    collect_markdown(mem_dir, &mut md_files)?;

    let mut md_entries: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(md_files.len());
    for abs in &md_files {
        let rel = abs
            .strip_prefix(mem_dir)
            .expect("markdown file must live under mem_dir");
        md_entries.push((rel.to_path_buf(), fs::read(abs)?));
    }

    // Source the per-entity authoring provenance from the folder mem's
    // own mutation log (`.memstead/changes.jsonl`), read through the folder
    // backend so the JSONL parsing has one home. A mem with no changelog
    // yields no rationale, but every entity still gets its record.
    use crate::backend::MemBackend;
    let backend = crate::storage::FilesystemBackend::new(mem_dir.to_path_buf());
    let entity_paths = entity_paths_of(
        &md_entries
            .iter()
            .map(|(p, _)| p.clone())
            .collect::<Vec<_>>(),
    );
    let records = backend.read_provenance(None).unwrap_or_default();
    let (provenance, redactions) = build_redacted_archive_provenance(&records, &entity_paths);

    // Source the engine-owned anchors sidecar (`.memstead/anchors.json`)
    // through the same backend so it travels inside the `.mem` archive.
    // Absent (a mem with no anchors) → no member, distinct from an empty
    // sidecar. The recognised-member set + canonical re-pack already accept
    // and thread it verbatim; export is the producer half of that contract.
    let anchors_bytes = backend.read_anchors_sidecar().ok().flatten();

    // Source the sealed check records from the workspace ledger (the
    // engine's, never the mem's): the latest record per entity and kind
    // for the entities this archive carries. No root, no ledger, no
    // record: no member.
    let (checks_bytes, check_redactions) =
        sealed_checks_bytes_for(workspace_root, explicit_name, &entity_paths, rows);

    export_entries_to_bytes(
        config,
        workspace_root,
        workspace_schemas_dir,
        explicit_name,
        md_entries,
        Some(&provenance),
        anchors_bytes.as_deref(),
        checks_bytes.as_deref(),
        ref_schema_source,
    )
    .map(|mut r| {
        r.redactions = merge_redactions(redactions, check_redactions);
        r
    })
}

/// Seal already-collected entity bytes into a portable `.mem` archive —
/// the storage-agnostic core shared by the folder exporter
/// ([`export_mem_to_bytes`], which walks a directory) and the
/// in-memory exporter (which lists entities from a
/// [`crate::backend::MemBackend`] holding them in RAM). Same wire
/// format either way: whitelist config projection, embedded schema
/// source, deterministic path-sorted entries, fixed mtime, and the same
/// pre-write lenient validation pass.
///
/// `md_entries` are `(mem-relative path, bytes)` pairs; paths are
/// posix-normalised for the archive. Entries need not be pre-sorted — the
/// archive sort makes the output deterministic regardless of input order.
/// The archive identity of a mem name: its LEAF segment. A hierarchical
/// mem (`planning/plan-x`) publishes as `plan-x`: the path is workspace
/// routing, not mem identity, and the archive format's name grammar
/// admits no `/`. Flat names pass through unchanged. One definition for
/// every export path, so an archive's name and the links inside it are
/// derived by the same rule.
pub fn archive_identity(mem_name: &str) -> &str {
    mem_name.rsplit('/').next().unwrap_or(mem_name)
}

/// Retarget an entity file's mem-qualified wiki-links from the mem's
/// workspace name to its archive identity: `[[<mem>--slug]]` and
/// `[[<mem>:slug]]` become `[[<archive>--slug]]` / `[[<archive>:slug]]`.
/// The archive is validated and installed under the leaf name, so a
/// link that qualifies itself with the workspace path would read there
/// as ambiguous (`a/b--slug`) or as a foreign mem (`a/b:slug`) — the
/// write path accepted it as a self-reference, and the export must not
/// write what install refuses. A no-op when the two names agree; bytes
/// that are not UTF-8 pass through untouched (the validator judges them).
pub fn retarget_mem_links(bytes: Vec<u8>, mem_name: &str, archive_name: &str) -> Vec<u8> {
    if mem_name == archive_name {
        return bytes;
    }
    match std::str::from_utf8(&bytes) {
        Ok(text) => {
            let (out, n) =
                crate::entity::wikilink_rewrite::rewrite_mem_prefix(text, mem_name, archive_name);
            if n == 0 { bytes } else { out.into_bytes() }
        }
        Err(_) => bytes,
    }
}

/// The `content_hash` the loader will derive for an entity from these
/// bytes, the store's one recipe ([`crate::entity::parser::compute_hash`]
/// over the file text), so a sealed record is compared against exactly
/// the hash the mount computes. `None` for bytes that are not UTF-8 (the
/// validator judges those; no hash of theirs is ever keyed).
pub fn archived_content_hash(bytes: &[u8]) -> Option<String> {
    std::str::from_utf8(bytes)
        .ok()
        .map(crate::entity::parser::compute_hash)
}

/// Re-key the sealed check records to the archived entity bytes: for
/// each `(entity path, pre-rewrite hash, post-rewrite hash)` the export
/// changed, every record of that entity that was fresh at the
/// pre-rewrite hash moves to the archived hash and is marked
/// `carried_from: {hash, reason: "export"}` ([`crate::check::SealedChecks::rekey_entity`]);
/// a record stale before the export keeps its hash and stays stale on
/// the mount. The member bytes come back unchanged when nothing moved
/// (or when they do not parse; the validator refuses those), so a
/// mem whose bytes the export never rewrites exports byte-identically.
pub fn rekey_sealed_checks(
    checks_bytes: Option<Vec<u8>>,
    rewrites: &[(String, String, String)],
) -> Option<Vec<u8>> {
    let bytes = checks_bytes?;
    if rewrites.is_empty() {
        return Some(bytes);
    }
    let Ok(mut sealed) = crate::check::SealedChecks::from_archive_bytes(&bytes) else {
        return Some(bytes);
    };
    let mut moved = 0;
    for (path, pre, post) in rewrites {
        moved += sealed.rekey_entity(path, pre, post);
    }
    if moved == 0 {
        return Some(bytes);
    }
    Some(sealed.to_archive_bytes().unwrap_or(bytes))
}

/// Carry an adopted body's origin marks across the link retarget an export
/// applies, so a published archive keeps saying which of its bodies came
/// from a contributor.
///
/// A hierarchical mem publishes under its leaf, so the export rewrites every
/// self-qualified wiki-link in every entity, which moves the bytes a mark
/// hashes. Unfollowed, the archive serves a contributor's untouched sentences
/// as its owner's own the moment a consuming deployment vouches for the mem
/// ([`crate::Engine::declare_mem_origin`]) — the third place this same
/// rewrite had to be taught to carry the mark, after a rename and a mem
/// rename.
///
/// Only a mark that still held over the pre-rewrite bytes is carried, and
/// only for the keys the record names, so no schema and no load-bearing set
/// enters here. Returns the bytes unchanged when there is nothing to carry.
pub fn rekey_proposal_marks(
    record_bytes: Option<Vec<u8>>,
    rewrites: &[(String, ProposalMarkSections, ProposalMarkSections)],
) -> Option<Vec<u8>> {
    let bytes = record_bytes?;
    if rewrites.is_empty() {
        return Some(bytes);
    }
    let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
        return Some(bytes);
    };
    if record.structural_defect().is_some() {
        // A record the reader calls defective is left exactly as it is, the
        // stance every write that follows a mark takes: the mem is quarantined
        // on purpose, and an export that repaired the file would ship an
        // archive claiming a record it can trust.
        return Some(bytes);
    }
    let mut moved = false;
    for (slug, was, now) in rewrites {
        for proposal in &mut record.proposals {
            let Some(entry) = proposal.entities.get_mut(slug) else {
                continue;
            };
            let Some(marks) = entry.landed_sections.as_mut() else {
                continue;
            };
            for (key, hash) in marks.iter_mut() {
                let (Some(was), Some(now)) = (was.get(key), now.get(key)) else {
                    continue;
                };
                if was == now || &crate::preparation::entity_section_prepared_hash(key, was) != hash
                {
                    continue;
                }
                *hash = crate::preparation::entity_section_prepared_hash(key, now);
                moved = true;
            }
        }
    }
    if !moved {
        return Some(bytes);
    }
    Some(record.to_bytes())
}

/// An entity's sections as the STORE holds them, which is the map the marks
/// were computed over
/// ([`crate::preparation::entity_load_bearing_section_marks`]).
///
/// The caller derives it, because only the caller has the schema: the store's
/// map is schema-shaped (a catch-all section's value is the join of its own
/// content and every undeclared heading re-emitted under it), so a
/// schema-free re-parse disagrees on exactly those keys and would silently
/// carry no mark for them, publishing an archive whose marks no longer hold
/// over its own bytes.
pub type ProposalMarkSections = indexmap::IndexMap<String, String>;

/// The rewrite triple [`rekey_sealed_checks`] takes, for one entity file
/// whose bytes the export changed: `None` when the archived bytes hash the
/// same as the source bytes (nothing to re-key) or either side is not UTF-8.
pub fn entity_rewrite(rel: &Path, before: &[u8], after: &[u8]) -> Option<(String, String, String)> {
    let pre = archived_content_hash(before)?;
    let post = archived_content_hash(after)?;
    if pre == post {
        return None;
    }
    let path = entity_paths_of(std::slice::from_ref(&rel.to_path_buf())).remove(0);
    Some((path, pre, post))
}

#[allow(clippy::too_many_arguments)]
pub fn export_entries_to_bytes(
    config: &MemConfig,
    workspace_root: Option<&Path>,
    workspace_schemas_dir: Option<&Path>,
    mem_name: &str,
    md_entries: Vec<(PathBuf, Vec<u8>)>,
    provenance: Option<&ArchiveProvenance>,
    anchors_bytes: Option<&[u8]>,
    checks_bytes: Option<&[u8]>,
    ref_schema_source: Option<Vec<SchemaSourceFile>>,
) -> Result<MemExportBytes, MemExportError> {
    let explicit_name = archive_identity(mem_name);
    let published = published_config_from(config, explicit_name)?;
    let config_bytes = canonical_json(&published)
        .map_err(|e| MemExportError::Canonical(e.to_string()))?
        .into_bytes();

    // The git-branch schema store wins where the caller resolved it —
    // the same precedence the git-branch export path applies — so a
    // schema sealed by `memstead schema install` on the `__MEMSTEAD`
    // ref exports for folder mems too, not only for branch mems.
    let schema_files = match ref_schema_source {
        Some(files) => files,
        None => collect_schema_source(workspace_root, workspace_schemas_dir, &published.schema)?,
    };

    let entity_count = md_entries.len();
    // A hierarchical mem publishes under its leaf, so every link that
    // qualifies itself with the workspace path follows the name into the
    // archive. That rewrite moves the entity's content hash, and a sealed
    // check record fresh against the source bytes is re-keyed to the
    // archived bytes so it stays fresh on the mount (a stale one stays
    // stale). Retargeted before the member is placed, so the member the
    // archive carries already speaks of the archived bytes.
    let mut rewrites: Vec<(String, String, String)> = Vec::new();
    let md_entries: Vec<(PathBuf, Vec<u8>)> = md_entries
        .into_iter()
        .map(|(rel, bytes)| {
            let retargeted = retarget_mem_links(bytes.clone(), mem_name, &published.name);
            if let Some(rw) = entity_rewrite(&rel, &bytes, &retargeted) {
                rewrites.push(rw);
            }
            (rel, retargeted)
        })
        .collect();
    let checks_bytes = rekey_sealed_checks(checks_bytes.map(<[u8]>::to_vec), &rewrites);
    let mut all_entries: Vec<(String, Vec<u8>)> =
        Vec::with_capacity(2 + schema_files.len() + md_entries.len());
    all_entries.push((ARCHIVE_CONFIG_PATH.to_string(), config_bytes));
    // Embed the authoring-provenance payload when present. Serialised
    // canonically; the validator tolerates it as a recognised meta member
    // and the consumer reads it back via `read_archive_provenance`.
    if let Some(prov) = provenance
        && let Ok(bytes) = prov.to_archive_bytes()
    {
        all_entries.push((ARCHIVE_PROVENANCE_PATH.to_string(), bytes));
    }
    // Embed the engine-owned anchors sidecar verbatim when the mem carries
    // one. A recognised `.memstead/` member: the archive validator strictly
    // validates it and the canonical re-pack threads it through unchanged.
    if let Some(anchors) = anchors_bytes {
        all_entries.push((ARCHIVE_ANCHORS_PATH.to_string(), anchors.to_vec()));
    }
    // Embed the sealed check records when the mem has any. A recognised
    // `.memstead/` member like the anchors: strictly validated by the
    // archive validator, threaded verbatim through the canonical re-pack.
    if let Some(checks) = checks_bytes {
        all_entries.push((ARCHIVE_CHECKS_PATH.to_string(), checks));
    }
    for sf in &schema_files {
        all_entries.push((
            format!("{ARCHIVE_SCHEMA_PREFIX}{}", sf.archive_path),
            sf.bytes.clone(),
        ));
    }
    for (rel, bytes) in md_entries {
        all_entries.push((posix_path(&rel), bytes));
    }
    all_entries.sort_by(|a, b| a.0.cmp(&b.0));

    let mut buf: Vec<u8> = Vec::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut zip = zip::ZipWriter::new(cursor);
        let options = SimpleFileOptions::default()
            .compression_method(CompressionMethod::Deflated)
            .last_modified_time(fixed_mtime())
            .unix_permissions(0o644);

        for (archive_path, bytes) in &all_entries {
            zip.start_file(archive_path, options)?;
            zip.write_all(bytes)?;
        }
        zip.finish()?;
    }

    // Strict
    // archive validation runs against the in-memory bytes before they
    // leave this function. Export and install share one validator
    // pass — the trust boundary fires at export rather than letting an
    // invalid archive land on disk and refuse only at the next install
    // attempt. If the produced archive doesn't validate (legacy
    // on-disk drift, hand-edited markdown, archive-imports from
    // non-canonical sources), surface the typed refusal; the
    // disk-shaped wrapper (`export_mem`) never writes a broken
    // archive because validation happens here, pre-write.
    //
    // The *lenient* variant collects cross-mem edges (whose target
    // won't travel inside this single-mem archive) instead of
    // refusing on them — export warns and still produces, where install
    // refuses. Every other strict check still refuses, so a
    // genuinely-broken archive never lands.
    let validated = crate::validator::validate_and_normalize_archive_lenient(&buf)
        .map_err(|e| MemExportError::ArchiveValidationFailed(e.to_string()))?;

    Ok(MemExportBytes {
        bytes: buf,
        name: published.name.clone(),
        version: published.version.to_string(),
        entity_count,
        dangling_cross_mem_edges: validated.dangling_cross_mem_edges,
        redactions: Vec::new(),
    })
}

/// Zip's minimum representable timestamp — 1980-01-01 00:00:00. Used
/// as a fixed mtime so archives are byte-stable across exports.
fn fixed_mtime() -> DateTime {
    DateTime::default()
}

fn posix_path(path: &Path) -> String {
    path.components()
        .filter_map(|c| c.as_os_str().to_str())
        .collect::<Vec<_>>()
        .join("/")
}

/// Recursively collect `.md` files. Skips hidden directories and
/// `README.md` (same policy as the entity loaders — a folder mem living
/// visibly in a repository tree carries a human-facing README beside its
/// entity files, and what load skips, export must skip too).
fn collect_markdown(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), std::io::Error> {
    let mut children: Vec<_> = fs::read_dir(dir)?.collect::<Result<_, _>>()?;
    children.sort_by_key(|e| e.file_name());

    for entry in children {
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();

        if path.is_dir() {
            if name.starts_with('.') {
                continue;
            }
            collect_markdown(&path, out)?;
        } else if name.ends_with(".md") && name.as_ref() != "README.md" {
            out.push(path);
        }
    }
    Ok(())
}