memstead_base/engine/lifecycle/mounts.rs
1//! Mount registration: registering and unregistering writable mems and read mounts, the load-warning channel, the full refresh and the state persist.
2
3use super::*;
4
5impl Engine {
6 /// Unregister a writable mem at runtime. Engine-level
7 /// primitive that `memstead_mem_delete` builds on.
8 ///
9 /// Removes the named mount from [`Self::mounts`], drops the
10 /// mem's entities from the store, refreshes the
11 /// [`MemRouterSnapshot`] via `Arc::make_mut` (COW swap so
12 /// readers holding a pre-swap snapshot see the pre-state for
13 /// their lifetime), and invalidates the community + search
14 /// memos. Does NOT touch the backend's on-disk state — the
15 /// caller (`delete_mem` orchestrator) decides whether to
16 /// remove the directory / gitdir after this returns.
17 ///
18 /// Returns `Ok(Some(backend))` when the mem was present and
19 /// unregistered — the caller can drive any backend-specific
20 /// follow-up cleanup (`backend.delete_artifacts()` for the
21 /// mem-repo branch + `__MEMSTEAD` config when `delete_files=true`).
22 /// Returns `Ok(None)` when no mount named the mem (idempotent —
23 /// repeated calls are safe).
24 pub fn unregister_writable_mem(
25 &mut self,
26 mem_name: &str,
27 ) -> Result<Option<Box<dyn MemBackend>>, EngineError> {
28 let pos = self.mounts.iter().position(|m| m.mount.mem == mem_name);
29 let Some(idx) = pos else {
30 return Ok(None);
31 };
32
33 // Drop the mount first — releases all engine-side state that
34 // referenced the backend. The `Box<dyn MemBackend>` itself
35 // travels back to the caller so backend-side cleanup
36 // (`delete_artifacts`) can run after the engine snapshot
37 // settled.
38 let mount = self.mounts.remove(idx);
39
40 // Drop the schema entry for this mem (kept in lockstep
41 // with `self.mounts`).
42 self.schemas_remove(&mount.mount.mem);
43
44 // Drop entities. The store's mem index is the
45 // authoritative count; the return value (number of
46 // entities removed) is informational only — the caller
47 // already knows the mem and doesn't need the count.
48 let _removed = self.store.remove_entities_by_mem(mem_name);
49
50 // Purge load-time warnings attributed to the removed mem.
51 // `health()` merges `self.load_warnings` unconditionally, so
52 // a skipped purge leaves phantom warnings citing entities the
53 // store no longer holds — for the whole engine lifetime, since
54 // nothing else clears the accumulator on the MCP path.
55 // Attribution is by SOURCE mem only (`WarningHint::source_mem`):
56 // a warning whose source entity lives in a surviving mem stays
57 // even when its target pointed into the deleted mem — the
58 // invalid row still exists in that survivor's markdown and
59 // remains visible drift (recover-worthy), not stale state.
60 self.load_warnings
61 .retain(|w| w.source_mem() != Some(mem_name));
62
63 // COW snapshot swap on the mem_router. `Arc::make_mut`
64 // clones the inner snapshot when other Arcs exist; if this
65 // is the only handle (typical for the engine's lifetime),
66 // it returns the existing inner directly without cloning.
67 // Readers that captured an `Arc` before this call observe
68 // the pre-swap state — the in-flight handler's
69 // `mem_router()` borrow is unaffected by this mutation.
70 Arc::make_mut(&mut self.mem_router).remove_writable(mem_name);
71
72 // Invalidate dependent memos — community detection + search
73 // indexes were computed over the pre-removal store and are
74 // now stale. Mutation paths already invalidate; this
75 // matches the contract.
76 self.invalidate_communities();
77 self.invalidate_search_indexes();
78
79 Ok(Some(mount.backend))
80 }
81
82 /// Register a read-only mount at runtime — the install path's
83 /// engine primitive. Same registration pipeline as
84 /// [`Self::register_writable_mem`] (collision probe, config read,
85 /// schema resolution, entity load, router swap); the router branch
86 /// lands the mount in the read-only slot for
87 /// `capability: ReadOnly` + `Archive` storage, so `is_writable`
88 /// stays false and `archive_path_for_mem` resolves.
89 pub fn register_read_mount(
90 &mut self,
91 mount: Mount,
92 backend: Box<dyn MemBackend>,
93 origin: MemOrigin,
94 ) -> Result<(), EngineError> {
95 self.register_writable_mem_inner(mount, backend, origin, true)
96 }
97
98 /// Unregister a read-only mount at runtime — the uninstall path's
99 /// engine primitive, mirroring [`Self::unregister_writable_mem`]
100 /// for the read-only slot. Returns `Ok(None)` when the name is
101 /// not a registered read-only mount (writable mems are the
102 /// delete/unregister verbs' business, deliberately not this
103 /// one's). Registration removal only — the backing archive file
104 /// (global cache) is never touched.
105 pub fn unregister_read_mount(
106 &mut self,
107 mem_name: &str,
108 ) -> Result<Option<Box<dyn MemBackend>>, EngineError> {
109 let pos = self.mounts.iter().position(|m| {
110 m.mount.mem == mem_name
111 && m.mount.capability == crate::workspace::MountCapability::ReadOnly
112 });
113 let Some(idx) = pos else {
114 // A read-only mount held in quarantine (an installed archive
115 // this machine's cache lacks, say) is unregistered too: it
116 // has no backend to hand back, but leaving its roster entry
117 // would let the next state write resurrect it.
118 // A mount quarantined at boot is absent from the merge
119 // baseline (so a state write never drops it by accident);
120 // removing it on purpose enters it there, so the merge
121 // reads the removal as ours.
122 if let Some(q) = self.quarantined.iter().find(|q| {
123 q.mount.mem == mem_name
124 && q.mount.capability == crate::workspace::MountCapability::ReadOnly
125 }) {
126 let mut baseline = self.mounts_baseline.borrow_mut();
127 if !baseline.iter().any(|m| m.mem == mem_name) {
128 baseline.push(q.mount.clone());
129 }
130 }
131 self.quarantined.retain(|q| {
132 !(q.mount.mem == mem_name
133 && q.mount.capability == crate::workspace::MountCapability::ReadOnly)
134 });
135 return Ok(None);
136 };
137 let mount = self.mounts.remove(idx);
138 self.schemas_remove(&mount.mount.mem);
139 let _removed = self.store.remove_entities_by_mem(mem_name);
140 self.load_warnings
141 .retain(|w| w.source_mem() != Some(mem_name));
142 Arc::make_mut(&mut self.mem_router).remove_read_only(mem_name);
143 self.invalidate_communities();
144 self.invalidate_search_indexes();
145 Ok(Some(mount.backend))
146 }
147
148 /// Append a typed load-time warning from outside the engine's own
149 /// load pipeline — the boot orchestrators (which live in the full
150 /// crate) use this to surface one-time migrations they perform
151 /// around engine construction.
152 pub fn push_load_warning(&mut self, warning: crate::ops::WarningHint) {
153 self.load_warnings.push(warning);
154 }
155
156 /// Register a writable mem at runtime. Engine-level primitive
157 /// that `memstead_mem_create` builds on.
158 ///
159 /// Steps:
160 /// 1. Name collision probe against the current `mem_router`
161 /// snapshot. Writable AND read-only entries collide; the
162 /// error surfaces the colliding source so the orchestrator
163 /// can render a recovery hint.
164 /// 2. Schema resolution via the built-in catalogue (mirrors
165 /// [`Self::from_mounts`]; workspace-authored schema
166 /// resolution lifts later).
167 /// 3. Per-mem config load (folder backends only; git-branch /
168 /// archive return None — same contract as
169 /// [`Self::from_mounts`]).
170 /// 4. Entity load via the backend, parse, push into the engine's
171 /// store with a `LoadCollector` so drift warnings forward to
172 /// `self.load_warnings`.
173 /// 5. Insert schema into [`Self::schemas`].
174 /// 6. Push the [`MountedBackend`] into [`Self::mounts`].
175 /// 7. COW snapshot swap on [`Self::mem_router`] via
176 /// `Arc::make_mut` + `add_writable(name, dir, origin, mem_path)`.
177 /// Folder mounts surface their on-disk path; other backends
178 /// register with `dir: None` (matches full's contract).
179 /// `mem_path` carries the create-time organisational `path`
180 /// component (mirrors `MemCreateParams.path`) — the
181 /// delete-side lifecycle composer reads it back to rebuild the
182 /// `<mem_path>/<name>` candidate the create-side composer
183 /// matched against. Caller threads `None` for flat-layout
184 /// registrations and `Some(p)` for hierarchical ones.
185 /// 8. Invalidate community + search memos.
186 ///
187 /// Returns `Err(EngineError::MemNameCollision)` when the name
188 /// is already registered. Other failures (schema-not-found,
189 /// backend read errors) propagate as their typed variants. On
190 /// failure no engine mutation happens: every potentially-
191 /// mutating step runs only after the collision probe succeeds,
192 /// and intermediate failures propagate before the mount /
193 /// router are touched.
194 pub fn register_writable_mem(
195 &mut self,
196 mount: Mount,
197 backend: Box<dyn MemBackend>,
198 origin: MemOrigin,
199 ) -> Result<(), EngineError> {
200 self.register_writable_mem_inner(mount, backend, origin, true)
201 }
202
203 /// [`Self::register_writable_mem`] with the workspace-global
204 /// passes (relation validation, alias remap, memo invalidation)
205 /// made optional: `run_global_passes: false` lets a batch caller
206 /// ([`Self::full_refresh`]) attach N mounts and run the global
207 /// passes ONCE afterwards instead of N times under the engine
208 /// lock. A `false` caller MUST run
209 /// [`Self::finish_batched_registrations`] after its loop, or
210 /// loaded relations skip validation and alias edges stay
211 /// unmapped.
212 fn register_writable_mem_inner(
213 &mut self,
214 mount: Mount,
215 backend: Box<dyn MemBackend>,
216 origin: MemOrigin,
217 run_global_passes: bool,
218 ) -> Result<(), EngineError> {
219 // Step 1: name collision probe.
220 if let Some(existing) = self.mem_router.origin_for_mem(&mount.mem) {
221 return Err(EngineError::MemNameCollision {
222 name: mount.mem.clone(),
223 source_origin: existing.render_source(),
224 });
225 }
226 if self.mem_router.archive_path_for_mem(&mount.mem).is_some() {
227 return Err(EngineError::MemNameCollision {
228 name: mount.mem.clone(),
229 source_origin: "attached read mem".to_string(),
230 });
231 }
232
233 // Step 2: per-mem config load via the backend trait. Read
234 // before resolving the schema — the mem's own config carries
235 // the authoritative pin (mirrors the boot path), so a mem
236 // re-registered or mounted from another machine resolves from
237 // its own backend, not this workspace's mount expectation.
238 let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
239 let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
240 memstead_schema::config::parse_mem_config(&value).ok()
241 });
242
243 // Step 3: schema resolution. `MemConfig.schema` is the
244 // authoritative settled pin; `Mount.schema` is the fallback when
245 // the config carries none, and an expectation assertion when it
246 // does — a disagreement surfaces `SchemaPinMismatch` (config
247 // wins, neither silently dropped). Mirrors `from_mounts_inner`.
248 // Resolve against the engine's full loaded catalogue (already-
249 // loaded workspace/local-storage schemas layered over built-ins)
250 // so a mem registered against a backend-installed (e.g.
251 // git-branch `__MEMSTEAD:schemas/` ref) schema resolves.
252 let mut builtin_schemas: Vec<std::sync::Arc<memstead_schema::Schema>> =
253 self.workspace_schemas().to_vec();
254 // An archive-backed mount's own sealed vocabulary sits between
255 // the workspace tier and the built-ins, for this resolution
256 // only — see `from_mounts_inner` for why it never joins the
257 // shared catalogue.
258 builtin_schemas.extend(crate::engine::boot::embedded_archive_schemas(&mount));
259 builtin_schemas.extend(
260 memstead_schema::builtins::load_builtin_schemas()
261 .map_err(|e| EngineError::SchemaResolverInit(e.to_string()))?,
262 );
263 let config_pin = mem_config.as_ref().and_then(|c| c.schema.as_ref());
264 let mount_pin = mount.schema.as_ref();
265 if let (Some(cfg), Some(mp)) = (config_pin, mount_pin)
266 && cfg != mp
267 {
268 self.load_warnings
269 .push(crate::ops::WarningHint::SchemaPinMismatch {
270 mem: mount.mem.clone(),
271 config_pin: cfg.as_display(),
272 mount_pin: mp.as_display(),
273 });
274 }
275 let settled_pin = config_pin.or(mount_pin);
276 let effective_pin = mount
277 .migration_target
278 .as_ref()
279 .or(settled_pin)
280 .ok_or_else(|| EngineError::MemConfigIncomplete {
281 mem: mount.mem.clone(),
282 missing_fields: vec!["schema".to_string()],
283 })?
284 .clone();
285 let schema = crate::engine::SchemaResolver::new(&builtin_schemas)
286 .resolve(&effective_pin)
287 .map_err(|sources| {
288 EngineError::SchemaNotFound {
289 mem: mount.mem.clone(),
290 pin: effective_pin.as_display(),
291 sources,
292 install_hint: None,
293 }
294 .with_schema_install_probe(self.workspace_root())
295 })?;
296
297 // Step 4: load entities via the backend, push into the
298 // engine's store with a LoadCollector so drift warnings
299 // forward into `self.load_warnings`. Derive the mem
300 // roster + last-segment suffixes from the POST-registration
301 // view (new mem included) so cross-mem references
302 // targeting the new mem resolve correctly during this
303 // load.
304 let (entries, read_errors) = collect_source_entries(backend.as_ref())?;
305 if let Some(w) = crate::engine::boot::unbacked_mount_warning(
306 &mount,
307 backend.as_ref(),
308 Some(entries.len()),
309 ) {
310 self.load_warnings.push(w);
311 }
312 let load_result = parse_entries(entries, read_errors, &mount.mem, schema.as_ref());
313
314 let mut mem_names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
315 mem_names.push(mount.mem.clone());
316 let known_suffixes: Vec<String> = mem_names
317 .iter()
318 .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
319 .collect();
320 let fallback = engine_fallback_type();
321 push_entities_into_store(
322 &mut self.store,
323 load_result.entities,
324 fallback.as_ref(),
325 Some(crate::entity::store_builder::LoadCollector {
326 warnings: &mut self.load_warnings,
327 known_suffixes: &known_suffixes,
328 mem_names: &mem_names,
329 }),
330 );
331 self.load_errors.extend(load_result.errors);
332
333 // Step 5: insert schema (kept in lockstep with `self.mounts`).
334 self.schemas_insert(mount.mem.clone(), schema);
335
336 // Re-run the parse-time relation validator now that the new
337 // mem's schema is in `self.schemas`. Mirrors the boot path
338 // (`Engine::from_mounts_inner`) — hand-edited or externally-
339 // generated markdown in the newly-attached mount goes through
340 // the same gauntlet (grammar / unknown_rel_type / shape /
341 // cycle) and offending relations are dropped with typed
342 // `PARSED_RELATION_INVALID` warnings on `self.load_warnings`.
343 // The newly-pushed mount isn't in `self.mounts` yet (that's
344 // Step 6 below), so build the map from `self.mounts` plus the
345 // about-to-be-attached mount we're still holding.
346 if run_global_passes {
347 let mut mount_caps: std::collections::HashMap<
348 String,
349 crate::workspace::MountCapability,
350 > = self
351 .mounts
352 .iter()
353 .map(|m| (m.mount.mem.clone(), m.mount.capability))
354 .collect();
355 mount_caps.insert(mount.mem.clone(), mount.capability);
356 crate::entity::store_builder::validate_loaded_relations(
357 &mut self.store,
358 &self.schemas,
359 &mount_caps,
360 &mut self.load_warnings,
361 );
362 crate::entity::store_builder::remap_alias_target_edge_sources(
363 &mut self.store,
364 &self.schemas,
365 );
366 }
367
368 // Step 6: push the MountedBackend.
369 let last_known_head = backend.current_head().ok().flatten();
370 let mem_name_for_router = mount.mem.clone();
371 let storage_for_router = mount.storage.clone();
372 let mount_capability_for_router = mount.capability;
373 self.mounts.push(MountedBackend {
374 mount,
375 backend,
376 last_known_head,
377 mem_config,
378 // A runtime-created mem is authored live, not installed from
379 // an archive — it carries no archive-borne provenance payload
380 // and no sealed check records.
381 archive_provenance: None,
382 archive_checks: None,
383 // Registered live and loaded in this call — never deferred.
384 deferred: false,
385 });
386
387 // Step 7: COW snapshot swap on mem_router, branched on the
388 // mount's capability — a read-only archive mount registers in
389 // the router's read-only slot (so `is_writable` stays false
390 // and `archive_path_for_mem` resolves), everything else in the
391 // writable slot. Folder mounts surface their on-disk path;
392 // other backends register with `dir: None` (mem-repo-backed
393 // mounts have no working tree).
394 match (&mount_capability_for_router, &storage_for_router) {
395 (crate::workspace::MountCapability::ReadOnly, MountStorage::Archive { path }) => {
396 Arc::make_mut(&mut self.mem_router)
397 .add_read_only(mem_name_for_router, path.clone());
398 }
399 _ => {
400 let dir: Option<PathBuf> = match &storage_for_router {
401 MountStorage::Folder { path } => Some(path.clone()),
402 MountStorage::GitBranch { .. }
403 | MountStorage::Archive { .. }
404 | MountStorage::InMemory => None,
405 };
406 Arc::make_mut(&mut self.mem_router).add_writable(mem_name_for_router, dir, origin);
407 }
408 }
409
410 // Step 8: invalidate dependent memos.
411 if run_global_passes {
412 self.invalidate_communities();
413 self.invalidate_search_indexes();
414 }
415
416 Ok(())
417 }
418
419 /// The batched tail of `register_writable_mem_inner(...,
420 /// run_global_passes: false)`: one workspace-global relation
421 /// validation, one alias remap, one memo invalidation for the
422 /// whole batch of registrations.
423 /// [`Self::register_writable_mem`] without the workspace-global
424 /// passes — the batch form the roster reconciliation uses; the
425 /// caller runs [`Self::finish_batched_registrations`] once after.
426 pub(crate) fn register_writable_mem_batched(
427 &mut self,
428 mount: Mount,
429 backend: Box<dyn MemBackend>,
430 origin: MemOrigin,
431 ) -> Result<(), EngineError> {
432 self.register_writable_mem_inner(mount, backend, origin, false)
433 }
434
435 pub(crate) fn finish_batched_registrations(&mut self) {
436 let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
437 .mounts
438 .iter()
439 .map(|m| (m.mount.mem.clone(), m.mount.capability))
440 .collect();
441 crate::entity::store_builder::validate_loaded_relations(
442 &mut self.store,
443 &self.schemas,
444 &mount_caps,
445 &mut self.load_warnings,
446 );
447 crate::entity::store_builder::remap_alias_target_edge_sources(
448 &mut self.store,
449 &self.schemas,
450 );
451 self.invalidate_communities();
452 self.invalidate_search_indexes();
453 }
454
455 /// Additive full refresh — the warm-server half of "restart the
456 /// process": re-scan the schema sources and the mount manifest,
457 /// making newly installed schema versions resolvable and newly
458 /// registered mems usable, WITHOUT applying removals. The
459 /// asymmetry is deliberate and is the whole safety argument:
460 /// adding extends what the in-memory store can answer, while
461 /// removing can strand entities, in-flight handles, and cached
462 /// hashes the process is still serving. Removals are skipped and
463 /// reported; a restart applies them.
464 ///
465 /// Failure model is per-item: a schema source or a mount that
466 /// fails to refresh lands in `failures` and never surfaces as
467 /// newly available; the others proceed. Each mount registration
468 /// is all-or-nothing (every fallible step runs before the store
469 /// is touched), so a failed item leaves no half-updated state.
470 /// The workspace-global passes (relation validation, alias remap,
471 /// memo invalidation) run ONCE per refresh regardless of how many
472 /// mounts attached.
473 ///
474 /// A newly mounted mem starts cold and loads like any other
475 /// mount. Content reload of pre-existing mems is NOT part of this
476 /// method — callers that want both (the `memstead_reload
477 /// full=true` surface) run the existing content-reload sweep
478 /// alongside.
479 pub fn full_refresh(&mut self) -> crate::ops::FullRefreshReport {
480 let started = std::time::Instant::now();
481 let mut report = crate::ops::FullRefreshReport::default();
482
483 let Some(_root) = self.workspace_root.clone() else {
484 report.failures.push(crate::ops::RefreshFailure {
485 item: "workspace".to_string(),
486 error: "engine has no workspace root (ad-hoc mount-list construction) — \
487 nothing to re-scan"
488 .to_string(),
489 });
490 report.elapsed_ms = started.elapsed().as_millis() as u64;
491 return report;
492 };
493
494 // Workspace policy — same best-effort refresh the
495 // workspace-wide content reload performs.
496 self.refresh_workspace_settings_if_possible();
497
498 // --- Schema sources, additively. ---
499 self.refresh_schema_sources(&mut report);
500
501 // --- Mount roster: the same reconciliation every operation runs
502 // (roster.rs), forced here even when the fingerprint says
503 // unchanged so the report is authoritative. Removals APPLY. ---
504 match self.reconcile_roster_forced() {
505 Ok(change) => {
506 report.mems_mounted = change.added;
507 report.mems_unmounted = change.removed;
508 report.mems_quarantined = change.quarantined;
509 report.failures.extend(change.failures);
510 }
511 Err(e) => report.failures.push(crate::ops::RefreshFailure {
512 item: "mount-manifest".to_string(),
513 error: e.to_string(),
514 }),
515 }
516 report.mems_mounted.sort();
517 report.mems_unmounted.sort();
518 report.mems_quarantined.sort();
519
520 report.elapsed_ms = started.elapsed().as_millis() as u64;
521 report
522 }
523
524 /// Re-scan the schema sources additively into `report`
525 /// (`schemas_added`, `schema_removals_skipped`, per-source failures).
526 pub(crate) fn refresh_schema_sources(&mut self, report: &mut crate::ops::FullRefreshReport) {
527 let Some(root) = self.workspace_root.clone() else {
528 return;
529 };
530 use crate::schema_source::SchemaSource as _;
531 let mut fresh: Vec<std::sync::Arc<memstead_schema::Schema>> = Vec::new();
532 let mut sources_complete = true;
533 match crate::schema_source::FolderSchemaSource::for_workspace(&root).read_schemas() {
534 Ok(mut s) => fresh.append(&mut s),
535 Err(e) => {
536 sources_complete = false;
537 report.failures.push(crate::ops::RefreshFailure {
538 item: "schema-source:folder".to_string(),
539 error: e.to_string(),
540 });
541 }
542 }
543 if let Some(ops) = self.git_branch_ops() {
544 match (ops.read_ref_schemas)(&root) {
545 Ok(mut s) => fresh.append(&mut s),
546 Err(e) => {
547 sources_complete = false;
548 report.failures.push(crate::ops::RefreshFailure {
549 item: "schema-source:memstead-ref".to_string(),
550 error: e.to_string(),
551 });
552 }
553 }
554 }
555 let key = |s: &memstead_schema::Schema| {
556 let (name, version) = s.id();
557 format!("{name}@{version}")
558 };
559 let existing: std::collections::HashSet<String> =
560 self.workspace_schemas.iter().map(|s| key(s)).collect();
561 let fresh_keys: std::collections::HashSet<String> = fresh.iter().map(|s| key(s)).collect();
562 for schema in fresh {
563 let k = key(&schema);
564 if !existing.contains(&k) && !report.schemas_added.contains(&k) {
565 report.schemas_added.push(k);
566 self.workspace_schemas.push(schema);
567 }
568 }
569 report.schemas_added.sort();
570 // Removal detection is only meaningful when every source was
571 // actually readable — otherwise an unreadable source would
572 // masquerade as a mass removal.
573 if sources_complete {
574 report.schema_removals_skipped = existing
575 .difference(&fresh_keys)
576 .cloned()
577 .collect::<Vec<_>>();
578 report.schema_removals_skipped.sort();
579 }
580 }
581
582 /// Override the workspace root after construction. The full
583 /// boot helper `memstead_git_branch::engine_from_workspace_root`
584 /// calls this so the engine knows the path even when the boot
585 /// route runs through the full adapter rather than
586 /// [`Self::from_workspace_root`].
587 pub fn set_workspace_root(&mut self, root: PathBuf) {
588 self.workspace_root = Some(root);
589 self.capture_roster_fingerprint();
590 }
591
592 /// Persist the engine's current mount list to the workspace
593 /// store so a freshly-booted sibling process observes the same
594 /// mem membership. Called by
595 /// [`crate::mem_management::create_mem`] /
596 /// [`crate::mem_management::delete_mem`] after the in-memory
597 /// router mutation lands — without this, the per-mem content
598 /// (branch + `__MEMSTEAD` config blob, or folder + `.memstead/config.json`)
599 /// is already on disk, but the next process boot reads an empty
600 /// `.memstead/state/mounts.json` and the engine starts with zero
601 /// writable mems.
602 ///
603 /// No-op when `workspace_root` is unset (tests / ad-hoc
604 /// consumers that build the engine directly from a mount list).
605 /// Production boot paths (`Engine::from_workspace_root` and the
606 /// full counterpart) always set the root, so the engine-side
607 /// fix covers every caller — in-process embedders included
608 /// — by construction.
609 ///
610 /// Hardcoded against [`crate::FileWorkspaceStore`] because that
611 /// is the only V1 adapter; a future SQLite or remote adapter
612 /// would install through a setter mirroring
613 /// [`Self::set_backend_factory`].
614 pub fn persist_state(&self) -> Result<(), EngineError> {
615 let Some(root) = self.workspace_root.as_ref() else {
616 return Ok(());
617 };
618 use crate::workspace_store::WorkspaceStoreAdapter as _;
619 let store = crate::FileWorkspaceStore::new();
620 let map = |e: crate::workspace_store::StoreError| {
621 EngineError::Mem(format!("persist workspace state: {e}"))
622 };
623
624 // Publish THIS engine's changes, not its whole cached view. An
625 // earlier version serialized `self.mounts` wholesale, so a
626 // long-lived process silently dropped every mount a sibling
627 // process had registered since the cache was taken — the same
628 // condition the mem-config writers close by re-reading, reaching
629 // the workspace roster through the one writer they did not cover.
630 // The delta is computed against `mounts_baseline` (what this
631 // engine last read or wrote) rather than against a clock: a
632 // single-writer workspace has an identical on-disk roster, so
633 // the merge is a no-op there.
634 // The roster this engine speaks for is the attached mounts PLUS
635 // the quarantined ones: a quarantined mem's retained Mount is
636 // what lets `reload` re-attempt the attach after a repair, and
637 // dropping it from the file is how "degrade, never disappear"
638 // turns into "disappear". It is also the record the
639 // quarantine-repair path repins before asking for a state write.
640 let ours: Vec<crate::workspace::Mount> = self
641 .mounts
642 .iter()
643 .map(|m| m.mount.clone())
644 .chain(self.quarantined.iter().map(|q| q.mount.clone()))
645 .collect();
646
647 for attempt in 0..8 {
648 let expected = store.read_state_bytes(root).map_err(map)?;
649 let on_disk: Vec<crate::workspace::Mount> = match expected.as_deref() {
650 Some(bytes) => store.parse_state_bytes(root, bytes).map_err(map)?,
651 None => Vec::new(),
652 };
653
654 let merged = {
655 let baseline = self.mounts_baseline.borrow();
656 merge_mount_rosters(&baseline, &ours, on_disk)
657 };
658 let workspace = crate::workspace::Workspace {
659 mounts: merged,
660 settings: self.settings.clone(),
661 };
662
663 if store
664 .save_state_cas(root, &workspace, expected.as_deref())
665 .map_err(map)?
666 {
667 *self.mounts_baseline.borrow_mut() = ours;
668 return Ok(());
669 }
670 if attempt == 7 {
671 return Err(EngineError::Mem(
672 "workspace state is being written concurrently: eight compare-and-set \
673 attempts all lost the race. Retry, or find the writer that is not \
674 backing off."
675 .to_string(),
676 ));
677 }
678 }
679 unreachable!("the loop returns on success and on exhaustion")
680 }
681}
682
683/// Three-way merge of a mount roster for a state write.
684///
685/// `baseline` is what the writing engine last read or wrote, `ours` is
686/// its roster now, `on_disk` is what the file holds at this instant.
687/// The result keeps every on-disk mount the writer did not touch (so a
688/// sibling's registration survives), drops the ones the writer removed
689/// since its baseline, and applies the ones it added or changed.
690///
691/// A mount present in `ours` unchanged since the baseline does NOT
692/// overwrite the on-disk record of the same name: if a sibling edited
693/// it and we did not, the sibling's edit is the newer statement about
694/// it, and republishing our stale copy is exactly the loss this merge
695/// exists to prevent.
696fn merge_mount_rosters(
697 baseline: &[crate::workspace::Mount],
698 ours: &[crate::workspace::Mount],
699 on_disk: Vec<crate::workspace::Mount>,
700) -> Vec<crate::workspace::Mount> {
701 use std::collections::{HashMap, HashSet};
702
703 let ours_names: HashSet<&str> = ours.iter().map(|m| m.mem.as_str()).collect();
704 let removed_by_us: HashSet<&str> = baseline
705 .iter()
706 .map(|m| m.mem.as_str())
707 .filter(|n| !ours_names.contains(n))
708 .collect();
709 let baseline_by_name: HashMap<&str, &crate::workspace::Mount> =
710 baseline.iter().map(|m| (m.mem.as_str(), m)).collect();
711
712 let mut merged: Vec<crate::workspace::Mount> = on_disk
713 .into_iter()
714 .filter(|m| !removed_by_us.contains(m.mem.as_str()))
715 .collect();
716
717 for mount in ours {
718 let untouched_by_us = baseline_by_name
719 .get(mount.mem.as_str())
720 .is_some_and(|b| *b == mount);
721 match merged.iter_mut().find(|d| d.mem == mount.mem) {
722 Some(slot) => {
723 if !untouched_by_us {
724 *slot = mount.clone();
725 }
726 }
727 None => merged.push(mount.clone()),
728 }
729 }
730 merged
731}