Skip to main content

memstead_base/engine/
query.rs

1//! Engine read paths — accessors and queries.
2//!
3//! Read-only methods on `Engine`: store / schema / mount accessors,
4//! per-mem path helpers (`gitdir_for` / `worktree_for`), aggregated
5//! views (`communities`, `orphans`, `stubs`, `most_connected`,
6//! `missing_required_outgoing`), per-mem summaries (`health`,
7//! `status`, `context`), search (`list`, `search`,
8//! `search_indexes`), and the bytes-level read wrappers
9//! (`list_entities`, `read_entity`, `read_provenance`). Capability and
10//! cross-mem link gating live here too — they're consulted by
11//! handlers before any mutation reaches the backend.
12
13use std::cell::OnceCell;
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use memstead_schema::Schema;
19
20use crate::engine_fallback_type;
21use crate::entity::{Entity, EntityId};
22use crate::graph::{LouvainOutput, community::detect_communities};
23use crate::mem::MemRouterSnapshot;
24use crate::ops::{ContextResult, Direction, NeighborInfo, SearchResult, SearchScope, WarningHint};
25use crate::provenance::Provenance;
26#[cfg(not(target_arch = "wasm32"))]
27use crate::search_index::{MemIndex, build_all};
28use crate::store::Store;
29use crate::workspace::{MountCapability, MountStorage, WorkspaceSettings};
30
31use super::{BackendFactory, Engine, EngineError, MountedBackend};
32
33impl Engine {
34    /// In-memory store populated at construction time from every
35    /// mount's backend. Read-only at this point in the rebuild —
36    /// mutation paths land in a later session.
37    pub fn store(&self) -> &Store {
38        &self.store
39    }
40
41    /// Per-mem schema, keyed by mount's mem name. Each entry is the
42    /// schema resolved from that mount's pin at boot, so the map holds
43    /// genuinely heterogeneous schemas in a multi-schema workspace.
44    pub fn schemas(&self) -> &HashMap<String, Arc<Schema>> {
45        &self.schemas
46    }
47
48    /// Workspace-authored schemas loaded from
49    /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
50    /// [`Self::schemas`] (per-mem, only schemas pinned by a mount):
51    /// this slice carries every workspace-loaded schema regardless of
52    /// whether a mem pins it. Used by `memstead_overview` to enumerate
53    /// schemas referenced by `mem_create_rules.schemas[]` but not
54    /// pinned by any mem — agents see what could be pinned without
55    /// looking up the workspace.toml directly.
56    pub fn workspace_schemas(&self) -> &[Arc<Schema>] {
57        &self.workspace_schemas
58    }
59
60    /// Embedded built-in schemas loaded once at boot. Handlers
61    /// resolving a schema pin by `<name>@<version>` (MCP's `memstead_schema`,
62    /// `memstead_overview` rendering) walk mem-pinned, workspace, and
63    /// built-in catalogues in order — built-ins are the catch-all when
64    /// no mem or workspace dir pins the schema. Workspace schemas
65    /// shadow built-ins on `(name, version)` collision; resolve from
66    /// `workspace_schemas()` first.
67    pub fn builtin_schemas(&self) -> &[Arc<Schema>] {
68        &self.builtin_schemas
69    }
70
71    /// Classify a schema's trust origin — the single authority every read
72    /// surface consults before serving a schema's instruction-prose.
73    ///
74    /// A schema is [`OriginClass::FirstParty`] iff it is an engine built-in
75    /// **or** pinned by a writable mount in this workspace. Built-ins are
76    /// compiled into the binary — unforgeable. A non-built-in schema earns
77    /// first-party status only once the operator *adopts* it by writably
78    /// mounting a mem that pins it: writing into a mem is the act that
79    /// legitimately needs a schema's authoring prose (`system_message`,
80    /// `write_rules`, …), and the mount's writable posture is set by the
81    /// consumer's own config — a publisher cannot forge it.
82    ///
83    /// Everything else is [`OriginClass::ThirdParty`]: a schema present in
84    /// the catalogue but pinned only by read-only mounts (a registry-
85    /// installed read-mem or an adopted foreign folder/clone), or one the
86    /// engine cannot vouch for at all. Its prose is served structural-only
87    /// so a stranger's free-text never reaches a consuming agent as
88    /// instructions. This classifies by the mount graph — never by scanning
89    /// the schema's content, which a publisher controls — and `ThirdParty`
90    /// is the safe default for any ambiguous origin.
91    ///
92    /// Note a read-only mount pinning a *built-in* schema (e.g. a registry
93    /// mem on `default@1.0.0`) resolves to the consumer's own clean copy
94    /// and stays first-party — the de-framing targets only foreign,
95    /// non-built-in schemas that no writable mem has adopted.
96    pub fn schema_origin(&self, schema: &Arc<Schema>) -> crate::render::OriginClass {
97        use crate::render::OriginClass;
98        let (name, version) = schema.id();
99        // Built-in schemas are compiled in — first-party, unforgeable.
100        let is_builtin = self.builtin_schemas.iter().any(|s| {
101            let id = s.id();
102            id.0 == name && id.1 == version
103        });
104        if is_builtin {
105            return OriginClass::FirstParty;
106        }
107        // Adoption signal: some writable mount pins this exact schema, so
108        // the operator authors against it here.
109        let canon = format!("{name}@{version}");
110        let pinned_by_writable = self.mounts().iter().any(|m| {
111            m.schema.as_ref().map(|s| s.to_string()).as_deref() == Some(canon.as_str())
112                && self.mem_router().is_writable(&m.mem)
113        });
114        if pinned_by_writable {
115            OriginClass::FirstParty
116        } else {
117            OriginClass::ThirdParty
118        }
119    }
120
121    /// Classify a mem's *data* trust origin — the authority every read
122    /// surface consults before serving an entity's content (bodies,
123    /// snippets, titles). A writable mount is [`OriginClass::FirstParty`]:
124    /// its content is authored in this workspace. Anything else — a
125    /// read-only mount (a registry-installed read-mem or an adopted
126    /// foreign folder/clone) or an unknown mem — is
127    /// [`OriginClass::ThirdParty`], so the consuming agent/host treats the
128    /// content as quoted, untrusted data.
129    ///
130    /// This reads the deployment's declaration when one exists (see
131    /// [`Self::declare_mem_origin`]), else the mount's already-decided
132    /// writable/read-only posture (fixed at adopt/mount time) — it never
133    /// scans content, and both levers are consumer-side config, so a
134    /// publisher cannot forge first-party. Distinct from
135    /// [`Self::schema_origin`], which governs a schema's
136    /// instruction-prose: the data channel and the instruction channel
137    /// are separate vectors with separate authorities.
138    pub fn mem_origin_class(&self, mem: &str) -> crate::render::OriginClass {
139        if let Some(declared) = self.declared_origins.get(mem) {
140            return *declared;
141        }
142        if self.mem_router().is_writable(mem) {
143            crate::render::OriginClass::FirstParty
144        } else {
145            crate::render::OriginClass::ThirdParty
146        }
147    }
148
149    /// Classify ONE ENTITY's data trust origin — the grain a read surface
150    /// labels, and the grain a host quarantines at.
151    ///
152    /// [`Self::mem_origin_class`] answers for the whole mem, which is the
153    /// answer for every entity of a read-only mount. It is not the answer
154    /// inside a WRITABLE mem that accepts contributions: a body merged
155    /// from a fork is a stranger's prose sitting in a mem classified
156    /// first-party, and served undifferentiated it reads to an agent as
157    /// part of the document it was told to trust. This narrows that case
158    /// and nothing else:
159    ///
160    /// - the mem is third-party → third-party (unchanged);
161    /// - the mem's proposal record does not parse → third-party for every
162    ///   entity of that mem, because the record is the only evidence of
163    ///   which bodies are a contributor's, and a trust label may not fail
164    ///   open on a file it could not read;
165    /// - the entity's slug carries marks and any marked section still
166    ///   hashes to its recorded value → third-party, because that section
167    ///   is still the proposer's bytes;
168    /// - anything else → the mem's class.
169    ///
170    /// The lookup is by slug and nothing else. A rename or a re-keying
171    /// retype follows the marks in the mutation's own commit
172    /// ([`crate::engine::mutation::stage_proposal_marks_rename`],
173    /// [`crate::engine::mutation::stage_proposal_marks_retype`]), so this
174    /// path never has to guess. Inferring a moved body from matching
175    /// content across slugs was tried and removed: a type whose
176    /// load-bearing set is one section (many are) turns the guess into a
177    /// one-line coincidence, so an owner's own entity sharing a single
178    /// section with an adopted body was branded a stranger's, and a
179    /// contributor could aim that by adopting a copy of it.
180    ///
181    /// Per marked section rather than one hash over the whole body, so an
182    /// owner who rewrites one of three load-bearing sections does not
183    /// launder the two the contributor wrote, and so the comparison needs
184    /// neither the schema pin nor the entity type: a repin or a retype
185    /// changes which sections a type calls load-bearing, and a comparison
186    /// that depended on the current declaration would report a rewrite
187    /// that never happened.
188    ///
189    /// The classification stays decided-at-write-time: the deciding act is
190    /// the merge, which records the marks under the owner's own identity on
191    /// the target branch, and the read only checks whether what was decided
192    /// still describes the bytes. Content is read to see whether a mark
193    /// still holds, never to award a class: all the content can do is DROP
194    /// the third-party label by no longer matching, and only the owner can
195    /// write it. The caller-declared `Identity:` trailer is never consulted
196    /// — a contributor who wrote the body also chooses that string, so
197    /// trust derived from it would be trust they grant themselves.
198    ///
199    /// The relation to [`Self::mem_origin_class`] is one-directional: this
200    /// only ever tightens. Nothing a mem serves as third-party becomes
201    /// first-party here, so a host that already quarantines on
202    /// `third-party` quarantines the merged entity with no change on its
203    /// side.
204    pub fn entity_origin_class(&self, id: &crate::entity::EntityId) -> crate::render::OriginClass {
205        let mem_class = self.mem_origin_class(id.mem());
206        if mem_class.is_third_party() {
207            return mem_class;
208        }
209        let Some(marks) = self.foreign_entities().get(id.mem()) else {
210            return mem_class;
211        };
212        if marks.record_unreadable.is_some() {
213            return crate::render::OriginClass::ThirdParty;
214        }
215        let Some(entity) = self.store.get(id).filter(|e| !e.stub) else {
216            return mem_class;
217        };
218        let holds = |key: &String, hash: &String| -> bool {
219            entity.sections.get(key).is_some_and(|content| {
220                !content.trim().is_empty()
221                    && &crate::preparation::entity_section_prepared_hash(key, content) == hash
222            })
223        };
224        let foreign = marks
225            .by_slug
226            .get(id.path())
227            .is_some_and(|sections| sections.iter().any(|(key, hash)| holds(key, hash)));
228        if foreign {
229            crate::render::OriginClass::ThirdParty
230        } else {
231            mem_class
232        }
233    }
234
235    /// The per-mem foreign-section marks, read once from each writable
236    /// mem's proposal record and memoised on the derived key (a merge's
237    /// own [`Self::invalidate_communities`] refreshes it).
238    ///
239    /// Read-only mounts are skipped: every entity of one is already
240    /// third-party at the mem grain, so a mark would change no answer.
241    fn foreign_entities(&self) -> &crate::engine::ForeignMarks {
242        if let Some((memo_key, _)) = self.foreign_entities_memo.get() {
243            debug_assert_eq!(
244                *memo_key,
245                self.derived_key(),
246                "foreign-entity memo key lags the engine — a mutation path missed \
247                 invalidate_communities"
248            );
249        }
250        &self
251            .foreign_entities_memo
252            .get_or_init(|| (self.derived_key(), self.compute_foreign_entities()))
253            .1
254    }
255
256    fn compute_foreign_entities(&self) -> crate::engine::ForeignMarks {
257        let mut out: crate::engine::ForeignMarks = HashMap::new();
258        for mounted in &self.mounts {
259            let mem = mounted.mount.mem.as_str();
260            // By CLASS, not by writability. Every entity of a third-party
261            // mem is already third-party, so a mark would change no answer
262            // there; but a deployment may vouch for an installed archive as
263            // first-party, and that archive carries its own record of the
264            // bodies ITS owner adopted from contributors. Skipping by
265            // writability served those as the vouching deployment's own.
266            if self.mem_origin_class(mem).is_third_party() {
267                continue;
268            }
269            let record = match self.read_proposal_record(mem) {
270                Ok(Some(record)) => record,
271                Ok(None) => continue,
272                // The record is the only evidence of which bodies came from
273                // a fork. Unreadable, the honest answer is that this mem's
274                // entities are unconfirmable, and the conservative side of
275                // unconfirmable is the stranger's: a corrupt file must not
276                // relabel every adopted body as the workspace's own.
277                Err(e) => {
278                    out.insert(
279                        mem.to_string(),
280                        crate::engine::MemForeignMarks::unreadable(e.prose_render()),
281                    );
282                    continue;
283                }
284            };
285            // One owner for the rules ([`crate::ops::proposal::ProposalRecord`]):
286            // the write paths that have to follow a mark read them through the
287            // same two methods, because four rounds of review found the same
288            // defect one position over while the write path kept its own copy.
289            if let Some(reason) = record.structural_defect() {
290                out.insert(
291                    mem.to_string(),
292                    crate::engine::MemForeignMarks::unreadable(reason),
293                );
294                continue;
295            }
296            let marks = crate::engine::MemForeignMarks {
297                by_slug: record.effective_marks_by_slug(),
298                record_unreadable: None,
299            };
300            if !marks.by_slug.is_empty() {
301                out.insert(mem.to_string(), marks);
302            }
303        }
304        out
305    }
306
307    /// Why a mem's proposal record could not be read, when it could not.
308    ///
309    /// The origin read fails closed on such a mem: every entity of it serves
310    /// `third-party`. Read surfaces pair the label with this reason for the
311    /// same purpose the unreadable-anchors-sidecar condition is stated: a
312    /// conservative label with no cause tells an operator that the engine
313    /// calls their own mem a stranger's, and tells them nothing about why or
314    /// what to repair.
315    pub fn proposal_record_error(&self, mem: &str) -> Option<String> {
316        self.foreign_entities()
317            .get(mem)
318            .and_then(|m| m.record_unreadable.clone())
319    }
320
321    /// Declare the workspace's own writing identities — a deployment fact
322    /// on the same terms as [`Self::declare_mem_origin`]: set by the
323    /// process that owns the engine, never persisted with a mem, never
324    /// reachable over MCP.
325    ///
326    /// It classifies text that a party other than the workspace authored
327    /// into WORKSPACE state, which is the check ledger: a row's `method`
328    /// note and finding message are whatever agent the owner pointed at the
329    /// ledger wrote, under an identity the launching side assigned. The
330    /// assignment is the point — the identity is the deployer's declaration
331    /// about who ran, not the authoring party's claim about itself, so
332    /// unlike a mem-repo trailer it is a lever the authored bytes cannot
333    /// move.
334    ///
335    /// Undeclared (the default) means every ledger identity inherits its
336    /// mem's class, so an existing deployment is byte-identical.
337    pub fn declare_owner_identities<I, S>(&mut self, identities: I)
338    where
339        I: IntoIterator<Item = S>,
340        S: Into<String>,
341    {
342        self.owner_identities
343            .extend(identities.into_iter().map(Into::into));
344        self.foreign_entities_memo = OnceCell::new();
345    }
346
347    /// The trust class of the prose one check row carries — its `method`
348    /// note and finding message, which every surface renders verbatim.
349    ///
350    /// Two sources, and the STRICTER of the two wins. This deployment's own
351    /// reading comes from its declared identities
352    /// ([`Self::check_row_origin_class`]). An archive mount may additionally
353    /// carry the class the exporting workspace sealed beside the row
354    /// ([`crate::check::SealedCheck::origin`]), which is the only party that
355    /// knew which identities were its own, and which matters where the mem
356    /// grain cannot answer: a deployment may vouch for an installed archive
357    /// as first-party, and a row the publisher's foreign checker wrote inside
358    /// it is still a stranger's sentence.
359    ///
360    /// The sealed value may only tighten. It is publisher-supplied bytes, so
361    /// honouring a sealed `first-party` would admit a caller-supplied
362    /// first-party claim on a mem nobody vouched for, which is the one thing
363    /// no read path may do; the closed vocabulary at validation stops an
364    /// unrecognised token, not a well-formed lie.
365    pub fn check_row_prose_origin(
366        &self,
367        mem: &str,
368        entity_id: &str,
369        rec: &crate::check::CheckRecord,
370    ) -> crate::render::OriginClass {
371        let derived = self.check_row_origin_class(mem, rec.identity.as_deref());
372        if derived.is_third_party() {
373            return derived;
374        }
375        match self.sealed_check_row_origin(mem, entity_id, rec) {
376            Some(sealed) if sealed.is_third_party() => sealed,
377            _ => derived,
378        }
379    }
380
381    /// The class an ARCHIVE mount's sealed row carries, verbatim. `None` for
382    /// every other mount and for a member sealed without the field.
383    ///
384    /// Callers go through [`Self::check_row_prose_origin`], which takes the
385    /// stricter of this and the local reading; used raw, this is a
386    /// publisher's claim.
387    fn sealed_check_row_origin(
388        &self,
389        mem: &str,
390        entity_id: &str,
391        rec: &crate::check::CheckRecord,
392    ) -> Option<crate::render::OriginClass> {
393        if !self.is_archive_mount(mem) {
394            return None;
395        }
396        let sealed = self.archive_checks_for(mem)?;
397        let path = crate::EntityId(entity_id.to_string()).path().to_string();
398        sealed
399            .entities
400            .get(&path)?
401            .get(&crate::check::sealed_kind_of(rec))
402            .and_then(|sc| sc.sealed_origin())
403    }
404
405    /// Whether the deployment declared any owner identity. Undeclared is
406    /// the default and means every ledger row inherits its mem's class.
407    pub fn declares_owner_identities(&self) -> bool {
408        !self.owner_identities.is_empty()
409    }
410
411    /// Classify the origin of text a check row carries (its `method` note,
412    /// its finding message) for a row recorded under `identity` against an
413    /// entity of `mem`.
414    ///
415    /// Third-party when owner identities are declared and this row's
416    /// identity is not one of them. An absent identity is unconfirmable,
417    /// not foreign: it inherits the mem's class, the same reading the
418    /// independence gate takes for a row that names nobody. With nothing
419    /// declared every row inherits, which is what the engine served
420    /// before.
421    pub fn check_row_origin_class(
422        &self,
423        mem: &str,
424        identity: Option<&str>,
425    ) -> crate::render::OriginClass {
426        let mem_class = self.mem_origin_class(mem);
427        // Tighten-only, like `entity_origin_class`: this may make a row
428        // third-party, never first-party. On a third-party mem the identity
429        // on a row is the PUBLISHER's bytes, carried verbatim from the
430        // archive, so honouring it here would admit a caller-supplied
431        // first-party claim, which is the one thing no read path may do.
432        if mem_class.is_third_party() || self.owner_identities.is_empty() {
433            return mem_class;
434        }
435        match identity {
436            // Absence is unconfirmable, never guessed foreign: the reading
437            // the independence gate takes for a row that names nobody.
438            None => mem_class,
439            Some(id) if self.owner_identities.contains(id) => mem_class,
440            Some(_) => crate::render::OriginClass::ThirdParty,
441        }
442    }
443
444    /// Declare a mem's data-trust origin as a deployment fact — the
445    /// embedding process (a curated hosted read tier, an app that vouches
446    /// for a bundled mem) overrides the writability inference for one mem.
447    /// Composition-layer-only by design: not persisted, not reachable over
448    /// MCP, never derived from mem content — the operator running the
449    /// process is the only authority that can set it, so a served mem the
450    /// deployment does *not* vouch for keeps reporting third-party on
451    /// every surface. (Deliberately absent from the CLI: that surface
452    /// operates a workspace, not a deployment; the CLI counterpart would be
453    /// a workspace-config knob no use case demands yet.)
454    pub fn declare_mem_origin(
455        &mut self,
456        mem: impl Into<String>,
457        origin: crate::render::OriginClass,
458    ) {
459        self.declared_origins.insert(mem.into(), origin);
460        // The foreign-mark map skips mems that are third-party at the mem
461        // grain, so a declaration changes which mems it covers. Its validity
462        // key is the store generation, which a declaration does not move, so
463        // the memo has to be dropped here or a read taken before this call
464        // would keep serving a vouched archive's adopted bodies as the
465        // vouching deployment's own.
466        self.foreign_entities_memo = OnceCell::new();
467    }
468
469    /// Per-file errors collected during load. Non-fatal: the engine
470    /// continues with whatever did parse. Empty when every backend's
471    /// content parses cleanly.
472    pub fn load_errors(&self) -> &[(PathBuf, String)] {
473        &self.load_errors
474    }
475
476    /// Resolve a VISIBLE mem to its folder-storage root on disk.
477    ///
478    /// Unknown or quarantined names refuse `UNKNOWN_MEM` (the same
479    /// visibility gate `search` and the conflicts door apply); a
480    /// visible mount whose storage is not folder-backed returns
481    /// `Ok(None)` so callers branch on backend applicability without
482    /// inventing a typed error. Read-only mounts resolve too — this is
483    /// a read accessor, not a write gate. Generic by design: any
484    /// consumer that needs a folder mem's disk root (per-mem changelog
485    /// readers, export tooling, future doors) gets the same answer.
486    pub fn folder_mem_root(&self, mem: &str) -> Result<Option<PathBuf>, EngineError> {
487        let mount = self
488            .mounts
489            .iter()
490            .find(|m| m.mount.mem == mem)
491            .ok_or_else(|| self.unknown_mem_error(mem))?;
492        if self.quarantine_reason(mem).is_some() {
493            return Err(self.unknown_mem_error(mem));
494        }
495        match &mount.mount.storage {
496            crate::workspace::MountStorage::Folder { path } => Ok(Some(path.clone())),
497            _ => Ok(None),
498        }
499    }
500
501    /// Workspace-level operator policy (mem create/delete rules,
502    /// cross-mem links). Defaults to empty; populated via
503    /// [`Engine::set_settings`] after construction. Surfaced for MCP
504    /// handlers (`memstead_health { include_config: true }`,
505    /// `memstead_overview`'s lifecycle-namespaces section) and other
506    /// consumers that need to read workspace policy.
507    pub fn settings(&self) -> &WorkspaceSettings {
508        &self.settings
509    }
510
511    /// The pipeline configs — the v2 single-record binding store — loaded
512    /// from the workspace at boot: the read-only queryable surface the
513    /// loader exposes. Empty for engines not booted from a workspace root,
514    /// or for a workspace that declares no pipelines. The ingest skill
515    /// and future MCP tools consume this structured form
516    /// rather than re-reading the JSON folders.
517    pub fn pipeline_configs(&self) -> &crate::pipeline_store::BindingConfigs {
518        &self.pipeline_configs
519    }
520
521    /// The pipeline configs serialized as a JSON string — the read
522    /// counterpart of the `add_projection_json` edit entry point.
523    /// Serialization-boundary callers (where serde does not live)
524    /// get the store in one call and deserialize on their side.
525    ///
526    /// Shape: `{ "bindings": [{ mem, name, config }] }` — the v2
527    /// single-record store (`config` carries the whole binding: inline
528    /// `sources`, `operations`, everything). The `mediums` / `facets` /
529    /// `ingests` keys are **gone** with their record kinds. This reads the
530    /// live binding store fresh (like the brief path) rather than the
531    /// in-memory snapshot, so an edit shows back immediately. A missing
532    /// root or a legacy/unreadable store yields the fallback empty object.
533    pub fn pipeline_configs_json(&self) -> String {
534        let empty = || "{\"bindings\":[]}".to_string();
535        let Some(root) = self.workspace_root() else {
536            return empty();
537        };
538        match crate::pipeline_store::load_pipeline_configs(root) {
539            Ok(configs) => serde_json::to_string(&configs).unwrap_or_else(|_| empty()),
540            Err(_) => empty(),
541        }
542    }
543
544    /// Overwrite the in-memory pipeline configs. The workspace-root boot
545    /// paths call this after [`crate::pipeline_store::load_pipeline_configs`];
546    /// exposed so the full boot helper (a separate crate) can populate the
547    /// same surface.
548    pub fn set_pipeline_configs(&mut self, configs: crate::pipeline_store::BindingConfigs) {
549        self.pipeline_configs = configs;
550    }
551
552    /// Build a [`WarningHint::NoteMissing`] when the workspace has
553    /// `[mutations].require_notes = true` and the caller omitted (or
554    /// passed a blank/whitespace-only) `note`; `None` otherwise.
555    ///
556    /// This is the single enforcement point for the `require_notes`
557    /// provenance nudge. Every mutation that accepts a `note` calls it
558    /// on its commit-landing path and pushes the result onto the
559    /// outcome's `warnings`, so both the CLI and the MCP transports
560    /// inherit identical behaviour from the engine response rather than
561    /// each re-deriving the policy at its own boundary (the drift that
562    /// left the policy decorative on the CLI). `tool` becomes the
563    /// warning's `details.tool` — callers pass the engine-level verb
564    /// (`create_entity`, `update_entity`, `relate_entity`,
565    /// `delete_entity`, `rename_entity`, `create_mem`,
566    /// `delete_mem`), matching the commit `Tool:` provenance trailer.
567    /// The mutation still commits — the policy nudges, it never blocks.
568    pub fn note_missing_warning(&self, tool: &str, note: Option<&str>) -> Option<WarningHint> {
569        if !self.settings.mutations.require_notes.unwrap_or(false) {
570            return None;
571        }
572        let has_note = note.map(|n| !n.trim().is_empty()).unwrap_or(false);
573        if has_note {
574            return None;
575        }
576        Some(WarningHint::NoteMissing {
577            tool: tool.to_string(),
578        })
579    }
580
581    /// Backend factory currently installed on this engine. Returned by
582    /// value because [`BackendFactory`] is a function pointer (`Copy`).
583    /// Used by [`crate::mem_management::create_mem`] to materialise
584    /// the backend for a freshly-registered mount; consumers that need
585    /// to instantiate a backend ad-hoc can call this directly.
586    pub fn backend_factory(&self) -> BackendFactory {
587        self.backend_factory
588    }
589
590    /// A backend for `mount`, built by the installed factory and told
591    /// what the engine tells every backend it serves: how long a load
592    /// or a direct read may wait for the mem's write lock, which is the
593    /// workspace's write-lock deadline. Every backend the engine builds
594    /// after boot comes from here, so none is served, or loaded, under
595    /// a limit the workspace did not set.
596    pub fn instantiate_backend(
597        &self,
598        mount: &crate::workspace::Mount,
599    ) -> Result<Box<dyn crate::backend::MemBackend>, crate::workspace_store::InstantiateError> {
600        let backend = (self.backend_factory)(mount)?;
601        backend.set_lock_wait(self.settings.mutations.write_lock_timeout());
602        Ok(backend)
603    }
604
605    /// Git-branch ops bundle currently installed on this engine.
606    /// `None` on engines without the git-branch crate, which see no mem-repo
607    /// mounts. Returned by value because [`super::GitBranchOps`] is
608    /// `Copy`. `create_mem` reaches for
609    /// the bundle to drive `prune_residue` against an unmounted
610    /// gitdir when the `ForceOverwrite` recovery action is selected.
611    pub fn git_branch_ops(&self) -> Option<super::GitBranchOps> {
612        self.git_branch_ops
613    }
614
615    /// Whether a cross-mem edge from `from_mem` to `to_mem` is
616    /// permitted under the current [`crate::WorkspaceSettings`]
617    /// cross-mem link policy.
618    ///
619    /// Resolution rules (matches full's `mem_router` semantics):
620    /// 1. Same-mem edge (`from_mem == to_mem`) → always
621    ///    allowed; the policy gates *cross*-mem edges only.
622    /// 2. Explicit `cross_mem_links[from_mem]`:
623    ///    - `"*"` (wildcard) → allowed regardless of target.
624    ///    - `["a", ...]` (allowlist) → allowed iff `to_mem` is in
625    ///      the list.
626    /// 3. Per-create-rule `default_cross_links` synthesis — if
627    ///    rule (1) didn't grant permission and `from_mem` matches
628    ///    a `[[mem_management.create]]` rule whose
629    ///    `default_cross_links` is set, the synthesised value
630    ///    contributes:
631    ///    - `"*"` → allowed regardless of target.
632    ///    - `["a", ...]` → allowed iff `to_mem` is in the list.
633    /// 4. Otherwise → denied (default-deny posture).
634    ///
635    /// The synthesis layer compiles a [`crate::mem_management::CreateRuleSet`]
636    /// lazily on first call and caches it; [`Self::set_settings`]
637    /// invalidates the cache. Compilation failure (malformed glob
638    /// in a rule) logs a warning and the synthesis layer is silently
639    /// skipped — the resolver still returns `true` from explicit
640    /// policy alone, so a half-broken config doesn't lock out edges
641    /// the operator did intend to allow. Operators who want hard
642    /// validation pre-compile via
643    /// [`crate::mem_management::CreateRuleSet::new`] before
644    /// calling [`Self::set_settings`].
645    ///
646    /// The MCP `memstead_relate` handler's cross-mem gate consumes
647    /// this method directly.
648    pub fn cross_mem_link_allowed(&self, from_mem: &str, to_mem: &str) -> bool {
649        use memstead_schema::workspace_config::CrossLinkValue;
650        if from_mem == to_mem {
651            return true;
652        }
653
654        // Step 1: explicit cross_mem_links policy.
655        if let Some(value) = self.settings.cross_mem_links.get(from_mem) {
656            match value {
657                CrossLinkValue::Wildcard => return true,
658                CrossLinkValue::List(targets) => {
659                    if targets.iter().any(|t| t == to_mem) {
660                        return true;
661                    }
662                    // Fall through to synthesis check — a List that
663                    // doesn't include the target may still allow it
664                    // via per-rule default_cross_links union.
665                }
666            }
667        }
668
669        // Step 2: per-create-rule default_cross_links synthesis.
670        let rule_set = self.create_rule_set_memo.get_or_init(|| {
671            crate::mem_management::CreateRuleSet::new(
672                self.settings.mem_create_rules.clone(),
673            )
674            .unwrap_or_else(|err| {
675                tracing::warn!(
676                    error = %err,
677                    "cross_mem_link_allowed: failed to compile mem_create_rules — synthesis disabled (resolver falls back to explicit-policy-only)"
678                );
679                crate::mem_management::CreateRuleSet::default()
680            })
681        });
682
683        // Compose the same `<mem_path>/<name>` candidate the create-rule
684        // composer matched against. The rule globs are keyed on the composed
685        // lifecycle path (e.g. `memstead/project`, compiled with
686        // `literal_separator`), not the bare leaf name — matching
687        // `from_mem` alone silently misses, so synthesis denied a link
688        // that `memstead_overview` rendered as rule-granted (the
689        // leaf-vs-composed-path divergence). Flat-layout mems (no
690        // hierarchical path) keep the bare leaf, matching their bare rule.
691        let candidate = match self.mount(from_mem).and_then(|m| m.mem_path()) {
692            Some(path) => format!("{path}/{from_mem}"),
693            None => from_mem.to_string(),
694        };
695        if let Some(matched) = rule_set.first_match(std::path::Path::new(&candidate))
696            && let Some(synth) = matched.default_cross_links.as_ref()
697        {
698            return match synth {
699                CrossLinkValue::Wildcard => true,
700                CrossLinkValue::List(targets) => targets.iter().any(|t| t == to_mem),
701            };
702        }
703
704        false
705    }
706
707    pub(super) fn find_mount(&self, mem: &str) -> Result<&MountedBackend, EngineError> {
708        self.mounts
709            .iter()
710            .find(|m| m.mount.mem == mem)
711            .ok_or_else(|| self.unknown_mem_error(mem))
712    }
713}
714
715// -------------------------------------------------------------------------
716// Cut by concern. Each child opens its own `impl Engine` block, so every
717// method keeps its name, signature and visibility and no consumer moves.
718// -------------------------------------------------------------------------
719
720mod anchors;
721mod health;
722mod mounts;
723mod reads;
724
725pub use anchors::*;
726
727#[cfg(test)]
728mod tests;