Eats in the ai-audit-report-template as a module. The template is the mutable skin: describeTemplate() infers per-section data demands from ##/### headings (keyword rules), so editing/renaming/reordering sections does not require touching collect or render code. - src/domains/seal/reports/: describe (heading to demand), collect (performance/ risk blocks/template groups, fetched only for declared demands), render (fills tables by section+column signature, rewrites narrative by structure not line number), monthly (orchestrator returning content + per-section completeness + notes). - report-templates/: the template body, assets, example, and downstream validate.py/render.py (not bundled; next.validate/render in the result point at them). - Capability sealReportMonthlyGet (read-only, allow-listed) + CLI "seal-use report monthly --month <YYYY-MM>" + help + KNOWN_FLAGS month + read-only report:monthly. - SKILL.md: routing row + a section stating the two hard rules: the template is swappable, and metrics with no upstream source keep template sample values with a warning note instead of fabricated numbers. Template-path resolution branches on isCompiledBinary() (dev: module-relative to repo root; compiled: cwd), matching how rules lint --file resolves paths, since templates are not embedded. Verified: bun test 633 pass (6 new reports tests), tsc clean, oxlint 0 warnings. Live smoke: 2026-08 report for a real corp fills real accuracy/counts/distribution and marks human-accuracy + mismatch-classification + section-6 sample rows with gap notes.
234 lines
9.2 KiB
Python
234 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""AI 审核报告结构校验器。
|
||
|
||
文档是纯 Markdown(无 frontmatter、无模板标记),校验器只看文档本身:
|
||
- 结构:标题层级、章节编号、表格列数、代码围栏、必填报告信息、图片可解析
|
||
- 纯净:不得出现任何模板机制痕迹(slot/@table/{{}}/render:stop/frontmatter)
|
||
- 数值:总览表求和与占比、小节标题张数、§6 明细与正文、公式算术——全部从正文推导
|
||
|
||
用法:
|
||
python3 tools/validate.py # 校验根目录全部 .md(README 除外)
|
||
python3 tools/validate.py 某文件.md
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
|
||
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
|
||
FORBIDDEN_MARKS = [
|
||
(r"<!--slot:", "slot 标记"),
|
||
(r"<!--/slot", "slot 闭合"),
|
||
(r"<!--@", "@table/@block 区域标记"),
|
||
(r"<!-- render:stop", "render:stop 标记"),
|
||
(r"\{\{", "{{槽位}}"),
|
||
]
|
||
|
||
|
||
class Report:
|
||
def __init__(self, path: Path):
|
||
self.path = path
|
||
self.issues: list[tuple[str, str, str]] = []
|
||
self.n_tables = 0
|
||
self.n_figs = 0
|
||
|
||
def err(self, code: str, msg: str) -> None:
|
||
self.issues.append(("ERROR", code, msg))
|
||
|
||
def warn(self, code: str, msg: str) -> None:
|
||
self.issues.append(("WARN", code, msg))
|
||
|
||
def ok(self) -> bool:
|
||
return not any(lv == "ERROR" for lv, _, _ in self.issues)
|
||
|
||
|
||
def cells(line: str) -> list[str]:
|
||
"""按未转义的 | 拆单元格;\\| 视为字面竖线。"""
|
||
s = line.strip()
|
||
if s.startswith("|"):
|
||
s = s[1:]
|
||
if s.endswith("|") and not s.endswith("\\|"):
|
||
s = s[:-1]
|
||
return [p.replace("\\|", "|").strip() for p in re.split(r"(?<!\\)\|", s)]
|
||
|
||
|
||
def is_sep(line: str) -> bool:
|
||
return line.strip() != "" and "-" in line and set(line.strip()) <= set("|-: ")
|
||
|
||
|
||
def iter_tables(lines: list[str]):
|
||
i = 0
|
||
while i < len(lines):
|
||
if lines[i].startswith("|") and i + 1 < len(lines) and is_sep(lines[i + 1]):
|
||
header = cells(lines[i])
|
||
body, j = [], i + 2
|
||
while j < len(lines) and lines[j].startswith("|"):
|
||
body.append((j + 1, cells(lines[j])))
|
||
j += 1
|
||
yield i + 1, header, body
|
||
i = j
|
||
else:
|
||
i += 1
|
||
|
||
|
||
def table_by_header(lines: list[str], keyword: str) -> dict | None:
|
||
"""按表头关键词找表,返回 {rows, start, end}(行号 1-based,含表头与分隔行)。"""
|
||
for lineno, header, rows in iter_tables(lines):
|
||
if keyword in "".join(header).replace(" ", ""):
|
||
end = rows[-1][0] if rows else lineno + 1
|
||
return {"rows": [r for _, r in rows], "start": lineno, "end": end}
|
||
return None
|
||
|
||
|
||
def pct(x: str) -> float | None:
|
||
m = re.search(r"(\d+(?:\.\d+)?)\s*%", x)
|
||
return float(m.group(1)) if m else None
|
||
|
||
|
||
def count(x: str) -> float | None:
|
||
m = re.search(r"(\d+(?:\.\d+)?)", x)
|
||
return float(m.group(1)) if m else None
|
||
|
||
|
||
def check(path: Path) -> Report:
|
||
r = Report(path)
|
||
text = path.read_text(encoding="utf-8")
|
||
lines = text.split("\n")
|
||
|
||
# 1. 纯净性:单层纯 Markdown
|
||
if text.startswith("---\n"):
|
||
r.err("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
|
||
for pat, name in FORBIDDEN_MARKS:
|
||
if re.search(pat, text):
|
||
r.err("MK001", f"出现模板机制痕迹({name}),模板应是纯 Markdown 文档")
|
||
|
||
# 2. 代码围栏
|
||
fences = [i for i, ln in enumerate(lines, 1) if ln.startswith("```")]
|
||
if len(fences) % 2:
|
||
r.err("MD001", f"代码围栏为奇数({len(fences)}),存在未闭合代码块")
|
||
|
||
# 3. 表格列数与表头
|
||
for lineno, header, rows in iter_tables(lines):
|
||
r.n_tables += 1
|
||
n = len(header)
|
||
for rl, row in rows:
|
||
if len(row) != n:
|
||
r.err("TB001", f"第 {rl} 行表格列数 {len(row)} ≠ 表头 {n} 列")
|
||
if any("**" in c for c in header):
|
||
r.err("TB002", f"第 {lineno} 行表头含加粗标记 **")
|
||
|
||
# 4. 标题层级与章节编号
|
||
prev, seen = 0, []
|
||
for ln in lines:
|
||
m = re.match(r"^(#{1,6})\s+(.*)$", ln)
|
||
if not m:
|
||
continue
|
||
lvl = len(m.group(1))
|
||
if prev and lvl > prev + 1:
|
||
r.err("HD001", f"标题层级跳级({prev} → {lvl}):{m.group(2)[:40]}")
|
||
prev = lvl
|
||
m2 = re.match(r"^(\d+)\.", m.group(2))
|
||
if lvl == 2 and m2:
|
||
seen.append(m2.group(1))
|
||
if seen and seen != SECTION_NUMBERS:
|
||
r.err("HD002", f"## 章节编号应为 {SECTION_NUMBERS},实际 {seen}")
|
||
|
||
# 5. 报告信息表
|
||
info = table_by_header(lines, "报告信息")
|
||
if not info:
|
||
r.err("INFO001", "缺少「报告信息」表")
|
||
else:
|
||
keys = {row[0] for row in info["rows"] if row}
|
||
missing = REQUIRED_INFO_ROWS - keys
|
||
if missing:
|
||
r.err("INFO001", f"报告信息表缺少:{', '.join(sorted(missing))}")
|
||
empty = [row[0] for row in info["rows"] if row and len(row) > 1 and not row[1].strip()]
|
||
if empty:
|
||
r.err("INFO002", f"报告信息表以下项为空:{', '.join(empty)}")
|
||
|
||
# 6. 图片可解析:http(s) 或存在的本地文件
|
||
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
|
||
src = m.group(1).strip()
|
||
r.n_figs += 1
|
||
if src.startswith(("http://", "https://")):
|
||
continue
|
||
if not (path.parent / src).exists():
|
||
r.err("IMG001", f"图片不存在:{src}")
|
||
|
||
# 7. 数值自洽(全部从正文推导)
|
||
for tag, kw in (("NM001", "失准类型"), ("NM002", "风险类型")):
|
||
tb = table_by_header(lines, kw)
|
||
if not tb:
|
||
continue
|
||
rows = tb["rows"]
|
||
tops = [(c[0], count(c[3])) for c in rows if len(c) > 3 and c[0].startswith("TOP")]
|
||
totals = [count(c[3]) for c in rows if len(c) > 3 and c[0] in ("合计", "总计", "—")]
|
||
if tops and totals and all(c is not None for _, c in tops):
|
||
if sum(c for _, c in tops) != totals[0]:
|
||
r.err(tag, f"{kw}各维度之和 {sum(c for _, c in tops)} ≠ 合计 {totals[0]}")
|
||
base = totals[0] if totals else None
|
||
for c in rows:
|
||
if len(c) < 4:
|
||
continue
|
||
share, cnt = pct(c[2]), count(c[3])
|
||
if share and cnt and base and c[0].startswith("TOP") and abs(cnt / base * 100 - share) > 0.15:
|
||
r.err("NM003", f"{kw}「{c[1]}」占比 {share}% ≠ {cnt:.0f}/{base:.0f} = {cnt / base * 100:.1f}%")
|
||
# 小节标题里的张数与总览表一致
|
||
for no, cnt in tops:
|
||
sec = "2" if kw == "失准类型" else "3"
|
||
m = re.search(r"###\s*%s\.\d+\s*%s[^(]*((\d+)\s*张" % (sec, re.escape(no)), text)
|
||
if m and cnt is not None and int(m.group(1)) != cnt:
|
||
r.err(tag, f"{no} 小节标题写 {m.group(1)} 张,总览表写 {cnt:.0f} 张")
|
||
|
||
# NM004:§6 明细表的结论分类计数 = 正文数字
|
||
pr = table_by_header(lines, "原因分类")
|
||
if pr:
|
||
d4 = sum(1 for c in pr["rows"] if len(c) > 4 and "依规正确" in c[4])
|
||
miss = sum(1 for c in pr["rows"] if len(c) > 4 and "失准" in c[4])
|
||
m = re.search(r"((\d+)\s*/\s*(\d+)\s*笔)", text)
|
||
m2 = re.search(r"仅有\s*\*{0,2}(\d+)\s*笔", text)
|
||
if m and int(m.group(1)) != d4:
|
||
r.err("NM004", f"正文称依规正确 {m.group(1)} 笔,明细表实际 {d4} 行")
|
||
if m and int(m.group(2)) != len(pr["rows"]):
|
||
r.err("NM004", f"正文称合计 {m.group(2)} 笔,明细表实际 {len(pr['rows'])} 行")
|
||
if m2 and int(m2.group(1)) != miss:
|
||
r.err("NM004", f"正文称 AI 失准 {m2.group(1)} 笔,明细表实际 {miss} 行")
|
||
|
||
# NM005:公式算术自洽,且代入值能在正文别处找到
|
||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||
outside = "\n".join(l for l in lines if not l.strip().startswith("$$"))
|
||
for ln in formula_lines:
|
||
for frac in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", ln):
|
||
a, b, p = int(frac.group(1)), int(frac.group(2)), float(frac.group(3))
|
||
if b and abs(a / b * 100 - p) > 0.05:
|
||
r.err("NM005", f"公式 {a}/{b} = {p}% 算术不成立(实为 {a / b * 100:.2f}%)")
|
||
for tok in re.findall(r"\d+(?:\.\d+)?", ln):
|
||
if tok not in outside:
|
||
r.err("NM005", f"公式中的数值 {tok} 在正文别处找不到,可能与数据脱节")
|
||
|
||
return r
|
||
|
||
|
||
def default_paths() -> list[Path]:
|
||
"""默认校验根目录全部 .md(README.md 除外)。"""
|
||
return sorted(p for p in Path(".").glob("*.md") if p.name != "README.md")
|
||
|
||
|
||
def main() -> int:
|
||
paths = [Path(a) for a in sys.argv[1:]] or default_paths()
|
||
failed = False
|
||
for p in paths:
|
||
rep = check(p)
|
||
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
|
||
for lv, code, msg in rep.issues:
|
||
print(f" {lv} {code}: {msg}")
|
||
failed |= not rep.ok()
|
||
return 1 if failed else 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|