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    ///
155    /// The pin switch writes into the mem's storage, and a write holds
156    /// the mem's write lock. The caller's workspace lock covers the
157    /// mems in service and not this one, so the lock is taken here,
158    /// before anything is repinned: a mem can be out of service because
159    /// another process holds that very lock over a commit it has not
160    /// applied, and the repair must not write beside that writer. When
161    /// the lock cannot be had the call refuses `WRITE_LOCK_TIMEOUT` and
162    /// has changed nothing, neither in storage nor on the roster.
163    pub(super) fn set_schema_on_quarantined(
164        &mut self,
165        mem: &str,
166        target: &memstead_schema::SchemaRef,
167    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
168        use crate::storage::path_lock;
169        // The capability gate of the ordinary branch, judged on the
170        // roster as it stands: a pin change is a write, and a mount the
171        // roster gives read-only refuses it in quarantine as it does in
172        // service. Without this the repair path would write a pin into
173        // storage the workspace may only read.
174        if let Some(capability) = self.roster_capability_on_disk(mem)
175            && let Some(q) = self.quarantined.iter_mut().find(|q| q.mount.mem == mem)
176        {
177            q.mount.capability = capability;
178        }
179        if self.quarantined.iter().any(|q| {
180            q.mount.mem == mem && q.mount.capability != crate::workspace::MountCapability::Write
181        }) {
182            return Err(EngineError::ReadOnlyMount(mem.to_string()));
183        }
184        // Same target-ref validation as the ordinary branch.
185        if self.resolve_schema_by_ref(target).is_none() {
186            let consulted: Vec<_> = self
187                .workspace_schemas
188                .iter()
189                .chain(self.builtin_schemas.iter())
190                .cloned()
191                .collect();
192            return Err(EngineError::SchemaNotFound {
193                mem: mem.to_string(),
194                pin: target.as_display(),
195                sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
196                    &target.name,
197                    &target.version,
198                    &consulted,
199                ),
200                install_hint: None,
201            }
202            .with_schema_install_probe(self.workspace_root()));
203        }
204        let Some(q_idx) = self.quarantined.iter().position(|q| q.mount.mem == mem) else {
205            return Err(self.unknown_mem_error(mem));
206        };
207        let backend = self
208            .instantiate_backend(&self.quarantined[q_idx].mount)
209            .ok();
210        let lock = backend.as_ref().and_then(|b| b.write_lock_path());
211        let mut held = None;
212        if let Some(path) = lock {
213            // This thread holds the locks of the mems in service, taken
214            // in one sorted order, and this lock is outside that set: a
215            // writer of this mem may be waiting for one of those. So it
216            // is looked at once and not waited for; with no other lock
217            // held the wait is the workspace's write-lock deadline.
218            let started = std::time::Instant::now();
219            let taken = if path_lock::holds_another(&path) {
220                path_lock::try_acquire(&path)
221            } else {
222                path_lock::acquire_within(&path, self.settings().mutations.write_lock_timeout())
223            };
224            match taken {
225                Ok(true) => held = Some(path),
226                Ok(false) => {
227                    return Err(EngineError::WriteLockTimeout {
228                        mem: mem.to_string(),
229                        waited_ms: started.elapsed().as_millis() as u64,
230                    });
231                }
232                // A lock file that cannot be opened: storage that is
233                // gone or may not be written. The pin lands on the
234                // roster alone, and the reattach below names the cause.
235                Err(_) => {}
236            }
237        }
238        let writable = held.is_some()
239            || backend
240                .as_ref()
241                .is_some_and(|b| b.write_lock_path().is_none());
242        let outcome =
243            self.repin_quarantined(mem, target, q_idx, backend.as_deref().filter(|_| writable));
244        if let Some(path) = held {
245            path_lock::release(&path);
246        }
247        outcome
248    }
249
250    /// The writes of [`Self::set_schema_on_quarantined`], under the
251    /// mem's write lock where its storage has one: repin the retained
252    /// mount and, where a backend is given, the authoritative backend
253    /// config (shared value-level bump, the same writer as the ordinary
254    /// branch), persist the mount state, then re-attempt the attach.
255    fn repin_quarantined(
256        &mut self,
257        mem: &str,
258        target: &memstead_schema::SchemaRef,
259        q_idx: usize,
260        backend: Option<&dyn crate::backend::MemBackend>,
261    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
262        use crate::engine::{SetSchemaOutcome, SetSchemaResult};
263        self.quarantined[q_idx].mount.schema = Some(target.clone());
264        self.quarantined[q_idx].mount.migration_target = None;
265        if let Some(backend) = backend {
266            let ctx = self.session_commit_context(Some("set_mem_schema"), None);
267            let _ = bump_backend_schema_pin(backend, target, &ctx);
268        }
269        self.persist_state()?;
270        // Re-attempt the attach. A failure keeps the quarantine with its
271        // fresh reason on the roster, and the pin switch stands; the call
272        // reports that failure, because a repair that leaves the mem out
273        // of service did not repair it.
274        self.reattach_quarantined_mem(mem)?;
275        // The below-gate repair path validated nothing, so it stamps
276        // nothing: the marker reports what the last validated mutation
277        // stamped (read from the re-attached mount when the repair
278        // succeeded), and the next entity write re-stamps it.
279        let stamped_schema = self
280            .mounts
281            .iter()
282            .position(|m| m.mount.mem == mem)
283            .and_then(|idx| self.stamped_schema_of(idx));
284        Ok(SetSchemaOutcome {
285            mem: mem.to_string(),
286            schema_pin: target.as_display(),
287            migration_target: None,
288            outcome: SetSchemaResult::Switched,
289            findings: Vec::new(),
290            stamped_schema,
291        })
292    }
293
294    /// Re-attempt the boot-time attach of a quarantined mem —
295    /// backend instantiation, schema resolution (same resolver and
296    /// catalogue layering as boot: workspace-authored schemas over
297    /// built-ins), then a per-mem entity load. Success removes the
298    /// roster entry and the mem serves again in the same process;
299    /// any failure keeps (re-)quarantining with the fresh typed
300    /// reason, so the roster never goes stale against the live state.
301    fn reattach_quarantined_mem(
302        &mut self,
303        mem: &str,
304    ) -> Result<crate::ops::ReloadResult, EngineError> {
305        let Some(q_idx) = self.quarantined.iter().position(|q| q.mount.mem == mem) else {
306            return Err(self.unknown_mem_error(mem));
307        };
308        // A mem that comes back into service is new to every caller.
309        self.callers.forget_mem(mem);
310        // The roster may have changed this mount's capability since it
311        // was quarantined, and no reconciliation need have run in
312        // between: the row on disk decides, so the attach never restores
313        // an access the roster withdrew.
314        if let Some(capability) = self.roster_capability_on_disk(mem) {
315            self.quarantined[q_idx].mount.capability = capability;
316        }
317        let mount = self.quarantined[q_idx].mount.clone();
318
319        let requarantine = |this: &mut Self, e: &EngineError| {
320            this.quarantined[q_idx].reason_code = e.code().to_string();
321            this.quarantined[q_idx].reason_message = e.to_string();
322        };
323
324        let backend = match self.instantiate_backend(&mount) {
325            Ok(b) => b,
326            Err(e) => {
327                let err = EngineError::Mem(e.to_string());
328                requarantine(self, &err);
329                return Err(self.unknown_mem_error(mem));
330            }
331        };
332
333        // Same config / pin-authority reads as the boot loop.
334        let last_known_head = backend.current_head().ok().flatten();
335        let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
336            let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
337            memstead_schema::config::parse_mem_config(&value).ok()
338        });
339        let archive_provenance = backend
340            .read_archive_provenance()
341            .ok()
342            .flatten()
343            .and_then(|bytes| memstead_schema::ArchiveProvenance::from_archive_bytes(&bytes).ok());
344        let archive_checks = backend
345            .read_archive_checks()
346            .ok()
347            .flatten()
348            .and_then(|bytes| crate::check::SealedChecks::from_archive_bytes(&bytes).ok());
349        let config_pin = mem_config.as_ref().and_then(|c| c.schema.clone());
350        let effective_pin = mount
351            .migration_target
352            .clone()
353            .or(config_pin)
354            .or(mount.schema.clone());
355        let Some(effective_pin) = effective_pin else {
356            let err = EngineError::MemConfigIncomplete {
357                mem: mem.to_string(),
358                missing_fields: vec!["schema".to_string()],
359            };
360            requarantine(self, &err);
361            return Err(self.unknown_mem_error(mem));
362        };
363        // Same catalogue order as boot: workspace tier, then the mount's
364        // own embedded vocabulary when it is archive-backed, then the
365        // built-ins.
366        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
367            .workspace_schemas
368            .iter()
369            .cloned()
370            .chain(crate::engine::boot::embedded_archive_schemas(&mount))
371            .chain(self.builtin_schemas.iter().cloned())
372            .collect();
373        let schema = match crate::engine::SchemaResolver::new(&catalogue).resolve(&effective_pin) {
374            Ok(s) => s,
375            Err(sources) => {
376                let err = EngineError::SchemaNotFound {
377                    mem: mem.to_string(),
378                    pin: effective_pin.as_display(),
379                    sources,
380                    install_hint: None,
381                }
382                .with_schema_install_probe(self.workspace_root());
383                requarantine(self, &err);
384                return Err(self.unknown_mem_error(mem));
385            }
386        };
387
388        // Attach, then load entities through the ordinary per-mem
389        // reload. An entity-load failure re-quarantines (the mount is
390        // detached again) — quarantine is not tolerance.
391        self.quarantined.remove(q_idx);
392        self.schemas_insert(mem.to_string(), schema);
393        self.mounts.push(crate::engine::MountedBackend {
394            mount,
395            backend: backend.into(),
396            last_known_head,
397            mem_config,
398            archive_provenance,
399            archive_checks,
400            // The reattach loads entities immediately below — a
401            // quarantine return-to-service is never deferred.
402            deferred: false,
403            reload_failure: None,
404            strays: Default::default(),
405        });
406        self.mem_router = std::sync::Arc::new(crate::engine::boot::build_mem_router_from_mounts(
407            &self.mounts,
408        ));
409        let mut sink: Vec<WarningHint> = Vec::new();
410        match self.reload_one_mem_inner(mem, &mut sink) {
411            Ok(result) => {
412                self.load_warnings.retain(|w| w.source_mem() != Some(mem));
413                self.load_warnings
414                    .extend(sink.into_iter().filter(|w| w.source_mem() == Some(mem)));
415                self.invalidate_communities();
416                Ok(result)
417            }
418            Err(e) => {
419                let mount_idx = self.mounts.len() - 1;
420                let mounted = self.mounts.remove(mount_idx);
421                self.schemas_remove(mem);
422                self.mem_router = std::sync::Arc::new(
423                    crate::engine::boot::build_mem_router_from_mounts(&self.mounts),
424                );
425                self.quarantined.push(crate::engine::QuarantinedMem {
426                    mount: mounted.mount,
427                    reason_code: e.code().to_string(),
428                    reason_message: e.to_string(),
429                });
430                // Same epoch-moved staleness as the deferred-load
431                // quarantine branch: `schemas_remove` bumped the
432                // epoch, so both memos must clear.
433                self.invalidate_communities();
434                self.invalidate_search_indexes();
435                Err(e)
436            }
437        }
438    }
439
440    /// Inner per-mem body shared by [`Self::reload_one_mem`]
441    /// and [`Self::reload_each_writable_mem`]. The caller passes
442    /// a warning sink so the workspace-wide reload can forward
443    /// warnings into `self.load_warnings` while the single-mem
444    /// path keeps the accumulator pristine.
445    fn reload_one_mem_inner(
446        &mut self,
447        mem: &str,
448        warnings_sink: &mut Vec<WarningHint>,
449    ) -> Result<crate::ops::ReloadResult, EngineError> {
450        // Locate the target mount + schema. Unknown mem short-
451        // circuits before any store mutation.
452        let mount_idx = self
453            .mounts
454            .iter()
455            .position(|m| m.mount.mem == mem)
456            .ok_or_else(|| self.unknown_mem_error(mem))?;
457        let schema = self
458            .schemas
459            .get(mem)
460            .cloned()
461            .ok_or_else(|| self.unknown_mem_error(mem))?;
462
463        // Snapshot pre-reload (id, content_hash) for this mem.
464        let pre: HashMap<EntityId, String> = self
465            .store
466            .all_entities()
467            .filter(|e| !e.stub && e.mem == mem)
468            .map(|e| (e.id.clone(), e.content_hash.clone()))
469            .collect();
470        let pre_ids: std::collections::HashSet<EntityId> = pre.keys().cloned().collect();
471
472        // Walk the backend; surface read-time errors instead of
473        // mutating the store on a failed reload.
474        // A backend that still holds the staged writes of a failed
475        // mutation would serve them to this load as content.
476        self.discard_strays(mem).map_err(|e| {
477            EngineError::Mem(format!(
478                "reload of mem `{mem}` refused: writes a failed mutation left staged could not \
479                 be discarded: {e}"
480            ))
481        })?;
482        let mut completed_commit = None;
483        let read = collect_source_entries(
484            mem,
485            self.mounts[mount_idx].backend.as_ref(),
486            &mut completed_commit,
487        );
488        // Reported on the next response whatever becomes of this reload.
489        self.completed_commits.extend(completed_commit.clone());
490        let read = read?;
491        // A reload replaces a whole view with what it reads. A file that
492        // could not be read would leave its entity out of the new view
493        // with nothing to show for it, and a write of that id would then
494        // land over the file. The view in place is behind and whole;
495        // keep it and report the reload as failed.
496        if let Some(reason) = read.incomplete() {
497            return Err(EngineError::Mem(format!(
498                "reload of mem `{mem}` is incomplete: {reason}"
499            )));
500        }
501        // Everything was read: the view this reload builds is level
502        // with storage, whoever asked for it.
503        self.mounts[mount_idx].reload_failure = None;
504        let backend = self.mounts[mount_idx].backend.as_ref();
505        let (entries, read_errors) = (read.entries, read.read_errors);
506        // The unbacked-mount probe rides the reload like the other
507        // load-time warnings: a branch that appeared (or vanished) since
508        // boot changes the answer, and the sink's per-mem replace below
509        // drops the boot-time one.
510        let unbacked =
511            crate::engine::boot::unbacked_mount_warning(&self.mounts[mount_idx].mount, backend);
512        let load_result = parse_entries(entries, read_errors, mem, schema.as_ref());
513
514        // Build the LoadCollector inputs — mem roster + last-
515        // segment suffixes — so the parser pipeline can emit
516        // typed drift warnings into the caller's sink.
517        let mem_names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
518        let known_suffixes: Vec<String> = mem_names
519            .iter()
520            .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
521            .collect();
522
523        // Failure fence above; below this point the store is mutated.
524        let prior_targets = self.targets_of_mem(mem);
525        self.store.remove_entities_by_mem(mem);
526        warnings_sink.extend(completed_commit);
527        if let Some(w) = unbacked {
528            warnings_sink.push(w);
529        }
530        let fallback = engine_fallback_type();
531        push_entities_into_store(
532            &mut self.store,
533            load_result.entities,
534            fallback.as_ref(),
535            Some(crate::entity::store_builder::LoadCollector {
536                warnings: warnings_sink,
537                known_suffixes: &known_suffixes,
538                mem_names: &mem_names,
539            }),
540        );
541        // Re-run parse-time relation validation across the workspace.
542        // A reload re-parses one mem but the validator's cycle pass
543        // is global (acyclic-rel-type subgraphs span mems), so the
544        // scan runs against the whole store. Hand-edits arriving via
545        // sibling-writer commits get the same gauntlet boot enforces
546        // (grammar / unknown_rel_type / shape / cycle).
547        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
548            .mounts
549            .iter()
550            .map(|m| (m.mount.mem.clone(), m.mount.capability))
551            .collect();
552        // Restore cross-mem edges that point INTO this mem. The
553        // removal cascade above dropped their incoming mirrors and the
554        // re-push only rebuilt edges authored by this mem's own
555        // entities, so a cross-mem `A→B` would silently vanish from the
556        // index until a workspace-wide reload. Reconstruct from the
557        // authoritative source records (in-memory only — no other mem is
558        // re-read), then let the remap pass below reclassify alias sources.
559        // Stubs the re-read left without a referrer go too.
560        self.settle_slice(mem, &prior_targets);
561        crate::entity::store_builder::validate_loaded_relations(
562            &mut self.store,
563            &self.schemas,
564            &mount_caps,
565            warnings_sink,
566        );
567        crate::entity::store_builder::remap_alias_target_edge_sources(
568            &mut self.store,
569            &self.schemas,
570        );
571        // Surface load errors back through the engine's accumulator
572        // so subsequent `load_errors()` calls reflect the latest read.
573        // THIS mem's stale entries are replaced, not accumulated — a
574        // repaired file (e.g. a resolved merge conflict) must stop
575        // reporting its old refusal, and a re-read of a still-broken
576        // file must not duplicate its entry. Other mems' entries are
577        // untouched (their reloads own them). Folder mounts key their
578        // entries by absolute source path under the mem root; other
579        // backends have no path-attributable entries to replace.
580        if let crate::workspace::MountStorage::Folder { path } =
581            &self.mounts[mount_idx].mount.storage
582        {
583            let root = path.clone();
584            self.load_errors.retain(|(p, _)| !p.starts_with(&root));
585            // The backend walk yields mem-relative paths while the boot
586            // loader yields absolute ones — normalize to absolute so the
587            // replace-on-reload key stays uniform across both origins.
588            self.load_errors
589                .extend(load_result.errors.into_iter().map(|(p, m)| {
590                    let abs = if p.is_relative() { root.join(&p) } else { p };
591                    (abs, m)
592                }));
593        } else {
594            self.load_errors.extend(load_result.errors);
595        }
596
597        // Refresh the mem's config from the backend too. `sync_state`
598        // (the projection baselines) and the schema pin / write guidance are
599        // mem-scoped state that rides the mem branch, so an out-of-band write
600        // — a sibling `projection advance` / `mem set-sync-state` — must become
601        // visible after a per-mem reload, not only entity changes. A missing or
602        // unparseable config leaves the cached value untouched (best-effort:
603        // the reload never fails on a config read hiccup).
604        if let Ok(Some(bytes)) = self.mounts[mount_idx].backend.read_mem_config()
605            && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
606            && let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
607        {
608            self.mounts[mount_idx].mem_config = Some(cfg);
609        }
610
611        // Diff post-reload against the snapshot.
612        let mut added: Vec<EntityId> = Vec::new();
613        let mut changed: Vec<EntityId> = Vec::new();
614        for entity in self.store.all_entities() {
615            if entity.stub || entity.mem != mem {
616                continue;
617            }
618            match pre.get(&entity.id) {
619                None => added.push(entity.id.clone()),
620                Some(prev_hash) if prev_hash != &entity.content_hash => {
621                    changed.push(entity.id.clone());
622                }
623                Some(_) => {}
624            }
625        }
626        let post_ids: std::collections::HashSet<EntityId> = self
627            .store
628            .all_entities()
629            .filter(|e| !e.stub && e.mem == mem)
630            .map(|e| e.id.clone())
631            .collect();
632        let mut removed: Vec<EntityId> = pre_ids.difference(&post_ids).cloned().collect();
633        added.sort_by(|a, b| a.0.cmp(&b.0));
634        changed.sort_by(|a, b| a.0.cmp(&b.0));
635        removed.sort_by(|a, b| a.0.cmp(&b.0));
636
637        self.invalidate_communities();
638        self.invalidate_search_indexes();
639
640        Ok(crate::ops::ReloadResult {
641            added,
642            changed,
643            removed,
644        })
645    }
646
647    /// Rich-shape variant of [`Self::reload_one_mem`] that returns a
648    /// [`crate::ops::ReloadReport`] (mem + head_before + head_after +
649    /// entities_loaded + changed_entity_ids) instead of the slim
650    /// [`crate::ops::ReloadResult`]. Handler-facing wrapper consumed
651    /// by the `memstead_reload` MCP tool — the rich shape is the wire
652    /// contract MCP callers depend on; the slim form stays for
653    /// programmatic consumers that just want the diff lists.
654    ///
655    /// `head_before` is the engine's **prior cursor** for this mem
656    /// (its cached `last_known_head`), *not* the current on-disk tip:
657    /// when a sibling has committed since, the tip has already advanced,
658    /// so reporting it would make the advertised
659    /// `changes_since(since=head_before)` recipe span an empty range.
660    /// `head_after` is the freshly-peeled tip from
661    /// [`crate::backend::MemBackend::current_head`]; the reload also
662    /// advances the cursor to it, so a follow-up staleness probe does
663    /// not re-reload the same window. Backends without history (folder,
664    /// archive) carry no cursor and return `Ok(None)`; both fields fall
665    /// back to [`crate::ops::EMPTY_TREE_SHA`] for wire-shape stability.
666    ///
667    /// `entities_loaded` is the post-reload non-stub count for the
668    /// mem — same semantic as full's report.
669    ///
670    /// `changed_entity_ids` is the union of `added ∪ changed ∪
671    /// removed` from the underlying [`crate::ops::ReloadResult`]
672    /// so callers don't have to merge three lists themselves —
673    /// matches full's bundled wire shape.
674    pub fn reload_one_mem_report(
675        &mut self,
676        mem: &str,
677    ) -> Result<crate::ops::ReloadReport, EngineError> {
678        // Before anything is reloaded: what other callers wrote through
679        // this engine is news to the caller and no part of the report,
680        // which covers what the reload itself brings in.
681        self.bring_caller_up_to_date();
682        // `head_before` is the engine's PRIOR cursor — the SHA it last
683        // knew for this mem — not the current (possibly already
684        // drifted) on-disk tip. Reporting the tip would collapse the
685        // `changes_since(since=head_before)` range to empty in exactly
686        // the sibling-drift case the recipe targets. `current_head` is
687        // backend-defined: git-branch serves a git cursor, the folder
688        // backend serves its change-ledger watermark, and a backend
689        // without a head signal returns None — for those, `head_before`
690        // stays the empty-tree sentinel that pairs with the
691        // equally-empty `head_after` below.
692        let tracks_head = self
693            .mounts
694            .iter()
695            .find(|m| m.mount.mem == mem)
696            .and_then(|m| m.backend.current_head().ok().flatten())
697            .is_some();
698        let head_before = if tracks_head {
699            self.mounts
700                .iter()
701                .find(|m| m.mount.mem == mem)
702                .and_then(|m| m.last_known_head.clone())
703                .unwrap_or_else(|| crate::ops::EMPTY_TREE_SHA.to_string())
704        } else {
705            crate::ops::EMPTY_TREE_SHA.to_string()
706        };
707
708        let result = self.reload_one_mem(mem)?;
709
710        // Capture head_after = the freshly-peeled tip, and advance the
711        // engine's cursor to it. Without this advance the next
712        // operation's `reload_if_stale` would compare the stale cursor
713        // against the same tip and re-reload the identical window,
714        // re-emitting a spurious `MEM_RELOADED`. Only history-backed
715        // mounts (current_head → Some) carry a cursor to advance.
716        let head_after_raw = self
717            .mounts
718            .iter()
719            .find(|m| m.mount.mem == mem)
720            .and_then(|m| m.backend.current_head().ok().flatten());
721        if let Some(new_head) = head_after_raw.clone()
722            && let Some(m) = self.mounts.iter_mut().find(|m| m.mount.mem == mem)
723        {
724            let before = m
725                .last_known_head
726                .replace(new_head.clone())
727                .unwrap_or_default();
728            // The caller asked for this reload and reads what it brought
729            // in from the report: it has seen the new head. A caller that
730            // was behind the engine before the reload stays behind and is
731            // told on its next operation.
732            self.caller_saw_own_write(mem, &before, &new_head);
733        }
734        let head_after = head_after_raw.unwrap_or_else(|| crate::ops::EMPTY_TREE_SHA.to_string());
735
736        let entities_loaded = self
737            .store
738            .all_entities()
739            .filter(|e| !e.stub && e.mem == mem)
740            .count();
741
742        // Union of added + changed + removed, sorted lexicographically
743        // for deterministic wire output. Matches full's "single
744        // changed_entity_ids list" contract — saves callers from
745        // merging three slices themselves.
746        let mut changed_entity_ids: Vec<EntityId> = result
747            .added
748            .into_iter()
749            .chain(result.changed)
750            .chain(result.removed)
751            .collect();
752        changed_entity_ids.sort_by(|a, b| a.0.cmp(&b.0));
753
754        Ok(crate::ops::ReloadReport {
755            mem: mem.to_string(),
756            head_before,
757            head_after,
758            entities_loaded,
759            changed_entity_ids,
760        })
761    }
762
763    /// Batched rich-shape variant — returns one
764    /// [`crate::ops::ReloadReport`] per mounted mem in declaration
765    /// order. Counterpart to [`Self::reload_each_writable_mem`]
766    /// (slim) that the `memstead_reload` MCP tool's no-mem path
767    /// consumes.
768    ///
769    /// `load_warnings` semantics ride on the per-mem contract: each
770    /// [`Self::reload_one_mem`] in the sweep refreshes its own mem's
771    /// slice of the engine-wide accumulator, so a full sweep leaves
772    /// the accumulator equivalent to a fresh boot. (Earlier this
773    /// variant discarded every reload warning while its slim
774    /// counterpart repopulated — the MCP workspace-wide reload could
775    /// never clear a stale warning.) On first-error-abort, mems
776    /// reloaded before the failure carry refreshed slices and the
777    /// rest keep their boot-time entries — no slice is lost.
778    ///
779    /// Also re-reads `.memstead/workspace.toml` and refreshes
780    /// [`crate::workspace::WorkspaceSettings`] before sweeping the
781    /// mems — this is the pairing with the CLI's
782    /// `memstead workspace allow-create / grant-cross-link / set-mutations`
783    /// family. Without this re-read, a CLI write would land on disk but
784    /// the running MCP would still serve the engine's boot-time policy
785    /// snapshot; every subsequent `memstead_mem_create` against the new
786    /// allowlist would fail with `MEM_PATH_NOT_ALLOWED` until process
787    /// restart. The workspace-wide form runs the heavier path; the
788    /// per-mem form (`reload_one_mem_report`) intentionally skips
789    /// the workspace re-read — content drift doesn't imply policy
790    /// drift.
791    ///
792    /// Reload of `workspace.toml` is best-effort: a missing or
793    /// unparseable file leaves the existing settings untouched. The
794    /// per-mem sweep is the primary contract — settings refresh is
795    /// the additive bonus.
796    ///
797    /// First-error-aborts: if any mem's reload fails, the loop
798    /// stops and the error propagates. Mems reloaded before the
799    /// failing one are already mutated in the store; the returned
800    /// error has no rollback. Operators run the per-mem form to
801    /// retry the failing mem explicitly.
802    pub fn reload_each_writable_mem_reports(
803        &mut self,
804    ) -> Result<Vec<crate::ops::ReloadReport>, EngineError> {
805        self.refresh_workspace_settings_if_possible();
806        let names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
807        let mut out = Vec::with_capacity(names.len());
808        for name in names {
809            let report = self.reload_one_mem_report(&name)?;
810            out.push(report);
811        }
812        Ok(out)
813    }
814
815    /// Best-effort refresh of [`crate::workspace::WorkspaceSettings`]
816    /// from the workspace's `.memstead/workspace.toml`. Called by the
817    /// workspace-wide reload sweep so CLI-driven policy edits become
818    /// visible to a live engine without process restart.
819    ///
820    /// Silent no-op when the engine has no `workspace_root` (legacy
821    /// in-memory constructions) or when the on-disk file is missing /
822    /// unparseable. The per-mem reload contract stays the canonical
823    /// failure surface; settings refresh failures are intentionally
824    /// non-fatal so a malformed workspace.toml doesn't break content
825    /// drift detection.
826    pub(crate) fn refresh_workspace_settings_if_possible(&mut self) {
827        let Some(root) = self.workspace_root.clone() else {
828            return;
829        };
830        let store = crate::workspace_store::FileWorkspaceStore::new();
831        let workspace = match crate::workspace_store::WorkspaceStoreAdapter::load(&store, &root) {
832            Ok(w) => w,
833            Err(_) => return,
834        };
835        self.set_settings(workspace.settings);
836    }
837
838    /// Reload every mounted mem in declaration order; returns one
839    /// `(mem, ReloadResult)` per mount.
840    ///
841    /// Failure model is **first-error-aborts**: if any mem's reload
842    /// fails, the loop stops and the error propagates. Mems reloaded
843    /// before the failing one are already mutated in the store; the
844    /// returned error has no rollback. Operators run the per-mem
845    /// form to retry the failing mem explicitly.
846    ///
847    /// Caller-friendly batching wrapper around [`Self::reload_one_mem`];
848    /// internal cache invalidation happens once per mem (the inner
849    /// call invalidates) so an N-mem batch invalidates the memos
850    /// N times. That's wasteful for large workspaces; once the
851    /// `memstead_reload` MCP handler migrates we can tighten this to one
852    /// invalidation at the end.
853    pub fn reload_each_writable_mem(
854        &mut self,
855    ) -> Result<Vec<(String, crate::ops::ReloadResult)>, EngineError> {
856        let names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
857        // Workspace-wide reload semantics: take the engine-wide
858        // sink, clear it, route per-mem inner reloads through it,
859        // put it back. The result is `self.load_warnings` carries
860        // every typed drift warning the reload sweep produced (so
861        // the next `engine.health()` call surfaces them).
862        let mut sink = std::mem::take(&mut self.load_warnings);
863        sink.clear();
864        let mut out = Vec::with_capacity(names.len());
865        let mut loop_err = None;
866        for name in names {
867            match self.reload_one_mem_inner(&name, &mut sink) {
868                Ok(result) => out.push((name, result)),
869                Err(e) => {
870                    loop_err = Some(e);
871                    break;
872                }
873            }
874        }
875        self.load_warnings = sink;
876        if let Some(e) = loop_err {
877            return Err(e);
878        }
879        Ok(out)
880    }
881}
882
883/// Value-level schema-pin bump on a backend's mem config: read the
884/// config blob, rewrite ONLY the `"schema"` string, write it back —
885/// every other field (`readMems`, write guidance, sync state, …) is
886/// preserved verbatim. Config-absent backends (no `config.json`) are a
887/// clean no-op returning `None`; the caller's `Mount.schema` then
888/// stays the settled pin. Returns the updated JSON value on a write so
889/// callers can refresh caches.
890///
891/// One shared implementation for the booted path
892/// (`Engine::persist_mem_schema_pin`) and the below-boot repair path
893/// (memstead-git-branch) — the two must never fork: a pin written by
894/// repair must be byte-shaped exactly as one written by the engine.
895/// Field names on which the stored config differs from `cached`.
896///
897/// Compared as JSON so the comparison covers every field the struct models
898/// without a hand-written field list that a new field would silently escape.
899/// A parse failure yields no fields rather than a false report: the write
900/// itself will surface the malformed config.
901pub(super) fn changed_config_fields(
902    cached: &memstead_schema::config::MemConfig,
903    stored_bytes: &[u8],
904) -> Vec<String> {
905    let (Ok(a), Ok(b)) = (
906        serde_json::to_value(cached),
907        serde_json::from_slice::<serde_json::Value>(stored_bytes),
908    ) else {
909        return Vec::new();
910    };
911    let (Some(a), Some(b)) = (a.as_object(), b.as_object()) else {
912        return Vec::new();
913    };
914    let mut keys: std::collections::BTreeSet<&String> = a.keys().collect();
915    keys.extend(b.keys());
916    keys.into_iter()
917        .filter(|k| a.get(*k) != b.get(*k))
918        .map(|k| k.to_string())
919        .collect()
920}