1pub const INSTALL_PROVENANCE_FILE: &str = "install-provenance.json";
32
33use std::path::{Path, PathBuf};
34
35use crate::builtins::builtin_schemas_dir;
36use crate::config::SchemaRef;
37
38#[derive(Debug, Clone)]
46pub struct SchemaSourceFile {
47 pub archive_path: String,
48 pub bytes: Vec<u8>,
49}
50
51#[derive(Debug, thiserror::Error)]
52pub enum SchemaSourceError {
53 #[error(
54 "schema {schema_ref} not found — candidate paths tried: [{}]",
55 .candidates.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ")
56 )]
57 NotFound {
58 schema_ref: String,
59 candidates: Vec<PathBuf>,
63 },
64
65 #[error("i/o error reading schema source at {}: {source}", .path.display())]
66 Io {
67 path: PathBuf,
68 #[source]
69 source: std::io::Error,
70 },
71
72 #[error(
73 "schema manifest at {} does not declare version '{expected}' (found '{found}')",
74 .path.display()
75 )]
76 VersionMismatch {
77 path: PathBuf,
78 expected: String,
79 found: String,
80 },
81
82 #[error("schema manifest at {} is malformed: {reason}", .path.display())]
83 MalformedManifest { path: PathBuf, reason: String },
84}
85
86impl SchemaSourceError {
87 pub fn code(&self) -> &'static str {
89 match self {
90 SchemaSourceError::NotFound { .. } => "SCHEMA_NOT_FOUND",
91 SchemaSourceError::Io { .. } => "IO_ERROR",
92 SchemaSourceError::VersionMismatch { .. }
93 | SchemaSourceError::MalformedManifest { .. } => "SCHEMA_VALIDATION_FAILED",
94 }
95 }
96
97 pub fn details(&self) -> serde_json::Value {
99 match self {
100 SchemaSourceError::NotFound {
101 schema_ref,
102 candidates,
103 } => serde_json::json!({ "schema_ref": schema_ref, "candidates": candidates }),
104 SchemaSourceError::Io { path, source } => {
105 serde_json::json!({ "path": path, "reason": source.to_string() })
106 }
107 SchemaSourceError::VersionMismatch {
108 path,
109 expected,
110 found,
111 } => serde_json::json!({ "path": path, "expected": expected, "found": found }),
112 SchemaSourceError::MalformedManifest { path, reason } => {
113 serde_json::json!({ "path": path, "reason": reason })
114 }
115 }
116 }
117}
118
119pub fn collect_schema_source(
140 _workspace_root: Option<&Path>,
141 workspace_schemas_dir: Option<&Path>,
142 schema_ref: &SchemaRef,
143) -> Result<Vec<SchemaSourceFile>, SchemaSourceError> {
144 let mut candidates: Vec<PathBuf> = Vec::new();
145
146 if let Some(ws_dir) = workspace_schemas_dir {
147 let versioned_dir = ws_dir.join(format!("{}@{}", schema_ref.name, schema_ref.version));
151 candidates.push(versioned_dir.clone());
152 if versioned_dir.is_dir()
153 && let Some(files) = try_collect_dir(&versioned_dir, schema_ref)?
154 {
155 return Ok(files);
156 }
157 let ws_schema_dir = ws_dir.join(&schema_ref.name);
158 candidates.push(ws_schema_dir.clone());
159 if ws_schema_dir.is_dir()
160 && let Some(files) = try_collect_dir(&ws_schema_dir, schema_ref)?
161 {
162 return Ok(files);
163 }
164 }
165
166 if let Some(files) = collect_builtin_source(schema_ref)? {
167 return Ok(files);
168 }
169
170 Err(SchemaSourceError::NotFound {
171 schema_ref: schema_ref.as_display(),
172 candidates,
173 })
174}
175
176fn try_collect_dir(
181 dir: &Path,
182 schema_ref: &SchemaRef,
183) -> Result<Option<Vec<SchemaSourceFile>>, SchemaSourceError> {
184 let manifest_path = dir.join("schema.yaml");
185 let manifest_bytes = std::fs::read(&manifest_path).map_err(|e| SchemaSourceError::Io {
186 path: manifest_path.clone(),
187 source: e,
188 })?;
189
190 if !manifest_matches(&manifest_bytes, schema_ref, &manifest_path)? {
191 return Ok(None);
192 }
193
194 let mut out = vec![SchemaSourceFile {
195 archive_path: "schema.yaml".to_string(),
196 bytes: manifest_bytes,
197 }];
198
199 let marker_path = dir.join(crate::loader::SCHEMA_FORMAT_MARKER_FILE);
203 if marker_path.is_file() {
204 let bytes = std::fs::read(&marker_path).map_err(|e| SchemaSourceError::Io {
205 path: marker_path.clone(),
206 source: e,
207 })?;
208 out.push(SchemaSourceFile {
209 archive_path: crate::loader::SCHEMA_FORMAT_MARKER_FILE.to_string(),
210 bytes,
211 });
212 }
213
214 let types_dir = dir.join("types");
215 if types_dir.is_dir() {
216 let entries = std::fs::read_dir(&types_dir).map_err(|e| SchemaSourceError::Io {
217 path: types_dir.clone(),
218 source: e,
219 })?;
220 for entry in entries {
221 let entry = entry.map_err(|e| SchemaSourceError::Io {
222 path: types_dir.clone(),
223 source: e,
224 })?;
225 let path = entry.path();
226 if path.extension().and_then(|s| s.to_str()) != Some("yaml") {
227 continue;
228 }
229 let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
230 continue;
231 };
232 let bytes = std::fs::read(&path).map_err(|e| SchemaSourceError::Io {
233 path: path.clone(),
234 source: e,
235 })?;
236 out.push(SchemaSourceFile {
237 archive_path: format!("types/{stem}.yaml"),
238 bytes,
239 });
240 }
241 }
242
243 out.sort_by(|a, b| a.archive_path.cmp(&b.archive_path));
244 Ok(Some(out))
245}
246
247fn collect_builtin_source(
248 schema_ref: &SchemaRef,
249) -> Result<Option<Vec<SchemaSourceFile>>, SchemaSourceError> {
250 if let Some(schema_dir) = builtin_schemas_dir().get_dir(schema_ref.name.as_str())
252 && let Some(files) = collect_builtin_dir(schema_dir, schema_ref)?
253 {
254 return Ok(Some(files));
255 }
256 for schema_dir in builtin_schemas_dir().dirs() {
264 if let Some(files) = collect_builtin_dir(schema_dir, schema_ref)? {
265 return Ok(Some(files));
266 }
267 }
268 Ok(None)
269}
270
271fn collect_builtin_dir(
276 schema_dir: &include_dir::Dir<'static>,
277 schema_ref: &SchemaRef,
278) -> Result<Option<Vec<SchemaSourceFile>>, SchemaSourceError> {
279 let prefix = schema_dir.path().display().to_string();
283 let manifest_key = format!("{prefix}/schema.yaml");
284 let Some(manifest_file) = schema_dir.get_file(manifest_key.as_str()) else {
285 return Ok(None);
286 };
287 let manifest_bytes = manifest_file.contents().to_vec();
288 if !manifest_matches(
289 &manifest_bytes,
290 schema_ref,
291 &PathBuf::from(format!("<builtin:{prefix}>/schema.yaml")),
292 )? {
293 return Ok(None);
294 }
295
296 let mut out = vec![SchemaSourceFile {
297 archive_path: "schema.yaml".to_string(),
298 bytes: manifest_bytes,
299 }];
300
301 let marker_key = format!("{prefix}/{}", crate::loader::SCHEMA_FORMAT_MARKER_FILE);
304 if let Some(marker) = schema_dir.get_file(marker_key.as_str()) {
305 out.push(SchemaSourceFile {
306 archive_path: crate::loader::SCHEMA_FORMAT_MARKER_FILE.to_string(),
307 bytes: marker.contents().to_vec(),
308 });
309 }
310
311 let types_key = format!("{prefix}/types");
312 if let Some(types_dir) = schema_dir.get_dir(types_key.as_str()) {
313 for file in types_dir.files() {
314 if file.path().extension().and_then(|s| s.to_str()) != Some("yaml") {
315 continue;
316 }
317 let Some(stem) = file.path().file_stem().and_then(|s| s.to_str()) else {
318 continue;
319 };
320 out.push(SchemaSourceFile {
321 archive_path: format!("types/{stem}.yaml"),
322 bytes: file.contents().to_vec(),
323 });
324 }
325 }
326
327 out.sort_by(|a, b| a.archive_path.cmp(&b.archive_path));
328 Ok(Some(out))
329}
330
331fn manifest_matches(
338 manifest_bytes: &[u8],
339 schema_ref: &SchemaRef,
340 source_path: &Path,
341) -> Result<bool, SchemaSourceError> {
342 #[derive(serde::Deserialize)]
343 struct ManifestId {
344 name: String,
345 version: String,
346 }
347 let id: ManifestId = serde_yaml_ng::from_slice(manifest_bytes).map_err(|e| {
348 SchemaSourceError::MalformedManifest {
349 path: source_path.to_path_buf(),
350 reason: e.to_string(),
351 }
352 })?;
353 if id.name != schema_ref.name {
354 return Ok(false);
355 }
356 let declared =
357 semver::Version::parse(&id.version).map_err(|e| SchemaSourceError::MalformedManifest {
358 path: source_path.to_path_buf(),
359 reason: format!("invalid semver '{}': {e}", id.version),
360 })?;
361 if declared != schema_ref.version {
362 if source_path.to_string_lossy().starts_with("<builtin:") {
375 return Ok(false);
376 }
377 return Err(SchemaSourceError::VersionMismatch {
378 path: source_path.to_path_buf(),
379 expected: schema_ref.version.to_string(),
380 found: declared.to_string(),
381 });
382 }
383 Ok(true)
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use tempfile::TempDir;
390
391 fn write_schema(dir: &Path, name: &str, version: &str, types: &[&str]) {
392 let manifest = format!(
393 r#"name: {name}
394version: {version}
395description: test
396when_to_use: test
397types:
398 - {type_list}
399relationships:
400 mode: strict
401 definitions:
402 - name: _default
403 description: default
404 default_weight: 1.0
405 - name: PART_OF
406 description: hier
407 default_weight: 3.0
408community:
409 resolution: 1.0
410 seed: 42
411"#,
412 name = name,
413 version = version,
414 type_list = types.join("\n - "),
415 );
416 std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
417 for t in types {
418 let td = format!(
419 r#"name: {t}
420description: test
421when_to_use: test
422sections:
423 - key: body
424 heading: Body
425 required: true
426 search_weight: 10.0
427 catch_all: true
428metadata_fields: []
429title_weight: 1.0
430text_fields: [body]
431hierarchy_relationship: PART_OF
432no_self_loop_relationships: []
433updatable_fields: [title, body]
434health_required_fields: [body]
435staleness_threshold_days: 30
436write_rules: []
437"#
438 );
439 std::fs::write(dir.join(format!("types/{t}.yaml")), td).unwrap();
440 }
441 }
442
443 #[test]
447 fn collectors_carry_format_marker_as_found() {
448 let marked: SchemaRef = "default@1.3.0".parse().unwrap();
449 let files = collect_schema_source(None, None, &marked).unwrap();
450 assert!(
451 files
452 .iter()
453 .any(|f| f.archive_path == crate::loader::SCHEMA_FORMAT_MARKER_FILE),
454 "current generation collects its marker"
455 );
456
457 let legacy: SchemaRef = "default@1.2.0".parse().unwrap();
458 let files = collect_schema_source(None, None, &legacy).unwrap();
459 assert!(
460 !files
461 .iter()
462 .any(|f| f.archive_path == crate::loader::SCHEMA_FORMAT_MARKER_FILE),
463 "retained pre-flip generation stays unmarked"
464 );
465 }
466
467 #[test]
468 fn collects_builtin_default_source() {
469 let schema_ref = SchemaRef::new("default", semver::Version::new(1, 0, 0));
470 let files = collect_schema_source(None, None, &schema_ref).unwrap();
471
472 assert!(
473 files.iter().any(|f| f.archive_path == "schema.yaml"),
474 "embedded builtin must expose schema.yaml"
475 );
476 let type_count = files
477 .iter()
478 .filter(|f| f.archive_path.starts_with("types/"))
479 .count();
480 assert_eq!(type_count, 10, "default schema has 10 types");
481 for pair in files.windows(2) {
482 assert!(pair[0].archive_path < pair[1].archive_path, "sorted");
483 }
484 }
485
486 #[test]
493 fn collects_builtin_source_for_every_retained_version() {
494 for (name, version) in [
495 ("planning", semver::Version::new(0, 2, 0)),
496 ("planning", semver::Version::new(0, 4, 0)),
497 ("ingest", semver::Version::new(0, 1, 0)),
498 ("ingest", semver::Version::new(0, 5, 0)),
499 ] {
500 let schema_ref = SchemaRef::new(name, version.clone());
501 let files = collect_schema_source(None, None, &schema_ref)
502 .unwrap_or_else(|e| panic!("{name}@{version} must resolve: {e}"));
503 let manifest = files
504 .iter()
505 .find(|f| f.archive_path == "schema.yaml")
506 .expect("manifest present");
507 let text = String::from_utf8_lossy(&manifest.bytes);
508 assert!(
509 text.contains(&format!("version: {version}")),
510 "{name}@{version}: collected manifest must carry the requested version"
511 );
512 }
513
514 let ghost = SchemaRef::new("planning", semver::Version::new(9, 9, 9));
517 assert!(matches!(
518 collect_schema_source(None, None, &ghost),
519 Err(SchemaSourceError::NotFound { .. })
520 ));
521 }
522
523 #[test]
524 fn workspace_schema_wins_over_builtin() {
525 let tmp = TempDir::new().unwrap();
526 let ws_dir = tmp.path().join("schemas");
527 let schema_dir = ws_dir.join("default");
528 std::fs::create_dir_all(schema_dir.join("types")).unwrap();
529 write_schema(&schema_dir, "default", "1.0.0", &["spec"]);
532 let schema_ref = SchemaRef::new("default", semver::Version::new(1, 0, 0));
533 let files = collect_schema_source(Some(tmp.path()), Some(&ws_dir), &schema_ref).unwrap();
534 let type_count = files
535 .iter()
536 .filter(|f| f.archive_path.starts_with("types/"))
537 .count();
538 assert_eq!(type_count, 1, "workspace override takes priority");
539 }
540
541 #[test]
542 fn workspace_mismatched_version_errors() {
543 let tmp = TempDir::new().unwrap();
544 let ws_dir = tmp.path().join("schemas");
545 let schema_dir = ws_dir.join("recipe");
546 std::fs::create_dir_all(schema_dir.join("types")).unwrap();
547 write_schema(&schema_dir, "recipe", "1.0.0", &["spec"]);
548 let schema_ref = SchemaRef::new("recipe", semver::Version::new(2, 0, 0));
549 let err = collect_schema_source(Some(tmp.path()), Some(&ws_dir), &schema_ref).unwrap_err();
550 assert!(matches!(err, SchemaSourceError::VersionMismatch { .. }));
551 }
552
553 #[test]
558 fn legacy_cache_directory_is_not_a_source() {
559 let tmp = TempDir::new().unwrap();
560 let dir = tmp.path().join(".memstead.cache/schemas/recipe-1.0.0");
561 std::fs::create_dir_all(dir.join("types")).unwrap();
562 write_schema(&dir, "recipe", "1.0.0", &["spec"]);
563 let schema_ref = SchemaRef::new("recipe", semver::Version::new(1, 0, 0));
564 let err = collect_schema_source(Some(tmp.path()), None, &schema_ref).unwrap_err();
565 assert!(
566 matches!(err, SchemaSourceError::NotFound { .. }),
567 "got {err:?}"
568 );
569 }
570
571 #[test]
572 fn unknown_schema_returns_not_found() {
573 let schema_ref = SchemaRef::new("nonexistent", semver::Version::new(1, 0, 0));
574 let err = collect_schema_source(None, None, &schema_ref).unwrap_err();
575 assert!(matches!(err, SchemaSourceError::NotFound { .. }));
576 }
577
578 #[test]
582 fn versioned_workspace_shape_wins_over_the_bare_one() {
583 let tmp = TempDir::new().unwrap();
584 let ws_dir = tmp.path().join("schemas");
585 let bare = ws_dir.join("software");
587 std::fs::create_dir_all(bare.join("types")).unwrap();
588 write_schema(&bare, "software", "1.0.0", &["spec", "memo"]);
589 let versioned = ws_dir.join("software@1.0.0");
591 std::fs::create_dir_all(versioned.join("types")).unwrap();
592 write_schema(&versioned, "software", "1.0.0", &["spec"]);
593
594 let schema_ref = SchemaRef::new("software", semver::Version::new(1, 0, 0));
595 let files = collect_schema_source(Some(tmp.path()), Some(&ws_dir), &schema_ref).unwrap();
596 let type_count = files
597 .iter()
598 .filter(|f| f.archive_path.starts_with("types/"))
599 .count();
600 assert_eq!(type_count, 1, "the versioned install shape must win");
601 }
602
603 #[test]
604 fn not_found_lists_every_candidate_path() {
605 let tmp = TempDir::new().unwrap();
606 let ws_dir = tmp.path().join("schemas");
607 std::fs::create_dir_all(&ws_dir).unwrap();
608
609 let schema_ref = SchemaRef::new("missing", semver::Version::new(2, 3, 4));
610 let err = collect_schema_source(Some(tmp.path()), Some(&ws_dir), &schema_ref).unwrap_err();
611 match err {
612 SchemaSourceError::NotFound {
613 schema_ref: name,
614 candidates,
615 } => {
616 assert_eq!(name, "missing@2.3.4");
617 assert_eq!(candidates.len(), 2, "got {candidates:?}");
621 assert!(candidates[0].ends_with("schemas/missing@2.3.4"));
622 assert!(candidates[1].ends_with("schemas/missing"));
623 }
624 other => panic!("expected NotFound, got {other:?}"),
625 }
626 }
627}