step_ref_check.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """跨文件步骤号一致性检查器。
  4. 扫描 SKILL.md / README.md / FAQ.md 中所有形如「<reference名> 第<中文数字>步」的引用,
  5. 比对目标 reference 文件实际「### 第N步」章节号,报告不匹配项。
  6. 用于防止步骤号漂移(如 v1.9.0 新增「第二步点五」导致后续步骤号 +1 后,
  7. 历史变更日志/FAQ 中的步骤号引用未同步更新)。
  8. 用法:
  9. python step_ref_check.py [--root <技能根目录>]
  10. 退出码:
  11. 0 = 全部匹配
  12. 1 = 发现不匹配或错误
  13. """
  14. import argparse
  15. import os
  16. import re
  17. import sys
  18. # 中文数字映射
  19. CN_NUM = {
  20. "一": 1, "二": 2, "三": 3, "四": 4, "五": 5,
  21. "六": 6, "七": 7, "八": 8, "九": 9, "十": 10,
  22. }
  23. # 匹配「<reference名>.md ... 第<中文数字>步」或「`<reference名>` ... 第<中文数字>步」
  24. # reference 名形如 software-project / code-generation / bug-diagnosis 等
  25. REF_RE = re.compile(
  26. r'`?([a-z][a-z0-9-]+)(?:\.md)?`?[\s\S]{0,30}?第([一二三四五六七八九十]+)步'
  27. )
  28. # 匹配目标文件中的「### 第<N>步:」章节标题
  29. STEP_HEAD_RE = re.compile(r'^###\s*第([一二三四五六七八九十]+)步', re.MULTILINE)
  30. # 已知的 19 个子技能 reference 名(用于过滤误匹配;与 SKILL.md / README / FAQ 的"19 个子技能"口径一致)
  31. KNOWN_REFS = {
  32. "software-project", "website-project", "api-design", "bug-diagnosis",
  33. "karpathy-coding-guidelines", "spec-driven-development", "code-review",
  34. "code-generation", "task-decomposition-and-execution", "tech-selection",
  35. "doc-generation", "test-generation", "performance-benchmark", "refactoring",
  36. "project-memory-management", "cms-development", "frontend-design",
  37. "mysql-database", "project-knowledge-graph",
  38. }
  39. def cn_to_int(cn):
  40. """中文数字转整数(支持一到九十九)。"""
  41. if cn == "十":
  42. return 10
  43. if cn.startswith("十"):
  44. return 10 + CN_NUM.get(cn[1:], 0)
  45. if cn.endswith("十"):
  46. return CN_NUM.get(cn[:-1], 0) * 10
  47. if "十" in cn:
  48. parts = cn.split("十")
  49. return CN_NUM.get(parts[0], 0) * 10 + CN_NUM.get(parts[1], 0)
  50. return CN_NUM.get(cn, 0)
  51. def int_to_cn(n):
  52. """整数转中文数字(支持一到十)。"""
  53. cn_map = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五",
  54. 6: "六", 7: "七", 8: "八", 9: "九", 10: "十"}
  55. return cn_map.get(n, str(n))
  56. def find_step_heads(content):
  57. """在文件内容中查找所有「第N步」章节,返回步骤号集合。"""
  58. steps = {}
  59. for m in STEP_HEAD_RE.finditer(content):
  60. cn = m.group(1)
  61. n = cn_to_int(cn)
  62. if n > 0:
  63. steps[n] = cn
  64. return steps
  65. def check_file(ref_root, src_path, src_name):
  66. """检查单个源文件中的所有步骤号引用。"""
  67. try:
  68. with open(src_path, encoding="utf-8") as f:
  69. content = f.read()
  70. except OSError as e:
  71. print("[STEP-CHECK] 错误:读取 %s 失败: %s" % (src_name, e), file=sys.stderr)
  72. return [], 0
  73. issues = []
  74. checked = 0
  75. seen = set() # 去重:(ref, expected)
  76. for m in REF_RE.finditer(content):
  77. ref_name = m.group(1)
  78. cn_step = m.group(2)
  79. expected = cn_to_int(cn_step)
  80. # 只检查已知的 reference 名,过滤误匹配
  81. if ref_name not in KNOWN_REFS:
  82. continue
  83. key = (ref_name, expected)
  84. if key in seen:
  85. continue
  86. seen.add(key)
  87. ref_path = os.path.join(ref_root, "references", ref_name + ".md")
  88. if not os.path.isfile(ref_path):
  89. continue
  90. try:
  91. with open(ref_path, encoding="utf-8") as f:
  92. ref_content = f.read()
  93. except OSError:
  94. continue
  95. actual_steps = find_step_heads(ref_content)
  96. checked += 1
  97. if expected not in actual_steps:
  98. actual_str = "、".join(
  99. "第%s步" % actual_steps[k] for k in sorted(actual_steps)
  100. ) if actual_steps else "无步骤章节"
  101. issues.append({
  102. "src": src_name,
  103. "ref": ref_name,
  104. "expected_cn": cn_step,
  105. "expected_n": expected,
  106. "actual": actual_str,
  107. "context": m.group(0).replace("\n", " ")[:80],
  108. })
  109. return issues, checked
  110. def _fix_stdout_encoding():
  111. """Windows 默认控制台为 GBK,直接 print emoji(✅/❌)会抛 UnicodeEncodeError。
  112. 若 stdout 编码非 utf-8 且无缓冲能力,回退到对无法编码字符做替换,保证脚本不崩。"""
  113. try:
  114. if sys.stdout.encoding and sys.stdout.encoding.lower().replace("-", "") not in (
  115. "utf8", "utf8"
  116. ):
  117. import io
  118. sys.stdout = io.TextIOWrapper(
  119. sys.stdout.buffer, encoding="utf-8", errors="replace"
  120. )
  121. except Exception:
  122. pass
  123. def main():
  124. _fix_stdout_encoding()
  125. parser = argparse.ArgumentParser(
  126. description="跨文件步骤号一致性检查器",
  127. formatter_class=argparse.RawDescriptionHelpFormatter,
  128. )
  129. parser.add_argument(
  130. "--root",
  131. default=None,
  132. help="技能根目录(默认:脚本上级目录)",
  133. )
  134. args = parser.parse_args()
  135. root = args.root or os.path.abspath(
  136. os.path.join(os.path.dirname(__file__), "..")
  137. )
  138. refs_dir = os.path.join(root, "references")
  139. if not os.path.isdir(refs_dir):
  140. print("[STEP-CHECK] 错误:references 目录不存在: %s" % refs_dir, file=sys.stderr)
  141. return 1
  142. src_files = ["SKILL.md", "README.md", "FAQ.md"]
  143. all_issues = []
  144. total_checked = 0
  145. for src in src_files:
  146. src_path = os.path.join(root, src)
  147. if not os.path.isfile(src_path):
  148. continue
  149. issues, checked = check_file(root, src_path, src)
  150. all_issues.extend(issues)
  151. total_checked += checked
  152. print("[STEP-CHECK] 检查完成:扫描 %d 处步骤号引用" % total_checked)
  153. if not all_issues:
  154. print("[STEP-CHECK] ✅ 全部匹配")
  155. return 0
  156. print("[STEP-CHECK] ❌ 发现 %d 处不匹配:" % len(all_issues))
  157. for i, issue in enumerate(all_issues, 1):
  158. print(" %d. [%s] %s 期望 第%s步(%d),实际 %s" % (
  159. i, issue["src"], issue["ref"],
  160. issue["expected_cn"], issue["expected_n"], issue["actual"]
  161. ))
  162. print(" 上下文: %s" % issue["context"])
  163. return 1
  164. if __name__ == "__main__":
  165. sys.exit(main())