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_link_cycles();
150        self.check_meta_schemas();
151    }
152
153    /// 单个分支目录的结构 / 身份 / 引用规则。
154    fn check_branch(&mut self, idx: usize) {
155        let scan = self.scan;
156        let v: &Visit = &scan.visits[idx];
157        let rel = v.rel.clone();
158        let depth = v.depth;
159        let Some(meta) = v.meta.as_ref() else {
160            return; // 解析失败已在扫描期报出
161        };
162
163        // 档位 vs 深度
164        let expected_kind = match depth {
165            0 => Kind::Root,
166            1 => Kind::Node,
167            _ => Kind::Branch,
168        };
169        if let Some(k) = meta.kind {
170            if k != expected_kind {
171                self.err(
172                    code::KIND_DEPTH,
173                    rel.clone(),
174                    format!(
175                        "深度 {depth} 的 `kind` 必须是 `{}`,实为 `{}`",
176                        expected_kind.as_str(),
177                        k.as_str()
178                    ),
179                );
180            }
181        }
182
183        if let Some(ver) = meta.str_version {
184            if ver != crate::STR_MAJOR {
185                self.err(
186                    code::SPEC_UNSUPPORTED,
187                    rel.clone(),
188                    format!("`str` = {ver},本实现只支持主版本 {}", crate::STR_MAJOR),
189                );
190            }
191        }
192
193        // 目录名 vs id
194        let dir_name = v
195            .dir
196            .file_name()
197            .map(|s| s.to_string_lossy().to_string())
198            .unwrap_or_default();
199        if depth >= 1 {
200            if !util::is_uuid(&dir_name) {
201                self.err(
202                    code::ID_NOT_UUID,
203                    rel.clone(),
204                    format!("分支目录名 {dir_name:?} 不是合法 UUID"),
205                );
206            } else if let Some(ver) = util::uuid_version(&dir_name) {
207                if ver != self.policies.id_version {
208                    self.err(
209                        code::ID_VERSION,
210                        rel.clone(),
211                        format!(
212                            "目录名 UUID 版本为 {ver},`policies.id_version` 要求 {}",
213                            self.policies.id_version
214                        ),
215                    );
216                }
217            }
218            if let Some(id) = meta.id.as_deref() {
219                if id != dir_name {
220                    self.err(
221                        code::ID_MISMATCH,
222                        rel.clone(),
223                        format!("`id` = {id:?} 与目录名 {dir_name:?} 不一致"),
224                    );
225                }
226            }
227        }
228
229        // 深度
230        if depth > self.policies.max_depth {
231            self.err(
232                code::DEPTH_EXCEEDED,
233                rel.clone(),
234                format!(
235                    "深度 {depth} 超过 `policies.max_depth` = {}",
236                    self.policies.max_depth
237                ),
238            );
239        } else if depth > self.policies.deep_tree_warn {
240            self.warn(
241                code::DEEP_TREE,
242                rel.clone(),
243                format!(
244                    "深度 {depth} 超过 `policies.deep_tree_warn` = {},建议拆分",
245                    self.policies.deep_tree_warn
246                ),
247            );
248        }
249
250        if depth >= 1 && meta.summary.is_none() {
251            self.warn(
252                code::NO_SUMMARY,
253                rel.clone(),
254                "建议补充 `summary`(AI 检索依据)",
255            );
256        }
257        if depth >= 1 && meta.r#type.is_none() {
258            self.warn(code::NO_TYPE, rel.clone(), "建议补充 `type`");
259        }
260
261        for issue in meta.revision_issues(&rel) {
262            self.report.push(issue);
263        }
264
265        // 跨枝引用
266        let own_id = meta.id.clone();
267        let refs = meta.refs.clone();
268        let mut bad_targets: Vec<(usize, String, String)> = Vec::new();
269        for (n, r) in refs.iter().enumerate() {
270            if Some(r.target.as_str()) == own_id.as_deref() {
271                self.err(
272                    code::REF_SELF,
273                    format!("{rel} #refs[{n}]"),
274                    "关联线指向自身",
275                );
276                continue;
277            }
278            if !r.target.is_empty() && scan.resolve(&r.target).is_none() {
279                bad_targets.push((n, r.target.clone(), rel.clone()));
280            }
281        }
282        for (n, target, rel) in bad_targets {
283            self.err(
284                code::REF_NO_TARGET,
285                format!("{rel} #refs[{n}]"),
286                format!("`target` = {target:?} 无法在本 bundle 内解析到任何分支"),
287            );
288        }
289
290        // 软连接子分支(规范 §4.6.1)
291        self.check_links(idx);
292
293        // 硬链接分支(§4.6.1 `mode = "hard"`):内容所有权唯一在目标分支 ——
294        // 自有 `entries` 只允许子分支(结构),登记内容条目即 `E_LINK_OWN_CONTENT`。
295        // (磁盘上未登记的内容文件由清单比对按 ghost 拦,双重兜底。)
296        if v.hard_link_to.is_some() {
297            for (n, e) in meta.entries.iter().enumerate() {
298                if matches!(e.role.as_str(), "payload" | "asset" | "dir") {
299                    self.err(
300                        code::LINK_OWN_CONTENT,
301                        format!("{rel} #entries[{n}]"),
302                        format!(
303                            "硬链接分支不得登记内容条目(`role = {:?}`):内容所有权唯一在目标分支,仅允许子分支",
304                            e.role
305                        ),
306                    );
307                }
308            }
309        }
310
311        // 清单
312        self.check_manifest(idx);
313    }
314
315    /// 链接条目(`role = "link"`,软 / 硬)的单条自守(规范 §4.6.1)。
316    ///
317    /// 成环是全图判定(见 `check_link_cycles`,仅软连接的 target 引用参与),
318    /// 这里只问「这一条本身是否合法」:
319    /// - **软连接**:声明式(无 id、无目录、不参与清单比对),`path` = `target`;
320    /// - **硬链接**:有身份的真实分支 —— 必写 `id` 且 `path = id` = 自身目录名
321    ///   (参与清单比对),内容所有权唯一在目标分支(自有 entries 只允许子分支,
322    ///   由 `check_branch` 按 `E_LINK_OWN_CONTENT` 把关)。
323    fn check_links(&mut self, idx: usize) {
324        let scan = self.scan;
325        let v: &Visit = &scan.visits[idx];
326        let rel = v.rel.clone();
327        let Some(meta) = v.meta.as_ref() else {
328            return;
329        };
330        let mut seen: HashSet<&str> = HashSet::new();
331        for (n, e) in meta.entries.iter().enumerate() {
332            if !e.is_link() {
333                // `mode` 仅在链接行上有意义
334                if e.mode.is_some() {
335                    self.err(
336                        code::SCHEMA_FIELD,
337                        format!("{rel} #entries[{n}]"),
338                        "`mode` 仅适用于 `role = \"link\"` 的条目",
339                    );
340                }
341                continue;
342            }
343            let ep = format!("{rel} #entries[{n}]");
344
345            // 同父重复挂载(重复path 由 LINK_DUP 报,不再走通用的 MANIFEST_DUP)
346            if !seen.insert(e.path.as_str()) {
347                self.err(
348                    code::LINK_DUP,
349                    ep.clone(),
350                    format!("同一父分支内重复挂载目标 `{path}`", path = e.path),
351                );
352            }
353
354            // mode 取值(缺省 soft)
355            let hard = match e.mode.as_deref() {
356                None => false,
357                Some("soft") => false,
358                Some("hard") => true,
359                Some(other) => {
360                    self.err(
361                        code::SCHEMA_FIELD,
362                        ep.clone(),
363                        format!("`mode` = {other:?} 非法(只允许 \"soft\" / \"hard\")"),
364                    );
365                    continue;
366                }
367            };
368
369            // 只读视图:链接不承载数据。soft 另禁 `id`(身份由 target 给出);
370            // hard 必写 `id`(自身目录名,见下)。
371            let mut payload: Vec<&str> = Vec::new();
372            if e.id.is_some() && !hard {
373                payload.push("id");
374            }
375            if e.size.is_some() {
376                payload.push("size");
377            }
378            if e.sha256.is_some() {
379                payload.push("sha256");
380            }
381            if e.count.is_some() {
382                payload.push("count");
383            }
384            if e.media_type.is_some() {
385                payload.push("media_type");
386            }
387            if e.schema.is_some() {
388                payload.push("schema");
389            }
390            if !payload.is_empty() {
391                self.err(
392                    code::LINK_HAS_PAYLOAD,
393                    ep.clone(),
394                    format!(
395                        "链接是只读视图,不得携带 {}(所有权唯一在目标分支)",
396                        payload.join(" / ")
397                    ),
398                );
399            }
400
401            let Some(target) = e.target.clone() else {
402                self.err(
403                    code::LINK_NO_TARGET,
404                    ep.clone(),
405                    "`role = \"link\"` 缺少必填字段 `target`",
406                );
407                continue;
408            };
409            if hard {
410                // 硬链接:有身份的真实分支,`path` = `id` = 自身目录名。
411                match e.id.as_deref() {
412                    None => self.err(
413                        code::LINK_TARGET_INVALID,
414                        ep.clone(),
415                        "硬链接(`mode = \"hard\"`)必须写 `id`(= 自身目录名,参与清单比对)",
416                    ),
417                    Some(id) if e.path != id => self.err(
418                        code::LINK_TARGET_INVALID,
419                        ep.clone(),
420                        format!("硬链接的 `path` 必须等于 `id`({id:?}),实为 {p:?}", p = e.path),
421                    ),
422                    _ => {}
423                }
424            } else if e.path != target {
425                self.err(
426                    code::LINK_TARGET_INVALID,
427                    ep.clone(),
428                    format!("软连接的 `path` 必须等于 `target`({target:?}),实为 {p:?}", p = e.path),
429                );
430            }
431            let Some(dst) = scan.resolve(&target) else {
432                self.err(
433                    code::LINK_NO_TARGET,
434                    ep.clone(),
435                    format!("`target` = {target:?} 无法在本 bundle 内解析到任何分支"),
436                );
437                continue;
438            };
439            if scan.visits[dst].depth == 0 {
440                self.err(
441                    code::LINK_TARGET_INVALID,
442                    ep.clone(),
443                    "链接的目标不得是 ROOT(可挂载对象只有 `node` / `branch`)",
444                );
445                continue;
446            }
447        }
448    }
449
450    /// 清单一致性(规范 4.8)与角色 / 深度一致性。
451    fn check_manifest(&mut self, idx: usize) {
452        let scan = self.scan;
453        let bundle = self.bundle;
454        let v: &Visit = &scan.visits[idx];
455        let rel = v.rel.clone();
456        let dir = v.dir.clone();
457        let meta: &Meta = match v.meta.as_ref() {
458            Some(m) => m,
459            None => return,
460        };
461        let entries: Vec<Entry> = meta.entries.clone();
462
463        // path 重复
464        let mut seen: HashSet<String> = HashSet::new();
465        let mut dups: Vec<String> = Vec::new();
466        for e in &entries {
467            // 软连接的重复挂载由 `check_links` 以 `E_LINK_DUP` 报出(更精确),此处不重复报;
468            // 硬链接是真实分支行(path = 自身 id),参与通用重复检查。
469            if e.is_link() && e.mode.as_deref() != Some("hard") {
470                continue;
471            }
472            if !seen.insert(e.path.clone()) {
473                dups.push(e.path.clone());
474            }
475        }
476        for p in dups {
477            self.err(
478                code::MANIFEST_DUP,
479                format!("{rel} #entries"),
480                format!("`entries[].path` = {p:?} 重复"),
481            );
482        }
483
484        let actual = bundle.list_names(&dir).unwrap_or_default();
485
486        // 实际侧 → 逐条比对
487        for (name, is_dir) in &actual {
488            let ep = format!("{rel}/{name}");
489            if util::is_meta_file(name) || util::is_lock_file(name) {
490                continue; // `.str.toml` / `.lock` 不参与清单
491            }
492            if util::is_reserved_name(name) {
493                // `.str.` 保留命名空间(规范 v1.17.0 §1.3 约束 5 / §4.8:保留目录免登记、
494                // 不参与清单比对):
495                // - `.str.schema` / `.str.cache` 是已知保留目录 → **免登记**、放行(显式登记亦合法,属可选声明);
496                // - 其余 `.str.*`(无论目录 / 文件、登记与否)→ 占用保留命名空间 → `E_RESERVED_NAME`。
497                let known = name == crate::util::SCHEMA_DIR || name == crate::util::CACHE_DIR;
498                if !known {
499                    self.err(
500                        code::RESERVED_NAME,
501                        ep.clone(),
502                        "业务条目不得使用 `.str.` 保留命名空间",
503                    );
504                }
505                continue;
506            }
507            if name.starts_with("._") {
508                // AppleDouble 伴生文件命名模式(规范 v1.17.0:格式保留名已改用 `.str.` 前缀,
509                // `._*` 与格式名零冲突,退化为纯噪声豁免):
510                // - 未登记的 `._*` 普通文件 → macOS 跨文件系统拷贝噪声 → 豁免;
511                // - 业务**目录**以 `._` 开头(AppleDouble 只产生文件,必然是人为创建)或
512                //   **已登记**的 `._*` 条目 → 作者显式声明为业务内容 → `E_RESERVED_NAME`。
513                let declared_here = entries.iter().any(|e| e.path == *name);
514                if declared_here || *is_dir {
515                    self.err(
516                        code::RESERVED_NAME,
517                        ep.clone(),
518                        "业务条目不得以 `._` 开头(该命名模式为 macOS AppleDouble 伴生文件保留)",
519                    );
520                }
521                continue;
522            }
523            // 忽略名单命中(规范 4.7 `policies.ignore` + `.gitignore`):
524            // 不报 `E_MANIFEST_MISSING` / `W_DOTFILE` 等问题,视同不存在。
525            let rel_name = if rel == "." {
526                name.clone()
527            } else {
528                format!("{rel}/{name}")
529            };
530            if !scan.ignore.is_empty() && scan.ignore.is_ignored(&rel_name, *is_dir) {
531                continue;
532            }
533            if util::is_os_noise(name) {
534                continue; // `.DS_Store` / `Thumbs.db` / `desktop.ini`
535            }
536            if util::is_other_dotfile(name) {
537                self.warn(
538                    code::DOTFILE,
539                    ep.clone(),
540                    "出现非 `.str.toml` / `.lock` 的点文件(不计入清单要求)",
541                );
542                continue;
543            }
544            // ROOT 允许承载任意内容(规范 3.3:任意目录可放任意文件),
545            // 但「既非 UUID 命名的分支目录、又未登记进 entries」的条目属散落内容 → 告警。
546            let declared_here = entries.iter().any(|e| e.path == *name);
547            if v.depth == 0 && !util::is_uuid(name) && !declared_here {
548                self.warn(
549                    code::ROOT_STRAY,
550                    ep.clone(),
551                    "ROOT 下出现既非分支目录(UUID 命名)又未登记的条目",
552                );
553            }
554            match entries.iter().find(|e| e.path == *name) {
555                None => {
556                    let what = if *is_dir { "目录" } else { "文件" };
557                    self.manifest_issue(
558                        code::MANIFEST_MISSING,
559                        code::MANIFEST_MISSING_W,
560                        ep.clone(),
561                        format!("磁盘存在{what}但 `entries` 未登记"),
562                    );
563                }
564                Some(e) => {
565                    let e = e.clone();
566                    self.check_entry(&dir, v.depth, meta, &e, &ep, *is_dir);
567                }
568            }
569        }
570
571        // 声明侧 → 幽灵条目
572        let mut ghosts: Vec<(String, bool)> = Vec::new();
573        for e in &entries {
574            // 软连接在磁盘上**没有对应目录**(声明式挂载,规范 §4.6.1 规则 1):
575            // 不参与清单比对,故不得报 `E_MANIFEST_GHOST`。硬链接是有身份的真实
576            // 分支(目录必须存在),参与比对 —— 目录缺失照报 ghost。
577            if e.is_link() && e.mode.as_deref() != Some("hard") {
578                continue;
579            }
580            let path: PathBuf = dir.join(&e.path);
581            if path.exists() {
582                continue;
583            }
584            if e.optional {
585                self.warn(
586                    code::OPTIONAL_MISSING,
587                    format!("{rel}/{}", e.path),
588                    "`optional = true` 的条目当前缺失(允许)",
589                );
590            } else {
591                ghosts.push((format!("{rel}/{}", e.path), false));
592            }
593        }
594        for (ep, _) in ghosts {
595            self.manifest_issue(
596                code::MANIFEST_GHOST,
597                code::MANIFEST_GHOST_W,
598                ep,
599                "`entries` 已登记但磁盘不存在",
600            );
601        }
602    }
603
604    /// 单条已登记条目 vs 磁盘实际。
605    fn check_entry(
606        &mut self,
607        dir: &Path,
608        parent_depth: usize,
609        meta: &Meta,
610        e: &Entry,
611        ep: &str,
612        is_dir: bool,
613    ) {
614        let bundle = self.bundle;
615        let path: PathBuf = dir.join(&e.path);
616
617        match e.role.as_str() {
618            "link" => {
619                // 硬链接(`mode = "hard"`)有真实目录:必须是含 `.str.toml` 的分支目录。
620                // 软连接是声明行、磁盘无目录,不会作为磁盘侧命中走到这里。
621                if !is_dir {
622                    self.err(
623                        code::ENTRY_ROLE_DEPTH,
624                        ep,
625                        "`role = \"link\"`(硬链接)要求目录,但磁盘上是文件",
626                    );
627                    return;
628                }
629                if !bundle.has_meta(&path) {
630                    self.err(code::META_MISSING, ep, "硬链接目录内缺少 `.str.toml`");
631                }
632            }
633            "node" | "branch" | "dir" => {
634                if !is_dir {
635                    self.err(
636                        code::ENTRY_ROLE_DEPTH,
637                        ep,
638                        format!("`role = {:?}` 要求目录,但磁盘上是文件", e.role),
639                    );
640                    return;
641                }
642                let dir_name = path
643                    .file_name()
644                    .map(|s| s.to_string_lossy().to_string())
645                    .unwrap_or_default();
646                let child_has_meta = bundle.has_meta(&path);
647                if e.role == "dir" {
648                    if util::is_sub_bundle(&dir_name) {
649                        self.err(
650                            code::ENTRY_ROLE_DEPTH,
651                            ep,
652                            "该目录名以 `.str` 结尾(独立子 bundle),应登记为 `role = \"bundle\"`",
653                        );
654                        return;
655                    }
656                    if child_has_meta {
657                        self.err(
658                            code::ENTRY_ROLE_DEPTH,
659                            ep,
660                            "该子目录含 `.str.toml`(已是分支),却被登记为 `role = \"dir\"`",
661                        );
662                    }
663                    return;
664                }
665                if !child_has_meta {
666                    self.err(code::META_MISSING, ep, "登记为分支但目录内缺少 `.str.toml`");
667                    return;
668                }
669                let want_node = e.role == "node";
670                if parent_depth == 0 && !want_node {
671                    self.err(
672                        code::ENTRY_ROLE_DEPTH,
673                        ep,
674                        "ROOT 的直接子分支必须是 `role = \"node\"`",
675                    );
676                } else if parent_depth >= 1 && want_node {
677                    self.err(
678                        code::ENTRY_ROLE_DEPTH,
679                        ep,
680                        "深度 ≥1 的子分支必须是 `role = \"branch\"`",
681                    );
682                }
683                if let Some(id) = &e.id {
684                    let dir_name = path
685                        .file_name()
686                        .map(|s| s.to_string_lossy().to_string())
687                        .unwrap_or_default();
688                    if *id != dir_name {
689                        self.err(
690                            code::ENTRY_ID_MISMATCH,
691                            ep,
692                            format!("`entries[].id` = {id:?} 与子目录名 {dir_name:?} 不一致"),
693                        );
694                    }
695                }
696                // 子分支自身的 `kind` 是否与父级 `role` 相符
697                let child_kind = match bundle.read_meta(&path) {
698                    Ok(crate::meta::MetaLoad::Ok(child, _)) => child.kind,
699                    _ => None,
700                };
701                if let Some(k) = child_kind {
702                    let expect = if want_node { Kind::Node } else { Kind::Branch };
703                    if k != expect {
704                        self.err(
705                            code::ENTRY_ROLE_DEPTH,
706                            ep,
707                            format!(
708                                "父级登记 `role = {:?}`,但子分支 `kind` = `{}`",
709                                e.role,
710                                k.as_str()
711                            ),
712                        );
713                    }
714                }
715            }
716            "payload" | "asset" => {
717                if is_dir {
718                    self.err(
719                        code::ENTRY_ROLE_DEPTH,
720                        ep,
721                        format!("`role = {:?}` 要求文件,但磁盘上是目录", e.role),
722                    );
723                    return;
724                }
725                self.check_file_digest(e, ep, &path);
726                if e.role == "payload" {
727                    self.check_payload_schema(meta, e, ep, &path);
728                }
729            }
730            "schema" | "cache" => {
731                if !is_dir {
732                    self.err(
733                        code::ENTRY_ROLE_DEPTH,
734                        ep,
735                        format!("`role = {:?}` 要求目录", e.role),
736                    );
737                }
738            }
739            "bundle" => {
740                // 独立子 bundle:目录名须以 `.str` 结尾;父 bundle 不进入其内部
741                let dir_name = path
742                    .file_name()
743                    .map(|s| s.to_string_lossy().to_string())
744                    .unwrap_or_default();
745                if !is_dir {
746                    self.err(
747                        code::ENTRY_ROLE_DEPTH,
748                        ep,
749                        "`role = \"bundle\"` 要求目录",
750                    );
751                } else if !util::is_sub_bundle(&dir_name) {
752                    self.err(
753                        code::ENTRY_ROLE_DEPTH,
754                        ep,
755                        format!("`role = \"bundle\"` 要求目录名以 `.str` 结尾,实为 {dir_name:?}"),
756                    );
757                }
758            }
759            _ => {}
760        }
761    }
762
763    /// 文件类条目的 `size` / `sha256` 强制与一致性。
764    fn check_file_digest(&mut self, e: &Entry, ep: &str, path: &Path) {
765        if self.policies.sha256 == ShaPolicy::Required && (e.size.is_none() || e.sha256.is_none()) {
766            self.err(
767                code::MANIFEST_DIGEST_MISSING,
768                ep,
769                "`policies.sha256 = \"required\"`:文件类条目必须同时提供 `size` 与 `sha256`",
770            );
771        }
772        let Ok(md) = std::fs::metadata(path) else {
773            return;
774        };
775        let real_size = md.len();
776        if let Some(s) = e.size {
777            if s < 0 || s as u64 != real_size {
778                self.manifest_issue(
779                    code::MANIFEST_HASH,
780                    code::MANIFEST_HASH_W,
781                    ep,
782                    format!("`size` = {s} 与实际 {real_size} 不符"),
783                );
784            }
785        }
786        if self.policies.sha256 != ShaPolicy::Off {
787            if let Some(declared) = e.sha256.clone() {
788                match util::sha256_file(path) {
789                    Ok(real) if real == declared => {}
790                    Ok(real) => {
791                        let d = &declared[..declared.len().min(12)];
792                        let r = &real[..12];
793                        self.manifest_issue(
794                            code::MANIFEST_HASH,
795                            code::MANIFEST_HASH_W,
796                            ep,
797                            format!("`sha256` 不符:声明 {d}…,实际 {r}…"),
798                        );
799                    }
800                    Err(err) => {
801                        self.manifest_issue(
802                            code::MANIFEST_HASH,
803                            code::MANIFEST_HASH_W,
804                            ep,
805                            format!("无法计算摘要:{err}"),
806                        );
807                    }
808                }
809            }
810        }
811        if real_size > self.policies.large_asset_bytes {
812            self.warn(
813                code::LARGE_ASSET,
814                ep,
815                format!(
816                    "文件 {real_size} 字节,超过 `large_asset_bytes` = {}",
817                    self.policies.large_asset_bytes
818                ),
819            );
820        }
821    }
822
823    /// `E_REVISION_STALE` 的**历史**判定:`updated_at` 变了但 `revision` 没有前进(规范 §6.1)。
824    ///
825    /// 依据 `.str.cache/revisions.json`(由写入端登记,见 [`crate::baseline`])。无基线时跳过 ——
826    /// 单份 `.str.toml` 不含历史,无从判定;`str sync` 会把基线刷到当前状态。
827    fn check_revision_history(&mut self) {
828        let baseline = crate::baseline::load(self.bundle);
829        if baseline.branches.is_empty() {
830            return;
831        }
832        let mut found: Vec<(String, String, i64, i64, String)> = Vec::new();
833        for v in &self.scan.visits {
834            let Some(meta) = v.meta.as_ref() else {
835                continue;
836            };
837            let Some(snap) = baseline.branches.get(&v.rel) else {
838                continue;
839            };
840            let (Some(rev), Some(updated)) = (meta.revision, meta.updated_at.as_deref()) else {
841                continue;
842            };
843            let changed = match (
844                util::parse_rfc3339(&snap.updated_at),
845                util::parse_rfc3339(updated),
846            ) {
847                (Some(a), Some(b)) => a != b,
848                _ => snap.updated_at != updated,
849            };
850            if changed && rev <= snap.revision {
851                found.push((
852                    v.rel.clone(),
853                    snap.updated_at.clone(),
854                    snap.revision,
855                    rev,
856                    updated.to_string(),
857                ));
858            }
859        }
860        for (rel, was, old_rev, new_rev, now) in found {
861            self.err(
862                code::REVISION_STALE,
863                rel,
864                format!(
865                    "`updated_at` 已由 {was} 变为 {now},但 `revision` 未前进({old_rev} → {new_rev});\
866                     规范 §7.2 要求每次写入同时 +1 并刷新时间"
867                ),
868            );
869        }
870    }
871
872    /// `refs` 关联图成环检测(迭代式 DFS)。
873    fn check_ref_cycles(&mut self) {
874        let scan = self.scan;
875        let n = scan.visits.len();
876        let mut edges: Vec<Vec<usize>> = vec![Vec::new(); n];
877        for (i, v) in scan.visits.iter().enumerate() {
878            if let Some(m) = &v.meta {
879                for r in &m.refs {
880                    if let Some(j) = scan.resolve(&r.target) {
881                        edges[i].push(j);
882                    }
883                }
884            }
885        }
886
887        let mut color = vec![0u8; n]; // 0 未访问 / 1 在栈 / 2 已完成
888        let mut hits: Vec<String> = Vec::new();
889        for start in 0..n {
890            if color[start] != 0 {
891                continue;
892            }
893            let mut stack: Vec<(usize, usize)> = vec![(start, 0)];
894            color[start] = 1;
895            while !stack.is_empty() {
896                let top = stack.len() - 1;
897                let (node, k) = stack[top];
898                if k < edges[node].len() {
899                    let next = edges[node][k];
900                    stack[top].1 += 1;
901                    match color[next] {
902                        0 => {
903                            color[next] = 1;
904                            stack.push((next, 0));
905                        }
906                        1 => hits.push(scan.visits[next].rel.clone()),
907                        _ => {}
908                    }
909                } else {
910                    color[node] = 2;
911                    stack.pop();
912                }
913            }
914        }
915        hits.sort();
916        hits.dedup();
917        for path in hits {
918            self.err(
919                code::REF_CYCLE,
920                path,
921                "`refs` 关联图成环(追踪终点回到链上已有分支)",
922            );
923        }
924    }
925
926    /// 软连接挂载图成环检测(规范 §4.6.1 规则 5,迭代式 DFS,与 `check_ref_cycles` 同法)。
927    ///
928    /// 图的边集 = **真实父子边**(父 → 子)∪ **挂载边**(挂载点 → 目标):沿这个图从
929    /// 任一分支出发能回到自己 ⇒ 按挂载点递归渲染就是无限展开。「挂进自己的祖先」
930    /// 正因此而按环拒绝(祖先 → 自己是真实边);「挂进自己的后代」不是环(DAG,
931    /// 子树多处可见)。必须在校验期拦住,否则 GUI / `tree` 渲染会无限递归。
932    fn check_link_cycles(&mut self) {
933        let scan = self.scan;
934        let n = scan.visits.len();
935        let mut edges: Vec<Vec<usize>> = vec![Vec::new(); n];
936        for (i, v) in scan.visits.iter().enumerate() {
937            if let Some(p) = v.parent {
938                edges[p].push(i);
939            }
940            if let Some(m) = &v.meta {
941                for e in &m.entries {
942                    // 硬链接的 target 是**内容来源**(只读内容视图,目标的分支结构
943                    // 不跟过来)——不构成渲染递归,不参与挂载环判定;其「不得挂
944                    // 自己的后代」由 `check_links` 的 ancestors 检查单独把关。
945                    if !e.is_link() || e.mode.as_deref() == Some("hard") {
946                        continue;
947                    }
948                    if let Some(t) = &e.target {
949                        if let Some(j) = scan.resolve(t) {
950                            edges[i].push(j);
951                        }
952                    }
953                }
954            }
955        }
956
957        let mut color = vec![0u8; n]; // 0 未访问 / 1 在栈 / 2 已完成
958        let mut hits: Vec<String> = Vec::new();
959        for start in 0..n {
960            if color[start] != 0 {
961                continue;
962            }
963            let mut stack: Vec<(usize, usize)> = vec![(start, 0)];
964            color[start] = 1;
965            while !stack.is_empty() {
966                let top = stack.len() - 1;
967                let (node, k) = stack[top];
968                if k < edges[node].len() {
969                    let next = edges[node][k];
970                    stack[top].1 += 1;
971                    match color[next] {
972                        0 => {
973                            color[next] = 1;
974                            stack.push((next, 0));
975                        }
976                        1 => hits.push(scan.visits[next].rel.clone()),
977                        _ => {}
978                    }
979                } else {
980                    color[node] = 2;
981                    stack.pop();
982                }
983            }
984        }
985        hits.sort();
986        hits.dedup();
987        for path in hits {
988            self.err(
989                code::LINK_CYCLE,
990                path,
991                "软连接挂载图成环(沿挂载链可回到本分支,含自我挂载)",
992            );
993        }
994    }
995
996    /// 每个分支的 `.str.toml` 归一化后过 JSON Schema(规范 4.1 校验链路)。
997    fn check_meta_schemas(&mut self) {
998        let scan = self.scan;
999        let bundle = self.bundle;
1000        let items: Vec<(String, JValue, &'static str)> = scan
1001            .visits
1002            .iter()
1003            .filter_map(|v| {
1004                let m = v.meta.as_ref()?;
1005                let name: &'static str = match v.depth {
1006                    0 => "root-meta.schema.json",
1007                    1 => "node-meta.schema.json",
1008                    _ => "branch-meta.schema.json",
1009                };
1010                Some((v.rel.clone(), m.to_json(), name))
1011            })
1012            .collect();
1013
1014        for (rel, instance, name) in items {
1015            let schema = load_meta_schema(bundle, name);
1016            let Ok(validator) = jsonschema::validator_for(&schema) else {
1017                continue;
1018            };
1019            let msgs: Vec<String> = validator
1020                .iter_errors(&instance)
1021                .map(|e| format!("{e}(位于 {})", e.instance_path()))
1022                .collect();
1023            for m in msgs {
1024                self.err(code::SCHEMA_FAIL, rel.clone(), m);
1025            }
1026        }
1027    }
1028
1029    /// payload 的业务 Schema 校验(`entries[].schema` 或分支级 `schema`)。
1030    fn check_payload_schema(&mut self, meta: &Meta, e: &Entry, ep: &str, path: &Path) {
1031        let Some(schema_ref) = e.schema.clone().or_else(|| meta.schema.clone()) else {
1032            return;
1033        };
1034        let schema_path = self.bundle.root.join(&schema_ref);
1035        let Ok(schema_bytes) = std::fs::read(&schema_path) else {
1036            return;
1037        };
1038        let Ok(schema) = serde_json::from_slice::<JValue>(&schema_bytes) else {
1039            return;
1040        };
1041        let Ok(validator) = jsonschema::validator_for(&schema) else {
1042            return;
1043        };
1044        let Ok(bytes) = std::fs::read(path) else {
1045            return;
1046        };
1047        let Ok(instance) = serde_json::from_slice::<JValue>(&bytes) else {
1048            return; // 非 JSON payload 不做 Schema 校验
1049        };
1050        let msgs: Vec<String> = validator
1051            .iter_errors(&instance)
1052            .map(|err| format!("{err}(位于 {})", err.instance_path()))
1053            .collect();
1054        for m in msgs {
1055            self.err(
1056                code::SCHEMA_FAIL,
1057                ep,
1058                format!("payload 不满足 `{schema_ref}`:{m}"),
1059            );
1060        }
1061    }
1062}
1063
1064/// 取某档位的 `.str.toml` Schema:优先 bundle 内 `.str.schema/`,否则用内嵌兜底。
1065fn load_meta_schema(bundle: &Bundle, name: &str) -> JValue {
1066    let local = bundle.root.join(SCHEMA_DIR).join(name);
1067    if local.is_file() {
1068        if let Ok(bytes) = std::fs::read(&local) {
1069            if let Ok(v) = serde_json::from_slice::<JValue>(&bytes) {
1070                return v;
1071            }
1072        }
1073    }
1074    crate::EMBEDDED_SCHEMAS
1075        .iter()
1076        .find(|(n, _)| *n == name)
1077        .and_then(|(_, t)| serde_json::from_str(t).ok())
1078        .unwrap_or_else(|| JValue::Object(Default::default()))
1079}
1080
1081/// 统计某目录下的条目数(`str sync` 用)。
1082pub fn count_dir_entries(dir: &Path) -> usize {
1083    std::fs::read_dir(dir)
1084        .map(|rd| rd.flatten().filter(|e| !util::is_meta_file(&e.file_name().to_string_lossy())).count())
1085        .unwrap_or(0)
1086}
1087
1088/// 计算目录直接子项数(含点文件,排除 `.str.toml`)。
1089pub fn dir_child_count(dir: &Path) -> Option<i64> {
1090    std::fs::read_dir(dir).ok().map(|rd| {
1091        rd.flatten()
1092            .filter(|e| !util::is_meta_file(&e.file_name().to_string_lossy()))
1093            .count() as i64
1094    })
1095}
1096
1097/// 收集目录内除了 `.str.toml`、OS 噪声与忽略名单命中之外的名字(`str sync` 用)。
1098///
1099/// `rel` 为该目录的 bundle 相对路径(ROOT 为 `.`),用于忽略模式匹配。
1100pub fn real_entries(dir: &Path, rel: &str, ignore: &crate::ignore::IgnoreSet) -> Vec<(String, bool)> {
1101    let mut out = Vec::new();
1102    let Ok(rd) = std::fs::read_dir(dir) else {
1103        return out;
1104    };
1105    for ent in rd.flatten() {
1106        let name = ent.file_name().to_string_lossy().to_string();
1107        if util::is_meta_file(&name) || util::is_os_noise(&name) || util::is_lock_file(&name) {
1108            continue;
1109        }
1110        let is_dir = ent.file_type().map(|t| t.is_dir()).unwrap_or(false);
1111        if !ignore.is_empty() {
1112            let rel_name = if rel == "." || rel.is_empty() {
1113                name.clone()
1114            } else {
1115                format!("{rel}/{name}")
1116            };
1117            if ignore.is_ignored(&rel_name, is_dir) {
1118                continue;
1119            }
1120        }
1121        out.push((name, is_dir));
1122    }
1123    out.sort();
1124    out
1125}
1126
1127/// 供测试与工具使用:一次扫描的 `id` → 相对路径映射。
1128pub fn id_index(scan: &Scan) -> HashMap<String, String> {
1129    scan.by_id
1130        .iter()
1131        .filter_map(|(id, idxs)| idxs.first().map(|i| (id.clone(), scan.visits[*i].rel.clone())))
1132        .collect()
1133}