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