Skip to main content

folderbase_core/
validation.rs

1use std::{
2    collections::HashMap,
3    fs,
4    io::Read,
5    path::{Path, PathBuf},
6};
7
8use cap_fs_ext::{FollowSymlinks, OpenOptionsFollowExt};
9use cap_std::fs::{Dir, OpenOptions};
10use chrono::DateTime;
11use serde_json::Value;
12use sha2::{Digest, Sha256};
13use uuid::Uuid;
14use walkdir::WalkDir;
15
16use crate::{
17    FolderbaseError, Result, ValidationFinding, ValidationLevel, ValidationReport,
18    ValidationSeverity,
19    root_attestation::{
20        MAX_FOLDERBASE_MANIFEST_BYTES, ManifestProtocolProfile, attest_folderbase_root,
21        decode_manifest_protocol_profile, metadata_is_link_or_reparse,
22    },
23};
24
25const MANIFEST: &str = ".folderbase/manifest.json";
26
27/// Validate a folderbase without modifying or repairing it.
28pub fn validate(root: impl AsRef<Path>, level: ValidationLevel) -> Result<ValidationReport> {
29    let root = canonical_directory(root.as_ref())?;
30    let root_dir = open_root_directory_nofollow(&root)?;
31    let mut findings = Findings::default();
32
33    let manifest_path = Path::new(MANIFEST);
34    let manifest = match safe_discovery_file(&root, &root_dir, manifest_path)? {
35        DiscoveryFile::Missing => {
36            findings.error(
37                "missing_manifest",
38                Some(PathBuf::from(MANIFEST)),
39                "A folderbase root must contain .folderbase/manifest.json.",
40            );
41            None
42        }
43        DiscoveryFile::Symlink => {
44            findings.error(
45                "discovery_file_symlink",
46                Some(PathBuf::from(MANIFEST)),
47                "The manifest must be a regular file inside the folderbase root, not a symlink.",
48            );
49            None
50        }
51        DiscoveryFile::Regular => {
52            let encoded = read_cap_bytes_bounded(
53                &root,
54                &root_dir,
55                manifest_path,
56                MAX_FOLDERBASE_MANIFEST_BYTES,
57            )?;
58            match decode_manifest_protocol_profile(&encoded) {
59                Ok((manifest, _, _, profile)) => match attest_folderbase_root(&root) {
60                    Ok(attestation)
61                        if attestation.manifest_sha256
62                            == format!("{:x}", Sha256::digest(&encoded)) =>
63                    {
64                        Some((manifest, profile))
65                    }
66                    Ok(_) => {
67                        findings.error(
68                            "manifest_changed_during_validation",
69                            Some(PathBuf::from(MANIFEST)),
70                            "The manifest changed while validation was reading it.",
71                        );
72                        None
73                    }
74                    Err(source) => {
75                        findings.error(
76                            source.code(),
77                            Some(PathBuf::from(MANIFEST)),
78                            source.to_string(),
79                        );
80                        None
81                    }
82                },
83                Err(source) => {
84                    findings.error(
85                        source.code(),
86                        Some(PathBuf::from(MANIFEST)),
87                        source.to_string(),
88                    );
89                    None
90                }
91            }
92        }
93    };
94
95    if let Some((manifest, profile)) = manifest.as_ref() {
96        if profile.requires_legacy_root_files() {
97            validate_legacy_root_files(&root, &root_dir, &mut findings)?;
98        }
99        validate_manifest(&root, &root_dir, manifest, profile, &mut findings);
100    }
101
102    let known_objects = validate_objects(&root, &root_dir, level, &mut findings)?;
103    validate_relationships(&known_objects, &mut findings);
104    validate_record_states(
105        &root,
106        &root_dir,
107        ".folderbase/migrations",
108        "plan.json",
109        &[
110            "analyzing",
111            "questions",
112            "proposed",
113            "approved",
114            "applying",
115            "verified",
116            "rejected",
117            "rolled_back",
118        ],
119        "migration",
120        &mut findings,
121    )?;
122    validate_record_states(
123        &root,
124        &root_dir,
125        ".folderbase/changesets",
126        ".json",
127        &[
128            "proposed",
129            "approved",
130            "applying",
131            "applied",
132            "conflicted",
133            "rejected",
134        ],
135        "change_set",
136        &mut findings,
137    )?;
138
139    findings.sort();
140    let valid = !findings
141        .items
142        .iter()
143        .any(|finding| finding.severity == ValidationSeverity::Error);
144
145    Ok(ValidationReport {
146        root,
147        level,
148        valid,
149        findings: findings.items,
150    })
151}
152
153fn open_root_directory_nofollow(root: &Path) -> Result<Dir> {
154    let mut options = fs::OpenOptions::new();
155    options.read(true);
156    #[cfg(unix)]
157    {
158        use std::os::unix::fs::OpenOptionsExt;
159
160        options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
161    }
162    #[cfg(windows)]
163    {
164        use std::os::windows::fs::OpenOptionsExt;
165        use windows_sys::Win32::Storage::FileSystem::{
166            FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
167            FILE_SHARE_WRITE,
168        };
169
170        options
171            .access_mode(0)
172            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
173            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
174    }
175    let file = options
176        .open(root)
177        .map_err(|source| FolderbaseError::io(root, source))?;
178    let metadata = file
179        .metadata()
180        .map_err(|source| FolderbaseError::io(root, source))?;
181    if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
182        return Err(FolderbaseError::InvalidRoot(root.to_path_buf()));
183    }
184    Ok(Dir::from_std_file(file))
185}
186
187fn validate_legacy_root_files(root: &Path, root_dir: &Dir, findings: &mut Findings) -> Result<()> {
188    let entry_path = Path::new("FOLDERBASE.md");
189    match safe_discovery_file(root, root_dir, entry_path)? {
190        DiscoveryFile::Missing => findings.error(
191            "missing_folderbase_entry",
192            Some(entry_path.to_path_buf()),
193            "A legacy Folderbase root must contain FOLDERBASE.md.",
194        ),
195        DiscoveryFile::Symlink => findings.error(
196            "discovery_file_symlink",
197            Some(entry_path.to_path_buf()),
198            "Legacy FOLDERBASE.md must be a regular file inside the Folderbase root.",
199        ),
200        DiscoveryFile::Regular => match read_cap_string(root, root_dir, entry_path) {
201            Ok(contents) => validate_folderbase_entry(&contents, findings),
202            Err(source) => findings.error(
203                "folderbase_entry_not_utf8",
204                Some(entry_path.to_path_buf()),
205                format!("Legacy FOLDERBASE.md must be readable UTF-8 Markdown: {source}"),
206            ),
207        },
208    }
209    let ignore_path = Path::new(".folderbaseignore");
210    match safe_discovery_file(root, root_dir, ignore_path)? {
211        DiscoveryFile::Missing => findings.error(
212            "missing_ignore_file",
213            Some(ignore_path.to_path_buf()),
214            "A legacy Folderbase root must contain .folderbaseignore.",
215        ),
216        DiscoveryFile::Symlink => findings.error(
217            "discovery_file_symlink",
218            Some(ignore_path.to_path_buf()),
219            "Legacy .folderbaseignore must be a regular file inside the Folderbase root.",
220        ),
221        DiscoveryFile::Regular => {}
222    }
223    Ok(())
224}
225
226fn canonical_directory(path: &Path) -> Result<PathBuf> {
227    if !path.is_dir() {
228        return Err(FolderbaseError::InvalidRoot(path.to_path_buf()));
229    }
230    path.canonicalize()
231        .map_err(|source| FolderbaseError::io(path, source))
232}
233
234enum DiscoveryFile {
235    Missing,
236    Symlink,
237    Regular,
238}
239
240fn safe_discovery_file(root: &Path, root_dir: &Dir, path: &Path) -> Result<DiscoveryFile> {
241    match root_dir.symlink_metadata(path) {
242        Ok(metadata) if metadata.file_type().is_symlink() => Ok(DiscoveryFile::Symlink),
243        Ok(metadata) if metadata.is_file() => Ok(DiscoveryFile::Regular),
244        Ok(_) => Ok(DiscoveryFile::Missing),
245        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(DiscoveryFile::Missing),
246        Err(source) => Err(FolderbaseError::io(root.join(path), source)),
247    }
248}
249
250fn read_cap_string(root: &Path, root_dir: &Dir, path: &Path) -> Result<String> {
251    let mut file = root_dir
252        .open(path)
253        .map_err(|source| FolderbaseError::io(root.join(path), source))?;
254    let mut contents = String::new();
255    file.read_to_string(&mut contents)
256        .map_err(|source| FolderbaseError::io(root.join(path), source))?;
257    Ok(contents)
258}
259
260fn read_cap_bytes_bounded(
261    root: &Path,
262    root_dir: &Dir,
263    path: &Path,
264    maximum_bytes: u64,
265) -> Result<Vec<u8>> {
266    let display = root.join(path);
267    let mut options = OpenOptions::new();
268    options.read(true).follow(FollowSymlinks::No);
269    let mut file = root_dir
270        .open_with(path, &options)
271        .map_err(|source| FolderbaseError::io(&display, source))?;
272    let before = file
273        .metadata()
274        .map_err(|source| FolderbaseError::io(&display, source))?;
275    if !before.is_file() || before.len() > maximum_bytes {
276        return Err(FolderbaseError::InvalidRecord {
277            path: display,
278            message: "manifest is not a bounded regular file".to_owned(),
279        });
280    }
281    let mut contents = Vec::new();
282    file.by_ref()
283        .take(maximum_bytes + 1)
284        .read_to_end(&mut contents)
285        .map_err(|source| FolderbaseError::io(&display, source))?;
286    let after = file
287        .metadata()
288        .map_err(|source| FolderbaseError::io(&display, source))?;
289    if contents.len() as u64 > maximum_bytes || before.len() != after.len() {
290        return Err(FolderbaseError::InvalidRecord {
291            path: display,
292            message: "manifest exceeded its bound or changed while validation read it".to_owned(),
293        });
294    }
295    Ok(contents)
296}
297
298fn read_json_record(
299    root: &Path,
300    root_dir: &Dir,
301    path: &Path,
302    code: &str,
303    findings: &mut Findings,
304) -> Result<Option<Value>> {
305    let contents = read_cap_string(root, root_dir, path)?;
306    match serde_json::from_str(&contents) {
307        Ok(value) => Ok(Some(value)),
308        Err(source) => {
309            findings.error(
310                code,
311                Some(path.to_path_buf()),
312                format!("JSON could not be parsed: {source}"),
313            );
314            Ok(None)
315        }
316    }
317}
318
319fn validate_folderbase_entry(contents: &str, findings: &mut Findings) {
320    if !contents
321        .lines()
322        .find(|line| !line.trim().is_empty())
323        .is_some_and(|line| line.trim_start().starts_with("# "))
324    {
325        findings.error(
326            "missing_folderbase_title",
327            Some(PathBuf::from("FOLDERBASE.md")),
328            "FOLDERBASE.md must begin with a human-readable title.",
329        );
330    }
331
332    for heading in [
333        "## Purpose",
334        "## Current state",
335        "## Navigate",
336        "## Operating rules",
337        "## Unresolved work",
338    ] {
339        if !contents.lines().any(|line| line.trim() == heading) {
340            findings.error(
341                "missing_folderbase_entry_section",
342                Some(PathBuf::from("FOLDERBASE.md")),
343                format!("FOLDERBASE.md is missing the required {heading} section."),
344            );
345        }
346    }
347}
348
349fn validate_manifest(
350    root: &Path,
351    root_dir: &Dir,
352    manifest: &Value,
353    profile: &ManifestProtocolProfile,
354    findings: &mut Findings,
355) {
356    let Some(record) = manifest.as_object() else {
357        findings.error(
358            "manifest_not_object",
359            Some(PathBuf::from(MANIFEST)),
360            "The manifest root must be a JSON object.",
361        );
362        return;
363    };
364
365    match record
366        .get("protocol_version")
367        .and_then(Value::as_str)
368        .map(protocol_compatibility)
369    {
370        Some(ProtocolCompatibility::Supported) => {}
371        Some(ProtocolCompatibility::FutureMinor) => findings.warning(
372            "future_protocol_minor",
373            Some(PathBuf::from(MANIFEST)),
374            "This folderbase uses a newer 0.x protocol minor. Known 0.1 fields were validated and unknown fields were preserved.",
375        ),
376        Some(ProtocolCompatibility::Unsupported) => findings.error(
377            "unsupported_protocol_version",
378            Some(PathBuf::from(MANIFEST)),
379            "protocol_version must be a supported semantic 0.x version.",
380        ),
381        None => findings.error(
382            "missing_protocol_version",
383            Some(PathBuf::from(MANIFEST)),
384            "protocol_version is required.",
385        ),
386    }
387
388    let Some(folderbase) = record.get("folderbase").and_then(Value::as_object) else {
389        findings.error(
390            "missing_folderbase_record",
391            Some(PathBuf::from(MANIFEST)),
392            "folderbase must be a JSON object.",
393        );
394        return;
395    };
396
397    match folderbase.get("id").and_then(Value::as_str) {
398        Some(id)
399            if id
400                .strip_prefix("folderbase_")
401                .is_some_and(|uuid| Uuid::parse_str(uuid).is_ok()) => {}
402        _ => findings.error(
403            "invalid_folderbase_id",
404            Some(PathBuf::from(MANIFEST)),
405            "folderbase.id must be a non-empty identifier prefixed with folderbase_.",
406        ),
407    }
408    require_nonempty_string(folderbase, "name", "missing_folderbase_name", findings);
409    require_enum(
410        folderbase,
411        "kind",
412        &[
413            "person",
414            "organization",
415            "engagement",
416            "project",
417            "customer",
418            "temporary",
419            "custom",
420        ],
421        "invalid_folderbase_kind",
422        findings,
423    );
424    require_enum(
425        folderbase,
426        "status",
427        &["active", "paused", "archived"],
428        "invalid_folderbase_status",
429        findings,
430    );
431
432    match folderbase.get("created_at").and_then(Value::as_str) {
433        Some(created_at) if DateTime::parse_from_rfc3339(created_at).is_ok() => {}
434        _ => findings.error(
435            "invalid_created_at",
436            Some(PathBuf::from(MANIFEST)),
437            "folderbase.created_at must be an RFC 3339 timestamp.",
438        ),
439    }
440
441    if profile.requires_legacy_root_files() {
442        match folderbase.get("entry").and_then(Value::as_str) {
443            Some(entry) => {
444                if entry != "FOLDERBASE.md" {
445                    findings.error(
446                        "noncanonical_folderbase_entry",
447                        Some(PathBuf::from(MANIFEST)),
448                        "folderbase.entry must point to the canonical FOLDERBASE.md entry point.",
449                    );
450                }
451                validate_declared_path(
452                    root,
453                    root_dir,
454                    entry,
455                    true,
456                    true,
457                    "folderbase.entry",
458                    findings,
459                );
460            }
461            None => findings.error(
462                "missing_folderbase_entry_field",
463                Some(PathBuf::from(MANIFEST)),
464                "folderbase.entry is required.",
465            ),
466        }
467    }
468
469    if let Some(adapters) = record.get("adapters") {
470        let Some(adapters) = adapters.as_array() else {
471            findings.error(
472                "invalid_adapters",
473                Some(PathBuf::from(MANIFEST)),
474                "adapters must be an array when present.",
475            );
476            return;
477        };
478        for (index, adapter) in adapters.iter().enumerate() {
479            if adapter
480                .get("agent")
481                .and_then(Value::as_str)
482                .is_none_or(|agent| agent.trim().is_empty())
483            {
484                findings.error(
485                    "invalid_adapter_agent",
486                    Some(PathBuf::from(MANIFEST)),
487                    format!("adapters[{index}].agent must be a non-empty string."),
488                );
489            }
490            match adapter.get("path").and_then(Value::as_str) {
491                Some(path) => {
492                    validate_declared_path(
493                        root,
494                        root_dir,
495                        path,
496                        true,
497                        true,
498                        &format!("adapters[{index}].path"),
499                        findings,
500                    );
501                }
502                None => findings.error(
503                    "missing_adapter_path",
504                    Some(PathBuf::from(MANIFEST)),
505                    format!("adapters[{index}].path is required."),
506                ),
507            }
508        }
509    }
510
511    let Some(policies) = record.get("policies").and_then(Value::as_object) else {
512        findings.error(
513            "missing_policies",
514            Some(PathBuf::from(MANIFEST)),
515            "policies must be a JSON object.",
516        );
517        return;
518    };
519    require_enum_at(
520        policies,
521        "availability",
522        &["keep_local", "managed", "cloud_only"],
523        "invalid_availability_policy",
524        findings,
525    );
526    require_enum_at(
527        policies,
528        "structural_changes",
529        &["suggest", "approve", "autonomous"],
530        "invalid_structural_policy",
531        findings,
532    );
533    require_enum_at(
534        policies,
535        "archive",
536        &["manual", "approve", "automatic"],
537        "invalid_archive_policy",
538        findings,
539    );
540    require_enum_at(
541        policies,
542        "cloud_sync",
543        &["disabled", "enabled"],
544        "invalid_cloud_sync_policy",
545        findings,
546    );
547}
548
549#[derive(Default)]
550struct KnownObjects {
551    ids: HashMap<String, PathBuf>,
552    relationships: Vec<PendingRelationship>,
553}
554
555struct PendingRelationship {
556    record_path: PathBuf,
557    target: String,
558}
559
560fn validate_objects(
561    root: &Path,
562    root_dir: &Dir,
563    level: ValidationLevel,
564    findings: &mut Findings,
565) -> Result<KnownObjects> {
566    let relative_object_root = Path::new(".folderbase/objects");
567    match root_dir.symlink_metadata(relative_object_root) {
568        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
569            findings.error(
570                "protocol_directory_invalid",
571                Some(relative_object_root.to_path_buf()),
572                ".folderbase/objects must be a directory inside the folderbase root, not a symlink.",
573            );
574            return Ok(KnownObjects::default());
575        }
576        Ok(_) => {}
577        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
578            return Ok(KnownObjects::default());
579        }
580        Err(source) => return Err(FolderbaseError::io(root.join(relative_object_root), source)),
581    }
582    let object_root = root.join(relative_object_root);
583
584    let mut records = collect_files(&object_root, |path| {
585        path.extension().and_then(|extension| extension.to_str()) == Some("json")
586    })?;
587    records.sort();
588
589    let mut known = KnownObjects::default();
590    for record_path in records {
591        let Some(relative_record) = relative_to(root, &record_path) else {
592            findings.error(
593                "protocol_record_escapes_root",
594                None,
595                "An object metadata record was discovered outside the folderbase root.",
596            );
597            continue;
598        };
599        let Some(record) = read_json_record(
600            root,
601            root_dir,
602            &relative_record,
603            "object_json_invalid",
604            findings,
605        )?
606        else {
607            continue;
608        };
609        let Some(object) = record.as_object() else {
610            findings.error(
611                "object_not_object",
612                Some(relative_record),
613                "Object metadata must be a JSON object.",
614            );
615            continue;
616        };
617
618        let id = match object.get("id").and_then(Value::as_str) {
619            Some(id) if valid_prefixed_uuid(id, "obj_") => {
620                if let Some(first_path) = known.ids.insert(id.to_owned(), relative_record.clone()) {
621                    findings.error(
622                        "duplicate_object_id",
623                        Some(relative_record.clone()),
624                        format!(
625                            "Object ID {id} is already declared in {}.",
626                            first_path.display()
627                        ),
628                    );
629                }
630                Some(id.to_owned())
631            }
632            _ => {
633                findings.error(
634                    "invalid_object_id",
635                    Some(relative_record.clone()),
636                    "Object id must be a non-empty identifier prefixed with obj_.",
637                );
638                None
639            }
640        };
641
642        if !object
643            .get("type")
644            .and_then(Value::as_str)
645            .is_some_and(is_protocol_token)
646        {
647            findings.error(
648                "invalid_object_type",
649                Some(relative_record.clone()),
650                "Object type must be a non-empty lowercase protocol token.",
651            );
652        }
653
654        let lifecycle = object.get("lifecycle").and_then(Value::as_object);
655        let status = lifecycle
656            .and_then(|lifecycle| lifecycle.get("status"))
657            .and_then(Value::as_str);
658        if !matches!(
659            status,
660            Some("draft" | "canonical" | "superseded" | "archived" | "deleted")
661        ) {
662            findings.error(
663                "invalid_object_lifecycle",
664                Some(relative_record.clone()),
665                "lifecycle.status must be a supported object lifecycle.",
666            );
667        }
668        if let Some(superseded_by) = lifecycle
669            .and_then(|lifecycle| lifecycle.get("superseded_by"))
670            .and_then(Value::as_str)
671            && !valid_prefixed_uuid(superseded_by, "obj_")
672        {
673            findings.error(
674                "invalid_superseded_by",
675                Some(relative_record.clone()),
676                "lifecycle.superseded_by must be an object identifier.",
677            );
678        }
679        if status == Some("superseded")
680            && lifecycle
681                .and_then(|value| value.get("superseded_by"))
682                .is_none()
683        {
684            findings.error(
685                "missing_superseded_by",
686                Some(relative_record.clone()),
687                "A superseded object must identify its replacement.",
688            );
689        }
690        if status == Some("archived") {
691            for field in ["remote_size", "expected_restore_size"] {
692                if lifecycle
693                    .and_then(|value| value.get(field))
694                    .and_then(Value::as_u64)
695                    .is_none()
696                {
697                    findings.error(
698                        "missing_archive_size",
699                        Some(relative_record.clone()),
700                        format!("An archived object requires lifecycle.{field}."),
701                    );
702                }
703            }
704        }
705
706        let provenance = object.get("provenance").and_then(Value::as_object);
707        if provenance.is_none() {
708            findings.error(
709                "missing_object_provenance",
710                Some(relative_record.clone()),
711                "Object provenance must be a JSON object.",
712            );
713        } else {
714            let created_at = provenance
715                .and_then(|value| value.get("created_at"))
716                .and_then(Value::as_str);
717            if created_at.is_none_or(|value| DateTime::parse_from_rfc3339(value).is_err()) {
718                findings.error(
719                    "invalid_object_created_at",
720                    Some(relative_record.clone()),
721                    "provenance.created_at must be an RFC 3339 timestamp.",
722                );
723            }
724            if provenance
725                .and_then(|value| value.get("source"))
726                .and_then(Value::as_str)
727                .is_none_or(|source| source.trim().is_empty())
728            {
729                findings.error(
730                    "invalid_object_source",
731                    Some(relative_record.clone()),
732                    "provenance.source must be a non-empty string.",
733                );
734            }
735            if let Some(source_path) = provenance
736                .and_then(|value| value.get("source_path"))
737                .and_then(Value::as_str)
738            {
739                validate_declared_path(
740                    root,
741                    root_dir,
742                    source_path,
743                    false,
744                    false,
745                    "provenance.source_path",
746                    findings,
747                );
748            }
749        }
750
751        let object_path = object.get("path").and_then(Value::as_str);
752        if let Some(path) = object_path {
753            let materialized = validate_declared_path(
754                root,
755                root_dir,
756                path,
757                !matches!(status, Some("archived" | "deleted")),
758                false,
759                "object.path",
760                findings,
761            );
762            if materialized && level == ValidationLevel::ContentIntegrity {
763                validate_content_digest(root, root_dir, path, object, &relative_record, findings)?;
764            }
765        } else {
766            findings.error(
767                "missing_object_path",
768                Some(relative_record.clone()),
769                "Object path is required.",
770            );
771        }
772
773        if let Some(relationships) = object.get("relationships") {
774            if let Some(relationships) = relationships.as_array() {
775                for (index, relationship) in relationships.iter().enumerate() {
776                    if !relationship
777                        .get("type")
778                        .and_then(Value::as_str)
779                        .is_some_and(is_protocol_token)
780                    {
781                        findings.error(
782                            "invalid_relationship_type",
783                            Some(relative_record.clone()),
784                            format!(
785                                "relationships[{index}].type must be a lowercase protocol token."
786                            ),
787                        );
788                    }
789
790                    let target = relationship.get("target").and_then(Value::as_str);
791                    let external = relationship.get("external").and_then(Value::as_object);
792                    match (target, external) {
793                        (Some(target), None) if valid_prefixed_uuid(target, "obj_") => {
794                            known.relationships.push(PendingRelationship {
795                                record_path: relative_record.clone(),
796                                target: target.to_owned(),
797                            });
798                        }
799                        (Some(_), None) => findings.error(
800                            "invalid_relationship_target",
801                            Some(relative_record.clone()),
802                            format!(
803                                "relationships[{index}].target must be an object identifier."
804                            ),
805                        ),
806                        (None, Some(external))
807                            if external
808                                .get("kind")
809                                .and_then(Value::as_str)
810                                .is_some_and(|value| !value.trim().is_empty())
811                                && external
812                                    .get("id")
813                                    .and_then(Value::as_str)
814                                    .is_some_and(|value| !value.trim().is_empty()) =>
815                        {
816                            // External relationships are informational and
817                            // never grant local access or require resolution.
818                        }
819                        (None, Some(_)) => findings.error(
820                            "invalid_external_relationship",
821                            Some(relative_record.clone()),
822                            format!(
823                                "relationships[{index}].external requires non-empty kind and id."
824                            ),
825                        ),
826                        _ => findings.error(
827                            "ambiguous_relationship_target",
828                            Some(relative_record.clone()),
829                            format!(
830                                "relationships[{index}] must contain exactly one of target or external."
831                            ),
832                        ),
833                    }
834                }
835            } else {
836                findings.error(
837                    "invalid_relationships",
838                    Some(relative_record.clone()),
839                    "relationships must be an array.",
840                );
841            }
842        }
843
844        let _ = id;
845    }
846    Ok(known)
847}
848
849fn validate_relationships(known: &KnownObjects, findings: &mut Findings) {
850    for relationship in &known.relationships {
851        if !known.ids.contains_key(&relationship.target) {
852            findings.error(
853                "unresolved_relationship_target",
854                Some(relationship.record_path.clone()),
855                format!(
856                    "Relationship target {} does not name a local object or an explicit external target.",
857                    relationship.target
858                ),
859            );
860        }
861    }
862}
863
864fn valid_prefixed_uuid(value: &str, prefix: &str) -> bool {
865    value
866        .strip_prefix(prefix)
867        .is_some_and(|uuid| Uuid::parse_str(uuid).is_ok())
868}
869
870fn is_protocol_token(value: &str) -> bool {
871    let mut bytes = value.bytes();
872    bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
873        && bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
874}
875
876fn validate_content_digest(
877    root: &Path,
878    root_dir: &Dir,
879    relative_path: &str,
880    object: &serde_json::Map<String, Value>,
881    record_path: &Path,
882    findings: &mut Findings,
883) -> Result<()> {
884    let Some(content) = object.get("content").and_then(Value::as_object) else {
885        findings.error(
886            "missing_content_digest",
887            Some(record_path.to_path_buf()),
888            "Content-integrity validation requires content metadata with a sha256 digest.",
889        );
890        return Ok(());
891    };
892    let algorithm = content.get("algorithm").and_then(Value::as_str);
893    let digest = content.get("digest").and_then(Value::as_str);
894    match (algorithm, digest) {
895        (Some("sha256"), Some(expected)) => {
896            let actual = sha256_file(root, root_dir, Path::new(relative_path))?;
897            if !actual.eq_ignore_ascii_case(expected) {
898                findings.error(
899                    "content_digest_mismatch",
900                    Some(PathBuf::from(relative_path)),
901                    format!("Expected sha256 {expected}, found {actual}."),
902                );
903            }
904        }
905        (Some(other), _) => findings.error(
906            "unsupported_digest_algorithm",
907            Some(record_path.to_path_buf()),
908            format!("Digest algorithm {other:?} is not supported."),
909        ),
910        _ => findings.error(
911            "missing_content_digest",
912            Some(record_path.to_path_buf()),
913            "Content-integrity validation requires a sha256 digest.",
914        ),
915    }
916    Ok(())
917}
918
919fn sha256_file(root: &Path, root_dir: &Dir, path: &Path) -> Result<String> {
920    let mut file = root_dir
921        .open(path)
922        .map_err(|source| FolderbaseError::io(root.join(path), source))?;
923    let mut hasher = Sha256::new();
924    let mut buffer = [0_u8; 64 * 1024];
925    loop {
926        let read = file
927            .read(&mut buffer)
928            .map_err(|source| FolderbaseError::io(root.join(path), source))?;
929        if read == 0 {
930            break;
931        }
932        hasher.update(&buffer[..read]);
933    }
934    Ok(format!("{:x}", hasher.finalize()))
935}
936
937fn validate_record_states(
938    root: &Path,
939    root_dir: &Dir,
940    relative_root: &str,
941    filename_match: &str,
942    allowed: &[&str],
943    record_kind: &str,
944    findings: &mut Findings,
945) -> Result<()> {
946    let relative_root_path = Path::new(relative_root);
947    match root_dir.symlink_metadata(relative_root_path) {
948        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
949            findings.error(
950                "protocol_directory_invalid",
951                Some(relative_root_path.to_path_buf()),
952                format!(
953                    "{relative_root} must be a directory inside the folderbase root, not a symlink."
954                ),
955            );
956            return Ok(());
957        }
958        Ok(_) => {}
959        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
960        Err(source) => return Err(FolderbaseError::io(root.join(relative_root_path), source)),
961    }
962
963    let records_root = root.join(relative_root);
964    let mut records = collect_files(&records_root, |path| {
965        if filename_match.starts_with('.') {
966            path.extension().and_then(|extension| extension.to_str())
967                == Some(filename_match.trim_start_matches('.'))
968        } else {
969            path.file_name().and_then(|name| name.to_str()) == Some(filename_match)
970        }
971    })?;
972    records.sort();
973
974    for record_path in records {
975        let Some(relative_record) = relative_to(root, &record_path) else {
976            findings.error(
977                "protocol_record_escapes_root",
978                None,
979                format!("A {record_kind} record was discovered outside the folderbase root."),
980            );
981            continue;
982        };
983        let Some(record) = read_json_record(
984            root,
985            root_dir,
986            &relative_record,
987            "state_record_json_invalid",
988            findings,
989        )?
990        else {
991            continue;
992        };
993        let Some(record) = record.as_object() else {
994            findings.error(
995                "state_record_not_object",
996                Some(relative_record),
997                format!("{record_kind} metadata must be a JSON object."),
998            );
999            continue;
1000        };
1001        let required = if record_kind == "migration" {
1002            &[
1003                "protocol_version",
1004                "id",
1005                "state",
1006                "source_inventory",
1007                "base_folderbase_version",
1008                "questions",
1009                "proposed_folderbases",
1010                "operations",
1011                "exclusions",
1012                "storage_impact",
1013                "rollback",
1014            ][..]
1015        } else {
1016            &["id", "checkout_id", "base_version", "operations", "status"][..]
1017        };
1018        for field in required {
1019            if !record.contains_key(*field) {
1020                findings.error(
1021                    "missing_record_field",
1022                    Some(relative_record.clone()),
1023                    format!("{record_kind}.{field} is required."),
1024                );
1025            }
1026        }
1027        if record
1028            .get("operations")
1029            .is_some_and(|value| !value.is_array())
1030        {
1031            findings.error(
1032                "invalid_record_operations",
1033                Some(relative_record.clone()),
1034                format!("{record_kind}.operations must be an array."),
1035            );
1036        }
1037
1038        let state_field = if record_kind == "migration" {
1039            "state"
1040        } else {
1041            "status"
1042        };
1043        let status = record.get(state_field).and_then(Value::as_str);
1044        if !status.is_some_and(|status| allowed.contains(&status)) {
1045            findings.error(
1046                "invalid_record_state",
1047                Some(relative_record),
1048                format!(
1049                    "{record_kind}.{state_field} must be one of {}.",
1050                    allowed.join(", ")
1051                ),
1052            );
1053        }
1054    }
1055    Ok(())
1056}
1057
1058fn collect_files(root: &Path, include: impl Fn(&Path) -> bool) -> Result<Vec<PathBuf>> {
1059    let mut files = Vec::new();
1060    for entry in WalkDir::new(root).follow_links(false) {
1061        let entry = entry.map_err(|source| {
1062            let path = source
1063                .path()
1064                .map(Path::to_path_buf)
1065                .unwrap_or_else(|| root.to_path_buf());
1066            FolderbaseError::io(path, std::io::Error::other(source.to_string()))
1067        })?;
1068        if entry.file_type().is_file() && include(entry.path()) {
1069            files.push(entry.path().to_path_buf());
1070        }
1071    }
1072    Ok(files)
1073}
1074
1075fn validate_declared_path(
1076    root: &Path,
1077    root_dir: &Dir,
1078    declared: &str,
1079    require_materialized: bool,
1080    require_regular_file: bool,
1081    field: &str,
1082    findings: &mut Findings,
1083) -> bool {
1084    let relative = PathBuf::from(declared);
1085    if !is_safe_protocol_path(declared) {
1086        findings.error(
1087            "unsafe_protocol_path",
1088            Some(relative),
1089            format!(
1090                "{field} must be a portable relative path that cannot escape the folderbase root."
1091            ),
1092        );
1093        return false;
1094    }
1095
1096    match root_dir.symlink_metadata(&relative) {
1097        Ok(metadata) if metadata.file_type().is_symlink() => {
1098            findings.error(
1099                "declared_path_symlink",
1100                Some(relative.clone()),
1101                format!("{field} must not resolve through a symlink."),
1102            );
1103            false
1104        }
1105        Ok(metadata) if require_regular_file && !metadata.is_file() => {
1106            findings.error(
1107                "declared_path_not_file",
1108                Some(relative.clone()),
1109                format!("{field} must resolve to a regular file."),
1110            );
1111            false
1112        }
1113        Ok(_) => true,
1114        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
1115            if require_materialized {
1116                findings.error(
1117                    "declared_path_missing",
1118                    Some(relative),
1119                    format!("{field} does not resolve to materialized content."),
1120                );
1121            }
1122            false
1123        }
1124        Err(source) => {
1125            findings.error(
1126                "declared_path_unreadable",
1127                Some(relative),
1128                format!(
1129                    "{field} could not be resolved within {}: {source}",
1130                    root.display()
1131                ),
1132            );
1133            false
1134        }
1135    }
1136}
1137
1138fn is_safe_protocol_path(path: &str) -> bool {
1139    if path.is_empty()
1140        || path.starts_with('/')
1141        || path.starts_with('\\')
1142        || path.contains('\\')
1143        || path.contains('\0')
1144    {
1145        return false;
1146    }
1147    let mut segments = path.split('/');
1148    let Some(first) = segments.next() else {
1149        return false;
1150    };
1151    if first.ends_with(':') || first.is_empty() || matches!(first, "." | "..") {
1152        return false;
1153    }
1154    segments.all(|segment| !segment.is_empty() && !matches!(segment, "." | ".."))
1155}
1156
1157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1158enum ProtocolCompatibility {
1159    Supported,
1160    FutureMinor,
1161    Unsupported,
1162}
1163
1164fn protocol_compatibility(version: &str) -> ProtocolCompatibility {
1165    let mut version_parts = version.splitn(2, ['-', '+']);
1166    let numeric = version_parts.next().unwrap_or_default();
1167    if version_parts.next().is_some_and(|suffix| {
1168        suffix.is_empty()
1169            || !suffix
1170                .bytes()
1171                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-'))
1172    }) {
1173        return ProtocolCompatibility::Unsupported;
1174    }
1175
1176    let mut parts = numeric.split('.');
1177    let (Some(major), Some(minor), Some(patch), None) =
1178        (parts.next(), parts.next(), parts.next(), parts.next())
1179    else {
1180        return ProtocolCompatibility::Unsupported;
1181    };
1182    if [major, minor, patch]
1183        .iter()
1184        .any(|part| part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()))
1185    {
1186        return ProtocolCompatibility::Unsupported;
1187    }
1188    let Ok(major) = major.parse::<u64>() else {
1189        return ProtocolCompatibility::Unsupported;
1190    };
1191    let Ok(minor) = minor.parse::<u64>() else {
1192        return ProtocolCompatibility::Unsupported;
1193    };
1194    match (major, minor) {
1195        (0, 1 | 5) => ProtocolCompatibility::Supported,
1196        (0, minor) if minor > 1 => ProtocolCompatibility::FutureMinor,
1197        _ => ProtocolCompatibility::Unsupported,
1198    }
1199}
1200
1201fn require_nonempty_string(
1202    record: &serde_json::Map<String, Value>,
1203    field: &str,
1204    code: &str,
1205    findings: &mut Findings,
1206) {
1207    if record
1208        .get(field)
1209        .and_then(Value::as_str)
1210        .is_none_or(|value| value.trim().is_empty())
1211    {
1212        findings.error(
1213            code,
1214            Some(PathBuf::from(MANIFEST)),
1215            format!("folderbase.{field} must be a non-empty string."),
1216        );
1217    }
1218}
1219
1220fn require_enum(
1221    record: &serde_json::Map<String, Value>,
1222    field: &str,
1223    allowed: &[&str],
1224    code: &str,
1225    findings: &mut Findings,
1226) {
1227    if !record
1228        .get(field)
1229        .and_then(Value::as_str)
1230        .is_some_and(|value| allowed.contains(&value))
1231    {
1232        findings.error(
1233            code,
1234            Some(PathBuf::from(MANIFEST)),
1235            format!("folderbase.{field} must be one of {}.", allowed.join(", ")),
1236        );
1237    }
1238}
1239
1240fn require_enum_at(
1241    record: &serde_json::Map<String, Value>,
1242    field: &str,
1243    allowed: &[&str],
1244    code: &str,
1245    findings: &mut Findings,
1246) {
1247    if !record
1248        .get(field)
1249        .and_then(Value::as_str)
1250        .is_some_and(|value| allowed.contains(&value))
1251    {
1252        findings.error(
1253            code,
1254            Some(PathBuf::from(MANIFEST)),
1255            format!("policies.{field} must be one of {}.", allowed.join(", ")),
1256        );
1257    }
1258}
1259
1260fn relative_to(root: &Path, path: &Path) -> Option<PathBuf> {
1261    path.strip_prefix(root).ok().map(Path::to_path_buf)
1262}
1263
1264#[derive(Default)]
1265struct Findings {
1266    items: Vec<ValidationFinding>,
1267}
1268
1269impl Findings {
1270    fn error(
1271        &mut self,
1272        code: impl Into<String>,
1273        path: Option<PathBuf>,
1274        message: impl Into<String>,
1275    ) {
1276        self.push(ValidationSeverity::Error, code, path, message);
1277    }
1278
1279    fn warning(
1280        &mut self,
1281        code: impl Into<String>,
1282        path: Option<PathBuf>,
1283        message: impl Into<String>,
1284    ) {
1285        self.push(ValidationSeverity::Warning, code, path, message);
1286    }
1287
1288    fn push(
1289        &mut self,
1290        severity: ValidationSeverity,
1291        code: impl Into<String>,
1292        path: Option<PathBuf>,
1293        message: impl Into<String>,
1294    ) {
1295        self.items.push(ValidationFinding {
1296            code: code.into(),
1297            severity,
1298            path,
1299            message: message.into(),
1300        });
1301    }
1302
1303    fn sort(&mut self) {
1304        self.items.sort_by(|left, right| {
1305            left.code
1306                .cmp(&right.code)
1307                .then_with(|| left.path.cmp(&right.path))
1308                .then_with(|| left.message.cmp(&right.message))
1309        });
1310    }
1311}
1312
1313#[cfg(test)]
1314mod tests {
1315    use super::*;
1316    use crate::{InitializationOptions, initialize, plan_initialization};
1317
1318    fn initialized_folderbase() -> tempfile::TempDir {
1319        let temp = tempfile::tempdir().unwrap();
1320        let plan = plan_initialization(temp.path(), InitializationOptions::default()).unwrap();
1321        initialize(&plan).unwrap();
1322        temp
1323    }
1324
1325    #[test]
1326    fn initialized_folderbase_is_shallow_valid() {
1327        let temp = initialized_folderbase();
1328        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1329        assert!(report.valid, "{:?}", report.findings);
1330        assert!(
1331            report.findings.is_empty(),
1332            "the exact native 0.5 profile is supported without compatibility warnings: {:?}",
1333            report.findings
1334        );
1335    }
1336
1337    #[test]
1338    fn v05_entry_extension_has_no_protocol_path_authority() {
1339        let temp = initialized_folderbase();
1340        let manifest_path = temp.path().join(MANIFEST);
1341        let mut manifest: Value =
1342            serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
1343        manifest["folderbase"]["entry"] = Value::String("../outside.md".to_owned());
1344        fs::write(
1345            &manifest_path,
1346            serde_json::to_string_pretty(&manifest).unwrap(),
1347        )
1348        .unwrap();
1349
1350        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1351        assert!(report.valid, "{:?}", report.findings);
1352    }
1353
1354    #[test]
1355    fn content_integrity_reports_a_digest_mismatch() {
1356        let temp = initialized_folderbase();
1357        fs::create_dir_all(temp.path().join(".folderbase/objects")).unwrap();
1358        fs::write(temp.path().join("note.md"), "changed bytes").unwrap();
1359        fs::write(
1360            temp.path().join(".folderbase/objects/obj_test.json"),
1361            serde_json::to_string_pretty(&serde_json::json!({
1362                "id": "obj_019f9b75-4f42-7f65-a012-2bfecdd8c473",
1363                "type": "file",
1364                "path": "note.md",
1365                "content": {
1366                    "algorithm": "sha256",
1367                    "digest": "000000"
1368                },
1369                "lifecycle": {
1370                    "status": "canonical"
1371                },
1372                "provenance": {
1373                    "created_at": "2026-07-25T00:00:00Z",
1374                    "source": "test"
1375                },
1376                "relationships": []
1377            }))
1378            .unwrap(),
1379        )
1380        .unwrap();
1381
1382        let report = validate(temp.path(), ValidationLevel::ContentIntegrity).unwrap();
1383        assert!(!report.valid);
1384        assert!(
1385            report
1386                .findings
1387                .iter()
1388                .any(|finding| finding.code == "content_digest_mismatch")
1389        );
1390    }
1391
1392    #[test]
1393    fn content_integrity_requires_a_digest() {
1394        let temp = initialized_folderbase();
1395        fs::create_dir_all(temp.path().join(".folderbase/objects")).unwrap();
1396        fs::write(temp.path().join("note.md"), "durable knowledge").unwrap();
1397        fs::write(
1398            temp.path().join(".folderbase/objects/obj_test.json"),
1399            serde_json::to_string_pretty(&serde_json::json!({
1400                "id": "obj_019f9b75-4f42-7f65-a012-2bfecdd8c474",
1401                "type": "file",
1402                "path": "note.md",
1403                "lifecycle": {
1404                    "status": "canonical"
1405                },
1406                "provenance": {
1407                    "created_at": "2026-07-25T00:00:00Z",
1408                    "source": "test"
1409                },
1410                "relationships": []
1411            }))
1412            .unwrap(),
1413        )
1414        .unwrap();
1415
1416        let report = validate(temp.path(), ValidationLevel::ContentIntegrity).unwrap();
1417        assert!(!report.valid);
1418        assert!(
1419            report
1420                .findings
1421                .iter()
1422                .any(|finding| finding.code == "missing_content_digest")
1423        );
1424    }
1425
1426    #[test]
1427    fn optional_v05_folderbase_md_has_no_required_sections() {
1428        let temp = initialized_folderbase();
1429        let entry_path = temp.path().join("FOLDERBASE.md");
1430        fs::write(entry_path, "# Any user narrative\n").unwrap();
1431
1432        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1433        assert!(report.valid, "{:?}", report.findings);
1434    }
1435
1436    #[cfg(unix)]
1437    #[test]
1438    fn declared_symlink_is_invalid() {
1439        use std::os::unix::fs::symlink;
1440
1441        let temp = initialized_folderbase();
1442        fs::create_dir_all(temp.path().join(".folderbase/objects")).unwrap();
1443        symlink("FOLDERBASE.md", temp.path().join("linked.md")).unwrap();
1444        fs::write(
1445            temp.path().join(".folderbase/objects/obj_test.json"),
1446            serde_json::to_string_pretty(&serde_json::json!({
1447                "id": "obj_019f9b75-4f42-7f65-a012-2bfecdd8c475",
1448                "type": "file",
1449                "path": "linked.md",
1450                "lifecycle": {
1451                    "status": "canonical"
1452                },
1453                "provenance": {
1454                    "created_at": "2026-07-25T00:00:00Z",
1455                    "source": "test"
1456                },
1457                "relationships": []
1458            }))
1459            .unwrap(),
1460        )
1461        .unwrap();
1462
1463        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1464        assert!(!report.valid);
1465        assert!(
1466            report
1467                .findings
1468                .iter()
1469                .any(|finding| finding.code == "declared_path_symlink")
1470        );
1471    }
1472
1473    #[test]
1474    fn external_relationship_does_not_require_a_local_target() {
1475        let temp = initialized_folderbase();
1476        fs::create_dir_all(temp.path().join(".folderbase/objects")).unwrap();
1477        fs::write(temp.path().join("note.md"), "durable knowledge").unwrap();
1478        fs::write(
1479            temp.path().join(".folderbase/objects/obj_test.json"),
1480            serde_json::to_string_pretty(&serde_json::json!({
1481                "id": "obj_019f9b75-4f42-7f65-a012-2bfecdd8c476",
1482                "type": "file",
1483                "path": "note.md",
1484                "lifecycle": {
1485                    "status": "canonical"
1486                },
1487                "provenance": {
1488                    "created_at": "2026-07-25T00:00:00Z",
1489                    "source": "test"
1490                },
1491                "relationships": [{
1492                    "type": "belongs_to",
1493                    "external": {
1494                        "kind": "folderbase",
1495                        "id": "folderbase_remote"
1496                    }
1497                }]
1498            }))
1499            .unwrap(),
1500        )
1501        .unwrap();
1502
1503        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1504        assert!(report.valid, "{:?}", report.findings);
1505    }
1506
1507    #[test]
1508    fn future_minor_protocol_is_valid_with_a_warning() {
1509        let temp = initialized_folderbase();
1510        let manifest_path = temp.path().join(MANIFEST);
1511        let mut manifest: Value =
1512            serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
1513        manifest["protocol_version"] = Value::String("0.2.0".to_owned());
1514        manifest["folderbase"]["entry"] = Value::String("FOLDERBASE.md".to_owned());
1515        fs::write(
1516            temp.path().join("FOLDERBASE.md"),
1517            "# Legacy Folderbase\n\n## Purpose\nTest compatibility.\n\n## Current state\nReady.\n\n## Navigate\nUse ordinary files.\n\n## Operating rules\nPreserve bytes.\n\n## Unresolved work\nNone.\n",
1518        )
1519        .unwrap();
1520        fs::write(temp.path().join(".folderbaseignore"), "").unwrap();
1521        fs::write(
1522            &manifest_path,
1523            serde_json::to_string_pretty(&manifest).unwrap(),
1524        )
1525        .unwrap();
1526
1527        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1528        assert!(report.valid, "{:?}", report.findings);
1529        assert!(
1530            report
1531                .findings
1532                .iter()
1533                .any(|finding| finding.code == "future_protocol_minor")
1534        );
1535    }
1536
1537    #[test]
1538    fn migration_uses_state_and_requires_protocol_fields() {
1539        let temp = initialized_folderbase();
1540        let migration_root = temp.path().join(".folderbase/migrations/migration_test");
1541        fs::create_dir_all(&migration_root).unwrap();
1542        fs::write(
1543            migration_root.join("plan.json"),
1544            serde_json::to_string_pretty(&serde_json::json!({
1545                "state": "approved",
1546                "operations": []
1547            }))
1548            .unwrap(),
1549        )
1550        .unwrap();
1551
1552        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1553        assert!(!report.valid);
1554        assert!(
1555            report
1556                .findings
1557                .iter()
1558                .any(|finding| finding.code == "missing_record_field")
1559        );
1560        assert!(!report.findings.iter().any(|finding| {
1561            finding.code == "invalid_record_state" && finding.message.starts_with("migration.state")
1562        }));
1563    }
1564
1565    #[test]
1566    fn validation_does_not_rewrite_unknown_manifest_fields() {
1567        let temp = initialized_folderbase();
1568        let manifest_path = temp.path().join(MANIFEST);
1569        let mut manifest: Value =
1570            serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
1571        manifest["future_extension"] = serde_json::json!({ "kept": true });
1572        let original = serde_json::to_string_pretty(&manifest).unwrap();
1573        fs::write(&manifest_path, &original).unwrap();
1574
1575        let report = validate(temp.path(), ValidationLevel::Shallow).unwrap();
1576        assert!(report.valid, "{:?}", report.findings);
1577        assert_eq!(fs::read_to_string(&manifest_path).unwrap(), original);
1578    }
1579}