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 pin = config.schema.as_ref()?;
241 self.schema_registry_gitdirs()
242 .iter()
243 .find_map(|gitdir| (ops.collect_ref_schema_source)(gitdir, pin).ok().flatten())
244 }
245
246 pub fn export_mem(
247 &self,
248 mem_name: &str,
249 output_path: &std::path::Path,
250 ) -> Result<crate::ops::MemExportResult, EngineError> {
251 let mount = self
252 .mounts
253 .iter()
254 .find(|m| m.mount.mem == mem_name)
255 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
256 let config = self.mem_config_for(mem_name).ok_or_else(|| {
257 EngineError::InvalidInput(format!(
258 "mem '{mem_name}' has no loaded MemConfig — cannot export"
259 ))
260 })?;
261 // Surface the missing-version case as a typed
262 // `MEM_CONFIG_INCOMPLETE` envelope with structured recovery
263 // details, rather than letting it bubble through as the
264 // backend's `INTERNAL` collapse pointing at the wrong path
265 // (`.memstead/config.json` is the folder-backend layout — the
266 // mem-repo backend keeps the blob under `__MEMSTEAD:mems/`).
267 // The check fires for both backends symmetrically.
268 if config.version.is_none() {
269 return Err(EngineError::MemConfigIncomplete {
270 mem: mem_name.to_string(),
271 missing_fields: vec!["version".to_string()],
272 });
273 }
274 // Collected before the backend split so both storage kinds report
275 // it. `install` refuses the archive for each of these; naming them at
276 // export time is the same courtesy the dangling cross-mem edges get,
277 // and for the same reason: an operator who learns at install time has
278 // already shared the archive.
279 let fenced: Vec<String> = self
280 .store
281 .all_entities()
282 .filter(|e| e.mem == mem_name && !e.stub)
283 .filter(|e| {
284 e.sections
285 .values()
286 .any(|v| crate::markdown::closing_fence_if_unterminated(v.trim()).is_some())
287 })
288 .map(|e| e.id.to_string())
289 .collect();
290 let workspace_root = self.workspace_root.as_deref();
291 // Authored schemas live at the fixed `<workspace>/.memstead/schemas/`
292 // location (the `schemas_dir` key is retired). Absent dir → the
293 // schema-source chain falls through to cache/built-in, as before.
294 let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
295 let workspace_schemas_dir = fixed_schemas_dir.as_deref();
296 let exported = match &mount.mount.storage {
297 MountStorage::Folder { path } => crate::ops::export::export_mem(
298 path,
299 config,
300 output_path,
301 workspace_root,
302 workspace_schemas_dir,
303 self.ref_schema_source_for(config),
304 Some(&self.sealed_row_reader(mem_name)),
305 )
306 .map_err(|e| EngineError::Backend(BackendError::Other(format!("export_mem: {e}")))),
307 MountStorage::GitBranch { gitdir, branch } => {
308 let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
309 EngineError::Backend(BackendError::Other(
310 "git-branch export hook not installed (git-branch ops not wired)"
311 .to_string(),
312 ))
313 })?;
314 // Source per-entity provenance from the git-branch mutation
315 // log (commit trailers) and hand the serialised payload to
316 // the export hook to embed — symmetric with the bytes path.
317 let entity_paths = crate::ops::export::entity_paths_of(
318 &mount
319 .backend
320 .list_entities()
321 .map_err(EngineError::Backend)?,
322 );
323 let records = mount.backend.read_provenance(None).unwrap_or_default();
324 let (provenance, redactions) =
325 crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
326 let provenance_bytes = provenance.to_archive_bytes().ok();
327 // Source the anchors sidecar from the branch tip — symmetric
328 // with the bytes-export path so the disk `.mem` carries anchors.
329 let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
330 // The sealed check records come from the workspace ledger
331 // the engine holds, each with the independence reading the
332 // engine derives; the hook only places the member.
333 let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
334 workspace_root,
335 mem_name,
336 &entity_paths,
337 Some(&self.sealed_row_reader(mem_name)),
338 );
339 (hook.export)(
340 gitdir,
341 branch,
342 mem_name,
343 config,
344 output_path,
345 workspace_root,
346 workspace_schemas_dir,
347 provenance_bytes.as_deref(),
348 anchors_bytes.as_deref(),
349 checks_bytes.as_deref(),
350 )
351 .map(|mut r| {
352 r.redactions =
353 crate::ops::export::merge_redactions(redactions, check_redactions);
354 r
355 })
356 .map_err(EngineError::Backend)
357 }
358 MountStorage::Archive { .. } => Err(EngineError::Backend(BackendError::Sealed)),
359 // `.mem` export from an in-memory mem lands with the
360 // writable-session-server plan (it needs a backend-level
361 // archive builder); this plan adds the backend, not the
362 // export path, so refuse explicitly rather than silently.
363 MountStorage::InMemory => Err(EngineError::Backend(BackendError::Other(
364 "export not yet supported for in-memory backend".to_string(),
365 ))),
366 };
367 exported.map(|mut r| {
368 r.unterminated_fence_entities = fenced;
369 r
370 })
371 }
372
373 /// Update a mem's `version` field in its per-mem config and
374 /// persist it through the backend. Backend-symmetric: folder
375 /// backends rewrite `.memstead/config.json`; git-branch backends
376 /// commit `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts
377 /// reject with `BackendError::Sealed`.
378 ///
379 /// Returns the (mem, old_version, new_version) triple so
380 /// callers can surface the change without an extra read. Reads
381 /// the current value from the in-memory `MemConfig` and
382 /// updates it on success, keeping the next call free of a
383 /// stale-version read.
384 ///
385 /// `EngineError::UnknownMem` when the name resolves to no
386 /// mount; `EngineError::ReadOnlyMount` when the mount is sealed
387 /// for writes; `EngineError::InvalidInput` when the mount has no
388 /// loaded `MemConfig` (folder mount with no
389 /// `.memstead/config.json`; the residual missing-config path is
390 /// distinct from the missing-version path).
391 /// Record pipeline-edit provenance through `mem`'s backend — the
392 /// bridge the pipeline-edit block (outside the engine module) uses
393 /// to reach a mount's backend. A mem that isn't currently mounted
394 /// is a successful no-op: pipeline configs may reference unmounted
395 /// mems, and provenance is recorded against the mounted set.
396 pub fn record_pipeline_edit_provenance(
397 &self,
398 mem: &str,
399 kind: &str,
400 edits: &[(String, Option<Vec<u8>>)],
401 note: Option<&str>,
402 verb: &str,
403 ) -> Result<(), crate::backend::BackendError> {
404 let ctx =
405 self.session_commit_context(Some("memstead_pipeline_edit"), note.map(String::from));
406 match self.mounts.iter().find(|m| m.mount.mem == mem) {
407 Some(m) => m.backend.record_pipeline_edit(kind, edits, &ctx, verb),
408 None => Ok(()),
409 }
410 }
411}