flow-comet 1.6.4 → 1.7.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 (85) hide show
  1. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  2. package/.flow-comet/skills/flow-comet/SKILL.md +36 -6
  3. package/.flow-comet/skills/flow-comet/reference/artifact-template-overlay.md +154 -0
  4. package/.flow-comet/skills/flow-comet/reference/artifact-templates.json +387 -0
  5. package/.flow-comet/skills/flow-comet/reference/commit-discipline.md +1 -1
  6. package/.flow-comet/skills/flow-comet/reference/entry-detail.md +29 -4
  7. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +22 -0
  8. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +26 -23
  9. package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +174 -0
  10. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +17 -95
  11. package/.flow-comet/skills/flow-comet/scripts/health.mjs +28 -4
  12. package/.flow-comet/skills/flow-comet/scripts/items/a.mjs +136 -19
  13. package/.flow-comet/skills/flow-comet/scripts/items/b.mjs +54 -18
  14. package/.flow-comet/skills/flow-comet/scripts/items/c.mjs +6 -6
  15. package/.flow-comet/skills/flow-comet/scripts/items/e.mjs +52 -10
  16. package/.flow-comet/skills/flow-comet/scripts/items/h.mjs +25 -10
  17. package/.flow-comet/skills/flow-comet/scripts/items/l.mjs +4 -2
  18. package/.flow-comet/skills/flow-comet/scripts/items/m.mjs +21 -13
  19. package/.flow-comet/skills/flow-comet/scripts/items/n.mjs +163 -0
  20. package/.flow-comet/skills/flow-comet/scripts/lib/ac-coverage.mjs +317 -0
  21. package/.flow-comet/skills/flow-comet/scripts/lib/guard-artifact-skeleton.mjs +448 -0
  22. package/.flow-comet/skills/flow-comet/scripts/lib/guard-evidence-gates.mjs +396 -27
  23. package/.flow-comet/skills/flow-comet/scripts/lib/guard-gates.mjs +1035 -172
  24. package/.flow-comet/skills/flow-comet/scripts/lib/guard-routing.mjs +129 -98
  25. package/.flow-comet/skills/flow-comet/scripts/lib/guard-state-io.mjs +8 -6
  26. package/.flow-comet/skills/flow-comet/scripts/lib/guard-template-fidelity.mjs +797 -232
  27. package/.flow-comet/skills/flow-comet/scripts/lib/guard-uidesign.mjs +91 -22
  28. package/.flow-comet/skills/flow-comet/scripts/lib/lessons-hits.mjs +160 -0
  29. package/.flow-comet/skills/flow-comet/scripts/lib/run-root.mjs +21 -0
  30. package/.flow-comet/skills/flow-comet/scripts/lib/section-body.mjs +92 -0
  31. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-admin.mjs +69 -13
  32. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-flow.mjs +454 -135
  33. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-recovery.mjs +66 -0
  34. package/.flow-comet/skills/flow-comet/scripts/lib/state-explain.mjs +109 -13
  35. package/.flow-comet/skills/flow-comet/scripts/lib/state-io.mjs +55 -2
  36. package/.flow-comet/skills/flow-comet/scripts/lib/state-skillmarkers.mjs +149 -34
  37. package/.flow-comet/skills/flow-comet/scripts/lib/system-fixtures.mjs +79 -9
  38. package/.flow-comet/skills/flow-comet/scripts/lib/task-graph.mjs +84 -31
  39. package/.flow-comet/skills/flow-comet/scripts/lib/test-fixtures.mjs +78 -8
  40. package/.flow-comet/skills/flow-comet/scripts/lib/test-helpers.mjs +60 -3
  41. package/.flow-comet/skills/flow-comet/scripts/lib/text-anchor-checks.mjs +167 -3
  42. package/.flow-comet/skills/flow-comet/scripts/lib/wave-projection.mjs +341 -0
  43. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +287 -0
  44. package/.flow-comet/skills/flow-comet/scripts/scenarios/a.mjs +1454 -16
  45. package/.flow-comet/skills/flow-comet/scripts/scenarios/b.mjs +1202 -8
  46. package/.flow-comet/skills/flow-comet/scripts/scenarios/c.mjs +1205 -77
  47. package/.flow-comet/skills/flow-comet/scripts/scenarios/d.mjs +753 -5
  48. package/.flow-comet/skills/flow-comet/scripts/scenarios/e.mjs +52 -11
  49. package/.flow-comet/skills/flow-comet/scripts/scenarios/f.mjs +582 -3
  50. package/.flow-comet/skills/flow-comet/scripts/scenarios/g.mjs +9 -1
  51. package/.flow-comet/skills/flow-comet/scripts/scenarios/i.mjs +5 -0
  52. package/.flow-comet/skills/flow-comet/scripts/scenarios/j.mjs +22 -6
  53. package/.flow-comet/skills/flow-comet/scripts/scenarios/k.mjs +2 -0
  54. package/.flow-comet/skills/flow-comet/scripts/scenarios/l.mjs +18 -5
  55. package/.flow-comet/skills/flow-comet/scripts/scenarios/n.mjs +4100 -0
  56. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +135 -0
  57. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +6 -5
  58. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +203 -4
  59. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +312 -63
  60. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +5 -2
  61. package/.flow-comet/skills/flow-comet-archive/SKILL.md +6 -2
  62. package/.flow-comet/skills/flow-comet-change/SKILL.md +6 -2
  63. package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +13 -3
  64. package/.flow-comet/skills/flow-comet-design/SKILL.md +15 -8
  65. package/.flow-comet/skills/flow-comet-dev/SKILL.md +1 -1
  66. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +1 -0
  67. package/.flow-comet/skills/flow-comet-execute/SKILL.md +42 -15
  68. package/.flow-comet/skills/flow-comet-health/SKILL.md +1 -1
  69. package/.flow-comet/skills/flow-comet-integration/SKILL.md +1 -1
  70. package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +14 -4
  71. package/.flow-comet/skills/flow-comet-open/SKILL.md +11 -9
  72. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +13 -3
  73. package/.flow-comet/skills/flow-comet-plan/SKILL.md +21 -10
  74. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +1 -1
  75. package/.flow-comet/skills/flow-comet-review/SKILL.md +33 -18
  76. package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +13 -3
  77. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +44 -16
  78. package/.flow-comet/skills/flow-comet-task/SKILL.md +3 -2
  79. package/.flow-comet/skills/flow-comet-test/SKILL.md +6 -2
  80. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +2 -2
  81. package/.flow-comet/skills/flow-comet-verify/SKILL.md +12 -8
  82. package/README.md +3 -3
  83. package/package.json +1 -1
  84. package/scripts/dsh-bridge.mjs +2 -2
  85. package/scripts/lib/installer-flowkit.mjs +43 -3
@@ -1,215 +1,831 @@
1
- // 模板保真门禁(守卫模块):SUMMARY 模板保真(execute / subagent-execute 出口)、TASK 7 字段
2
- // 完整性(plan 出口)、CHANGE/REQUIREMENT/DESIGN 模板保真(open / design 出口)。
1
+ // 产出物模板结构门禁(守卫模块):标题形态 / 首部字段(键 + 非空值)/ 全骨架(模板 H2 + 登记表
2
+ // 结构型 H3,模板外多余段不参与)/ 段序 / 空正文(六词白名单)/ 与模板该段正文逐字相同(判未填,
3
+ // 含模板里的示例表格行)/ 条件段标题必须在场(可选段按模板自述可整段删除)/ 增量段位置。段名与
4
+ // 结构一律由 lib/guard-artifact-skeleton.mjs 的骨架派生(模板是内容权威,登记表只补条件段/结构
5
+ // 子段/增量段/首部/标题形态)——本模块不自持段名清单,段名归一复用 route-node 的 normalizeHeading。
3
6
  //
4
- // 判据骨架统一从 <runRoot>/flow-kit/templates/ 派生(模板缺失 → 内置骨架兜底,且不据此新增阻断);
5
- // 段名归一委托 route-node 共享 heading 归一(单一权威)——不在本模块另写一份段名解析。
7
+ // 模板整份缺失(derived=false,含登记表缺失 registry-missing,C13)→ 模板派生判据全部跳过并输出
8
+ // 「未校验(模板缺失)」;标题形态与首部字段来自登记表而非模板正文,照常校验(既有语义)。
9
+ // 分级沿用 isNewChange:新 change → BLOCKED,旧 change → WARN(C10 无例外)。
10
+ //
11
+ // 两阶段报错(AC-15):首次只给「模板路径 + 类别与数量」,不列「缺段」的段名;同一工件再次
12
+ // 失败时读 .specs/<change>/.template-hints.json 并列段名;该工件通过后清除其键(C5)。其它类别
13
+ // (标题/首部/条件段/段序/空正文/占位符/结构子段/增量段)本身即定位信息,首次就点到具体项——
14
+ // 只有「缺段」会成片出现,才需要先引导读模板。
6
15
 
7
16
  import { promises as fs } from 'fs';
8
17
  import path from 'path';
9
18
  import { EXECUTE_FAMILY_NODE_IDS, normalizeHeading } from '../route-node.mjs';
10
19
  import { taskOpeningAttrs, taskBlocks as extractTaskBlocks } from '../task-parsing.mjs';
