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::{BackendError, 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, 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 callers: Default::default(),
657 caller_synced: false,
658 caller_first_contact: false,
659 appeared_heads: Default::default(),
660 completed_commits: completed_at_boot
661 .into_iter()
662 .map(|(_, warning)| warning)
663 .collect(),
664 roster_fingerprint: None,
665 roster_subscribers: Arc::new(std::sync::Mutex::new((0, Vec::new()))),
666 recently_unmounted: std::collections::HashSet::new(),
667 #[cfg(test)]
668 inject_unmount_failure: None,
669 mutation_clock: Arc::new(crate::engine::mutation::wall_clock_now),
670 current_role: crate::vcs::Role::Unspecified,
671 current_identity: None,
672 current_actor: crate::vcs::Actor::Agent,
673 current_client: None,
674 })
675 }
676
677 /// Boot an engine from a workspace root using only the local
678 /// backends (folder + archive): the folder boot path. The CLI's
679 /// folder-workspace path reaches the engine through this entry
680 /// point; git-branch mounts quarantine unless a backend factory is set.
681 ///
682 /// Loads the workspace through [`crate::FileWorkspaceStore`],
683 /// instantiates each mount's backend via
684 /// [`crate::instantiate_local_backend`], and constructs the
685 /// engine via [`Engine::from_mounts`].
686 ///
687 /// Errors:
688 /// - [`Layout::Empty`](crate::Layout) → [`BootError::NotInitialised`]
689 /// - any mount declaring [`crate::workspace::MountStorage::GitBranch`]
690 /// → [`BootError::Instantiate`] wrapping
691 /// [`crate::InstantiateError::GitBranchBackendUnavailable`]
692 /// - underlying store / engine failures lift through the
693 /// `#[from]` conversions
694 pub fn from_workspace_root(workspace_root: &Path) -> Result<Self, BootError> {
695 use crate::workspace_store::{
696 FileWorkspaceStore, Layout, WorkspaceStoreAdapter, detect_layout,
697 instantiate_local_backend,
698 };
699
700 let workspace = match detect_layout(workspace_root) {
701 // Standalone collapse: a bare folder mem (`.memstead/config.json`,
702 // no `workspace.toml`) roots as a one-mount workspace rather than
703 // refusing — the lone-mem boot path is the unified one.
704 Layout::Empty => match crate::workspace_store::standalone_workspace(workspace_root) {
705 Some(ws) => ws,
706 None => {
707 return Err(BootError::NotInitialised(workspace_root.to_path_buf()));
708 }
709 },
710 Layout::New => FileWorkspaceStore::new().load(workspace_root)?,
711 };
712
713 let settings = workspace.settings.clone();
714 let mut mounts: Vec<(Mount, Box<dyn MemBackend>)> =
715 Vec::with_capacity(workspace.mounts.len());
716 // Backend-instantiation failures quarantine the mem instead of
717 // failing the workspace (degrade, never disappear); the roster
718 // entry lands on the engine after construction.
719 let mut instantiate_quarantine: Vec<crate::engine::QuarantinedMem> = Vec::new();
720 for mount in workspace.mounts {
721 match instantiate_local_backend(&mount) {
722 Ok(backend) => {
723 // Before the first load: a load waits for the mem's
724 // write lock no longer than the workspace says.
725 backend.set_lock_wait(settings.mutations.write_lock_timeout());
726 mounts.push((mount, backend))
727 }
728 Err(e) => instantiate_quarantine.push(crate::engine::QuarantinedMem {
729 reason_code: e.code().to_string(),
730 reason_message: e.to_string(),
731 mount,
732 }),
733 }
734 }
735 // Folder-backend authoring path: authored schema packages live
736 // at the fixed `<workspace>/.memstead/schemas/<name>@<version>/`
737 // location — the folder analogue of the git-branch backend's
738 // `__MEMSTEAD:schemas/` ref. Read them through the folder
739 // `SchemaSource` (which no-ops when the directory is absent, so a
740 // workspace that authored no schemas resolves exactly as before —
741 // built-ins only). This is the folder boot path's schema-authoring
742 // path, which it lacked.
743 let fixed_dir = workspace_root.join(".memstead").join("schemas");
744 let (local, failed) = load_workspace_schemas_with_failures(Some(fixed_dir.as_path()));
745 // Root is known here, so an unresolved pin can be enriched with
746 // the never-installed-package hint before it surfaces.
747 let mut engine = Engine::from_mounts_inner(mounts, local, failed)
748 .map_err(|e| e.with_schema_install_probe(Some(workspace_root)))?;
749 engine.quarantined.extend(instantiate_quarantine);
750 engine.set_settings(settings);
751 engine.workspace_root = Some(workspace_root.to_path_buf());
752 engine.capture_roster_fingerprint();
753 // Load the workspace store's pipeline configs — the v2 single-record
754 // binding store — and expose them read-only. A malformed config
755 // surfaces a typed `StoreError::Parse` naming the file (early
756 // validation of operator-edited configs); an absent `projections/`
757 // directory resolves to empty. A file in a retired binding format
758 // quarantines its binding with `StoreError::LegacyProjectionStore`
759 // (the engine never reads a prior generation and no longer converts
760 // one; the binding is re-authored with `memstead projection init`).
761 engine.set_pipeline_configs(crate::pipeline_store::load_pipeline_configs(
762 workspace_root,
763 )?);
764 // The authoring meta-schemas are NOT published here. They are an
765 // editor convenience for hand-authored schema YAML, and publishing
766 // them at boot made every read of a mem write to the directory it
767 // read: pointing the binary at a workspace stamped a newer binary's
768 // meta-schemas over the ones on disk. That broke read-only mounts,
769 // installed third-party mems, and sealed corpora, which cannot be
770 // verified without being modified. Publishing now happens in the
771 // schema-authoring commands (`memstead schema new` / `validate` /
772 // `install`), the only paths that produce YAML an editor validates.
773 // Boot is a read; a read does not write.
774 Ok(engine)
775 }
776}
777
778/// Derive a [`MemRouterSnapshot`] from the engine's resolved mount
779/// list. Mirrors full's `Engine::from_init` mount-register loop so the
780/// runtime router carries the same writable/visible roster regardless
781/// of which backend serves each mem.
782///
783/// One pass over the mounts through
784/// [`MemRouterSnapshot::add_mount`], the one rule boot and runtime
785/// registration share: writable mounts take the writable slot,
786/// read-only mounts the read-only slot whatever their storage.
787///
788/// Origin is `MemOrigin::ExplicitToml` for every mount built from
789/// `Workspace.mounts` — the file-adapter case. `RuntimeCreated`
790/// origins land when `memstead_mem_create` migrates onto the unified
791/// engine and produces fresh runtime registrations.
792pub(crate) fn build_mem_router_from_mounts(mounts: &[MountedBackend]) -> MemRouterSnapshot {
793 let mut router = MemRouterSnapshot::new();
794 for m in mounts {
795 router.add_mount(&m.mount, MemOrigin::ExplicitToml);
796 }
797 router
798}
799
800/// Public re-export of [`resolve_builtin_schema_pin`] for the lifecycle
801/// orchestrators in `crate::mem_management`. Mirrors the orchestrators'
802/// `resolve_mem_schema` against the built-in catalogue;
803/// workspace-schema-registry resolution lifts later.
804pub fn resolve_builtin_schema_pin_pub(
805 pin: &memstead_schema::SchemaRef,
806 catalogue: &[Arc<memstead_schema::Schema>],
807) -> Option<Arc<memstead_schema::Schema>> {
808 resolve_builtin_schema_pin(pin, catalogue)
809}
810
811/// The newest version registered in the built-in catalogue under
812/// `name` — real `semver::Version` ordering (0.10.0 beats 0.9.0),
813/// never string ordering. `None` when no built-in carries the name.
814/// Feeds the `SCHEMA_GENERATIONS_BEHIND` boot hint.
815fn newest_builtin_version<'a>(
816 name: &str,
817 builtins: &'a [Arc<memstead_schema::Schema>],
818) -> Option<&'a semver::Version> {
819 builtins
820 .iter()
821 .filter(|s| s.manifest.name == name)
822 .map(|s| &s.version)
823 .max()
824}
825
826/// The engine's schema-pin resolver — the single named entry point a
827/// load path resolves a `name@version` pin through. Consults schema
828/// sources in a fixed order: **local storage** (the mem's own storage
829/// backend — folder `.memstead/schemas/` or the git-branch
830/// `__MEMSTEAD:schemas/` ref, layered first into the catalogue so it
831/// wins on `(name, version)` collision), **built-in** (compiled into the
832/// binary), **remote** (a registry, reserved, not implemented). The
833/// order is fixed in code — local-over-built-in by the catalogue's
834/// insertion precedence, remote always last. On a miss it yields the
835/// per-source [`SchemaSourceDiagnostic`] trail the `SCHEMA_NOT_FOUND`
836/// envelope carries.
837///
838/// Holds a borrowed view of the merged catalogue (`local ⧺ built-in`)
839/// the boot / register paths assemble, so resolution allocates nothing.
840pub struct SchemaResolver<'a> {
841 catalogue: &'a [Arc<memstead_schema::Schema>],
842}
843
844impl<'a> SchemaResolver<'a> {
845 /// Wrap the merged resolution catalogue (workspace-authored schemas
846 /// layered over the built-in set, local winning on collision).
847 pub fn new(catalogue: &'a [Arc<memstead_schema::Schema>]) -> Self {
848 Self { catalogue }
849 }
850
851 /// Resolve a pin to its schema, or the fixed-order source
852 /// diagnostics on a miss (fed straight into
853 /// `EngineError::SchemaNotFound`'s `sources`).
854 pub fn resolve(
855 &self,
856 pin: &memstead_schema::SchemaRef,
857 ) -> Result<Arc<memstead_schema::Schema>, Vec<crate::engine::error::SchemaSourceDiagnostic>>
858 {
859 resolve_builtin_schema_pin(pin, self.catalogue).ok_or_else(|| {
860 crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
861 &pin.name,
862 &pin.version,
863 self.catalogue,
864 )
865 })
866 }
867}
868
869/// Walk `schemas_dir` and load every immediate subdirectory as a
870/// workspace-authored schema. Each subdirectory must contain a
871/// `schema.yaml` manifest (and optional `types/*.yaml`) — silently
872/// skips entries that don't carry the manifest. `pub` so the folder
873/// `SchemaSource` and the below-boot repair path (memstead-git-branch)
874/// read through the same walker the boot path uses — one loader, no
875/// resolution fork between the booted and below-boot surfaces.
876pub fn load_workspace_schemas(
877 schemas_dir: Option<&Path>,
878) -> Result<Vec<Arc<memstead_schema::Schema>>, EngineError> {
879 Ok(load_workspace_schemas_with_failures(schemas_dir).0)
880}
881
882/// One workspace-authored schema package that failed to load — the
883/// package is SKIPPED (never fails the boot; degrade, never
884/// disappear), and a mem pinning it quarantines with this failure as
885/// its typed reason. `name`/`version` are best-effort peeks at the
886/// package's `schema.yaml` header so the pin match works even though
887/// the full load refused.
888#[derive(Debug, Clone)]
889pub struct FailedSchemaPackage {
890 pub path: PathBuf,
891 pub name: Option<String>,
892 pub version: Option<String>,
893 /// The loader's typed failure, rendered.
894 pub error: String,
895}
896
897/// The sealed schema package an archive-backed mount carries inside its
898/// `.mem` (`.memstead/schema/`), read through the same sealed reader
899/// the install validator uses, so the mount can resolve its pin from
900/// the archive itself. Empty for every other storage kind, for an
901/// archive mount with no on-disk path (the from-bytes boot already
902/// threads its embedded schemas through `extra_schemas`), and for an
903/// archive that cannot be read: the pin then fails to resolve and the
904/// mem quarantines with the ordinary not-found reason, which names the
905/// sources consulted.
906pub(crate) fn embedded_archive_schemas(mount: &Mount) -> Vec<Arc<Schema>> {
907 let crate::workspace::MountStorage::Archive { path } = &mount.storage else {
908 return Vec::new();
909 };
910 if path.as_os_str().is_empty() || !path.is_file() {
911 return Vec::new();
912 }
913 use crate::schema_source::SchemaSource as _;
914 crate::schema_source::ArchiveSchemaSource::from_path(path)
915 .ok()
916 .and_then(|source| source.read_schemas().ok())
917 .unwrap_or_default()
918}
919
920/// Tolerant form of [`load_workspace_schemas`]: broken packages are
921/// skipped and recorded instead of failing the whole walk (the
922/// historical `?` made one refusing package — e.g. a schema still on
923/// the retired `propagating_relationships` key after a binary
924/// upgrade — take every mem in the workspace down).
925pub fn load_workspace_schemas_with_failures(
926 schemas_dir: Option<&Path>,
927) -> (Vec<Arc<memstead_schema::Schema>>, Vec<FailedSchemaPackage>) {
928 let Some(dir) = schemas_dir else {
929 return (Vec::new(), Vec::new());
930 };
931 if !dir.is_dir() {
932 return (Vec::new(), Vec::new());
933 }
934 let entries = match std::fs::read_dir(dir) {
935 Ok(e) => e,
936 Err(_) => return (Vec::new(), Vec::new()),
937 };
938 let mut schemas: Vec<Arc<memstead_schema::Schema>> = Vec::new();
939 let mut failures: Vec<FailedSchemaPackage> = Vec::new();
940 for entry in entries.flatten() {
941 let path = entry.path();
942 if !path.is_dir() {
943 continue;
944 }
945 if !path.join("schema.yaml").is_file() {
946 continue;
947 }
948 match memstead_schema::load_schema_from_dir(&path) {
949 Ok(schema) => schemas.push(Arc::new(schema)),
950 Err(e) => {
951 // Best-effort header peek without a YAML dependency:
952 // top-level `name:` / `version:` are single-line
953 // scalars in every real package.
954 let header = std::fs::read_to_string(path.join("schema.yaml")).unwrap_or_default();
955 let peek = |k: &str| {
956 header
957 .lines()
958 .find_map(|l| l.strip_prefix(&format!("{k}:")))
959 .map(|v| v.trim().trim_matches('"').to_string())
960 .filter(|v| !v.is_empty())
961 };
962 failures.push(FailedSchemaPackage {
963 path: path.clone(),
964 name: peek("name"),
965 version: peek("version"),
966 error: e.to_string(),
967 });
968 }
969 }
970 }
971 (schemas, failures)
972}
973
974pub(super) fn resolve_builtin_schema_pin(
975 pin: &memstead_schema::SchemaRef,
976 catalogue: &[Arc<memstead_schema::Schema>],
977) -> Option<Arc<memstead_schema::Schema>> {
978 catalogue
979 .iter()
980 .find(|s| {
981 let id = s.id();
982 id.0 == pin.name && id.1 == pin.version
983 })
984 .cloned()
985}
986
987/// Why a mount whose storage does not exist is quarantined, as
988/// `(reason_code, reason_message)`. A read-only mem installed into the
989/// archive cache whose file this machine's cache lacks is
990/// `ARCHIVE_NOT_INSTALLED`, with the install command as the repair and,
991/// when the cache holds the same mem under other content, that file
992/// named as what is NOT mounted in its place. Every other missing
993/// storage is `MOUNT_UNBACKED`.
994pub fn missing_storage_reason(mount: &crate::workspace::Mount) -> (String, String) {
995 use crate::workspace::MountStorage;
996 if let MountStorage::Archive { path } = &mount.storage
997 && let Some(file) = crate::workspace_store::installed_archive_file(path)
998 {
999 let mem = &mount.mem;
1000 let key = file
1001 .strip_prefix(&format!("{mem}-"))
1002 .and_then(|r| r.strip_suffix(".mem"))
1003 .unwrap_or("?");
1004 let dir = path
1005 .parent()
1006 .map(|p| p.display().to_string())
1007 .unwrap_or_default();
1008 let others: Vec<String> = path
1009 .parent()
1010 .and_then(|p| std::fs::read_dir(p).ok())
1011 .map(|rd| {
1012 rd.filter_map(|e| e.ok())
1013 .map(|e| e.file_name().to_string_lossy().into_owned())
1014 .filter(|n| {
1015 n.starts_with(&format!("{mem}-")) && n.ends_with(".mem") && *n != file
1016 })
1017 .collect()
1018 })
1019 .unwrap_or_default();
1020 let other_note = if others.is_empty() {
1021 String::new()
1022 } else {
1023 format!(
1024 " The cache holds {} with different content; it does not match the recorded \
1025 identity and is not mounted in its place.",
1026 others
1027 .iter()
1028 .map(|o| format!("`{o}`"))
1029 .collect::<Vec<_>>()
1030 .join(", ")
1031 )
1032 };
1033 return (
1034 "ARCHIVE_NOT_INSTALLED".to_string(),
1035 format!(
1036 "mem `{mem}` is an installed archive (`{file}`, content key `{key}`) that this \
1037 machine's archive cache ({dir}) does not hold.{other_note} Install it here, \
1038 from the archive file (`memstead install <path to {file}>`) or from the \
1039 registry it was published to (`memstead install <scope>/{mem}`), then run \
1040 `memstead reload --full`."
1041 ),
1042 );
1043 }
1044 let location = match &mount.storage {
1045 MountStorage::GitBranch { branch, .. } => branch.clone(),
1046 MountStorage::Folder { path } | MountStorage::Archive { path } => {
1047 path.display().to_string()
1048 }
1049 MountStorage::InMemory => String::new(),
1050 };
1051 (
1052 "MOUNT_UNBACKED".to_string(),
1053 format!(
1054 "the mount's storage is gone ({location}); it is configured but cannot \
1055 serve, so it is held out of the roster rather than answering reads \
1056 with an empty graph"
1057 ),
1058 )
1059}
1060
1061/// The quarantine reason for a mount whose backend could not be
1062/// instantiated: an archive mount whose file does not exist is the
1063/// missing-storage case ([`missing_storage_reason`]); any other failure
1064/// keeps the instantiation error's own code and message.
1065pub fn instantiate_failure_reason(
1066 mount: &crate::workspace::Mount,
1067 code: &str,
1068 message: String,
1069) -> (String, String) {
1070 if let crate::workspace::MountStorage::Archive { path } = &mount.storage
1071 && !path.exists()
1072 {
1073 return missing_storage_reason(mount);
1074 }
1075 (code.to_string(), message)
1076}
1077
1078/// The `MOUNT_UNBACKED` probe for one mount: `Some(warning)` when the
1079/// storage the mount names does not exist (`missing_ref` /
1080/// `missing_path`, from [`MemBackend::storage_present`]). A probe
1081/// failure reads as present: best-effort, never a boot failure. An
1082/// empty mem (`empty`) is not stored here: the engine's own writes
1083/// change it, so it is derived from the live store when read
1084/// ([`Engine::unbacked_mount_warnings`]).
1085pub(super) fn unbacked_mount_warning(
1086 mount: &crate::workspace::Mount,
1087 backend: &dyn MemBackend,
1088) -> Option<WarningHint> {
1089 use crate::ops::MountUnbackedReason;
1090 use crate::workspace::MountStorage;
1091 let (location, missing_reason) = match &mount.storage {
1092 MountStorage::GitBranch { branch, .. } => (branch.clone(), MountUnbackedReason::MissingRef),
1093 MountStorage::Folder { path } => {
1094 (path.display().to_string(), MountUnbackedReason::MissingPath)
1095 }
1096 MountStorage::Archive { path } => {
1097 (path.display().to_string(), MountUnbackedReason::MissingPath)
1098 }
1099 MountStorage::InMemory => return None,
1100 };
1101 if !backend.storage_present().unwrap_or(true) {
1102 return Some(WarningHint::MountUnbacked {
1103 mem: mount.mem.clone(),
1104 reason: missing_reason,
1105 location,
1106 });
1107 }
1108 None
1109}
1110
1111/// What one whole-mem read produced: the entries, the per-path read
1112/// failures, and the warning for an interrupted commit the read
1113/// completed first.
1114pub(super) struct SourceRead {
1115 pub(super) entries: Vec<SourceEntry>,
1116 pub(super) read_errors: Vec<SourceReadError>,
1117 /// Files storage listed and could not deliver (an IO failure, not a
1118 /// file that reads and does not decode). A view built without them
1119 /// is incomplete in a way nothing in it shows: the entity is simply
1120 /// absent, and a write of that id would land over the unread file.
1121 pub(super) unread: Vec<String>,
1122}
1123
1124impl SourceRead {
1125 /// Why a view built from this read must take no write, if it must
1126 /// not.
1127 pub(super) fn incomplete(&self) -> Option<String> {
1128 (!self.unread.is_empty()).then(|| {
1129 format!(
1130 "{} file(s) could not be read from storage: {}",
1131 self.unread.len(),
1132 self.unread.join(", ")
1133 )
1134 })
1135 }
1136}
1137
1138/// Read every entity of `mem` for a load. The one funnel boot, reload
1139/// and a runtime mount share, so the storage recovery in front of the
1140/// read cannot be left out by one of them: a commit that was decided
1141/// and cut off is completed before a byte is read, and a mem is never
1142/// loaded with part of a commit visible.
1143///
1144/// `completed` receives the warning for an interrupted commit this call
1145/// completed, as soon as it is completed: the read that follows can
1146/// still fail, and the completion happened all the same.
1147pub(super) fn collect_source_entries(
1148 mem: &str,
1149 backend: &dyn MemBackend,
1150 completed: &mut Option<WarningHint>,
1151) -> Result<SourceRead, EngineError> {
1152 // A commit that is decided and cannot be completed now (another
1153 // process holds the mem's write lock past the workspace's deadline,
1154 // or a step of the completion failed) is the mem's own typed
1155 // condition, named with the mem: the caller, or the quarantine
1156 // roster of a boot, reads `COMMIT_NOT_APPLIED` and not a generic
1157 // storage failure.
1158 let named = |e: BackendError| match e {
1159 BackendError::CommitNotApplied { detail } => EngineError::CommitNotApplied {
1160 mem: mem.to_string(),
1161 detail,
1162 },
1163 other => EngineError::from(other),
1164 };
1165 *completed = backend
1166 .complete_interrupted_commit()
1167 .map_err(named)?
1168 .map(|commit| WarningHint::InterruptedCommitCompleted {
1169 mem: mem.to_string(),
1170 files: commit.files,
1171 });
1172 // One backend pass for the whole mem: the git-branch backend
1173 // answers with a single tree walk, where the per-path route
1174 // re-inflated the root tree once per entity (quadratic in the
1175 // mem size — the boot cost the sizing curve reported as
1176 // super-linear).
1177 let reads = backend.read_all_entities().map_err(named)?;
1178 let mut entries: Vec<SourceEntry> = Vec::with_capacity(reads.len());
1179 let mut errors: Vec<SourceReadError> = Vec::new();
1180 let mut unread: Vec<String> = Vec::new();
1181 for (path, read) in reads {
1182 match read {
1183 Ok(bytes) => match String::from_utf8(bytes) {
1184 Ok(content) => entries.push(SourceEntry {
1185 relative_path: path.to_string_lossy().into_owned(),
1186 source_path: path.clone(),
1187 content,
1188 }),
1189 Err(e) => errors.push(SourceReadError {
1190 source_path: path,
1191 error: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
1192 }),
1193 },
1194 Err(e) => {
1195 unread.push(path.to_string_lossy().into_owned());
1196 errors.push(SourceReadError {
1197 source_path: path,
1198 error: std::io::Error::other(e.to_string()),
1199 });
1200 }
1201 }
1202 }
1203 Ok(SourceRead {
1204 entries,
1205 read_errors: errors,
1206 unread,
1207 })
1208}
1209
1210#[cfg(test)]
1211mod tests;