Skip to main content

memstead_base/engine/lifecycle/
schema_pin.rs

1//! The mem schema pin and its migration: setting the pin, reading the stamped generation, persisting it, and bumping the backend's copy.
2
3use super::reload::changed_config_fields;
4use super::*;
5
6impl Engine {
7    /// Set a mem's schema pin — the conformance-gated schema-migration
8    /// trigger. Behaviour per the pinned contract:
9    ///
10    /// - requested == current pin → `Noop`, no state change.
11    /// - requested != pin, mem integral against the target →
12    ///   atomic switch (`schema_pin = target`, migration state
13    ///   cleared) in one workspace-store write → `Switched`.
14    /// - requested != pin, mem NOT integral → enter (or stay in)
15    ///   dual-pin: `migration_target = target`, writes validate
16    ///   against the target from this call on, `findings` carries
17    ///   the non-integral entities → `MigrationStarted`
18    ///   (first call) / `MigrationPending` (same target re-issued).
19    /// - re-issued with the in-flight target once every entity is
20    ///   integral → atomic switch → `Switched`.
21    ///
22    /// The trigger is a label change gated by the conformance check —
23    /// no content hashing. The response hands the agent findings and
24    /// nothing else (no migration scripts, no hints); each repair
25    /// write is validated strictly against the target.
26    pub fn set_mem_schema(
27        &mut self,
28        mem: &str,
29        target: &memstead_schema::SchemaRef,
30    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
31        use crate::engine::{SetSchemaOutcome, SetSchemaResult};
32        // A quarantined mem's set-schema IS the repair path (an
33        // unresolvable pin is the commonest quarantine cause): repin
34        // the retained mount, then re-attempt the attach — the same
35        // in-process recovery `reload` performs after an external
36        // repair. Ordinary mounts proceed below unchanged.
37        if self.quarantine_reason(mem).is_some() {
38            return self.set_schema_on_quarantined(mem, target);
39        }
40        let mount_idx = self
41            .mounts
42            .iter()
43            .position(|m| m.mount.mem == mem)
44            .ok_or_else(|| self.unknown_mem_error(mem))?;
45        // Capability gate, identical in shape and position to the six
46        // sibling setters (`set_mem_version` … `set_mem_sync_state`):
47        // a schema-pin change starts a migration — the one lifecycle
48        // mutation a read-only mount must be able to refuse like any
49        // other.
50        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
51            return Err(EngineError::ReadOnlyMount(mem.to_string()));
52        }
53
54        // The requested target must resolve before anything else —
55        // an unknown ref is an error, not a migration into nowhere.
56        let target_schema = self.resolve_schema_by_ref(target).ok_or_else(|| {
57            // The migration resolver consulted workspace-authored
58            // schemas layered over the built-ins (`resolve_schema_by_ref`).
59            let consulted: Vec<_> = self
60                .workspace_schemas
61                .iter()
62                .chain(self.builtin_schemas.iter())
63                .cloned()
64                .collect();
65            EngineError::SchemaNotFound {
66                mem: mem.to_string(),
67                pin: target.as_display(),
68                sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
69                    &target.name,
70                    &target.version,
71                    &consulted,
72                ),
73                install_hint: None,
74            }
75            .with_schema_install_probe(self.workspace_root())
76        })?;
77
78        // `Mount.schema` is now the optional assertion; for a mem the
79        // operator is actively re-pinning it is normally `Some` (and kept
80        // in sync with the config by the switch below). `<unset>` covers a
81        // mount that carried no assertion.
82        let current_pin = self.mounts[mount_idx].mount.schema.clone();
83        let current_pin_display = current_pin
84            .as_ref()
85            .map(|p| p.as_display())
86            .unwrap_or_else(|| "<unset>".to_string());
87        let in_flight = self.mounts[mount_idx].mount.migration_target.clone();
88
89        // The noop question is asked of the pin the engine actually
90        // serves (the loaded schema, resolved from the authoritative
91        // backend config at boot), never of the mount's expectation
92        // alone. With a `SCHEMA_PIN_MISMATCH` (mount says 0.4.0, config
93        // says 0.1.0) the old comparison against the mount answered
94        // "noop" for a target of 0.4.0 and the config stayed at 0.1.0
95        // forever: the one command meant to repair the mismatch could
96        // not. When the served pin already equals the target and only
97        // the mount expectation lags, the expectation is aligned in
98        // place and reported as switched.
99        let served_pin: Option<memstead_schema::SchemaRef> = self.schemas.get(mem).map(|s| {
100            let (name, version) = s.id();
101            memstead_schema::SchemaRef::new(name, version)
102        });
103        // During a dual-pin migration the served schema IS the target
104        // (writes validate against it) while the config still pins the
105        // old generation, so the shortcut applies only with no migration
106        // in flight; an in-flight target falls through to the
107        // conformance gate that completes it.
108        if served_pin.as_ref() == Some(target) && in_flight.is_none() {
109            if current_pin.as_ref() == Some(target) {
110                return Ok(SetSchemaOutcome {
111                    mem: mem.to_string(),
112                    schema_pin: current_pin_display,
113                    migration_target: in_flight.map(|t| t.as_display()),
114                    outcome: SetSchemaResult::Noop,
115                    findings: Vec::new(),
116                    stamped_schema: self.stamped_schema_of(mount_idx),
117                });
118            }
119            self.mounts[mount_idx].mount.schema = Some(target.clone());
120            self.mounts[mount_idx].mount.migration_target = None;
121            self.persist_state()?;
122            return Ok(SetSchemaOutcome {
123                mem: mem.to_string(),
124                schema_pin: target.as_display(),
125                migration_target: None,
126                outcome: SetSchemaResult::Switched,
127                findings: Vec::new(),
128                stamped_schema: self.stamped_schema_of(mount_idx),
129            });
130        }
131
132        // Conformance gate against the requested target. The full
133        // integrity definition includes the consistency axis, but the
134        // schema-switch gate is conformance: consistency breaks are
135        // schema-independent (they neither block nor are caused by a
136        // pin change) and keep their always-available repair paths.
137        let findings = crate::ops::integrity::conformance_findings(
138            &self.store,
139            mem,
140            target_schema.as_ref(),
141            &self.schemas,
142        );
143
144        if findings.is_empty() {
145            // Atomic switch. The pin's authoritative home is the backend
146            // config (boot resolution prefers it over `Mount.schema`), so
147            // persist there FIRST — if that write fails, every other piece
148            // of state stays untouched and the switch is a clean no-op.
149            // Without this the new pin landed only in `mounts.json` and was
150            // silently reverted on the next process boot for any
151            // config-present mem.
152            self.persist_mem_schema_pin(mount_idx, target)?;
153            self.mounts[mount_idx].mount.schema = Some(target.clone());
154            self.mounts[mount_idx].mount.migration_target = None;
155            self.schemas_insert(mem.to_string(), target_schema);
156            self.invalidate_communities();
157            // The index field set derives from the pinned schema — the
158            // schema-switch staleness the whole-map drop used to mask:
159            // this mem's index must be
160            // rebuilt against the new field set.
161            self.invalidate_search_indexes();
162            self.persist_state()?;
163            // The completed migration re-stamps the mutation stamp (the
164            // marker `ENGINE_VERSION_SKEW` reads) with the generation
165            // the mem now sits on. Without this the marker kept naming
166            // the old pin until the next entity write, and an agent
167            // reading it after the migration re-derived from a stale
168            // generation (B5 grader finding, 2026-09-02). The stamp
169            // writer's equality guard keeps a no-move write from
170            // happening; its warnings ride entity mutations and have no
171            // channel on this outcome, the same standing as the sweep.
172            let _stamp_warnings_have_no_channel_here = self.stamp_mutation_versions(mount_idx);
173            return Ok(SetSchemaOutcome {
174                mem: mem.to_string(),
175                schema_pin: target.as_display(),
176                migration_target: None,
177                outcome: SetSchemaResult::Switched,
178                findings: Vec::new(),
179                stamped_schema: self.stamped_schema_of(mount_idx),
180            });
181        }
182
183        let outcome = if in_flight.as_ref() == Some(target) {
184            SetSchemaResult::MigrationPending
185        } else {
186            SetSchemaResult::MigrationStarted
187        };
188        self.mounts[mount_idx].mount.migration_target = Some(target.clone());
189        // Writes validate against the target from this point on —
190        // the load-bearing dual-pin semantic.
191        self.schemas_insert(mem.to_string(), target_schema);
192        self.invalidate_communities();
193        // Same field-set dependency as the atomic-switch branch above.
194        self.invalidate_search_indexes();
195        self.persist_state()?;
196        // A dual-pin entry never moves the marker: the mem still sits
197        // on the old generation until every entity is integral, and
198        // the outcome says which generation the marker carries.
199        Ok(SetSchemaOutcome {
200            mem: mem.to_string(),
201            schema_pin: current_pin_display,
202            migration_target: Some(target.as_display()),
203            outcome,
204            findings,
205            stamped_schema: self.stamped_schema_of(mount_idx),
206        })
207    }
208
209    /// The resolved schema the mem's mutation stamp names, from the
210    /// engine's cached config (kept current by the shared config
211    /// writer), or `None` when the mem carries no stamp.
212    pub(super) fn stamped_schema_of(&self, mount_idx: usize) -> Option<String> {
213        self.mounts
214            .get(mount_idx)
215            .and_then(|m| m.mem_config.as_ref())
216            .and_then(|c| c.mutation_stamp.as_ref())
217            .map(|st| st.schema.clone())
218    }
219
220    /// Persist a mem's new schema pin into the authoritative backend
221    /// config (`.memstead/config.json` for folder, the `__MEMSTEAD`
222    /// mem-config blob for git-branch).
223    ///
224    /// Boot resolution treats the backend config as the authoritative
225    /// settled pin and `Mount.schema` (the `mounts.json` copy) as a
226    /// cross-checked assertion. A schema switch that updated only
227    /// `mounts.json` would therefore be silently reverted on the next
228    /// process boot — the config still names the old pin. This keeps the
229    /// authoritative home in sync at switch time.
230    ///
231    /// Value-level field bump: only the `"schema"` string is rewritten;
232    /// every other config field (`readMems`, write guidance, …) is
233    /// preserved verbatim. Config-absent mems (no `config.json`) keep
234    /// `Mount.schema` as their settled pin, so there is nothing to update
235    /// — a clean no-op.
236    /// **The one way this engine writes a mem config.** Every config-writing
237    /// operation goes through it; none serializes its cached struct
238    /// (consistency-sweep 04/03, criteria 1 and 2).
239    ///
240    /// The defect it removes: a long-lived MCP server reads each mem's config
241    /// once at boot and holds it for days. Eight operations used to clone that
242    /// cached struct, set one field, and write the whole thing back, so
243    /// anything a sibling process changed in between was gone. The
244    /// reload-before-operation invariant did not save them, because the
245    /// staleness probe watches the entity branch (git-branch) or the change
246    /// log (folder) and a config-only write advances neither.
247    ///
248    /// What this does instead is what the schema-pin writer next door already
249    /// did: read the config the backend HAS, mutate the one field on that
250    /// JSON, write it back. A field this call did not set cannot be reverted,
251    /// because this call never had an opinion about it.
252    ///
253    /// `apply` receives the freshly-read config, PARSED. It deliberately does
254    /// not receive raw JSON: an earlier draft handed out the `Value` and each
255    /// closure wrote its own key name, which put `review_mark` in the file
256    /// where the struct reads `reviewMark` and lost the field on the next
257    /// read. Serde owns the wire names; the closures must not restate them.
258    /// Unknown fields survive because `MemConfig` flattens them into `extra`.
259    ///
260    /// `apply` runs again on a re-read if the file moved between the read and
261    /// the write, so it must be a pure function of the config it is handed,
262    /// never of the engine's cache.
263    ///
264    /// Returns the parsed new config plus, when the stored config had moved on
265    /// from what this engine last observed, the fields the intervening writer
266    /// had changed. The caller rides that on its own response as
267    /// `CONFIG_WRITE_INTERVENED`.
268    pub(crate) fn write_mem_config_merged(
269        &mut self,
270        mount_idx: usize,
271        mem_name: &str,
272        tool: &'static str,
273        note: Option<&str>,
274        apply: &dyn Fn(&mut memstead_schema::config::MemConfig),
275    ) -> Result<(memstead_schema::config::MemConfig, Vec<String>), EngineError> {
276        // The config-write commit carries the operation's provenance
277        // like every other commit: the tool that caused it, the
278        // session's actor, client, role and identity, and the note.
279        let ctx = self.session_commit_context(Some(tool), note.map(String::from));
280        let backend = self.mounts[mount_idx].backend.as_ref();
281        let read = |b: &dyn crate::backend::MemBackend| -> Result<Vec<u8>, EngineError> {
282            b.read_mem_config()
283                .map_err(|e| EngineError::Mem(format!("read mem config for update: {e}")))?
284                .ok_or_else(|| {
285                    EngineError::InvalidInput(format!(
286                        "mem '{mem_name}' has no stored MemConfig (initialize the mem via \
287                         `memstead init` or `memstead mem create` first)"
288                    ))
289                })
290        };
291
292        let stored = read(backend)?;
293        // What the intervening writer changed, if anyone did. Compared against
294        // the engine's cached copy, never against a clock: the rule forbids
295        // reacting to cache age, and a single-writer workspace has an
296        // identical cache, so this is empty there.
297        let intervened = match self.mounts[mount_idx].mem_config.as_ref() {
298            Some(cached) => changed_config_fields(cached, &stored),
299            None => Vec::new(),
300        };
301
302        let render =
303            |raw: &[u8]| -> Result<(memstead_schema::config::MemConfig, Vec<u8>), EngineError> {
304                let value: serde_json::Value = serde_json::from_slice(raw)
305                    .map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
306                let mut cfg = memstead_schema::config::parse_mem_config(&value)
307                    .map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
308                apply(&mut cfg);
309                let mut bytes = serde_json::to_vec_pretty(&cfg)
310                    .map_err(|e| EngineError::Mem(format!("serialize mem config: {e}")))?;
311                bytes.push(b'\n');
312                Ok((cfg, bytes))
313            };
314        let (mut parsed, mut bytes) = render(&stored)?;
315
316        // Compare-and-set, done by the backend so the check and the write are
317        // one step. An earlier draft re-read here and then wrote, which is
318        // check-then-write and leaves exactly the lost-update window
319        // open. On a mismatch the loop re-reads, re-applies onto what is
320        // there, and retries: the intervening writer's change is merged, never
321        // overwritten. Bounded, because an unbounded retry against a hot
322        // writer is a hang, and reaching the bound is a real contention
323        // problem the caller should hear about rather than a state to spin in.
324        let mut expected = stored;
325        for attempt in 0..8 {
326            let wrote = self.mounts[mount_idx].backend.write_mem_config_cas(
327                Some(&expected),
328                &bytes,
329                &ctx,
330            )?;
331            if wrote {
332                break;
333            }
334            if attempt == 7 {
335                return Err(EngineError::Mem(format!(
336                    "mem '{mem_name}' config is being written concurrently: eight \
337                     compare-and-set attempts all lost the race. Retry, or find the \
338                     writer that is not backing off."
339                )));
340            }
341            expected = read(self.mounts[mount_idx].backend.as_ref())?;
342            let rendered = render(&expected)?;
343            parsed = rendered.0;
344            bytes = rendered.1;
345        }
346
347        let mounted = &mut self.mounts[mount_idx];
348        mounted.mem_config = Some(parsed.clone());
349        // Refresh the head cursor so the next drift probe does not surface
350        // MEM_RELOADED for the commit this call just produced.
351        if let Some(sha) = mounted.backend.current_head().ok().flatten() {
352            mounted.last_known_head = Some(sha);
353        }
354        Ok((parsed, intervened))
355    }
356
357    fn persist_mem_schema_pin(
358        &mut self,
359        mount_idx: usize,
360        target: &memstead_schema::SchemaRef,
361    ) -> Result<(), EngineError> {
362        let ctx = self.session_commit_context(Some("set_mem_schema"), None);
363        let value = bump_backend_schema_pin(self.mounts[mount_idx].backend.as_ref(), target, &ctx)?;
364        // Refresh the cached parsed config so in-session reads observe the
365        // new pin without a reload.
366        if let Some(value) = value
367            && let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
368        {
369            self.mounts[mount_idx].mem_config = Some(cfg);
370        }
371        Ok(())
372    }
373}
374
375pub fn bump_backend_schema_pin(
376    backend: &dyn crate::backend::MemBackend,
377    target: &memstead_schema::SchemaRef,
378    ctx: &crate::vcs::CommitContext<'_>,
379) -> Result<Option<serde_json::Value>, EngineError> {
380    let Some(bytes) = backend
381        .read_mem_config()
382        .map_err(|e| EngineError::Mem(format!("read mem config for pin update: {e}")))?
383    else {
384        return Ok(None);
385    };
386    let mut value: serde_json::Value = serde_json::from_slice(&bytes)
387        .map_err(|e| EngineError::Mem(format!("parse mem config for pin update: {e}")))?;
388    value["schema"] = serde_json::Value::String(target.as_display());
389    let new_bytes = serde_json::to_vec_pretty(&value)
390        .map_err(|e| EngineError::Mem(format!("serialize mem config for pin update: {e}")))?;
391    backend
392        .write_mem_config(&new_bytes, ctx)
393        .map_err(|e| EngineError::Mem(format!("write mem config for pin update: {e}")))?;
394    Ok(Some(value))
395}