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