Skip to main content

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        &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
63        for mount in &self.mounts {
64            let mem_name = mount.mount.mem.as_str();
65            if let Some(filter) = mem_filter
66                && mem_name != filter
67            {
68                continue;
69            }
70            let MountStorage::Folder { path: mem_dir } = &mount.mount.storage else {
71                skipped_mounts.push(crate::ops::SkippedMount {
72                    mem: mem_name.to_string(),
73                    active_backend: mount.mount.storage.backend_id().to_string(),
74                    reason: "backend_does_not_support_markdown_export".to_string(),
75                });
76                continue;
77            };
78            let schema = match self.schemas.get(mem_name) {
79                Some(s) => s,
80                None => continue,
81            };
82
83            for entity in self.store.all_entities() {
84                if entity.stub || entity.file_path.is_empty() {
85                    continue;
86                }
87                if entity.id.mem() != mem_name {
88                    continue;
89                }
90                if let Some(filter) = schema_filter
91                    && entity.entity_type != filter
92                {
93                    continue;
94                }
95                let type_def = schema
96                    .get_type(&entity.entity_type)
97                    .unwrap_or_else(|| fallback.clone());
98                let generated = generate_markdown(entity, type_def.as_ref());
99
100                let full_path = mem_dir.join(&entity.file_path);
101                let needs_write = match std::fs::read_to_string(&full_path) {
102                    Ok(existing) => existing != generated,
103                    Err(_) => true,
104                };
105                if needs_write {
106                    match crate::entity::writer::write_entity(entity, mem_dir, type_def.as_ref()) {
107                        Ok(_) => total_written += 1,
108                        // The one refusal the export must not swallow: writing
109                        // this entity would bury the sections its open fence
110                        // absorbed. Name it and carry on — an export that
111                        // aborted here would strand every other entity.
112                        Err(e @ crate::entity::writer::WriteError::UnterminatedFence { .. }) => {
113                            refused.push(crate::ops::RefusedEntity {
114                                id: entity.id.to_string(),
115                                reason: "UNTERMINATED_FENCE_IN_STORED_BODY".to_string(),
116                                detail: e.to_string(),
117                            });
118                        }
119                        Err(_) => {}
120                    }
121                } else {
122                    total_unchanged += 1;
123                }
124            }
125        }
126
127        Ok(crate::ops::ExportResult {
128            refused_entities: refused,
129            written: total_written,
130            unchanged: total_unchanged,
131            skipped_mounts,
132        })
133    }
134
135    /// Export a mem as a portable `.mem` archive.
136    ///
137    /// Dispatch is internal: the engine looks up the mount whose mem
138    /// name matches and branches on its `MountStorage`. Folder mounts
139    /// produce a snapshot archive (current `.md` files + config);
140    /// git-branch mounts invoke the registered [`GitBranchOps::export`]
141    /// hook to produce a history archive (the per-mem branch tip's
142    /// tree); archive mounts reject with `BackendError::Sealed`
143    /// (already-an-archive — no meaningful re-export).
144    ///
145    /// The mem's `MemConfig` is looked up via
146    /// [`Self::mem_config_for`]; unloaded configs (folder mounts
147    /// without a `.memstead/config.json`, git-branch mounts without a
148    /// `__MEMSTEAD:mems/<mem>/config.json`) surface as
149    /// `EngineError::InvalidInput`. Workspace-level schema dir is
150    /// threaded from `self.settings.schemas_dir` for the
151    /// schema-source resolution chain.
152    /// Resolve the mem's pinned schema from the workspace's
153    /// `__MEMSTEAD:schemas/` ref (git-branch schema store) for the
154    /// export paths of NON-git-branch mounts. `None` when the git-branch
155    /// ops are not wired, the workspace has no mem-repo, or the
156    /// package is not on the ref — callers then fall through to the
157    /// disk/builtin chain unchanged. Without this, a folder mem whose
158    /// schema `memstead schema install` sealed on the ref LOADS but
159    /// cannot EXPORT: the loader and the archive assembler must read
160    /// the same store.
161    pub(crate) fn ref_schema_source_for(
162        &self,
163        config: &memstead_schema::MemConfig,
164    ) -> Option<Vec<memstead_schema::SchemaSourceFile>> {
165        let ops = self.git_branch_ops.as_ref()?;
166        let root = self.workspace_root.as_deref()?;
167        let pin = config.schema.as_ref()?;
168        (ops.collect_ref_schema_source)(root, pin).ok().flatten()
169    }
170
171    pub fn export_mem(
172        &self,
173        mem_name: &str,
174        output_path: &std::path::Path,
175    ) -> Result<crate::ops::MemExportResult, EngineError> {
176        let mount = self
177            .mounts
178            .iter()
179            .find(|m| m.mount.mem == mem_name)
180            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
181        let config = self.mem_config_for(mem_name).ok_or_else(|| {
182            EngineError::InvalidInput(format!(
183                "mem '{mem_name}' has no loaded MemConfig — cannot export"
184            ))
185        })?;
186        // F1: surface the missing-version case as a typed
187        // `MEM_CONFIG_INCOMPLETE` envelope with structured recovery
188        // details, rather than letting it bubble through as the
189        // backend's `INTERNAL` collapse pointing at the wrong path
190        // (`.memstead/config.json` is the folder-backend layout — the
191        // mem-repo backend keeps the blob under `__MEMSTEAD:mems/`).
192        // The check fires for both backends symmetrically.
193        if config.version.is_none() {
194            return Err(EngineError::MemConfigIncomplete {
195                mem: mem_name.to_string(),
196                missing_fields: vec!["version".to_string()],
197            });
198        }
199        // Collected before the backend split so both storage kinds report
200        // it. `install` refuses the archive for each of these; naming them at
201        // export time is the same courtesy the dangling cross-mem edges get,
202        // and for the same reason: an operator who learns at install time has
203        // already shared the archive.
204        let fenced: Vec<String> = self
205            .store
206            .all_entities()
207            .filter(|e| e.mem == mem_name && !e.stub)
208            .filter(|e| {
209                e.sections
210                    .values()
211                    .any(|v| crate::markdown::closing_fence_if_unterminated(v.trim()).is_some())
212            })
213            .map(|e| e.id.to_string())
214            .collect();
215        let workspace_root = self.workspace_root.as_deref();
216        // Authored schemas live at the fixed `<workspace>/.memstead/schemas/`
217        // location (the `schemas_dir` key is retired). Absent dir → the
218        // schema-source chain falls through to cache/built-in, as before.
219        let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
220        let workspace_schemas_dir = fixed_schemas_dir.as_deref();
221        let exported = match &mount.mount.storage {
222            MountStorage::Folder { path } => crate::ops::export::export_mem(
223                path,
224                config,
225                output_path,
226                workspace_root,
227                workspace_schemas_dir,
228                self.ref_schema_source_for(config),
229                Some(&self.sealed_row_reader(mem_name)),
230            )
231            .map_err(|e| EngineError::Backend(BackendError::Other(format!("export_mem: {e}")))),
232            MountStorage::GitBranch { gitdir, branch } => {
233                let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
234                    EngineError::Backend(BackendError::Other(
235                        "git-branch export hook not installed (git-branch ops not wired)"
236                            .to_string(),
237                    ))
238                })?;
239                // Source per-entity provenance from the git-branch mutation
240                // log (commit trailers) and hand the serialised payload to
241                // the export hook to embed — symmetric with the bytes path.
242                let entity_paths = crate::ops::export::entity_paths_of(
243                    &mount
244                        .backend
245                        .list_entities()
246                        .map_err(EngineError::Backend)?,
247                );
248                let records = mount.backend.read_provenance(None).unwrap_or_default();
249                let (provenance, redactions) =
250                    crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
251                let provenance_bytes = provenance.to_archive_bytes().ok();
252                // Source the anchors sidecar from the branch tip — symmetric
253                // with the bytes-export path so the disk `.mem` carries anchors.
254                let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
255                // The sealed check records come from the workspace ledger
256                // the engine holds, each with the independence reading the
257                // engine derives; the hook only places the member.
258                let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
259                    workspace_root,
260                    mem_name,
261                    &entity_paths,
262                    Some(&self.sealed_row_reader(mem_name)),
263                );
264                (hook.export)(
265                    gitdir,
266                    branch,
267                    mem_name,
268                    config,
269                    output_path,
270                    workspace_root,
271                    workspace_schemas_dir,
272                    provenance_bytes.as_deref(),
273                    anchors_bytes.as_deref(),
274                    checks_bytes.as_deref(),
275                )
276                .map(|mut r| {
277                    r.redactions =
278                        crate::ops::export::merge_redactions(redactions, check_redactions);
279                    r
280                })
281                .map_err(EngineError::Backend)
282            }
283            MountStorage::Archive { .. } => Err(EngineError::Backend(BackendError::Sealed)),
284            // `.mem` export from an in-memory mem lands with the
285            // writable-session-server plan (it needs a backend-level
286            // archive builder); this plan adds the backend, not the
287            // export path, so refuse explicitly rather than silently.
288            MountStorage::InMemory => Err(EngineError::Backend(BackendError::Other(
289                "export not yet supported for in-memory backend".to_string(),
290            ))),
291        };
292        exported.map(|mut r| {
293            r.unterminated_fence_entities = fenced;
294            r
295        })
296    }
297
298    /// Update a mem's `version` field in its per-mem config and
299    /// persist it through the backend. Backend-symmetric: folder
300    /// backends rewrite `.memstead/config.json`; git-branch backends
301    /// commit `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts
302    /// reject with `BackendError::Sealed`.
303    ///
304    /// Returns the (mem, old_version, new_version) triple so
305    /// callers can surface the change without an extra read. Reads
306    /// the current value from the in-memory `MemConfig` and
307    /// updates it on success, keeping the next call free of a
308    /// stale-version read.
309    ///
310    /// `EngineError::UnknownMem` when the name resolves to no
311    /// mount; `EngineError::ReadOnlyMount` when the mount is sealed
312    /// for writes; `EngineError::InvalidInput` when the mount has no
313    /// loaded `MemConfig` (folder mount with no
314    /// `.memstead/config.json`; the residual missing-config path is
315    /// distinct from the missing-version path). F1.
316    /// Record pipeline-edit provenance through `mem`'s backend — the
317    /// bridge the pipeline-edit block (outside the engine module) uses
318    /// to reach a mount's backend. A mem that isn't currently mounted
319    /// is a successful no-op: pipeline configs may reference unmounted
320    /// mems, and provenance is recorded against the mounted set.
321    pub fn record_pipeline_edit_provenance(
322        &self,
323        mem: &str,
324        kind: &str,
325        edits: &[(String, Option<Vec<u8>>)],
326        note: Option<&str>,
327        verb: &str,
328    ) -> Result<(), crate::backend::BackendError> {
329        let ctx =
330            self.session_commit_context(Some("memstead_pipeline_edit"), note.map(String::from));
331        match self.mounts.iter().find(|m| m.mount.mem == mem) {
332            Some(m) => m.backend.record_pipeline_edit(kind, edits, &ctx, verb),
333            None => Ok(()),
334        }
335    }
336}