ohos-devloop 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. ohos_devloop/__init__.py +2 -0
  2. ohos_devloop/_version.py +24 -0
  3. ohos_devloop/agents/skills/collab-delegate/SKILL.md +79 -0
  4. ohos_devloop/agents/skills/loop-iterate/SKILL.md +54 -0
  5. ohos_devloop/agents/skills/openharmony-ci/SKILL.md +71 -0
  6. ohos_devloop/agents/skills/openharmony-ci/agents/openai.yaml +4 -0
  7. ohos_devloop/agents/skills/openharmony-ci/scripts/openharmony_ci.py +520 -0
  8. ohos_devloop/agents/skills/pool-status/SKILL.md +47 -0
  9. ohos_devloop/config/e2e-cases.yaml +31 -0
  10. ohos_devloop/config/e2e-hap.yaml +54 -0
  11. ohos_devloop/config/inventory-template.yaml +35 -0
  12. ohos_devloop/config/inventory.yaml +68 -0
  13. ohos_devloop/config/report-templates/analysis-report.md +48 -0
  14. ohos_devloop/config/report-templates/impl-report.md +47 -0
  15. ohos_devloop/config/task-template.md +21 -0
  16. ohos_devloop/config/tdd-board.yaml +31 -0
  17. ohos_devloop/config/tdd-coverage.yaml +47 -0
  18. ohos_devloop/config/tdd-emulator.yaml +36 -0
  19. ohos_devloop/config/tdd-host.yaml +26 -0
  20. ohos_devloop/config/tdd-suites.yaml +34 -0
  21. ohos_devloop/config/templates/agents-user.md +11 -0
  22. ohos_devloop/config/templates/quickstart.md +82 -0
  23. ohos_devloop/config/verify.yaml +45 -0
  24. ohos_devloop/examples/anchor-e2e.yaml +55 -0
  25. ohos_devloop/examples/assert-smoke.yaml +33 -0
  26. ohos_devloop/examples/diffcov-fixture/cov.json +6688 -0
  27. ohos_devloop/examples/diffcov-fixture/diff.txt +24 -0
  28. ohos_devloop/examples/diffcov-smoke.yaml +32 -0
  29. ohos_devloop/examples/e2e-emu-smoke.yaml +45 -0
  30. ohos_devloop/examples/layout-fixture.norm.json +1 -0
  31. ohos_devloop/examples/smoke.yaml +27 -0
  32. ohos_devloop/ohos_cli.py +131 -0
  33. ohos_devloop/scripts/agent-run-v3.sh +149 -0
  34. ohos_devloop/scripts/apply.py +1448 -0
  35. ohos_devloop/scripts/check_env.py +284 -0
  36. ohos_devloop/scripts/collab.py +303 -0
  37. ohos_devloop/scripts/diffcov.py +211 -0
  38. ohos_devloop/scripts/flash.py +511 -0
  39. ohos_devloop/scripts/mount_ws.py +192 -0
  40. ohos_devloop/scripts/release.py +2645 -0
  41. ohos_devloop/scripts/release_audit.py +260 -0
  42. ohos_devloop/scripts/release_metadata.py +397 -0
  43. ohos_devloop/scripts/release_smoke.py +287 -0
  44. ohos_devloop/scripts/report_draft.py +234 -0
  45. ohos_devloop/scripts/server_init.py +310 -0
  46. ohos_devloop/scripts/sgrep.py +82 -0
  47. ohos_devloop/scripts/sign_hap.py +256 -0
  48. ohos_devloop/scripts/telemetry.py +260 -0
  49. ohos_devloop/scripts/ui_probe.py +396 -0
  50. ohos_devloop/scripts/verify_frame_diff.py +138 -0
  51. ohos_devloop/scripts/ws_init.py +131 -0
  52. ohos_devloop/scripts/wsroot.py +192 -0
  53. ohos_devloop-0.1.2.dist-info/METADATA +177 -0
  54. ohos_devloop-0.1.2.dist-info/RECORD +58 -0
  55. ohos_devloop-0.1.2.dist-info/WHEEL +5 -0
  56. ohos_devloop-0.1.2.dist-info/entry_points.txt +2 -0
  57. ohos_devloop-0.1.2.dist-info/licenses/LICENSE +202 -0
  58. ohos_devloop-0.1.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """release_audit.py —— 发布前审计门(库 + CLI,REL-02):对构建产物 fail-closed 四步全链。
4
+
5
+ 一步不绿即阻断上传(任一步失败整体 rc!=0;绝不提供 skip/force/only-warn 通道):
6
+ 1. twine check --strict <wheel>(子进程;twine 缺失 → fail-closed 引导安装,绝不放行)
7
+ 2. wheel 条目对 packaging/wheel-manifest.yaml 允许清单对账
8
+ (与 tests/test_wheel_contents.py 双向断言同源——三件套自该测试提升复用,单一清单源)
9
+ 3. 敏感值黑名单扫描:packaging/audit-blacklist.yaml(文本类条目全文 + METADATA,
10
+ zipfile 只读 + decode + 正则——制品是数据不是代码,绝不 import/exec 被扫内容)
11
+ 4. METADATA 公开要素断言(License-Expression / Project-URL / Classifier 非空,04-02 地基)
12
+
13
+ 黑名单落仓根 packaging/(wheel 外——进包即自指恒红 + 真实值二次分发);本脚本本体不含
14
+ 任何真实值,可随包分发。安装态运行时判不出仓根 packaging/ → 黑名单缺失分支 fail-closed。
15
+
16
+ CLI:
17
+ python ohos_devloop/scripts/release_audit.py <wheel>
18
+ ohos-devloop release-audit <wheel> (ohos_cli MAP 第 12 条)
19
+ 退出码:0=四步全绿(过门,允许上传) 1=审计命中/环境缺失(fail-closed) 2=用法/输入错误
20
+ 维护配方与判据见 RUNBOOK「发布前审计门(release_audit)」节。
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import fnmatch
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+ import zipfile
30
+ from pathlib import Path
31
+
32
+ import yaml
33
+
34
+ PKG = Path(__file__).resolve().parent.parent # 与 wsroot.PKG 同源锚定(ohos_devloop/)
35
+ REPO = PKG.parent # 源码仓检出态 = 仓根(审计从检出态运行)
36
+ BLACKLIST = REPO / "packaging" / "audit-blacklist.yaml"
37
+ MANIFEST = REPO / "packaging" / "wheel-manifest.yaml"
38
+ # 文本类条目白名单(只扫文本,二进制条目不进扫描面);.dist-info/METADATA 单独点名
39
+ TEXT_SUFFIXES = (".py", ".yaml", ".yml", ".md", ".sh", ".json", ".toml", ".txt")
40
+ METADATA_SUFFIX = ".dist-info/METADATA"
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # 三件套(自 tests/test_wheel_contents.py:36-82 原样提升——测试改 import 复用,单一清单源)
45
+ # ---------------------------------------------------------------------------
46
+
47
+ def build_wheel() -> Path:
48
+ """构建 wheel 到独立临时 outdir(不污染仓库;并发/中断不共享构建状态)。"""
49
+ out = tempfile.mkdtemp(prefix="wheelout-")
50
+ subprocess.run(
51
+ [sys.executable, "-m", "build", "--wheel", "--outdir", out],
52
+ cwd=REPO, check=True, capture_output=True, timeout=600) # IN-06:卡死构建不拖挂全套件
53
+ return next(Path(out).glob("*.whl"))
54
+
55
+
56
+ def wheel_asset_names(wheel: Path) -> set[str]:
57
+ """wheel 内 `ohos_devloop/` 前缀资产条目(剔除 dist-info 与构建期生成的版本文件)。"""
58
+ with zipfile.ZipFile(wheel) as z:
59
+ names = {
60
+ n for n in z.namelist()
61
+ if n.startswith("ohos_devloop/") and ".dist-info" not in n
62
+ }
63
+ # _version.py 构建期生成、git 未跟踪:不进期望集合,由 test_version_file_injected 单独断言
64
+ names.discard("ohos_devloop/_version.py")
65
+ return names
66
+
67
+
68
+ def _match_segs(p: list[str], t: list[str]) -> bool:
69
+ if not p:
70
+ return not t
71
+ if p[0] == "**":
72
+ # ** 匹配零或多个路径段(根级 config/inventory.yaml 经 config/**/* 命中)
73
+ return _match_segs(p[1:], t) or (bool(t) and _match_segs(p, t[1:]))
74
+ if not t:
75
+ return False
76
+ return fnmatch.fnmatchcase(t[0], p[0]) and _match_segs(p[1:], t[1:])
77
+
78
+
79
+ def _match_glob(pattern: str, path: str) -> bool:
80
+ """段级 glob:`**` 匹配零或多个路径段,`*` 匹配单段内任意字符。
81
+
82
+ 不能直接用 fnmatch.fnmatchcase 整串匹配——它把 `**` 编译成 `.*` 却要求字面斜杠,
83
+ 根级文件(config/inventory.yaml 之于 config/**/*)必然漏配。
84
+ """
85
+ return _match_segs(pattern.split("/"), path.split("/"))
86
+
87
+
88
+ def manifest_expected(manifest: dict) -> set[str]:
89
+ """期望集合 = git ls-files ohos_devloop/ 与 include 模式求交(锚定 git,不信 glob 的隐含行为)。"""
90
+ tracked = subprocess.run(
91
+ ["git", "ls-files", "ohos_devloop/"], cwd=REPO,
92
+ check=True, capture_output=True, text=True).stdout.splitlines()
93
+ return {f for f in tracked if any(_match_glob(p, f) for p in manifest["include"])}
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # 审计门本体
98
+ # ---------------------------------------------------------------------------
99
+
100
+ def load_blacklist(path: Path) -> dict:
101
+ """黑名单数据源(yaml.safe_load——黑名单只作数据,绝不执行其中内容)。"""
102
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
103
+ if not isinstance(data, dict) or not isinstance(data.get("patterns"), dict):
104
+ raise ValueError(f"黑名单结构不合法(缺 patterns 映射): {path}")
105
+ if "generic" in data and not isinstance(data["generic"], dict):
106
+ raise ValueError(f"黑名单 generic 段类型不合法: {path}")
107
+ if "documented_exceptions" in data and not isinstance(data["documented_exceptions"], list):
108
+ raise ValueError(f"黑名单 documented_exceptions 段类型不合法: {path}")
109
+ return data
110
+
111
+
112
+ def _is_excepted(entry: str, line: str, exceptions: list) -> bool:
113
+ """三键窄域例外:(值, 文件) 精确匹配才放行——同值出现在其它条目仍报(例外不是万能放行通道)。"""
114
+ for x in exceptions:
115
+ value, fname = x.get("value"), x.get("file")
116
+ if not value or not fname:
117
+ continue
118
+ if value in line and (entry == fname or entry.endswith("/" + fname)):
119
+ return True
120
+ return False
121
+
122
+
123
+ def scan_wheel_text(wheel: Path, blacklist: dict) -> list[tuple[str, str, int, str]]:
124
+ """wheel 全文敏感值扫描(纯数据面:zipfile 只读 + decode + re,绝不 import/exec 被扫内容)。
125
+
126
+ 返回命中记录 (pattern 名, 条目路径, 行号, 截断 80 字符行);零命中 = 空列表。
127
+ """
128
+ rules = [(name, re.compile(str(pat)))
129
+ for name, pat in {**blacklist.get("patterns", {}),
130
+ **blacklist.get("generic", {})}.items()]
131
+ exceptions = blacklist.get("documented_exceptions") or []
132
+ hits: list[tuple[str, str, int, str]] = []
133
+ with zipfile.ZipFile(wheel) as z:
134
+ for n in z.namelist():
135
+ if not (n.endswith(TEXT_SUFFIXES) or n.endswith(METADATA_SUFFIX)):
136
+ continue
137
+ for ln, line in enumerate(
138
+ z.read(n).decode("utf-8", errors="replace").splitlines(), 1):
139
+ for name, rx in rules:
140
+ if rx.search(line):
141
+ if _is_excepted(n, line, exceptions):
142
+ continue
143
+ hits.append((name, n, ln, line.strip()[:80]))
144
+ return hits
145
+
146
+
147
+ def run_twine_strict(wheel: Path) -> list[str]:
148
+ """twine check --strict 子进程。失败/缺失/超时 → 非空 findings(fail-closed,绝不静默放行)。"""
149
+ try:
150
+ p = subprocess.run(
151
+ [sys.executable, "-m", "twine", "check", "--strict", str(wheel)],
152
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300)
153
+ except FileNotFoundError:
154
+ return ["twine 不可用:python -m pip install --group dev(或 pip install twine)后重跑"
155
+ "——审计门绝不降级放行"]
156
+ except subprocess.TimeoutExpired:
157
+ return ["twine check --strict 超时(300s)——按失败处理(fail-closed)"]
158
+ if p.returncode != 0:
159
+ detail = (p.stdout or "") + (p.stderr or "")
160
+ return [f"twine check --strict 失败(rc={p.returncode}):\n{detail.strip()[:2000]}"]
161
+ return []
162
+
163
+
164
+ def reconcile_manifest(wheel: Path) -> list[str]:
165
+ """第 2 步:wheel 条目对允许清单对账(双向相等——多一个、少一个都算不匹配)。"""
166
+ with open(MANIFEST, encoding="utf-8") as f:
167
+ manifest = yaml.safe_load(f)
168
+ actual = wheel_asset_names(wheel)
169
+ expected = manifest_expected(manifest)
170
+ findings = []
171
+ missing = sorted(expected - actual)
172
+ extra = sorted(actual - expected)
173
+ if missing:
174
+ findings.append(f"清单允许但 wheel 缺失 {len(missing)} 项: {missing[:5]}")
175
+ if extra:
176
+ findings.append(f"wheel 多出清单外条目 {len(extra)} 项: {extra[:5]}"
177
+ "(脏树构建或打包配置漂移——fail-closed)")
178
+ return findings
179
+
180
+
181
+ def check_metadata(wheel: Path) -> list[str]:
182
+ """第 4 步:METADATA 公开要素断言(License-Expression / Project-URL / Classifier 非空)。"""
183
+ with zipfile.ZipFile(wheel) as z:
184
+ meta = next((n for n in z.namelist() if n.endswith(METADATA_SUFFIX)), None)
185
+ if meta is None:
186
+ return [f"wheel 缺 {METADATA_SUFFIX} 条目——不是合法 wheel?: {wheel.name}"]
187
+ text = z.read(meta).decode("utf-8", errors="replace")
188
+ findings = []
189
+ for field in ("License-Expression", "Project-URL", "Classifier"):
190
+ ok = any(line.startswith(field + ":") and line[len(field) + 1:].strip()
191
+ for line in text.splitlines())
192
+ if not ok:
193
+ findings.append(f"METADATA 公开要素缺失或为空: {field}"
194
+ "(04-02 公开元数据地基——pyproject [project] 补齐后重建)")
195
+ return findings
196
+
197
+
198
+ def main(argv: list[str] | None = None) -> int:
199
+ # Windows 中文输出纪律:CLI 入口统一 UTF-8(check_env/telemetry/ohos_cli 同款)
200
+ try:
201
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
202
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
203
+ except Exception:
204
+ pass
205
+ args = list(sys.argv[1:] if argv is None else argv)
206
+ if not args:
207
+ print("用法: python ohos_devloop/scripts/release_audit.py <wheel>"
208
+ " (或 ohos-devloop release-audit <wheel>)", file=sys.stderr)
209
+ return 2
210
+ wheel = Path(args[0])
211
+ if not wheel.is_file():
212
+ print(f"ERROR: wheel 文件不存在: {wheel}", file=sys.stderr)
213
+ return 2
214
+ if not BLACKLIST.is_file():
215
+ print(f"ERROR: 审计黑名单缺失: {BLACKLIST}\n"
216
+ "审计门面向维护者发布流,需源码仓检出态(packaging/audit-blacklist.yaml 在仓根、"
217
+ "wheel 外;安装态运行天然落入本分支——fail-closed 拒绝审计,绝不降级放行)",
218
+ file=sys.stderr)
219
+ return 1
220
+ try:
221
+ blacklist = load_blacklist(BLACKLIST)
222
+ except (OSError, yaml.YAMLError, ValueError) as e:
223
+ print(f"ERROR: 审计黑名单不可用(fail-closed): {e}", file=sys.stderr)
224
+ return 1
225
+
226
+ steps: list[tuple[str, list[str]]] = [("twine check --strict", run_twine_strict(wheel))]
227
+ try:
228
+ steps.append(("wheel 允许清单对账", reconcile_manifest(wheel)))
229
+ except (OSError, yaml.YAMLError, subprocess.SubprocessError) as e:
230
+ steps.append(("wheel 允许清单对账", [f"清单对账无法执行(fail-closed): {e}"]))
231
+ try:
232
+ steps.append(("敏感值黑名单扫描",
233
+ [f"{n}:{ln} [{pat}] {ex}" for pat, n, ln, ex
234
+ in scan_wheel_text(wheel, blacklist)]))
235
+ except (OSError, zipfile.BadZipFile, re.error) as e:
236
+ steps.append(("敏感值黑名单扫描", [f"黑名单扫描无法执行(fail-closed): {e}"]))
237
+ try:
238
+ steps.append(("METADATA 公开要素断言", check_metadata(wheel)))
239
+ except (OSError, zipfile.BadZipFile) as e:
240
+ steps.append(("METADATA 公开要素断言", [f"METADATA 断言无法执行(fail-closed): {e}"]))
241
+
242
+ findings = 0
243
+ for label, fs in steps:
244
+ if fs:
245
+ print(f"FAIL {label}:")
246
+ for item in fs:
247
+ print(f" - {item}")
248
+ findings += len(fs)
249
+ else:
250
+ print(f"PASS {label}")
251
+ if findings:
252
+ print(f"审计未通过: {findings} 项命中——修复合并后重建 wheel 再审"
253
+ "(fail-closed,无跳过/放行通道)")
254
+ return 1
255
+ print(f"审计通过: {wheel.name}(四步全绿)")
256
+ return 0
257
+
258
+
259
+ if __name__ == "__main__":
260
+ sys.exit(main())
@@ -0,0 +1,397 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """release_metadata.py —— 公开发布元数据的一致性正本(库形态,REL-04/REL-05)。
4
+
5
+ D-15/D-17/D-18/D-19 的可执行判据(消费方:发布命令 preflight 与 tests/test_release_metadata):
6
+ - candidate_version / next_public_version:下一公开版本从本地严格 v* tags 运行时计算
7
+ (最高线 patch +1),绝不硬编码候选常量,也绝不回填/重发旧测试 tag。
8
+ - extract_changelog_section:Keep a Changelog 严格 section 提取——返回含版本标题的原文,
9
+ 供 wheel 正文(dynamic readme 前段)与 GitCode Release body 同源使用;缺 section /
10
+ 版本不符 / 非法日期 / 缺分类 / 空分类一律 MetadataError(fail-closed,T-5-06)。
11
+ - check_remote_files_model:远程发布面文件模型(PyPI urls[] 形状)只接受单条
12
+ bdist_wheel——sdist / zip / 双制品 fail-closed(REL-05 wheel-only 的远端判据,T-5-04)。
13
+ - validate_release_metadata:CHANGELOG 契约 + pyproject dynamic readme 顺序 + 四个
14
+ Project-URL 与当前 tag 的一致性校验(D-18/D-19 同 tag 闭合)。
15
+
16
+ 错误只报结构 / 版本 / URL 事实,不携带凭据、响应体或签名参数。本模块无 CLI
17
+ (发布命令经 release.py 编排;测试直读库形态)。
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import datetime as _dt
22
+ import re
23
+ import subprocess
24
+ import tomllib
25
+ from pathlib import Path
26
+
27
+ REPO = Path(__file__).resolve().parents[2] # 源码仓检出态仓根(与 release_audit 同款锚定)
28
+
29
+ STRICT_TAG_RE = re.compile(r"^v\d+\.\d+\.\d+$") # 严格 vX.Y.Z(与 release.py 同款发布 tag 语法)
30
+ VERSION_HEADING_RE = re.compile(r"^## \[(Unreleased|\d+\.\d+\.\d+)\](?: - (\S+))?\s*$", re.M)
31
+ CATEGORIES = ("Added", "Changed", "Fixed", "Security") # Keep a Changelog 1.1.0 中文项目四分类
32
+ GITCODE_BASE_RE = re.compile(r'^https://gitcode\.com/([^/\s"]+)/([^/\s"]+)$')
33
+
34
+ # 05-RESEARCH Pattern 4 已验证的 URL 模板(正本仓公开后匿名可达;签名 URL 绝不出现)
35
+ RAW_URL_TEMPLATE = "https://gitcode.com/api/v5/repos/{owner}/{repo}/raw/{path}?ref={tag}"
36
+ BLOB_URL_TEMPLATE = "https://gitcode.com/{owner}/{repo}/blob/{tag}/{path}"
37
+ SOURCE_URL_TEMPLATE = "https://gitcode.com/{owner}/{repo}/tree/{tag}"
38
+ RELEASE_URL_TEMPLATE = "https://gitcode.com/{owner}/{repo}/releases/{tag}"
39
+
40
+ LOGIN_MARKERS = ("登录", "sign in", "log in") # 匿名 GET 命中即判登录页(公开失败,非目标内容)
41
+
42
+
43
+ class MetadataError(Exception):
44
+ """公开元数据契约不满足(fail-closed)。消息只含结构与版本事实。"""
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # D-15:下一公开版本(运行时求值,绝不硬编码)
49
+ # ---------------------------------------------------------------------------
50
+
51
+ def candidate_version(tags) -> str:
52
+ """从既有严格 v* tag 计算下一公开版本:最高版本线 patch +1。
53
+
54
+ 例:{v0.1.0, v0.1.1} → '0.1.2'。非严格形态(v1.2、v0.1.2-rc1)不进基线。
55
+ """
56
+ versions = []
57
+ for t in tags:
58
+ t = str(t).strip()
59
+ if STRICT_TAG_RE.match(t):
60
+ versions.append(tuple(int(x) for x in t[1:].split(".")))
61
+ if not versions:
62
+ return "0.1.0"
63
+ top = max(versions)
64
+ return ".".join(str(n) for n in (*top[:-1], top[-1] + 1))
65
+
66
+
67
+ def next_public_version(repo: Path) -> str:
68
+ """仓内本地严格 v* tags → 下一公开候选版本(D-15 运行时求值入口)。"""
69
+ try:
70
+ p = subprocess.run(["git", "-C", str(Path(repo)), "tag", "--list", "v*"],
71
+ capture_output=True, text=True, encoding="utf-8",
72
+ errors="replace", timeout=120)
73
+ except (OSError, subprocess.SubprocessError) as e:
74
+ raise MetadataError(f"git tag --list 不可执行(候选版本求值 fail-closed): {e}") from e
75
+ if p.returncode != 0:
76
+ raise MetadataError("git tag --list 失败(候选版本求值 fail-closed)")
77
+ return candidate_version(p.stdout.splitlines())
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # D-17:CHANGELOG 严格 section 提取(wheel 正文与 GitCode body 同源正本)
82
+ # ---------------------------------------------------------------------------
83
+
84
+ def extract_changelog_section(text: str, version: str) -> str:
85
+ """提取 [version] 版本 section 原文(含 `## [x.y.z] - 日期` 标题行)。
86
+
87
+ 契约(缺一即 MetadataError,fail-closed):
88
+ - 版本条目存在且带 ISO 日期(合法日历日、不在未来——须为实际 release-prep 日);
89
+ - Added / Changed / Fixed / Security 四分类齐全且各含至少 1 条目(空分类 = 未如实分类,
90
+ 发布说明不得隐瞒分类下的变化,T-5-06);
91
+ - 返回标题行起到下一 `## [` 标题前的原文(调用方零改写,保证逐字同源)。
92
+ """
93
+ if not isinstance(text, str) or not text.strip():
94
+ raise MetadataError("CHANGELOG 文本为空(D-17 正本缺失)")
95
+ target = None
96
+ for hm in VERSION_HEADING_RE.finditer(text):
97
+ if hm.group(1) == version:
98
+ target = hm
99
+ break
100
+ if target is None:
101
+ raise MetadataError(f"CHANGELOG 无 [{version}] 版本条目(首条须为当前发布候选)")
102
+ date = target.group(2)
103
+ if not date:
104
+ raise MetadataError(f"[{version}] 标题缺 ISO 日期(## [x.y.z] - YYYY-MM-DD)")
105
+ if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
106
+ raise MetadataError(f"[{version}] 日期非 ISO 形: {date}")
107
+ try:
108
+ d = _dt.date.fromisoformat(date)
109
+ except ValueError as e:
110
+ raise MetadataError(f"[{version}] 日期不合法: {date} ({e})") from e
111
+ if d > _dt.date.today():
112
+ raise MetadataError(f"[{version}] 日期在未来: {date}(须为实际 release-prep 日,不得预填)")
113
+ nxt = next((hm for hm in VERSION_HEADING_RE.finditer(text) if hm.start() > target.start()), None)
114
+ section = text[target.start():nxt.start() if nxt else len(text)]
115
+ for cat in CATEGORIES:
116
+ cm = re.search(rf"^### {cat}\s*$", section, re.M)
117
+ if cm is None:
118
+ raise MetadataError(f"[{version}] section 缺 ### {cat} 分类(四分类缺一 fail-closed)")
119
+ block = section[cm.end():]
120
+ later = re.search(r"^###? ", block, re.M)
121
+ if later:
122
+ block = block[:later.start()]
123
+ if not any(ln.strip().startswith(("-", "*")) for ln in block.splitlines()):
124
+ raise MetadataError(f"[{version}] ### {cat} 分类为空(空分类 fail-closed——"
125
+ "发布说明不得漏分类隐瞒变化)")
126
+ return section.rstrip("\n")
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # REL-05:远程文件模型(发布面 wheel-only 判据)
131
+ # ---------------------------------------------------------------------------
132
+
133
+ def check_remote_files_model(files) -> str:
134
+ """远程发布面版本文件模型(PyPI urls[] 形状)只接受恰一条 bdist_wheel。
135
+
136
+ 返回 wheel 文件名;sdist / zip / 双制品 / 空列表 / 缺键均 MetadataError。
137
+ """
138
+ if not isinstance(files, list) or len(files) != 1:
139
+ n = len(files) if isinstance(files, list) else type(files).__name__
140
+ raise MetadataError(f"发布面文件模型须恰一条(wheel-only),实际 {n}——"
141
+ "多制品或空模型 fail-closed(REL-05)")
142
+ f = files[0]
143
+ if not isinstance(f, dict) or f.get("packagetype") != "bdist_wheel":
144
+ ptype = f.get("packagetype") if isinstance(f, dict) else type(f).__name__
145
+ raise MetadataError(f"发布面出现非 bdist_wheel 条目(packagetype={ptype!r})——"
146
+ "REL-05 wheel-only fail-closed")
147
+ name = str(f.get("filename", ""))
148
+ if not name.endswith(".whl"):
149
+ raise MetadataError(f"发布面文件名非 wheel: {name or '<空>'}(sdist/zip 不进入发布面)")
150
+ return name
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # D-18/D-19:pyproject dynamic readme 与版本化 project_urls 一致性
155
+ # ---------------------------------------------------------------------------
156
+
157
+ def _load_pyproject(repo: Path) -> dict:
158
+ try:
159
+ with open(Path(repo) / "pyproject.toml", "rb") as f:
160
+ return tomllib.load(f)
161
+ except OSError as e:
162
+ raise MetadataError(f"pyproject.toml 不可读: {e}") from e
163
+ except tomllib.TOMLDecodeError as e:
164
+ raise MetadataError(f"pyproject.toml 解析失败: {e}") from e
165
+
166
+
167
+ def gitcode_coords(repo: Path) -> tuple[str, str]:
168
+ """[project.urls] Repository → (owner, repo_name)——URL 一致性校验的对账源。"""
169
+ data = _load_pyproject(repo)
170
+ url = str(((data.get("project", {}) or {}).get("urls", {}) or {}).get("Repository", "")).strip()
171
+ m = GITCODE_BASE_RE.match(url)
172
+ if not m:
173
+ raise MetadataError("[project.urls] Repository 须为 https://gitcode.com/<owner>/<repo>"
174
+ "(公开 URL 模板与匿名可达检查的对账源)")
175
+ return m.group(1), m.group(2)
176
+
177
+
178
+ def validate_release_metadata(repo: Path, tag: str) -> dict:
179
+ """D-17/D-18/D-19 一致性校验:CHANGELOG 首条、dynamic readme 顺序、四 URL 同 tag 闭合。
180
+
181
+ 返回摘要 dict(版本 / tag / 正文字符数 / 四 URL——只含稳定事实,无凭据/响应体)。
182
+ """
183
+ repo = Path(repo)
184
+ tag = str(tag).strip()
185
+ if not STRICT_TAG_RE.match(tag):
186
+ raise MetadataError(f"tag 须为严格 vX.Y.Z: {tag!r}")
187
+ version = tag[1:]
188
+ try:
189
+ text = (repo / "CHANGELOG.md").read_text(encoding="utf-8")
190
+ except OSError as e:
191
+ raise MetadataError(f"CHANGELOG.md 不可读(D-17 正本缺失): {e}") from e
192
+ headings = [hm.group(1) for hm in VERSION_HEADING_RE.finditer(text)]
193
+ versions = [h for h in headings if h != "Unreleased"]
194
+ if not versions:
195
+ raise MetadataError("CHANGELOG 无版本条目(首条须为当前发布候选)")
196
+ if versions[0] != version:
197
+ raise MetadataError(f"CHANGELOG 首条版本 {versions[0]} != 当前 tag 版本 {version}"
198
+ "(说明/正文/URL 必须在同一 tag 上闭合)")
199
+ section = extract_changelog_section(text, version)
200
+
201
+ data = _load_pyproject(repo)
202
+ project = data.get("project", {}) or {}
203
+ if "readme" in project:
204
+ raise MetadataError("[project] 残留静态 readme 键(D-18 须转 dynamic 双文件合成)")
205
+ dynamic = project.get("dynamic")
206
+ if not isinstance(dynamic, list) or "version" not in dynamic or "readme" not in dynamic:
207
+ raise MetadataError("[project] dynamic 须同时含 version 与 readme")
208
+ dyn = ((data.get("tool", {}).get("setuptools", {}) or {}).get("dynamic", {}) or {}).get("readme")
209
+ if not isinstance(dyn, dict) or dyn.get("file") != ["CHANGELOG.md", "README.md"]:
210
+ raise MetadataError("dynamic readme.file 顺序必须严格为 [CHANGELOG.md, README.md]"
211
+ "(当前版本说明须在 PyPI 正文前部,不是只有链接)")
212
+ if dyn.get("content-type") != "text/markdown":
213
+ raise MetadataError("dynamic readme 须声明 content-type = text/markdown")
214
+
215
+ owner, repo_name = gitcode_coords(repo)
216
+ urls = project.get("urls", {}) or {}
217
+ expected = {
218
+ "Homepage": f"https://gitcode.com/{owner}/{repo_name}",
219
+ "Repository": f"https://gitcode.com/{owner}/{repo_name}",
220
+ "Source": SOURCE_URL_TEMPLATE.format(owner=owner, repo=repo_name, tag=tag),
221
+ "Release Notes": RELEASE_URL_TEMPLATE.format(owner=owner, repo=repo_name, tag=tag),
222
+ }
223
+ for key, want in expected.items():
224
+ got = urls.get(key)
225
+ if got != want:
226
+ raise MetadataError(f"Project-URL {key} 不符: 期望 {want},实际 {got!r}"
227
+ "(D-19:Source/Release Notes 钉当前 tag,Homepage/Repository 稳定)")
228
+ return {"version": version, "tag": tag, "section_chars": len(section),
229
+ "urls": dict(expected)}
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # T-5-05:README 公开资产校验(raw/blob 钉 tag、git 跟踪、匿名判据 A1)
234
+ # ---------------------------------------------------------------------------
235
+
236
+ def extract_public_urls(text: str) -> list[tuple[str, str]]:
237
+ """提取 Markdown 图片/链接与 HTML img src 的 (url, image|link) 列表。"""
238
+ urls: list[tuple[str, str]] = []
239
+ for m in re.finditer(r"!\[[^\]]*\]\(([^)\s]+)\)", text):
240
+ urls.append((m.group(1), "image"))
241
+ for m in re.finditer(r"(?<!!)\[[^\]]*\]\(([^)\s]+)\)", text):
242
+ urls.append((m.group(1), "link"))
243
+ for m in re.finditer(r'<img[^>]+src="([^"]+)"', text):
244
+ urls.append((m.group(1), "image"))
245
+ return urls
246
+
247
+
248
+ def _looks_like_login(body: bytes) -> bool:
249
+ """匿名 GET 命中登录引导即判登录页(公开失败,非目标内容)。"""
250
+ head = body[:4096].decode("utf-8", errors="replace").lower()
251
+ return any(marker in head for marker in LOGIN_MARKERS)
252
+
253
+
254
+ def _git_tracked(repo: Path) -> set[str]:
255
+ """git ls-files 全集(资产跟踪判据:未跟踪文件不进发布正文)。"""
256
+ try:
257
+ p = subprocess.run(["git", "-C", str(Path(repo)), "ls-files"],
258
+ capture_output=True, text=True, encoding="utf-8",
259
+ errors="replace", timeout=120)
260
+ except (OSError, subprocess.SubprocessError) as e:
261
+ raise MetadataError(f"git ls-files 不可执行(资产跟踪校验 fail-closed): {e}") from e
262
+ if p.returncode != 0:
263
+ raise MetadataError("git ls-files 失败(资产跟踪校验 fail-closed)")
264
+ return {line for line in p.stdout.splitlines() if line.strip()}
265
+
266
+
267
+ def _safe_get(transport, url: str, entry: dict) -> tuple[int | None, str, bytes]:
268
+ """调用匿名 transport;异常脱敏为不可达(只记 status,绝不记响应体/异常文本)。"""
269
+ try:
270
+ status, ctype, body = transport(url)
271
+ status = int(status)
272
+ entry["status"] = status
273
+ return status, str(ctype or ""), body or b""
274
+ except Exception as e: # 脱敏:只区分「不可达」,不携带异常文本/URL 细节
275
+ entry["status"] = None
276
+ del e
277
+ return None, "", b""
278
+
279
+
280
+ def _check_html_page(entry: dict, url: str, tag: str, transport, kind: str) -> dict:
281
+ """blob/source 页面匿名判据:200 + 非登录页 + 页面含当前 tag(canonical 一致)。"""
282
+ if transport is None:
283
+ entry["ok"], entry["reason"] = True, "形态/跟踪校验通过(匿名可达由发布门回填)"
284
+ return entry
285
+ status, _ctype, body = _safe_get(transport, url, entry)
286
+ if status != 200:
287
+ entry["reason"] = f"匿名 GET 非 200/不可达({status})"
288
+ return entry
289
+ if _looks_like_login(body):
290
+ entry["reason"] = "返回登录页(匿名不可达)"
291
+ return entry
292
+ if tag not in body[:8192].decode("utf-8", errors="replace"):
293
+ entry["reason"] = "通用 SPA/canonical tag 不符(页面未指向当前 tag,空 200 不是证据)"
294
+ return entry
295
+ entry["ok"], entry["reason"] = True, "匿名页面含当前 tag(canonical 一致)"
296
+ return entry
297
+
298
+
299
+ def _check_public_url(url: str, tag: str, base: str, raw_re: re.Pattern,
300
+ blob_re: re.Pattern, tracked: set[str], transport) -> dict:
301
+ entry = {"url": url, "kind": "unknown", "asset": None, "tracked": None,
302
+ "status": None, "ok": False, "reason": ""}
303
+
304
+ def fail(reason: str, kind: str) -> dict:
305
+ entry["kind"] = kind
306
+ entry["reason"] = reason
307
+ return entry
308
+
309
+ if not url.startswith("https://"):
310
+ return fail("相对/非 HTTPS 链接在 PyPI 正文不可达(须当前 tag 的 GitCode raw/blob URL)",
311
+ "relative")
312
+ m = raw_re.match(url)
313
+ if m:
314
+ entry["kind"], entry["asset"] = "raw", m.group(1)
315
+ if m.group(2) != tag:
316
+ return fail(f"raw URL ref={m.group(2)} != 当前 tag {tag}(tag 漂移)", "raw")
317
+ if m.group(1) not in tracked:
318
+ return fail(f"资产未被 git 跟踪: {m.group(1)}(未跟踪文件不进发布正文)", "raw")
319
+ entry["tracked"] = True
320
+ if transport is None:
321
+ entry["ok"], entry["reason"] = True, "形态/跟踪校验通过(匿名可达由发布门回填)"
322
+ return entry
323
+ status, ctype, body = _safe_get(transport, url, entry)
324
+ if status != 200:
325
+ return fail(f"匿名 GET 非 200/不可达({status})", "raw")
326
+ if "html" in ctype.lower():
327
+ return fail("raw 端点返回 HTML 包装(登录页/通用 SPA 冒充资产字节,非目标内容)", "raw")
328
+ if not body:
329
+ return fail("raw 端点返回空体(非目标资产)", "raw")
330
+ entry["ok"], entry["reason"] = True, "匿名返回目标内容字节"
331
+ return entry
332
+ m = blob_re.match(url)
333
+ if m:
334
+ entry["kind"], entry["asset"] = "blob", m.group(2)
335
+ if m.group(1) != tag:
336
+ return fail(f"blob URL tag={m.group(1)} != 当前 tag {tag}(tag 漂移)", "blob")
337
+ if m.group(2) not in tracked:
338
+ return fail(f"资产未被 git 跟踪: {m.group(2)}", "blob")
339
+ entry["tracked"] = True
340
+ return _check_html_page(entry, url, tag, transport, "blob")
341
+ if url == f"{base}/tree/{tag}":
342
+ entry["kind"] = "source"
343
+ return _check_html_page(entry, url, tag, transport, "source")
344
+ if url == f"{base}/releases/{tag}":
345
+ # A1(05-RESEARCH Pitfall 1):Release 页面创建前只校验模板——绝不 GET,
346
+ # 通用 SPA 的 HTTP 200 不是 Release 存在/可达证据;创建后由发布门验证。
347
+ entry["kind"], entry["ok"] = "release-notes", True
348
+ entry["reason"] = "A1:模板校验通过;Release 页面创建后由发布门验证(不匿名 GET)"
349
+ return entry
350
+ if url.startswith(base + "/"):
351
+ return fail("未登记的 GitCode URL 形态(须 raw/blob/tree/releases 之一)", "gitcode")
352
+ entry["kind"], entry["ok"] = "external", True
353
+ entry["reason"] = "外部链接(非本仓资产,不在版本锚定判据内)"
354
+ return entry
355
+
356
+
357
+ def validate_public_asset_links(repo: Path, tag: str, transport=None) -> list[dict]:
358
+ """README 公开资产一致性校验(T-5-05;D-19/05-RESEARCH Pattern 4 + A1)。
359
+
360
+ 判据(每 URL 一条结果,只含稳定 URL/status/reason——绝不返回响应体或签名参数):
361
+ - 图片须为当前 tag 的 GitCode raw HTTPS URL(api/v5 .../raw/<path>?ref=<tag>);
362
+ - 仓内文档(RUNBOOK/AGENTS/LICENSE…)须为当前 tag 的 blob HTTPS URL;
363
+ - 相对 / 非 HTTPS / 未跟踪资产 / tag 漂移一律 ok=False(fail-closed);
364
+ - 给 transport 时进一步区分目标内容与登录页/通用 SPA:raw 端点返回 HTML 包装、
365
+ blob/source 页缺当前 tag、非 200 均失败;transport=None 只做形态/跟踪校验
366
+ (真实匿名 GET 由发布门 05-08/05-10 回填,不以本地 mock 关闭真实判据)。
367
+ """
368
+ repo = Path(repo)
369
+ tag = str(tag).strip()
370
+ if not STRICT_TAG_RE.match(tag):
371
+ raise MetadataError(f"tag 须为严格 vX.Y.Z: {tag!r}")
372
+ try:
373
+ text = (repo / "README.md").read_text(encoding="utf-8")
374
+ except OSError as e:
375
+ raise MetadataError(f"README.md 不可读: {e}") from e
376
+ owner, repo_name = gitcode_coords(repo)
377
+ base = f"https://gitcode.com/{owner}/{repo_name}"
378
+ raw_re = re.compile(
379
+ rf"^https://gitcode\.com/api/v5/repos/{re.escape(owner)}/{re.escape(repo_name)}"
380
+ rf"/raw/(.+?)\?ref=([^&\s]+)$")
381
+ blob_re = re.compile(rf"^{re.escape(base)}/blob/([^/\s]+)/(.+)$")
382
+ tracked = _git_tracked(repo)
383
+ return [_check_public_url(url, tag, base, raw_re, blob_re, tracked, transport)
384
+ for url, _hint in extract_public_urls(text)]
385
+
386
+
387
+ if __name__ == "__main__":
388
+ # 库形态无独立 CLI:直接运行给出只读自检(维护者诊断用,退出码 0/1 同仓约定)
389
+ import json
390
+ import sys
391
+
392
+ try:
393
+ summary = validate_release_metadata(REPO, "v" + next_public_version(REPO))
394
+ except MetadataError as e:
395
+ print(f"FAIL {e}", file=sys.stderr)
396
+ raise SystemExit(1) from e
397
+ print(json.dumps(summary, ensure_ascii=False, indent=2))