Files
tdc-rs/scripts/check-citations.py
T
adminandClaude Code 1a0fdbf879 feat(upstream-parity): 移植上游测试用例 —— 29 条对位用例 + 第五把尺子
**影响**
- 生产档弱密钥守卫从「只比默认值」升级为上游 `ProdGuard` 的**六条判据**(纯函数),
  弱令牌用「默认值加后缀」绕过、弱标记词、长度下限三类都拦得住;`CIPHER_KEY`(协议共享值)**不受管**。
- 出向 TDS 超时**外置到 env**(`SSW_TDS_CONNECT_TIMEOUT_MS` / `SSW_TDS_READ_TIMEOUT_MS`),
  且**只有 cause 链里真有超时**才改写文案 ⇒ 连接被拒 / DNS 失败不再被误报成「超时」(排查方向不被带偏)。
- 上游 15 个测试类全部**登记在册**:3 个已移植(29 条对位用例)、12 个判定超范围(逐条记理由)。
- 新增第五把尺子 `scripts/check-upstream-tests.sh`:台账 ⇄ 代码 ⇄ 上游测试类集合三向对账,
  上游新增测试类而台账没登记 ⇒ **红**(不靠"记得看"防漂移)。
- 回归网:`cargo test` 246 → **278**(+32),其余四把尺子与引用自检**全绿**。

**改动**
- `src/platform/guard.rs`(新):上游 `ProdGuard.violations` 的纯函数移植(弱值清单 / 弱标记词整体词匹配 / `MIN_LEN=12` / 逐条点名)。
- `src/platform/config.rs`:`check_secret_guard` 改走守卫判据;新增 `guard_values`(只放本部署真有的键)
  与出向超时两项配置(非法值回落默认,不让连接器起不来)。
- `src/tdc/client/tds.rs`:新增 `cause_chain_has_timeout` / `timeout_text_or_null`(cause 链遍历**有界** `depth<16`),
  `TdsClient::with_timeouts` 接受超时。
- `tests/upstream_guard_parity.rs`(新 · 19 条)+ `tests/upstream_tds_timeout_parity.rs`(新 · 10 条)。
- `scripts/upstream-test-ledger.tsv`(台账真源)+ `scripts/upstream-test-census.py`(上游测试类普查/对账)
  + `scripts/check-upstream-tests.sh`(第五把尺子)。
- 文档:`docs/UPSTREAM-TEST-PARITY.md`(新)+ `docs/known-limitations.md` L8 + `docs/decisions.md` D22/D23
  + `CLAUDE.md` 同步(尺子表 / 目录树 / 命令速查 / 实现细节 22–23 / 坑位表)。

**设计**
- 上游 hop 1 的「反射读 socket 工厂」**抄不了**(`reqwest::Client` 不暴露超时 getter)⇒ 改用**行为级**判别
  (同一延迟 TCP 服务器:短超时⇒超时错、长超时⇒成功)⇒ 结论等价且更强(真跑 socket 层)。
- 上游 `*SelfTest.java` **surefire 不跑**(无统一入口)⇒ 判据落成 `cargo test` 常规用例(纯函数 ⇒ 可离线断言)。
- 超范围判定原则:**本仓没有对应功能 ⇒ 不搬**(硬搬只会是假绿);「机制」已覆盖的(P2P 那条)按机制记账。

Co-Authored-By: Claude Code <[email protected]>
2026-10-27 09:04:08 +08:00

