flow-comet 1.6.3 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  2. package/.flow-comet/skills/flow-comet/SKILL.md +21 -3
  3. package/.flow-comet/skills/flow-comet/reference/artifact-template-overlay.md +154 -0
  4. package/.flow-comet/skills/flow-comet/reference/artifact-templates.json +387 -0
  5. package/.flow-comet/skills/flow-comet/reference/entry-detail.md +8 -2
  6. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +22 -0
  7. package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +11 -13
  8. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +2 -2
  9. package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +180 -6
  10. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +69 -18878
  11. package/.flow-comet/skills/flow-comet/scripts/health.mjs +29 -5
  12. package/.flow-comet/skills/flow-comet/scripts/items/a.mjs +1053 -0
  13. package/.flow-comet/skills/flow-comet/scripts/items/b.mjs +830 -0
  14. package/.flow-comet/skills/flow-comet/scripts/items/c.mjs +781 -0
  15. package/.flow-comet/skills/flow-comet/scripts/items/d.mjs +99 -0
  16. package/.flow-comet/skills/flow-comet/scripts/items/e.mjs +185 -0
  17. package/.flow-comet/skills/flow-comet/scripts/items/f.mjs +90 -0
  18. package/.flow-comet/skills/flow-comet/scripts/items/g.mjs +59 -0
  19. package/.flow-comet/skills/flow-comet/scripts/items/h.mjs +817 -0
  20. package/.flow-comet/skills/flow-comet/scripts/items/i.mjs +77 -0
  21. package/.flow-comet/skills/flow-comet/scripts/items/j.mjs +75 -0
  22. package/.flow-comet/skills/flow-comet/scripts/items/k.mjs +1427 -0
  23. package/.flow-comet/skills/flow-comet/scripts/items/l.mjs +275 -0
  24. package/.flow-comet/skills/flow-comet/scripts/items/m.mjs +618 -0
  25. package/.flow-comet/skills/flow-comet/scripts/items/n.mjs +154 -0
  26. package/.flow-comet/skills/flow-comet/scripts/lib/count-derivation.mjs +97 -0
  27. package/.flow-comet/skills/flow-comet/scripts/lib/fix-loop-node.mjs +196 -0
  28. package/.flow-comet/skills/flow-comet/scripts/lib/guard-artifact-skeleton.mjs +406 -0
  29. package/.flow-comet/skills/flow-comet/scripts/lib/guard-evidence-gates.mjs +756 -0
  30. package/.flow-comet/skills/flow-comet/scripts/lib/guard-gates.mjs +1235 -0
  31. package/.flow-comet/skills/flow-comet/scripts/lib/guard-routing.mjs +384 -0
  32. package/.flow-comet/skills/flow-comet/scripts/lib/guard-state-io.mjs +404 -0
  33. package/.flow-comet/skills/flow-comet/scripts/lib/guard-template-fidelity.mjs +714 -0
  34. package/.flow-comet/skills/flow-comet/scripts/lib/guard-uidesign.mjs +204 -0
  35. package/.flow-comet/skills/flow-comet/scripts/lib/reentry-node.mjs +237 -0
  36. package/.flow-comet/skills/flow-comet/scripts/lib/replan-node.mjs +209 -0
  37. package/.flow-comet/skills/flow-comet/scripts/lib/state-branch.mjs +49 -0
  38. package/.flow-comet/skills/flow-comet/scripts/lib/state-bridgecheck.mjs +201 -0
  39. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-admin.mjs +179 -0
  40. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-flow.mjs +714 -0
  41. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-recovery.mjs +578 -0
  42. package/.flow-comet/skills/flow-comet/scripts/lib/state-determine.mjs +52 -0
  43. package/.flow-comet/skills/flow-comet/scripts/lib/state-evolve-hint.mjs +55 -0
  44. package/.flow-comet/skills/flow-comet/scripts/lib/state-explain.mjs +123 -0
  45. package/.flow-comet/skills/flow-comet/scripts/lib/state-intelscan.mjs +58 -0
  46. package/.flow-comet/skills/flow-comet/scripts/lib/state-io.mjs +147 -0
  47. package/.flow-comet/skills/flow-comet/scripts/lib/state-skillmarkers.mjs +249 -0
  48. package/.flow-comet/skills/flow-comet/scripts/lib/system-fixtures.mjs +1505 -0
  49. package/.flow-comet/skills/flow-comet/scripts/lib/task-graph.mjs +471 -0
  50. package/.flow-comet/skills/flow-comet/scripts/lib/test-assertions.mjs +509 -0
  51. package/.flow-comet/skills/flow-comet/scripts/lib/test-fixtures.mjs +1248 -0
  52. package/.flow-comet/skills/flow-comet/scripts/lib/test-helpers.mjs +237 -0
  53. package/.flow-comet/skills/flow-comet/scripts/lib/text-anchor-checks.mjs +2493 -0
  54. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +214 -2
  55. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +72 -1123
  56. package/.flow-comet/skills/flow-comet/scripts/scenarios/a.mjs +976 -0
  57. package/.flow-comet/skills/flow-comet/scripts/scenarios/b.mjs +1233 -0
  58. package/.flow-comet/skills/flow-comet/scripts/scenarios/c.mjs +1382 -0
  59. package/.flow-comet/skills/flow-comet/scripts/scenarios/d.mjs +483 -0
  60. package/.flow-comet/skills/flow-comet/scripts/scenarios/e.mjs +1398 -0
  61. package/.flow-comet/skills/flow-comet/scripts/scenarios/f.mjs +1466 -0
  62. package/.flow-comet/skills/flow-comet/scripts/scenarios/g.mjs +1367 -0
  63. package/.flow-comet/skills/flow-comet/scripts/scenarios/h.mjs +1287 -0
  64. package/.flow-comet/skills/flow-comet/scripts/scenarios/i.mjs +1436 -0
  65. package/.flow-comet/skills/flow-comet/scripts/scenarios/j.mjs +1384 -0
  66. package/.flow-comet/skills/flow-comet/scripts/scenarios/k.mjs +1338 -0
  67. package/.flow-comet/skills/flow-comet/scripts/scenarios/l.mjs +1492 -0
  68. package/.flow-comet/skills/flow-comet/scripts/scenarios/m.mjs +971 -0
  69. package/.flow-comet/skills/flow-comet/scripts/scenarios/n.mjs +2125 -0
  70. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +1 -1
  71. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +59 -7559
  72. package/.flow-comet/skills/flow-comet/scripts/time-utils.mjs +4 -4
  73. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +223 -2476
  74. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +5 -5
  75. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +27 -2190
  76. package/.flow-comet/skills/flow-comet-archive/SKILL.md +6 -2
  77. package/.flow-comet/skills/flow-comet-change/SKILL.md +6 -2
  78. package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +13 -3
  79. package/.flow-comet/skills/flow-comet-design/SKILL.md +15 -8
  80. package/.flow-comet/skills/flow-comet-dev/SKILL.md +1 -1
  81. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +1 -0
  82. package/.flow-comet/skills/flow-comet-execute/SKILL.md +13 -10
  83. package/.flow-comet/skills/flow-comet-health/SKILL.md +1 -1
  84. package/.flow-comet/skills/flow-comet-integration/SKILL.md +1 -1
  85. package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +14 -4
  86. package/.flow-comet/skills/flow-comet-open/SKILL.md +11 -9
  87. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +13 -3
  88. package/.flow-comet/skills/flow-comet-plan/SKILL.md +11 -7
  89. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +1 -1
  90. package/.flow-comet/skills/flow-comet-review/SKILL.md +15 -9
  91. package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +13 -3
  92. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +11 -8
  93. package/.flow-comet/skills/flow-comet-task/SKILL.md +1 -1
  94. package/.flow-comet/skills/flow-comet-test/SKILL.md +6 -2
  95. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +2 -2
  96. package/.flow-comet/skills/flow-comet-verify/SKILL.md +12 -8
  97. package/README.md +52 -69
  98. package/package.json +3 -2
  99. package/scripts/dsh-bridge.mjs +2 -2
  100. package/scripts/lib/installer-cleanup.mjs +152 -0
  101. package/scripts/lib/installer-flowkit.mjs +159 -0
  102. package/scripts/lib/installer-hooks.mjs +363 -0
  103. package/scripts/lib/installer-loader.mjs +220 -0
  104. package/scripts/lib/installer-migrate.mjs +236 -0
  105. package/scripts/lib/installer-platforms.mjs +314 -0
  106. package/scripts/prepare-env.mjs +21 -1313
