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