flow-comet 1.5.0-rc.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.
Files changed (59) hide show
  1. package/.flow-comet/rules/flow-comet-orchestration.md +13 -0
  2. package/.flow-comet/skills/flow-comet/GUIDANCE.md +196 -0
  3. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -0
  4. package/.flow-comet/skills/flow-comet/SKILL.md +196 -0
  5. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +19 -0
  6. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +115 -0
  7. package/.flow-comet/skills/flow-comet/reference/authoring-lanes.json +33 -0
  8. package/.flow-comet/skills/flow-comet/reference/composition-report.md +65 -0
  9. package/.flow-comet/skills/flow-comet/reference/decision-points.md +64 -0
  10. package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +30 -0
  11. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +169 -0
  12. package/.flow-comet/skills/flow-comet/reference/init-detection.md +58 -0
  13. package/.flow-comet/skills/flow-comet/reference/recovery.md +20 -0
  14. package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +661 -0
  15. package/.flow-comet/skills/flow-comet/reference/skill-review.md +13 -0
  16. package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +7 -0
  17. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +681 -0
  18. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +52 -0
  19. package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +61 -0
  20. package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +909 -0
  21. package/.flow-comet/skills/flow-comet/scripts/comet-plan.mjs +2 -0
  22. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +312 -0
  23. package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +136 -0
  24. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +7331 -0
  25. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +376 -0
  26. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +230 -0
  27. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +99 -0
  28. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +4017 -0
  29. package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +28 -0
  30. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +2396 -0
  31. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +378 -0
  32. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +1263 -0
  33. package/.flow-comet/skills/flow-comet-archive/SKILL.md +195 -0
  34. package/.flow-comet/skills/flow-comet-change/SKILL.md +29 -0
  35. package/.flow-comet/skills/flow-comet-compose/SKILL.md +249 -0
  36. package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +23 -0
  37. package/.flow-comet/skills/flow-comet-design/SKILL.md +161 -0
  38. package/.flow-comet/skills/flow-comet-dev/SKILL.md +51 -0
  39. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +26 -0
  40. package/.flow-comet/skills/flow-comet-execute/SKILL.md +182 -0
  41. package/.flow-comet/skills/flow-comet-health/SKILL.md +31 -0
  42. package/.flow-comet/skills/flow-comet-integration/SKILL.md +45 -0
  43. package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +36 -0
  44. package/.flow-comet/skills/flow-comet-open/SKILL.md +161 -0
  45. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +33 -0
  46. package/.flow-comet/skills/flow-comet-plan/SKILL.md +169 -0
  47. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +27 -0
  48. package/.flow-comet/skills/flow-comet-review/SKILL.md +204 -0
  49. package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +29 -0
  50. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +214 -0
  51. package/.flow-comet/skills/flow-comet-task/SKILL.md +33 -0
  52. package/.flow-comet/skills/flow-comet-test/SKILL.md +41 -0
  53. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +26 -0
  54. package/.flow-comet/skills/flow-comet-verify/SKILL.md +164 -0
  55. package/LICENSE +21 -0
  56. package/README.md +255 -0
  57. package/package.json +27 -0
  58. package/scripts/dsh-bridge.mjs +461 -0
  59. package/scripts/prepare-env.mjs +1526 -0
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import './workflow-state.mjs';
@@ -0,0 +1,312 @@
1
+ #!/usr/bin/env node
2
+ // context-init.mjs — 自动初始化检测(init 前置步骤)
3
+ // 探测项目上下文状态 → 判决 A~F → 提示/静默;--init-context 全量生成 .specs/CONTEXT.md
4
+ // 由 workflow-state.mjs init 分支调用;独立模块便于 guard-self-test 集成测试。
5
+ // 文案为公开描述性中文(无未公开概念)。
6
+
7
+ import { promises as fs } from 'fs';
8
+ import path from 'path';
9
+
10
+ // 既有 AI 上下文文档探测清单(与 flow-kit 入场判定同源:AGENTS/CLAUDE/Cursor/Windsurf/Copilot/Cline)
11
+ const AI_DOC_CANDIDATES = [
12
+ { name: 'AGENTS.md', dirs: ['.'] },
13
+ { name: 'CLAUDE.md', dirs: ['.', '.claude'] },
14
+ { name: '.clinerules', dirs: ['.'] },
15
+ { name: '.github/copilot-instructions.md', dirs: ['.'] },
16
+ ];
17
+ const AI_DOC_GLOBS = ['.cursor/rules', '.windsurf/rules'];
18
+
19
+ // 项目级文档(非 AI 专用但含项目信息——整合时一并读取)
20
+ const PROJECT_DOC_CANDIDATES = [
21
+ { name: 'README.md', dirs: ['.'] },
22
+ { name: 'ARCHITECTURE.md', dirs: ['.', 'docs'] },
23
+ { name: 'CONTRIBUTING.md', dirs: ['.'] },
24
+ ];
25
+
26
+ // 代码上下文信号(判定 greenfield)
27
+ const CODE_SIGNAL_FILES = [
28
+ 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml', 'pom.xml',
29
+ 'build.gradle', 'composer.json', 'Gemfile', 'requirements.txt', 'tsconfig.json',
30
+ ];
31
+ const CODE_SIGNAL_DIRS = ['src', 'lib', 'app'];
32
+
33
+ const CONTEXT_90_DAYS = 90 * 24 * 60 * 60 * 1000;
34
+
35
+ async function exists(p) {
36
+ try { await fs.access(p); return true; } catch { return false; }
37
+ }
38
+
39
+ async function listMd(root, dirRel) {
40
+ const dir = path.join(root, dirRel);
41
+ try {
42
+ const entries = await fs.readdir(dir, { withFileTypes: true });
43
+ return entries.filter((e) => e.isFile() && e.name.endsWith('.md')).map((e) => path.join(dirRel, e.name));
44
+ } catch { return []; }
45
+ }
46
+
47
+ // 探测项目上下文:返回 { hasContext, lastScanDays, aiDocs, projectDocs, hasCodeContext }
48
+ export async function probeProject(runRoot, state) {
49
+ const specsContext = path.join(runRoot, '.specs', 'CONTEXT.md');
50
+ const rootContext = path.join(runRoot, 'CONTEXT.md');
51
+ const hasContext = await exists(specsContext) || await exists(rootContext);
52
+
53
+ let lastScanDays = null;
54
+ if (state && state.last_intel_scan) {
55
+ const t = Date.parse(state.last_intel_scan);
56
+ if (!Number.isNaN(t)) lastScanDays = Math.floor((Date.now() - t) / (24 * 60 * 60 * 1000));
57
+ }
58
+
59
+ const aiDocs = [];
60
+ for (const c of AI_DOC_CANDIDATES) {
61
+ for (const d of c.dirs) {
62
+ const p = path.join(runRoot, d, c.name);
63
+ if (await exists(p)) aiDocs.push(path.join(d, c.name).replace(/^\.\//, ''));
64
+ }
65
+ }
66
+ for (const g of AI_DOC_GLOBS) {
67
+ const found = await listMd(runRoot, g);
68
+ aiDocs.push(...found);
69
+ }
70
+
71
+ const projectDocs = [];
72
+ for (const c of PROJECT_DOC_CANDIDATES) {
73
+ for (const d of c.dirs) {
74
+ const p = path.join(runRoot, d, c.name);
75
+ if (await exists(p)) projectDocs.push(path.join(d, c.name).replace(/^\.\//, ''));
76
+ }
77
+ }
78
+
79
+ let hasCodeContext = false;
80
+ for (const f of CODE_SIGNAL_FILES) {
81
+ if (await exists(path.join(runRoot, f))) { hasCodeContext = true; break; }
82
+ }
83
+ if (!hasCodeContext) {
84
+ for (const d of CODE_SIGNAL_DIRS) {
85
+ if (await exists(path.join(runRoot, d))) { hasCodeContext = true; break; }
86
+ }
87
+ }
88
+
89
+ return { hasContext, lastScanDays, aiDocs, projectDocs, hasCodeContext };
90
+ }
91
+
92
+ // 判决:A 记忆静默 / B 新鲜静默 / C 过期 HINT / D 有 AI 文档 NEEDED / E 有代码 NEEDED / F greenfield NEEDED-skeleton
93
+ export function classify(probe, state) {
94
+ if (state && state.ai_context_doc) return 'skip'; // A
95
+ if (probe.hasContext) {
96
+ if (probe.lastScanDays !== null && probe.lastScanDays <= 90) return 'skip'; // B
97
+ return 'hint'; // C
98
+ }
99
+ if (probe.aiDocs.length > 0) return 'needed-d'; // D
100
+ if (probe.hasCodeContext) return 'needed'; // E
101
+ return 'needed-skeleton'; // F
102
+ }
103
+
104
+ // 输出提示(公开描述性文案;INIT-NEEDED 含预算说明与参数指引)
105
+ // C 优化(2026-08-10):CONTEXT 已满足模板但无扫描记录(agent 生成后未重跑)→
106
+ // 提示精准动作(记录扫描时间)而非误导性的"刷新"文案。
107
+ export async function printDetection(runRoot, probe, verdict, out = console) {
108
+ if (verdict === 'skip') return;
109
+ if (verdict === 'hint') {
110
+ // DF-1: 无扫描记录(旧项目迁移,lastScanDays=null)时不拼 null 进文案
111
+ const freshness = probe.lastScanDays === null ? '上次扫描时间未知' : `上次扫描已 ${probe.lastScanDays} 天`;
112
+ if (probe.lastScanDays === null) {
113
+ // C: CONTEXT 已满足模板(agent 生成后未重跑)→ 精准指引;不满足 → 刷新/重写指引
114
+ const { missingSections, formatIssues } = await validateContext(runRoot);
115
+ if (missingSections.length === 0 && formatIssues.length === 0) {
116
+ out.log('INIT-HINT: 项目上下文(CONTEXT.md)已就绪(7 段 + 模板格式校验通过)但尚未记录扫描时间。运行 init <change-id> --init-context 记录扫描时间即可(此后 90 天内不再提示)。');
117
+ return;
118
+ }
119
+ }
120
+ out.log(`INIT-HINT: 项目上下文(CONTEXT.md)已存在但${freshness}。可重跑全量刷新:init <change-id> --init-context(可选,不强制)。`);
121
+ return;
122
+ }
123
+ let detail = '';
124
+ if (verdict === 'needed-d') {
125
+ detail = `检测到既有 AI 上下文文档:\n - ${probe.aiDocs.join('\n - ')}`;
126
+ }
127
+ const skeletonNote = verdict === 'needed-skeleton' ? '(新项目骨架,占位随流程沉淀)' : '';
128
+ out.log(`INIT-NEEDED: 项目上下文(CONTEXT.md)尚未初始化${skeletonNote}。${detail ? '\n' + detail : ''}\n初始化将:读取既有文档并整合(带出处标注)+ 全量代码探测,生成结构化的项目上下文。\n成本:约 15-30k tokens(仅首次)。同意请重跑:init <change-id> --init-context;拒绝:--init-skip。`);
129
+ }
130
+
131
+ // CONTEXT 模板 7 段标题(校验基准——agent 生成后脚本校验结构完整性)
132
+ // 2026-08-10 改进:段清单从 flow-kit/templates/CONTEXT.md 解析派生(括号前前缀),
133
+ // 模板缺失/解析不到时 fallback 内置(对齐 C2 段名校验模板派生模式,消灭手抄漂移)。
134
+ const CONTEXT_SECTIONS_FALLBACK = [
135
+ '## 项目概要',
136
+ '## 技术栈',
137
+ '## 域语言',
138
+ '## 已锁决策',
139
+ '## 默认偏好',
140
+ '## 既有抽象索引',
141
+ '## intel-scan 元数据',
142
+ ];
143
+
144
+ // 模板存在性探测:返回 { exists, path }——flow-kit 是否安装在目标项目
145
+ export async function probeTemplate(runRoot) {
146
+ const p = path.join(runRoot, 'flow-kit', 'templates', 'CONTEXT.md');
147
+ try { await fs.access(p); return { exists: true, path: p }; } catch { return { exists: false, path: p }; }
148
+ }
149
+
150
+ // 从模板派生 7 段标题清单(`## 名称(后缀)` → `## 名称` 前缀);模板缺失/解析失败返回 null
151
+ async function deriveSections(runRoot) {
152
+ const { exists, path: p } = await probeTemplate(runRoot);
153
+ if (!exists) return null;
154
+ try {
155
+ const text = await fs.readFile(p, 'utf8');
156
+ const sections = [...text.matchAll(/^## ([^\n((]+)/gm)]
157
+ .map((m) => m[1].trim())
158
+ .filter((s) => s.length > 0 && s.length <= 30);
159
+ return sections.length >= 7 ? sections : null;
160
+ } catch { return null; }
161
+ }
162
+
163
+ // 校验段清单(模板派生优先,fallback 内置)
164
+ async function contextSections(runRoot) {
165
+ const derived = await deriveSections(runRoot);
166
+ return derived ?? CONTEXT_SECTIONS_FALLBACK;
167
+ }
168
+
169
+ // 模板关键格式检查(flow-kit/templates/CONTEXT.md 基准——段存在时校验其内格式,确定性检查)
170
+ const CONTEXT_FORMAT_CHECKS = [
171
+ {
172
+ name: '已锁决策条目日期前缀',
173
+ applies: (t) => t.includes('## 已锁决策'),
174
+ // 段内列表条目须带日期 `- [20xx-xx-xx]`;占位条目([xxx] 形态/待沉淀类/模板尖括号)放行——
175
+ // 新项目骨架(无历史决策)不应被格式校验拒绝(DF-5)。
176
+ passes: (t) => {
177
+ const seg = (t.split('## 已锁决策')[1] ?? '').split('\n##')[0];
178
+ const items = seg.split('\n').filter((l) => /^\s*-\s+/.test(l));
179
+ if (items.length === 0) return true; // 空段放行
180
+ const bare = items.filter((l) => {
181
+ if (/-\s+\[20\d\d-\d\d-\d\d\]/.test(l)) return false; // 真实日期条目
182
+ if (/-\s+\[[^\]]*\]/.test(l)) return false; // [xxx] 形态(含模板占位 [YYYY-MM-DD])
183
+ if (/-\s+(?(待沉淀|待补充|待写入)|<[^>]+>/.test(l)) return false; // 中文占位 / 模板尖括号
184
+ return true; // 裸条目(无日期无占位形态)
185
+ });
186
+ return bare.length === 0;
187
+ },
188
+ hint: '模板格式 `- [YYYY-MM-DD] 决策 — 来自 @...`',
189
+ },
190
+ {
191
+ name: 'intel-scan 元数据三字段',
192
+ applies: (t) => t.includes('## intel-scan 元数据'),
193
+ passes: (t) => t.includes('**last_intel_scan**') && t.includes('**scanner**') && t.includes('**下次重扫建议**'),
194
+ hint: '模板字段 last_intel_scan / scanner / 下次重扫建议',
195
+ },
196
+ {
197
+ name: '域语言表格表头',
198
+ applies: (t) => t.includes('## 域语言'),
199
+ passes: (t) => /\|\s*术语\s*\|\s*定义\s*\|/.test(t),
200
+ hint: '模板表格 `| 术语 | 定义 |`',
201
+ },
202
+ ];
203
+
204
+ // 段名规范化:兼容「带 `## ` 前缀」(内置 fallback)与「不带前缀」(模板派生)两种来源,
205
+ // 并剥离模板标题的括注后缀(`已锁决策(ADR 摘要)` → `已锁决策`,与 deriveSections 同口径)。
206
+ function normalizeSectionName(name) {
207
+ return String(name ?? '').replace(/^#{1,6}\s*/, '').replace(/[((].*$/, '').trim();
208
+ }
209
+
210
+ // 围栏代码块剥离:标题/格式判定的输入必须是「文档结构」,而代码示例里的 `## 段名` 只是示例文本。
211
+ // 不剥离会让缺段的 CONTEXT 假通过——只要围栏示例里出现该段名,标题解析就把它当成段存在
212
+ // (校验放行并写入扫描时间)。围栏识别按 CommonMark 收口:
213
+ // · 开栏 = 至多 3 空格缩进 + 连续 3 个及以上 ` 或 ~(后续为语言标注等信息串)
214
+ // · 反引号围栏的信息串不得含反引号(否则是行内代码而非围栏)
215
+ // · 闭栏须与开栏同字符、长度不短于开栏、其后仅余空白;不同字符的围栏互不闭合
216
+ // · 围栏内的行(含 `## 标题`)一律不计入结构判定
217
+ function stripFencedCodeBlocks(text) {
218
+ const kept = [];
219
+ let fenceChar = null;
220
+ let fenceLength = 0;
221
+ for (const line of String(text ?? '').split('\n')) {
222
+ const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
223
+ if (fenceChar === null) {
224
+ if (fence && !(fence[1][0] === '`' && fence[2].includes('`'))) {
225
+ fenceChar = fence[1][0];
226
+ fenceLength = fence[1].length;
227
+ continue;
228
+ }
229
+ kept.push(line);
230
+ continue;
231
+ }
232
+ if (
233
+ fence &&
234
+ fence[1][0] === fenceChar &&
235
+ fence[1].length >= fenceLength &&
236
+ fence[2].trim() === ''
237
+ ) {
238
+ fenceChar = null;
239
+ fenceLength = 0;
240
+ }
241
+ }
242
+ return kept.join('\n');
243
+ }
244
+
245
+ // 文档标题集合(ATX 标题行:行首 #~###### + 空白 + 标题文本;正文文本不参与)。
246
+ // 输入为「文档结构」文本(围栏代码块已由 stripFencedCodeBlocks 剥离——见 validateContext)。
247
+ function headingSet(text) {
248
+ const set = new Set();
249
+ for (const m of String(text ?? '').matchAll(/^#{1,6}[ \t]+(.+?)[ \t]*$/gm)) {
250
+ set.add(normalizeSectionName(m[1]));
251
+ }
252
+ return set;
253
+ }
254
+
255
+ // 校验 .specs/CONTEXT.md 7 段结构 + 模板关键格式;文件缺失 = 全缺。返回
256
+ // { missingSections, formatIssues, template }(missingSections 与 formatIssues 皆空 = 通过)。
257
+ // 段存在判定 = **精确标题匹配**(标题名归一后相等):全文 includes 会把段名变体
258
+ // (`## 项目概要补充`)与正文提及误判为段存在,使不满足模板的 CONTEXT 记录为完成。
259
+ // 生成由 agent 执行(intel-scan 全量阅读语义)——脚本只做确定性结构/格式校验,不做智能整合。
260
+ export async function validateContext(runRoot) {
261
+ const target = path.join(runRoot, '.specs', 'CONTEXT.md');
262
+ const sections = await contextSections(runRoot);
263
+ let text;
264
+ try {
265
+ text = await fs.readFile(target, 'utf8');
266
+ } catch {
267
+ return { missingSections: [...sections], formatIssues: [], template: await probeTemplate(runRoot) };
268
+ }
269
+ // 结构判定一律只看「文档结构」文本:围栏代码块(代码示例)内的行不参与段存在与格式判定——
270
+ // 两条判据共用同一输入,避免同一份文本上出现两条相反口径
271
+ const body = stripFencedCodeBlocks(text);
272
+ const headings = headingSet(body);
273
+ const missingSections = sections.filter((s) => !headings.has(normalizeSectionName(s)));
274
+ const formatIssues = CONTEXT_FORMAT_CHECKS
275
+ .filter((c) => c.applies(body) && !c.passes(body))
276
+ .map((c) => c.name + '(' + c.hint + ')');
277
+ return { missingSections, formatIssues, template: await probeTemplate(runRoot) };
278
+ }
279
+
280
+ // 生成指引(--init-context 时 CONTEXT 缺失或不满足模板时输出)——生成由 agent 全量阅读执行:
281
+ // 读取既有文档(含既有 CONTEXT 的累积术语/决策)并整合(出处标注 `来自 <doc>:<line>`),
282
+ // 探测代码技术栈/抽象索引,**对照 flow-kit/templates/CONTEXT.md 模板**产出 7 段;既有文档零写入。
283
+ // rewrite=true:CONTEXT 已存在但不满足模板(缺段/格式不符)——重写,保留既有累积内容。
284
+ export async function printGenerationGuide(runRoot, probe, { rewrite = false, problems = [] } = {}, out = console) {
285
+ const template = await probeTemplate(runRoot);
286
+ const tplNote = template.exists
287
+ ? '模板:flow-kit/templates/CONTEXT.md(已检测到——严格对照模板段名与条目格式)'
288
+ : '模板:flow-kit/templates/CONTEXT.md(未检测到——按 7 段基准:项目概要 / 技术栈 / 域语言 / 已锁决策 / 默认偏好 / 既有抽象索引 / intel-scan 元数据)';
289
+ const lines = [];
290
+ if (rewrite) {
291
+ const why = problems.length > 0 ? problems.join(';') : '缺段';
292
+ lines.push(`INIT-VALIDATE-FAILED: CONTEXT.md 已存在但不满足模板(${why})。请重写——保留既有 CONTEXT 的累积术语/决策(跨 change 长期累积语义),出处标注 \`来自 <doc>:<line>\`,原文档零写入。${tplNote}`);
293
+ } else {
294
+ lines.push('INIT-GENERATE: 项目上下文未初始化——请生成 .specs/CONTEXT.md。' + tplNote);
295
+ }
296
+ const docs = [...probe.aiDocs, ...probe.projectDocs];
297
+ if (docs.length > 0) {
298
+ lines.push('源文档(全量阅读并整合,出处标注 `来自 <doc>:<line>`;原文档零写入):');
299
+ for (const d of docs) lines.push(' - ' + d);
300
+ }
301
+ if (probe.hasCodeContext) {
302
+ lines.push('代码信号:已检测到代码上下文(依赖文件或源码目录)——探测技术栈并登记既有抽象索引。');
303
+ }
304
+ lines.push('生成后重跑:init <change-id> --init-context(脚本校验 7 段并记录扫描时间)。');
305
+ out.log(lines.join('\n'));
306
+ }
307
+
308
+ // --init-skip:记 none(由调用方写回 state)
309
+ export function skipInit(state) {
310
+ state.ai_context_doc = 'none';
311
+ return state;
312
+ }
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * contract-check.mjs — 前后端契约核对辅助脚本(O-8)
4
+ *
5
+ * 用途:审查(Round 1.5)时自动提取前后端的枚举值/校验规则,输出两端清单,
6
+ * 供 reviewer 快速比对一致性(防 status/type 枚举错位、字段名、min/required 不匹配)。
7
+ *
8
+ * 用法:
9
+ * node contract-check.mjs <field> [--project <root>]
10
+ * 例:node contract-check.mjs status
11
+ * --project <root> 优先于当前目录(未指定时用 cwd)
12
+ *
13
+ * 输出:后端定义清单 + 前端定义清单,人工比对(脚本不自动判定正确性——需要业务语义)。
14
+ */
15
+ import { promises as fs } from 'fs';
16
+ import path from 'path';
17
+
18
+ const runRoot = process.cwd();
19
+ const field = process.argv[2];
20
+ if (!field) {
21
+ console.error('用法: node contract-check.mjs <field> [--project <root>]');
22
+ console.error('例: node contract-check.mjs status');
23
+ process.exit(1);
24
+ }
25
+
26
+ // 正则元字符转义(field 直接拼进 RegExp 会改变匹配语义:`item[0]` 被当字符类;`[` 直接抛错)
27
+ const escapedField = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
28
+
29
+ // --project <root>:显式项目根优先于 cwd 兜底;其后缺值(或缺值处又跟了选项)→ 明确报错
30
+ const projectFlagIndex = process.argv.indexOf('--project');
31
+ const projectRoot = projectFlagIndex === -1 ? null : process.argv[projectFlagIndex + 1];
32
+ if (projectFlagIndex !== -1
33
+ && (typeof projectRoot !== 'string' || projectRoot.trim() === '' || projectRoot.startsWith('--'))) {
34
+ console.error('用法: node contract-check.mjs <field> [--project <root>]');
35
+ console.error('--project 后缺少项目根目录值');
36
+ process.exit(1);
37
+ }
38
+
39
+ // 定位后端/前端目录(从 project root 或约定路径)
40
+ async function findRoots() {
41
+ const candidates = [
42
+ ...(projectRoot ? [projectRoot] : []),
43
+ runRoot,
44
+ ];
45
+ for (const root of candidates) {
46
+ const backend = path.join(root, 'pingpong-tournament', 'app');
47
+ const frontend = path.join(root, 'frontend', 'src');
48
+ if ((await exists(backend)) && (await exists(frontend))) {
49
+ return { root, backend, frontend };
50
+ }
51
+ }
52
+ const fallback = projectRoot ?? runRoot;
53
+ return { root: fallback, backend: path.join(fallback, 'app'), frontend: path.join(fallback, 'src') };
54
+ }
55
+
56
+ async function exists(p) {
57
+ try { await fs.access(p); return true; } catch { return false; }
58
+ }
59
+
60
+ async function grepFiles(dir, patterns, exclude = ['node_modules', '__pycache__', 'dist']) {
61
+ const hits = [];
62
+ async function walk(d) {
63
+ let entries;
64
+ try { entries = await fs.readdir(d, { withFileTypes: true }); } catch { return; }
65
+ for (const e of entries) {
66
+ if (exclude.includes(e.name)) continue;
67
+ const full = path.join(d, e.name);
68
+ if (e.isDirectory()) await walk(full);
69
+ else if (/\.(py|ts|tsx)$/.test(e.name)) {
70
+ const text = await fs.readFile(full, 'utf8');
71
+ for (const pat of patterns) {
72
+ const re = new RegExp(pat, 'g');
73
+ let m;
74
+ while ((m = re.exec(text)) !== null) {
75
+ const line = text.slice(0, m.index).split('\n').length;
76
+ hits.push({ file: path.relative(dir, full), line, match: m[0].trim() });
77
+ }
78
+ }
79
+ }
80
+ }
81
+ }
82
+ await walk(dir);
83
+ return hits;
84
+ }
85
+
86
+ async function main() {
87
+ const { root, backend, frontend } = await findRoots();
88
+ console.log(`# 契约核对: ${field}(project: ${root})\n`);
89
+
90
+ // 后端:Pydantic 校验 + service 赋值
91
+ console.log('## 后端(Pydantic 校验 / service 赋值)');
92
+ const backendHits = await grepFiles(backend, [
93
+ `(?:Field\\([^)]*ge=|le=)[^)]*\\b${escapedField}\\b`,
94
+ `\\b${escapedField}\\s*=\\s*Field\\(`,
95
+ `\\b${escapedField}\\s*=\\s*\\d+`, // status = 3 类赋值
96
+ `status=\\d+`, // update_status(..., status=N)
97
+ `${escapedField}\\s*:\\s*Literal`,
98
+ ]);
99
+ if (backendHits.length === 0) {
100
+ console.log('(未命中——该字段可能无后端校验/赋值,或路径不对)');
101
+ } else {
102
+ const seen = new Set();
103
+ for (const h of backendHits.slice(0, 30)) {
104
+ const key = `${h.file}:${h.line}:${h.match}`;
105
+ if (seen.has(key)) continue;
106
+ seen.add(key);
107
+ console.log(`- ${h.file}:${h.line} ${h.match}`);
108
+ }
109
+ }
110
+
111
+ // 前端:map / derive / Form rules
112
+ console.log('\n## 前端(map / derive / form rules)');
113
+ const frontendHits = await grepFiles(frontend, [
114
+ `\\b${escapedField}===\\s*\\d+`, // status===3
115
+ `\\b${escapedField}\\s*===?\\s*\\d+`,
116
+ `['"]${escapedField}['"]\\s*:.*ge|le|min|max`, // 校验
117
+ `Record<number.*>`,
118
+ `Field\\([^)]*ge=|le=`,
119
+ ]);
120
+ if (frontendHits.length === 0) {
121
+ console.log('(未命中)');
122
+ } else {
123
+ const seen = new Set();
124
+ for (const h of frontendHits.slice(0, 30)) {
125
+ const key = `${h.file}:${h.line}:${h.match}`;
126
+ if (seen.has(key)) continue;
127
+ seen.add(key);
128
+ console.log(`- ${h.file}:${h.line} ${h.match}`);
129
+ }
130
+ }
131
+
132
+ console.log('\n> 提示:人工比对两端枚举值/校验规则是否一致(脚本不判定语义正确性)。');
133
+ console.log('> 常见错位:前端 map 值 ≠ 后端 status 语义(如后端 3=已生成、前端 3=已发布)。');
134
+ }
135
+
136
+ main().catch((e) => { console.error(e.message); process.exit(1); });