@@ -0,0 +1,756 @@
1
+ // 证据与产物门禁(守卫模块):直显授权约束、在飞委托、SUMMARY 必填段与自检方法、LESSONS 扫描段
2
+ // 与命中核对、execute 出口、
3
+ // verify 出口(真实执行验证命令并记录失败计数)、Return Contract、subagent-execute 摘要与多趟完成
4
+ // 判定、required-skill / schema / 产物 存在性门禁——即「完成声明必须有证据与产物」这一族判据。
5
+ //
6
+ // 分级沿用既有语义:新 change(init 标记)强制 BLOCKED + 恢复指引,旧 change 渐进 WARN 不阻断。
7
+
8
+ import { promises as fs } from 'fs';
9
+ import path from 'path';
10
+ import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor } from '../state-schema.mjs';
11
+ import { EXECUTE_FAMILY_NODE_IDS, analyzeDependencyGraph, normalizeHeading } from '../route-node.mjs';
12
+ import { taskOpeningAttrs, taskBlocks as extractTaskBlocks } from '../task-parsing.mjs';
13
+ import { runRoot, fileExists, statePath, writeJson } from './guard-state-io.mjs';
14
+ import {
15
+ eligibleParallelBlocks,
16
+ inFlightHandoffRequests,
17
+ isArchivedChange,
18
+ isNewChange,
19
+ missingAugmentationChecks,
20
+ missingRequiredArtifacts,
21
+ missingRequiredSchemaEvidence,
22
+ missingRequiredSkillChecks,
23
+ taskDependsOn,
24
+ verifySummaries,
25
+ } from './guard-routing.mjs';
26
+ import { applicabilityGatedBinding, frontendCriterion } from './guard-uidesign.mjs';
27
+ import { buildSkeleton, headingPattern, LESSONS_SCAN_SECTION } from './guard-artifact-skeleton.mjs';
28
+
29
+ // directOverride 授权约束(direct 是用户决策点,不可自决——机制约束)——execute / subagent-execute
30
+ // 出口校验:executionMode=direct 且 directOverride=true(显式直显授权态)须存在授权审计记录
31
+ // (directOverrideAt/来源,由 workflow-state execution-mode 命令在协调者显式授权时写入)——否则
32
+ // BLOCKED + 恢复指引(协调者显式授权 / 回 subagent)。旧 state 缺省(directOverride=false / 缺字段)
33
+ // 放行(前向兼容——未处于显式 direct 不受影响)。
34
+ export function runDirectOverrideGate({ node, state }) {
35
+ if (!EXECUTE_FAMILY_NODE_IDS.has(node.id) || !state.activeChange) return;
36
+ const directMode = state.executionMode ?? 'subagent';
37
+ if (directMode === 'direct' && state.directOverride === true) {
38
+ const hasAuditRecord = typeof state.directOverrideAt === 'string'
39
+ && state.directOverrideAt.trim() !== '';
40
+ if (!hasAuditRecord) {
41
+ console.error('BLOCKED: executionMode=direct 且 directOverride=true 但无授权审计记录(direct 是用户决策点,不可自决——须存在授权留痕 directOverrideAt/来源,由协调者显式 execution-mode direct 写入)');
42
+ console.error('恢复: 由协调者执行 workflow-state.mjs execution-mode direct 显式授权(写入授权审计记录)后重试 exit;或 execution-mode subagent 切回(清除 directOverride)后重试 exit;禁止手改 state 机器字段');
43
+ process.exit(1);
44
+ }
45
+ }
46
+ }
47
+
48
+ // 验证隔离「同一时刻只有一个写者」出口校验——读 state.evidence['subagent-execute'].handoffRequests:
49
+ // 存在条目且**至少一个无对应 handoffResult** ⇒ 在飞委托(写者未收工,跑全量判据会被未提交中间态
50
+ // 污染):新 change BLOCKED(含恢复指引「待写入者收工后重跑 / 已作废则撤回」)/ 旧 change WARN 渐进;
51
+ // 全部有对应 result ⇒ 放行;已撤回(withdrawnAt + withdrawnBy 齐备)的 request 不构成在飞委托 ⇒
52
+ // 放行;无该证据对象 ⇒ 零输出。落点 = 出口校验流(与其余 violations / WARN 同风格,不新增独立命令
53
+ // 面);判据经 inFlightHandoffRequests 单处求值(与 Return Contract 的 result 侧契约校验正交,不
54
+ // 重复判定)。
55
+ export function runInFlightHandoffGate({ node, state }) {
56
+ if (!EXECUTE_FAMILY_NODE_IDS.has(node.id)) return;
57
+ const inFlight = inFlightHandoffRequests(state.evidence?.['subagent-execute']);
58
+ if (inFlight.length > 0) {
59
+ const inFlightDetail = '存在在飞委托(handoffRequests 有 request 无对应 handoffResult): '
60
+ + inFlight.join(', ') + '——验证隔离要求同一时刻只有一个写者(写者未收工)';
61
+ if (isNewChange(state)) {
62
+ console.error('BLOCKED: ' + inFlightDetail);
63
+ console.error('恢复: 待写入者收工后重跑——子代理回传后用 workflow-handoff.mjs result <task-id> <Return Contract> 记录结果再重试 exit;若该委托已作废(零提交复验失败 / 写边界被拒后遗弃),用 workflow-handoff.mjs withdraw <task-id> --by <来源> [--reason <原因>] 撤回后再重试 exit(撤回留痕 withdrawnAt/withdrawnBy,已撤回 = 终态,历史不删)');
64
+ process.exit(1);
65
+ }
66
+ console.error('WARN: ' + inFlightDetail + '(旧 change 渐进不阻断;待写入者收工后重跑全量判据;已作废的委托可用 workflow-handoff.mjs withdraw <task-id> --by <来源> 撤回)');
67
+ }
68
+ }
69
+
70
+ // ---------- LESSONS 扫描(R1.8 · AC-18:开工前扫描可核对)----------
71
+ //
72
+ // 两条判据:① 每份 *-SUMMARY.md 含 `## LESSONS 扫描` 增量段;② 按任务 write_files 的路径段与该
73
+ // 段内应回应的条目编号(关键词求交、取前 5)必须逐条出现在该段里。段名 / 必填 / 位置三件事都来自
74
+ // 登记表(reference/artifact-templates.json 的 SUMMARY.increments)——位置语义由模板保真门禁按同一
75
+ // 条目执行,本门禁只判「在场 + 命中回应」,不写第二份位置判据(L-067)。
76
+ //
77
+ // 停用词表与命中上限单处定义(段名从骨架模块取用,不在本模块自持第二份清单)。关键词行
78
+ // (`- **关键词**:`)是唯一参与命中计算的字段——无关键词行的旧条目不参与(给旧条目一个不被
79
+ // 误命中的通道)。
80
+ const LESSONS_HIT_LIMIT = 5;
81
+ const LESSONS_PATH_STOPWORDS = new Set([
82
+ // 目录布局噪音
83
+ 'src', 'lib', 'libs', 'app', 'apps', 'core', 'pkg', 'packages', 'bin', 'dist', 'build', 'out',
84
+ 'tmp', 'temp', 'test', 'tests', 'spec', 'specs', 'unit', 'e2e', 'fixture', 'fixtures',
85
+ 'mock', 'mocks', 'docs', 'doc', 'scripts', 'script', 'assets', 'static', 'public',
86
+ 'config', 'configs', 'utils', 'util', 'helpers', 'helper', 'common', 'shared', 'internal',
87
+ 'modules', 'module', 'components', 'pages', 'views', 'styles', 'data', 'types', 'index',
88
+ // 扩展名 / 备份后缀残片
89
+ 'mjs', 'cjs', 'jsx', 'tsx', 'json', 'yaml', 'yml', 'toml', 'lock', 'bak', 'log', 'txt', 'css',
90
+ ]);
91
+
92
+ const LESSONS_ENTRY_HEADING = /^###\s*L-(\d+)\b/u;
93
+ const LESSONS_KEYWORD_LINE = /^[-*\s]*\*\*关键词\*\*\s*[::]\s*(.+)$/u;
94
+
95
+ // 段名 / 必填来自登记表;登记表或模板缺席时退回段名常量并保持必填——扫描段由 AC-18 要求,不因模板
96
+ // 派生失败而免检(「模板缺失」只让模板派生判据跳过,不让扫描声明消失)。
97
+ async function lessonsScanRule() {
98
+ const skeleton = await buildSkeleton('summary');
99
+ const wanted = normalizeHeading(LESSONS_SCAN_SECTION);
100
+ const entry = (skeleton.increments ?? []).find((item) => item.norm === wanted);
101
+ if (entry && entry.kind === 'section') {
102
+ return {
103
+ name: entry.section,
104
+ required: entry.required,
105
+ pattern: entry.pattern ?? headingPattern(entry.section, 2),
106
+ registered: true,
107
+ };
108
+ }
109
+ return { name: LESSONS_SCAN_SECTION, required: true, pattern: headingPattern(LESSONS_SCAN_SECTION, 2), registered: false };
110
+ }
111
+
112
+ // write_files 原文(键 = 任务 id)。块提取与开标签解析复用 task-parsing 的既有实现,只读元素文本。
113
+ async function taskWriteFiles(changeDir) {
114
+ const out = new Map();
115
+ let text = '';
116
+ try {
117
+ text = await fs.readFile(path.join(changeDir, 'TASK.md'), 'utf8');
118
+ } catch {
119
+ return out;
120
+ }
121
+ for (const block of extractTaskBlocks(text)) {
122
+ const attrs = taskOpeningAttrs(block);
123
+ if (!attrs || !attrs.id) continue;
124
+ const writeFiles = block.match(/<write_files>([\s\S]*?)<\/write_files>/i);
125
+ if (writeFiles) out.set(attrs.id, writeFiles[1]);
126
+ }
127
+ return out;
128
+ }
129
+
130
+ // 路径段 → 词元:目录名与文件主干(去最后一层扩展名)按非字母数字切分,长度 ≥3、去停用词、去纯数字。
131
+ // 只在「命中计算」这一侧做长度与停用词过滤——条目关键词侧原样保留,过滤口径不扩散成第二份规则。
132
+ function lessonsPathTokens(writeFilesText) {
133
+ const tokens = new Set();
134
+ for (const raw of String(writeFilesText ?? '').split(/[\n;]+/u)) {
135
+ const segments = raw.trim().replace(/\\/gu, '/').split('/').filter((s) => s !== '' && s !== '.' && s !== '..');
136
+ segments.forEach((segment, index) => {
137
+ const body = index === segments.length - 1 ? segment.replace(/\.[^.]*$/u, '') : segment;
138
+ for (const piece of body.split(/[^0-9A-Za-z\u4e00-\u9fff]+/u)) {
139
+ const token = piece.toLowerCase();
140
+ if ([...token].length < 3) continue;
141
+ if (/^\d+$/u.test(token)) continue;
142
+ if (LESSONS_PATH_STOPWORDS.has(token)) continue;
143
+ tokens.add(token);
144
+ }
145
+ });
146
+ }
147
+ return tokens;
148
+ }
149
+
150
+ // LESSONS 条目:`### L-NNN` 标题开启一个条目,块内 `- **关键词**:` 行的词元即命中输入;下一个 H2
151
+ // 结束条目区(区外的 `###` 不参与)。围栏代码块内是书写样例(模板里的「条目格式」示例即此形态),
152
+ // 按行扫描会被误当成真条目——围栏内一律跳过。无关键词行的条目不进结果集(旧条目跳过)。
153
+ function lessonsEntries(lessonsText) {
154
+ const entries = [];
155
+ let current = null;
156
+ let inFence = false;
157
+ for (const line of String(lessonsText ?? '').replace(/\r\n?/gu, '\n').split('\n')) {
158
+ if (/^\s*```/u.test(line)) { inFence = !inFence; continue; }
159
+ if (inFence) continue;
160
+ if (/^##\s/u.test(line)) { current = null; continue; }
161
+ const heading = line.match(LESSONS_ENTRY_HEADING);
162
+ if (heading) {
163
+ current = { id: 'L-' + String(Number(heading[1])).padStart(3, '0'), tokens: [], order: entries.length };
164
+ entries.push(current);
165
+ continue;
166
+ }
167
+ if (current === null) continue;
168
+ const keyword = line.match(LESSONS_KEYWORD_LINE);
169
+ if (!keyword) continue;
170
+ for (const piece of keyword[1].split(/[\s,,、;;/|]+/u)) {
171
+ const token = piece.trim().toLowerCase();
172
+ if (token !== '') current.tokens.push(token);
173
+ }
174
+ }
175
+ return entries.filter((entry) => entry.tokens.length > 0);
176
+ }
177
+
178
+ // 命中计算:路径词元 × 条目关键词词元求交,共享词元多的条目优先(相关度),同分按条目出现顺序
179
+ // (结果确定、可复核),取前 LESSONS_HIT_LIMIT 条。
180
+ function lessonsHits(pathTokens, entries) {
181
+ if (pathTokens.size === 0) return [];
182
+ const scored = [];
183
+ for (const entry of entries) {
184
+ const shared = [...new Set(entry.tokens.filter((token) => pathTokens.has(token)))];
185
+ if (shared.length === 0) continue;
186
+ scored.push({ id: entry.id, shared, order: entry.order });
187
+ }
188
+ scored.sort((a, b) => b.shared.length - a.shared.length || a.order - b.order);
189
+ return scored.slice(0, LESSONS_HIT_LIMIT);
190
+ }
191
+
192
+ // 段正文:命中段标题行之后、到下一个 H2 / 分隔线 / 文件尾(行锚定——正文里「引用段名」不劫持匹配)。
193
+ // 围栏代码块内的 `## ` 与 `---` 是正文示例,不当作段边界。段缺席返回 null(与「段在场但正文为空」
194
+ // 区分:前者是缺声明,后者由正文判据另行处理)。
195
+ function lessonsScanBody(content, pattern) {
196
+ const lines = String(content ?? '').replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n').split('\n');
197
+ const start = lines.findIndex((line) => pattern.test(line));
198
+ if (start === -1) return null;
199
+ const body = [];
200
+ let inFence = false;
201
+ for (let i = start + 1; i < lines.length; i += 1) {
202
+ if (/^\s*```/u.test(lines[i])) inFence = !inFence;
203
+ if (!inFence && (/^##\s/u.test(lines[i]) || /^---\s*$/u.test(lines[i]))) break;
204
+ body.push(lines[i]);
205
+ }
206
+ return body.join('\n');
207
+ }
208
+
209
+ // 编号在段内出现的判定:两侧非数字边界(L-501 不算命中 L-5012),大小写不敏感(执行者常写小写
210
+ // `l-501`)。转义集不含 `-`——字符类外的连字符本就是字面量,而在 `u` 标志下 `\-` 是非法转义
211
+ // (会抛 Invalid regular expression)。
212
+ function mentionsLessonsId(body, id) {
213
+ const escaped = id.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
214
+ return new RegExp('(^|[^0-9])' + escaped + '(?![0-9])', 'iu').test(body);
215
+ }
216
+
217
+ // 每份 SUMMARY 的两条判据 → 问题描述数组(分级由调用方按 isNewChange 决定:新 change BLOCKED /
218
+ // 旧 change WARN——C10 无例外)。TASK.md 或 .specs/LESSONS.md 缺席时对应输入为空:段在场判据照常,
219
+ // 命中计算自然为空集(无条目可命中)。
220
+ async function lessonsScanProblems(changeDir, summaryFiles) {
221
+ if (summaryFiles.length === 0) return [];
222
+ const rule = await lessonsScanRule();
223
+ const lessonsText = await fs.readFile(path.join(runRoot, '.specs', 'LESSONS.md'), 'utf8').catch(() => '');
224
+ const entries = lessonsEntries(lessonsText);
225
+ const writeFilesById = await taskWriteFiles(changeDir);
226
+ const problems = [];
227
+ for (const file of summaryFiles) {
228
+ let content = '';
229
+ try {
230
+ content = await fs.readFile(path.join(changeDir, file), 'utf8');
231
+ } catch (error) {
232
+ // 读失败不得静默跳过(L-079:依赖解析失败必须可见)——判据无法求值本身就是问题,按同一分级上报。
233
+ problems.push(file + ' 无法读取(' + String(error?.message ?? error) + ')——LESSONS 扫描判据无法求值');
234
+ continue;
235
+ }
236
+ const body = lessonsScanBody(content, rule.pattern);
237
+ if (body === null) {
238
+ if (rule.required) {
239
+ problems.push(file + ' 缺 ## ' + rule.name + ' 段(SUMMARY 增量段须声明扫描结果与命中回应'
240
+ + (rule.registered ? ';位置按登记表登记:自检方法之后' : '') + ')');
241
+ }
242
+ continue;
243
+ }
244
+ const taskId = file.replace(/-SUMMARY\.md$/iu, '');
245
+ const hits = lessonsHits(lessonsPathTokens(writeFilesById.get(taskId) ?? ''), entries);
246
+ const unanswered = hits.filter((hit) => !mentionsLessonsId(body, hit.id));
247
+ if (unanswered.length > 0) {
248
+ problems.push(file + ' 的 ## ' + rule.name + ' 段未回应命中条目 '
249
+ + unanswered.map((hit) => hit.id + '(关键词: ' + hit.shared.join('、') + ')').join('、')
250
+ + '——R1.8 要求逐条声明「仍适用 / 差异是 X」');
251
+ }
252
+ }
253
+ return problems;
254
+ }
255
+
256
+ // execute / subagent-execute 出口校验每份 SUMMARY 含三个必填段 + 6 维自查非空 + 自检方法声明
257
+ // (brooks-review / cache-brooks / builtin-quickcheck 三级降级路径)+ LESSONS 扫描段与命中核对
258
+ export async function runSummarySectionsGate({ node, state }) {
259
+ if (!EXECUTE_FAMILY_NODE_IDS.has(node.id)) return;
260
+ const changeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
261
+ const violations = await verifySummaries(changeDir);
262
+ // brooks-lint 自检方法审计:检查 6 维自查段是否声明了自检方法
263
+ const summaryFiles = (await fs.readdir(changeDir).catch(() => [])).filter(f => f.endsWith('-SUMMARY.md'));
264
+ for (const f of summaryFiles) {
265
+ try {
266
+ const content = await fs.readFile(path.join(changeDir, f), 'utf8');
267
+ // 段终止 lookahead 用 \n##\s(而非 \n##):###/#### 级子标题(如 "### 🟢 R1")是段内内容,
268
+ // 不是段结束。段尾同样 = 段标题 / 分隔线 / 输入末尾;末尾一律写 (?![\s\S]),不得写 \Z
269
+ // (JS 无 \Z——它是「字面字符 Z」,且本正则带 i 标志,连小写 z 都会命中,段被静默截断)
270
+ const sixDim = content.match(/##\s*6\s*维自查[\s\S]*?(?=\n##\s|\n---|(?![\s\S]))/i);
271
+ // 6 维自查段非空——去掉所有标题行后剩余实质内容 ≥ 10 字符。按行过滤标题(/^\s*#/)比正则
272
+ // 替换稳健:任何标题格式(emoji 🟢/中英文/数字)都不计入内容
273
+ const dimBody = sixDim ? sixDim[0].split('\n').filter(l => !/^\s*#/.test(l)).join('').trim() : '';
274
+ if (sixDim && dimBody.length < 10) {
275
+ violations.push(f + ' 的 6 维自查段无实质内容');
276
+ }
277
+ // 生产代码任务必填 ## 自检方法,声明 brooks-review 或 builtin-quickcheck。格式兼容:方法名行
278
+ // 允许中文前缀/括号说明(如 "方法:brooks-review"),按关键词搜索而非 [a-z-]+ 硬匹配。段名
279
+ // 允许带括号后缀(如 "## 自检方法(声明 brooks-review 或 builtin-quickcheck)"——括号为说明非
280
+ // 段名部分,执行者常按模板标题原样书写导致旧正则不匹配落入"旧格式 WARN";括号后缀与段名等价)。
281
+ // 分隔符用 .?(任意字符)而非 \.?(字面点):canonical 名 "brooks-review"/"builtin-quickcheck"
282
+ // 是连字符,与既有 /brooks.?review/ 约定一致。真实项目端到端验证实证:方法名可能在段内后续行
283
+ // (子代理列表写法)——段内全文搜索而非仅第一行。段内容截取到下一个段标题(\n## )或分隔线
284
+ // (\n---)或文件尾(split 处理,避免 JS 无 \Z 的问题)
285
+ const methodMatch = content.match(/##\s*自检方法(?:[((][^))\n]*[))])?\s*\n([\s\S]*)/i);
286
+ const methodSection = methodMatch ? methodMatch[1].split(/\n##\s|\n---/)[0] : null;
287
+ const method = methodSection ? /brooks.?review|cache.?brooks|builtin.?quickcheck/i.exec(methodSection) : null;
288
+ if (!method) {
289
+ // 过渡规则:旧格式 SUMMARY 无 ## 自检方法 段——若全文已声明 brooks-review/cache-brooks/
290
+ // builtin(旧模板行为),WARN 兼容不 BLOCKED;无任何自检声明才 BLOCKED
291
+ if (/brooks.?review|cache.?brooks|builtin.?quickcheck/i.test(content)) {
292
+ if (isNewChange(state)) {
293
+ violations.push(f + ' 缺 ## 自检方法 段(新 change 强制声明自检方法)');
294
+ } else {
295
+ console.error('BROOKS-LINT WARN: ' + f + ' 缺 ## 自检方法 段(旧格式),6 维自查已声明自检方法——兼容通过,建议补全');
296
+ }
297
+ } else {
298
+ violations.push(f + ' 缺 ## 自检方法 字段(必须声明 brooks-review 或 builtin-quickcheck)');
299
+ }
300
+ } else if (/builtin/i.test(method[0])) {
301
+ // builtin 降级两级校验——① 必须声明不可用原因;② 必须含缓存尝试证据(已尝试 Read 插件缓存
302
+ // 协议文件手动执行仍不可行——两级降级路径第 2 级;防「未尝试读缓存」的偷懒降级)。关键词
303
+ // 声明级校验(设计边界:不做语义判断);缺失 → 新 change BLOCKED / 旧 SUMMARY WARN 渐进
304
+ if (!/brooks-lint 不可用|插件不可用|unavailable|N\/A/i.test(content)) {
305
+ if (isNewChange(state)) {
306
+ console.error('BLOCKED: SUMMARY 使用 builtin-quickcheck 未声明 brooks-lint 不可用原因(新 change 强制);恢复: 在 ## 自检方法 段补原因(声明级校验——须含关键词: brooks-lint 不可用 / 插件不可用 / unavailable / N/A,如「brooks-lint 不可用(Skill 仅返回占位,插件执行体未加载)」)');
307
+ process.exit(1);
308
+ }
309
+ console.error('BROOKS-LINT WARN: ' + f + ' 使用 builtin-quickcheck 但未声明 brooks-lint 不可用原因');
310
+ } else if (!/插件缓存|缓存协议|协议文件|plugins\/cache/i.test(content)) {
311
+ if (isNewChange(state)) {
312
+ console.error('BLOCKED: SUMMARY 使用 builtin-quickcheck 未声明缓存尝试证据(新 change 强制先 Read 插件缓存协议文件);恢复: 在 ## 自检方法 段声明缓存尝试(须含关键词: 插件缓存 / 缓存协议 / 协议文件 / plugins/cache,如「已 Read 插件缓存协议文件(~/.claude/plugins/cache/...)手动执行仍不可行」)');
313
+ process.exit(1);
314
+ }
315
+ console.error('BROOKS-LINT WARN: ' + f + ' 使用 builtin-quickcheck 但未声明缓存尝试证据(应先 Read 插件缓存协议文件手动执行完整 brooks 流程)');
316
+ }
317
+ }
318
+ if (sixDim && !/brooks.?review|cache.?brooks/i.test(sixDim[0])) {
319
+ if (isNewChange(state)) {
320
+ console.error('BLOCKED: SUMMARY 的 6 维自查未声明使用 /brooks-review(新 change 强制声明自检方法);恢复: 在 6 维自查段声明 /brooks-review 或理由');
321
+ process.exit(1);
322
+ }
323
+ console.error('BROOKS-LINT WARN: ' + f + ' 的 6 维自查未声明使用 /brooks-review(可能使用了内置快查)');
324
+ }
325
+ } catch {}
326
+ }
327
+ // LESSONS 扫描(AC-18):每份 SUMMARY 的扫描段在场 + 命中条目逐条回应。分级沿用既有语义——
328
+ // 新 change BLOCKED / 旧 change WARN(C10 无例外)。
329
+ const lessonsProblems = await lessonsScanProblems(changeDir, summaryFiles);
330
+ if (lessonsProblems.length > 0) {
331
+ if (isNewChange(state)) {
332
+ violations.push(...lessonsProblems);
333
+ } else {
334
+ for (const problem of lessonsProblems) {
335
+ console.error('LESSONS SCAN WARN: ' + problem + '(旧 change 渐进,不阻断;新 change 将强制)');
336
+ }
337
+ }
338
+ }
339
+ if (violations.length > 0) {
340
+ console.error('BLOCKED: SUMMARY 关键段校验失败: ' + violations.join('; '));
341
+ if (lessonsProblems.length > 0 && isNewChange(state)) {
342
+ console.error('恢复: 按 flow-kit/templates/SUMMARY.md 在 ## 自检方法 之后补 ## LESSONS 扫描 段,并逐条写出命中条目编号与差异声明(无命中写「无 active 条目命中」);命中来源 = TASK.md 该任务 write_files 的路径段 × .specs/LESSONS.md 条目的关键词行');
343
+ }
344
+ process.exit(1);
345
+ }
346
+ }
347
+
348
+ // execute 出口门禁:空退出豁免活性(收窄)+ 串行 pending 拦截 + done 任务 SUMMARY 完整性 +
349
+ // 越俎代庖检测 + 越权委托检测。返回 { exempt }——豁免活性(仅全并行 change 且显式豁免时成立),
350
+ // 由产物门禁消费(含串行任务时豁免不生效,产物/摘要校验照常执行)。
351
+ export async function runExecuteExitGate({ protocol, node, state, emptyExitApproved }) {
352
+ if (node.id !== 'execute' || !state.activeChange) return { exempt: false };
353
+ let exempt = false;
354
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
355
+ try {
356
+ const taskContent = await fs.readFile(taskFile, 'utf8');
357
+ // 解析 TASK.md 全部 task 的 {id, status, parallel}——开标签属性解析共享 task-parsing.mjs
358
+ // (属性序无关、不读块内文本;与 workflow-state 路由同语义)
359
+ const taskList = extractTaskBlocks(taskContent);
360
+ const tasks = taskList.map(block => {
361
+ const a = taskOpeningAttrs(block) || {};
362
+ return { id: a.id, status: a.status, parallel: a.parallel };
363
+ }).filter(t => t.id);
364
+
365
+ // 串行 pending → BLOCKED(execute 任务没做完)——emptyExitApproved 不豁免串行 pending:豁免语义
366
+ // 是"全 parallel 无串行可做时空退出";存在未完成串行任务时豁免不应生效(防规划错误被豁免掩盖;
367
+ // 豁免仅作用于后续产物校验跳过,审计提示保留)
368
+ if (emptyExitApproved) {
369
+ // 豁免前置条件(收窄):TASK 存在任一串行任务块(parallel!=="true",含缺省)时豁免不生效,
370
+ // 无论该串行任务 pending 还是 done——陈旧标记不得跳过产物/摘要校验。
371
+ if (tasks.some(t => !t.parallel)) {
372
+ console.error('EMPTY-EXIT 未生效:本 change 含串行任务,豁免仅适用于全并行 change');
373
+ } else {
374
+ exempt = true;
375
+ console.error('EMPTY-EXIT: execute 空退出豁免已生效(evidence.execute.emptyExitApproved)——审计记录:该 change 在无串行任务时显式豁免空退出');
376
+ }
377
+ }
378
+ // serialPending 收窄为「可运行串行」(出口拦截集合收窄):仅 deps ⊆ doneIds 的未完成串行计入
379
+ // 拦截——deps 未满足的串行 pending 是等后续波次的合法中间态,放行由多趟路由按依赖拓扑分趟驱动。
380
+ // doneIds 就地派生;deps 提取复用 taskDependsOn(<depends_on> 内容按 [,\s]+ 切分,与路由谓词
381
+ // 同一解析口径),不新增状态。
382
+ const doneIds = new Set(tasks.filter(t => t.status === 'done').map(t => t.id));
383
+ const blockById = new Map();
384
+ for (const block of taskList) {
385
+ const a = taskOpeningAttrs(block);
386
+ if (a && a.id) blockById.set(a.id, block);
387
+ }
388
+ const serialRunnable = tasks.filter(t =>
389
+ !t.parallel && t.status === 'pending'
390
+ && taskDependsOn(blockById.get(t.id) || '').every(d => doneIds.has(d)));
391
+ if (serialRunnable.length > 0) {
392
+ console.error('BLOCKED: execute 出口仍有串行 pending 任务: ' + serialRunnable.map(t => t.id).join(', ')
393
+ + '——空退出豁免不适用于存在未完成可运行串行任务的情况(先完成该串行任务,或修正任务标记)'
394
+ + ';无可执行的常规恢复动作时,可用 workflow-state.mjs advance 渡过结构性死结(逃生口:使用后本节点须重新 entry 并重做交付记录);常规缺产物/缺证据情形不适用');
395
+ process.exit(1);
396
+ }
397
+
398
+ // done 任务 ↔ SUMMARY 完整性:done 任务 ↔ <id>-SUMMARY.md 存在(WARN 渐进不 BLOCK——防旧
399
+ // change 卡死;结构级校验与 TASK 签名同源:任务完成声明须有对应产物)。新 change(enter 机制
400
+ // 激活)升级为 BLOCKED——执行遗漏(声称完成但无产物)不静默进归档;旧 change 保持渐进。
401
+ const ki8ChangeDir = path.join(runRoot, '.specs', state.activeChange ?? '');
402
+ for (const tid of tasks.filter(t => t.status === 'done').map(t => t.id)) {
403
+ if (!(await fileExists(path.join(ki8ChangeDir, tid + '-SUMMARY.md')))) {
404
+ if (isNewChange(state)) {
405
+ console.error('BLOCKED: done 任务 ' + tid + ' 缺少 ' + tid + '-SUMMARY.md——execute 产物不完整(新 change 强制任务完成须有对应 SUMMARY;旧 change 渐进 WARN)');
406
+ console.error('恢复: 补写 ' + tid + '-SUMMARY.md 后重试 exit;任务完成后补产物即可');
407
+ process.exit(1);
408
+ }
409
+ console.error('WARN: done 任务 ' + tid + ' 缺少 ' + tid + '-SUMMARY.md——execute 产物不完整(任务完成须有对应 SUMMARY)');
410
+ }
411
+ }
412
+
413
+ // 豁免机制:evidence(当前节点 execute)含 parallelTakeoverApproved: true 时跳过越俎代庖检测
414
+ // (只保留串行 pending 检测)
415
+ const executeEvidence = state.evidence['execute'];
416
+ const takeoverApproved = !!(executeEvidence && executeEvidence.parallelTakeoverApproved);
417
+
418
+ if (!takeoverApproved) {
419
+ // 越俎代庖检测按 executionMode 分支:
420
+ // - direct(逃生口):串行任务主代理直写,不需 handoff;parallel 仍必须委托(防 execute 吞 parallel 回归)
421
+ // - subagent(默认):所有 done 任务需 handoff(统一委托下只能由子代理完成)
422
+ const executionMode = state.executionMode ?? 'subagent';
423
+ const he = state.evidence['subagent-execute'];
424
+ const results = he && he.handoffResult ? he.handoffResult : {};
425
+ let unauthorized;
426
+ if (executionMode === 'direct') {
427
+ unauthorized = tasks.filter(t => t.parallel && t.status === 'done' && !results[t.id]);
428
+ } else {
429
+ unauthorized = tasks.filter(t => t.status === 'done' && !results[t.id]);
430
+ }
431
+ if (unauthorized.length > 0) {
432
+ console.error('BLOCKED: 任务被主代理直接标记 done(越俎代庖)' + (executionMode === 'direct' ? ',direct 模式下 parallel 任务仍必须委托子代理' : ',统一委托下只能由子代理完成并记录 handoff') + ': ' + unauthorized.map(t => t.id).join(', '));
433
+ console.error('解决: 回退这些任务的 done 标记,重新委托子代理;或用 workflow-state.mjs record execute \'{"parallelTakeoverApproved":true}\' 显式豁免');
434
+ process.exit(1);
435
+ }
436
+ // parallel 仍 pending → 合法(下一步 determineNode 路由到 subagent-execute)
437
+ }
438
+
439
+ // 越权委托检测(execute 出口第一道)——TASK 有 parallel done 任务 + completedNodes 无
440
+ // subagent-execute + 非 direct 模式 + 协议含 subagent-execute 节点 → WARN 渐进([P] 任务应由
441
+ // subagent-execute 节点委托——execute 阶段完成 [P] 是越权委托痕迹;handoff 记录存在但节点未
442
+ // exit——真实项目端到端验证实证)
443
+ const ki10ParallelDone = tasks.filter(t => t.parallel && t.status === 'done').map(t => t.id);
444
+ const ki10ProtocolHasSubagent = (protocol.nodes ?? []).some(n => n.id === 'subagent-execute');
445
+ if (ki10ParallelDone.length > 0
446
+ && !(state.completedNodes ?? []).includes('subagent-execute')
447
+ && (state.executionMode ?? 'subagent') !== 'direct'
448
+ && !takeoverApproved
449
+ && ki10ProtocolHasSubagent) {
450
+ if (isNewChange(state)) {
451
+ console.error('BLOCKED: TASK 有 parallel done 任务(' + ki10ParallelDone.join(', ')
452
+ + ')但 subagent-execute 节点未 exit——新 change 强制 [P] 任务由 subagent-execute 节点委托');
453
+ console.error('恢复: 经 subagent-execute 节点完成委托后再 exit;或说明越权委托原因');
454
+ process.exit(1);
455
+ }
456
+ console.error('WARN: TASK 有 parallel done 任务(' + ki10ParallelDone.join(', ')
457
+ + ')但 subagent-execute 节点未 exit——疑似 execute 阶段越权委托,[P] 任务应由 subagent-execute 节点委托');
458
+ }
459
+ } catch {}
460
+ return { exempt };
461
+ }
462
+
463
+ // verify 出口必须真实跑命令(严格版)——历史归档 change 豁免(过渡规则)。命令来源三级:TEST.md 的
464
+ // ## 验证命令 段 → state 的 verifyCommand → 项目探测回退。失败按 change 隔离计数(≥4 次要求用户
465
+ // 决策)。二段式执行(受限沙箱兼容):首选管道式捕获,仅当 spawn 层被拒(EPERM)时以继承 stdio
466
+ // 重试同一命令(真实执行保持、退出码判定不变)。
467
+ export async function runVerifyExitGate({ protocol, node, state }) {
468
+ if (node.id !== 'verify') return;
469
+ if (await isArchivedChange(state.activeChange)) return;
470
+ // 越权委托兜底检测(verify 出口)——同 execute 出口的判定(TASK parallel done + completedNodes
471
+ // 无 subagent-execute + 非 direct + 协议含 subagent-execute 节点),verify 时仍未 exit → WARN
472
+ // 兜底(execute 出口未拦截的提示)
473
+ try {
474
+ const ki9TaskText = await fs.readFile(path.join(runRoot, '.specs', state.activeChange ?? '', 'TASK.md'), 'utf8');
475
+ const ki9TaskBlocks = extractTaskBlocks(ki9TaskText);
476
+ const ki9Tasks = ki9TaskBlocks.map(block => {
477
+ const a = taskOpeningAttrs(block) || {};
478
+ return { id: a.id, status: a.status, parallel: a.parallel };
479
+ }).filter(t => t.id);
480
+ const ki9ParallelDone = ki9Tasks.filter(t => t.parallel && t.status === 'done').map(t => t.id);
481
+ const ki9ProtocolHasSubagent = (protocol.nodes ?? []).some(n => n.id === 'subagent-execute');
482
+ const ki9TakeoverApproved = !!(state.evidence?.execute && state.evidence.execute.parallelTakeoverApproved);
483
+ if (ki9ParallelDone.length > 0
484
+ && !(state.completedNodes ?? []).includes('subagent-execute')
485
+ && (state.executionMode ?? 'subagent') !== 'direct'
486
+ && !ki9TakeoverApproved
487
+ && ki9ProtocolHasSubagent) {
488
+ if (isNewChange(state)) {
489
+ console.error('BLOCKED: TASK 有 parallel done 任务(' + ki9ParallelDone.join(', ')
490
+ + ')但 subagent-execute 节点未 exit——新 change 强制(verify 兜底拦截)');
491
+ console.error('恢复: 经 subagent-execute 节点完成委托后再 exit;或说明越权委托原因');
492
+ process.exit(1);
493
+ }
494
+ console.error('WARN: TASK 有 parallel done 任务(' + ki9ParallelDone.join(', ')
495
+ + ')但 subagent-execute 节点未 exit——疑似越权委托(execute 出口未拦截,verify 兜底提示)');
496
+ }
497
+ } catch {}
498
+ const { spawnSync } = await import('child_process');
499
+ let verifyCommand = null;
500
+ // 1) TEST.md 的 ## 验证命令 段(首行代码块首行)
501
+ const testDoc = path.join(runRoot, '.specs', state.activeChange ?? '', 'TEST.md');
502
+ if (await fileExists(testDoc)) {
503
+ const text = await fs.readFile(testDoc, 'utf8');
504
+ // 段名允许括号后缀(与 ## 自检方法 段的括号后缀兼容风格一致——执行者按模板标题原样书写或补充
505
+ // 说明时不被误 BLOCKED)
506
+ const m = text.match(/##\s*验证命令(?:[((][^))\n]*[))])?\s*\n\s*```[^\n]*\n([\s\S]*?)```/);
507
+ if (m) verifyCommand = m[1].trim().split('\n').filter(l => l.trim() && !l.trim().startsWith('#')).join(' && ');
508
+ }
509
+ // 2) state 的 verifyCommand
510
+ if (!verifyCommand && state.verifyCommand) verifyCommand = state.verifyCommand;
511
+ // 3) 项目探测回退
512
+ if (!verifyCommand) {
513
+ if (await fileExists(path.join(runRoot, 'pingpong-tournament', 'pyproject.toml'))) verifyCommand = 'cd pingpong-tournament && python -m pytest tests/ -q';
514
+ else if (await fileExists(path.join(runRoot, 'frontend', 'package.json'))) verifyCommand = 'cd frontend && npm test';
515
+ }
516
+ if (!verifyCommand) {
517
+ console.error('BLOCKED: TEST.md 需声明 ## 验证命令 段(严格版要求)');
518
+ process.exit(1);
519
+ }
520
+ // verify 命令 timeout 可配置——FLOW_COMET_VERIFY_TIMEOUT_MS 环境变量优先,缺省 300000ms(300s;
521
+ // 后端测试耗时可超 300s,用 env 调大);非数字/0 → 回退缺省
522
+ const verifyTimeoutMs = Number.parseInt(process.env.FLOW_COMET_VERIFY_TIMEOUT_MS ?? '300000', 10) || 300000;
523
+ try {
524
+ // 测试钩子(仅测试用途):FLOW_COMET_VERIFY_FORCE_EPERM=1 使首次管道执行模拟 EPERM 拒绝——
525
+ // 真实受限会话中命令在管道阶段不会启动,故跳过管道阶段直接产生 EPERM 结果,让降级路径可确定性
526
+ // 自动化断言(生产触发条件是真实 spawn 层 EPERM,不经此钩子)
527
+ const forceEperm = process.env.FLOW_COMET_VERIFY_FORCE_EPERM === '1';
528
+ const first = forceEperm
529
+ ? { status: null, error: Object.assign(new Error('spawn verify EPERM(FLOW_COMET_VERIFY_FORCE_EPERM=1 模拟受限沙箱拒绝)'), { code: 'EPERM' }), stdout: '', stderr: '' }
530
+ : spawnSync(verifyCommand, { cwd: runRoot, shell: true, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: verifyTimeoutMs });
531
+ const firstFailed = first.error != null || first.status !== 0;
532
+ const epermDenied = first.error != null && (first.error.code === 'EPERM' || String(first.error.message ?? '').includes('EPERM'));
533
+ if (firstFailed && epermDenied) {
534
+ console.error('VERIFY-DEGRADED: ' + verifyCommand + '(沙箱管道受限,以 inherit 重试)');
535
+ const r2 = spawnSync(verifyCommand, { cwd: runRoot, shell: true, stdio: 'inherit', timeout: verifyTimeoutMs });
536
+ if (!(r2.error == null && r2.status === 0)) {
537
+ throw new Error(r2.error != null ? String(r2.error.message) : ('exit code ' + r2.status));
538
+ }
539
+ } else if (firstFailed) {
540
+ // 非 EPERM 失败维持现状路径——抛出与既有 execSync 形态兼容的错误对象(stdout 优先展示)
541
+ const e = new Error('Command failed: ' + verifyCommand + '\n' + String(first.stderr ?? ''));
542
+ e.stdout = first.stdout;
543
+ throw e;
544
+ }
545
+ } catch (e) {
546
+ // verify-fail 自动递增(无需 LLM 主动调用)——计数按当前 change 存储(verifyFailuresByChange,
547
+ // 切换 change 不串扰;旧顶层字段迁移并入)
548
+ const count = verifyFailuresFor(state) + 1;
549
+ setVerifyFailuresFor(state, count);
550
+ const file = await statePath(protocol);
551
+ const bad = validateStateFields(state);
552
+ if (bad.length) { console.error('BLOCKED: state 字段类型非法: ' + bad[0]); process.exit(1); }
553
+ await writeJson(file, state);
554
+ if (count >= 4) {
555
+ console.error('BLOCKED: verify 已失败 ' + count + ' 次,需用户决策(继续修/停止)。');
556
+ } else {
557
+ // stdout 为空(如超时被 kill 时 stdout 是空 Buffer——truthy)→ 显示错误消息;消息中带实际
558
+ // 应用的 timeout(超时可诊断,且与 Node 版本无关)
559
+ const detail = (e.stdout && e.stdout.length) ? e.stdout : e.message;
560
+ console.error('BLOCKED: verify 命令失败(timeout ' + verifyTimeoutMs + 'ms): ' + verifyCommand + '\n' + String(detail).slice(0, 500));
561
+ console.error('VERIFY-FAIL: ' + count + '/3');
562
+ }
563
+ process.exit(1);
564
+ }
565
+ }
566
+
567
+ // Return Contract 校验——每个 delegated task 的 result 必须含 commitHash + greenEvidence;handoff
568
+ // guarded 落实——每个 result 的 completedChecks 必须包含 required-skill:subagent-execute.<skill>
569
+ // (skill 名从协议 requiredSkillCalls 读)。严格模式:旧格式非 JSON result(无 completedChecks
570
+ // 载体)同样 BLOCKED,无旧 change 豁免——补录/重录必须回传完整契约(含 completedChecks),不允许
571
+ // 历史格式绕过委托证明。
572
+ export function runReturnContractGate({ node, state }) {
573
+ if (node.id !== 'subagent-execute') return;
574
+ const he = state.evidence['subagent-execute'];
575
+ const results = he && he.handoffResult ? he.handoffResult : {};
576
+ const requiredChecks = (node.requiredSkillCalls ?? [])
577
+ .map((binding) => 'required-skill:' + node.id + '.' + binding.skill);
578
+ const violations = [];
579
+ for (const [taskId, rec] of Object.entries(results)) {
580
+ const r = typeof rec.result === 'object' && rec.result !== null ? rec.result : null;
581
+ if (!r) { violations.push(taskId + ' 非 Return Contract(旧格式,缺 completedChecks)'); continue; }
582
+ // 零提交语义对齐:request 记录 noCommit(write_files 为空,或全部字面路径可证明被 gitignore)的
583
+ // 任务无提交可回传,豁免 commitHash 缺失断言(其余契约校验不变)——与 workflow-handoff 零提交
584
+ // 跳过同构
585
+ const taskReq = he.handoffRequests ? he.handoffRequests[taskId] : null;
586
+ const noCommitTask = !!(taskReq && taskReq.noCommit === true);
587
+ if (!r.commitHash && !noCommitTask) violations.push(taskId + ' 缺 commitHash');
588
+ if (!r.greenEvidence || !r.greenEvidence.command) violations.push(taskId + ' 缺 greenEvidence');
589
+ // redEvidence 缺失警告(过渡期不阻断)——新 change(enter 机制激活)升级为 BLOCKED(TDD RED 证据强制)
590
+ if (r && !r.redEvidence) {
591
+ if (isNewChange(state)) {
592
+ violations.push(taskId + ' 缺 redEvidence(新 change 强制 TDD RED 证据;旧 change 渐进 WARN)');
593
+ } else {
594
+ console.error('HANDOFF WARN: ' + taskId + ' 缺 redEvidence(可能未执行 TDD RED 阶段)');
595
+ }
596
+ }
597
+ // completedChecks 严格校验(无旧 change 豁免)
598
+ if (requiredChecks.length > 0) {
599
+ const checks = Array.isArray(r.completedChecks) ? r.completedChecks : [];
600
+ const missing = requiredChecks.filter((check) => !checks.includes(check));
601
+ if (missing.length > 0) {
602
+ violations.push(taskId + ' 缺 completedChecks: ' + missing.join(', '));
603
+ }
604
+ }
605
+ }
606
+ if (violations.length > 0) {
607
+ console.error('BLOCKED: Return Contract 校验失败: ' + violations.join('; '));
608
+ console.error('恢复: 子代理回传完整契约(含缺失字段)后用 workflow-handoff.mjs result 重录——新 change 强制 TDD RED/GREEN 证据与 completedChecks;注意:若已记录 greenEvidence 而缺 redEvidence,时序防护会拦截事后补录(防掩盖缺 RED)——确认子代理真实执行过 TDD RED 且证据在对应 SUMMARY 中时,用 workflow-state.mjs record subagent-execute 合并写入真实 redEvidence(证据可溯源),或重新委托任务获取完整契约');
609
+ process.exit(1);
610
+ }
611
+ }
612
+
613
+ // subagent-execute 出口——done 任务缺 SUMMARY(新 change BLOCKED;旧 change 渐进 WARN)。已知边界:
614
+ // SUMMARY 段内容校验只查已存在的 SUMMARY;执行遗漏(声称完成无产物)不应静默进归档。
615
+ export async function runSubagentSummaryGate({ node, state }) {
616
+ if (node.id !== 'subagent-execute' || !state.activeChange) return;
617
+ const saTaskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
618
+ try {
619
+ const saContent = await fs.readFile(saTaskFile, 'utf8');
620
+ const saTasks = (saContent.match(/<task[^>]*>[\s\S]*?<\/task>/g) || [])
621
+ .map(block => ({ id: (block.match(/id="([^"]+)"/) || [])[1] || null, status: (block.match(/status="([^"]+)"/) || [])[1] || null }))
622
+ .filter(t => t.id);
623
+ const saDir = path.join(runRoot, '.specs', state.activeChange ?? '');
624
+ for (const t of saTasks.filter(t => t.status === 'done')) {
625
+ if (!(await fileExists(path.join(saDir, t.id + '-SUMMARY.md')))) {
626
+ if (isNewChange(state)) {
627
+ console.error('BLOCKED: done 任务 ' + t.id + ' 缺少 ' + t.id + '-SUMMARY.md——subagent-execute 产物不完整(新 change 强制任务完成须有对应 SUMMARY;旧 change 渐进 WARN)');
628
+ console.error('恢复: 补写 ' + t.id + '-SUMMARY.md 后重试 exit;任务完成后补产物即可');
629
+ process.exit(1);
630
+ }
631
+ console.error('WARN: done 任务 ' + t.id + ' 缺少 ' + t.id + '-SUMMARY.md——subagent-execute 产物不完整(任务完成须有对应 SUMMARY)');
632
+ }
633
+ }
634
+ } catch {}
635
+ }
636
+
637
+ // 多趟完成判定(完成判定谓词决策·合取语义)——subagent-execute 每趟出口校验:
638
+ // ① 可委托集合必须为空:仍存在 p(parallel ∧ pending ∧ deps⊆done)→ 本趟未委派完即退 → BLOCK
639
+ // 「尚有可委托并行任务(继续委托)」(每趟须委托全部依赖已满足的并行任务);
640
+ // ② 孤儿并行单独区分文案:parallel ∧ pending 且依赖链无法满足(直接依赖缺失,或陷入依赖环/被环
641
+ // 传递拖累)→ BLOCK「孤儿并行任务依赖无法满足(检查 depends_on)」——数据异常 fail-closed,
642
+ // 防静默跳过(三重防呆决策之二)。
643
+ // serial pending 不阻断:合法趟间态(回 execute 消化串行)——最终完成的另一支「无 serial pending」
644
+ // 由 execute 出口的串行 pending 校验把关,两支在流程推进中自然合取。
645
+ export async function runMultiPassCompletionGate({ node, state }) {
646
+ if (node.id !== 'subagent-execute' || !state.activeChange) return;
647
+ try {
648
+ const mpContent = await fs.readFile(path.join(runRoot, '.specs', state.activeChange, 'TASK.md'), 'utf8');
649
+ const mpBlocks = extractTaskBlocks(mpContent);
650
+ const mpDoneIds = new Set(mpBlocks
651
+ .map(taskOpeningAttrs)
652
+ .filter((a) => a && a.status === 'done' && a.id)
653
+ .map((a) => a.id));
654
+ const delegable = eligibleParallelBlocks(mpBlocks, mpDoneIds);
655
+ if (delegable.length > 0) {
656
+ console.error('BLOCKED: 尚有可委托并行任务(继续委托): ' + delegable
657
+ .map((b) => (taskOpeningAttrs(b) || {}).id).join(', ') +
658
+ '——多趟语义下每趟须委派全部依赖已满足的并行任务后才能退出');
659
+ console.error('恢复: 继续委托上述任务(子代理回传 Return Contract 后再 exit);若确需提前收尾,先调整其 depends_on 使其脱离可委派状态');
660
+ process.exit(1);
661
+ }
662
+ const mpGraph = analyzeDependencyGraph(mpBlocks);
663
+ const parallelPending = mpBlocks.filter((b) => {
664
+ const a = taskOpeningAttrs(b);
665
+ return a && a.parallel && a.status === 'pending';
666
+ });
667
+ let orphans = [];
668
+ if (mpGraph.cyclic || mpGraph.missing.length > 0) {
669
+ // doomed 闭包:直接依赖缺失的任务 ∪ 环上/被环拖累的任务,再传递扩散到一切(传递)依赖它们的
670
+ // 任务——这些任务永远进不了可委派状态,一并视为孤儿。
671
+ const doomed = new Set(mpGraph.cycleIds);
672
+ for (const m of mpGraph.missing) doomed.add(m.id);
673
+ let changed = true;
674
+ while (changed) {
675
+ changed = false;
676
+ for (const [id, deps] of mpGraph.depsById) {
677
+ if (doomed.has(id)) continue;
678
+ if (deps.some((d) => doomed.has(d))) { doomed.add(id); changed = true; }
679
+ }
680
+ }
681
+ orphans = parallelPending.filter((b) => {
682
+ const a = taskOpeningAttrs(b);
683
+ return a && a.id && doomed.has(a.id);
684
+ });
685
+ }
686
+ if (orphans.length > 0) {
687
+ console.error('BLOCKED: 孤儿并行任务依赖无法满足(检查 depends_on): ' + orphans
688
+ .map((b) => (taskOpeningAttrs(b) || {}).id).join(', ') +
689
+ '——依赖引用了不存在的任务或陷入依赖环,永远无法进入可委派状态');
690
+ console.error('恢复: 调整这些任务的 depends_on——指向真实存在且无环的任务 id 后重试;依赖环应在 plan 出口被前置拦截,执行期出现请核对 TASK.md 是否被手改');
691
+ process.exit(1);
692
+ }
693
+ } catch {}
694
+ }
695
+
696
+ // 自动补 required-skill completedChecks——节点被完成即视为其实现 skill 已加载。分派(ui-design 门):
697
+ // 仅「guarded 且适用性判据成立(判前端)」的登记绑定在**新 change** 上停止自动补——该绑定须真实
698
+ // skill-load 声明,由后续 missingRequiredSkillChecks 拦截;判据不成立(非前端)、旧 change(渐进
699
+ // 兼容——自动补写保持原语义,工件门照常 WARN)或未登记的绑定 → 逐字保持原自动补语义(其它节点/
700
+ // 绑定不受影响)。随后校验 Output Schema evidence 存在性。
701
+ export async function runEvidenceCompletionGate({ protocol, node, state, evidence }) {
702
+ if ((node.requiredSkillCalls ?? []).length > 0) {
703
+ const checks = Array.isArray(evidence.completedChecks) ? evidence.completedChecks : [];
704
+ for (const binding of node.requiredSkillCalls ?? []) {
705
+ const check = 'required-skill:' + node.id + '.' + binding.skill;
706
+ const applicabilityGated = applicabilityGatedBinding(node, binding.skill) !== null;
707
+ if (applicabilityGated && isNewChange(state) && (await frontendCriterion(state.activeChange)).applicable) continue;
708
+ if (!checks.includes(check)) checks.push(check);
709
+ }
710
+ evidence.completedChecks = checks;
711
+ }
712
+ const missingSchemaEvidence = missingRequiredSchemaEvidence(protocol, node, evidence);
713
+ if (missingSchemaEvidence.length > 0) {
714
+ console.error('BLOCKED: missing Output Schema evidence: ' + missingSchemaEvidence.join(', '));
715
+ process.exit(1);
716
+ }
717
+ }
718
+
719
+ // 产物门禁 + 空退出豁免跳过面:仅当豁免活性成立(显式豁免且 TASK 无任何串行任务)时跳过产物校验
720
+ // (全 parallel 无 SUMMARY 属预期);含串行任务的 change 豁免不生效,照常校验,不得静默放行。生效
721
+ // 时追加被跳过项清单(EMPTY-EXIT-SKIPPED)。
722
+ export async function runArtifactGate({ protocol, node, state, emptyExitApproved, emptyExitExempt }) {
723
+ const checkedArtifacts = await missingRequiredArtifacts(protocol, node, state.activeChange);
724
+ let missingArtifacts = checkedArtifacts;
725
+ if (emptyExitApproved && emptyExitExempt) {
726
+ console.error('EMPTY-EXIT-SKIPPED: ' + (checkedArtifacts.length > 0 ? checkedArtifacts.join(', ') : '(无缺失产物项)'));
727
+ missingArtifacts = [];
728
+ }
729
+ if (missingArtifacts.length > 0) {
730
+ console.error('BLOCKED: missing Output Schema artifacts: ' + missingArtifacts.join(', '));
731
+ process.exit(1);
732
+ }
733
+ }
734
+
735
+ // required-skill / augmentation 声明门禁:适用性门控绑定缺的是「真实 skill-load 声明」(出口不再
736
+ // 自动补写)——给出补齐路径(判据与该门同源:applicabilityGatedBinding 查询,不另写键表)
737
+ export function runRequiredEvidenceGate({ node, evidence }) {
738
+ const missingRequired = missingRequiredSkillChecks(node, evidence);
739
+ if (missingRequired.length > 0) {
740
+ console.error('BLOCKED: missing required Skill evidence: ' + missingRequired.join(', '));
741
+ for (const binding of node.requiredSkillCalls ?? []) {
742
+ const check = 'required-skill:' + node.id + '.' + binding.skill;
743
+ if (missingRequired.includes(check) && applicabilityGatedBinding(node, binding.skill) !== null) {
744
+ console.error('恢复: ' + check + ' 不再由出口自动补写(guarded + 适用性判据成立)——先加载 ' + binding.skill
745
+ + ' 并运行 workflow-state.mjs skill-load ' + node.id + ' ' + binding.skill
746
+ + ' --prompt <flow-kit/prompts/ 协议文件> 声明已加载后重试 exit');
747
+ }
748
+ }
749
+ process.exit(1);
750
+ }
751
+ const missingAugmentations = missingAugmentationChecks(node, evidence);
752
+ if (missingAugmentations.length > 0) {
753
+ console.error('BLOCKED: missing augmentation evidence: ' + missingAugmentations.join(', '));
754
+ process.exit(1);
755
+ }
756
+ }