flow-comet 1.5.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.flow-comet/rules/flow-comet-orchestration.md +13 -0
  2. package/.flow-comet/skills/flow-comet/GUIDANCE.md +196 -0
  3. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -0
  4. package/.flow-comet/skills/flow-comet/SKILL.md +196 -0
  5. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +19 -0
  6. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +115 -0
  7. package/.flow-comet/skills/flow-comet/reference/authoring-lanes.json +33 -0
  8. package/.flow-comet/skills/flow-comet/reference/composition-report.md +65 -0
  9. package/.flow-comet/skills/flow-comet/reference/decision-points.md +64 -0
  10. package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +30 -0
  11. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +169 -0
  12. package/.flow-comet/skills/flow-comet/reference/init-detection.md +58 -0
  13. package/.flow-comet/skills/flow-comet/reference/recovery.md +20 -0
  14. package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +661 -0
  15. package/.flow-comet/skills/flow-comet/reference/skill-review.md +13 -0
  16. package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +7 -0
  17. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +681 -0
  18. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +52 -0
  19. package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +61 -0
  20. package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +909 -0
  21. package/.flow-comet/skills/flow-comet/scripts/comet-plan.mjs +2 -0
  22. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +312 -0
  23. package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +136 -0
  24. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +7331 -0
  25. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +376 -0
  26. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +230 -0
  27. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +99 -0
  28. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +4017 -0
  29. package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +28 -0
  30. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +2396 -0
  31. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +378 -0
  32. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +1263 -0
  33. package/.flow-comet/skills/flow-comet-archive/SKILL.md +195 -0
  34. package/.flow-comet/skills/flow-comet-change/SKILL.md +29 -0
  35. package/.flow-comet/skills/flow-comet-compose/SKILL.md +249 -0
  36. package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +23 -0
  37. package/.flow-comet/skills/flow-comet-design/SKILL.md +161 -0
  38. package/.flow-comet/skills/flow-comet-dev/SKILL.md +51 -0
  39. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +26 -0
  40. package/.flow-comet/skills/flow-comet-execute/SKILL.md +182 -0
  41. package/.flow-comet/skills/flow-comet-health/SKILL.md +31 -0
  42. package/.flow-comet/skills/flow-comet-integration/SKILL.md +45 -0
  43. package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +36 -0
  44. package/.flow-comet/skills/flow-comet-open/SKILL.md +161 -0
  45. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +33 -0
  46. package/.flow-comet/skills/flow-comet-plan/SKILL.md +169 -0
  47. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +27 -0
  48. package/.flow-comet/skills/flow-comet-review/SKILL.md +204 -0
  49. package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +29 -0
  50. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +214 -0
  51. package/.flow-comet/skills/flow-comet-task/SKILL.md +33 -0
  52. package/.flow-comet/skills/flow-comet-test/SKILL.md +41 -0
  53. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +26 -0
  54. package/.flow-comet/skills/flow-comet-verify/SKILL.md +164 -0
  55. package/LICENSE +21 -0
  56. package/README.md +255 -0
  57. package/package.json +27 -0
  58. package/scripts/dsh-bridge.mjs +461 -0
  59. package/scripts/prepare-env.mjs +1526 -0
