flow-comet 1.6.4 → 1.6.5

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 (64) hide show
  1. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  2. package/.flow-comet/skills/flow-comet/SKILL.md +21 -3
  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/entry-detail.md +8 -2
  6. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +22 -0
  7. package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +174 -0
  8. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +3 -1
  9. package/.flow-comet/skills/flow-comet/scripts/health.mjs +28 -4
  10. package/.flow-comet/skills/flow-comet/scripts/items/a.mjs +41 -18
  11. package/.flow-comet/skills/flow-comet/scripts/items/b.mjs +16 -16
  12. package/.flow-comet/skills/flow-comet/scripts/items/c.mjs +6 -6
  13. package/.flow-comet/skills/flow-comet/scripts/items/h.mjs +9 -7
  14. package/.flow-comet/skills/flow-comet/scripts/items/l.mjs +2 -2
  15. package/.flow-comet/skills/flow-comet/scripts/items/m.mjs +17 -13
  16. package/.flow-comet/skills/flow-comet/scripts/items/n.mjs +154 -0
  17. package/.flow-comet/skills/flow-comet/scripts/lib/guard-artifact-skeleton.mjs +406 -0
  18. package/.flow-comet/skills/flow-comet/scripts/lib/guard-evidence-gates.mjs +206 -3
  19. package/.flow-comet/skills/flow-comet/scripts/lib/guard-gates.mjs +458 -60
  20. package/.flow-comet/skills/flow-comet/scripts/lib/guard-routing.mjs +38 -58
  21. package/.flow-comet/skills/flow-comet/scripts/lib/guard-template-fidelity.mjs +642 -230
  22. package/.flow-comet/skills/flow-comet/scripts/lib/guard-uidesign.mjs +85 -14
  23. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-admin.mjs +43 -5
  24. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-flow.mjs +15 -1
  25. package/.flow-comet/skills/flow-comet/scripts/lib/state-explain.mjs +18 -1
  26. package/.flow-comet/skills/flow-comet/scripts/lib/state-skillmarkers.mjs +60 -0
  27. package/.flow-comet/skills/flow-comet/scripts/lib/system-fixtures.mjs +73 -9
  28. package/.flow-comet/skills/flow-comet/scripts/lib/test-fixtures.mjs +21 -1
  29. package/.flow-comet/skills/flow-comet/scripts/lib/text-anchor-checks.mjs +9 -0
  30. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +212 -0
  31. package/.flow-comet/skills/flow-comet/scripts/scenarios/a.mjs +15 -5
  32. package/.flow-comet/skills/flow-comet/scripts/scenarios/c.mjs +4 -4
  33. package/.flow-comet/skills/flow-comet/scripts/scenarios/e.mjs +20 -10
  34. package/.flow-comet/skills/flow-comet/scripts/scenarios/g.mjs +4 -1
  35. package/.flow-comet/skills/flow-comet/scripts/scenarios/j.mjs +6 -6
  36. package/.flow-comet/skills/flow-comet/scripts/scenarios/l.mjs +13 -5
  37. package/.flow-comet/skills/flow-comet/scripts/scenarios/n.mjs +2125 -0
  38. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +6 -5
  39. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +74 -2
  40. package/.flow-comet/skills/flow-comet-archive/SKILL.md +6 -2
  41. package/.flow-comet/skills/flow-comet-change/SKILL.md +6 -2
  42. package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +13 -3
  43. package/.flow-comet/skills/flow-comet-design/SKILL.md +15 -8
  44. package/.flow-comet/skills/flow-comet-dev/SKILL.md +1 -1
  45. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +1 -0
  46. package/.flow-comet/skills/flow-comet-execute/SKILL.md +13 -10
  47. package/.flow-comet/skills/flow-comet-health/SKILL.md +1 -1
  48. package/.flow-comet/skills/flow-comet-integration/SKILL.md +1 -1
  49. package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +14 -4
  50. package/.flow-comet/skills/flow-comet-open/SKILL.md +11 -9
  51. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +13 -3
  52. package/.flow-comet/skills/flow-comet-plan/SKILL.md +11 -7
  53. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +1 -1
  54. package/.flow-comet/skills/flow-comet-review/SKILL.md +15 -9
  55. package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +13 -3
  56. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +11 -8
  57. package/.flow-comet/skills/flow-comet-task/SKILL.md +1 -1
  58. package/.flow-comet/skills/flow-comet-test/SKILL.md +6 -2
  59. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +2 -2
  60. package/.flow-comet/skills/flow-comet-verify/SKILL.md +12 -8
  61. package/README.md +3 -3
  62. package/package.json +1 -1
  63. package/scripts/dsh-bridge.mjs +2 -2
  64. package/scripts/lib/installer-flowkit.mjs +43 -3
