memstead-base 0.27.1

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
//! Export: the markdown and mem-archive writers, and the pipeline-edit provenance they record.

use super::*;

impl Engine {
    /// Regenerate entity markdown files from the in-memory store.
    ///
    /// Dispatch:
    /// - When `mem_filter` is `Some(name)`, only that mem's mount
    ///   is considered. If its active backend doesn't support markdown
    ///   regeneration in place (today: anything other than
    ///   `MountStorage::Folder`), the call refuses with
    ///   [`EngineError::MarkdownExportUnsupportedBackend`] carrying
    ///   the active backend's id and the supported-backend list.
    /// - When `mem_filter` is `None`, every mount is iterated.
    ///   Folder mounts regenerate as today; non-folder mounts are
    ///   recorded in [`crate::ops::ExportResult::skipped_mounts`] so
    ///   the caller can surface the partial-success shape.
    ///
    /// Per-folder-mount behaviour: iterate the store, regenerate each
    /// non-stub entity belonging to the mount's mem, compare to the
    /// on-disk file, write if changed.
    ///
    /// `schema_filter` narrows the per-entity-type subset: when
    /// `Some(name)`, only entities whose `entity_type` matches are
    /// regenerated. `None` exports every type.
    ///
    /// Pre-fix this returned
    /// `ExportResult { written: 0, unchanged: 0 }` for git-branch /
    /// archive mounts — a successful-looking no-op that masked the
    /// backend-incompatibility. The typed refusal (per-mem) and the
    /// `skipped_mounts` channel (workspace-wide) give the caller an
    /// agent-actionable signal in one round-trip.
    pub fn export_markdown(
        &mut self,
        mem_filter: Option<&str>,
        schema_filter: Option<&str>,
    ) -> Result<crate::ops::ExportResult, EngineError> {
        use crate::workspace::MountStorage;
        let fallback = engine_fallback_type();
        let supported_backends = vec!["folder".to_string()];

        if let Some(name) = mem_filter {
            let mount = self
                .mounts
                .iter()
                .find(|m| m.mount.mem == name)
                .ok_or_else(|| self.unknown_mem_error(name))?;
            if !matches!(mount.mount.storage, MountStorage::Folder { .. }) {
                return Err(EngineError::MarkdownExportUnsupportedBackend {
                    mem: name.to_string(),
                    active_backend: mount.mount.storage.backend_id().to_string(),
                    supported_backends,
                });
            }
        }

        let mut total_written = 0;
        let mut refused: Vec<crate::ops::RefusedEntity> = Vec::new();
        let mut total_unchanged = 0;
        let mut skipped_mounts: Vec<crate::ops::SkippedMount> = Vec::new();
        let mut warnings: Vec<crate::ops::WarningHint> = Vec::new();

        // The entities whose files an export rewrote, with the hash of the
        // bytes it wrote: the engine's view takes them once the commit
        // lands, as any write's view takes the bytes it wrote.
        let mut rewritten: Vec<(crate::entity::EntityId, String)> = Vec::new();
        // The folder mems in scope; the others are reported skipped.
        let mut targets: Vec<(usize, String)> = Vec::new();
        for (mount_idx, mount) in self.mounts.iter().enumerate() {
            let mem_name = mount.mount.mem.as_str();
            if let Some(filter) = mem_filter
                && mem_name != filter
            {
                continue;
            }
            if !matches!(mount.mount.storage, MountStorage::Folder { .. }) {
                skipped_mounts.push(crate::ops::SkippedMount {
                    mem: mem_name.to_string(),
                    active_backend: mount.mount.storage.backend_id().to_string(),
                    reason: "backend_does_not_support_markdown_export".to_string(),
                });
                continue;
            }
            targets.push((mount_idx, mem_name.to_string()));
        }
        for (mount_idx, mem) in targets {
            // Export writes files into the mem: it holds the mem's write
            // lock and plans from a view read under it (a write another
            // process landed before the lock is in the view, never
            // overwritten), stages every file through the backend and
            // commits once, so it lands through the commit call like any
            // write.
            let _write_lock = self.lock_mems_for_write(&[mem.as_str()])?;
            warnings.extend(self.level_for_write(&[mem.as_str()]));
            let mem_name = mem.as_str();
            let mount = &self.mounts[mount_idx];
            let MountStorage::Folder { path: mem_dir } = &mount.mount.storage else {
                continue;
            };
            let schema = match self.schemas.get(mem_name) {
                Some(s) => s,
                None => continue,
            };
            let backend = mount.backend.as_ref();
            let mut staged: usize = 0;
            let mut mem_rewritten: Vec<(crate::entity::EntityId, String)> = Vec::new();

            for entity in self.store.all_entities() {
                if entity.stub || entity.file_path.is_empty() {
                    continue;
                }
                if entity.id.mem() != mem_name {
                    continue;
                }
                if let Some(filter) = schema_filter
                    && entity.entity_type != filter
                {
                    continue;
                }
                let type_def = schema
                    .get_type(&entity.entity_type)
                    .unwrap_or_else(|| fallback.clone());
                let generated = generate_markdown(entity, type_def.as_ref());

                let full_path = mem_dir.join(&entity.file_path);
                let needs_write = match std::fs::read_to_string(&full_path) {
                    Ok(existing) => existing != generated,
                    Err(_) => true,
                };
                if !needs_write {
                    total_unchanged += 1;
                    continue;
                }
                // The one refusal the export must not perform: writing
                // this entity would bury the sections its open fence
                // absorbed. Name it and carry on — an export that aborted
                // here would strand every other entity.
                if let Some(detail) = crate::entity::writer::unterminated_fence(entity) {
                    refused.push(crate::ops::RefusedEntity {
                        id: entity.id.to_string(),
                        reason: "UNTERMINATED_FENCE_IN_STORED_BODY".to_string(),
                        detail,
                    });
                    continue;
                }
                // A file that cannot be opened for writing would fail the
                // one commit for every entity: it is named and left out,
                // and the others land.
                if full_path.exists()
                    && let Err(e) = std::fs::OpenOptions::new().write(true).open(&full_path)
                {
                    refused.push(crate::ops::RefusedEntity {
                        id: entity.id.to_string(),
                        reason: "EXPORT_TARGET_NOT_WRITABLE".to_string(),
                        detail: format!("{}: {e}", full_path.display()),
                    });
                    continue;
                }
                match backend.write_entity(
                    std::path::Path::new(&entity.file_path),
                    generated.as_bytes(),
                ) {
                    Ok(()) => {
                        staged += 1;
                        mem_rewritten.push((
                            entity.id.clone(),
                            crate::entity::parser::compute_hash(&generated),
                        ));
                    }
                    Err(e) => refused.push(crate::ops::RefusedEntity {
                        id: entity.id.to_string(),
                        reason: "EXPORT_WRITE_FAILED".to_string(),
                        detail: e.to_string(),
                    }),
                }
            }
            if staged > 0 {
                let landed = self.commit_staged(
                    mount_idx,
                    "memstead: export markdown",
                    &crate::vcs::CommitContext::internal(),
                    &[],
                )?;
                warnings.extend(landed.warnings);
                total_written += staged;
                rewritten.extend(mem_rewritten);
            }
        }
        if !rewritten.is_empty() {
            for (id, hash) in rewritten {
                if let Some(entity) = self.store.get_mut(&id) {
                    entity.content_hash = hash;
                }
            }
            self.invalidate_communities();
            self.invalidate_search_indexes();
        }

        Ok(crate::ops::ExportResult {
            refused_entities: refused,
            warnings,
            written: total_written,
            unchanged: total_unchanged,
            skipped_mounts,
        })
    }