193 lines
6.9 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""文档引用自检:B5 文档里的 `文件:行号` 引用是否**真的指向那个文件的那一行**。
用法:
python3 scripts/check-citations.py # 跑全部
python3 scripts/check-citations.py --docs a.md b.md
🔴 **查什么**(机械层):
① 引用的文件**存在**吗?
② 引用的行号**在文件范围内**吗?
③ 行号那行的内容**与引用上下文**有词面交集吗?(可选,靠 `--strict`)
🔴 **不查什么**:语义是否真的一致(那要人读)—— 本脚本只保证「不会指到空气」。
语义抽查由人做(v3 spec §8 B5 验收:「抽查 5 条属实」)。
"""
import argparse
import os
import re
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 上游只读克隆(Java TDC 真源)。文档里常写**相对片段**(如 `entity/ProductEntity.java`),
# ⇒ 建一张「片段 → 真实路径」的索引来解析。
UPSTREAM_ROOT = "/tmp/sswtdc-probe"
# 上游 j7 框架 jar 内的文件 —— **不在克隆里**(jar 是编译产物)⇒ 引用合法但查不了行号。
UPSTREAM_IN_JAR = {
"PasswordTokenGranter.java",
"AuthTokenSupport.java",
"InternalTokenSupport.java",
}
# 引用模式:`路径:行号` 或 `路径:行号/行号` 或 `路径:行号-行号`
# 路径里允许 `/ . _ -` 与字母数字;行号部分是数字。
REF = re.compile(
r"(?<![\w/])((?:[\w.\-]+/)*[\w.\-]+\.(?:rs|sh|md|sql|py|toml|ts|vue|java|yml|yaml))"
r":(\d+)(?:\s*[-/]\s*(\d+))?"
)
# 这些路径是「仓库外的上游真源」⇒ 只做存在性检查,不查行号(上游会变)。
UPSTREAM_PREFIXES = ("/tmp/", "~/")
_upstream_index = None
def upstream_index():
"""(片段 → 真实路径) 索引:按**路径后缀**匹配。"""
global _upstream_index
if _upstream_index is not None:
return _upstream_index
idx = {}
if os.path.isdir(UPSTREAM_ROOT):
for dirpath, _d, files in os.walk(UPSTREAM_ROOT):
for f in files:
full = os.path.join(dirpath, f)
rel = os.path.relpath(full, UPSTREAM_ROOT)
idx[rel] = full
# 也允许只写文件名
idx.setdefault(f, full)
_upstream_index = idx
return idx
def resolve_upstream(path_text):
"""在上游克隆里解析一个**相对片段**;找不到返回 None。"""
idx = upstream_index()
if path_text in idx:
return idx[path_text]
# 后缀匹配:`entity/ProductEntity.java` ⇒ 任何以它结尾的路径
cands = [p for rel, p in idx.items() if rel.endswith("/" + path_text)]
if len(cands) == 1:
return cands[0]
if cands:
return sorted(cands)[0]
return None
DEFAULT_DOCS = [
"docs/contract.md",
"docs/decisions.md",
"docs/known-limitations.md",
"docs/runbook.md",
"docs/ACCOUNT-LAYER.md",
"docs/CONSOLE-ACCEPTANCE.md",
"docs/UPSTREAM-TEST-PARITY.md",
"MIGRATION.md",
"HOWTO_ENTITY.md",
"CLAUDE.md",
]
def resolve(path_text):
"""把文档里写的路径解析成仓库内的真实路径。
文档里的路径常写成 `src/tdc/entity/mod.rs`(仓库根相对),
也可能写成 `../src/tdc/entity/mod.rs`(相对 `docs/`)⇒ 两种都试。
"""
cands = [
os.path.join(ROOT, path_text),
os.path.join(ROOT, "docs", path_text),
]
if path_text.startswith("../"):
cands.append(os.path.join(ROOT, "docs", path_text))
for c in cands:
if os.path.isfile(c):
return c
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--docs", nargs="*", default=None)
args = ap.parse_args()
docs = args.docs if args.docs else DEFAULT_DOCS
total = 0
bad = []
per_doc = {}
for doc_rel in docs:
doc_path = os.path.join(ROOT, doc_rel)
if not os.path.isfile(doc_path):
print("❌ 文档不存在:%s" % doc_rel)
bad.append((doc_rel, 0, doc_rel, "文档不存在"))
continue
with open(doc_path, encoding="utf-8") as fh:
lines = fh.read().splitlines()
n_ok = 0
for lineno, line in enumerate(lines, 1):
# 跳过代码块里的示意性引用?—— 不跳过,代码块里的引用同样要真。
for m in REF.finditer(line):
path_text, a, b = m.group(1), int(m.group(2)), m.group(3)
total += 1
if path_text.startswith(UPSTREAM_PREFIXES) or path_text.startswith("/"):
if not os.path.exists(os.path.expanduser(path_text)):
bad.append((doc_rel, lineno, m.group(0), "上游路径不存在"))
else:
n_ok += 1
continue
real = resolve(path_text)
if real is None:
# 上游片段(`TdcCrudController.java:83` 这种)⇒ 去上游克隆里找
base = os.path.basename(path_text)
if base in UPSTREAM_IN_JAR:
n_ok += 1 # j7 jar 内 ⇒ 行号查不了,但引用合法
continue
up = resolve_upstream(path_text)
if up is None:
bad.append((doc_rel, lineno, m.group(0), "文件不存在(仓内与上游都没有)"))
continue
real = up
else:
# 仓内命中 ⇒ 但同名上游文件也可能存在(`.java` 不会同名,忽略)
pass
with open(real, encoding="utf-8", errors="replace") as fh:
n_lines = sum(1 for _ in fh)
hi = int(b) if b else a
if a < 1 or hi > n_lines or hi < a:
bad.append(
(
doc_rel,
lineno,
m.group(0),
"行号越界(该文件共 %d 行)" % n_lines,
)
)
continue
n_ok += 1
per_doc[doc_rel] = (n_ok, len(lines))
print("文档引用自检")
print("-" * 60)
for doc_rel, (n_ok, n_lines) in per_doc.items():
print(" %-32s 引用 %3d 条 ✅(文档 %d 行)" % (doc_rel, n_ok, n_lines))
print("-" * 60)
print("合计 %d 条引用,%d 条失效" % (total, len(bad)))
if bad:
print("\n❌ 失效 %d 处:" % len(bad))
for doc_rel, lineno, ref, why in bad[:80]:
print(" - %s:%d %s → %s" % (doc_rel, lineno, ref, why))
if len(bad) > 80:
print(" … 还有 %d 处" % (len(bad) - 80))
sys.exit(1)
print("✅ 全部引用都指向真实存在的文件与行号")
return 0
if __name__ == "__main__":
sys.exit(main())