memstead_base/engine/lifecycle/export.rs
1//! Export: the markdown and mem-archive writers, and the pipeline-edit provenance they record.
2
3use super::*;
4
5impl Engine {
6 /// Regenerate entity markdown files from the in-memory store.
7 ///
8 /// Dispatch:
9 /// - When `mem_filter` is `Some(name)`, only that mem's mount
10 /// is considered. If its active backend doesn't support markdown
11 /// regeneration in place (today: anything other than
12 /// `MountStorage::Folder`), the call refuses with
13 /// [`EngineError::MarkdownExportUnsupportedBackend`] carrying
14 /// the active backend's id and the supported-backend list.
15 /// - When `mem_filter` is `None`, every mount is iterated.
16 /// Folder mounts regenerate as today; non-folder mounts are
17 /// recorded in [`crate::ops::ExportResult::skipped_mounts`] so
18 /// the caller can surface the partial-success shape.
19 ///
20 /// Per-folder-mount behaviour: iterate the store, regenerate each
21 /// non-stub entity belonging to the mount's mem, compare to the
22 /// on-disk file, write if changed.
23 ///
24 /// `schema_filter` narrows the per-entity-type subset: when
25 /// `Some(name)`, only entities whose `entity_type` matches are
26 /// regenerated. `None` exports every type.
27 ///
28 /// Pre-fix this returned
29 /// `ExportResult { written: 0, unchanged: 0 }` for git-branch /
30 /// archive mounts — a successful-looking no-op that masked the
31 /// backend-incompatibility. The typed refusal (per-mem) and the
32 /// `skipped_mounts` channel (workspace-wide) give the caller an
33 /// agent-actionable signal in one round-trip.
34 pub fn export_markdown(
35 &mut self,
36 mem_filter: Option<&str>,
37 schema_filter: Option<&str>,
38 ) -> Result<crate::ops::ExportResult, EngineError> {
39 use crate::workspace::MountStorage;
40 let fallback = engine_fallback_type();
41 let supported_backends = vec!["folder".to_string()];
42
43 if let Some(name) = mem_filter {
44 let mount = self
45 .mounts
46 .iter()
47 .find(|m| m.mount.mem == name)
48 .ok_or_else(|| self.unknown_mem_error(name))?;
49 if !matches!(mount.mount.storage, MountStorage::Folder { .. }) {
50 return Err(EngineError::MarkdownExportUnsupportedBackend {
51 mem: name.to_string(),
52 active_backend: mount.mount.storage.backend_id().to_string(),
53 supported_backends,
54 });
55 }
56 }
57
58 let mut total_written = 0;
59 let mut refused: Vec<crate::ops::RefusedEntity> = Vec::new();
60 let mut total_unchanged = 0;
61 let mut skipped_mounts: Vec<crate::ops::SkippedMount> = Vec::new();
62 let mut warnings: Vec<crate::ops::WarningHint> = Vec::new();
63
64 // The entities whose files an export rewrote, with the hash of the
65 // bytes it wrote: the engine's view takes them once the commit
66 // lands, as any write's view takes the bytes it wrote.
67 let mut rewritten: Vec<(crate::entity::EntityId, String)> = Vec::new();
68 // The folder mems in scope; the others are reported skipped.
69 let mut targets: Vec<(usize, String)> = Vec::new();
70 for (mount_idx, mount) in self.mounts.iter().enumerate() {
71 let mem_name = mount.mount.mem.as_str();
72 if let Some(filter) = mem_filter
73 && mem_name != filter
74 {
75 continue;
76 }
77 if !matches!(mount.mount.storage, MountStorage::Folder { .. }) {
78 skipped_mounts.push(crate::ops::SkippedMount {
79 mem: mem_name.to_string(),
80 active_backend: mount.mount.storage.backend_id().to_string(),
81 reason: "backend_does_not_support_markdown_export".to_string(),
82 });
83 continue;
84 }
85 targets.push((mount_idx, mem_name.to_string()));
86 }
87 for (mount_idx, mem) in targets {
88 // Export writes files into the mem: it holds the mem's write
89 // lock and plans from a view read under it (a write another
90 // process landed before the lock is in the view, never
91 // overwritten), stages every file through the backend and
92 // commits once, so it lands through the commit call like any
93 // write.
94 let _write_lock = self.lock_mems_for_write(&[mem.as_str()])?;
95 warnings.extend(self.level_for_write(&[mem.as_str()]));
96 let mem_name = mem.as_str();
97 let mount = &self.mounts[mount_idx];
98 let MountStorage::Folder { path: mem_dir } = &mount.mount.storage else {
99 continue;
100 };
101 let schema = match self.schemas.get(mem_name) {
102 Some(s) => s,
103 None => continue,
104 };
105 let backend = mount.backend.as_ref();
106 let mut staged: usize = 0;
107 let mut mem_rewritten: Vec<(crate::entity::EntityId, String)> = Vec::new();
108
109 for entity in self.store.all_entities() {
110 if entity.stub || entity.file_path.is_empty() {
111 continue;
112 }
113 if entity.id.mem() != mem_name {
114 continue;
115 }
116 if let Some(filter) = schema_filter
117 && entity.entity_type != filter
118 {
119 continue;
120 }
121 let type_def = schema
122 .get_type(&entity.entity_type)
123 .unwrap_or_else(|| fallback.clone());
124 let generated = generate_markdown(entity, type_def.as_ref());
125
126 let full_path = mem_dir.join(&entity.file_path);
127 let needs_write = match std::fs::read_to_string(&full_path) {
128 Ok(existing) => existing != generated,
129 Err(_) => true,
130 };
131 if !needs_write {
132 total_unchanged += 1;
133 continue;
134 }
135 // The one refusal the export must not perform: writing
136 // this entity would bury the sections its open fence
137 // absorbed. Name it and carry on — an export that aborted
138 // here would strand every other entity.
139 if let Some(detail) = crate::entity::writer::unterminated_fence(entity) {
140 refused.push(crate::ops::RefusedEntity {
141 id: entity.id.to_string(),
142 reason: "UNTERMINATED_FENCE_IN_STORED_BODY".to_string(),
143 detail,
144 });
145 continue;
146 }
147 // A file that cannot be opened for writing would fail the
148 // one commit for every entity: it is named and left out,
149 // and the others land.
150 if full_path.exists()
151 && let Err(e) = std::fs::OpenOptions::new().write(true).open(&full_path)
152 {
153 refused.push(crate::ops::RefusedEntity {
154 id: entity.id.to_string(),
155 reason: "EXPORT_TARGET_NOT_WRITABLE".to_string(),
156 detail: format!("{}: {e}", full_path.display()),
157 });
158 continue;
159 }
160 match backend.write_entity(
161 std::path::Path::new(&entity.file_path),
162 generated.as_bytes(),
163 ) {
164 Ok(()) => {
165 staged += 1;
166 mem_rewritten.push((
167 entity.id.clone(),
168 crate::entity::parser::compute_hash(&generated),
169 ));
170 }
171 Err(e) => refused.push(crate::ops::RefusedEntity {
172 id: entity.id.to_string(),
173 reason: "EXPORT_WRITE_FAILED".to_string(),
174 detail: e.to_string(),
175 }),
176 }
177 }
178 if staged > 0 {
179 let landed = self.commit_staged(
180 mount_idx,
181 "memstead: export markdown",
182 &crate::vcs::CommitContext::internal(),
183 &[],
184 )?;
185 warnings.extend(landed.warnings);
186 total_written += staged;
187 rewritten.extend(mem_rewritten);
188 }
189 }
190 if !rewritten.is_empty() {
191 for (id, hash) in rewritten {
192 if let Some(entity) = self.store.get_mut(&id) {
193 entity.content_hash = hash;
194 }
195 }
196 self.invalidate_communities();
197 self.invalidate_search_indexes();
198 }
199
200 Ok(crate::ops::ExportResult {
201 refused_entities: refused,
202 warnings,
203 written: total_written,
204 unchanged: total_unchanged,
205 skipped_mounts,
206 })
207 }
208
209 /// Export a mem as a portable `.mem` archive.
210 ///
211 /// Dispatch is internal: the engine looks up the mount whose mem
212 /// name matches and branches on its `MountStorage`. Folder mounts
213 /// produce a snapshot archive (current `.md` files + config);
214 /// git-branch mounts invoke the registered [`GitBranchOps::export`]
215 /// hook to produce a history archive (the per-mem branch tip's
216 /// tree); archive mounts reject with `BackendError::Sealed`
217 /// (already-an-archive — no meaningful re-export).
218 ///
219 /// The mem's `MemConfig` is looked up via
220 /// [`Self::mem_config_for`]; unloaded configs (folder mounts
221 /// without a `.memstead/config.json`, git-branch mounts without a
222 /// `__MEMSTEAD:mems/<mem>/config.json`) surface as
223 /// `EngineError::InvalidInput`. Workspace-level schema dir is
224 /// threaded from `self.settings.schemas_dir` for the
225 /// schema-source resolution chain.
226 /// Resolve the mem's pinned schema from the workspace's
227 /// `__MEMSTEAD:schemas/` ref (git-branch schema store) for the
228 /// export paths of NON-git-branch mounts. `None` when the git-branch
229 /// ops are not wired, the workspace has no mem-repo, or the
230 /// package is not on the ref — callers then fall through to the
231 /// disk/builtin chain unchanged. Without this, a folder mem whose
232 /// schema `memstead schema install` sealed on the ref LOADS but
233 /// cannot EXPORT: the loader and the archive assembler must read
234 /// the same store.
235 pub(crate) fn ref_schema_source_for(
236 &self,
237 config: &memstead_schema::MemConfig,
238 ) -> Option<Vec<memstead_schema::SchemaSourceFile>> {
239 let ops = self.git_branch_ops.as_ref()?;
240 let root = self.workspace_root.as_deref()?;
241 let pin = config.schema.as_ref()?;
242 (ops.collect_ref_schema_source)(root, pin).ok().flatten()
243 }
244
245 pub fn export_mem(
246 &self,
247 mem_name: &str,
248 output_path: &std::path::Path,
249 ) -> Result<crate::ops::MemExportResult, EngineError> {
250 let mount = self
251 .mounts
252 .iter()
253 .find(|m| m.mount.mem == mem_name)
254 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
255 let config = self.mem_config_for(mem_name).ok_or_else(|| {
256 EngineError::InvalidInput(format!(
257 "mem '{mem_name}' has no loaded MemConfig — cannot export"
258 ))
259 })?;
260 // Surface the missing-version case as a typed
261 // `MEM_CONFIG_INCOMPLETE` envelope with structured recovery
262 // details, rather than letting it bubble through as the
263 // backend's `INTERNAL` collapse pointing at the wrong path
264 // (`.memstead/config.json` is the folder-backend layout — the
265 // mem-repo backend keeps the blob under `__MEMSTEAD:mems/`).
266 // The check fires for both backends symmetrically.
267 if config.version.is_none() {
268 return Err(EngineError::MemConfigIncomplete {
269 mem: mem_name.to_string(),
270 missing_fields: vec!["version".to_string()],
271 });
272 }
273 // Collected before the backend split so both storage kinds report
274 // it. `install` refuses the archive for each of these; naming them at
275 // export time is the same courtesy the dangling cross-mem edges get,
276 // and for the same reason: an operator who learns at install time has
277 // already shared the archive.
278 let fenced: Vec<String> = self
279 .store
280 .all_entities()
281 .filter(|e| e.mem == mem_name && !e.stub)
282 .filter(|e| {
283 e.sections
284 .values()
285 .any(|v| crate::markdown::closing_fence_if_unterminated(v.trim()).is_some())
286 })
287 .map(|e| e.id.to_string())
288 .collect();
289 let workspace_root = self.workspace_root.as_deref();
290 // Authored schemas live at the fixed `<workspace>/.memstead/schemas/`
291 // location (the `schemas_dir` key is retired). Absent dir → the
292 // schema-source chain falls through to cache/built-in, as before.
293 let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
294 let workspace_schemas_dir = fixed_schemas_dir.as_deref();
295 let exported = match &mount.mount.storage {
296 MountStorage::Folder { path } => crate::ops::export::export_mem(
297 path,
298 config,
299 output_path,
300 workspace_root,
301 workspace_schemas_dir,
302 self.ref_schema_source_for(config),
303 Some(&self.sealed_row_reader(mem_name)),
304 )
305 .map_err(|e| EngineError::Backend(BackendError::Other(format!("export_mem: {e}")))),
306 MountStorage::GitBranch { gitdir, branch } => {
307 let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
308 EngineError::Backend(BackendError::Other(
309 "git-branch export hook not installed (git-branch ops not wired)"
310 .to_string(),
311 ))
312 })?;
313 // Source per-entity provenance from the git-branch mutation
314 // log (commit trailers) and hand the serialised payload to
315 // the export hook to embed — symmetric with the bytes path.
316 let entity_paths = crate::ops::export::entity_paths_of(
317 &mount
318 .backend
319 .list_entities()
320 .map_err(EngineError::Backend)?,
321 );
322 let records = mount.backend.read_provenance(None).unwrap_or_default();
323 let (provenance, redactions) =
324 crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
325 let provenance_bytes = provenance.to_archive_bytes().ok();
326 // Source the anchors sidecar from the branch tip — symmetric
327 // with the bytes-export path so the disk `.mem` carries anchors.
328 let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
329 // The sealed check records come from the workspace ledger
330 // the engine holds, each with the independence reading the
331 // engine derives; the hook only places the member.
332 let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
333 workspace_root,
334 mem_name,
335 &entity_paths,
336 Some(&self.sealed_row_reader(mem_name)),
337 );
338 (hook.export)(
339 gitdir,
340 branch,
341 mem_name,
342 config,
343 output_path,
344 workspace_root,
345 workspace_schemas_dir,
346 provenance_bytes.as_deref(),
347 anchors_bytes.as_deref(),
348 checks_bytes.as_deref(),
349 )
350 .map(|mut r| {
351 r.redactions =
352 crate::ops::export::merge_redactions(redactions, check_redactions);
353 r
354 })
355 .map_err(EngineError::Backend)
356 }
357 MountStorage::Archive { .. } => Err(EngineError::Backend(BackendError::Sealed)),
358 // `.mem` export from an in-memory mem lands with the
359 // writable-session-server plan (it needs a backend-level
360 // archive builder); this plan adds the backend, not the
361 // export path, so refuse explicitly rather than silently.
362 MountStorage::InMemory => Err(EngineError::Backend(BackendError::Other(
363 "export not yet supported for in-memory backend".to_string(),
364 ))),
365 };
366 exported.map(|mut r| {
367 r.unterminated_fence_entities = fenced;
368 r
369 })
370 }
371
372 /// Update a mem's `version` field in its per-mem config and
373 /// persist it through the backend. Backend-symmetric: folder
374 /// backends rewrite `.memstead/config.json`; git-branch backends
375 /// commit `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts
376 /// reject with `BackendError::Sealed`.
377 ///
378 /// Returns the (mem, old_version, new_version) triple so
379 /// callers can surface the change without an extra read. Reads
380 /// the current value from the in-memory `MemConfig` and
381 /// updates it on success, keeping the next call free of a
382 /// stale-version read.
383 ///
384 /// `EngineError::UnknownMem` when the name resolves to no
385 /// mount; `EngineError::ReadOnlyMount` when the mount is sealed
386 /// for writes; `EngineError::InvalidInput` when the mount has no
387 /// loaded `MemConfig` (folder mount with no
388 /// `.memstead/config.json`; the residual missing-config path is
389 /// distinct from the missing-version path).
390 /// Record pipeline-edit provenance through `mem`'s backend — the
391 /// bridge the pipeline-edit block (outside the engine module) uses
392 /// to reach a mount's backend. A mem that isn't currently mounted
393 /// is a successful no-op: pipeline configs may reference unmounted
394 /// mems, and provenance is recorded against the mounted set.
395 pub fn record_pipeline_edit_provenance(
396 &self,
397 mem: &str,
398 kind: &str,
399 edits: &[(String, Option<Vec<u8>>)],
400 note: Option<&str>,
401 verb: &str,
402 ) -> Result<(), crate::backend::BackendError> {
403 let ctx =
404 self.session_commit_context(Some("memstead_pipeline_edit"), note.map(String::from));
405 match self.mounts.iter().find(|m| m.mount.mem == mem) {
406 Some(m) => m.backend.record_pipeline_edit(kind, edits, &ctx, verb),
407 None => Ok(()),
408 }
409 }
410}