    /// Export a mem as a portable `.mem` archive.
    ///
    /// Dispatch is internal: the engine looks up the mount whose mem
    /// name matches and branches on its `MountStorage`. Folder mounts
    /// produce a snapshot archive (current `.md` files + config);
    /// git-branch mounts invoke the registered [`GitBranchOps::export`]
    /// hook to produce a history archive (the per-mem branch tip's
    /// tree); archive mounts reject with `BackendError::Sealed`
    /// (already-an-archive — no meaningful re-export).
    ///
    /// The mem's `MemConfig` is looked up via
    /// [`Self::mem_config_for`]; unloaded configs (folder mounts
    /// without a `.memstead/config.json`, git-branch mounts without a
    /// `__MEMSTEAD:mems/<mem>/config.json`) surface as
    /// `EngineError::InvalidInput`. Workspace-level schema dir is
    /// threaded from `self.settings.schemas_dir` for the
    /// schema-source resolution chain.
    /// Resolve the mem's pinned schema from the workspace's
    /// `__MEMSTEAD:schemas/` ref (git-branch schema store) for the
    /// export paths of NON-git-branch mounts. `None` when the git-branch
    /// ops are not wired, the workspace has no mem-repo, or the
    /// package is not on the ref — callers then fall through to the
    /// disk/builtin chain unchanged. Without this, a folder mem whose
    /// schema `memstead schema install` sealed on the ref LOADS but
    /// cannot EXPORT: the loader and the archive assembler must read
    /// the same store.
    pub(crate) fn ref_schema_source_for(
        &self,
        config: &memstead_schema::MemConfig,
    ) -> Option<Vec<memstead_schema::SchemaSourceFile>> {
        let ops = self.git_branch_ops.as_ref()?;
        let pin = config.schema.as_ref()?;
        self.schema_registry_gitdirs()
            .iter()
            .find_map(|gitdir| (ops.collect_ref_schema_source)(gitdir, pin).ok().flatten())
    }