11
- import { runRoot, fileExists } from './guard-state-io.mjs';
12
- import { isNewChange, templateSectionPatterns } from './guard-routing.mjs';
20
+ import {
21
+ nodeTemplateDeclaration,
22
+ readProtocolFile,
23
+ templateKeyFromArtifactName,
24
+ templateKeyOf,
25
+ } from '../protocol-utils.mjs';
26
+ import { runRoot, fileExists, protocolPath } from './guard-state-io.mjs';
27
+ import { isNewChange } from './guard-routing.mjs';
28
+ import { buildSkeleton, LEGACY_SUMMARY_ORDER } from './guard-artifact-skeleton.mjs';
29
+ import { scanHeadings } from './section-body.mjs';
13
30
  import { TASK7_REQUIRED } from './task-graph.mjs';
14
31
 
15
- // 段名归一化:委托 route-node 共享 heading 归一(单一权威)——去标题标记 / 尾部括号(如
16
- // Why(为什么做)→ Why)/ 编号前缀(1. 决策清单 → 决策清单)/ 闭合 ATX,去首尾空白 + 小写。
17
- function normalizeTemplateHeading(raw) {
18
- return normalizeHeading(raw);
32
+ const HINT_FILE_NAME = '.template-hints.json';
33
+ const FRONTMATTER_KEY_LINE = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/u;
34
+
35
+ // 空正文白名单(AC-5):判据是**整段取值**而非子串——词后必须是行尾 / 空白 / 标点 / 括注,
36
+ // 「无变更风险;影响两份工件」这类真实句子仍是已填(判据不得退化为子串命中)。
37
+ const NOT_APPLICABLE_BODY =
38
+ /^(?:无变更|不适用|未涉及|N\/A|无|—)(?=$|[\s,。;、,;.::!!??…—()()【】「」『』“”"'])/iu;
39
+
40
+ // 包裹符号(AC-8):粗体 / 下划线 / 引用 / 列表 / 有序列表 / 括号 / 反引号只是同一个词的写法,
41
+ // 不改变「整段只有一个白名单词」这一事实。剥离只用于本判据,**剥离后仍须以白名单词开头**
42
+ // (AC-9:「**见 N/A**」「(说明:N/A)」剥掉包装后开头是实词,仍是已填);只剥包装、不扩词表。
43
+ // 同族的另一种合法写法是「词 + 闭合标记 + 为什么」(`**N/A**(理由)`):说明紧跟闭合标记时
44
+ // 剥离只剥得掉尾部裸标记,词后不再紧邻边界——由 isNotApplicableBody 的第二条判据接住。
45
+ const NOT_APPLICABLE_WRAPPER_LEAD = /^(?:\*\*|__|>|[-*+]|\d+[.)、.]|[((]|`)\s*/u;
46
+ const NOT_APPLICABLE_WRAPPER_TAIL = /\s*(?:\*\*|__|`)$/u;
47
+
48
+ // 「N/A 意图痕迹」只喂补充提示,不参与缺子段判定:父段正文去掉子段标题行后,第一条非空内容行的
49
+ // **开头若干字符**内出现白名单词,才算当事人真想写「整段不适用」。「(说明:N/A)」「见 N/A」这类
50
+ // 带前置说明词 / 包裹的形态落在这个窗口里;普通正文(无白名单词)不落入——把提示挂在与 N/A 无关的
51
+ // 工件上,只会让当事人去改一个它本来没打算写的段落。
52
+ const NOT_APPLICABLE_INTENT = /(?:N\/A|不适用|无变更)/iu;
53
+ const NOT_APPLICABLE_INTENT_WINDOW = 24;
54
+
55
+ function bareNotApplicableBody(text) {
56
+ let stripped = text;
57
+ for (;;) {
58
+ const next = stripped.replace(NOT_APPLICABLE_WRAPPER_LEAD, '').replace(NOT_APPLICABLE_WRAPPER_TAIL, '');
59
+ if (next === stripped) return stripped;
60
+ stripped = next;
61
+ }
19
62
  }
20
63
 
21
- // 提取文档全部 ^## 段(归一化后),供段序/缺段校验
22
- function documentSectionHeadings(content) {
23
- const out = [];
24
- for (const m of String(content).matchAll(/^##\s+(.+)$/gmu)) {
25
- out.push({ raw: m[1].trim(), norm: normalizeTemplateHeading(m[1]) });
64
+ // 整段「不适用」判定(唯一消费点):裸文本以白名单词开头即成立;另接受**闭合标记之后紧跟说明**的
65
+ // 形态——`**N/A**(本轮无变更)` 剥完是 `N/A**(本轮无变更)`,词后紧跟的是闭合标记而不是边界。
66
+ // 说明文字是「为什么不适用」,不改变「整段不适用」这一事实(旧实现据此判已填,于是同一份工件
67
+ // 既被判「写了 N/A」又被要求补子段)。前提仍是白名单词开头:`**见 N/A**` 剥完是 `见 N/A`,
68
+ // 开头是实词 ⇒ 仍是已填(否定式 / 指向式的句子不得吞成整段豁免)。
69
+ const NOT_APPLICABLE_CLOSE_THEN_NOTE = /\s*(?:\*\*|__|`)[\s\S]*$/u;
70
+ function isNotApplicableBody(text) {
71
+ const bare = bareNotApplicableBody(text);
72
+ if (NOT_APPLICABLE_BODY.test(bare)) return true;
73
+ const closed = bare.replace(NOT_APPLICABLE_CLOSE_THEN_NOTE, '');
74
+ return closed !== bare && NOT_APPLICABLE_BODY.test(closed);
75
+ }
76
+
77
+ function literalRegExp(text) {
78
+ return String(text ?? '').replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
79
+ }
80
+
81
+ // 段名精确认键:归一(去编号 / 大小写 / 尾部括号)沿用 route-node 的单一实现,这里**只追加**尾部
82
+ // 括号内容作为区分位——归一口径会把 Button (Primary)/(Secondary) 合成同键(C2),unique=false 的
83
+ // 结构子段必须按精确名匹配,否则「只写了 Secondary」也算 Primary 在场。不复制一份编号/大小写规则。
84
+ function qualifiedHeading(raw) {
85
+ const paren = String(raw ?? '').match(/[((]([^))\n]*)[))]\s*$/u);
86
+ return normalizeHeading(raw) + '\u0000' + (paren ? paren[1].trim().toLowerCase() : '');
87
+ }
88
+
89
+ // 工件文本 → 行锚定轮廓(L-128:只认行首标题,正文里引用段名不劫持)。frontmatter 仅做顶层键
90
+ // 行级解析(不引入 YAML 库):一个键的值区 = 行内余下文本 + 到下一个顶层键之前的非空行
91
+ // (嵌套映射是缩进行,而「值另起一行且不缩进」也同样是已填——两种书写形态都不判空)。
92
+ // 段结构(哪些标题行真的开一段、段到哪里结束、哪些 H3 属于本段)一律取 lib/section-body.mjs 的
93
+ // 围栏感知扫描(scanHeadings):围栏代码块里的 `## ` / `### ` 是正文示例,不开段、也不算子段。
94
+ // 旧实现自带一份按行扫 `^##` 的循环(围栏盲),段序 / 缺段 / 空正文 / 增量段位置四个判据因此共用
95
+ // 同一处盲区:示例里贴一行段标题,那段就被读成「在场」——删段换到放行的写法。
96
+ function parseOutline(text) {
97
+ const { lines, headings } = scanHeadings(text);
98
+ const outline = { frontmatter: { present: false, keys: [] }, titleLine: '', headerLines: [], sections: [] };
99
+ let cursor = 0;
100
+ if (lines[0] !== undefined && lines[0].trim() === '---') {
101
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === '---');
102
+ if (end > 0) {
103
+ outline.frontmatter.present = true;
104
+ const body = lines.slice(1, end);
105
+ for (let index = 0; index < body.length; index += 1) {
106
+ const matched = body[index].match(FRONTMATTER_KEY_LINE);
107
+ if (!matched) continue;
108
+ let value = matched[2].trim();
109
+ if (value === '') {
110
+ for (let next = index + 1; next < body.length && !FRONTMATTER_KEY_LINE.test(body[next]); next += 1) {
111
+ if (body[next].trim() !== '') { value = 'filled'; break; }
112
+ }
113
+ }
114
+ outline.frontmatter.keys.push({ key: matched[1].toLowerCase(), value });
115
+ }
116
+ cursor = end + 1;
117
+ }
118
+ }
119
+ const sectionHeadings = headings.filter((heading) => heading.level === 2);
120
+ const subsectionHeadings = headings.filter((heading) => heading.level === 3);
121
+ while (cursor < lines.length && lines[cursor].trim() === '') cursor += 1;
122
+ outline.titleLine = lines[cursor] ?? '';
123
+ cursor += 1;
124
+ const firstSection = sectionHeadings.length > 0 ? sectionHeadings[0].index : lines.length;
125
+ while (cursor < lines.length && cursor < firstSection) {
126
+ outline.headerLines.push(lines[cursor]);
127
+ cursor += 1;
128
+ }
129
+ for (let index = 0; index < sectionHeadings.length; index += 1) {
130
+ const heading = sectionHeadings[index];
131
+ const end = index + 1 < sectionHeadings.length ? sectionHeadings[index + 1].index : lines.length;
132
+ const section = {
133
+ raw: heading.text.trim(),
134
+ norm: normalizeHeading(heading.text),
135
+ qualified: qualifiedHeading(heading.text),
136
+ bodyLines: lines.slice(heading.index + 1, end),
137
+ // 直系正文(不含子段标题行)由同一次扫描给出:子段标题行的行下标在扫描里就是已知的,
138
+ // 不必回头对 bodyLines 再做一次文本匹配(那会重新掉进围栏盲区)。
139
+ directLines: [],
140
+ subsections: [],
141
+ };
142
+ const subsectionIndexes = new Set();
143
+ for (const sub of subsectionHeadings) {
144
+ if (sub.index <= heading.index || sub.index >= end) continue;
145
+ section.subsections.push({
146
+ raw: sub.text.trim(),
147
+ norm: normalizeHeading(sub.text),
148
+ qualified: qualifiedHeading(sub.text),
149
+ });
150
+ subsectionIndexes.add(sub.index);
151
+ }
152
+ for (let at = heading.index + 1; at < end; at += 1) {
153
+ if (!subsectionIndexes.has(at)) section.directLines.push(lines[at]);
154
+ }
155
+ outline.sections.push(section);
156
+ }
157
+ return outline;
158
+ }
159
+
160
+ // 段正文归一(首尾空行剥离、行尾空白剥离):逐字比对与空正文判定共用同一口径。
161
+ function bodyText(lines) {
162
+ const trimmed = (lines ?? []).map((line) => String(line).replace(/\s+$/u, ''));
163
+ let start = 0;
164
+ let end = trimmed.length;
165
+ while (start < end && trimmed[start].trim() === '') start += 1;
166
+ while (end > start && trimmed[end - 1].trim() === '') end -= 1;
167
+ return trimmed.slice(start, end).join('\n');
168
+ }
169
+
170
+ // 父段的**直系正文**:parseOutline 在扫描时就把子段标题行记了下标(bodyLines 仍含它们,子段归属与
171
+ // 逐字比对要靠那份行序),directLines 是同一份 bodyLines 减去**围栏外**的子段标题行——不剥掉的话
172
+ // 「父段只要写了任一子段」就等同于「父段有正文」,补充提示随即对从未想写 N/A 的工件发声。
173
+ // 只剥标题行,子段的正文内容原样保留(它仍是父段正文的一部分)。
174
+ function directBodyLines(section) {
175
+ return section?.directLines ?? [];
176
+ }
177
+
178
+ // 父段正文是否留下 N/A 意图痕迹:第一条非空内容行的开头若干字符里找白名单词——包裹符号
179
+ // (**N/A** / > N/A / (N/A))与前置说明词((说明:N/A)、见 N/A)都落在这个窗口内。
180
+ function hasNotApplicableIntent(lines) {
181
+ const first = (lines ?? []).map((line) => String(line)).find((line) => line.trim() !== '');
182
+ if (first === undefined) return false;
183
+ return NOT_APPLICABLE_INTENT.test(first.trim().slice(0, NOT_APPLICABLE_INTENT_WINDOW));
184
+ }
185
+
186
+ // 父段名:报文里必须是**真实段名**。骨架里的段名(模板标题,同一份工件不管怎么改写都显示同一个
187
+ // 名字)优先;骨架未派生该段时退到文档段自己的标题行(parseOutline 的 raw 已剥离开栏井号,这里再
188
+ // 去编号)。两条都取不到才用兜底常量——「父段「」」既没有定位价值,也掩盖了「父段没被识别」。
189
+ const PARENT_NAME_FALLBACK = '(该父段名未派生)';
190
+
191
+ function parentSectionName(skeleton, parentNorm, docSection) {
192
+ const fromSkeleton = String(skeleton.sections.find((section) => section.norm === parentNorm)?.name ?? '').trim();
193
+ if (fromSkeleton !== '') return fromSkeleton;
194
+ const fromHeading = String(docSection?.raw ?? '').replace(/^\d+(?:\.\d+)*\.?\s*/u, '').trim();
195
+ return fromHeading === '' ? PARENT_NAME_FALLBACK : fromHeading;
196
+ }
197
+
198
+ // 模板轮廓缓存(键 = 模板绝对路径):逐字比对要模板该段正文,路径来自骨架(不在此推导模板位置)。
199
+ const templateOutlineCache = new Map();
200
+
201
+ async function templateOutlineFor(skeleton) {
202
+ const file = path.resolve(runRoot, ...String(skeleton.file).split('/'));
203
+ if (templateOutlineCache.has(file)) return templateOutlineCache.get(file);
204
+ let outline = null;
205
+ try {
206
+ outline = parseOutline(await fs.readFile(file, 'utf8'));
207
+ } catch {
208
+ outline = null;
209
+ }
210
+ templateOutlineCache.set(file, outline);
211
+ return outline;
212
+ }
213
+
214
+ function emptyIssues() {
215
+ return {
216
+ title: null,
217
+ headerMissing: [],
218
+ headerEmpty: [],
219
+ frontmatter: [],
220
+ missing: [],
221
+ conditional: [],
222
+ order: null,
223
+ empty: [],
224
+ verbatim: [],
225
+ structure: [],
226
+ structureAdvice: [],
227
+ increments: [],
228
+ };
229
+ }
230
+
231
+ // 表格分隔行(`|---|---|`):其后的行才是数据行,表头行不参与「示例数据」判定。
232
+ const TABLE_SEPARATOR_LINE = /^\s*\|(?:\s*:?-{2,}:?\s*\|)+\s*$/u;
233
+
234
+ // 模板正文里的**示例表格行**是成品形态:照抄它等于把别的项目的示例内容(如 SUMMARY「改动文件」
235
+ // 的示例文件清单)当成自己的工件内容。空表格(只有表头 / 分隔行 / 全空单元行)不属示例数据——
236
+ // 照抄空表与「这一项没有内容」同义。
237
+ function tableHasExampleRow(body) {
238
+ let afterSeparator = false;
239
+ for (const line of String(body ?? '').split('\n')) {
240
+ const trimmed = line.trim();
241
+ if (trimmed === '' || !trimmed.startsWith('|')) {
242
+ afterSeparator = false;
243
+ continue;
244
+ }
245
+ if (TABLE_SEPARATOR_LINE.test(trimmed)) {
246
+ afterSeparator = true;
247
+ continue;
248
+ }
249
+ if (!afterSeparator) continue;
250
+ const cells = trimmed.replace(/^\|/u, '').replace(/\|$/u, '').split('|').map((cell) => cell.trim());
251
+ if (cells.some((cell) => cell !== '')) return true;
26
252
  }
27
- return out;
253
+ return false;
28
254
  }
29
255
 
30
- // 模板段序骨架:段名从 flow-kit/templates 派生(与段名校验同源,模板缺失 fallback 内置骨架)
31
- const TEMPLATE_FIDELITY_FALLBACK_SKELETON = {
32
- change: ['why', 'what', '视觉调性', '影响面', '范围排除', '验收线', '风险与未知'],
33
- requirement: ['用户故事', '验收准则', '范围切分', '非功能性需求', '依赖与假设'],
34
- design: ['技术栈选定', '既有架构对齐', '决策清单', '数据流', '关键状态机', 'adr 索引', '风险', '不在范围', '架构沉淀建议'],
35
- // SUMMARY 模板缺失时的内置全骨架:十段(含条件段——条件段允许正文 N/A,但 H2 标题须在场)
36
- summary: ['做了什么', '改动文件', 'verify 输出', '6 维自查', '数据库迁移', '越界检查', '破坏性变更', '决策与偏离', '是否触发新工作', '完成判定'],
37
- };
256
+ // 模板正文是否留了待填位:尖括号占位符(排除 HTML 注释)或未勾选复选框——照抄即未填。
257
+ function templateBodyHasFillInSlot(body) {
258
+ return /<(?!\/?!--)[^<>\n]+>/u.test(body) || /^\s*[-*]\s*\[\s*\]/mu.test(body);
259
+ }
38
260
 
39
- async function templateSkeleton(key) {
40
- const tpl = await templateSectionPatterns(); // 复用模板缓存(runRoot 内模板)
41
- const src = tpl[key] ?? [];
42
- if (src.length > 0) return src.map((s) => normalizeTemplateHeading(s.name));
43
- return (TEMPLATE_FIDELITY_FALLBACK_SKELETON[key] ?? []).map((s) => normalizeTemplateHeading(s));
261
+ // 模板正文是否「成品形态」:留了待填位,或本身已是示例成品(示例表格行)。只有这类正文才做逐字
262
+ // 比对——表头 / 图例 / 空表格 / 占位注释这类正文本身就是骨架的段,照抄不算未填(自指试跑在真实
263
+ // TASK.md 的状态字段说明、空阻塞日志、Fix 任务占位区上实证)。
264
+ function templateBodyIsFinishedForm(body) {
265
+ return templateBodyHasFillInSlot(body) || tableHasExampleRow(body);
44
266
  }
45
267
 
46
- // SUMMARY 全骨架来源:模板全部 H2 派生(derived=true);模板缺失/无 H2 → 内置十段兜底
47
- // (derived=false——调用方据此保持渐进兼容,不新增硬阻断)
48
- async function summaryTemplateSkeleton() {
49
- const tpl = await templateSectionPatterns();
50
- const derived = (tpl.summary ?? []).length > 0;
51
- return { derived, sections: await templateSkeleton('summary') };
268
+ // 结构子段的键:unique=false 的(如 Button (Primary)/(Secondary))按带括号的精确名,其余按
269
+ // 归一名——「在场判定」与「实际挂在哪的诊断」共用这一份键,避免同一口径写两处。
270
+ function structureSubsectionMatches(docSub, sub) {
271
+ return sub.unique === false
272
+ ? docSub.qualified === qualifiedHeading(sub.name)
273
+ : docSub.norm === sub.norm;
52
274
  }
53
275
 
54
- // 段序校核(宽容):模板骨架段里「实际出现」的段须按模板先后出现;返回乱序描述(无则 null)
55
- function templateOrderViolation(skeletons, headings) {
56
- let last = -1;
57
- for (const h of headings) {
58
- const idx = skeletons.indexOf(h.norm);
59
- if (idx === -1) continue;
60
- if (idx < last) return h.raw;
61
- last = idx;
276
+ // 缺结构子段时的定位诊断:同名 H3 若实际写在别的骨架父段下、或落在模板骨架之外(文末的模板外
277
+ // 段落),报错点名它真正的位置。这里只读地找「同名 H3 出现在哪」——归属判定仍是
278
+ // 上面的 subsectionsByParent 一份,本函数不改归属、也不参与豁免。
279
+ function locateStructureSubsection(occurrences, lastSkeletonIndex, sub) {
280
+ for (const occurrence of occurrences) {
281
+ if (!structureSubsectionMatches(occurrence, sub)) continue;
282
+ if (occurrence.index > lastSkeletonIndex) return { kind: 'tail' };
283
+ if (occurrence.registered) {
284
+ // 挂在本父段下的同名 H3 已在候选集里(found 为真)——走到这里只可能是重复骨架段,
285
+ // 不给指向自己的误导性定位。
286
+ return occurrence.section.norm === sub.parentNorm
287
+ ? null
288
+ : { kind: 'parent', heading: occurrence.section.raw };
289
+ }
290
+ // 模板外 H2 下的 H3:按「其上最近的骨架 H2」归因(与归属算法同口径)。
291
+ return { kind: 'parent', heading: occurrence.enclosing.raw };
62
292
  }
63
293
  return null;
64
294
  }
65
295
 
66
- // M1 判据:SUMMARY 模板保真——标题 # SUMMARY: + 首部 4 字段 + 段序(含 flow-comet 增量 ## 自检方法)。
67
- // 返回各维度缺口;调用方按新 BLOCK / 旧 WARN 渐进处置。
68
- const SUMMARY_TEMPLATE_HEADER_FIELDS = [
69
- { label: 'Change ID', re: /\*\*\s*Change\s+ID\s*\*\*/i },
70
- { label: 'Task ID', re: /\*\*\s*Task\s+ID\s*\*\*/i },
71
- { label: '完成时间', re: /\*\*\s*完成时间\s*\*\*/ },
72
- { label: 'AI 角色', re: /\*\*\s*AI\s*角色\s*\*\*/ },
73
- ];
74
- // 段序(含 flow-comet 增量段;越界检查在模板中位于 6 维自查 与 自检方法 之间)
75
- const SUMMARY_ORDERED_SECTIONS = ['做了什么', '改动文件', 'verify 输出', '6 维自查', '越界检查', '自检方法']
76
- .map(normalizeTemplateHeading);
77
-
78
- function summaryTemplateFidelity(content) {
79
- const text = String(content).replace(/\uFEFF/g, '');
80
- const firstRealLine = (text.split('\n').find((l) => l.trim().length > 0) || '').trim();
81
- const titleMissing = !/^#\s*summary\s*:/i.test(firstRealLine);
82
- const headerRegion = text.split(/\n##\s/)[0];
83
- const headerMissing = SUMMARY_TEMPLATE_HEADER_FIELDS
84
- .filter((f) => !f.re.test(headerRegion))
85
- .map((f) => f.label);
86
- const headings = documentSectionHeadings(text);
87
- const seen = new Set();
88
- let last = -1;
89
- let orderIssue = null;
90
- for (const h of headings) {
91
- const idx = SUMMARY_ORDERED_SECTIONS.indexOf(normalizeTemplateHeading(h.raw));
92
- if (idx === -1) continue;
93
- if (idx < last) { orderIssue = h.raw; break; }
94
- last = idx;
95
- seen.add(idx);
96
- }
97
- const missingSections = [];
98
- for (let i = 0; i < SUMMARY_ORDERED_SECTIONS.length; i++) {
99
- if (!seen.has(i)) missingSections.push(SUMMARY_ORDERED_SECTIONS[i]);
100
- }
101
- return { titleMissing, headerMissing, orderIssue, missingSections };
102
- }
103
-
104
- // 全骨架保真:骨架来自 SUMMARY 模板全部 H2;每段须存在(条件段内容可写 N/A,但须有 H2 标题),
105
- // 实际出现的骨架段须按模板先后排列。## 自检方法 不进入骨架,单独校验:须位于 ## 越界检查 之后,
106
- // 且只允许两种位置——紧随 ## 越界检查 之后(下一段即自检方法)或位于全文末尾(最后一个 H2)。
107
- function summarySkeletonFidelity(content, skeleton) {
108
- const text = String(content).replace(/\uFEFF/g, '');
109
- const headings = documentSectionHeadings(text);
296
+ function collectSectionIssues({ text, skeleton, template, issues }) {
297
+ const outline = parseOutline(text);
298
+ const indexByNorm = new Map();
299
+ for (let index = 0; index < skeleton.sections.length; index += 1) {
300
+ const section = skeleton.sections[index];
301
+ if (!indexByNorm.has(section.norm)) indexByNorm.set(section.norm, index);
302
+ }
303
+ const matched = new Map();
304
+ for (const section of outline.sections) {
305
+ if (indexByNorm.has(section.norm) && !matched.has(section.norm)) matched.set(section.norm, section);
306
+ }
307
+ // 标题缺席分两类(模板自述决定,不得并成一支):conditional = 模板标注「条件适用 / 如有」,
308
+ // 标题必须在场(正文可写 N/A);optional = 模板允许整段删除(UI-DESIGN §0「greenfield 删掉此段」),
309
+ // 整段缺席合法——把 optional 当 conditional 会把按模板指示删段的工件拦死(C-1)。
310
+ for (const section of skeleton.sections) {
311
+ if (matched.has(section.norm)) continue;
312
+ if (section.conditional === true) issues.conditional.push(section.name);
313
+ else if (section.optional !== true) issues.missing.push(section.name);
314
+ }
315
+ // 段序:只对模板骨架段排序,模板外多余段直接跳过(AC-10)
316
+ let lastIndex = -1;
317
+ for (const section of outline.sections) {
318
+ const index = indexByNorm.get(section.norm);
319
+ if (index === undefined) continue;
320
+ if (index < lastIndex) {
321
+ issues.order = { heading: section.raw };
322
+ break;
323
+ }
324
+ lastIndex = index;
325
+ }
326
+ const parentNorms = new Set();
327
+ for (const sub of skeleton.structureSubsections) {
328
+ if (sub.parentNorm !== null) parentNorms.add(sub.parentNorm);
329
+ }
330
+ // 结构子段归属到「其上最近的骨架 H2」:模板外多余段(如工具输出贴入的 `## Findings`)夹在父段与
331
+ // 子段之间时不切断归属(AC-10:多余段不参与骨架判定)。occurrences 是同一份归属数据的旁路记录
332
+ // (H3 所在的 H2 + 最近的骨架 H2),只供「缺子段时它实际挂在哪」的诊断使用,不参与归属判定。
333
+ const subsectionsByParent = new Map();
334
+ const subsectionOccurrences = [];
335
+ let enclosing = null;
336
+ for (let index = 0; index < outline.sections.length; index += 1) {
337
+ const section = outline.sections[index];
338
+ const registered = indexByNorm.has(section.norm);
339
+ if (registered) enclosing = section;
340
+ if (enclosing === null) continue;
341
+ if (!subsectionsByParent.has(enclosing.norm)) subsectionsByParent.set(enclosing.norm, []);
342
+ subsectionsByParent.get(enclosing.norm).push(...section.subsections);
343
+ for (const docSub of section.subsections) {
344
+ subsectionOccurrences.push({
345
+ index,
346
+ registered,
347
+ section,
348
+ enclosing,
349
+ norm: docSub.norm,
350
+ qualified: docSub.qualified,
351
+ });
352
+ }
353
+ }
354
+ const lastSkeletonIndex = outline.sections.reduce(
355
+ (last, section, index) => (indexByNorm.has(section.norm) ? index : last),
356
+ -1,
357
+ );
358
+ for (const section of skeleton.sections) {
359
+ const docSection = matched.get(section.norm);
360
+ if (!docSection) continue;
361
+ const body = bodyText(docSection.bodyLines);
362
+ // 结构型父段的正文由子段承载,空正文只在叶子段判(父段只写子标题是合法形态)
363
+ if (!parentNorms.has(section.norm) && body === '') issues.empty.push(section.name);
364
+ if (template === null) continue;
365
+ const templateSection = template.sections.find((item) => item.norm === section.norm);
366
+ const templateBody = templateSection ? bodyText(templateSection.bodyLines) : '';
367
+ // 与模板该段正文逐字相同 ⇒ 判未填:模板正文留了待填位(占位符 / 复选框)或本身是示例成品
368
+ // (示例表格行)时,逐字相同只可能是照抄模板(AC-6);模板正文本身即骨架形态的段不判。
369
+ if (templateBody !== '' && body === templateBody && templateBodyIsFinishedForm(templateBody)) {
370
+ issues.verbatim.push(section.name);
371
+ }
372
+ }
373
+ // 结构子段:父段在场才要求;父段整段 N/A → 子段不要求(AC-8 ②)。父段的「整段不适用」接受
374
+ // 包裹符号(含「闭合标记 + 说明」形态),但剥掉包装后仍要以白名单词开头(AC-8 / AC-9)。
375
+ for (const sub of skeleton.structureSubsections) {
376
+ const parent = sub.parentNorm === null ? null : matched.get(sub.parentNorm);
377
+ if (!parent) continue;
378
+ const parentBody = bodyText(parent.bodyLines);
379
+ if (isNotApplicableBody(parentBody)) continue;
380
+ const candidates = subsectionsByParent.get(sub.parentNorm) ?? parent.subsections;
381
+ const found = candidates.some((docSub) => structureSubsectionMatches(docSub, sub));
382
+ if (found) continue;
383
+ issues.structure.push({
384
+ name: sub.name,
385
+ placement: locateStructureSubsection(subsectionOccurrences, lastSkeletonIndex, sub),
386
+ });
387
+ // 父段正文留下 N/A 意图痕迹(如「(说明:N/A)」/「见 N/A」)却写不进白名单:子段仍要求,并
388
+ // 给出可照抄的写法(AC-10)。触发条件是**意图痕迹**而不是「正文非空」——普通正文漏写子段时当事人
389
+ // 根本没想写整段不适用,这条提示只会把注意力引到无关段落上;空正文同理(父段正文由子段承载时
390
+ // 它本就是空的)。父段名用真实名,文案里的「父段「」」没有定位价值。
391
+ if (!hasNotApplicableIntent(directBodyLines(parent))) continue;
392
+ const parentName = parentSectionName(skeleton, sub.parentNorm, parent);
393
+ if (!issues.structureAdvice.includes(parentName)) issues.structureAdvice.push(parentName);
394
+ }
395
+ // 增量段:只校验在场者的位置(必填与否由登记表 required + 各自门禁决定,本模块不做存在性兜底)
396
+ for (const increment of skeleton.increments) {
397
+ if (increment.kind !== 'section') continue;
398
+ const docIndex = outline.sections.findIndex((section) => section.norm === increment.norm);
399
+ if (docIndex === -1) continue;
400
+ const laterSkeletonSection = outline.sections
401
+ .slice(docIndex + 1)
402
+ .some((section) => indexByNorm.has(section.norm));
403
+ const position = increment.position ?? {};
404
+ if (position.mode === 'after-or-end') {
405
+ const previous = outline.sections[docIndex - 1];
406
+ const followsAnchor = previous !== undefined
407
+ && position.afterNorm !== null && position.afterNorm !== undefined
408
+ && previous.norm === position.afterNorm;
409
+ // 「文末」分支允许其后再有其它登记的增量段(如 LESSONS 扫描 紧随自检方法,AC-12 ②⑤)
410
+ if (!followsAnchor && laterSkeletonSection) issues.increments.push(increment.section);
411
+ } else if (position.mode === 'end') {
412
+ if (laterSkeletonSection) issues.increments.push(increment.section);
413
+ } else if (position.mode === 'anywhere' && position.constraint === 'code-block-follows') {
414
+ const firstContentLine = outline.sections[docIndex].bodyLines.find((line) => line.trim() !== '');
415
+ if (firstContentLine === undefined || !/^\s*(?:```|~~~)/u.test(firstContentLine)) {
416
+ issues.increments.push(increment.section);
417
+ }
418
+ }
419
+ }
420
+ }
421
+
422
+ // underivedPolicy:模板缺席时保留哪些检查。'registry'(缺省)= 保留登记表级的标题/首部检查(入口文档
423
+ // 的既有语义);'skip' = 整体判「未校验(模板缺失)」(UI-DESIGN 等完全由模板形态定义的工件)。
424
+ function collectArtifactIssues({ text, skeleton, derived, template, requiredHeaderFields = [], underivedPolicy = 'registry' }) {
425
+ const issues = emptyIssues();
426
+ if (!derived && underivedPolicy === 'skip') return issues;
427
+ const outline = parseOutline(text);
428
+ if (skeleton.titleRegExp !== null) {
429
+ const title = outline.titleLine.trim();
430
+ if (title === '' || !skeleton.titleRegExp.test(title)) {
431
+ issues.title = { expected: skeleton.titleForm ?? '' };
432
+ }
433
+ }
434
+ const headerText = outline.headerLines.join('\n');
435
+ // 首部行的正则只用行内空白([ \t]):`\s*` 会吃掉换行并把下一行当成字段值,空值判断随即失效。
436
+ for (const field of requiredHeaderFields) {
437
+ const pattern = new RegExp('^[ \\t]*[-*][ \\t]+\\*\\*[ \\t]*' + literalRegExp(field) + '[ \\t]*\\*\\*[ \\t]*[::]', 'mu');
438
+ if (!pattern.test(headerText)) issues.headerMissing.push(field);
439
+ }
440
+ for (const field of skeleton.headerFields ?? []) {
441
+ // 只校验「已在场的键」的值非空(「有键无值」视为未填,AC-4);键集本身不新增硬性要求
442
+ const pattern = new RegExp('^[ \\t]*[-*][ \\t]+\\*\\*[ \\t]*' + literalRegExp(field) + '[ \\t]*\\*\\*[ \\t]*[::][ \\t]*(.*)$', 'mu');
443
+ const matched = headerText.match(pattern);
444
+ if (matched && matched[1].trim() === '') issues.headerEmpty.push(field);
445
+ }
446
+ if (!derived) return issues;
447
+ for (const key of skeleton.frontmatterKeys ?? []) {
448
+ const entry = outline.frontmatter.keys.find((item) => item.key === String(key).toLowerCase());
449
+ if (!entry || entry.value === '') issues.frontmatter.push(key);
450
+ }
451
+ collectSectionIssues({ text, skeleton, template, issues });
452
+ return issues;
453
+ }
454
+
455
+ function hasAnyIssue(issues) {
456
+ return issues.title !== null
457
+ || issues.order !== null
458
+ || issues.headerMissing.length > 0
459
+ || issues.headerEmpty.length > 0
460
+ || issues.frontmatter.length > 0
461
+ || issues.missing.length > 0
462
+ || issues.conditional.length > 0
463
+ || issues.empty.length > 0
464
+ || issues.verbatim.length > 0
465
+ || issues.structure.length > 0
466
+ || issues.increments.length > 0;
467
+ }
468
+
469
+ // 两阶段记忆的类别集合沿用 C5 的七类词表:结构子段归 missing(缺的是骨架的一部分),
470
+ // 增量段位置归 order(位置偏离)。
471
+ function hintCategories(issues) {
472
+ const categories = new Set();
473
+ if (issues.title !== null) categories.add('title');
474
+ if (issues.headerMissing.length > 0 || issues.headerEmpty.length > 0 || issues.frontmatter.length > 0) {
475
+ categories.add('header');
476
+ }
477
+ if (issues.missing.length > 0 || issues.structure.length > 0) categories.add('missing');
478
+ if (issues.conditional.length > 0) categories.add('conditional');
479
+ if (issues.order !== null || issues.increments.length > 0) categories.add('order');
480
+ if (issues.empty.length > 0) categories.add('empty');
481
+ if (issues.verbatim.length > 0) categories.add('placeholder');
482
+ return [...categories];
483
+ }
484
+
485
+ // 缺子段定位的人读文本:挂在另一个骨架父段下 / 落在模板骨架之外(文末)。
486
+ function placementText(placement) {
487
+ return placement.kind === 'tail' ? '实际在文末' : '实际挂在 ' + placement.heading + ' 段下';
488
+ }
489
+
490
+ // 结构问题清单 → 人读片段(唯一实现):末尾的完整出口报告行与只读的结构预检共用这一个格式器,
491
+ // 两种模式的措辞因此不会各自漂移。escalate 只控制「缺段是否列出段名」(该工件上一轮也失败过才列);
492
+ // 预检不读提示账本,一律以 false 调用。本函数只拼文本——账本由 reportArtifactStructure 写,所以
493
+ // 调用方拿到同形报文不需要复制一份实现。
494
+ export function formatIssueParts(issues, { escalate }) {
495
+ const parts = [];
496
+ if (issues.title !== null) parts.push('标题形态不符(模板首行: `' + issues.title.expected + '`)');
497
+ if (issues.headerMissing.length > 0) parts.push('首部缺字段: ' + issues.headerMissing.join('、'));
498
+ if (issues.headerEmpty.length > 0) parts.push('首部字段有键无值: ' + issues.headerEmpty.join('、'));
499
+ if (issues.frontmatter.length > 0) parts.push('frontmatter 缺键或值为空: ' + issues.frontmatter.join('、'));
500
+ if (issues.missing.length > 0) {
501
+ parts.push('缺段 ' + issues.missing.length + ' 项' + (escalate ? ': ' + issues.missing.join('、') : ''));
502
+ }
503
+ if (issues.conditional.length > 0) {
504
+ parts.push('条件段标题缺席 ' + issues.conditional.length + ' 项: ' + issues.conditional.join('、'));
505
+ }
506
+ if (issues.order !== null) {
507
+ parts.push('段序偏离模板(「' + issues.order.heading + '」排在模板中更早的段之后)');
508
+ }
509
+ if (issues.empty.length > 0) parts.push('正文为空 ' + issues.empty.length + ' 项: ' + issues.empty.join('、'));
510
+ if (issues.verbatim.length > 0) {
511
+ parts.push('与模板该段正文逐字相同(判未填)' + issues.verbatim.length + ' 项: ' + issues.verbatim.join('、'));
512
+ }
513
+ if (issues.structure.length > 0) {
514
+ const entries = issues.structure.map((entry) => (entry.placement === null
515
+ ? entry.name
516
+ : entry.name + '(' + placementText(entry.placement) + ')'));
517
+ parts.push('缺结构子段 ' + issues.structure.length + ' 项: ' + entries.join('、'));
518
+ }
519
+ if (issues.structureAdvice.length > 0) {
520
+ // 报文必须与判据一致:包裹符号(粗体 / 引用 / 括号)**本身就被接受**,旧措辞「不要加粗或引用」
521
+ // 与判据相反,会把人推去改一个本来能通过的写法;真正要的是「白名单词开头」,以及带说明时的
522
+ // 正确位置(闭合标记之后,见 isNotApplicableBody)。
523
+ parts.push('父段「' + issues.structureAdvice.join('」「') + '」正文不在「整段不适用」白名单——'
524
+ + '若要整段不适用,请让整段以 N/A 开头(包裹符号本身就被接受:粗体 / 引用 / 括号都算);'
525
+ + '闭合标记之后要跟说明,写成 `**N/A**(理由)` 这种形态');
526
+ }
527
+ if (issues.increments.length > 0) parts.push('增量段位置非法: ' + issues.increments.join('、'));
528
+ return parts;
529
+ }
530
+
531
+ async function readHints(hintsFile) {
532
+ try {
533
+ const data = JSON.parse(await fs.readFile(hintsFile, 'utf8'));
534
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
535
+ } catch {
536
+ return {};
537
+ }
538
+ }
539
+
540
+ async function writeHints(hintsFile, hints) {
541
+ if (Object.keys(hints).length === 0) {
542
+ await fs.rm(hintsFile, { force: true }).catch(() => {});
543
+ return;
544
+ }
545
+ await fs.mkdir(path.dirname(hintsFile), { recursive: true }).catch(() => {});
546
+ await fs.writeFile(hintsFile, JSON.stringify(hints, null, 2) + '\n', 'utf8').catch(() => {});
547
+ }
548
+
549
+ function notCheckedReason(skeleton) {
550
+ const file = skeleton.file ?? '(登记表未登记该工件)';
551
+ if (skeleton.reason === 'registry-missing' || skeleton.reason === 'registry-unreadable') {
552
+ return '结构登记表缺失(' + skeleton.reason + '),骨架无从派生——模板在场也不静默判通过';
553
+ }
554
+ if (skeleton.reason === 'unknown-key') return '登记表未登记该工件键,结构无从派生';
555
+ if (skeleton.reason === 'template-undeclared') return '登记表未声明该工件的模板路径';
556
+ return file + ' 不存在或不可读(模板缺失)——安装 flow-kit 模板后本工件才会做结构校验';
557
+ }
558
+
559
+ // 骨架评估入口(供产出物门禁与 ui-design 门共用):返回骨架、派生状态与问题清单。
560
+ export async function evaluateArtifact(key, text, options = {}) {
561
+ const skeleton = await buildSkeleton(key);
562
+ const derived = skeleton.derived === true;
563
+ const template = derived ? await templateOutlineFor(skeleton) : null;
564
+ const issues = collectArtifactIssues({
565
+ text,
566
+ skeleton,
567
+ derived,
568
+ template,
569
+ requiredHeaderFields: options.requiredHeaderFields ?? [],
570
+ underivedPolicy: options.underivedPolicy ?? 'registry',
571
+ });
572
+ return { skeleton, derived, issues };
573
+ }
574
+
575
+ // 单工件判定(纯函数,不输出):把问题清单压成报错编排要的形态(是否阻断 + 类别 + 提示账本键)。
576
+ // 结构子段缺席与其它结构问题同权——父段「适用」时子段必须在场(AC-2/AC-8),不按工件分叉。
577
+ export function assessArtifact({ fileLabel, skeleton, derived, issues }) {
578
+ return {
579
+ fileLabel,
580
+ key: skeleton.key,
581
+ skeleton,
582
+ derived,
583
+ hardIssues: issues,
584
+ hard: hasAnyIssue(issues),
585
+ categories: hintCategories(issues),
586
+ };
587
+ }
588
+
589
+ // 记忆键 = 工件键 + 文件:同一个模板键会被多份工件共用(execute 出口的每份 *-SUMMARY.md 都是
590
+ // SUMMARY),只按键记忆会让后一份工件继承前一份的「再犯」状态——同一次出口就升级成列段名,而修好
591
+ // 其中一份时另一份的失败又替它保住了键。
592
+ function hintKeyOf(item) {
593
+ return item.key + ':' + item.fileLabel;
594
+ }
595
+
596
+ // 提示账本(两阶段记忆的纯逻辑,不写盘):把失败记进 hints 并给出各工件的报告行;escalate = 该工件
597
+ // 上一次也失败过(此时列出段名)。escalate 取自**进入本次报告前**的账本快照——同一次报告里两份
598
+ // 工件各自首败时互不升级。
599
+ function planFailureLines(hints, failing) {
600
+ const lines = [];
601
+ const previous = new Set(Object.keys(hints));
602
+ for (const item of failing) {
603
+ const hintKey = hintKeyOf(item);
604
+ const escalate = previous.has(hintKey);
605
+ hints[hintKey] = { failedAt: new Date().toISOString(), categories: item.categories };
606
+ lines.push(item.fileLabel + ' 模板结构校验失败: '
607
+ + formatIssueParts(item.hardIssues, { escalate }).join('; ')
608
+ + '(模板: ' + (item.skeleton.file ?? '(登记表未登记模板路径)') + ')');
609
+ }
610
+ return lines;
611
+ }
612
+
613
+ // 通过的工件释放其记忆键(返回是否有改动,避免无谓写盘)。通过面在**每次**报告都释放——只在
614
+ // 「全部通过」时释放,会让已修好的工件在别的工件仍失败时留着旧键,下次再坏就被当成再犯。
615
+ function releasePassedHints(hints, assessments) {
616
+ let changed = false;
617
+ for (const item of assessments) {
618
+ const hintKey = hintKeyOf(item);
619
+ if (!Object.prototype.hasOwnProperty.call(hints, hintKey)) continue;
620
+ delete hints[hintKey];
621
+ changed = true;
622
+ }
623
+ return changed;
624
+ }
625
+
626
+ // 报错编排(单一实现):模板缺席 → 未校验行;有硬问题 → 两阶段 BLOCKED/WARN;通过面每次都释放
627
+ // 记忆键(与本次出口是否还有其他工件失败无关)。
628
+ // 同一出口的全部工件合并成一次报告——逐件 exit 会让执行者修一个再撞下一个,而这次出口的所有
629
+ // 结构问题一次就能看全。
630
+ export async function reportArtifactStructure({ changeDir, state, assessments }) {
631
+ for (const item of assessments) {
632
+ if (!item.derived) {
633
+ console.error('未校验(模板缺失): ' + item.fileLabel + ' —— ' + notCheckedReason(item.skeleton));
634
+ }
635
+ }
636
+ const failing = assessments.filter((item) => item.hard);
637
+ const hintsFile = path.join(changeDir, HINT_FILE_NAME);
638
+ const hints = await readHints(hintsFile);
639
+ const released = releasePassedHints(hints, assessments.filter((item) => !item.hard));
640
+ if (failing.length > 0) {
641
+ const lines = planFailureLines(hints, failing);
642
+ await writeHints(hintsFile, hints);
643
+ if (isNewChange(state)) {
644
+ for (const line of lines) console.error('BLOCKED: ' + line);
645
+ const templatePaths = [...new Set(failing.map((item) => item.skeleton.file ?? '(未登记模板路径)'))];
646
+ console.error('恢复: 对照 ' + templatePaths.join(' / ') + ' 修正标题 / 首部字段 / 段序,并按模板补齐缺失的 H2 与结构型 H3 标题'
647
+ + '(条件段与无内容段正文可写 N/A;可选段按模板自述可整段删除)后重试 exit;同一工件再次失败时会列出具体段名'
648
+ + '(已记录在 .specs/' + (state.activeChange ?? '<change>') + '/' + HINT_FILE_NAME + ')');
649
+ process.exit(1);
650
+ }
651
+ for (const line of lines) {
652
+ console.error('TEMPLATE-STRUCTURE WARN: ' + line + '(旧 change 渐进,不阻断;新 change 将强制)');
653
+ }
654
+ } else if (released) {
655
+ await writeHints(hintsFile, hints);
656
+ }
657
+ }
658
+
659
+ // SUMMARY 模板缺席时的既有段序兜底(无模板可派生骨架时仍拦乱序/缺段——这是模板权威门禁落地前
660
+ // 就有的判据,保留它避免「模板缺席 = 连乱序也不看」的倒退)。清单唯一来源 = 骨架模块的导出
661
+ // (本模块不自持第二份段名清单,只做归一)。
662
+ const LEGACY_SUMMARY_ORDER_NORMALIZED = LEGACY_SUMMARY_ORDER.map((name) => normalizeHeading(name));
663
+
664
+ function addLegacySummaryIssues(text, issues) {
665
+ const outline = parseOutline(text);
110
666
  const seen = new Set();
111
- for (const h of headings) {
112
- const idx = skeleton.sections.indexOf(h.norm);
113
- if (idx !== -1) seen.add(idx);
114
- }
115
- // 段序复用既有骨架校核(单一实现),段存在性单列——两者共用同一骨架
116
- const orderIssue = templateOrderViolation(skeleton.sections, headings);
117
- const missingSections = [];
118
- for (let i = 0; i < skeleton.sections.length; i++) {
119
- if (!seen.has(i)) missingSections.push(skeleton.sections[i]);
120
- }
121
- const selfHeading = normalizeTemplateHeading('自检方法');
122
- const boundsHeading = normalizeTemplateHeading('越界检查');
123
- const selfIdx = headings.findIndex((h) => h.norm === selfHeading);
124
- const boundsIdx = headings.findIndex((h) => h.norm === boundsHeading);
125
- let selfCheckIssue = null;
126
- if (selfIdx === -1) {
127
- selfCheckIssue = '缺 ## 自检方法 段(须位于 ## 越界检查 之后:文末或紧随越界检查两种合法位置)';
128
- } else if (
129
- boundsIdx === -1 ||
130
- selfIdx < boundsIdx ||
131
- (selfIdx !== headings.length - 1 && selfIdx !== boundsIdx + 1)
132
- ) {
133
- selfCheckIssue = '## 自检方法 位置非法(须位于 ## 越界检查 之后:只允许文末或紧随越界检查两种位置)';
134
- }
135
- return { missingSections, orderIssue, selfCheckIssue };
136
- }
137
-
138
- // SUMMARY 模板保真出口门禁(execute / subagent-execute):每份 *-SUMMARY.md 校 ① 标题首行
139
- // # SUMMARY: ② 首部 4 字段(Change ID/Task ID/完成时间/AI 角色)③ 段序(做了什么→改动文件→
140
- // verify 输出→6 维自查→…→自检方法);宽容匹配(大小写/编号前缀/括号后缀)。④ 全骨架存在 +
141
- // 模板序(骨架从 flow-kit/templates/SUMMARY.md 全部 H2 派生,条件段允许正文 N/A);## 自检方法
142
- // 不在骨架内,单独要求且只允许「文末」「紧随越界检查」两种位置。新 change 任一缺失 → BLOCK
143
- // (含缺失点 + 恢复指引);旧 change/归档批 → WARN 渐进;模板缺失(无权威骨架来源)→ 新规则只
144
- // 告警不阻断,保持旧格式渐进。
667
+ let lastIndex = -1;
668
+ for (const section of outline.sections) {
669
+ const index = LEGACY_SUMMARY_ORDER_NORMALIZED.indexOf(section.norm);
670
+ if (index === -1) continue;
671
+ if (index < lastIndex && issues.order === null) issues.order = { heading: section.raw };
672
+ lastIndex = Math.max(lastIndex, index);
673
+ seen.add(index);
674
+ }
675
+ for (let index = 0; index < LEGACY_SUMMARY_ORDER_NORMALIZED.length; index += 1) {
676
+ if (!seen.has(index)) issues.missing.push(LEGACY_SUMMARY_ORDER_NORMALIZED[index]);
677
+ }
678
+ }
679
+
680
+ // SUMMARY 结构门禁(execute / subagent-execute):标题形态 / 首部四字段 / 全骨架(H2 + 结构型 H3,
681
+ // 条件段允许正文 N/A)/ 段序 / 空正文 / 逐字占位 / 增量段位置(自检方法 紧随越界检查或文末;
682
+ // LESSONS 扫描 紧随自检方法或在自检方法之后),新 change BLOCKED、旧 change WARN;模板缺席时
683
+ // 只保留既有兜底段序判据并显式输出「未校验(模板缺失)」。
145
684
  export async function runSummaryTemplateFidelityGate({ node, state }) {
146
685
  if (!EXECUTE_FAMILY_NODE_IDS.has(node.id)) return;
147
- const summaryChangeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
148
- const summaryFiles = (await fs.readdir(summaryChangeDir).catch(() => [])).filter((f) => f.endsWith('-SUMMARY.md'));
149
- const skeleton = await summaryTemplateSkeleton();
150
- const hardIssues = [];
151
- let skeletonGuidanceNeeded = false;
152
- for (const f of summaryFiles) {
686
+ const changeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
687
+ const files = (await fs.readdir(changeDir).catch(() => [])).filter((file) => file.endsWith('-SUMMARY.md'));
688
+ if (files.length === 0) return;
689
+ const skeleton = await buildSkeleton('SUMMARY');
690
+ const derived = skeleton.derived === true;
691
+ const template = derived ? await templateOutlineFor(skeleton) : null;
692
+ const entries = [];
693
+ for (const file of files) {
694
+ let text;
153
695
  try {
154
- const content = await fs.readFile(path.join(summaryChangeDir, f), 'utf8');
155
- const fidelity = summaryTemplateFidelity(content);
156
- const problems = [];
157
- if (fidelity.titleMissing) {
158
- problems.push('首行缺 `# SUMMARY: <Task>-<名>` 标题(大小写不敏感,标题可带括号说明后缀)');
159
- }
160
- if (fidelity.headerMissing.length > 0) {
161
- problems.push('首部缺字段: ' + fidelity.headerMissing.join('、'));
162
- }
163
- if (fidelity.orderIssue) {
164
- problems.push('段序乱(「' + fidelity.orderIssue.replace(/^##\s*/, '') +
165
- '」偏离模板段序——应为 做了什么→改动文件→verify 输出→6 维自查→越界检查→自检方法)');
166
- }
167
- if (fidelity.missingSections.length > 0) {
168
- problems.push('缺段: ' + fidelity.missingSections.join('、'));
169
- }
170
- if (problems.length > 0) {
171
- if (isNewChange(state)) {
172
- hardIssues.push(f + ' 模板保真校验失败: ' + problems.join('; '));
173
- } else {
174
- console.error('SUMMARY TEMPLATE WARN: ' + f + ' ' + problems.join('; ') +
175
- '(旧 change/归档批渐进,不阻断;新 change 将强制)');
176
- }
177
- }
178
- // ④ 全骨架保真:模板在场时新 change 缺段/乱序/自检位置非法 → BLOCK;
179
- // 模板缺失时骨架来自内置兜底,不据此新增阻断(旧格式兼容)。
180
- const skeletonFidelity = summarySkeletonFidelity(content, skeleton);
181
- const skeletonProblems = [];
182
- if (skeletonFidelity.missingSections.length > 0) {
183
- skeletonProblems.push('缺段: ' + skeletonFidelity.missingSections.join('、'));
184
- }
185
- if (skeletonFidelity.orderIssue) {
186
- skeletonProblems.push('段序乱(「' + skeletonFidelity.orderIssue.replace(/^##\s*/, '') +
187
- '」偏离 flow-kit/templates/SUMMARY.md 的段序)');
188
- }
189
- if (skeletonFidelity.selfCheckIssue) {
190
- skeletonProblems.push(skeletonFidelity.selfCheckIssue);
191
- }
192
- if (skeletonProblems.length > 0) {
193
- if (isNewChange(state) && skeleton.derived) {
194
- skeletonGuidanceNeeded = true;
195
- hardIssues.push(f + ' SUMMARY 全骨架校验失败: ' + skeletonProblems.join('; '));
196
- } else {
197
- console.error('SUMMARY TEMPLATE WARN: ' + f + ' ' + skeletonProblems.join('; ') +
198
- (skeleton.derived
199
- ? '(旧 change/归档批渐进,不阻断;新 change 将强制)'
200
- : '(模板缺失,按内置骨架提示;不新增阻断)'));
201
- }
696
+ text = await fs.readFile(path.join(changeDir, file), 'utf8');
697
+ } catch {
698
+ continue;
699
+ }
700
+ // 首部字段键集来自登记表(模板缺席时同样可得)——SUMMARY 首部四字段是既有硬要求,不退化为软提醒
701
+ const issues = collectArtifactIssues({
702
+ text,
703
+ skeleton,
704
+ derived,
705
+ template,
706
+ requiredHeaderFields: skeleton.headerFields,
707
+ });
708
+ if (!derived) addLegacySummaryIssues(text, issues);
709
+ entries.push({ fileLabel: file, issues });
710
+ }
711
+ if (entries.length === 0) return;
712
+ await reportArtifactStructure({
713
+ changeDir,
714
+ state,
715
+ assessments: entries.map((entry) => assessArtifact({ ...entry, skeleton, derived })),
716
+ });
717
+ }
718
+
719
+ // 节点 → 待校验工件:单一来源 = 协议。**该节点是否受模板门禁**由 protocol-utils 的
720
+ // nodeTemplateDeclaration 决定(内置节点取引擎映射、自定义节点取协议 node.templates,未声明 =
721
+ // 零模板 ⇒ 不校验,ADR-002 特化层);**产出哪份工件**取该节点 outputSchemas 的 artifacts[].paths
722
+ // (`<change-id>/…` 基),工件名 → 模板键的派生取 protocol-utils 的 templateKeyFromArtifactName
723
+ // (与结构预检的模板指针**同一实现**:口径只有一处,本模块不再持副本)——本模块不另写节点→工件映射。
724
+ // SUMMARY 由 execute 家族的专用门负责(它还要消费无模板时的兜底段序),此处跳过以免同一工件被
725
+ // 两条门重复判定。
726
+ async function nodeArtifactTargets(node) {
727
+ let protocol = null;
728
+ try {
729
+ protocol = await readProtocolFile(runRoot, protocolPath);
730
+ } catch {
731
+ return [];
732
+ }
733
+ const schemas = new Map((protocol.outputSchemas ?? []).map((schema) => [schema.id, schema]));
734
+ const targets = [];
735
+ for (const schemaId of node.outputSchemas ?? []) {
736
+ const schema = schemas.get(schemaId);
737
+ for (const artifact of schema?.artifacts ?? []) {
738
+ for (const pattern of artifact.paths ?? []) {
739
+ const segments = String(pattern ?? '').replaceAll('\\', '/').split('/');
740
+ if (segments.length !== 2 || segments[0] !== '<change-id>') continue;
741
+ // 传整条声明路径:路径归一(取末段、通配取末个 `*` 之后)由共享派生统一承担,
742
+ // 两处消费面因此走的是同一段归一逻辑,而不是各自先切一刀再交给共用的键归一。
743
+ const key = templateKeyFromArtifactName(pattern);
744
+ if (key === null) continue;
745
+ targets.push({ key, namePattern: segments[1] });
202
746
  }
203
- } catch {}
747
+ }
204
748
  }
205
- if (hardIssues.length > 0) {
206
- console.error('BLOCKED: SUMMARY 模板保真校验失败: ' + hardIssues.join('; '));
207
- console.error('恢复: 对照 flow-kit/templates/SUMMARY.md 修正标题/首部/段序(含 flow-comet 增量 ## 自检方法 段)后重试 exit;新 change 强制模板保真');
208
- if (skeletonGuidanceNeeded) {
209
- console.error('恢复: 对照 flow-kit/templates/SUMMARY.md 补齐缺失段的 H2 标题(条件段内容可写 N/A)并按模板顺序排列;## 自检方法 只允许文末或紧随 ## 越界检查 之后两种位置');
749
+ return targets;
750
+ }
751
+
752
+ async function expandArtifactTargets(changeDir, targets) {
753
+ const expanded = [];
754
+ for (const target of targets) {
755
+ if (!target.namePattern.includes('*')) {
756
+ expanded.push({ key: target.key, file: target.namePattern });
757
+ continue;
758
+ }
759
+ const matcher = new RegExp('^' + target.namePattern.split('*').map(literalRegExp).join('.*') + '$', 'u');
760
+ for (const entry of await fs.readdir(changeDir).catch(() => [])) {
761
+ if (matcher.test(entry)) expanded.push({ key: target.key, file: entry });
210
762
  }
763
+ }
764
+ return expanded;
765
+ }
766
+
767
+ // 工件 → 首部硬要求:入口文档(CHANGE/REQUIREMENT/DESIGN)沿用既有「Change ID 必在场」检查,
768
+ // SUMMARY 的四字段由专用门要求;其余工件的键集不新增硬性要求(只校验已在场键的值非空)。
769
+ const INTAKE_HEADER_KEYS = new Set(['CHANGE', 'REQUIREMENT', 'DESIGN']);
770
+
771
+ // 产出物的结构门(各节点出口):受门禁的节点逐个校验本节点产出的登记工件(模板权威)。导出名沿用
772
+ // 既有调用面(workflow-guard 的固定出口链)。所有工件同一口径:父段「适用」时结构子段必须在场
773
+ // (缺席即阻断,AC-2/AC-8),只有父段整段 N/A / 不适用时子段才豁免——不按工件分叉。
774
+ export async function runIntakeDocFidelityGate({ node, state }) {
775
+ if (!state.activeChange) return;
776
+ const declaration = nodeTemplateDeclaration(node);
777
+ if (declaration.source === 'none') return;
778
+ const changeDir = path.join(runRoot, '.specs', state.activeChange);
779
+ const declaredKeys = new Set([...declaration.required, ...declaration.optional].map((name) => templateKeyOf(name)));
780
+ const targets = await nodeArtifactTargets(node);
781
+ const assessments = [];
782
+ for (const target of await expandArtifactTargets(changeDir, targets)) {
783
+ const key = target.key;
784
+ if (templateKeyOf(key) === 'summary') continue;
785
+ if (declaration.source === 'protocol' && !declaredKeys.has(templateKeyOf(key))) continue;
786
+ const skeleton = await buildSkeleton(key);
787
+ if (skeleton.reason === 'unknown-key') continue; // 未登记的工件(UAT / DESIGN-lite 等)不做结构校验
788
+ const filePath = path.join(changeDir, target.file);
789
+ if (!(await fileExists(filePath))) continue;
790
+ let text;
791
+ try {
792
+ text = await fs.readFile(filePath, 'utf8');
793
+ } catch {
794
+ continue;
795
+ }
796
+ const evaluated = await evaluateArtifact(key, text, {
797
+ requiredHeaderFields: INTAKE_HEADER_KEYS.has(String(key).toUpperCase()) ? ['Change ID'] : [],
798
+ });
799
+ assessments.push(assessArtifact({
800
+ fileLabel: target.file,
801
+ skeleton: evaluated.skeleton,
802
+ derived: evaluated.derived,
803
+ issues: evaluated.issues,
804
+ }));
805
+ }
806
+ if (assessments.length > 0) await reportArtifactStructure({ changeDir, state, assessments });
807
+ if (node.id === 'design' && assessments.length === 0) await legacyDesignLiteTitle(changeDir, state);
808
+ }
809
+
810
+ // DESIGN-lite 不是登记工件(模板权威不收它的段形)→ 只保留既有标题形态校验。
811
+ async function legacyDesignLiteTitle(changeDir, state) {
812
+ const file = path.join(changeDir, 'DESIGN-lite.md');
813
+ if (!(await fileExists(file))) return;
814
+ let text;
815
+ try {
816
+ text = await fs.readFile(file, 'utf8');
817
+ } catch {
818
+ return;
819
+ }
820
+ const firstLine = (text.replace(/^\uFEFF/u, '').split('\n').find((line) => line.trim() !== '') ?? '').trim();
821
+ if (/^#\s*design\b/iu.test(firstLine)) return;
822
+ const message = 'DESIGN-lite.md 标题应以 # DESIGN 开头(如 `# DESIGN: <标题>`,大小写不敏感、冒号可省)';
823
+ if (isNewChange(state)) {
824
+ console.error('BLOCKED: ' + message);
825
+ console.error('恢复: 修正 DESIGN-lite.md 首行标题后重试 exit design');
211
826
  process.exit(1);
212
827
  }
828
+ console.error('INTAKE-DOC WARN: ' + message + '(旧 change 渐进,不阻断;新 change 将强制)');
213
829
  }
214
830
 
215
831
  // TASK 7 字段完整性门禁(plan 出口):每个 <task> 块须含
@@ -249,54 +865,3 @@ export async function runTaskSevenFieldGate({ node, state }) {
249
865
  }
250
866
  } catch {}
251
867
  }
252
-
253
- // 入口文档模板保真门禁(open / design 出口):标题与模板一致(# CHANGE: / # REQUIREMENT: /
254
- // # DESIGN:,大小写不敏感、冒号可省)+ 段序按模板派生骨架宽容匹配(编号前缀/括号后缀兼容);
255
- // 首部必要字段(Change ID)缺失 → 渐进 WARN。新 change 标题/段序失配 → BLOCK + 恢复指引;
256
- // 旧 change/归档批 → WARN 渐进。
257
- export async function runIntakeDocFidelityGate({ node, state }) {
258
- if ((node.id !== 'open' && node.id !== 'design') || !state.activeChange) return;
259
- const intakeDir = path.join(runRoot, '.specs', state.activeChange);
260
- const skeletonsCache = {};
261
- const hardProblems = [];
262
- const softWarnings = [];
263
- const checkIntakeDoc = async (file, key, label, titleRe) => {
264
- const p = path.join(intakeDir, file);
265
- if (!(await fileExists(p))) return; // 文件缺失由产物校验兜底
266
- const text = await fs.readFile(p, 'utf8');
267
- const firstLine = (text.replace(/\uFEFF/g, '').split('\n').find((l) => l.trim().length > 0) || '').trim();
268
- if (!titleRe.test(firstLine)) {
269
- hardProblems.push(file + ' 标题应以 # ' + label + ' 开头(如 `# ' + label + ': <标题>`,大小写不敏感、冒号可省)');
270
- }
271
- if (!skeletonsCache[key]) skeletonsCache[key] = await templateSkeleton(key);
272
- const viol = templateOrderViolation(skeletonsCache[key], documentSectionHeadings(text));
273
- if (viol) {
274
- hardProblems.push(file + ' 段序乱(「' + String(viol).replace(/^##\s*/, '') + '」偏离 ' + label + ' 模板段序)');
275
- }
276
- const changeIdMissing = !/\*\*\s*Change\s+ID\s*\*\*/i.test(text.split(/\n##\s/)[0]);
277
- const intakeMsg = file + ' 首部缺 Change ID 字段(' + label + ' 模板首部含 `- **Change ID**: <id>`)';
278
- if (changeIdMissing) {
279
- if (isNewChange(state)) hardProblems.push(intakeMsg);
280
- else softWarnings.push(intakeMsg + '(渐进提示;新 change 将强制)');
281
- }
282
- };
283
- if (node.id === 'open') {
284
- await checkIntakeDoc('CHANGE.md', 'change', 'CHANGE', /^#\s*change\b/i);
285
- await checkIntakeDoc('REQUIREMENT.md', 'requirement', 'REQUIREMENT', /^#\s*requirement\b/i);
286
- } else {
287
- // design:与既有校验一致的 target 选择(DESIGN.md 优先,DESIGN-lite 兜底)
288
- const designFile = path.join(intakeDir, 'DESIGN.md');
289
- const designLite = path.join(intakeDir, 'DESIGN-lite.md');
290
- const chosen = (await fileExists(designFile)) ? 'DESIGN.md' : ((await fileExists(designLite)) ? 'DESIGN-lite.md' : null);
291
- if (chosen) await checkIntakeDoc(chosen, 'design', 'DESIGN', /^#\s*design\b/i);
292
- }
293
- for (const w of softWarnings) console.error('INTAKE-DOC WARN: ' + w + '(渐进提示,不阻断;新 change 同)');
294
- if (hardProblems.length > 0) {
295
- if (isNewChange(state)) {
296
- console.error('BLOCKED: 入口文档模板保真校验失败: ' + hardProblems.join('; '));
297
- console.error('恢复: 对照 flow-kit/templates/{CHANGE,REQUIREMENT,DESIGN}.md 修正标题与段序后重试 exit;新 change 强制模板保真');
298
- process.exit(1);
299
- }
300
- for (const h of hardProblems) console.error('INTAKE-DOC WARN: ' + h + '(旧 change/归档批渐进,不阻断;新 change 将强制)');
301
- }
302
- }