Skip to main content

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