memstead_base/runtime_validator.rs
1//! Runtime CRUD validators consumed by the unified [`crate::Engine`] —
2//! the single mutation engine, whatever storage backend (mem-repo git
3//! branch, plain folder, archive) sits behind a mount.
4//!
5//! Distinct concern from [`crate::validator`], which validates sealed
6//! archive bytes at the registry / read-mem ingress boundary. This
7//! module sits *inside* the mutation engine and gates per-mutation
8//! payloads (section keys, metadata keys, enum values) against the
9//! pinned schema. The wire-format error codes
10//! (`UNKNOWN_SECTION`, `UNKNOWN_METADATA`, `INVALID_ENUM_VALUE`,
11//! `MISSING_REQUIRED_SECTION`) are stable regardless of workspace
12//! storage, so MCP callers always see the same envelope shape.
13//!
14//! Returns a typed [`ValidationError`] (or a list of
15//! [`MissingRequiredSection`] for the warning surface) — the engine
16//! layer above wraps these into its error/Result type.
17
18use std::sync::OnceLock;
19
20use indexmap::IndexMap;
21use memstead_schema::{
22 CrossMemRelationshipEntry, FieldType, RelationshipDef, RelationshipMode, Schema, Serialization,
23 TypeDefinition,
24};
25use regex::Regex;
26
27use crate::entity::MetadataValue;
28
29/// Compact relationship-vocabulary entry — `name` plus optional
30/// `when_to_use` prose. Surfaces inside [`ValidationError::InvalidRelationshipType`]
31/// recovery payloads so an agent reads the canonical vocabulary in
32/// the same response that rejected the call. Mirrors the public
33/// `RelationshipHint` shape in `memstead-git-branch`; the engine adapter
34/// there converts between the two with a 1:1 field copy.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct RelationshipHint {
37 pub name: String,
38 pub when_to_use: Option<String>,
39}
40
41/// Inline rendering on the text mirror is the relationship name —
42/// `when_to_use` stays on `details.allowed[].when_to_use` for callers
43/// that branch on the typed shape.
44impl std::fmt::Display for RelationshipHint {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 f.write_str(&self.name)
47 }
48}
49
50/// A typed CRUD-time validation failure. Mirrors the wire-format error
51/// codes the MCP layer surfaces; the engine adapters convert each
52/// variant into their own error type.
53#[derive(Debug, Clone, thiserror::Error)]
54pub enum ValidationError {
55 /// `UNKNOWN_SECTION`: section key not declared on the type and
56 /// not absorbed by a `catch_all` section.
57 #[error("unknown section '{key}' for type '{entity_type}'")]
58 UnknownSection {
59 key: String,
60 entity_type: String,
61 declared: Vec<String>,
62 suggestion: Option<String>,
63 },
64 /// `UNKNOWN_METADATA`: metadata key not declared on the type.
65 #[error("unknown metadata field '{key}' for type '{entity_type}'")]
66 UnknownMetadata {
67 key: String,
68 entity_type: String,
69 declared: Vec<String>,
70 suggestion: Option<String>,
71 },
72 /// `INVALID_ENUM_VALUE`: enum-typed metadata field rejected the
73 /// supplied value.
74 #[error("invalid value '{value}' for field '{field}' on type '{entity_type}'")]
75 InvalidEnumValue {
76 field: String,
77 value: String,
78 allowed: Vec<String>,
79 field_description: Option<String>,
80 suggestion: Option<String>,
81 type_write_rules: Vec<String>,
82 entity_type: String,
83 },
84 /// `READ_ONLY_FIELD`: caller tried to set or unset a read-only
85 /// metadata key (`mem`, `id`, `type`) on update.
86 #[error("cannot change read-only field '{field}' via update")]
87 ReadOnlyField { field: String },
88 /// `SECTION_NOT_UPDATABLE`: the section is not in the type's
89 /// `updatable_fields` allowlist, or it is the virtual
90 /// `relationships` surface (which is managed by `memstead_relate`,
91 /// not `memstead_update`).
92 #[error("section '{section}' is not updatable for type '{entity_type}'")]
93 SectionNotUpdatable {
94 section: String,
95 entity_type: String,
96 },
97 /// `INVALID_REL_TYPE`: the relationship name is not declared in
98 /// the active schema and the schema runs in strict mode. Open-mode
99 /// schemas admit unknown names with a warning instead — see
100 /// [`check_relationship_strict_or_open`].
101 #[error("invalid relationship type '{input}'")]
102 InvalidRelationshipType {
103 input: String,
104 allowed: Vec<RelationshipHint>,
105 suggestion: Option<String>,
106 },
107 /// `INVALID_REL_SHAPE`: the edge's `(from_type, to_type)` pair
108 /// violates the schema's declared `source_types` / `target_types`
109 /// for this relationship. Only fires for shape-pinned edges; an
110 /// edge with empty constraint lists admits any pair.
111 #[error(
112 "relationship '{rel_type}' from type '{from_type}' to type '{to_type}' violates declared shape"
113 )]
114 InvalidRelationshipShape {
115 rel_type: String,
116 from_type: String,
117 to_type: String,
118 allowed_source_types: Vec<String>,
119 allowed_target_types: Vec<String>,
120 suggestion: Option<RelationshipHint>,
121 },
122 /// `SECTION_CONTENT_INVALID`: a section body contains a `^## `
123 /// line (level-2 heading) which the entity's compose-then-reparse
124 /// pipeline would interpret as a section delimiter. Without this
125 /// guard a caller can inject content into a different section by
126 /// embedding a heading in another section's body. Deeper headings
127 /// (`### ` and below) are allowed — the parser anchors only on
128 /// level 2.
129 #[error(
130 "section '{section}' content contains an embedded reserved (`# ` / `## `) heading line '{embedded_heading}' — \
131 the compose-then-reparse pipeline would split the value at that heading; use `### ` or \
132 deeper for sub-headings"
133 )]
134 SectionContentInvalid {
135 section: String,
136 embedded_heading: String,
137 },
138 /// `EMPTY_UNDECLARED_HEADING`: caller-supplied content carries a heading
139 /// the type does not declare with NO body under it.
140 /// The catch-all builder skips empty content, so such
141 /// a heading is dropped on the write that accepts it: the caller is told
142 /// now rather than discovering the loss afterwards.
143 ///
144 /// The boundary is exactly the complement of the catch-all exemption
145 /// [`validate_section_content`] grants: an undeclared heading WITH a body
146 /// survives verbatim and is accepted, one without a body does not survive
147 /// and is refused. The exemption and this refusal are the same rule read
148 /// from its two sides.
149 #[error(
150 "section '{section}' carries heading '{heading}', which type '{entity_type}' does not \
151 declare and which has no body under it. The catch-all keeps absorbed content but skips \
152 empty content, so this heading would be dropped by the write. Give it a body, or \
153 remove the heading."
154 )]
155 EmptyUndeclaredHeading {
156 section: String,
157 heading: String,
158 entity_type: String,
159 },
160 /// `UNTERMINATED_FENCE`: caller-supplied section content ends inside a
161 /// fenced code block that never closes.
162 /// Nothing about the parse is wrong: an open fence's range
163 /// runs to end of text in CommonMark, so every `## ` line the generator
164 /// writes after this section lands inside the fence, is masked, and is
165 /// absorbed into this section's body on the next read. The sections then
166 /// render as empty and the entity reads as healthy.
167 ///
168 /// The sibling guard [`ValidationError::SectionContentInvalid`] refuses
169 /// content that would BECOME a delimiter; this one refuses content that
170 /// would HIDE one. Both are about the same seam from opposite sides, and
171 /// neither can see the other's case: a fence opener is not a heading line,
172 /// and the heading guard's own mask is what renders the hidden heading
173 /// invisible to it.
174 ///
175 /// The oracle is `markdown::closing_fence_if_unterminated`, the referee's
176 /// existing sentinel probe. No second fence model is written here.
177 #[error(
178 "section '{section}' ends inside an unterminated `{fence}` code fence — every section \
179 heading written after it would be swallowed into this body and read back as empty. \
180 Close the fence with a line of `{fence}`."
181 )]
182 UnterminatedFence { section: String, fence: String },
183 /// `SECTION_CONTENT_INVALID` (control-byte sub-case): a section body
184 /// contains a control character other than tab (`\t`) or newline
185 /// (`\n`). A NUL especially makes git classify the `.md` blob as
186 /// binary, defeating the diffable-markdown invariant the storage
187 /// model rests on, and downstream text tooling truncates at it.
188 /// Shares the wire code with the heading-injection case (both are
189 /// `SECTION_CONTENT_INVALID`) — the `control_char`/`byte_offset`
190 /// recovery fields discriminate it from `embedded_heading`. Mirrors
191 /// the title control-char guard (refuse with an actionable hint, not
192 /// silent strip). `\t` and `\n` stay legal; the verbatim-escape
193 /// contract is untouched (this screens a byte class, it does not
194 /// de-escape).
195 #[error(
196 "section '{section}' content contains a disallowed control character U+{codepoint:04X} \
197 at byte offset {byte_offset} — only tab and newline are permitted in section bodies"
198 )]
199 SectionContentControlByte {
200 section: String,
201 /// The offending control character (a `char`, since the body is
202 /// already valid UTF-8 — a NUL is `U+0000`).
203 control_char: char,
204 /// Its Unicode scalar value, surfaced as a number for
205 /// unambiguous machine reading (the string form JSON-escapes).
206 codepoint: u32,
207 /// Byte offset into the section body — matches the `od -c` view a
208 /// caller uses to locate the byte.
209 byte_offset: usize,
210 },
211 /// `INVALID_FIELD_VALUE`: a non-enum typed metadata field received a
212 /// value that does not parse as its declared type — a `Date` field
213 /// given `"not-a-real-date"` or `""`, or a `Number` field given
214 /// non-numeric text. Distinct from `INVALID_ENUM_VALUE` (the key and
215 /// type are valid but the value is out of an enum's vocabulary) and
216 /// `UNKNOWN_METADATA_FIELD` (the key is not declared): here the key
217 /// and field-type are valid but the *value* is malformed for the
218 /// type. Without this check the value round-trips raw and corrupts
219 /// range-filter results (a non-date string sorts lexically against
220 /// real dates, so `*_after` matches it).
221 #[error(
222 "invalid value '{value}' for field '{field}' on type '{entity_type}' — expected {expected_type}"
223 )]
224 InvalidFieldValue {
225 field: String,
226 value: String,
227 expected_type: String,
228 expected_format: Option<String>,
229 field_description: Option<String>,
230 entity_type: String,
231 },
232}
233
234impl ValidationError {
235 /// Stable `UPPER_SNAKE_CASE` wire code for this validation sub-variant.
236 /// Single source of truth — both `EngineError::code()` (via the
237 /// `Validation(_)` arm) and the MCP `validation_envelope` mapper read
238 /// from here, so the wire code cannot drift between channels.
239 pub fn code(&self) -> &'static str {
240 match self {
241 ValidationError::UnknownSection { .. } => "UNKNOWN_SECTION",
242 ValidationError::UnknownMetadata { .. } => "UNKNOWN_METADATA_FIELD",
243 ValidationError::InvalidEnumValue { .. } => "INVALID_ENUM_VALUE",
244 ValidationError::ReadOnlyField { .. } => "READ_ONLY_FIELD",
245 ValidationError::SectionNotUpdatable { .. } => "SECTION_NOT_UPDATABLE",
246 ValidationError::InvalidRelationshipType { .. } => "INVALID_REL_TYPE",
247 ValidationError::InvalidRelationshipShape { .. } => "INVALID_REL_SHAPE",
248 ValidationError::EmptyUndeclaredHeading { .. } => "EMPTY_UNDECLARED_HEADING",
249 ValidationError::UnterminatedFence { .. } => "UNTERMINATED_FENCE",
250 ValidationError::SectionContentInvalid { .. } => "SECTION_CONTENT_INVALID",
251 ValidationError::SectionContentControlByte { .. } => "SECTION_CONTENT_INVALID",
252 ValidationError::InvalidFieldValue { .. } => "INVALID_FIELD_VALUE",
253 }
254 }
255
256 /// Structured recovery payload for this validation sub-variant. The
257 /// payload mirrors the variant's declared fields so callers branching
258 /// on `code` can read the same shape `validation_envelope` ships on
259 /// the MCP wire. Returned shape is documented in the MCP tool
260 /// descriptions — see `Errors:` blocks on `memstead_create` / `memstead_update`
261 /// / `memstead_relate`.
262 pub fn details(&self) -> serde_json::Value {
263 match self {
264 ValidationError::UnknownSection {
265 key,
266 entity_type,
267 declared,
268 suggestion,
269 } => serde_json::json!({
270 "key": key,
271 "entity_type": entity_type,
272 "declared": declared,
273 "suggestion": suggestion,
274 }),
275 ValidationError::UnknownMetadata {
276 key,
277 entity_type,
278 declared,
279 suggestion,
280 } => serde_json::json!({
281 "key": key,
282 "entity_type": entity_type,
283 "declared": declared,
284 "suggestion": suggestion,
285 }),
286 ValidationError::InvalidEnumValue {
287 field,
288 value,
289 allowed,
290 field_description,
291 suggestion,
292 type_write_rules,
293 entity_type,
294 } => serde_json::json!({
295 "field": field,
296 "value": value,
297 "allowed": allowed,
298 "field_description": field_description,
299 "suggestion": suggestion,
300 "type_write_rules": type_write_rules,
301 "entity_type": entity_type,
302 }),
303 ValidationError::ReadOnlyField { field } => serde_json::json!({
304 "field": field,
305 }),
306 ValidationError::SectionNotUpdatable {
307 section,
308 entity_type,
309 } => serde_json::json!({
310 "section": section,
311 "entity_type": entity_type,
312 }),
313 ValidationError::InvalidRelationshipType {
314 input,
315 allowed,
316 suggestion,
317 } => {
318 let allowed_json: Vec<serde_json::Value> = allowed
319 .iter()
320 .map(|h| {
321 serde_json::json!({
322 "name": h.name,
323 "when_to_use": h.when_to_use,
324 })
325 })
326 .collect();
327 serde_json::json!({
328 "input": input,
329 "allowed": allowed_json,
330 "suggestion": suggestion,
331 })
332 }
333 ValidationError::InvalidRelationshipShape {
334 rel_type,
335 from_type,
336 to_type,
337 allowed_source_types,
338 allowed_target_types,
339 suggestion,
340 } => {
341 let suggestion_json = suggestion.as_ref().map(|h| {
342 serde_json::json!({
343 "name": h.name,
344 "when_to_use": h.when_to_use,
345 })
346 });
347 let mut details = serde_json::Map::new();
348 details.insert(
349 "rel_type".into(),
350 serde_json::Value::String(rel_type.clone()),
351 );
352 details.insert(
353 "from_type".into(),
354 serde_json::Value::String(from_type.clone()),
355 );
356 details.insert("to_type".into(), serde_json::Value::String(to_type.clone()));
357 // Empty source/target_types in the schema mean shape-free
358 // (any type admitted). Surface that as an omitted field on
359 // the structured payload — presence implies a constraint,
360 // absence implies "any". Disambiguates "no targets allowed"
361 // (which the engine cannot produce — empty is never a
362 // forbid-all signal) from "any target allowed".
363 if !allowed_source_types.is_empty() {
364 details.insert(
365 "allowed_source_types".into(),
366 serde_json::json!(allowed_source_types),
367 );
368 }
369 if !allowed_target_types.is_empty() {
370 details.insert(
371 "allowed_target_types".into(),
372 serde_json::json!(allowed_target_types),
373 );
374 }
375 details.insert("suggestion".into(), serde_json::json!(suggestion_json));
376 serde_json::Value::Object(details)
377 }
378 ValidationError::UnterminatedFence { section, fence } => serde_json::json!({
379 "section": section,
380 "fence": fence,
381 "expected": format!(
382 "close the fence with a line of `{fence}`, or remove the opener"
383 ),
384 }),
385 ValidationError::EmptyUndeclaredHeading {
386 section,
387 heading,
388 entity_type,
389 } => serde_json::json!({
390 "section": section,
391 "heading": heading,
392 "entity_type": entity_type,
393 "expected": "give the heading a body, or remove it: the catch-all keeps \
394 absorbed content but skips empty content",
395 }),
396 ValidationError::SectionContentInvalid {
397 section,
398 embedded_heading,
399 } => serde_json::json!({
400 "section": section,
401 "embedded_heading": embedded_heading,
402 }),
403 ValidationError::SectionContentControlByte {
404 section,
405 control_char,
406 codepoint,
407 byte_offset,
408 } => serde_json::json!({
409 "section": section,
410 "control_char": control_char.to_string(),
411 "codepoint": codepoint,
412 "byte_offset": byte_offset,
413 }),
414 ValidationError::InvalidFieldValue {
415 field,
416 value,
417 expected_type,
418 expected_format,
419 field_description,
420 entity_type,
421 } => serde_json::json!({
422 "field": field,
423 "value": value,
424 "expected_type": expected_type,
425 "expected_format": expected_format,
426 "field_description": field_description,
427 "entity_type": entity_type,
428 }),
429 }
430 }
431
432 /// Render rich, fully-inlined recovery prose for the agent-visible
433 /// text channel. Closes the asymmetry where warnings render their
434 /// structured `details` inline but errors collapse `details.X`
435 /// references to a "+N more — see details.X" pointer pointing at a
436 /// channel the agent's MCP client doesn't surface to the model. The
437 /// structured
438 /// `details()` channel is unchanged — this method only governs
439 /// `result.content[0].text`. `Display` stays terse for logs and
440 /// `tracing::warn!` consumers.
441 pub fn prose_render(&self) -> String {
442 match self {
443 ValidationError::UnknownSection {
444 key,
445 entity_type,
446 declared,
447 suggestion,
448 } => {
449 let declared_inline = if declared.is_empty() {
450 "(none)".to_string()
451 } else {
452 declared.join(", ")
453 };
454 let suggestion_clause = suggestion
455 .as_deref()
456 .map(|s| format!(" Did you mean '{s}'?"))
457 .unwrap_or_default();
458 format!(
459 "unknown section '{key}' for type '{entity_type}' — declared sections: {declared_inline}.{suggestion_clause}"
460 )
461 }
462 ValidationError::UnknownMetadata {
463 key,
464 entity_type,
465 declared,
466 suggestion,
467 } => {
468 let declared_inline = if declared.is_empty() {
469 "(none)".to_string()
470 } else {
471 declared.join(", ")
472 };
473 let suggestion_clause = suggestion
474 .as_deref()
475 .map(|s| format!(" Did you mean '{s}'?"))
476 .unwrap_or_default();
477 format!(
478 "unknown metadata field '{key}' for type '{entity_type}' — declared fields: {declared_inline}.{suggestion_clause}"
479 )
480 }
481 ValidationError::InvalidEnumValue {
482 field,
483 value,
484 allowed,
485 field_description,
486 suggestion,
487 type_write_rules,
488 entity_type,
489 } => {
490 let allowed_inline = if allowed.is_empty() {
491 "(none)".to_string()
492 } else {
493 allowed.join(", ")
494 };
495 let desc_clause = field_description
496 .as_deref()
497 .map(|d| format!(" Field purpose: {d}."))
498 .unwrap_or_default();
499 let suggestion_clause = suggestion
500 .as_deref()
501 .map(|s| format!(" Did you mean '{s}'?"))
502 .unwrap_or_default();
503 let rules_clause = if type_write_rules.is_empty() {
504 String::new()
505 } else {
506 format!(" Type-level write_rules: {}.", type_write_rules.join("; "))
507 };
508 format!(
509 "invalid value '{value}' for field '{field}' on type '{entity_type}' — allowed: {allowed_inline}.{desc_clause}{suggestion_clause}{rules_clause}"
510 )
511 }
512 ValidationError::ReadOnlyField { field } => {
513 format!("cannot change read-only field '{field}' via update")
514 }
515 ValidationError::SectionNotUpdatable {
516 section,
517 entity_type,
518 } => format!("section '{section}' is not updatable for type '{entity_type}'"),
519 ValidationError::InvalidRelationshipType {
520 input,
521 allowed,
522 suggestion,
523 } => {
524 let allowed_inline = if allowed.is_empty() {
525 "(none)".to_string()
526 } else {
527 allowed
528 .iter()
529 .map(|h| h.name.clone())
530 .collect::<Vec<_>>()
531 .join(", ")
532 };
533 let suggestion_clause = suggestion
534 .as_deref()
535 .map(|s| format!(" Did you mean '{s}'?"))
536 .unwrap_or_default();
537 format!(
538 "invalid relationship type '{input}' — must be one of the schema's declared types: {allowed_inline}.{suggestion_clause}"
539 )
540 }
541 ValidationError::InvalidRelationshipShape {
542 rel_type,
543 from_type,
544 to_type,
545 allowed_source_types,
546 allowed_target_types,
547 suggestion,
548 } => {
549 let sources_inline = if allowed_source_types.is_empty() {
550 "any".to_string()
551 } else {
552 allowed_source_types.join(", ")
553 };
554 let targets_inline = if allowed_target_types.is_empty() {
555 "any".to_string()
556 } else {
557 allowed_target_types.join(", ")
558 };
559 let suggestion_clause = suggestion
560 .as_ref()
561 .map(|h| format!(" Suggested rel-type: '{}'.", h.name))
562 .unwrap_or_default();
563 format!(
564 "relationship '{rel_type}' from type '{from_type}' to type '{to_type}' violates declared shape — allowed sources: {sources_inline}; allowed targets: {targets_inline}.{suggestion_clause}"
565 )
566 }
567 ValidationError::EmptyUndeclaredHeading {
568 section,
569 heading,
570 entity_type,
571 } => format!(
572 "section '{section}' carries heading '{heading}', which type '{entity_type}' does \
573 not declare and which has no body under it. An undeclared heading WITH content \
574 is kept byte-verbatim in the catch-all; an empty one is skipped, so this write \
575 would drop it. Give the heading a body, or remove it."
576 ),
577 ValidationError::UnterminatedFence { section, fence } => format!(
578 "section '{section}' ends inside an unterminated `{fence}` code fence. In \
579 CommonMark an open fence runs to the end of the text, so every section heading \
580 written after this one would land inside the fence, be masked, and be read back \
581 as part of THIS section's body: the sections after it would render empty and \
582 the entity would still read as healthy. Close the fence with a line of \
583 `{fence}`, or remove the opener."
584 ),
585 ValidationError::SectionContentInvalid {
586 section,
587 embedded_heading,
588 } => format!(
589 "section '{section}' content contains an embedded reserved (`# ` / `## `) heading line '{embedded_heading}' — use `### ` or deeper for sub-headings"
590 ),
591 ValidationError::SectionContentControlByte {
592 section,
593 codepoint,
594 byte_offset,
595 ..
596 } => format!(
597 "section '{section}' content contains a disallowed control character U+{codepoint:04X} at byte offset {byte_offset} — \
598 only tab (U+0009) and newline (U+000A) are permitted in section bodies. Remove the control character: it would break \
599 the diffable-markdown invariant (a NUL makes git treat the file as binary and text tooling truncates at it)."
600 ),
601 ValidationError::InvalidFieldValue {
602 field,
603 value,
604 expected_type,
605 expected_format,
606 field_description,
607 entity_type,
608 } => {
609 let format_clause = expected_format
610 .as_deref()
611 .map(|f| format!(" Expected format: {f}."))
612 .unwrap_or_default();
613 let desc_clause = field_description
614 .as_deref()
615 .map(|d| format!(" Field purpose: {d}."))
616 .unwrap_or_default();
617 format!(
618 "invalid value '{value}' for field '{field}' on type '{entity_type}' — \
619 not a valid {expected_type}.{format_clause}{desc_clause}"
620 )
621 }
622 }
623 }
624}
625
626/// Reserved metadata keys — the entity's identity/discriminator triple.
627/// No write path accepts them as caller-supplied metadata (create and
628/// update both refuse a *set*); letting them ride the schema's declared
629/// fields would silently drift the entity-id contract. Unset is the one
630/// sanctioned exception: `metadata_unset` may name a reserved key to
631/// repair an entity that acquired a smuggled one before the write gates
632/// closed — removing a reserved key can only move the entity toward the
633/// invariant (the `type` discriminator is re-seeded by the engine, never
634/// left absent).
635pub const READ_ONLY_METADATA_KEYS: &[&str] = &["mem", "id", "type"];
636
637/// Reject a caller-supplied reserved identity/discriminator key
638/// (`mem` / `id` / `type`) as metadata — the create-path half of the
639/// reservation, deliberate and typed
640/// ([`ValidationError::ReadOnlyField`]) rather than the incidental
641/// `UNKNOWN_METADATA_FIELD` a reserved key would otherwise trip
642/// (no installable schema can declare one). Timestamp fields are NOT
643/// checked here: create's posture for `init_timestamp` /
644/// `auto_timestamp` fields is stamp-and-proceed with an
645/// `IGNORED_READONLY_FIELD` warning, deliberately.
646///
647/// The `_` prefix is refused as a namespace, not as a key list: every
648/// underscore-prefixed frontmatter key is a computed read-channel slot
649/// (`_hash`, `_tokens`, `_signals`, ...), so a stored metadata key in
650/// that namespace would render as a second, stale copy of a computed
651/// field — frontmatter copied out of a read response and pasted into a
652/// write is the observed ingress. Unset stays permissive (see
653/// [`validate_unsettable_metadata_key`]): removing a smuggled `_` key
654/// is the same sanctioned repair as removing a smuggled reserved key.
655pub fn validate_reserved_metadata_key(key: &str) -> Result<(), ValidationError> {
656 if READ_ONLY_METADATA_KEYS.contains(&key) || key.starts_with('_') {
657 return Err(ValidationError::ReadOnlyField {
658 field: key.to_string(),
659 });
660 }
661 Ok(())
662}
663
664/// Reject any attempt to **set** a read-only metadata key. The single
665/// mutation engine (`memstead-base`) calls this from its `update_entity`
666/// path over the `metadata` map: the `mem` / `id` / `type` triple stays
667/// engine-authoritative, and the schema's `init_timestamp` /
668/// `auto_timestamp` annotations are honoured on write — the engine
669/// owns those values on create (`init_timestamp`, set once) and on
670/// every update (`auto_timestamp`, re-stamped). Returns
671/// [`ValidationError::ReadOnlyField`] on rejection. The unset path has
672/// its own gate ([`validate_unsettable_metadata_key`]) because the
673/// reserved triple is unset-allowed there as the sanctioned repair.
674pub fn validate_writable_metadata_key(
675 key: &str,
676 schema: &TypeDefinition,
677) -> Result<(), ValidationError> {
678 validate_reserved_metadata_key(key)?;
679 if let Some(field) = schema.metadata_field(key)
680 && (field.init_timestamp || field.auto_timestamp)
681 {
682 return Err(ValidationError::ReadOnlyField {
683 field: key.to_string(),
684 });
685 }
686 Ok(())
687}
688
689/// Gate for `metadata_unset` keys. Unlike the set path
690/// ([`validate_writable_metadata_key`]), the reserved
691/// identity/discriminator triple (`mem` / `id` / `type`) IS
692/// unsettable: removing one can only move an entity toward the
693/// invariant, and it is the sanctioned repair for entities that
694/// acquired a smuggled reserved key before the write gates closed
695/// (delete-and-recreate would destroy provenance and edges).
696/// Engine-stamped timestamp fields (`init_timestamp` /
697/// `auto_timestamp`) stay refused on unset — the engine owns their
698/// values and re-stamps them; unsetting one is caller confusion, not
699/// repair.
700pub fn validate_unsettable_metadata_key(
701 key: &str,
702 schema: &TypeDefinition,
703) -> Result<(), ValidationError> {
704 if let Some(field) = schema.metadata_field(key)
705 && (field.init_timestamp || field.auto_timestamp)
706 {
707 return Err(ValidationError::ReadOnlyField {
708 field: key.to_string(),
709 });
710 }
711 Ok(())
712}
713
714/// Reject an `memstead_update` attempt to write a section that is either
715/// the virtual `relationships` surface (managed by `memstead_relate`) or
716/// not part of the type's `updatable_fields` allowlist. When the
717/// allowlist is empty the section passes — types that opt out of the
718/// allowlist accept any declared section.
719pub fn validate_updatable_section(
720 section: &str,
721 schema: &TypeDefinition,
722) -> Result<(), ValidationError> {
723 if section == "relationships" {
724 return Err(ValidationError::SectionNotUpdatable {
725 section: section.to_string(),
726 entity_type: schema.name.clone(),
727 });
728 }
729 if !schema.updatable_fields.is_empty() && !schema.updatable_fields.iter().any(|f| f == section)
730 {
731 return Err(ValidationError::SectionNotUpdatable {
732 section: section.to_string(),
733 entity_type: schema.name.clone(),
734 });
735 }
736 Ok(())
737}
738
739/// Tier-2 warning shape — the create / update path emits one entry per
740/// required section that is missing or empty. Same payload the MCP
741/// layer surfaces as `MISSING_REQUIRED_SECTION` warnings. Type-level
742/// `write_rules` no longer ride per warning — they ship once at the
743/// mutation-response top level on `type_guidance` keyed by
744/// `entity_type`.
745#[derive(Debug, Clone)]
746pub struct MissingRequiredSection {
747 pub entity_type: String,
748 pub key: String,
749 pub heading: String,
750 pub write_rules: Vec<String>,
751}
752
753/// What a type's catch-all absorbs, for [`validate_section_content`].
754#[derive(Debug, Clone, Copy)]
755pub struct CatchAllContext<'a> {
756 /// The catch-all section's key.
757 pub key: &'a str,
758 /// The entity type, so a refusal can name what does not declare the
759 /// heading rather than leaving the caller to work it out.
760 pub entity_type: &'a str,
761 /// Every heading the type declares. A `## ` line matching one of these
762 /// forks the entity even inside the catch-all, so it stays refused.
763 pub declared_headings: &'a [&'a str],
764}
765
766/// Build a [`CatchAllContext`] for a type, when it has a catch-all section.
767/// The borrowed heading list lives in `buf`, which the caller owns.
768pub fn catch_all_context<'a>(
769 type_def: &'a memstead_schema::TypeDefinition,
770 buf: &'a mut Vec<&'a str>,
771) -> Option<CatchAllContext<'a>> {
772 let key = type_def.catch_all_section()?.key.as_str();
773 buf.extend(type_def.sections.iter().map(|s| s.heading.as_str()));
774 Some(CatchAllContext {
775 key,
776 entity_type: type_def.name.as_str(),
777 declared_headings: buf,
778 })
779}
780
781/// Whether the lines after `heading` in `body`, up to the next `## ` line,
782/// are all blank. That is what the catch-all builder skips.
783fn heading_body_is_empty(body: &str, heading_line: &str) -> bool {
784 let mut lines = body.lines().skip_while(|l| *l != heading_line);
785 lines.next();
786 for line in lines {
787 if line.starts_with("## ") {
788 return true;
789 }
790 if !line.trim().is_empty() {
791 return false;
792 }
793 }
794 true
795}
796
797/// Refuse section content that would round-trip through the compose
798/// pipeline as a section delimiter. The compose-then-reparse loop's
799/// parser anchors on `(?m)^## (.+)$` over the *masked* body, so a
800/// section body that shows a `^## ` line to that scan gets split at
801/// that heading on the next read — content after the heading lands
802/// under a different section key (or a fabricated one). Deeper
803/// headings (`### ` and below) are safe — the parser only matches
804/// level 2.
805///
806/// The guard is applied to the content **as the reparse will see it**,
807/// which is what makes it exact rather than approximate:
808///
809/// - the content is trimmed first, because the splitter stores the
810/// trimmed body — an indented block opening a section loses its
811/// indent on write-back, so ` ## Not A Heading` becomes a real
812/// column-0 delimiter on the next parse. Checking the still-indented
813/// provided content missed that fork entirely;
814/// - code blocks are masked first, by the same CommonMark referee the
815/// splitter uses ([`crate::markdown`]) — a `## ` inside a fenced or
816/// indented code block never splits anything, so refusing it was the
817/// write path disagreeing with the read path about what a code block
818/// is.
819///
820/// `catch_all` names the type's catch-all section and its declared headings,
821/// when the caller knows them. Inside
822/// the CATCH-ALL body only, a `## ` line whose heading the type does not
823/// declare is accepted, because the reparse absorbs it straight back into the
824/// catch-all: the content does not land under a different key, which is the
825/// whole basis of this guard. That case is not hypothetical — it is what the
826/// engine itself emits, since the catch-all builder re-emits absorbed content
827/// under its original heading line, and an agent that read an entity and wrote
828/// that section back in replace mode was refused its own value.
829///
830/// This does NOT weaken the guard. A DECLARED heading inside the catch-all
831/// still refuses, because that one really does fork: the reparse would move
832/// the content to the declared key. Every other section is unchanged, and a
833/// caller who passes `None` gets exactly the old behaviour.
834pub fn validate_section_content<'a>(
835 sections: impl Iterator<Item = (&'a str, &'a str)>,
836 catch_all: Option<CatchAllContext<'_>>,
837) -> Result<(), ValidationError> {
838 for (key, value) in sections {
839 // Refuse control characters other than tab/newline before the
840 // heading check. A NUL (and other C0/C1/DEL controls) persists
841 // verbatim today and breaks the diffable-markdown invariant — a
842 // NUL makes git classify the blob as binary and downstream text
843 // tooling truncates at it. Mirrors the title control-char guard
844 // (`char::is_control`, refuse-with-actionable-hint) but keeps
845 // `\t`/`\n` legal, which titles disallow. We refuse rather than
846 // strip — silently mutating caller-sent content is the
847 // no-silent-data-loss anti-pattern the title fix already flagged.
848 // The verbatim-escape contract is untouched: this screens a byte
849 // class, it does not interpret or de-escape content.
850 if let Some((byte_offset, ch)) = value
851 .char_indices()
852 .find(|(_, c)| c.is_control() && *c != '\t' && *c != '\n')
853 {
854 return Err(ValidationError::SectionContentControlByte {
855 section: key.to_string(),
856 control_char: ch,
857 codepoint: ch as u32,
858 byte_offset,
859 });
860 }
861 // Before the heading walk, because the two guards diagnose the same
862 // seam and this one has the better answer when both apply: a body
863 // that leaves a fence open AND carries a heading is swallowed, not
864 // forked, so naming the fence tells the caller what to fix.
865 if let Some(fence) = crate::markdown::closing_fence_if_unterminated(value.trim()) {
866 return Err(ValidationError::UnterminatedFence {
867 section: key.to_string(),
868 fence,
869 });
870 }
871 // What the splitter will store, and what the splitter will
872 // see in it. `stored` and `masked` share byte offsets and line
873 // count, so the two line sequences correspond one-to-one and
874 // the refusal can quote the real line.
875 let stored = crate::entity::parser::stored_section_text(value).0;
876 let masked = crate::markdown::mask_code_blocks(stored);
877 for (line, masked_line) in stored.lines().zip(masked.lines()) {
878 // Match the parser's regex shape: `^## ` (two hashes, one
879 // space, at least one trailing char). The trailing space
880 // requirement excludes bare `##` (which the parser does
881 // not match either) and `###`+ headings. `^# ` joins the
882 // guard: h1 and h2 are the entity's own levels
883 // — the title and the section delimiters — so neither may
884 // be embedded in a section body.
885 let is_h2 = masked_line.starts_with("## ") && masked_line.len() > 3;
886 let is_h1 = masked_line.starts_with("# ") && masked_line.len() > 2;
887 // The one exemption, and it is exact: the catch-all re-absorbs an
888 // undeclared h2 rather than forking on it — but only when there is
889 // something under it. An undeclared heading WITH a body survives
890 // the round trip verbatim; one with NO body is skipped by the
891 // catch-all builder and silently dropped by the write, so it
892 // refuses instead. The exemption and the refusal are the same rule
893 // read from its two sides. "Declared" is decided by the key the
894 // parser derives from the heading (case, spaces and trailing
895 // blanks folded), never by the heading text, because the parser
896 // keeps the first body per key and drops the rest.
897 if is_h2
898 && catch_all.is_some_and(|c| {
899 let derived = memstead_schema::derive_section_key(masked_line[3..].trim());
900 c.key == key
901 && !c
902 .declared_headings
903 .iter()
904 .any(|h| memstead_schema::derive_section_key(h) == derived)
905 })
906 {
907 if heading_body_is_empty(stored, line) {
908 return Err(ValidationError::EmptyUndeclaredHeading {
909 section: key.to_string(),
910 heading: masked_line[3..].to_string(),
911 entity_type: catch_all
912 .map(|c| c.entity_type.to_string())
913 .unwrap_or_default(),
914 });
915 }
916 continue;
917 }
918 if is_h2 || is_h1 {
919 return Err(ValidationError::SectionContentInvalid {
920 section: key.to_string(),
921 embedded_heading: line.to_string(),
922 });
923 }
924 }
925 }
926 Ok(())
927}
928
929/// Validate that every section key in `provided` is either schema-declared
930/// for `schema`, or — if the schema has a catch-all section — admitted by
931/// it. Unknown keys return [`ValidationError::UnknownSection`] carrying
932/// the declared list plus a Levenshtein suggestion (or the catch-all key
933/// when no close match exists).
934///
935/// Pure function: no I/O, no allocation outside the eventual error
936/// payload. The `"relationships"` section is allowed through here — the
937/// engine layer above gates it via its own SectionNotUpdatable check.
938pub fn validate_section_keys<'a>(
939 provided: impl Iterator<Item = &'a str>,
940 schema: &TypeDefinition,
941) -> Result<(), ValidationError> {
942 let mut declared: Vec<String> = schema.sections.iter().map(|s| s.key.clone()).collect();
943 declared.sort();
944 let declared_set: std::collections::HashSet<&str> =
945 schema.sections.iter().map(|s| s.key.as_str()).collect();
946 let catch_all_key = schema.catch_all_section().map(|s| s.key.clone());
947
948 for key in provided {
949 if key == "relationships" {
950 continue;
951 }
952 if declared_set.contains(key) {
953 continue;
954 }
955 let suggestion = schema
956 .suggest_section(key)
957 .or_else(|| catch_all_key.clone());
958 return Err(ValidationError::UnknownSection {
959 key: key.to_string(),
960 entity_type: schema.name.clone(),
961 declared: declared.clone(),
962 suggestion,
963 });
964 }
965 Ok(())
966}
967
968/// Parse a metadata value string into the appropriate
969/// [`MetadataValue`] type, consulting the schema for field-type
970/// information. Validates enum constraints when the field definition
971/// specifies `enum_values`.
972///
973/// Unknown keys are a hard error — engine code that builds metadata
974/// only emits schema-declared fields, so a lenient insert would
975/// silently drop the value at write time and the agent would read a
976/// success response while losing data.
977pub fn parse_metadata_value(
978 key: &str,
979 value: &str,
980 schema: &TypeDefinition,
981) -> Result<MetadataValue, ValidationError> {
982 let Some(field_def) = schema.metadata_field(key) else {
983 let mut declared: Vec<String> = schema
984 .metadata_fields
985 .iter()
986 .map(|f| f.key.clone())
987 .collect();
988 declared.sort();
989 return Err(ValidationError::UnknownMetadata {
990 key: key.to_string(),
991 entity_type: schema.name.clone(),
992 declared,
993 suggestion: schema.suggest_metadata_field(key),
994 });
995 };
996
997 if let Some(ref allowed) = field_def.enum_values
998 && !allowed.iter().any(|v| v == value)
999 {
1000 let suggestion = nearest_str_match(value, allowed);
1001 return Err(ValidationError::InvalidEnumValue {
1002 field: key.to_string(),
1003 value: value.to_string(),
1004 allowed: allowed.clone(),
1005 field_description: Some(field_def.description.clone()),
1006 suggestion,
1007 type_write_rules: schema.write_rules.clone(),
1008 entity_type: schema.name.clone(),
1009 });
1010 }
1011
1012 // A declared `value_pattern` binds every written value in full; a
1013 // csv-array field is checked member by member so the refusal names
1014 // the one malformed entry, not the whole list.
1015 if let Some(pattern) = field_def.value_pattern.as_ref()
1016 && let Ok(re) = regex::Regex::new(&format!("^(?:{pattern})$"))
1017 {
1018 let members: Vec<&str> = if field_def.serialization == Serialization::CsvArray {
1019 value.split(',').map(str::trim).collect()
1020 } else {
1021 vec![value]
1022 };
1023 if let Some(bad) = members.iter().find(|m| !re.is_match(m)) {
1024 return Err(ValidationError::InvalidFieldValue {
1025 field: key.to_string(),
1026 value: (*bad).to_string(),
1027 // The field's declared type, as the schema spells it
1028 // (`number`, `date`, `string`): a pattern binds any type.
1029 expected_type: serde_json::to_value(field_def.field_type)
1030 .ok()
1031 .and_then(|v| v.as_str().map(str::to_string))
1032 .unwrap_or_else(|| "string".to_string()),
1033 expected_format: Some(format!("matching the pattern `{pattern}`")),
1034 field_description: Some(field_def.description.clone()),
1035 entity_type: schema.name.clone(),
1036 });
1037 }
1038 }
1039
1040 Ok(match field_def.field_type {
1041 FieldType::Boolean => {
1042 // `true` / `false` in any case, or their digits. Anything else
1043 // is refused like a non-number in a Number field: read as
1044 // `false`, a typo would land as a real value.
1045 if value.eq_ignore_ascii_case("true") || value == "1" {
1046 MetadataValue::Bool(true)
1047 } else if value.eq_ignore_ascii_case("false") || value == "0" {
1048 MetadataValue::Bool(false)
1049 } else {
1050 return Err(ValidationError::InvalidFieldValue {
1051 field: key.to_string(),
1052 value: value.to_string(),
1053 expected_type: "Boolean".to_string(),
1054 expected_format: Some("true or false".to_string()),
1055 field_description: Some(field_def.description.clone()),
1056 entity_type: schema.name.clone(),
1057 });
1058 }
1059 }
1060 FieldType::Number => {
1061 if let Ok(n) = value.parse::<i64>() {
1062 MetadataValue::Integer(n)
1063 } else if let Ok(f) = value.parse::<f64>() {
1064 MetadataValue::Float(f)
1065 } else {
1066 // Pre-fix this fell back to `String`, silently storing
1067 // non-numeric text in a Number field. Reject so the
1068 // value never reaches the store (and never corrupts a
1069 // range filter on the field).
1070 return Err(ValidationError::InvalidFieldValue {
1071 field: key.to_string(),
1072 value: value.to_string(),
1073 expected_type: "Number".to_string(),
1074 expected_format: Some("an integer or decimal number".to_string()),
1075 field_description: Some(field_def.description.clone()),
1076 entity_type: schema.name.clone(),
1077 });
1078 }
1079 }
1080 FieldType::Date => {
1081 // The field's declared shape is `YYYY-MM-DD` (or the ISO
1082 // datetime form). Pre-fix any string — including `""` and
1083 // arbitrary text — fell through to the `String` arm and was
1084 // stored raw; a non-date value then sorts lexically against
1085 // real dates and produces false `*_after` / `*_before`
1086 // range-filter matches. Validate at the write boundary so
1087 // the corruption can never land.
1088 if !is_date_shaped(value) {
1089 return Err(ValidationError::InvalidFieldValue {
1090 field: key.to_string(),
1091 value: value.to_string(),
1092 expected_type: "Date".to_string(),
1093 expected_format: Some("YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ".to_string()),
1094 field_description: Some(field_def.description.clone()),
1095 entity_type: schema.name.clone(),
1096 });
1097 }
1098 MetadataValue::String(value.to_string())
1099 }
1100 _ => MetadataValue::String(value.to_string()),
1101 })
1102}
1103
1104/// Does `s` match the shape a `Date`-typed metadata value must have —
1105/// `YYYY-MM-DD` or the ISO-8601 datetime form `YYYY-MM-DDTHH:MM:SSZ`?
1106///
1107/// Single source of truth for the date-shape check, shared by the CRUD
1108/// write path ([`parse_metadata_value`]) and the archive-ingress strict
1109/// validator (`crate::validator::strict::value_matches_type`). Keeping
1110/// one regex means the value a `memstead_create` accepts and the value an
1111/// import re-accepts cannot drift apart.
1112pub fn is_date_shaped(s: &str) -> bool {
1113 static RE: OnceLock<Regex> = OnceLock::new();
1114 RE.get_or_init(|| Regex::new(r"^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?$").unwrap())
1115 .is_match(s)
1116}
1117
1118/// Tier-2 warning shape — the create path emits one entry per required
1119/// metadata field that is not auto-filled by the schema (no
1120/// `default_value`, no `init_timestamp`, no `auto_timestamp`) and was
1121/// not supplied by the caller. Same payload the MCP layer surfaces as
1122/// `MISSING_REQUIRED_FIELD` warnings — mirrors the
1123/// `REQUIRED_FIELD_UNSET` error envelope so a single decoder handles
1124/// both surfaces.
1125#[derive(Debug, Clone)]
1126pub struct MissingRequiredField {
1127 pub entity_type: String,
1128 pub key: String,
1129 pub description: String,
1130 pub enum_values: Vec<String>,
1131}
1132
1133/// Return one [`MissingRequiredField`] per required metadata field that
1134/// the caller did not supply and the schema does not auto-fill. A field
1135/// is "auto-filled" when it carries `default_value`, `init_timestamp`,
1136/// or `auto_timestamp` — the engine writes a non-trivial value without
1137/// caller input. Optional fields and supplied fields are skipped.
1138///
1139/// Caller-side intent: the warning fires when the entity would land in
1140/// a stuck state (placeholder today's-date / empty string) that the
1141/// agent did not opt into. Surfaced from the create path so dry-run
1142/// and real-write preview the same set of warnings.
1143pub fn missing_required_fields(
1144 schema: &TypeDefinition,
1145 supplied: &IndexMap<String, String>,
1146) -> Vec<MissingRequiredField> {
1147 schema
1148 .metadata_fields
1149 .iter()
1150 .filter(|f| {
1151 // Engine-managed fields (`type`, `id`, `mem`) are seeded
1152 // independently of caller input; not the agent's
1153 // responsibility to supply.
1154 !READ_ONLY_METADATA_KEYS.contains(&f.key.as_str())
1155 && f.is_required()
1156 && f.default_value.is_none()
1157 && !f.init_timestamp
1158 && !f.auto_timestamp
1159 && !supplied.contains_key(f.key.as_str())
1160 })
1161 .map(|f| MissingRequiredField {
1162 entity_type: schema.name.clone(),
1163 key: f.key.clone(),
1164 description: f.description.clone(),
1165 enum_values: f.enum_values.clone().unwrap_or_default(),
1166 })
1167 .collect()
1168}
1169
1170/// Return one [`MissingRequiredSection`] per required section that is
1171/// absent or empty in `sections`. Empty (whitespace-only) bodies count
1172/// as missing — same predicate as the health report uses.
1173pub fn missing_required_sections(
1174 schema: &TypeDefinition,
1175 sections: &IndexMap<String, String>,
1176) -> Vec<MissingRequiredSection> {
1177 schema
1178 .required_sections()
1179 .filter_map(|sec| {
1180 let is_empty = sections
1181 .get(sec.key.as_str())
1182 .is_none_or(|c| c.trim().is_empty());
1183 is_empty.then(|| MissingRequiredSection {
1184 entity_type: schema.name.clone(),
1185 key: sec.key.clone(),
1186 heading: sec.heading.clone(),
1187 write_rules: sec.write_rules.clone(),
1188 })
1189 })
1190 .collect()
1191}
1192
1193/// Outcome of running a relationship name against a schema. The
1194/// engine adapter above decides whether to ride the warning out on
1195/// the response (open mode) or convert the error into its own type
1196/// (strict mode).
1197#[derive(Debug, Clone)]
1198pub enum RelationshipCheck {
1199 /// Name is declared in the schema's relationship vocabulary.
1200 Ok,
1201 /// Schema runs in open mode and admits the name with a warning
1202 /// the engine layer can surface to the agent.
1203 OpenWarning(String),
1204}
1205
1206/// Validate a relationship name against a mem schema's vocabulary.
1207/// Strict-mode schemas reject undeclared names with
1208/// [`ValidationError::InvalidRelationshipType`]; open-mode schemas
1209/// admit unknown names and return a warning string for the engine to
1210/// surface.
1211///
1212/// The mutation engine calls this from its `memstead_relate` path; the
1213/// wire shape (`INVALID_REL_TYPE`, `allowed[]`, `suggestion`) is stable
1214/// regardless of workspace storage.
1215pub fn validate_rel_type(
1216 rel_type: &str,
1217 schema: &Schema,
1218) -> Result<RelationshipCheck, ValidationError> {
1219 if schema.relationship_known(rel_type) {
1220 return Ok(RelationshipCheck::Ok);
1221 }
1222 match schema.mode() {
1223 RelationshipMode::Strict => {
1224 let allowed = declared_relationship_hints(schema);
1225 let candidate_names: Vec<String> = allowed.iter().map(|h| h.name.clone()).collect();
1226 let suggestion = nearest_str_match(rel_type, &candidate_names);
1227 Err(ValidationError::InvalidRelationshipType {
1228 input: rel_type.to_string(),
1229 allowed,
1230 suggestion,
1231 })
1232 }
1233 RelationshipMode::Open => {
1234 let declared: Vec<String> = declared_relationship_hints(schema)
1235 .into_iter()
1236 .map(|h| h.name)
1237 .collect();
1238 let suggestion = schema
1239 .suggest_relationship(rel_type)
1240 .map(|s| format!(" Did you mean '{s}'?"))
1241 .unwrap_or_default();
1242 let (schema_name, schema_version) = schema.id();
1243 Ok(RelationshipCheck::OpenWarning(format!(
1244 "relationship '{rel_type}' is not declared in schema \
1245 '{schema_name}@{schema_version}' (mode: open). \
1246 Accepted with default weight. Declared: [{}].{suggestion}",
1247 declared.join(", "),
1248 )))
1249 }
1250 }
1251}
1252
1253/// Reject an edge whose `(from_type, to_type)` pair violates the
1254/// schema's declared `source_types` / `target_types` for this
1255/// relationship. No-op when both constraint lists are empty
1256/// (shape-free edges) or when the relationship name is unknown
1257/// (callers run this only after [`validate_rel_type`] succeeds, so
1258/// this branch is defensive). The target-type check is skipped when
1259/// `to_type` is `None` — happens for auto-stubbed targets that have
1260/// no type yet; once the stub is authored as a real entity, future
1261/// edges land under the strict check.
1262///
1263/// Suggestion: nearest-match edge in the schema whose declared shape
1264/// would admit `(from_type, to_type)`. Tiebreaker is declaration
1265/// order in the YAML (deterministic).
1266pub fn validate_rel_shape(
1267 rel_type: &str,
1268 from_type: &str,
1269 to_type: Option<&str>,
1270 schema: &Schema,
1271) -> Result<(), ValidationError> {
1272 let Some(def) = schema.relationship_def(rel_type) else {
1273 return Ok(());
1274 };
1275 let source_ok = def.source_types.is_empty() || def.source_types.iter().any(|t| t == from_type);
1276 let target_ok = def.target_types.is_empty()
1277 || to_type.is_none_or(|t| def.target_types.iter().any(|d| d == t));
1278 if source_ok && target_ok {
1279 return Ok(());
1280 }
1281 let to_for_err = to_type.unwrap_or("<unknown>").to_string();
1282 let suggestion = suggest_shape_admitting(from_type, to_type, schema);
1283 Err(ValidationError::InvalidRelationshipShape {
1284 rel_type: rel_type.to_string(),
1285 from_type: from_type.to_string(),
1286 to_type: to_for_err,
1287 allowed_source_types: def.source_types.clone(),
1288 allowed_target_types: def.target_types.clone(),
1289 suggestion,
1290 })
1291}
1292
1293/// Outcome of looking up a rel-type against a cross-mem entry in
1294/// the source schema's `cross_mem_relationships:` vocabulary.
1295/// `EdgeNotDeclared` carries the recovery payload the engine layer
1296/// wraps into [`crate::EngineError::CrossMemEdgeNotDeclared`]; the
1297/// other variants reuse the existing `ValidationError` shapes so
1298/// agents reading the wire shape decode `INVALID_REL_TYPE` /
1299/// `INVALID_REL_SHAPE` identically in both intra- and cross-mem
1300/// flows.
1301#[derive(Debug, Clone)]
1302pub enum CrossMemRelCheck {
1303 /// `(rel_type, from_type, to_type)` are admitted by the matched
1304 /// cross-mem entry's declared vocabulary and shape. The engine
1305 /// proceeds with the relate write.
1306 Ok,
1307 /// The source schema declares no cross-mem entry whose
1308 /// `to_schema:` matches the target schema. Carries the recovery
1309 /// payload for `CROSS_MEM_EDGE_NOT_DECLARED`.
1310 EdgeNotDeclared,
1311 /// Validation tripped the matched cross-mem entry's own
1312 /// vocabulary / shape — reuses the existing `INVALID_REL_TYPE` /
1313 /// `INVALID_REL_SHAPE` envelopes (carried as the wrapped
1314 /// `ValidationError`) so wire-shape decoders stay flat.
1315 Invalid(ValidationError),
1316}
1317
1318/// Validate a cross-mem edge whose source and target mems pin
1319/// schemas with *different names* against the source schema's
1320/// outbound `cross_mem_relationships:` vocabulary.
1321///
1322/// Caller responsibility: only invoke when the source and target
1323/// schema *names* differ — same-name mems (any version pair) fall
1324/// through to the intra-mem path ([`validate_rel_type`] +
1325/// [`validate_rel_shape`]); same-name is same domain.
1326///
1327/// The lookup goes through [`Schema::cross_mem_entry`], which
1328/// matches by target schema name only — eligibility is name-based,
1329/// so the target mem's pinned version never participates and a
1330/// version bump on the target side cannot invalidate a declaration.
1331///
1332/// On a match, the cross-mem entry's `definitions` list is the sole
1333/// vocabulary for this edge: the source schema's intra-mem
1334/// `relationships.definitions` is NOT consulted in this regime. A rel-type present intra-mem but absent cross-mem
1335/// surfaces here as `INVALID_REL_TYPE`; a shape violation surfaces
1336/// here as `INVALID_REL_SHAPE` with the cross-mem entry's shape
1337/// (not the intra-mem entry's, if both exist).
1338pub fn validate_cross_mem_edge(
1339 rel_type: &str,
1340 from_type: &str,
1341 to_type: Option<&str>,
1342 source_schema: &Schema,
1343 target_schema_ref: &memstead_schema::SchemaRef,
1344) -> CrossMemRelCheck {
1345 // Priority-ordered entries: exact-name declaration first, then the
1346 // `to_schema: "*"` wildcard (loader-bound to the schema's alias
1347 // target rel-type). First rel-type hit across the entries wins, so
1348 // structural declarations for a destination never shadow the
1349 // wildcarded alias links into it.
1350 let entries = source_schema.cross_mem_entries(&target_schema_ref.name);
1351 if entries.is_empty() {
1352 return CrossMemRelCheck::EdgeNotDeclared;
1353 }
1354
1355 let Some(def) = entries
1356 .iter()
1357 .find_map(|entry| entry.definitions.iter().find(|d| d.name == rel_type))
1358 else {
1359 // Only the wildcard matched and it doesn't carry this
1360 // rel-type: for THIS destination schema the rel-type has
1361 // genuinely no declaration — the historical
1362 // `CROSS_MEM_EDGE_NOT_DECLARED` refusal, so a structural edge
1363 // into an undeclared schema reads the same with or without a
1364 // wildcard present (the wildcard only ever admits the alias
1365 // rel-type).
1366 if !entries.iter().any(|e| e.to_schema != "*") {
1367 return CrossMemRelCheck::EdgeNotDeclared;
1368 }
1369 let allowed: Vec<RelationshipHint> = cross_mem_entries_hints(&entries);
1370 let candidate_names: Vec<String> = allowed.iter().map(|h| h.name.clone()).collect();
1371 let suggestion = nearest_str_match(rel_type, &candidate_names);
1372 return CrossMemRelCheck::Invalid(ValidationError::InvalidRelationshipType {
1373 input: rel_type.to_string(),
1374 allowed,
1375 suggestion,
1376 });
1377 };
1378
1379 let source_ok = def.source_types.is_empty() || def.source_types.iter().any(|t| t == from_type);
1380 let target_ok = def.target_types.is_empty()
1381 || to_type.is_none_or(|t| def.target_types.iter().any(|d| d == t));
1382 if source_ok && target_ok {
1383 return CrossMemRelCheck::Ok;
1384 }
1385 let to_for_err = to_type.unwrap_or("<unknown>").to_string();
1386 let suggestion = entries
1387 .iter()
1388 .find_map(|entry| cross_mem_suggest_shape(entry, from_type, to_type));
1389 CrossMemRelCheck::Invalid(ValidationError::InvalidRelationshipShape {
1390 rel_type: rel_type.to_string(),
1391 from_type: from_type.to_string(),
1392 to_type: to_for_err,
1393 allowed_source_types: def.source_types.clone(),
1394 allowed_target_types: def.target_types.clone(),
1395 suggestion,
1396 })
1397}
1398
1399/// Union of [`cross_mem_entry_hints`] across priority-ordered entries,
1400/// de-duplicated by rel-type name (first entry's hint wins) and
1401/// re-sorted.
1402fn cross_mem_entries_hints(entries: &[&CrossMemRelationshipEntry]) -> Vec<RelationshipHint> {
1403 let mut out: Vec<RelationshipHint> = Vec::new();
1404 for entry in entries {
1405 for hint in cross_mem_entry_hints(entry) {
1406 if !out.iter().any(|h| h.name == hint.name) {
1407 out.push(hint);
1408 }
1409 }
1410 }
1411 out.sort_by(|a, b| a.name.cmp(&b.name));
1412 out
1413}
1414
1415/// Sorted vocabulary hints for one cross-mem entry, excluding the
1416/// `_default` sentinel — same shape as
1417/// [`declared_relationship_hints`] but scoped to a single cross-mem
1418/// declaration.
1419fn cross_mem_entry_hints(entry: &CrossMemRelationshipEntry) -> Vec<RelationshipHint> {
1420 let mut out: Vec<RelationshipHint> = entry
1421 .definitions
1422 .iter()
1423 .filter(|d| d.name != "_default")
1424 .map(|d| RelationshipHint {
1425 name: d.name.clone(),
1426 when_to_use: d.when_to_use.clone(),
1427 })
1428 .collect();
1429 out.sort_by(|a, b| a.name.cmp(&b.name));
1430 out
1431}
1432
1433/// First cross-mem `definition` in declaration order whose declared
1434/// shape would admit `(from_type, to_type)`. Mirrors
1435/// [`suggest_shape_admitting`] but scoped to a single cross-mem
1436/// entry.
1437fn cross_mem_suggest_shape(
1438 entry: &CrossMemRelationshipEntry,
1439 from_type: &str,
1440 to_type: Option<&str>,
1441) -> Option<RelationshipHint> {
1442 entry
1443 .definitions
1444 .iter()
1445 .filter(|d| d.name != "_default")
1446 .find(|d| cross_mem_def_admits(d, from_type, to_type))
1447 .map(|d| RelationshipHint {
1448 name: d.name.clone(),
1449 when_to_use: d.when_to_use.clone(),
1450 })
1451}
1452
1453fn cross_mem_def_admits(d: &RelationshipDef, from_type: &str, to_type: Option<&str>) -> bool {
1454 let src_ok = d.source_types.is_empty() || d.source_types.iter().any(|t| t == from_type);
1455 let tgt_ok =
1456 d.target_types.is_empty() || to_type.is_none_or(|t| d.target_types.iter().any(|x| x == t));
1457 src_ok && tgt_ok
1458}
1459
1460/// First edge in declaration order whose declared shape would admit
1461/// the `(from_type, to_type)` pair. Empty `source_types` /
1462/// `target_types` admit anything. Returns `None` when no such edge
1463/// exists. The `_default` sentinel is excluded — it carries no shape
1464/// and is never a real edge's rel_type.
1465fn suggest_shape_admitting(
1466 from_type: &str,
1467 to_type: Option<&str>,
1468 schema: &Schema,
1469) -> Option<RelationshipHint> {
1470 schema
1471 .manifest
1472 .relationships
1473 .definitions
1474 .iter()
1475 .filter(|d| d.name != "_default")
1476 .find(|d| {
1477 let src_ok = d.source_types.is_empty() || d.source_types.iter().any(|t| t == from_type);
1478 let tgt_ok = d.target_types.is_empty()
1479 || to_type.is_none_or(|t| d.target_types.iter().any(|x| x == t));
1480 src_ok && tgt_ok
1481 })
1482 .map(|d| RelationshipHint {
1483 name: d.name.clone(),
1484 when_to_use: d.when_to_use.clone(),
1485 })
1486}
1487
1488/// Sorted relationship vocabulary as `RelationshipHint`s, excluding
1489/// the internal `_default` catch-all. Used inside
1490/// [`validate_rel_type`] to populate the `INVALID_REL_TYPE` recovery
1491/// payload's `allowed[]` list.
1492fn declared_relationship_hints(schema: &Schema) -> Vec<RelationshipHint> {
1493 let mut out: Vec<RelationshipHint> = schema
1494 .manifest
1495 .relationships
1496 .definitions
1497 .iter()
1498 .filter(|d| d.name != "_default")
1499 .map(|d| RelationshipHint {
1500 name: d.name.clone(),
1501 when_to_use: d.when_to_use.clone(),
1502 })
1503 .collect();
1504 out.sort_by(|a, b| a.name.cmp(&b.name));
1505 out
1506}
1507
1508/// Levenshtein-nearest match against a candidate set, with a noise
1509/// floor of `chars/2` (beyond that the input shares almost nothing with
1510/// the schema vocabulary, so a "did you mean" suggestion does not
1511/// help). Returns `None` when no candidate is close enough.
1512fn nearest_str_match(needle: &str, candidates: &[String]) -> Option<String> {
1513 let noise_floor = (needle.chars().count() / 2).max(1);
1514 let mut best: Option<(usize, String)> = None;
1515 for cand in candidates {
1516 let d = strsim::levenshtein(needle, cand);
1517 if d == 0 || d > noise_floor {
1518 continue;
1519 }
1520 match &best {
1521 Some((bd, _)) if *bd <= d => {}
1522 _ => best = Some((d, cand.clone())),
1523 }
1524 }
1525 best.map(|(_, name)| name)
1526}
1527
1528#[cfg(test)]
1529mod tests;