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