Skip to main content

memstead_base/engine/lifecycle/
reload.rs

1//! Reload: loading mems on demand, reloading one mem or every writable one with their reports, the quarantine reattach, and the settings refresh.
2
3use super::*;
4
5impl Engine {
6    /// Re-read the named mount's backend entities and refresh the
7    /// in-memory store for that mem. Returns the diff against the
8    /// pre-reload snapshot — `added` (ids newly present), `removed`
9    /// (ids no longer present), `changed` (same id, different
10    /// `content_hash`).
11    ///
12    /// Operator-triggered: useful when an external writer modified
13    /// disk while this engine instance was alive (the folder backend
14    /// assumes single-writer; this primitive is the escape hatch when
15    /// that assumption breaks). On the happy path the diff is empty.
16    ///
17    /// Drift detection (whether disk *did* change) is not part of this
18    /// surface — callers that want to short-circuit on "nothing
19    /// changed" must compare `added.is_empty() && changed.is_empty()
20    /// && removed.is_empty()` against the result. Backend-specific
21    /// drift signals (git HEAD comparison, mtime check) live in the
22    /// backends where they have meaning.
23    ///
24    /// Invalidates community + search-index memos on success.
25    /// Load every DEFERRED (lazy, not-yet-loaded) mem matching `mem`
26    /// (`None` = all) into the store — the first-read trigger of the
27    /// lazy-mount lifecycle. Runs before the staleness probes on every
28    /// operation ([`Self::reload_if_stale`] calls it first), so an
29    /// operation scoped to one mem loads exactly that mem, and a
30    /// workspace-scoped operation (search, overview, health) loads
31    /// whatever it needs to answer over a complete store — a count
32    /// computed over a partial store is never presented as truth.
33    ///
34    /// Loading rides the ordinary per-mem reload (entity walk, store
35    /// push, the workspace-global validation passes, memo
36    /// invalidation), so a lazily-loaded mem gets the same refusals and
37    /// warnings an eager boot produces for the same content — deferral
38    /// changes WHEN the gauntlet runs, never whether. After each load,
39    /// pending `SuspiciousNestedPrefix` warnings whose target arrived
40    /// with this mem are dropped — the same legitimate-cross-mem
41    /// exemption the eager boot applies once every mount is loaded.
42    ///
43    /// A deferred load that FAILS quarantines the mem with the same
44    /// typed reporting an eager boot failure produces, at this first
45    /// read: the mount leaves the serving roster, the quarantine roster
46    /// gains the typed reason, and the existing reattach contract
47    /// applies. Deferral never converts a load failure into an
48    /// empty-mem impression.
49    ///
50    /// No-op for workspaces without lazy mounts, for already-loaded
51    /// mems, and for a filter naming no deferred mem.
52    pub fn ensure_mems_loaded(&mut self, mem: Option<&str>) {
53        let pending: Vec<String> = self
54            .mounts
55            .iter()
56            .filter(|m| m.deferred && mem.is_none_or(|v| m.mount.mem == v))
57            .map(|m| m.mount.mem.clone())
58            .collect();
59        for name in pending {
60            match self.reload_one_mem(&name) {
61                Ok(_) => {
62                    if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name) {
63                        state.deferred = false;
64                    }
65                    // Cross-mem links INTO this mem were scanned by the
66                    // nested-prefix detector against a store that did
67                    // not yet carry it; now that its entities exist,
68                    // drop any hit the arrival resolves (mirrors the
69                    // boot-time retain over the complete store).
70                    let store = &self.store;
71                    self.load_warnings.retain(|w| match w {
72                        crate::ops::WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
73                            store.get(resolved_id).is_none_or(|e| e.stub)
74                        }
75                        _ => true,
76                    });
77                }
78                Err(e) => {
79                    // Quarantine at the moment of first read — mirror
80                    // the eager boot failure path byte-for-byte in
81                    // consequence: out of the serving roster, onto the
82                    // quarantine roster with the typed reason.
83                    let Some(idx) = self.mounts.iter().position(|m| m.mount.mem == name) else {
84                        continue;
85                    };
86                    let removed = self.mounts.remove(idx);
87                    self.schemas_remove(&name);
88                    self.quarantined.push(crate::engine::QuarantinedMem {
89                        mount: removed.mount,
90                        reason_code: e.code().to_string(),
91                        reason_message: e.to_string(),
92                    });
93                    self.mem_router = std::sync::Arc::new(
94                        crate::engine::boot::build_mem_router_from_mounts(&self.mounts),
95                    );
96                    self.invalidate_communities();
97                    // The schemas epoch just moved (`schemas_remove`),
98                    // so a filled search memo is stale-keyed — clear it
99                    // here or the next search trips the memo-key
100                    // assert on this branch.
101                    self.invalidate_search_indexes();
102                }
103            }
104        }
105    }
106
107    pub fn reload_one_mem(&mut self, mem: &str) -> Result<crate::ops::ReloadResult, EngineError> {
108        // Per-mem reload refreshes THIS mem's slice of the engine-wide
109        // `load_warnings` accumulator: stale boot-time warnings for the
110        // mem drop, fresh re-parse warnings take their place, other
111        // mems' entries stay untouched. (The earlier "intentionally
112        // silent" contract let a reload heal drift on disk while
113        // `health()` kept reporting the healed warning forever — the
114        // same class of stale-state lie the mem-delete purge closes.)
115        //
116        // The sink is filtered by source-mem attribution before it
117        // merges: `validate_loaded_relations` scans the whole store, so
118        // in principle the sink can carry other mems' warnings. In the
119        // common case those mems' invalid rows were already dropped
120        // from the in-memory store at their own load, so the filter is
121        // a no-op guard against cross-mem duplicates, not a routine
122        // trim. Failure leaves the accumulator untouched (`?` fires
123        // before the merge), matching the inner fn's no-mutation-on-
124        // failed-read fence. Drift events still surface as
125        // `MemReloaded` warnings via `reload_if_stale`.
126        // A quarantined mem's reload is the way back into service:
127        // re-attempt the whole attach (backend, schema resolution,
128        // entity load). On success the roster entry disappears; on
129        // failure the mem stays quarantined with a refreshed reason.
130        if self.quarantine_reason(mem).is_some() {
131            return self.reattach_quarantined_mem(mem);
132        }
133        let mut sink: Vec<WarningHint> = Vec::new();
134        let result = self.reload_one_mem_inner(mem, &mut sink)?;
135        // The view is level with storage again: a write may land on it.
136        if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == mem) {
137            state.reload_failure = None;
138        }
139        self.load_warnings.retain(|w| w.source_mem() != Some(mem));
140        self.load_warnings
141            .extend(sink.into_iter().filter(|w| w.source_mem() == Some(mem)));
142        Ok(result)
143    }
144
145    /// The quarantine branch of [`Self::set_mem_schema`]: repin the
146    /// retained mount (target must resolve — the same booted resolver;
147    /// repair never force-writes a pin that resolves nowhere), bump
148    /// the backend config through the shared value-level writer,
149    /// persist the mount state, then re-attempt the attach. A reattach
150    /// that still fails (some second cause) leaves the mem quarantined
151    /// with its refreshed reason — the pin switch itself is durable
152    /// either way. The booted path's conformance gate cannot run over
153    /// an unloaded mem; findings surface on the post-reattach health.
154    pub(super) fn set_schema_on_quarantined(
155        &mut self,
156        mem: &str,
157        target: &memstead_schema::SchemaRef,
158    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
159        use crate::engine::{SetSchemaOutcome, SetSchemaResult};
160        // The capability gate of the ordinary branch, judged on the
161        // roster as it stands: a pin change is a write, and a mount the
162        // roster gives read-only refuses it in quarantine as it does in
163        // service. Without this the repair path would write a pin into
164        // storage the workspace may only read.
165        if let Some(capability) = self.roster_capability_on_disk(mem)
166            && let Some(q) = self.quarantined.iter_mut().find(|q| q.mount.mem == mem)
167        {
168            q.mount.capability = capability;
169        }
170        if self.quarantined.iter().any(|q| {
171            q.mount.mem == mem && q.mount.capability != crate::workspace::MountCapability::Write
172        }) {
173            return Err(EngineError::ReadOnlyMount(mem.to_string()));
174        }
175        // Same target-ref validation as the ordinary branch.
176        if self.resolve_schema_by_ref(target).is_none() {
177            let consulted: Vec<_> = self
178                .workspace_schemas
179                .iter()
180                .chain(self.builtin_schemas.iter())
181                .cloned()
182                .collect();
183            return Err(EngineError::SchemaNotFound {
184                mem: mem.to_string(),
185                pin: target.as_display(),
186                sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
187                    &target.name,
188                    &target.version,
189                    &consulted,
190                ),
191                install_hint: None,
192            }
193            .with_schema_install_probe(self.workspace_root()));
194        }
195        let Some(q_idx) = self.quarantined.iter().position(|q| q.mount.mem == mem) else {
196            return Err(self.unknown_mem_error(mem));
197        };
198        // Repin the retained mount and, where a backend can be
199        // instantiated, the authoritative backend config (shared
200        // value-level bump — same writer as the ordinary branch).
201        self.quarantined[q_idx].mount.schema = Some(target.clone());
202        self.quarantined[q_idx].mount.migration_target = None;
203        if let Ok(backend) = (self.backend_factory)(&self.quarantined[q_idx].mount) {
204            let ctx = self.session_commit_context(Some("set_mem_schema"), None);
205            let _ = bump_backend_schema_pin(backend.as_ref(), target, &ctx);
206        }
207        self.persist_state()?;
208        // Re-attempt the attach. A failure keeps the quarantine with its
209        // fresh reason on the roster, and the pin switch stands; the call
210        // reports that failure, because a repair that leaves the mem out
211        // of service did not repair it.
212        self.reattach_quarantined_mem(mem)?;
213        // The below-gate repair path validated nothing, so it stamps
214        // nothing: the marker reports what the last validated mutation
215        // stamped (read from the re-attached mount when the repair
216        // succeeded), and the next entity write re-stamps it.
217        let stamped_schema = self
218            .mounts
219            .iter()
220            .position(|m| m.mount.mem == mem)
221            .and_then(|idx| self.stamped_schema_of(idx));
222        Ok(SetSchemaOutcome {
223            mem: mem.to_string(),
224            schema_pin: target.as_display(),
225            migration_target: None,
226            outcome: SetSchemaResult::Switched,
227            findings: Vec::new(),
228            stamped_schema,
229        })
230    }
231
232    /// Re-attempt the boot-time attach of a quarantined mem —
233    /// backend instantiation, schema resolution (same resolver and
234    /// catalogue layering as boot: workspace-authored schemas over
235    /// built-ins), then a per-mem entity load. Success removes the
236    /// roster entry and the mem serves again in the same process;
237    /// any failure keeps (re-)quarantining with the fresh typed
238    /// reason, so the roster never goes stale against the live state.
239    fn reattach_quarantined_mem(
240        &mut self,
241        mem: &str,
242    ) -> Result<crate::ops::ReloadResult, EngineError> {
243        let Some(q_idx) = self.quarantined.iter().position(|q| q.mount.mem == mem) else {
244            return Err(self.unknown_mem_error(mem));
245        };
246        // A mem that comes back into service is new to every caller.
247        self.callers.forget_mem(mem);
248        // The roster may have changed this mount's capability since it
249        // was quarantined, and no reconciliation need have run in
250        // between: the row on disk decides, so the attach never restores
251        // an access the roster withdrew.
252        if let Some(capability) = self.roster_capability_on_disk(mem) {
253            self.quarantined[q_idx].mount.capability = capability;
254        }
255        let mount = self.quarantined[q_idx].mount.clone();
256
257        let requarantine = |this: &mut Self, e: &EngineError| {
258            this.quarantined[q_idx].reason_code = e.code().to_string();
259            this.quarantined[q_idx].reason_message = e.to_string();
260        };
261
262        let backend = match (self.backend_factory)(&mount) {
263            Ok(b) => b,
264            Err(e) => {
265                let err = EngineError::Mem(e.to_string());
266                requarantine(self, &err);
267                return Err(self.unknown_mem_error(mem));
268            }
269        };
270
271        // Same config / pin-authority reads as the boot loop.
272        let last_known_head = backend.current_head().ok().flatten();
273        let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
274            let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
275            memstead_schema::config::parse_mem_config(&value).ok()
276        });
277        let archive_provenance = backend
278            .read_archive_provenance()
279            .ok()
280            .flatten()
281            .and_then(|bytes| memstead_schema::ArchiveProvenance::from_archive_bytes(&bytes).ok());
282        let archive_checks = backend
283            .read_archive_checks()
284            .ok()
285            .flatten()
286            .and_then(|bytes| crate::check::SealedChecks::from_archive_bytes(&bytes).ok());
287        let config_pin = mem_config.as_ref().and_then(|c| c.schema.clone());
288        let effective_pin = mount
289            .migration_target
290            .clone()
291            .or(config_pin)
292            .or(mount.schema.clone());
293        let Some(effective_pin) = effective_pin else {
294            let err = EngineError::MemConfigIncomplete {
295                mem: mem.to_string(),
296                missing_fields: vec!["schema".to_string()],
297            };
298            requarantine(self, &err);
299            return Err(self.unknown_mem_error(mem));
300        };
301        // Same catalogue order as boot: workspace tier, then the mount's
302        // own embedded vocabulary when it is archive-backed, then the
303        // built-ins.
304        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
305            .workspace_schemas
306            .iter()
307            .cloned()
308            .chain(crate::engine::boot::embedded_archive_schemas(&mount))
309            .chain(self.builtin_schemas.iter().cloned())
310            .collect();
311        let schema = match crate::engine::SchemaResolver::new(&catalogue).resolve(&effective_pin) {
312            Ok(s) => s,
313            Err(sources) => {
314                let err = EngineError::SchemaNotFound {
315                    mem: mem.to_string(),
316                    pin: effective_pin.as_display(),
317                    sources,
318                    install_hint: None,
319                }
320                .with_schema_install_probe(self.workspace_root());
321                requarantine(self, &err);
322                return Err(self.unknown_mem_error(mem));
323            }
324        };
325
326        // Attach, then load entities through the ordinary per-mem
327        // reload. An entity-load failure re-quarantines (the mount is
328        // detached again) — quarantine is not tolerance.
329        self.quarantined.remove(q_idx);
330        self.schemas_insert(mem.to_string(), schema);
331        self.mounts.push(crate::engine::MountedBackend {
332            mount,
333            backend: backend.into(),
334            last_known_head,
335            mem_config,
336            archive_provenance,
337            archive_checks,
338            // The reattach loads entities immediately below — a
339            // quarantine return-to-service is never deferred.
340            deferred: false,
341            reload_failure: None,
342            strays: Default::default(),
343        });
344        self.mem_router = std::sync::Arc::new(crate::engine::boot::build_mem_router_from_mounts(
345            &self.mounts,
346        ));
347        let mut sink: Vec<WarningHint> = Vec::new();
348        match self.reload_one_mem_inner(mem, &mut sink) {
349            Ok(result) => {
350                self.load_warnings.retain(|w| w.source_mem() != Some(mem));
351                self.load_warnings
352                    .extend(sink.into_iter().filter(|w| w.source_mem() == Some(mem)));
353                self.invalidate_communities();
354                Ok(result)
355            }
356            Err(e) => {
357                let mount_idx = self.mounts.len() - 1;
358                let mounted = self.mounts.remove(mount_idx);
359                self.schemas_remove(mem);
360                self.mem_router = std::sync::Arc::new(
361                    crate::engine::boot::build_mem_router_from_mounts(&self.mounts),
362                );
363                self.quarantined.push(crate::engine::QuarantinedMem {
364                    mount: mounted.mount,
365                    reason_code: e.code().to_string(),
366                    reason_message: e.to_string(),
367                });
368                // Same epoch-moved staleness as the deferred-load
369                // quarantine branch: `schemas_remove` bumped the
370                // epoch, so both memos must clear.
371                self.invalidate_communities();
372                self.invalidate_search_indexes();
373                Err(e)
374            }
375        }
376    }
377
378    /// Inner per-mem body shared by [`Self::reload_one_mem`]
379    /// and [`Self::reload_each_writable_mem`]. The caller passes
380    /// a warning sink so the workspace-wide reload can forward
381    /// warnings into `self.load_warnings` while the single-mem
382    /// path keeps the accumulator pristine.
383    fn reload_one_mem_inner(
384        &mut self,
385        mem: &str,
386        warnings_sink: &mut Vec<WarningHint>,
387    ) -> Result<crate::ops::ReloadResult, EngineError> {
388        // Locate the target mount + schema. Unknown mem short-
389        // circuits before any store mutation.
390        let mount_idx = self
391            .mounts
392            .iter()
393            .position(|m| m.mount.mem == mem)
394            .ok_or_else(|| self.unknown_mem_error(mem))?;
395        let schema = self
396            .schemas
397            .get(mem)
398            .cloned()
399            .ok_or_else(|| self.unknown_mem_error(mem))?;
400
401        // Snapshot pre-reload (id, content_hash) for this mem.
402        let pre: HashMap<EntityId, String> = self
403            .store
404            .all_entities()
405            .filter(|e| !e.stub && e.mem == mem)
406            .map(|e| (e.id.clone(), e.content_hash.clone()))
407            .collect();
408        let pre_ids: std::collections::HashSet<EntityId> = pre.keys().cloned().collect();
409
410        // Walk the backend; surface read-time errors instead of
411        // mutating the store on a failed reload.
412        // A backend that still holds the staged writes of a failed
413        // mutation would serve them to this load as content.
414        self.discard_strays(mem).map_err(|e| {
415            EngineError::Mem(format!(
416                "reload of mem `{mem}` refused: writes a failed mutation left staged could not \
417                 be discarded: {e}"
418            ))
419        })?;
420        let mut completed_commit = None;
421        let read = collect_source_entries(
422            mem,
423            self.mounts[mount_idx].backend.as_ref(),
424            &mut completed_commit,
425        );
426        // Reported on the next response whatever becomes of this reload.
427        self.completed_commits.extend(completed_commit.clone());
428        let read = read?;
429        // A reload replaces a whole view with what it reads. A file that
430        // could not be read would leave its entity out of the new view
431        // with nothing to show for it, and a write of that id would then
432        // land over the file. The view in place is behind and whole;
433        // keep it and report the reload as failed.
434        if let Some(reason) = read.incomplete() {
435            return Err(EngineError::Mem(format!(
436                "reload of mem `{mem}` is incomplete: {reason}"
437            )));
438        }
439        // Everything was read: the view this reload builds is level
440        // with storage, whoever asked for it.
441        self.mounts[mount_idx].reload_failure = None;
442        let backend = self.mounts[mount_idx].backend.as_ref();
443        let (entries, read_errors) = (read.entries, read.read_errors);
444        // The unbacked-mount probe rides the reload like the other
445        // load-time warnings: a branch that appeared (or vanished) since
446        // boot changes the answer, and the sink's per-mem replace below
447        // drops the boot-time one.
448        let unbacked =
449            crate::engine::boot::unbacked_mount_warning(&self.mounts[mount_idx].mount, backend);
450        let load_result = parse_entries(entries, read_errors, mem, schema.as_ref());
451
452        // Build the LoadCollector inputs — mem roster + last-
453        // segment suffixes — so the parser pipeline can emit
454        // typed drift warnings into the caller's sink.
455        let mem_names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
456        let known_suffixes: Vec<String> = mem_names
457            .iter()
458            .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
459            .collect();
460
461        // Failure fence above; below this point the store is mutated.
462        let prior_targets = self.targets_of_mem(mem);
463        self.store.remove_entities_by_mem(mem);
464        warnings_sink.extend(completed_commit);
465        if let Some(w) = unbacked {
466            warnings_sink.push(w);
467        }
468        let fallback = engine_fallback_type();
469        push_entities_into_store(
470            &mut self.store,
471            load_result.entities,
472            fallback.as_ref(),
473            Some(crate::entity::store_builder::LoadCollector {
474                warnings: warnings_sink,
475                known_suffixes: &known_suffixes,
476                mem_names: &mem_names,
477            }),
478        );
479        // Re-run parse-time relation validation across the workspace.
480        // A reload re-parses one mem but the validator's cycle pass
481        // is global (acyclic-rel-type subgraphs span mems), so the
482        // scan runs against the whole store. Hand-edits arriving via
483        // sibling-writer commits get the same gauntlet boot enforces
484        // (grammar / unknown_rel_type / shape / cycle).
485        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
486            .mounts
487            .iter()
488            .map(|m| (m.mount.mem.clone(), m.mount.capability))
489            .collect();
490        // Restore cross-mem edges that point INTO this mem. The
491        // removal cascade above dropped their incoming mirrors and the
492        // re-push only rebuilt edges authored by this mem's own
493        // entities, so a cross-mem `A→B` would silently vanish from the
494        // index until a workspace-wide reload. Reconstruct from the
495        // authoritative source records (in-memory only — no other mem is
496        // re-read), then let the remap pass below reclassify alias sources.
497        // Stubs the re-read left without a referrer go too.
498        self.settle_slice(mem, &prior_targets);
499        crate::entity::store_builder::validate_loaded_relations(
500            &mut self.store,
501            &self.schemas,
502            &mount_caps,
503            warnings_sink,
504        );
505        crate::entity::store_builder::remap_alias_target_edge_sources(
506            &mut self.store,
507            &self.schemas,
508        );
509        // Surface load errors back through the engine's accumulator
510        // so subsequent `load_errors()` calls reflect the latest read.
511        // THIS mem's stale entries are replaced, not accumulated — a
512        // repaired file (e.g. a resolved merge conflict) must stop
513        // reporting its old refusal, and a re-read of a still-broken
514        // file must not duplicate its entry. Other mems' entries are
515        // untouched (their reloads own them). Folder mounts key their
516        // entries by absolute source path under the mem root; other
517        // backends have no path-attributable entries to replace.
518        if let crate::workspace::MountStorage::Folder { path } =
519            &self.mounts[mount_idx].mount.storage
520        {
521            let root = path.clone();
522            self.load_errors.retain(|(p, _)| !p.starts_with(&root));
523            // The backend walk yields mem-relative paths while the boot
524            // loader yields absolute ones — normalize to absolute so the
525            // replace-on-reload key stays uniform across both origins.
526            self.load_errors
527                .extend(load_result.errors.into_iter().map(|(p, m)| {
528                    let abs = if p.is_relative() { root.join(&p) } else { p };
529                    (abs, m)
530                }));
531        } else {
532            self.load_errors.extend(load_result.errors);
533        }
534
535        // Refresh the mem's config from the backend too. `sync_state`
536        // (the projection baselines) and the schema pin / write guidance are
537        // mem-scoped state that rides the mem branch, so an out-of-band write
538        // — a sibling `projection advance` / `mem set-sync-state` — must become
539        // visible after a per-mem reload, not only entity changes. A missing or
540        // unparseable config leaves the cached value untouched (best-effort:
541        // the reload never fails on a config read hiccup).
542        if let Ok(Some(bytes)) = self.mounts[mount_idx].backend.read_mem_config()
543            && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
544            && let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
545        {
546            self.mounts[mount_idx].mem_config = Some(cfg);
547        }
548
549        // Diff post-reload against the snapshot.
550        let mut added: Vec<EntityId> = Vec::new();
551        let mut changed: Vec<EntityId> = Vec::new();
552        for entity in self.store.all_entities() {
553            if entity.stub || entity.mem != mem {
554                continue;
555            }
556            match pre.get(&entity.id) {
557                None => added.push(entity.id.clone()),
558                Some(prev_hash) if prev_hash != &entity.content_hash => {
559                    changed.push(entity.id.clone());
560                }
561                Some(_) => {}
562            }
563        }
564        let post_ids: std::collections::HashSet<EntityId> = self
565            .store
566            .all_entities()
567            .filter(|e| !e.stub && e.mem == mem)
568            .map(|e| e.id.clone())
569            .collect();
570        let mut removed: Vec<EntityId> = pre_ids.difference(&post_ids).cloned().collect();
571        added.sort_by(|a, b| a.0.cmp(&b.0));
572        changed.sort_by(|a, b| a.0.cmp(&b.0));
573        removed.sort_by(|a, b| a.0.cmp(&b.0));
574
575        self.invalidate_communities();
576        self.invalidate_search_indexes();
577
578        Ok(crate::ops::ReloadResult {
579            added,
580            changed,
581            removed,
582        })
583    }
584
585    /// Rich-shape variant of [`Self::reload_one_mem`] that returns a
586    /// [`crate::ops::ReloadReport`] (mem + head_before + head_after +
587    /// entities_loaded + changed_entity_ids) instead of the slim
588    /// [`crate::ops::ReloadResult`]. Handler-facing wrapper consumed
589    /// by the `memstead_reload` MCP tool — the rich shape is the wire
590    /// contract MCP callers depend on; the slim form stays for
591    /// programmatic consumers that just want the diff lists.
592    ///
593    /// `head_before` is the engine's **prior cursor** for this mem
594    /// (its cached `last_known_head`), *not* the current on-disk tip:
595    /// when a sibling has committed since, the tip has already advanced,
596    /// so reporting it would make the advertised
597    /// `changes_since(since=head_before)` recipe span an empty range.
598    /// `head_after` is the freshly-peeled tip from
599    /// [`crate::backend::MemBackend::current_head`]; the reload also
600    /// advances the cursor to it, so a follow-up staleness probe does
601    /// not re-reload the same window. Backends without history (folder,
602    /// archive) carry no cursor and return `Ok(None)`; both fields fall
603    /// back to [`crate::ops::EMPTY_TREE_SHA`] for wire-shape stability.
604    ///
605    /// `entities_loaded` is the post-reload non-stub count for the
606    /// mem — same semantic as full's report.
607    ///
608    /// `changed_entity_ids` is the union of `added ∪ changed ∪
609    /// removed` from the underlying [`crate::ops::ReloadResult`]
610    /// so callers don't have to merge three lists themselves —
611    /// matches full's bundled wire shape.
612    pub fn reload_one_mem_report(
613        &mut self,
614        mem: &str,
615    ) -> Result<crate::ops::ReloadReport, EngineError> {
616        // Before anything is reloaded: what other callers wrote through
617        // this engine is news to the caller and no part of the report,
618        // which covers what the reload itself brings in.
619        self.bring_caller_up_to_date();
620        // `head_before` is the engine's PRIOR cursor — the SHA it last
621        // knew for this mem — not the current (possibly already
622        // drifted) on-disk tip. Reporting the tip would collapse the
623        // `changes_since(since=head_before)` range to empty in exactly
624        // the sibling-drift case the recipe targets. `current_head` is
625        // backend-defined: git-branch serves a git cursor, the folder
626        // backend serves its change-ledger watermark, and a backend
627        // without a head signal returns None — for those, `head_before`
628        // stays the empty-tree sentinel that pairs with the
629        // equally-empty `head_after` below.
630        let tracks_head = self
631            .mounts
632            .iter()
633            .find(|m| m.mount.mem == mem)
634            .and_then(|m| m.backend.current_head().ok().flatten())
635            .is_some();
636        let head_before = if tracks_head {
637            self.mounts
638                .iter()
639                .find(|m| m.mount.mem == mem)
640                .and_then(|m| m.last_known_head.clone())
641                .unwrap_or_else(|| crate::ops::EMPTY_TREE_SHA.to_string())
642        } else {
643            crate::ops::EMPTY_TREE_SHA.to_string()
644        };
645
646        let result = self.reload_one_mem(mem)?;
647
648        // Capture head_after = the freshly-peeled tip, and advance the
649        // engine's cursor to it. Without this advance the next
650        // operation's `reload_if_stale` would compare the stale cursor
651        // against the same tip and re-reload the identical window,
652        // re-emitting a spurious `MEM_RELOADED`. Only history-backed
653        // mounts (current_head → Some) carry a cursor to advance.
654        let head_after_raw = self
655            .mounts
656            .iter()
657            .find(|m| m.mount.mem == mem)
658            .and_then(|m| m.backend.current_head().ok().flatten());
659        if let Some(new_head) = head_after_raw.clone()
660            && let Some(m) = self.mounts.iter_mut().find(|m| m.mount.mem == mem)
661        {
662            let before = m
663                .last_known_head
664                .replace(new_head.clone())
665                .unwrap_or_default();
666            // The caller asked for this reload and reads what it brought
667            // in from the report: it has seen the new head. A caller that
668            // was behind the engine before the reload stays behind and is
669            // told on its next operation.
670            self.caller_saw_own_write(mem, &before, &new_head);
671        }
672        let head_after = head_after_raw.unwrap_or_else(|| crate::ops::EMPTY_TREE_SHA.to_string());
673
674        let entities_loaded = self
675            .store
676            .all_entities()
677            .filter(|e| !e.stub && e.mem == mem)
678            .count();
679
680        // Union of added + changed + removed, sorted lexicographically
681        // for deterministic wire output. Matches full's "single
682        // changed_entity_ids list" contract — saves callers from
683        // merging three slices themselves.
684        let mut changed_entity_ids: Vec<EntityId> = result
685            .added
686            .into_iter()
687            .chain(result.changed)
688            .chain(result.removed)
689            .collect();
690        changed_entity_ids.sort_by(|a, b| a.0.cmp(&b.0));
691
692        Ok(crate::ops::ReloadReport {
693            mem: mem.to_string(),
694            head_before,
695            head_after,
696            entities_loaded,
697            changed_entity_ids,
698        })
699    }
700
701    /// Batched rich-shape variant — returns one
702    /// [`crate::ops::ReloadReport`] per mounted mem in declaration
703    /// order. Counterpart to [`Self::reload_each_writable_mem`]
704    /// (slim) that the `memstead_reload` MCP tool's no-mem path
705    /// consumes.
706    ///
707    /// `load_warnings` semantics ride on the per-mem contract: each
708    /// [`Self::reload_one_mem`] in the sweep refreshes its own mem's
709    /// slice of the engine-wide accumulator, so a full sweep leaves
710    /// the accumulator equivalent to a fresh boot. (Earlier this
711    /// variant discarded every reload warning while its slim
712    /// counterpart repopulated — the MCP workspace-wide reload could
713    /// never clear a stale warning.) On first-error-abort, mems
714    /// reloaded before the failure carry refreshed slices and the
715    /// rest keep their boot-time entries — no slice is lost.
716    ///
717    /// Also re-reads `.memstead/workspace.toml` and refreshes
718    /// [`crate::workspace::WorkspaceSettings`] before sweeping the
719    /// mems — this is the pairing with the CLI's
720    /// `memstead workspace allow-create / grant-cross-link / set-mutations`
721    /// family. Without this re-read, a CLI write would land on disk but
722    /// the running MCP would still serve the engine's boot-time policy
723    /// snapshot; every subsequent `memstead_mem_create` against the new
724    /// allowlist would fail with `MEM_PATH_NOT_ALLOWED` until process
725    /// restart. The workspace-wide form runs the heavier path; the
726    /// per-mem form (`reload_one_mem_report`) intentionally skips
727    /// the workspace re-read — content drift doesn't imply policy
728    /// drift.
729    ///
730    /// Reload of `workspace.toml` is best-effort: a missing or
731    /// unparseable file leaves the existing settings untouched. The
732    /// per-mem sweep is the primary contract — settings refresh is
733    /// the additive bonus.
734    ///
735    /// First-error-aborts: if any mem's reload fails, the loop
736    /// stops and the error propagates. Mems reloaded before the
737    /// failing one are already mutated in the store; the returned
738    /// error has no rollback. Operators run the per-mem form to
739    /// retry the failing mem explicitly.
740    pub fn reload_each_writable_mem_reports(
741        &mut self,
742    ) -> Result<Vec<crate::ops::ReloadReport>, EngineError> {
743        self.refresh_workspace_settings_if_possible();
744        let names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
745        let mut out = Vec::with_capacity(names.len());
746        for name in names {
747            let report = self.reload_one_mem_report(&name)?;
748            out.push(report);
749        }
750        Ok(out)
751    }
752
753    /// Best-effort refresh of [`crate::workspace::WorkspaceSettings`]
754    /// from the workspace's `.memstead/workspace.toml`. Called by the
755    /// workspace-wide reload sweep so CLI-driven policy edits become
756    /// visible to a live engine without process restart.
757    ///
758    /// Silent no-op when the engine has no `workspace_root` (legacy
759    /// in-memory constructions) or when the on-disk file is missing /
760    /// unparseable. The per-mem reload contract stays the canonical
761    /// failure surface; settings refresh failures are intentionally
762    /// non-fatal so a malformed workspace.toml doesn't break content
763    /// drift detection.
764    pub(crate) fn refresh_workspace_settings_if_possible(&mut self) {
765        let Some(root) = self.workspace_root.clone() else {
766            return;
767        };
768        let store = crate::workspace_store::FileWorkspaceStore::new();
769        let workspace = match crate::workspace_store::WorkspaceStoreAdapter::load(&store, &root) {
770            Ok(w) => w,
771            Err(_) => return,
772        };
773        self.set_settings(workspace.settings);
774    }
775
776    /// Reload every mounted mem in declaration order; returns one
777    /// `(mem, ReloadResult)` per mount.
778    ///
779    /// Failure model is **first-error-aborts**: if any mem's reload
780    /// fails, the loop stops and the error propagates. Mems reloaded
781    /// before the failing one are already mutated in the store; the
782    /// returned error has no rollback. Operators run the per-mem
783    /// form to retry the failing mem explicitly.
784    ///
785    /// Caller-friendly batching wrapper around [`Self::reload_one_mem`];
786    /// internal cache invalidation happens once per mem (the inner
787    /// call invalidates) so an N-mem batch invalidates the memos
788    /// N times. That's wasteful for large workspaces; once the
789    /// `memstead_reload` MCP handler migrates we can tighten this to one
790    /// invalidation at the end.
791    pub fn reload_each_writable_mem(
792        &mut self,
793    ) -> Result<Vec<(String, crate::ops::ReloadResult)>, EngineError> {
794        let names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
795        // Workspace-wide reload semantics: take the engine-wide
796        // sink, clear it, route per-mem inner reloads through it,
797        // put it back. The result is `self.load_warnings` carries
798        // every typed drift warning the reload sweep produced (so
799        // the next `engine.health()` call surfaces them).
800        let mut sink = std::mem::take(&mut self.load_warnings);
801        sink.clear();
802        let mut out = Vec::with_capacity(names.len());
803        let mut loop_err = None;
804        for name in names {
805            match self.reload_one_mem_inner(&name, &mut sink) {
806                Ok(result) => out.push((name, result)),
807                Err(e) => {
808                    loop_err = Some(e);
809                    break;
810                }
811            }
812        }
813        self.load_warnings = sink;
814        if let Some(e) = loop_err {
815            return Err(e);
816        }
817        Ok(out)
818    }
819}
820
821/// Value-level schema-pin bump on a backend's mem config: read the
822/// config blob, rewrite ONLY the `"schema"` string, write it back —
823/// every other field (`readMems`, write guidance, sync state, …) is
824/// preserved verbatim. Config-absent backends (no `config.json`) are a
825/// clean no-op returning `None`; the caller's `Mount.schema` then
826/// stays the settled pin. Returns the updated JSON value on a write so
827/// callers can refresh caches.
828///
829/// One shared implementation for the booted path
830/// (`Engine::persist_mem_schema_pin`) and the below-boot repair path
831/// (memstead-git-branch) — the two must never fork: a pin written by
832/// repair must be byte-shaped exactly as one written by the engine.
833/// Field names on which the stored config differs from `cached`.
834///
835/// Compared as JSON so the comparison covers every field the struct models
836/// without a hand-written field list that a new field would silently escape.
837/// A parse failure yields no fields rather than a false report: the write
838/// itself will surface the malformed config.
839pub(super) fn changed_config_fields(
840    cached: &memstead_schema::config::MemConfig,
841    stored_bytes: &[u8],
842) -> Vec<String> {
843    let (Ok(a), Ok(b)) = (
844        serde_json::to_value(cached),
845        serde_json::from_slice::<serde_json::Value>(stored_bytes),
846    ) else {
847        return Vec::new();
848    };
849    let (Some(a), Some(b)) = (a.as_object(), b.as_object()) else {
850        return Vec::new();
851    };
852    let mut keys: std::collections::BTreeSet<&String> = a.keys().collect();
853    keys.extend(b.keys());
854    keys.into_iter()
855        .filter(|k| a.get(*k) != b.get(*k))
856        .map(|k| k.to_string())
857        .collect()
858}