memstead-base 0.21.0

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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! The mem setting verbs: version, description, title, subject, internal and sync state, each carrying its own read-only refusal.

use super::*;

impl Engine {
    pub fn set_mem_version(
        &mut self,
        mem_name: &str,
        new_version: semver::Version,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemVersionOutcome, EngineError> {
        // Resolve the mount up-front so an unknown-mem name refuses
        // before any drift-probe side effect lands.
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }

        // Probe for concurrent-drift before the write — a sibling
        // engine that committed between our last snapshot and now
        // surfaces `MEM_RELOADED` on the response so callers see
        // the drift without a separate read round-trip. Drift
        // warnings ride alongside the success outcome; an
        // unreachable-backend probe collapses to no warnings (the
        // existing accessor warn-logs internally and skips).
        let mut warnings = self.reload_if_stale(Some(mem_name));
        // Provenance nudge — same posture as every other commit-
        // producing mutation: when `require_notes` is set and no note
        // was supplied, ride a non-blocking `NOTE_MISSING` warning.
        // The version bump still commits.
        if let Some(w) = self.note_missing_warning("set_mem_version", note) {
            warnings.push(w);
        }

        // The old value is read from the STORED config, not the cache: the
        // cache may be days stale, and reporting a version the file has not
        // held since boot would be its own small lie.
        let old_version = self.mounts[mount_idx]
            .mem_config
            .as_ref()
            .and_then(|c| c.version.clone());
        let target = new_version.clone();
        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_version",
            note,
            &move |c: &mut memstead_schema::config::MemConfig| {
                c.version = Some(target.clone());
            },
        )?;
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemVersionOutcome {
            mem: mem_name.to_string(),
            old_version,
            new_version,
            warnings,
        })
    }

    /// Update a mem's `description` field in its per-mem config and
    /// persist it through the backend — the one-line text mem-archive
    /// export embeds and the registry card surfaces. `None` clears the
    /// field. Same backend symmetry, drift probe, and provenance-note
    /// posture as [`Self::set_mem_version`]; archive mounts reject with
    /// `BackendError::Sealed`.
    pub fn set_mem_description(
        &mut self,
        mem_name: &str,
        new_description: Option<String>,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemDescriptionOutcome, EngineError> {
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }

        let mut warnings = self.reload_if_stale(Some(mem_name));
        if let Some(w) = self.note_missing_warning("set_mem_description", note) {
            warnings.push(w);
        }

        let old_description = self.mounts[mount_idx]
            .mem_config
            .as_ref()
            .and_then(|c| c.description.clone());
        let target = new_description.clone();
        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_description",
            note,
            &move |c: &mut memstead_schema::config::MemConfig| {
                c.description = target.clone();
            },
        )?;
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemDescriptionOutcome {
            mem: mem_name.to_string(),
            old_description,
            new_description,
            warnings,
        })
    }

    /// Update a mem's display `title` — free text, NOT identity: the
    /// mem name stays the sole handle everywhere. `None` clears it.
    /// Mirrors [`Self::set_mem_description`] in backend symmetry,
    /// drift probe, and provenance-note posture.
    pub fn set_mem_title(
        &mut self,
        mem_name: &str,
        new_title: Option<String>,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemTitleOutcome, EngineError> {
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }

        let mut warnings = self.reload_if_stale(Some(mem_name));
        if let Some(w) = self.note_missing_warning("set_mem_title", note) {
            warnings.push(w);
        }

        let old_title = self.mounts[mount_idx]
            .mem_config
            .as_ref()
            .and_then(|c| c.title.clone());
        let target = new_title.clone();
        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_title",
            note,
            &move |c: &mut memstead_schema::config::MemConfig| {
                c.title = target.clone();
            },
        )?;
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemTitleOutcome {
            mem: mem_name.to_string(),
            old_title,
            new_title,
            warnings,
        })
    }

    /// Update a mem's `subject` block — scope, method, deliberate
    /// exclusions, published verbatim. `None` clears the block AS A
    /// UNIT. Mirrors [`Self::set_mem_description`].
    pub fn set_mem_subject(
        &mut self,
        mem_name: &str,
        new_subject: Option<memstead_schema::MemSubject>,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemSubjectOutcome, EngineError> {
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }

        let mut warnings = self.reload_if_stale(Some(mem_name));
        if let Some(w) = self.note_missing_warning("set_mem_subject", note) {
            warnings.push(w);
        }

        let old_subject = self.mounts[mount_idx]
            .mem_config
            .as_ref()
            .and_then(|c| c.subject.clone());
        let target = new_subject.clone();
        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_subject",
            note,
            &move |c: &mut memstead_schema::config::MemConfig| {
                c.subject = target.clone();
            },
        )?;
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemSubjectOutcome {
            mem: mem_name.to_string(),
            old_subject,
            new_subject,
            warnings,
        })
    }

    /// Mark (or unmark) a mem as **internal** — hidden from the default
    /// `memstead_overview` roster and public projections, while remaining a
    /// real, schema-validated, diffable mem (inspectable when explicitly
    /// scoped by name, and deletable). The ingest process-state redesign
    /// (candidate (b)) flags each `ingest/<name>` process mem this way so it
    /// does not clutter the roster alongside real content.
    ///
    /// Stored as the top-level `internal` config field (captured by the
    /// flattened `extra` map). Backend-symmetric like
    /// [`Self::set_mem_description`]; `EngineError::UnknownMem` /
    /// `ReadOnlyMount` / `InvalidInput` on the usual failures.
    pub fn set_mem_internal(
        &mut self,
        mem_name: &str,
        internal: bool,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemInternalOutcome, EngineError> {
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }

        let _ = self.reload_if_stale(Some(mem_name));

        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_internal",
            note,
            &move |c: &mut memstead_schema::config::MemConfig| {
                if internal {
                    c.extra
                        .insert("internal".to_string(), serde_json::Value::Bool(true));
                } else {
                    c.extra.remove("internal");
                }
            },
        )?;
        // This one used to return a bare `bool` and so had nowhere to put the
        // intervention report: it was dropped, not even logged.
        // A writer whose signature
        // cannot carry a warning is a writer that silently will not.
        let mut warnings = Vec::new();
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemInternalOutcome {
            mem: mem_name.to_string(),
            internal,
            warnings,
        })
    }

    /// Declare (or clear) the mem's paired process mem: the mem that
    /// holds its process tier (verification targets, findings, inquiry
    /// entries). The declaration wins over the binding-name convention
    /// the brief renderer and the open-questions health axis otherwise
    /// derive (`crate::binding_run::derived_process_mem_name`); `None`
    /// returns the mem to that convention. The target must be a mounted
    /// mem pinned to an `ingest@*` schema and must not be the mem
    /// itself; anything else refuses [`EngineError::ProcessMemNotEligible`]
    /// before any write. Backend-symmetric like the sibling setters:
    /// one config commit, `CONFIG_WRITE_INTERVENED` on the outcome when
    /// the stored config had moved.
    pub fn set_mem_process_mem(
        &mut self,
        mem_name: &str,
        process_mem: Option<String>,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemProcessMemOutcome, EngineError> {
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }
        if let Some(target) = process_mem.as_deref() {
            let refuse =
                |reason: &'static str, schema: Option<String>| EngineError::ProcessMemNotEligible {
                    mem: mem_name.to_string(),
                    process_mem: target.to_string(),
                    reason,
                    schema,
                };
            if target == mem_name {
                return Err(refuse("self_pairing", None));
            }
            let Some(target_mount) = self.mount(target) else {
                return Err(refuse("not_mounted", None));
            };
            let pin = target_mount
                .schema
                .as_ref()
                .map(|s| format!("{}@{}", s.name, s.version));
            let is_ingest = target_mount
                .schema
                .as_ref()
                .is_some_and(|s| s.name == crate::binding_run::PROCESS_MEM_SCHEMA_NAME);
            if !is_ingest {
                return Err(refuse("not_ingest_schema", pin));
            }
        }

        let mut warnings = self.reload_if_stale(Some(mem_name));
        if let Some(w) = self.note_missing_warning("set_mem_process_mem", note) {
            warnings.push(w);
        }

        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
        let value = process_mem.clone();
        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_process_mem",
            note,
            &|c: &mut memstead_schema::config::MemConfig| {
                *seen.borrow_mut() = c.process_mem.clone();
                c.process_mem = value.clone();
            },
        )?;
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemProcessMemOutcome {
            mem: mem_name.to_string(),
            previous: seen.into_inner(),
            process_mem,
            warnings,
        })
    }

    /// Set (or clear) one opaque sync-state token in a mem's per-mem
    /// config and persist it through the backend. The ingest layer calls
    /// this after a successful pass over a source's changed slice to
    /// record "the source state the graph was last synced against".
    ///
    /// `key` and `token` are both opaque to the engine: the key is
    /// conventionally `"<ingest>/<facet>"` but the engine treats it as an
    /// arbitrary string; the token's meaning belongs to the medium-type
    /// layer (git → commit id, graph → snapshot token, filesystem → a
    /// JSON-stringified stat digest). The engine never parses either.
    /// An **empty** `token` removes the key — the surface for clearing a
    /// baseline (which the next ingest pass re-seeds at the current
    /// source state).
    ///
    /// Backend-symmetric like [`Self::set_mem_version`]: folder backends
    /// rewrite `.memstead/config.json`; git-branch backends commit
    /// `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts reject with
    /// `BackendError::Sealed`.
    ///
    /// Returns the (mem, key, previous-token) triple so callers can
    /// surface the change without an extra 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`.
    pub fn set_mem_sync_state(
        &mut self,
        mem_name: &str,
        key: &str,
        token: &str,
        note: Option<&str>,
    ) -> Result<crate::ops::SetMemSyncStateOutcome, EngineError> {
        // Resolve the mount up-front so an unknown-mem name refuses
        // before any drift-probe side effect lands.
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }

        // Probe for concurrent-drift before the write — same posture as
        // every other commit-producing mutation; a sibling engine that
        // committed since our last snapshot surfaces `MEM_RELOADED`.
        let mut warnings = self.reload_if_stale(Some(mem_name));
        if let Some(w) = self.note_missing_warning("set_mem_sync_state", note) {
            warnings.push(w);
        }

        // `previous` has to come from the config this write actually lands
        // on, not from the cache: a sibling ingest pass may have moved the
        // very token this call is replacing, and reporting the cached value
        // would name a baseline that has not been current since boot. The
        // cell is written by each `apply` pass, so after a compare-and-set
        // retry it holds what was really overwritten.
        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
        let key_owned = key.to_string();
        let token_owned = token.to_string();
        let (_, intervened) = self.write_mem_config_merged(
            mount_idx,
            mem_name,
            "set_mem_sync_state",
            note,
            &|c: &mut memstead_schema::config::MemConfig| {
                *seen.borrow_mut() = if token_owned.is_empty() {
                    c.sync_state.remove(&key_owned)
                } else {
                    c.sync_state.insert(key_owned.clone(), token_owned.clone())
                };
            },
        )?;
        let previous = seen.into_inner();
        // `removed` distinguishes a no-op clear (key absent) from a real one
        // so the outcome is honest.
        let removed = token.is_empty() && previous.is_some();
        if !intervened.is_empty() {
            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
                mem: mem_name.to_string(),
                fields: intervened,
            });
        }

        Ok(crate::ops::SetMemSyncStateOutcome {
            mem: mem_name.to_string(),
            key: key.to_string(),
            previous,
            removed,
            warnings,
        })
    }
}