dsh-project-dept 1.0.1 → 1.0.3
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.
- package/README.md +5 -3
- package/README.zh.md +5 -3
- package/index.js +26 -12
- package/locale/en.json +4 -2
- package/locale/zh.json +4 -2
- package/package.json +2 -2
- package/skills/loop-ops/SKILL.md +124 -0
- package/skills/project-dept/README.md +366 -8
- package/skills/project-dept/README_EN.md +436 -7
- package/skills/project-dept/SKILL.md +10 -21
- package/skills/project-dept/evals/evals.json +252 -7
- package/skills/project-dept/manifest.yaml +29 -3
- package/skills/project-dept/references/blind-review.md +35 -0
- package/skills/project-dept/references/project-scaffold.md +10 -4
- package/skills/project-dept/scripts/check_review_form.py +649 -0
- package/skills/project-dept/scripts/check_skill.py +943 -0
- package/skills/project-dept/scripts/dept_gate.py +90 -7
- package/skills/project-dept/scripts/run_evals.py +1344 -0
- package/skills/project-dept/static/core/output-contract.md +7 -1
- package/skills/project-dept/static/core/workflow.md +3 -2
- package/skills/project-dept/tests/test_check_review_form.py +453 -0
- package/skills/project-dept/tests/test_check_skill.py +620 -0
- package/skills/project-dept/tests/test_dept_gate_baseline.py +229 -0
- package/skills/project-dept/tests/test_dept_gate_json.py +116 -0
- package/skills/project-dept/tests/test_run_evals.py +644 -0
- package/tests/bundle.test.js +29 -9
|
@@ -0,0 +1,943 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""check_skill.py — project-dept skill 包静态自检器(作者自查工具,不是验收工具)。
|
|
4
|
+
|
|
5
|
+
只查「机械可判的腐化」,不判断内容好坏:
|
|
6
|
+
1. frontmatter name / description / metadata.version 存在且合法
|
|
7
|
+
2. 版本一致 SKILL.md / manifest.yaml / README.md / README_EN.md 的当前版本号一致
|
|
8
|
+
3. 声明资产存在 manifest 与 SKILL.md 正文里声明的相对路径必须真实存在
|
|
9
|
+
4. 禁出现文件名 VERIFICATION.md / 修复进度.md / 看板.md / 交付登记簿.md 不得出现在入口文档里
|
|
10
|
+
5. 上下文预算 SKILL.md ≤ 3000 tokens(**硬上限:超了算缺陷**);
|
|
11
|
+
SKILL.md + always_load ≤ 9000 tokens(超限只警告)
|
|
12
|
+
6. evals 可读 evals/evals.json 合法 JSON、evals 数组、每例字段齐全、id 不重复
|
|
13
|
+
7. 包完整性 manifest/SKILL/README* /static /references /质量脚本 /tests /evals 都在
|
|
14
|
+
8. manifest 语法 manifest.yaml 必须能被解析(有 PyYAML 就 safe_load,无则启发式抓断行)
|
|
15
|
+
|
|
16
|
+
用法:
|
|
17
|
+
python scripts/check_skill.py # 检查脚本所在包(上两级目录)
|
|
18
|
+
python scripts/check_skill.py --root <dir> # 检查指定包目录
|
|
19
|
+
python scripts/check_skill.py --json # 机器可读输出(stdout 上只有 JSON)
|
|
20
|
+
|
|
21
|
+
退出码:
|
|
22
|
+
0 = 无缺陷(可有警告)
|
|
23
|
+
1 = 有缺陷
|
|
24
|
+
2 = 无法执行(目录不存在 / SKILL.md 缺失 / 文件读不出来)
|
|
25
|
+
|
|
26
|
+
已知局限(见 README 里的说明):
|
|
27
|
+
- manifest 与 SKILL.md 正文用「前缀 + 文件扩展名」识别相对路径;不带扩展名的裸目录
|
|
28
|
+
(例如正文里写 static/core 而不是 static/core/xxx.md)不参与存在性核对,避免把
|
|
29
|
+
「tests/evals」这类散文词误判成路径。
|
|
30
|
+
- README 的「当前版本」取文内出现的最高版本号(变更记录按倒序排列,旧版本号不计)。
|
|
31
|
+
- 禁出现文件名是纯文本匹配:入口文档里即使只是「历史记录里提到该文件名」也会被判 [x],
|
|
32
|
+
这是宽严取舍 —— 对「不随包分发」的承诺做机械约束,宁可多报。
|
|
33
|
+
"""
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import argparse
|
|
37
|
+
import json
|
|
38
|
+
import math
|
|
39
|
+
import re
|
|
40
|
+
import sys
|
|
41
|
+
from dataclasses import dataclass, field
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
|
|
44
|
+
# ---------------------------------------------------------------- 常量
|
|
45
|
+
|
|
46
|
+
EXPECTED_NAME = "project-dept"
|
|
47
|
+
|
|
48
|
+
FORBIDDEN_FILENAMES = ("VERIFICATION.md", "修复进度.md", "看板.md", "交付登记簿.md")
|
|
49
|
+
|
|
50
|
+
REQUIRED_PATHS = (
|
|
51
|
+
"manifest.yaml",
|
|
52
|
+
"SKILL.md",
|
|
53
|
+
"README.md",
|
|
54
|
+
"README_EN.md",
|
|
55
|
+
"static/",
|
|
56
|
+
"references/",
|
|
57
|
+
"scripts/dept_gate.py",
|
|
58
|
+
"scripts/check_doc.py",
|
|
59
|
+
"tests/",
|
|
60
|
+
"evals/evals.json",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
TOKEN_LIMIT_SKILL_MD = 3000
|
|
64
|
+
TOKEN_LIMIT_ALWAYS_LOAD = 9000
|
|
65
|
+
# v1.2.1:真实单次开工成本还包括命中的轴片段(static/fragments/<轴>/<值>.md,每轴取最大那份)。
|
|
66
|
+
# 以前只算 SKILL.md + always_load,往片段里塞几万字也不会报警(R2 实测 +15,311 字符仍 exit 0)。
|
|
67
|
+
TOKEN_LIMIT_PER_RUN_WARN = 9000
|
|
68
|
+
TOKEN_LIMIT_PER_RUN_DEFECT = 14000
|
|
69
|
+
|
|
70
|
+
# 「写死脚本个数」这类陈述会随实体变化腐化(R1 抓到 README 还写"两个脚本/两个质量工具",实体已 4 个)。
|
|
71
|
+
STALE_TWO_SCRIPTS_PHRASES = ("两个脚本", "两个质量工具", "two scripts", "two quality tools")
|
|
72
|
+
QUALITY_TOOL_SCRIPT_RE = re.compile(
|
|
73
|
+
r"(?m)^\s+(?:gate_script|audit_script|skill_lint_script|eval_runner)\s*:\s*(\S+)\s*$"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
PATH_PREFIXES = ("static", "references", "scripts", "agents", "tests", "evals")
|
|
77
|
+
FILE_EXTS = {
|
|
78
|
+
"md", "markdown", "py", "json", "yaml", "yml", "txt", "rst",
|
|
79
|
+
"ps1", "sh", "bat", "cmd", "csv", "tsv", "toml", "ini", "cfg",
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
# 「声明处」出现的相对路径 token(前缀 + 至少一段)
|
|
83
|
+
PATH_TOKEN_RE = re.compile(
|
|
84
|
+
r"(?<![\w./\\-])"
|
|
85
|
+
r"((?:%s)/[A-Za-z0-9_.\-/]*)" % "|".join(PATH_PREFIXES)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
VERSION_RE = re.compile(r"(?<![\d.])(\d+\.\d+\.\d+)(?![\d.])")
|
|
89
|
+
|
|
90
|
+
TAGS = {"ok": "[ok]", "warn": "[!]", "defect": "[x]"}
|
|
91
|
+
|
|
92
|
+
# CJK 码位区间:按 1 token/字计,其余按 3.5 字符/token
|
|
93
|
+
CJK_RANGES = (
|
|
94
|
+
(0x3000, 0x303F), # CJK 标点
|
|
95
|
+
(0x3040, 0x30FF), # 日文假名(v1.2.1 补:此前漏掉,纯假名文本按 3.5 字符/token 估算,可绕过预算上限)
|
|
96
|
+
(0x3400, 0x4DBF), # 扩展 A
|
|
97
|
+
(0x4E00, 0x9FFF), # 基本区
|
|
98
|
+
(0xAC00, 0xD7A3), # 谚文音节(v1.2.1 补:同上)
|
|
99
|
+
(0xF900, 0xFAFF), # 兼容表意
|
|
100
|
+
(0xFF00, 0xFFEF), # 全角形式
|
|
101
|
+
(0x1F300, 0x1FAFF), # emoji(v1.2.1 补:按 1 token/字保守计,避免用表情凑体积逃检)
|
|
102
|
+
(0x20000, 0x2A6DF), # 扩展 B(v1.2.1 补)
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ---------------------------------------------------------------- 结果容器
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class CheckResult:
|
|
111
|
+
number: int
|
|
112
|
+
title: str
|
|
113
|
+
details: list = field(default_factory=list)
|
|
114
|
+
defects: list = field(default_factory=list)
|
|
115
|
+
warnings: list = field(default_factory=list)
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def status(self) -> str:
|
|
119
|
+
if self.defects:
|
|
120
|
+
return "defect"
|
|
121
|
+
if self.warnings:
|
|
122
|
+
return "warn"
|
|
123
|
+
return "ok"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Ctx:
|
|
127
|
+
def __init__(self, root: Path, skill_text: str, manifest_text, fm, body,
|
|
128
|
+
body_line_offset: int, fm_error, allow_dirname_mismatch: bool = False):
|
|
129
|
+
self.root = root
|
|
130
|
+
self.skill_text = skill_text
|
|
131
|
+
self.manifest_text = manifest_text # str | None
|
|
132
|
+
self.fm = fm # dict | None
|
|
133
|
+
self.body = body or ""
|
|
134
|
+
self.body_line_offset = body_line_offset
|
|
135
|
+
self.fm_error = fm_error
|
|
136
|
+
self.allow_dirname_mismatch = allow_dirname_mismatch
|
|
137
|
+
self.budget = {}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------- 通用工具
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def is_cjk(cp: int) -> bool:
|
|
144
|
+
for lo, hi in CJK_RANGES:
|
|
145
|
+
if lo <= cp <= hi:
|
|
146
|
+
return True
|
|
147
|
+
return False
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def estimate_tokens(text: str) -> int:
|
|
151
|
+
cjk = sum(1 for ch in text if is_cjk(ord(ch)))
|
|
152
|
+
other = len(text) - cjk
|
|
153
|
+
return int(math.ceil(cjk + other / 3.5))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def read_text(path: Path):
|
|
157
|
+
"""按 UTF-8(容忍 BOM)读文本;读不出来返回 None。"""
|
|
158
|
+
try:
|
|
159
|
+
return path.read_text(encoding="utf-8-sig")
|
|
160
|
+
except (OSError, UnicodeDecodeError):
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def unquote(value: str) -> str:
|
|
165
|
+
value = value.strip()
|
|
166
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
|
167
|
+
return value[1:-1]
|
|
168
|
+
# 去掉 YAML 行尾注释(只处理「空格 + #」)
|
|
169
|
+
m = re.search(r"\s+#", value)
|
|
170
|
+
if m:
|
|
171
|
+
value = value[:m.start()].rstrip()
|
|
172
|
+
return value
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def classify_token(token: str):
|
|
176
|
+
"""把 path token 分成 ('file', path) / ('dir', path) / None(不核对)。
|
|
177
|
+
|
|
178
|
+
- 以 / 结尾 → 目录
|
|
179
|
+
- 最后一段带已知文件扩展名 → 文件
|
|
180
|
+
- 其余(如 static/core、tests/evals 这类散文词/裸目录)→ None,不核对
|
|
181
|
+
"""
|
|
182
|
+
token = token.rstrip(".,;:!?)]}'\"").strip()
|
|
183
|
+
if not token:
|
|
184
|
+
return None
|
|
185
|
+
if token.endswith("/"):
|
|
186
|
+
return "dir", token
|
|
187
|
+
last = token.rsplit("/", 1)[-1]
|
|
188
|
+
if "." in last:
|
|
189
|
+
ext = last.rsplit(".", 1)[-1].lower()
|
|
190
|
+
if ext in FILE_EXTS:
|
|
191
|
+
return "file", token
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def exists_with_kind(root: Path, kind: str, token: str) -> bool:
|
|
196
|
+
target = root / token
|
|
197
|
+
return target.is_dir() if kind == "dir" else target.is_file()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def version_key(version: str):
|
|
201
|
+
return tuple(int(part) for part in version.split("."))
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def extract_versions(text: str):
|
|
205
|
+
return [m.group(1) for m in VERSION_RE.finditer(text)]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ---------------------------------------------------------------- frontmatter 解析
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def parse_frontmatter(text: str):
|
|
212
|
+
"""极简 YAML frontmatter 解析(不依赖 PyYAML)。
|
|
213
|
+
|
|
214
|
+
返回 (data, body, body_line_offset, error)。
|
|
215
|
+
data 只支持一层嵌套(metadata: 下的键),足够本包使用。
|
|
216
|
+
"""
|
|
217
|
+
lines = text.splitlines()
|
|
218
|
+
if not lines or lines[0].strip() != "---":
|
|
219
|
+
return None, None, 0, "SKILL.md 首行不是 YAML frontmatter 分隔符 '---'"
|
|
220
|
+
|
|
221
|
+
end = None
|
|
222
|
+
for i in range(1, len(lines)):
|
|
223
|
+
if lines[i].strip() == "---":
|
|
224
|
+
end = i
|
|
225
|
+
break
|
|
226
|
+
if end is None:
|
|
227
|
+
return None, None, 0, "frontmatter 缺少结束分隔符 '---'"
|
|
228
|
+
|
|
229
|
+
data: dict = {}
|
|
230
|
+
current = data
|
|
231
|
+
i = 1
|
|
232
|
+
while i < end:
|
|
233
|
+
raw = lines[i]
|
|
234
|
+
stripped = raw.strip()
|
|
235
|
+
if not stripped or stripped.startswith("#"):
|
|
236
|
+
i += 1
|
|
237
|
+
continue
|
|
238
|
+
|
|
239
|
+
indent = len(raw) - len(raw.lstrip(" \t"))
|
|
240
|
+
m = re.match(r"^([A-Za-z0-9_][A-Za-z0-9_.\-]*)\s*:\s*(.*)$", stripped)
|
|
241
|
+
if not m:
|
|
242
|
+
i += 1
|
|
243
|
+
continue
|
|
244
|
+
|
|
245
|
+
key, value = m.group(1), m.group(2).strip()
|
|
246
|
+
if value == "" and indent == 0:
|
|
247
|
+
# 进入嵌套块(例如 metadata:)
|
|
248
|
+
current = {}
|
|
249
|
+
data[key] = current
|
|
250
|
+
elif value[:1] in ("|", ">"):
|
|
251
|
+
# 块标量
|
|
252
|
+
block = []
|
|
253
|
+
j = i + 1
|
|
254
|
+
while j < end:
|
|
255
|
+
nxt = lines[j]
|
|
256
|
+
nindent = len(nxt) - len(nxt.lstrip(" \t"))
|
|
257
|
+
if nxt.strip() and nindent <= indent:
|
|
258
|
+
break
|
|
259
|
+
block.append(nxt.strip())
|
|
260
|
+
j += 1
|
|
261
|
+
sep = "\n" if value.startswith("|") else " "
|
|
262
|
+
joined = sep.join(block).strip()
|
|
263
|
+
if indent == 0:
|
|
264
|
+
data[key] = joined
|
|
265
|
+
current = data
|
|
266
|
+
else:
|
|
267
|
+
current[key] = joined
|
|
268
|
+
i = j
|
|
269
|
+
continue
|
|
270
|
+
else:
|
|
271
|
+
parsed = unquote(value)
|
|
272
|
+
if indent == 0:
|
|
273
|
+
data[key] = parsed
|
|
274
|
+
current = data
|
|
275
|
+
else:
|
|
276
|
+
current[key] = parsed
|
|
277
|
+
i += 1
|
|
278
|
+
|
|
279
|
+
body = "\n".join(lines[end + 1:])
|
|
280
|
+
return data, body, end + 1, None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# ---------------------------------------------------------------- 各项检查
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def check_frontmatter(ctx: Ctx) -> CheckResult:
|
|
287
|
+
r = CheckResult(1, "frontmatter")
|
|
288
|
+
if ctx.fm_error:
|
|
289
|
+
r.defects.append(f"SKILL.md: {ctx.fm_error}")
|
|
290
|
+
return r
|
|
291
|
+
|
|
292
|
+
fm = ctx.fm or {}
|
|
293
|
+
name = fm.get("name")
|
|
294
|
+
desc = fm.get("description")
|
|
295
|
+
meta = fm.get("metadata") if isinstance(fm.get("metadata"), dict) else {}
|
|
296
|
+
ver = meta.get("version")
|
|
297
|
+
|
|
298
|
+
if not isinstance(name, str) or not name.strip():
|
|
299
|
+
r.defects.append("frontmatter 缺少 name")
|
|
300
|
+
name = ""
|
|
301
|
+
else:
|
|
302
|
+
name = name.strip().rstrip("/")
|
|
303
|
+
if name != ctx.root.name:
|
|
304
|
+
msg = (f"frontmatter name='{name}' 与目录名 '{ctx.root.name}' 不符")
|
|
305
|
+
if ctx.allow_dirname_mismatch:
|
|
306
|
+
r.warnings.append(msg + "(--allow-dirname-mismatch 已放开:只用于验证被改名的副本)")
|
|
307
|
+
else:
|
|
308
|
+
r.defects.append(msg)
|
|
309
|
+
|
|
310
|
+
if not isinstance(desc, str) or not desc.strip():
|
|
311
|
+
r.defects.append("frontmatter 缺少 description")
|
|
312
|
+
elif len(desc) > 1024:
|
|
313
|
+
r.defects.append(f"description 长度 {len(desc)} 字符 > 上限 1024")
|
|
314
|
+
|
|
315
|
+
if not isinstance(ver, str) or not ver.strip():
|
|
316
|
+
r.defects.append("frontmatter 缺少 metadata.version")
|
|
317
|
+
ver = ""
|
|
318
|
+
|
|
319
|
+
if not r.defects:
|
|
320
|
+
r.details.append(
|
|
321
|
+
f"name={name} · description={len(desc)} 字符(上限 1024) · metadata.version={ver}"
|
|
322
|
+
)
|
|
323
|
+
return r
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def parse_manifest_version(manifest_text) -> str | None:
|
|
327
|
+
if not manifest_text:
|
|
328
|
+
return None
|
|
329
|
+
m = re.search(r"(?m)^version\s*:\s*['\"]?(\d+\.\d+\.\d+)", manifest_text)
|
|
330
|
+
return m.group(1) if m else None
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def check_version_consistency(ctx: Ctx) -> CheckResult:
|
|
334
|
+
r = CheckResult(2, "版本一致")
|
|
335
|
+
values = {}
|
|
336
|
+
|
|
337
|
+
if ctx.fm and isinstance(ctx.fm.get("metadata"), dict):
|
|
338
|
+
v = ctx.fm["metadata"].get("version")
|
|
339
|
+
values["SKILL.md metadata.version"] = str(v).strip() if v else None
|
|
340
|
+
else:
|
|
341
|
+
values["SKILL.md metadata.version"] = None
|
|
342
|
+
|
|
343
|
+
values["manifest.yaml version"] = parse_manifest_version(ctx.manifest_text)
|
|
344
|
+
|
|
345
|
+
readme_notes = {}
|
|
346
|
+
for doc in ("README.md", "README_EN.md"):
|
|
347
|
+
path = ctx.root / doc
|
|
348
|
+
if not path.is_file():
|
|
349
|
+
values[doc] = None
|
|
350
|
+
continue
|
|
351
|
+
text = read_text(path)
|
|
352
|
+
if text is None:
|
|
353
|
+
values[doc] = None
|
|
354
|
+
continue
|
|
355
|
+
tokens = extract_versions(text)
|
|
356
|
+
if not tokens:
|
|
357
|
+
values[doc] = None
|
|
358
|
+
continue
|
|
359
|
+
best = max(tokens, key=version_key)
|
|
360
|
+
values[doc] = best
|
|
361
|
+
readme_notes[doc] = len(set(tokens))
|
|
362
|
+
|
|
363
|
+
missing = [key for key, val in values.items() if not val]
|
|
364
|
+
if missing:
|
|
365
|
+
r.defects.append("缺少版本号: " + "、".join(missing))
|
|
366
|
+
|
|
367
|
+
present = {key: val for key, val in values.items() if val}
|
|
368
|
+
if len(set(present.values())) > 1:
|
|
369
|
+
r.defects.append(
|
|
370
|
+
"版本不一致: " + ", ".join(f"{key}={values[key]}" for key in values)
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
if not r.defects:
|
|
374
|
+
r.details.append("一致: " + "、".join(f"{key}={val}" for key, val in values.items()))
|
|
375
|
+
for doc, count in readme_notes.items():
|
|
376
|
+
if count > 1:
|
|
377
|
+
r.details.append(
|
|
378
|
+
f"{doc} 文内另有 {count - 1} 个更旧的版本号(变更记录),不计入"
|
|
379
|
+
)
|
|
380
|
+
return r
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def parse_always_load(manifest_text):
|
|
384
|
+
"""解析 manifest.yaml 的 always_load 列表(只取 `- ` 条目)。"""
|
|
385
|
+
if not manifest_text:
|
|
386
|
+
return []
|
|
387
|
+
items = []
|
|
388
|
+
in_block = False
|
|
389
|
+
for line in manifest_text.splitlines():
|
|
390
|
+
if re.match(r"^always_load\s*:\s*$", line):
|
|
391
|
+
in_block = True
|
|
392
|
+
continue
|
|
393
|
+
if not in_block:
|
|
394
|
+
continue
|
|
395
|
+
if not line.strip():
|
|
396
|
+
continue
|
|
397
|
+
stripped = line.lstrip()
|
|
398
|
+
if stripped.startswith("- "):
|
|
399
|
+
item = unquote(stripped[2:].strip())
|
|
400
|
+
if item:
|
|
401
|
+
items.append(item)
|
|
402
|
+
continue
|
|
403
|
+
if not line[0].isspace():
|
|
404
|
+
break
|
|
405
|
+
return items
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def resolve_declared(root: Path, rel: str):
|
|
409
|
+
"""把声明里的相对路径落到实体:先按原样,找不到且无扩展名时按「同 stem + 任意扩展名」唯一匹配。"""
|
|
410
|
+
p = root / rel
|
|
411
|
+
if p.is_file() or p.is_dir():
|
|
412
|
+
return p
|
|
413
|
+
last = rel.rsplit("/", 1)[-1]
|
|
414
|
+
if "." not in last:
|
|
415
|
+
hits = sorted(p.parent.glob(last + ".*"))
|
|
416
|
+
if len(hits) == 1:
|
|
417
|
+
return hits[0]
|
|
418
|
+
return None
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def parse_fragment_groups(manifest_text):
|
|
422
|
+
"""从 manifest 的 axes.values 抽出片段,按轴分组:{轴名: [片段相对路径, ...]}。"""
|
|
423
|
+
groups = {}
|
|
424
|
+
if not manifest_text:
|
|
425
|
+
return groups
|
|
426
|
+
for line in manifest_text.splitlines():
|
|
427
|
+
m = re.match(
|
|
428
|
+
r"^\s+[A-Za-z_][\w-]*:\s+(static/fragments/([A-Za-z0-9_.\-]+)/[A-Za-z0-9_.\-]+\.md)\s*$",
|
|
429
|
+
line,
|
|
430
|
+
)
|
|
431
|
+
if m:
|
|
432
|
+
groups.setdefault(m.group(2), []).append(m.group(1))
|
|
433
|
+
return groups
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def check_declared_assets(ctx: Ctx) -> CheckResult:
|
|
437
|
+
r = CheckResult(3, "声明资产存在")
|
|
438
|
+
checked = 0
|
|
439
|
+
seen = set()
|
|
440
|
+
|
|
441
|
+
def scan(text, label, line_offset):
|
|
442
|
+
nonlocal checked
|
|
443
|
+
for lineno, line in enumerate(text.splitlines(), 1):
|
|
444
|
+
for m in PATH_TOKEN_RE.finditer(line):
|
|
445
|
+
kind_token = classify_token(m.group(1))
|
|
446
|
+
if not kind_token:
|
|
447
|
+
continue
|
|
448
|
+
kind, token = kind_token
|
|
449
|
+
checked += 1
|
|
450
|
+
if exists_with_kind(ctx.root, kind, token):
|
|
451
|
+
continue
|
|
452
|
+
if label == "manifest.yaml":
|
|
453
|
+
where = f"manifest.yaml:{lineno}"
|
|
454
|
+
else:
|
|
455
|
+
file_lineno = line_offset + lineno
|
|
456
|
+
where = f"SKILL.md:{file_lineno}"
|
|
457
|
+
key = (where, token)
|
|
458
|
+
if key in seen:
|
|
459
|
+
continue
|
|
460
|
+
seen.add(key)
|
|
461
|
+
r.defects.append(f"{where} → {token}")
|
|
462
|
+
|
|
463
|
+
if ctx.manifest_text is None:
|
|
464
|
+
r.defects.append("manifest.yaml 缺失,无法核对声明资产")
|
|
465
|
+
else:
|
|
466
|
+
scan(ctx.manifest_text, "manifest.yaml", 0)
|
|
467
|
+
|
|
468
|
+
if ctx.body:
|
|
469
|
+
scan(ctx.body, "SKILL.md", ctx.body_line_offset)
|
|
470
|
+
|
|
471
|
+
# v1.2.1:结构化的脚本声明必须落到实体。以前只认「前缀 + 带扩展名」的路径 token,
|
|
472
|
+
# 写成 `scripts/check_skill`(无扩展名)就整条逃检 —— 与 manifest 的
|
|
473
|
+
# missing_asset_policy「declared 缺失即 DEFECT」相冲突(R2 的 M6 实测)。
|
|
474
|
+
tool_scripts = []
|
|
475
|
+
if ctx.manifest_text:
|
|
476
|
+
for m in QUALITY_TOOL_SCRIPT_RE.finditer(ctx.manifest_text):
|
|
477
|
+
rel = m.group(1).strip().rstrip(",;")
|
|
478
|
+
tool_scripts.append(rel)
|
|
479
|
+
if resolve_declared(ctx.root, rel) is None:
|
|
480
|
+
r.defects.append(
|
|
481
|
+
f"manifest.yaml quality_tools → {rel}(找不到实体;无扩展名的声明也必须有对应文件)"
|
|
482
|
+
)
|
|
483
|
+
else:
|
|
484
|
+
checked += 1
|
|
485
|
+
|
|
486
|
+
for rel in parse_always_load(ctx.manifest_text):
|
|
487
|
+
if resolve_declared(ctx.root, rel) is None:
|
|
488
|
+
r.defects.append(f"manifest.yaml always_load → {rel}(找不到实体)")
|
|
489
|
+
|
|
490
|
+
# v1.2.1:写死「两个脚本 / 两个质量工具」这类计数会随实体变化腐化。
|
|
491
|
+
if len(tool_scripts) and len(tool_scripts) != 2:
|
|
492
|
+
# v1.2.2:以前只扫三份"入口"文档,references/ 里同一条旧措辞就逃过了检查(复核人实抓)。
|
|
493
|
+
# 规则要么全包生效、要么等于没有——所以扫包内所有 .md。
|
|
494
|
+
docs = sorted(
|
|
495
|
+
p for p in ctx.root.rglob("*.md")
|
|
496
|
+
if "__pycache__" not in p.parts and p.is_file()
|
|
497
|
+
)
|
|
498
|
+
for path in docs:
|
|
499
|
+
text = read_text(path)
|
|
500
|
+
if text is None:
|
|
501
|
+
# v1.3.0(P-15-5):以前这里静默 continue —— 一个 GBK/UTF-16 的 .md
|
|
502
|
+
# 就能让「陈旧计数措辞」这条规则对它永不生效(复核人实测逃检)。
|
|
503
|
+
r.defects.append(
|
|
504
|
+
path.relative_to(ctx.root).as_posix()
|
|
505
|
+
+ " 不是 UTF-8 文本,读不出来 —— 陈旧措辞扫描对它没有生效"
|
|
506
|
+
"(GBK/UTF-16 会静默逃过;请统一转成 UTF-8)"
|
|
507
|
+
)
|
|
508
|
+
continue
|
|
509
|
+
doc = path.relative_to(ctx.root).as_posix()
|
|
510
|
+
for lineno, line in enumerate(text.splitlines(), 1):
|
|
511
|
+
for phrase in STALE_TWO_SCRIPTS_PHRASES:
|
|
512
|
+
if phrase in line:
|
|
513
|
+
r.defects.append(
|
|
514
|
+
f"{doc}:{lineno} 写「{phrase}」,但 manifest 声明了 {len(tool_scripts)} 个脚本"
|
|
515
|
+
"(计数已腐化:改成指向 manifest.yaml 的 quality_tools,不要写死个数)"
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
if not r.defects:
|
|
519
|
+
r.details.append(f"全部存在(核对 {checked} 处声明)")
|
|
520
|
+
return r
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def check_forbidden_names(ctx: Ctx) -> CheckResult:
|
|
524
|
+
r = CheckResult(4, "不随包分发文件名")
|
|
525
|
+
hits = 0
|
|
526
|
+
for doc in ("SKILL.md", "README.md", "README_EN.md", "manifest.yaml"):
|
|
527
|
+
path = ctx.root / doc
|
|
528
|
+
if not path.is_file():
|
|
529
|
+
continue
|
|
530
|
+
text = read_text(path)
|
|
531
|
+
if text is None:
|
|
532
|
+
# v1.3.0(P-15-5):同样不许静默跳过
|
|
533
|
+
r.defects.append(
|
|
534
|
+
doc + " 不是 UTF-8 文本,读不出来 —— 禁名检查对它没有生效"
|
|
535
|
+
"(GBK/UTF-16 会静默逃过;请统一转成 UTF-8)"
|
|
536
|
+
)
|
|
537
|
+
continue
|
|
538
|
+
for lineno, line in enumerate(text.splitlines(), 1):
|
|
539
|
+
for name in FORBIDDEN_FILENAMES:
|
|
540
|
+
if name in line:
|
|
541
|
+
hits += 1
|
|
542
|
+
r.defects.append(f"{doc}:{lineno} 出现「{name}」")
|
|
543
|
+
if not hits:
|
|
544
|
+
r.details.append(
|
|
545
|
+
"入口文档均未出现: " + "、".join(FORBIDDEN_FILENAMES)
|
|
546
|
+
)
|
|
547
|
+
return r
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def check_budget(ctx: Ctx) -> CheckResult:
|
|
551
|
+
r = CheckResult(5, "上下文预算")
|
|
552
|
+
skill_tokens = estimate_tokens(ctx.skill_text)
|
|
553
|
+
skill_lines = len(ctx.skill_text.splitlines())
|
|
554
|
+
files = [{"path": "SKILL.md", "lines": skill_lines, "tokens": skill_tokens}]
|
|
555
|
+
warnings = []
|
|
556
|
+
|
|
557
|
+
if skill_tokens > TOKEN_LIMIT_SKILL_MD:
|
|
558
|
+
# v1.2.0:入口正文改成硬上限。理由:入口每个 token 都挤掉真实工作的上下文,
|
|
559
|
+
# 它涨上去没人拦,实际后果是"加载一个 skill 就吃掉几 K 预算"。下沉到 references/README 即可。
|
|
560
|
+
r.defects.append(
|
|
561
|
+
f"SKILL.md 估算 {skill_tokens} tokens > 硬上限 {TOKEN_LIMIT_SKILL_MD}"
|
|
562
|
+
"(把细节下沉到 references/ 或 README.md;入口只留路由与不可协商项)"
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
always_total = 0
|
|
566
|
+
always_missing = []
|
|
567
|
+
for rel in parse_always_load(ctx.manifest_text):
|
|
568
|
+
path = ctx.root / rel
|
|
569
|
+
if not path.is_file():
|
|
570
|
+
always_missing.append(rel)
|
|
571
|
+
continue
|
|
572
|
+
text = read_text(path)
|
|
573
|
+
if text is None:
|
|
574
|
+
always_missing.append(rel)
|
|
575
|
+
continue
|
|
576
|
+
tokens = estimate_tokens(text)
|
|
577
|
+
always_total += tokens
|
|
578
|
+
files.append({"path": rel, "lines": len(text.splitlines()), "tokens": tokens})
|
|
579
|
+
|
|
580
|
+
total = skill_tokens + always_total
|
|
581
|
+
groups = parse_fragment_groups(ctx.manifest_text)
|
|
582
|
+
per_run = total
|
|
583
|
+
per_run_parts = []
|
|
584
|
+
for axis in sorted(groups):
|
|
585
|
+
best = None
|
|
586
|
+
for rel in groups[axis]:
|
|
587
|
+
text = read_text(ctx.root / rel)
|
|
588
|
+
if text is None:
|
|
589
|
+
r.defects.append(f"manifest.yaml 轴片段 → {rel}(找不到实体)")
|
|
590
|
+
continue
|
|
591
|
+
tokens = estimate_tokens(text)
|
|
592
|
+
if best is None or tokens > best[1]:
|
|
593
|
+
best = (rel, tokens, len(text.splitlines()))
|
|
594
|
+
if best:
|
|
595
|
+
per_run += best[1]
|
|
596
|
+
files.append(
|
|
597
|
+
{"path": f"{best[0]} [{axis} 轴最大]", "lines": best[2], "tokens": best[1]}
|
|
598
|
+
)
|
|
599
|
+
per_run_parts.append(f"{axis}={best[1]}")
|
|
600
|
+
if per_run > TOKEN_LIMIT_PER_RUN_DEFECT:
|
|
601
|
+
r.defects.append(
|
|
602
|
+
f"单次开工实际加载(SKILL.md + always_load + 每轴最大片段)估算 {per_run} tokens"
|
|
603
|
+
f" > 硬上限 {TOKEN_LIMIT_PER_RUN_DEFECT}(片段膨胀同样挤占真实工作上下文)"
|
|
604
|
+
)
|
|
605
|
+
elif per_run > TOKEN_LIMIT_PER_RUN_WARN:
|
|
606
|
+
warnings.append(
|
|
607
|
+
f"单次开工实际加载估算 {per_run} tokens > 警戒 {TOKEN_LIMIT_PER_RUN_WARN}"
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
if total > TOKEN_LIMIT_ALWAYS_LOAD:
|
|
611
|
+
warnings.append(
|
|
612
|
+
f"SKILL.md + always_load 合计 {total} tokens > 上限 {TOKEN_LIMIT_ALWAYS_LOAD}"
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
r.details.append("文件明细(行数 / 估算 tokens;SKILL.md 含 frontmatter,保守口径):")
|
|
616
|
+
for item in files:
|
|
617
|
+
r.details.append(f"{item['path']} {item['lines']} 行 {item['tokens']} tokens")
|
|
618
|
+
r.details.append(
|
|
619
|
+
f"合计: SKILL.md {skill_tokens} + always_load {always_total} = {total} tokens"
|
|
620
|
+
f"(上限 {TOKEN_LIMIT_SKILL_MD} / {TOKEN_LIMIT_ALWAYS_LOAD})"
|
|
621
|
+
)
|
|
622
|
+
if per_run_parts:
|
|
623
|
+
r.details.append(
|
|
624
|
+
"单次开工实际加载: %d tokens"
|
|
625
|
+
"(+ 每轴最大片段 %s;警戒 %d / 硬上限 %d)"
|
|
626
|
+
% (per_run, "、".join(per_run_parts), TOKEN_LIMIT_PER_RUN_WARN, TOKEN_LIMIT_PER_RUN_DEFECT)
|
|
627
|
+
)
|
|
628
|
+
if always_missing:
|
|
629
|
+
r.details.append("always_load 缺失,未计入: " + "、".join(always_missing))
|
|
630
|
+
if not warnings:
|
|
631
|
+
r.details.insert(0, "预算内")
|
|
632
|
+
|
|
633
|
+
r.warnings.extend(warnings)
|
|
634
|
+
ctx.budget = {
|
|
635
|
+
"skill_md_tokens": skill_tokens,
|
|
636
|
+
"always_load_tokens": always_total,
|
|
637
|
+
"total_tokens": total,
|
|
638
|
+
"skill_md_limit": TOKEN_LIMIT_SKILL_MD,
|
|
639
|
+
"total_limit": TOKEN_LIMIT_ALWAYS_LOAD,
|
|
640
|
+
"per_run_tokens": per_run,
|
|
641
|
+
"per_run_limit_warn": TOKEN_LIMIT_PER_RUN_WARN,
|
|
642
|
+
"per_run_limit_defect": TOKEN_LIMIT_PER_RUN_DEFECT,
|
|
643
|
+
"files": files,
|
|
644
|
+
}
|
|
645
|
+
return r
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def check_evals(ctx: Ctx) -> CheckResult:
|
|
649
|
+
r = CheckResult(6, "evals 可读")
|
|
650
|
+
path = ctx.root / "evals" / "evals.json"
|
|
651
|
+
if not path.is_file():
|
|
652
|
+
r.defects.append("evals/evals.json 缺失")
|
|
653
|
+
return r
|
|
654
|
+
|
|
655
|
+
text = read_text(path)
|
|
656
|
+
if text is None:
|
|
657
|
+
r.defects.append("evals/evals.json 无法按 UTF-8 读取")
|
|
658
|
+
return r
|
|
659
|
+
try:
|
|
660
|
+
data = json.loads(text)
|
|
661
|
+
except json.JSONDecodeError as exc:
|
|
662
|
+
r.defects.append(f"evals/evals.json 不是合法 JSON: {exc}")
|
|
663
|
+
return r
|
|
664
|
+
|
|
665
|
+
if not isinstance(data, dict):
|
|
666
|
+
r.defects.append("evals/evals.json 顶层不是 JSON 对象")
|
|
667
|
+
return r
|
|
668
|
+
|
|
669
|
+
cases = data.get("evals")
|
|
670
|
+
if not isinstance(cases, list):
|
|
671
|
+
r.defects.append("evals/evals.json 顶层缺少 evals 数组")
|
|
672
|
+
return r
|
|
673
|
+
|
|
674
|
+
seen = set()
|
|
675
|
+
for idx, case in enumerate(cases, 1):
|
|
676
|
+
if not isinstance(case, dict):
|
|
677
|
+
r.defects.append(f"case #{idx} 不是 JSON 对象")
|
|
678
|
+
continue
|
|
679
|
+
for field_name in ("id", "prompt", "expected_output"):
|
|
680
|
+
value = case.get(field_name)
|
|
681
|
+
if not isinstance(value, str) or not value.strip():
|
|
682
|
+
r.defects.append(
|
|
683
|
+
f"case #{idx}(id={case.get('id')!r})缺少或为空: {field_name}"
|
|
684
|
+
)
|
|
685
|
+
cid = case.get("id")
|
|
686
|
+
if isinstance(cid, str) and cid.strip():
|
|
687
|
+
if cid in seen:
|
|
688
|
+
r.defects.append(f"case id 重复: {cid}")
|
|
689
|
+
seen.add(cid)
|
|
690
|
+
|
|
691
|
+
if not r.defects:
|
|
692
|
+
r.details.append(f"{len(cases)} 个用例,id 唯一,字段齐全")
|
|
693
|
+
return r
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _yaml_suspicion(text: str):
|
|
697
|
+
"""没有 PyYAML 时的保守启发式:找出「父键是 plain scalar、子行却像 key: value」的断行。
|
|
698
|
+
|
|
699
|
+
这一族错误本包已犯两次(都是把带冒号的说明写成续行),而当时 PyYAML 恰好又不在
|
|
700
|
+
运行环境里,于是没有任何检查能抓到。所以即使装了 PyYAML 也保留这条兜底。
|
|
701
|
+
"""
|
|
702
|
+
lines = text.splitlines()
|
|
703
|
+
hits = []
|
|
704
|
+
for idx, line in enumerate(lines):
|
|
705
|
+
if not line.strip() or line.lstrip().startswith("#"):
|
|
706
|
+
continue
|
|
707
|
+
indent = len(line) - len(line.lstrip())
|
|
708
|
+
if indent < 4:
|
|
709
|
+
continue
|
|
710
|
+
# 找最近的、缩进更小的非空父行
|
|
711
|
+
parent = None
|
|
712
|
+
for j in range(idx - 1, -1, -1):
|
|
713
|
+
pl = lines[j]
|
|
714
|
+
if not pl.strip() or pl.lstrip().startswith("#"):
|
|
715
|
+
continue
|
|
716
|
+
if len(pl) - len(pl.lstrip()) < indent:
|
|
717
|
+
parent = pl.rstrip()
|
|
718
|
+
break
|
|
719
|
+
if parent is None:
|
|
720
|
+
continue
|
|
721
|
+
if parent.lstrip().startswith("- "):
|
|
722
|
+
continue # 序列项(- key: value)的子键,合法
|
|
723
|
+
if parent.endswith(":") or parent.endswith((">-", "|", "|-", ">", "|+")):
|
|
724
|
+
continue # 容器或块标量,子行合法
|
|
725
|
+
m = re.match(r"^\s*([A-Za-z_][\w .\-]{0,40}):\s+\S", line)
|
|
726
|
+
if m:
|
|
727
|
+
hits.append((idx + 1, line.strip()[:70]))
|
|
728
|
+
return hits
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def _duplicate_top_level_keys(text):
|
|
732
|
+
"""返回重复的顶层键名列表(PyYAML 会用后者静默覆盖前者,不报错)。"""
|
|
733
|
+
seen = {}
|
|
734
|
+
for line in text.splitlines():
|
|
735
|
+
if not line or line[0] in (" ", "\t", "#", "-"):
|
|
736
|
+
continue
|
|
737
|
+
match = re.match(r"^([A-Za-z_][\w-]*)\s*:", line)
|
|
738
|
+
if match is None:
|
|
739
|
+
continue
|
|
740
|
+
seen[match.group(1)] = seen.get(match.group(1), 0) + 1
|
|
741
|
+
return sorted(key for key, count in seen.items() if count > 1)
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def check_manifest_syntax(ctx: Ctx) -> CheckResult:
|
|
745
|
+
r = CheckResult(8, "manifest 语法")
|
|
746
|
+
if ctx.manifest_text is None:
|
|
747
|
+
r.defects.append("manifest.yaml 缺失或无法按 UTF-8 读取 —— 后面几项检查都失去依据")
|
|
748
|
+
return r
|
|
749
|
+
duplicates = _duplicate_top_level_keys(ctx.manifest_text)
|
|
750
|
+
for key in duplicates:
|
|
751
|
+
r.defects.append(
|
|
752
|
+
"manifest.yaml 顶层键 %r 出现多次 —— YAML 解析时后者会静默覆盖前者" % key
|
|
753
|
+
)
|
|
754
|
+
try:
|
|
755
|
+
import yaml # type: ignore
|
|
756
|
+
except Exception:
|
|
757
|
+
hits = _yaml_suspicion(ctx.manifest_text)
|
|
758
|
+
for line_no, snippet in hits:
|
|
759
|
+
r.defects.append(
|
|
760
|
+
"疑似 YAML 断行(父键是 plain scalar,续行却含 'key: ')第 %d 行:%s"
|
|
761
|
+
" —— 本机没有 PyYAML,用的是保守启发式;装 PyYAML 后应复核" % (line_no, snippet)
|
|
762
|
+
)
|
|
763
|
+
if not hits:
|
|
764
|
+
r.details.append("本机无 PyYAML,仅做保守启发式检查(未发现断行)")
|
|
765
|
+
return r
|
|
766
|
+
try:
|
|
767
|
+
data = yaml.safe_load(ctx.manifest_text)
|
|
768
|
+
except Exception as exc: # noqa: BLE001 - 报告原始解析错误最有用
|
|
769
|
+
r.defects.append("manifest.yaml 不是合法 YAML:%s" % str(exc).replace("\n", " "))
|
|
770
|
+
return r
|
|
771
|
+
if not isinstance(data, dict):
|
|
772
|
+
r.defects.append("manifest.yaml 顶层不是映射(YAML 解析得到 %s)" % type(data).__name__)
|
|
773
|
+
return r
|
|
774
|
+
hits = _yaml_suspicion(ctx.manifest_text)
|
|
775
|
+
for line_no, snippet in hits:
|
|
776
|
+
r.defects.append("疑似 YAML 断行(PyYAML 能过但语义多半不对)第 %d 行:%s" % (line_no, snippet))
|
|
777
|
+
r.details.append("PyYAML 解析通过,顶层键 %d 个" % len(data))
|
|
778
|
+
return r
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def check_package_completeness(ctx: Ctx) -> CheckResult:
|
|
782
|
+
r = CheckResult(7, "包完整性")
|
|
783
|
+
for rel in REQUIRED_PATHS:
|
|
784
|
+
path = ctx.root / rel
|
|
785
|
+
ok = path.is_dir() if rel.endswith("/") else path.is_file()
|
|
786
|
+
if not ok:
|
|
787
|
+
r.defects.append(f"缺失: {rel}")
|
|
788
|
+
if not r.defects:
|
|
789
|
+
r.details.append(f"{len(REQUIRED_PATHS)} 项齐全")
|
|
790
|
+
return r
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
# ---------------------------------------------------------------- 输出
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def emit_fatal(root: Path, reason: str, as_json: bool) -> int:
|
|
797
|
+
if as_json:
|
|
798
|
+
payload = {
|
|
799
|
+
"ok": False,
|
|
800
|
+
"defects": [],
|
|
801
|
+
"warnings": [],
|
|
802
|
+
"budget": {},
|
|
803
|
+
"checks": [],
|
|
804
|
+
"root": str(root),
|
|
805
|
+
"error": reason,
|
|
806
|
+
"exit_code": 2,
|
|
807
|
+
}
|
|
808
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
809
|
+
else:
|
|
810
|
+
print(f"SKILL CHECK · {root}")
|
|
811
|
+
print(f"[x] 无法执行:{reason}")
|
|
812
|
+
print("结论:未执行(exit 2)")
|
|
813
|
+
return 2
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def print_report(root: Path, results) -> int:
|
|
817
|
+
defects = [d for r in results for d in r.defects]
|
|
818
|
+
warnings = [w for r in results for w in r.warnings]
|
|
819
|
+
ok = not defects
|
|
820
|
+
exit_code = 0 if ok else 1
|
|
821
|
+
|
|
822
|
+
print(f"SKILL CHECK · {root}")
|
|
823
|
+
for r in results:
|
|
824
|
+
print(f"[{r.number}/{len(results)}] {r.title} {TAGS[r.status]}")
|
|
825
|
+
for item in r.details:
|
|
826
|
+
print(f" - {item}")
|
|
827
|
+
for item in r.defects:
|
|
828
|
+
print(f" [x] {item}")
|
|
829
|
+
for item in r.warnings:
|
|
830
|
+
print(f" [!] {item}")
|
|
831
|
+
print(f"缺陷 {len(defects)} 项,警告 {len(warnings)} 项")
|
|
832
|
+
print(f"结论:{'通过' if ok else '有缺陷'}(exit {exit_code})")
|
|
833
|
+
return exit_code
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def build_payload(root: Path, results, exit_code: int, error=None):
|
|
837
|
+
defects = [d for r in results for d in r.defects]
|
|
838
|
+
warnings = [w for r in results for w in r.warnings]
|
|
839
|
+
budget = {}
|
|
840
|
+
for r in results:
|
|
841
|
+
if r.number == 5 and getattr(r, "_budget", None):
|
|
842
|
+
budget = r._budget
|
|
843
|
+
return {
|
|
844
|
+
"ok": not defects and error is None,
|
|
845
|
+
"defects": defects,
|
|
846
|
+
"warnings": warnings,
|
|
847
|
+
"budget": budget,
|
|
848
|
+
"checks": [
|
|
849
|
+
{
|
|
850
|
+
"id": r.number,
|
|
851
|
+
"title": r.title,
|
|
852
|
+
"status": r.status,
|
|
853
|
+
"details": r.details,
|
|
854
|
+
"defects": r.defects,
|
|
855
|
+
"warnings": r.warnings,
|
|
856
|
+
}
|
|
857
|
+
for r in results
|
|
858
|
+
],
|
|
859
|
+
"root": str(root),
|
|
860
|
+
"exit_code": exit_code,
|
|
861
|
+
"error": error,
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
# ---------------------------------------------------------------- main
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
def run(root: Path, as_json: bool, allow_dirname_mismatch: bool = False) -> int:
|
|
869
|
+
skill_path = root / "SKILL.md"
|
|
870
|
+
if not root.is_dir():
|
|
871
|
+
return emit_fatal(root, f"包目录不存在: {root}", as_json)
|
|
872
|
+
if not skill_path.is_file():
|
|
873
|
+
return emit_fatal(root, f"SKILL.md 缺失: {skill_path}", as_json)
|
|
874
|
+
|
|
875
|
+
skill_text = read_text(skill_path)
|
|
876
|
+
if skill_text is None:
|
|
877
|
+
return emit_fatal(root, f"SKILL.md 无法按 UTF-8 读取: {skill_path}", as_json)
|
|
878
|
+
|
|
879
|
+
manifest_path = root / "manifest.yaml"
|
|
880
|
+
manifest_text = read_text(manifest_path) if manifest_path.is_file() else None
|
|
881
|
+
|
|
882
|
+
fm, body, body_offset, fm_error = parse_frontmatter(skill_text)
|
|
883
|
+
ctx = Ctx(root, skill_text, manifest_text, fm, body, body_offset, fm_error,
|
|
884
|
+
allow_dirname_mismatch=allow_dirname_mismatch)
|
|
885
|
+
|
|
886
|
+
results = [
|
|
887
|
+
check_frontmatter(ctx),
|
|
888
|
+
check_version_consistency(ctx),
|
|
889
|
+
check_declared_assets(ctx),
|
|
890
|
+
check_forbidden_names(ctx),
|
|
891
|
+
check_budget(ctx),
|
|
892
|
+
check_evals(ctx),
|
|
893
|
+
check_package_completeness(ctx),
|
|
894
|
+
check_manifest_syntax(ctx),
|
|
895
|
+
]
|
|
896
|
+
# 预算结果挂到对应 CheckResult 上,供 --json 使用
|
|
897
|
+
results[4]._budget = ctx.budget
|
|
898
|
+
|
|
899
|
+
if not as_json:
|
|
900
|
+
return print_report(root, results)
|
|
901
|
+
|
|
902
|
+
exit_code = 0 if not any(r.defects for r in results) else 1
|
|
903
|
+
print(json.dumps(build_payload(root, results, exit_code), ensure_ascii=False, indent=2))
|
|
904
|
+
return exit_code
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def main(argv=None) -> int:
|
|
908
|
+
try:
|
|
909
|
+
sys.stdout.reconfigure(errors="backslashreplace")
|
|
910
|
+
except Exception: # pragma: no cover - 旧解释器/非常规 stdout
|
|
911
|
+
pass
|
|
912
|
+
|
|
913
|
+
parser = argparse.ArgumentParser(
|
|
914
|
+
description="project-dept skill 包静态自检器(只查机械可判的腐化)"
|
|
915
|
+
)
|
|
916
|
+
parser.add_argument(
|
|
917
|
+
"--root",
|
|
918
|
+
default=None,
|
|
919
|
+
help="包目录;缺省为脚本所在包(脚本上两级目录)",
|
|
920
|
+
)
|
|
921
|
+
parser.add_argument(
|
|
922
|
+
"--json",
|
|
923
|
+
action="store_true",
|
|
924
|
+
help="输出机器可读 JSON(stdout 上只有 JSON)",
|
|
925
|
+
)
|
|
926
|
+
parser.add_argument(
|
|
927
|
+
"--allow-dirname-mismatch",
|
|
928
|
+
action="store_true",
|
|
929
|
+
help="把「frontmatter name 与目录名不符」降级为警告(只用于验证被改名的副本;"
|
|
930
|
+
"正式包必须让目录名等于 name)",
|
|
931
|
+
)
|
|
932
|
+
args = parser.parse_args(argv)
|
|
933
|
+
|
|
934
|
+
if args.root:
|
|
935
|
+
root = Path(args.root).expanduser().resolve()
|
|
936
|
+
else:
|
|
937
|
+
root = Path(__file__).resolve().parent.parent
|
|
938
|
+
|
|
939
|
+
return run(root, args.json, args.allow_dirname_mismatch)
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
if __name__ == "__main__":
|
|
943
|
+
sys.exit(main())
|