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;
pub fn build_archive_provenance(
records: &[Provenance],
entity_paths: &[String],
) -> ArchiveProvenance {
build_redacted_archive_provenance(records, entity_paths).0
}
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()
}
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) {
Some((ts, _)) if *ts > r.timestamp => {}
_ => {
by_path.insert(path, (r.timestamp, (candidate, counts)));
}
}
}
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),
)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SealedRowFacts {
pub independence: Option<crate::engine::independence::Independence>,
pub origin: Option<crate::render::OriginClass>,
}
pub type SealedRowReader<'a> = &'a dyn Fn(&crate::check::CheckRecord) -> SealedRowFacts;
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();
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),
)
}
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).in_standing_order();
let (sealed, redactions) = build_redacted_sealed_checks(&records, mem_name, entity_paths, rows);
(sealed.and_then(|s| s.to_archive_bytes().ok()), redactions)
}
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)
}
#[derive(Debug, Clone)]
pub struct MemExportBytes {
pub bytes: Vec<u8>,
pub name: String,
pub version: String,
pub entity_count: usize,
pub redactions: Vec<crate::ops::redaction::RedactionCount>,
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),
#[error("export archive failed strict validation: {0}")]
ArchiveValidationFailed(String),
}
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,
})
}
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)?));
}
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);
let anchors_bytes = backend.read_anchors_sidecar().ok().flatten();
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
})
}
pub fn archive_identity(mem_name: &str) -> &str {
mem_name.rsplit('/').next().unwrap_or(mem_name)
}
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,
}
}
pub fn archived_content_hash(bytes: &[u8]) -> Option<String> {
std::str::from_utf8(bytes)
.ok()
.map(crate::entity::parser::compute_hash)
}
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))
}
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() {
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())
}
pub type ProposalMarkSections = indexmap::IndexMap<String, String>;
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();
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();
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));
if let Some(prov) = provenance
&& let Ok(bytes) = prov.to_archive_bytes()
{
all_entries.push((ARCHIVE_PROVENANCE_PATH.to_string(), bytes));
}
if let Some(anchors) = anchors_bytes {
all_entries.push((ARCHIVE_ANCHORS_PATH.to_string(), anchors.to_vec()));
}
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()?;
}
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(),
})
}
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("/")
}
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;
}
if crate::mem::is_nested_mem_root(&path) {
continue;
}
collect_markdown(&path, out)?;
} else if name.ends_with(".md") && name.as_ref() != "README.md" {
out.push(path);
}
}
Ok(())
}