#!/usr/bin/env python3 # -*- coding: utf-8 -*- """探针健康闸(S1 语法 / S2 出处 / S3 崩溃 vs 判红)。 Why: 仪器坏了,它给出的所有产品判据就同时失去意义——而它伪装得 perfectly 像产品缺陷。 本轮就踩了两回: · `check-manual.py` 里 `io.open` 忘了 import ⇒ NameError ⇒ EXIT=1, 看起来是"手册漂移判红",实际手册一点事没有;更糟的是它挂在 `mbad = run_measured(doc) + stale_snapshots()` 这一行上, **已经算完的实测对账结果连同 print 一起被吞掉**,我一度以为实测数也红了。 · `alt.py` 语法坏了且从未跑成(目录里从来没有 alt.html)—— "备好但没跑"的脚本要等到授权那一刻执行时才炸。 三段各自配负例;正例基线必须先绿,否则负例的"抓到了"不作数。 """ import ast import glob import json import os import re import shutil import subprocess import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) # 冻结区:按名登记(见 _archive/README.md)。不在名单里的 _archive 内容是漏登记。 ARCHIVE_OK = {"alt.py", "README.md"} # S2 跳过本闸自身:它的负例夹具里必须原样写出"生成器声明输出"那段子串, # 否则夹具就不是被扫到的真文本——于是本闸会被自己的 S2 判成"从未跑成"。 # 跳过是点名跳过而非模式排除;名单里的文件必须真实存在(防陈旧豁免)。 S2_SKIP = {"check-probes.py"} # S3 要跑的闸。GATES 必须覆盖盘上所有 check-*.py + 交叉核验/演练脚本, # 漏一个就等于给它发了免检牌(同族:check-assets 的目录覆盖收缩守卫)。 # 每项是 (脚本, 预期):**预期是数据,不是巧合**。check-docsync 断言的是"文档补丁已落地 # 之后"的仓库状态,#20 未授权执行前它必须红——本闸第一轮把这条当成意外红在查, # 其实是它正常工作。落库后把它翻成 green,闸就改为要求它绿; # 红但不是预期原因,同样判失败。 GATES = [("check-assets.py", "green"), ("check-manual.py", "green"), ("verify-assets-cross.py", "green"), ("rehearse.py", "green"), ("check-wordmark-copies.py --post", "green"), # 已落库 ⇒ 该查"旧标清零+新标逐字节装上",不再是 --pre ("check-wordmark-copies.py --sync", "green"), # P6:内联副本必须与真源逐字节同步 ("check-docsync.py", "green")] # 2026-10-16 17:59 落库后翻绿:三处文档锚点已应用 PENDING_RED = {"check-docsync.py": ("仍含旧句", "落库(#20)未执行 ⇒ 仓库 DESIGN.md/CONTEXT.md 仍是旧文案")} # 已落库的回滚凭据(按名登记;文件数 <8 视为空壳,仍报红) LANDED_BACKUP = {"backup-20261016-175916"} SELF = "check-probes.py" # 本闸不递归跑自己 # S4:#20 落库链的文件,按"谁写的"登记(写手源码里必须真的出现这个名字)。 LAND_REQ = { "make-landing.py": ["logo.svg", "logo-white.svg", "favicon.svg", "favicon.ico", "favicon-16x16.png", "favicon-32x32.png", "favicon-48x48.png", "apple-touch-icon.png", "apply.sh", "rollback.sh"], "make-docsync.py": ["docsync.sh"], "make-pr-desc.py": ["PR-BRAND-ASSETS.md", "PR-SHAPE-TEST.md", "finish-pr-desc.sh"], "make-codepatch.py": ["codepatch.sh"], } # S4b:另一笔授权(P1 色板迁移)的暂存件也要有同样的"齐全+可追写手"检查, # 否则新目录里的可执行脚本落在治理判据的盲区里 —— 它不属于 landing/,但同样会在授权那一刻被执行。 STAGING_REQ = {"make-tokensync.py": ("staging-p1", "tokensync.sh"), "make-fontsync.py": ("staging-p2", "fontsync.sh")} # 崩溃 = 非故意的异常。AssertionError / SystemExit 是闸自己的"判红",属结论不属仪器。 VERDICT_EXC = {"AssertionError", "SystemExit", "Failed"} def s1_syntax(root): bad = [] for f in sorted(glob.glob(os.path.join(root, "*.py"))): try: ast.parse(open(f, encoding="utf-8").read(), filename=f) except SyntaxError as e: bad.append("%s:%s 语法错误:%s" % (os.path.basename(f), e.lineno, e.msg)) return bad def s2_provenance(root): """声明要写 X.html 的生成器,X.html 必须在盘上。""" out, n = [], 0 skip = [s for s in S2_SKIP if not os.path.exists(os.path.join(root, s))] if root == HERE else [] for f in sorted(glob.glob(os.path.join(root, "*.py"))): base = os.path.basename(f) if root == HERE and base in S2_SKIP: continue src = open(f, encoding="utf-8").read() outs = set(re.findall(r'os\.path\.join\(HERE,\s*"([^"]+\.html)"\)', src)) outs = {o for o in outs if not o.startswith("_")} # 下划线=自测/中间产物,不交付 if not outs: continue n += 1 for o in sorted(outs): if not os.path.exists(os.path.join(root, o)): out.append("%s 声明生成 %s,但文件不存在 ⇒ 该脚本从未跑成" % (base, o)) for s in skip: out.append("S2_SKIP 里有 %s,但文件不存在 ⇒ 陈旧豁免,必须删掉这一项" % s) return out, n def classify(exitcode, text): """把一次闸运行分成 GREEN / VERDICT-RED / CRASH 三档。""" m = re.findall(r"^\s*([A-Za-z_][\w.]*(?:Error|Exception|Exit)): ", text, re.M) crash = [c for c in m if c.rsplit(".", 1)[-1] not in VERDICT_EXC] if crash: return "CRASH", crash return ("GREEN", []) if exitcode == 0 else ("RED", []) def s3_gates(root, gates=None): gates = gates if gates is not None else GATES bad, rows = [], [] for g, expect in gates: argv = g.split() # 允许「脚本 参数」一条目跑同一脚本的另一种模式 p = os.path.join(root, argv[0]) if not os.path.exists(p): bad.append("闸清单里有 %s,但文件不存在" % g) continue try: r = subprocess.run([sys.executable] + argv, cwd=root, capture_output=True, text=True, timeout=900) except subprocess.TimeoutExpired: bad.append("%s 超时 900s ⇒ 无法判读" % g) rows.append((g, expect, "TIMEOUT", "")) continue txt = (r.stdout or "") + (r.stderr or "") kind, exc = classify(r.returncode, txt) rows.append((g, expect, kind + ("" if not exc else ":" + ",".join(exc)), "EXIT=%d" % r.returncode)) if kind == "CRASH": tail = [l for l in txt.split("\n") if l.strip()][-1] if txt.strip() else "" bad.append("%s 仪器崩溃(%s)——它的退出码与结论整批作废:%s" % (g, ",".join(exc), tail[:120])) elif expect == "green" and kind == "RED": bad.append("%s 判红(EXIT=%d),这是结论不是故障" % (g, r.returncode)) elif expect == "red": if g not in PENDING_RED: bad.append("%s 标了 red 却没在 PENDING_RED 登记预期原因 ⇒ 「预期要红」不能是一句咒语" % g) else: why, note = PENDING_RED[g] if kind != "RED": bad.append("%s 预期应红(%s),实际 %s" % (g, note, kind)) elif why and why not in txt: bad.append("%s 红了但**不是预期的原因**(应含「%s」)⇒ 红因换一个就必须另案处理" % (g, why)) disk = sorted(x for x in os.listdir(root) if (x.startswith("check-") or x.startswith("verify-") or x == "rehearse.py") and x.endswith(".py")) listed = {g.split()[0] for g, _ in gates} miss = [x for x in disk if x not in listed and x != SELF] if miss: bad.append("盘上有闸未进清单(免检牌):%s" % ", ".join(miss)) if disk and not [x for x in disk if x != SELF]: bad.append("除本闸外一个闸都没找到 ⇒ S3 0 目标,绿灯无意义") return bad, rows def s4_landing(root): """#20 落库链的文件必须齐全,且每一件都能追到"谁写的"。 Why: `make-landing.py` 过去一句 `rmtree(landing/)` 会把别人的产物吃掉——重跑一次, `docsync.sh` 就没了,而 `DOCSYNC-PATCH.md` 里仍然写着"见 landing/docsync.sh"。 那是**授权那一刻才会暴露的空指**:文档同步这一步无声失踪,PR 描述照旧完整。 所以这里不只是"看文件在不在",还断言每个写手脚本的源码确实声明写这个文件 (登记了但脚本不写 = 空头登记);顺带检查 landing/ 里没有残留备份目录 (有 backup- 说明上一轮执行过且没回滚,必须先弄清状态再谈授权)。""" out = [] ldir = os.path.join(root, "landing") if not os.path.isdir(ldir): return ["landing/ 不存在 ⇒ #20 无暂存,落库链整条不可执行"] for f in sorted(os.listdir(ldir)): if f.startswith("backup-"): n = sum(len(fs) for _r, _d, fs in os.walk(os.path.join(ldir, f))) if f in LANDED_BACKUP and n >= 8: continue # 已落库:这份备份是回滚凭据,留着才对 out.append("landing/%s 未登记(登记条件是『名字在 LANDED_BACKUP 且内含 ≥8 个文件』;" "现 %d 个)⇒ 要么是执行过没回滚的残留,要么是空壳凭据" % (f, n)) for writer, files in LAND_REQ.items(): wsrc_path = os.path.join(root, writer) if not os.path.exists(wsrc_path): out.append("登记里的写手 %s 不存在" % writer) continue wsrc = open(wsrc_path, encoding="utf-8").read() for f in files: if not os.path.exists(os.path.join(ldir, f)): out.append("落库链缺 landing/%s(应由 %s 产出)" % (f, writer)) elif f not in wsrc: out.append("%s 登记为 %s 的产出,但其源码里没有这个名字 ⇒ 空头登记" % (f, writer)) orphans = [f for f in sorted(os.listdir(ldir)) if os.path.isfile(os.path.join(ldir, f)) and f not in {x for fs in LAND_REQ.values() for x in fs}] for f in orphans: out.append("landing/%s 没有登记写手 ⇒ 谁写的、该不该在,无从判断" % f) return out def s4b_staging(root): out = [] for writer, (d, fn) in STAGING_REQ.items(): wsrc = os.path.join(root, writer) tgt = os.path.join(root, d, fn) if not os.path.exists(wsrc): out.append('登记里的写手 %s 不存在' % writer) continue if not os.path.exists(tgt): out.append('暂存件 %s/%s 不在盘上 ⇒ %s 未跑或产物被删(P1 无可执行件)' % (d, fn, writer)) elif fn not in open(wsrc, encoding='utf-8').read(): out.append('%s 登记为 %s 的产出,但其源码里没有这个名字 ⇒ 空头登记' % (fn, writer)) for stray in sorted(os.listdir(os.path.dirname(tgt))): if stray != fn: out.append('%s/%s 未登记写手 ⇒ 谁写的、该不该在,无从判断' % (d, stray)) return out def negatives(): """每条负例各验一段;改的是临时副本,真树一个字节都不动。 夹具要复现**当初那个具体失效**,不是"随便一个错"——S3 的崩溃夹具第一版写成 `io.open("x")` 触发的是 FileNotFoundError,而我被骗的那次是 NameError(漏 import)。 分档逻辑当时就判对了,是我的断言写成了"必须是 NameError"才把这条夹具拦下来。""" msgs, real = [], s1_syntax(HERE) + s2_provenance(HERE)[0] + s4_landing(HERE) + s4b_staging(HERE) sb = tempfile.mkdtemp(prefix="probes-") try: open(os.path.join(sb, "broken.py"), "w", encoding="utf-8").write( 'CASES = [dict(idea="前半"后半")]\n') # 嵌套半角引号:本轮的元凶本身 open(os.path.join(sb, "gen_orphan.py"), "w", encoding="utf-8").write( 'import os\nopen(os.path.join(HERE, "missing.html"), "w").close()\n') b1 = s1_syntax(sb) msgs.append(("S1 语法负例(嵌套半角引号)", len(b1) == 1, b1)) b2, n2 = s2_provenance(sb) msgs.append(("S2 出处负例(声明 missing.html 但跑之前盘上没有)", len(b2) == 1 and "missing.html" in b2[0], b2)) # S3 四元夹具:崩溃 / 预期红(原因对) / 红但原因不对 / 正常绿 w = lambda n, s: open(os.path.join(sb, n), "w", encoding="utf-8").write(s) w("check-boom.py", 'x = io.open("q")\n') # NameError:漏 import w("check-quiet.py", 'print("文档同步断言:未通过")\nprint(" · 仍含旧句 X")\nraise SystemExit(1)\n') w("check-other.py", 'print("判红:磁盘不足")\nraise SystemExit(1)\n') w("check-ok.py", 'print("ok")\n') gs = [("check-boom.py", "green"), ("check-quiet.py", "red"), ("check-other.py", "red"), ("check-ok.py", "green")] globals()["PENDING_RED"] = {"check-quiet.py": ("仍含旧句", "沙箱夹具"), "check-other.py": ("仍含旧句", "沙箱夹具:红因不匹配")} b3, rows3 = s3_gates(sb, gs) crash = [x for x in b3 if "仪器崩溃" in x and "NameError" in x] wrong = [x for x in b3 if "不是预期的原因" in x and "check-other.py" in x] quiet_ok = not any("check-quiet.py" in x for x in b3) msgs.append(("S3 崩溃分档(漏 import 的 NameError 不得被当成结论)", len(crash) == 1, rows3)) msgs.append(("S3 pending-red 分档(预期红+原因对 → 不得报;红因不对 → 必须报)", len(wrong) == 1 and quiet_ok, b3)) # S4 负例:把落库链的三种失效各造一次(少一件 / 残留备份 / 孤儿未登记) ld = os.path.join(sb, "landing") os.makedirs(ld) for w, files in LAND_REQ.items(): open(os.path.join(sb, w), "w", encoding="utf-8").write("\n".join(files) + "\n") for f in sorted({x for v in LAND_REQ.values() for x in v}): if f != "docsync.sh": open(os.path.join(ld, f), "w", encoding="utf-8").write("x\n") os.makedirs(os.path.join(ld, "backup-20261016-000000")) open(os.path.join(ld, "mystery.txt"), "w", encoding="utf-8").write("x\n") b4 = s4_landing(sb) miss_doc = [x for x in b4 if "缺 landing/docsync.sh" in x] stale_bk = [x for x in b4 if "残留" in x] orphan = [x for x in b4 if "mystery.txt" in x and "没有登记写手" in x] # 第四种失效:登记了、但写手源码里根本没有这个名字(空头登记)⇒ 抹掉一个名字复现它 wp = os.path.join(sb, "make-pr-desc.py") open(wp, "w", encoding="utf-8").write( "\n".join(x for x in LAND_REQ["make-pr-desc.py"] if x != "PR-SHAPE-TEST.md") + "\n") b4b = s4_landing(sb) hollow = [x for x in b4b if "空头登记" in x and "PR-SHAPE-TEST.md" in x] msgs.append(("S4 落库链负例(缺 1 件 / 残留备份 / 孤儿 / 空头登记,四样都要报)", len(miss_doc) == 1 and len(stale_bk) == 1 and len(orphan) == 1 and len(hollow) == 1, b4 + hollow)) finally: shutil.rmtree(sb, ignore_errors=True) globals()["PENDING_RED"] = {"check-docsync.py": ("仍含旧句", "落库(#20)未执行 ⇒ 仓库 DESIGN.md/CONTEXT.md 仍是旧文案")} return msgs, real def main(): print("=== S1 语法:根目录每个 .py 必须解析得过 ===") b1 = s1_syntax(HERE) for b in b1: print(" ✗ " + b) nfiles = len(glob.glob(os.path.join(HERE, "*.py"))) print(" 扫描 %d 个脚本,语法错误 %d 个 %s" % (nfiles, len(b1), "✓" if not b1 else "✗")) if nfiles < 50: print(" ✗ 目标数异常收缩(应上百)⇒ 本段不作数") print("=== S2 出处:声明写 X.html 的生成器,X.html 必须在盘上 ===") b2, n2 = s2_provenance(HERE) for b in b2: print(" ✗ " + b) print(" 生成器 %d 个,输出缺失 %d 处 %s" % (n2, len(b2), "✓" if not b2 else "✗")) print("=== S4 落库链(#20):每件产物都在,且都能追到写手 ===") b4 = s4_landing(HERE) + s4b_staging(HERE) for b in b4: print(" ✗ " + b) n_land = len([f for f in os.listdir(os.path.join(HERE, "landing")) if os.path.isfile(os.path.join(HERE, "landing", f))]) if os.path.isdir(os.path.join(HERE, "landing")) else 0 print(" landing/ 实文件 %d 个,登记 %d 件,缺失/空头/孤儿 %d 项 %s" % (n_land, sum(len(v) for v in LAND_REQ.values()), len(b4), "✓" if not b4 else "✗")) print("=== S3 闸运行:崩溃 ≠ 判红(前者的结论整批作废;pending-red 还要核对红因)===") b3, rows3 = s3_gates(HERE) for g, expect, kind, note in rows3: print(" %-24s 预期 %-6s %-28s %s" % (g, expect, kind, note)) for b in b3: print(" ✗ " + b) for g, e in GATES: if e == "red": print(" 注:%s 的红是**登记在册的待办**(%s);#20 落库后把预期翻成 green" % (g, PENDING_RED[g][1])) print("=== 负例(本闸自己的可失败性)===") msgs, real = negatives() for name, ok, detail in msgs: print(" %-52s %s" % (name, "✓" if ok else "✗ 未抓到:" + json.dumps(detail, ensure_ascii=False)[:160])) bad = b1 + b2 + b3 + b4 + real ok = not bad and all(ok for _, ok, _ in msgs) print("=== 冻结区登记:_archive 内文件必须逐名在册 ===") adir = os.path.join(HERE, "_archive") unreg = [] if os.path.isdir(adir): unreg = [x for x in sorted(os.listdir(adir)) if os.path.isfile(os.path.join(adir, x)) and x not in ARCHIVE_OK] for x in unreg: print(" ✗ _archive/%s 未在 ARCHIVE_OK 登记" % x) if not unreg: print(" ✓ 已登记:%s" % ", ".join(sorted(ARCHIVE_OK))) if unreg: ok = False print("\n结论:%s" % ("S1/S2/S3/S4 四段全绿,且四段负例都能被抓到;_archive 登记自洽" if ok else "仪器层有问题,先修闸再谈产品判据")) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())