Skip to main content

str_format/
validate.rs

1//! 规范第 6 章全部错误码的实现。
2//!
3//! 覆盖四类规则:结构 / 身份、清单一致性、跨枝引用、JSON Schema。
4
5use std::collections::{HashMap, HashSet};
6use std::path::{Path, PathBuf};
7
8use serde_json::Value as JValue;
9
10use crate::bundle::{Bundle, Scan, Visit};
11use crate::error::{Issue, Report, Result, Stats, code};
12use crate::meta::{Entry, Kind, ManifestPolicy, Meta, Policies, ShaPolicy};
13use crate::util::{self, SCHEMA_DIR};
14
15/// 校验入口。
16pub fn validate(bundle: &Bundle) -> Result<Report> {
17    let scan = bundle.scan()?;
18    let mut checker = Checker::new(bundle, &scan);
19    checker.run();
20    checker.check_revision_history();
21    Ok(checker.report)
22}
23
24/// 校验器内部状态。
25struct Checker<'a> {
26    bundle: &'a Bundle,
27    scan: &'a Scan,
28    report: Report,
29    policies: Policies,
30}
31
32impl<'a> Checker<'a> {
33    fn new(bundle: &'a Bundle, scan: &'a Scan) -> Self {
34        let policies = scan
35            .root_index
36            .and_then(|i| scan.visits[i].meta.as_ref())
37            .map(|m| m.policies.clone())
38            .unwrap_or_default();
39        let mut report = Report {
40            bundle: bundle.name(),
41            issues: Vec::new(),
42            stats: Stats::default(),
43        };
44        report.issues.extend(scan.issues.iter().cloned());
45        Self {
46            bundle,
47            scan,
48            report,
49            policies,
50        }
51    }
52
53    // ── 基础输出 ────────────────────────────────────────────
54
55    fn strict(&self) -> bool {
56        self.policies.manifest == ManifestPolicy::Strict
57    }
58
59    fn warn(&mut self, code: &'static str, path: impl Into<String>, msg: impl Into<String>) {
60        self.report.push(Issue::warn(code, path, msg));
61    }
62
63    fn err(&mut self, code: &'static str, path: impl Into<String>, msg: impl Into<String>) {
64        self.report.push(Issue::error(code, path, msg));
65    }
66
67    /// 清单类问题:`manifest = advisory` 时降级为告警(规范 4.8)。
68    fn manifest_issue(
69        &mut self,
70        e_code: &'static str,
71        w_code: &'static str,
72        path: impl Into<String>,
73        msg: impl Into<String>,
74    ) {
75        let path = path.into();
76        let msg = msg.into();
77        if self.strict() {
78            self.err(e_code, path, msg);
79        } else {
80            self.warn(w_code, path, msg);
81        }
82    }
83
84    // ── 主流程 ─────────────────────────────────────────────
85
86    fn run(&mut self) {
87        let scan = self.scan;
88        let name = self.bundle.name();
89        if !name.ends_with(".str") {
90            self.warn(
91                code::BUNDLE_SUFFIX,
92                ".",
93                format!("根目录名 {name:?} 未以 `.str` 结尾"),
94            );
95        }
96
97        let Some(root_idx) = scan.root_index else {
98            return;
99        };
100        self.report.stats.depth = scan.max_depth;
101
102        for v in &scan.visits {
103            match v.depth {
104                0 => {}
105                1 => self.report.stats.nodes += 1,
106                _ => self.report.stats.branches += 1,
107            }
108            if let Some(m) = &v.meta {
109                self.report.stats.entries += m.entries.len();
110            }
111        }
112
113        // 重复 id
114        let dups: Vec<(String, String, usize)> = scan
115            .by_id
116            .iter()
117            .filter(|(_, idxs)| idxs.len() > 1)
118            .map(|(id, idxs)| {
119                (
120                    id.clone(),
121                    scan.visits[idxs[0]].rel.clone(),
122                    idxs.len(),
123                )
124            })
125            .collect();
126        for (id, path, n) in dups {
127            self.err(code::ID_DUP, path, format!("id `{id}` 在 {n} 处重复出现"));
128        }
129
130        // ROOT 自身要求
131        if let Some(m) = scan.visits[root_idx].meta.as_ref() {
132            if m.kind != Some(Kind::Root) {
133                self.err(
134                    code::KIND_DEPTH,
135                    ".",
136                    format!("深度 0 的 `kind` 必须是 `root`,实为 {:?}", m.kind_raw),
137                );
138            }
139            if m.name.is_none() {
140                self.err(code::SCHEMA_FIELD, ".", "root 缺少必填字段 `name`");
141            }
142        }
143
144        for i in 0..scan.visits.len() {
145            self.check_branch(i);
146        }
147
148        self.check_ref_cycles();
149        self.check_meta_schemas();
150    }
151
152    /// 单个分支目录的结构 / 身份 / 引用规则。
153    fn check_branch(&mut self, idx: usize) {
154        let scan = self.scan;
155        let v: &Visit = &scan.visits[idx];
156        let rel = v.rel.clone();
157        let depth = v.depth;
158        let Some(meta) = v.meta.as_ref() else {
159            return; // 解析失败已在扫描期报出
160        };
161
162        // 档位 vs 深度
163        let expected_kind = match depth {
164            0 => Kind::Root,
165            1 => Kind::Node,
166            _ => Kind::Branch,
167        };
168        if let Some(k) = meta.kind {
169            if k != expected_kind {
170                self.err(
171                    code::KIND_DEPTH,
172                    rel.clone(),
173                    format!(
174                        "深度 {depth} 的 `kind` 必须是 `{}`,实为 `{}`",
175                        expected_kind.as_str(),
176                        k.as_str()
177                    ),
178                );
179            }
180        }
181
182        if let Some(ver) = meta.str_version {
183            if ver != crate::STR_MAJOR {
184                self.err(
185                    code::SPEC_UNSUPPORTED,
186                    rel.clone(),
187                    format!("`str` = {ver},本实现只支持主版本 {}", crate::STR_MAJOR),
188                );
189            }
190        }
191
192        // 目录名 vs id
193        let dir_name = v
194            .dir
195            .file_name()
196            .map(|s| s.to_string_lossy().to_string())
197            .unwrap_or_default();
198        if depth >= 1 {
199            if !util::is_uuid(&dir_name) {
200                self.err(
201                    code::ID_NOT_UUID,
202                    rel.clone(),
203                    format!("分支目录名 {dir_name:?} 不是合法 UUID"),
204                );
205            } else if let Some(ver) = util::uuid_version(&dir_name) {
206                if ver != self.policies.id_version {
207                    self.err(
208                        code::ID_VERSION,
209                        rel.clone(),
210                        format!(
211                            "目录名 UUID 版本为 {ver},`policies.id_version` 要求 {}",
212                            self.policies.id_version
213                        ),
214                    );
215                }
216            }
217            if let Some(id) = meta.id.as_deref() {
218                if id != dir_name {
219                    self.err(
220                        code::ID_MISMATCH,
221                        rel.clone(),
222                        format!("`id` = {id:?} 与目录名 {dir_name:?} 不一致"),
223                    );
224                }
225            }
226        }
227
228        // 深度
229        if depth > self.policies.max_depth {
230            self.err(
231                code::DEPTH_EXCEEDED,
232                rel.clone(),
233                format!(
234                    "深度 {depth} 超过 `policies.max_depth` = {}",
235                    self.policies.max_depth
236                ),
237            );
238        } else if depth > self.policies.deep_tree_warn {
239            self.warn(
240                code::DEEP_TREE,
241                rel.clone(),
242                format!(
243                    "深度 {depth} 超过 `policies.deep_tree_warn` = {},建议拆分",
244                    self.policies.deep_tree_warn
245                ),
246            );
247        }
248
249        if depth >= 1 && meta.summary.is_none() {
250            self.warn(
251                code::NO_SUMMARY,
252                rel.clone(),
253                "建议补充 `summary`(AI 检索依据)",
254            );
255        }
256        if depth >= 1 && meta.r#type.is_none() {
257            self.warn(code::NO_TYPE, rel.clone(), "建议补充 `type`");
258        }
259
260        for issue in meta.revision_issues(&rel) {
261            self.report.push(issue);
262        }
263
264        // 跨枝引用
265        let own_id = meta.id.clone();
266        let refs = meta.refs.clone();
267        let mut bad_targets: Vec<(usize, String, String)> = Vec::new();
268        for (n, r) in refs.iter().enumerate() {
269            if Some(r.target.as_str()) == own_id.as_deref() {
270                self.err(
271                    code::REF_SELF,
272                    format!("{rel} #refs[{n}]"),
273                    "关联线指向自身",
274                );
275                continue;
276            }
277            if !r.target.is_empty() && scan.resolve(&r.target).is_none() {
278                bad_targets.push((n, r.target.clone(), rel.clone()));
279            }
280        }
281        for (n, target, rel) in bad_targets {
282            self.err(
283                code::REF_NO_TARGET,
284                format!("{rel} #refs[{n}]"),
285                format!("`target` = {target:?} 无法在本 bundle 内解析到任何分支"),
286            );
287        }
288
289        // 清单
290        self.check_manifest(idx);
291    }
292
293    /// 清单一致性(规范 4.8)与角色 / 深度一致性。
294    fn check_manifest(&mut self, idx: usize) {
295        let scan = self.scan;
296        let bundle = self.bundle;
297        let v: &Visit = &scan.visits[idx];
298        let rel = v.rel.clone();
299        let dir = v.dir.clone();
300        let meta: &Meta = match v.meta.as_ref() {
301            Some(m) => m,
302            None => return,
303        };
304        let entries: Vec<Entry> = meta.entries.clone();
305
306        // path 重复
307        let mut seen: HashSet<String> = HashSet::new();
308        let mut dups: Vec<String> = Vec::new();
309        for e in &entries {
310            if !seen.insert(e.path.clone()) {
311                dups.push(e.path.clone());
312            }
313        }
314        for p in dups {
315            self.err(
316                code::MANIFEST_DUP,
317                format!("{rel} #entries"),
318                format!("`entries[].path` = {p:?} 重复"),
319            );
320        }
321
322        let actual = bundle.list_names(&dir).unwrap_or_default();
323
324        // 实际侧 → 逐条比对
325        for (name, is_dir) in &actual {
326            let ep = format!("{rel}/{name}");
327            if util::is_meta_file(name) || util::is_lock_file(name) {
328                continue; // `._meta` / `.lock` 不参与清单
329            }
330            if util::is_reserved_name(name) {
331                // 保留命名空间判定(规范 v1.12.0 §1.3 约束 5 / §4.8:保留目录免登记、不参与清单比对):
332                // - `._schema` / `._cache` 是已知保留目录 → **免登记**、放行(显式登记亦合法,属可选声明);
333                // - 业务**目录**以 `._` 开头 → 必然不是 AppleDouble(该机制只产生文件)→ `E_RESERVED_NAME`;
334                // - 其余以 `._` 开头且**已登记**或为**目录**者 → 作者显式声明为业务内容 → `E_RESERVED_NAME`;
335                // - 其余 `._*` **普通文件** → 视为 macOS AppleDouble 噪声,豁免(规范 3.4)。
336                let known = name == crate::util::SCHEMA_DIR || name == crate::util::CACHE_DIR;
337                let declared_here = entries.iter().any(|e| e.path == *name);
338                if !known && (*is_dir || declared_here) {
339                    self.err(
340                        code::RESERVED_NAME,
341                        ep.clone(),
342                        "业务条目不得以 `._` 开头(`._` 为格式保留命名空间)",
343                    );
344                }
345                continue;
346            }
347            // 忽略名单命中(规范 4.7 `policies.ignore` + `.gitignore`):
348            // 不报 `E_MANIFEST_MISSING` / `W_DOTFILE` 等问题,视同不存在。
349            let rel_name = if rel == "." {
350                name.clone()
351            } else {
352                format!("{rel}/{name}")
353            };
354            if !scan.ignore.is_empty() && scan.ignore.is_ignored(&rel_name, *is_dir) {
355                continue;
356            }
357            if util::is_os_noise(name) {
358                continue; // `.DS_Store` / `Thumbs.db` / `desktop.ini`
359            }
360            if util::is_other_dotfile(name) {
361                self.warn(
362                    code::DOTFILE,
363                    ep.clone(),
364                    "出现非 `._meta` / `.lock` 的点文件(不计入清单要求)",
365                );
366                continue;
367            }
368            // ROOT 允许承载任意内容(规范 3.3:任意目录可放任意文件),
369            // 但「既非 UUID 命名的分支目录、又未登记进 entries」的条目属散落内容 → 告警。
370            let declared_here = entries.iter().any(|e| e.path == *name);
371            if v.depth == 0 && !util::is_uuid(name) && !declared_here {
372                self.warn(
373                    code::ROOT_STRAY,
374                    ep.clone(),
375                    "ROOT 下出现既非分支目录(UUID 命名)又未登记的条目",
376                );
377            }
378            match entries.iter().find(|e| e.path == *name) {
379                None => {
380                    let what = if *is_dir { "目录" } else { "文件" };
381                    self.manifest_issue(
382                        code::MANIFEST_MISSING,
383                        code::MANIFEST_MISSING_W,
384                        ep.clone(),
385                        format!("磁盘存在{what}但 `entries` 未登记"),
386                    );
387                }
388                Some(e) => {
389                    let e = e.clone();
390                    self.check_entry(&dir, v.depth, meta, &e, &ep, *is_dir);
391                }
392            }
393        }
394
395        // 声明侧 → 幽灵条目
396        let mut ghosts: Vec<(String, bool)> = Vec::new();
397        for e in &entries {
398            let path: PathBuf = dir.join(&e.path);
399            if path.exists() {
400                continue;
401            }
402            if e.optional {
403                self.warn(
404                    code::OPTIONAL_MISSING,
405                    format!("{rel}/{}", e.path),
406                    "`optional = true` 的条目当前缺失(允许)",
407                );
408            } else {
409                ghosts.push((format!("{rel}/{}", e.path), false));
410            }
411        }
412        for (ep, _) in ghosts {
413            self.manifest_issue(
414                code::MANIFEST_GHOST,
415                code::MANIFEST_GHOST_W,
416                ep,
417                "`entries` 已登记但磁盘不存在",
418            );
419        }
420    }
421
422    /// 单条已登记条目 vs 磁盘实际。
423    fn check_entry(
424        &mut self,
425        dir: &Path,
426        parent_depth: usize,
427        meta: &Meta,
428        e: &Entry,
429        ep: &str,
430        is_dir: bool,
431    ) {
432        let bundle = self.bundle;
433        let path: PathBuf = dir.join(&e.path);
434
435        match e.role.as_str() {
436            "node" | "branch" | "dir" => {
437                if !is_dir {
438                    self.err(
439                        code::ENTRY_ROLE_DEPTH,
440                        ep,
441                        format!("`role = {:?}` 要求目录,但磁盘上是文件", e.role),
442                    );
443                    return;
444                }
445                let dir_name = path
446                    .file_name()
447                    .map(|s| s.to_string_lossy().to_string())
448                    .unwrap_or_default();
449                let child_has_meta = bundle.has_meta(&path);
450                if e.role == "dir" {
451                    if util::is_sub_bundle(&dir_name) {
452                        self.err(
453                            code::ENTRY_ROLE_DEPTH,
454                            ep,
455                            "该目录名以 `.str` 结尾(独立子 bundle),应登记为 `role = \"bundle\"`",
456                        );
457                        return;
458                    }
459                    if child_has_meta {
460                        self.err(
461                            code::ENTRY_ROLE_DEPTH,
462                            ep,
463                            "该子目录含 `._meta`(已是分支),却被登记为 `role = \"dir\"`",
464                        );
465                    }
466                    return;
467                }
468                if !child_has_meta {
469                    self.err(code::META_MISSING, ep, "登记为分支但目录内缺少 `._meta`");
470                    return;
471                }
472                let want_node = e.role == "node";
473                if parent_depth == 0 && !want_node {
474                    self.err(
475                        code::ENTRY_ROLE_DEPTH,
476                        ep,
477                        "ROOT 的直接子分支必须是 `role = \"node\"`",
478                    );
479                } else if parent_depth >= 1 && want_node {
480                    self.err(
481                        code::ENTRY_ROLE_DEPTH,
482                        ep,
483                        "深度 ≥1 的子分支必须是 `role = \"branch\"`",
484                    );
485                }
486                if let Some(id) = &e.id {
487                    let dir_name = path
488                        .file_name()
489                        .map(|s| s.to_string_lossy().to_string())
490                        .unwrap_or_default();
491                    if *id != dir_name {
492                        self.err(
493                            code::ENTRY_ID_MISMATCH,
494                            ep,
495                            format!("`entries[].id` = {id:?} 与子目录名 {dir_name:?} 不一致"),
496                        );
497                    }
498                }
499                // 子分支自身的 `kind` 是否与父级 `role` 相符
500                let child_kind = match bundle.read_meta(&path) {
501                    Ok(crate::meta::MetaLoad::Ok(child, _)) => child.kind,
502                    _ => None,
503                };
504                if let Some(k) = child_kind {
505                    let expect = if want_node { Kind::Node } else { Kind::Branch };
506                    if k != expect {
507                        self.err(
508                            code::ENTRY_ROLE_DEPTH,
509                            ep,
510                            format!(
511                                "父级登记 `role = {:?}`,但子分支 `kind` = `{}`",
512                                e.role,
513                                k.as_str()
514                            ),
515                        );
516                    }
517                }
518            }
519            "payload" | "asset" => {
520                if is_dir {
521                    self.err(
522                        code::ENTRY_ROLE_DEPTH,
523                        ep,
524                        format!("`role = {:?}` 要求文件,但磁盘上是目录", e.role),
525                    );
526                    return;
527                }
528                self.check_file_digest(e, ep, &path);
529                if e.role == "payload" {
530                    self.check_payload_schema(meta, e, ep, &path);
531                }
532            }
533            "schema" | "cache" => {
534                if !is_dir {
535                    self.err(
536                        code::ENTRY_ROLE_DEPTH,
537                        ep,
538                        format!("`role = {:?}` 要求目录", e.role),
539                    );
540                }
541            }
542            "bundle" => {
543                // 独立子 bundle:目录名须以 `.str` 结尾;父 bundle 不进入其内部
544                let dir_name = path
545                    .file_name()
546                    .map(|s| s.to_string_lossy().to_string())
547                    .unwrap_or_default();
548                if !is_dir {
549                    self.err(
550                        code::ENTRY_ROLE_DEPTH,
551                        ep,
552                        "`role = \"bundle\"` 要求目录",
553                    );
554                } else if !util::is_sub_bundle(&dir_name) {
555                    self.err(
556                        code::ENTRY_ROLE_DEPTH,
557                        ep,
558                        format!("`role = \"bundle\"` 要求目录名以 `.str` 结尾,实为 {dir_name:?}"),
559                    );
560                }
561            }
562            _ => {}
563        }
564    }
565
566    /// 文件类条目的 `size` / `sha256` 强制与一致性。
567    fn check_file_digest(&mut self, e: &Entry, ep: &str, path: &Path) {
568        if self.policies.sha256 == ShaPolicy::Required && (e.size.is_none() || e.sha256.is_none()) {
569            self.err(
570                code::MANIFEST_DIGEST_MISSING,
571                ep,
572                "`policies.sha256 = \"required\"`:文件类条目必须同时提供 `size` 与 `sha256`",
573            );
574        }
575        let Ok(md) = std::fs::metadata(path) else {
576            return;
577        };
578        let real_size = md.len();
579        if let Some(s) = e.size {
580            if s < 0 || s as u64 != real_size {
581                self.manifest_issue(
582                    code::MANIFEST_HASH,
583                    code::MANIFEST_HASH_W,
584                    ep,
585                    format!("`size` = {s} 与实际 {real_size} 不符"),
586                );
587            }
588        }
589        if self.policies.sha256 != ShaPolicy::Off {
590            if let Some(declared) = e.sha256.clone() {
591                match util::sha256_file(path) {
592                    Ok(real) if real == declared => {}
593                    Ok(real) => {
594                        let d = &declared[..declared.len().min(12)];
595                        let r = &real[..12];
596                        self.manifest_issue(
597                            code::MANIFEST_HASH,
598                            code::MANIFEST_HASH_W,
599                            ep,
600                            format!("`sha256` 不符:声明 {d}…,实际 {r}…"),
601                        );
602                    }
603                    Err(err) => {
604                        self.manifest_issue(
605                            code::MANIFEST_HASH,
606                            code::MANIFEST_HASH_W,
607                            ep,
608                            format!("无法计算摘要:{err}"),
609                        );
610                    }
611                }
612            }
613        }
614        if real_size > self.policies.large_asset_bytes {
615            self.warn(
616                code::LARGE_ASSET,
617                ep,
618                format!(
619                    "文件 {real_size} 字节,超过 `large_asset_bytes` = {}",
620                    self.policies.large_asset_bytes
621                ),
622            );
623        }
624    }
625
626    /// `E_REVISION_STALE` 的**历史**判定:`updated_at` 变了但 `revision` 没有前进(规范 §6.1)。
627    ///
628    /// 依据 `._cache/revisions.json`(由写入端登记,见 [`crate::baseline`])。无基线时跳过 ——
629    /// 单份 `._meta` 不含历史,无从判定;`str sync` 会把基线刷到当前状态。
630    fn check_revision_history(&mut self) {
631        let baseline = crate::baseline::load(self.bundle);
632        if baseline.branches.is_empty() {
633            return;
634        }
635        let mut found: Vec<(String, String, i64, i64, String)> = Vec::new();
636        for v in &self.scan.visits {
637            let Some(meta) = v.meta.as_ref() else {
638                continue;
639            };
640            let Some(snap) = baseline.branches.get(&v.rel) else {
641                continue;
642            };
643            let (Some(rev), Some(updated)) = (meta.revision, meta.updated_at.as_deref()) else {
644                continue;
645            };
646            let changed = match (
647                util::parse_rfc3339(&snap.updated_at),
648                util::parse_rfc3339(updated),
649            ) {
650                (Some(a), Some(b)) => a != b,
651                _ => snap.updated_at != updated,
652            };
653            if changed && rev <= snap.revision {
654                found.push((
655                    v.rel.clone(),
656                    snap.updated_at.clone(),
657                    snap.revision,
658                    rev,
659                    updated.to_string(),
660                ));
661            }
662        }
663        for (rel, was, old_rev, new_rev, now) in found {
664            self.err(
665                code::REVISION_STALE,
666                rel,
667                format!(
668                    "`updated_at` 已由 {was} 变为 {now},但 `revision` 未前进({old_rev} → {new_rev});\
669                     规范 §7.2 要求每次写入同时 +1 并刷新时间"
670                ),
671            );
672        }
673    }
674
675    /// `refs` 关联图成环检测(迭代式 DFS)。
676    fn check_ref_cycles(&mut self) {
677        let scan = self.scan;
678        let n = scan.visits.len();
679        let mut edges: Vec<Vec<usize>> = vec![Vec::new(); n];
680        for (i, v) in scan.visits.iter().enumerate() {
681            if let Some(m) = &v.meta {
682                for r in &m.refs {
683                    if let Some(j) = scan.resolve(&r.target) {
684                        edges[i].push(j);
685                    }
686                }
687            }
688        }
689
690        let mut color = vec![0u8; n]; // 0 未访问 / 1 在栈 / 2 已完成
691        let mut hits: Vec<String> = Vec::new();
692        for start in 0..n {
693            if color[start] != 0 {
694                continue;
695            }
696            let mut stack: Vec<(usize, usize)> = vec![(start, 0)];
697            color[start] = 1;
698            while !stack.is_empty() {
699                let top = stack.len() - 1;
700                let (node, k) = stack[top];
701                if k < edges[node].len() {
702                    let next = edges[node][k];
703                    stack[top].1 += 1;
704                    match color[next] {
705                        0 => {
706                            color[next] = 1;
707                            stack.push((next, 0));
708                        }
709                        1 => hits.push(scan.visits[next].rel.clone()),
710                        _ => {}
711                    }
712                } else {
713                    color[node] = 2;
714                    stack.pop();
715                }
716            }
717        }
718        hits.sort();
719        hits.dedup();
720        for path in hits {
721            self.err(
722                code::REF_CYCLE,
723                path,
724                "`refs` 关联图成环(追踪终点回到链上已有分支)",
725            );
726        }
727    }
728
729    /// 每个分支的 `._meta` 归一化后过 JSON Schema(规范 4.1 校验链路)。
730    fn check_meta_schemas(&mut self) {
731        let scan = self.scan;
732        let bundle = self.bundle;
733        let items: Vec<(String, JValue, &'static str)> = scan
734            .visits
735            .iter()
736            .filter_map(|v| {
737                let m = v.meta.as_ref()?;
738                let name: &'static str = match v.depth {
739                    0 => "root-meta.schema.json",
740                    1 => "node-meta.schema.json",
741                    _ => "branch-meta.schema.json",
742                };
743                Some((v.rel.clone(), m.to_json(), name))
744            })
745            .collect();
746
747        for (rel, instance, name) in items {
748            let schema = load_meta_schema(bundle, name);
749            let Ok(validator) = jsonschema::validator_for(&schema) else {
750                continue;
751            };
752            let msgs: Vec<String> = validator
753                .iter_errors(&instance)
754                .map(|e| format!("{e}(位于 {})", e.instance_path()))
755                .collect();
756            for m in msgs {
757                self.err(code::SCHEMA_FAIL, rel.clone(), m);
758            }
759        }
760    }
761
762    /// payload 的业务 Schema 校验(`entries[].schema` 或分支级 `schema`)。
763    fn check_payload_schema(&mut self, meta: &Meta, e: &Entry, ep: &str, path: &Path) {
764        let Some(schema_ref) = e.schema.clone().or_else(|| meta.schema.clone()) else {
765            return;
766        };
767        let schema_path = self.bundle.root.join(&schema_ref);
768        let Ok(schema_bytes) = std::fs::read(&schema_path) else {
769            return;
770        };
771        let Ok(schema) = serde_json::from_slice::<JValue>(&schema_bytes) else {
772            return;
773        };
774        let Ok(validator) = jsonschema::validator_for(&schema) else {
775            return;
776        };
777        let Ok(bytes) = std::fs::read(path) else {
778            return;
779        };
780        let Ok(instance) = serde_json::from_slice::<JValue>(&bytes) else {
781            return; // 非 JSON payload 不做 Schema 校验
782        };
783        let msgs: Vec<String> = validator
784            .iter_errors(&instance)
785            .map(|err| format!("{err}(位于 {})", err.instance_path()))
786            .collect();
787        for m in msgs {
788            self.err(
789                code::SCHEMA_FAIL,
790                ep,
791                format!("payload 不满足 `{schema_ref}`:{m}"),
792            );
793        }
794    }
795}
796
797/// 取某档位的 `._meta` Schema:优先 bundle 内 `._schema/`,否则用内嵌兜底。
798fn load_meta_schema(bundle: &Bundle, name: &str) -> JValue {
799    let local = bundle.root.join(SCHEMA_DIR).join(name);
800    if local.is_file() {
801        if let Ok(bytes) = std::fs::read(&local) {
802            if let Ok(v) = serde_json::from_slice::<JValue>(&bytes) {
803                return v;
804            }
805        }
806    }
807    crate::EMBEDDED_SCHEMAS
808        .iter()
809        .find(|(n, _)| *n == name)
810        .and_then(|(_, t)| serde_json::from_str(t).ok())
811        .unwrap_or_else(|| JValue::Object(Default::default()))
812}
813
814/// 统计某目录下的条目数(`str sync` 用)。
815pub fn count_dir_entries(dir: &Path) -> usize {
816    std::fs::read_dir(dir)
817        .map(|rd| rd.flatten().filter(|e| !util::is_meta_file(&e.file_name().to_string_lossy())).count())
818        .unwrap_or(0)
819}
820
821/// 计算目录直接子项数(含点文件,排除 `._meta`)。
822pub fn dir_child_count(dir: &Path) -> Option<i64> {
823    std::fs::read_dir(dir).ok().map(|rd| {
824        rd.flatten()
825            .filter(|e| !util::is_meta_file(&e.file_name().to_string_lossy()))
826            .count() as i64
827    })
828}
829
830/// 收集目录内除了 `._meta`、OS 噪声与忽略名单命中之外的名字(`str sync` 用)。
831///
832/// `rel` 为该目录的 bundle 相对路径(ROOT 为 `.`),用于忽略模式匹配。
833pub fn real_entries(dir: &Path, rel: &str, ignore: &crate::ignore::IgnoreSet) -> Vec<(String, bool)> {
834    let mut out = Vec::new();
835    let Ok(rd) = std::fs::read_dir(dir) else {
836        return out;
837    };
838    for ent in rd.flatten() {
839        let name = ent.file_name().to_string_lossy().to_string();
840        if util::is_meta_file(&name) || util::is_os_noise(&name) || util::is_lock_file(&name) {
841            continue;
842        }
843        let is_dir = ent.file_type().map(|t| t.is_dir()).unwrap_or(false);
844        if !ignore.is_empty() {
845            let rel_name = if rel == "." || rel.is_empty() {
846                name.clone()
847            } else {
848                format!("{rel}/{name}")
849            };
850            if ignore.is_ignored(&rel_name, is_dir) {
851                continue;
852            }
853        }
854        out.push((name, is_dir));
855    }
856    out.sort();
857    out
858}
859
860/// 供测试与工具使用:一次扫描的 `id` → 相对路径映射。
861pub fn id_index(scan: &Scan) -> HashMap<String, String> {
862    scan.by_id
863        .iter()
864        .filter_map(|(id, idxs)| idxs.first().map(|i| (id.clone(), scan.visits[*i].rel.clone())))
865        .collect()
866}