Skip to main content

memstead_base/engine/
boot.rs

1//! Engine construction — `from_mounts*` and `from_workspace_root`.
2//!
3//! `from_mounts` is the in-process constructor every test, in-process
4//! embedder, and the MCP filesystem server reach through.
5//! `from_workspace_root` is the folder boot path that produces the
6//! same engine from a workspace root; the git-branch counterpart lives in
7//! `memstead_git_branch::engine_from_workspace_root` and follows the same
8//! shape with the git-branch backend added to the factory.
9//!
10//! Free helpers in this module materialise the workspace schemas
11//! catalogue, walk each mount's backend at load-time, and synthesise
12//! the [`MemRouterSnapshot`] from the resolved mount list — pieces
13//! the two entry points share.
14
15use std::cell::OnceCell;
16use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20use memstead_schema::Schema;
21
22use crate::backend::MemBackend;
23use crate::engine_fallback_type;
24use crate::entity::loader::parse_entries;
25use crate::entity::source::{SourceEntry, SourceReadError};
26use crate::entity::store_builder::push_entities_into_store;
27use crate::mem::{MemOrigin, MemRouterSnapshot};
28use crate::ops::WarningHint;
29use crate::store::Store;
30use crate::workspace::{Mount, MountCapability, MountStorage, WorkspaceSettings};
31
32use super::{BootError, Engine, EngineError, MountedBackend};
33
34impl Engine {
35    /// Build an engine from `(mount, backend)` pairs. The backend
36    /// is the implementor that will serve reads / writes for that
37    /// mount's mem.
38    ///
39    /// Returns [`EngineError::DuplicateMem`] when two mounts name
40    /// the same mem; that's a configuration error the caller must
41    /// fix before the engine can route deterministically. An empty
42    /// mount list is allowed (returns an engine that errors
43    /// `UnknownMem` on every read) — useful for tests; production
44    /// callers will reject empty inputs at the persistence-adapter
45    /// layer.
46    pub fn from_mounts(mounts: Vec<(Mount, Box<dyn MemBackend>)>) -> Result<Self, EngineError> {
47        Self::from_mounts_inner(mounts, Vec::new(), Vec::new())
48    }
49
50    /// Construct an engine from mounts plus an optional workspace
51    /// schemas directory. Loads every subdirectory of `schemas_dir`
52    /// as a workspace-authored schema and combines with the builtin
53    /// catalogue for per-mem schema-pin resolution. Workspace
54    /// schemas take precedence on (name, version) collision —
55    /// matches full's behaviour.
56    ///
57    /// `schemas_dir = None` is equivalent to [`Self::from_mounts`].
58    /// Used by `engine_from_workspace_root` to thread the
59    /// `[schemas_dir]` workspace-toml entry into schema resolution.
60    pub fn from_mounts_with_schemas_dir(
61        mounts: Vec<(Mount, Box<dyn MemBackend>)>,
62        schemas_dir: Option<&Path>,
63    ) -> Result<Self, EngineError> {
64        let (extra_schemas, failed) = load_workspace_schemas_with_failures(schemas_dir);
65        Self::from_mounts_inner(mounts, extra_schemas, failed)
66    }
67
68    /// Like [`Self::from_mounts_with_schemas_dir`] but layers additional,
69    /// pre-loaded local-storage schemas (e.g. those a git-branch backend
70    /// reads from its `__MEMSTEAD:schemas/` ref via `SchemaSource`) on
71    /// top of the folder `schemas_dir` set. Both are local-storage
72    /// schemas — they override built-ins on `(name, version)` collision.
73    /// The git-branch boot path uses this to make ref-installed schemas
74    /// resolvable, which `from_mounts_with_schemas_dir` (folder only)
75    /// does not.
76    pub fn from_mounts_with_schemas_dir_and_extra(
77        mounts: Vec<(Mount, Box<dyn MemBackend>)>,
78        schemas_dir: Option<&Path>,
79        mut extra: Vec<Arc<memstead_schema::Schema>>,
80    ) -> Result<Self, EngineError> {
81        let (mut local, failed) = load_workspace_schemas_with_failures(schemas_dir);
82        local.append(&mut extra);
83        Self::from_mounts_inner(mounts, local, failed)
84    }
85
86    pub(crate) fn from_mounts_inner(
87        mounts: Vec<(Mount, Box<dyn MemBackend>)>,
88        extra_schemas: Vec<Arc<memstead_schema::Schema>>,
89        failed_schema_packages: Vec<FailedSchemaPackage>,
90    ) -> Result<Self, EngineError> {
91        let mut seen: std::collections::HashSet<String> =
92            std::collections::HashSet::with_capacity(mounts.len());
93        let mut mounted: Vec<MountedBackend> = Vec::with_capacity(mounts.len());
94        for (mount, backend) in mounts {
95            if !seen.insert(mount.mem.clone()) {
96                return Err(EngineError::DuplicateMem(mount.mem));
97            }
98            // Seed the per-mount drift baseline. A backend that
99            // doesn't track HEAD (folder, archive) returns Ok(None)
100            // — drift detection is then a no-op for the mount. A
101            // probe failure during init falls back to None so a
102            // later successful probe can establish the baseline.
103            let last_known_head = backend.current_head().ok().flatten();
104            // Load the per-mem `.memstead/config.json` via the
105            // backend trait. Each backend resolves its own
106            // canonical location (folder: `<root>/.memstead/config.json`;
107            // archive: inside the zip; git-branch:
108            // `__MEMSTEAD:mems/<leaf>/config.json`). Read failures
109            // or missing files surface as
110            // `None` — `memstead_health` accommodates the missing-config
111            // case (handler emits empty `writeGuidance` + `extra`).
112            let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
113                let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
114                memstead_schema::config::parse_mem_config(&value).ok()
115            });
116            // Read the optional authoring-provenance payload the archive
117            // carries (`.memstead/provenance.json`). A malformed payload is
118            // downgraded to `None` (the member is additive — a parse
119            // failure means "provenance absent", not "mount failed").
120            let archive_provenance =
121                backend
122                    .read_archive_provenance()
123                    .ok()
124                    .flatten()
125                    .and_then(|bytes| {
126                        memstead_schema::ArchiveProvenance::from_archive_bytes(&bytes).ok()
127                    });
128            // The sealed check records, an archive mount's only source of
129            // check state. A malformed member downgrades to `None` the way
130            // provenance does; install validated the member already.
131            let archive_checks = backend
132                .read_archive_checks()
133                .ok()
134                .flatten()
135                .and_then(|bytes| crate::check::SealedChecks::from_archive_bytes(&bytes).ok());
136            mounted.push(MountedBackend {
137                mount,
138                backend,
139                last_known_head,
140                mem_config,
141                archive_provenance,
142                archive_checks,
143                // Set below, after the schema pin resolves: a lazy mount
144                // whose METADATA half fails still quarantines at boot;
145                // only the entity load defers.
146                deferred: false,
147            });
148        }
149
150        // Walk each backend, parse entries, populate one shared Store.
151        // Resolve each mount's schema pin against the built-in schema
152        // catalogue. The schema-registry resolver (which would also
153        // honor workspace-authored schemas living inside the storage
154        // backend) lands as a separate plan; this resolution closes
155        // the gap for the built-in catalogue so a workspace pinning
156        // a non-default built-in (e.g. `software`, `memory`) surfaces
157        // the right schema rather than silently downgrading to
158        // `default`.
159        let builtin_schemas_only = memstead_schema::builtins::load_builtin_schemas()
160            .map_err(|e| EngineError::SchemaResolverInit(e.to_string()))?;
161        // Workspace-authored schemas resolve first (override builtins
162        // on (name, version) collision); builtins fill the rest.
163        let workspace_schemas = extra_schemas.clone();
164        let mut catalogue: Vec<Arc<memstead_schema::Schema>> =
165            Vec::with_capacity(extra_schemas.len() + builtin_schemas_only.len());
166        catalogue.extend(extra_schemas);
167        catalogue.extend(builtin_schemas_only.clone());
168        let builtin_schemas = catalogue;
169        let mut store = Store::new();
170        let mut load_errors: Vec<(PathBuf, String)> = Vec::new();
171        let mut schemas: HashMap<String, Arc<Schema>> = HashMap::with_capacity(mounted.len());
172        let fallback = engine_fallback_type();
173
174        // Derive the mem roster + last-segment suffixes ONCE so the
175        // per-mount load loop hands the same view to every
176        // `LoadCollector`. `known_suffixes` is the input the
177        // nested-prefix detector compares against; the full
178        // `mem_names` list feeds the two-pass cross-mem resolver
179        // in `push_entities_into_store`.
180        let mem_names: Vec<String> = mounted.iter().map(|m| m.mount.mem.clone()).collect();
181        let known_suffixes: Vec<String> = mem_names
182            .iter()
183            .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
184            .collect();
185        let mut load_warnings: Vec<WarningHint> = Vec::new();
186
187        // Mem-level failures quarantine the mem instead of failing the
188        // workspace (degrade, never disappear: before this, one
189        // broken mem took every healthy sibling offline). Nothing is
190        // weakened: everything that failed the boot still fails it,
191        // the blast radius shrinks to the one mem, which serves
192        // nothing until repaired + reloaded.
193        let mut quarantined: Vec<crate::engine::QuarantinedMem> = Vec::new();
194        let mut quarantined_idx: std::collections::HashSet<usize> =
195            std::collections::HashSet::new();
196        // Mounts whose entity load is DEFERRED (`lifecycle: lazy`): the
197        // metadata half above and the schema resolution below still run
198        // at boot — the roster must know the mem exists, with its pin —
199        // but the entity walk is skipped until the first operation that
200        // needs the mem triggers [`Engine::ensure_mems_loaded`].
201        let mut deferred_idx: std::collections::HashSet<usize> = std::collections::HashSet::new();
202
203        for (m_idx, m) in mounted.iter().enumerate() {
204            // Schema-pin authority: the mem's own per-mem config is
205            // the authoritative settled pin, so a copied or cloned mem
206            // resolves its schema from its own backend without consulting
207            // this workspace's `mounts.json`. `Mount.schema` (the mount
208            // record's pin) is the fallback when the config carries no
209            // schema, and an expectation assertion when it does — a
210            // disagreement surfaces a `SchemaPinMismatch` warning rather
211            // than silently preferring either.
212            let config_pin = m.mem_config.as_ref().and_then(|c| c.schema.as_ref());
213            let mount_pin = m.mount.schema.as_ref();
214            // `Mount.schema` is an optional expectation assertion: warn
215            // only when it is set *and* disagrees with the authoritative
216            // config pin.
217            if let (Some(cfg), Some(mp)) = (config_pin, mount_pin)
218                && cfg != mp
219            {
220                load_warnings.push(WarningHint::SchemaPinMismatch {
221                    mem: m.mount.mem.clone(),
222                    config_pin: cfg.as_display(),
223                    mount_pin: mp.as_display(),
224                });
225            }
226            // Boot-honesty skew check: a mem whose engine-owned
227            // mutation stamp names a different engine version than
228            // this binary gets a warn-tier hint — informative, never
229            // fatal, and a stamp-less (pre-stamp) mem is silent by
230            // construction. Read-only: the stamp is only ever
231            // rewritten by the next mutation.
232            //
233            // Compared as SEMVER, not as full strings.
234            // The old rule fired on any difference including the `+g<sha>`
235            // build metadata, so every rebuild between releases read as
236            // skew — noise on any workspace whose binary is built from
237            // source, which is every one of this project's own workspaces. Semver ordering
238            // ignores build metadata, so what survives is a real version
239            // difference, and it now carries its direction.
240            if let Some(stamp) = m
241                .mem_config
242                .as_ref()
243                .and_then(|c| c.mutation_stamp.as_ref())
244                && let Some(direction) = crate::build_info::skew_direction(
245                    &stamp.engine_version,
246                    crate::build_info::full_version(),
247                )
248            {
249                load_warnings.push(WarningHint::EngineVersionSkew {
250                    mem: m.mount.mem.clone(),
251                    stamped_engine: stamp.engine_version.clone(),
252                    running_engine: crate::build_info::full_version().to_string(),
253                    stamped_schema: stamp.schema.clone(),
254                    direction,
255                });
256            }
257            // Authoritative pin first (the backend config), then the
258            // mount assertion as fallback when the config carries none.
259            let settled_pin = config_pin.or(mount_pin);
260            // Dual-pin: a mem mid-migration validates against the
261            // migration target, not the settled pin.
262            let Some(effective_pin) = m.mount.migration_target.as_ref().or(settled_pin) else {
263                // Missing pin: quarantine, don't abort the workspace.
264                let e = EngineError::MemConfigIncomplete {
265                    mem: m.mount.mem.clone(),
266                    missing_fields: vec!["schema".to_string()],
267                };
268                quarantined.push(crate::engine::QuarantinedMem {
269                    mount: m.mount.clone(),
270                    reason_code: e.code().to_string(),
271                    reason_message: e.to_string(),
272                });
273                quarantined_idx.insert(m_idx);
274                continue;
275            };
276            // An archive-backed mount carries its own sealed vocabulary
277            // and resolves against it on every workspace shape: a
278            // folder workspace has no sealed-package storage to stage a
279            // third party's schema into, and a mem published under such
280            // a schema would otherwise quarantine there. The embedded
281            // package is layered per mount, between the workspace tier
282            // and the built-ins, and never into the shared catalogue —
283            // a sealed vocabulary is this mount's, not something a
284            // writable mem may pin.
285            let embedded = embedded_archive_schemas(&m.mount);
286            let resolved = if embedded.is_empty() {
287                SchemaResolver::new(&builtin_schemas).resolve(effective_pin)
288            } else {
289                let mut per_mount: Vec<Arc<Schema>> = Vec::with_capacity(
290                    workspace_schemas.len() + embedded.len() + builtin_schemas_only.len(),
291                );
292                per_mount.extend(workspace_schemas.iter().cloned());
293                per_mount.extend(embedded);
294                per_mount.extend(builtin_schemas_only.iter().cloned());
295                SchemaResolver::new(&per_mount).resolve(effective_pin)
296            };
297            let schema = match resolved {
298                Ok(schema) => schema,
299                Err(sources) => {
300                    // Unresolvable pin (the mem names a schema no
301                    // source can supply): quarantine this mem, serve
302                    // the rest. When the pin names a
303                    // workspace-authored package that
304                    // FAILED to load (e.g. one still on the retired
305                    // `propagating_relationships` key), that load
306                    // failure is the honest reason — not a generic
307                    // not-found.
308                    let failed = failed_schema_packages.iter().find(|f| {
309                        f.name.as_deref() == Some(effective_pin.name.as_str())
310                            && f.version
311                                .as_deref()
312                                .is_none_or(|v| v == effective_pin.version.to_string())
313                    });
314                    let (reason_code, reason_message) = match failed {
315                        Some(f) => (
316                            "SCHEMA_LOAD_FAILED".to_string(),
317                            format!(
318                                "schema package at {} failed to load: {}",
319                                f.path.display(),
320                                f.error
321                            ),
322                        ),
323                        None => {
324                            let e = EngineError::SchemaNotFound {
325                                mem: m.mount.mem.clone(),
326                                pin: effective_pin.as_display(),
327                                sources,
328                                install_hint: None,
329                            };
330                            (e.code().to_string(), e.to_string())
331                        }
332                    };
333                    quarantined.push(crate::engine::QuarantinedMem {
334                        mount: m.mount.clone(),
335                        reason_code,
336                        reason_message,
337                    });
338                    quarantined_idx.insert(m_idx);
339                    continue;
340                }
341            };
342            schemas.insert(m.mount.mem.clone(), schema.clone());
343
344            // Generation-behind hint (warn-tier, ungated, never
345            // blocking): the pin resolved from the BUILT-IN catalogue
346            // and the catalogue registers at least one strictly-higher
347            // version of the same name. Locally-installed
348            // (workspace-storage) pins are silent — the engine only
349            // knows generations for built-ins, and a local install
350            // shadowing a built-in (name, version) counts as local
351            // (that is also the resolver's precedence). Real semver
352            // ordering via `semver::Version`, never string ordering.
353            let locally_installed = workspace_schemas.iter().any(|s| {
354                s.manifest.name == effective_pin.name && s.version == effective_pin.version
355            });
356            let is_builtin = builtin_schemas_only.iter().any(|s| {
357                s.manifest.name == effective_pin.name && s.version == effective_pin.version
358            });
359            if !locally_installed
360                && is_builtin
361                && let Some(newest) =
362                    newest_builtin_version(&effective_pin.name, &builtin_schemas_only)
363                && *newest > effective_pin.version
364            {
365                load_warnings.push(WarningHint::SchemaGenerationsBehind {
366                    mem: m.mount.mem.clone(),
367                    pinned: effective_pin.as_display(),
368                    newest: newest.to_string(),
369                });
370            }
371
372            // Sealed schemas keep loading even when they violate the
373            // heading round-trip rule new installs are refused for —
374            // the violation surfaces as a health finding here, never
375            // as a boot failure (refusing would brick the workspace).
376            if let Err(memstead_schema::SchemaLoadError::SectionHeadingMismatch { violations }) =
377                memstead_schema::check_section_heading_roundtrip(&schema)
378            {
379                let (name, version) = schema.id();
380                load_warnings.push(WarningHint::SchemaHeadingRoundtripViolation {
381                    mem: m.mount.mem.clone(),
382                    schema_ref: format!("{name}@{version}"),
383                    violations: violations.iter().map(Into::into).collect(),
384                });
385            }
386
387            // Lazy lifecycle: everything above (config, provenance, pin
388            // resolution, schema warnings — the metadata half) ran; the
389            // entity walk is the expensive leg and defers to first read.
390            // A lazy mount with a broken pin still quarantined above —
391            // deferral never converts a metadata failure into silence.
392            if m.mount.lifecycle == crate::workspace::MountLifecycle::Lazy {
393                if let Some(w) = unbacked_mount_warning(&m.mount, m.backend.as_ref(), None) {
394                    load_warnings.push(w);
395                }
396                deferred_idx.insert(m_idx);
397                continue;
398            }
399
400            let (entries, read_errors) = match collect_source_entries(m.backend.as_ref()) {
401                Ok(pair) => pair,
402                Err(e) => {
403                    // Backend read failure: quarantine this mem, serve
404                    // the rest.
405                    quarantined.push(crate::engine::QuarantinedMem {
406                        mount: m.mount.clone(),
407                        reason_code: e.code().to_string(),
408                        reason_message: e.to_string(),
409                    });
410                    quarantined_idx.insert(m_idx);
411                    schemas.remove(&m.mount.mem);
412                    continue;
413                }
414            };
415            // Storage that is GONE quarantines rather than serving an empty
416            // graph (04/05). "Configured but cannot serve" is exactly what
417            // quarantine already means, its three sibling causes already
418            // quarantine, and this ends an incoherence: the same broken mount
419            // used to quarantine or serve empty depending on whether the
420            // mounts file happened to carry a schema assertion, which is
421            // unrelated to the breakage. A mem that answers reads with an
422            // empty graph is a worse default than one that refuses by name
423            // with a reason.
424            //
425            // The quarantine roster is rendered on every roster surface, which
426            // is what keeps this from trading a mount that looks healthy for a
427            // mount that is simply gone.
428            //
429            // SCOPED TO PATH-BACKED STORAGE, and the exception is a deliberate
430            // departure from backend parity rather than an oversight. For a
431            // git-branch mount, "the ref does not exist" is ALSO the normal
432            // state of a mem never pushed or never cloned, and quarantine
433            // removes the mount from the serving set. Parity was attempted
434            // twice. Each attempt cleared one blocker and uncovered the next:
435            // the mount lookup (a line), the pre-push gate's schema-before-ref
436            // ordering (fixed here, and worth fixing on its own), and finally
437            // `pull`'s pre-fast-forward validation, which needs a resolved
438            // schema a quarantined mem does not have. That last one is a
439            // semantic decision about what validation means for a mem being
440            // cloned, not plumbing. Recorded in the session log.
441            let path_backed = matches!(
442                m.mount.storage,
443                crate::workspace::MountStorage::Folder { .. }
444                    | crate::workspace::MountStorage::Archive { .. }
445            );
446            if path_backed && !m.backend.storage_present().unwrap_or(true) {
447                let location = match &m.mount.storage {
448                    crate::workspace::MountStorage::GitBranch { branch, .. } => branch.clone(),
449                    crate::workspace::MountStorage::Folder { path }
450                    | crate::workspace::MountStorage::Archive { path } => {
451                        path.display().to_string()
452                    }
453                    crate::workspace::MountStorage::InMemory => String::new(),
454                };
455                quarantined.push(crate::engine::QuarantinedMem {
456                    mount: m.mount.clone(),
457                    reason_code: "MOUNT_UNBACKED".to_string(),
458                    reason_message: format!(
459                        "the mount's storage is gone ({location}); it is configured but cannot \
460                         serve, so it is held out of the roster rather than answering reads \
461                         with an empty graph"
462                    ),
463                });
464                quarantined_idx.insert(m_idx);
465                schemas.remove(&m.mount.mem);
466                continue;
467            }
468            // A mount that is PRESENT but holds nothing still only warns: an
469            // empty mem is a legitimate state and must never be reported as
470            // unbacked or quarantined.
471            if let Some(w) =
472                unbacked_mount_warning(&m.mount, m.backend.as_ref(), Some(entries.len()))
473            {
474                load_warnings.push(w);
475            }
476            let load_result = parse_entries(entries, read_errors, &m.mount.mem, schema.as_ref());
477            // Wire the LoadCollector so the parser/store-builder
478            // pipeline forwards typed drift warnings
479            // (`SuspiciousNestedPrefix`, `DuplicateSectionHeading`,
480            // `InlineWikiLinkAutoStubbed`) into `load_warnings`.
481            // Mutation paths still pass `None` to stay silent.
482            push_entities_into_store(
483                &mut store,
484                load_result.entities,
485                fallback.as_ref(),
486                Some(crate::entity::store_builder::LoadCollector {
487                    warnings: &mut load_warnings,
488                    known_suffixes: &known_suffixes,
489                    mem_names: &mem_names,
490                }),
491            );
492            // Normalize folder-mount error paths to absolute (the
493            // backend walk yields mem-relative ones) so the per-mem
494            // reload can later replace exactly this mem's entries —
495            // a repaired file must stop reporting its old refusal.
496            if let crate::workspace::MountStorage::Folder { path } = &m.mount.storage {
497                let root = path.clone();
498                load_errors.extend(load_result.errors.into_iter().map(|(p, msg)| {
499                    let abs = if p.is_relative() { root.join(&p) } else { p };
500                    (abs, msg)
501                }));
502            } else {
503                load_errors.extend(load_result.errors);
504            }
505        }
506
507        // Stamp the deferred flags before the quarantine retain below
508        // renumbers the vector.
509        for idx in &deferred_idx {
510            mounted[*idx].deferred = true;
511        }
512
513        // Drop quarantined mounts from the serving roster: a
514        // quarantined mem has no backend in service, no entities in
515        // the store, no schema in the per-mem map — it exists only on
516        // the quarantine roster until repair + reload re-attach it.
517        if !quarantined_idx.is_empty() {
518            let mut keep_idx = 0usize;
519            mounted.retain(|_| {
520                let keep = !quarantined_idx.contains(&keep_idx);
521                keep_idx += 1;
522                keep
523            });
524        }
525
526        // Parse-time relation validation runs after every mount's
527        // entities are loaded so cross-mem target types are
528        // resolvable. Hand-edits, external tooling, and embedder
529        // editor surfaces can inject relations that bypass
530        // `memstead_relate`; this is the only place those get caught.
531        // Mutation paths pre-validate before writing, so they
532        // never trip the warning post-load.
533        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> =
534            mounted
535                .iter()
536                .map(|m| (m.mount.mem.clone(), m.mount.capability))
537                .collect();
538        crate::entity::store_builder::validate_loaded_relations(
539            &mut store,
540            &schemas,
541            &mount_caps,
542            &mut load_warnings,
543        );
544
545        // Stamp `EdgeSource::BodyLink` on edges whose rel-type matches
546        // the source mem's `alias_target_rel_type` pointer. Runs
547        // after `validate_loaded_relations` so the surviving relation
548        // set is schema-clean before the labeling pass.
549        crate::entity::store_builder::remap_alias_target_edge_sources(&mut store, &schemas);
550
551        // The nested-prefix drift scan runs per mount, so a cross-mem
552        // link into a mem loaded LATER in the mount order probes an
553        // incomplete store and false-positives on a perfectly valid id
554        // (e.g. `registry--registry-service` referenced from a mem that
555        // mounts before `registry`). Now that every mount is loaded,
556        // drop any hit whose resolved target exists as a real entity —
557        // the same legitimate-cross-mem-reference exemption the
558        // in-batch scan already applies when load order permits.
559        load_warnings.retain(|w| match w {
560            WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
561                store.get(resolved_id).is_none_or(|e| e.stub)
562            }
563            _ => true,
564        });
565
566        // Derive the runtime mem router from the mount list.
567        // Mirrors full's `Engine::from_init` step that registers every
568        // mount with `MemRouterSnapshot` so handlers reach a
569        // consistent writable/visible roster regardless of which
570        // backend serves the mem.
571        let mem_router = build_mem_router_from_mounts(&mounted);
572
573        // The baseline a later `persist_state` diffs against: the roster
574        // as handed to this constructor. A mount quarantined before this
575        // point is deliberately absent from it, so the merge treats its
576        // on-disk record as "not ours to remove" and leaves it standing —
577        // degrade, never disappear.
578        let mounts_baseline =
579            std::cell::RefCell::new(mounted.iter().map(|m| m.mount.clone()).collect::<Vec<_>>());
580
581        Ok(Self {
582            mounts: mounted,
583            mounts_baseline,
584            store,
585            schemas,
586            workspace_schemas,
587            builtin_schemas: builtin_schemas_only,
588            load_errors,
589            community_memo: OnceCell::new(),
590            labelling_memo: OnceCell::new(),
591            #[cfg(not(target_arch = "wasm32"))]
592            search_indexes_memo: OnceCell::new(),
593            settings: WorkspaceSettings::default(),
594            create_rule_set_memo: OnceCell::new(),
595            declared_origins: HashMap::new(),
596            owner_identities: std::collections::BTreeSet::new(),
597            foreign_entities_memo: OnceCell::new(),
598            workspace_root: None,
599            load_warnings,
600            quarantined,
601            boot_diagnosis: None,
602            pipeline_configs: crate::pipeline_store::BindingConfigs::default(),
603            mem_router: Arc::new(mem_router),
604            backend_factory: crate::workspace_store::instantiate_local_backend,
605            unmounted_storage_prober: None,
606            schemas_epoch: 0,
607            git_branch_ops: None,
608            event_subscribers: Arc::new(std::sync::Mutex::new(
609                crate::engine::events::SubscriberRegistry::new(),
610            )),
611            pending_mem_changed: Vec::new(),
612            roster_fingerprint: None,
613            roster_subscribers: Arc::new(std::sync::Mutex::new((0, Vec::new()))),
614            recently_unmounted: std::collections::HashSet::new(),
615            #[cfg(test)]
616            inject_unmount_failure: None,
617            mutation_clock: Arc::new(crate::engine::mutation::wall_clock_now),
618            current_role: crate::vcs::Role::Unspecified,
619            current_identity: None,
620            current_actor: crate::vcs::Actor::Agent,
621            current_client: None,
622        })
623    }
624
625    /// Boot an engine from a workspace root using only the local
626    /// backends (folder + archive): the folder boot path. The CLI's
627    /// folder-workspace path reaches the engine through this entry
628    /// point; git-branch mounts quarantine unless a backend factory is set.
629    ///
630    /// Loads the workspace through [`crate::FileWorkspaceStore`],
631    /// instantiates each mount's backend via
632    /// [`crate::instantiate_local_backend`], and constructs the
633    /// engine via [`Engine::from_mounts`].
634    ///
635    /// Errors:
636    /// - [`Layout::Empty`](crate::Layout) → [`BootError::NotInitialised`]
637    /// - any mount declaring [`crate::workspace::MountStorage::GitBranch`]
638    ///   → [`BootError::Instantiate`] wrapping
639    ///   [`crate::InstantiateError::GitBranchBackendUnavailable`]
640    /// - underlying store / engine failures lift through the
641    ///   `#[from]` conversions
642    pub fn from_workspace_root(workspace_root: &Path) -> Result<Self, BootError> {
643        use crate::workspace_store::{
644            FileWorkspaceStore, Layout, WorkspaceStoreAdapter, detect_layout,
645            instantiate_local_backend,
646        };
647
648        let workspace = match detect_layout(workspace_root) {
649            // Standalone collapse: a bare folder mem (`.memstead/config.json`,
650            // no `workspace.toml`) roots as a one-mount workspace rather than
651            // refusing — the lone-mem boot path is the unified one.
652            Layout::Empty => match crate::workspace_store::standalone_workspace(workspace_root) {
653                Some(ws) => ws,
654                None => {
655                    return Err(BootError::NotInitialised(workspace_root.to_path_buf()));
656                }
657            },
658            Layout::New => FileWorkspaceStore::new().load(workspace_root)?,
659        };
660
661        let settings = workspace.settings.clone();
662        let mut mounts: Vec<(Mount, Box<dyn MemBackend>)> =
663            Vec::with_capacity(workspace.mounts.len());
664        // Backend-instantiation failures quarantine the mem instead of
665        // failing the workspace (degrade, never disappear); the roster
666        // entry lands on the engine after construction.
667        let mut instantiate_quarantine: Vec<crate::engine::QuarantinedMem> = Vec::new();
668        for mount in workspace.mounts {
669            match instantiate_local_backend(&mount) {
670                Ok(backend) => mounts.push((mount, backend)),
671                Err(e) => instantiate_quarantine.push(crate::engine::QuarantinedMem {
672                    reason_code: e.code().to_string(),
673                    reason_message: e.to_string(),
674                    mount,
675                }),
676            }
677        }
678        // Folder-backend authoring path: authored schema packages live
679        // at the fixed `<workspace>/.memstead/schemas/<name>@<version>/`
680        // location — the folder analogue of the git-branch backend's
681        // `__MEMSTEAD:schemas/` ref. Read them through the folder
682        // `SchemaSource` (which no-ops when the directory is absent, so a
683        // workspace that authored no schemas resolves exactly as before —
684        // built-ins only). This is the folder boot path's schema-authoring
685        // path, which it lacked.
686        let fixed_dir = workspace_root.join(".memstead").join("schemas");
687        let (local, failed) = load_workspace_schemas_with_failures(Some(fixed_dir.as_path()));
688        // Root is known here, so an unresolved pin can be enriched with
689        // the never-installed-package hint before it surfaces.
690        let mut engine = Engine::from_mounts_inner(mounts, local, failed)
691            .map_err(|e| e.with_schema_install_probe(Some(workspace_root)))?;
692        engine.quarantined.extend(instantiate_quarantine);
693        engine.set_settings(settings);
694        engine.workspace_root = Some(workspace_root.to_path_buf());
695        engine.capture_roster_fingerprint();
696        // Load the workspace store's pipeline configs — the v2 single-record
697        // binding store — and expose them read-only. A malformed config
698        // surfaces a typed `StoreError::Parse` naming the file (early
699        // validation of operator-edited configs); an absent `projections/`
700        // directory resolves to empty. A file in a retired binding format
701        // quarantines its binding with `StoreError::LegacyProjectionStore`
702        // (the engine never reads a prior generation and no longer converts
703        // one; the binding is re-authored with `memstead projection init`).
704        engine.set_pipeline_configs(crate::pipeline_store::load_pipeline_configs(
705            workspace_root,
706        )?);
707        // The authoring meta-schemas are NOT published here. They are an
708        // editor convenience for hand-authored schema YAML, and publishing
709        // them at boot made every read of a mem write to the directory it
710        // read: pointing the binary at a workspace stamped a newer binary's
711        // meta-schemas over the ones on disk. That broke read-only mounts,
712        // installed third-party mems, and sealed corpora, which cannot be
713        // verified without being modified. Publishing now happens in the
714        // schema-authoring commands (`memstead schema new` / `validate` /
715        // `install`), the only paths that produce YAML an editor validates.
716        // Boot is a read; a read does not write.
717        Ok(engine)
718    }
719}
720
721/// Derive a [`MemRouterSnapshot`] from the engine's resolved mount
722/// list. Mirrors full's `Engine::from_init` mount-register loop so the
723/// runtime router carries the same writable/visible roster regardless
724/// of which backend serves each mem.
725///
726/// One pass over the mounts:
727/// - Writable mounts ([`MountCapability::Write`]) register via
728///   `add_writable` with the storage's worktree path. Folder mounts
729///   surface `MountStorage::Folder.path`; git-branch mounts surface
730///   `None` (the mem content lives only inside the gitdir).
731///   Archive mounts should never be writable; if one slips through,
732///   it registers with `dir: None`.
733/// - Read-only folder / git-branch mounts also register via
734///   `add_writable` with `dir: None`, then are *visible-only* —
735///   `is_writable` returns `false` because we follow up with a
736///   `remove_writable` (no-op for archives because archives are
737///   registered as `add_read_only`).
738///
739/// Actually we keep it simple: writable mounts go through
740/// `add_writable`; read-only mounts go through `add_read_only` with
741/// a synthesized archive-style path. For folder/git-branch read-only
742/// mounts we use the path the storage offers as the archive_path
743/// argument — semantically wrong but the router treats
744/// `add_read_only` data as opaque for visibility tracking. The two
745/// callers that care (`archive_path_for_mem`, `dir_for_mem`)
746/// branch on backend type at the handler level rather than reading
747/// these synthesized paths.
748///
749/// Origin is `MemOrigin::ExplicitToml` for every mount built from
750/// `Workspace.mounts` — the file-adapter case. `RuntimeCreated`
751/// origins land when `memstead_mem_create` migrates onto the unified
752/// engine and produces fresh runtime registrations.
753pub(crate) fn build_mem_router_from_mounts(mounts: &[MountedBackend]) -> MemRouterSnapshot {
754    let mut router = MemRouterSnapshot::new();
755    for m in mounts {
756        match m.mount.capability {
757            MountCapability::Write => {
758                let dir: Option<PathBuf> = match &m.mount.storage {
759                    MountStorage::Folder { path } => Some(path.clone()),
760                    MountStorage::GitBranch { .. } => None,
761                    MountStorage::Archive { .. } => None,
762                    // In-memory mounts have no on-disk working dir —
763                    // they register writable with `dir: None`, the same
764                    // shape mem-repo-backed mounts use.
765                    MountStorage::InMemory => None,
766                };
767                router.add_writable(m.mount.mem.clone(), dir, MemOrigin::ExplicitToml);
768            }
769            MountCapability::ReadOnly => match &m.mount.storage {
770                MountStorage::Archive { path } => {
771                    router.add_read_only(m.mount.mem.clone(), path.clone());
772                }
773                MountStorage::Folder { path } => {
774                    router.add_read_only(m.mount.mem.clone(), path.clone());
775                }
776                MountStorage::GitBranch { gitdir, .. } => {
777                    router.add_read_only(m.mount.mem.clone(), gitdir.clone());
778                }
779                // A read-only in-memory mount has no on-disk read
780                // source to register. The engine never produces this
781                // configuration (in-memory mounts are created writable
782                // for ephemeral sessions); handled here only to keep
783                // the match total.
784                MountStorage::InMemory => {}
785            },
786        }
787    }
788    router
789}
790
791/// Public re-export of [`resolve_builtin_schema_pin`] for the lifecycle
792/// orchestrators in `crate::mem_management`. Mirrors the orchestrators'
793/// `resolve_mem_schema` against the built-in catalogue;
794/// workspace-schema-registry resolution lifts later.
795pub fn resolve_builtin_schema_pin_pub(
796    pin: &memstead_schema::SchemaRef,
797    catalogue: &[Arc<memstead_schema::Schema>],
798) -> Option<Arc<memstead_schema::Schema>> {
799    resolve_builtin_schema_pin(pin, catalogue)
800}
801
802/// The newest version registered in the built-in catalogue under
803/// `name` — real `semver::Version` ordering (0.10.0 beats 0.9.0),
804/// never string ordering. `None` when no built-in carries the name.
805/// Feeds the `SCHEMA_GENERATIONS_BEHIND` boot hint.
806fn newest_builtin_version<'a>(
807    name: &str,
808    builtins: &'a [Arc<memstead_schema::Schema>],
809) -> Option<&'a semver::Version> {
810    builtins
811        .iter()
812        .filter(|s| s.manifest.name == name)
813        .map(|s| &s.version)
814        .max()
815}
816
817/// The engine's schema-pin resolver — the single named entry point a
818/// load path resolves a `name@version` pin through. Consults schema
819/// sources in a fixed order: **local storage** (the mem's own storage
820/// backend — folder `.memstead/schemas/` or the git-branch
821/// `__MEMSTEAD:schemas/` ref, layered first into the catalogue so it
822/// wins on `(name, version)` collision), **built-in** (compiled into the
823/// binary), **remote** (memstead.io, reserved, not implemented). The
824/// order is fixed in code — local-over-built-in by the catalogue's
825/// insertion precedence, remote always last. On a miss it yields the
826/// per-source [`SchemaSourceDiagnostic`] trail the `SCHEMA_NOT_FOUND`
827/// envelope carries.
828///
829/// Holds a borrowed view of the merged catalogue (`local ⧺ built-in`)
830/// the boot / register paths assemble, so resolution allocates nothing.
831pub struct SchemaResolver<'a> {
832    catalogue: &'a [Arc<memstead_schema::Schema>],
833}
834
835impl<'a> SchemaResolver<'a> {
836    /// Wrap the merged resolution catalogue (workspace-authored schemas
837    /// layered over the built-in set, local winning on collision).
838    pub fn new(catalogue: &'a [Arc<memstead_schema::Schema>]) -> Self {
839        Self { catalogue }
840    }
841
842    /// Resolve a pin to its schema, or the fixed-order source
843    /// diagnostics on a miss (fed straight into
844    /// `EngineError::SchemaNotFound`'s `sources`).
845    pub fn resolve(
846        &self,
847        pin: &memstead_schema::SchemaRef,
848    ) -> Result<Arc<memstead_schema::Schema>, Vec<crate::engine::error::SchemaSourceDiagnostic>>
849    {
850        resolve_builtin_schema_pin(pin, self.catalogue).ok_or_else(|| {
851            crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
852                &pin.name,
853                &pin.version,
854                self.catalogue,
855            )
856        })
857    }
858}
859
860/// Walk `schemas_dir` and load every immediate subdirectory as a
861/// workspace-authored schema. Each subdirectory must contain a
862/// `schema.yaml` manifest (and optional `types/*.yaml`) — silently
863/// skips entries that don't carry the manifest. `pub` so the folder
864/// `SchemaSource` and the below-boot repair path (memstead-git-branch)
865/// read through the same walker the boot path uses — one loader, no
866/// resolution fork between the booted and below-boot surfaces.
867pub fn load_workspace_schemas(
868    schemas_dir: Option<&Path>,
869) -> Result<Vec<Arc<memstead_schema::Schema>>, EngineError> {
870    Ok(load_workspace_schemas_with_failures(schemas_dir).0)
871}
872
873/// One workspace-authored schema package that failed to load — the
874/// package is SKIPPED (never fails the boot; degrade, never
875/// disappear), and a mem pinning it quarantines with this failure as
876/// its typed reason. `name`/`version` are best-effort peeks at the
877/// package's `schema.yaml` header so the pin match works even though
878/// the full load refused.
879#[derive(Debug, Clone)]
880pub struct FailedSchemaPackage {
881    pub path: PathBuf,
882    pub name: Option<String>,
883    pub version: Option<String>,
884    /// The loader's typed failure, rendered.
885    pub error: String,
886}
887
888/// The sealed schema package an archive-backed mount carries inside its
889/// `.mem` (`.memstead/schema/`), read through the same sealed reader
890/// the install validator uses, so the mount can resolve its pin from
891/// the archive itself. Empty for every other storage kind, for an
892/// archive mount with no on-disk path (the from-bytes boot already
893/// threads its embedded schemas through `extra_schemas`), and for an
894/// archive that cannot be read: the pin then fails to resolve and the
895/// mem quarantines with the ordinary not-found reason, which names the
896/// sources consulted.
897pub(crate) fn embedded_archive_schemas(mount: &Mount) -> Vec<Arc<Schema>> {
898    let crate::workspace::MountStorage::Archive { path } = &mount.storage else {
899        return Vec::new();
900    };
901    if path.as_os_str().is_empty() || !path.is_file() {
902        return Vec::new();
903    }
904    use crate::schema_source::SchemaSource as _;
905    crate::schema_source::ArchiveSchemaSource::from_path(path)
906        .ok()
907        .and_then(|source| source.read_schemas().ok())
908        .unwrap_or_default()
909}
910
911/// Tolerant form of [`load_workspace_schemas`]: broken packages are
912/// skipped and recorded instead of failing the whole walk (the
913/// historical `?` made one refusing package — e.g. a schema still on
914/// the retired `propagating_relationships` key after a binary
915/// upgrade — take every mem in the workspace down).
916pub fn load_workspace_schemas_with_failures(
917    schemas_dir: Option<&Path>,
918) -> (Vec<Arc<memstead_schema::Schema>>, Vec<FailedSchemaPackage>) {
919    let Some(dir) = schemas_dir else {
920        return (Vec::new(), Vec::new());
921    };
922    if !dir.is_dir() {
923        return (Vec::new(), Vec::new());
924    }
925    let entries = match std::fs::read_dir(dir) {
926        Ok(e) => e,
927        Err(_) => return (Vec::new(), Vec::new()),
928    };
929    let mut schemas: Vec<Arc<memstead_schema::Schema>> = Vec::new();
930    let mut failures: Vec<FailedSchemaPackage> = Vec::new();
931    for entry in entries.flatten() {
932        let path = entry.path();
933        if !path.is_dir() {
934            continue;
935        }
936        if !path.join("schema.yaml").is_file() {
937            continue;
938        }
939        match memstead_schema::load_schema_from_dir(&path) {
940            Ok(schema) => schemas.push(Arc::new(schema)),
941            Err(e) => {
942                // Best-effort header peek without a YAML dependency:
943                // top-level `name:` / `version:` are single-line
944                // scalars in every real package.
945                let header = std::fs::read_to_string(path.join("schema.yaml")).unwrap_or_default();
946                let peek = |k: &str| {
947                    header
948                        .lines()
949                        .find_map(|l| l.strip_prefix(&format!("{k}:")))
950                        .map(|v| v.trim().trim_matches('"').to_string())
951                        .filter(|v| !v.is_empty())
952                };
953                failures.push(FailedSchemaPackage {
954                    path: path.clone(),
955                    name: peek("name"),
956                    version: peek("version"),
957                    error: e.to_string(),
958                });
959            }
960        }
961    }
962    (schemas, failures)
963}
964
965pub(super) fn resolve_builtin_schema_pin(
966    pin: &memstead_schema::SchemaRef,
967    catalogue: &[Arc<memstead_schema::Schema>],
968) -> Option<Arc<memstead_schema::Schema>> {
969    catalogue
970        .iter()
971        .find(|s| {
972            let id = s.id();
973            id.0 == pin.name && id.1 == pin.version
974        })
975        .cloned()
976}
977
978/// The `MOUNT_UNBACKED` probe for one mount: `Some(warning)` when the
979/// storage the mount names does not exist (`missing_ref` /
980/// `missing_path`, from [`MemBackend::storage_present`]) or, when
981/// `entity_count` is known and zero, holds no entity (`empty`). A
982/// probe failure reads as present — best-effort, never a boot failure.
983/// Lazy mounts pass `None` for the count: their walk is deferred, so
984/// only the storage half is judged at boot.
985pub(super) fn unbacked_mount_warning(
986    mount: &crate::workspace::Mount,
987    backend: &dyn MemBackend,
988    entity_count: Option<usize>,
989) -> Option<WarningHint> {
990    use crate::ops::MountUnbackedReason;
991    use crate::workspace::MountStorage;
992    let (location, missing_reason) = match &mount.storage {
993        MountStorage::GitBranch { branch, .. } => (branch.clone(), MountUnbackedReason::MissingRef),
994        MountStorage::Folder { path } => {
995            (path.display().to_string(), MountUnbackedReason::MissingPath)
996        }
997        MountStorage::Archive { path } => {
998            (path.display().to_string(), MountUnbackedReason::MissingPath)
999        }
1000        MountStorage::InMemory => return None,
1001    };
1002    if !backend.storage_present().unwrap_or(true) {
1003        return Some(WarningHint::MountUnbacked {
1004            mem: mount.mem.clone(),
1005            reason: missing_reason,
1006            location,
1007        });
1008    }
1009    if entity_count == Some(0) {
1010        return Some(WarningHint::MountUnbacked {
1011            mem: mount.mem.clone(),
1012            reason: MountUnbackedReason::Empty,
1013            location,
1014        });
1015    }
1016    None
1017}
1018
1019pub(super) fn collect_source_entries(
1020    backend: &dyn MemBackend,
1021) -> Result<(Vec<SourceEntry>, Vec<SourceReadError>), EngineError> {
1022    // One backend pass for the whole mem: the git-branch backend
1023    // answers with a single tree walk, where the per-path route
1024    // re-inflated the root tree once per entity (quadratic in the
1025    // mem size — the boot cost the sizing curve reported as
1026    // super-linear).
1027    let reads = backend.read_all_entities()?;
1028    let mut entries: Vec<SourceEntry> = Vec::with_capacity(reads.len());
1029    let mut errors: Vec<SourceReadError> = Vec::new();
1030    for (path, read) in reads {
1031        match read {
1032            Ok(bytes) => match String::from_utf8(bytes) {
1033                Ok(content) => entries.push(SourceEntry {
1034                    relative_path: path.to_string_lossy().into_owned(),
1035                    source_path: path.clone(),
1036                    content,
1037                }),
1038                Err(e) => errors.push(SourceReadError {
1039                    source_path: path,
1040                    error: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
1041                }),
1042            },
1043            Err(e) => errors.push(SourceReadError {
1044                source_path: path,
1045                error: std::io::Error::other(e.to_string()),
1046            }),
1047        }
1048    }
1049    Ok((entries, errors))
1050}
1051
1052#[cfg(test)]
1053mod tests;