@@ -0,0 +1,2396 @@
1
+ #!/usr/bin/env node
2
+ import { constants as fsConstants, promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { createHash } from 'crypto';
6
+ import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor, RUNTIME_STATE_PATH, LEGACY_RUNTIME_STATE_PATH } from './state-schema.mjs';
7
+ import { resolveProtocol, readProtocolFile, validateProtocolSchema, NODE_PROTOCOL_FILES } from './protocol-utils.mjs';
8
+ import { taskOpeningAttrs, taskBlocks as extractTaskBlocks } from './task-parsing.mjs';
9
+ import { resolveNextNode } from './route-node.mjs';
10
+
11
+ const command = process.argv[2] ?? 'verify';
12
+ const nodeId = process.argv[3] ?? null;
13
+ const apply = process.argv.includes('--apply');
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ const packageRoot = path.resolve(__dirname, '..');
16
+ const runRoot = process.env.FLOW_COMET_RUN_ROOT ? path.resolve(process.env.FLOW_COMET_RUN_ROOT) : process.cwd();
17
+ // 协议路径解析(resolveProtocol):--protocol 全局参数从命令后的剩余参数提取(command=argv[2]),
18
+ // 其次 FLOW_COMET_PROTOCOL 环境变量,最后内置默认 <packageRoot>/reference/workflow-protocol.json
19
+ const protocolPath = resolveProtocol(packageRoot, runRoot, process.argv.slice(3));
20
+
21
+
22
+ const WORKFLOW_PROJECT_FILE_MAX_BYTES = 2 * 1024 * 1024;
23
+
24
+ // W1-A: 节点 → 合法 exit 的前置条件(对齐 flow-kit 阶段门 + flowkit.*.v1 evidence)
25
+ const NODE_TRANSITION_GATES = {
26
+ open: { evidence: ['intake-summary'] },
27
+ design: { evidence: ['design-summary'] },
28
+ plan: { evidence: ['plan-summary'] },
29
+ execute: { evidence: ['implementation-summary'] },
30
+ 'subagent-execute':{ evidence: ['handoff-result'] },
31
+ review: { evidence: ['review-summary'] },
32
+ verify: { evidence: ['verification-result'] },
33
+ archive: { evidence: ['archive-summary'] },
34
+ };
35
+
36
+ // 节点协议映射(单一来源): NODE_PROTOCOL_FILES 已移入 protocol-utils.mjs(exit 协议声明校验 + record 自动补声明共用)
37
+
38
+ // 声明标记 protocol → basename 提取(exit 校验与 节点协议映射表 basename 精确比对)。
39
+ // 兼容新旧两种格式:新格式(skill-load 写入)= 纯 basename(如 0-change.md),原样返回;
40
+ // 旧格式(缺陷修复前写入)= resolveProtocol 解析后的完整绝对路径(Windows 反斜杠 /
41
+ // POSIX 斜杠),提取最后一段后可比对。非字符串(null——skill-load 未传 --protocol 的
42
+ // 新格式缺省)→ null(协议集内无 null,fail-closed 由 includes 比对兜底)。
43
+ // R6: 新旧 change 区分——init 写入的 newChange: true = 新 change(严格,不依赖 entry——防系统性
44
+ // 跳 entry 绕过);缺失/非 true(旧 change) = 渐进 WARN 兼容。供 R1/R2 升级与 M 机制使用。
45
+ function isNewChange(state) {
46
+ return state.newChange === true;
47
+ }
48
+
49
+ function markerProtocolBasename(value) {
50
+ if (typeof value !== 'string' || value === '') return null;
51
+ return String(value).replaceAll('\\', '/').split('/').pop() || null;
52
+ }
53
+
54
+ // REVIEW.md 发现区条目处置状态提取——"## 发现" 段下 Critical/Major/Minor
55
+ // 子区的发现项 = 以 "- **" 开头的列表项(加粗标题);"无" 条目("- 无" / "无(...)")表示
56
+ // 该级别无发现,豁免。返回缺处置状态标记([已修]/[升级]/[转待办])的条目标题列表——
57
+ // 结构级校验(不做语义判断:标记存在即视为已处置)。发现项(含 Minor)不得"记录后无声消失"。
58
+ function reviewFindingsMissingDisposition(text) {
59
+ const missing = [];
60
+ for (const section of text.split(/\n##\s+/)) {
61
+ if (!/^发现/.test(section)) continue;
62
+ for (const line of section.split('\n')) {
63
+ const m = line.match(/^\s*-\s*\*\*(.+?)\*\*/);
64
+ if (!m) continue;
65
+ if (/^无/.test(m[1].trim())) continue; // "无" 条目豁免
66
+ // 四要素字段行豁免:REVIEW 发现条目的 Symptom/Source/Consequence/Remedy
67
+ // 是 brooks 审查输出格式的字段行(带 ** 加粗),不是发现条目本身——不豁免会误判
68
+ // 为"发现项缺处置标记"(执行者按 4 要素格式书写时被误 BLOCKED)。
69
+ // 精确匹配完整标签(允许尾冒号)——"Source maps expose paths" 这类以 Source 开头的
70
+ // 真实发现标题不得被前缀匹配误豁免(其处置校验必须照常进行)
71
+ if (/^(?:Symptom|Source|Consequence|Remedy)\s*:?\s*$/i.test(m[1].trim())) continue;
72
+ if (!/\[已修\]|\[升级\]|\[转待办\]/.test(line)) missing.push(m[1]);
73
+ }
74
+ }
75
+ return missing;
76
+ }
77
+
78
+ // W1-B: flow-kit SUMMARY 模板必填段(正则匹配,大小写不敏感 + 变体兼容)
79
+ const SUMMARY_REQUIRED_SECTIONS = [
80
+ { regex: /##\s*verify\s*输出/i, label: '## verify 输出' },
81
+ { regex: /##\s*6\s*维自查/i, label: '## 6 维自查' },
82
+ { regex: /##\s*(越界检查|边界检查)/i, label: '## 越界检查' },
83
+ ];
84
+
85
+ function workflowPathInside(root, target) {
86
+ const relative = path.relative(root, target);
87
+ return (
88
+ relative === '' ||
89
+ (!path.isAbsolute(relative) &&
90
+ relative !== '..' &&
91
+ !relative.startsWith('..' + path.sep))
92
+ );
93
+ }
94
+
95
+ async function inspectWorkflowProtectedPath(
96
+ projectRoot,
97
+ target,
98
+ label,
99
+ expected = 'any',
100
+ ) {
101
+ const lexicalRoot = path.resolve(projectRoot);
102
+ const lexicalTarget = path.resolve(target);
103
+ if (!workflowPathInside(lexicalRoot, lexicalTarget)) {
104
+ throw new Error(label + ' must stay inside the project root');
105
+ }
106
+ const rootStat = await fs.lstat(lexicalRoot);
107
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
108
+ throw new Error(label + ' project root must be a real directory');
109
+ }
110
+ const realRoot = await fs.realpath(lexicalRoot);
111
+ const relative = path.relative(lexicalRoot, lexicalTarget);
112
+ const segments = relative === '' ? [] : relative.split(path.sep);
113
+ let cursor = lexicalRoot;
114
+ for (let index = 0; index < segments.length; index++) {
115
+ cursor = path.join(cursor, segments[index]);
116
+ let stat;
117
+ try {
118
+ stat = await fs.lstat(cursor);
119
+ } catch (error) {
120
+ if (
121
+ error &&
122
+ typeof error === 'object' &&
123
+ (error.code === 'ENOENT' || error.code === 'ENOTDIR')
124
+ ) {
125
+ return { target: lexicalTarget, exists: false };
126
+ }
127
+ throw error;
128
+ }
129
+ const display = path.relative(lexicalRoot, cursor).replaceAll('\\', '/');
130
+ if (stat.isSymbolicLink()) {
131
+ throw new Error(label + ' crosses a symbolic link or junction at ' + display);
132
+ }
133
+ const final = index === segments.length - 1;
134
+ if (!final && !stat.isDirectory()) {
135
+ throw new Error(label + ' ancestor ' + display + ' must be a real directory');
136
+ }
137
+ if (
138
+ final &&
139
+ ((expected === 'file' && !stat.isFile()) ||
140
+ (expected === 'directory' && !stat.isDirectory()) ||
141
+ (expected === 'any' && !stat.isFile() && !stat.isDirectory()))
142
+ ) {
143
+ throw new Error(label + ' must be a real ' + expected);
144
+ }
145
+ const physical = await fs.realpath(cursor);
146
+ if (!workflowPathInside(realRoot, physical)) {
147
+ throw new Error(label + ' resolves outside the project root');
148
+ }
149
+ }
150
+ return { target: lexicalTarget, exists: true };
151
+ }
152
+
153
+ function workflowFileObjectIdentity(stat) {
154
+ return {
155
+ dev: stat.dev,
156
+ ino: stat.ino,
157
+ birthtime: typeof stat.birthtimeNs === 'bigint' ? stat.birthtimeNs : stat.birthtimeMs,
158
+ };
159
+ }
160
+
161
+ function workflowHasIdentity(value) {
162
+ return value !== 0 && value !== 0n && value !== '0';
163
+ }
164
+
165
+ function workflowSameFileObject(left, right) {
166
+ const comparableDevice = workflowHasIdentity(left.dev) && workflowHasIdentity(right.dev);
167
+ const comparableInode = workflowHasIdentity(left.ino) && workflowHasIdentity(right.ino);
168
+ if (comparableDevice && left.dev !== right.dev) return false;
169
+ if (comparableInode && left.ino !== right.ino) return false;
170
+ if (comparableDevice && comparableInode) return true;
171
+ return left.birthtime === right.birthtime;
172
+ }
173
+
174
+ function workflowSameFileStat(left, right) {
175
+ return (
176
+ workflowSameFileObject(
177
+ workflowFileObjectIdentity(left),
178
+ workflowFileObjectIdentity(right),
179
+ ) &&
180
+ left.size === right.size &&
181
+ left.ctimeNs === right.ctimeNs
182
+ );
183
+ }
184
+
185
+ async function readWorkflowProtectedFile(
186
+ projectRoot,
187
+ file,
188
+ label,
189
+ maxBytes,
190
+ hooks = {},
191
+ ) {
192
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
193
+ throw new Error(label + ' byte limit must be a positive integer');
194
+ }
195
+ const inspection = await inspectWorkflowProtectedPath(
196
+ projectRoot,
197
+ file,
198
+ label,
199
+ 'file',
200
+ );
201
+ if (!inspection.exists) {
202
+ const error = new Error(label + ' does not exist');
203
+ error.code = 'ENOENT';
204
+ throw error;
205
+ }
206
+ const before = await fs.lstat(file, { bigint: true });
207
+ if (!before.isFile() || before.isSymbolicLink()) {
208
+ throw new Error(label + ' must be a real file');
209
+ }
210
+ if (before.size > BigInt(maxBytes)) {
211
+ throw new Error(label + ' exceeds ' + String(maxBytes) + ' bytes');
212
+ }
213
+ const beforeRealPath = await fs.realpath(file);
214
+ await hooks.afterLstat?.();
215
+ const flags =
216
+ process.platform === 'win32'
217
+ ? fsConstants.O_RDONLY
218
+ : fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK;
219
+ let handle;
220
+ try {
221
+ handle = await fs.open(file, flags);
222
+ } catch (error) {
223
+ if (error && typeof error === 'object' && error.code === 'ELOOP') {
224
+ throw new Error(label + ' must be a real file');
225
+ }
226
+ throw error;
227
+ }
228
+ try {
229
+ const [opened, afterOpen, afterOpenRealPath] = await Promise.all([
230
+ handle.stat({ bigint: true }),
231
+ fs.lstat(file, { bigint: true }),
232
+ fs.realpath(file),
233
+ ]);
234
+ if (
235
+ !opened.isFile() ||
236
+ !afterOpen.isFile() ||
237
+ afterOpen.isSymbolicLink() ||
238
+ afterOpenRealPath !== beforeRealPath ||
239
+ !workflowSameFileStat(before, opened) ||
240
+ !workflowSameFileStat(before, afterOpen)
241
+ ) {
242
+ throw new Error(label + ' changed while opening');
243
+ }
244
+ await inspectWorkflowProtectedPath(projectRoot, file, label, 'file');
245
+ await hooks.afterOpen?.();
246
+ const chunks = [];
247
+ let total = 0;
248
+ const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1));
249
+ for (;;) {
250
+ const remaining = maxBytes + 1 - total;
251
+ const { bytesRead } = await handle.read(
252
+ buffer,
253
+ 0,
254
+ Math.min(buffer.length, remaining),
255
+ null,
256
+ );
257
+ if (bytesRead === 0) break;
258
+ total += bytesRead;
259
+ if (total > maxBytes) {
260
+ throw new Error(label + ' exceeds ' + String(maxBytes) + ' bytes');
261
+ }
262
+ chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
263
+ }
264
+ await hooks.beforeFinalCheck?.();
265
+ const [afterHandle, afterPath, afterRealPath] = await Promise.all([
266
+ handle.stat({ bigint: true }),
267
+ fs.lstat(file, { bigint: true }),
268
+ fs.realpath(file),
269
+ ]);
270
+ if (
271
+ !afterPath.isFile() ||
272
+ afterPath.isSymbolicLink() ||
273
+ afterRealPath !== beforeRealPath ||
274
+ !workflowSameFileStat(before, afterHandle) ||
275
+ !workflowSameFileStat(before, afterPath)
276
+ ) {
277
+ throw new Error(label + ' changed while reading');
278
+ }
279
+ await inspectWorkflowProtectedPath(projectRoot, file, label, 'file');
280
+ return Buffer.concat(chunks, total);
281
+ } finally {
282
+ await handle.close();
283
+ }
284
+ }
285
+
286
+ function workflowRelativeSegments(value, label, allowWildcards = false) {
287
+ if (typeof value !== 'string') throw new Error(label + ' must be a string');
288
+ const trimmed = value.trim().replaceAll('\\', '/');
289
+ if (
290
+ trimmed.length === 0 ||
291
+ path.posix.isAbsolute(trimmed) ||
292
+ path.win32.isAbsolute(trimmed) ||
293
+ trimmed.startsWith('~') ||
294
+ trimmed.startsWith('/') ||
295
+ trimmed.startsWith('\\')
296
+ ) {
297
+ throw new Error(label + ' must be relative to its declared path base');
298
+ }
299
+ const segments = trimmed.split('/');
300
+ if (segments.some((segment) => segment === '..')) {
301
+ const boundary = label === 'workflow-run statePath' ? 'the project root' : 'its declared path base';
302
+ throw new Error(label + ' must stay inside ' + boundary);
303
+ }
304
+ if (segments.some((segment) => segment === '' || segment === '.')) {
305
+ throw new Error(label + ' must not contain empty or dot path segments');
306
+ }
307
+ if (!allowWildcards && (trimmed.includes('*') || trimmed.includes('?'))) {
308
+ throw new Error(label + ' cannot contain wildcards');
309
+ }
310
+ return segments;
311
+ }
312
+
313
+ function resolveWorkflowRelativePath(base, value, label, allowWildcards = false) {
314
+ const segments = workflowRelativeSegments(value, label, allowWildcards);
315
+ const target = path.resolve(base, ...segments);
316
+ const relative = path.relative(path.resolve(base), target);
317
+ if (
318
+ path.isAbsolute(relative) ||
319
+ relative === '..' ||
320
+ relative.startsWith('..' + path.sep)
321
+ ) {
322
+ const boundary = label === 'workflow-run statePath' ? 'the project root' : 'its declared path base';
323
+ throw new Error(label + ' must stay inside ' + boundary);
324
+ }
325
+ return { target, segments };
326
+ }
327
+
328
+
329
+ async function workflowProtectedDirectorySnapshot(projectRoot, directory, label) {
330
+ const inspection = await inspectWorkflowProtectedPath(
331
+ projectRoot,
332
+ directory,
333
+ label,
334
+ 'directory',
335
+ );
336
+ if (!inspection.exists) {
337
+ throw new Error(label + ' does not exist');
338
+ }
339
+ const stat = await fs.lstat(directory, { bigint: true });
340
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
341
+ throw new Error(label + ' must be a real directory');
342
+ }
343
+ return {
344
+ stat,
345
+ realPath: await fs.realpath(directory),
346
+ };
347
+ }
348
+
349
+ async function assertWorkflowProtectedDirectorySnapshot(
350
+ projectRoot,
351
+ directory,
352
+ label,
353
+ expected,
354
+ ) {
355
+ const actual = await workflowProtectedDirectorySnapshot(
356
+ projectRoot,
357
+ directory,
358
+ label,
359
+ );
360
+ if (
361
+ actual.realPath !== expected.realPath ||
362
+ !workflowSameFileObject(
363
+ workflowFileObjectIdentity(actual.stat),
364
+ workflowFileObjectIdentity(expected.stat),
365
+ )
366
+ ) {
367
+ throw new Error(label + ' changed before commit');
368
+ }
369
+ }
370
+
371
+ async function ensureWorkflowProtectedDirectory(projectRoot, directory, label) {
372
+ const root = path.resolve(projectRoot);
373
+ const target = path.resolve(directory);
374
+ if (!workflowPathInside(root, target)) {
375
+ throw new Error(label + ' must stay inside the project root');
376
+ }
377
+ const relative = path.relative(root, target);
378
+ const segments = relative === '' ? [] : relative.split(path.sep);
379
+ let cursor = root;
380
+ await inspectWorkflowProtectedPath(root, cursor, label, 'directory');
381
+ for (const segment of segments) {
382
+ const parent = cursor;
383
+ cursor = path.join(cursor, segment);
384
+ const inspection = await inspectWorkflowProtectedPath(
385
+ root,
386
+ cursor,
387
+ label,
388
+ 'directory',
389
+ );
390
+ if (!inspection.exists) {
391
+ const parentSnapshot = await workflowProtectedDirectorySnapshot(
392
+ root,
393
+ parent,
394
+ label + ' parent',
395
+ );
396
+ try {
397
+ await fs.mkdir(cursor);
398
+ } catch (error) {
399
+ if (!error || typeof error !== 'object' || error.code !== 'EEXIST') {
400
+ throw error;
401
+ }
402
+ }
403
+ await assertWorkflowProtectedDirectorySnapshot(
404
+ root,
405
+ parent,
406
+ label + ' parent',
407
+ parentSnapshot,
408
+ );
409
+ }
410
+ const created = await inspectWorkflowProtectedPath(
411
+ root,
412
+ cursor,
413
+ label,
414
+ 'directory',
415
+ );
416
+ if (!created.exists) {
417
+ throw new Error(label + ' could not be created safely');
418
+ }
419
+ }
420
+ }
421
+
422
+ async function workflowProtectedTargetSnapshot(projectRoot, file, label) {
423
+ const inspection = await inspectWorkflowProtectedPath(
424
+ projectRoot,
425
+ file,
426
+ label,
427
+ 'file',
428
+ );
429
+ if (!inspection.exists) return { exists: false };
430
+ const stat = await fs.lstat(file, { bigint: true });
431
+ if (!stat.isFile() || stat.isSymbolicLink()) {
432
+ throw new Error(label + ' must be a real file');
433
+ }
434
+ return {
435
+ exists: true,
436
+ stat,
437
+ realPath: await fs.realpath(file),
438
+ };
439
+ }
440
+
441
+ async function assertWorkflowProtectedTargetSnapshot(
442
+ projectRoot,
443
+ file,
444
+ label,
445
+ expected,
446
+ ) {
447
+ const actual = await workflowProtectedTargetSnapshot(projectRoot, file, label);
448
+ if (actual.exists !== expected.exists) {
449
+ throw new Error(label + ' changed before commit');
450
+ }
451
+ if (
452
+ actual.exists &&
453
+ expected.exists &&
454
+ (actual.realPath !== expected.realPath ||
455
+ !workflowSameFileStat(actual.stat, expected.stat))
456
+ ) {
457
+ throw new Error(label + ' changed before commit');
458
+ }
459
+ }
460
+
461
+ async function writeWorkflowProtectedFile(
462
+ projectRoot,
463
+ file,
464
+ label,
465
+ value,
466
+ maxBytes,
467
+ ) {
468
+ const bytes = Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8');
469
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
470
+ throw new Error(label + ' byte limit must be a positive integer');
471
+ }
472
+ if (bytes.length > maxBytes) {
473
+ throw new Error(label + ' exceeds ' + String(maxBytes) + ' bytes');
474
+ }
475
+ const root = path.resolve(projectRoot);
476
+ const target = path.resolve(file);
477
+ const directory = path.dirname(target);
478
+ await ensureWorkflowProtectedDirectory(root, directory, label + ' directory');
479
+ const directorySnapshot = await workflowProtectedDirectorySnapshot(
480
+ root,
481
+ directory,
482
+ label + ' directory',
483
+ );
484
+ const targetSnapshot = await workflowProtectedTargetSnapshot(root, target, label);
485
+ await assertWorkflowProtectedDirectorySnapshot(
486
+ root,
487
+ directory,
488
+ label + ' directory',
489
+ directorySnapshot,
490
+ );
491
+ await assertWorkflowProtectedTargetSnapshot(root, target, label, targetSnapshot);
492
+
493
+ const temporary = path.join(
494
+ directory,
495
+ '.' +
496
+ path.basename(target) +
497
+ '.' +
498
+ String(process.pid) +
499
+ '.' +
500
+ String(Date.now()) +
501
+ '.' +
502
+ Math.random().toString(16).slice(2) +
503
+ '.tmp',
504
+ );
505
+ const flags =
506
+ fsConstants.O_WRONLY |
507
+ fsConstants.O_CREAT |
508
+ fsConstants.O_EXCL |
509
+ (process.platform === 'win32' ? 0 : fsConstants.O_NOFOLLOW);
510
+ let handle;
511
+ let committed = false;
512
+ try {
513
+ await assertWorkflowProtectedDirectorySnapshot(
514
+ root,
515
+ directory,
516
+ label + ' directory',
517
+ directorySnapshot,
518
+ );
519
+ handle = await fs.open(temporary, flags, 0o600);
520
+ await handle.writeFile(bytes);
521
+ await handle.sync();
522
+ const temporaryStat = await handle.stat({ bigint: true });
523
+ if (!temporaryStat.isFile()) {
524
+ throw new Error(label + ' temporary path must be a real file');
525
+ }
526
+ await handle.close();
527
+ handle = undefined;
528
+ await inspectWorkflowProtectedPath(
529
+ root,
530
+ temporary,
531
+ label + ' temporary file',
532
+ 'file',
533
+ );
534
+ await assertWorkflowProtectedDirectorySnapshot(
535
+ root,
536
+ directory,
537
+ label + ' directory',
538
+ directorySnapshot,
539
+ );
540
+ await assertWorkflowProtectedTargetSnapshot(root, target, label, targetSnapshot);
541
+ await fs.rename(temporary, target);
542
+ committed = true;
543
+ await inspectWorkflowProtectedPath(root, target, label, 'file');
544
+ await assertWorkflowProtectedDirectorySnapshot(
545
+ root,
546
+ directory,
547
+ label + ' directory',
548
+ directorySnapshot,
549
+ );
550
+ } finally {
551
+ if (handle) {
552
+ await handle.close().catch(() => {});
553
+ }
554
+ if (!committed) {
555
+ try {
556
+ await assertWorkflowProtectedDirectorySnapshot(
557
+ root,
558
+ directory,
559
+ label + ' directory',
560
+ directorySnapshot,
561
+ );
562
+ await fs.rm(temporary, { force: true });
563
+ } catch {
564
+ // Do not follow a replaced parent during cleanup.
565
+ }
566
+ }
567
+ }
568
+ }
569
+
570
+ function slug(value) {
571
+ return String(value).toLowerCase().replace(/[^a-z0-9._-]+/gu, '-').replace(/^-+|-+$/gu, '');
572
+ }
573
+
574
+ function generatedNodeSkillName(protocol, id) {
575
+ return (slug(protocol.name) || 'workflow') + '-' + (slug(id) || 'node');
576
+ }
577
+
578
+ // 组装 statePath 失效错误:声明的字段值 + 实际解析出的绝对路径 + 跨命名空间探测 + 调整指引。
579
+ // 交叉探测的两个命名空间取值来自 state-schema.mjs 的运行时路径常量(单一来源,本文件不再硬编码);
580
+ // 探测只读、只改善错误措辞,不参与路径解析,也不改变控制流(绝不回退到另一命名空间,fail-closed 语义不变)。
581
+ // 探测基准 = statePath 所在目录的父目录(项目根布局下即项目根);该基准落在项目外时回落
582
+ // 到项目根,保证探测点不越出项目。探测失败一律按"未探测到"处理,不掩盖主错误。
583
+ async function statePathMissingError(declared, target) {
584
+ const lines = [
585
+ 'workflow-run statePath does not exist: ' + declared + ' (resolved to ' + target + ')',
586
+ ];
587
+ const parent = path.resolve(path.dirname(target), '..');
588
+ const probeBase = workflowPathInside(runRoot, parent) ? parent : runRoot;
589
+ const declaredNormalized = declared.replaceAll('\\', '/');
590
+ const elsewhere = [];
591
+ for (const candidate of [LEGACY_RUNTIME_STATE_PATH, RUNTIME_STATE_PATH]) {
592
+ if (candidate === declaredNormalized) continue;
593
+ if (await fileExists(path.resolve(probeBase, ...candidate.split('/')))) elsewhere.push(candidate);
594
+ }
595
+ if (elsewhere.length > 0) {
596
+ lines.push(
597
+ 'hint: a state file exists in the other runtime namespace (' + elsewhere.join(', ') +
598
+ ') — the project may not be migrated yet; run the installer (prepare-env) to finish the migration, or correct the statePath field',
599
+ );
600
+ }
601
+ lines.push(
602
+ 'fix: edit "state.statePath" in the workflow protocol JSON (' + protocolPath +
603
+ ') — the value must be the state file path relative to the project root (current runtime namespace: ' +
604
+ RUNTIME_STATE_PATH + ')',
605
+ );
606
+ const error = new Error(lines.join('\n'));
607
+ error.code = 'ENOENT';
608
+ return error;
609
+ }
610
+
611
+ async function statePath(protocol) {
612
+ const preferred = String(protocol.state?.statePath ?? '');
613
+ const target = resolveWorkflowRelativePath(
614
+ runRoot,
615
+ preferred,
616
+ 'workflow-run statePath',
617
+ ).target;
618
+ const inspection = await inspectWorkflowProtectedPath(
619
+ runRoot,
620
+ target,
621
+ 'workflow-run statePath',
622
+ 'file',
623
+ );
624
+ if (!inspection.exists) {
625
+ throw await statePathMissingError(preferred, target);
626
+ }
627
+ return target;
628
+ }
629
+
630
+ async function readStateJson(file) {
631
+ // 容忍 UTF-8 BOM(外部写入可能带 BOM)
632
+ return JSON.parse(
633
+ (
634
+ await readWorkflowProtectedFile(
635
+ runRoot,
636
+ file,
637
+ 'workflow-run state',
638
+ WORKFLOW_PROJECT_FILE_MAX_BYTES,
639
+ )
640
+ ).toString('utf8').replace(/^/, ''),
641
+ );
642
+ }
643
+
644
+ async function writeJson(file, value) {
645
+ await writeWorkflowProtectedFile(
646
+ runRoot,
647
+ file,
648
+ 'workflow-run state',
649
+ JSON.stringify(value, null, 2) + '\n',
650
+ WORKFLOW_PROJECT_FILE_MAX_BYTES,
651
+ );
652
+ }
653
+
654
+ function route(protocol) {
655
+ return protocol.nodes.filter((node) => !node.disabled);
656
+ }
657
+
658
+ function findNode(protocol, id) {
659
+ return route(protocol).find((node) => node.id === id || generatedNodeSkillName(protocol, node.id) === id) ?? null;
660
+ }
661
+
662
+ function completedSet(state) {
663
+ return new Set(Array.isArray(state.completedNodes) ? state.completedNodes : []);
664
+ }
665
+
666
+ // 路由判定统一委托共享模块 route-node.mjs 的 resolveNextNode(单一实现——guard 与
667
+ // workflow-state 两侧同语义,含多趟 parallel 回流与串行 pending → execute)。展示层
668
+ // (NEXT/NODE/SKILL 行)保留在本文件(AC-6 展示文案逐字)。无活跃 change → null(完成态)。
669
+ async function nextNode(protocol, state) {
670
+ if (!state.activeChange) return null;
671
+ const id = await resolveNextNode({
672
+ runRoot,
673
+ changeName: state.activeChange,
674
+ protocol,
675
+ completedNodes: Array.isArray(state.completedNodes) ? state.completedNodes : [],
676
+ });
677
+ return id ? findNode(protocol, id) : null;
678
+ }
679
+
680
+ // ---------- 多趟路由共享判定(依赖图校验决策与完成判定谓词决策 · 多趟路由架构决策记录) ----------
681
+
682
+ // <depends_on> 提取(逗号/空白分隔)。DESIGN 0.5.2:与 workflow-state.mjs 各自保留既有正则实现、
683
+ // 不提取到共享解析层(task-parsing/state-schema 冻结为只消费)——两处语义由场景族锚定一致。
684
+ function taskDependsOn(block) {
685
+ const m = String(block ?? '').match(/<depends_on>([\s\S]*?)<\/depends_on>/);
686
+ if (!m || !m[1].trim()) return [];
687
+ return m[1].trim().split(/[,\s]+/).filter(Boolean);
688
+ }
689
+
690
+ // 委托进入谓词(每趟求值):∃ p ∈ tasks:p.parallel ∧ p.status=pending ∧ deps(p) ⊆ doneIds。
691
+ // 返回满足谓词的任务块数组——subagent-execute 出口的「尚有可委托」判定用,
692
+ // 与 workflow-state.mjs determineNode 的路由谓词同语义(镜像同步点)。
693
+ function eligibleParallelBlocks(blocks, doneIds) {
694
+ return blocks.filter((block) => {
695
+ const a = taskOpeningAttrs(block);
696
+ if (!a || !a.parallel || a.status !== 'pending') return false;
697
+ const deps = taskDependsOn(block);
698
+ return deps.every((d) => doneIds.has(d));
699
+ });
700
+ }
701
+
702
+ // 依赖图分析:对全部 <task> 块建依赖图(deps 边),Kahn 拓扑排序判环 + 缺失依赖收集。
703
+ // 返回 { ids, depsById, missing: [{id, dep}], cyclic, cycleIds }(cycleIds = 拓扑排序无解的
704
+ // 任务集合,含被环传递拖累的下游任务)。plan 出口波次校验与 subagent-execute 出口孤儿检测
705
+ // 共用同一实现(单一语义:依赖图无环 + 依赖链可满足)。
706
+ function analyzeDependencyGraph(blocks) {
707
+ const parsed = blocks
708
+ .map((block) => ({ block, attrs: taskOpeningAttrs(block) }))
709
+ .filter((x) => x.attrs && x.attrs.id);
710
+ const ids = new Set(parsed.map((x) => x.attrs.id));
711
+ const depsById = new Map();
712
+ const missing = [];
713
+ for (const x of parsed) {
714
+ const deps = [...new Set(taskDependsOn(x.block))];
715
+ depsById.set(x.attrs.id, deps);
716
+ for (const d of deps) {
717
+ if (!ids.has(d)) missing.push({ id: x.attrs.id, dep: d });
718
+ }
719
+ }
720
+ const indegree = new Map([...ids].map((id) => [id, 0]));
721
+ const dependents = new Map([...ids].map((id) => [id, []]));
722
+ for (const [id, deps] of depsById) {
723
+ for (const d of deps) {
724
+ if (!ids.has(d)) continue;
725
+ indegree.set(id, indegree.get(id) + 1);
726
+ dependents.get(d).push(id);
727
+ }
728
+ }
729
+ let queue = [...ids].filter((id) => indegree.get(id) === 0);
730
+ const sorted = [];
731
+ while (queue.length > 0) {
732
+ const n = queue.shift();
733
+ sorted.push(n);
734
+ for (const m of dependents.get(n)) {
735
+ indegree.set(m, indegree.get(m) - 1);
736
+ if (indegree.get(m) === 0) queue.push(m);
737
+ }
738
+ }
739
+ const cyclic = sorted.length < ids.size;
740
+ const cycleIds = cyclic ? [...ids].filter((id) => !sorted.includes(id)) : [];
741
+ return { ids, depsById, missing, cyclic, cycleIds };
742
+ }
743
+
744
+ function printNext(protocol, node) {
745
+ if (!node) {
746
+ console.log('NEXT: done');
747
+ return;
748
+ }
749
+ console.log('NEXT: auto');
750
+ console.log('NODE: ' + node.id);
751
+ console.log('SKILL: ' + generatedNodeSkillName(protocol, node.id));
752
+ }
753
+
754
+ function evidenceFor(state, id) {
755
+ const value = state.evidence && typeof state.evidence === 'object' ? state.evidence[id] : null;
756
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
757
+ }
758
+
759
+ function missingRequiredSkillChecks(node, evidence) {
760
+ const values = Array.isArray(evidence?.completedChecks) ? evidence.completedChecks : [];
761
+ return (node.requiredSkillCalls ?? [])
762
+ .map((binding) => 'required-skill:' + node.id + '.' + binding.skill)
763
+ .filter((check) => !values.includes(check));
764
+ }
765
+
766
+ function missingAugmentationChecks(node, evidence) {
767
+ const values = Array.isArray(evidence?.completedChecks) ? evidence.completedChecks : [];
768
+ return (node.augmentations ?? [])
769
+ .filter((binding) => binding.enforcement && binding.enforcement !== 'advisory')
770
+ .map((binding) => 'augmentation:' + node.id + '.' + binding.skill)
771
+ .filter((check) => !values.includes(check));
772
+ }
773
+
774
+ function hasEvidenceField(evidence, id) {
775
+ if (Object.prototype.hasOwnProperty.call(evidence, id)) return true;
776
+ const schemaEvidence = evidence.schemaEvidence;
777
+ return !!(
778
+ schemaEvidence &&
779
+ typeof schemaEvidence === 'object' &&
780
+ !Array.isArray(schemaEvidence) &&
781
+ Object.prototype.hasOwnProperty.call(schemaEvidence, id)
782
+ );
783
+ }
784
+
785
+ // 共用证据库 handoffResult 识别——subagent-execute 的委托结果由 workflow-handoff
786
+ // result 写入嵌套 handoffResult({ <taskId>: { result, completedAt } }),非顶层
787
+ // handoff-result 字段;嵌套对象存在且非空(至少一个任务记录)视为该 evidence 已产生
788
+ // (gate 只认存在性,内容严格校验由 W1-D Return Contract 校验负责)。
789
+ function hasNonEmptyHandoffResult(evidence) {
790
+ const handoff = evidence?.handoffResult;
791
+ return !!(
792
+ handoff &&
793
+ typeof handoff === 'object' &&
794
+ !Array.isArray(handoff) &&
795
+ Object.keys(handoff).length > 0
796
+ );
797
+ }
798
+
799
+ function schemaMap(protocol) {
800
+ return new Map((protocol.outputSchemas ?? []).map((schema) => [schema.id, schema]));
801
+ }
802
+
803
+ function missingRequiredSchemaEvidence(protocol, node, evidence) {
804
+ const schemas = schemaMap(protocol);
805
+ const missing = [];
806
+ // schema evidence 缺失但 record 传了 summary → 以 summary 视为产出证据(避免手动构造各字段)
807
+ const hasSummary = typeof evidence?.summary === 'string' && evidence.summary.trim() !== '';
808
+ for (const schemaId of node.outputSchemas ?? []) {
809
+ const schema = schemas.get(schemaId);
810
+ for (const field of schema?.evidence ?? []) {
811
+ if (field.required && !hasEvidenceField(evidence, field.id) && !hasSummary) {
812
+ missing.push(schemaId + '.' + field.id);
813
+ }
814
+ }
815
+ }
816
+ return missing;
817
+ }
818
+
819
+ // 并行文件依赖检测——解析 TASK.md 中本趟可运行的 parallel=pending 任务的 read/write_files 声明,
820
+ // 分两级返回:write∩write(写写绝对冲突,强判)与 read∩write(共享读写嫌疑,弱判——仅对彼此
821
+ // 无显式 depends_on 关联的并行对探测,有显式关联=依赖已声明,跳过→合法拓扑零新增告警)。
822
+ // 路径解析按声明实际内容(换行切分 → 分号二次切分 → trim → 滤空与 HTML 注释),不做扩展名
823
+ // 白名单过滤——txt/log/无扩展名路径同等检出(链式重命名的 .txt 事故面闭合;与既有自动解析
824
+ // 同源实现)。开标签属性解析与 workflow-state 路由共享 taskOpeningAttrs(属性序无关;不读块内文本)。
825
+ async function findParallelWriteConflicts(changeDir) {
826
+ const taskFile = path.join(changeDir, 'TASK.md');
827
+ let text;
828
+ try { text = await fs.readFile(taskFile, 'utf8'); } catch { return { writeConflicts: [], readWarnings: [] }; }
829
+ const allBlocks = extractTaskBlocks(text);
830
+ // 依赖资格收窄:仅统计「本趟可运行」的并行任务——deps ⊆ doneIds;
831
+ // 等待后续趟次的并行任务(依赖未满足)与已交付任务不参与同趟冲突判定,
832
+ // 使 A→B 同写路径的跨趟合法计划不再被首趟误拦(与路由谓词同一口径)。
833
+ const doneIds = new Set(allBlocks
834
+ .map((b) => taskOpeningAttrs(b))
835
+ .filter((a) => a && a.id && a.status === 'done')
836
+ .map((a) => a.id));
837
+ const dependsOnOf = (b) => {
838
+ const m = b.match(/<depends_on>([\s\S]*?)<\/depends_on>/);
839
+ return m ? m[1].trim().split(/[,\s]+/).filter(Boolean) : [];
840
+ };
841
+ const blocks = allBlocks.filter((b) => {
842
+ const a = taskOpeningAttrs(b);
843
+ if (!a || !a.parallel || a.status !== 'pending') return false;
844
+ return dependsOnOf(b).every((d) => doneIds.has(d));
845
+ });
846
+ // 路径解析与既有自动解析同源:剥 HTML 注释 → 换行切分 → 分号二次切分 → trim → 滤空
847
+ // 路径归一化(CodeRabbit 采纳):分隔符统一 '/'、解 '.' 段(`./` / `a/./b`)、`..` 逃出项目根
848
+ // 按越界处理(返回 null 不参与重叠比较)——`src/a.mjs` vs `src/./a.mjs` / `src\a.mjs` 变体不再
849
+ // 绕过写写强判与读写弱判;与委托入口共用同一函数(两侧同语义)。
850
+ const normalizeTaskPath = (raw) => {
851
+ const p = String(raw).trim();
852
+ if (p === '') return null;
853
+ const segments = p.replace(/\\/g, '/').split('/').filter((s) => s !== '' && s !== '.');
854
+ const out = [];
855
+ for (const seg of segments) {
856
+ if (seg === '..') {
857
+ if (out.length === 0) return null; // 逃出项目根 → 越界(不参与比较)
858
+ out.pop();
859
+ } else {
860
+ out.push(seg);
861
+ }
862
+ }
863
+ return out.join('/');
864
+ };
865
+ const parsePaths = (matchText) => String(matchText ?? '')
866
+ .replace(/<!--[\s\S]*?-->/g, '')
867
+ .trim().split(/\s*\n\s*/).map((l) => l.trim()).filter(Boolean)
868
+ .flatMap((l) => l.split(';')).map((l) => l.trim()).filter(Boolean)
869
+ .map(normalizeTaskPath)
870
+ .filter((p) => p !== null && p !== '');
871
+ const perTask = [];
872
+ for (const b of blocks) {
873
+ const a = taskOpeningAttrs(b);
874
+ if (!a || !a.id) continue;
875
+ const wf = b.match(/<write_files>([\s\S]*?)<\/write_files>/);
876
+ const rf = b.match(/<read_files>([\s\S]*?)<\/read_files>/);
877
+ if (!wf && !rf) continue;
878
+ perTask.push({
879
+ id: a.id,
880
+ deps: new Set(dependsOnOf(b)),
881
+ writes: new Set(parsePaths(wf && wf[1])),
882
+ reads: new Set(parsePaths(rf && rf[1])),
883
+ });
884
+ }
885
+ const writeConflicts = [];
886
+ const readWarnings = [];
887
+ for (let i = 0; i < perTask.length; i++) {
888
+ for (let j = i + 1; j < perTask.length; j++) {
889
+ const overlap = [...perTask[i].writes].filter((f) => perTask[j].writes.has(f));
890
+ if (overlap.length) writeConflicts.push({ a: perTask[i].id, b: perTask[j].id, files: overlap });
891
+ // 读写弱判触发面:仅无显式 depends_on 关联的并行对(有显式关联=依赖已声明,跳过)
892
+ const associated = perTask[i].deps.has(perTask[j].id) || perTask[j].deps.has(perTask[i].id);
893
+ if (associated) continue;
894
+ const readOverlap = [...perTask[i].reads].filter((f) => perTask[j].writes.has(f));
895
+ if (readOverlap.length) readWarnings.push({ a: perTask[i].id, b: perTask[j].id, files: readOverlap });
896
+ const readOverlap2 = [...perTask[j].reads].filter((f) => perTask[i].writes.has(f));
897
+ if (readOverlap2.length) readWarnings.push({ a: perTask[j].id, b: perTask[i].id, files: readOverlap2 });
898
+ }
899
+ }
900
+ return { writeConflicts, readWarnings };
901
+ }
902
+
903
+ function escapeRegExp(value) {
904
+ return String(value).replace(/[|\\{}()[\]^$+?.]/gu, '\\$&');
905
+ }
906
+
907
+ function patternToRegExp(pattern) {
908
+ return new RegExp('^' + String(pattern).split('*').map(escapeRegExp).join('.*') + '$', 'u');
909
+ }
910
+
911
+ async function pathPatternExists(root, relativePattern) {
912
+ const parts = workflowRelativeSegments(relativePattern, 'artifact path', true);
913
+ async function walk(current, index) {
914
+ const inspection = await inspectWorkflowProtectedPath(
915
+ runRoot,
916
+ current,
917
+ 'workflow artifact path',
918
+ index >= parts.length ? 'any' : 'directory',
919
+ );
920
+ if (!inspection.exists) return false;
921
+ if (index >= parts.length) {
922
+ return true;
923
+ }
924
+ const part = parts[index];
925
+ if (!part.includes('*')) {
926
+ return walk(path.join(current, part), index + 1);
927
+ }
928
+ let entries;
929
+ try {
930
+ entries = await fs.readdir(current, { withFileTypes: true });
931
+ } catch {
932
+ return false;
933
+ }
934
+ const matcher = patternToRegExp(part);
935
+ for (const entry of entries) {
936
+ if (entry.isSymbolicLink()) {
937
+ throw new Error(
938
+ 'workflow artifact path crosses a symbolic link or junction at ' +
939
+ path.join(current, entry.name),
940
+ );
941
+ }
942
+ if (matcher.test(entry.name) && (await walk(path.join(current, entry.name), index + 1))) {
943
+ return true;
944
+ }
945
+ }
946
+ return false;
947
+ }
948
+ return walk(root, 0);
949
+ }
950
+
951
+ // 产物根解析:'project'/缺省 → runRoot;'specs-root' → runRoot/.specs。
952
+ // classic/native 等 pathBase 依赖项目配置文件,已随 Comet 感知层剥离——不再读取任何项目配置,
953
+ // 遇到即显式报错(fail-fast,与 route-node.mjs 的状态机推导侧同语义),不静默兜底。
954
+ async function workflowArtifactRoot(pathBase) {
955
+ if (pathBase === undefined || pathBase === 'project') {
956
+ await inspectWorkflowProtectedPath(runRoot, runRoot, 'workflow path base', 'directory');
957
+ return runRoot;
958
+ }
959
+ if (pathBase === 'specs-root') {
960
+ return path.join(runRoot, '.specs');
961
+ }
962
+ throw new Error('产物根 pathBase "' + pathBase + '" 不再支持——请改用 specs-root/project + 完整路径(如 project + openspec/changes/xxx.md)');
963
+ }
964
+
965
+ async function missingRequiredArtifacts(protocol, node, change) {
966
+ const schemas = schemaMap(protocol);
967
+ const missing = [];
968
+ for (const schemaId of node.outputSchemas ?? []) {
969
+ const schema = schemas.get(schemaId);
970
+ for (const artifact of schema?.artifacts ?? []) {
971
+ if (!artifact.required) continue;
972
+ const exists = (
973
+ await Promise.all(
974
+ (artifact.paths ?? []).map(async (artifactPath) => {
975
+ // 替换 <change-id> 占位符为实际 change(如 name-format-unify)
976
+ const resolvedPath = change ? artifactPath.replaceAll('<change-id>', change) : artifactPath;
977
+ return pathPatternExists(await workflowArtifactRoot(artifact.pathBase), resolvedPath);
978
+ }),
979
+ )
980
+ ).some(Boolean);
981
+ if (!exists) missing.push(schemaId + '.' + artifact.id);
982
+ }
983
+ }
984
+ return missing;
985
+ }
986
+
987
+ async function fileExists(file) {
988
+ try { await fs.access(file); return true; } catch { return false; }
989
+ }
990
+
991
+ // W1-B: 校验 change 目录下每份 *-SUMMARY.md 含 SUMMARY 模板的三个必填段
992
+ // 用正则(大小写不敏感 + 变体兼容)——避免现有 SUMMARY 格式漂移导致误 BLOCKED
993
+ async function verifySummaries(changeDir) {
994
+ const files = (await fs.readdir(changeDir).catch(() => [])).filter(f => f.endsWith('-SUMMARY.md'));
995
+ const violations = [];
996
+ for (const f of files) {
997
+ const content = await fs.readFile(path.join(changeDir, f), 'utf8');
998
+ for (const section of SUMMARY_REQUIRED_SECTIONS) {
999
+ if (!section.regex.test(content)) violations.push(`${f} 缺 ${section.label}`);
1000
+ }
1001
+ }
1002
+ return violations;
1003
+ }
1004
+
1005
+ // W1-C 过渡规则: 历史归档 change 不强制真实跑验证命令(判断 .specs/archive/ 目录)
1006
+ async function isArchivedChange(changeName) {
1007
+ if (!changeName) return false;
1008
+ const archiveRoot = path.join(runRoot, '.specs', 'archive');
1009
+ if (await fileExists(path.join(archiveRoot, changeName))) return true;
1010
+ const entries = await fs.readdir(archiveRoot).catch(() => []);
1011
+ return entries.some(e => e === changeName || e.endsWith('-' + changeName));
1012
+ }
1013
+
1014
+ // 声明标记目录解析——活动路径 .specs/<change-id>/.skill-loads/ 优先;归档路径兜底
1015
+ // (archive 节点「先移目录后 record/exit」顺序下 change 目录已在 .specs/archive/<前缀>-<change-id>/,
1016
+ // 标记只随目录移动——只查活动路径会把「标记存在」误判成「机制未激活」)。归档扫描匹配后缀
1017
+ // -<change-id>(前缀可含日期等,与协议 flowkit.archive.v1 的 archive/*-<change-id> 同构)。
1018
+ // 两者皆无 → null(声明机制从未激活,调用方按旧 change 兼容跳过)。
1019
+ async function findSkillLoadsDir(root, changeName) {
1020
+ const activeDir = path.join(root, '.specs', changeName, '.skill-loads');
1021
+ if (await fileExists(activeDir)) {
1022
+ return { dir: activeDir, display: '.specs/' + changeName + '/.skill-loads/' };
1023
+ }
1024
+ const archiveRoot = path.join(root, '.specs', 'archive');
1025
+ const entries = await fs.readdir(archiveRoot).catch(() => []);
1026
+ for (const entry of entries) {
1027
+ if (!entry.endsWith('-' + changeName)) continue;
1028
+ const candidate = path.join(archiveRoot, entry, '.skill-loads');
1029
+ if (await fileExists(candidate)) {
1030
+ return { dir: candidate, display: '.specs/archive/' + entry + '/.skill-loads/' };
1031
+ }
1032
+ }
1033
+ return null;
1034
+ }
1035
+
1036
+ // C2: 段名校验从模板自动派生——读 <runRoot>/flow-kit/templates/{CHANGE,REQUIREMENT,DESIGN}.md
1037
+ // 提取全部 ^## 段名,正则化生成宽松匹配模式;模板目录/文件缺失时 fallback 内置段名
1038
+ let templateSectionPatternsCacheRoot = null;
1039
+ let templateSectionPatternsCache = null;
1040
+
1041
+ const TEMPLATE_FALLBACK_SECTION_PATTERNS = {
1042
+ changeWhy: /^##\s*Why\b/im,
1043
+ requirementUserStory: /^##\s*用户故事/im,
1044
+ requirementAcceptance: /##\s*(验收准则|验收标准|AC|Acceptance Criteria)/i,
1045
+ designDecisionList: /^##\s*\d*\.?\s*决策清单/m,
1046
+ };
1047
+
1048
+ // 模板段名 → 宽松匹配正则:编号前缀(1. / 0.5)可选 + 段名主体字面匹配 + 尾部括号内容(如 (AC))可选
1049
+ function templateSectionPattern(rawName) {
1050
+ const name = String(rawName).trim();
1051
+ const body = name
1052
+ .replace(/[((][^))\n]*[))]\s*$/u, '') // 去尾部括号内容:Why(为什么做)→ Why
1053
+ .replace(/^\d+(?:\.\d+)?\.?\s*/u, '') // 去编号前缀:1. 决策清单 → 决策清单
1054
+ .trim();
1055
+ const escaped = escapeRegExp(body || name);
1056
+ return new RegExp(
1057
+ '^##\\s*(?:\\d+(?:\\.\\d+)?\\.?\\s*)?' + escaped + '\\s*(?:[((][^\\n))]*[))])?\\s*$',
1058
+ 'im',
1059
+ );
1060
+ }
1061
+
1062
+ // 读取模板全部段名生成模式列表(模块级缓存,避免每次 exit 重复读文件);pick 按关键词选段,找不到 → fallback
1063
+ async function templateSectionPatterns() {
1064
+ if (templateSectionPatternsCacheRoot === runRoot && templateSectionPatternsCache) {
1065
+ return templateSectionPatternsCache;
1066
+ }
1067
+ const templateDir = path.join(runRoot, 'flow-kit', 'templates');
1068
+ const result = { change: [], requirement: [], design: [] };
1069
+ for (const [key, fileName] of Object.entries({
1070
+ change: 'CHANGE.md',
1071
+ requirement: 'REQUIREMENT.md',
1072
+ design: 'DESIGN.md',
1073
+ })) {
1074
+ const templateFile = path.join(templateDir, fileName);
1075
+ if (await fileExists(templateFile)) {
1076
+ try {
1077
+ const text = await fs.readFile(templateFile, 'utf8');
1078
+ for (const match of text.matchAll(/^##\s+(.+)$/gmu)) {
1079
+ const sectionName = match[1].trim();
1080
+ result[key].push({ name: sectionName, regex: templateSectionPattern(sectionName) });
1081
+ }
1082
+ } catch {}
1083
+ }
1084
+ }
1085
+ result.pick = (key, keywords, fallback) => {
1086
+ for (const section of result[key] ?? []) {
1087
+ if (keywords.some((keyword) => section.name.includes(keyword))) return section.regex;
1088
+ }
1089
+ return fallback;
1090
+ };
1091
+ templateSectionPatternsCache = result;
1092
+ templateSectionPatternsCacheRoot = runRoot;
1093
+ return result;
1094
+ }
1095
+
1096
+ // ===== 模板保真(M1/M2/M3·设计语义 / AC-7~AC-9)=====
1097
+ // 段名归一化:去标题标记 + 去尾部括号(如 Why(为什么做)→ Why)+ 去编号前缀(如 1. 决策清单 → 决策清单)
1098
+ // + 去首尾空白 + ASCII 小写(中文无大小写;英文侧大小写不敏感)——沿用 C2 宽容匹配风格
1099
+ function normalizeTemplateHeading(raw) {
1100
+ return String(raw)
1101
+ .replace(/\r/g, '')
1102
+ .replace(/^#{1,6}\s*/, '')
1103
+ .replace(/[((][^))\n]*[))]\s*$/u, '')
1104
+ .replace(/^\d+(?:\.\d+)?\.?\s*/u, '')
1105
+ .trim()
1106
+ .toLowerCase();
1107
+ }
1108
+
1109
+ // 提取文档全部 ^## 段(归一化后),供段序/缺段校验
1110
+ function documentSectionHeadings(content) {
1111
+ const out = [];
1112
+ for (const m of String(content).matchAll(/^##\s+(.+)$/gmu)) {
1113
+ out.push({ raw: m[1].trim(), norm: normalizeTemplateHeading(m[1]) });
1114
+ }
1115
+ return out;
1116
+ }
1117
+
1118
+ // 模板段序骨架:段名从 flow-kit/templates 派生(与 C2 同源,模板缺失 fallback 内置骨架)
1119
+ const TEMPLATE_FIDELITY_FALLBACK_SKELETON = {
1120
+ change: ['why', 'what', '视觉调性', '影响面', '范围排除', '验收线', '风险与未知'],
1121
+ requirement: ['用户故事', '验收准则', '范围切分', '非功能性需求', '依赖与假设'],
1122
+ design: ['技术栈选定', '既有架构对齐', '决策清单', '数据流', '关键状态机', 'adr 索引', '风险', '不在范围', '架构沉淀建议'],
1123
+ };
1124
+
1125
+ async function templateSkeleton(key) {
1126
+ const tpl = await templateSectionPatterns(); // 复用 C2 模板缓存(runRoot 内模板)
1127
+ const src = tpl[key] ?? [];
1128
+ if (src.length > 0) return src.map((s) => normalizeTemplateHeading(s.name));
1129
+ return TEMPLATE_FIDELITY_FALLBACK_SKELETON[key] ?? [];
1130
+ }
1131
+
1132
+ // 段序校核(宽容):模板骨架段里「实际出现」的段须按模板先后出现;返回乱序描述(无则 null)
1133
+ function templateOrderViolation(skeletons, headings) {
1134
+ let last = -1;
1135
+ for (const h of headings) {
1136
+ const idx = skeletons.indexOf(h.norm);
1137
+ if (idx === -1) continue;
1138
+ if (idx < last) return h.raw;
1139
+ last = idx;
1140
+ }
1141
+ return null;
1142
+ }
1143
+
1144
+ // M1: SUMMARY 模板保真——标题 # SUMMARY: + 首部 4 字段 + 段序(含 flow-comet 增量 ## 自检方法)。
1145
+ // 返回各维度缺口;调用方按新 BLOCK / 旧 WARN 渐进处置
1146
+ const SUMMARY_TEMPLATE_HEADER_FIELDS = [
1147
+ { label: 'Change ID', re: /\*\*\s*Change\s+ID\s*\*\*/i },
1148
+ { label: 'Task ID', re: /\*\*\s*Task\s+ID\s*\*\*/i },
1149
+ { label: '完成时间', re: /\*\*\s*完成时间\s*\*\*/ },
1150
+ { label: 'AI 角色', re: /\*\*\s*AI\s*角色\s*\*\*/ },
1151
+ ];
1152
+ // 段序(含 flow-comet 增量段;越界检查在模板中位于 6 维自查 与 自检方法 之间)
1153
+ const SUMMARY_ORDERED_SECTIONS = ['做了什么', '改动文件', 'verify 输出', '6 维自查', '越界检查', '自检方法']
1154
+ .map(normalizeTemplateHeading);
1155
+
1156
+ function summaryTemplateFidelity(content) {
1157
+ const text = String(content).replace(/\uFEFF/g, '');
1158
+ const firstRealLine = (text.split('\n').find((l) => l.trim().length > 0) || '').trim();
1159
+ const titleMissing = !/^#\s*summary\s*:/i.test(firstRealLine);
1160
+ const headerRegion = text.split(/\n##\s/)[0];
1161
+ const headerMissing = SUMMARY_TEMPLATE_HEADER_FIELDS
1162
+ .filter((f) => !f.re.test(headerRegion))
1163
+ .map((f) => f.label);
1164
+ const headings = documentSectionHeadings(text);
1165
+ const seen = new Set();
1166
+ let last = -1;
1167
+ let orderIssue = null;
1168
+ for (const h of headings) {
1169
+ const idx = SUMMARY_ORDERED_SECTIONS.indexOf(normalizeTemplateHeading(h.raw));
1170
+ if (idx === -1) continue;
1171
+ if (idx < last) { orderIssue = h.raw; break; }
1172
+ last = idx;
1173
+ seen.add(idx);
1174
+ }
1175
+ const missingSections = [];
1176
+ for (let i = 0; i < SUMMARY_ORDERED_SECTIONS.length; i++) {
1177
+ if (!seen.has(i)) missingSections.push(SUMMARY_ORDERED_SECTIONS[i]);
1178
+ }
1179
+ return { titleMissing, headerMissing, orderIssue, missingSections };
1180
+ }
1181
+
1182
+ // C3: TASK.md 任务集签名——提取全部 <task> 块,剥离开标签上的标记类属性(仅保留 id/parallel),排序防顺序漂移,拼接后 sha256
1183
+ // 行尾规范化——Windows 下 bash heredoc 写 LF、python 写 CRLF(os.linesep),跨工具编辑
1184
+ // 导致"任务集逻辑未变但字节变"的误报 BLOCK;签名前统一 CRLF → LF(仅归一化行尾,不改变内容语义)
1185
+ // 标记类属性白名单——子代理标记 task done 会在开标签追加 completed_at/started_at/finished_at/
1186
+ // assigned_to/updated_at 等属性(纯状态标记),仅剥离 status 仍误报 BLOCK;改为开标签只保留
1187
+ // 影响路由语义的 id/parallel,其余属性一律剥离(含未来新增标记属性,无需再改);
1188
+ // 任务内容(name/action/write_files/verify/depends_on)保持签名敏感
1189
+ function taskSetSignature(taskContent) {
1190
+ const normalized = String(taskContent).replace(/\r\n/g, '\n');
1191
+ const blocks = (normalized.match(/<task[\s\S]*?<\/task>/g) || [])
1192
+ .map((block) =>
1193
+ block.replace(/<task[^>]*>/, (open) =>
1194
+ open.replace(/\s+[a-zA-Z_][\w-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'))?/g, (attr) =>
1195
+ /^\s*(?:id|parallel)(?=[\s=>])/.test(attr) ? attr : ''
1196
+ )
1197
+ )
1198
+ )
1199
+ .sort();
1200
+ return createHash('sha256').update(blocks.join('\n'), 'utf8').digest('hex');
1201
+ }
1202
+
1203
+ // WARN 计数——entry/exit 成功路径末尾输出汇总行(可观测性;追加不改变既有输出)
1204
+ let __warnCount = 0;
1205
+ const __origError = console.error;
1206
+
1207
+ async function main() {
1208
+ // 包装 console.error 统计 WARN 输出(转发原实现,行为不变)
1209
+ console.error = (...args) => {
1210
+ if (/WARN/.test(args.join(' '))) __warnCount += 1;
1211
+ __origError(...args);
1212
+ };
1213
+ // 受保护读取 + fail-closed schema 校验(读失败/校验失败沿用 throw → main().catch 统一处理)
1214
+ const protocol = await readProtocolFile(runRoot, protocolPath);
1215
+ validateProtocolSchema(protocol);
1216
+ if (command === 'verify') {
1217
+ console.log('workflow-guard-ok');
1218
+ return;
1219
+ }
1220
+ if (command !== 'entry' && command !== 'exit') throw new Error('Unknown command: ' + command);
1221
+ if (!nodeId) throw new Error(command + ' requires a Node id.');
1222
+ const node = findNode(protocol, nodeId);
1223
+ if (!node) throw new Error('Unknown workflow Node: ' + nodeId);
1224
+ const file = await statePath(protocol);
1225
+ const state = await readStateJson(file);
1226
+ state.completedNodes = Array.isArray(state.completedNodes) ? state.completedNodes : [];
1227
+ state.evidence = state.evidence && typeof state.evidence === 'object' ? state.evidence : {};
1228
+ if (command === 'entry') {
1229
+ const current = state.currentNode ?? (await nextNode(protocol, state))?.id ?? null;
1230
+ if (current !== node.id && !state.completedNodes.includes(node.id)) {
1231
+ console.error('BLOCKED: current Node is ' + String(current) + ', cannot enter ' + node.id + '.');
1232
+ process.exit(1);
1233
+ }
1234
+ // E2: entry archive 分支校验(新模式 branchMode=true)——归档必须在 change/<activeChange> 分支上进行
1235
+ // 旧模式(无 branchMode 字段 / 非 git 仓库 / git 不可用)跳过,向后兼容
1236
+ if (node.id === 'archive' && state.branchMode === true && state.activeChange) {
1237
+ const { execFileSync } = await import('child_process');
1238
+ try {
1239
+ const branch = String(execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' })).trim();
1240
+ // 归档分支前缀用 state.branchPrefix(缺省 'change/',适配仓库自身规范)
1241
+ const archivePrefix = state.branchPrefix ?? 'change/';
1242
+ if (branch !== archivePrefix + state.activeChange) {
1243
+ console.error('BLOCKED: 归档必须在 ' + archivePrefix + state.activeChange + ' 分支上进行(当前: ' + branch + ')');
1244
+ process.exit(1);
1245
+ }
1246
+ } catch {
1247
+ // git 不可用 → 跳过分支校验(旧模式兼容)
1248
+ }
1249
+ }
1250
+ // 并行冲突检测——subagent-execute 委托前校验 wave 内 parallel 任务 write_files 无交集
1251
+ // (第二道写写锚:只取强判组,行为与消息保持既有语义不变)
1252
+ if (node.id === 'subagent-execute' && state.activeChange) {
1253
+ const { writeConflicts } = await findParallelWriteConflicts(path.join(runRoot, '.specs', state.activeChange));
1254
+ if (writeConflicts.length > 0) {
1255
+ console.error('BLOCKED: parallel tasks write_files 冲突: ' + writeConflicts.map((c) => `${c.a}×${c.b}(${c.files.join(',')})`).join('; '));
1256
+ process.exit(1);
1257
+ }
1258
+ }
1259
+ // C4: 委托前工件 commit 检查——worktree isolation 子代理看不到未提交工件(WARN 不 BLOCKED)
1260
+ if ((node.id === 'execute' || node.id === 'subagent-execute') && state.activeChange) {
1261
+ const { execFileSync } = await import('child_process');
1262
+ try {
1263
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: runRoot, stdio: 'pipe' });
1264
+ const statusOut = execFileSync(
1265
+ 'git',
1266
+ ['status', '--porcelain', '--', path.posix.join('.specs', state.activeChange) + '/'],
1267
+ { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' },
1268
+ );
1269
+ if (String(statusOut).trim() !== '') {
1270
+ console.error('WORKTREE WARN: .specs/' + state.activeChange + '/ 有未提交工件,worktree isolation 子代理将看不到它们——建议先 commit 或 prompt 内联上下文');
1271
+ }
1272
+ } catch (err) {
1273
+ // 检测失败可见化——非 git 仓库/路径不可查时提示 SKIP 原因(防静默失效)
1274
+ console.error('C4-CHECK SKIP: ' + (err && err.message ? String(err.message).split('\n')[0] : String(err)));
1275
+ }
1276
+ }
1277
+ // C7: PROGRESS.md 存在警告(清窗恢复产物,R1.6 反重复)
1278
+ if (node.id === 'execute' && state.activeChange) {
1279
+ if (await fileExists(path.join(runRoot, '.specs', state.activeChange, 'PROGRESS.md'))) {
1280
+ console.error('WARNING: PROGRESS.md 存在(清窗恢复产物),先读"已排除方案"段(R1.6 反重复)');
1281
+ }
1282
+ }
1283
+ // C3: enter execute / subagent-execute 记录 TASK.md 任务集签名(exit 时比对,防 execute 期间增删任务/改 action/改边界)
1284
+ if ((node.id === 'execute' || node.id === 'subagent-execute') && state.activeChange) {
1285
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
1286
+ if (await fileExists(taskFile)) {
1287
+ try {
1288
+ state.taskHash = taskSetSignature(await fs.readFile(taskFile, 'utf8'));
1289
+ const bad = validateStateFields(state);
1290
+ if (bad.length) { console.error('BLOCKED: state 字段类型非法: ' + bad[0]); process.exit(1); }
1291
+ await writeJson(file, state);
1292
+ } catch {}
1293
+ }
1294
+ }
1295
+ // 协调者禁令:execute / subagent-execute 阶段主会话只能委托,禁止直接写源码
1296
+ // 例外:direct 模式 execute 是主代理直写(逃生口),不输出协调者禁令
1297
+ const entryExecutionMode = state.executionMode ?? 'subagent';
1298
+ if (node.id === 'execute' || node.id === 'subagent-execute') {
1299
+ if (!(entryExecutionMode === 'direct' && node.id === 'execute')) {
1300
+ console.log('COORDINATOR: 你是协调者,不是执行者。禁止在主会话直接修改源码;只能通过 Agent 工具 worktree isolation 委托子代理;子代理回传后仅更新 TASK.md / SUMMARY / handoff evidence。');
1301
+ }
1302
+ }
1303
+ // M1: enter 证据——entry 记录节点进入标记(enteredNodes),exit 检测未 entry(防跳过 entry 无痕)
1304
+ state.enteredNodes = Array.isArray(state.enteredNodes) ? state.enteredNodes : [];
1305
+ if (!state.enteredNodes.includes(node.id)) {
1306
+ state.enteredNodes.push(node.id);
1307
+ const bad = validateStateFields(state);
1308
+ if (bad.length) { console.error('BLOCKED: state 字段类型非法: ' + bad[0]); process.exit(1); }
1309
+ await writeJson(file, state);
1310
+ // G13: 进入已记录提示(执行者可知 entry 有副作用——进入证据写入)
1311
+ console.log('ENTER RECORDED: ' + node.id + ' 进入已记录(enteredNodes)');
1312
+ }
1313
+ // 输出点名(机器点名节点技能):进入节点时机器点名该节点实现技能必须经 Skill 工具加载——
1314
+ // skill 名取节点实现 skill(内置协议 = flow-comet-plan 等,与 SKILL: 行一致)
1315
+ const entryImplSkill = node.implementation && typeof node.implementation === 'object' && node.implementation.skill
1316
+ ? node.implementation.skill
1317
+ : null;
1318
+ if (entryImplSkill) {
1319
+ console.log('LOAD SKILL: ' + entryImplSkill + '(用 Skill 工具,禁止跳过)');
1320
+ }
1321
+ console.log('ENTRY OK: ' + node.id);
1322
+ return;
1323
+ }
1324
+ const evidence = evidenceFor(state, node.id);
1325
+ if (!evidence) {
1326
+ console.error('BLOCKED: missing evidence for Node ' + node.id + '.');
1327
+ console.error('恢复: 该节点已完成但缺证据记录 → 用 workflow-state.mjs record ' + node.id + ' \'{"summary":"<完成摘要>"}\' 补证据后重试;状态漂移 → advance/select;禁止手改 state 机器字段');
1328
+ process.exit(1);
1329
+ }
1330
+ // W1-A: 转移前置约束——currentNode 必须等于被 exit 的节点(防跳阶段)
1331
+ // M2(2026-08-29 容错落地 · L-061 修复候选):currentNode 已漂移到文件推导位置
1332
+ // (resolveNextNode(completedNodes) === currentNode,如 execute 证据/产物齐后路由已指向
1333
+ // review)且本节点 evidence 齐 + 产物齐(执行者确认本节点实际已完成)→ 容错放行 exit
1334
+ // (漂移/提前校正态可补欠账;BLOCK 消息/提示标注「漂移态可用容错 exit」——不再只有不可行的
1335
+ // advance/select 指引)。漂移但 evidence/产物不齐 → 仍严格 BLOCK(容错不放开未完成)。
1336
+ const driftedNodeEvidence = evidenceFor(state, node.id);
1337
+ if (state.currentNode !== node.id) {
1338
+ let tolerable = false;
1339
+ if (driftedNodeEvidence) {
1340
+ const derivedNext = await nextNode(protocol, state);
1341
+ const missingDriftArtifacts = await missingRequiredArtifacts(protocol, node, state.activeChange);
1342
+ const missingDriftSchemaEvidence = missingRequiredSchemaEvidence(protocol, node, driftedNodeEvidence);
1343
+ tolerable = !!(
1344
+ derivedNext && derivedNext.id === state.currentNode
1345
+ && missingDriftArtifacts.length === 0
1346
+ && missingDriftSchemaEvidence.length === 0
1347
+ );
1348
+ }
1349
+ if (tolerable) {
1350
+ console.log('NOTE: 容错放行——currentNode 已为文件推导下一节点且本节点证据/产物齐(执行者确认本节点实际已完成),exit ' + node.id + ' --apply 补齐欠账(漂移容忍路径)');
1351
+ }
1352
+ if (!tolerable) {
1353
+ console.error('BLOCKED: currentNode is ' + String(state.currentNode) + ', cannot exit ' + node.id + '.');
1354
+ console.error('恢复: 若节点状态漂移/卡死 → 用 workflow-state.mjs advance(强制推进,确认节点实际已完成后再用)或 select(切换 change);禁止手改 state 机器字段');
1355
+ console.error('提示: 若 currentNode 已漂移到文件推导位置且本节点证据/产物齐(执行者确认本节点实际已完成)→ 可用容错 exit ' + node.id + ' --apply 补齐欠账(漂移容忍路径,不再只有不可行的 advance/select 指引);漂移但证据/产物不齐则不适用');
1356
+ process.exit(1);
1357
+ }
1358
+ }
1359
+ // M1/R2: enter 证据检测——未 entry 直接 exit:新 change(init 标记)强制 BLOCKED,旧 change 渐进 WARN
1360
+ // 跳过 entry 会漏掉进入检查(协调者禁令/C4 WORKTREE/PROGRESS/签名记录)
1361
+ if (isNewChange(state)) {
1362
+ if (!Array.isArray(state.enteredNodes) || !state.enteredNodes.includes(node.id)) {
1363
+ console.error('BLOCKED: 节点 ' + node.id + ' 未执行 entry 直接 exit——新 change 强制先 entry(进入检查/协调者禁令/签名记录)');
1364
+ console.error('恢复: 先运行 workflow-guard.mjs entry ' + node.id + ' 再重试 exit;状态漂移 → advance/select');
1365
+ process.exit(1);
1366
+ }
1367
+ } else if (Array.isArray(state.enteredNodes) && !state.enteredNodes.includes(node.id)) {
1368
+ console.error('ENTER WARN: 节点 ' + node.id + ' 未执行 entry 直接 exit——entry 的进入检查(协调者禁令/C4 委托前检查/签名记录)被跳过,请先 entry 该节点再 exit(旧 change 渐进不阻断)');
1369
+ }
1370
+ // E2: exit archive 分支合并检查(WARN 不 BLOCK)——分支未合并到 main 允许"归档先行、合并后补"
1371
+ if (node.id === 'archive' && state.branchMode === true && state.activeChange) {
1372
+ const { execFileSync } = await import('child_process');
1373
+ try {
1374
+ const branch = String(execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' })).trim();
1375
+ const mergedOut = String(execFileSync('git', ['branch', '--merged', 'main'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' }));
1376
+ const mergedBranches = mergedOut.split('\n').map(l => l.trim().replace(/^\*\s*/, ''));
1377
+ if (!mergedBranches.includes(branch)) {
1378
+ console.error('WARN: 分支 change/' + state.activeChange + ' 未合并到 main——归档后请完成 merge + 删除分支');
1379
+ }
1380
+ } catch {
1381
+ // git 不可用 / main 不存在 → 跳过合并检查
1382
+ }
1383
+ }
1384
+ // 特化校验按节点 id 绑定(ADR-002):内置节点 id 触发 flow-kit 契约校验;自定义协议节点不误触发(通用层防线对其生效)
1385
+ // E7: 追加位置结构检测(全部 WARN 不 BLOCK)——防 CONTEXT/LESSONS/STATE/CHANGELOG 文件尾追加破坏插入位置纪律
1386
+ if (node.id === 'open' && state.activeChange) {
1387
+ const contextFile = path.join(runRoot, '.specs', 'CONTEXT.md');
1388
+ try {
1389
+ const content = await fs.readFile(contextFile, 'utf8');
1390
+ const m = content.match(/^## (术语|已锁决策|决策|术语表)[((][^\n]*(?:追加|update)[^\n]*$/im);
1391
+ if (m) {
1392
+ if (isNewChange(state)) {
1393
+ console.error('BLOCKED: CONTEXT.md 检测到孤立追加段(新 change 强制插入既有结构段);恢复: 把内容移入术语表/已锁决策段');
1394
+ process.exit(1);
1395
+ }
1396
+ console.error('WARN: CONTEXT.md 检测到孤立追加段(术语/决策应插入既有结构段):' + m[0].replace(/^##\s*/, '').trim());
1397
+ }
1398
+ } catch {}
1399
+ }
1400
+ if ((node.id === 'verify' || node.id === 'archive') && state.activeChange) {
1401
+ const lessonsFile = path.join(runRoot, '.specs', 'LESSONS.md');
1402
+ try {
1403
+ const content = await fs.readFile(lessonsFile, 'utf8');
1404
+ // 条目区锚点兼容:## 条目区(模板)/ ## 活跃条目 + ## 已解决条目(实际项目结构)——取最早条目段
1405
+ const zoneIndex = (() => {
1406
+ const hits = ['条目区', '活跃条目', '已解决条目']
1407
+ .map(s => content.search(new RegExp('^##\\s*' + s + '\\s*$', 'm')))
1408
+ .filter(i => i !== -1);
1409
+ return hits.length ? Math.min(...hits) : -1;
1410
+ })();
1411
+ const headings = [...content.matchAll(/^###\s*L-(\d+)/gm)];
1412
+ if (zoneIndex !== -1) {
1413
+ const outside = headings.some(h => h.index < zoneIndex);
1414
+ if (outside) {
1415
+ if (isNewChange(state)) {
1416
+ console.error('BLOCKED: LESSONS.md 有条目在条目区外(新 change 强制条目插入条目区);恢复: 移入条目区');
1417
+ process.exit(1);
1418
+ }
1419
+ // 诊断信息附带 zoneIndex/条目位置——偶发 WARN 排查时可直接定位(文件时序/编码差异兜底)
1420
+ console.error('WARN: LESSONS.md 有条目在条目区外(zoneIndex=' + zoneIndex + ', 条目数=' + headings.length + ', 区外条目: ' + headings.filter(h => h.index < zoneIndex).map(h => 'L-' + h[1]).join(',') + ')');
1421
+ }
1422
+ }
1423
+ const nums = headings.map(h => parseInt(h[1], 10));
1424
+ // 分段检测:按 ## 标题分段,仅同段内比较编号递增(多段 LESSONS 如「活跃条目/已解决条目」编号体系可独立)
1425
+ const sectionStarts = [...content.matchAll(/^##\s+.*$/gm)].map(m => m.index);
1426
+ for (let i = 1; i < nums.length; i++) {
1427
+ const sameSection = !sectionStarts.some(s => s > headings[i - 1].index && s < headings[i].index);
1428
+ if (sameSection && nums[i] <= nums[i - 1]) {
1429
+ if (isNewChange(state)) {
1430
+ console.error('BLOCKED: LESSONS.md 条目编号乱序(新 change 强制按编号插入条目区);恢复: 按 L-NNN 顺序插入');
1431
+ process.exit(1);
1432
+ }
1433
+ console.error('WARN: LESSONS.md 条目编号乱序(L-' + String(nums[i]).padStart(3, '0') + ' 应按序插入条目区)');
1434
+ break;
1435
+ }
1436
+ }
1437
+ } catch {}
1438
+ }
1439
+ if (node.id === 'archive') {
1440
+ const stateMd = path.join(runRoot, 'STATE.md');
1441
+ try {
1442
+ const content = await fs.readFile(stateMd, 'utf8');
1443
+ const dates = [...content.matchAll(/^- `?\[(\d{4}-\d{2}-\d{2})\]/gm)].map(m => m[1]);
1444
+ for (let i = 1; i < dates.length; i++) {
1445
+ if (dates[i] > dates[i - 1]) {
1446
+ if (isNewChange(state)) {
1447
+ console.error('BLOCKED: STATE.md 决策日志非倒序(新 change 强制顶部插入);恢复: 顶部插入新决策');
1448
+ process.exit(1);
1449
+ }
1450
+ console.error('WARN: STATE.md 决策日志非倒序(新决策应插入顶部)');
1451
+ break;
1452
+ }
1453
+ }
1454
+ } catch {}
1455
+ const changelogFile = path.join(runRoot, '.specs', 'CHANGELOG.md');
1456
+ try {
1457
+ const content = await fs.readFile(changelogFile, 'utf8');
1458
+ const dates = [...content.matchAll(/^\| (\d{4}-\d{2}-\d{2}) \|/gm)].map(m => m[1]);
1459
+ for (let i = 1; i < dates.length; i++) {
1460
+ if (dates[i] > dates[i - 1]) {
1461
+ if (isNewChange(state)) {
1462
+ console.error('BLOCKED: CHANGELOG.md 表格日期非倒序(新 change 强制顶部插入);恢复: 表格顶部插入新条目');
1463
+ process.exit(1);
1464
+ }
1465
+ console.error('WARN: CHANGELOG.md 表格日期非倒序(新条目应插入表格顶部)');
1466
+ break;
1467
+ }
1468
+ }
1469
+ // 归档收尾登记兜底(WARN 渐进,新旧一致)——CHANGELOG 未含本 change 标识
1470
+ // (change-id)→ 提示补登记,防静默遗漏(实测:提交信息声称已登记但实际未改,
1471
+ // 机制无兜底;检测为存在级——含 change-id 字样即视为已登记)
1472
+ if (state.activeChange && !content.includes(state.activeChange)) {
1473
+ console.error('WARN: CHANGELOG.md 未登记本 change(' + state.activeChange + ')——归档收尾应在 CHANGELOG 顶部插入本 change 条目(跟随项目既有格式)');
1474
+ }
1475
+ } catch {}
1476
+ }
1477
+ // W1-A: 每个节点合法 exit 必须满足前置 evidence(对应 flowkit.*.v1 的 evidence)
1478
+ // 语义与 missingRequiredSchemaEvidence 一致:summary 视同满足(record 命令默认只写 summary)
1479
+ const gate = NODE_TRANSITION_GATES[node.id];
1480
+ if (gate) {
1481
+ for (const ev of gate.evidence) {
1482
+ // subagent-execute 的 handoff-result gate 兼容共用证据库——委托结果记录在
1483
+ // 嵌套 handoffResult(键名契约 handoff-result vs handoffResult 错位),非空即满足
1484
+ // (存在性校验;每个委托内容的 Return Contract 严格校验由 W1-D 负责)
1485
+ const satisfied = hasEvidenceField(evidence, ev) ||
1486
+ (typeof evidence.summary === 'string' && evidence.summary.trim() !== '') ||
1487
+ (node.id === 'subagent-execute' && ev === 'handoff-result' && hasNonEmptyHandoffResult(evidence));
1488
+ if (!satisfied) {
1489
+ console.error('BLOCKED: node ' + node.id + ' exit requires evidence: ' + ev);
1490
+ process.exit(1);
1491
+ }
1492
+ }
1493
+ }
1494
+ // C3: exit execute / subagent-execute 校验 TASK.md 任务集签名未变(status 标记 done 合法已剥离;增删任务/改 action/改边界 BLOCKED)
1495
+ if ((node.id === 'execute' || node.id === 'subagent-execute') && state.activeChange) {
1496
+ if (typeof state.taskHash === 'string' && state.taskHash.length > 0) {
1497
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
1498
+ if (await fileExists(taskFile)) {
1499
+ try {
1500
+ const currentHash = taskSetSignature(await fs.readFile(taskFile, 'utf8'));
1501
+ if (currentHash !== state.taskHash) {
1502
+ console.error('BLOCKED: TASK.md 任务集被修改(签名不匹配),execute 期间不允许增删任务/改 action/改边界');
1503
+ process.exit(1);
1504
+ }
1505
+ } catch {}
1506
+ }
1507
+ }
1508
+ }
1509
+ // open exit 校验 REQUIREMENT 含 AC 段(段名基准从 REQUIREMENT 模板派生,模板缺失 fallback 内置段名)
1510
+ if (node.id === 'open' && state.activeChange) {
1511
+ const reqFile = path.join(runRoot, '.specs', state.activeChange, 'REQUIREMENT.md');
1512
+ try {
1513
+ const content = await fs.readFile(reqFile, 'utf8');
1514
+ const acceptance = (await templateSectionPatterns()).pick('requirement', ['验收'], TEMPLATE_FALLBACK_SECTION_PATTERNS.requirementAcceptance);
1515
+ if (!acceptance.test(content) && !/Given/i.test(content)) {
1516
+ console.error('BLOCKED: REQUIREMENT.md 缺少验收标准/AC 段');
1517
+ process.exit(1);
1518
+ }
1519
+ } catch {}
1520
+ }
1521
+ // design exit 校验 DESIGN 含技术栈段
1522
+ if (node.id === 'design' && state.activeChange) {
1523
+ const designFile = path.join(runRoot, '.specs', state.activeChange, 'DESIGN.md');
1524
+ const designLite = path.join(runRoot, '.specs', state.activeChange, 'DESIGN-lite.md');
1525
+ const target = (await fileExists(designFile)) ? designFile : (await fileExists(designLite)) ? designLite : null;
1526
+ if (target) {
1527
+ try {
1528
+ const content = await fs.readFile(target, 'utf8');
1529
+ if (!/##\s*0[\s.]/.test(content) && !/##\s*技术栈/.test(content)) {
1530
+ console.error('BLOCKED: DESIGN.md 缺少 §0 技术栈段');
1531
+ process.exit(1);
1532
+ }
1533
+ } catch {}
1534
+ }
1535
+ }
1536
+ // C2: open exit 补必填段校验(结构+存在级,不做语义)——CHANGE.md 含 Why 段;REQUIREMENT.md 含 用户故事 段
1537
+ if (node.id === 'open' && state.activeChange) {
1538
+ const changeDir = path.join(runRoot, '.specs', state.activeChange);
1539
+ // 段名基准从 flow-kit 模板派生(CHANGE 模板 "## Why(为什么做)"、REQUIREMENT 模板 "## 用户故事"),模板缺失 fallback
1540
+ const tpl = await templateSectionPatterns();
1541
+ const required = [
1542
+ ['CHANGE.md', tpl.pick('change', ['Why', '为什么'], TEMPLATE_FALLBACK_SECTION_PATTERNS.changeWhy)],
1543
+ ['REQUIREMENT.md', tpl.pick('requirement', ['用户故事'], TEMPLATE_FALLBACK_SECTION_PATTERNS.requirementUserStory)],
1544
+ ];
1545
+ for (const [file, regex] of required) {
1546
+ const p = path.join(changeDir, file);
1547
+ if (await fileExists(p)) {
1548
+ try {
1549
+ const text = await fs.readFile(p, 'utf8');
1550
+ if (!regex.test(text)) {
1551
+ console.error('BLOCKED: ' + file + ' 缺必填段 ' + regex);
1552
+ process.exit(1);
1553
+ }
1554
+ } catch {}
1555
+ }
1556
+ }
1557
+ }
1558
+ // C2: design exit 补必填段校验——DESIGN.md 含 ## 决策清单(段名基准从 DESIGN 模板派生,"## 1. 决策清单" 编号前缀可选)
1559
+ if (node.id === 'design' && state.activeChange) {
1560
+ const designFile = path.join(runRoot, '.specs', state.activeChange, 'DESIGN.md');
1561
+ const designLite = path.join(runRoot, '.specs', state.activeChange, 'DESIGN-lite.md');
1562
+ const target = (await fileExists(designFile)) ? designFile : (await fileExists(designLite)) ? designLite : null;
1563
+ if (target) {
1564
+ try {
1565
+ const text = await fs.readFile(target, 'utf8');
1566
+ const decisionList = (await templateSectionPatterns()).pick('design', ['决策清单'], TEMPLATE_FALLBACK_SECTION_PATTERNS.designDecisionList);
1567
+ if (!decisionList.test(text)) {
1568
+ console.error('BLOCKED: DESIGN.md 缺必填段 ## 决策清单');
1569
+ process.exit(1);
1570
+ }
1571
+ } catch {}
1572
+ }
1573
+ }
1574
+ // plan exit 校验 TASK 含 task 块和 verify 字段
1575
+ if (node.id === 'plan' && state.activeChange) {
1576
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
1577
+ try {
1578
+ const content = await fs.readFile(taskFile, 'utf8');
1579
+ // <task> 块提取与属性解析统一走 task-parsing.mjs(开标签语义,属性序无关)
1580
+ const taskList = extractTaskBlocks(content);
1581
+ if (taskList.length === 0) {
1582
+ console.error('BLOCKED: TASK.md 无 <task> 块');
1583
+ process.exit(1);
1584
+ }
1585
+ const missingVerify = taskList.filter(b => !/<verify>/.test(b));
1586
+ if (missingVerify.length > 0) {
1587
+ console.error('BLOCKED: TASK.md 中 ' + missingVerify.length + ' 个 task 缺 <verify> 字段');
1588
+ process.exit(1);
1589
+ }
1590
+ // 波次散文一致性检测: 波次散文一致性检测(WARN 渐进)——## 波次划分 的 Wave 行任务带 [P] 标记
1591
+ // (并行语义)但 XML 任务无 parallel="true" → WARN(散文与机器路由依据不一致,以任务
1592
+ // 标记为准)。容错:无并行语义的 Wave 行不参与比对;解析不到波次段跳过(不误报)。
1593
+ const waveSection = content.match(/##\s*波次划分\s*\n([\s\S]*?)(?=\n##\s|\n---|\Z)/);
1594
+ if (waveSection) {
1595
+ const proseParallelIds = [];
1596
+ for (const line of waveSection[1].split('\n')) {
1597
+ if (!/(Wave|\d+\s*波|parallel|并行)/i.test(line)) continue; // 无并行语义行跳过
1598
+ for (const m of line.matchAll(/([A-Z][A-Z0-9-]*)\[P\]/g)) proseParallelIds.push(m[1]);
1599
+ }
1600
+ if (proseParallelIds.length > 0) {
1601
+ const xmlParallelIds = taskList
1602
+ .filter(b => { const a = taskOpeningAttrs(b); return a && a.parallel; })
1603
+ .map(b => (taskOpeningAttrs(b) || {}).id)
1604
+ .filter(Boolean);
1605
+ const missing = proseParallelIds.filter(id => !xmlParallelIds.includes(id));
1606
+ if (missing.length > 0) {
1607
+ if (isNewChange(state)) {
1608
+ console.error('BLOCKED: 波次散文标记任务为并行([P])但任务无 parallel="true"(新 change 强制散文与任务标记一致);恢复: 对齐散文或任务标记');
1609
+ process.exit(1);
1610
+ }
1611
+ console.error('WARN: 波次散文标记为并行([P])但任务无 parallel="true"——散文与任务标记不一致(以任务标记为准): ' + missing.join(', '));
1612
+ }
1613
+ }
1614
+ }
1615
+ // 波次分组校验重定义(依赖图校验决策 · 混排合法化):原「并行块必须单个连续且居首/尾」形态约束废除——
1616
+ // 串行任务位置不再受限,串→并→串 / 并→串→并 / 多波混合均合法(多趟循环路由按依赖拓扑分趟)。
1617
+ // 改为依赖图校验:① 全部任务建依赖图(deps 边)做 Kahn 拓扑排序判环——有环即规划结构性死锁;
1618
+ // ② 全部引用的任务 id 必须存在(无环图下「每个 parallel 任务的全部传递依赖存在且非环」
1619
+ // ⟺ 直接引用都存在)。违规分级:新 change BLOCKED(含「依赖环」/缺失依赖明细 + depends_on
1620
+ // 调整恢复指引);旧 change 渐进 WARN 不阻断。波次散文一致性检测保留不动(与形态约束正交的既有独立检测,维持不变)。
1621
+ const depGraph = analyzeDependencyGraph(taskList);
1622
+ if (depGraph.cyclic || depGraph.missing.length > 0) {
1623
+ const detail = depGraph.cyclic
1624
+ ? '依赖环(拓扑排序无解,涉及任务: ' + depGraph.cycleIds.join(', ') + ')'
1625
+ : '依赖不存在的任务: ' + depGraph.missing.map((m) => m.id + '→' + m.dep).join(', ');
1626
+ const guide = ';恢复: 调整任务 depends_on——移除成环引用或改为真实存在的任务 id 后重试';
1627
+ if (isNewChange(state)) {
1628
+ console.error('BLOCKED: TASK.md ' + detail + '——依赖图不可满足(任务的依赖链必须存在且无环)' + guide);
1629
+ process.exit(1);
1630
+ }
1631
+ console.error('WARN: TASK.md ' + detail + '——依赖图不可满足(旧 change 渐进不阻断)' + guide);
1632
+ }
1633
+ // 伪并行检测(真实载体验证暴露的设计盲区兜底):如果一个标记为并行的任务只写测试文件
1634
+ // 而无任何生产代码文件,它很可能隐式依赖某个实现类并行任务的产出(如测试 import
1635
+ // 尚未存在的函数)。这种"伪并行"在多趟路由下会导致委托后测试失败。
1636
+ // 启发式:并行任务的 write_files 全部匹配 tests/ 或 test_ 前缀 → 视为疑似伪并行。
1637
+ // WARN 渐进不阻断——由执行者判断是否真独立(纯测试基础设施改动可合法全测试面)。
1638
+ const testOnlyParallelIds = [];
1639
+ for (const block of taskList) {
1640
+ const attrs = taskOpeningAttrs(block);
1641
+ if (!attrs || !attrs.parallel || attrs.status !== 'pending') continue;
1642
+ const wfMatch = block.match(/<write_files>([\s\S]*?)<\/write_files>/);
1643
+ if (!wfMatch) continue;
1644
+ // 分号容错:与 workflow-handoff.mjs 自动解析同源实现(分号容错双点内联,与 workflow-handoff.mjs 同源互锚)——
1645
+ // 换行切分后逐段按 ';' 二次切分、trim、滤空与 HTML 注释行(路径含分号的极端形态不支持,须换行书写)
1646
+ const blockContent = wfMatch[1].replace(/<!--[\s\S]*?-->/g, '');
1647
+ const filePaths = blockContent.trim().split(/\s*\n\s*/).map(l => l.trim()).filter(Boolean)
1648
+ .flatMap(l => l.split(';')).map(l => l.trim()).filter(Boolean);
1649
+ if (filePaths.length === 0) continue;
1650
+ const prodFiles = filePaths.filter(f => !/(?:^|[\/\\])(?:__tests__\/|test_|tests?\/)|\.(?:test|spec)\.(?:mjs|js|jsx|ts|tsx|cjs)$/.test(f));
1651
+ if (prodFiles.length === 0) {
1652
+ testOnlyParallelIds.push(attrs.id || 'unknown');
1653
+ }
1654
+ }
1655
+ if (testOnlyParallelIds.length > 0) {
1656
+ console.error('WARN: 伪并行检测——以下并行任务仅写测试文件而无生产代码文件: '
1657
+ + testOnlyParallelIds.join(', ')
1658
+ + '。测试通常依赖实现产出的符号,可能存在隐式依赖;建议添加 depends_on 声明或合并为垂直切片');
1659
+ }
1660
+ // 并行文件依赖检测前移(触发面):write∩write 写写强判(新 change BLOCKED / 旧 change
1661
+ // WARN 渐进,与依赖环分级同先例)+ read∩write 读写弱判(仅无显式 depends_on 关联的并行对;
1662
+ // WARN 提示级,新/旧均不 BLOCK——渐进提示)。与委托前既有拦截并存(委托前为第二道写写锚,
1663
+ // 行为与消息保持既有语义不变)。
1664
+ const { writeConflicts, readWarnings } = await findParallelWriteConflicts(path.join(runRoot, '.specs', state.activeChange));
1665
+ if (writeConflicts.length > 0) {
1666
+ const detail = writeConflicts.map((c) => `${c.a}×${c.b}(${c.files.join(',')})`).join('; ');
1667
+ const guide = ';恢复: 补显式 depends_on 或拆为串行任务后重试';
1668
+ if (isNewChange(state)) {
1669
+ console.error('BLOCKED: TASK.md 并行任务 write_files 重叠(写写冲突,同波次并行会竞态覆盖): ' + detail + guide);
1670
+ process.exit(1);
1671
+ }
1672
+ console.error('WARN: TASK.md 并行任务 write_files 重叠(写写冲突,建议补显式 depends_on 或拆为串行任务): ' + detail + guide);
1673
+ }
1674
+ if (readWarnings.length > 0) {
1675
+ console.error('WARN: TASK.md 并行任务 read∩write 隐式依赖嫌疑(一方读取对方写路径,建议补显式 depends_on 声明): '
1676
+ + readWarnings.map((c) => `${c.a}×${c.b}(${c.files.join(',')})`).join('; '));
1677
+ }
1678
+ } catch {}
1679
+ }
1680
+ // review exit 校验 REVIEW 含实质内容 + 发现区条目处置状态结构级校验
1681
+ if (node.id === 'review' && state.activeChange) {
1682
+ const reviewFile = path.join(runRoot, '.specs', state.activeChange, 'REVIEW.md');
1683
+ try {
1684
+ const stat = await fs.stat(reviewFile);
1685
+ if (stat.size < 100) {
1686
+ console.error('BLOCKED: REVIEW.md 内容不足(' + stat.size + ' 字节,需 ≥ 100)');
1687
+ process.exit(1);
1688
+ }
1689
+ // L3-1: 发现项(含 Minor)须有处置状态标记——[已修](对应 fix 任务)/ [升级](用户决策:
1690
+ // 接受+理由)/ [转待办](归档时进 KNOWN-ISSUES)。结构级校验,WARN 渐进不 BLOCK:
1691
+ // 旧 REVIEW 未按新格式写标记只警告不阻断(防旧 REVIEW 卡死),执行者补标记后可消除。
1692
+ const missingDisposition = reviewFindingsMissingDisposition(await fs.readFile(reviewFile, 'utf8'));
1693
+ if (missingDisposition.length > 0) {
1694
+ if (isNewChange(state)) {
1695
+ console.error('BLOCKED: REVIEW.md 发现区 ' + missingDisposition.length + ' 项条目缺处置状态标记([已修]/[升级]/[转待办])——新 change 强制每项发现须有处置');
1696
+ console.error('恢复: 为发现区条目补处置标记后重试;未处置的发现(含 Minor)不应无声消失');
1697
+ process.exit(1);
1698
+ }
1699
+ console.error('REVIEW WARN: REVIEW.md 发现区 ' + missingDisposition.length +
1700
+ ' 项条目缺处置状态标记([已修]/[升级]/[转待办]): ' + missingDisposition.join('、') +
1701
+ '——未处置的发现(含 Minor)不应无声消失,补标记后本警告消除(渐进不阻断)');
1702
+ }
1703
+ } catch {}
1704
+ }
1705
+ // W3: directOverride 授权约束(direct 是用户决策点,不可自决——机制约束)——
1706
+ // execute / subagent-execute 出口校验:executionMode=direct 且 directOverride=true(显式
1707
+ // 直显授权态)须存在授权审计记录(directOverrideAt/来源,由 workflow-state execution-mode
1708
+ // 命令在协调者显式授权时写入)——否则 BLOCKED + 恢复指引(协调者显式授权 / 回 subagent)。
1709
+ // 旧 state 缺省(directOverride=false / 缺字段)放行(前向兼容——未处于显式 direct 不受影响)。
1710
+ if ((node.id === 'execute' || node.id === 'subagent-execute') && state.activeChange) {
1711
+ const directMode = state.executionMode ?? 'subagent';
1712
+ if (directMode === 'direct' && state.directOverride === true) {
1713
+ const hasAuditRecord = typeof state.directOverrideAt === 'string'
1714
+ && state.directOverrideAt.trim() !== '';
1715
+ if (!hasAuditRecord) {
1716
+ console.error('BLOCKED: executionMode=direct 且 directOverride=true 但无授权审计记录(direct 是用户决策点,不可自决——须存在授权留痕 directOverrideAt/来源,由协调者显式 execution-mode direct 写入)');
1717
+ console.error('恢复: 由协调者执行 workflow-state.mjs execution-mode direct 显式授权(写入授权审计记录)后重试 exit;或 execution-mode subagent 切回(清除 directOverride)后重试 exit;禁止手改 state 机器字段');
1718
+ process.exit(1);
1719
+ }
1720
+ }
1721
+ }
1722
+ // W1-B: execute / subagent-execute 出口校验每份 SUMMARY 含三个必填段 + 6 维自查非空 + 自检方法
1723
+ if (node.id === 'execute' || node.id === 'subagent-execute') {
1724
+ const changeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
1725
+ const violations = await verifySummaries(changeDir);
1726
+ // brooks-lint 自检方法审计:检查 6 维自查段是否声明了自检方法
1727
+ const summaryFiles = (await fs.readdir(changeDir).catch(() => [])).filter(f => f.endsWith('-SUMMARY.md'));
1728
+ for (const f of summaryFiles) {
1729
+ try {
1730
+ const content = await fs.readFile(path.join(changeDir, f), 'utf8');
1731
+ // 段终止 lookahead 用 \n##\s(而非 \n##):###/#### 级子标题(如 "### 🟢 R1")是段内内容,不是段结束
1732
+ const sixDim = content.match(/##\s*6\s*维自查[\s\S]*?(?=\n##\s|\n---|\Z)/i);
1733
+ // C1: 6 维自查段非空——去掉所有标题行后剩余实质内容 ≥ 10 字符
1734
+ // 按行过滤标题(/^\s*#/)比正则替换稳健:任何标题格式(emoji 🟢/中英文/数字)都不计入内容
1735
+ const dimBody = sixDim ? sixDim[0].split('\n').filter(l => !/^\s*#/.test(l)).join('').trim() : '';
1736
+ if (sixDim && dimBody.length < 10) {
1737
+ violations.push(f + ' 的 6 维自查段无实质内容');
1738
+ }
1739
+ // 生产代码任务必填 ## 自检方法,声明 brooks-review 或 builtin-quickcheck
1740
+ // 格式兼容:方法名行允许中文前缀/括号说明(如 "方法:brooks-review"),按关键词搜索而非 [a-z-]+ 硬匹配
1741
+ // 段名允许带括号后缀(如 "## 自检方法(声明 brooks-review 或 builtin-quickcheck)"——括号为说明非段名部分,
1742
+ // 执行者常按模板标题原样书写导致旧正则不匹配落入"旧格式 WARN";括号后缀与段名等价)
1743
+ // 分隔符用 .?(任意字符)而非 \.?(字面点):canonical 名 "brooks-review"/"builtin-quickcheck" 是连字符,与既有 /brooks.?review/ 约定一致
1744
+ // 真实项目端到端验证实证:方法名可能在段内后续行(子代理列表写法)——段内全文搜索而非仅第一行
1745
+ // 段内容截取到下一个段标题(\n## )或分隔线(\n---)或文件尾(split 处理,避免 JS 无 \Z 的问题)
1746
+ const methodMatch = content.match(/##\s*自检方法(?:[((][^))\n]*[))])?\s*\n([\s\S]*)/i);
1747
+ const methodSection = methodMatch ? methodMatch[1].split(/\n##\s|\n---/)[0] : null;
1748
+ const method = methodSection ? /brooks.?review|cache.?brooks|builtin.?quickcheck/i.exec(methodSection) : null;
1749
+ if (!method) {
1750
+ // 过渡规则:旧格式 SUMMARY 无 ## 自检方法 段——
1751
+ // 若全文已声明 brooks-review/cache-brooks/builtin(旧模板行为),WARN 兼容不 BLOCKED;无任何自检声明才 BLOCKED
1752
+ if (/brooks.?review|cache.?brooks|builtin.?quickcheck/i.test(content)) {
1753
+ if (isNewChange(state)) {
1754
+ violations.push(f + ' 缺 ## 自检方法 段(新 change 强制声明自检方法)');
1755
+ } else {
1756
+ console.error('BROOKS-LINT WARN: ' + f + ' 缺 ## 自检方法 段(旧格式),6 维自查已声明自检方法——兼容通过,建议补全');
1757
+ }
1758
+ } else {
1759
+ violations.push(f + ' 缺 ## 自检方法 字段(必须声明 brooks-review 或 builtin-quickcheck)');
1760
+ }
1761
+ } else if (/builtin/i.test(method[0])) {
1762
+ // builtin 降级两级校验——① 必须声明不可用原因(既有);② 必须含缓存尝试证据
1763
+ // (已尝试 Read 插件缓存协议文件手动执行仍不可行——两级降级路径第 2 级;防「未尝试读缓存」的偷懒降级)
1764
+ // 关键词声明级校验(设计边界:不做语义判断);缺失 → WARN 渐进(不 BLOCK,向后兼容旧 SUMMARY)
1765
+ if (!/brooks-lint 不可用|插件不可用|unavailable|N\/A/i.test(content)) {
1766
+ if (isNewChange(state)) {
1767
+ console.error('BLOCKED: SUMMARY 使用 builtin-quickcheck 未声明 brooks-lint 不可用原因(新 change 强制);恢复: 在 ## 自检方法 段补原因(声明级校验——须含关键词: brooks-lint 不可用 / 插件不可用 / unavailable / N/A,如「brooks-lint 不可用(Skill 仅返回占位,插件执行体未加载)」)');
1768
+ process.exit(1);
1769
+ }
1770
+ console.error('BROOKS-LINT WARN: ' + f + ' 使用 builtin-quickcheck 但未声明 brooks-lint 不可用原因');
1771
+ } else if (!/插件缓存|缓存协议|协议文件|plugins\/cache/i.test(content)) {
1772
+ if (isNewChange(state)) {
1773
+ console.error('BLOCKED: SUMMARY 使用 builtin-quickcheck 未声明缓存尝试证据(新 change 强制先 Read 插件缓存协议文件);恢复: 在 ## 自检方法 段声明缓存尝试(须含关键词: 插件缓存 / 缓存协议 / 协议文件 / plugins/cache,如「已 Read 插件缓存协议文件(~/.claude/plugins/cache/...)手动执行仍不可行」)');
1774
+ process.exit(1);
1775
+ }
1776
+ console.error('BROOKS-LINT WARN: ' + f + ' 使用 builtin-quickcheck 但未声明缓存尝试证据(应先 Read 插件缓存协议文件手动执行完整 brooks 流程)');
1777
+ }
1778
+ }
1779
+ if (sixDim && !/brooks.?review|cache.?brooks/i.test(sixDim[0])) {
1780
+ if (isNewChange(state)) {
1781
+ console.error('BLOCKED: SUMMARY 的 6 维自查未声明使用 /brooks-review(新 change 强制声明自检方法);恢复: 在 6 维自查段声明 /brooks-review 或理由');
1782
+ process.exit(1);
1783
+ }
1784
+ console.error('BROOKS-LINT WARN: ' + f + ' 的 6 维自查未声明使用 /brooks-review(可能使用了内置快查)');
1785
+ }
1786
+ } catch {}
1787
+ }
1788
+ if (violations.length > 0) {
1789
+ console.error('BLOCKED: SUMMARY 关键段校验失败: ' + violations.join('; '));
1790
+ process.exit(1);
1791
+ }
1792
+ }
1793
+ // execute 出口校验——统一委托后所有 done 任务需 handoff(越俎代庖检测覆盖串行/并行)
1794
+ if (node.id === 'execute' && state.activeChange) {
1795
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
1796
+ try {
1797
+ const taskContent = await fs.readFile(taskFile, 'utf8');
1798
+ // 解析 TASK.md 全部 task 的 {id, status, parallel}——开标签属性解析共享 task-parsing.mjs
1799
+ // (属性序无关、不读块内文本;与 workflow-state 路由同语义)
1800
+ const taskList = extractTaskBlocks(taskContent);
1801
+ const tasks = taskList.map(block => {
1802
+ const a = taskOpeningAttrs(block) || {};
1803
+ return { id: a.id, status: a.status, parallel: a.parallel };
1804
+ }).filter(t => t.id);
1805
+
1806
+ // 串行 pending → BLOCKED(execute 任务没做完)——emptyExitApproved 不豁免串行 pending:
1807
+ // 豁免语义是"全 parallel 无串行可做时空退出";存在未完成串行任务时豁免不应生效
1808
+ // (防规划错误被豁免掩盖;豁免仅作用于后续产物校验跳过,审计提示保留)
1809
+ const emptyExitApproved = !!(state.evidence?.execute && state.evidence.execute.emptyExitApproved);
1810
+ if (emptyExitApproved) {
1811
+ console.error('EMPTY-EXIT: execute 空退出豁免已生效(evidence.execute.emptyExitApproved)——审计记录:该 change 在无串行任务时显式豁免空退出');
1812
+ }
1813
+ // serialPending 收窄为「可运行串行」(出口拦截集合收窄):仅 deps ⊆ doneIds 的
1814
+ // 未完成串行计入拦截——deps 未满足的串行 pending 是等后续波次的合法中间态,放行由多趟
1815
+ // 路由按依赖拓扑分趟驱动。doneIds 就地派生;deps 提取复用 taskDependsOn(<depends_on>
1816
+ // 内容按 [,\s]+ 切分,与路由谓词同一解析口径),不新增状态。
1817
+ const doneIds = new Set(tasks.filter(t => t.status === 'done').map(t => t.id));
1818
+ const blockById = new Map();
1819
+ for (const block of taskList) {
1820
+ const a = taskOpeningAttrs(block);
1821
+ if (a && a.id) blockById.set(a.id, block);
1822
+ }
1823
+ const serialRunnable = tasks.filter(t =>
1824
+ !t.parallel && t.status === 'pending'
1825
+ && taskDependsOn(blockById.get(t.id) || '').every(d => doneIds.has(d)));
1826
+ if (serialRunnable.length > 0) {
1827
+ console.error('BLOCKED: execute 出口仍有串行 pending 任务: ' + serialRunnable.map(t => t.id).join(', ')
1828
+ + '——空退出豁免不适用于存在未完成可运行串行任务的情况(先完成该串行任务,或修正任务标记)'
1829
+ + ';无可执行的常规恢复动作时,可用 workflow-state.mjs advance 渡过结构性死结(逃生口:使用后本节点须重新 entry 并重做交付记录);常规缺产物/缺证据情形不适用');
1830
+ process.exit(1);
1831
+ }
1832
+
1833
+ // done 任务 ↔ SUMMARY 完整性: done 任务 ↔ <id>-SUMMARY.md 存在(WARN 渐进不 BLOCK——防旧 change 卡死;
1834
+ // 结构级校验与 TASK 签名同源:任务完成声明须有对应产物)
1835
+ // M2: 新 change(enter 机制激活)升级为 BLOCKED——执行遗漏(声称完成但无产物)不静默进归档;旧 change 保持渐进
1836
+ const ki8ChangeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
1837
+ for (const tid of tasks.filter(t => t.status === 'done').map(t => t.id)) {
1838
+ if (!(await fileExists(path.join(ki8ChangeDir, tid + '-SUMMARY.md')))) {
1839
+ if (isNewChange(state)) {
1840
+ console.error('BLOCKED: done 任务 ' + tid + ' 缺少 ' + tid + '-SUMMARY.md——execute 产物不完整(新 change 强制任务完成须有对应 SUMMARY;旧 change 渐进 WARN)');
1841
+ console.error('恢复: 补写 ' + tid + '-SUMMARY.md 后重试 exit;任务完成后补产物即可');
1842
+ process.exit(1);
1843
+ }
1844
+ console.error('WARN: done 任务 ' + tid + ' 缺少 ' + tid + '-SUMMARY.md——execute 产物不完整(任务完成须有对应 SUMMARY)');
1845
+ }
1846
+ }
1847
+
1848
+ // 豁免机制:evidence(当前节点 execute)含 parallelTakeoverApproved: true 时跳过越俎代庖检测(只保留串行 pending 检测)
1849
+ const executeEvidence = state.evidence['execute'];
1850
+ const takeoverApproved = !!(executeEvidence && executeEvidence.parallelTakeoverApproved);
1851
+
1852
+ if (!takeoverApproved) {
1853
+ // 越俎代庖检测按 executionMode 分支:
1854
+ // - direct(逃生口):串行任务主代理直写,不需 handoff;parallel 仍必须委托(防 execute 吞 parallel 回归)
1855
+ // - subagent(默认):所有 done 任务需 handoff(统一委托下只能由子代理完成)
1856
+ const executionMode = state.executionMode ?? 'subagent';
1857
+ const he = state.evidence['subagent-execute'];
1858
+ const results = he && he.handoffResult ? he.handoffResult : {};
1859
+ let unauthorized;
1860
+ if (executionMode === 'direct') {
1861
+ unauthorized = tasks.filter(t => t.parallel && t.status === 'done' && !results[t.id]);
1862
+ } else {
1863
+ unauthorized = tasks.filter(t => t.status === 'done' && !results[t.id]);
1864
+ }
1865
+ if (unauthorized.length > 0) {
1866
+ console.error('BLOCKED: 任务被主代理直接标记 done(越俎代庖)' + (executionMode === 'direct' ? ',direct 模式下 parallel 任务仍必须委托子代理' : ',统一委托下只能由子代理完成并记录 handoff') + ': ' + unauthorized.map(t => t.id).join(', '));
1867
+ console.error('解决: 回退这些任务的 done 标记,重新委托子代理;或用 workflow-state.mjs record execute \'{"parallelTakeoverApproved":true}\' 显式豁免');
1868
+ process.exit(1);
1869
+ }
1870
+ // parallel 仍 pending → 合法(下一步 determineNode 路由到 subagent-execute)
1871
+ }
1872
+
1873
+ // 越权委托检测(execute 出口): 越权委托检测(execute 出口第一道)——TASK 有 parallel done 任务 +
1874
+ // completedNodes 无 subagent-execute + 非 direct 模式 + 协议含 subagent-execute 节点
1875
+ // → WARN 渐进([P] 任务应由 subagent-execute 节点委托——execute 阶段完成 [P] 是
1876
+ // 越权委托痕迹;handoff 记录存在但节点未 exit——上轮真实项目端到端验证实证)
1877
+ const ki10ParallelDone = tasks.filter(t => t.parallel && t.status === 'done').map(t => t.id);
1878
+ const ki10ProtocolHasSubagent = (protocol.nodes ?? []).some(n => n.id === 'subagent-execute');
1879
+ if (ki10ParallelDone.length > 0
1880
+ && !(state.completedNodes ?? []).includes('subagent-execute')
1881
+ && (state.executionMode ?? 'subagent') !== 'direct'
1882
+ && !takeoverApproved
1883
+ && ki10ProtocolHasSubagent) {
1884
+ if (isNewChange(state)) {
1885
+ console.error('BLOCKED: TASK 有 parallel done 任务(' + ki10ParallelDone.join(', ')
1886
+ + ')但 subagent-execute 节点未 exit——新 change 强制 [P] 任务由 subagent-execute 节点委托');
1887
+ console.error('恢复: 经 subagent-execute 节点完成委托后再 exit;或说明越权委托原因');
1888
+ process.exit(1);
1889
+ }
1890
+ console.error('WARN: TASK 有 parallel done 任务(' + ki10ParallelDone.join(', ')
1891
+ + ')但 subagent-execute 节点未 exit——疑似 execute 阶段越权委托,[P] 任务应由 subagent-execute 节点委托');
1892
+ }
1893
+ } catch {}
1894
+ }
1895
+ // W1-C: verify 出口必须真实跑命令(严格版)——历史归档 change 豁免(过渡规则)
1896
+ if (node.id === 'verify' && !(await isArchivedChange(state.activeChange))) {
1897
+ // 越权委托兜底检测(verify 出口): 越权委托兜底检测(verify 出口)——同 KI-10 判定(TASK parallel done +
1898
+ // completedNodes 无 subagent-execute + 非 direct + 协议含 subagent-execute 节点),
1899
+ // verify 时仍未 exit → WARN 兜底(execute 出口未拦截的提示)
1900
+ try {
1901
+ const ki9TaskText = await fs.readFile(path.join(runRoot, '.specs', state.activeChange ?? '', 'TASK.md'), 'utf8');
1902
+ const ki9TaskBlocks = extractTaskBlocks(ki9TaskText);
1903
+ const ki9Tasks = ki9TaskBlocks.map(block => {
1904
+ const a = taskOpeningAttrs(block) || {};
1905
+ return { id: a.id, status: a.status, parallel: a.parallel };
1906
+ }).filter(t => t.id);
1907
+ const ki9ParallelDone = ki9Tasks.filter(t => t.parallel && t.status === 'done').map(t => t.id);
1908
+ const ki9ProtocolHasSubagent = (protocol.nodes ?? []).some(n => n.id === 'subagent-execute');
1909
+ const ki9TakeoverApproved = !!(state.evidence?.execute && state.evidence.execute.parallelTakeoverApproved);
1910
+ if (ki9ParallelDone.length > 0
1911
+ && !(state.completedNodes ?? []).includes('subagent-execute')
1912
+ && (state.executionMode ?? 'subagent') !== 'direct'
1913
+ && !ki9TakeoverApproved
1914
+ && ki9ProtocolHasSubagent) {
1915
+ if (isNewChange(state)) {
1916
+ console.error('BLOCKED: TASK 有 parallel done 任务(' + ki9ParallelDone.join(', ')
1917
+ + ')但 subagent-execute 节点未 exit——新 change 强制(verify 兜底拦截)');
1918
+ console.error('恢复: 经 subagent-execute 节点完成委托后再 exit;或说明越权委托原因');
1919
+ process.exit(1);
1920
+ }
1921
+ console.error('WARN: TASK 有 parallel done 任务(' + ki9ParallelDone.join(', ')
1922
+ + ')但 subagent-execute 节点未 exit——疑似越权委托(execute 出口未拦截,verify 兜底提示)');
1923
+ }
1924
+ } catch {}
1925
+ const { spawnSync } = await import('child_process');
1926
+ let verifyCommand = null;
1927
+ // 1) TEST.md 的 ## 验证命令 段(首行代码块首行)
1928
+ const testDoc = path.join(runRoot, '.specs', state.activeChange ?? '', 'TEST.md');
1929
+ if (await fileExists(testDoc)) {
1930
+ const text = await fs.readFile(testDoc, 'utf8');
1931
+ // 段名允许括号后缀(与 ## 自检方法 段的括号后缀兼容风格一致——执行者按
1932
+ // 模板标题原样书写或补充说明时不被误 BLOCKED)
1933
+ const m = text.match(/##\s*验证命令(?:[((][^))\n]*[))])?\s*\n\s*```[^\n]*\n([\s\S]*?)```/);
1934
+ if (m) verifyCommand = m[1].trim().split('\n').filter(l => l.trim() && !l.trim().startsWith('#')).join(' && ');
1935
+ }
1936
+ // 2) state 的 verifyCommand
1937
+ if (!verifyCommand && state.verifyCommand) verifyCommand = state.verifyCommand;
1938
+ // 3) 项目探测回退
1939
+ if (!verifyCommand) {
1940
+ if (await fileExists(path.join(runRoot, 'pingpong-tournament', 'pyproject.toml'))) verifyCommand = 'cd pingpong-tournament && python -m pytest tests/ -q';
1941
+ else if (await fileExists(path.join(runRoot, 'frontend', 'package.json'))) verifyCommand = 'cd frontend && npm test';
1942
+ }
1943
+ if (!verifyCommand) {
1944
+ console.error('BLOCKED: TEST.md 需声明 ## 验证命令 段(严格版要求)');
1945
+ process.exit(1);
1946
+ }
1947
+ // verify 命令 timeout 可配置——FLOW_COMET_VERIFY_TIMEOUT_MS 环境变量优先,
1948
+ // 缺省 300000ms(300s;后端测试耗时可超 300s,用 env 调大);非数字/0 → 回退缺省
1949
+ const verifyTimeoutMs = Number.parseInt(process.env.FLOW_COMET_VERIFY_TIMEOUT_MS ?? '300000', 10) || 300000;
1950
+ // 二段式执行(受限沙箱兼容):首选管道式捕获(输出可用、行为与既有等价);仅当管道式
1951
+ // 执行在 spawn 层被拒(EPERM——如受限沙箱会话,此时子进程根本不启动)时降级:以继承
1952
+ // stdio 重试同一命令(真实执行保持、退出码判定不变),VERIFY-DEGRADED 行标记降级捕获;
1953
+ // 非 EPERM 失败维持现状路径(不降级,避免吞掉真实测试失败)。
1954
+ try {
1955
+ // 测试钩子(仅测试用途):FLOW_COMET_VERIFY_FORCE_EPERM=1 使首次管道执行模拟 EPERM
1956
+ // 拒绝——真实受限会话中命令在管道阶段不会启动,故跳过管道阶段直接产生 EPERM 结果,
1957
+ // 让降级路径可确定性自动化断言(生产触发条件是真实 spawn 层 EPERM,不经此钩子)
1958
+ const forceEperm = process.env.FLOW_COMET_VERIFY_FORCE_EPERM === '1';
1959
+ const first = forceEperm
1960
+ ? { status: null, error: Object.assign(new Error('spawn verify EPERM(FLOW_COMET_VERIFY_FORCE_EPERM=1 模拟受限沙箱拒绝)'), { code: 'EPERM' }), stdout: '', stderr: '' }
1961
+ : spawnSync(verifyCommand, { cwd: runRoot, shell: true, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: verifyTimeoutMs });
1962
+ const firstFailed = first.error != null || first.status !== 0;
1963
+ const epermDenied = first.error != null && (first.error.code === 'EPERM' || String(first.error.message ?? '').includes('EPERM'));
1964
+ if (firstFailed && epermDenied) {
1965
+ console.error('VERIFY-DEGRADED: ' + verifyCommand + '(沙箱管道受限,以 inherit 重试)');
1966
+ const r2 = spawnSync(verifyCommand, { cwd: runRoot, shell: true, stdio: 'inherit', timeout: verifyTimeoutMs });
1967
+ if (!(r2.error == null && r2.status === 0)) {
1968
+ throw new Error(r2.error != null ? String(r2.error.message) : ('exit code ' + r2.status));
1969
+ }
1970
+ } else if (firstFailed) {
1971
+ // 非 EPERM 失败维持现状路径——抛出与既有 execSync 形态兼容的错误对象(stdout 优先展示)
1972
+ const e = new Error('Command failed: ' + verifyCommand + '\n' + String(first.stderr ?? ''));
1973
+ e.stdout = first.stdout;
1974
+ throw e;
1975
+ }
1976
+ } catch (e) {
1977
+ // verify-fail 自动递增(无需 LLM 主动调用)——计数按当前 change 存储
1978
+ // (verifyFailuresByChange,切换 change 不串扰;旧顶层字段迁移并入)
1979
+ const count = verifyFailuresFor(state) + 1;
1980
+ setVerifyFailuresFor(state, count);
1981
+ const file = await statePath(protocol);
1982
+ const bad = validateStateFields(state);
1983
+ if (bad.length) { console.error('BLOCKED: state 字段类型非法: ' + bad[0]); process.exit(1); }
1984
+ await writeJson(file, state);
1985
+ if (count >= 4) {
1986
+ console.error('BLOCKED: verify 已失败 ' + count + ' 次,需用户决策(继续修/停止)。');
1987
+ } else {
1988
+ // stdout 为空(如超时被 kill 时 stdout 是空 Buffer——truthy)→ 显示错误消息;
1989
+ // 消息中带实际应用的 timeout(超时可诊断,且与 Node 版本无关)
1990
+ const detail = (e.stdout && e.stdout.length) ? e.stdout : e.message;
1991
+ console.error('BLOCKED: verify 命令失败(timeout ' + verifyTimeoutMs + 'ms): ' + verifyCommand + '\n' + String(detail).slice(0, 500));
1992
+ console.error('VERIFY-FAIL: ' + count + '/3');
1993
+ }
1994
+ process.exit(1);
1995
+ }
1996
+ }
1997
+ // W1-D: Return Contract 校验——每个 delegated task 的 result 必须含 commitHash + greenEvidence
1998
+ // handoff-guarded 落实——每个 result 的 completedChecks 必须包含
1999
+ // required-skill:subagent-execute.<skill>(skill 名从协议 requiredSkillCalls 读)。
2000
+ // 严格模式:旧格式非 JSON result(无 completedChecks 载体)同样 BLOCKED,无旧 change 豁免——
2001
+ // 补录/重录必须回传完整契约(含 completedChecks),不允许历史格式绕过委托证明
2002
+ if (node.id === 'subagent-execute') {
2003
+ const he = state.evidence['subagent-execute'];
2004
+ const results = he && he.handoffResult ? he.handoffResult : {};
2005
+ const requiredChecks = (node.requiredSkillCalls ?? [])
2006
+ .map((binding) => 'required-skill:' + node.id + '.' + binding.skill);
2007
+ const violations = [];
2008
+ for (const [taskId, rec] of Object.entries(results)) {
2009
+ const r = typeof rec.result === 'object' && rec.result !== null ? rec.result : null;
2010
+ if (!r) { violations.push(taskId + ' 非 Return Contract(旧格式,缺 completedChecks)'); continue; }
2011
+ // 零提交语义对齐:request 记录 noCommit(write_files 空)的任务无提交可回传,
2012
+ // 豁免 commitHash 缺失断言(其余契约校验不变)——与 workflow-handoff 零提交跳过同构
2013
+ const taskReq = he.handoffRequests ? he.handoffRequests[taskId] : null;
2014
+ const noCommitTask = !!(taskReq && taskReq.noCommit === true);
2015
+ if (!r.commitHash && !noCommitTask) violations.push(taskId + ' 缺 commitHash');
2016
+ if (!r.greenEvidence || !r.greenEvidence.command) violations.push(taskId + ' 缺 greenEvidence');
2017
+ // redEvidence 缺失警告(过渡期不阻断)——M3: 新 change(enter 机制激活)升级为 BLOCKED(TDD RED 证据强制)
2018
+ if (r && !r.redEvidence) {
2019
+ if (isNewChange(state)) {
2020
+ violations.push(taskId + ' 缺 redEvidence(新 change 强制 TDD RED 证据;旧 change 渐进 WARN)');
2021
+ } else {
2022
+ console.error('HANDOFF WARN: ' + taskId + ' 缺 redEvidence(可能未执行 TDD RED 阶段)');
2023
+ }
2024
+ }
2025
+ // completedChecks 严格校验(无旧 change 豁免)
2026
+ if (requiredChecks.length > 0) {
2027
+ const checks = Array.isArray(r.completedChecks) ? r.completedChecks : [];
2028
+ const missing = requiredChecks.filter((check) => !checks.includes(check));
2029
+ if (missing.length > 0) {
2030
+ violations.push(taskId + ' 缺 completedChecks: ' + missing.join(', '));
2031
+ }
2032
+ }
2033
+ }
2034
+ if (violations.length > 0) {
2035
+ console.error('BLOCKED: Return Contract 校验失败: ' + violations.join('; '));
2036
+ console.error('恢复: 子代理回传完整契约(含缺失字段)后用 workflow-handoff.mjs result 重录——新 change 强制 TDD RED/GREEN 证据与 completedChecks;注意:若已记录 greenEvidence 而缺 redEvidence,时序防护会拦截事后补录(防掩盖缺 RED)——确认子代理真实执行过 TDD RED 且证据在对应 SUMMARY 中时,用 workflow-state.mjs record subagent-execute 合并写入真实 redEvidence(证据可溯源),或重新委托任务获取完整契约');
2037
+ process.exit(1);
2038
+ }
2039
+ }
2040
+ // M2: subagent-execute 出口——done 任务缺 SUMMARY(新 change BLOCKED;旧 change 渐进 WARN)
2041
+ // 此前为已知边界(W1-B 只查存在 SUMMARY 的段内容);执行遗漏(声称完成无产物)不应静默进归档
2042
+ if (node.id === 'subagent-execute' && state.activeChange) {
2043
+ const saTaskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
2044
+ try {
2045
+ const saContent = await fs.readFile(saTaskFile, 'utf8');
2046
+ const saTasks = (saContent.match(/<task[^>]*>[\s\S]*?<\/task>/g) || [])
2047
+ .map(block => ({ id: (block.match(/id="([^"]+)"/) || [])[1] || null, status: (block.match(/status="([^"]+)"/) || [])[1] || null }))
2048
+ .filter(t => t.id);
2049
+ const saDir = path.join(runRoot, '.specs', state.activeChange ?? '');
2050
+ for (const t of saTasks.filter(t => t.status === 'done')) {
2051
+ if (!(await fileExists(path.join(saDir, t.id + '-SUMMARY.md')))) {
2052
+ if (isNewChange(state)) {
2053
+ console.error('BLOCKED: done 任务 ' + t.id + ' 缺少 ' + t.id + '-SUMMARY.md——subagent-execute 产物不完整(新 change 强制任务完成须有对应 SUMMARY;旧 change 渐进 WARN)');
2054
+ console.error('恢复: 补写 ' + t.id + '-SUMMARY.md 后重试 exit;任务完成后补产物即可');
2055
+ process.exit(1);
2056
+ }
2057
+ console.error('WARN: done 任务 ' + t.id + ' 缺少 ' + t.id + '-SUMMARY.md——subagent-execute 产物不完整(任务完成须有对应 SUMMARY)');
2058
+ }
2059
+ }
2060
+ } catch {}
2061
+ }
2062
+ // 多趟完成判定(完成判定谓词决策·合取语义)——subagent-execute 每趟出口校验:
2063
+ // ① 可委托集合必须为空:仍存在 p(parallel ∧ pending ∧ deps⊆done)→ 本趟未委派完即退 →
2064
+ // BLOCK「尚有可委托并行任务(继续委托)」(AC-1:每趟委托全部依赖已满足的并行任务);
2065
+ // ② 孤儿并行单独区分文案:parallel ∧ pending 且依赖链无法满足(直接依赖缺失,或陷入依赖环/
2066
+ // 被环传递拖累)→ BLOCK「孤儿并行任务依赖无法满足(检查 depends_on)」——数据异常 fail-closed,
2067
+ // 防静默跳过(三重防呆决策之二)。
2068
+ // serial pending 不阻断:合法趟间态(回 execute 消化串行)——最终完成的另一支「无 serial pending」
2069
+ // 由 execute 出口的串行 pending 校验把关,两支在流程推进中自然合取。
2070
+ if (node.id === 'subagent-execute' && state.activeChange) {
2071
+ try {
2072
+ const mpContent = await fs.readFile(path.join(runRoot, '.specs', state.activeChange, 'TASK.md'), 'utf8');
2073
+ const mpBlocks = extractTaskBlocks(mpContent);
2074
+ const mpDoneIds = new Set(mpBlocks
2075
+ .map(taskOpeningAttrs)
2076
+ .filter((a) => a && a.status === 'done' && a.id)
2077
+ .map((a) => a.id));
2078
+ const delegable = eligibleParallelBlocks(mpBlocks, mpDoneIds);
2079
+ if (delegable.length > 0) {
2080
+ console.error('BLOCKED: 尚有可委托并行任务(继续委托): ' + delegable
2081
+ .map((b) => (taskOpeningAttrs(b) || {}).id).join(', ') +
2082
+ '——多趟语义下每趟须委派全部依赖已满足的并行任务后才能退出');
2083
+ console.error('恢复: 继续委托上述任务(子代理回传 Return Contract 后再 exit);若确需提前收尾,先调整其 depends_on 使其脱离可委派状态');
2084
+ process.exit(1);
2085
+ }
2086
+ const mpGraph = analyzeDependencyGraph(mpBlocks);
2087
+ const parallelPending = mpBlocks.filter((b) => {
2088
+ const a = taskOpeningAttrs(b);
2089
+ return a && a.parallel && a.status === 'pending';
2090
+ });
2091
+ let orphans = [];
2092
+ if (mpGraph.cyclic || mpGraph.missing.length > 0) {
2093
+ // doomed 闭包:直接依赖缺失的任务 ∪ 环上/被环拖累的任务,再传递扩散到一切(传递)依赖它们
2094
+ // 的任务——这些任务永远进不了可委派状态,一并视为孤儿。
2095
+ const doomed = new Set(mpGraph.cycleIds);
2096
+ for (const m of mpGraph.missing) doomed.add(m.id);
2097
+ let changed = true;
2098
+ while (changed) {
2099
+ changed = false;
2100
+ for (const [id, deps] of mpGraph.depsById) {
2101
+ if (doomed.has(id)) continue;
2102
+ if (deps.some((d) => doomed.has(d))) { doomed.add(id); changed = true; }
2103
+ }
2104
+ }
2105
+ orphans = parallelPending.filter((b) => {
2106
+ const a = taskOpeningAttrs(b);
2107
+ return a && a.id && doomed.has(a.id);
2108
+ });
2109
+ }
2110
+ if (orphans.length > 0) {
2111
+ console.error('BLOCKED: 孤儿并行任务依赖无法满足(检查 depends_on): ' + orphans
2112
+ .map((b) => (taskOpeningAttrs(b) || {}).id).join(', ') +
2113
+ '——依赖引用了不存在的任务或陷入依赖环,永远无法进入可委派状态');
2114
+ console.error('恢复: 调整这些任务的 depends_on——指向真实存在且无环的任务 id 后重试;依赖环应在 plan 出口被前置拦截,执行期出现请核对 TASK.md 是否被手改');
2115
+ process.exit(1);
2116
+ }
2117
+ } catch {}
2118
+ }
2119
+ // exit 协议声明标记校验——节点 exit 时扫描 .specs/<change-id>/.skill-loads/ 下该节点标记
2120
+ // (<node>-*.json,执行者加载节点 skill 后经 skill-load 写入,含 protocol 字段——指向
2121
+ // flow-kit/prompts/ 协议文件,只读引用),校验至少一个标记的 protocol ∈ 该节点协议集(节点协议映射表)。
2122
+ // 缺失 → BLOCKED(提示缺协议声明标记 + 指引 skill-load --prompt);有 → 通过。
2123
+ // 诚实边界:标记是执行者的自我声明——校验只确认「声明存在且 protocol 归属节点」,
2124
+ // 无法证明执行者真的阅读了协议(声明非物理证明,仅保证协议阅读声明可追溯)。
2125
+ // 旧 change 兼容:旧 change/旧 evidence 不追溯——.skill-loads/ 目录不存在(该 change 从未运行过
2126
+ // skill-load,声明机制未激活)→ 跳过校验;节点已 exit 不重验(校验只在当前 exit 时执行);
2127
+ // 节点重新 exit(重入后再退)时按新规则要求,无豁免。
2128
+ if (state.activeChange && NODE_PROTOCOL_FILES[node.id]) {
2129
+ // 标记目录活动/归档双路径解析(archive 节点「先移目录后 exit」顺序下标记只在
2130
+ // 归档路径——单查活动路径会误报「机制未激活」静默放行);两处皆无才走旧 change 兼容
2131
+ const loadsDir = await findSkillLoadsDir(runRoot, state.activeChange);
2132
+ if (loadsDir) {
2133
+ const prefix = node.id + '-';
2134
+ const protocolSet = NODE_PROTOCOL_FILES[node.id];
2135
+ const markers = (await fs.readdir(loadsDir.dir).catch(() => []))
2136
+ .filter((f) => f.startsWith(prefix) && f.endsWith('.json'));
2137
+ const malformed = [];
2138
+ let declared = false;
2139
+ for (const f of markers) {
2140
+ try {
2141
+ const marker = JSON.parse(await fs.readFile(path.join(loadsDir.dir, f), 'utf8'));
2142
+ // 比对 basename——新格式(skill-load 写入 basename)与旧格式(完整绝对路径)
2143
+ // 经 markerProtocolBasename 提取后统一比对;损坏值(null/非字符串/超集外 basename)
2144
+ // 提取为 null 或不匹配 → 不进 declared,fail-closed
2145
+ if (marker && typeof marker === 'object' && protocolSet.includes(markerProtocolBasename(marker.protocol))) {
2146
+ declared = true;
2147
+ // R3: auto 标记提示——record 自动补的标记(auto:true)不证明手动加载,提示建议手动声明
2148
+ if (marker.auto === true) {
2149
+ console.error('SKILL-LOAD HINT: ' + f + ' 为 record 自动补写标记(auto)——建议手动 skill-load 声明(如实记录加载动作与协议文件)');
2150
+ }
2151
+ break;
2152
+ }
2153
+ } catch {
2154
+ malformed.push(f);
2155
+ }
2156
+ }
2157
+ if (!declared) {
2158
+ console.error('BLOCKED: 节点 ' + node.id + ' exit 缺协议声明标记——' + loadsDir.display +
2159
+ ' 下需有 ' + prefix + '*.json 且 protocol ∈ [' + protocolSet.join(', ') +
2160
+ '];执行 skill-load --prompt <flow-kit/prompts/ 协议文件> 声明已阅读协议(声明非物理证明,仅可追溯)' +
2161
+ (malformed.length > 0 ? ';不可解析标记: ' + malformed.join(', ') : ''));
2162
+ process.exit(1);
2163
+ }
2164
+ } else {
2165
+ // 旧 change 兼容 过渡规则:旧 change 兼容——活动与归档路径均无声明标记目录(机制未激活)不追溯;
2166
+ // 首个 skill-load 写入后新规则生效(该 change 后续节点 exit 均需声明标记)
2167
+ console.error('SKILL-LOAD WARN: 旧 change 兼容——.specs/' + state.activeChange +
2168
+ '/.skill-loads/(活动与归档路径)不存在,协议声明校验跳过(机制未激活;首个 skill-load 后新规则生效)');
2169
+ }
2170
+ }
2171
+
2172
+ // ===== M1: SUMMARY 模板保真(execute / subagent-execute 出口·设计语义 / AC-7)=====
2173
+ // 每份 *-SUMMARY.md 校 ① 标题首行 # SUMMARY: ② 首部 4 字段(Change ID/Task ID/完成时间/AI 角色)
2174
+ // ③ 段序(做了什么→改动文件→verify 输出→6 维自查→…→自检方法);宽容匹配(大小写/编号前缀/括号后缀)。
2175
+ // 新 change 任一缺失 → BLOCK(含缺失点 + 恢复指引);旧 change/归档批 → WARN 渐进。
2176
+ if (node.id === 'execute' || node.id === 'subagent-execute') {
2177
+ const summaryChangeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
2178
+ const summaryFiles = (await fs.readdir(summaryChangeDir).catch(() => [])).filter((f) => f.endsWith('-SUMMARY.md'));
2179
+ const hardIssues = [];
2180
+ for (const f of summaryFiles) {
2181
+ try {
2182
+ const fidelity = summaryTemplateFidelity(await fs.readFile(path.join(summaryChangeDir, f), 'utf8'));
2183
+ const problems = [];
2184
+ if (fidelity.titleMissing) {
2185
+ problems.push('首行缺 `# SUMMARY: <Task>-<名>` 标题(大小写不敏感,标题可带括号说明后缀)');
2186
+ }
2187
+ if (fidelity.headerMissing.length > 0) {
2188
+ problems.push('首部缺字段: ' + fidelity.headerMissing.join('、'));
2189
+ }
2190
+ if (fidelity.orderIssue) {
2191
+ problems.push('段序乱(「' + fidelity.orderIssue.replace(/^##\s*/, '') +
2192
+ '」偏离模板段序——应为 做了什么→改动文件→verify 输出→6 维自查→越界检查→自检方法)');
2193
+ }
2194
+ if (fidelity.missingSections.length > 0) {
2195
+ problems.push('缺段: ' + fidelity.missingSections.join('、'));
2196
+ }
2197
+ if (problems.length > 0) {
2198
+ if (isNewChange(state)) {
2199
+ hardIssues.push(f + ' 模板保真校验失败: ' + problems.join('; '));
2200
+ } else {
2201
+ console.error('SUMMARY TEMPLATE WARN: ' + f + ' ' + problems.join('; ') +
2202
+ '(旧 change/归档批渐进,不阻断;新 change 将强制)');
2203
+ }
2204
+ }
2205
+ } catch {}
2206
+ }
2207
+ if (hardIssues.length > 0) {
2208
+ console.error('BLOCKED: SUMMARY 模板保真校验失败: ' + hardIssues.join('; '));
2209
+ console.error('恢复: 对照 flow-kit/templates/SUMMARY.md 修正标题/首部/段序(含 flow-comet 增量 ## 自检方法 段)后重试 exit;新 change 强制模板保真');
2210
+ process.exit(1);
2211
+ }
2212
+ }
2213
+
2214
+ // ===== M2: TASK 7 字段完整性(plan 出口·设计语义 / AC-8)=====
2215
+ // 每个 <task> 块须含 name/read_files/write_files/action/verify/done/depends_on;缺任一 → 新 BLOCK / 旧 WARN。
2216
+ // 开标签解析/整块提取沿用 task-parsing.mjs(属性序无关)。宽容:任务块采用旧式一字段形态(无 <name> 标记)
2217
+ // 的 TASK 视为旧格式 → 仅渐进 WARN(不误拦既有波次/路由回归载体);采用新模板形态(含 <name>)则按 7 字段强校验。
2218
+ if (node.id === 'plan' && state.activeChange) {
2219
+ const task7File = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
2220
+ try {
2221
+ const task7Blocks = extractTaskBlocks(await fs.readFile(task7File, 'utf8'));
2222
+ const TASK7_REQUIRED = ['name', 'read_files', 'write_files', 'action', 'verify', 'done', 'depends_on'];
2223
+ const planNewFormat = task7Blocks.some((b) => /<name\b/i.test(b));
2224
+ const broken = [];
2225
+ for (const b of task7Blocks) {
2226
+ const missing = TASK7_REQUIRED.filter((field) => !new RegExp('</?' + field + '\\b', 'i').test(b));
2227
+ if (missing.length > 0) {
2228
+ const idAttr = (taskOpeningAttrs(b) || {})?.id || '?';
2229
+ broken.push((idAttr && idAttr !== '?' ? idAttr + ' ' : '') + '缺 ' + missing.join('/'));
2230
+ }
2231
+ }
2232
+ if (broken.length > 0) {
2233
+ if (planNewFormat) {
2234
+ if (isNewChange(state)) {
2235
+ console.error('BLOCKED: TASK.md 任务缺 7 字段(name/read_files/write_files/action/verify/done/depends_on): ' + broken.join('; '));
2236
+ console.error('恢复: 对照 flow-kit/templates/TASK.md 补齐每个 <task> 的缺字段后重试 exit;新 change 强制任务块结构完整');
2237
+ process.exit(1);
2238
+ }
2239
+ console.error('TASK-7FIELD WARN: TASK.md ' + broken.join('; ') + '(旧 change 渐进,不阻断;新 change 将强制补齐 7 字段)');
2240
+ } else {
2241
+ console.error('TASK-7FIELD WARN: TASK.md 任务为旧式一字段模板形态(' + broken.join('; ') +
2242
+ ')——建议按 flow-kit/templates/TASK.md 补全 7 字段(渐进不阻断)');
2243
+ }
2244
+ }
2245
+ } catch {}
2246
+ }
2247
+
2248
+ // ===== M3: CHANGE/REQUIREMENT/DESIGN 模板保真(open / design 出口·设计语义 / AC-9)=====
2249
+ // 标题与模板一致(# CHANGE: / # REQUIREMENT: / # DESIGN:,大小写不敏感、冒号可省)+ 段序按模板派生骨架宽容匹配
2250
+ // (编号前缀/括号后缀兼容);首部必要字段(Change ID)缺失 → 渐进 WARN。新 change 标题/段序失配 → BLOCK + 恢复指引;
2251
+ // 旧 change/归档批 → WARN 渐进。
2252
+ if ((node.id === 'open' || node.id === 'design') && state.activeChange) {
2253
+ const intakeDir = path.join(runRoot, '.specs', state.activeChange);
2254
+ const skeletonsCache = {};
2255
+ const hardProblems = [];
2256
+ const softWarnings = [];
2257
+ const checkIntakeDoc = async (file, key, label, titleRe) => {
2258
+ const p = path.join(intakeDir, file);
2259
+ if (!(await fileExists(p))) return; // 文件缺失由产物校验兜底
2260
+ const text = await fs.readFile(p, 'utf8');
2261
+ const firstLine = (text.replace(/\uFEFF/g, '').split('\n').find((l) => l.trim().length > 0) || '').trim();
2262
+ if (!titleRe.test(firstLine)) {
2263
+ hardProblems.push(file + ' 标题应以 # ' + label + ' 开头(如 `# ' + label + ': <标题>`,大小写不敏感、冒号可省)');
2264
+ }
2265
+ if (!skeletonsCache[key]) skeletonsCache[key] = await templateSkeleton(key);
2266
+ const viol = templateOrderViolation(skeletonsCache[key], documentSectionHeadings(text));
2267
+ if (viol) {
2268
+ hardProblems.push(file + ' 段序乱(「' + String(viol).replace(/^##\s*/, '') + '」偏离 ' + label + ' 模板段序)');
2269
+ }
2270
+ const changeIdMissing = !/\*\*\s*Change\s+ID\s*\*\*/i.test(text.split(/\n##\s/)[0]);
2271
+ const intakeMsg = file + ' 首部缺 Change ID 字段(' + label + ' 模板首部含 `- **Change ID**: <id>`)';
2272
+ if (changeIdMissing) {
2273
+ if (isNewChange(state)) hardProblems.push(intakeMsg);
2274
+ else softWarnings.push(intakeMsg + '(渐进提示;新 change 将强制)');
2275
+ }
2276
+ };
2277
+ if (node.id === 'open') {
2278
+ await checkIntakeDoc('CHANGE.md', 'change', 'CHANGE', /^#\s*change\b/i);
2279
+ await checkIntakeDoc('REQUIREMENT.md', 'requirement', 'REQUIREMENT', /^#\s*requirement\b/i);
2280
+ } else {
2281
+ // design:与既有校验一致的 target 选择(DESIGN.md 优先,DESIGN-lite 兜底)
2282
+ const designFile = path.join(intakeDir, 'DESIGN.md');
2283
+ const designLite = path.join(intakeDir, 'DESIGN-lite.md');
2284
+ const chosen = (await fileExists(designFile)) ? 'DESIGN.md' : ((await fileExists(designLite)) ? 'DESIGN-lite.md' : null);
2285
+ if (chosen) await checkIntakeDoc(chosen, 'design', 'DESIGN', /^#\s*design\b/i);
2286
+ }
2287
+ for (const w of softWarnings) console.error('INTAKE-DOC WARN: ' + w + '(渐进提示,不阻断;新 change 同)');
2288
+ if (hardProblems.length > 0) {
2289
+ if (isNewChange(state)) {
2290
+ console.error('BLOCKED: 入口文档模板保真校验失败: ' + hardProblems.join('; '));
2291
+ console.error('恢复: 对照 flow-kit/templates/{CHANGE,REQUIREMENT,DESIGN}.md 修正标题与段序后重试 exit;新 change 强制模板保真');
2292
+ process.exit(1);
2293
+ }
2294
+ for (const h of hardProblems) console.error('INTAKE-DOC WARN: ' + h + '(旧 change/归档批渐进,不阻断;新 change 将强制)');
2295
+ }
2296
+ }
2297
+
2298
+ // 自动补 required-skill completedChecks——节点被完成即视为其实现 skill 已加载
2299
+ if ((node.requiredSkillCalls ?? []).length > 0) {
2300
+ const checks = Array.isArray(evidence.completedChecks) ? evidence.completedChecks : [];
2301
+ for (const binding of node.requiredSkillCalls ?? []) {
2302
+ const check = 'required-skill:' + node.id + '.' + binding.skill;
2303
+ if (!checks.includes(check)) checks.push(check);
2304
+ }
2305
+ evidence.completedChecks = checks;
2306
+ }
2307
+ const missingSchemaEvidence = missingRequiredSchemaEvidence(protocol, node, evidence);
2308
+ if (missingSchemaEvidence.length > 0) {
2309
+ console.error('BLOCKED: missing Output Schema evidence: ' + missingSchemaEvidence.join(', '));
2310
+ process.exit(1);
2311
+ }
2312
+ // M6: execute 显式空退出豁免——evidence.execute.emptyExitApproved 时跳过产物校验(全 parallel 无 SUMMARY 属预期)
2313
+ const missingArtifacts = (node.id === 'execute' && state.evidence?.execute?.emptyExitApproved)
2314
+ ? [] : await missingRequiredArtifacts(protocol, node, state.activeChange);
2315
+ if (missingArtifacts.length > 0) {
2316
+ console.error('BLOCKED: missing Output Schema artifacts: ' + missingArtifacts.join(', '));
2317
+ process.exit(1);
2318
+ }
2319
+ const missingRequired = missingRequiredSkillChecks(node, evidence);
2320
+ if (missingRequired.length > 0) {
2321
+ console.error('BLOCKED: missing required Skill evidence: ' + missingRequired.join(', '));
2322
+ process.exit(1);
2323
+ }
2324
+ const missingAugmentations = missingAugmentationChecks(node, evidence);
2325
+ if (missingAugmentations.length > 0) {
2326
+ console.error('BLOCKED: missing augmentation evidence: ' + missingAugmentations.join(', '));
2327
+ process.exit(1);
2328
+ }
2329
+ if (apply) {
2330
+ const completed = completedSet(state);
2331
+ completed.add(node.id);
2332
+ // W2-A: verify exit --apply 成功 → 当前 change 的 verifyFailures 清零
2333
+ if (node.id === 'verify') setVerifyFailuresFor(state, 0);
2334
+ state.completedNodes = route(protocol).filter((item) => completed.has(item.id)).map((item) => item.id);
2335
+ // archive 节点完成后 change 已归档 → 清空活跃 change(flow-comet 回到无活跃状态)
2336
+ const isArchive = node.id === 'archive';
2337
+ if (isArchive) state.activeChange = null;
2338
+ let next = isArchive ? null : await nextNode(protocol, state);
2339
+ // 多趟路由诊断保留(展示层,不并入共享判定):出口推进后下一候选非委托节点时,若任务集存在
2340
+ // parallel 标记任务与任一 pending 任务但无 pending parallel 可委托块,输出路由诊断提示。
2341
+ // 静默边界(M4 批次扩展):(a) 全部任务 done 时无 pending 不输出(收尾静默锚);
2342
+ // (b) 剩余 pending 全为串行且各 parallel 块均带 status(结构正常、P→S 收尾转换)→ 静默
2343
+ // (「全 done 静默」扩展为「全串行剩余」也静默);(c) 存在「parallel 缺 status」的
2344
+ // 畸形/旧模板块且仍有 pending → 仍报(结构校验严格,缺 status 不视为 pending,
2345
+ // 不因扩展误静音——反过静音锚)。路由决策本身由 resolveNextNode 单一实现(不维护第二份并行镜像)。
2346
+ if (next && next.id !== 'subagent-execute' && state.activeChange) {
2347
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
2348
+ try {
2349
+ const taskContent = await fs.readFile(taskFile, 'utf8');
2350
+ const taskList = extractTaskBlocks(taskContent);
2351
+ const hasParallelTag = taskList.some((block) => {
2352
+ const a = taskOpeningAttrs(block);
2353
+ return a && a.parallel;
2354
+ });
2355
+ const hasPending = taskList.some((block) => {
2356
+ const a = taskOpeningAttrs(block);
2357
+ return a && a.status === 'pending';
2358
+ });
2359
+ const hasParallelPending = taskList.some((block) => {
2360
+ const a = taskOpeningAttrs(block);
2361
+ return a && a.parallel && a.status === 'pending';
2362
+ });
2363
+ // 畸形/旧模板信号:parallel 标记但缺 status 属性(无法分类为 done/pending——缺 status
2364
+ // 不视为 pending;这正是诊断要提示的检查点)。taskOpeningAttrs 缺属性时 status 返回 null,
2365
+ // 故判 `status == null`(null 或 undefined 双容)。
2366
+ const hasParallelMissingStatus = taskList.some((block) => {
2367
+ const a = taskOpeningAttrs(block);
2368
+ return a && a.parallel && (a.status === null || a.status === undefined);
2369
+ });
2370
+ if (hasPending && hasParallelTag && !hasParallelPending && hasParallelMissingStatus) {
2371
+ console.error('ROUTE WARN: 未找到 parallel="true" status="pending" 的任务块——存在 parallel="true" 但缺 status 属性的任务块(缺 status 不视为 pending、无法参与委托判定),检查 task 开标签的 parallel/status 属性(属性序无关)');
2372
+ }
2373
+ } catch {}
2374
+ }
2375
+ state.currentNode = isArchive ? null : (next?.id ?? null);
2376
+ state.status = next ? 'running' : 'completed';
2377
+ state.history = Array.isArray(state.history) ? state.history : [];
2378
+ state.history.push({ event: 'exit-applied', node: node.id, at: new Date().toISOString() });
2379
+ const bad = validateStateFields(state);
2380
+ if (bad.length) { console.error('BLOCKED: state 字段类型非法: ' + bad[0]); process.exit(1); }
2381
+ await writeJson(file, state);
2382
+ console.log('ALL CHECKS PASSED');
2383
+ printNext(protocol, next);
2384
+ return;
2385
+ }
2386
+ console.log('ALL CHECKS PASSED');
2387
+ console.log('APPLY: rerun with --apply to update workflow state');
2388
+ }
2389
+
2390
+ main().then(() => {
2391
+ // 成功路径末尾输出 WARN COUNT 汇总(用未包装的 console.error——避免自增)
2392
+ if (__warnCount > 0) __origError('WARN COUNT: ' + __warnCount);
2393
+ }).catch((error) => {
2394
+ console.error(error.message);
2395
+ process.exit(1);
2396
+ });