@@ -0,0 +1,2125 @@
1
+ // 场景组 n — 模板权威(L1):REQUIREMENT 的 25 条验收准则逐条落夹具。
2
+ // 元素形态 `{ name, run }`;计数由 `lib/count-derivation.mjs` 从本目录聚合,不手抄数字。
3
+ //
4
+ // 夹具设计纪律(本组每一条都遵守):
5
+ // · **模板夹具自足**:每个夹具根自己写 `flow-kit/templates/<DOC>.md`(维护者检出取 vendored
6
+ // 真迹作内容权威,CI 全新检出无 vendored 副本时按登记表合成等价段形)——判据的来源是夹具根
7
+ // 内的模板,因此断言不依赖检出形态,也不会因「模板缺席」被静默跳过。
8
+ // · **每条带反向构造**:负例(抽掉 / 改掉目标 → 必红)与正例(恢复到合规形态 → 必绿)成对构造;
9
+ // 文本类判据用「同一判据函数 + 变异探针」,抽掉目标文字后判据必须发声。
10
+ // · **只判结构级**:断言落在「拦没拦 / 报出了什么类别」上,不断言散文措辞(措辞由 T08/T09 定稿)。
11
+ //
12
+ // 待实现面:本组场景先于实现落盘(RED),由产出物门禁扩展 / 加载链 / 扫描与提名 / 侧命令 /
13
+ // 文本同步各任务转绿。
14
+
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+ import { spawnSync } from 'child_process';
18
+ import {
19
+ assertExit,
20
+ assertNotOut,
21
+ assertOut,
22
+ assertTrue,
23
+ baseState,
24
+ runGuard,
25
+ runState,
26
+ writeFile,
27
+ writeState,
28
+ } from '../lib/test-helpers.mjs';
29
+ import {
30
+ CHANGE_ID,
31
+ REPO_ROOT,
32
+ SCRIPTS_DIR,
33
+ TASK_DONE,
34
+ customProtocol,
35
+ dropNamedImport,
36
+ engineDefinitionHits,
37
+ engineDefinitionModule,
38
+ engineScriptTexts,
39
+ handoffFor,
40
+ } from '../lib/test-fixtures.mjs';
41
+ import { scenarioProtocolPath } from '../lib/test-assertions.mjs';
42
+ import { maintainerFacePresent, singleSourceImportProblems } from '../lib/text-anchor-checks.mjs';
43
+
44
+ // ---------- 登记表与模板夹具(夹具输入面,不是判据) ----------
45
+
46
+ const REGISTRY_FILE = path.join(SCRIPTS_DIR, '..', 'reference', 'artifact-templates.json');
47
+ const CHANGE_DIR = '.specs/' + CHANGE_ID;
48
+ const SKILLS_ROOT = path.join(SCRIPTS_DIR, '..', '..');
49
+
50
+ let registryMemo;
51
+ function artifactRegistry() {
52
+ if (registryMemo === undefined) {
53
+ try {
54
+ registryMemo = JSON.parse(fs.readFileSync(REGISTRY_FILE, 'utf8'));
55
+ } catch (e) {
56
+ throw new Error('登记表不可读: ' + REGISTRY_FILE + '(' + e.message + ')——模板权威场景的前提条件');
57
+ }
58
+ }
59
+ return registryMemo;
60
+ }
61
+
62
+ function docEntry(key) {
63
+ const templates = artifactRegistry().templates ?? {};
64
+ const hit = Object.keys(templates).find((name) => name.toLowerCase() === String(key).toLowerCase());
65
+ if (!hit) throw new Error('登记表缺模板键: ' + key);
66
+ return templates[hit];
67
+ }
68
+
69
+ function docRel(key) {
70
+ return docEntry(key).file;
71
+ }
72
+
73
+ function docBase(key) {
74
+ return path.posix.basename(docRel(key));
75
+ }
76
+
77
+ function docTitle(key) {
78
+ return String(docEntry(key).titleForm ?? '# ' + key).replace(/<[^>]*>/g, '夹具');
79
+ }
80
+
81
+ // 模板夹具正文:每段给一行占位正文,供「与模板该段逐字相同」判据构造(CI 合成形态与真实模板
82
+ // 同构的只有段形;真实模板在场时正文直接取真迹,判据更强)。正文整体包进尖括号——「模板留了待填位」
83
+ // 因此在不带 vendored 模板的全新检出(CI)里同样成立,AC-6 的逐字判据不会退化成空转。
84
+ function templatePlaceholder(sectionName) {
85
+ return '<模板占位正文(' + sectionName + '):照抄本行即视为未填写。>';
86
+ }
87
+
88
+ // 登记表合成形态的段正文覆盖:LESSONS 的「条目格式」段是条目字段键判据(C20)的唯一派生源,
89
+ // ARCHITECTURE 的「ADR 列表」段是 §3 条目字段键判据的唯一派生源——CI 全新检出没有 vendored 模板时
90
+ // 也要给出等价书写样例,否则该判据在 CI 里会退化成「无法派生」而空转(报告只能声明未校验)。
91
+ const TEMPLATE_BODY_FIXTURES = {
92
+ ARCHITECTURE: [[
93
+ 'ADR 列表',
94
+ [
95
+ '### ADR-NNN · <标题>',
96
+ '',
97
+ '- **状态**:proposed | accepted | deprecated | superseded by ADR-NNN',
98
+ '- **取舍**:…',
99
+ '- **决定**:…',
100
+ '- **理由**:…',
101
+ '- **代价**:…',
102
+ '- **来源 change**:<change-id 或 (initial)>',
103
+ '- **推翻成本**:低 / 中 / 高',
104
+ ].join('\n'),
105
+ ]],
106
+ LESSONS: [[
107
+ '条目格式',
108
+ [
109
+ '```markdown',
110
+ '### L-NNN · [tag1, tag2] 标题(一行内说清,便于目录扫读)',
111
+ '',
112
+ '- **首发**: <change-id> · <task-id> · <YYYY-MM-DD>',
113
+ '- **上次复核**: <YYYY-MM-DD>',
114
+ '- **适用栈**: <例 React 18+ / Node 20 / SQLite 当前 schema>',
115
+ '- **状态**: active / superseded-by:L-MMM / deprecated:<原因>',
116
+ '- **关键词**: <空格分隔,方便 grep;用任务里会出现的词>',
117
+ '```',
118
+ ].join('\n'),
119
+ ]],
120
+ };
121
+
122
+ function templateFixtureText(key) {
123
+ const realFile = path.join(REPO_ROOT, ...docRel(key).split('/'));
124
+ if (fs.existsSync(realFile)) return fs.readFileSync(realFile, 'utf8');
125
+ const entry = docEntry(key);
126
+ const lines = [docTitle(key), ''];
127
+ for (const section of entry.sections ?? []) {
128
+ const override = (TEMPLATE_BODY_FIXTURES[key] ?? []).find(([needle]) => section.name.includes(needle));
129
+ lines.push('## ' + section.name, '', override ? override[1] : templatePlaceholder(section.name), '');
130
+ }
131
+ return lines.join('\n');
132
+ }
133
+
134
+ function writeTemplateFixture(dir, key) {
135
+ writeFile(dir, docRel(key), templateFixtureText(key));
136
+ }
137
+
138
+ // 模板夹具(示例表格形态):把某段正文替换成一张带示例数据行的表。用于构造「照抄模板里的示例
139
+ // 表格」的逐字判据——真实模板在两种检出下形态不同(vendored 真迹 / 按登记表合成),这里显式给出
140
+ // 等价段形 + 示例数据,使夹具同构;判据只看模板该段正文是否属成品形态(示例表格行),不看措辞。
141
+ function writeTableTemplateFixture(dir, key, sectionNeedle, tableText) {
142
+ const lines = templateFixtureText(key).replace(/\uFEFF/g, '').replace(/\r\n?/g, '\n').split('\n');
143
+ const out = [];
144
+ let skipping = false;
145
+ let replaced = false;
146
+ for (const line of lines) {
147
+ if (/^##\s+/.test(line)) {
148
+ skipping = line.includes(sectionNeedle);
149
+ replaced = replaced || skipping;
150
+ if (skipping) out.push(line, '', tableText, '');
151
+ else out.push(line);
152
+ continue;
153
+ }
154
+ if (skipping) continue;
155
+ out.push(line);
156
+ }
157
+ if (!replaced) throw new Error('夹具构造失败:模板段不在场 ' + key + ' / ' + sectionNeedle);
158
+ writeFile(dir, docRel(key), out.join('\n'));
159
+ }
160
+
161
+ // 模板夹具(删段形态):把某段整段(标题 + 正文)从模板里删掉——构造「上游回退 / 模板比登记表少
162
+ // 一段」的滞后面,用于 C14「登记表多出的段被忽略并 WARN」与 C9「整份缺席 vs 只缺某段」两组判据。
163
+ // 行锚定只删 `## ` 起始的段块(正文里引用段名不会劫持,L-128)。
164
+ function writeTemplateFixtureOmittingSection(dir, key, sectionNeedle) {
165
+ const lines = templateFixtureText(key).replace(/\uFEFF/g, '').replace(/\r\n?/g, '\n').split('\n');
166
+ const out = [];
167
+ let skipping = false;
168
+ let removed = false;
169
+ for (const line of lines) {
170
+ if (/^##\s+/.test(line)) {
171
+ skipping = line.includes(sectionNeedle);
172
+ removed = removed || skipping;
173
+ if (skipping) continue;
174
+ out.push(line);
175
+ continue;
176
+ }
177
+ if (skipping) continue;
178
+ out.push(line);
179
+ }
180
+ if (!removed) throw new Error('夹具构造失败:模板段不在场 ' + key + ' / ' + sectionNeedle);
181
+ writeFile(dir, docRel(key), out.join('\n'));
182
+ }
183
+
184
+ // 模板某段正文(行锚定:段标题之后、下一个 H2 之前;首尾空行剥掉)。
185
+ function templateSectionBody(key, needle) {
186
+ const lines = templateFixtureText(key).replace(/\uFEFF/g, '').replace(/\r\n?/g, '\n').split('\n');
187
+ const out = [];
188
+ let inside = false;
189
+ for (const line of lines) {
190
+ if (/^##\s+/.test(line)) {
191
+ if (inside) break;
192
+ inside = line.includes(needle);
193
+ continue;
194
+ }
195
+ if (inside) out.push(line);
196
+ }
197
+ return out.join('\n').replace(/^\n+/, '').replace(/\n+$/, '');
198
+ }
199
+
200
+ // ---------- 工件渲染(夹具;段形与顺序全部由登记表驱动) ----------
201
+
202
+ const HEADER_VALUES = {
203
+ 'Change ID': CHANGE_ID,
204
+ '创建日期': '2026-10-20',
205
+ '路径建议': '完整',
206
+ '状态': 'active',
207
+ '关联': '@.specs/' + CHANGE_ID + '/REQUIREMENT.md',
208
+ '作者': 'AI + 人工 review',
209
+ 'Task ID': 'T01',
210
+ '完成时间': '2026-10-20 10:00',
211
+ 'AI 角色': 'Dev',
212
+ '审查时间': '2026-10-20 10:00',
213
+ '审查者': 'AI',
214
+ '总体结论': '通过',
215
+ '项目类型': 'backend',
216
+ '维护者': 'AI',
217
+ '首次创建': '2026-10-20',
218
+ '最近修订': '2026-10-20',
219
+ '当前 ADR 编号最大值': 'ADR-021',
220
+ '暂停时间': '2026-10-20 10:00',
221
+ '触发清窗的信号': '上下文将满',
222
+ };
223
+
224
+ // 条件段正文:显式标注「不适用」(同时也是「视觉调性缺席 → 前端」判据的负向标记形态)。
225
+ const CONDITIONAL_BODY = '不适用(本 change 不涉及该条件段,按模板占位)。';
226
+
227
+ const SIX_DIM_BODY = [
228
+ '- 功能: 通过(brooks-review 已跑)',
229
+ '- 性能: 无影响',
230
+ '- 安全: 无影响',
231
+ '- 兼容: 通过',
232
+ '- 可观测: 通过',
233
+ '- 可维护: 通过',
234
+ ].join('\n');
235
+
236
+ const VERIFY_COMMAND_BODY = ['```', 'node --check baseline.js', '```'].join('\n');
237
+
238
+ const TASK_BLOCK_BODY = '<task id="T01" status="done"><action>实现夹具被测项</action>'
239
+ + '<write_files>src/fixture.mjs</write_files><verify>node --check baseline.js</verify></task>';
240
+
241
+ // 段级正文覆盖:[模板键, 段名片段, 正文]——只在夹具需要实质内容的位置使用。
242
+ const BODY_OVERRIDES = [
243
+ ['SUMMARY', '6 维自查', SIX_DIM_BODY],
244
+ ['SUMMARY', 'verify 输出', VERIFY_COMMAND_BODY],
245
+ ['REQUIREMENT', '验收准则', '- Given 夹具前置\n- When 夹具动作\n- Then 夹具结果(AC 夹具)'],
246
+ ['REQUIREMENT', '用户故事', '- US-1 作为执行者,我想让夹具可通过结构校验。'],
247
+ ['TASK', '任务清单', TASK_BLOCK_BODY],
248
+ ['REVIEW', '2.2', '- **F1 · 夹具发现**:某处存在一个可记录的衰退风险 [已修]\n'
249
+ + ' - **Symptom**: 夹具现象\n - **Source**: 夹具来源\n'
250
+ + ' - **Consequence**: 夹具后果\n - **Remedy**: 夹具处置'],
251
+ ['TEST', '1.5', SIX_DIM_BODY],
252
+ ];
253
+
254
+ const INCREMENT_BODIES = {
255
+ '自检方法': 'brooks-review(夹具声明)。',
256
+ 'LESSONS 扫描': '扫描结果:无 active 条目命中(夹具)。',
257
+ '验证命令': VERIFY_COMMAND_BODY,
258
+ };
259
+
260
+ function defaultBody() {
261
+ return '本段按模板要求填写:实质内容(夹具,非模板原文)。';
262
+ }
263
+
264
+ function bodyFor(key, section, opts) {
265
+ for (const [needle, text] of opts.body ?? []) {
266
+ if (section.name.includes(needle)) return text;
267
+ }
268
+ for (const [docKey, needle, text] of BODY_OVERRIDES) {
269
+ if (docKey === key && section.name.includes(needle)) return text;
270
+ }
271
+ return section.conditional === true ? CONDITIONAL_BODY : defaultBody();
272
+ }
273
+
274
+ // 结构子段的正文:opts.body 的段名片段覆盖优先(构造「2.2 下的发现条目」这类子段正文形态),
275
+ // 其次段级默认正文(BODY_OVERRIDES,如 REVIEW 2.2 的列表项发现),最后才是通用占位正文。
276
+ function subsectionBody(key, name, opts) {
277
+ const override = (opts.body ?? []).find(([needle]) => name.includes(needle));
278
+ if (override) return override[1];
279
+ const registered = BODY_OVERRIDES.find(([docKey, needle]) => docKey === key && name.includes(needle));
280
+ return registered ? registered[2] : '本子段按模板要求填写:实质内容(夹具)。';
281
+ }
282
+
283
+ function matchesAny(name, needles) {
284
+ return (needles ?? []).some((needle) => name.includes(needle));
285
+ }
286
+
287
+ // 渲染工件。opts:
288
+ // title / headerEmpty / omit / rename([片段, 替换标题])/ swap([段A, 段B] 互换位置)/
289
+ // body([片段, 正文])/ subsectionOmit / incrementAfter([增量段, 锚段])/ insertAfter([锚段, 文本])/
290
+ // extra(追加到文末的文本块数组)
291
+ function renderDoc(key, opts = {}) {
292
+ const entry = docEntry(key);
293
+ const sections = (entry.sections ?? [])
294
+ .filter((section) => !matchesAny(section.name, opts.omit))
295
+ .map((section) => ({ ...section, heading: section.name }));
296
+ for (const section of sections) {
297
+ const renamed = (opts.rename ?? []).find(([needle]) => section.name.includes(needle));
298
+ if (renamed) section.heading = renamed[1];
299
+ }
300
+ for (const [a, b] of opts.swap ?? []) {
301
+ const ia = sections.findIndex((section) => section.name.includes(a));
302
+ const ib = sections.findIndex((section) => section.name.includes(b));
303
+ if (ia === -1 || ib === -1) throw new Error('夹具构造失败:swap 段不在登记表 ' + a + ' / ' + b);
304
+ const moved = sections.splice(ia, 1)[0];
305
+ sections.splice(ib, 0, moved);
306
+ }
307
+
308
+ const header = [opts.title !== undefined ? opts.title : docTitle(key), ''];
309
+ for (const field of entry.headerFields ?? []) {
310
+ header.push('- **' + field + '**: ' + (matchesAny(field, opts.headerEmpty) ? '' : (HEADER_VALUES[field] ?? '夹具值')), '');
311
+ }
312
+ if ((entry.headerFields ?? []).length > 0) header.push('---', '');
313
+
314
+ const blocks = [];
315
+ for (const section of sections) {
316
+ const body = bodyFor(key, section, opts);
317
+ const text = ['## ' + section.heading, '', body, ''].join('\n');
318
+ blocks.push({ name: section.name, text });
319
+ for (const [anchor, inserted] of opts.insertAfter ?? []) {
320
+ if (section.name.includes(anchor)) blocks.push({ name: anchor + '#inserted', text: inserted + '\n' });
321
+ }
322
+ // 条件段的正文仍是「不适用」占位 → 父段不适用,其结构子段不必在场;正文被覆盖成实质内容
323
+ // = 父段适用 → 结构子段必须在场(子段缺席即 BLOCK,无 WARN 让步)。不区分这一点会让夹具
324
+ // 自相矛盾:写了实质正文却不带子段,合规判据必然把它判成缺段。
325
+ if (section.conditional === true && body === CONDITIONAL_BODY) continue;
326
+ for (const child of (entry.structureSubsections ?? []).filter((item) => item.parent === section.name)) {
327
+ if (matchesAny(child.name, opts.subsectionOmit)) continue;
328
+ blocks.push({
329
+ name: child.name,
330
+ text: ['### ' + child.name, '', subsectionBody(key, child.name, opts), ''].join('\n'),
331
+ });
332
+ }
333
+ }
334
+
335
+ // 增量段(kind=section):默认把「自检方法」放在「紧随越界检查」这一合法位置(登记表的
336
+ // after-or-end 的 after 分支),其余增量段落文末;incrementAllAtEnd 构造「全部落在文末」的变体,
337
+ // incrementAfter 指定其它位置(用于非法位置的反向构造)。
338
+ const anchors = opts.incrementAllAtEnd === true
339
+ ? []
340
+ : (opts.incrementAfter ?? [['自检方法', '越界检查']]);
341
+ const pending = [];
342
+ for (const increment of entry.increments ?? []) {
343
+ if (increment.kind === 'marker') continue;
344
+ if (matchesAny(increment.section, opts.omit)) continue;
345
+ // 增量段正文同样接受 opts.body 覆盖(命中回应这类「可自定义正文」的判据需要构造正例);
346
+ // INCREMENT_BODIES 保留为兜底——自检方法段的默认正文是 brooks 判据的输入,不能被 defaultBody() 顶掉。
347
+ const override = (opts.body ?? []).find(([needle]) => increment.section.includes(needle));
348
+ const text = ['## ' + increment.section, '',
349
+ override ? override[1] : (INCREMENT_BODIES[increment.section] ?? defaultBody()), ''].join('\n');
350
+ const anchor = anchors.find(([needle]) => increment.section.includes(needle));
351
+ if (anchor) {
352
+ const idx = blocks.findIndex((block) => block.name.includes(anchor[1]));
353
+ if (idx === -1) throw new Error('夹具构造失败:增量段锚点不在登记表 ' + anchor[1]);
354
+ blocks.splice(idx + 1, 0, { name: increment.section, text });
355
+ } else {
356
+ pending.push({ name: increment.section, text });
357
+ }
358
+ }
359
+ blocks.push(...pending);
360
+ for (const extra of opts.extra ?? []) blocks.push({ name: 'extra', text: extra + '\n' });
361
+
362
+ return header.concat(blocks.map((block) => block.text)).join('\n');
363
+ }
364
+
365
+ // ---------- 状态与夹具根 ----------
366
+
367
+ function newChangeState(node) {
368
+ const st = baseState(node);
369
+ st.newChange = true;
370
+ st.enteredNodes = [node];
371
+ return st;
372
+ }
373
+
374
+ function exitNode(dir, node) {
375
+ return runGuard(['exit', node, '--apply'], dir);
376
+ }
377
+
378
+ function writeBaseline(dir) {
379
+ writeFile(dir, 'baseline.js', 'export const baseline = 1;\n');
380
+ }
381
+
382
+ // UI-DESIGN 工件:frontmatter 顶层键(登记表 frontmatterKeys)+ 模板段形。omitKeys 抽掉某个键,
383
+ // 用于「存在但缺 frontmatter 键」的判据;正文按登记表段形渲染。
384
+ function uiDesignDoc(opts = {}, omitKeys = []) {
385
+ const keys = docEntry('UI-DESIGN').frontmatterKeys ?? [];
386
+ const values = {
387
+ name: '夹具项目',
388
+ description: '夹具美学定位:温暖纸面编辑式。',
389
+ colors: ' brand: "oklch(0.62 0.12 250)"\n bg: "oklch(0.98 0.005 90)"',
390
+ typography: ' display:\n fontFamily: "Fixture Serif, serif"',
391
+ spacing: ' base: "4px"\n md: "12px"',
392
+ rounded: ' md: "8px"',
393
+ motion: ' fast: "120ms"',
394
+ shadow: ' sm: "0 1px 2px oklch(0 0 0 / 8%)"',
395
+ };
396
+ const lines = ['---'];
397
+ for (const key of keys) {
398
+ if (omitKeys.includes(key)) continue;
399
+ lines.push(key + ':', values[key] ?? ' fixture: true');
400
+ }
401
+ lines.push('---', '', renderDoc('UI-DESIGN', opts));
402
+ return lines.join('\n');
403
+ }
404
+
405
+ // 前端 change 的声明标记:节点自身协议标记(design → 2-design.md)与 ui-design 技能标记
406
+ // (guarded 绑定要求真实声明)。两者缺一都会先被证据门 / 标记门拦下,掩盖被测的段形判据。
407
+ function writeFrontendDesignMarkers(dir) {
408
+ writeFile(dir, CHANGE_DIR + '/.skill-loads/design-flow-comet-design.json',
409
+ JSON.stringify({
410
+ node: 'design', skill: 'flow-comet-design', protocol: '2-design.md',
411
+ templates: ['DESIGN'], at: '2026-08-01T00:00:00.000Z',
412
+ }, null, 2) + '\n');
413
+ writeFile(dir, CHANGE_DIR + '/.skill-loads/design-flow-comet-ui-design.json',
414
+ JSON.stringify({
415
+ node: 'design', skill: 'flow-comet-ui-design', protocol: '2a-ui-design.md',
416
+ templates: ['UI-DESIGN'], at: '2026-08-01T00:00:00.000Z',
417
+ }, null, 2) + '\n');
418
+ }
419
+
420
+ // 每个 setup 先清空 change 目录与归档目录:同一夹具根里连续构造多组用例时,上一组残留的工件
421
+ // (UI-DESIGN.md / .skill-loads/ 声明标记)会让「缺件」「缺声明」一类判据形同虚设。
422
+ function resetFixture(dir) {
423
+ for (const rel of [CHANGE_DIR, '.specs/archive']) {
424
+ fs.rmSync(path.join(dir, rel), { recursive: true, force: true });
425
+ }
426
+ }
427
+
428
+ function setupOpen(dir, changeOpts = {}, requirementOpts = {}) {
429
+ resetFixture(dir);
430
+ writeTemplateFixture(dir, 'CHANGE');
431
+ writeTemplateFixture(dir, 'REQUIREMENT');
432
+ writeFile(dir, CHANGE_DIR + '/CHANGE.md', renderDoc('CHANGE', changeOpts));
433
+ writeFile(dir, CHANGE_DIR + '/REQUIREMENT.md', renderDoc('REQUIREMENT', requirementOpts));
434
+ const st = newChangeState('open');
435
+ st.evidence.open = { summary: 'intake complete' };
436
+ writeState(dir, st);
437
+ }
438
+
439
+ function setupDesign(dir, { changeOpts = {}, designOpts = {}, uiDesign = undefined, declareUiDesign = false } = {}) {
440
+ resetFixture(dir);
441
+ writeTemplateFixture(dir, 'CHANGE');
442
+ writeTemplateFixture(dir, 'DESIGN');
443
+ writeFile(dir, CHANGE_DIR + '/CHANGE.md', renderDoc('CHANGE', changeOpts));
444
+ writeFile(dir, CHANGE_DIR + '/DESIGN.md', renderDoc('DESIGN', designOpts));
445
+ if (uiDesign !== undefined) {
446
+ writeTemplateFixture(dir, 'UI-DESIGN');
447
+ writeFile(dir, CHANGE_DIR + '/UI-DESIGN.md', uiDesign);
448
+ }
449
+ const st = newChangeState('design');
450
+ // guarded 绑定的 required-skill 证据:前端 change 必须在证据里声明已加载 ui-design 技能
451
+ st.evidence.design = declareUiDesign
452
+ ? { summary: 'design done', completedChecks: ['required-skill:design.flow-comet-ui-design'] }
453
+ : { summary: 'design done' };
454
+ writeState(dir, st);
455
+ }
456
+
457
+ function setupPlan(dir, taskOpts = {}) {
458
+ resetFixture(dir);
459
+ writeTemplateFixture(dir, 'TASK');
460
+ writeFile(dir, CHANGE_DIR + '/TASK.md', renderDoc('TASK', taskOpts));
461
+ const st = newChangeState('plan');
462
+ st.evidence.plan = { summary: 'plan done' };
463
+ writeState(dir, st);
464
+ }
465
+
466
+ function setupExecute(dir, summaryOpts = {}) {
467
+ resetFixture(dir);
468
+ writeTemplateFixture(dir, 'SUMMARY');
469
+ writeBaseline(dir);
470
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY', summaryOpts));
471
+ writeFile(dir, CHANGE_DIR + '/TASK.md', '# TASK\n\n## 任务清单\n\n' + TASK_DONE);
472
+ const st = newChangeState('execute');
473
+ st.evidence.execute = { summary: 'executed' };
474
+ st.evidence['subagent-execute'] = { handoffResult: handoffFor(['T01']) };
475
+ writeState(dir, st);
476
+ }
477
+
478
+ function setupReview(dir, reviewOpts = {}) {
479
+ resetFixture(dir);
480
+ writeTemplateFixture(dir, 'REVIEW');
481
+ writeFile(dir, CHANGE_DIR + '/REVIEW.md', renderDoc('REVIEW', reviewOpts));
482
+ const st = newChangeState('review');
483
+ st.evidence.review = { summary: 'review done' };
484
+ writeState(dir, st);
485
+ }
486
+
487
+ function setupVerify(dir, testOpts = {}) {
488
+ resetFixture(dir);
489
+ writeTemplateFixture(dir, 'TEST');
490
+ writeBaseline(dir);
491
+ writeFile(dir, CHANGE_DIR + '/TEST.md', renderDoc('TEST', testOpts));
492
+ writeFile(dir, CHANGE_DIR + '/UAT.md', '# UAT\n\n## 验收结果\n\n- 通过(夹具)。\n');
493
+ const st = newChangeState('verify');
494
+ st.evidence.verify = { summary: 'verified' };
495
+ writeState(dir, st);
496
+ }
497
+
498
+ const LESSONS_FIXTURE = [
499
+ '# LESSONS — 跨任务失败知识库(夹具)',
500
+ '',
501
+ '## 条目区(夹具)',
502
+ '',
503
+ '### L-501',
504
+ '',
505
+ '- **关键词**: guard, template',
506
+ '',
507
+ '夹具条目正文:判据必须按结构级校验,不做语义判断。',
508
+ '',
509
+ '### L-502',
510
+ '',
511
+ '- **关键词**: archive, nomination',
512
+ '',
513
+ '夹具条目正文:归档提名须留痕。',
514
+ '',
515
+ ].join('\n');
516
+
517
+ function setupArchive(dir, { evidence = {}, lessons = LESSONS_FIXTURE, summaryCount = 2 } = {}) {
518
+ resetFixture(dir);
519
+ writeFile(dir, '.specs/LESSONS.md', lessons);
520
+ for (let i = 1; i <= summaryCount; i += 1) {
521
+ writeFile(dir, CHANGE_DIR + '/T0' + i + '-SUMMARY.md',
522
+ '# SUMMARY: T0' + i + ' - 夹具\n\n## 做了什么\n\n夹具任务。\n');
523
+ }
524
+ writeFile(dir, '.specs/archive/2026-10-20-' + CHANGE_ID + '/KNOWN-ISSUES.md', '# KNOWN-ISSUES\n\n无遗留。\n');
525
+ const st = newChangeState('archive');
526
+ st.evidence.archive = { summary: 'archived', ...evidence };
527
+ writeState(dir, st);
528
+ }
529
+
530
+ function runSideCommand(dir, scriptRel, args) {
531
+ const res = spawnSync(process.execPath, [path.join(SCRIPTS_DIR, scriptRel), ...args], {
532
+ cwd: dir,
533
+ env: { ...process.env, FLOW_COMET_RUN_ROOT: dir, FLOW_COMET_PROTOCOL: scenarioProtocolPath(dir) },
534
+ encoding: 'utf8',
535
+ timeout: 60000,
536
+ });
537
+ return { status: res.status ?? 1, output: String(res.stdout || '') + String(res.stderr || '') };
538
+ }
539
+
540
+ function skillBookText(name) {
541
+ return fs.readFileSync(path.join(SKILLS_ROOT, name, 'SKILL.md'), 'utf8');
542
+ }
543
+
544
+ function repoFileText(rel) {
545
+ return fs.readFileSync(path.join(REPO_ROOT, ...rel.split('/')), 'utf8');
546
+ }
547
+
548
+ function repoFileExists(rel) {
549
+ return fs.existsSync(path.join(REPO_ROOT, ...rel.split('/')));
550
+ }
551
+
552
+ // 文本判据(同一函数驱动真实断言与变异探针):rules = [{ rel, label, include[], exclude[] }]。
553
+ function textRuleProblems(docs, rules) {
554
+ const problems = [];
555
+ for (const rule of rules) {
556
+ const text = docs.get(rule.rel);
557
+ if (typeof text !== 'string') {
558
+ problems.push(rule.rel + ' 不在判据面内(' + rule.label + ')');
559
+ continue;
560
+ }
561
+ for (const needle of rule.include ?? []) {
562
+ if (!text.includes(needle)) problems.push(rule.rel + ' 缺「' + needle + '」(' + rule.label + ')');
563
+ }
564
+ for (const needle of rule.exclude ?? []) {
565
+ if (text.includes(needle)) problems.push(rule.rel + ' 仍含旧表述「' + needle + '」(' + rule.label + ')');
566
+ }
567
+ }
568
+ return problems;
569
+ }
570
+
571
+ // 变异探针:同一判据函数驱动——正向探针(把目标文字抽掉 / 改回旧表述 ⇒ 必须报),反向探针
572
+ // (把缺失的目标文字补上 ⇒ 必须不再报,证明判据不恒真)。判别力不能只靠「判据能报违规」证。
573
+ function assertProbesDiscriminate(problems, docs, rules, probes) {
574
+ for (const [label, rel, mutate, expected, expectReported = true] of probes) {
575
+ const before = docs.get(rel);
576
+ const probed = new Map(docs).set(rel, mutate(before));
577
+ if (probed.get(rel) === before) {
578
+ problems.push('反向构造前提失效(' + label + '):变异未改变 ' + rel);
579
+ continue;
580
+ }
581
+ const reported = textRuleProblems(probed, rules).some((problem) => problem.includes(expected));
582
+ if (reported !== expectReported) {
583
+ problems.push('反向构造判别力缺失(' + label + ':' + (expectReported ? '未被判违规' : '被误判违规') + ')');
584
+ }
585
+ }
586
+ }
587
+
588
+ export const ENTRIES = [
589
+
590
+ // ============================================================================================
591
+ // 产出物结构(七类工件)
592
+ // ============================================================================================
593
+
594
+ // TA-01 · 七类产出物缺段被拦(AC-1)——每类取一个夹具:缺模板中的一个必填 H2 → BLOCKED,报文含
595
+ // 模板路径与「缺段」类别计数;首次**不列具体段名**(段名清单留到再犯时给,见 TA-15)。
596
+ // 反向构造:同夹具补回该段 → 通过(旧逻辑对这批段本就不查,故负例在旧实现上必然放过)。
597
+ {
598
+ name: 'TA-01 七类产出物缺必填 H2:各节点出口 BLOCKED(含模板路径与缺段计数),补回后通过',
599
+ run: async (dir) => {
600
+ const cases = [
601
+ { doc: 'CHANGE', node: 'open', omit: '影响面', setup: setupOpen },
602
+ { doc: 'REQUIREMENT', node: 'open', omit: '非功能性需求', setup: (root, opts) => setupOpen(root, {}, opts) },
603
+ { doc: 'DESIGN', node: 'design', omit: '风险', setup: (root, opts) => setupDesign(root, { designOpts: opts }) },
604
+ { doc: 'TASK', node: 'plan', omit: '阻塞日志', setup: setupPlan },
605
+ { doc: 'SUMMARY', node: 'execute', omit: '是否触发新工作', setup: setupExecute },
606
+ { doc: 'REVIEW', node: 'review', omit: '总结', setup: setupReview },
607
+ { doc: 'TEST', node: 'verify', omit: '新增测试登记', setup: setupVerify },
608
+ ];
609
+ for (const item of cases) {
610
+ const label = item.doc + ' 缺「' + item.omit + '」';
611
+ // ① 负例:缺段 → BLOCKED,且报文带模板路径与缺段类别
612
+ item.setup(dir, { omit: [item.omit] });
613
+ const blocked = exitNode(dir, item.node);
614
+ assertTrue(blocked.status === 1, label + ' 应被拦(exit 1),实际 exit ' + blocked.status + '\n' + blocked.output);
615
+ assertOut(blocked, 'BLOCKED');
616
+ assertOut(blocked, 'flow-kit/templates/' + docBase(item.doc));
617
+ assertTrue(/缺段[^\n]{0,12}\d/.test(blocked.output), label + ' 报文应含「缺段」类别与计数,实际: ' + blocked.output);
618
+ // 首次不列段名:抽掉的段名不得出现在报文里(否则「先读模板」的引导被绕过)
619
+ assertNotOut(blocked, item.omit);
620
+ // ② 反向构造:补回该段 → 通过
621
+ item.setup(dir);
622
+ const passed = exitNode(dir, item.node);
623
+ assertTrue(passed.status === 0, '补回「' + item.omit + '」后应通过,实际 exit ' + passed.status + '\n' + passed.output);
624
+ assertOut(passed, 'ALL CHECKS PASSED');
625
+ }
626
+ },
627
+ },
628
+
629
+ // TA-02 · H3 结构子段纳入、示例条目排除(AC-2)——① TEST 缺 1.5 结构子段 → BLOCKED;
630
+ // ② SUMMARY 缺「已知接受 + 理由」→ BLOCKED;③ 示例条目(🔴 / ADR- / AC- / L- 形态)未出现
631
+ // **不算缺段**(正例即「无任何示例条目的工件必须放行」)。
632
+ {
633
+ name: 'TA-02 H3 结构子段缺则拦(TEST 1.5 / SUMMARY 已知接受 + 理由),示例条目不参与骨架',
634
+ run: async (dir) => {
635
+ // ① TEST 缺结构子段
636
+ setupVerify(dir, { subsectionOmit: ['测试质量自检'] });
637
+ const resTest = exitNode(dir, 'verify');
638
+ assertExit(resTest, 1);
639
+ assertOut(resTest, '测试质量自检');
640
+ // ② SUMMARY 缺结构子段
641
+ setupExecute(dir, { subsectionOmit: ['已知接受'] });
642
+ const resSummary = exitNode(dir, 'execute');
643
+ assertExit(resSummary, 1);
644
+ assertOut(resSummary, '已知接受');
645
+ // ③ 反向构造:示例条目缺席不算缺段(正例;旧口径把示例当骨架即误拦)
646
+ const exampleFree = renderDoc('TEST');
647
+ assertTrue(!/🔴|ADR-\d|L-\d{3}/.test(exampleFree), '夹具前提不成立:正例正文不该含示例条目形态');
648
+ setupVerify(dir);
649
+ const resBaseline = exitNode(dir, 'verify');
650
+ assertExit(resBaseline, 0);
651
+ assertOut(resBaseline, 'ALL CHECKS PASSED');
652
+ // ④ 反向构造(判别力):被抽掉的 TEST 子段确实来自登记表骨架,而不是标题巧合
653
+ const registered = (docEntry('TEST').structureSubsections ?? []).map((s) => s.name).join('\n');
654
+ assertTrue(registered.includes('测试质量自检'), '登记表未登记 TEST 的 1.5 结构子段——判据无处生根');
655
+ },
656
+ },
657
+
658
+ // TA-03 · 段序按模板全序(AC-3)——SUMMARY 把「数据库迁移」排到「越界检查」之后 → BLOCKED 且报文
659
+ // 指明段序偏离。反向构造:同夹具保持模板序 → 通过。
660
+ {
661
+ name: 'TA-03 段序偏离模板全序:SUMMARY 数据库迁移排到越界检查之后 → BLOCKED(报文含段序)',
662
+ run: async (dir) => {
663
+ setupExecute(dir, { swap: [['数据库迁移', '越界检查']] });
664
+ const res = exitNode(dir, 'execute');
665
+ assertExit(res, 1);
666
+ assertOut(res, 'BLOCKED');
667
+ assertOut(res, '段序');
668
+ assertOut(res, '数据库迁移');
669
+ setupExecute(dir);
670
+ const ok = exitNode(dir, 'execute');
671
+ assertExit(ok, 0);
672
+ assertOut(ok, 'ALL CHECKS PASSED');
673
+ },
674
+ },
675
+
676
+ // TA-04 · 标题形态与首部字段(AC-4)——① 标题不是模板形态(`# 变更文档`)→ 拦;② 首部
677
+ // `- **Change ID**:` 有键但值为空 → 视为未填 → 拦。反向构造:两者都合规 → 通过。
678
+ {
679
+ name: 'TA-04 标题形态与首部空值:`# 变更文档` / `- **Change ID**:` 空值均拦,合规形态通过',
680
+ run: async (dir) => {
681
+ // ① 标题形态
682
+ setupOpen(dir, { title: '# 变更文档' });
683
+ const resTitle = exitNode(dir, 'open');
684
+ assertExit(resTitle, 1);
685
+ assertOut(resTitle, 'CHANGE');
686
+ // ② 首部有键无值(旧口径只查键在场 → 必然放过)
687
+ setupOpen(dir, { headerEmpty: ['Change ID'] });
688
+ const resHeader = exitNode(dir, 'open');
689
+ assertExit(resHeader, 1);
690
+ assertOut(resHeader, 'Change ID');
691
+ // ③ 反向构造:标题与首部合规 → 通过
692
+ setupOpen(dir);
693
+ const ok = exitNode(dir, 'open');
694
+ assertExit(ok, 0);
695
+ assertOut(ok, 'ALL CHECKS PASSED');
696
+ },
697
+ },
698
+
699
+ // TA-05 · 无条件段空正文被拦 + 六词白名单(AC-5)——CHANGE 的「影响面」空白 → BLOCKED;
700
+ // 同段写 无 / N/A / 不适用 / — / 未涉及 / 无变更 任一 → 通过(逐词对照组)。
701
+ {
702
+ name: 'TA-05 无条件段空正文:影响面空白拦,六个白名单词逐一放行',
703
+ run: async (dir) => {
704
+ // ① 空白正文(含仅空白行)
705
+ setupOpen(dir, { body: [['影响面', ' \n\n\t']] });
706
+ const blank = exitNode(dir, 'open');
707
+ assertExit(blank, 1);
708
+ assertOut(blank, 'BLOCKED');
709
+ assertOut(blank, '影响面');
710
+ // ② 六词白名单(单变量:只改该段正文)
711
+ for (const word of ['无', 'N/A', '不适用', '—', '未涉及', '无变更']) {
712
+ setupOpen(dir, { body: [['影响面', word]] });
713
+ const res = exitNode(dir, 'open');
714
+ assertTrue(res.status === 0, '白名单词「' + word + '」应放行,实际 exit ' + res.status + '\n' + res.output);
715
+ assertOut(res, 'ALL CHECKS PASSED');
716
+ }
717
+ // ③ 反向构造(判别力):白名单是**整段取值**而非子串——含白名单词的真实句子仍算已填,不误拦
718
+ setupOpen(dir, { body: [['影响面', '无变更风险;影响 CHANGE 与 REQUIREMENT 两份工件。']] });
719
+ const ok = exitNode(dir, 'open');
720
+ assertTrue(ok.status === 0, '含白名单词的真实句子应放行(判据不得退化为子串命中),实际 exit '
721
+ + ok.status + '\n' + ok.output);
722
+ },
723
+ },
724
+
725
+ // TA-06 · 照抄模板正文被拦(AC-6)——① 含待填位的模板正文(尖括号占位 / 复选框)逐字相同 →
726
+ // 判未填 → BLOCKED;② 模板正文为成品形态(示例表格行)同样逐字比对——SUMMARY「改动文件」照抄
727
+ // 模板里的示例文件清单(别的项目的文件)→ BLOCKED;两处各配「改写一个字符 → 通过」的单变量对照。
728
+ {
729
+ name: 'TA-06 与模板该段逐字相同判未填:照抄占位符拦,改写后通过',
730
+ run: async (dir) => {
731
+ const verbatim = templateSectionBody('CHANGE', '影响面');
732
+ assertTrue(verbatim.trim() !== '', '夹具前提不成立:模板「影响面」段正文为空,无法构造逐字相同夹具');
733
+ // ① 逐字相同 → 拦
734
+ setupOpen(dir, { body: [['影响面', verbatim]] });
735
+ const copied = exitNode(dir, 'open');
736
+ assertExit(copied, 1);
737
+ assertOut(copied, 'BLOCKED');
738
+ // ② 反向构造:改写一个字符 → 通过
739
+ const rewritten = verbatim + '(已按本 change 实际情况改写)';
740
+ assertTrue(rewritten !== verbatim, '夹具前提不成立:改写未改变正文');
741
+ setupOpen(dir, { body: [['影响面', rewritten]] });
742
+ const ok = exitNode(dir, 'open');
743
+ assertExit(ok, 0);
744
+ assertOut(ok, 'ALL CHECKS PASSED');
745
+ // ③ 模板正文为成品形态:示例表格行(无尖括号占位 / 复选框)照抄同样判未填。
746
+ // 夹具自建该段正文(示例文件清单是「已填好的别的项目」形态),模板夹具与工件写同一内容。
747
+ const exampleTable = [
748
+ '| 文件 | 性质 | 说明 |',
749
+ '|---|---|---|',
750
+ '| `src/example/Fixture.ts` | 新增 | 模板示例行:实现夹具能力 |',
751
+ '| `src/example/fixture.test.ts` | 新增 | 模板示例行:单元测试 |',
752
+ ].join('\n');
753
+ setupExecute(dir);
754
+ writeTableTemplateFixture(dir, 'SUMMARY', '改动文件', exampleTable);
755
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY', { body: [['改动文件', exampleTable]] }));
756
+ const copiedTable = exitNode(dir, 'execute');
757
+ assertExit(copiedTable, 1);
758
+ assertOut(copiedTable, '改动文件');
759
+ assertOut(copiedTable, '逐字');
760
+ // ④ 反向构造(判别力):只改表格里一个值(换成本任务自己的文件)→ 通过
761
+ const rewrittenTable = exampleTable.replace('src/example/Fixture.ts', 'src/real/Real.ts');
762
+ assertTrue(rewrittenTable !== exampleTable, '夹具前提不成立:改写未改变示例表');
763
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY', { body: [['改动文件', rewrittenTable]] }));
764
+ const okTable = exitNode(dir, 'execute');
765
+ assertExit(okTable, 0);
766
+ assertOut(okTable, 'ALL CHECKS PASSED');
767
+ },
768
+ },
769
+
770
+ // TA-07 · 条件段标题必须在场(AC-7)——① CHANGE 缺「视觉调性」标题 → BLOCKED(标题缺席);
771
+ // ② 标题在场、正文写「不适用」→ 通过。反向构造即 ②。
772
+ {
773
+ name: 'TA-07 条件段标题必须在场:CHANGE 缺视觉调性拦,正文写不适用放行',
774
+ run: async (dir) => {
775
+ // ① 标题缺席
776
+ setupOpen(dir, { omit: ['视觉调性'] });
777
+ const missing = exitNode(dir, 'open');
778
+ assertExit(missing, 1);
779
+ assertOut(missing, '视觉调性');
780
+ // ② 标题在场 + 正文不适用 → 通过
781
+ setupOpen(dir, { body: [['视觉调性', '不适用']] });
782
+ const ok = exitNode(dir, 'open');
783
+ assertExit(ok, 0);
784
+ assertOut(ok, 'ALL CHECKS PASSED');
785
+ // ③ 反向构造(判别力):把「视觉调性」改名成核心词不同的形态 ⇒ 等价于标题缺席,仍须拦
786
+ setupOpen(dir, { rename: [['视觉调性', '视觉风格']] });
787
+ const renamed = exitNode(dir, 'open');
788
+ assertExit(renamed, 1);
789
+ },
790
+ },
791
+
792
+ // TA-08 · 条件子段与父段豁免(AC-8)+ 可选段语义(C-1)——① 前端 change 的 UI-DESIGN 缺
793
+ // `### Button (Primary)` → BLOCKED(注意 Primary / Secondary 归一后同键:只写 Secondary 不得算
794
+ // Primary 在场);② 非前端 change 的 TEST 第 4 轮整段 N/A 且缺 4.1~4.4 子段 → 通过(父段 N/A →
795
+ // 子段不要求);⑤⑥ UI-DESIGN §0(optional)整段删除合法,但保留标题就得填。
796
+ {
797
+ name: 'TA-08 条件子段与父段豁免:UI-DESIGN 缺 Button (Primary) 拦;TEST 第 4 轮 N/A 放行',
798
+ run: async (dir) => {
799
+ const frontendChange = { body: [['视觉调性', '- **选定**:6 有机 / Organic\n- **理由**:前端夹具']] };
800
+ // ① 前端 change:缺 Button (Primary)(同段保留 Button (Secondary) 作单变量对照)
801
+ setupDesign(dir, {
802
+ changeOpts: frontendChange,
803
+ uiDesign: uiDesignDoc({ subsectionOmit: ['Button (Primary)'] }),
804
+ declareUiDesign: true,
805
+ });
806
+ writeFrontendDesignMarkers(dir);
807
+ const resUi = exitNode(dir, 'design');
808
+ assertExit(resUi, 1);
809
+ assertOut(resUi, 'Button (Primary)');
810
+ // ② 反向构造:补回 Primary(Secondary 同时在场)→ 通过
811
+ setupDesign(dir, { changeOpts: frontendChange, uiDesign: uiDesignDoc(), declareUiDesign: true });
812
+ writeFrontendDesignMarkers(dir);
813
+ const okUi = exitNode(dir, 'design');
814
+ assertExit(okUi, 0);
815
+ // ③ 非前端 change:第 4 轮父段 N/A、缺 4.1~4.4 子段 → 通过(默认夹具即此形态)
816
+ setupVerify(dir);
817
+ const okTest = exitNode(dir, 'verify');
818
+ assertExit(okTest, 0);
819
+ assertOut(okTest, 'ALL CHECKS PASSED');
820
+ // ④ 反向构造(判别力):把第 4 轮改成有实质内容 → 其结构子段重新变为必填 → 缺子段必拦
821
+ setupVerify(dir, { body: [['兼容性测试', '实测了三种视口组合的兼容性结论。']], subsectionOmit: ['跨浏览器'] });
822
+ const resRound4 = exitNode(dir, 'verify');
823
+ assertExit(resRound4, 1);
824
+ assertOut(resRound4, '跨浏览器');
825
+ // ⑤ 可选段(optional)语义:UI-DESIGN §0 是模板自述「greenfield 删掉此段」的可选段——
826
+ // 整段缺席合法,不得报「条件段标题缺席」(与 conditional 分流;conditional 仍要求标题在场,见 TA-07)。
827
+ setupDesign(dir, {
828
+ changeOpts: frontendChange,
829
+ uiDesign: uiDesignDoc({ omit: ['0. 视觉语汇对齐'] }),
830
+ declareUiDesign: true,
831
+ });
832
+ writeFrontendDesignMarkers(dir);
833
+ const okOptional = exitNode(dir, 'design');
834
+ assertExit(okOptional, 0);
835
+ assertOut(okOptional, 'ALL CHECKS PASSED');
836
+ // ⑥ 反向构造(判别力):保留 §0 标题但正文空、且不带 0.1~0.3 子段 → 必拦
837
+ // (可选段「保留即须填」——缺席与留空壳是两件事)
838
+ setupDesign(dir, {
839
+ changeOpts: frontendChange,
840
+ uiDesign: uiDesignDoc({ body: [['视觉语汇对齐', ' ']], subsectionOmit: ['0.1', '0.2', '0.3'] }),
841
+ declareUiDesign: true,
842
+ });
843
+ writeFrontendDesignMarkers(dir);
844
+ const resEmptyOptional = exitNode(dir, 'design');
845
+ assertExit(resEmptyOptional, 1);
846
+ assertOut(resEmptyOptional, '0.1');
847
+ },
848
+ },
849
+
850
+ // TA-09 · 段名宽容四变体(AC-9)——省括号 / 括号不同 / 大小写不同 → 均通过;核心词不同
851
+ // (`0.5 架构对齐`)→ BLOCKED。
852
+ // 正例的两个条件父段(`0.5 既有架构对齐` / `9. 架构沉淀建议`)都给实质正文 = 父段适用 → 其结构
853
+ // 子段(0.5.1~0.5.3 与 9.1~9.5)必须同时在场的合规形态;只改父段标题的写法,不得动子段。
854
+ {
855
+ name: 'TA-09 段名宽容:省括号/换括号/大小写三变体通过,核心词不同的段名拦',
856
+ run: async (dir) => {
857
+ const variants = [
858
+ ['省括号', '0.5 既有架构对齐'],
859
+ ['括号不同', '0.5 既有架构对齐(brownfield 场景夹具说明)'],
860
+ ['形态差异', '0.5 既有架构对齐(B2 老项目护栏)'],
861
+ ['大小写', '0.5 既有架构对齐(BROWNFIELD 必填)'],
862
+ ];
863
+ // 两个条件父段的实质正文(父段适用 → 登记表列出的结构子段逐条要求)
864
+ const applicableBodies = [
865
+ ['既有架构对齐', '本 change 触碰的既有模块与沿用对照见下表(夹具)。'],
866
+ ['架构沉淀建议', '本 change 有可复用的沉淀候选,逐项见各子段(夹具)。'],
867
+ ];
868
+ for (const [label, heading] of variants) {
869
+ setupDesign(dir, {
870
+ designOpts: {
871
+ rename: [['既有架构对齐', heading]],
872
+ body: applicableBodies,
873
+ },
874
+ });
875
+ const res = exitNode(dir, 'design');
876
+ assertTrue(res.status === 0, '段名宽容变体「' + label + '」(' + heading + ')应通过,实际 exit '
877
+ + res.status + '\n' + res.output);
878
+ assertOut(res, 'ALL CHECKS PASSED');
879
+ }
880
+ // 反向构造(判别力):父段适用却抽掉结构子段 → 必拦(证明子段要求真的在跑,正例不是空转)
881
+ setupDesign(dir, {
882
+ designOpts: { body: applicableBodies, subsectionOmit: ['0.5.2'] },
883
+ });
884
+ const resSubsection = exitNode(dir, 'design');
885
+ assertExit(resSubsection, 1);
886
+ assertOut(resSubsection, '0.5.2');
887
+ // 反向构造:核心词不同(既有架构对齐 → 架构对齐)→ 拦
888
+ setupDesign(dir, {
889
+ designOpts: {
890
+ rename: [['既有架构对齐', '0.5 架构对齐']],
891
+ body: applicableBodies,
892
+ },
893
+ });
894
+ const resCore = exitNode(dir, 'design');
895
+ assertExit(resCore, 1);
896
+ assertOut(resCore, 'BLOCKED');
897
+ },
898
+ },
899
+
900
+ // TA-10 · 模板外多余段允许(AC-10)——TEST 含模板之外的 `## Findings`(工具输出原样贴入)→ 通过,
901
+ // 且该段不参与段序判定(把它插在模板段中间也不得触发段序偏离)。
902
+ {
903
+ name: 'TA-10 模板外多余段:TEST 插入 ## Findings 放行且不参与段序判定',
904
+ run: async (dir) => {
905
+ const findings = '## Findings\n\n工具输出原样贴入:0 findings(夹具)。';
906
+ setupVerify(dir, { insertAfter: [['功能测试', findings]] });
907
+ const res = exitNode(dir, 'verify');
908
+ assertExit(res, 0);
909
+ assertOut(res, 'ALL CHECKS PASSED');
910
+ assertNotOut(res, '段序');
911
+ // 反向构造(判别力):多余段若真的参与排序,把它换成模板段的错位顺序必须被判段序偏离
912
+ // (下面这组是错位形态 → 必拦;两侧共用同一判据,证明上一条不是判据空转)
913
+ setupVerify(dir, { swap: [['回归保护', '本次测试范围声明']] });
914
+ const resOrder = exitNode(dir, 'verify');
915
+ assertExit(resOrder, 1);
916
+ },
917
+ },
918
+
919
+ // TA-11 · 旧 change 只告警(AC-11)——旧 change(无 newChange 标记)同构缺段 → 不阻断并输出 WARN;
920
+ // 反向构造:同一夹具置 newChange → BLOCKED。
921
+ {
922
+ name: 'TA-11 旧 change 同构缺段只 WARN 不阻断;同一夹具新 change 必 BLOCKED',
923
+ run: async (dir) => {
924
+ const missing = { omit: ['影响面'] };
925
+ // ① 新 change:拦(对照基准——同一份缺损工件)
926
+ setupOpen(dir, missing);
927
+ const newRes = exitNode(dir, 'open');
928
+ assertExit(newRes, 1);
929
+ // ② 旧 change:WARN 不阻断(唯一差异 = state 缺 newChange 标记)
930
+ setupOpen(dir, missing);
931
+ const legacy = baseState('open');
932
+ legacy.evidence.open = { summary: 'intake complete' };
933
+ writeState(dir, legacy);
934
+ const legacyRes = exitNode(dir, 'open');
935
+ assertExit(legacyRes, 0);
936
+ assertOut(legacyRes, 'WARN');
937
+ assertNotOut(legacyRes, 'BLOCKED');
938
+ // ③ design 侧段缺席:同一判据——CHANGE.md「视觉调性」段缺席,新 change 由 uidesign 门兜底拦,
939
+ // 不再默认判非前端(段缺席与段内声明「不适用」是两件事,只有后者是决策)。
940
+ setupDesign(dir, { changeOpts: { omit: ['视觉调性'] } });
941
+ const designNew = exitNode(dir, 'design');
942
+ assertExit(designNew, 1);
943
+ assertOut(designNew, '「视觉调性」段缺席');
944
+ assertOut(designNew, '新 change 须显式标注「不适用」');
945
+ // ④ 反向构造(同一份缺损工件,唯一差异 = state 缺 newChange 标记):旧 change 兼容跳过、不阻断。
946
+ setupDesign(dir, { changeOpts: { omit: ['视觉调性'] } });
947
+ const designLegacy = baseState('design');
948
+ designLegacy.evidence.design = { summary: 'design done' };
949
+ writeState(dir, designLegacy);
950
+ const designLegacyRes = exitNode(dir, 'design');
951
+ assertExit(designLegacyRes, 0);
952
+ assertOut(designLegacyRes, '旧 change 兼容');
953
+ },
954
+ },
955
+
956
+ // TA-12 · 增量段合法位置(AC-12)——①②④⑤ 合法位置通过;③ 自检方法夹在中间 → BLOCKED。
957
+ // 合法位置:紧随越界检查 / 文末 / 验证命令标题后紧跟代码块 / LESSONS 扫描位于自检方法之后。
958
+ {
959
+ name: 'TA-12 增量段位置:紧随越界检查/文末/验证命令+代码块/LESSONS 扫描在后均通过,夹中间拦',
960
+ run: async (dir) => {
961
+ // ① 紧随越界检查(默认渲染即此形态)
962
+ setupExecute(dir);
963
+ const afterBounds = exitNode(dir, 'execute');
964
+ assertExit(afterBounds, 0);
965
+ assertOut(afterBounds, 'ALL CHECKS PASSED');
966
+ // ② 位于文末(两个增量段都落在骨架段之后,自检方法在最末之前 —— 登记表的 end 分支)
967
+ setupExecute(dir, { incrementAllAtEnd: true });
968
+ const atEnd = exitNode(dir, 'execute');
969
+ assertExit(atEnd, 0);
970
+ assertOut(atEnd, 'ALL CHECKS PASSED');
971
+ // ④ 验证命令标题后紧跟代码块(TEST 默认渲染即此形态)
972
+ setupVerify(dir);
973
+ const verifyCmd = exitNode(dir, 'verify');
974
+ assertExit(verifyCmd, 0);
975
+ assertOut(verifyCmd, 'ALL CHECKS PASSED');
976
+ // ⑤ LESSONS 扫描位于自检方法之后(默认渲染即此形态)
977
+ const summaryText = renderDoc('SUMMARY');
978
+ assertTrue(summaryText.indexOf('## LESSONS 扫描') > summaryText.indexOf('## 自检方法'),
979
+ '夹具前提不成立:LESSONS 扫描应位于自检方法之后');
980
+ // ③ 反向构造:自检方法夹在 6 维自查与数据库迁移之间 → BLOCKED
981
+ setupExecute(dir, { incrementAfter: [['自检方法', '6 维自查']] });
982
+ const inMiddle = exitNode(dir, 'execute');
983
+ assertExit(inMiddle, 1);
984
+ assertOut(inMiddle, 'BLOCKED');
985
+ assertOut(inMiddle, '自检方法');
986
+ },
987
+ },
988
+
989
+ // ============================================================================================
990
+ // 加载链与协议面
991
+ // ============================================================================================
992
+
993
+ // TA-13 · 加载链(AC-13)——入口的两条指针(步骤权威 / 段形权威)与声明面:
994
+ // ① `entry <内置节点>` 先打 `READ PROMPT:` 再打 `READ TEMPLATE:`,顺序按输出行索引判
995
+ // (不是只查两行在不在——行序是语义的一部分);
996
+ // ② 声明别的节点的协议文件(open 声明 execute 的 4-dev.md)→ 入口 BLOCK,报文点名「与节点协议文件不符」;
997
+ // ③ design 的 2a-ui-design.md 是条件提示词(属该节点协议面)→ 不拦;入口按前端判据追出条件行
998
+ // (非前端不打印,反向构造即同一夹具只改「视觉调性」);换成无关文件 → 拦;
999
+ // ④ record 缺 `--templates` 声明 → BLOCK,补上 → 放行;⑤ explain 现问输出 `TEMPLATE:` 行。
1000
+ // 反向构造:②③ 各用真实 skill-load 只改 --prompt(其余参数不变)构造正例——排除「标记存在与否」
1001
+ // 这另一变量;① 另带「同一判据 + 变异探针」,对调两条指针后判据必须翻假,否则顺序断言退化成包含断言。
1002
+ // 声明面走真实命令而非手写标记:标记形态由生产写入路径产生,正是场景最容易与真实链路分叉的地方。
1003
+ {
1004
+ name: 'TA-13 加载链:entry 先 READ PROMPT 后 READ TEMPLATE,--prompt 错路径入口拦(条件提示词放行),record 缺 --templates 拦,explain 有 TEMPLATE 行',
1005
+ run: async (dir) => {
1006
+ // 声明走真实命令 skill-load(而不是手写标记 JSON):标记形态(protocol 取 basename、templates
1007
+ // 清单)由生产写入路径产生,入口判据读到的就是真实链路的形态。
1008
+ const skillLoad = (node, skill, prompt, templates) => runState(
1009
+ ['skill-load', node, skill, '--prompt', 'flow-kit/prompts/' + prompt, '--templates', templates],
1010
+ dir,
1011
+ );
1012
+ // 反例标记只能手写:skill-load 对新 change 拒绝「缺模板」的声明(那正是 ④ 要构造的缺陷态)。
1013
+ const writeMarker = (node, skill, protocol) => writeFile(
1014
+ dir,
1015
+ CHANGE_DIR + '/.skill-loads/' + node + '-' + skill + '.json',
1016
+ JSON.stringify({ node, skill, protocol, at: '2026-08-01T00:00:00.000Z' }, null, 2) + '\n',
1017
+ );
1018
+ const removeMarker = (node, skill) => fs.rmSync(
1019
+ path.join(dir, CHANGE_DIR, '.skill-loads', node + '-' + skill + '.json'),
1020
+ { force: true },
1021
+ );
1022
+ // 行序判据(单一函数供正向断言与变异探针共用):两条指针都在场,且全部提示词行在全部模板行之前。
1023
+ const lineIndexes = (lines, prefix) => lines
1024
+ .map((line, index) => (line.startsWith(prefix) ? index : -1))
1025
+ .filter((index) => index !== -1);
1026
+ const promptLinesBeforeTemplates = (text) => {
1027
+ const lines = text.split('\n');
1028
+ const promptAt = lineIndexes(lines, 'READ PROMPT:');
1029
+ const templateAt = lineIndexes(lines, 'READ TEMPLATE:');
1030
+ return promptAt.length > 0 && templateAt.length > 0
1031
+ && Math.max(...promptAt) < Math.min(...templateAt);
1032
+ };
1033
+
1034
+ // ① 顺序:open 是两提示词 + 两模板的节点,取「最后一条提示词 < 第一条模板」的收敛形态
1035
+ setupOpen(dir);
1036
+ const load = skillLoad('open', 'flow-comet-change', '0-change.md', 'CHANGE.md,REQUIREMENT.md');
1037
+ assertExit(load, 0);
1038
+ assertOut(load, 'SKILL-LOAD: open flow-comet-change');
1039
+ const entry = runGuard(['entry', 'open'], dir);
1040
+ assertExit(entry, 0);
1041
+ assertOut(entry, 'READ PROMPT: flow-kit/prompts/0-change.md');
1042
+ assertOut(entry, 'READ PROMPT: flow-kit/prompts/1-requirement.md');
1043
+ assertOut(entry, 'READ TEMPLATE: flow-kit/templates/CHANGE.md');
1044
+ assertTrue(promptLinesBeforeTemplates(entry.output),
1045
+ '入口两条指针顺序错:READ PROMPT 行应全部先于 READ TEMPLATE 行\n实际输出:\n' + entry.output);
1046
+ // 反向构造(同一判据 + 变异探针):对调两串标签后同一判据必须翻假
1047
+ const swapped = entry.output.replace(/READ (PROMPT|TEMPLATE):/g,
1048
+ (match, label) => 'READ ' + (label === 'PROMPT' ? 'TEMPLATE' : 'PROMPT') + ':');
1049
+ assertTrue(swapped !== entry.output, '变异探针前提失效:入口输出里没有可对调的两条指针');
1050
+ assertTrue(!promptLinesBeforeTemplates(swapped), '顺序判据不具判别力:对调两条指针后仍判通过');
1051
+
1052
+ // ①b 指针不校验文件在否:模板整体缺席时两行照常打印——指针标识的是「该读哪份模板」,文件
1053
+ // 缺席由产出物门禁的「未校验(模板缺失)」报告(公开文档的口径以此为准)。
1054
+ fs.rmSync(path.join(dir, 'flow-kit'), { recursive: true, force: true });
1055
+ assertTrue(!fs.existsSync(path.join(dir, 'flow-kit', 'templates', 'CHANGE.md')),
1056
+ '夹具前提失效:模板文件应确实不在磁盘上(否则本条退化成「指针必指向已有文件」的旧表述)');
1057
+ const noTemplateEntry = runGuard(['entry', 'open'], dir);
1058
+ assertExit(noTemplateEntry, 0);
1059
+ assertOut(noTemplateEntry, 'READ TEMPLATE: flow-kit/templates/CHANGE.md');
1060
+ assertOut(noTemplateEntry, 'READ PROMPT: flow-kit/prompts/0-change.md');
1061
+
1062
+ // ② 错路径:open 声明 execute 的协议文件 4-dev.md → 入口 BLOCK(报文点名不符)
1063
+ // 声明命令本身只校验 flow-kit/prompts/ 前缀,归属判定由入口负责——故这里真实命令成功、入口拦。
1064
+ assertExit(skillLoad('open', 'flow-comet-change', '4-dev.md', 'CHANGE.md,REQUIREMENT.md'), 0);
1065
+ const wrongPrompt = runGuard(['entry', 'open'], dir);
1066
+ assertExit(wrongPrompt, 1);
1067
+ assertOut(wrongPrompt, 'BLOCKED');
1068
+ assertOut(wrongPrompt, '与节点协议文件不符');
1069
+ assertOut(wrongPrompt, '4-dev.md');
1070
+ // 反向构造:真实命令只把 --prompt 改回本节点协议文件 → 放行(拦点是被声明的路径,不是标记存在性)
1071
+ assertExit(skillLoad('open', 'flow-comet-change', '0-change.md', 'CHANGE.md,REQUIREMENT.md'), 0);
1072
+ const correctedPrompt = runGuard(['entry', 'open'], dir);
1073
+ assertExit(correctedPrompt, 0);
1074
+ assertNotOut(correctedPrompt, '与节点协议文件不符');
1075
+
1076
+ // ③ 条件提示词不误拦 + 按前端判定打印:design 声明 2a-ui-design.md(条件提示词,属该节点协议面)
1077
+ // → 放行;前端 change 的入口追出条件行(与条件模板行对称),非前端 change 不打印。
1078
+ const frontendChange = { body: [['视觉调性', '- **选定**:6 有机 / Organic\n- **理由**:前端夹具']] };
1079
+ const conditionalPromptLine = 'READ PROMPT(条件提示词): flow-kit/prompts/2a-ui-design.md(仅前端 change)';
1080
+ // 条件行判据:逐行精确匹配(不用「包含文件名」的宽写法——标签或尾注漂移同样该红)。
1081
+ const hasConditionalPromptLine = (text) => text.split(/\r?\n/).includes(conditionalPromptLine);
1082
+ setupDesign(dir, { changeOpts: frontendChange });
1083
+ assertExit(skillLoad('design', 'flow-comet-design', '2-design.md', 'DESIGN.md'), 0);
1084
+ assertExit(skillLoad('design', 'flow-comet-ui-design', '2a-ui-design.md', 'DESIGN.md,UI-DESIGN.md'), 0);
1085
+ const conditionalOk = runGuard(['entry', 'design'], dir);
1086
+ assertExit(conditionalOk, 0);
1087
+ assertNotOut(conditionalOk, '与节点协议文件不符');
1088
+ assertOut(conditionalOk, 'READ PROMPT: flow-kit/prompts/2-design.md');
1089
+ assertTrue(hasConditionalPromptLine(conditionalOk.output),
1090
+ '前端 change 的 entry 未打印条件提示词行 ' + JSON.stringify(conditionalPromptLine)
1091
+ + '\n实际输出:\n' + conditionalOk.output);
1092
+ // 反向构造(同一判据 + 单变量):只把「视觉调性」改成「不适用」→ 前端判据为假,条件行必须消失
1093
+ // (实现若无视判据无条件打印,此处必红);必填提示词行不受影响。
1094
+ setupDesign(dir, { changeOpts: { body: [['视觉调性', '不适用']] } });
1095
+ assertExit(skillLoad('design', 'flow-comet-design', '2-design.md', 'DESIGN.md'), 0);
1096
+ assertExit(skillLoad('design', 'flow-comet-ui-design', '2a-ui-design.md', 'DESIGN.md,UI-DESIGN.md'), 0);
1097
+ const conditionalSkipped = runGuard(['entry', 'design'], dir);
1098
+ assertExit(conditionalSkipped, 0);
1099
+ assertOut(conditionalSkipped, 'READ PROMPT: flow-kit/prompts/2-design.md');
1100
+ assertTrue(!hasConditionalPromptLine(conditionalSkipped.output),
1101
+ '非前端 change 的 entry 不应打印条件提示词行\n实际输出:\n' + conditionalSkipped.output);
1102
+ // 反向构造:真实命令只把 --prompt 换成无关文件 → 同一夹具立刻拦
1103
+ assertExit(skillLoad('design', 'flow-comet-ui-design', '3-task.md', 'DESIGN.md,UI-DESIGN.md'), 0);
1104
+ const conditionalWrong = runGuard(['entry', 'design'], dir);
1105
+ assertExit(conditionalWrong, 1);
1106
+ assertOut(conditionalWrong, 'BLOCKED');
1107
+ assertOut(conditionalWrong, '与节点协议文件不符');
1108
+ assertOut(conditionalWrong, '3-task.md');
1109
+ // 移除条件提示词声明,④⑤ 回到单声明形态(与原有 record / explain 断言同形)
1110
+ removeMarker('design', 'flow-comet-ui-design');
1111
+
1112
+ // ④ 标记缺模板声明 → record BLOCKED 且提示 --templates;反向构造:声明了模板 → 放行
1113
+ writeMarker('design', 'flow-comet-design', '2-design.md');
1114
+ const recordBlocked = runState(['record', 'design', '{"summary":"design done"}'], dir);
1115
+ assertExit(recordBlocked, 1);
1116
+ assertOut(recordBlocked, '--templates');
1117
+ // 重新声明指引同时给出 --prompt:模板与提示词是同一次声明的两面,而 skill-load 重跑会覆写
1118
+ // 同一标记——只补 --templates 会把 protocol 写成 null,下一次 exit 反被判「缺协议声明标记」。
1119
+ // 记录侧没有 skill 名(只有它仍是 <skill> 占位);提示词路径必须是真实路径,不是占位符。
1120
+ assertOut(recordBlocked, '--prompt flow-kit/prompts/2-design.md');
1121
+ assertNotOut(recordBlocked, '--prompt <');
1122
+ assertExit(skillLoad('design', 'flow-comet-design', '2-design.md', 'DESIGN.md'), 0);
1123
+ const recordOk = runState(['record', 'design', '{"summary":"design done"}'], dir);
1124
+ assertExit(recordOk, 0);
1125
+ assertNotOut(recordOk, 'BLOCKED');
1126
+
1127
+ // ⑤ explain 现问输出模板行
1128
+ const explain = runState(['explain', 'design'], dir);
1129
+ assertExit(explain, 0);
1130
+ assertOut(explain, 'TEMPLATE:');
1131
+ assertOut(explain, 'flow-kit/templates/DESIGN.md');
1132
+ },
1133
+ },
1134
+
1135
+ // TA-14 · 自定义协议按声明决定(AC-14)——① 自定义节点未声明模板 → 不校验(结构缺损也放行);
1136
+ // ② 同节点声明了模板 → 校验(同样的缺损 → BLOCKED);③ 内置节点未声明 → BLOCKED。
1137
+ {
1138
+ name: 'TA-14 自定义协议三态:未声明不校验 / 声明则校验 / 内置节点未声明拦',
1139
+ run: async (dir) => {
1140
+ const protocolWith = (templates) => {
1141
+ const proto = customProtocol();
1142
+ proto.nodes[0].outputSchemas = ['compose.change.v1'];
1143
+ proto.outputSchemas = [{
1144
+ id: 'compose.change.v1',
1145
+ description: 'CHANGE.md(自定义节点产物)',
1146
+ artifacts: [{
1147
+ id: 'change-doc', kind: 'file', required: true,
1148
+ paths: ['<change-id>/CHANGE.md'], pathBase: 'specs-root',
1149
+ }],
1150
+ evidence: [{ id: 'change-summary', required: true }],
1151
+ }];
1152
+ if (templates !== undefined) proto.nodes[0].templates = templates;
1153
+ return proto;
1154
+ };
1155
+ const writeProtocol = (proto) => writeFile(dir, 'reference/workflow-protocol.json', JSON.stringify(proto, null, 2) + '\n');
1156
+ const writeCustomFixture = () => {
1157
+ writeTemplateFixture(dir, 'CHANGE');
1158
+ writeFile(dir, changeDirOf(), renderDoc('CHANGE', { omit: ['影响面'] }));
1159
+ const st = baseState('brainstorm');
1160
+ st.activeChange = CHANGE_ID;
1161
+ st.newChange = true;
1162
+ st.enteredNodes = ['brainstorm'];
1163
+ st.evidence.brainstorm = { summary: 'notes done' };
1164
+ writeState(dir, st);
1165
+ };
1166
+ function changeDirOf() { return CHANGE_DIR + '/CHANGE.md'; }
1167
+ // ① 未声明 → 不校验
1168
+ writeProtocol(protocolWith(undefined));
1169
+ writeCustomFixture();
1170
+ const undeclared = runGuard(['exit', 'brainstorm'], dir);
1171
+ assertExit(undeclared, 0);
1172
+ assertNotOut(undeclared, 'BLOCKED');
1173
+ // ② 声明了模板 → 校验(同样的结构缺损 → 拦)
1174
+ writeProtocol(protocolWith(['CHANGE']));
1175
+ writeCustomFixture();
1176
+ const declared = runGuard(['exit', 'brainstorm'], dir);
1177
+ assertExit(declared, 1);
1178
+ assertOut(declared, 'BLOCKED');
1179
+ // ③ 反向构造:内置节点缺模板声明 → 拦(把内置协议副本的节点声明删掉)
1180
+ writeProtocol((() => {
1181
+ const builtin = JSON.parse(fs.readFileSync(path.join(SCRIPTS_DIR, '..', 'reference', 'workflow-protocol.json'), 'utf8'));
1182
+ for (const node of builtin.nodes) delete node.templates;
1183
+ return builtin;
1184
+ })());
1185
+ setupOpen(dir, { omit: ['影响面'] });
1186
+ const builtinUndeclared = runGuard(['exit', 'open'], dir);
1187
+ assertExit(builtinUndeclared, 1);
1188
+ assertOut(builtinUndeclared, 'BLOCKED');
1189
+ // ④ 重新声明指引的提示词面(单一来源的直接判据):内置节点拼该节点首个协议文件的真实路径
1190
+ // (与入口 READ PROMPT 同源);自定义节点没有内置映射 → 不拼(不编造路径,也不打占位符)。
1191
+ const { nodeTemplateDeclaration, templateDeclareCommand } = await import('../protocol-utils.mjs');
1192
+ const builtinCommand = templateDeclareCommand(
1193
+ nodeTemplateDeclaration({ id: 'execute' }), { nodeId: 'execute', skillName: 'flow-comet-dev' });
1194
+ assertTrue(builtinCommand === 'workflow-state.mjs skill-load execute flow-comet-dev'
1195
+ + ' --templates SUMMARY.md --prompt flow-kit/prompts/4-dev.md',
1196
+ '内置节点的重新声明命令应带真实提示词路径,实际: ' + builtinCommand);
1197
+ const customCommand = templateDeclareCommand(
1198
+ nodeTemplateDeclaration({ id: 'brainstorm', templates: ['CHANGE'] }), { nodeId: 'brainstorm', skillName: 'fixture-skill' });
1199
+ assertTrue(customCommand === 'workflow-state.mjs skill-load brainstorm fixture-skill --templates CHANGE.md',
1200
+ '自定义节点无内置提示词映射时不应拼 --prompt,实际: ' + customCommand);
1201
+ },
1202
+ },
1203
+
1204
+ // TA-15 · 报错两阶段与记忆(AC-15)——同一工件首次因缺段被拦:只给模板路径 + 类别计数,不列段名;
1205
+ // 再犯:列出段名;工件通过后标记清除。反向构造:修复后复检 + 标记文件不再记录该工件。
1206
+ // 记忆按**文件**计:execute 出口的多份 *-SUMMARY.md 共用同一个模板键,各份必须独立记忆——同一次
1207
+ // 出口各自首败不互相升级,修好一份即释放该份的键(不许被另一份的失败永久保键)。
1208
+ {
1209
+ name: 'TA-15 两阶段报错:首次不列段名、再犯列段名、通过后清标记(多份 SUMMARY 各记各的)',
1210
+ run: async (dir) => {
1211
+ // 单份工件的失败行(同一份工件在报告里占一行;用于按文件断言,避免整串输出互相串味)
1212
+ const failureLine = (res, file) => res.output.split(/\r?\n/)
1213
+ .find((line) => line.includes(file + ' 模板结构校验失败')) ?? '';
1214
+ setupExecute(dir, { omit: ['是否触发新工作'] });
1215
+ const first = exitNode(dir, 'execute');
1216
+ assertExit(first, 1);
1217
+ assertOut(first, 'BLOCKED');
1218
+ assertNotOut(first, '是否触发新工作');
1219
+ const hintFile = path.join(dir, CHANGE_DIR, '.template-hints.json');
1220
+ assertTrue(fs.existsSync(hintFile), '首次结构失败应写入 .specs/<change>/.template-hints.json(跨两次 exit 记忆)');
1221
+ const second = exitNode(dir, 'execute');
1222
+ assertExit(second, 1);
1223
+ assertOut(second, '是否触发新工作');
1224
+ // 反向构造:工件通过 → 标记清除
1225
+ setupExecute(dir);
1226
+ const passed = exitNode(dir, 'execute');
1227
+ assertExit(passed, 0);
1228
+ assertOut(passed, 'ALL CHECKS PASSED');
1229
+ const cleared = !fs.existsSync(hintFile)
1230
+ || !JSON.stringify(JSON.parse(fs.readFileSync(hintFile, 'utf8'))).toUpperCase().includes('SUMMARY');
1231
+ assertTrue(cleared, '工件通过后应清除该工件的两阶段标记,实际: '
1232
+ + (fs.existsSync(hintFile) ? fs.readFileSync(hintFile, 'utf8') : '(文件已删)'));
1233
+ // ⑤ 两份 SUMMARY 同一次出口各自首败 → 都不升级(后一份不许继承前一份刚写下的键)
1234
+ const omitSection = (res, file) => {
1235
+ const line = failureLine(res, file);
1236
+ assertTrue(line !== '', '两份 SUMMARY 都应出现在同一次出口的失败报告里(缺 ' + file + ')');
1237
+ return line.includes('是否触发新工作');
1238
+ };
1239
+ setupExecute(dir, { omit: ['是否触发新工作'] });
1240
+ writeFile(dir, CHANGE_DIR + '/T02-SUMMARY.md', renderDoc('SUMMARY', { omit: ['是否触发新工作'] }));
1241
+ const pairFirst = exitNode(dir, 'execute');
1242
+ assertExit(pairFirst, 1);
1243
+ assertTrue(!omitSection(pairFirst, 'T01-SUMMARY.md'), 'T01 首败不应列段名: ' + failureLine(pairFirst, 'T01-SUMMARY.md'));
1244
+ assertTrue(!omitSection(pairFirst, 'T02-SUMMARY.md'),
1245
+ 'T02 首败不应列段名(另一份刚写下的键不许把它升级成再犯): ' + failureLine(pairFirst, 'T02-SUMMARY.md'));
1246
+ const pairKeys = Object.keys(JSON.parse(fs.readFileSync(hintFile, 'utf8')));
1247
+ for (const file of ['T01-SUMMARY.md', 'T02-SUMMARY.md']) {
1248
+ assertTrue(pairKeys.some((key) => key.includes(file)),
1249
+ '记忆账本应按文件分开记录(缺 ' + file + '): ' + pairKeys.join(', '));
1250
+ }
1251
+ // ⑥ 反向构造:两份都再犯 → 两份都列段名(按文件记忆不削弱「再犯」判据)
1252
+ const pairSecond = exitNode(dir, 'execute');
1253
+ assertExit(pairSecond, 1);
1254
+ for (const file of ['T01-SUMMARY.md', 'T02-SUMMARY.md']) {
1255
+ assertTrue(omitSection(pairSecond, file), file + ' 再犯应列出段名: ' + failureLine(pairSecond, file));
1256
+ }
1257
+ // ⑦ 修好一份、另一份仍红 → 修好的那份释放记忆键;再坏一次仍算首败(同一次出口里的另一份
1258
+ // 仍在失败,不许把它拖回再犯)。
1259
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY'));
1260
+ const oneFixed = exitNode(dir, 'execute');
1261
+ assertExit(oneFixed, 1); // T02 仍缺段:出口照常拦
1262
+ assertTrue(omitSection(oneFixed, 'T02-SUMMARY.md'),
1263
+ '仍失败的 T02 应保持再犯形态: ' + failureLine(oneFixed, 'T02-SUMMARY.md'));
1264
+ const afterFixKeys = Object.keys(JSON.parse(fs.readFileSync(hintFile, 'utf8')));
1265
+ assertTrue(!afterFixKeys.some((key) => key.includes('T01-SUMMARY.md')),
1266
+ '修好的 T01 应释放其记忆键(不许靠 T02 的失败永久保键): ' + afterFixKeys.join(', '));
1267
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY', { omit: ['是否触发新工作'] }));
1268
+ const brokeAgain = exitNode(dir, 'execute');
1269
+ assertExit(brokeAgain, 1);
1270
+ assertTrue(!omitSection(brokeAgain, 'T01-SUMMARY.md'),
1271
+ '释放后再次坏掉应按首败处理(不列段名): ' + failureLine(brokeAgain, 'T01-SUMMARY.md'));
1272
+ },
1273
+ },
1274
+
1275
+ // TA-16 · REVIEW 发现必须在模板位置(AC-16)——① 发现写在 `## 发现` 而 `### 2.2` 下无条目
1276
+ // → BLOCKED 并提示迁移到 2.2;② 按模板写在 2.2 → 通过;③ 模板范例形态(`### 🔴 …` + 粗体
1277
+ // 字段)同样是「发现」——缺处置标记 → BLOCKED(修复前该形态整段静默空过 = RED),同内容改回
1278
+ // 列表项 → 同样 BLOCKED(书写形态不改变判别力),带处置标记的 H3 条目 → 通过;④ H3 Major
1279
+ // [转待办] 无用户裁决 → BLOCKED,同段裁决 + [升级] 承接 → 通过(严重度按标题前缀派生)。
1280
+ {
1281
+ name: 'TA-16 REVIEW 发现位置:写在 ## 发现 而 2.2 空则拦,写在 2.2 通过',
1282
+ run: async (dir) => {
1283
+ // ① 发现写在模板外的段
1284
+ setupReview(dir, {
1285
+ body: [['2.2', '(夹具:本段无条目。)']],
1286
+ extra: ['## 发现\n\n- **F1 · 夹具发现**:写在模板外的发现条目 [已修]'],
1287
+ });
1288
+ const misplaced = exitNode(dir, 'review');
1289
+ assertExit(misplaced, 1);
1290
+ assertOut(misplaced, 'BLOCKED');
1291
+ assertOut(misplaced, '2.2');
1292
+ // ② 反向构造:按模板写在 2.2 → 通过
1293
+ setupReview(dir);
1294
+ const ok = exitNode(dir, 'review');
1295
+ assertExit(ok, 0);
1296
+ assertOut(ok, 'ALL CHECKS PASSED');
1297
+ // ③ H3 + 粗体字段形态(模板 2.2 的书写范例)缺处置标记 → BLOCKED
1298
+ const h3Finding = [
1299
+ '### 🔴 C-2 · 夹具 H3 形态的发现:按模板范例书写',
1300
+ '**Symptom**:某处存在一个可记录的衰退风险',
1301
+ '**Source**:夹具来源',
1302
+ '**Consequence**:若不修会怎样',
1303
+ '**Remedy**:怎么改',
1304
+ '**生成 fix 任务**:T-FIX-99',
1305
+ ].join('\n');
1306
+ setupReview(dir, { body: [['2.2', h3Finding]] });
1307
+ const h3Missing = exitNode(dir, 'review');
1308
+ assertExit(h3Missing, 1);
1309
+ assertOut(h3Missing, 'BLOCKED');
1310
+ assertOut(h3Missing, '发现区 1 项'); // H3 条目被计入发现(未识别时计数为 0)
1311
+ // ④ 同内容换回列表项形态 → 同样被拦(同一判据对两种写法同等判别)
1312
+ setupReview(dir, {
1313
+ body: [['2.2', '- **C-2 · 夹具 H3 形态的发现:按模板范例书写**:某处存在一个可记录的衰退风险']],
1314
+ });
1315
+ const listMissing = exitNode(dir, 'review');
1316
+ assertExit(listMissing, 1);
1317
+ assertOut(listMissing, 'BLOCKED');
1318
+ assertOut(listMissing, '发现区 1 项');
1319
+ // ⑤ 反向构造:H3 条目在标题行带处置标记 → 通过
1320
+ setupReview(dir, { body: [['2.2', h3Finding.replace('按模板范例书写', '按模板范例书写 [已修]')]] });
1321
+ const h3Done = exitNode(dir, 'review');
1322
+ assertExit(h3Done, 0);
1323
+ assertOut(h3Done, 'ALL CHECKS PASSED');
1324
+ // ⑥ H3 Major [转待办] 无用户裁决记录 → BLOCKED
1325
+ setupReview(dir, {
1326
+ body: [['2.2', ['### 🟡 M-2 · 夹具 H3 形态的延期 [转待办]',
1327
+ '**Symptom**:某处问题', '**Remedy**:下一 change 首修'].join('\n')]],
1328
+ });
1329
+ const h3Deferred = exitNode(dir, 'review');
1330
+ assertExit(h3Deferred, 1);
1331
+ assertOut(h3Deferred, 'BLOCKED');
1332
+ assertOut(h3Deferred, 'M-2'); // 严重度按 H3 标题前缀派生 → 计入 Major 延期门禁
1333
+ assertOut(h3Deferred, '用户裁决');
1334
+ // ⑦ 反向构造:同段用户裁决 + [升级] 承接 → 通过
1335
+ setupReview(dir, {
1336
+ body: [['2.2', ['### 🟡 M-2 · 夹具 H3 形态的延期 [升级] [转待办](用户裁决:接受延期,下一 change 首修)',
1337
+ '**Symptom**:某处问题'].join('\n')]],
1338
+ });
1339
+ const h3Adjudicated = exitNode(dir, 'review');
1340
+ assertExit(h3Adjudicated, 0);
1341
+ assertOut(h3Adjudicated, 'ALL CHECKS PASSED');
1342
+ },
1343
+ },
1344
+
1345
+ // ============================================================================================
1346
+ // LESSONS:旧形态迁移 / 开工扫描 / 归档提名
1347
+ // ============================================================================================
1348
+
1349
+ // TA-17 · LESSONS 旧形态在 open / verify / archive 三处出口被拦(AC-17)——报文逐行给出
1350
+ // 「文件:行号 → 应改成 ### L-NNN」;迁移后三处通过。
1351
+ {
1352
+ name: 'TA-17 LESSONS 旧形态(## L-NNN)在 open/verify/archive 三处出口拦并给逐行改法',
1353
+ run: async (dir) => {
1354
+ const legacyLessons = [
1355
+ '# LESSONS — 跨任务失败知识库(夹具)',
1356
+ '',
1357
+ '## 条目区(夹具)',
1358
+ '',
1359
+ '## L-501',
1360
+ '',
1361
+ '- **关键词**: guard, template',
1362
+ '',
1363
+ '夹具旧形态条目。',
1364
+ '',
1365
+ ].join('\n');
1366
+ // ① open 出口
1367
+ setupOpen(dir);
1368
+ writeFile(dir, '.specs/LESSONS.md', legacyLessons);
1369
+ const resOpen = exitNode(dir, 'open');
1370
+ assertExit(resOpen, 1);
1371
+ assertOut(resOpen, 'LESSONS.md');
1372
+ assertOut(resOpen, '### L-501');
1373
+ assertTrue(/LESSONS\.md:\d+/.test(resOpen.output), '报文应逐行给出「文件:行号」,实际: ' + resOpen.output);
1374
+ // ② verify 出口
1375
+ setupVerify(dir);
1376
+ writeFile(dir, '.specs/LESSONS.md', legacyLessons);
1377
+ const resVerify = exitNode(dir, 'verify');
1378
+ assertExit(resVerify, 1);
1379
+ assertOut(resVerify, '### L-501');
1380
+ // ③ archive 出口
1381
+ setupArchive(dir, { lessons: legacyLessons });
1382
+ const resArchive = exitNode(dir, 'archive');
1383
+ assertExit(resArchive, 1);
1384
+ assertOut(resArchive, '### L-501');
1385
+ // ④ 反向构造:迁移(改级 + 留在条目区)后三处通过——archive 一侧须同时给出齐全的归档提名
1386
+ // 证据(TA-19 起「缺 lessonsNomination 即拦」是独立判据,本条只验证旧形态迁移已消失)。
1387
+ setupOpen(dir);
1388
+ writeFile(dir, '.specs/LESSONS.md', LESSONS_FIXTURE);
1389
+ assertExit(exitNode(dir, 'open'), 0);
1390
+ setupVerify(dir);
1391
+ writeFile(dir, '.specs/LESSONS.md', LESSONS_FIXTURE);
1392
+ assertExit(exitNode(dir, 'verify'), 0);
1393
+ setupArchive(dir, {
1394
+ evidence: { lessonsNomination: { scanned: 2, nominated: ['L-501'], reasonIfNone: '' } },
1395
+ });
1396
+ const archiveOk = exitNode(dir, 'archive');
1397
+ assertExit(archiveOk, 0);
1398
+ // ⑤ C20 字段键:新 change 的模板形态新条目缺 5 键任一 → BLOCKED(字段键从 LESSONS 模板的
1399
+ // 「条目格式」书写样例派生,不在门禁里写第二份字面清单;模板夹具在场是判据可派生前提)。
1400
+ setupVerify(dir);
1401
+ writeTemplateFixture(dir, 'LESSONS');
1402
+ writeFile(dir, '.specs/LESSONS.md', [
1403
+ '# LESSONS — 跨任务失败知识库(夹具)',
1404
+ '',
1405
+ '## 条目区(夹具)',
1406
+ '',
1407
+ '### L-503 · [proc] 夹具新条目只有标题与关键词行',
1408
+ '',
1409
+ '- **关键词**: fixture field gate',
1410
+ '',
1411
+ '夹具条目正文:只有关键词行,缺其余字段键。',
1412
+ '',
1413
+ ].join('\n'));
1414
+ const missingFields = exitNode(dir, 'verify');
1415
+ assertExit(missingFields, 1);
1416
+ assertOut(missingFields, 'BLOCKED');
1417
+ assertOut(missingFields, 'L-503');
1418
+ assertOut(missingFields, '首发');
1419
+ // ⑤c runRoot 与 cwd 漂移:字段键从 runRoot 下的模板派生——guard 可能在与项目根不同的 cwd
1420
+ // 被调起(运行上下文由 FLOW_COMET_RUN_ROOT 给定)。按 cwd 解析会在模板在场时也判「模板缺失」,
1421
+ // C20 随之静默退化为未校验;反向断言同一份夹具不得出现该降级行。
1422
+ const cwdOffset = path.join(dir, 'cwd-offset');
1423
+ fs.mkdirSync(cwdOffset, { recursive: true });
1424
+ const drift = spawnSync(process.execPath, [path.join(SCRIPTS_DIR, 'workflow-guard.mjs'), 'exit', 'verify', '--apply'], {
1425
+ cwd: cwdOffset,
1426
+ env: { ...process.env, FLOW_COMET_RUN_ROOT: dir, FLOW_COMET_PROTOCOL: scenarioProtocolPath(dir) },
1427
+ encoding: 'utf8',
1428
+ timeout: 60000,
1429
+ });
1430
+ const driftRes = { status: drift.status ?? 1, output: String(drift.stdout ?? '') + String(drift.stderr ?? '') };
1431
+ assertExit(driftRes, 1);
1432
+ assertOut(driftRes, 'BLOCKED');
1433
+ assertOut(driftRes, 'L-503');
1434
+ assertNotOut(driftRes, 'LESSONS 条目字段 未校验(模板缺失)');
1435
+ // ⑤b 新条目只有标题与正文(无任何字段键)同样 BLOCKED——正面回应「新条目可绕过关键词扫描」的
1436
+ // 失效模式(修复前整类条目静默通过 = RED)。
1437
+ writeFile(dir, '.specs/LESSONS.md', [
1438
+ '# LESSONS — 跨任务失败知识库(夹具)',
1439
+ '',
1440
+ '## 条目区(夹具)',
1441
+ '',
1442
+ '### L-506 · [proc] 夹具只有标题与正文的新条目',
1443
+ '',
1444
+ '夹具条目正文:一个字段键都没有。',
1445
+ '',
1446
+ ].join('\n'));
1447
+ const noFieldKeys = exitNode(dir, 'verify');
1448
+ assertExit(noFieldKeys, 1);
1449
+ assertOut(noFieldKeys, 'BLOCKED');
1450
+ assertOut(noFieldKeys, 'L-506');
1451
+ // ⑥ 迁移形态旧条目(`### L-NNN:` 冒号标题,迁移保留原标题形态)缺字段 → 只 WARN,不阻断
1452
+ setupVerify(dir);
1453
+ writeTemplateFixture(dir, 'LESSONS');
1454
+ writeFile(dir, '.specs/LESSONS.md', [
1455
+ '# LESSONS — 跨任务失败知识库(夹具)',
1456
+ '',
1457
+ '## 条目区(夹具)',
1458
+ '',
1459
+ '### L-504: 夹具迁移形态条目',
1460
+ '',
1461
+ '夹具迁移条目正文:迁移保留原标题形态,无字段行。',
1462
+ '',
1463
+ ].join('\n'));
1464
+ const migratedOld = exitNode(dir, 'verify');
1465
+ assertExit(migratedOld, 0);
1466
+ assertOut(migratedOld, 'L-504');
1467
+ assertOut(migratedOld, 'WARN');
1468
+ // ⑦ 反向构造:新条目补全 5 键 → 通过
1469
+ writeFile(dir, '.specs/LESSONS.md', [
1470
+ '# LESSONS — 跨任务失败知识库(夹具)',
1471
+ '',
1472
+ '## 条目区(夹具)',
1473
+ '',
1474
+ '### L-505 · [proc] 夹具完整条目',
1475
+ '',
1476
+ '- **首发**: ' + CHANGE_ID + ' · T01 · 2026-10-20',
1477
+ '- **上次复核**: 2026-10-20',
1478
+ '- **适用栈**: Node 18+ / 夹具',
1479
+ '- **状态**: active',
1480
+ '- **关键词**: fixture complete entry',
1481
+ '',
1482
+ '夹具条目正文。',
1483
+ '',
1484
+ ].join('\n'));
1485
+ const fieldsOk = exitNode(dir, 'verify');
1486
+ assertExit(fieldsOk, 0);
1487
+ assertOut(fieldsOk, 'ALL CHECKS PASSED');
1488
+ },
1489
+ },
1490
+
1491
+ // TA-18 · 开工前 LESSONS 扫描可核对(AC-18)——① SUMMARY 缺 `## LESSONS 扫描` → BLOCKED;
1492
+ // ② 引擎按任务 write_files 命中某条关键词、而 SUMMARY 未逐条回应该编号 → BLOCKED;补齐后通过。
1493
+ {
1494
+ name: 'TA-18 LESSONS 扫描:缺声明段拦;命中条目未回应拦;补齐并逐条回应后通过',
1495
+ run: async (dir) => {
1496
+ // ① 缺 ## LESSONS 扫描 段(登记为 SUMMARY 的必填增量段)
1497
+ setupExecute(dir, { omit: ['LESSONS 扫描'] });
1498
+ writeFile(dir, '.specs/LESSONS.md', LESSONS_FIXTURE);
1499
+ const missingSection = exitNode(dir, 'execute');
1500
+ assertExit(missingSection, 1);
1501
+ assertOut(missingSection, 'LESSONS 扫描');
1502
+ // ② 声明段在场但命中条目未回应
1503
+ setupExecute(dir);
1504
+ writeFile(dir, '.specs/LESSONS.md', LESSONS_FIXTURE);
1505
+ writeFile(dir, CHANGE_DIR + '/TASK.md', '# TASK\n\n## 任务清单\n\n'
1506
+ + '<task id="T01" status="done"><action>改模板保真门禁</action>'
1507
+ + '<write_files>scripts/lib/guard-template-fidelity.mjs</write_files>'
1508
+ + '<verify>node --check baseline.js</verify></task>\n');
1509
+ const unanswered = exitNode(dir, 'execute');
1510
+ assertExit(unanswered, 1);
1511
+ assertOut(unanswered, 'L-501');
1512
+ // ③ 反向构造:逐条回应命中编号 → 通过
1513
+ setupExecute(dir, { body: [['LESSONS 扫描', '- L-501:已读并声明差异(夹具回应)。']] });
1514
+ writeFile(dir, '.specs/LESSONS.md', LESSONS_FIXTURE);
1515
+ writeFile(dir, CHANGE_DIR + '/TASK.md', '# TASK\n\n## 任务清单\n\n'
1516
+ + '<task id="T01" status="done"><action>改模板保真门禁</action>'
1517
+ + '<write_files>scripts/lib/guard-template-fidelity.mjs</write_files>'
1518
+ + '<verify>node --check baseline.js</verify></task>\n');
1519
+ const answered = exitNode(dir, 'execute');
1520
+ assertExit(answered, 0);
1521
+ assertOut(answered, 'ALL CHECKS PASSED');
1522
+ },
1523
+ },
1524
+
1525
+ // TA-19 · 归档提名留痕并核对(AC-19)——缺 lessonsNomination / 提名编号不存在 / 扫描份数不符
1526
+ // 三者均 BLOCKED;补齐并核对一致后通过(三负一正)。
1527
+ {
1528
+ name: 'TA-19 归档提名:缺字段/编号不存在/份数不符三负例拦,补齐后通过',
1529
+ run: async (dir) => {
1530
+ // ① 缺 lessonsNomination 字段
1531
+ setupArchive(dir);
1532
+ const missingField = exitNode(dir, 'archive');
1533
+ assertExit(missingField, 1);
1534
+ assertOut(missingField, 'BLOCKED');
1535
+ assertOut(missingField, 'lessonsNomination');
1536
+ // ② 提名编号在 LESSONS 中不存在
1537
+ setupArchive(dir, {
1538
+ evidence: { lessonsNomination: { scanned: 2, nominated: ['L-999'], reasonIfNone: '' } },
1539
+ });
1540
+ const unknownId = exitNode(dir, 'archive');
1541
+ assertExit(unknownId, 1);
1542
+ assertOut(unknownId, 'L-999');
1543
+ // ③ 扫描份数 ≠ 该 change 内 *-SUMMARY.md 数量(夹具 2 份,声明 3)
1544
+ setupArchive(dir, {
1545
+ evidence: { lessonsNomination: { scanned: 3, nominated: ['L-501'], reasonIfNone: '' } },
1546
+ });
1547
+ const countMismatch = exitNode(dir, 'archive');
1548
+ assertExit(countMismatch, 1);
1549
+ // ④ 反向构造:三项一致 → 通过
1550
+ setupArchive(dir, {
1551
+ evidence: { lessonsNomination: { scanned: 2, nominated: ['L-501'], reasonIfNone: '' } },
1552
+ });
1553
+ const ok = exitNode(dir, 'archive');
1554
+ assertExit(ok, 0);
1555
+ assertOut(ok, 'ALL CHECKS PASSED');
1556
+ },
1557
+ },
1558
+
1559
+ // ============================================================================================
1560
+ // 项目级工件 / 降级面 / 治理
1561
+ // ============================================================================================
1562
+
1563
+ // TA-20 · 项目级工件的触发点(AC-20)——① CONTEXT 存在但缺模板段 → open 出口拦;
1564
+ // ② UI-DESIGN 存在但缺 frontmatter 键 → 前端 change 的 design 出口拦;
1565
+ // ③ `.specs/ARCHITECTURE.md` 缺段 → 侧命令报告列出结构问题但**不阻断**(只读)。
1566
+ {
1567
+ name: 'TA-20 项目级工件:CONTEXT 缺段拦、UI-DESIGN 缺 frontmatter 键拦、ARCHITECTURE 只读报告',
1568
+ run: async (dir) => {
1569
+ // ① CONTEXT 缺段(文件存在才查)——段清单基准来自 CONTEXT 模板,故夹具根必须带模板:
1570
+ // 模板缺席时判据按 C9 整体跳过并显式「未校验(模板缺失)」,该形态由 TA-21 覆盖。
1571
+ setupOpen(dir);
1572
+ writeTemplateFixture(dir, 'CONTEXT');
1573
+ writeFile(dir, '.specs/CONTEXT.md', '# CONTEXT — 项目共享上下文\n\n## 项目概要\n\n夹具。\n');
1574
+ const resContext = exitNode(dir, 'open');
1575
+ assertExit(resContext, 1);
1576
+ assertOut(resContext, 'CONTEXT');
1577
+ // ② UI-DESIGN 缺 frontmatter 键(motion)
1578
+ setupDesign(dir, {
1579
+ changeOpts: { body: [['视觉调性', '- **选定**:6 有机 / Organic\n- **理由**:前端夹具']] },
1580
+ uiDesign: uiDesignDoc({}, ['motion']),
1581
+ declareUiDesign: true,
1582
+ });
1583
+ writeFrontendDesignMarkers(dir);
1584
+ const resUiKey = exitNode(dir, 'design');
1585
+ assertExit(resUiKey, 1);
1586
+ assertOut(resUiKey, 'motion');
1587
+ // ③ ARCHITECTURE 缺段 → 侧命令只读报告(不阻断)。模板夹具必须在场:骨架不可派生时报告走
1588
+ // 「未校验(模板缺失)」分支,此时只断言「结构问题」在降级面上空转——真实比对分支才是被测面。
1589
+ // 夹具自带 §3 的占位 ADR 条目(TEMPLATE_BODY_FIXTURES)——没有 vendored 模板的检出按登记表
1590
+ // 合成的模板因此与真迹同构,§3 字段键派生同样真跑(不会退化成「结构问题依据」里的未校验)。
1591
+ writeTemplateFixture(dir, 'ARCHITECTURE');
1592
+ writeFile(dir, '.specs/ARCHITECTURE.md', '# ARCHITECTURE — 项目级系统架构(活文档)\n\n## 1. 系统概览\n\n夹具。\n');
1593
+ const side = runSideCommand(dir, 'evolve.mjs', ['scan', '--root', dir, '--stdout']);
1594
+ assertExit(side, 0);
1595
+ assertOut(side, '结构问题');
1596
+ assertOut(side, 'ARCHITECTURE');
1597
+ assertOut(side, '缺 H2 段 7/8'); // 8 个 H2 段只写了 1 个
1598
+ assertOut(side, '2. 模块清单'); // 逐条列出缺哪个段名,不是只报数量
1599
+ assertNotOut(side, '未校验'); // 走的是真实比对分支,不是模板缺席降级
1600
+ assertNotOut(side, 'BLOCKED'); // 只读报告:结构问题不进退出码、不阻断
1601
+ // 反向构造(判别力):按模板补齐 8 个 H2 段 → 同一判据报 0 项(证明「缺段」不是常量输出)
1602
+ writeFile(dir, '.specs/ARCHITECTURE.md', renderDoc('ARCHITECTURE'));
1603
+ const sideOk = runSideCommand(dir, 'evolve.mjs', ['scan', '--root', dir, '--stdout']);
1604
+ assertExit(sideOk, 0);
1605
+ assertOut(sideOk, '结构问题(.specs/ARCHITECTURE.md):0 项');
1606
+ },
1607
+ },
1608
+
1609
+ // TA-21 · 模板缺席时降级并显式声明(AC-21)——夹具根没有 flow-kit/templates/ → 不阻断,输出显式
1610
+ // 「未校验(模板缺失)」。反向构造:模板在场时同一工件必被拦(证明不是判据空转)。
1611
+ // ③④ 追加「段名清单单一来源」:模板缺席时仍要生效的四份段名清单(SUMMARY 段序兜底 / open·design 段名回退 /
1612
+ // LESSONS 扫描段名 / SUMMARY 必填三段)只许骨架模块登记一份——静态单源锁 + 行为侧反向构造。
1613
+ {
1614
+ name: 'TA-21 模板缺席降级:不阻断且显式输出「未校验(模板缺失)」;模板在场时同夹具被拦;段名清单单源锁',
1615
+ run: async (dir) => {
1616
+ // ① 模板缺席:只写工件,不写 flow-kit/templates/
1617
+ writeFile(dir, CHANGE_DIR + '/CHANGE.md', renderDoc('CHANGE', { omit: ['影响面'] }));
1618
+ writeFile(dir, CHANGE_DIR + '/REQUIREMENT.md', renderDoc('REQUIREMENT'));
1619
+ const st = newChangeState('open');
1620
+ st.evidence.open = { summary: 'intake complete' };
1621
+ writeState(dir, st);
1622
+ const degraded = exitNode(dir, 'open');
1623
+ assertExit(degraded, 0);
1624
+ assertOut(degraded, '未校验');
1625
+ assertOut(degraded, '模板缺失');
1626
+ assertNotOut(degraded, 'BLOCKED');
1627
+ // ② 反向构造:模板在场 → 同一工件被拦(缺段判据确实在跑)
1628
+ setupOpen(dir, { omit: ['影响面'] });
1629
+ const blocked = exitNode(dir, 'open');
1630
+ assertExit(blocked, 1);
1631
+ assertOut(blocked, 'BLOCKED');
1632
+
1633
+ // ③ 段名清单单一来源静态锁:四份清单的定义面必须落在**骨架模块**(由骨架实现符号
1634
+ // `buildSkeleton` 反查,不写文件名),消费面由文本里的真实引用派生(模块搬迁 / 新增消费方
1635
+ // 不必改锚)。消费方只取用:自带第二份定义、或改从别处取用,都由同一判据判定违规。
1636
+ const skeletonModule = engineDefinitionModule('buildSkeleton');
1637
+ assertTrue(skeletonModule !== null,
1638
+ '骨架实现的定义面应恰一处(反查失败): ' + JSON.stringify(engineDefinitionHits('buildSkeleton')));
1639
+ const texts = engineScriptTexts();
1640
+ const segmentSymbols = [
1641
+ 'LEGACY_SUMMARY_ORDER',
1642
+ 'TEMPLATE_FALLBACK_SECTION_PATTERNS',
1643
+ 'LESSONS_SCAN_SECTION',
1644
+ 'SUMMARY_REQUIRED_SECTIONS',
1645
+ ];
1646
+ const issues = [];
1647
+ for (const symbol of segmentSymbols) {
1648
+ const lookup = engineDefinitionModule(symbol);
1649
+ if (lookup === null) {
1650
+ issues.push(symbol + ' 的定义面不唯一(应恰一处): ' + JSON.stringify(engineDefinitionHits(symbol)));
1651
+ continue;
1652
+ }
1653
+ if (lookup.file !== skeletonModule.file) {
1654
+ issues.push(symbol + ' 的清单落在 ' + lookup.file + '(唯一来源应是骨架模块 ' + skeletonModule.file + ')');
1655
+ }
1656
+ for (const problem of singleSourceImportProblems({ symbol, sourceRel: lookup.file, texts })) {
1657
+ issues.push(problem);
1658
+ }
1659
+ }
1660
+ assertTrue(issues.length === 0, '段名清单单源违规: ' + issues.join(' | '));
1661
+
1662
+ // ③b 反向构造(同一判据驱动 · 逐项改坏输入 ⇒ 必报,还原 ⇒ 复绿):四份清单逐份证明判别力,
1663
+ // 不是「只有某一份碰巧被测到」。
1664
+ {
1665
+ const sourceRel = skeletonModule.file;
1666
+ const sourceText = texts.get(sourceRel);
1667
+ for (const symbol of segmentSymbols) {
1668
+ const consumer = [...texts.keys()].find((rel) => rel !== sourceRel
1669
+ && new RegExp('import\\s*\\{[^}]*\\b' + symbol + '\\b').test(texts.get(rel)));
1670
+ if (consumer === undefined) {
1671
+ issues.push('反向构造前提不成立:找不到 ' + symbol + ' 的具名取用消费方');
1672
+ continue;
1673
+ }
1674
+ const consumerText = texts.get(consumer);
1675
+ // 探针对象带 changed(变异落在哪个文件),前提检查按它判定——不拿展示用 label 当控制流。
1676
+ const probes = [
1677
+ ['消费方自带第二份定义',
1678
+ new Map(texts).set(consumer, consumerText + '\nconst ' + symbol + ' = [];\n'), '自带第二份', consumer],
1679
+ ['源侧定义被抽掉(单源面被破坏)',
1680
+ new Map(texts).set(sourceRel,
1681
+ sourceText.replace('export const ' + symbol + ' =', 'const renamedSegmentOrderProbe =')),
1682
+ '单一来源被破坏', sourceRel],
1683
+ ['消费方不再取用(import 被抽掉)',
1684
+ new Map(texts).set(consumer, dropNamedImport(consumerText, symbol)), '未从', consumer],
1685
+ ];
1686
+ for (const [label, mutated, expected, changed] of probes) {
1687
+ if (mutated.get(changed) === texts.get(changed)) {
1688
+ issues.push(symbol + ' 反向构造前提失效(' + label + '):变异未改变 ' + changed);
1689
+ continue;
1690
+ }
1691
+ const reported = singleSourceImportProblems({ symbol, sourceRel, texts: mutated });
1692
+ if (!reported.some((problem) => problem.includes(expected))) {
1693
+ issues.push(symbol + ' 反向构造判别力缺失(' + label + ' 未被判违规)');
1694
+ }
1695
+ }
1696
+ if (singleSourceImportProblems({ symbol, sourceRel, texts }).length !== 0) {
1697
+ issues.push(symbol + ' 反向构造还原后未复绿(判据受输入顺序影响)');
1698
+ }
1699
+ }
1700
+ assertTrue(issues.length === 0, '段名清单单源锁反向构造失败: ' + issues.join(' | '));
1701
+ }
1702
+
1703
+ // ④ 行为侧反向构造:模板缺席时 SUMMARY 的段序判据确实吃清单——负例(段序偏离)被拦、
1704
+ // 正例(按模板段序)通过;清单若与真实段序脱节,两格至少一格红(清单不是摆设)。
1705
+ const executeState = () => {
1706
+ const next = newChangeState('execute');
1707
+ next.evidence.execute = { summary: 'executed' };
1708
+ next.evidence['subagent-execute'] = { handoffResult: handoffFor(['T01']) };
1709
+ return next;
1710
+ };
1711
+ resetFixture(dir);
1712
+ writeBaseline(dir);
1713
+ writeFile(dir, CHANGE_DIR + '/TASK.md', '# TASK\n\n## 任务清单\n\n' + TASK_DONE);
1714
+ // 负例:把「做了什么」挪到「越界检查」之后 → 偏离兜底段序 → BLOCKED(模板缺席也判)
1715
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY', { swap: [['做了什么', '越界检查']] }));
1716
+ writeState(dir, executeState());
1717
+ const outOfOrder = exitNode(dir, 'execute');
1718
+ assertExit(outOfOrder, 1);
1719
+ assertOut(outOfOrder, '未校验');
1720
+ assertOut(outOfOrder, '段序');
1721
+ // 正例:段序按清单 → 通过
1722
+ writeFile(dir, CHANGE_DIR + '/T01-SUMMARY.md', renderDoc('SUMMARY'));
1723
+ writeState(dir, executeState());
1724
+ const ordered = exitNode(dir, 'execute');
1725
+ assertExit(ordered, 0);
1726
+ assertOut(ordered, 'ALL CHECKS PASSED');
1727
+
1728
+ // ⑤ 模板整份缺席:命名段检查**全部跳过**(含 pick 类)。夹具:没有
1729
+ // flow-kit/templates/,且 CHANGE.md 连 `## Why` 都没有——旧实现拿
1730
+ // `TEMPLATE_FALLBACK_SECTION_PATTERNS.changeWhy` 判「缺必填段」而 BLOCKED,与「模板缺失全部
1731
+ // 跳过」相反。跳过后必须放行,且输出仍显式声明未校验(跳过可见、不是静默通过,L-079)。
1732
+ fs.rmSync(path.join(dir, 'flow-kit'), { recursive: true, force: true });
1733
+ resetFixture(dir);
1734
+ writeFile(dir, CHANGE_DIR + '/CHANGE.md', renderDoc('CHANGE', { omit: ['Why'] }));
1735
+ writeFile(dir, CHANGE_DIR + '/REQUIREMENT.md', renderDoc('REQUIREMENT'));
1736
+ const openState = () => {
1737
+ const next = newChangeState('open');
1738
+ next.evidence.open = { summary: 'intake complete' };
1739
+ return next;
1740
+ };
1741
+ writeState(dir, openState());
1742
+ const noFallback = exitNode(dir, 'open');
1743
+ assertExit(noFallback, 0);
1744
+ assertNotOut(noFallback, '缺必填段');
1745
+ assertOut(noFallback, '未校验');
1746
+ assertOut(noFallback, '模板缺失');
1747
+
1748
+ // ⑥ C9 后半句(反向构造):模板**在场**但该段名缺席(上游改版)⇒ 命名段 fallback 仍生效。
1749
+ // 同一缺 Why 的工件在「模板不含 Why」的夹具上必须被拦——否则「整份缺席不回落」会被写成
1750
+ // 「干脆不查」。
1751
+ resetFixture(dir);
1752
+ writeTemplateFixtureOmittingSection(dir, 'CHANGE', 'Why');
1753
+ writeFile(dir, CHANGE_DIR + '/CHANGE.md', renderDoc('CHANGE', { omit: ['Why'] }));
1754
+ writeFile(dir, CHANGE_DIR + '/REQUIREMENT.md', renderDoc('REQUIREMENT'));
1755
+ writeState(dir, openState());
1756
+ const fallbackStill = exitNode(dir, 'open');
1757
+ assertExit(fallbackStill, 1);
1758
+ assertOut(fallbackStill, '缺必填段');
1759
+
1760
+ // ⑦ 判据形态(同一 pick 的两态):整份模板缺席 ⇒ 返回显式「跳过」判据(`skip` 标记 +
1761
+ // `.test` 恒真),不是 fallback 正则、也不是 null——消费方里有闭包外直接 `.test` 的调用点
1762
+ // (「视觉调性」段读取),返回 null 会把「跳过」退化成 TypeError 崩溃(未校验变失败)。
1763
+ const routing = await import('../lib/guard-routing.mjs');
1764
+ const underivedPatterns = await routing.templateSectionPatterns({ runRoot: path.join(dir, 'bare-root') });
1765
+ const skippedPick = underivedPatterns.pick('change', ['Why'], routing.TEMPLATE_FALLBACK_SECTION_PATTERNS.changeWhy);
1766
+ assertTrue(skippedPick !== routing.TEMPLATE_FALLBACK_SECTION_PATTERNS.changeWhy
1767
+ && skippedPick?.skip === true
1768
+ && skippedPick.test('不含 Why 的夹具正文(旧实现据此判缺段)') === true,
1769
+ '整份模板缺席时 pick 应返回显式跳过判据(不回落 fallback),实际: ' + String(skippedPick));
1770
+ const derivedPatterns = await routing.templateSectionPatterns({ runRoot: dir });
1771
+ const fallbackPick = derivedPatterns.pick('change', ['Why'], routing.TEMPLATE_FALLBACK_SECTION_PATTERNS.changeWhy);
1772
+ assertTrue(fallbackPick instanceof RegExp && fallbackPick.test('## Why(为什么做)'),
1773
+ '模板在场但缺该段名时 pick 仍回落 fallback 正则(C9 后半句),实际: ' + String(fallbackPick));
1774
+ },
1775
+ },
1776
+
1777
+ // TA-22 · 版本漂移在发版期被发现(AC-22)——登记表记录的模板指纹与锁定快照不一致 → 漂移可判;
1778
+ // 一致时零漂移。反向构造:改写一个字节后 drift 必为 true(同一判据函数)。
1779
+ // 指纹判据的输入必须是模板真迹:没有 vendored 模板的检出(CI 全新检出)里夹具按登记表合成段形,
1780
+ // 合成文本的 sha 与登记表锁定的 sha 天然不可比——此时「一致 → 无漂移」无从执行,不得当作通过
1781
+ // (未验证 ≠ 通过),也不得据此断言漂移(登记表并没有错)。真迹在场才全强度执行,否则可见 SKIP。
1782
+ {
1783
+ name: 'TA-22 指纹漂移:模板与锁定快照一致判无漂移,改一字节判漂移(模板非真迹时显式 SKIP)',
1784
+ run: async (dir) => {
1785
+ const skeleton = await import('../lib/guard-artifact-skeleton.mjs');
1786
+ // 骨架按项目根缓存——漂移对比必须落在另一个项目根上,否则读到的是缓存值(判据空转)
1787
+ const cleanRoot = path.join(dir, 'clean');
1788
+ const driftRoot = path.join(dir, 'drift');
1789
+ const realTemplateRel = docRel('SUMMARY');
1790
+ const realTemplatePresent = fs.existsSync(path.join(REPO_ROOT, ...realTemplateRel.split('/')));
1791
+ // ① 一致 → drift === false
1792
+ writeFile(cleanRoot, realTemplateRel, templateFixtureText('SUMMARY'));
1793
+ const clean = await skeleton.templateFingerprint('SUMMARY', { runRoot: cleanRoot });
1794
+ assertTrue(clean.derived === true, '模板在场时骨架应可派生(derived=true),实际: ' + JSON.stringify(clean));
1795
+ if (realTemplatePresent) {
1796
+ assertTrue(clean.drift === false, '模板与登记表指纹一致时应判无漂移,实际: ' + JSON.stringify(clean));
1797
+ // ② 反向构造:改一个字节 → drift === true
1798
+ writeFile(driftRoot, realTemplateRel, templateFixtureText('SUMMARY') + '\n漂移探针。\n');
1799
+ const drifted = await skeleton.templateFingerprint('SUMMARY', { runRoot: driftRoot });
1800
+ assertTrue(drifted.drift === true, '模板被改写后应判漂移,实际: ' + JSON.stringify(drifted));
1801
+ } else {
1802
+ console.log('SKIP: TA-22 的指纹漂移判据(模板非真迹:本检出无 vendored ' + realTemplateRel
1803
+ + ',夹具按登记表合成段形,实测 sha ' + clean.actualSha256 + ' 与登记表锁定 '
1804
+ + clean.recordedSha256 + ' 不可比)——本次检出未执行「一致 → 无漂移 / 改一字节 → 漂移」,'
1805
+ + '请在权威源检出重跑本套件(未验证 ≠ 通过)');
1806
+ }
1807
+ // ②b 指纹归一化:BOM / 行尾是检出噪音——同一内容的 LF 形态与 BOM+CRLF 形态必须同指纹
1808
+ // (归一化由骨架模块单实现)。反向构造:内容真变一行 → 指纹必不同,证明「同值」不是恒等判据。
1809
+ const lfText = templateFixtureText('SUMMARY').replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n');
1810
+ const bomCrlfText = '\uFEFF' + lfText.replace(/\n/gu, '\r\n');
1811
+ assertTrue(bomCrlfText.startsWith('\uFEFF') && bomCrlfText.includes('\r\n'),
1812
+ '夹具前提不成立:BOM+CRLF 形态未构造出来');
1813
+ const crlfRoot = path.join(dir, 'crlf');
1814
+ writeFile(crlfRoot, docRel('SUMMARY'), bomCrlfText);
1815
+ const byCrlf = await skeleton.templateFingerprint('SUMMARY', { runRoot: crlfRoot });
1816
+ assertTrue(byCrlf.derived === true, 'BOM+CRLF 模板应仍可派生,实际: ' + JSON.stringify(byCrlf));
1817
+ assertTrue(byCrlf.actualSha256 === clean.actualSha256,
1818
+ 'BOM+CRLF 与 LF 形态应同指纹(行尾/BOM 不改变指纹),实际: '
1819
+ + byCrlf.actualSha256 + ' vs ' + clean.actualSha256);
1820
+ // 反向构造(判别力):同一构造再加一行 → 指纹必不同(否则「同值」可能只是判据恒等)
1821
+ const mutatedRoot = path.join(dir, 'crlf-mutated');
1822
+ writeFile(mutatedRoot, docRel('SUMMARY'), bomCrlfText + '\n归一化探针。\n');
1823
+ const byMutated = await skeleton.templateFingerprint('SUMMARY', { runRoot: mutatedRoot });
1824
+ assertTrue(byMutated.actualSha256 !== clean.actualSha256,
1825
+ '内容多一行后指纹必须不同(归一化不得吞掉内容),实际仍为 ' + byMutated.actualSha256);
1826
+
1827
+ // ③ 关外键:登记表没有的模板键 → 显式未知(不静默当作「无漂移」)
1828
+ const unknown = await skeleton.templateFingerprint('NO-SUCH-TEMPLATE', { runRoot: cleanRoot });
1829
+ assertTrue(unknown.derived === false && unknown.reason === 'unknown-key',
1830
+ '未知模板键应显式标注 unknown-key,实际: ' + JSON.stringify(unknown));
1831
+ // ④ 发版期检查接线:CI 已包含登记表指纹比对步骤。CI workflow 属主仓分发面(安装副本无
1832
+ // `.github/`):结构性缺席时输出可见 SKIP(未验证 ≠ 通过),不让缺席把整条场景判红。
1833
+ const ciRel = '.github/workflows/ci.yml';
1834
+ if (!repoFileExists(ciRel)) {
1835
+ console.log('SKIP: TA-22 的发版期检查接线面(' + ciRel + ' 不在本检出)——本次检出未校验 CI 是否比对'
1836
+ + '登记表指纹,请在权威源检出重跑本套件(未验证 ≠ 通过)');
1837
+ } else {
1838
+ assertTrue(repoFileText(ciRel).includes('artifact-templates.json'),
1839
+ '发版期检查应比对登记表指纹(CI 需引用 reference/artifact-templates.json)');
1840
+ }
1841
+
1842
+ // ⑤ 登记表与模板分叉(正例):登记表登记的段在模板里不存在(模板回退 / 上游删段)⇒ 按模板为准忽略
1843
+ // 并**可见 WARN**,不阻断。旧实现把这批登记项静默丢弃(`registered` 标志算出后无消费方),
1844
+ // 登记表滞后因此不可见。单位面看骨架把这类段单独报出;端到端看门禁真实发声且不阻断。
1845
+ const staleRoot = path.join(dir, 'stale');
1846
+ writeTemplateFixtureOmittingSection(staleRoot, 'CHANGE', '视觉调性');
1847
+ const stale = await skeleton.buildSkeleton('CHANGE', { runRoot: staleRoot });
1848
+ const toneEntry = (docEntry('CHANGE').sections ?? []).find((section) => section.name.includes('视觉调性'));
1849
+ assertTrue(toneEntry !== undefined, '登记表 CHANGE 缺「视觉调性」段(夹具前提不成立)');
1850
+ assertTrue(stale.derived === true, '模板仍在场(只少一段)时应可派生,实际: ' + JSON.stringify(stale));
1851
+ assertTrue((stale.registryOnlySections ?? []).includes(toneEntry.name),
1852
+ '登记表多出的段应被单独报出(不是静默丢弃),实际: ' + JSON.stringify(stale.registryOnlySections));
1853
+ resetFixture(dir);
1854
+ writeTemplateFixtureOmittingSection(dir, 'CHANGE', '视觉调性');
1855
+ writeFile(dir, CHANGE_DIR + '/CHANGE.md', renderDoc('CHANGE'));
1856
+ writeFile(dir, CHANGE_DIR + '/REQUIREMENT.md', renderDoc('REQUIREMENT'));
1857
+ const openState = () => {
1858
+ const next = newChangeState('open');
1859
+ next.evidence.open = { summary: 'intake complete' };
1860
+ return next;
1861
+ };
1862
+ writeState(dir, openState());
1863
+ const warned = exitNode(dir, 'open');
1864
+ assertExit(warned, 0);
1865
+ assertOut(warned, 'TEMPLATE-REGISTRY WARN');
1866
+ assertOut(warned, '视觉调性');
1867
+ assertNotOut(warned, 'BLOCKED');
1868
+
1869
+ // ⑥ 登记表与模板分叉(反例):登记表与模板一致 ⇒ 同一门禁不得发声(WARN 是滞后信号,不是常驻噪音,
1870
+ // 否则真信号会被自己淹没)。
1871
+ setupOpen(dir);
1872
+ const fresh = await skeleton.buildSkeleton('CHANGE', { runRoot: dir });
1873
+ assertTrue(fresh.registryOnlySections.length === 0,
1874
+ '登记表与模板一致时不得报「多出的段」,实际: ' + JSON.stringify(fresh.registryOnlySections));
1875
+ const quiet = exitNode(dir, 'open');
1876
+ assertExit(quiet, 0);
1877
+ assertNotOut(quiet, 'TEMPLATE-REGISTRY WARN');
1878
+ },
1879
+ },
1880
+
1881
+ // TA-23 · 覆盖声明与同步面(AC-23)——7 册「必填段清单」两栏表与引擎一致;14 册锚句在场;
1882
+ // Guardrails 表中被新门禁覆盖的行不再声称「guard 不校验」;verify 册 UAT 的「验收结果」改为仅存在性;
1883
+ // 入口册覆盖声明四要素齐备。全部为仓库级文本断言,逐条带变异探针。
1884
+ {
1885
+ name: 'TA-23 覆盖声明与同步面:7 册两栏表、14 册锚句、Guardrails 同步、UAT 仅存在性',
1886
+ run: () => {
1887
+ const twoColumnBooks = [
1888
+ 'flow-comet-open', 'flow-comet-design', 'flow-comet-plan', 'flow-comet-execute',
1889
+ 'flow-comet-review', 'flow-comet-verify', 'flow-comet-subagent-execute',
1890
+ ];
1891
+ const books = new Map();
1892
+ for (const name of twoColumnBooks) books.set(name + '/SKILL.md', skillBookText(name));
1893
+ books.set('flow-comet/SKILL.md', skillBookText('flow-comet'));
1894
+ books.set('flow-comet-review/SKILL.md', skillBookText('flow-comet-review'));
1895
+ books.set('flow-comet-verify/SKILL.md', skillBookText('flow-comet-verify'));
1896
+ books.set('flow-comet-archive/SKILL.md', skillBookText('flow-comet-archive'));
1897
+
1898
+ const rules = [];
1899
+ for (const name of twoColumnBooks) {
1900
+ rules.push({
1901
+ rel: name + '/SKILL.md',
1902
+ label: '两栏表(左无条件段 / 右条件段与增量段)',
1903
+ include: ['无条件段', '增量段', 'flow-kit/templates/'],
1904
+ });
1905
+ }
1906
+ rules.push({
1907
+ rel: 'flow-comet/SKILL.md',
1908
+ label: '覆盖声明四要素',
1909
+ include: ['只读', '不采用', '沿用', '以本节为准'],
1910
+ });
1911
+ // phase-gated 反转句:四要素在场不等于方向反转还在——「本仓是 phase-gated」对抗上游 artifact-first 的那句是
1912
+ // 覆盖声明的实质(既引用上游又表态取向),抽掉它四要素仍全在,故单独锚。
1913
+ rules.push({
1914
+ rel: 'flow-comet/SKILL.md',
1915
+ label: 'phase-gated 反转句',
1916
+ include: ['artifact-first', '本仓是 **phase-gated**:8 节点 entry/exit 门'],
1917
+ });
1918
+ // 方向反转之外还须说明阶段门与工件门的关系:只有「有门」说不出门守的是什么,抽掉该句入口册
1919
+ // 读起来就像拿阶段门替代工件(「阶段门 = 工件检查的替代品」正是本仓要挡的过度解读)。
1920
+ rules.push({
1921
+ rel: 'flow-comet/SKILL.md',
1922
+ label: '阶段门与工件门的关系句',
1923
+ include: ['阶段门是工件门的加强,不是替代'],
1924
+ });
1925
+ rules.push({
1926
+ rel: 'flow-comet-review/SKILL.md',
1927
+ label: 'Guardrails 行与新门禁同步',
1928
+ include: ['test-pyramid-checked'],
1929
+ exclude: ['test-pyramid-checked` | TEST.md 5-round completeness verified | 执行纪律(review 把关),guard 不校验'],
1930
+ });
1931
+ rules.push({
1932
+ rel: 'flow-comet-verify/SKILL.md',
1933
+ label: 'Guardrails 行与新门禁同步 + UAT 仅存在性',
1934
+ include: ['lessons-nominated', '仅存在性'],
1935
+ });
1936
+ rules.push({
1937
+ rel: 'flow-comet-archive/SKILL.md',
1938
+ label: 'Guardrails 行与新门禁同步',
1939
+ include: ['changelog-updated'],
1940
+ exclude: ['changelog-updated` | CHANGELOG.md has new entry | 执行纪律(review 把关),guard 不校验'],
1941
+ });
1942
+
1943
+ const problems = textRuleProblems(books, rules);
1944
+ // 变异探针:正向(抽掉目标文字 ⇒ 必报)与反向(补上缺失文字 ⇒ 不再报,证判据不恒真)。
1945
+ // 预期片段一律取报文里的成句形态(缺「X」/ 仍含旧表述),避免与规则标签串混淆。
1946
+ assertProbesDiscriminate(problems, books, rules, [
1947
+ ['抽掉两栏表左栏', 'flow-comet-open/SKILL.md', (text) => text.replace(/无条件段/g, '必填段'), '缺「无条件段」'],
1948
+ ['抽掉两栏表右栏', 'flow-comet-design/SKILL.md', (text) => text.replace(/增量段/g, '追加段'), '缺「增量段」'],
1949
+ ['补上两栏表', 'flow-comet-plan/SKILL.md',
1950
+ (text) => text + '\n| 左栏:无条件段 | 右栏:条件段 / 增量段(flow-kit/templates/ 派生) |\n', '缺「无条件段」', false],
1951
+ ['抽掉覆盖声明要素', 'flow-comet/SKILL.md', (text) => text.replace(/以本节为准/g, ''), '缺「以本节为准」'],
1952
+ ['补上覆盖声明要素', 'flow-comet/SKILL.md', (text) => text + '\n与本册冲突时以本节为准。\n沿用项见上表。\n', '缺「以本节为准」', false],
1953
+ ['抽掉 phase-gated 反转句', 'flow-comet/SKILL.md',
1954
+ (text) => text.replace('本仓是 **phase-gated**:8 节点 entry/exit 门', '本仓方向与上游一致'),
1955
+ '缺「本仓是 **phase-gated**:8 节点 entry/exit 门」'],
1956
+ ['抽掉阶段门关系句', 'flow-comet/SKILL.md',
1957
+ (text) => text.replace('阶段门是工件门的加强,不是替代', ''),
1958
+ '缺「阶段门是工件门的加强,不是替代」'],
1959
+ ['Guardrails 行改回旧表述', 'flow-comet-review/SKILL.md',
1960
+ (text) => text.replace('test-pyramid-checked',
1961
+ 'test-pyramid-checked` | TEST.md 5-round completeness verified | 执行纪律(review 把关),guard 不校验'), 'guard 不校验'],
1962
+ ['补上 UAT 仅存在性', 'flow-comet-verify/SKILL.md',
1963
+ (text) => text + '\nUAT.md 的 `## 验收结果` 段仅存在性校验。\n', '缺「仅存在性」', false],
1964
+ ]);
1965
+ if (problems.length > 0) throw new Error('覆盖声明与同步面不符: ' + problems.join('; '));
1966
+ },
1967
+ },
1968
+
1969
+ // TA-24 · 公开面不再说假话(AC-24)——5 对双语公开文本的覆盖表述与实际门禁范围一致:不再有
1970
+ // 「完全继承 / 段名在运行时派生」这类 overclaim;机制册的「哪些节点查段名」表覆盖全部出口;
1971
+ // 故障排查给出两阶段报错指引;工件保真条点明本仓增量段。
1972
+ {
1973
+ name: 'TA-24 公开面口径:5 对双语去除 overclaim,机制表覆盖全出口,排查给两阶段指引',
1974
+ run: () => {
1975
+ const docs = new Map();
1976
+ const missingFaces = [];
1977
+ const pairs = [
1978
+ ['README.md', 'README-zh.md'],
1979
+ ['CONTRIBUTING.md', 'CONTRIBUTING-zh.md'],
1980
+ ['docs/USAGE.md', 'docs/USAGE-zh.md'],
1981
+ ['docs/MECHANISM.md', 'docs/MECHANISM-zh.md'],
1982
+ ['docs/TROUBLESHOOTING.md', 'docs/TROUBLESHOOTING-zh.md'],
1983
+ ];
1984
+ for (const [en, zh] of pairs) {
1985
+ const missing = [en, zh].filter((rel) => !repoFileExists(rel));
1986
+ if (missing.length > 0) {
1987
+ missingFaces.push(...missing);
1988
+ continue;
1989
+ }
1990
+ docs.set(en, repoFileText(en));
1991
+ docs.set(zh, repoFileText(zh));
1992
+ }
1993
+ // 公开面在安装副本形态结构性缺席(目标项目只有技能包,无本仓公开文档):整面输出一条可见
1994
+ // SKIP(未验证 ≠ 通过)——缺席既不算「判据违规」,也不静默当成已校验。
1995
+ if (missingFaces.length > 0) {
1996
+ console.log('SKIP: TA-24 的公开面口径判据(' + [...new Set(missingFaces)].join('、') + ' 不在本检出)——'
1997
+ + '本次检出未校验 5 对双语公开文档的 overclaim / 机制表 / 排查指引口径,请在权威源检出重跑本套件(未验证 ≠ 通过)');
1998
+ }
1999
+ const rules = [
2000
+ { rel: 'README-zh.md', label: '去 overclaim(继承表述)', exclude: ['完全继承'] },
2001
+ { rel: 'README.md', label: '去 overclaim(继承表述)', exclude: ['inherits its artifacts and rules'] },
2002
+ { rel: 'CONTRIBUTING-zh.md', label: '段名来源改为上游模板 + 本仓增量', exclude: ['段名在运行时从 vendored 模板派生'] },
2003
+ { rel: 'docs/USAGE-zh.md', label: '工件保真条点明增量段', include: ['增量段'] },
2004
+ { rel: 'docs/TROUBLESHOOTING-zh.md', label: '两阶段报错指引', include: ['两阶段'] },
2005
+ { rel: 'docs/MECHANISM-zh.md', label: '机制表覆盖全出口', include: ['段名是否符合模板'] },
2006
+ ];
2007
+ // 判据只落在本检出真实存在的文档上:缺席面已由上方 SKIP 行显式声明未验证。
2008
+ const activeRules = rules.filter((rule) => docs.has(rule.rel));
2009
+ const problems = textRuleProblems(docs, activeRules);
2010
+ // 机制表一行的出口清单覆盖:execute / verify 必须在列(旧表只列 5 个出口)
2011
+ for (const [rel, needNodes] of [
2012
+ ['docs/MECHANISM-zh.md', ['execute', 'verify']],
2013
+ ['docs/MECHANISM.md', ['execute', 'verify']],
2014
+ ]) {
2015
+ const text = docs.get(rel);
2016
+ if (typeof text !== 'string') continue;
2017
+ const row = text.split(/\r?\n/).find((line) => line.includes('段名') && /open|design|plan/.test(line)) ?? '';
2018
+ if (row === '') {
2019
+ problems.push(rel + ' 缺「节点文档是否符合模板」机制行(无法核对出口面)');
2020
+ continue;
2021
+ }
2022
+ for (const node of needNodes) {
2023
+ if (!row.includes(node)) problems.push(rel + ' 机制行未覆盖出口 ' + node + '(口径落后于门禁范围)');
2024
+ }
2025
+ }
2026
+ // 变异探针:正向(overclaim 写回 / 口径改回旧形态)与反向(补上缺失口径 ⇒ 不再报)。
2027
+ // 含缺席面的探针不执行——上方 SKIP 行已显式声明该面未验证。
2028
+ const activeProbes = [
2029
+ ['overclaim 写回', 'README-zh.md', (text) => text + '\n工件与规则完全继承。\n', '仍含旧表述「完全继承」'],
2030
+ ['段名来源改回运行时派生', 'CONTRIBUTING-zh.md',
2031
+ (text) => text + '\n段名在运行时从 vendored 模板派生。\n', '仍含旧表述「段名在运行时从 vendored 模板派生」'],
2032
+ ['补上两阶段指引', 'docs/TROUBLESHOOTING-zh.md',
2033
+ (text) => text + '\n## 缺段报错(两阶段)\n\n首次只给模板路径与类别计数,再犯才列段名。\n', '缺「两阶段」', false],
2034
+ ['补上增量段口径', 'docs/USAGE-zh.md',
2035
+ (text) => text + '\n工件保真 = 上游模板段 + 本仓增量段。\n', '缺「增量段」', false],
2036
+ ].filter(([, rel]) => docs.has(rel));
2037
+ assertProbesDiscriminate(problems, docs, activeRules, activeProbes);
2038
+ if (problems.length > 0) throw new Error('公开面口径不符: ' + problems.join('; '));
2039
+ },
2040
+ },
2041
+
2042
+ // TA-25 · 治理落盘(AC-25)——4 条 ADR 在场;已锁决策 / 定义更新;机制册新增条目;发布清单增
2043
+ // 模板指纹检查项;主仓指导文件的 guard 校验描述同步;债务账本登记本批债务。
2044
+ // 维护者面(docs/internal、.specs)整组缺席时输出可见 SKIP(未验证 ≠ 通过)。
2045
+ {
2046
+ name: 'TA-25 治理落盘:4 条 ADR + 已锁决策/机制册/发布清单/指导文件同步 + 债务登记',
2047
+ run: () => {
2048
+ const problems = [];
2049
+ // 治理落盘面 = 维护者主树面(docs/internal/ + CLAUDE.md + .specs 流程工件面)。安装副本
2050
+ // 结构性缺席该面时输出一条可见 SKIP(未验证 ≠ 通过):载体自带的 CONTEXT / ADR 与本仓治理
2051
+ // 面同名不同物,不能拿它们当本批落盘证据,也不该因它们的存在把场景判红。
2052
+ if (!maintainerFacePresent()) {
2053
+ console.log('SKIP: TA-25 的治理落盘判据(docs/internal/ 维护者面与 .specs 流程工件面结构性缺席)——'
2054
+ + '本次检出未校验 4 条 ADR、已锁决策/机制册/发布清单/指导文件同步与债务登记,请在维护者主树重跑本套件(未验证 ≠ 通过)');
2055
+ return;
2056
+ }
2057
+ // ① 4 条 ADR 在场(编号 + 主题骨架)
2058
+ const adrDir = path.join(REPO_ROOT, '.specs', 'adr');
2059
+ const adrNumbers = ['018', '019', '020', '021'];
2060
+ if (!fs.existsSync(adrDir)) {
2061
+ console.log('SKIP: 治理落盘判据——.specs/adr/ 不在本检出(流程工件面缺席,未验证 ≠ 通过)');
2062
+ } else {
2063
+ const files = fs.readdirSync(adrDir);
2064
+ for (const number of adrNumbers) {
2065
+ if (!files.some((name) => name.startsWith('ADR-' + number + '-'))) {
2066
+ problems.push('缺 ADR-' + number + '(本批治理决策应落盘 4 条)');
2067
+ }
2068
+ }
2069
+ }
2070
+ // ② 维护者文档面(docs/internal 缺席 → 整组可见 SKIP)
2071
+ const maintainerDocs = [
2072
+ 'docs/internal/ARCHITECTURE.md',
2073
+ 'docs/internal/MECHANISM.md',
2074
+ 'docs/internal/DOC-CHECKLIST.md',
2075
+ 'docs/internal/ROADMAP.md',
2076
+ ];
2077
+ const present = maintainerDocs.filter(repoFileExists);
2078
+ if (present.length !== maintainerDocs.length) {
2079
+ console.log('SKIP: 治理落盘判据——docs/internal/ 维护者面缺席(' + maintainerDocs.filter((rel) => !repoFileExists(rel)).join('、')
2080
+ + ');本次检出未校验该面,请回维护者主树重跑');
2081
+ } else {
2082
+ const docs = new Map(maintainerDocs.map((rel) => [rel, repoFileText(rel)]));
2083
+ const rules = [
2084
+ {
2085
+ rel: 'docs/internal/ARCHITECTURE.md',
2086
+ label: '已锁决策补模板权威与结构级校验边界',
2087
+ include: ['已锁决策', '模板', '结构级'],
2088
+ },
2089
+ { rel: 'docs/internal/MECHANISM.md', label: '机制册新增模板权威条目', include: ['模板权威'] },
2090
+ { rel: 'docs/internal/DOC-CHECKLIST.md', label: '发布期登记表指纹检查项', include: ['指纹'] },
2091
+ ];
2092
+ problems.push(...textRuleProblems(docs, rules));
2093
+ // ③ 债务账本登记——账本段内至少三行分别指向模板 / 指纹 / 骨架三类债务主题
2094
+ const roadmap = docs.get('docs/internal/ROADMAP.md') ?? '';
2095
+ const ledger = roadmap.split(/^## /m).find((chunk) => chunk.startsWith('债务账本')) ?? '';
2096
+ const debtLines = ledger.split(/\r?\n/).filter((line) => /模板|指纹|骨架/.test(line) && /^\|/.test(line)).length;
2097
+ if (debtLines < 3) {
2098
+ problems.push('债务账本应登记本批 3 条债务(模板/指纹/骨架 相关行),实际 ' + debtLines + ' 行');
2099
+ }
2100
+ assertProbesDiscriminate(problems, docs, rules, [
2101
+ ['补上模板指纹检查项', 'docs/internal/DOC-CHECKLIST.md',
2102
+ (text) => text + '\n- 发布期比对条件段登记表的模板指纹。\n', '缺「指纹」', false],
2103
+ ['补上机制册条目', 'docs/internal/MECHANISM.md',
2104
+ (text) => text + '\n## 模板权威(版本漂移检查)\n', '缺「模板权威」', false],
2105
+ ]);
2106
+ }
2107
+ // ④ CONTEXT 的已锁决策段(流程工件面)
2108
+ if (!repoFileExists('.specs/CONTEXT.md')) {
2109
+ console.log('SKIP: 治理落盘判据——.specs/CONTEXT.md 不在本检出(流程工件面缺席,未验证 ≠ 通过)');
2110
+ } else {
2111
+ const context = repoFileText('.specs/CONTEXT.md');
2112
+ if (!context.includes('## 已锁决策')) problems.push('.specs/CONTEXT.md 缺「## 已锁决策」段');
2113
+ if (!context.includes('模板')) problems.push('.specs/CONTEXT.md 已锁决策/定义未更新模板权威口径');
2114
+ }
2115
+ // ⑤ 主仓指导文件的 guard 校验描述同步(维护者面:缺席即跳过并可见)
2116
+ if (!repoFileExists('CLAUDE.md')) {
2117
+ console.log('SKIP: 治理落盘判据——CLAUDE.md 不在本检出(主仓私有面缺席,未验证 ≠ 通过)');
2118
+ } else {
2119
+ const guide = repoFileText('CLAUDE.md');
2120
+ if (!guide.includes('模板')) problems.push('CLAUDE.md 的 guard 校验描述未同步模板权威口径');
2121
+ }
2122
+ if (problems.length > 0) throw new Error('治理落盘不符: ' + problems.join('; '));
2123
+ },
2124
+ },
2125
+ ];