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