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,406 @@
1
+ // guard-artifact-skeleton.mjs — 工件骨架计算(单一实现)
2
+ //
3
+ // 输入:`<runRoot>/flow-kit/templates/<DOC>.md`(上游模板,内容权威)+ `<packageRoot>/reference/
4
+ // artifact-templates.json`(本仓登记表:条件段 / 可选段 / 结构子段 / 增量段 / 首部 / 标题形态 / 指纹)。
5
+ // 输出:规范化骨架(H2 序列 + 条件标记 + 结构型 H3 + 增量段位置 + 派生来源与指纹)。
6
+ //
7
+ // 单一实现纪律(L-067):骨架只在本模块计算。任何门禁(guard-routing / guard-template-fidelity /
8
+ // evolve / health)一律调用本模块,不得自持「读模板 + 抽 H2」的派生副本。段名归一复用 route-node 的
9
+ // normalizeHeading(去编号 / 去尾部括号 / 大小写归一),本模块不另写第二份段名归一。
10
+ // 「模板缺席时的段名清单」同样只在本模块登记(文件末尾的段名清单段)——消费方只 import,不自持
11
+ // 第二份字面清单(段名清单单一来源)。
12
+ //
13
+ // 模板缺席:derived=false 且 sections 为空(不内置任何兜底骨架)——调用方据此跳过校验并显式声明
14
+ // 「未校验(模板缺失)」。本模块对「登记表缺失 / 模板缺失 / 键未知」一律不抛错。
15
+ //
16
+ // 缓存:按 runRoot 键控(同一进程内每个项目根只算一次)。返回的骨架对象是共享缓存值,消费方只读。
17
+
18
+ import { createHash } from 'crypto';
19
+ import { promises as fs } from 'fs';
20
+ import path from 'path';
21
+ import { normalizeHeading } from '../route-node.mjs';
22
+ import { escapeRegExp } from './task-graph.mjs';
23
+ import { packageRoot, runRoot } from './guard-state-io.mjs';
24
+
25
+ const REGISTRY_PATH = path.join(packageRoot, 'reference', 'artifact-templates.json');
26
+ const HEADING_LINE = { 2: /^##\s+(.+?)\s*$/u, 3: /^###\s+(.+?)\s*$/u };
27
+
28
+ // 模板文本归一(BOM / 行尾):指纹与标题解析共用同一口径——行尾差异是检出的噪音,不应改变指纹。
29
+ function normalizeTemplateText(text) {
30
+ return String(text ?? '').replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n');
31
+ }
32
+
33
+ // vendored flow-kit 的版本读数:项目根下 flow-kit/ 的 git HEAD(安装器按锁定快照 --detach 检出,
34
+ // 开发检出通常在分支上)。只读 HEAD 与 ref 两个小文件,不起 git 子进程、不写任何东西;读不到 /
35
+ // 非常规形态一律返回 null——「无从判断」不等于「版本不符」,不得据此提示。
36
+ async function readVendoredCommit(root) {
37
+ const flowKitDir = path.join(root, 'flow-kit');
38
+ let gitDir = path.join(flowKitDir, '.git');
39
+ try {
40
+ if ((await fs.stat(gitDir)).isFile()) {
41
+ // worktree / 子模块形态:.git 是指针文件(gitdir: <路径>)
42
+ const matched = normalizeTemplateText(await fs.readFile(gitDir, 'utf8')).trim().match(/^gitdir:\s*(.+)$/u);
43
+ if (matched === null) return null;
44
+ gitDir = path.resolve(flowKitDir, matched[1].trim());
45
+ }
46
+ } catch {
47
+ return null;
48
+ }
49
+ let head = null;
50
+ try {
51
+ head = normalizeTemplateText(await fs.readFile(path.join(gitDir, 'HEAD'), 'utf8')).trim();
52
+ } catch {
53
+ return null;
54
+ }
55
+ if (/^[0-9a-f]{40}$/u.test(head)) return head;
56
+ const symbolic = head.match(/^ref:\s*(\S+)$/u);
57
+ if (symbolic === null) return null;
58
+ const ref = symbolic[1];
59
+ try {
60
+ const sha = normalizeTemplateText(await fs.readFile(path.join(gitDir, ...ref.split('/')), 'utf8')).trim();
61
+ if (/^[0-9a-f]{40}$/u.test(sha)) return sha;
62
+ } catch {
63
+ // 松引用缺席时退到 packed-refs(git gc 后的正常形态)
64
+ }
65
+ try {
66
+ const packed = normalizeTemplateText(await fs.readFile(path.join(gitDir, 'packed-refs'), 'utf8'));
67
+ for (const line of packed.split('\n')) {
68
+ const matched = line.match(/^([0-9a-f]{40})\s+(\S+)$/u);
69
+ if (matched !== null && matched[2] === ref) return matched[1];
70
+ }
71
+ } catch {
72
+ // 两个落点都读不到——按「无从判断」处理
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // 运行期轻提示:登记表锁定的快照 commit 与项目 vendored flow-kit 的 HEAD 不一致时,打一行
78
+ // 提示即返回——不阻断任何门禁、不改状态、不落盘。每个项目根在同一进程内只判定一次(骨架按根缓存,
79
+ // 重复判定只会得到同一结论)。
80
+ const vendoredCommitChecked = new Set();
81
+
82
+ async function maybeWarnVendoredCommit(root, lockedCommit) {
83
+ if (typeof lockedCommit !== 'string' || lockedCommit === '') return;
84
+ if (vendoredCommitChecked.has(root)) return;
85
+ vendoredCommitChecked.add(root);
86
+ const vendored = await readVendoredCommit(root);
87
+ if (vendored === null || vendored === lockedCommit) return;
88
+ console.error('TEMPLATE-FINGERPRINT WARN: 项目 flow-kit 检出 ' + vendored.slice(0, 12)
89
+ + ' ≠ 登记表锁定快照 ' + lockedCommit.slice(0, 12)
90
+ + ' —— 骨架按登记表快照校验(不阻断);升级 flow-kit 时须同批更新 reference/artifact-templates.json 的 templateCommit 与每模板 sha256');
91
+ }
92
+
93
+ // 标题行提取(行锚定):只认行首 ATX 标题。非锚定子串命中会被正文里「引用段名」劫持(L-128)。
94
+ function headingLines(text, level) {
95
+ const matcher = HEADING_LINE[level];
96
+ const out = [];
97
+ for (const line of normalizeTemplateText(text).split('\n')) {
98
+ const matched = line.match(matcher);
99
+ if (matched) out.push(matched[1].trim());
100
+ }
101
+ return out;
102
+ }
103
+
104
+ // 段名宽容匹配(单一实现):主体取 normalizeHeading 的结果,译为行锚定正则。编号前缀与尾部括号在
105
+ // 正则里同样是可选的——「省编号 / 换括号措辞 / 大小写不同」命中同一段,核心词不同则不命中(AC-9)。
106
+ // escapeRegExp 的既有契约是 glob 片段(调用方先 split('*')),故不转义 `*`;段名是字面文本,缺口在
107
+ // 这一行显式闭合,而不是另写一份转义实现。
108
+ export function headingPattern(rawName, level = 2) {
109
+ const normalized = normalizeHeading(rawName);
110
+ const body = normalized === '' ? String(rawName ?? '').trim() : normalized;
111
+ const literal = escapeRegExp(body).replace(/\*/gu, '\\*');
112
+ const marker = level === 3 ? '###' : '##';
113
+ return new RegExp(
114
+ '^' + marker + '\\s*(?:\\d+(?:\\.\\d+)?\\.?\\s*)?' + literal + '\\s*(?:[((][^\\n))]*[))])?\\s*$',
115
+ 'im',
116
+ );
117
+ }
118
+
119
+ // 登记表读取(进程内一次)
120
+ let registryCache = null;
121
+
122
+ async function loadRegistry() {
123
+ if (registryCache === null) {
124
+ try {
125
+ registryCache = {
126
+ available: true,
127
+ data: JSON.parse(normalizeTemplateText(await fs.readFile(REGISTRY_PATH, 'utf8'))),
128
+ };
129
+ } catch (error) {
130
+ registryCache = {
131
+ available: false,
132
+ reason: error?.code === 'ENOENT' ? 'registry-missing' : 'registry-unreadable',
133
+ };
134
+ }
135
+ }
136
+ return registryCache;
137
+ }
138
+
139
+ function compileTitlePattern(source) {
140
+ if (typeof source !== 'string' || source.trim() === '') return null;
141
+ try {
142
+ return new RegExp(source, 'i');
143
+ } catch {
144
+ return null;
145
+ }
146
+ }
147
+
148
+ // 骨架对象形态的唯一定义处:缺失 / 未派生路径直接返回它(derived=false + 空集合),正常路径在它上面
149
+ // 填充。单一形态定义让消费方只记一套字段——任何原因下键集合都相同,判「能不能校验」只看 derived。
150
+ function baseSkeleton(key, reason) {
151
+ return {
152
+ key,
153
+ derived: false,
154
+ reason,
155
+ file: null,
156
+ titleForm: null,
157
+ titleRegExp: null,
158
+ headerFields: [],
159
+ frontmatterKeys: [],
160
+ sections: [],
161
+ registryOnlySections: [],
162
+ structureSubsections: [],
163
+ increments: [],
164
+ templateCommit: null,
165
+ templateSha256: null,
166
+ actualSha256: null,
167
+ };
168
+ }
169
+
170
+ // 归一后同名的段在宽容口径下不可区分(典型:Button (Primary) / Button (Secondary) 都归一成 button)
171
+ // ——标记 unique=false,消费方须改用精确名匹配,避免「只写了 Secondary 也算 Primary 在场」的静默放过。
172
+ function markUniqueness(entries, scopeOf) {
173
+ const counts = new Map();
174
+ for (const entry of entries) {
175
+ const scope = scopeOf(entry) + '\u0000' + entry.norm;
176
+ counts.set(scope, (counts.get(scope) ?? 0) + 1);
177
+ }
178
+ for (const entry of entries) {
179
+ const scope = scopeOf(entry) + '\u0000' + entry.norm;
180
+ entry.unique = counts.get(scope) === 1;
181
+ }
182
+ return entries;
183
+ }
184
+
185
+ // H2 骨架 = 模板标题行(顺序即模板顺序)+ 登记表标记。段集合以**模板**为准(C14),两个方向分开:
186
+ // 模板有而登记表没登记的段按无条件段处理(模板是权威,不告警);登记表登记了而模板里没有的段按模板
187
+ // 忽略,但作为独立集合(registryOnlySections)报出——它是登记表滞后 / 上游删段的唯一可见信号
188
+ // (登记表与模板分叉),静默丢弃会让「模板权威」变成单向失明。
189
+ function buildSections(templateHeadings, registeredSections) {
190
+ const registered = new Map();
191
+ for (const entry of Array.isArray(registeredSections) ? registeredSections : []) {
192
+ if (typeof entry?.name !== 'string') continue;
193
+ registered.set(normalizeHeading(entry.name), entry);
194
+ }
195
+ const sections = templateHeadings.map((name, index) => {
196
+ const norm = normalizeHeading(name);
197
+ const flags = registered.get(norm);
198
+ return {
199
+ name,
200
+ norm,
201
+ index,
202
+ conditional: flags?.conditional === true,
203
+ optional: flags?.optional === true,
204
+ pattern: headingPattern(name, 2),
205
+ };
206
+ });
207
+ const templateNorms = new Set(sections.map((section) => section.norm));
208
+ const registryOnlySections = [...registered.entries()]
209
+ .filter(([norm]) => !templateNorms.has(norm))
210
+ .map(([, entry]) => entry.name);
211
+ return { sections: markUniqueness(sections, () => ''), registryOnlySections };
212
+ }
213
+
214
+ // 结构型 H3 由登记表显式列举(不用正则识别示例条目——示例条目是书写样例,不是骨架)
215
+ function buildStructureSubsections(registeredSubsections) {
216
+ const subsections = [];
217
+ for (const entry of Array.isArray(registeredSubsections) ? registeredSubsections : []) {
218
+ if (typeof entry?.name !== 'string') continue;
219
+ const parent = typeof entry.parent === 'string' ? entry.parent : null;
220
+ subsections.push({
221
+ name: entry.name,
222
+ norm: normalizeHeading(entry.name),
223
+ parent,
224
+ parentNorm: parent === null ? null : normalizeHeading(parent),
225
+ pattern: headingPattern(entry.name, 3),
226
+ });
227
+ }
228
+ return markUniqueness(subsections, (entry) => entry.parentNorm ?? '');
229
+ }
230
+
231
+ // 增量段(上游模板没有、本仓追加的段/标记):位置由登记表表达,供消费方按位置校验(AC-12)
232
+ function buildIncrements(registeredIncrements) {
233
+ const increments = [];
234
+ for (const entry of Array.isArray(registeredIncrements) ? registeredIncrements : []) {
235
+ if (typeof entry?.section !== 'string') continue;
236
+ const position = entry.position && typeof entry.position === 'object' ? entry.position : {};
237
+ const kind = entry.kind === 'marker' ? 'marker' : 'section';
238
+ increments.push({
239
+ section: entry.section,
240
+ norm: normalizeHeading(entry.section),
241
+ kind,
242
+ required: entry.required === true,
243
+ position: {
244
+ mode: typeof position.mode === 'string' ? position.mode : 'anywhere',
245
+ afterSection: position.afterSection ?? null,
246
+ afterNorm: typeof position.afterSection === 'string' ? normalizeHeading(position.afterSection) : null,
247
+ section: position.section ?? null,
248
+ sectionNorm: typeof position.section === 'string' ? normalizeHeading(position.section) : null,
249
+ constraint: position.constraint ?? null,
250
+ },
251
+ pattern: kind === 'marker' ? null : headingPattern(entry.section, 2),
252
+ });
253
+ }
254
+ return increments;
255
+ }
256
+
257
+ async function computeSkeleton(requestedKey, root) {
258
+ const registry = await loadRegistry();
259
+ if (!registry.available) return baseSkeleton(requestedKey, registry.reason);
260
+
261
+ const templates = registry.data?.templates ?? {};
262
+ const registeredKey = Object.keys(templates)
263
+ .find((key) => key.toLowerCase() === requestedKey.toLowerCase()) ?? null;
264
+ if (registeredKey === null) {
265
+ const skeleton = baseSkeleton(requestedKey, 'unknown-key');
266
+ skeleton.availableKeys = Object.keys(templates);
267
+ return skeleton;
268
+ }
269
+
270
+ const entry = templates[registeredKey];
271
+ const skeleton = baseSkeleton(registeredKey, null);
272
+ skeleton.file = typeof entry.file === 'string' ? entry.file : null;
273
+ skeleton.titleForm = typeof entry.titleForm === 'string' ? entry.titleForm : null;
274
+ skeleton.titleRegExp = compileTitlePattern(entry.titlePattern);
275
+ skeleton.headerFields = Array.isArray(entry.headerFields) ? [...entry.headerFields] : [];
276
+ skeleton.frontmatterKeys = Array.isArray(entry.frontmatterKeys) ? [...entry.frontmatterKeys] : [];
277
+ skeleton.templateCommit = registry.data?.templateCommit ?? null;
278
+ skeleton.templateSha256 = typeof entry.sha256 === 'string' ? entry.sha256 : null;
279
+
280
+ if (skeleton.file === null) {
281
+ skeleton.reason = 'template-undeclared';
282
+ return skeleton;
283
+ }
284
+ let text = null;
285
+ try {
286
+ text = await fs.readFile(path.resolve(root, ...skeleton.file.split('/')), 'utf8');
287
+ } catch {
288
+ text = null;
289
+ }
290
+ if (text === null) {
291
+ skeleton.reason = 'template-missing';
292
+ return skeleton;
293
+ }
294
+
295
+ const built = buildSections(headingLines(text, 2), entry.sections);
296
+ skeleton.sections = built.sections;
297
+ skeleton.registryOnlySections = built.registryOnlySections;
298
+ skeleton.structureSubsections = buildStructureSubsections(entry.structureSubsections);
299
+ skeleton.increments = buildIncrements(entry.increments);
300
+ skeleton.actualSha256 = createHash('sha256')
301
+ .update(Buffer.from(normalizeTemplateText(text), 'utf8'))
302
+ .digest('hex');
303
+ skeleton.derived = skeleton.sections.length > 0;
304
+ if (!skeleton.derived) skeleton.reason = 'template-empty';
305
+ // 登记表比模板多登记的段:按模板忽略(不阻断),但必须可见——否则登记表滞后只能等发版期指纹
306
+ // 检查才发现(且指纹只报「模板变了」,不说「哪段没用了」)。每个根 + 每个模板键只判一次(骨架
307
+ // 按根缓存),故不会重复刷屏。
308
+ if (skeleton.registryOnlySections.length > 0) {
309
+ console.error('TEMPLATE-REGISTRY WARN: 登记表登记的段在模板里不存在 '
310
+ + skeleton.registryOnlySections.length + ' 处(' + skeleton.registryOnlySections.join('、')
311
+ + ';模板 ' + skeleton.file + ')——段集合以模板为准,已按忽略处理(不阻断);'
312
+ + '请同批更新 reference/artifact-templates.json');
313
+ }
314
+ await maybeWarnVendoredCommit(root, skeleton.templateCommit);
315
+ return skeleton;
316
+ }
317
+
318
+ function resolveRoot(opts) {
319
+ const explicit = opts?.runRoot;
320
+ if (typeof explicit === 'string' && explicit.trim() !== '') return path.resolve(explicit);
321
+ return path.resolve(runRoot);
322
+ }
323
+
324
+ const skeletonCache = new Map(); // 项目根 → (小写键 → 骨架)
325
+
326
+ // 规范化骨架。key 大小写不敏感(既有消费方用 'change'/'summary' 等小写键,登记表用模板基名大写)。
327
+ // opts.runRoot 可指向另一个项目根(测试与临时夹具用);缺省用运行上下文 runRoot。
328
+ export async function buildSkeleton(key, opts = {}) {
329
+ const requested = String(key ?? '').trim();
330
+ const root = resolveRoot(opts);
331
+ let perRoot = skeletonCache.get(root);
332
+ if (!perRoot) {
333
+ perRoot = new Map();
334
+ skeletonCache.set(root, perRoot);
335
+ }
336
+ const cacheKey = requested.toLowerCase();
337
+ const cached = perRoot.get(cacheKey);
338
+ if (cached) return cached;
339
+ const skeleton = await computeSkeleton(requested, root);
340
+ perRoot.set(cacheKey, skeleton);
341
+ return skeleton;
342
+ }
343
+
344
+ // 模板指纹:登记表锁定的 commit + sha256 与实际模板读数。drift 三态——true/false = 可比对
345
+ // 且结论明确,null = 无从判断(模板或登记表读数缺失);「模板是否可读」看 actualSha256 是否为 null,
346
+ // 不另设第二个字段表达同一事实。发版期检查据此报红;运行期只做轻提示(computeSkeleton 的
347
+ // maybeWarnVendoredCommit——本函数自身不打印)。
348
+ export async function templateFingerprint(key, opts = {}) {
349
+ const skeleton = await buildSkeleton(key, opts);
350
+ const drift = skeleton.templateSha256 !== null && skeleton.actualSha256 !== null
351
+ ? skeleton.templateSha256 !== skeleton.actualSha256
352
+ : null;
353
+ return {
354
+ key: skeleton.key,
355
+ file: skeleton.file,
356
+ templateCommit: skeleton.templateCommit,
357
+ recordedSha256: skeleton.templateSha256,
358
+ actualSha256: skeleton.actualSha256,
359
+ drift,
360
+ derived: skeleton.derived,
361
+ reason: skeleton.reason,
362
+ };
363
+ }
364
+
365
+ // 登记表全部模板的骨架(键 = 模板基名)。登记表不可读 → 空对象(调用方按「未校验」处理)。
366
+ export async function allSkeletons(opts = {}) {
367
+ const registry = await loadRegistry();
368
+ if (!registry.available) return {};
369
+ const out = {};
370
+ for (const key of Object.keys(registry.data?.templates ?? {})) {
371
+ out[key] = await buildSkeleton(key, opts);
372
+ }
373
+ return out;
374
+ }
375
+
376
+ // ---------- 段名清单(全系统唯一一份)----------
377
+ //
378
+ // 模板缺席(模板未安装 / 登记表不可读)时仍然要生效的判据基准:模板缺席恰恰没有骨架可派生,所以
379
+ // 这些名字不可能由骨架算出来——它们是「模板缺席也要拦」的既有判据输入。此前它们以字面清单分散在
380
+ // 骨架模块之外的三处门禁模块里,「段名从哪来」因此有两个答案;现在一律在此登记,消费方只 import,
381
+ // 不得自持字面清单(静态单源锁 + 变异探针见 scenarios/n.mjs 的 TA-21)。
382
+ //
383
+ // 段名归一仍由消费方复用 route-node 的 normalizeHeading——本模块不另写第二份归一。
384
+
385
+ // SUMMARY 模板缺席时的段序兜底:登记表不可读 / 模板未安装时,SUMMARY 门禁仍判乱序与缺段。
386
+ export const LEGACY_SUMMARY_ORDER = ['做了什么', '改动文件', 'verify 输出', '6 维自查', '越界检查', '自检方法'];
387
+
388
+ // 模板缺席时 open / design 出口的段名回退(键形态保持不变,消费方按既有键取用)。
389
+ export const TEMPLATE_FALLBACK_SECTION_PATTERNS = {
390
+ changeWhy: /^##\s*Why\b/im,
391
+ changeVisualTone: /^##\s*视觉调性/im,
392
+ requirementUserStory: /^##\s*用户故事/im,
393
+ requirementAcceptance: /##\s*(验收准则|验收标准|AC|Acceptance Criteria)/i,
394
+ designDecisionList: /^##\s*\d*\.?\s*决策清单/m,
395
+ };
396
+
397
+ // LESSONS 扫描段名:登记表缺席时的回退名,同时是登记表 increment 的查找键。
398
+ export const LESSONS_SCAN_SECTION = 'LESSONS 扫描';
399
+
400
+ // SUMMARY 必填三段:每个 change 目录下每份 *-SUMMARY.md 都要在场(既有存在性判据,与模板派生
401
+ // 判据并行——它不依赖模板是否安装,故同样属于「段名基准」而不是骨架派生值)。
402
+ export const SUMMARY_REQUIRED_SECTIONS = [
403
+ { regex: /##\s*verify\s*输出/i, label: '## verify 输出' },
404
+ { regex: /##\s*6\s*维自查/i, label: '## 6 维自查' },
405
+ { regex: /##\s*(越界检查|边界检查)/i, label: '## 越界检查' },
406
+ ];
@@ -1,4 +1,5 @@
1
- // 证据与产物门禁(守卫模块):直显授权约束、在飞委托、SUMMARY 必填段与自检方法、execute 出口、
1
+ // 证据与产物门禁(守卫模块):直显授权约束、在飞委托、SUMMARY 必填段与自检方法、LESSONS 扫描段
2
+ // 与命中核对、execute 出口、
2
3
  // verify 出口(真实执行验证命令并记录失败计数)、Return Contract、subagent-execute 摘要与多趟完成
3
4
  // 判定、required-skill / schema / 产物 存在性门禁——即「完成声明必须有证据与产物」这一族判据。
4
5
  //
@@ -7,7 +8,7 @@
7
8
  import { promises as fs } from 'fs';
8
9
  import path from 'path';
9
10
  import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor } from '../state-schema.mjs';
10
- import { EXECUTE_FAMILY_NODE_IDS, analyzeDependencyGraph } from '../route-node.mjs';
11
+ import { EXECUTE_FAMILY_NODE_IDS, analyzeDependencyGraph, normalizeHeading } from '../route-node.mjs';
11
12
  import { taskOpeningAttrs, taskBlocks as extractTaskBlocks } from '../task-parsing.mjs';
12
13
  import { runRoot, fileExists, statePath, writeJson } from './guard-state-io.mjs';
13
14
  import {
@@ -23,6 +24,7 @@ import {
23
24
  verifySummaries,
24
25
  } from './guard-routing.mjs';
25
26
  import { applicabilityGatedBinding, frontendCriterion } from './guard-uidesign.mjs';
27
+ import { buildSkeleton, headingPattern, LESSONS_SCAN_SECTION } from './guard-artifact-skeleton.mjs';
26
28
 
27
29
  // directOverride 授权约束(direct 是用户决策点,不可自决——机制约束)——execute / subagent-execute
28
30
  // 出口校验:executionMode=direct 且 directOverride=true(显式直显授权态)须存在授权审计记录
@@ -65,8 +67,194 @@ export function runInFlightHandoffGate({ node, state }) {
65
67
  }
66
68
  }
67
69
 
70
+ // ---------- LESSONS 扫描(R1.8 · AC-18:开工前扫描可核对)----------
71
+ //
72
+ // 两条判据:① 每份 *-SUMMARY.md 含 `## LESSONS 扫描` 增量段;② 按任务 write_files 的路径段与该
73
+ // 段内应回应的条目编号(关键词求交、取前 5)必须逐条出现在该段里。段名 / 必填 / 位置三件事都来自
74
+ // 登记表(reference/artifact-templates.json 的 SUMMARY.increments)——位置语义由模板保真门禁按同一
75
+ // 条目执行,本门禁只判「在场 + 命中回应」,不写第二份位置判据(L-067)。
76
+ //
77
+ // 停用词表与命中上限单处定义(段名从骨架模块取用,不在本模块自持第二份清单)。关键词行
78
+ // (`- **关键词**:`)是唯一参与命中计算的字段——无关键词行的旧条目不参与(给旧条目一个不被
79
+ // 误命中的通道)。
80
+ const LESSONS_HIT_LIMIT = 5;
81
+ const LESSONS_PATH_STOPWORDS = new Set([
82
+ // 目录布局噪音
83
+ 'src', 'lib', 'libs', 'app', 'apps', 'core', 'pkg', 'packages', 'bin', 'dist', 'build', 'out',
84
+ 'tmp', 'temp', 'test', 'tests', 'spec', 'specs', 'unit', 'e2e', 'fixture', 'fixtures',
85
+ 'mock', 'mocks', 'docs', 'doc', 'scripts', 'script', 'assets', 'static', 'public',
86
+ 'config', 'configs', 'utils', 'util', 'helpers', 'helper', 'common', 'shared', 'internal',
87
+ 'modules', 'module', 'components', 'pages', 'views', 'styles', 'data', 'types', 'index',
88
+ // 扩展名 / 备份后缀残片
89
+ 'mjs', 'cjs', 'jsx', 'tsx', 'json', 'yaml', 'yml', 'toml', 'lock', 'bak', 'log', 'txt', 'css',
90
+ ]);
91
+
92
+ const LESSONS_ENTRY_HEADING = /^###\s*L-(\d+)\b/u;
93
+ const LESSONS_KEYWORD_LINE = /^[-*\s]*\*\*关键词\*\*\s*[::]\s*(.+)$/u;
94
+
95
+ // 段名 / 必填来自登记表;登记表或模板缺席时退回段名常量并保持必填——扫描段由 AC-18 要求,不因模板
96
+ // 派生失败而免检(「模板缺失」只让模板派生判据跳过,不让扫描声明消失)。
97
+ async function lessonsScanRule() {
98
+ const skeleton = await buildSkeleton('summary');
99
+ const wanted = normalizeHeading(LESSONS_SCAN_SECTION);
100
+ const entry = (skeleton.increments ?? []).find((item) => item.norm === wanted);
101
+ if (entry && entry.kind === 'section') {
102
+ return {
103
+ name: entry.section,
104
+ required: entry.required,
105
+ pattern: entry.pattern ?? headingPattern(entry.section, 2),
106
+ registered: true,
107
+ };
108
+ }
109
+ return { name: LESSONS_SCAN_SECTION, required: true, pattern: headingPattern(LESSONS_SCAN_SECTION, 2), registered: false };
110
+ }
111
+
112
+ // write_files 原文(键 = 任务 id)。块提取与开标签解析复用 task-parsing 的既有实现,只读元素文本。
113
+ async function taskWriteFiles(changeDir) {
114
+ const out = new Map();
115
+ let text = '';
116
+ try {
117
+ text = await fs.readFile(path.join(changeDir, 'TASK.md'), 'utf8');
118
+ } catch {
119
+ return out;
120
+ }
121
+ for (const block of extractTaskBlocks(text)) {
122
+ const attrs = taskOpeningAttrs(block);
123
+ if (!attrs || !attrs.id) continue;
124
+ const writeFiles = block.match(/<write_files>([\s\S]*?)<\/write_files>/i);
125
+ if (writeFiles) out.set(attrs.id, writeFiles[1]);
126
+ }
127
+ return out;
128
+ }
129
+
130
+ // 路径段 → 词元:目录名与文件主干(去最后一层扩展名)按非字母数字切分,长度 ≥3、去停用词、去纯数字。
131
+ // 只在「命中计算」这一侧做长度与停用词过滤——条目关键词侧原样保留,过滤口径不扩散成第二份规则。
132
+ function lessonsPathTokens(writeFilesText) {
133
+ const tokens = new Set();
134
+ for (const raw of String(writeFilesText ?? '').split(/[\n;]+/u)) {
135
+ const segments = raw.trim().replace(/\\/gu, '/').split('/').filter((s) => s !== '' && s !== '.' && s !== '..');
136
+ segments.forEach((segment, index) => {
137
+ const body = index === segments.length - 1 ? segment.replace(/\.[^.]*$/u, '') : segment;
138
+ for (const piece of body.split(/[^0-9A-Za-z\u4e00-\u9fff]+/u)) {
139
+ const token = piece.toLowerCase();
140
+ if ([...token].length < 3) continue;
141
+ if (/^\d+$/u.test(token)) continue;
142
+ if (LESSONS_PATH_STOPWORDS.has(token)) continue;
143
+ tokens.add(token);
144
+ }
145
+ });
146
+ }
147
+ return tokens;
148
+ }
149
+
150
+ // LESSONS 条目:`### L-NNN` 标题开启一个条目,块内 `- **关键词**:` 行的词元即命中输入;下一个 H2
151
+ // 结束条目区(区外的 `###` 不参与)。围栏代码块内是书写样例(模板里的「条目格式」示例即此形态),
152
+ // 按行扫描会被误当成真条目——围栏内一律跳过。无关键词行的条目不进结果集(旧条目跳过)。
153
+ function lessonsEntries(lessonsText) {
154
+ const entries = [];
155
+ let current = null;
156
+ let inFence = false;
157
+ for (const line of String(lessonsText ?? '').replace(/\r\n?/gu, '\n').split('\n')) {
158
+ if (/^\s*```/u.test(line)) { inFence = !inFence; continue; }
159
+ if (inFence) continue;
160
+ if (/^##\s/u.test(line)) { current = null; continue; }
161
+ const heading = line.match(LESSONS_ENTRY_HEADING);
162
+ if (heading) {
163
+ current = { id: 'L-' + String(Number(heading[1])).padStart(3, '0'), tokens: [], order: entries.length };
164
+ entries.push(current);
165
+ continue;
166
+ }
167
+ if (current === null) continue;
168
+ const keyword = line.match(LESSONS_KEYWORD_LINE);
169
+ if (!keyword) continue;
170
+ for (const piece of keyword[1].split(/[\s,,、;;/|]+/u)) {
171
+ const token = piece.trim().toLowerCase();
172
+ if (token !== '') current.tokens.push(token);
173
+ }
174
+ }
175
+ return entries.filter((entry) => entry.tokens.length > 0);
176
+ }
177
+
178
+ // 命中计算:路径词元 × 条目关键词词元求交,共享词元多的条目优先(相关度),同分按条目出现顺序
179
+ // (结果确定、可复核),取前 LESSONS_HIT_LIMIT 条。
180
+ function lessonsHits(pathTokens, entries) {
181
+ if (pathTokens.size === 0) return [];
182
+ const scored = [];
183
+ for (const entry of entries) {
184
+ const shared = [...new Set(entry.tokens.filter((token) => pathTokens.has(token)))];
185
+ if (shared.length === 0) continue;
186
+ scored.push({ id: entry.id, shared, order: entry.order });
187
+ }
188
+ scored.sort((a, b) => b.shared.length - a.shared.length || a.order - b.order);
189
+ return scored.slice(0, LESSONS_HIT_LIMIT);
190
+ }
191
+
192
+ // 段正文:命中段标题行之后、到下一个 H2 / 分隔线 / 文件尾(行锚定——正文里「引用段名」不劫持匹配)。
193
+ // 围栏代码块内的 `## ` 与 `---` 是正文示例,不当作段边界。段缺席返回 null(与「段在场但正文为空」
194
+ // 区分:前者是缺声明,后者由正文判据另行处理)。
195
+ function lessonsScanBody(content, pattern) {
196
+ const lines = String(content ?? '').replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n').split('\n');
197
+ const start = lines.findIndex((line) => pattern.test(line));
198
+ if (start === -1) return null;
199
+ const body = [];
200
+ let inFence = false;
201
+ for (let i = start + 1; i < lines.length; i += 1) {
202
+ if (/^\s*```/u.test(lines[i])) inFence = !inFence;
203
+ if (!inFence && (/^##\s/u.test(lines[i]) || /^---\s*$/u.test(lines[i]))) break;
204
+ body.push(lines[i]);
205
+ }
206
+ return body.join('\n');
207
+ }
208
+
209
+ // 编号在段内出现的判定:两侧非数字边界(L-501 不算命中 L-5012),大小写不敏感(执行者常写小写
210
+ // `l-501`)。转义集不含 `-`——字符类外的连字符本就是字面量,而在 `u` 标志下 `\-` 是非法转义
211
+ // (会抛 Invalid regular expression)。
212
+ function mentionsLessonsId(body, id) {
213
+ const escaped = id.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
214
+ return new RegExp('(^|[^0-9])' + escaped + '(?![0-9])', 'iu').test(body);
215
+ }
216
+
217
+ // 每份 SUMMARY 的两条判据 → 问题描述数组(分级由调用方按 isNewChange 决定:新 change BLOCKED /
218
+ // 旧 change WARN——C10 无例外)。TASK.md 或 .specs/LESSONS.md 缺席时对应输入为空:段在场判据照常,
219
+ // 命中计算自然为空集(无条目可命中)。
220
+ async function lessonsScanProblems(changeDir, summaryFiles) {
221
+ if (summaryFiles.length === 0) return [];
222
+ const rule = await lessonsScanRule();
223
+ const lessonsText = await fs.readFile(path.join(runRoot, '.specs', 'LESSONS.md'), 'utf8').catch(() => '');
224
+ const entries = lessonsEntries(lessonsText);
225
+ const writeFilesById = await taskWriteFiles(changeDir);
226
+ const problems = [];
227
+ for (const file of summaryFiles) {
228
+ let content = '';
229
+ try {
230
+ content = await fs.readFile(path.join(changeDir, file), 'utf8');
231
+ } catch (error) {
232
+ // 读失败不得静默跳过(L-079:依赖解析失败必须可见)——判据无法求值本身就是问题,按同一分级上报。
233
+ problems.push(file + ' 无法读取(' + String(error?.message ?? error) + ')——LESSONS 扫描判据无法求值');
234
+ continue;
235
+ }
236
+ const body = lessonsScanBody(content, rule.pattern);
237
+ if (body === null) {
238
+ if (rule.required) {
239
+ problems.push(file + ' 缺 ## ' + rule.name + ' 段(SUMMARY 增量段须声明扫描结果与命中回应'
240
+ + (rule.registered ? ';位置按登记表登记:自检方法之后' : '') + ')');
241
+ }
242
+ continue;
243
+ }
244
+ const taskId = file.replace(/-SUMMARY\.md$/iu, '');
245
+ const hits = lessonsHits(lessonsPathTokens(writeFilesById.get(taskId) ?? ''), entries);
246
+ const unanswered = hits.filter((hit) => !mentionsLessonsId(body, hit.id));
247
+ if (unanswered.length > 0) {
248
+ problems.push(file + ' 的 ## ' + rule.name + ' 段未回应命中条目 '
249
+ + unanswered.map((hit) => hit.id + '(关键词: ' + hit.shared.join('、') + ')').join('、')
250
+ + '——R1.8 要求逐条声明「仍适用 / 差异是 X」');
251
+ }
252
+ }
253
+ return problems;
254
+ }
255
+
68
256
  // execute / subagent-execute 出口校验每份 SUMMARY 含三个必填段 + 6 维自查非空 + 自检方法声明
69
- // (brooks-review / cache-brooks / builtin-quickcheck 三级降级路径)
257
+ // (brooks-review / cache-brooks / builtin-quickcheck 三级降级路径)+ LESSONS 扫描段与命中核对
70
258
  export async function runSummarySectionsGate({ node, state }) {
71
259
  if (!EXECUTE_FAMILY_NODE_IDS.has(node.id)) return;
72
260
  const changeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
@@ -136,8 +324,23 @@ export async function runSummarySectionsGate({ node, state }) {
136
324
  }
137
325
  } catch {}
138
326
  }
327
+ // LESSONS 扫描(AC-18):每份 SUMMARY 的扫描段在场 + 命中条目逐条回应。分级沿用既有语义——
328
+ // 新 change BLOCKED / 旧 change WARN(C10 无例外)。
329
+ const lessonsProblems = await lessonsScanProblems(changeDir, summaryFiles);
330
+ if (lessonsProblems.length > 0) {
331
+ if (isNewChange(state)) {
332
+ violations.push(...lessonsProblems);
333
+ } else {
334
+ for (const problem of lessonsProblems) {
335
+ console.error('LESSONS SCAN WARN: ' + problem + '(旧 change 渐进,不阻断;新 change 将强制)');
336
+ }
337
+ }
338
+ }
139
339
  if (violations.length > 0) {
140
340
  console.error('BLOCKED: SUMMARY 关键段校验失败: ' + violations.join('; '));
341
+ if (lessonsProblems.length > 0 && isNewChange(state)) {
342
+ console.error('恢复: 按 flow-kit/templates/SUMMARY.md 在 ## 自检方法 之后补 ## LESSONS 扫描 段,并逐条写出命中条目编号与差异声明(无命中写「无 active 条目命中」);命中来源 = TASK.md 该任务 write_files 的路径段 × .specs/LESSONS.md 条目的关键词行');
343
+ }
141
344
  process.exit(1);
142
345
  }
143
346
  }