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