    pub fn export_mem(
        &self,
        mem_name: &str,
        output_path: &std::path::Path,
    ) -> Result<crate::ops::MemExportResult, EngineError> {
        let mount = self
            .mounts
            .iter()
            .find(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        let config = self.mem_config_for(mem_name).ok_or_else(|| {
            EngineError::InvalidInput(format!(
                "mem '{mem_name}' has no loaded MemConfig — cannot export"
            ))
        })?;
        // Surface the missing-version case as a typed
        // `MEM_CONFIG_INCOMPLETE` envelope with structured recovery
        // details, rather than letting it bubble through as the
        // backend's `INTERNAL` collapse pointing at the wrong path
        // (`.memstead/config.json` is the folder-backend layout — the
        // mem-repo backend keeps the blob under `__MEMSTEAD:mems/`).
        // The check fires for both backends symmetrically.
        if config.version.is_none() {
            return Err(EngineError::MemConfigIncomplete {
                mem: mem_name.to_string(),
                missing_fields: vec!["version".to_string()],
            });
        }
        // Collected before the backend split so both storage kinds report
        // it. `install` refuses the archive for each of these; naming them at
        // export time is the same courtesy the dangling cross-mem edges get,
        // and for the same reason: an operator who learns at install time has
        // already shared the archive.
        let fenced: Vec<String> = self
            .store
            .all_entities()
            .filter(|e| e.mem == mem_name && !e.stub)
            .filter(|e| {
                e.sections
                    .values()
                    .any(|v| crate::markdown::closing_fence_if_unterminated(v.trim()).is_some())
            })
            .map(|e| e.id.to_string())
            .collect();
        let workspace_root = self.workspace_root.as_deref();
        // Authored schemas live at the fixed `<workspace>/.memstead/schemas/`
        // location (the `schemas_dir` key is retired). Absent dir → the
        // schema-source chain falls through to cache/built-in, as before.
        let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
        let workspace_schemas_dir = fixed_schemas_dir.as_deref();
        let exported = match &mount.mount.storage {
            MountStorage::Folder { path } => crate::ops::export::export_mem(
                path,
                config,
                output_path,
                workspace_root,
                workspace_schemas_dir,
                self.ref_schema_source_for(config),
                Some(&self.sealed_row_reader(mem_name)),
            )
            .map_err(|e| EngineError::Backend(BackendError::Other(format!("export_mem: {e}")))),
            MountStorage::GitBranch { gitdir, branch } => {
                let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
                    EngineError::Backend(BackendError::Other(
                        "git-branch export hook not installed (git-branch ops not wired)"
                            .to_string(),
                    ))
                })?;
                // Source per-entity provenance from the git-branch mutation
                // log (commit trailers) and hand the serialised payload to
                // the export hook to embed — symmetric with the bytes path.
                let entity_paths = crate::ops::export::entity_paths_of(
                    &mount
                        .backend
                        .list_entities()
                        .map_err(EngineError::Backend)?,
                );
                let records = mount.backend.read_provenance(None).unwrap_or_default();
                let (provenance, redactions) =
                    crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
                let provenance_bytes = provenance.to_archive_bytes().ok();
                // Source the anchors sidecar from the branch tip — symmetric
                // with the bytes-export path so the disk `.mem` carries anchors.
                let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
                // The sealed check records come from the workspace ledger
                // the engine holds, each with the independence reading the
                // engine derives; the hook only places the member.
                let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
                    workspace_root,
                    mem_name,
                    &entity_paths,
                    Some(&self.sealed_row_reader(mem_name)),
                );
                (hook.export)(
                    gitdir,
                    branch,
                    mem_name,
                    config,
                    output_path,
                    workspace_root,
                    workspace_schemas_dir,
                    provenance_bytes.as_deref(),
                    anchors_bytes.as_deref(),
                    checks_bytes.as_deref(),
                )
                .map(|mut r| {
                    r.redactions =
                        crate::ops::export::merge_redactions(redactions, check_redactions);
                    r
                })
                .map_err(EngineError::Backend)
            }
            MountStorage::Archive { .. } => Err(EngineError::Backend(BackendError::Sealed)),
            // `.mem` export from an in-memory mem lands with the
            // writable-session-server plan (it needs a backend-level
            // archive builder); this plan adds the backend, not the
            // export path, so refuse explicitly rather than silently.
            MountStorage::InMemory => Err(EngineError::Backend(BackendError::Other(
                "export not yet supported for in-memory backend".to_string(),
            ))),
        };
        exported.map(|mut r| {
            r.unterminated_fence_entities = fenced;
            r
        })
    }

    /// Update a mem's `version` field in its per-mem config and
    /// persist it through the backend. Backend-symmetric: folder
    /// backends rewrite `.memstead/config.json`; git-branch backends
    /// commit `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts
    /// reject with `BackendError::Sealed`.
    ///
    /// Returns the (mem, old_version, new_version) triple so
    /// callers can surface the change without an extra read. Reads
    /// the current value from the in-memory `MemConfig` and
    /// updates it on success, keeping the next call free of a
    /// stale-version read.
    ///
    /// `EngineError::UnknownMem` when the name resolves to no
    /// mount; `EngineError::ReadOnlyMount` when the mount is sealed
    /// for writes; `EngineError::InvalidInput` when the mount has no
    /// loaded `MemConfig` (folder mount with no
    /// `.memstead/config.json`; the residual missing-config path is
    /// distinct from the missing-version path).
    /// Record pipeline-edit provenance through `mem`'s backend — the
    /// bridge the pipeline-edit block (outside the engine module) uses
    /// to reach a mount's backend. A mem that isn't currently mounted
    /// is a successful no-op: pipeline configs may reference unmounted
    /// mems, and provenance is recorded against the mounted set.
    pub fn record_pipeline_edit_provenance(
        &self,
        mem: &str,
        kind: &str,
        edits: &[(String, Option<Vec<u8>>)],
        note: Option<&str>,
        verb: &str,
    ) -> Result<(), crate::backend::BackendError> {
        let ctx =
            self.session_commit_context(Some("memstead_pipeline_edit"), note.map(String::from));
        match self.mounts.iter().find(|m| m.mount.mem == mem) {
            Some(m) => m.backend.record_pipeline_edit(kind, edits, &ctx, verb),
            None => Ok(()),
        }
    }
}