dsh-harness-kit 0.0.0-stage → 0.1.0

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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -2
  3. package/README.zh-CN.md +278 -0
  4. package/client.js +1272 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/DETAIL.en.md +97 -0
  7. package/docs/DETAIL.md +73 -0
  8. package/docs/assets/ui-new-task.png +0 -0
  9. package/docs/assets/ui-onboarding.png +0 -0
  10. package/docs/assets/ui-war-room.png +0 -0
  11. package/icon.svg +7 -0
  12. package/index.js +49 -0
  13. package/kernel/advance.js +96 -0
  14. package/kernel/bindings.js +24 -0
  15. package/kernel/commands.js +927 -0
  16. package/kernel/env.js +64 -0
  17. package/kernel/exec.js +41 -0
  18. package/kernel/flows.js +89 -0
  19. package/kernel/guards.js +79 -0
  20. package/kernel/miniyaml.js +133 -0
  21. package/kernel/models.js +104 -0
  22. package/kernel/panel.js +1103 -0
  23. package/kernel/paths.js +53 -0
  24. package/kernel/roles.js +67 -0
  25. package/kernel/setup.js +644 -0
  26. package/kernel/state.js +59 -0
  27. package/kernel/steer.js +27 -0
  28. package/kernel/sync.js +140 -0
  29. package/kernel/te.js +122 -0
  30. package/kernel/worktree.js +868 -0
  31. package/locale/en.json +14 -0
  32. package/locale/zh.json +14 -0
  33. package/package.json +63 -4
  34. package/packs/ai-coding/agents/business-analyst.md +90 -0
  35. package/packs/ai-coding/agents/code-reviewer.md +156 -0
  36. package/packs/ai-coding/agents/developer.md +147 -0
  37. package/packs/ai-coding/agents/project-manager.md +190 -0
  38. package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
  39. package/packs/ai-coding/agents/solution-architect.md +122 -0
  40. package/packs/ai-coding/agents/test-engineer.md +230 -0
  41. package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
  42. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
  43. package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
  44. package/packs/ai-coding/assets/scripts/harness.py +38 -0
  45. package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
  46. package/packs/ai-coding/assets/scripts/lib.py +1011 -0
  47. package/packs/ai-coding/assets/scripts/run_field.py +295 -0
  48. package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
  49. package/packs/ai-coding/assets/scripts/update_board.py +524 -0
  50. package/packs/ai-coding/assets/scripts/verify.py +184 -0
  51. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
  52. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
  53. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
  54. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
  55. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
  56. package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
  57. package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
  58. package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
  59. package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
  60. package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
  61. package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
  62. package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
  63. package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
  64. package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
  65. package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
  66. package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
  67. package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
  68. package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
  69. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
  70. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
  71. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
  72. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
  73. package/packs/ai-coding/flows/_router.yml +14 -0
  74. package/packs/ai-coding/flows/bugfix.yml +37 -0
  75. package/packs/ai-coding/flows/fix.yml +44 -0
  76. package/packs/ai-coding/flows/init.yml +83 -0
  77. package/packs/ai-coding/flows/new.yml +29 -0
  78. package/packs/ai-coding/flows/quick.yml +40 -0
  79. package/packs/ai-coding/flows/refactor.yml +50 -0
  80. package/packs/ai-coding/flows/standard.yml +49 -0
  81. package/packs/ai-coding/rules/code-standards.md +30 -0
  82. package/packs/ai-coding/rules/core.md +83 -0
  83. package/packs/ai-coding/templates/bugfix.md +29 -0
  84. package/packs/ai-coding/templates/memory-entry.md +46 -0
  85. package/packs/ai-coding/templates/proposal.md +47 -0
  86. package/packs/ai-coding/templates/spec-template.md +34 -0
  87. package/screenshots.json +5 -0
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env python3
2
+ # .harness/scripts/run_field.py
3
+ # 执行子工程 .harness/build.json 声明的构建/启动字段(统一执行入口的 CLI 外壳)。
4
+ #
5
+ # 为什么要有这个脚本:Agent / Skill / 人**手敲** `mvn ...`、`npm ...` 时,
6
+ # 继承的是当前 shell 的 PATH —— 机器上装了多个 JDK 时大概率选中错的那个,
7
+ # 于是报出与被改代码无关的怪错。走这里 = 强制先按子工程声明的版本解析运行时。
8
+ #
9
+ # 用法:
10
+ # python3 .harness/scripts/run_field.py <子工程> <字段> # compile / test / package / package-incr
11
+ # python3 .harness/scripts/run_field.py <子工程> start # 启动并按判据判定,**不自动停止**
12
+ # python3 .harness/scripts/run_field.py <子工程> stop # 停止(人工显式执行)
13
+ # python3 .harness/scripts/run_field.py <子工程> compile --timeout 600
14
+ # python3 .harness/scripts/run_field.py --all compile # 所有子工程
15
+ #
16
+ # start 的判定依据全部由**子工程自己声明**(框架层不硬编码任何工程的启动日志串):
17
+ # build.json: { "start": "...", "start-ok": "<成功判据正则>", "start-timeout": 180, "start-port": 9778 }
18
+ # - 有 start-ok → 等日志命中该正则 = 启动成功
19
+ # - 无 start-ok → 只起不判,明确报「未验证」并非零退出(不制造凭空 PASS)
20
+ #
21
+ # ⚠️ start **不会自动停止服务**:判定完成后若为交互终端会询问「是否停止」,
22
+ # 非交互(Agent/hook)一律保持运行并打印停止指引,由人显式执行 stop。
23
+ import json, os, re, subprocess, sys, time
24
+ from pathlib import Path
25
+ import lib
26
+
27
+ FIELDS = ("compile", "test", "package", "package-incr", "start", "stop")
28
+ START_OK = "start-ok"
29
+ START_TIMEOUT = "start-timeout"
30
+ START_PORT = "start-port"
31
+ DEFAULT_START_TIMEOUT = 180
32
+ # 构建命令里的 `clean` 目标(作为独立 token 匹配,不误伤 -Dmaven.clean.skip 之类的参数值)
33
+ CLEAN_TOKEN = re.compile(r"(?:^|\s)clean(?:\s|$)")
34
+
35
+
36
+ def _usage():
37
+ print("用法: python3 .harness/scripts/run_field.py [--all] <子工程> <字段> [--timeout 秒]")
38
+ print("字段: " + " | ".join(FIELDS) + "(以子工程 build.json 实际声明为准)")
39
+ print(" start 的判据由 build.json 的 start-ok / start-timeout / start-port 声明")
40
+ return 2
41
+
42
+
43
+ def _logs_dir(name: str) -> Path:
44
+ """start 的日志与 pidfile 落在**仓库根**的 .harness/.logs/run/<子工程>/。
45
+
46
+ 刻意不写进 <子工程>/.harness/.logs/:子模块工作区只认**它自己的** .gitignore
47
+ (超项目的规则管不到子模块内部),日志会被当成未跟踪文件冒出来——还会污染
48
+ dev_gate 的「有改动才编译」判定。而进程生命周期本来就由 harness 拥有,不属子工程。
49
+ """
50
+ d = lib.repo_root() / ".harness" / ".logs" / "run" / name
51
+ d.mkdir(parents=True, exist_ok=True)
52
+ return d
53
+
54
+
55
+ def _pidfile(name: str) -> Path:
56
+ return _logs_dir(name) / "start.pid"
57
+
58
+
59
+ def _read_pidfile(name: str) -> dict:
60
+ try:
61
+ return json.loads(_pidfile(name).read_text(encoding="utf-8"))
62
+ except (OSError, json.JSONDecodeError):
63
+ return {}
64
+
65
+
66
+ def _say_run(name, pid, port, logfile):
67
+ print(f" PID : {pid}")
68
+ if port:
69
+ print(f" 端口 : {port}")
70
+ if logfile:
71
+ print(f" 日志 : {logfile}")
72
+ print(f" 停止 : python3 .harness/scripts/harness.py run-field {name} stop")
73
+
74
+
75
+ def _drain(logfile: Path, pos: int):
76
+ """读日志新增部分(返回 内容, 新偏移)。"""
77
+ try:
78
+ with open(logfile, "r", encoding="utf-8", errors="replace") as f:
79
+ f.seek(pos)
80
+ chunk = f.read()
81
+ return chunk, f.tell()
82
+ except OSError:
83
+ return "", pos
84
+
85
+
86
+ def _tail_until_match(logfile: Path, proc, ok_re, timeout):
87
+ """轮询日志:实时透传到终端 + 匹配成功判据。返回 (status, elapsed)。
88
+
89
+ status ∈ ok | exit | timeout。输出已实时透传,失败路径不必再重复打印尾行。
90
+ """
91
+ t0, pos = time.time(), 0
92
+ while True:
93
+ elapsed = time.time() - t0
94
+ chunk, pos = _drain(logfile, pos)
95
+ if chunk:
96
+ print(chunk, end="", flush=True)
97
+ if ok_re.search(chunk):
98
+ return "ok", elapsed
99
+ if proc.poll() is not None:
100
+ time.sleep(0.3) # 收尾:把剩余输出读干净
101
+ rest, pos = _drain(logfile, pos)
102
+ if rest:
103
+ print(rest, end="", flush=True)
104
+ return "exit", elapsed
105
+ if elapsed > timeout:
106
+ return "timeout", elapsed
107
+ time.sleep(0.2)
108
+
109
+
110
+ def _start(name, sp: Path, timeout):
111
+ cmd = lib.get_build_field(sp, "start")
112
+ if not cmd:
113
+ lib.c_warn(f"{name}: build.json 未声明 start,跳过")
114
+ return True
115
+ print(f"→ {name}: [start] $ {cmd}")
116
+ ok_re_src = lib.get_build_field(sp, START_OK)
117
+ port = lib.get_build_field(sp, START_PORT)
118
+ if timeout is None:
119
+ try:
120
+ timeout = int(lib.get_build_field(sp, START_TIMEOUT) or DEFAULT_START_TIMEOUT)
121
+ except ValueError:
122
+ timeout = DEFAULT_START_TIMEOUT
123
+ try:
124
+ ok_re = re.compile(ok_re_src) if ok_re_src else None
125
+ except re.error as e:
126
+ lib.c_fail(f"{name}: build.json 的 {START_OK} 不是合法正则: {e}")
127
+ return False
128
+
129
+ logfile = _logs_dir(name) / f"start-{time.strftime('%Y%m%d-%H%M%S')}.log"
130
+ try:
131
+ proc, _ = lib.spawn_build_field(sp, "start", log_path=logfile)
132
+ except lib.BuildEnvError as e:
133
+ lib.c_fail(str(e))
134
+ for m in e.missing:
135
+ print(f" → {m}")
136
+ return False
137
+ if proc is None:
138
+ lib.c_warn(f"{name}: start 命令为空,跳过")
139
+ return True
140
+ _pidfile(name).write_text(
141
+ json.dumps({"pid": proc.pid, "port": port, "log": str(logfile), "cmd": cmd},
142
+ ensure_ascii=False), encoding="utf-8")
143
+
144
+ if not ok_re:
145
+ # 无判据:只起不判。等一小会儿让启动输出落盘,再如实报「未验证」。
146
+ time.sleep(min(timeout, 20))
147
+ alive = proc.poll() is None
148
+ print(("\n".join(_drain(logfile, 0)[0].splitlines()[-15:])))
149
+ lib.c_fail(f"{name}: 未声明 {START_OK},**无法判定启动成功**"
150
+ f"(进程{'仍在运行' if alive else '已退出'},退出码 {proc.poll()})")
151
+ print(f" 这不是「启动失败」,是「未验证」——请在 <子工程>/.harness/build.json 声明 "
152
+ f'"{START_OK}": "<启动成功的日志判据>"')
153
+ _say_run(name, proc.pid, port, logfile)
154
+ return False
155
+
156
+ status, elapsed = _tail_until_match(logfile, proc, ok_re, timeout)
157
+ if status == "ok":
158
+ lib.c_pass(f"{name}: 启动成功({elapsed:.1f}s 命中判据 /{ok_re_src}/)")
159
+ elif status == "exit":
160
+ lib.c_fail(f"{name}: 进程提前退出({elapsed:.1f}s,未命中判据 /{ok_re_src}/)")
161
+ return False
162
+ else:
163
+ lib.c_fail(f"{name}: {timeout}s 内未命中判据 /{ok_re_src}/(进程仍在运行)")
164
+ _say_run(name, proc.pid, port, logfile)
165
+ return False
166
+
167
+ _say_run(name, proc.pid, port, logfile)
168
+
169
+ # ⚠️ 停止**永不自动**:交互终端里问一句,非交互一律留着。
170
+ if sys.stdin.isatty():
171
+ try:
172
+ ans = input(" 服务仍在运行 —— 现在停止吗?[y/N] ").strip().lower()
173
+ except (EOFError, KeyboardInterrupt):
174
+ ans = ""
175
+ if ans in ("y", "yes"):
176
+ if lib.stop_process(proc.pid):
177
+ lib.c_pass(f"{name}: 已停止(PID {proc.pid})")
178
+ _pidfile(name).unlink(missing_ok=True)
179
+ else:
180
+ lib.c_fail(f"{name}: 停止失败,请手动处理 PID {proc.pid}")
181
+ return False
182
+ else:
183
+ print(" 保持运行。需要时用上面的停止命令。")
184
+ else:
185
+ print(" ⚠️ 非交互环境:未停止服务(停止需人工确认)。")
186
+ return True
187
+
188
+
189
+ def _stop(name, sp: Path):
190
+ info = _read_pidfile(name)
191
+ pid = info.get("pid")
192
+ if not pid:
193
+ lib.c_warn(f"{name}: 无启动记录({_pidfile(name)}),无需停止")
194
+ return True
195
+ if not lib.process_alive(pid):
196
+ lib.c_warn(f"{name}: PID {pid} 已不在运行,清理记录")
197
+ _pidfile(name).unlink(missing_ok=True)
198
+ return True
199
+ print(f"→ {name}: 停止 PID {pid}({info.get('cmd', '')[:60]})")
200
+ if lib.stop_process(pid):
201
+ _pidfile(name).unlink(missing_ok=True)
202
+ lib.c_pass(f"{name}: 已停止")
203
+ return True
204
+ lib.c_fail(f"{name}: 停止失败,请手动处理 PID {pid}")
205
+ return False
206
+
207
+
208
+ def _warn_build_env(name, field, cmd):
209
+ """构建字段开跑前的**环境陷阱告警**(只提示,不阻断)。
210
+
211
+ 两类陷阱的共同点:**都不报错**,却让构建之后的一切验证结论失真——
212
+ 退出码 0 也说明不了「产物完整」或「跑的是新代码」。
213
+ 只告警不 FAIL 是刻意的:两者都属「合法但危险」的用法,框架判不了使用者的真实意图。
214
+ """
215
+ if CLEAN_TOKEN.search(cmd or ""):
216
+ lib.c_warn(f"{name}: [{field}] 命令含 `clean` —— 会先删掉子工程已产出的模块 jar"
217
+ f"(如 apps/modules/*.jar);增量场景请改用 package-incr,"
218
+ f"否则「构建成功」与「产物完整」是两回事")
219
+ info = _read_pidfile(name)
220
+ pid = info.get("pid")
221
+ if pid and lib.process_alive(pid):
222
+ lib.c_warn(f"{name}: [{field}] 该子工程的服务正在运行(PID {pid})—— 原地覆盖 jar 会使"
223
+ f"运行进程的类加载器视图失效(同一 inode 被重写),之后可能报 NoClassDefFoundError"
224
+ f" 或跑出旧代码,**PASS 与 FAIL 均不可采信**;请先 run-field {name} stop")
225
+
226
+
227
+ def _run_one(name, sp, field, timeout):
228
+ if field == "start":
229
+ return _start(name, sp, timeout)
230
+ if field == "stop":
231
+ return _stop(name, sp)
232
+ cmd = lib.get_build_field(sp, field)
233
+ if not cmd:
234
+ print(f" ⚠️ {name}: build.json 未声明 {field},跳过")
235
+ return True
236
+ _warn_build_env(name, field, cmd)
237
+ print(f"→ {name}: [{field}] $ {cmd}")
238
+ try:
239
+ r = lib.run_build_field(sp, field, timeout=timeout)
240
+ except FileNotFoundError as e:
241
+ lib.c_fail(f"{name}: 命令不可用: {e}")
242
+ return False
243
+ except Exception as e: # 含 subprocess.TimeoutExpired
244
+ lib.c_fail(f"{name}: {field} 异常: {e}")
245
+ return False
246
+ if r is None or r.returncode != 0:
247
+ if r is not None:
248
+ print(r.stdout[-2000:] if r.stdout else "")
249
+ print(r.stderr[-2000:] if r.stderr else "")
250
+ lib.c_fail(f"{name}: {field} 失败 (exit={None if r is None else r.returncode})")
251
+ return False
252
+ lib.c_pass(f"{name}: {field} 通过")
253
+ return True
254
+
255
+
256
+ def main(argv=None):
257
+ argv = list(sys.argv[1:] if argv is None else argv)
258
+ timeout = None
259
+ if "--timeout" in argv:
260
+ i = argv.index("--timeout")
261
+ try:
262
+ timeout = int(argv[i + 1])
263
+ except (IndexError, ValueError):
264
+ return _usage()
265
+ del argv[i:i + 2]
266
+ run_all = "--all" in argv
267
+ argv = [a for a in argv if a != "--all"]
268
+ if not argv:
269
+ return _usage()
270
+ field = argv[-1]
271
+ if field not in FIELDS:
272
+ lib.c_fail(f"未知字段: {field}")
273
+ return _usage()
274
+ if run_all:
275
+ if argv[:-1]:
276
+ return _usage()
277
+ targets = lib.discover_service_dirs(lib.repo_root())
278
+ else:
279
+ if len(argv) != 2:
280
+ return _usage()
281
+ sp = lib.resolve_service_dir(argv[0])
282
+ if sp is None:
283
+ lib.c_fail(f"子工程不存在: {argv[0]}(可写短名 `backend` 或路径 `services/backend`)")
284
+ return 1
285
+ targets = [(sp.name, sp)]
286
+ if not targets:
287
+ lib.c_fail("未发现任何子工程")
288
+ return 1
289
+ # 不用 all(...) 短路:所有子工程都要跑完,不能因为第一个失败就跳过其余
290
+ results = [_run_one(n, p, field, timeout) for n, p in targets]
291
+ return 0 if all(results) else 1
292
+
293
+
294
+ if __name__ == "__main__":
295
+ sys.exit(main())
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ spec_lint.py — Spec 编号体系门禁
4
+
5
+ 用法:
6
+ python3 .harness/scripts/spec_lint.py # 人读报告
7
+ python3 .harness/scripts/spec_lint.py --json # 机读 JSON
8
+ python3 .harness/scripts/spec_lint.py --specs-dir <dir> [--json] # 指定 specs 目录(spec_merge 门禁用)
9
+
10
+ 退出码: 有 ERROR → 1,否则 0
11
+ """
12
+
13
+ import sys, os, re, json, glob
14
+ from pathlib import Path
15
+ from collections import defaultdict
16
+
17
+ SCRIPT_DIR = Path(__file__).resolve().parent
18
+ SPECS_DIR = (SCRIPT_DIR / ".." / "specs").resolve()
19
+
20
+ # ── 解析 frontmatter ──────────────────────────────────────────────
21
+ RE_FRONTMATTER = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
22
+
23
+ # ── 码模式 ────────────────────────────────────────────────────────
24
+ RE_REQ = re.compile(r"^###\s+Requirement:\s+.+\s+\(([A-Z]{2,6})-R-(\d+)\)", re.MULTILINE)
25
+ RE_SCEN = re.compile(r"^####\s+Scenario:\s+.+\s+\(([A-Z]{2,6})-S-(\d+)\)", re.MULTILINE)
26
+ RE_TBD = re.compile(r"TBD|TODO", re.IGNORECASE)
27
+
28
+ # ── 残留原始行(spec_merge 变换失配的指纹)──────────────────────────
29
+ # 背景:spec_merge 的块变换一旦失配,整行会**原样**落进 spec.md —— 没有 `#### Scenario:` / `### Requirement:`
30
+ # 头,本脚本既不计入 reqs/scens、id_max 也不重算,该条**静默消失**(实例:`thing/spec.md` 的 TH-S-084,
31
+ # 归档时被吞,直到本门禁上线才被看见)。spec.md 只允许规范形态,原始块形态一律 ERROR。
32
+ RE_RAW_SCEN = re.compile(r"^\s*\*{0,3}Scenario[::]", re.MULTILINE)
33
+ RE_RAW_REQ = re.compile(r"^\s*####\s+REQ-[A-Z]{2,6}-\d+", re.MULTILINE)
34
+
35
+ # ── 发现 spec 文件 ────────────────────────────────────────────────
36
+ def discover_specs(specs_dir=None):
37
+ """发现 specs 目录下所有非 _ 前缀的 .md 文件,排除 _index.md _flows.md README.md。
38
+
39
+ 兼容两种布局:扁平 `specs/<domain>.md`(harness-kit 默认)与目录 `specs/<domain>/spec.md`(旧工程)。
40
+ """
41
+ if specs_dir is None:
42
+ specs_dir = SPECS_DIR
43
+ return [p for p in Path(specs_dir).glob("**/*.md")
44
+ if not p.name.startswith("_") and p.name not in ("README.md", "spec-template.md")]
45
+
46
+ # ── 解析 single spec ──────────────────────────────────────────────
47
+ def parse_spec(filepath: Path, specs_dir=None):
48
+ if specs_dir is None:
49
+ specs_dir = SPECS_DIR
50
+ text = filepath.read_text(encoding="utf-8")
51
+ try:
52
+ rel = str(filepath.resolve().relative_to(Path.cwd()))
53
+ except ValueError:
54
+ rel = str(filepath)
55
+
56
+ fm = {}
57
+ fm_match = RE_FRONTMATTER.match(text)
58
+ if fm_match:
59
+ try:
60
+ import yaml
61
+ fm = yaml.safe_load(fm_match.group(1)) or {}
62
+ except (ImportError, Exception):
63
+ # ImportError: yaml 未安装; 其他 Exception: YAML 数据格式错误
64
+ # 均降级为空 frontmatter,由后续 prefix 检查报告具体问题
65
+ fm = {}
66
+ else:
67
+ return {
68
+ "path": rel,
69
+ "name": filepath.stem,
70
+ "domain": filepath.stem,
71
+ "prefix": "",
72
+ "frontmatter": fm,
73
+ "reqs": [],
74
+ "scens": [],
75
+ "errors": [f"{rel}: 缺少 YAML frontmatter"],
76
+ "warnings": [],
77
+ }
78
+
79
+ prefix = fm.get("prefix", "")
80
+ id_max_r = fm.get("id_max_r", 0)
81
+ id_max_s = fm.get("id_max_s", 0)
82
+ retired = set(fm.get("retired") or [])
83
+ domain = fm.get("domain", filepath.stem)
84
+
85
+ errors = []
86
+ warnings = []
87
+ reqs = []
88
+ scens = []
89
+
90
+ # ── 扫描 Requirement ──────────────────────────────────────────
91
+ for m in RE_REQ.finditer(text):
92
+ r_prefix = m.group(1)
93
+ r_num = int(m.group(2))
94
+ title = m.group(0).strip()
95
+ full_code = f"{r_prefix}-R-{r_num}"
96
+ reqs.append({"code": full_code, "prefix": r_prefix, "num": r_num, "line": title})
97
+
98
+ if prefix and r_prefix != prefix:
99
+ errors.append(f"{rel}: {full_code} 前缀不符(码为 {r_prefix},frontmatter prefix={prefix})")
100
+ if id_max_r and r_num > id_max_r:
101
+ errors.append(f"{rel}: {full_code} 编号 {r_num} 超过 id_max_r={id_max_r}")
102
+ if full_code in retired:
103
+ errors.append(f"{rel}: {full_code} 为退役码,禁止复用")
104
+
105
+ # 检查 SHALL
106
+ body_start = m.end()
107
+ next_section = re.search(r"\n###", text[body_start:])
108
+ body = text[body_start: body_start + next_section.start()] if next_section else text[body_start:]
109
+ if "SHALL" not in body:
110
+ warnings.append(f"{rel}: {full_code} 缺少 SHALL 关键字")
111
+
112
+ # ── 扫描 Scenario ─────────────────────────────────────────────
113
+ for m in RE_SCEN.finditer(text):
114
+ s_prefix = m.group(1)
115
+ s_num = int(m.group(2))
116
+ title = m.group(0).strip()
117
+ full_code = f"{s_prefix}-S-{s_num}"
118
+ scens.append({"code": full_code, "prefix": s_prefix, "num": s_num, "line": title})
119
+
120
+ if prefix and s_prefix != prefix:
121
+ errors.append(f"{rel}: {full_code} 前缀不符(码为 {s_prefix},frontmatter prefix={prefix})")
122
+ if id_max_s and s_num > id_max_s:
123
+ errors.append(f"{rel}: {full_code} 编号 {s_num} 超过 id_max_s={id_max_s}")
124
+ if full_code in retired:
125
+ errors.append(f"{rel}: {full_code} 为退役码,禁止复用")
126
+
127
+ # ── 残留原始行检查(未被 spec_merge 变换掉的 §1 块形态)──────────
128
+ for pat, want in ((RE_RAW_SCEN, "`#### Scenario: 标题 (PREFIX-S-n)`"),
129
+ (RE_RAW_REQ, "`### Requirement: 标题 (PREFIX-R-n)`")):
130
+ for m in pat.finditer(text):
131
+ ln = text[:m.start()].count("\n") + 1
132
+ errors.append(f"{rel}:{ln} 残留未转换的原始块头 `{m.group(0).strip()}`"
133
+ f" —— 本条不会被计入/编号,等于静默丢失;应写成 {want}")
134
+
135
+ # ── TBD 检查 ──────────────────────────────────────────────────
136
+ for m in RE_TBD.finditer(text):
137
+ line = text[:m.start()].count("\n") + 1
138
+ warnings.append(f"{rel}:{line} 包含 TBD/TODO 占位符")
139
+
140
+ return {
141
+ "path": rel,
142
+ "name": filepath.stem,
143
+ "domain": domain,
144
+ "prefix": prefix,
145
+ "frontmatter": fm,
146
+ "reqs": reqs,
147
+ "scens": scens,
148
+ "errors": errors,
149
+ "warnings": warnings,
150
+ }
151
+
152
+ # ── 跨文件校验 ────────────────────────────────────────────────────
153
+ def cross_file_checks(specs, specs_dir=None):
154
+ if specs_dir is None:
155
+ specs_dir = SPECS_DIR
156
+ errors = []
157
+ warnings = []
158
+ infos = []
159
+
160
+ # 全局码去重
161
+ all_codes = defaultdict(list)
162
+ for s in specs:
163
+ for r in s["reqs"]:
164
+ all_codes[r["code"]].append(s["path"])
165
+ for sc in s["scens"]:
166
+ all_codes[sc["code"]].append(s["path"])
167
+
168
+ for code, paths in all_codes.items():
169
+ if len(paths) > 1:
170
+ errors.append(f"重号: {code} 出现在 {' / '.join(paths)}")
171
+
172
+ # _index.md 基本检查
173
+ index_path = Path(specs_dir) / "_index.md"
174
+ if index_path.exists():
175
+ index_text = index_path.read_text(encoding="utf-8")
176
+ # 检查每个有 prefix 的 spec 是否在 _index 中有对应行
177
+ for s in specs:
178
+ if s["prefix"] and s["prefix"] not in index_text:
179
+ warnings.append(f"_index.md: 缺少 prefix={s['prefix']} ({s['name']}) 的索引行")
180
+
181
+ return errors, warnings, infos
182
+
183
+ # ── 主入口 ────────────────────────────────────────────────────────
184
+ def lint(use_json=False, specs_dir=None):
185
+ if specs_dir is None:
186
+ specs_dir = SPECS_DIR
187
+ spec_files = discover_specs(specs_dir)
188
+ if not spec_files:
189
+ result = {"errors": ["specs/ 下无 spec 文件"], "warnings": [], "infos": [], "files": 0}
190
+ if use_json:
191
+ print(json.dumps(result, indent=2, ensure_ascii=False))
192
+ else:
193
+ print("● ERROR: specs/ 下无 spec 文件")
194
+ return 1
195
+
196
+ specs = [parse_spec(f, specs_dir) for f in spec_files]
197
+
198
+ cross_errors, cross_warnings, cross_infos = cross_file_checks(specs, specs_dir)
199
+
200
+ # 汇总
201
+ all_errors = []
202
+ all_warnings = []
203
+ all_infos = list(cross_infos)
204
+
205
+ for s in specs:
206
+ all_errors.extend(s["errors"])
207
+ all_warnings.extend(s["warnings"])
208
+ all_errors.extend(cross_errors)
209
+ all_warnings.extend(cross_warnings)
210
+
211
+ if use_json:
212
+ result = {
213
+ "errors": all_errors,
214
+ "warnings": all_warnings,
215
+ "infos": all_infos,
216
+ "files": len(spec_files),
217
+ "reqs": sum(len(s["reqs"]) for s in specs),
218
+ "scens": sum(len(s["scens"]) for s in specs),
219
+ }
220
+ print(json.dumps(result, indent=2, ensure_ascii=False))
221
+ else:
222
+ file_count = len(spec_files)
223
+ req_count = sum(len(s["reqs"]) for s in specs)
224
+ scen_count = sum(len(s["scens"]) for s in specs)
225
+ print(f"spec_lint — {file_count} 文件, {req_count} Requirement, {scen_count} Scenario\n")
226
+
227
+ for e in all_errors:
228
+ print(f"● ERROR: {e}")
229
+ for w in all_warnings:
230
+ print(f"○ WARN: {w}")
231
+ for i in all_infos:
232
+ print(f"○ INFO: {i}")
233
+
234
+ if not all_errors and not all_warnings and not all_infos:
235
+ print("✓ 全部通过")
236
+
237
+ return 1 if all_errors else 0
238
+
239
+
240
+ if __name__ == "__main__":
241
+ json_flag = "--json" in sys.argv
242
+ specs_dir = None
243
+ if "--specs-dir" in sys.argv:
244
+ i = sys.argv.index("--specs-dir")
245
+ if i + 1 < len(sys.argv):
246
+ specs_dir = sys.argv[i + 1]
247
+ sys.exit(lint(use_json=json_flag, specs_dir=specs_dir))