Skip to main content

memstead_base/engine/lifecycle/
mem_settings.rs

1//! The mem setting verbs: version, description, title, subject, internal and sync state, each carrying its own read-only refusal.
2
3use super::*;
4
5impl Engine {
6    pub fn set_mem_version(
7        &mut self,
8        mem_name: &str,
9        new_version: semver::Version,
10        note: Option<&str>,
11    ) -> Result<crate::ops::SetMemVersionOutcome, EngineError> {
12        // Resolve the mount up-front so an unknown-mem name refuses
13        // before any drift-probe side effect lands.
14        let mount_idx = self
15            .mounts
16            .iter()
17            .position(|m| m.mount.mem == mem_name)
18            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
19        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
20            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
21        }
22
23        // Probe for concurrent-drift before the write — a sibling
24        // engine that committed between our last snapshot and now
25        // surfaces `MEM_RELOADED` on the response so callers see
26        // the drift without a separate read round-trip. Drift
27        // warnings ride alongside the success outcome; an
28        // unreachable-backend probe collapses to no warnings (the
29        // existing accessor warn-logs internally and skips).
30        let mut warnings = self.reload_if_stale(Some(mem_name));
31        // Provenance nudge — same posture as every other commit-
32        // producing mutation: when `require_notes` is set and no note
33        // was supplied, ride a non-blocking `NOTE_MISSING` warning.
34        // The version bump still commits.
35        if let Some(w) = self.note_missing_warning("set_mem_version", note) {
36            warnings.push(w);
37        }
38
39        // The old value is read from the STORED config, not the cache: the
40        // cache may be days stale, and reporting a version the file has not
41        // held since boot would be its own small lie.
42        let old_version = self.mounts[mount_idx]
43            .mem_config
44            .as_ref()
45            .and_then(|c| c.version.clone());
46        let target = new_version.clone();
47        let (_, intervened) = self.write_mem_config_merged(
48            mount_idx,
49            mem_name,
50            "set_mem_version",
51            note,
52            &move |c: &mut memstead_schema::config::MemConfig| {
53                c.version = Some(target.clone());
54            },
55        )?;
56        if !intervened.is_empty() {
57            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
58                mem: mem_name.to_string(),
59                fields: intervened,
60            });
61        }
62
63        Ok(crate::ops::SetMemVersionOutcome {
64            mem: mem_name.to_string(),
65            old_version,
66            new_version,
67            warnings,
68        })
69    }
70
71    /// Update a mem's `description` field in its per-mem config and
72    /// persist it through the backend — the one-line text mem-archive
73    /// export embeds and the registry card surfaces. `None` clears the
74    /// field. Same backend symmetry, drift probe, and provenance-note
75    /// posture as [`Self::set_mem_version`]; archive mounts reject with
76    /// `BackendError::Sealed`.
77    pub fn set_mem_description(
78        &mut self,
79        mem_name: &str,
80        new_description: Option<String>,
81        note: Option<&str>,
82    ) -> Result<crate::ops::SetMemDescriptionOutcome, EngineError> {
83        let mount_idx = self
84            .mounts
85            .iter()
86            .position(|m| m.mount.mem == mem_name)
87            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
88        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
89            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
90        }
91
92        let mut warnings = self.reload_if_stale(Some(mem_name));
93        if let Some(w) = self.note_missing_warning("set_mem_description", note) {
94            warnings.push(w);
95        }
96
97        let old_description = self.mounts[mount_idx]
98            .mem_config
99            .as_ref()
100            .and_then(|c| c.description.clone());
101        let target = new_description.clone();
102        let (_, intervened) = self.write_mem_config_merged(
103            mount_idx,
104            mem_name,
105            "set_mem_description",
106            note,
107            &move |c: &mut memstead_schema::config::MemConfig| {
108                c.description = target.clone();
109            },
110        )?;
111        if !intervened.is_empty() {
112            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
113                mem: mem_name.to_string(),
114                fields: intervened,
115            });
116        }
117
118        Ok(crate::ops::SetMemDescriptionOutcome {
119            mem: mem_name.to_string(),
120            old_description,
121            new_description,
122            warnings,
123        })
124    }
125
126    /// Update a mem's display `title` — free text, NOT identity: the
127    /// mem name stays the sole handle everywhere. `None` clears it.
128    /// Mirrors [`Self::set_mem_description`] in backend symmetry,
129    /// drift probe, and provenance-note posture.
130    pub fn set_mem_title(
131        &mut self,
132        mem_name: &str,
133        new_title: Option<String>,
134        note: Option<&str>,
135    ) -> Result<crate::ops::SetMemTitleOutcome, EngineError> {
136        let mount_idx = self
137            .mounts
138            .iter()
139            .position(|m| m.mount.mem == mem_name)
140            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
141        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
142            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
143        }
144
145        let mut warnings = self.reload_if_stale(Some(mem_name));
146        if let Some(w) = self.note_missing_warning("set_mem_title", note) {
147            warnings.push(w);
148        }
149
150        let old_title = self.mounts[mount_idx]
151            .mem_config
152            .as_ref()
153            .and_then(|c| c.title.clone());
154        let target = new_title.clone();
155        let (_, intervened) = self.write_mem_config_merged(
156            mount_idx,
157            mem_name,
158            "set_mem_title",
159            note,
160            &move |c: &mut memstead_schema::config::MemConfig| {
161                c.title = target.clone();
162            },
163        )?;
164        if !intervened.is_empty() {
165            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
166                mem: mem_name.to_string(),
167                fields: intervened,
168            });
169        }
170
171        Ok(crate::ops::SetMemTitleOutcome {
172            mem: mem_name.to_string(),
173            old_title,
174            new_title,
175            warnings,
176        })
177    }
178
179    /// Update a mem's `subject` block — scope, method, deliberate
180    /// exclusions, published verbatim. `None` clears the block AS A
181    /// UNIT. Mirrors [`Self::set_mem_description`].
182    pub fn set_mem_subject(
183        &mut self,
184        mem_name: &str,
185        new_subject: Option<memstead_schema::MemSubject>,
186        note: Option<&str>,
187    ) -> Result<crate::ops::SetMemSubjectOutcome, EngineError> {
188        let mount_idx = self
189            .mounts
190            .iter()
191            .position(|m| m.mount.mem == mem_name)
192            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
193        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
194            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
195        }
196
197        let mut warnings = self.reload_if_stale(Some(mem_name));
198        if let Some(w) = self.note_missing_warning("set_mem_subject", note) {
199            warnings.push(w);
200        }
201
202        let old_subject = self.mounts[mount_idx]
203            .mem_config
204            .as_ref()
205            .and_then(|c| c.subject.clone());
206        let target = new_subject.clone();
207        let (_, intervened) = self.write_mem_config_merged(
208            mount_idx,
209            mem_name,
210            "set_mem_subject",
211            note,
212            &move |c: &mut memstead_schema::config::MemConfig| {
213                c.subject = target.clone();
214            },
215        )?;
216        if !intervened.is_empty() {
217            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
218                mem: mem_name.to_string(),
219                fields: intervened,
220            });
221        }
222
223        Ok(crate::ops::SetMemSubjectOutcome {
224            mem: mem_name.to_string(),
225            old_subject,
226            new_subject,
227            warnings,
228        })
229    }
230
231    /// Mark (or unmark) a mem as **internal** — hidden from the default
232    /// `memstead_overview` roster and public projections, while remaining a
233    /// real, schema-validated, diffable mem (inspectable when explicitly
234    /// scoped by name, and deletable). The ingest process-state redesign
235    /// (candidate (b)) flags each `ingest/<name>` process mem this way so it
236    /// does not clutter the roster alongside real content.
237    ///
238    /// Stored as the top-level `internal` config field (captured by the
239    /// flattened `extra` map). Backend-symmetric like
240    /// [`Self::set_mem_description`]; `EngineError::UnknownMem` /
241    /// `ReadOnlyMount` / `InvalidInput` on the usual failures.
242    pub fn set_mem_internal(
243        &mut self,
244        mem_name: &str,
245        internal: bool,
246        note: Option<&str>,
247    ) -> Result<crate::ops::SetMemInternalOutcome, EngineError> {
248        let mount_idx = self
249            .mounts
250            .iter()
251            .position(|m| m.mount.mem == mem_name)
252            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
253        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
254            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
255        }
256
257        let _ = self.reload_if_stale(Some(mem_name));
258
259        let (_, intervened) = self.write_mem_config_merged(
260            mount_idx,
261            mem_name,
262            "set_mem_internal",
263            note,
264            &move |c: &mut memstead_schema::config::MemConfig| {
265                if internal {
266                    c.extra
267                        .insert("internal".to_string(), serde_json::Value::Bool(true));
268                } else {
269                    c.extra.remove("internal");
270                }
271            },
272        )?;
273        // This one used to return a bare `bool` and so had nowhere to put the
274        // intervention report: it was dropped, not even logged.
275        // A writer whose signature
276        // cannot carry a warning is a writer that silently will not.
277        let mut warnings = Vec::new();
278        if !intervened.is_empty() {
279            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
280                mem: mem_name.to_string(),
281                fields: intervened,
282            });
283        }
284
285        Ok(crate::ops::SetMemInternalOutcome {
286            mem: mem_name.to_string(),
287            internal,
288            warnings,
289        })
290    }
291
292    /// Declare (or clear) the mem's paired process mem: the mem that
293    /// holds its process tier (verification targets, findings, inquiry
294    /// entries). The declaration wins over the binding-name convention
295    /// the brief renderer and the open-questions health axis otherwise
296    /// derive (`crate::binding_run::derived_process_mem_name`); `None`
297    /// returns the mem to that convention. The target must be a mounted
298    /// mem pinned to an `ingest@*` schema and must not be the mem
299    /// itself; anything else refuses [`EngineError::ProcessMemNotEligible`]
300    /// before any write. Backend-symmetric like the sibling setters:
301    /// one config commit, `CONFIG_WRITE_INTERVENED` on the outcome when
302    /// the stored config had moved.
303    pub fn set_mem_process_mem(
304        &mut self,
305        mem_name: &str,
306        process_mem: Option<String>,
307        note: Option<&str>,
308    ) -> Result<crate::ops::SetMemProcessMemOutcome, EngineError> {
309        let mount_idx = self
310            .mounts
311            .iter()
312            .position(|m| m.mount.mem == mem_name)
313            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
314        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
315            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
316        }
317        if let Some(target) = process_mem.as_deref() {
318            let refuse =
319                |reason: &'static str, schema: Option<String>| EngineError::ProcessMemNotEligible {
320                    mem: mem_name.to_string(),
321                    process_mem: target.to_string(),
322                    reason,
323                    schema,
324                };
325            if target == mem_name {
326                return Err(refuse("self_pairing", None));
327            }
328            let Some(target_mount) = self.mount(target) else {
329                return Err(refuse("not_mounted", None));
330            };
331            let pin = target_mount
332                .schema
333                .as_ref()
334                .map(|s| format!("{}@{}", s.name, s.version));
335            let is_ingest = target_mount
336                .schema
337                .as_ref()
338                .is_some_and(|s| s.name == crate::binding_run::PROCESS_MEM_SCHEMA_NAME);
339            if !is_ingest {
340                return Err(refuse("not_ingest_schema", pin));
341            }
342        }
343
344        let mut warnings = self.reload_if_stale(Some(mem_name));
345        if let Some(w) = self.note_missing_warning("set_mem_process_mem", note) {
346            warnings.push(w);
347        }
348
349        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
350        let value = process_mem.clone();
351        let (_, intervened) = self.write_mem_config_merged(
352            mount_idx,
353            mem_name,
354            "set_mem_process_mem",
355            note,
356            &|c: &mut memstead_schema::config::MemConfig| {
357                *seen.borrow_mut() = c.process_mem.clone();
358                c.process_mem = value.clone();
359            },
360        )?;
361        if !intervened.is_empty() {
362            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
363                mem: mem_name.to_string(),
364                fields: intervened,
365            });
366        }
367
368        Ok(crate::ops::SetMemProcessMemOutcome {
369            mem: mem_name.to_string(),
370            previous: seen.into_inner(),
371            process_mem,
372            warnings,
373        })
374    }
375
376    /// Set (or clear) one opaque sync-state token in a mem's per-mem
377    /// config and persist it through the backend. The ingest layer calls
378    /// this after a successful pass over a source's changed slice to
379    /// record "the source state the graph was last synced against".
380    ///
381    /// `key` and `token` are both opaque to the engine: the key is
382    /// conventionally `"<ingest>/<facet>"` but the engine treats it as an
383    /// arbitrary string; the token's meaning belongs to the medium-type
384    /// layer (git → commit id, graph → snapshot token, filesystem → a
385    /// JSON-stringified stat digest). The engine never parses either.
386    /// An **empty** `token` removes the key — the surface for clearing a
387    /// baseline (which the next ingest pass re-seeds at the current
388    /// source state).
389    ///
390    /// Backend-symmetric like [`Self::set_mem_version`]: folder backends
391    /// rewrite `.memstead/config.json`; git-branch backends commit
392    /// `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts reject with
393    /// `BackendError::Sealed`.
394    ///
395    /// Returns the (mem, key, previous-token) triple so callers can
396    /// surface the change without an extra read. `EngineError::UnknownMem`
397    /// when the name resolves to no mount; `EngineError::ReadOnlyMount`
398    /// when the mount is sealed for writes; `EngineError::InvalidInput`
399    /// when the mount has no loaded `MemConfig`.
400    pub fn set_mem_sync_state(
401        &mut self,
402        mem_name: &str,
403        key: &str,
404        token: &str,
405        note: Option<&str>,
406    ) -> Result<crate::ops::SetMemSyncStateOutcome, EngineError> {
407        // Resolve the mount up-front so an unknown-mem name refuses
408        // before any drift-probe side effect lands.
409        let mount_idx = self
410            .mounts
411            .iter()
412            .position(|m| m.mount.mem == mem_name)
413            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
414        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
415            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
416        }
417
418        // Probe for concurrent-drift before the write — same posture as
419        // every other commit-producing mutation; a sibling engine that
420        // committed since our last snapshot surfaces `MEM_RELOADED`.
421        let mut warnings = self.reload_if_stale(Some(mem_name));
422        if let Some(w) = self.note_missing_warning("set_mem_sync_state", note) {
423            warnings.push(w);
424        }
425
426        // `previous` has to come from the config this write actually lands
427        // on, not from the cache: a sibling ingest pass may have moved the
428        // very token this call is replacing, and reporting the cached value
429        // would name a baseline that has not been current since boot. The
430        // cell is written by each `apply` pass, so after a compare-and-set
431        // retry it holds what was really overwritten.
432        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
433        let key_owned = key.to_string();
434        let token_owned = token.to_string();
435        let (_, intervened) = self.write_mem_config_merged(
436            mount_idx,
437            mem_name,
438            "set_mem_sync_state",
439            note,
440            &|c: &mut memstead_schema::config::MemConfig| {
441                *seen.borrow_mut() = if token_owned.is_empty() {
442                    c.sync_state.remove(&key_owned)
443                } else {
444                    c.sync_state.insert(key_owned.clone(), token_owned.clone())
445                };
446            },
447        )?;
448        let previous = seen.into_inner();
449        // `removed` distinguishes a no-op clear (key absent) from a real one
450        // so the outcome is honest.
451        let removed = token.is_empty() && previous.is_some();
452        if !intervened.is_empty() {
453            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
454                mem: mem_name.to_string(),
455                fields: intervened,
456            });
457        }
458
459        Ok(crate::ops::SetMemSyncStateOutcome {
460            mem: mem_name.to_string(),
461            key: key.to_string(),
462            previous,
463            removed,
464            warnings,
465        })
466    }
467}