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    /// The index of `mem`'s attached mount, for the crate's own writers.
120    pub(crate) fn mounts_index_of(&self, mem: &str) -> Option<usize> {
121        self.mounts.iter().position(|m| m.mount.mem == mem)
122    }
123
124    pub fn mount(&self, mem: &str) -> Option<&crate::workspace::Mount> {
125        self.mounts
126            .iter()
127            .find(|m| m.mount.mem == mem)
128            .map(|m| &m.mount)
129    }
130
131    /// Orphan count attributed to each mem's pinned schema, over the
132    /// given `orphan_ids` (the caller pre-filters them by any mem scope).
133    /// Lets a health surface show that ingest-mem isolates (orphans by
134    /// design) and code-mem debt land in different schema buckets rather
135    /// than one blended, misleading total. Mems with no settled pin
136    /// bucket under the empty string.
137    pub fn orphans_by_schema(
138        &self,
139        orphan_ids: &[EntityId],
140    ) -> std::collections::BTreeMap<String, usize> {
141        let mut by_schema = std::collections::BTreeMap::new();
142        for id in orphan_ids {
143            let schema = self
144                .store()
145                .get(id)
146                .and_then(|e| self.mount(&e.mem))
147                .and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
148                .unwrap_or_default();
149            *by_schema.entry(schema).or_insert(0) += 1;
150        }
151        by_schema
152    }
153
154    /// Community count attributed to each schema across `mems`: a cluster
155    /// counts toward every schema whose mems it touches, so these figures
156    /// can sum above the global community count — the same "touches"
157    /// semantic as the mem-scoped count. Per-schema dedup keeps a cluster
158    /// touching two mems of one schema from being counted twice.
159    pub fn communities_by_schema(
160        &self,
161        mems: &[String],
162    ) -> std::collections::BTreeMap<String, usize> {
163        let louvain = self.communities();
164        let mut buckets: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
165            std::collections::BTreeMap::new();
166        for name in mems {
167            let schema = self
168                .mount(name)
169                .and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
170                .unwrap_or_default();
171            let clusters = crate::graph::community::clusters_in_mem(self.store(), louvain, name);
172            buckets.entry(schema).or_default().extend(clusters);
173        }
174        buckets
175            .into_iter()
176            .map(|(schema, set)| (schema, set.len()))
177            .collect()
178    }
179
180    /// All mounts the engine knows about, in declaration order.
181    /// Counterpart to [`Self::mem_names`] when the caller needs
182    /// the full mount shape (e.g. to enumerate by storage variant).
183    pub fn mounts(&self) -> Vec<&crate::workspace::Mount> {
184        self.mounts.iter().map(|m| &m.mount).collect()
185    }
186
187    /// Names of mems whose mount declares
188    /// [`crate::workspace::MountCapability::Write`], in declaration
189    /// order. Convenience over `mounts().iter().filter(...).map(...)`
190    /// for handlers that gate by writable status (`memstead_health`,
191    /// `memstead_overview`'s mem roster, the lifecycle tools'
192    /// candidate list). Read-only mounts (archive backends) are
193    /// excluded.
194    pub fn writable_mem_names(&self) -> Vec<&str> {
195        self.mounts
196            .iter()
197            .filter(|m| m.mount.capability == MountCapability::Write)
198            .map(|m| m.mount.mem.as_str())
199            .collect()
200    }
201
202    /// The default writable mem — the target a mutation lands in when
203    /// it omits `mem`. `None` when no writable mem is mounted.
204    ///
205    /// Defined as the **first writable mount in declaration order**, i.e.
206    /// the seed / earliest-created writable mem. This is a *stable*
207    /// designation, not a function of the current name set: new mems
208    /// register via `register_writable_mem`, which pushes onto the end
209    /// of the mount list (and `mounts.json` preserves that order across
210    /// reboots), so creating an additional mem never moves the default
211    /// — even one whose name sorts ahead alphabetically. Deleting the
212    /// current default promotes the next-earliest writable mem; that is
213    /// the only thing that shifts it. Both the MCP `resolve_mem` and the
214    /// CLI's omitted-`--mem` path resolve through here so the two
215    /// surfaces always agree (the
216    /// pre-fix MCP path read `writable_mems().iter().next()` off an
217    /// unordered `HashSet`, which silently retargeted writes when a second
218    /// mem appeared).
219    /// The default writable mem for a call that names none, or the
220    /// engine's refusal when there is none.
221    pub fn default_writable_mem_or_refuse(&self) -> Result<String, EngineError> {
222        self.default_writable_mem()
223            .map(str::to_string)
224            .ok_or(EngineError::NoWritableMem)
225    }
226
227    /// The one writable mem, for a call that acts on exactly one: refused
228    /// when none or several are mounted.
229    pub fn sole_writable_mem(&self) -> Result<String, EngineError> {
230        // Every mount, not only those with a readable config: counting only
231        // config-readable mems could report exactly one writable mem while a
232        // second, broken one exists, and act on the wrong one.
233        let mut writable: Vec<String> = self
234            .mounts_with_optional_config()
235            .filter(|(name, _)| self.mem_router().is_writable(name))
236            .map(|(name, _)| name.to_string())
237            .collect();
238        match writable.len() {
239            0 => Err(EngineError::NoWritableMem),
240            1 => Ok(writable.remove(0)),
241            _ => Err(EngineError::AmbiguousMem { mems: writable }),
242        }
243    }
244
245    pub fn default_writable_mem(&self) -> Option<&str> {
246        self.mounts
247            .iter()
248            .find(|m| m.mount.capability == MountCapability::Write)
249            .map(|m| m.mount.mem.as_str())
250    }
251
252    /// On-disk folder path for a folder-backed mount, or `None` for
253    /// any other backend (git-branch, archive) or unknown mem.
254    /// Convenience over `engine.mount(mem).map(|m| &m.storage)` +
255    /// matching on `MountStorage::Folder { path }`. Used by
256    /// handlers that need a filesystem path for a folder mem
257    /// (e.g. `memstead_health { include_config: true }`'s
258    /// `mems[].vcs.worktree` field for folder mounts).
259    pub fn folder_path_for_mem(&self, mem: &str) -> Option<&Path> {
260        match self.mount(mem).map(|m| &m.storage) {
261            Some(crate::workspace::MountStorage::Folder { path }) => Some(path.as_path()),
262            _ => None,
263        }
264    }
265
266    /// Runtime snapshot of writable / visible mems. Handlers that
267    /// need the writable roster (`memstead_health`'s `writable_mems` /
268    /// `read_mems`), per-mem origin tag (`include_config:
269    /// true`'s `mems[].origin`), or visibility check
270    /// (`memstead_overview`'s mem list, the lifecycle tools' collision
271    /// guard) consume the router here. Returned by reference — the
272    /// `Arc` is held on the engine; callers that need a clonable
273    /// handle can `Arc::clone` the engine's field directly when that
274    /// surface arrives.
275    pub fn mem_router(&self) -> &MemRouterSnapshot {
276        &self.mem_router
277    }
278
279    /// Resolve the gitdir for a writable mem. Used by `memstead_health
280    /// { include_config: true }` to surface per-mem `vcs.gitdir`
281    /// so outer-repo bookkeeping clients can `git -C <gitdir>` per
282    /// mem without hardcoding the layout.
283    ///
284    /// - `EngineError::UnknownMem` when the name does not resolve.
285    /// - `EngineError::Mem` when the mount's storage is not
286    ///   git-branch-backed (folder, archive — they have no gitdir).
287    pub fn gitdir_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
288        let m = self
289            .mount(mem_name)
290            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
291        match &m.storage {
292            MountStorage::GitBranch { gitdir, .. } => Ok(gitdir.clone()),
293            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
294                Err(EngineError::Mem(format!(
295                    "mem '{mem_name}' has no resolved gitdir"
296                )))
297            }
298        }
299    }
300
301    /// Resolve the worktree for a writable mem. Used by
302    /// `memstead_health { include_config: true }` to surface per-mem
303    /// `vcs.worktree`.
304    ///
305    /// - `EngineError::UnknownMem` when the name does not resolve.
306    /// - `EngineError::Mem` when the mount's backend has no
307    ///   worktree concept (git-branch with no working tree, archive).
308    ///
309    /// Folder mounts surface their on-disk path. Git-branch mounts
310    /// follow the `dir: Some(...)` composition pattern: when the
311    /// workspace root contains a folder named after the mem with a
312    /// `.memstead/config.json` marker, that folder is the worktree
313    /// (disk-shape composition). Otherwise — pure mem-repo-backed
314    /// — return Err.
315    pub fn worktree_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
316        let m = self
317            .mount(mem_name)
318            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
319        match &m.storage {
320            MountStorage::Folder { path } => Ok(path.clone()),
321            MountStorage::GitBranch { .. } => {
322                if let Some(root) = self.workspace_root.as_deref() {
323                    let candidate = root.join(mem_name);
324                    if candidate
325                        .join(crate::mem::MEM_META_DIR)
326                        .join("config.json")
327                        .is_file()
328                    {
329                        return Ok(candidate.canonicalize().unwrap_or(candidate));
330                    }
331                }
332                Err(EngineError::Mem(format!(
333                    "mem '{mem_name}' has no working tree (mem-repo-backed)"
334                )))
335            }
336            MountStorage::Archive { .. } => Err(EngineError::Mem(format!(
337                "mem '{mem_name}' is archive-backed and has no worktree"
338            ))),
339            MountStorage::InMemory => Err(EngineError::Mem(format!(
340                "mem '{mem_name}' is in-memory and has no worktree"
341            ))),
342        }
343    }
344
345    /// Per-mem `.memstead/config.json` payload, when available. Used
346    /// by `memstead_health { include_config: true }` to surface the
347    /// opaque `write_guidance` map and the catch-all `extra` fields
348    /// per mem.
349    ///
350    /// Folder-backed mounts return `Some(&MemConfig)` when
351    /// `<path>/.memstead/config.json` parsed cleanly at construction.
352    /// Git-branch and archive backends return `None` until the
353    /// read-from-storage-backend path lifts (the V1 unified engine
354    /// loads configs only from folder layouts; the file lives
355    /// inside the gitdir / archive for the other backends and
356    /// needs a backend-level read primitive).
357    ///
358    /// Unknown mem names return `None` (no error variant — the
359    /// accessor is intentionally lenient because memstead_health emits
360    /// an empty detail block per missing config rather than
361    /// aborting the call).
362    pub fn mem_config_for(&self, mem: &str) -> Option<&memstead_schema::config::MemConfig> {
363        self.mounts
364            .iter()
365            .find(|m| m.mount.mem == mem)
366            .and_then(|m| m.mem_config.as_ref())
367    }
368
369    /// The authoring-provenance payload an installed mem carries, read
370    /// from the archive's `.memstead/provenance.json` at construction.
371    /// `None` when the mem carries none (a pre-provenance archive, a
372    /// runtime-created mem, or a backend that does not surface one) —
373    /// the read path reports provenance as absent. Unknown mem names
374    /// return `None`.
375    pub fn archive_provenance_for(&self, mem: &str) -> Option<&memstead_schema::ArchiveProvenance> {
376        self.mounts
377            .iter()
378            .find(|m| m.mount.mem == mem)
379            .and_then(|m| m.archive_provenance.as_ref())
380    }
381
382    /// The sealed check records an archive mount carries
383    /// (`.memstead/checks.json`), or `None` when the mount is not an
384    /// archive or the archive carries none. The only check-state source
385    /// an archive mount has: a workspace ledger beside the mount is never
386    /// consulted for it, and a writable mount never reads a sealed member.
387    pub fn archive_checks_for(&self, mem: &str) -> Option<&crate::check::SealedChecks> {
388        self.mounts
389            .iter()
390            .find(|m| m.mount.mem == mem)
391            .filter(|m| {
392                matches!(
393                    m.mount.storage,
394                    crate::workspace::MountStorage::Archive { .. }
395                )
396            })
397            .and_then(|m| m.archive_checks.as_ref())
398    }
399
400    /// Whether `mem` is mounted from a sealed archive.
401    pub fn is_archive_mount(&self, mem: &str) -> bool {
402        self.mounts.iter().any(|m| {
403            m.mount.mem == mem
404                && matches!(
405                    m.mount.storage,
406                    crate::workspace::MountStorage::Archive { .. }
407                )
408        })
409    }
410
411    /// Iterate `(mem_name, &MemConfig)` for every mount whose
412    /// mem-config payload loaded at construction. Used by callers
413    /// that walk every writable mount's config (`memstead health`'s
414    /// per-mem dump, the workspace-dump CLI). The yielded `&str` is
415    /// the authoritative mem leaf from the mount record.
416    ///
417    /// Folder-backed mounts yield when their `.memstead/config.json`
418    /// parsed cleanly. Git-branch and archive backends are silent in
419    /// V1 (the same deferred-read-from-storage gap that
420    /// [`Self::mem_config_for`] documents).
421    pub fn mem_configs_named(
422        &self,
423    ) -> impl Iterator<Item = (&str, &memstead_schema::config::MemConfig)> {
424        self.mounts
425            .iter()
426            .filter_map(|m| m.mem_config.as_ref().map(|c| (m.mount.mem.as_str(), c)))
427    }
428
429    /// Every configured mount, with its config when one was readable.
430    ///
431    /// The counterpart to [`Self::mem_configs_named`], whose contract is "mems
432    /// WITH config" and which is therefore right to omit the rest. The trouble
433    /// was that callers wanting to enumerate mounts reached for it anyway: a
434    /// folder mount whose directory is gone returns no config rather than an
435    /// error, boot stores none, and the mount became invisible to every one of
436    /// them. Nine call sites shared that blind spot, and the omission was a
437    /// side effect of config readability rather than anything about the mount.
438    ///
439    /// Callers that genuinely want only configured mems keep using the other
440    /// one; drivers that want every mount ask for every mount.
441    pub fn mounts_with_optional_config(
442        &self,
443    ) -> impl Iterator<Item = (&str, Option<&memstead_schema::config::MemConfig>)> {
444        self.mounts
445            .iter()
446            .map(|m| (m.mount.mem.as_str(), m.mem_config.as_ref()))
447    }
448
449    /// Resolved `Arc<Schema>` for a writable mem by name. `None`
450    /// when the name is not a registered mount.
451    ///
452    /// Cheap — `Arc::clone` over the per-mem schema map. Resolved
453    /// schemas are stored in `HashMap<String, Arc<Schema>>` so the
454    /// lookup is a single hash hit + clone.
455    pub fn schema_for(&self, mem: &str) -> Option<std::sync::Arc<memstead_schema::Schema>> {
456        self.schemas.get(mem).cloned()
457    }
458
459    /// The resolved schema of `mem`, or the engine's refusal naming why
460    /// there is none: an unknown mem refuses `UNKNOWN_MEM`, a mem held out
461    /// of service at boot (an unresolvable pin among the reasons) refuses
462    /// `MEM_QUARANTINED` with its reason, and a mounted mem whose pin does
463    /// not resolve refuses `SCHEMA_NOT_FOUND` with the per-source
464    /// diagnostics. The one answer every surface renders for "this mem's
465    /// schema", so none builds the refusal by hand.
466    pub fn resolved_schema(
467        &self,
468        mem: &str,
469    ) -> Result<std::sync::Arc<memstead_schema::Schema>, EngineError> {
470        if let Some(schema) = self.schemas.get(mem) {
471            return Ok(schema.clone());
472        }
473        let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
474            return Err(self.unknown_mem_error(mem));
475        };
476        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
477            .workspace_schemas
478            .iter()
479            .cloned()
480            .chain(self.builtin_schemas.iter().cloned())
481            .collect();
482        let pin = m
483            .mem_config
484            .as_ref()
485            .and_then(|c| c.schema.clone())
486            .or_else(|| m.mount.schema.clone());
487        let (pin_display, sources) = match &pin {
488            Some(pin) => (
489                pin.as_display(),
490                crate::engine::SchemaResolver::new(&catalogue)
491                    .resolve(pin)
492                    .err()
493                    .unwrap_or_default(),
494            ),
495            None => ("<no schema pin>".to_string(), Vec::new()),
496        };
497        Err(EngineError::SchemaNotFound {
498            mem: mem.to_string(),
499            pin: pin_display,
500            sources,
501            install_hint: None,
502        }
503        .with_schema_install_probe(self.workspace_root()))
504    }
505
506    /// Cached current branch-tip cursor (typically a 40-char hex
507    /// SHA for git-branch backends; `None` for fresh mems or
508    /// backends that don't track a head — folder / archive).
509    ///
510    /// The value is the per-mount `last_known_head`, seeded at
511    /// construction by `backend.current_head()` and refreshed by
512    /// [`Self::reload_if_stale`] / mutation paths after a
513    /// successful commit.
514    ///
515    /// - `EngineError::UnknownMem` when the name does not resolve.
516    pub fn mem_head_sha(&self, mem_name: &str) -> Result<Option<String>, EngineError> {
517        let m = self
518            .mounts
519            .iter()
520            .find(|m| m.mount.mem == mem_name)
521            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
522        Ok(m.last_known_head.clone())
523    }
524
525    /// Whether a sibling writer has advanced this mem's backend past
526    /// the engine's cached `last_known_head` — a read-only drift probe
527    /// that does **not** reload (unlike [`Self::reload_if_stale`]). One
528    /// `backend.current_head()` read compared against the cached cursor;
529    /// the comparison clears once the engine re-reads (a `reload` /
530    /// `reload_if_stale` refreshes `last_known_head` to the live tip).
531    ///
532    /// Only git-branch backends track a head, so folder / archive /
533    /// in-memory mounts always report `false`. A backend that errors on
534    /// the probe (transient refdb hiccup) reports `false` rather than
535    /// surfacing the error — drift is advisory, and the next real
536    /// operation's reload path is the authoritative sync.
537    ///
538    /// - `EngineError::UnknownMem` when the name does not resolve.
539    pub fn mem_drifted(&self, mem_name: &str) -> Result<bool, EngineError> {
540        let m = self
541            .mounts
542            .iter()
543            .find(|m| m.mount.mem == mem_name)
544            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
545        let live = m.backend.current_head().ok().flatten();
546        Ok(live != m.last_known_head)
547    }
548
549    /// Workspace root the engine booted from, when one is known.
550    /// `None` for engines built directly from a mount list (tests,
551    /// ad-hoc consumers). Set by [`Self::from_workspace_root`] and
552    /// the full counterpart.
553    pub fn workspace_root(&self) -> Option<&Path> {
554        self.workspace_root.as_deref()
555    }
556
557    /// Typed warnings surfaced during mem load — drift findings
558    /// the loader pipeline collects per entity. Empty for V1; the
559    /// accessor surfaces them so handlers can merge into health
560    /// summaries uniformly.
561    pub fn load_warnings(&self) -> &[WarningHint] {
562        &self.load_warnings
563    }
564
565    /// Every `MOUNT_UNBACKED` warning as of now: the stored ones (the
566    /// storage the mount names is missing, a fact of the mount) and an
567    /// `empty` one for each loaded mount whose mem holds no entity in the
568    /// live store. The empty reason is derived here, never stored, so a
569    /// mem written into after its mount is not called empty.
570    pub fn unbacked_mount_warnings(&self) -> Vec<WarningHint> {
571        let mut out: Vec<WarningHint> = self
572            .load_warnings
573            .iter()
574            .filter(|w| w.code() == "MOUNT_UNBACKED")
575            .cloned()
576            .collect();
577        let deferred = self.deferred_mems();
578        for m in &self.mounts {
579            let mem = m.mount.mem.as_str();
580            if deferred.contains(&mem)
581                || out.iter().any(|w| w.source_mem() == Some(mem))
582                || self.store.all_entities().any(|e| e.mem == mem && !e.stub)
583            {
584                continue;
585            }
586            let location = match &m.mount.storage {
587                crate::workspace::MountStorage::GitBranch { branch, .. } => branch.clone(),
588                crate::workspace::MountStorage::Folder { path }
589                | crate::workspace::MountStorage::Archive { path } => path.display().to_string(),
590                crate::workspace::MountStorage::InMemory => continue,
591            };
592            out.push(WarningHint::MountUnbacked {
593                mem: mem.to_string(),
594                reason: crate::ops::MountUnbackedReason::Empty,
595                location,
596            });
597        }
598        out
599    }
600
601    /// The quarantine roster: mems that failed their mem-level boot
602    /// step and serve nothing until repaired + reloaded. Empty on a
603    /// fully healthy workspace. Surfaced on overview and health.
604    pub fn quarantined_mems(&self) -> &[crate::engine::QuarantinedMem] {
605        &self.quarantined
606    }
607
608    /// The quarantine entry for `mem`, when it is quarantined.
609    pub fn quarantine_reason(&self, mem: &str) -> Option<&crate::engine::QuarantinedMem> {
610        self.quarantined.iter().find(|q| q.mount.mem == mem)
611    }
612
613    /// Whether the store's entity set for `mem` can be trusted to answer the
614    /// question "does this entity still exist?".
615    ///
616    /// WHY this is a question and not an assumption: an anchor sidecar is
617    /// keyed by entity id, and a key with no entity behind it is a dangling
618    /// row. Detecting one means reading a NEGATIVE
619    /// from the store, and a negative is only evidence when the store is known
620    /// to hold everything the mem has. Four states break that, and each of
621    /// them would otherwise turn every anchor in the mem into a false dangling
622    /// report: the mem is not mounted at all, it is quarantined (serving
623    /// nothing), its lazy load has not run yet (mounted, entities absent), or
624    /// a file in it failed to parse, in which case an id missing from the
625    /// store may be a load failure rather than a deleted entity.
626    ///
627    /// The last case is deliberately COARSE for non-folder mounts: load-error
628    /// paths are normalized to absolute only for folder mounts, so a
629    /// git-branch mem's errors carry mem-relative paths that two mems can
630    /// spell identically. Attributing them by name would be a guess, and a
631    /// wrong guess here fabricates dangling rows. Any load error at all
632    /// therefore blocks reconciliation for a non-folder mem. The caller states
633    /// the block rather than skipping silently, which is the honest direction.
634    pub fn entity_set_is_reconcilable(&self, mem: &str) -> Result<(), &'static str> {
635        if self.quarantine_reason(mem).is_some() {
636            return Err("the mem is quarantined and serves no entities");
637        }
638        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
639            return Err("the mem is not mounted here");
640        };
641        if mount.deferred {
642            return Err("the mem's lazy entity load has not run this session");
643        }
644        if self.load_errors.is_empty() {
645            return Ok(());
646        }
647        match &mount.mount.storage {
648            crate::workspace::MountStorage::Folder { path } => {
649                if self.load_errors.iter().any(|(p, _)| p.starts_with(path)) {
650                    Err(
651                        "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",
652                    )
653                } else {
654                    Ok(())
655                }
656            }
657            _ => Err(
658                "this workspace has files that failed to parse, and their paths cannot be attributed to one mem",
659            ),
660        }
661    }
662
663    /// Whether `id` names an entity this mem no longer holds. A STUB counts
664    /// as missing: a stub is the placeholder an unresolved wiki-link target
665    /// leaves behind, not an entity anyone wrote, so an anchor keyed to one
666    /// is dangling exactly as if nothing were there.
667    ///
668    /// Only meaningful once [`Self::entity_set_is_reconcilable`] says yes.
669    pub fn entity_is_absent(&self, id: &EntityId) -> bool {
670        self.store.get(id).is_none_or(|e| e.stub)
671    }
672
673    /// Mems whose lazy entity load is still DEFERRED — on the mount
674    /// roster with a resolved schema pin, but with no entities in the
675    /// store yet. Read surfaces that render per-mem counts or
676    /// distributions consult this: a count over a deferred mem's slice
677    /// of the store is a count over nothing, and rendering it as a
678    /// bare zero is the silent absence the lazy-mount contract forbids.
679    /// Either trigger the load ([`Self::ensure_mems_loaded`]) or render
680    /// the load state explicitly.
681    pub fn deferred_mems(&self) -> Vec<&str> {
682        self.mounts
683            .iter()
684            .filter(|m| m.deferred)
685            .map(|m| m.mount.mem.as_str())
686            .collect()
687    }
688
689    /// Whether `mem` is a lazy mount whose entity load has not run yet.
690    pub fn mem_is_deferred(&self, mem: &str) -> bool {
691        self.mounts.iter().any(|m| m.deferred && m.mount.mem == mem)
692    }
693
694    /// The typed error for a mem name that did not resolve to a
695    /// serving mount: `MEM_QUARANTINED` (carrying the underlying boot
696    /// failure and its repair command) when the mem is on the
697    /// quarantine roster, `UNKNOWN_MEM` otherwise. Every lookup site
698    /// that fails to find a mem routes here so a quarantined mem is
699    /// never misreported as unknown — honest absence, with the reason.
700    /// Resolve an entity id that may lack its mem prefix — the one
701    /// rule every id-taking mutation verb applies before it reads the
702    /// id's mem. A full id (`mem--slug`) returns unchanged with no
703    /// hint, byte for byte the path it always took. A bare slug is
704    /// looked up across every mounted mem (loading deferred mems
705    /// first, so a lazily mounted carrier is not invisible): exactly
706    /// one carrier resolves the id and returns the
707    /// [`crate::ops::WarningHint::ShortIdResolved`] announcement the
708    /// verb rides on its outcome; zero or several carriers refuse
709    /// [`EngineError::EntityIdMissingMem`] naming every candidate.
710    /// Before this rule a bare slug reached the verbs as an id whose
711    /// mem was the empty string, and the caller was told a mem called
712    /// "" did not exist.
713    pub fn resolve_entity_id(
714        &mut self,
715        id: &EntityId,
716    ) -> Result<(EntityId, Option<crate::ops::WarningHint>), EngineError> {
717        if !id.mem().is_empty() {
718            return Ok((id.clone(), None));
719        }
720        // Grammar before resolution: a malformed bare string is an
721        // invalid id, not a slug nobody carries.
722        let slug = id.0.as_str();
723        if let Err(reason) = crate::entity::id::validate_id_path_grammar(slug) {
724            return Err(EngineError::InvalidEntityId {
725                id: id.0.clone(),
726                reason,
727            });
728        }
729        self.ensure_mems_loaded(None);
730        let mut candidates: Vec<EntityId> = self
731            .store
732            .all_entities()
733            .filter(|e| !e.stub && e.id.path() == slug)
734            .map(|e| e.id.clone())
735            .collect();
736        candidates.sort_by(|a, b| a.0.cmp(&b.0));
737        candidates.dedup();
738        if candidates.len() == 1 {
739            let resolved = candidates.remove(0);
740            let hint = crate::ops::WarningHint::ShortIdResolved {
741                given: id.0.clone(),
742                resolved: resolved.clone(),
743            };
744            return Ok((resolved, Some(hint)));
745        }
746        Err(EngineError::EntityIdMissingMem {
747            id: id.0.clone(),
748            candidates: candidates.into_iter().map(|c| c.0).collect(),
749        })
750    }
751
752    pub fn unknown_mem_error(&self, mem: &str) -> EngineError {
753        match self.quarantine_reason(mem) {
754            Some(q) => EngineError::MemQuarantined {
755                mem: mem.to_string(),
756                reason_code: q.reason_code.clone(),
757                reason_message: q.reason_message.clone(),
758            },
759            None if self.recently_unmounted(mem) => EngineError::MemUnmounted {
760                mem: mem.to_string(),
761            },
762            None => self.unknown_mem(mem),
763        }
764    }
765
766    /// The workspace-level boot diagnosis a diagnostic-shell engine
767    /// carries (`None` on ordinarily booted engines).
768    pub fn boot_diagnosis(&self) -> Option<(&str, &str)> {
769        self.boot_diagnosis
770            .as_ref()
771            .map(|(c, m)| (c.as_str(), m.as_str()))
772    }
773
774    /// Build a mem-less diagnostic-shell engine for a workspace whose
775    /// boot failed at the WORKSPACE level (nothing loadable — e.g. an
776    /// unparseable store). It serves no mems and no entities; its one
777    /// job is answering overview/health with the typed boot diagnosis
778    /// so a session can always ask WHY the graph is gone — the MCP
779    /// server serves this instead of exiting into `-32000 Connection
780    /// closed` (degrade, never disappear).
781    pub fn diagnostic_shell(reason_code: String, reason_message: String) -> Engine {
782        let mut engine =
783            Engine::from_mounts(Vec::new()).expect("an empty mount list always constructs");
784        engine.boot_diagnosis = Some((reason_code, reason_message));
785        engine
786    }
787
788    /// Append boot-path quarantine entries recorded outside
789    /// `from_mounts_inner` (backend-instantiation failures happen
790    /// before the mount list reaches the engine constructor). Boot
791    /// paths only — quarantine is a boot judgment, never a runtime
792    /// mutation.
793    pub fn extend_quarantine(&mut self, entries: Vec<crate::engine::QuarantinedMem>) {
794        self.quarantined.extend(entries);
795    }
796
797    // ---------------------------------------------------------------
798    // Read-side delegates onto the kernel ops/graph functions.
799    //
800    // The mem-router engine exposed each of these directly so the
801    // MCP layer could call them without reaching into the store. The
802    // unified engine mirrors that surface so the MCP migration is a
803    // straight rename rather than a re-architecture.
804    //
805    // Multi-mem cache strategy: per-mem community detection and
806    // per-mem search indexes are unnecessary at this layer — the
807    // engine-wide store already carries every mount's edges; Louvain
808    // and tantivy run once across the union. `mem_schemas` for
809    // health/search is the engine's existing `schemas` field as-is.
810    // ---------------------------------------------------------------
811}