Skip to main content

memstead_schema/
loader.rs

1//! Schema loader — reads on-disk schema directories (or in-memory YAML) into
2//! validated `Schema` values with `edge_weights` resolved.
3//!
4//! Three validation layers coordinate here:
5//! 1. Structural (serde + `deny_unknown_fields`) — handled by the deserialize.
6//! 2. Semantic (this module) — cross-field rules listed in `SchemaLoadError`.
7//! 3. Editor (JSON Schemas) — generated by `emit_json_schemas`, consumed by
8//!    schema authors via `# yaml-language-server: $schema=...`.
9
10use std::collections::{HashMap, HashSet};
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14use indexmap::IndexMap;
15use thiserror::Error;
16
17use crate::base_metadata;
18use crate::manifest::SchemaManifest;
19use crate::schema::Schema;
20use crate::types::TypeDefinition;
21
22#[derive(Debug, Error)]
23pub enum SchemaLoadError {
24    #[error("i/o error reading {}: {source}", .path.display())]
25    Io {
26        path: PathBuf,
27        #[source]
28        source: std::io::Error,
29    },
30
31    #[error("failed to parse manifest {}: {source}", .path.display())]
32    ParseManifest {
33        path: PathBuf,
34        #[source]
35        source: serde_yaml_ng::Error,
36    },
37
38    #[error("failed to parse type file {}: {source}", .path.display())]
39    ParseType {
40        path: PathBuf,
41        #[source]
42        source: serde_yaml_ng::Error,
43    },
44
45    #[error("invalid version '{value}': must be semver (e.g. 1.0.0)")]
46    InvalidVersion { value: String },
47
48    #[error("invalid schema name '{value}': {reason}")]
49    InvalidName { value: String, reason: &'static str },
50
51    #[error(
52        "schema type file mismatch — declared in manifest: [{}], found in types/: [{}]",
53        declared.join(", "),
54        found.join(", ")
55    )]
56    TypeFileMismatch {
57        declared: Vec<String>,
58        found: Vec<String>,
59    },
60
61    #[error(
62        "type file '{file}.yaml' has `name: {declared}` — filename and `name` field must match"
63    )]
64    TypeNameMismatch { file: String, declared: String },
65    /// The retired `propagating_relationships:` key was used in an
66    /// authoring context (a schema package loaded from a directory —
67    /// workspace `.memstead/schemas/`, `schema install`, `schema
68    /// validate`). The key's name promised propagation the engine
69    /// never performed; its only effect — refusing self-loops on the
70    /// listed rel-types — now lives under `no_self_loop_relationships`.
71    /// Sealed content (built-ins, installed refs) keeps loading with
72    /// the old key translated; only authoring refuses, so the fix is
73    /// one mechanical key rename per schema.
74    #[error(
75        "type '{type_name}': `propagating_relationships` was renamed — its only effect is \
76         refusing self-loops on the listed rel-types, so the key is now \
77         `no_self_loop_relationships` (optional; empty lists can simply be deleted). \
78         Rename the key and retry."
79    )]
80    PropagatingRelationshipsRenamed { type_name: String },
81
82    #[error(
83        "type '{type_name}' declares the retired `examples:` list — it was never \
84         validated nor served and is replaced by the engine-validated `exemplar:` \
85         (one canonical entity: title, metadata, sections, relations with \
86         placeholder targets). Move the material into `exemplar:` and retry."
87    )]
88    ExamplesRetired { type_name: String },
89
90    /// An exemplar relation entry used the retired authoring spelling
91    /// in an authoring context. Exemplars are authored in the mutation
92    /// vocabulary so what an agent copies from the served schema is
93    /// exactly what the write gate accepts. Sealed content keeps
94    /// loading with the old keys translated; only authoring refuses,
95    /// so the fix is one mechanical key rename per relation entry.
96    #[error(
97        "type '{type_name}': exemplar relation entries speak the mutation vocabulary — \
98         rename `to:` to `target:` and `type:` to `rel_type:`, then retry. (Sealed \
99         packages with the old spelling keep loading; only authoring refuses.)"
100    )]
101    ExemplarRelationSpellingRetired { type_name: String },
102
103    /// An exemplar relation entry is missing `target:` or `rel_type:`
104    /// after legacy translation — the entry cannot name an edge.
105    #[error(
106        "type '{type_name}': an exemplar relation entry must carry both `target:` \
107         (bare placeholder slug) and `rel_type:` (declared relationship name)."
108    )]
109    ExemplarRelationIncomplete { type_name: String },
110
111    /// The retired `optional:` metadata-field key was used in an
112    /// authoring context. The polarity flipped (first-author-path
113    /// plan 07): a field is optional unless it declares
114    /// `required: true` — the same rule sections follow. Sealed
115    /// content keeps loading with the old key inverted; only
116    /// authoring refuses, so the fix is one mechanical edit.
117    #[error(
118        "type '{type_name}' metadata field '{field}' declares the retired `optional:` key — \
119         fields are optional unless they declare `required: true`. Fix: delete `optional: true`; \
120         replace `optional: false` with `required: true`. Then retry."
121    )]
122    OptionalRetired { type_name: String, field: String },
123
124    /// A `due:` declaration referencing fields the type does not have
125    /// in the required shapes. `offender` names the bad reference,
126    /// `reason` states the shape rule it violates — the due axis is
127    /// spec (an external declaration), so its references validate at
128    /// load with the loader's usual recovery quality.
129    #[error("type '{type_name}' due axis is invalid: {reason} — offending name: '{offender}'")]
130    InvalidDueAxis {
131        type_name: String,
132        offender: String,
133        reason: String,
134    },
135
136    #[error("schema relationship vocabulary must include a '_default' definition")]
137    MissingDefaultWeight,
138
139    #[error("duplicate relationship definition: '{name}'")]
140    DuplicateRelationship { name: String },
141
142    #[error(
143        "type '{type_name}' references relationship '{relationship}' in field '{field}' — not declared in schema. Available: [{}]. {}",
144        available.join(", "),
145        format_suggestion(relationship, available)
146    )]
147    UndeclaredRelationship {
148        type_name: String,
149        field: &'static str,
150        relationship: String,
151        available: Vec<String>,
152    },
153
154    #[error(
155        "type '{type_name}' must have exactly one section with `catch_all: true` (found {count})"
156    )]
157    CatchAllViolation { type_name: String, count: usize },
158
159    #[error(
160        "type '{type_name}' field '{field}' references unknown key '{reference}' — not a section or metadata field"
161    )]
162    UnknownFieldReference {
163        type_name: String,
164        field: &'static str,
165        reference: String,
166    },
167
168    #[error(
169        "type '{type_name}' constraint ({kind}) is invalid: {reason} — offending name: '{offender}'"
170    )]
171    InvalidConstraint {
172        type_name: String,
173        kind: &'static str,
174        offender: String,
175        reason: String,
176    },
177
178    #[error("relationships.acyclic_sets is invalid: {reason} — offending entry: '{offender}'")]
179    InvalidAcyclicSet { offender: String, reason: String },
180
181    #[error("relationships.labelling is invalid: {reason} — offending name: '{offender}'")]
182    InvalidLabelling { offender: String, reason: String },
183
184    #[error(
185        "type '{type_name}' section '{section}' format declaration is invalid: {}",
186        problems.join("; ")
187    )]
188    InvalidSectionFormat {
189        type_name: String,
190        section: String,
191        /// EVERY problem of the section's declaration — the loader
192        /// names all offenders, never the first only, so one repair
193        /// pass fixes the schema.
194        problems: Vec<String>,
195    },
196
197    #[error(
198        "type '{type_name}' metadata field '{field}' default '{default}' is not listed in enum_values: [{}]",
199        allowed.join(", ")
200    )]
201    DefaultValueNotInEnum {
202        type_name: String,
203        field: String,
204        default: String,
205        allowed: Vec<String>,
206    },
207
208    #[error(
209        "type '{type_name}' redeclares engine-implicit metadata key '{field}' — remove it from the YAML; the loader injects it automatically"
210    )]
211    RedeclaredBaseField { type_name: String, field: String },
212
213    #[error(
214        "relationship '{relationship}' field '{field}' references unknown type '{reference}'. Declared types: [{}]. {}",
215        declared.join(", "),
216        format_suggestion(reference, declared)
217    )]
218    UndeclaredRelationshipType {
219        relationship: String,
220        field: &'static str,
221        reference: String,
222        declared: Vec<String>,
223    },
224
225    /// Schema declares a regular section or metadata field whose key
226    /// collides with an engine-invariant key. The reserved set covers
227    /// section key `relationships` (the parser's auto-managed
228    /// `## Relationships` section) and the metadata identity/
229    /// discriminator triple `type` / `mem` / `id`
230    /// ([`reserved_metadata_field_keys`]). Sections refuse at load;
231    /// metadata keys refuse on the install/strict-validation path
232    /// ([`check_reserved_metadata_keys`]) so sealed schemas keep
233    /// booting.
234    #[error(
235        "type '{type_name}' declares {kind} with reserved key '{offending_key}' — reserved keys: [{}]",
236        reserved_keys.join(", ")
237    )]
238    ReservedSchemaKey {
239        type_name: String,
240        kind: &'static str,
241        offending_key: String,
242        reserved_keys: Vec<String>,
243    },
244
245    /// A `cross_mem_relationships:` entry's `to_schema:` field is
246    /// not a bare schema name. Cross-mem eligibility is name-based —
247    /// versioned (`software@1.0.0`) and range (`software@^1.0`) forms
248    /// are refused so a version component can never silently re-enter
249    /// the eligibility path.
250    #[error(
251        "cross_mem_relationships[].to_schema '{value}' {reason} — expected a bare schema name (e.g. 'software', not 'software@1.0.0')"
252    )]
253    InvalidCrossMemToSchema { value: String, reason: String },
254
255    /// Two `cross_mem_relationships:` entries declare the same
256    /// `to_schema:`. A schema declares each target-schema at most once
257    /// — the second entry would otherwise silently shadow or split
258    /// the vocabulary.
259    #[error("cross_mem_relationships declares duplicate to_schema '{to_schema}'")]
260    DuplicateCrossMemToSchema { to_schema: String },
261
262    /// A sealed package's file list carries no `schema.yaml`. Only
263    /// reachable through [`load_sealed_package`] — the directory
264    /// loader surfaces a missing manifest as [`Self::Io`] instead.
265    #[error("sealed schema package carries no schema.yaml")]
266    SealedPackageMissingManifest,
267
268    /// A `to_schema: "*"` wildcard entry in a schema that declares no
269    /// `alias_target_rel_type`. The wildcard is BOUND to the
270    /// alias-synthesised rel-type — a schema that has not opted into
271    /// alias synthesis has made no decision the wildcard could extend.
272    #[error(
273        "cross_mem_relationships declares to_schema '*' but the schema declares no \
274         alias_target_rel_type — the wildcard is bound to the alias-synthesised rel-type; \
275         declare alias_target_rel_type, or name each destination schema explicitly"
276    )]
277    CrossMemWildcardWithoutAliasTarget,
278
279    /// A `to_schema: "*"` wildcard entry declaring a rel-type other
280    /// than the schema's `alias_target_rel_type`. Hand-authored
281    /// structural edges keep requiring a per-destination-schema
282    /// declaration — the wildcard only extends the soft, auto-emitted
283    /// alias references the author already permitted.
284    #[error(
285        "cross_mem_relationships[to_schema='*'] declares rel-type '{rel_type}', but the \
286         wildcard is bound to the schema's alias_target_rel_type '{alias_target}' — \
287         hand-authored structural edges need a per-destination-schema declaration"
288    )]
289    CrossMemWildcardNonAliasRelType {
290        rel_type: String,
291        alias_target: String,
292    },
293
294    /// A `cross_mem_relationships[].definitions[*].source_types` entry
295    /// references a type name not declared in the source schema's
296    /// `types` list. Source types belong to the source schema's
297    /// namespace; unknown names raise this error at load time.
298    /// (Target types are accepted as opaque strings — they belong to
299    /// the target schema's namespace, which is not in scope here.)
300    #[error(
301        "cross_mem_relationships[to_schema='{to_schema}'].definitions[name='{relationship}'].source_types references unknown type '{reference}'. Declared types: [{}]. {}",
302        declared.join(", "),
303        format_suggestion(reference, declared)
304    )]
305    UndeclaredCrossMemSourceType {
306        to_schema: String,
307        relationship: String,
308        reference: String,
309        declared: Vec<String>,
310    },
311
312    /// The schema's `alias_target_rel_type:` pointer names a rel-type
313    /// not declared in `relationships.definitions`. Surfaces at
314    /// schema-load time so the alias-synthesis pass can trust the
315    /// pointer is resolvable at every later mutation call.
316    #[error(
317        "schema '{schema}' alias_target_rel_type '{target}' is not declared in relationships. Declared: [{}]. {}",
318        declared.join(", "),
319        format_suggestion(target, declared)
320    )]
321    AliasTargetRelTypeNotDeclared {
322        schema: String,
323        target: String,
324        declared: Vec<String>,
325    },
326
327    /// One or more declared section headings do not derive back to their
328    /// declared keys (`derive_section_key(heading) != key`), so content
329    /// written under the heading could never be parsed back into the
330    /// section — it would silently fork into a second heading or fall
331    /// through to the catch-all. Raised by
332    /// [`check_section_heading_roundtrip`] on the authoring/installation
333    /// path only; a schema already sealed into a mem-repo keeps loading
334    /// and surfaces the condition through health instead.
335    #[error(
336        "schema declares section heading(s) that cannot round-trip to their key(s): {}. \
337         Fix: make each heading derive to its key — lowercasing the heading and replacing \
338         spaces with underscores must yield the key exactly (key `current_state` ⇒ heading \
339         `Current State`)",
340        format_heading_violations(violations)
341    )]
342    SectionHeadingMismatch {
343        violations: Vec<HeadingKeyViolation>,
344    },
345
346    /// Two or more independent semantic violations found in one load
347    /// pass. The loader accumulates every violation it can prove on
348    /// successfully parsed structure and refuses once, so the author
349    /// fixes the whole set in one edit instead of one violation per
350    /// validate round. Structural failures (a manifest that does not
351    /// parse, a declared-vs-found type-file mismatch) still
352    /// short-circuit — everything downstream of them would be noise
353    /// derived from a value that does not exist. A single violation is
354    /// returned bare, never as a one-element list.
355    #[error(
356        "schema has {} violations:\n{}",
357        errors.len(),
358        format_multiple(errors)
359    )]
360    Multiple { errors: Vec<SchemaLoadError> },
361}
362
363fn format_multiple(errors: &[SchemaLoadError]) -> String {
364    errors
365        .iter()
366        .enumerate()
367        .map(|(i, e)| format!("  {}. {e}", i + 1))
368        .collect::<Vec<_>>()
369        .join("\n")
370}
371
372/// Fold an accumulated violation list into one error: a single
373/// violation stays bare (the common case keeps today's message shape),
374/// several wrap in [`SchemaLoadError::Multiple`]. Callers guarantee
375/// the list is non-empty.
376fn collapse(mut errors: Vec<SchemaLoadError>) -> SchemaLoadError {
377    debug_assert!(!errors.is_empty());
378    if errors.len() == 1 {
379        errors.remove(0)
380    } else {
381        SchemaLoadError::Multiple { errors }
382    }
383}
384
385/// One `(type, key, heading, derived_key)` tuple in a
386/// [`SchemaLoadError::SectionHeadingMismatch`] refusal.
387#[derive(Debug, Clone, PartialEq, Eq)]
388pub struct HeadingKeyViolation {
389    pub type_name: String,
390    pub key: String,
391    pub heading: String,
392    pub derived_key: String,
393}
394
395fn format_heading_violations(violations: &[HeadingKeyViolation]) -> String {
396    violations
397        .iter()
398        .map(|v| {
399            format!(
400                "type '{}' section key '{}' has heading '{}' (derives to '{}')",
401                v.type_name, v.key, v.heading, v.derived_key
402            )
403        })
404        .collect::<Vec<_>>()
405        .join("; ")
406}
407
408/// Refuse a schema in which any declared section's heading does not
409/// derive back to that section's declared key. Collects **every**
410/// offending `(type, key, heading, derived_key)` tuple — a schema with
411/// one good and one bad section is refused whole, and the author sees
412/// the complete list in one round.
413///
414/// Installation-path gate only: callers are the schema-authoring
415/// surfaces (CLI `schema validate` / `schema install`, the engine's
416/// `install_schema` primitive). Boot and sealed-schema loads must NOT
417/// call this — a schema already sealed on `__MEMSTEAD` that violates
418/// the rule keeps loading, and the violation surfaces as a health
419/// finding, never as a boot failure.
420pub fn check_section_heading_roundtrip(schema: &Schema) -> Result<(), SchemaLoadError> {
421    let mut violations = Vec::new();
422    // Deterministic report order: sort type names (Schema.types is a
423    // HashMap); sections keep declaration order within a type.
424    let mut type_names: Vec<&String> = schema.types.keys().collect();
425    type_names.sort();
426    for type_name in type_names {
427        let t = &schema.types[type_name];
428        for s in &t.sections {
429            let derived_key = crate::types::derive_section_key(&s.heading);
430            if derived_key != s.key {
431                violations.push(HeadingKeyViolation {
432                    type_name: type_name.clone(),
433                    key: s.key.clone(),
434                    heading: s.heading.clone(),
435                    derived_key,
436                });
437            }
438        }
439    }
440    if violations.is_empty() {
441        Ok(())
442    } else {
443        Err(SchemaLoadError::SectionHeadingMismatch { violations })
444    }
445}
446
447/// Engine-invariant section keys reserved against schema use. The
448/// parser's auto-managed `## Relationships` section is the only entry
449/// today.
450pub fn reserved_section_keys() -> &'static [&'static str] {
451    &["relationships"]
452}
453
454/// Engine-invariant metadata-field keys reserved against schema use —
455/// the entity's identity/discriminator triple. `type` is the engine-set
456/// frontmatter discriminator; `mem` and `id` are the entity's
457/// structural identity, owned by the engine's id grammar and mount
458/// routing. One reservation, one behaviour: no installable schema may
459/// declare any of them (see [`check_reserved_metadata_keys`]), and the
460/// engine write paths refuse them as caller-supplied metadata.
461pub fn reserved_metadata_field_keys() -> &'static [&'static str] {
462    &["type", "mem", "id"]
463}
464
465/// Author/install-path check: refuse a schema whose types **declare**
466/// an engine-reserved metadata-field key (`type` / `mem` / `id`).
467/// Reads the raw pre-merge declaration list the loader records
468/// (`TypeDefinition::declared_metadata_keys`) so the engine-injected
469/// base fields never false-positive.
470///
471/// Same posture as [`check_section_heading_roundtrip`]: install and
472/// strict validation call this and refuse; boot and sealed-schema
473/// loads must NOT — a schema already sealed that violates the rule
474/// keeps loading (refusing at boot would brick the workspace), and the
475/// engine's write-path refusals keep the reserved keys unwritable
476/// regardless.
477pub fn check_reserved_metadata_keys(schema: &crate::Schema) -> Result<(), SchemaLoadError> {
478    for td in schema.types.values() {
479        for key in &td.declared_metadata_keys {
480            if reserved_metadata_field_keys().contains(&key.as_str()) {
481                return Err(SchemaLoadError::ReservedSchemaKey {
482                    type_name: td.name.clone(),
483                    kind: "metadata_field",
484                    offending_key: key.clone(),
485                    reserved_keys: reserved_metadata_field_keys()
486                        .iter()
487                        .map(|s| s.to_string())
488                        .collect(),
489                });
490            }
491        }
492    }
493    Ok(())
494}
495
496fn format_suggestion(needle: &str, candidates: &[String]) -> String {
497    let mut best: Option<(usize, &String)> = None;
498    for cand in candidates {
499        let d = strsim::levenshtein(needle, cand);
500        match best {
501            Some((bd, _)) if bd <= d => {}
502            _ => best = Some((d, cand)),
503        }
504    }
505    match best {
506        Some((d, cand)) if d > 0 && d <= needle.len().saturating_add(3) => {
507            format!("Did you mean '{cand}'?")
508        }
509        _ => String::new(),
510    }
511}
512
513/// Load a schema from a directory containing `schema.yaml` and `types/*.yaml`.
514pub fn load_schema_from_dir(path: &Path) -> Result<Schema, SchemaLoadError> {
515    let manifest_path = path.join("schema.yaml");
516    let manifest_text =
517        std::fs::read_to_string(&manifest_path).map_err(|e| SchemaLoadError::Io {
518            path: manifest_path.clone(),
519            source: e,
520        })?;
521
522    let types_dir = path.join("types");
523    let mut type_files: Vec<(String, String)> = Vec::new();
524    if types_dir.is_dir() {
525        let entries = std::fs::read_dir(&types_dir).map_err(|e| SchemaLoadError::Io {
526            path: types_dir.clone(),
527            source: e,
528        })?;
529        for entry in entries {
530            let entry = entry.map_err(|e| SchemaLoadError::Io {
531                path: types_dir.clone(),
532                source: e,
533            })?;
534            let p = entry.path();
535            if p.extension().and_then(|s| s.to_str()) != Some("yaml") {
536                continue;
537            }
538            let Some(stem) = p.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else {
539                continue;
540            };
541            let contents = std::fs::read_to_string(&p).map_err(|e| SchemaLoadError::Io {
542                path: p.clone(),
543                source: e,
544            })?;
545            type_files.push((stem, contents));
546        }
547    }
548    // read_dir order is filesystem-dependent; accumulated violations
549    // must report in a stable order across runs on the same input.
550    type_files.sort_by(|a, b| a.0.cmp(&b.0));
551
552    load_with_context(
553        &manifest_text,
554        &type_files,
555        Some(&manifest_path),
556        Some(&types_dir),
557        // Authoring context — the author writes the current language.
558        MetadataPolarityFormat::RequiredOptIn,
559    )
560}
561
562/// The metadata-field polarity generation of a sealed package —
563/// decided by the presence of the package's format marker
564/// (`schema-format.json`), never by heuristics over the document body.
565///
566/// Under the pre-flip language an absent `required`/`optional` key
567/// meant **required**; under the current language absence means
568/// **optional**. The two are syntactically indistinguishable, so an
569/// unmarked sealed package reads with [`Self::Legacy`] semantics —
570/// its effective behaviour conserved — while packages sealed from
571/// this change on carry the marker and read as
572/// [`Self::RequiredOptIn`]. Directory (authoring) loads are always
573/// `RequiredOptIn`: the author writes against the current language.
574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
575pub enum MetadataPolarityFormat {
576    /// Pre-flip sealed content: an absent key means required.
577    Legacy,
578    /// Current language: an absent key means optional.
579    RequiredOptIn,
580}
581
582/// The format-marker file name sealed alongside a schema package on
583/// the genuinely sealed surfaces — the `__MEMSTEAD` ref, published
584/// `.mem` archives (the export carries it, the archive validator
585/// admits it, the archive loader honors it), and new builtin version
586/// directories. Presence ⇒ [`MetadataPolarityFormat::RequiredOptIn`];
587/// absence ⇒ legacy. Content is informative JSON; presence is the
588/// contract.
589///
590/// Directory loads (`load_schema_from_dir`: workspace
591/// `.memstead/schemas/`, cache extractions, `schema validate` /
592/// `install`) are the AUTHORING tier and never consult the marker —
593/// they always read the current language, with the retired
594/// `optional:` key refusing loudly. A pre-flip directory package
595/// relying on absent-key-means-required flips soft (fields become
596/// optional — admits more, refuses nothing); that is the fail-soft
597/// direction by design, with `health_required_fields` and
598/// constraints as the data-quality backstop.
599pub const SCHEMA_FORMAT_MARKER_FILE: &str = "schema-format.json";
600
601/// The marker file's canonical content.
602pub const SCHEMA_FORMAT_MARKER_CONTENT: &str = "{\"metadata_polarity\":\"required-opt-in\"}\n";
603
604/// Append the format marker to a package's file list if absent.
605///
606/// **For content verified current-language only.** The marker is a
607/// generation claim, and this helper cannot verify one — a legacy
608/// package stamped here would flip every bare field from required to
609/// optional the moment the sealed copy is read. The one place that
610/// KNOWS a package is current is the authoring/install resolver (a
611/// directory source just validated under the current language, where
612/// the retired `optional:` key refuses loudly); sealed and builtin
613/// sources carry their generation as-found and are never stamped —
614/// absence IS the legacy claim, and inventing a marker over it is the
615/// silent-flip defect this contract exists to prevent.
616pub fn with_format_marker(mut files: Vec<(String, Vec<u8>)>) -> Vec<(String, Vec<u8>)> {
617    if !files
618        .iter()
619        .any(|(rel, _)| rel == SCHEMA_FORMAT_MARKER_FILE)
620    {
621        files.push((
622            SCHEMA_FORMAT_MARKER_FILE.to_string(),
623            SCHEMA_FORMAT_MARKER_CONTENT.as_bytes().to_vec(),
624        ));
625    }
626    files
627}
628
629/// Load a schema from in-memory YAML strings — **legacy sealed
630/// semantics** (an absent required/optional key means required).
631/// Use [`load_schema_from_memory_with_format`] when the caller knows
632/// the package's format generation from its marker.
633///
634/// `types_yamls` is a slice of `(filename_stem, contents)` tuples — the stems
635/// must match `manifest.types` exactly.
636pub fn load_schema_from_memory(
637    manifest_yaml: &str,
638    types_yamls: &[(String, String)],
639) -> Result<Schema, SchemaLoadError> {
640    load_with_context(
641        manifest_yaml,
642        types_yamls,
643        None,
644        None,
645        MetadataPolarityFormat::Legacy,
646    )
647}
648
649/// Load a **sealed** schema package from its `(relative-path, bytes)`
650/// file list — the shape every sealed surface carries: a published
651/// `.mem` archive's `.memstead/schema/` tree, the git-branch
652/// `__MEMSTEAD:schemas/<name>@<version>/` tree, a built-in version
653/// directory. Paths are package-relative (`schema.yaml`,
654/// `types/<stem>.yaml`, `schema-format.json`); anything else is
655/// ignored.
656///
657/// One function so the surfaces that *admit* a sealed package (the
658/// archive validator) and the surfaces that later *read it back* (the
659/// local schema source the install stages into) can never disagree —
660/// a package valid to publish stays valid to install. The metadata
661/// polarity comes from the package's own format marker, and keys
662/// retired after the package was sealed read with their written
663/// meaning instead of refusing.
664///
665/// Authoring content takes [`load_schema_from_dir`] instead, which
666/// refuses retired keys loudly so the author can act.
667pub fn load_sealed_package(files: &[(String, Vec<u8>)]) -> Result<Schema, SchemaLoadError> {
668    let mut manifest: Option<String> = None;
669    let mut types: Vec<(String, String)> = Vec::new();
670    let mut marked = false;
671    for (rel, bytes) in files {
672        if rel == "schema.yaml" {
673            manifest = Some(String::from_utf8_lossy(bytes).into_owned());
674        } else if rel == SCHEMA_FORMAT_MARKER_FILE {
675            marked = true;
676        } else if let Some(stem) = rel
677            .strip_prefix("types/")
678            .and_then(|f| f.strip_suffix(".yaml"))
679        {
680            types.push((
681                stem.to_string(),
682                String::from_utf8_lossy(bytes).into_owned(),
683            ));
684        }
685    }
686    let manifest = manifest.ok_or(SchemaLoadError::SealedPackageMissingManifest)?;
687    // Deterministic order regardless of how the caller enumerated the
688    // package — accumulated violations must report the same way twice.
689    types.sort_by(|a, b| a.0.cmp(&b.0));
690    let format = if marked {
691        MetadataPolarityFormat::RequiredOptIn
692    } else {
693        MetadataPolarityFormat::Legacy
694    };
695    load_with_context(&manifest, &types, None, None, format)
696}
697
698/// Would this package content pass the AUTHORING tier under the
699/// current language? Same strictness as [`load_schema_from_dir`] —
700/// retired keys (`propagating_relationships`, `examples:`, `optional:`)
701/// refuse loudly — but over in-memory content, so a caller holding a
702/// sealed package's files (git-branch `__MEMSTEAD:schemas/` tree,
703/// folder seal, archive) can ask whether the content is still
704/// re-authorable/installable without materialising a directory. The
705/// tolerant sealed read ([`load_sealed_package`]) is unaffected; this
706/// is a pure diagnosis — the health rot axis is the consumer.
707pub fn check_package_reauthorable(
708    manifest_yaml: &str,
709    types_yamls: &[(String, String)],
710) -> Result<(), SchemaLoadError> {
711    // The `types_dir: Some(..)` context is what selects the authoring-
712    // strict legacy-key gates; the path itself only labels error
713    // messages.
714    let strict_context = Path::new("<sealed package>");
715    load_with_context(
716        manifest_yaml,
717        types_yamls,
718        Some(strict_context),
719        Some(strict_context),
720        MetadataPolarityFormat::RequiredOptIn,
721    )
722    .map(|_| ())
723}
724
725/// Load a schema from in-memory YAML strings with an explicit
726/// metadata-polarity format generation (from the sealed package's
727/// format marker).
728pub fn load_schema_from_memory_with_format(
729    manifest_yaml: &str,
730    types_yamls: &[(String, String)],
731    format: MetadataPolarityFormat,
732) -> Result<Schema, SchemaLoadError> {
733    load_with_context(manifest_yaml, types_yamls, None, None, format)
734}
735
736fn load_with_context(
737    manifest_yaml: &str,
738    types_yamls: &[(String, String)],
739    manifest_path: Option<&Path>,
740    types_dir: Option<&Path>,
741    format: MetadataPolarityFormat,
742) -> Result<Schema, SchemaLoadError> {
743    // Semantic-violation accumulator. Every check operating on
744    // successfully parsed structure pushes here instead of returning,
745    // so the author sees the complete violation set in one refusal;
746    // only structural failures short-circuit (see
747    // [`SchemaLoadError::Multiple`]). Order is deterministic:
748    // manifest checks in declaration order, then type files in
749    // `types_yamls` order (sorted by stem when loaded from a
750    // directory).
751    let mut errors: Vec<SchemaLoadError> = Vec::new();
752
753    let mut manifest: SchemaManifest =
754        serde_yaml_ng::from_str(manifest_yaml).map_err(|e| SchemaLoadError::ParseManifest {
755            path: manifest_path
756                .map(Path::to_path_buf)
757                .unwrap_or_else(|| PathBuf::from("<memory>")),
758            source: e,
759        })?;
760
761    if let Err(e) = validate_name(&manifest.name) {
762        errors.push(e);
763    }
764
765    // `None` only ever coexists with a non-empty accumulator, so the
766    // `Schema` construction at the bottom (reached only when the
767    // accumulator is empty) can unwrap.
768    let version = match semver::Version::parse(&manifest.version) {
769        Ok(v) => Some(v),
770        Err(_) => {
771            errors.push(SchemaLoadError::InvalidVersion {
772                value: manifest.version.clone(),
773            });
774            None
775        }
776    };
777
778    // Relationship vocabulary: unique names + _default present
779    let mut rel_names: HashSet<String> = HashSet::new();
780    for def in &manifest.relationships.definitions {
781        if !rel_names.insert(def.name.clone()) {
782            errors.push(SchemaLoadError::DuplicateRelationship {
783                name: def.name.clone(),
784            });
785        }
786    }
787    if !rel_names.contains("_default") {
788        errors.push(SchemaLoadError::MissingDefaultWeight);
789    }
790    let available_rels: Vec<String> = manifest
791        .relationships
792        .definitions
793        .iter()
794        .map(|d| d.name.clone())
795        .collect();
796
797    // Validate that the schema-level alias_target_rel_type pointer (if
798    // set) names a declared rel-type. The synthesis pass later relies
799    // on this invariant — running it as a load-time check keeps the
800    // mutation path's hot loop free of resolution failures.
801    if let Some(target) = &manifest.alias_target_rel_type
802        && !rel_names.contains(target)
803    {
804        let mut declared = available_rels.clone();
805        declared.sort();
806        errors.push(SchemaLoadError::AliasTargetRelTypeNotDeclared {
807            schema: manifest.name.clone(),
808            target: target.clone(),
809            declared,
810        });
811    }
812
813    // Acyclicity sets: each set names two or more DECLARED rel-types,
814    // and a rel-type appears in at most one set across all sets
815    // (overlapping sets have no coherent refusal message; a duplicate
816    // inside one set is the same defect). A single-member set is the
817    // per-definition `acyclic` flag's job and refuses here.
818    let mut acyclic_set_member_seen: HashSet<&str> = HashSet::new();
819    for set in &manifest.relationships.acyclic_sets {
820        if set.len() < 2 {
821            errors.push(SchemaLoadError::InvalidAcyclicSet {
822                offender: set.join(", "),
823                reason: "a set needs at least two rel-types (a single member is the \
824                         per-definition `acyclic` flag)"
825                    .to_string(),
826            });
827        }
828        for name in set {
829            if !rel_names.contains(name.as_str()) {
830                errors.push(SchemaLoadError::InvalidAcyclicSet {
831                    offender: name.clone(),
832                    reason: "names no declared relationship".to_string(),
833                });
834            }
835            if !acyclic_set_member_seen.insert(name.as_str()) {
836                errors.push(SchemaLoadError::InvalidAcyclicSet {
837                    offender: name.clone(),
838                    reason: "a rel-type may appear in at most one acyclicity set".to_string(),
839                });
840            }
841        }
842    }
843
844    // Labelling declaration: `attack` names at least one declared
845    // rel-type; a `support` block names declared rel-types too (its
846    // `terminal_types` need every type loaded and are checked in the
847    // schema-level pass; its `direction` is a closed enum).
848    if let Some(lab) = &manifest.relationships.labelling {
849        if lab.attack.is_empty() {
850            errors.push(SchemaLoadError::InvalidLabelling {
851                offender: "(empty)".to_string(),
852                reason: "`labelling.attack` must name at least one rel-type".to_string(),
853            });
854        }
855        for name in &lab.attack {
856            if !rel_names.contains(name.as_str()) {
857                errors.push(SchemaLoadError::InvalidLabelling {
858                    offender: name.clone(),
859                    reason: "`labelling.attack` entry names no declared relationship".to_string(),
860                });
861            }
862        }
863        if let Some(sup) = &lab.support {
864            if sup.relationships.is_empty() {
865                errors.push(SchemaLoadError::InvalidLabelling {
866                    offender: "(empty)".to_string(),
867                    reason: "`labelling.support.relationships` must name at least one rel-type"
868                        .to_string(),
869                });
870            }
871            for name in &sup.relationships {
872                if !rel_names.contains(name.as_str()) {
873                    errors.push(SchemaLoadError::InvalidLabelling {
874                        offender: name.clone(),
875                        reason: "`labelling.support.relationships` entry names no declared \
876                                 relationship"
877                            .to_string(),
878                    });
879                }
880            }
881        }
882    }
883
884    // Option C coupling — auto-force `manual_authoring: forbidden` on
885    // the rel-type named by `alias_target_rel_type`. Schemas setting
886    // the pointer opt the named rel-type out of explicit authoring;
887    // the only path to a relation of that rel-type is via the
888    // alias-synthesis pass that emits one per body wiki-link. This
889    // closes the explicit/synthesised coexistence question: with the
890    // coupling in place, edges of the pointer rel-type are always
891    // engine-emitted, so `EdgeSource::BodyLink` is unambiguous and
892    // GC can drop pointer-rel-type relations without risking
893    // explicit-author data.
894    //
895    // The coupling is silent — a schema that writes
896    // `manual_authoring: allow` (or `warn`) on the named rel-type
897    // gets overridden to `forbidden` at load. The override is the
898    // schema-strictness contract; explicit `allow`/`warn` on the
899    // pointer rel-type is meaningless under the design and would
900    // surprise the validator at runtime, so the loader corrects it
901    // here.
902    if let Some(pointer) = manifest.alias_target_rel_type.clone() {
903        for def in &mut manifest.relationships.definitions {
904            if def.name == pointer {
905                def.manual_authoring = crate::manifest::ManualAuthoring::Forbidden;
906            }
907        }
908    }
909
910    // Cross-check `source_types` / `target_types` on each relationship
911    // definition against the manifest's declared type list. Unknown
912    // names raise `UndeclaredRelationshipType` with a "did you mean"
913    // suggestion — the schema-author equivalent of `INVALID_REL_SHAPE`.
914    for def in &manifest.relationships.definitions {
915        for t in &def.source_types {
916            if !manifest.types.iter().any(|d| d == t) {
917                errors.push(SchemaLoadError::UndeclaredRelationshipType {
918                    relationship: def.name.clone(),
919                    field: "source_types",
920                    reference: t.clone(),
921                    declared: manifest.types.clone(),
922                });
923            }
924        }
925        for t in &def.target_types {
926            if !manifest.types.iter().any(|d| d == t) {
927                errors.push(SchemaLoadError::UndeclaredRelationshipType {
928                    relationship: def.name.clone(),
929                    field: "target_types",
930                    reference: t.clone(),
931                    declared: manifest.types.clone(),
932                });
933            }
934        }
935    }
936
937    // Cross-mem relationships: validate `to_schema` is a bare schema
938    // name (cross-mem eligibility is name-based — a version suffix or
939    // range refuses), refuse duplicate target schemas, and cross-check
940    // `source_types` against the source schema's types. `target_types`
941    // are accepted as opaque strings — they belong to the target
942    // schema's namespace, which is out of scope at source-schema load
943    // time. The target schema may not even be present in the workspace
944    // when the source schema loads (and cross-mem declarations
945    // targeting absent schemas are legitimate for portable library
946    // schemas).
947    let mut seen_to_schemas: HashSet<String> = HashSet::new();
948    for entry in &manifest.cross_mem_relationships {
949        if entry.to_schema == "*" {
950            // Wildcard destination — bound to the alias-synthesised
951            // rel-type. The binding IS the safety argument: the author
952            // already permitted soft auto-emitted references of that
953            // type; the wildcard extends that decision across the mem
954            // boundary and introduces no new permission. Structural
955            // rel-types stay per-destination-schema.
956            match manifest.alias_target_rel_type.as_deref() {
957                None => errors.push(SchemaLoadError::CrossMemWildcardWithoutAliasTarget),
958                Some(alias) => {
959                    for def in &entry.definitions {
960                        if def.name != alias {
961                            errors.push(SchemaLoadError::CrossMemWildcardNonAliasRelType {
962                                rel_type: def.name.clone(),
963                                alias_target: alias.to_string(),
964                            });
965                        }
966                    }
967                }
968            }
969        } else if entry.to_schema.contains('@') {
970            errors.push(SchemaLoadError::InvalidCrossMemToSchema {
971                value: entry.to_schema.clone(),
972                reason: "must not carry a version or range".into(),
973            });
974        } else if let Err(reason) = name_shape(&entry.to_schema) {
975            errors.push(SchemaLoadError::InvalidCrossMemToSchema {
976                value: entry.to_schema.clone(),
977                reason: reason.into(),
978            });
979        }
980        if !seen_to_schemas.insert(entry.to_schema.clone()) {
981            errors.push(SchemaLoadError::DuplicateCrossMemToSchema {
982                to_schema: entry.to_schema.clone(),
983            });
984        }
985        for def in &entry.definitions {
986            for t in &def.source_types {
987                if !manifest.types.iter().any(|d| d == t) {
988                    errors.push(SchemaLoadError::UndeclaredCrossMemSourceType {
989                        to_schema: entry.to_schema.clone(),
990                        relationship: def.name.clone(),
991                        reference: t.clone(),
992                        declared: manifest.types.clone(),
993                    });
994                }
995            }
996        }
997    }
998
999    // Type file cross-check: declared vs found, set equality (order-insensitive)
1000    let mut found_stems: Vec<String> = types_yamls.iter().map(|(s, _)| s.clone()).collect();
1001    found_stems.sort();
1002    let mut declared = manifest.types.clone();
1003    declared.sort();
1004    if found_stems != declared {
1005        // Structural: the per-type pass below would run against a file
1006        // set the manifest never described. Refuse now, together with
1007        // every manifest-level violation already proven.
1008        errors.push(SchemaLoadError::TypeFileMismatch {
1009            declared,
1010            found: found_stems,
1011        });
1012        return Err(collapse(errors));
1013    }
1014
1015    // Per-type defaults map for edge_weights resolution
1016    let defaults: IndexMap<String, f32> = manifest
1017        .relationships
1018        .definitions
1019        .iter()
1020        .map(|d| (d.name.clone(), d.default_weight))
1021        .collect();
1022
1023    let mut types_map: HashMap<String, Arc<TypeDefinition>> = HashMap::new();
1024    let mut had_type_parse_failure = false;
1025
1026    for (stem, text) in types_yamls {
1027        let type_path = types_dir
1028            .map(|d| d.join(format!("{stem}.yaml")))
1029            .unwrap_or_else(|| PathBuf::from(format!("<memory>/{stem}.yaml")));
1030
1031        let mut td: TypeDefinition = match serde_yaml_ng::from_str(text) {
1032            Ok(td) => td,
1033            Err(e) => {
1034                // A type file that does not parse cannot be checked
1035                // semantically — record the parse failure, keep
1036                // checking the other files, and skip the cross-type
1037                // pass below (the missing type would make it noise).
1038                errors.push(SchemaLoadError::ParseType {
1039                    path: type_path.clone(),
1040                    source: e,
1041                });
1042                had_type_parse_failure = true;
1043                continue;
1044            }
1045        };
1046
1047        if td.name != *stem {
1048            errors.push(SchemaLoadError::TypeNameMismatch {
1049                file: stem.clone(),
1050                declared: td.name.clone(),
1051            });
1052        }
1053
1054        // Legacy-key gate: authoring contexts (loaded from a
1055        // directory — `types_dir` is `Some`) refuse the retired
1056        // `propagating_relationships` key with the rename error;
1057        // sealed contexts (in-memory: built-ins, installed refs)
1058        // translate it so shipped content keeps loading (install-time
1059        // strict, sealed-tolerant — the section-heading round-trip
1060        // doctrine).
1061        if let Some(legacy) = td.legacy_propagating_relationships.take() {
1062            if types_dir.is_some() {
1063                errors.push(SchemaLoadError::PropagatingRelationshipsRenamed {
1064                    type_name: td.name.clone(),
1065                });
1066            } else if td.no_self_loop_relationships.is_empty() {
1067                td.no_self_loop_relationships = legacy;
1068            }
1069        }
1070
1071        // Retired `examples:` list (agent-trust plan 09): dead
1072        // vocabulary — never validated, never served. Authoring
1073        // contexts refuse with the pointer at `exemplar:`; sealed
1074        // contexts tolerate and drop (nothing consumed it, so
1075        // dropping is lossless).
1076        if td.legacy_examples.take().is_some() && types_dir.is_some() {
1077            errors.push(SchemaLoadError::ExamplesRetired {
1078                type_name: td.name.clone(),
1079            });
1080        }
1081
1082        // Exemplar relation spelling (consistency-sweep 05-front-door/08
1083        // rider): entries are authored in the mutation vocabulary
1084        // (`target:` / `rel_type:`) so the served exemplar round-trips
1085        // into `memstead_create` unchanged. Authoring contexts refuse
1086        // the retired `to:` / `type:` spelling with the rename pointer;
1087        // sealed contexts translate it so every shipped version keeps
1088        // loading. After the gate, both resolved keys are guaranteed
1089        // present on every loaded schema.
1090        if let Some(ex) = td.exemplar.as_mut() {
1091            let mut retired_spelling = false;
1092            let mut incomplete = false;
1093            for rel in &mut ex.relations {
1094                let legacy_to = rel.legacy_to.take();
1095                let legacy_type = rel.legacy_type.take();
1096                if legacy_to.is_some() || legacy_type.is_some() {
1097                    if types_dir.is_some() {
1098                        retired_spelling = true;
1099                        continue;
1100                    }
1101                    if rel.target.is_none() {
1102                        rel.target = legacy_to;
1103                    }
1104                    if rel.rel_type.is_none() {
1105                        rel.rel_type = legacy_type;
1106                    }
1107                }
1108                if rel.target.is_none() || rel.rel_type.is_none() {
1109                    incomplete = true;
1110                }
1111            }
1112            if retired_spelling {
1113                errors.push(SchemaLoadError::ExemplarRelationSpellingRetired {
1114                    type_name: td.name.clone(),
1115                });
1116            }
1117            if incomplete {
1118                errors.push(SchemaLoadError::ExemplarRelationIncomplete {
1119                    type_name: td.name.clone(),
1120                });
1121            }
1122        }
1123
1124        // Metadata-required polarity (first-author-path plan 07):
1125        // authoring refuses the retired `optional:` key naming the
1126        // inversion; sealed content inverts it. An absent key resolves
1127        // by the package's format generation — legacy sealed content
1128        // reads absence as required (its written meaning), everything
1129        // else as optional.
1130        for field in &mut td.metadata_fields {
1131            // Current-language contexts (directory/authoring loads and
1132            // install validation, both RequiredOptIn) refuse the
1133            // retired key; only Legacy sealed loads invert silently.
1134            if matches!(format, MetadataPolarityFormat::RequiredOptIn)
1135                && field.legacy_optional.is_some()
1136            {
1137                errors.push(SchemaLoadError::OptionalRetired {
1138                    type_name: td.name.clone(),
1139                    field: field.key.clone(),
1140                });
1141            }
1142            field.required_resolved = match (field.required, field.legacy_optional.take()) {
1143                (Some(required), _) => required,
1144                (None, Some(optional)) => !optional,
1145                (None, None) => matches!(format, MetadataPolarityFormat::Legacy),
1146            };
1147        }
1148
1149        // Record the raw author-declared metadata keys BEFORE the
1150        // base-metadata merge, so the install-path reserved-key check
1151        // ([`check_reserved_metadata_keys`]) can tell a declared
1152        // `type`/`mem`/`id` from the engine-injected base fields. The
1153        // check itself deliberately does NOT run here: this loader
1154        // serves boot and sealed-schema reads too, and a schema sealed
1155        // before the reservation widened must keep loading (heading-
1156        // round-trip posture — refusal fires on the authoring/install
1157        // path, never at boot).
1158        td.declared_metadata_keys = td.metadata_fields.iter().map(|f| f.key.clone()).collect();
1159
1160        // Reject redeclarations of remaining engine-implicit base metadata
1161        // (`created_date`, `last_modified`, `tags`). The reserved `type`
1162        // case is excluded here — it refuses with the typed reserved-key
1163        // error on the install path instead.
1164        for field in &td.metadata_fields {
1165            if base_metadata::is_base_key(&field.key)
1166                && !reserved_metadata_field_keys().contains(&field.key.as_str())
1167            {
1168                errors.push(SchemaLoadError::RedeclaredBaseField {
1169                    type_name: td.name.clone(),
1170                    field: field.key.clone(),
1171                });
1172            }
1173        }
1174
1175        // Merge base metadata around the type-declared fields. Canonical
1176        // order: type, created_date, last_modified, <declared>, tags.
1177        let mut merged = base_metadata::prefix_fields();
1178        merged.append(&mut td.metadata_fields);
1179        merged.extend(base_metadata::suffix_fields());
1180        td.metadata_fields = merged;
1181
1182        compile_section_formats(&mut td);
1183        validate_type(&td, &rel_names, &available_rels, &mut errors);
1184
1185        // Resolve edge_weights: start with schema defaults, apply overrides.
1186        let mut weights = defaults.clone();
1187        for (k, v) in &td.edge_weight_overrides {
1188            weights.insert(k.clone(), *v);
1189        }
1190        td.edge_weights = weights;
1191
1192        types_map.insert(stem.clone(), Arc::new(td));
1193    }
1194
1195    // Schema-level constraint pass — checks that need every type
1196    // loaded. `enum_from_neighbour.section` names a section on the
1197    // *reached* entity, whose type this schema cannot pin statically;
1198    // requiring the key to exist on at least one declared type catches
1199    // the typo class without over-constraining the endpoint. Skipped
1200    // when a type file failed to parse — the missing type's sections
1201    // would make the existence check report noise.
1202    if !had_type_parse_failure {
1203        let all_section_keys: HashSet<&str> = types_map
1204            .values()
1205            .flat_map(|t| t.sections.iter().map(|s| s.key.as_str()))
1206            .collect();
1207        // Deterministic report order: sort type names (types_map is a
1208        // HashMap); constraints keep declaration order within a type.
1209        let mut type_names: Vec<&String> = types_map.keys().collect();
1210        type_names.sort();
1211        for type_name in type_names {
1212            let td = &types_map[type_name];
1213            for c in &td.constraints {
1214                if let crate::types::ConstraintDef::EnumFromNeighbour { section, .. } = c
1215                    && !all_section_keys.contains(section.as_str())
1216                {
1217                    errors.push(SchemaLoadError::InvalidConstraint {
1218                        type_name: td.name.clone(),
1219                        kind: "enum_from_neighbour",
1220                        offender: section.clone(),
1221                        reason: "`section` names a section key no type of this schema declares"
1222                            .to_string(),
1223                    });
1224                }
1225            }
1226            // `must_reach.terminal_types` name types of this schema —
1227            // checkable only once every type is loaded.
1228            for ob in &td.must_reach {
1229                for t in &ob.terminal_types {
1230                    if !types_map.contains_key(t.as_str()) {
1231                        errors.push(SchemaLoadError::InvalidConstraint {
1232                            type_name: td.name.clone(),
1233                            kind: "must_reach",
1234                            offender: t.clone(),
1235                            reason: "`terminal_types` entry names no type of this schema"
1236                                .to_string(),
1237                        });
1238                    }
1239                }
1240            }
1241            // A signal's neighbour pair reads the COUNTERPART entity,
1242            // whose type this schema cannot pin statically: the field
1243            // must be declared with `enum_values` on at least one type
1244            // of the schema, and the value must be a member on at
1245            // least one such declaring type.
1246            for sig in &td.signals {
1247                if let (Some(field), Some(value)) = (&sig.neighbour_field, &sig.neighbour_value) {
1248                    let declaring: Vec<&crate::types::MetadataFieldDef> = types_map
1249                        .values()
1250                        .flat_map(|t| t.metadata_fields.iter())
1251                        .filter(|f| f.key == *field && f.enum_values.is_some())
1252                        .collect();
1253                    if declaring.is_empty() {
1254                        errors.push(SchemaLoadError::InvalidConstraint {
1255                            type_name: td.name.clone(),
1256                            kind: "signal",
1257                            offender: field.clone(),
1258                            reason: "`neighbour_field` is declared with `enum_values` on no \
1259                                     type of this schema"
1260                                .to_string(),
1261                        });
1262                    } else if !declaring.iter().any(|f| {
1263                        f.enum_values
1264                            .as_ref()
1265                            .is_some_and(|allowed| allowed.contains(value))
1266                    }) {
1267                        errors.push(SchemaLoadError::InvalidConstraint {
1268                            type_name: td.name.clone(),
1269                            kind: "signal",
1270                            offender: value.clone(),
1271                            reason: format!(
1272                                "`neighbour_value` is outside `{field}`'s enum_values on every \
1273                                 declaring type"
1274                            ),
1275                        });
1276                    }
1277                }
1278            }
1279        }
1280    }
1281
1282    // `labelling.support.terminal_types` name types of this schema —
1283    // checkable only once every type is loaded (mirrors the
1284    // `must_reach` pass; skipped on type-parse failure like the rest
1285    // of the schema-level pass).
1286    if !had_type_parse_failure
1287        && let Some(lab) = &manifest.relationships.labelling
1288        && let Some(sup) = &lab.support
1289    {
1290        for t in &sup.terminal_types {
1291            if !types_map.contains_key(t.as_str()) {
1292                errors.push(SchemaLoadError::InvalidLabelling {
1293                    offender: t.clone(),
1294                    reason: "`labelling.support.terminal_types` entry names no type of this \
1295                             schema"
1296                        .to_string(),
1297                });
1298            }
1299        }
1300    }
1301
1302    if !errors.is_empty() {
1303        return Err(collapse(errors));
1304    }
1305
1306    Ok(Schema {
1307        manifest,
1308        version: version.expect("version parse failure would have accumulated an error"),
1309        types: types_map,
1310    })
1311}
1312
1313fn validate_name(name: &str) -> Result<(), SchemaLoadError> {
1314    name_shape(name).map_err(|reason| SchemaLoadError::InvalidName {
1315        value: name.into(),
1316        reason,
1317    })
1318}
1319
1320/// Author-time access to the schema-name shape rule — the same check
1321/// the loader runs on a manifest's `name:`. Exposed so scaffolding
1322/// tooling (`memstead schema new`) can refuse a bad name up front with
1323/// the loader's own reason string instead of a drifting copy of the
1324/// grammar.
1325pub fn validate_schema_name(name: &str) -> Result<(), &'static str> {
1326    name_shape(name)
1327}
1328
1329/// Shared shape rule for schema names — the manifest's own `name:` and
1330/// every `cross_mem_relationships[].to_schema` follow the same
1331/// grammar; the two callers wrap violations in their field-specific
1332/// error variants.
1333fn name_shape(name: &str) -> Result<(), &'static str> {
1334    if name.is_empty() {
1335        return Err("must not be empty");
1336    }
1337    let mut chars = name.chars();
1338    let first = chars.next().unwrap();
1339    if !first.is_ascii_lowercase() {
1340        return Err("must start with a lowercase letter");
1341    }
1342    for c in chars {
1343        if !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') {
1344            return Err("must contain only lowercase letters, digits, and hyphens");
1345        }
1346    }
1347    Ok(())
1348}
1349
1350/// Validate and compile the section-format declarations of a type
1351/// (plan 08). LENIENT at load: problems are recorded on the section
1352/// (`format_problems`) instead of refusing, so a sealed schema
1353/// carrying a bad declaration keeps loading — install and strict
1354/// validation refuse via [`check_section_formats`], and a defective
1355/// declaration is never enforced (`compiled_content` stays `None`). A
1356/// valid `content` expression is compiled once and cached.
1357fn compile_section_formats(td: &mut TypeDefinition) {
1358    use crate::content_expr::ContentExpr;
1359    for section in &mut td.sections {
1360        // A non-default severity only deserializes from an explicit
1361        // declaration, so a lone `format_severity: warn` without
1362        // `content` is detectable — and would otherwise load and be
1363        // silently ignored (`format_severity: block` alone equals the
1364        // default and is inherently a no-op).
1365        let declares_any = section.content.is_some()
1366            || section.item_pattern.is_some()
1367            || section.table.is_some()
1368            || section.example.is_some()
1369            || section.format_severity != crate::types::ConstraintSeverity::Block;
1370        if !declares_any {
1371            continue;
1372        }
1373        let mut problems: Vec<String> = Vec::new();
1374
1375        let compiled = match &section.content {
1376            None => {
1377                problems.push(
1378                    "`item_pattern` / `table` / `example` require a `content` declaration"
1379                        .to_string(),
1380                );
1381                None
1382            }
1383            Some(expr_src) => match ContentExpr::parse(expr_src) {
1384                Ok(expr) => Some(expr),
1385                Err(e) => {
1386                    problems.push(format!("`content` is invalid: {e}"));
1387                    None
1388                }
1389            },
1390        };
1391
1392        if let Some(pattern) = &section.item_pattern {
1393            if let Err(e) = regex::Regex::new(pattern) {
1394                problems.push(format!("`item_pattern` is not a valid regex: {e}"));
1395            }
1396            if let Some(expr) = &compiled {
1397                let names = expr.mentioned_names();
1398                let has_list = names.contains(&"list");
1399                let has_paragraph = names.contains(&"paragraph");
1400                if has_list == has_paragraph {
1401                    problems.push(
1402                        "`item_pattern` requires a `content` expression containing exactly                          one of `list` / `paragraph` (tables use `column_patterns`)"
1403                            .to_string(),
1404                    );
1405                }
1406            }
1407        }
1408
1409        if let Some(table) = &section.table {
1410            if let Some(expr) = &compiled
1411                && !expr.mentioned_names().contains(&"table")
1412            {
1413                problems.push(
1414                    "`table` block is only legal when `content` contains `table`".to_string(),
1415                );
1416            }
1417            if table.columns.is_empty() {
1418                problems.push("`table.columns` must name at least one column".to_string());
1419            }
1420            for (column, pattern) in &table.column_patterns {
1421                if !table.columns.contains(column) {
1422                    problems.push(format!(
1423                        "`column_patterns` names '{column}', which is not in `columns`"
1424                    ));
1425                }
1426                if let Err(e) = regex::Regex::new(pattern) {
1427                    problems.push(format!(
1428                        "`column_patterns.{column}` is not a valid regex: {e}"
1429                    ));
1430                }
1431            }
1432        }
1433
1434        if problems.is_empty() {
1435            section.compiled_content = compiled;
1436        } else {
1437            section.format_problems = problems;
1438        }
1439    }
1440}
1441
1442/// Refuse a schema whose section-format declarations are defective —
1443/// the install / strict-validation half of the loader-honesty rule.
1444/// Same posture as [`check_reserved_metadata_keys`]: install and
1445/// strict validation call this and refuse (naming EVERY problem of
1446/// the first defective section); boot and sealed-schema loads must
1447/// NOT — the recorded `format_problems` surface as health findings
1448/// instead, and the defective declaration is never enforced.
1449pub fn check_section_formats(schema: &crate::Schema) -> Result<(), SchemaLoadError> {
1450    // Aggregate EVERY defective section across every type — the
1451    // refusal names all offenders, never the first only. `type_name`
1452    // / `section` carry the first offender; entries beyond it are
1453    // prefixed with their own type/section inside `problems`.
1454    let mut first: Option<(String, String)> = None;
1455    let mut problems: Vec<String> = Vec::new();
1456    for td in schema.types.values() {
1457        for section in &td.sections {
1458            if section.format_problems.is_empty() {
1459                continue;
1460            }
1461            if first.is_none() {
1462                first = Some((td.name.clone(), section.key.clone()));
1463                problems.extend(section.format_problems.iter().cloned());
1464            } else {
1465                problems.extend(
1466                    section
1467                        .format_problems
1468                        .iter()
1469                        .map(|p| format!("[{}.{}] {p}", td.name, section.key)),
1470                );
1471            }
1472        }
1473    }
1474    match first {
1475        Some((type_name, section)) => Err(SchemaLoadError::InvalidSectionFormat {
1476            type_name,
1477            section,
1478            problems,
1479        }),
1480        None => Ok(()),
1481    }
1482}
1483
1484fn validate_type(
1485    td: &TypeDefinition,
1486    rel_names: &HashSet<String>,
1487    available_rels: &[String],
1488    errors: &mut Vec<SchemaLoadError>,
1489) {
1490    // Reserved-section check. Section key `relationships` collides
1491    // with the parser's auto-managed `## Relationships` section.
1492    // Domain conventions (`identity`, `purpose`, ...) are NOT reserved.
1493    // The reserved-metadata-key check runs earlier in
1494    // `load_with_context` against the *raw* author-declared field list
1495    // so the base-metadata merge doesn't false-positive against
1496    // engine-injected keys.
1497    for section in &td.sections {
1498        if reserved_section_keys().contains(&section.key.as_str()) {
1499            errors.push(SchemaLoadError::ReservedSchemaKey {
1500                type_name: td.name.clone(),
1501                kind: "section",
1502                offending_key: section.key.clone(),
1503                reserved_keys: reserved_section_keys()
1504                    .iter()
1505                    .map(|s| s.to_string())
1506                    .collect(),
1507            });
1508        }
1509    }
1510
1511    if let Err(e) = check_rel(
1512        &td.name,
1513        "hierarchy_relationship",
1514        &td.hierarchy_relationship,
1515        rel_names,
1516        available_rels,
1517    ) {
1518        errors.push(e);
1519    }
1520    for r in &td.no_self_loop_relationships {
1521        if let Err(e) = check_rel(
1522            &td.name,
1523            "no_self_loop_relationships",
1524            r,
1525            rel_names,
1526            available_rels,
1527        ) {
1528            errors.push(e);
1529        }
1530    }
1531    for r in td.edge_weight_overrides.keys() {
1532        if let Err(e) = check_rel(
1533            &td.name,
1534            "edge_weight_overrides",
1535            r,
1536            rel_names,
1537            available_rels,
1538        ) {
1539            errors.push(e);
1540        }
1541    }
1542    for block in &td.required_outgoing {
1543        for r in &block.relationships {
1544            if let Err(e) = check_rel(&td.name, "required_outgoing", r, rel_names, available_rels) {
1545                errors.push(e);
1546            }
1547        }
1548        // Conditional blocks: `when_field` / `when_value` travel as a
1549        // pair, the field must be a declared metadata field carrying
1550        // `enum_values`, and the value must be a member. Stricter than
1551        // `requires_when` (which tolerates non-enum trigger fields):
1552        // an edge obligation armed by a free-text value would never
1553        // fire predictably, so the loader refuses instead of loading a
1554        // dead condition.
1555        match (&block.when_field, &block.when_value) {
1556            (None, None) => {}
1557            (Some(f), None) => {
1558                errors.push(SchemaLoadError::InvalidConstraint {
1559                    type_name: td.name.clone(),
1560                    kind: "required_outgoing",
1561                    offender: f.clone(),
1562                    reason: "`when_field` requires `when_value` alongside it".to_string(),
1563                });
1564            }
1565            (None, Some(v)) => {
1566                errors.push(SchemaLoadError::InvalidConstraint {
1567                    type_name: td.name.clone(),
1568                    kind: "required_outgoing",
1569                    offender: v.clone(),
1570                    reason: "`when_value` requires `when_field` alongside it".to_string(),
1571                });
1572            }
1573            (Some(f), Some(v)) => match td.metadata_fields.iter().find(|mf| mf.key == *f) {
1574                None => {
1575                    errors.push(SchemaLoadError::InvalidConstraint {
1576                        type_name: td.name.clone(),
1577                        kind: "required_outgoing",
1578                        offender: f.clone(),
1579                        reason: "`when_field` names no metadata field of this type".to_string(),
1580                    });
1581                }
1582                Some(when_def) => match &when_def.enum_values {
1583                    None => {
1584                        errors.push(SchemaLoadError::InvalidConstraint {
1585                            type_name: td.name.clone(),
1586                            kind: "required_outgoing",
1587                            offender: f.clone(),
1588                            reason: format!(
1589                                "`when_field` must name a metadata field with `enum_values`; `{f}` declares none"
1590                            ),
1591                        });
1592                    }
1593                    Some(allowed) if !allowed.contains(v) => {
1594                        errors.push(SchemaLoadError::InvalidConstraint {
1595                            type_name: td.name.clone(),
1596                            kind: "required_outgoing",
1597                            offender: v.clone(),
1598                            reason: format!(
1599                                "`when_value` is not in `{f}`'s enum_values [{}]",
1600                                allowed.join(", ")
1601                            ),
1602                        });
1603                    }
1604                    Some(_) => {}
1605                },
1606            },
1607        }
1608    }
1609
1610    // Reachability obligations. Per-type checks here; `terminal_types`
1611    // needs every type loaded and is checked in the schema-level pass.
1612    for ob in &td.must_reach {
1613        if ob.relationships.is_empty() {
1614            errors.push(SchemaLoadError::InvalidConstraint {
1615                type_name: td.name.clone(),
1616                kind: "must_reach",
1617                offender: "(empty)".to_string(),
1618                reason: "`relationships` must name at least one relationship".to_string(),
1619            });
1620        }
1621        for r in &ob.relationships {
1622            if let Err(e) = check_rel(&td.name, "must_reach", r, rel_names, available_rels) {
1623                errors.push(e);
1624            }
1625        }
1626        if ob.terminal_types.is_empty() {
1627            errors.push(SchemaLoadError::InvalidConstraint {
1628                type_name: td.name.clone(),
1629                kind: "must_reach",
1630                offender: "(empty)".to_string(),
1631                reason: "`terminal_types` must name at least one type".to_string(),
1632            });
1633        }
1634        if ob.max_depth == Some(0) {
1635            errors.push(SchemaLoadError::InvalidConstraint {
1636                type_name: td.name.clone(),
1637                kind: "must_reach",
1638                offender: "0".to_string(),
1639                reason: "`max_depth` must be at least 1 — nothing is reachable in zero hops"
1640                    .to_string(),
1641            });
1642        }
1643        if ob.severity == crate::types::ConstraintSeverity::Block {
1644            // A transitive property is established by writes on OTHER
1645            // entities, so a write-time refusal would punish the wrong
1646            // mutation — refuse the promise rather than load-and-
1647            // downgrade (same posture as status_propagation).
1648            errors.push(SchemaLoadError::InvalidConstraint {
1649                type_name: td.name.clone(),
1650                kind: "must_reach",
1651                offender: "block".to_string(),
1652                reason: "must_reach is always warn-tier — a reachability gap is created by \
1653                         writes on other entities, so no single write can be refused for it"
1654                    .to_string(),
1655            });
1656        }
1657    }
1658
1659    // Aggregate signals. Per-type checks here; the neighbour pair's
1660    // cross-type validation needs every type loaded and runs in the
1661    // schema-level pass.
1662    let mut signal_names_seen: HashSet<&str> = HashSet::new();
1663    for sig in &td.signals {
1664        let name_ok = sig
1665            .name
1666            .chars()
1667            .next()
1668            .is_some_and(|c| c.is_ascii_lowercase())
1669            && sig
1670                .name
1671                .chars()
1672                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
1673        if !name_ok {
1674            errors.push(SchemaLoadError::InvalidConstraint {
1675                type_name: td.name.clone(),
1676                kind: "signal",
1677                offender: sig.name.clone(),
1678                reason: "`name` must match [a-z][a-z0-9_]*".to_string(),
1679            });
1680        }
1681        if !signal_names_seen.insert(sig.name.as_str()) {
1682            errors.push(SchemaLoadError::InvalidConstraint {
1683                type_name: td.name.clone(),
1684                kind: "signal",
1685                offender: sig.name.clone(),
1686                reason: "duplicate signal name on this type".to_string(),
1687            });
1688        }
1689        if sig.relationships.is_empty() {
1690            errors.push(SchemaLoadError::InvalidConstraint {
1691                type_name: td.name.clone(),
1692                kind: "signal",
1693                offender: sig.name.clone(),
1694                reason: "`relationships` must name at least one relationship".to_string(),
1695            });
1696        }
1697        for r in &sig.relationships {
1698            if let Err(e) = check_rel(&td.name, "signals", r, rel_names, available_rels) {
1699                errors.push(e);
1700            }
1701        }
1702        if sig.thresholds.is_empty() {
1703            errors.push(SchemaLoadError::InvalidConstraint {
1704                type_name: td.name.clone(),
1705                kind: "signal",
1706                offender: sig.name.clone(),
1707                reason: "`thresholds` must declare at least one step".to_string(),
1708            });
1709        }
1710        for pair in sig.thresholds.windows(2) {
1711            if pair[1].at_least <= pair[0].at_least {
1712                errors.push(SchemaLoadError::InvalidConstraint {
1713                    type_name: td.name.clone(),
1714                    kind: "signal",
1715                    offender: pair[1].at_least.to_string(),
1716                    reason: "`thresholds` must have strictly increasing `at_least` values"
1717                        .to_string(),
1718                });
1719            }
1720        }
1721        match (&sig.neighbour_field, &sig.neighbour_value) {
1722            (None, None) | (Some(_), Some(_)) => {}
1723            (Some(f), None) => {
1724                errors.push(SchemaLoadError::InvalidConstraint {
1725                    type_name: td.name.clone(),
1726                    kind: "signal",
1727                    offender: f.clone(),
1728                    reason: "`neighbour_field` requires `neighbour_value` alongside it".to_string(),
1729                });
1730            }
1731            (None, Some(v)) => {
1732                errors.push(SchemaLoadError::InvalidConstraint {
1733                    type_name: td.name.clone(),
1734                    kind: "signal",
1735                    offender: v.clone(),
1736                    reason: "`neighbour_value` requires `neighbour_field` alongside it".to_string(),
1737                });
1738            }
1739        }
1740    }
1741
1742    // Constraint vocabulary (loader honesty: a malformed declaration
1743    // refuses with a typed error naming the offender — never
1744    // load-and-ignore).
1745    let field_keys: std::collections::HashSet<&str> =
1746        td.metadata_fields.iter().map(|f| f.key.as_str()).collect();
1747    let section_keys: std::collections::HashSet<&str> =
1748        td.sections.iter().map(|sec| sec.key.as_str()).collect();
1749    for c in &td.constraints {
1750        match c {
1751            crate::types::ConstraintDef::RequiresWhen {
1752                field,
1753                when_field,
1754                when_value,
1755                ..
1756            } => {
1757                if !field_keys.contains(field.as_str()) && !section_keys.contains(field.as_str()) {
1758                    errors.push(SchemaLoadError::InvalidConstraint {
1759                        type_name: td.name.clone(),
1760                        kind: "requires_when",
1761                        offender: field.clone(),
1762                        reason: "`field` names neither a metadata field nor a section of this type"
1763                            .to_string(),
1764                    });
1765                }
1766                let Some(when_def) = td.metadata_fields.iter().find(|f| f.key == *when_field)
1767                else {
1768                    errors.push(SchemaLoadError::InvalidConstraint {
1769                        type_name: td.name.clone(),
1770                        kind: "requires_when",
1771                        offender: when_field.clone(),
1772                        reason: "`when_field` names no metadata field of this type".to_string(),
1773                    });
1774                    continue;
1775                };
1776                if let Some(allowed) = &when_def.enum_values
1777                    && !allowed.contains(when_value)
1778                {
1779                    errors.push(SchemaLoadError::InvalidConstraint {
1780                        type_name: td.name.clone(),
1781                        kind: "requires_when",
1782                        offender: when_value.clone(),
1783                        reason: format!(
1784                            "`when_value` is not in `{when_field}`'s enum_values [{}]",
1785                            allowed.join(", ")
1786                        ),
1787                    });
1788                }
1789            }
1790            crate::types::ConstraintDef::Unique { fields, .. } => {
1791                if fields.is_empty() {
1792                    errors.push(SchemaLoadError::InvalidConstraint {
1793                        type_name: td.name.clone(),
1794                        kind: "unique",
1795                        offender: "(empty)".to_string(),
1796                        reason: "`fields` must name at least one metadata field".to_string(),
1797                    });
1798                }
1799                for f in fields {
1800                    if !field_keys.contains(f.as_str()) {
1801                        errors.push(SchemaLoadError::InvalidConstraint {
1802                            type_name: td.name.clone(),
1803                            kind: "unique",
1804                            offender: f.clone(),
1805                            reason: "`fields` entry names no metadata field of this type"
1806                                .to_string(),
1807                        });
1808                    }
1809                }
1810            }
1811            crate::types::ConstraintDef::EnumFromNeighbour {
1812                field, rel_type, ..
1813            } => {
1814                if !field_keys.contains(field.as_str()) {
1815                    errors.push(SchemaLoadError::InvalidConstraint {
1816                        type_name: td.name.clone(),
1817                        kind: "enum_from_neighbour",
1818                        offender: field.clone(),
1819                        reason: "`field` names no metadata field of this type".to_string(),
1820                    });
1821                }
1822                if !rel_names.contains(rel_type) {
1823                    errors.push(SchemaLoadError::InvalidConstraint {
1824                        type_name: td.name.clone(),
1825                        kind: "enum_from_neighbour",
1826                        offender: rel_type.clone(),
1827                        reason: "`rel_type` is not in the schema's relationship vocabulary"
1828                            .to_string(),
1829                    });
1830                }
1831                // `section` names a key on the *reached* type, which
1832                // this per-type pass cannot see — the schema-level
1833                // pass after all types load checks it.
1834            }
1835            crate::types::ConstraintDef::TransitionRequiresChecks {
1836                field,
1837                to_value,
1838                relationships,
1839                ..
1840            } => {
1841                match td.metadata_fields.iter().find(|f| f.key == *field) {
1842                    None => {
1843                        errors.push(SchemaLoadError::InvalidConstraint {
1844                            type_name: td.name.clone(),
1845                            kind: "transition_requires_checks",
1846                            offender: field.clone(),
1847                            reason: "`field` names no metadata field of this type".to_string(),
1848                        });
1849                    }
1850                    Some(field_def) => {
1851                        if let Some(allowed) = &field_def.enum_values
1852                            && !allowed.contains(to_value)
1853                        {
1854                            errors.push(SchemaLoadError::InvalidConstraint {
1855                                type_name: td.name.clone(),
1856                                kind: "transition_requires_checks",
1857                                offender: to_value.clone(),
1858                                reason: format!(
1859                                    "`to_value` is not in `{field}`'s enum_values [{}]",
1860                                    allowed.join(", ")
1861                                ),
1862                            });
1863                        }
1864                    }
1865                }
1866                if relationships.is_empty() {
1867                    errors.push(SchemaLoadError::InvalidConstraint {
1868                        type_name: td.name.clone(),
1869                        kind: "transition_requires_checks",
1870                        offender: "(empty)".to_string(),
1871                        reason: "`relationships` must name at least one declared relationship"
1872                            .to_string(),
1873                    });
1874                }
1875                for rel in relationships {
1876                    if !rel_names.contains(rel) {
1877                        errors.push(SchemaLoadError::InvalidConstraint {
1878                            type_name: td.name.clone(),
1879                            kind: "transition_requires_checks",
1880                            offender: rel.clone(),
1881                            reason: "`relationships` entry is not in the schema's relationship \
1882                                     vocabulary"
1883                                .to_string(),
1884                        });
1885                    }
1886                }
1887            }
1888            crate::types::ConstraintDef::StatusPropagation {
1889                field,
1890                value,
1891                rel_type,
1892                rel_types,
1893                severity,
1894                ..
1895            } => {
1896                match td.metadata_fields.iter().find(|f| f.key == *field) {
1897                    None => {
1898                        errors.push(SchemaLoadError::InvalidConstraint {
1899                            type_name: td.name.clone(),
1900                            kind: "status_propagation",
1901                            offender: field.clone(),
1902                            reason: "`field` names no metadata field of this type".to_string(),
1903                        });
1904                    }
1905                    Some(field_def) => {
1906                        if let Some(allowed) = &field_def.enum_values
1907                            && !allowed.contains(value)
1908                        {
1909                            errors.push(SchemaLoadError::InvalidConstraint {
1910                                type_name: td.name.clone(),
1911                                kind: "status_propagation",
1912                                offender: value.clone(),
1913                                reason: format!(
1914                                    "`value` is not in `{field}`'s enum_values [{}]",
1915                                    allowed.join(", ")
1916                                ),
1917                            });
1918                        }
1919                    }
1920                }
1921                // Exactly one of `rel_type` / `rel_types`; every named
1922                // member must be declared; an empty set is a defect.
1923                match (rel_type, rel_types) {
1924                    (Some(_), Some(_)) => {
1925                        errors.push(SchemaLoadError::InvalidConstraint {
1926                            type_name: td.name.clone(),
1927                            kind: "status_propagation",
1928                            offender: "rel_type".to_string(),
1929                            reason: "declare `rel_type` or `rel_types`, not both".to_string(),
1930                        });
1931                    }
1932                    (None, None) => {
1933                        errors.push(SchemaLoadError::InvalidConstraint {
1934                            type_name: td.name.clone(),
1935                            kind: "status_propagation",
1936                            offender: "(missing)".to_string(),
1937                            reason: "one of `rel_type` / `rel_types` is required".to_string(),
1938                        });
1939                    }
1940                    (Some(single), None) => {
1941                        if !rel_names.contains(single) {
1942                            errors.push(SchemaLoadError::InvalidConstraint {
1943                                type_name: td.name.clone(),
1944                                kind: "status_propagation",
1945                                offender: single.clone(),
1946                                reason: "`rel_type` is not in the schema's relationship vocabulary"
1947                                    .to_string(),
1948                            });
1949                        }
1950                    }
1951                    (None, Some(set)) => {
1952                        if set.is_empty() {
1953                            errors.push(SchemaLoadError::InvalidConstraint {
1954                                type_name: td.name.clone(),
1955                                kind: "status_propagation",
1956                                offender: "(empty)".to_string(),
1957                                reason: "`rel_types` must name at least one relationship"
1958                                    .to_string(),
1959                            });
1960                        }
1961                        for name in set {
1962                            if !rel_names.contains(name) {
1963                                errors.push(SchemaLoadError::InvalidConstraint {
1964                                    type_name: td.name.clone(),
1965                                    kind: "status_propagation",
1966                                    offender: name.clone(),
1967                                    reason: "`rel_types` entry is not in the schema's \
1968                                             relationship vocabulary"
1969                                        .to_string(),
1970                                });
1971                            }
1972                        }
1973                    }
1974                }
1975                if *severity == crate::types::ConstraintSeverity::Block {
1976                    // Propagation can never refuse a write (the taint
1977                    // arises from the ancestor's later change), so a
1978                    // `block` declaration would be a promise the
1979                    // engine will not keep — refuse it rather than
1980                    // load-and-downgrade.
1981                    errors.push(SchemaLoadError::InvalidConstraint {
1982                        type_name: td.name.clone(),
1983                        kind: "status_propagation",
1984                        offender: "block".to_string(),
1985                        reason: "status_propagation is always warn-tier — a parent falling after \
1986                                 the child was written cannot retroactively make the child's \
1987                                 write illegal"
1988                            .to_string(),
1989                    });
1990                }
1991            }
1992        }
1993    }
1994
1995    // Due axis (first-author-path plan 08): the declaration's
1996    // references must exist on this type in the declared shapes.
1997    if let Some(due) = &td.due {
1998        match td.metadata_fields.iter().find(|f| f.key == due.date_field) {
1999            None => errors.push(SchemaLoadError::InvalidDueAxis {
2000                type_name: td.name.clone(),
2001                offender: due.date_field.clone(),
2002                reason: "`date_field` names no metadata field of this type".to_string(),
2003            }),
2004            Some(f) if f.field_type != crate::types::FieldType::Date => {
2005                errors.push(SchemaLoadError::InvalidDueAxis {
2006                    type_name: td.name.clone(),
2007                    offender: due.date_field.clone(),
2008                    reason: "`date_field` must name a date-typed metadata field".to_string(),
2009                })
2010            }
2011            Some(_) => {}
2012        }
2013        match td
2014            .metadata_fields
2015            .iter()
2016            .find(|f| f.key == due.status_field)
2017        {
2018            None => errors.push(SchemaLoadError::InvalidDueAxis {
2019                type_name: td.name.clone(),
2020                offender: due.status_field.clone(),
2021                reason: "`status_field` names no metadata field of this type".to_string(),
2022            }),
2023            Some(f) => match &f.enum_values {
2024                None => errors.push(SchemaLoadError::InvalidDueAxis {
2025                    type_name: td.name.clone(),
2026                    offender: due.status_field.clone(),
2027                    reason: "`status_field` must name an enum-typed metadata field \
2028                             (declare enum_values)"
2029                        .to_string(),
2030                }),
2031                Some(allowed) => {
2032                    for v in &due.open_values {
2033                        if !allowed.contains(v) {
2034                            errors.push(SchemaLoadError::InvalidDueAxis {
2035                                type_name: td.name.clone(),
2036                                offender: v.clone(),
2037                                reason: format!(
2038                                    "`open_values` entry is not in `{}`'s enum_values [{}]",
2039                                    due.status_field,
2040                                    allowed.join(", ")
2041                                ),
2042                            });
2043                        }
2044                    }
2045                }
2046            },
2047        }
2048        if due.open_values.is_empty() {
2049            errors.push(SchemaLoadError::InvalidDueAxis {
2050                type_name: td.name.clone(),
2051                offender: "(empty)".to_string(),
2052                reason: "`open_values` must name at least one open status value".to_string(),
2053            });
2054        }
2055        if let Some(lead) = &due.lead_section
2056            && !td.sections.iter().any(|s| s.key == *lead)
2057        {
2058            errors.push(SchemaLoadError::InvalidDueAxis {
2059                type_name: td.name.clone(),
2060                offender: lead.clone(),
2061                reason: "`lead_section` names no section of this type".to_string(),
2062            });
2063        }
2064    }
2065
2066    // Exactly one catch_all section
2067    let catch_all_count = td.sections.iter().filter(|s| s.catch_all).count();
2068    if catch_all_count != 1 {
2069        errors.push(SchemaLoadError::CatchAllViolation {
2070            type_name: td.name.clone(),
2071            count: catch_all_count,
2072        });
2073    }
2074
2075    // Field-reference integrity
2076    let section_keys: HashSet<&str> = td.sections.iter().map(|s| s.key.as_str()).collect();
2077    let meta_keys: HashSet<&str> = td.metadata_fields.iter().map(|m| m.key.as_str()).collect();
2078
2079    for f in &td.text_fields {
2080        // text_fields point at section content — not metadata.
2081        if !section_keys.contains(f.as_str()) {
2082            errors.push(SchemaLoadError::UnknownFieldReference {
2083                type_name: td.name.clone(),
2084                field: "text_fields",
2085                reference: f.clone(),
2086            });
2087        }
2088    }
2089    for f in &td.health_required_fields {
2090        if !section_keys.contains(f.as_str()) && !meta_keys.contains(f.as_str()) {
2091            errors.push(SchemaLoadError::UnknownFieldReference {
2092                type_name: td.name.clone(),
2093                field: "health_required_fields",
2094                reference: f.clone(),
2095            });
2096        }
2097    }
2098    for f in &td.updatable_fields {
2099        // `title` is the entity's filename-derived title — always updatable.
2100        if f == "title" {
2101            continue;
2102        }
2103        if !section_keys.contains(f.as_str()) && !meta_keys.contains(f.as_str()) {
2104            errors.push(SchemaLoadError::UnknownFieldReference {
2105                type_name: td.name.clone(),
2106                field: "updatable_fields",
2107                reference: f.clone(),
2108            });
2109        }
2110    }
2111
2112    // Metadata default_value must be a member of enum_values when both present.
2113    for m in &td.metadata_fields {
2114        if let (Some(default), Some(allowed)) = (m.default_value.as_ref(), m.enum_values.as_ref())
2115            && !allowed.contains(default)
2116        {
2117            errors.push(SchemaLoadError::DefaultValueNotInEnum {
2118                type_name: td.name.clone(),
2119                field: m.key.clone(),
2120                default: default.clone(),
2121                allowed: allowed.clone(),
2122            });
2123        }
2124    }
2125}
2126
2127fn check_rel(
2128    type_name: &str,
2129    field: &'static str,
2130    relationship: &str,
2131    rel_names: &HashSet<String>,
2132    available: &[String],
2133) -> Result<(), SchemaLoadError> {
2134    if rel_names.contains(relationship) {
2135        return Ok(());
2136    }
2137    Err(SchemaLoadError::UndeclaredRelationship {
2138        type_name: type_name.into(),
2139        field,
2140        relationship: relationship.into(),
2141        available: available.to_vec(),
2142    })
2143}