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