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            // 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 mem_name_for_router = mount.mem.clone();
384        let storage_for_router = mount.storage.clone();
385        let mount_capability_for_router = mount.capability;
386        self.mounts.push(MountedBackend {
387            mount,
388            backend: backend.into(),
389            last_known_head,
390            mem_config,
391            // A runtime-created mem is authored live, not installed from
392            // an archive — it carries no archive-borne provenance payload
393            // and no sealed check records.
394            archive_provenance: None,
395            archive_checks: None,
396            // Registered live and loaded in this call — never deferred.
397            deferred: false,
398            reload_failure: incomplete.map(crate::engine::ViewFailure::drift),
399            strays: Default::default(),
400        });
401
402        // Step 7: COW snapshot swap on mem_router, branched on the
403        // mount's capability — a read-only archive mount registers in
404        // the router's read-only slot (so `is_writable` stays false
405        // and `archive_path_for_mem` resolves), everything else in the
406        // writable slot. Folder mounts surface their on-disk path;
407        // other backends register with `dir: None` (mem-repo-backed
408        // mounts have no working tree).
409        match (&mount_capability_for_router, &storage_for_router) {
410            (crate::workspace::MountCapability::ReadOnly, MountStorage::Archive { path }) => {
411                Arc::make_mut(&mut self.mem_router)
412                    .add_read_only(mem_name_for_router, path.clone());
413            }
414            _ => {
415                let dir: Option<PathBuf> = match &storage_for_router {
416                    MountStorage::Folder { path } => Some(path.clone()),
417                    MountStorage::GitBranch { .. }
418                    | MountStorage::Archive { .. }
419                    | MountStorage::InMemory => None,
420                };
421                Arc::make_mut(&mut self.mem_router).add_writable(mem_name_for_router, dir, origin);
422            }
423        }
424
425        // Step 8: invalidate dependent memos.
426        if run_global_passes {
427            self.invalidate_communities();
428            self.invalidate_search_indexes();
429        }
430
431        Ok(())
432    }
433
434    /// The batched tail of `register_writable_mem_inner(...,
435    /// run_global_passes: false)`: one workspace-global relation
436    /// validation, one alias remap, one memo invalidation for the
437    /// whole batch of registrations.
438    /// [`Self::register_writable_mem`] without the workspace-global
439    /// passes — the batch form the roster reconciliation uses; the
440    /// caller runs [`Self::finish_batched_registrations`] once after.
441    pub(crate) fn register_writable_mem_batched(
442        &mut self,
443        mount: Mount,
444        backend: Box<dyn MemBackend>,
445        origin: MemOrigin,
446    ) -> Result<(), EngineError> {
447        self.register_writable_mem_inner(mount, backend, origin, false)
448    }
449
450    pub(crate) fn finish_batched_registrations(&mut self) {
451        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
452            .mounts
453            .iter()
454            .map(|m| (m.mount.mem.clone(), m.mount.capability))
455            .collect();
456        crate::entity::store_builder::validate_loaded_relations(
457            &mut self.store,
458            &self.schemas,
459            &mount_caps,
460            &mut self.load_warnings,
461        );
462        crate::entity::store_builder::remap_alias_target_edge_sources(
463            &mut self.store,
464            &self.schemas,
465        );
466        self.invalidate_communities();
467        self.invalidate_search_indexes();
468    }
469
470    /// Additive full refresh — the warm-server half of "restart the
471    /// process": re-scan the schema sources and the mount manifest,
472    /// making newly installed schema versions resolvable and newly
473    /// registered mems usable, WITHOUT applying removals. The
474    /// asymmetry is deliberate and is the whole safety argument:
475    /// adding extends what the in-memory store can answer, while
476    /// removing can strand entities, in-flight handles, and cached
477    /// hashes the process is still serving. Removals are skipped and
478    /// reported; a restart applies them.
479    ///
480    /// Failure model is per-item: a schema source or a mount that
481    /// fails to refresh lands in `failures` and never surfaces as
482    /// newly available; the others proceed. Each mount registration
483    /// is all-or-nothing (every fallible step runs before the store
484    /// is touched), so a failed item leaves no half-updated state.
485    /// The workspace-global passes (relation validation, alias remap,
486    /// memo invalidation) run ONCE per refresh regardless of how many
487    /// mounts attached.
488    ///
489    /// A newly mounted mem starts cold and loads like any other
490    /// mount. Content reload of pre-existing mems is NOT part of this
491    /// method — callers that want both (the `memstead_reload
492    /// full=true` surface) run the existing content-reload sweep
493    /// alongside.
494    pub fn full_refresh(&mut self) -> crate::ops::FullRefreshReport {
495        let started = std::time::Instant::now();
496        let mut report = crate::ops::FullRefreshReport::default();
497
498        let Some(_root) = self.workspace_root.clone() else {
499            report.failures.push(crate::ops::RefreshFailure {
500                item: "workspace".to_string(),
501                error: "engine has no workspace root (ad-hoc mount-list construction) — \
502                        nothing to re-scan"
503                    .to_string(),
504            });
505            report.elapsed_ms = started.elapsed().as_millis() as u64;
506            return report;
507        };
508
509        // Workspace policy — same best-effort refresh the
510        // workspace-wide content reload performs.
511        self.refresh_workspace_settings_if_possible();
512
513        // --- Schema sources, additively. ---
514        self.refresh_schema_sources(&mut report);
515
516        // --- Mount roster: the same reconciliation every operation runs
517        // (roster.rs), forced here even when the fingerprint says
518        // unchanged so the report is authoritative. Removals APPLY. ---
519        match self.reconcile_roster_forced() {
520            Ok(change) => {
521                report.mems_mounted = change.added;
522                report.mems_unmounted = change.removed;
523                report.mems_quarantined = change.quarantined;
524                report.failures.extend(change.failures);
525            }
526            Err(e) => report.failures.push(crate::ops::RefreshFailure {
527                item: "mount-manifest".to_string(),
528                error: e.to_string(),
529            }),
530        }
531        report.mems_mounted.sort();
532        report.mems_unmounted.sort();
533        report.mems_quarantined.sort();
534
535        report.elapsed_ms = started.elapsed().as_millis() as u64;
536        report
537    }
538
539    /// Re-scan the schema sources additively into `report`
540    /// (`schemas_added`, `schema_removals_skipped`, per-source failures).
541    pub(crate) fn refresh_schema_sources(&mut self, report: &mut crate::ops::FullRefreshReport) {
542        let Some(root) = self.workspace_root.clone() else {
543            return;
544        };
545        use crate::schema_source::SchemaSource as _;
546        let mut fresh: Vec<std::sync::Arc<memstead_schema::Schema>> = Vec::new();
547        let mut sources_complete = true;
548        match crate::schema_source::FolderSchemaSource::for_workspace(&root).read_schemas() {
549            Ok(mut s) => fresh.append(&mut s),
550            Err(e) => {
551                sources_complete = false;
552                report.failures.push(crate::ops::RefreshFailure {
553                    item: "schema-source:folder".to_string(),
554                    error: e.to_string(),
555                });
556            }
557        }
558        if let Some(ops) = self.git_branch_ops() {
559            match (ops.read_ref_schemas)(&root) {
560                Ok(mut s) => fresh.append(&mut s),
561                Err(e) => {
562                    sources_complete = false;
563                    report.failures.push(crate::ops::RefreshFailure {
564                        item: "schema-source:memstead-ref".to_string(),
565                        error: e.to_string(),
566                    });
567                }
568            }
569        }
570        let key = |s: &memstead_schema::Schema| {
571            let (name, version) = s.id();
572            format!("{name}@{version}")
573        };
574        let existing: std::collections::HashSet<String> =
575            self.workspace_schemas.iter().map(|s| key(s)).collect();
576        let fresh_keys: std::collections::HashSet<String> = fresh.iter().map(|s| key(s)).collect();
577        for schema in fresh {
578            let k = key(&schema);
579            if !existing.contains(&k) && !report.schemas_added.contains(&k) {
580                report.schemas_added.push(k);
581                self.workspace_schemas.push(schema);
582            }
583        }
584        report.schemas_added.sort();
585        // Removal detection is only meaningful when every source was
586        // actually readable — otherwise an unreadable source would
587        // masquerade as a mass removal.
588        if sources_complete {
589            report.schema_removals_skipped = existing
590                .difference(&fresh_keys)
591                .cloned()
592                .collect::<Vec<_>>();
593            report.schema_removals_skipped.sort();
594        }
595    }
596
597    /// Override the workspace root after construction. The full
598    /// boot helper `memstead_git_branch::engine_from_workspace_root`
599    /// calls this so the engine knows the path even when the boot
600    /// route runs through the full adapter rather than
601    /// [`Self::from_workspace_root`].
602    pub fn set_workspace_root(&mut self, root: PathBuf) {
603        self.workspace_root = Some(root);
604        self.capture_roster_fingerprint();
605    }
606
607    /// Persist the engine's current mount list to the workspace
608    /// store so a freshly-booted sibling process observes the same
609    /// mem membership. Called by
610    /// [`crate::mem_management::create_mem`] /
611    /// [`crate::mem_management::delete_mem`] after the in-memory
612    /// router mutation lands — without this, the per-mem content
613    /// (branch + `__MEMSTEAD` config blob, or folder + `.memstead/config.json`)
614    /// is already on disk, but the next process boot reads an empty
615    /// `.memstead/state/mounts.json` and the engine starts with zero
616    /// writable mems.
617    ///
618    /// No-op when `workspace_root` is unset (tests / ad-hoc
619    /// consumers that build the engine directly from a mount list).
620    /// Production boot paths (`Engine::from_workspace_root` and the
621    /// full counterpart) always set the root, so the engine-side
622    /// fix covers every caller — in-process embedders included
623    /// — by construction.
624    ///
625    /// Hardcoded against [`crate::FileWorkspaceStore`] because that
626    /// is the only V1 adapter; a future SQLite or remote adapter
627    /// would install through a setter mirroring
628    /// [`Self::set_backend_factory`].
629    pub fn persist_state(&self) -> Result<(), EngineError> {
630        let Some(root) = self.workspace_root.as_ref() else {
631            return Ok(());
632        };
633        use crate::workspace_store::WorkspaceStoreAdapter as _;
634        let store = crate::FileWorkspaceStore::new();
635        let map = |e: crate::workspace_store::StoreError| {
636            EngineError::Mem(format!("persist workspace state: {e}"))
637        };
638
639        // Publish THIS engine's changes, not its whole cached view. An
640        // earlier version serialized `self.mounts` wholesale, so a
641        // long-lived process silently dropped every mount a sibling
642        // process had registered since the cache was taken — the same
643        // condition the mem-config writers close by re-reading, reaching
644        // the workspace roster through the one writer they did not cover.
645        // The delta is computed against `mounts_baseline` (what this
646        // engine last read or wrote) rather than against a clock: a
647        // single-writer workspace has an identical on-disk roster, so
648        // the merge is a no-op there.
649        // The roster this engine speaks for is the attached mounts PLUS
650        // the quarantined ones: a quarantined mem's retained Mount is
651        // what lets `reload` re-attempt the attach after a repair, and
652        // dropping it from the file is how "degrade, never disappear"
653        // turns into "disappear". It is also the record the
654        // quarantine-repair path repins before asking for a state write.
655        let ours: Vec<crate::workspace::Mount> = self
656            .mounts
657            .iter()
658            .map(|m| m.mount.clone())
659            .chain(self.quarantined.iter().map(|q| q.mount.clone()))
660            .collect();
661
662        for attempt in 0..8 {
663            let expected = store.read_state_bytes(root).map_err(map)?;
664            let on_disk: Vec<crate::workspace::Mount> = match expected.as_deref() {
665                Some(bytes) => store.parse_state_bytes(root, bytes).map_err(map)?,
666                None => Vec::new(),
667            };
668
669            let merged = {
670                let baseline = self.mounts_baseline.borrow();
671                merge_mount_rosters(&baseline, &ours, on_disk)
672            };
673            let workspace = crate::workspace::Workspace {
674                mounts: merged,
675                settings: self.settings.clone(),
676            };
677
678            if store
679                .save_state_cas(root, &workspace, expected.as_deref())
680                .map_err(map)?
681            {
682                *self.mounts_baseline.borrow_mut() = ours;
683                return Ok(());
684            }
685            if attempt == 7 {
686                return Err(EngineError::Mem(
687                    "workspace state is being written concurrently: eight compare-and-set \
688                     attempts all lost the race. Retry, or find the writer that is not \
689                     backing off."
690                        .to_string(),
691                ));
692            }
693        }
694        unreachable!("the loop returns on success and on exhaustion")
695    }
696}
697
698/// Three-way merge of a mount roster for a state write.
699///
700/// `baseline` is what the writing engine last read or wrote, `ours` is
701/// its roster now, `on_disk` is what the file holds at this instant.
702/// The result keeps every on-disk mount the writer did not touch (so a
703/// sibling's registration survives), drops the ones the writer removed
704/// since its baseline, and applies the ones it added or changed.
705///
706/// A mount present in `ours` unchanged since the baseline does NOT
707/// overwrite the on-disk record of the same name: if a sibling edited
708/// it and we did not, the sibling's edit is the newer statement about
709/// it, and republishing our stale copy is exactly the loss this merge
710/// exists to prevent.
711fn merge_mount_rosters(
712    baseline: &[crate::workspace::Mount],
713    ours: &[crate::workspace::Mount],
714    on_disk: Vec<crate::workspace::Mount>,
715) -> Vec<crate::workspace::Mount> {
716    use std::collections::{HashMap, HashSet};
717
718    let ours_names: HashSet<&str> = ours.iter().map(|m| m.mem.as_str()).collect();
719    let removed_by_us: HashSet<&str> = baseline
720        .iter()
721        .map(|m| m.mem.as_str())
722        .filter(|n| !ours_names.contains(n))
723        .collect();
724    let baseline_by_name: HashMap<&str, &crate::workspace::Mount> =
725        baseline.iter().map(|m| (m.mem.as_str(), m)).collect();
726
727    let mut merged: Vec<crate::workspace::Mount> = on_disk
728        .into_iter()
729        .filter(|m| !removed_by_us.contains(m.mem.as_str()))
730        .collect();
731
732    for mount in ours {
733        let untouched_by_us = baseline_by_name
734            .get(mount.mem.as_str())
735            .is_some_and(|b| *b == mount);
736        match merged.iter_mut().find(|d| d.mem == mount.mem) {
737            Some(slot) => {
738                if !untouched_by_us {
739                    *slot = mount.clone();
740                }
741            }
742            None => merged.push(mount.clone()),
743        }
744    }
745    merged
746}
747
748impl Engine {
749    /// The ids `mem`'s entities point at, read before its slice of the
750    /// store is replaced: the candidates [`Self::settle_slice`] checks
751    /// for stubs the replacement left without a referrer.
752    pub(in crate::engine) fn targets_of_mem(&self, mem: &str) -> Vec<EntityId> {
753        let mut targets: Vec<EntityId> = Vec::new();
754        for entity in self.store.all_entities().filter(|e| e.mem == mem) {
755            targets.extend(entity.relationships.iter().map(|r| r.target.clone()));
756            targets.extend(
757                self.store
758                    .outgoing(&entity.id)
759                    .iter()
760                    .map(|e| e.target.clone()),
761            );
762        }
763        targets.sort_by(|a, b| a.0.cmp(&b.0));
764        targets.dedup();
765        targets
766    }
767
768    /// Settle the cross-mem state a fresh load derives, after `mem`'s
769    /// slice of the store was replaced (a reload of that mem, its
770    /// registration, its unregistration). Two things a fresh load
771    /// would build differently otherwise:
772    ///
773    /// - the edges other mems' entities point into `mem`: removing the
774    ///   slice dropped them, and only a fresh load of every mem would
775    ///   push them again. They are rebuilt from the other mems' records
776    ///   (a target `mem` no longer holds becomes the stub a fresh load
777    ///   makes for it).
778    /// - stubs nothing points at any more: a fresh load makes a stub
779    ///   only as some edge's target. The candidates are `mem`'s own
780    ///   ids and `prior_targets`, what `mem` pointed at before
781    ///   ([`Self::targets_of_mem`]), the only stubs the replacement can
782    ///   have left without a referrer.
783    pub(in crate::engine) fn settle_slice(&mut self, mem: &str, prior_targets: &[EntityId]) {
784        crate::entity::store_builder::reconstruct_incoming_cross_mem_edges(&mut self.store, mem);
785        let own: Vec<EntityId> = self
786            .store
787            .all_entities()
788            .filter(|e| e.stub && e.mem == mem)
789            .map(|e| e.id.clone())
790            .collect();
791        crate::engine::mutation::gc_orphan_stubs_among(
792            &mut self.store,
793            own.iter().chain(prior_targets.iter()),
794        );
795    }
796}