Skip to main content

memstead_base/engine/query/
mounts.rs

1//! Mounts and routing: which mems exist, where each one lives, which are writable, quarantined or deferred, and how an entity id resolves to one of them.
2
3use super::*;
4
5impl Engine {
6    /// Mem names the engine knows about, in declaration order.
7    /// Cheap; useful for callers that need to enumerate before
8    /// dispatching by mem.
9    pub fn mem_names(&self) -> Vec<&str> {
10        self.mounts.iter().map(|m| m.mount.mem.as_str()).collect()
11    }
12
13    /// Derivation-staleness report for one mem:
14    /// every EXPLICIT edge whose rel-type the mem's schema declares
15    /// `derivation: true`, compared against its recorded baseline.
16    /// Baseline differs from the target's current hash → `stale`;
17    /// no baseline recorded (edge predates the declaration, or was
18    /// load-derived) → `unbaselined`, distinctly — never fabricated
19    /// as fresh or stale. Fresh edges are not reported. A mem whose
20    /// schema declares no derivation rel-types returns the empty
21    /// report; an unreadable sidecar reads as empty (every edge
22    /// unbaselined) rather than an error.
23    pub fn derivation_report(
24        &self,
25        mem: &str,
26    ) -> Result<Vec<crate::ops::health::DerivationFinding>, EngineError> {
27        if !self.mem_router.is_visible(mem) {
28            return Err(self.unknown_mem_error(mem));
29        }
30        let Some(schema) = self.schemas.get(mem) else {
31            return Ok(Vec::new());
32        };
33        let declared: std::collections::HashSet<&str> = schema
34            .manifest
35            .relationships
36            .definitions
37            .iter()
38            .filter(|d| d.derivation)
39            .map(|d| d.name.as_str())
40            .collect();
41        if declared.is_empty() {
42            return Ok(Vec::new());
43        }
44        let sidecar = self
45            .mounts
46            .iter()
47            .find(|m| m.mount.mem == mem)
48            .and_then(|m| {
49                m.backend
50                    .read_entity(Path::new(crate::derivation::DERIVATION_SIDECAR_PATH))
51                    .ok()
52                    .flatten()
53            })
54            .and_then(|bytes| crate::derivation::DerivationSidecar::from_bytes(&bytes).ok())
55            .unwrap_or_default();
56
57        let mut out = Vec::new();
58        let mut sources: Vec<&crate::entity::Entity> = self
59            .store
60            .all_entities()
61            .filter(|e| !e.stub && e.id.mem() == mem)
62            .collect();
63        sources.sort_by(|a, b| a.id.as_ref().cmp(b.id.as_ref()));
64        for entity in sources {
65            for edge in self.store.outgoing(&entity.id) {
66                if !declared.contains(edge.rel_type.as_str())
67                    || edge.source != crate::store::EdgeSource::Explicit
68                {
69                    continue;
70                }
71                let current = self
72                    .store
73                    .get(&edge.target)
74                    .map(|t| t.content_hash.clone())
75                    .unwrap_or_default();
76                match sidecar.get(entity.id.as_ref(), &edge.rel_type, edge.target.as_ref()) {
77                    None => out.push(crate::ops::health::DerivationFinding {
78                        source: entity.id.clone(),
79                        rel_type: edge.rel_type.clone(),
80                        target: edge.target.clone(),
81                        state: "unbaselined".to_string(),
82                        baseline: None,
83                        current,
84                    }),
85                    Some(baseline) if baseline != current => {
86                        out.push(crate::ops::health::DerivationFinding {
87                            source: entity.id.clone(),
88                            rel_type: edge.rel_type.clone(),
89                            target: edge.target.clone(),
90                            state: "stale".to_string(),
91                            baseline: Some(baseline.to_string()),
92                            current,
93                        })
94                    }
95                    Some(_) => {}
96                }
97            }
98        }
99        Ok(out)
100    }
101
102    /// Public-shape mount record for `mem`, or `None` for an unknown
103    /// mem.
104    ///
105    /// Surfaces the operator-facing
106    /// [`crate::workspace::Mount`] (mem name, schema pin, storage
107    /// reference, capability, lifecycle, cross_linkable) so MCP / CLI
108    /// handlers can branch on backend-specific shapes via
109    /// [`crate::workspace::MountStorage`] when they need accessors
110    /// that don't make sense on every backend (e.g. gitdir / branch
111    /// for `memstead_health { include_config: true }`'s git-class
112    /// payload). Backends that want the equivalent of full's
113    /// `engine.gitdir_for(mem)` match
114    /// `engine.mount(mem).map(|m| &m.storage)` against
115    /// `MountStorage::GitBranch { gitdir, branch }` and walk
116    /// directly — keeps the engine surface backend-neutral.
117    ///
118    /// Counterpart to [`Self::mem_names`] which lists every mount.
119    pub fn mount(&self, mem: &str) -> Option<&crate::workspace::Mount> {
120        self.mounts
121            .iter()
122            .find(|m| m.mount.mem == mem)
123            .map(|m| &m.mount)
124    }
125
126    /// Orphan count attributed to each mem's pinned schema, over the
127    /// given `orphan_ids` (the caller pre-filters them by any mem scope).
128    /// Lets a health surface show that ingest-mem isolates (orphans by
129    /// design) and code-mem debt land in different schema buckets rather
130    /// than one blended, misleading total. Mems with no settled pin
131    /// bucket under the empty string.
132    pub fn orphans_by_schema(
133        &self,
134        orphan_ids: &[EntityId],
135    ) -> std::collections::BTreeMap<String, usize> {
136        let mut by_schema = std::collections::BTreeMap::new();
137        for id in orphan_ids {
138            let schema = self
139                .store()
140                .get(id)
141                .and_then(|e| self.mount(&e.mem))
142                .and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
143                .unwrap_or_default();
144            *by_schema.entry(schema).or_insert(0) += 1;
145        }
146        by_schema
147    }
148
149    /// Community count attributed to each schema across `mems`: a cluster
150    /// counts toward every schema whose mems it touches, so these figures
151    /// can sum above the global community count — the same "touches"
152    /// semantic as the mem-scoped count. Per-schema dedup keeps a cluster
153    /// touching two mems of one schema from being counted twice.
154    pub fn communities_by_schema(
155        &self,
156        mems: &[String],
157    ) -> std::collections::BTreeMap<String, usize> {
158        let louvain = self.communities();
159        let mut buckets: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
160            std::collections::BTreeMap::new();
161        for name in mems {
162            let schema = self
163                .mount(name)
164                .and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
165                .unwrap_or_default();
166            let clusters = crate::graph::community::clusters_in_mem(self.store(), louvain, name);
167            buckets.entry(schema).or_default().extend(clusters);
168        }
169        buckets
170            .into_iter()
171            .map(|(schema, set)| (schema, set.len()))
172            .collect()
173    }
174
175    /// All mounts the engine knows about, in declaration order.
176    /// Counterpart to [`Self::mem_names`] when the caller needs
177    /// the full mount shape (e.g. to enumerate by storage variant).
178    pub fn mounts(&self) -> Vec<&crate::workspace::Mount> {
179        self.mounts.iter().map(|m| &m.mount).collect()
180    }
181
182    /// Names of mems whose mount declares
183    /// [`crate::workspace::MountCapability::Write`], in declaration
184    /// order. Convenience over `mounts().iter().filter(...).map(...)`
185    /// for handlers that gate by writable status (`memstead_health`,
186    /// `memstead_overview`'s mem roster, the lifecycle tools'
187    /// candidate list). Read-only mounts (archive backends) are
188    /// excluded.
189    pub fn writable_mem_names(&self) -> Vec<&str> {
190        self.mounts
191            .iter()
192            .filter(|m| m.mount.capability == MountCapability::Write)
193            .map(|m| m.mount.mem.as_str())
194            .collect()
195    }
196
197    /// The default writable mem — the target a mutation lands in when
198    /// it omits `mem`. `None` when no writable mem is mounted.
199    ///
200    /// Defined as the **first writable mount in declaration order**, i.e.
201    /// the seed / earliest-created writable mem. This is a *stable*
202    /// designation, not a function of the current name set: new mems
203    /// register via `register_writable_mem`, which pushes onto the end
204    /// of the mount list (and `mounts.json` preserves that order across
205    /// reboots), so creating an additional mem never moves the default
206    /// — even one whose name sorts ahead alphabetically. Deleting the
207    /// current default promotes the next-earliest writable mem; that is
208    /// the only thing that shifts it. Both the MCP `resolve_mem` and the
209    /// CLI's omitted-`--mem` path resolve through here so the two
210    /// surfaces always agree (the
211    /// pre-fix MCP path read `writable_mems().iter().next()` off an
212    /// unordered `HashSet`, which silently retargeted writes when a second
213    /// mem appeared).
214    pub fn default_writable_mem(&self) -> Option<&str> {
215        self.mounts
216            .iter()
217            .find(|m| m.mount.capability == MountCapability::Write)
218            .map(|m| m.mount.mem.as_str())
219    }
220
221    /// On-disk folder path for a folder-backed mount, or `None` for
222    /// any other backend (git-branch, archive) or unknown mem.
223    /// Convenience over `engine.mount(mem).map(|m| &m.storage)` +
224    /// matching on `MountStorage::Folder { path }`. Used by
225    /// handlers that need a filesystem path for a folder mem
226    /// (e.g. `memstead_health { include_config: true }`'s
227    /// `mems[].vcs.worktree` field for folder mounts).
228    pub fn folder_path_for_mem(&self, mem: &str) -> Option<&Path> {
229        match self.mount(mem).map(|m| &m.storage) {
230            Some(crate::workspace::MountStorage::Folder { path }) => Some(path.as_path()),
231            _ => None,
232        }
233    }
234
235    /// Runtime snapshot of writable / visible mems. Handlers that
236    /// need the writable roster (`memstead_health`'s `writable_mems` /
237    /// `read_mems`), per-mem origin tag (`include_config:
238    /// true`'s `mems[].origin`), or visibility check
239    /// (`memstead_overview`'s mem list, the lifecycle tools' collision
240    /// guard) consume the router here. Returned by reference — the
241    /// `Arc` is held on the engine; callers that need a clonable
242    /// handle can `Arc::clone` the engine's field directly when that
243    /// surface arrives.
244    pub fn mem_router(&self) -> &MemRouterSnapshot {
245        &self.mem_router
246    }
247
248    /// Resolve the gitdir for a writable mem. Used by `memstead_health
249    /// { include_config: true }` to surface per-mem `vcs.gitdir`
250    /// so outer-repo bookkeeping clients can `git -C <gitdir>` per
251    /// mem without hardcoding the layout.
252    ///
253    /// - `EngineError::UnknownMem` when the name does not resolve.
254    /// - `EngineError::Mem` when the mount's storage is not
255    ///   git-branch-backed (folder, archive — they have no gitdir).
256    pub fn gitdir_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
257        let m = self
258            .mount(mem_name)
259            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
260        match &m.storage {
261            MountStorage::GitBranch { gitdir, .. } => Ok(gitdir.clone()),
262            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
263                Err(EngineError::Mem(format!(
264                    "mem '{mem_name}' has no resolved gitdir"
265                )))
266            }
267        }
268    }
269
270    /// Resolve the worktree for a writable mem. Used by
271    /// `memstead_health { include_config: true }` to surface per-mem
272    /// `vcs.worktree`.
273    ///
274    /// - `EngineError::UnknownMem` when the name does not resolve.
275    /// - `EngineError::Mem` when the mount's backend has no
276    ///   worktree concept (git-branch with no working tree, archive).
277    ///
278    /// Folder mounts surface their on-disk path. Git-branch mounts
279    /// follow the `dir: Some(...)` composition pattern: when the
280    /// workspace root contains a folder named after the mem with a
281    /// `.memstead/config.json` marker, that folder is the worktree
282    /// (disk-shape composition). Otherwise — pure mem-repo-backed
283    /// — return Err.
284    pub fn worktree_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
285        let m = self
286            .mount(mem_name)
287            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
288        match &m.storage {
289            MountStorage::Folder { path } => Ok(path.clone()),
290            MountStorage::GitBranch { .. } => {
291                if let Some(root) = self.workspace_root.as_deref() {
292                    let candidate = root.join(mem_name);
293                    if candidate
294                        .join(crate::mem::MEM_META_DIR)
295                        .join("config.json")
296                        .is_file()
297                    {
298                        return Ok(candidate.canonicalize().unwrap_or(candidate));
299                    }
300                }
301                Err(EngineError::Mem(format!(
302                    "mem '{mem_name}' has no working tree (mem-repo-backed)"
303                )))
304            }
305            MountStorage::Archive { .. } => Err(EngineError::Mem(format!(
306                "mem '{mem_name}' is archive-backed and has no worktree"
307            ))),
308            MountStorage::InMemory => Err(EngineError::Mem(format!(
309                "mem '{mem_name}' is in-memory and has no worktree"
310            ))),
311        }
312    }
313
314    /// Per-mem `.memstead/config.json` payload, when available. Used
315    /// by `memstead_health { include_config: true }` to surface the
316    /// opaque `write_guidance` map and the catch-all `extra` fields
317    /// per mem.
318    ///
319    /// Folder-backed mounts return `Some(&MemConfig)` when
320    /// `<path>/.memstead/config.json` parsed cleanly at construction.
321    /// Git-branch and archive backends return `None` until the
322    /// read-from-storage-backend path lifts (the V1 unified engine
323    /// loads configs only from folder layouts; the file lives
324    /// inside the gitdir / archive for the other backends and
325    /// needs a backend-level read primitive).
326    ///
327    /// Unknown mem names return `None` (no error variant — the
328    /// accessor is intentionally lenient because memstead_health emits
329    /// an empty detail block per missing config rather than
330    /// aborting the call).
331    pub fn mem_config_for(&self, mem: &str) -> Option<&memstead_schema::config::MemConfig> {
332        self.mounts
333            .iter()
334            .find(|m| m.mount.mem == mem)
335            .and_then(|m| m.mem_config.as_ref())
336    }
337
338    /// The authoring-provenance payload an installed mem carries, read
339    /// from the archive's `.memstead/provenance.json` at construction.
340    /// `None` when the mem carries none (a pre-provenance archive, a
341    /// runtime-created mem, or a backend that does not surface one) —
342    /// the read path reports provenance as absent. Unknown mem names
343    /// return `None`.
344    pub fn archive_provenance_for(&self, mem: &str) -> Option<&memstead_schema::ArchiveProvenance> {
345        self.mounts
346            .iter()
347            .find(|m| m.mount.mem == mem)
348            .and_then(|m| m.archive_provenance.as_ref())
349    }
350
351    /// The sealed check records an archive mount carries
352    /// (`.memstead/checks.json`), or `None` when the mount is not an
353    /// archive or the archive carries none. The only check-state source
354    /// an archive mount has: a workspace ledger beside the mount is never
355    /// consulted for it, and a writable mount never reads a sealed member.
356    pub fn archive_checks_for(&self, mem: &str) -> Option<&crate::check::SealedChecks> {
357        self.mounts
358            .iter()
359            .find(|m| m.mount.mem == mem)
360            .filter(|m| {
361                matches!(
362                    m.mount.storage,
363                    crate::workspace::MountStorage::Archive { .. }
364                )
365            })
366            .and_then(|m| m.archive_checks.as_ref())
367    }
368
369    /// Whether `mem` is mounted from a sealed archive.
370    pub fn is_archive_mount(&self, mem: &str) -> bool {
371        self.mounts.iter().any(|m| {
372            m.mount.mem == mem
373                && matches!(
374                    m.mount.storage,
375                    crate::workspace::MountStorage::Archive { .. }
376                )
377        })
378    }
379
380    /// Iterate `(mem_name, &MemConfig)` for every mount whose
381    /// mem-config payload loaded at construction. Used by callers
382    /// that walk every writable mount's config (`memstead health`'s
383    /// per-mem dump, the workspace-dump CLI). The yielded `&str` is
384    /// the authoritative mem leaf from the mount record.
385    ///
386    /// Folder-backed mounts yield when their `.memstead/config.json`
387    /// parsed cleanly. Git-branch and archive backends are silent in
388    /// V1 (the same deferred-read-from-storage gap that
389    /// [`Self::mem_config_for`] documents).
390    pub fn mem_configs_named(
391        &self,
392    ) -> impl Iterator<Item = (&str, &memstead_schema::config::MemConfig)> {
393        self.mounts
394            .iter()
395            .filter_map(|m| m.mem_config.as_ref().map(|c| (m.mount.mem.as_str(), c)))
396    }
397
398    /// Every configured mount, with its config when one was readable.
399    ///
400    /// The counterpart to [`Self::mem_configs_named`], whose contract is "mems
401    /// WITH config" and which is therefore right to omit the rest. The trouble
402    /// was that callers wanting to enumerate mounts reached for it anyway: a
403    /// folder mount whose directory is gone returns no config rather than an
404    /// error, boot stores none, and the mount became invisible to every one of
405    /// them. Nine call sites shared that blind spot, and the omission was a
406    /// side effect of config readability rather than anything about the mount
407    /// (04/05, criteria 1 and 8).
408    ///
409    /// Callers that genuinely want only configured mems keep using the other
410    /// one; drivers that want every mount ask for every mount.
411    pub fn mounts_with_optional_config(
412        &self,
413    ) -> impl Iterator<Item = (&str, Option<&memstead_schema::config::MemConfig>)> {
414        self.mounts
415            .iter()
416            .map(|m| (m.mount.mem.as_str(), m.mem_config.as_ref()))
417    }
418
419    /// Resolved `Arc<Schema>` for a writable mem by name. `None`
420    /// when the name is not a registered mount.
421    ///
422    /// Cheap — `Arc::clone` over the per-mem schema map. Resolved
423    /// schemas are stored in `HashMap<String, Arc<Schema>>` so the
424    /// lookup is a single hash hit + clone.
425    pub fn schema_for(&self, mem: &str) -> Option<std::sync::Arc<memstead_schema::Schema>> {
426        self.schemas.get(mem).cloned()
427    }
428
429    /// Cached current branch-tip cursor (typically a 40-char hex
430    /// SHA for git-branch backends; `None` for fresh mems or
431    /// backends that don't track a head — folder / archive).
432    ///
433    /// The value is the per-mount `last_known_head`, seeded at
434    /// construction by `backend.current_head()` and refreshed by
435    /// [`Self::reload_if_stale`] / mutation paths after a
436    /// successful commit.
437    ///
438    /// - `EngineError::UnknownMem` when the name does not resolve.
439    pub fn mem_head_sha(&self, mem_name: &str) -> Result<Option<String>, EngineError> {
440        let m = self
441            .mounts
442            .iter()
443            .find(|m| m.mount.mem == mem_name)
444            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
445        Ok(m.last_known_head.clone())
446    }
447
448    /// Whether a sibling writer has advanced this mem's backend past
449    /// the engine's cached `last_known_head` — a read-only drift probe
450    /// that does **not** reload (unlike [`Self::reload_if_stale`]). One
451    /// `backend.current_head()` read compared against the cached cursor;
452    /// the comparison clears once the engine re-reads (a `reload` /
453    /// `reload_if_stale` refreshes `last_known_head` to the live tip).
454    ///
455    /// Only git-branch backends track a head, so folder / archive /
456    /// in-memory mounts always report `false`. A backend that errors on
457    /// the probe (transient refdb hiccup) reports `false` rather than
458    /// surfacing the error — drift is advisory, and the next real
459    /// operation's reload path is the authoritative sync.
460    ///
461    /// - `EngineError::UnknownMem` when the name does not resolve.
462    pub fn mem_drifted(&self, mem_name: &str) -> Result<bool, EngineError> {
463        let m = self
464            .mounts
465            .iter()
466            .find(|m| m.mount.mem == mem_name)
467            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
468        let live = m.backend.current_head().ok().flatten();
469        Ok(live != m.last_known_head)
470    }
471
472    /// Workspace root the engine booted from, when one is known.
473    /// `None` for engines built directly from a mount list (tests,
474    /// ad-hoc consumers). Set by [`Self::from_workspace_root`] and
475    /// the full counterpart.
476    pub fn workspace_root(&self) -> Option<&Path> {
477        self.workspace_root.as_deref()
478    }
479
480    /// Typed warnings surfaced during mem load — drift findings
481    /// the loader pipeline collects per entity. Empty for V1; the
482    /// accessor surfaces them so handlers can merge into health
483    /// summaries uniformly.
484    pub fn load_warnings(&self) -> &[WarningHint] {
485        &self.load_warnings
486    }
487
488    /// The quarantine roster: mems that failed their mem-level boot
489    /// step and serve nothing until repaired + reloaded. Empty on a
490    /// fully healthy workspace. Surfaced on overview and health.
491    pub fn quarantined_mems(&self) -> &[crate::engine::QuarantinedMem] {
492        &self.quarantined
493    }
494
495    /// The quarantine entry for `mem`, when it is quarantined.
496    pub fn quarantine_reason(&self, mem: &str) -> Option<&crate::engine::QuarantinedMem> {
497        self.quarantined.iter().find(|q| q.mount.mem == mem)
498    }
499
500    /// Whether the store's entity set for `mem` can be trusted to answer the
501    /// question "does this entity still exist?".
502    ///
503    /// WHY this is a question and not an assumption: an anchor sidecar is
504    /// keyed by entity id, and a key with no entity behind it is a dangling
505    /// row (consistency-sweep 03/02). Detecting one means reading a NEGATIVE
506    /// from the store, and a negative is only evidence when the store is known
507    /// to hold everything the mem has. Four states break that, and each of
508    /// them would otherwise turn every anchor in the mem into a false dangling
509    /// report: the mem is not mounted at all, it is quarantined (serving
510    /// nothing), its lazy load has not run yet (mounted, entities absent), or
511    /// a file in it failed to parse, in which case an id missing from the
512    /// store may be a load failure rather than a deleted entity.
513    ///
514    /// The last case is deliberately COARSE for non-folder mounts: load-error
515    /// paths are normalized to absolute only for folder mounts, so a
516    /// git-branch mem's errors carry mem-relative paths that two mems can
517    /// spell identically. Attributing them by name would be a guess, and a
518    /// wrong guess here fabricates dangling rows. Any load error at all
519    /// therefore blocks reconciliation for a non-folder mem. The caller states
520    /// the block rather than skipping silently, which is the honest direction.
521    pub fn entity_set_is_reconcilable(&self, mem: &str) -> Result<(), &'static str> {
522        if self.quarantine_reason(mem).is_some() {
523            return Err("the mem is quarantined and serves no entities");
524        }
525        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
526            return Err("the mem is not mounted here");
527        };
528        if mount.deferred {
529            return Err("the mem's lazy entity load has not run this session");
530        }
531        if self.load_errors.is_empty() {
532            return Ok(());
533        }
534        match &mount.mount.storage {
535            crate::workspace::MountStorage::Folder { path } => {
536                if self.load_errors.iter().any(|(p, _)| p.starts_with(path)) {
537                    Err(
538                        "a file in this mem failed to parse, so an id missing from the store may be a load failure rather than a deleted entity",
539                    )
540                } else {
541                    Ok(())
542                }
543            }
544            _ => Err(
545                "this workspace has files that failed to parse, and their paths cannot be attributed to one mem",
546            ),
547        }
548    }
549
550    /// Whether `id` names an entity this mem no longer holds. A STUB counts
551    /// as missing: a stub is the placeholder an unresolved wiki-link target
552    /// leaves behind, not an entity anyone wrote, so an anchor keyed to one
553    /// is dangling exactly as if nothing were there.
554    ///
555    /// Only meaningful once [`Self::entity_set_is_reconcilable`] says yes.
556    pub fn entity_is_absent(&self, id: &EntityId) -> bool {
557        self.store.get(id).is_none_or(|e| e.stub)
558    }
559
560    /// Mems whose lazy entity load is still DEFERRED — on the mount
561    /// roster with a resolved schema pin, but with no entities in the
562    /// store yet. Read surfaces that render per-mem counts or
563    /// distributions consult this: a count over a deferred mem's slice
564    /// of the store is a count over nothing, and rendering it as a
565    /// bare zero is the silent absence the lazy-mount contract forbids.
566    /// Either trigger the load ([`Self::ensure_mems_loaded`]) or render
567    /// the load state explicitly.
568    pub fn deferred_mems(&self) -> Vec<&str> {
569        self.mounts
570            .iter()
571            .filter(|m| m.deferred)
572            .map(|m| m.mount.mem.as_str())
573            .collect()
574    }
575
576    /// Whether `mem` is a lazy mount whose entity load has not run yet.
577    pub fn mem_is_deferred(&self, mem: &str) -> bool {
578        self.mounts.iter().any(|m| m.deferred && m.mount.mem == mem)
579    }
580
581    /// The typed error for a mem name that did not resolve to a
582    /// serving mount: `MEM_QUARANTINED` (carrying the underlying boot
583    /// failure and its repair command) when the mem is on the
584    /// quarantine roster, `UNKNOWN_MEM` otherwise. Every lookup site
585    /// that fails to find a mem routes here so a quarantined mem is
586    /// never misreported as unknown — honest absence, with the reason.
587    /// Resolve an entity id that may lack its mem prefix — the one
588    /// rule every id-taking mutation verb applies before it reads the
589    /// id's mem. A full id (`mem--slug`) returns unchanged with no
590    /// hint, byte for byte the path it always took. A bare slug is
591    /// looked up across every mounted mem (loading deferred mems
592    /// first, so a lazily mounted carrier is not invisible): exactly
593    /// one carrier resolves the id and returns the
594    /// [`crate::ops::WarningHint::ShortIdResolved`] announcement the
595    /// verb rides on its outcome; zero or several carriers refuse
596    /// [`EngineError::EntityIdMissingMem`] naming every candidate.
597    /// Before this rule a bare slug reached the verbs as an id whose
598    /// mem was the empty string, and the caller was told a mem called
599    /// "" did not exist (B7 grader finding, 2026-09-02).
600    pub fn resolve_entity_id(
601        &mut self,
602        id: &EntityId,
603    ) -> Result<(EntityId, Option<crate::ops::WarningHint>), EngineError> {
604        if !id.mem().is_empty() {
605            return Ok((id.clone(), None));
606        }
607        // Grammar before resolution: a malformed bare string is an
608        // invalid id, not a slug nobody carries.
609        let slug = id.0.as_str();
610        if let Err(reason) = crate::entity::id::validate_id_path_grammar(slug) {
611            return Err(EngineError::InvalidEntityId {
612                id: id.0.clone(),
613                reason,
614            });
615        }
616        self.ensure_mems_loaded(None);
617        let mut candidates: Vec<EntityId> = self
618            .store
619            .all_entities()
620            .filter(|e| !e.stub && e.id.path() == slug)
621            .map(|e| e.id.clone())
622            .collect();
623        candidates.sort_by(|a, b| a.0.cmp(&b.0));
624        candidates.dedup();
625        if candidates.len() == 1 {
626            let resolved = candidates.remove(0);
627            let hint = crate::ops::WarningHint::ShortIdResolved {
628                given: id.0.clone(),
629                resolved: resolved.clone(),
630            };
631            return Ok((resolved, Some(hint)));
632        }
633        Err(EngineError::EntityIdMissingMem {
634            id: id.0.clone(),
635            candidates: candidates.into_iter().map(|c| c.0).collect(),
636        })
637    }
638
639    pub fn unknown_mem_error(&self, mem: &str) -> EngineError {
640        match self.quarantine_reason(mem) {
641            Some(q) => EngineError::MemQuarantined {
642                mem: mem.to_string(),
643                reason_code: q.reason_code.clone(),
644                reason_message: q.reason_message.clone(),
645            },
646            None if self.recently_unmounted(mem) => EngineError::MemUnmounted {
647                mem: mem.to_string(),
648            },
649            None => EngineError::UnknownMem(mem.to_string()),
650        }
651    }
652
653    /// The workspace-level boot diagnosis a diagnostic-shell engine
654    /// carries (`None` on ordinarily booted engines).
655    pub fn boot_diagnosis(&self) -> Option<(&str, &str)> {
656        self.boot_diagnosis
657            .as_ref()
658            .map(|(c, m)| (c.as_str(), m.as_str()))
659    }
660
661    /// Build a mem-less diagnostic-shell engine for a workspace whose
662    /// boot failed at the WORKSPACE level (nothing loadable — e.g. an
663    /// unparseable store). It serves no mems and no entities; its one
664    /// job is answering overview/health with the typed boot diagnosis
665    /// so a session can always ask WHY the graph is gone — the MCP
666    /// server serves this instead of exiting into `-32000 Connection
667    /// closed` (degrade, never disappear).
668    pub fn diagnostic_shell(reason_code: String, reason_message: String) -> Engine {
669        let mut engine =
670            Engine::from_mounts(Vec::new()).expect("an empty mount list always constructs");
671        engine.boot_diagnosis = Some((reason_code, reason_message));
672        engine
673    }
674
675    /// Append boot-path quarantine entries recorded outside
676    /// `from_mounts_inner` (backend-instantiation failures happen
677    /// before the mount list reaches the engine constructor). Boot
678    /// paths only — quarantine is a boot judgment, never a runtime
679    /// mutation.
680    pub fn extend_quarantine(&mut self, entries: Vec<crate::engine::QuarantinedMem>) {
681        self.quarantined.extend(entries);
682    }
683
684    // ---------------------------------------------------------------
685    // Read-side delegates onto the kernel ops/graph functions.
686    //
687    // The mem-router engine exposed each of these directly so the
688    // MCP layer could call them without reaching into the store. The
689    // unified engine mirrors that surface so the MCP migration is a
690    // straight rename rather than a re-architecture.
691    //
692    // Multi-mem cache strategy: per-mem community detection and
693    // per-mem search indexes are unnecessary at this layer — the
694    // engine-wide store already carries every mount's edges; Louvain
695    // and tantivy run once across the union. `mem_schemas` for
696    // health/search is the engine's existing `schemas` field as-is.
697    // ---------------------------------------------------------------
698}