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