Skip to main content

memstead_base/validator/
mod.rs

1//! Strict ingress validator for sealed `.mem` archives.
2//!
3//! Single trust boundary: every byte that enters any cache passes
4//! through `validate_and_normalize_archive`. Parses the zip, validates
5//! each markdown file against its declared schema over the **raw
6//! bytes** (tolerant-parser fallbacks are the wrong default at
7//! ingress), builds a `Store`, runs community detection, and
8//! canonically re-packs. Fails hard on any violation.
9//!
10//! Pure function: takes `&[u8]`, returns `Result<ValidatedMem,
11//! ValidationError>`, performs no I/O.
12
13use crate::entity::Entity;
14use crate::graph::LouvainOutput;
15use crate::store::Store;
16
17#[cfg(test)]
18mod adversarial;
19pub mod archive;
20pub mod canonical;
21pub mod config;
22pub mod graph;
23pub mod ids;
24pub mod strict;
25
26pub use graph::DanglingCrossMemEdge;
27pub use memstead_schema::PublishedMemConfig;
28
29/// Numeric limits enforced by archive-level checks. Callers that need
30/// different caps (e.g. enterprise registry) construct a custom
31/// instance; the default matches the published registry limits.
32#[derive(Debug, Clone, Copy)]
33pub struct ValidatorLimits {
34    pub max_compressed_archive: u64,
35    pub max_uncompressed_archive: u64,
36    pub max_uncompressed_entry: u64,
37    pub max_config_file: u64,
38    pub max_file_count: u32,
39    pub max_path_length: usize,
40    pub max_path_depth: usize,
41}
42
43impl ValidatorLimits {
44    pub const DEFAULT: Self = Self {
45        max_compressed_archive: 2 * 1024 * 1024,
46        max_uncompressed_archive: 20 * 1024 * 1024,
47        max_uncompressed_entry: 1024 * 1024,
48        max_config_file: 64 * 1024,
49        max_file_count: 10_000,
50        max_path_length: 512,
51        max_path_depth: 16,
52    };
53}
54
55impl Default for ValidatorLimits {
56    fn default() -> Self {
57        Self::DEFAULT
58    }
59}
60
61/// Outcome of a bounded zip-entry read.
62pub(crate) enum BoundedZipRead {
63    Within(Vec<u8>),
64    /// The entry's decompressed content exceeds the cap. The actual
65    /// size is unknowable without reading it all — which is the attack —
66    /// so only the cap is reported.
67    ExceedsCap,
68}
69
70/// Read a zip entry with a hard cap on decompressed bytes.
71///
72/// Every direct archive read path shares this so decompression is never
73/// sized by an attacker-declared header: the buffer grows only with
74/// bytes actually decompressed, and reading stops at `cap + 1`. The same
75/// idiom `archive::extract_entries` uses for the ingress validator.
76pub(crate) fn read_zip_entry_bounded(
77    reader: &mut impl std::io::Read,
78    cap: u64,
79) -> std::io::Result<BoundedZipRead> {
80    use std::io::Read as _;
81    let mut buf = Vec::new();
82    reader.take(cap + 1).read_to_end(&mut buf)?;
83    if buf.len() as u64 > cap {
84        return Ok(BoundedZipRead::ExceedsCap);
85    }
86    Ok(BoundedZipRead::Within(buf))
87}
88
89/// Which size cap a given `SizeCapExceeded` refers to.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum SizeCapKind {
92    CompressedArchive,
93    UncompressedArchive,
94    UncompressedEntry,
95    ConfigFile,
96    EntryCount,
97}
98
99/// Aggregate statistics reported alongside a successful validation.
100#[derive(Debug, Clone)]
101pub struct MemStats {
102    pub entities: usize,
103    pub edges: usize,
104    pub communities: usize,
105    pub schema: memstead_schema::SchemaRef,
106}
107
108/// The successful output of validation: strict-checked entities, a
109/// built graph, community assignments, and the canonical bytes that
110/// should replace the input in any cache.
111#[derive(Debug)]
112pub struct ValidatedMem {
113    pub config: PublishedMemConfig,
114    pub entities: Vec<Entity>,
115    pub store: Store,
116    pub communities: LouvainOutput,
117    pub stats: MemStats,
118    pub canonical_bytes: Vec<u8>,
119    /// Schema source files found under `.memstead/schema/` in the
120    /// archive.
121    /// Empty only if the archive was never meant to carry a schema
122    /// (callers typically short-circuit before reaching here).
123    /// `format: 2` archives (top-level `schema/` tree) are rejected
124    /// upstream in `check_format` and never materialize here.
125    pub schema_files: Vec<archive::SchemaFile>,
126    /// Relationships whose target lives outside this mem — edges that
127    /// can't resolve inside the single-mem archive. Always empty when
128    /// produced via the strict (`validate_and_normalize_archive`) path:
129    /// that path refuses on the first such edge. Populated only via
130    /// [`validate_and_normalize_archive_lenient`] (the export side),
131    /// which collects them so `export` can warn
132    /// (`DANGLING_CROSS_MEM_EDGE_IN_EXPORT`) rather than refuse.
133    pub dangling_cross_mem_edges: Vec<graph::DanglingCrossMemEdge>,
134    /// Raw bytes of the archive's authoring-provenance payload
135    /// (`.memstead/provenance.json`), or `None` when the archive carries
136    /// none. Surfaced so the registry and other validation consumers can
137    /// expose provenance without re-extracting the archive.
138    pub provenance_bytes: Option<Vec<u8>>,
139    /// Raw bytes of the archive's engine-owned anchors sidecar
140    /// (`.memstead/anchors.json`), or `None` when the archive carries
141    /// none. Structurally validated at extract time and threaded verbatim
142    /// through the canonical re-pack so publish/normalize does not strip
143    /// provenance anchors.
144    pub anchors_bytes: Option<Vec<u8>>,
145    /// Raw bytes of the archive's sealed check-records member
146    /// (`.memstead/checks.json`), or `None` when the archive carries
147    /// none. Validated at extract time (shape, vocabulary, entity
148    /// roster) and threaded verbatim through the canonical re-pack so
149    /// publish/normalize does not strip the records.
150    pub checks_bytes: Option<Vec<u8>>,
151    /// Raw bytes of the archive's proposal record
152    /// (`.memstead/proposals.json`), or `None` when the archive carries
153    /// none. Validated at extract time (it parses as a record) and
154    /// threaded verbatim through the canonical re-pack so
155    /// publish/normalize does not strip the dispositions.
156    pub proposals_bytes: Option<Vec<u8>>,
157}
158
159/// Every reason the validator can reject an archive. Each variant
160/// carries enough context (file path, reason string, size numbers) to
161/// give the caller an actionable error.
162#[derive(Debug, thiserror::Error)]
163pub enum ValidationError {
164    // Archive-level
165    #[error("zip error: {0}")]
166    Zip(String),
167    #[error("symlink entry is not allowed: {0}")]
168    Symlink(String),
169    #[error("unknown file type in archive: {0}")]
170    UnknownFile(String),
171    #[error("duplicate entry path: {0}")]
172    DuplicateEntry(String),
173    #[error("path too long ({len} > {limit}): {path}")]
174    PathTooLong {
175        path: String,
176        len: usize,
177        limit: usize,
178    },
179    #[error("path too deep ({depth} > {limit}): {path}")]
180    PathTooDeep {
181        path: String,
182        depth: usize,
183        limit: usize,
184    },
185    #[error("size cap exceeded ({kind:?}): {got} > {limit}")]
186    SizeCapExceeded {
187        kind: SizeCapKind,
188        got: u64,
189        limit: u64,
190    },
191    #[error("invalid UTF-8 at {path} offset {offset}")]
192    Utf8 { path: String, offset: usize },
193
194    // Config-level
195    #[error("archive is missing .memstead/config.json")]
196    MissingConfig,
197    #[error("invalid anchors sidecar (.memstead/anchors.json): {reason}")]
198    InvalidAnchorsMember { reason: String },
199    #[error("invalid sealed check records (.memstead/checks.json): {reason}")]
200    InvalidChecksMember { reason: String },
201    #[error("invalid proposal record (.memstead/proposals.json): {reason}")]
202    InvalidProposalsMember { reason: String },
203    #[error("invalid config: {reason}")]
204    InvalidConfig { reason: String },
205    #[error("invalid name: {reason}")]
206    InvalidName { reason: String },
207    #[error("invalid version: {reason}")]
208    InvalidVersion { reason: String },
209    #[error("unsupported format: {got} (expected {expected})")]
210    UnsupportedFormat { got: u32, expected: u32 },
211    #[error("unknown schema '{name}@{version}' — not registered")]
212    UnknownSchema {
213        name: String,
214        version: semver::Version,
215    },
216    #[error("unknown type: {name}")]
217    UnknownType { name: String },
218
219    #[error("embedded schema failed validation: {reason}")]
220    EmbeddedSchemaInvalid { reason: String },
221    #[error(
222        "embedded schema pins '{embedded}' but `.memstead/config.json` declares '{declared}' — archive is inconsistent"
223    )]
224    EmbeddedSchemaMismatch { embedded: String, declared: String },
225
226    // Entity-level
227    #[error("missing frontmatter at {path}")]
228    MissingFrontmatter { path: String },
229    #[error("invalid frontmatter at {path}: {reason}")]
230    InvalidFrontmatter { path: String, reason: String },
231    #[error("unknown frontmatter key at {path}: {key}")]
232    UnknownFrontmatterKey { path: String, key: String },
233    #[error("missing required field at {path}: {field}")]
234    MissingRequiredField { path: String, field: String },
235    #[error("field type mismatch at {path}: {field} (expected {expected})")]
236    FieldTypeMismatch {
237        path: String,
238        field: String,
239        expected: String,
240    },
241    #[error("enum violation at {path}: {field} = {got}")]
242    EnumViolation {
243        path: String,
244        field: String,
245        got: String,
246    },
247    #[error("missing `# Title` at {path}")]
248    MissingTitle { path: String },
249    #[error("missing required section at {path}: {section}")]
250    MissingRequiredSection { path: String, section: String },
251    #[error("unknown section at {path}: {section}")]
252    UnknownSection { path: String, section: String },
253    #[error("malformed relationship line at {path}: {line}")]
254    InvalidRelationshipLine { path: String, line: String },
255    #[error("invalid relationship type at {path}: {rel_type}")]
256    InvalidRelationshipType { path: String, rel_type: String },
257    #[error("invalid wiki-link at {path}: {link} ({reason})")]
258    InvalidWikiLink {
259        path: String,
260        link: String,
261        reason: String,
262    },
263    #[error("unbalanced brackets at {path}")]
264    UnbalancedBrackets { path: String },
265
266    // Cross-archive / graph
267    #[error("duplicate entity id {id} from {} and {}", paths.0, paths.1)]
268    DuplicateEntityId { id: String, paths: (String, String) },
269    #[error("cross-mem relationship at {path}: target {target}")]
270    CrossMemRelationship { path: String, target: String },
271    #[error("graph construction failed: {0}")]
272    GraphConstructionFailed(String),
273    #[error("community detection failed: {0}")]
274    CommunityDetectionFailed(String),
275}
276
277impl ValidationError {
278    /// The wire code every surface reports for this refusal: a schema the
279    /// archive carries that does not hold is its own condition, every other
280    /// reason is the archive failing validation.
281    pub fn code(&self) -> &'static str {
282        match self {
283            ValidationError::EmbeddedSchemaInvalid { .. }
284            | ValidationError::EmbeddedSchemaMismatch { .. } => "EMBEDDED_SCHEMA_INVALID",
285            _ => "ARCHIVE_VALIDATION_FAILED",
286        }
287    }
288}
289
290/// The single ingress entry point. Callers (registry publish, CLI
291/// install, MCP read-mem attach) hand in
292/// bytes and receive either a `ValidatedMem` with canonical bytes
293/// to install, or a typed `ValidationError`.
294///
295/// Runs every check with `ValidatorLimits::DEFAULT`. Use
296/// `validate_and_normalize_archive_with_limits` to supply custom caps
297/// (the registry may allow larger archives; the CLI keeps defaults).
298pub fn validate_and_normalize_archive(bytes: &[u8]) -> Result<ValidatedMem, ValidationError> {
299    validate_and_normalize_archive_with_limits(bytes, &ValidatorLimits::DEFAULT)
300}
301
302pub fn validate_and_normalize_archive_with_limits(
303    bytes: &[u8],
304    limits: &ValidatorLimits,
305) -> Result<ValidatedMem, ValidationError> {
306    // Strict posture: a cross-mem edge refuses the archive — the
307    // install / archive-load contract.
308    validate_impl(bytes, limits, true)
309}
310
311/// Export-side validation: identical strict checks, except a cross-mem
312/// edge whose target won't travel inside this single-mem archive is
313/// **collected** onto [`ValidatedMem::dangling_cross_mem_edges`]
314/// instead of refused. Lets `export` warn
315/// (`DANGLING_CROSS_MEM_EDGE_IN_EXPORT`) and still produce the archive,
316/// while `install` keeps refusing the same edge — one predicate, two
317/// postures. Every other strict
318/// check (schema drift, malformed markdown, …) still refuses, so export
319/// never emits an otherwise-invalid archive.
320pub fn validate_and_normalize_archive_lenient(
321    bytes: &[u8],
322) -> Result<ValidatedMem, ValidationError> {
323    validate_impl(bytes, &ValidatorLimits::DEFAULT, false)
324}
325
326/// The output of [`make_archive_self_contained`]: the canonical bytes of
327/// an archive that now passes strict validation, and every cross-mem
328/// edge that was dropped to get there.
329#[derive(Debug)]
330pub struct SelfContainedArchive {
331    /// Strictly validated, canonically packed bytes, ready for `install`.
332    pub bytes: Vec<u8>,
333    /// The relationship rows removed: each named the entity that carried
334    /// it and the target in the other mem. Empty when the input was
335    /// already self-contained (then `bytes` is its canonical form).
336    pub dropped: Vec<graph::DanglingCrossMemEdge>,
337}
338
339/// Make an archive self-contained: drop every `## Relationships` row
340/// whose target lives in another mem, re-pack canonically, and prove the
341/// result with the strict validator (the same pass `install` runs).
342///
343/// WHY: `export --format mem` admits cross-mem edges (it warns
344/// `DANGLING_CROSS_MEM_EDGE_IN_EXPORT` and still produces the archive),
345/// while `install` refuses them, so a mem that references its sibling
346/// mems could be exported but never installed anywhere, not even back
347/// into the workspace it came from. This project's own workspace's retired
348/// `features` mem carried fifty such rows, every one an alias row
349/// synthesised from a body wiki-link, so dropping the rows loses
350/// nothing the body does not still say. Rows that are NOT backed by a
351/// body link are dropped too; the caller reports every dropped edge so
352/// the author can see what the package no longer carries as a typed
353/// edge. Section text (body wiki-links included) is never touched.
354pub fn make_archive_self_contained(bytes: &[u8]) -> Result<SelfContainedArchive, ValidationError> {
355    let lenient = validate_impl(bytes, &ValidatorLimits::DEFAULT, false)?;
356    if lenient.dangling_cross_mem_edges.is_empty() {
357        return Ok(SelfContainedArchive {
358            bytes: lenient.canonical_bytes,
359            dropped: Vec::new(),
360        });
361    }
362    let mem_name = lenient.config.name.clone();
363    let mut dropped = Vec::new();
364    let mut entities = lenient.entities;
365    for entity in &mut entities {
366        let path = entity.file_path.clone();
367        entity.relationships.retain(|rel| {
368            let keep = rel.target.mem() == mem_name;
369            if !keep {
370                dropped.push(graph::DanglingCrossMemEdge {
371                    entity_path: path.clone(),
372                    target_id: rel.target.as_ref().to_string(),
373                    target_mem: rel.target.mem().to_string(),
374                });
375            }
376            keep
377        });
378    }
379    let embedded_schema = check_embedded_schema(&lenient.schema_files, &lenient.config)?;
380    let repacked = canonical::canonical_bytes(
381        &lenient.config,
382        &entities,
383        &lenient.schema_files,
384        embedded_schema.as_ref(),
385        lenient.provenance_bytes.as_deref(),
386        lenient.anchors_bytes.as_deref(),
387        lenient.checks_bytes.as_deref(),
388        lenient.proposals_bytes.as_deref(),
389    )?;
390    // The strict pass is the proof: what comes out is exactly what
391    // `install` accepts, or this returns the typed refusal.
392    let strict = validate_impl(&repacked, &ValidatorLimits::DEFAULT, true)?;
393    Ok(SelfContainedArchive {
394        bytes: strict.canonical_bytes,
395        dropped,
396    })
397}
398
399/// Cross-mem-only scan over an archive's bytes: extract + tolerant
400/// parse + the shared cross-mem predicate
401/// ([`graph::dangling_cross_mem_edges_in`]), with **no** strict
402/// section/field validation and no store construction. Returns every
403/// edge whose target won't travel inside this single-mem archive.
404///
405/// This is the lightweight export-side detector for backends that don't
406/// otherwise run the full archive validator (the git-branch export):
407/// it surfaces exactly the edges `install` will refuse on, without
408/// taking on the strict-validation refusal posture (which is a separate,
409/// pre-existing concern). Tolerant parse means section/field drift does
410/// not refuse here — only genuinely-unparseable markdown does.
411pub fn collect_dangling_cross_mem_edges_from_bytes(
412    bytes: &[u8],
413) -> Result<Vec<graph::DanglingCrossMemEdge>, ValidationError> {
414    let limits = &ValidatorLimits::DEFAULT;
415    let entries = archive::extract_entries(bytes, limits)?;
416    let config = config::parse_config_bytes(&entries.config_bytes)?;
417    let embedded_schema = check_embedded_schema(&entries.schema_files, &config)?;
418    let fallback_schema = graph::resolve_fallback_type(None);
419
420    let mut parse_results = Vec::with_capacity(entries.markdown_files.len());
421    for md in &entries.markdown_files {
422        let raw = md.content.as_str();
423        let type_name = crate::entity::parser::peek_type_from_frontmatter(raw);
424        let peeked_schema = type_name
425            .as_deref()
426            .and_then(|n| {
427                embedded_schema
428                    .as_ref()
429                    .and_then(|s| s.get_type(n))
430                    .or_else(|| memstead_schema::type_by_name(n))
431            })
432            .unwrap_or_else(|| fallback_schema.clone());
433
434        let parse_result =
435            crate::entity::parser::parse_markdown(raw, &md.path, &peeked_schema, &config.name)
436                .map_err(|e| map_parse_error(&md.path, &e))?;
437        parse_results.push(parse_result);
438    }
439
440    Ok(graph::dangling_cross_mem_edges_in(
441        &parse_results,
442        &config.name,
443    ))
444}
445
446fn validate_impl(
447    bytes: &[u8],
448    limits: &ValidatorLimits,
449    cross_mem_as_error: bool,
450) -> Result<ValidatedMem, ValidationError> {
451    // 1. Archive-level: unzip, enforce caps + whitelist, UTF-8 decode.
452    let entries = archive::extract_entries(bytes, limits)?;
453
454    // 2. Config: strict-parse the meta-dir config bytes.
455    let config = config::parse_config_bytes(&entries.config_bytes)?;
456
457    // 2b. Embedded schema integrity. Any `.memstead/schema/` tree in the
458    //     archive must (a) parse via the full loader and (b) declare
459    //     the same `(name, version)` as `config.schema`. An archive
460    //     whose embedded schema doesn't match its declared pin would
461    //     extract schema-a into the cache while loading entities
462    //     against schema-b — exactly the silent corruption the strict
463    //     ingress boundary exists to prevent. The returned schema
464    //     (when an embedded `.memstead/schema/` tree was present) is reused below as the
465    //     authoritative source for per-entity type resolution so a
466    //     user-defined schema's types validate against its own
467    //     metadata rules, not against the builtin `default` fallback.
468    let embedded_schema = check_embedded_schema(&entries.schema_files, &config)?;
469
470    // 3. Decide the fallback type the Store will use for
471    //    inline-link relationships and edge weights. Every listed
472    //    type in the config has already resolved — graph.rs picks
473    //    the first one; the runtime does the same during bulk-load
474    //    via `engine_fallback_type` (spec), but we prefer the
475    //    author's declared choice when available.
476    let fallback_schema = graph::resolve_fallback_type(None);
477
478    // 4. Per-entity: tolerant-parse + strict-check against raw bytes.
479    //    The same parse_markdown call the runtime uses; strict layer
480    //    catches what the tolerant parser papers over. When the
481    //    archive carries an embedded schema, its type table wins over
482    //    the builtin-default lookup; this lets a `recipe` archive
483    //    validate its `recipe` entities against the `recipe` type
484    //    definition instead of silently falling back to `spec`.
485    let mut parse_results = Vec::with_capacity(entries.markdown_files.len());
486    for md in &entries.markdown_files {
487        let raw = md.content.as_str();
488
489        let type_name = crate::entity::parser::peek_type_from_frontmatter(raw);
490        let peeked_schema = type_name
491            .as_deref()
492            .and_then(|n| {
493                embedded_schema
494                    .as_ref()
495                    .and_then(|s| s.get_type(n))
496                    .or_else(|| memstead_schema::type_by_name(n))
497            })
498            .unwrap_or_else(|| fallback_schema.clone());
499
500        let parse_result =
501            crate::entity::parser::parse_markdown(raw, &md.path, &peeked_schema, &config.name)
502                .map_err(|e| map_parse_error(&md.path, &e))?;
503
504        strict::validate_strict(raw, &parse_result.entity, &peeked_schema, &md.path)?;
505
506        parse_results.push(parse_result);
507    }
508
509    // 5. Entity-ID uniqueness (after all files parsed, before store
510    //    construction — a duplicate would silently overwrite in
511    //    upsert).
512    let parsed_entities: Vec<Entity> = parse_results.iter().map(|pr| pr.entity.clone()).collect();
513    ids::check_unique_ids(&parsed_entities)?;
514
515    // 6. Graph: build store, detect communities, cross-mem guard.
516    let graph_result = graph::build_and_check(
517        parse_results,
518        &fallback_schema,
519        &config.name,
520        cross_mem_as_error,
521    )?;
522
523    let (entity_count, edge_count) = graph::tally(&graph_result.store);
524
525    let stats = MemStats {
526        entities: entity_count,
527        edges: edge_count,
528        communities: graph_result.communities.count,
529        schema: config.schema.clone(),
530    };
531
532    // 7. Canonical re-pack: regenerate markdown + canonical JSON,
533    //    propagate schema files verbatim, write sorted zip with fixed
534    //    mtime. Pinned by golden tests.
535    let entities_for_canonical: Vec<Entity> = graph_result
536        .store
537        .all_entities()
538        .filter(|e| !e.stub)
539        .cloned()
540        .collect();
541    let canonical_bytes = canonical::canonical_bytes(
542        &config,
543        &entities_for_canonical,
544        &entries.schema_files,
545        embedded_schema.as_ref(),
546        entries.provenance_bytes.as_deref(),
547        entries.anchors_bytes.as_deref(),
548        entries.checks_bytes.as_deref(),
549        entries.proposals_bytes.as_deref(),
550    )?;
551
552    Ok(ValidatedMem {
553        config,
554        entities: parsed_entities,
555        store: graph_result.store,
556        communities: graph_result.communities,
557        stats,
558        canonical_bytes,
559        schema_files: entries.schema_files,
560        dangling_cross_mem_edges: graph_result.dangling_cross_mem_edges,
561        provenance_bytes: entries.provenance_bytes,
562        anchors_bytes: entries.anchors_bytes,
563        checks_bytes: entries.checks_bytes,
564        proposals_bytes: entries.proposals_bytes,
565    })
566}
567
568/// Run the embedded schema through the full loader and confirm its
569/// manifest identity matches the config's `schema` pin. Returns the
570/// loaded schema so downstream passes (entity parse/strict/canonical
571/// repack) can resolve user-defined types against it. Empty
572/// `schema_files` yields `Ok(None)` — the Engine's load-side
573/// extraction pass then looks up the pin in the existing registry.
574/// The `format: 3` publish path always embeds under `.memstead/schema/`,
575/// so post-migration archives always hit the integrity branch.
576fn check_embedded_schema(
577    schema_files: &[archive::SchemaFile],
578    config: &PublishedMemConfig,
579) -> Result<Option<std::sync::Arc<memstead_schema::Schema>>, ValidationError> {
580    if schema_files.is_empty() {
581        return Ok(None);
582    }
583    // The SAME reader the install-time staging and the local schema
584    // source use on the way back in — an archive whose schema is
585    // admitted here is an archive whose schema loads there.
586    let schema = memstead_schema::load_sealed_package(&archive::to_package_files(schema_files))
587        .map_err(|e| match e {
588            memstead_schema::SchemaLoadError::SealedPackageMissingManifest => {
589                ValidationError::EmbeddedSchemaInvalid {
590                    reason:
591                        "`.memstead/schema/` tree present but `.memstead/schema/schema.yaml` is missing"
592                            .into(),
593                }
594            }
595            other => ValidationError::EmbeddedSchemaInvalid {
596                reason: other.to_string(),
597            },
598        })?;
599
600    let (embedded_name, embedded_version) = schema.id();
601    if embedded_name != config.schema.name || embedded_version != config.schema.version {
602        return Err(ValidationError::EmbeddedSchemaMismatch {
603            embedded: format!("{embedded_name}@{embedded_version}"),
604            declared: config.schema.as_display(),
605        });
606    }
607    Ok(Some(std::sync::Arc::new(schema)))
608}
609
610fn map_parse_error(path: &str, e: &crate::entity::parser::ParseError) -> ValidationError {
611    use crate::entity::parser::ParseError;
612    match e {
613        ParseError::MissingFrontmatter => ValidationError::MissingFrontmatter {
614            path: path.to_string(),
615        },
616        ParseError::InvalidFrontmatter(reason) => ValidationError::InvalidFrontmatter {
617            path: path.to_string(),
618            reason: reason.clone(),
619        },
620        ParseError::MissingTitle => ValidationError::MissingTitle {
621            path: path.to_string(),
622        },
623        ParseError::Io(err) => ValidationError::InvalidFrontmatter {
624            path: path.to_string(),
625            reason: err.to_string(),
626        },
627    }
628}