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