1use crate::entity::Entity;
14use crate::graph::LouvainOutput;
15use crate::store::Store;
16
17#[cfg(test)]
18mod adversarial;
19pub mod archive;
20pub mod canonical;
21pub mod config;
22pub mod graph;
23pub mod ids;
24pub mod strict;
25
26pub use graph::DanglingCrossMemEdge;
27pub use memstead_schema::PublishedMemConfig;
28
29#[derive(Debug, Clone, Copy)]
33pub struct ValidatorLimits {
34 pub max_compressed_archive: u64,
35 pub max_uncompressed_archive: u64,
36 pub max_uncompressed_entry: u64,
37 pub max_config_file: u64,
38 pub max_file_count: u32,
39 pub max_path_length: usize,
40 pub max_path_depth: usize,
41}
42
43impl ValidatorLimits {
44 pub const DEFAULT: Self = Self {
45 max_compressed_archive: 2 * 1024 * 1024,
46 max_uncompressed_archive: 20 * 1024 * 1024,
47 max_uncompressed_entry: 1024 * 1024,
48 max_config_file: 64 * 1024,
49 max_file_count: 10_000,
50 max_path_length: 512,
51 max_path_depth: 16,
52 };
53}
54
55impl Default for ValidatorLimits {
56 fn default() -> Self {
57 Self::DEFAULT
58 }
59}
60
61pub(crate) enum BoundedZipRead {
63 Within(Vec<u8>),
64 ExceedsCap,
68}
69
70pub(crate) fn read_zip_entry_bounded(
77 reader: &mut impl std::io::Read,
78 cap: u64,
79) -> std::io::Result<BoundedZipRead> {
80 use std::io::Read as _;
81 let mut buf = Vec::new();
82 reader.take(cap + 1).read_to_end(&mut buf)?;
83 if buf.len() as u64 > cap {
84 return Ok(BoundedZipRead::ExceedsCap);
85 }
86 Ok(BoundedZipRead::Within(buf))
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum SizeCapKind {
92 CompressedArchive,
93 UncompressedArchive,
94 UncompressedEntry,
95 ConfigFile,
96 EntryCount,
97}
98
99#[derive(Debug, Clone)]
101pub struct MemStats {
102 pub entities: usize,
103 pub edges: usize,
104 pub communities: usize,
105 pub schema: memstead_schema::SchemaRef,
106}
107
108#[derive(Debug)]
112pub struct ValidatedMem {
113 pub config: PublishedMemConfig,
114 pub entities: Vec<Entity>,
115 pub store: Store,
116 pub communities: LouvainOutput,
117 pub stats: MemStats,
118 pub canonical_bytes: Vec<u8>,
119 pub schema_files: Vec<archive::SchemaFile>,
126 pub dangling_cross_mem_edges: Vec<graph::DanglingCrossMemEdge>,
134 pub provenance_bytes: Option<Vec<u8>>,
139 pub anchors_bytes: Option<Vec<u8>>,
145 pub checks_bytes: Option<Vec<u8>>,
151 pub proposals_bytes: Option<Vec<u8>>,
157}
158
159#[derive(Debug, thiserror::Error)]
163pub enum ValidationError {
164 #[error("zip error: {0}")]
166 Zip(String),
167 #[error("symlink entry is not allowed: {0}")]
168 Symlink(String),
169 #[error("unknown file type in archive: {0}")]
170 UnknownFile(String),
171 #[error("duplicate entry path: {0}")]
172 DuplicateEntry(String),
173 #[error("path too long ({len} > {limit}): {path}")]
174 PathTooLong {
175 path: String,
176 len: usize,
177 limit: usize,
178 },
179 #[error("path too deep ({depth} > {limit}): {path}")]
180 PathTooDeep {
181 path: String,
182 depth: usize,
183 limit: usize,
184 },
185 #[error("size cap exceeded ({kind:?}): {got} > {limit}")]
186 SizeCapExceeded {
187 kind: SizeCapKind,
188 got: u64,
189 limit: u64,
190 },
191 #[error("invalid UTF-8 at {path} offset {offset}")]
192 Utf8 { path: String, offset: usize },
193
194 #[error("archive is missing .memstead/config.json")]
196 MissingConfig,
197 #[error("invalid anchors sidecar (.memstead/anchors.json): {reason}")]
198 InvalidAnchorsMember { reason: String },
199 #[error("invalid sealed check records (.memstead/checks.json): {reason}")]
200 InvalidChecksMember { reason: String },
201 #[error("invalid proposal record (.memstead/proposals.json): {reason}")]
202 InvalidProposalsMember { reason: String },
203 #[error("invalid config: {reason}")]
204 InvalidConfig { reason: String },
205 #[error("invalid name: {reason}")]
206 InvalidName { reason: String },
207 #[error("invalid version: {reason}")]
208 InvalidVersion { reason: String },
209 #[error("unsupported format: {got} (expected {expected})")]
210 UnsupportedFormat { got: u32, expected: u32 },
211 #[error("unknown schema '{name}@{version}' — not registered")]
212 UnknownSchema {
213 name: String,
214 version: semver::Version,
215 },
216 #[error("unknown type: {name}")]
217 UnknownType { name: String },
218
219 #[error("embedded schema failed validation: {reason}")]
220 EmbeddedSchemaInvalid { reason: String },
221 #[error(
222 "embedded schema pins '{embedded}' but `.memstead/config.json` declares '{declared}' — archive is inconsistent"
223 )]
224 EmbeddedSchemaMismatch { embedded: String, declared: String },
225
226 #[error("missing frontmatter at {path}")]
228 MissingFrontmatter { path: String },
229 #[error("invalid frontmatter at {path}: {reason}")]
230 InvalidFrontmatter { path: String, reason: String },
231 #[error("unknown frontmatter key at {path}: {key}")]
232 UnknownFrontmatterKey { path: String, key: String },
233 #[error("missing required field at {path}: {field}")]
234 MissingRequiredField { path: String, field: String },
235 #[error("field type mismatch at {path}: {field} (expected {expected})")]
236 FieldTypeMismatch {
237 path: String,
238 field: String,
239 expected: String,
240 },
241 #[error("enum violation at {path}: {field} = {got}")]
242 EnumViolation {
243 path: String,
244 field: String,
245 got: String,
246 },
247 #[error("missing `# Title` at {path}")]
248 MissingTitle { path: String },
249 #[error("missing required section at {path}: {section}")]
250 MissingRequiredSection { path: String, section: String },
251 #[error("unknown section at {path}: {section}")]
252 UnknownSection { path: String, section: String },
253 #[error("malformed relationship line at {path}: {line}")]
254 InvalidRelationshipLine { path: String, line: String },
255 #[error("invalid relationship type at {path}: {rel_type}")]
256 InvalidRelationshipType { path: String, rel_type: String },
257 #[error("invalid wiki-link at {path}: {link} ({reason})")]
258 InvalidWikiLink {
259 path: String,
260 link: String,
261 reason: String,
262 },
263 #[error("unbalanced brackets at {path}")]
264 UnbalancedBrackets { path: String },
265
266 #[error("duplicate entity id {id} from {} and {}", paths.0, paths.1)]
268 DuplicateEntityId { id: String, paths: (String, String) },
269 #[error("cross-mem relationship at {path}: target {target}")]
270 CrossMemRelationship { path: String, target: String },
271 #[error("graph construction failed: {0}")]
272 GraphConstructionFailed(String),
273 #[error("community detection failed: {0}")]
274 CommunityDetectionFailed(String),
275}
276
277pub fn validate_and_normalize_archive(bytes: &[u8]) -> Result<ValidatedMem, ValidationError> {
286 validate_and_normalize_archive_with_limits(bytes, &ValidatorLimits::DEFAULT)
287}
288
289pub fn validate_and_normalize_archive_with_limits(
290 bytes: &[u8],
291 limits: &ValidatorLimits,
292) -> Result<ValidatedMem, ValidationError> {
293 validate_impl(bytes, limits, true)
296}
297
298pub fn validate_and_normalize_archive_lenient(
308 bytes: &[u8],
309) -> Result<ValidatedMem, ValidationError> {
310 validate_impl(bytes, &ValidatorLimits::DEFAULT, false)
311}
312
313#[derive(Debug)]
317pub struct SelfContainedArchive {
318 pub bytes: Vec<u8>,
320 pub dropped: Vec<graph::DanglingCrossMemEdge>,
324}
325
326pub fn make_archive_self_contained(bytes: &[u8]) -> Result<SelfContainedArchive, ValidationError> {
342 let lenient = validate_impl(bytes, &ValidatorLimits::DEFAULT, false)?;
343 if lenient.dangling_cross_mem_edges.is_empty() {
344 return Ok(SelfContainedArchive {
345 bytes: lenient.canonical_bytes,
346 dropped: Vec::new(),
347 });
348 }
349 let mem_name = lenient.config.name.clone();
350 let mut dropped = Vec::new();
351 let mut entities = lenient.entities;
352 for entity in &mut entities {
353 let path = entity.file_path.clone();
354 entity.relationships.retain(|rel| {
355 let keep = rel.target.mem() == mem_name;
356 if !keep {
357 dropped.push(graph::DanglingCrossMemEdge {
358 entity_path: path.clone(),
359 target_id: rel.target.as_ref().to_string(),
360 target_mem: rel.target.mem().to_string(),
361 });
362 }
363 keep
364 });
365 }
366 let embedded_schema = check_embedded_schema(&lenient.schema_files, &lenient.config)?;
367 let repacked = canonical::canonical_bytes(
368 &lenient.config,
369 &entities,
370 &lenient.schema_files,
371 embedded_schema.as_ref(),
372 lenient.provenance_bytes.as_deref(),
373 lenient.anchors_bytes.as_deref(),
374 lenient.checks_bytes.as_deref(),
375 lenient.proposals_bytes.as_deref(),
376 )?;
377 let strict = validate_impl(&repacked, &ValidatorLimits::DEFAULT, true)?;
380 Ok(SelfContainedArchive {
381 bytes: strict.canonical_bytes,
382 dropped,
383 })
384}
385
386pub fn collect_dangling_cross_mem_edges_from_bytes(
399 bytes: &[u8],
400) -> Result<Vec<graph::DanglingCrossMemEdge>, ValidationError> {
401 let limits = &ValidatorLimits::DEFAULT;
402 let entries = archive::extract_entries(bytes, limits)?;
403 let config = config::parse_config_bytes(&entries.config_bytes)?;
404 let embedded_schema = check_embedded_schema(&entries.schema_files, &config)?;
405 let fallback_schema = graph::resolve_fallback_type(None);
406
407 let mut parse_results = Vec::with_capacity(entries.markdown_files.len());
408 for md in &entries.markdown_files {
409 let raw = md.content.as_str();
410 let type_name = crate::entity::parser::peek_type_from_frontmatter(raw);
411 let peeked_schema = type_name
412 .as_deref()
413 .and_then(|n| {
414 embedded_schema
415 .as_ref()
416 .and_then(|s| s.get_type(n))
417 .or_else(|| memstead_schema::type_by_name(n))
418 })
419 .unwrap_or_else(|| fallback_schema.clone());
420
421 let parse_result =
422 crate::entity::parser::parse_markdown(raw, &md.path, &peeked_schema, &config.name)
423 .map_err(|e| map_parse_error(&md.path, &e))?;
424 parse_results.push(parse_result);
425 }
426
427 Ok(graph::dangling_cross_mem_edges_in(
428 &parse_results,
429 &config.name,
430 ))
431}
432
433fn validate_impl(
434 bytes: &[u8],
435 limits: &ValidatorLimits,
436 cross_mem_as_error: bool,
437) -> Result<ValidatedMem, ValidationError> {
438 let entries = archive::extract_entries(bytes, limits)?;
440
441 let config = config::parse_config_bytes(&entries.config_bytes)?;
443
444 let embedded_schema = check_embedded_schema(&entries.schema_files, &config)?;
456
457 let fallback_schema = graph::resolve_fallback_type(None);
464
465 let mut parse_results = Vec::with_capacity(entries.markdown_files.len());
473 for md in &entries.markdown_files {
474 let raw = md.content.as_str();
475
476 let type_name = crate::entity::parser::peek_type_from_frontmatter(raw);
477 let peeked_schema = type_name
478 .as_deref()
479 .and_then(|n| {
480 embedded_schema
481 .as_ref()
482 .and_then(|s| s.get_type(n))
483 .or_else(|| memstead_schema::type_by_name(n))
484 })
485 .unwrap_or_else(|| fallback_schema.clone());
486
487 let parse_result =
488 crate::entity::parser::parse_markdown(raw, &md.path, &peeked_schema, &config.name)
489 .map_err(|e| map_parse_error(&md.path, &e))?;
490
491 strict::validate_strict(raw, &parse_result.entity, &peeked_schema, &md.path)?;
492
493 parse_results.push(parse_result);
494 }
495
496 let parsed_entities: Vec<Entity> = parse_results.iter().map(|pr| pr.entity.clone()).collect();
500 ids::check_unique_ids(&parsed_entities)?;
501
502 let graph_result = graph::build_and_check(
504 parse_results,
505 &fallback_schema,
506 &config.name,
507 cross_mem_as_error,
508 )?;
509
510 let (entity_count, edge_count) = graph::tally(&graph_result.store);
511
512 let stats = MemStats {
513 entities: entity_count,
514 edges: edge_count,
515 communities: graph_result.communities.count,
516 schema: config.schema.clone(),
517 };
518
519 let entities_for_canonical: Vec<Entity> = graph_result
523 .store
524 .all_entities()
525 .filter(|e| !e.stub)
526 .cloned()
527 .collect();
528 let canonical_bytes = canonical::canonical_bytes(
529 &config,
530 &entities_for_canonical,
531 &entries.schema_files,
532 embedded_schema.as_ref(),
533 entries.provenance_bytes.as_deref(),
534 entries.anchors_bytes.as_deref(),
535 entries.checks_bytes.as_deref(),
536 entries.proposals_bytes.as_deref(),
537 )?;
538
539 Ok(ValidatedMem {
540 config,
541 entities: parsed_entities,
542 store: graph_result.store,
543 communities: graph_result.communities,
544 stats,
545 canonical_bytes,
546 schema_files: entries.schema_files,
547 dangling_cross_mem_edges: graph_result.dangling_cross_mem_edges,
548 provenance_bytes: entries.provenance_bytes,
549 anchors_bytes: entries.anchors_bytes,
550 checks_bytes: entries.checks_bytes,
551 proposals_bytes: entries.proposals_bytes,
552 })
553}
554
555fn check_embedded_schema(
564 schema_files: &[archive::SchemaFile],
565 config: &PublishedMemConfig,
566) -> Result<Option<std::sync::Arc<memstead_schema::Schema>>, ValidationError> {
567 if schema_files.is_empty() {
568 return Ok(None);
569 }
570 let schema = memstead_schema::load_sealed_package(&archive::to_package_files(schema_files))
574 .map_err(|e| match e {
575 memstead_schema::SchemaLoadError::SealedPackageMissingManifest => {
576 ValidationError::EmbeddedSchemaInvalid {
577 reason:
578 "`.memstead/schema/` tree present but `.memstead/schema/schema.yaml` is missing"
579 .into(),
580 }
581 }
582 other => ValidationError::EmbeddedSchemaInvalid {
583 reason: other.to_string(),
584 },
585 })?;
586
587 let (embedded_name, embedded_version) = schema.id();
588 if embedded_name != config.schema.name || embedded_version != config.schema.version {
589 return Err(ValidationError::EmbeddedSchemaMismatch {
590 embedded: format!("{embedded_name}@{embedded_version}"),
591 declared: config.schema.as_display(),
592 });
593 }
594 Ok(Some(std::sync::Arc::new(schema)))
595}
596
597fn map_parse_error(path: &str, e: &crate::entity::parser::ParseError) -> ValidationError {
598 use crate::entity::parser::ParseError;
599 match e {
600 ParseError::MissingFrontmatter => ValidationError::MissingFrontmatter {
601 path: path.to_string(),
602 },
603 ParseError::InvalidFrontmatter(reason) => ValidationError::InvalidFrontmatter {
604 path: path.to_string(),
605 reason: reason.clone(),
606 },
607 ParseError::MissingTitle => ValidationError::MissingTitle {
608 path: path.to_string(),
609 },
610 ParseError::Io(err) => ValidationError::InvalidFrontmatter {
611 path: path.to_string(),
612 reason: err.to_string(),
613 },
614 }
615}