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,378 @@
1
+ #!/usr/bin/env node
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { validateStateFields, looksLikeObjectLiteral, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME } from './state-schema.mjs';
6
+
7
+ // workflow-handoff.mjs: Record subagent handoff evidence
8
+ // evidence 统一记录在 subagent-execute 名下作为委托证据库——execute(串行委托)与 subagent-execute(并行委托)共用。不改成节点参数,保持最小改动。
9
+ // Usage:
10
+ // node workflow-handoff.mjs request <task-id> <description> [--write-files <files...>] -- record handoff request (W2-D: optional writeFiles allow-list)
11
+ // node workflow-handoff.mjs result <task-id> <result-or-JSON> -- record handoff result (W1-D: JSON Return Contract; W2-D: commitHash subset check; : completedChecks 规范化; redEvidence 时间顺序校验)
12
+ // node workflow-handoff.mjs status -- show all handoff evidence
13
+
14
+ const runRoot = process.cwd();
15
+ // 状态文件路径(单一来源:state-schema.mjs 的运行时路径常量)
16
+ const statePath = path.join(runRoot, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME);
17
+
18
+ async function fileExists(f) { try { await fs.access(f); return true; } catch { return false; } }
19
+
20
+ // 技能加载声明标记存在性(技能加载前置门·方案 A):校验 .skill-loads/ 下
21
+ // 是否有该节点的声明标记 <node>-*.json(任一 skill 标记即算已声明——与 guard exit 侧
22
+ // 的 exit 协议声明标记校验、workflow-state record 前置门同构:按 <node>- 前缀扫描;
23
+ // 活动路径优先,归档路径兜底)。委托前置门在「先加载技能(Skill 工具)并 skill-load
24
+ // 声明」之前拦截"先干活后补声明"。诚实边界:标记是自我声明,非物理证明。
25
+ async function nodeSkillDeclared(nodeId, changeName) {
26
+ if (!nodeId || !changeName) return false;
27
+ const prefix = nodeId + '-';
28
+ const scan = async (dir) => {
29
+ try {
30
+ const entries = await fs.readdir(dir);
31
+ return entries.some((f) => f.startsWith(prefix) && f.endsWith('.json'));
32
+ } catch {
33
+ return false;
34
+ }
35
+ };
36
+ const activeDir = path.join(runRoot, '.specs', changeName, '.skill-loads');
37
+ if (await scan(activeDir)) return true;
38
+ const archiveRoot = path.join(runRoot, '.specs', 'archive');
39
+ const archiveEntries = await fs.readdir(archiveRoot).catch(() => []);
40
+ for (const entry of archiveEntries) {
41
+ if (!entry.endsWith('-' + changeName)) continue;
42
+ if (await scan(path.join(archiveRoot, entry, '.skill-loads'))) return true;
43
+ }
44
+ return false;
45
+ }
46
+
47
+ // 契约解析失败判定(单一来源):looksLikeObjectLiteral 由 state-schema.mjs 导出——
48
+ // trim 后以 {/[ 开头 → 视作"形似对象字面量";若 JSON.parse 失败 → fail-closed。
49
+
50
+ // --json-file 路径校验:解析后必须位于项目根内(与 record 同规则——拒绝越界路径,
51
+ // 防读取任意文件内容进 evidence;runRoot 内绝对路径合法)。符号链接解析后的实际路径
52
+ // 同样必须在项目根内(词法校验不防 symlink 穿越——realpath 后再次校验)。
53
+ // 非字符串/空值(如 --json-file 为最后一个参数)→ 用法错误,与 record 同消息
54
+ async function resolveJsonFileWithinRunRoot(jsonFile) {
55
+ if (typeof jsonFile !== 'string' || jsonFile.trim() === '') {
56
+ throw new Error('--json-file requires a path argument');
57
+ }
58
+ const abs = path.resolve(runRoot, jsonFile);
59
+ const rel = path.relative(runRoot, abs);
60
+ if (path.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + path.sep)) {
61
+ throw new Error('--json-file 路径必须在项目根内: ' + jsonFile);
62
+ }
63
+ // 统一对 runRoot 也 realpath——Windows 上 runRoot 可能是 8.3 短路径(如 LONGYI~1),
64
+ // realpath 会展开为长路径,两者直接 relative 会误判越界
65
+ const realRoot = await fs.realpath(runRoot);
66
+ const real = await fs.realpath(abs);
67
+ const realRel = path.relative(realRoot, real);
68
+ if (path.isAbsolute(realRel) || realRel === '..' || realRel.startsWith('..' + path.sep)) {
69
+ throw new Error('--json-file 路径经符号链接解析后越出项目根: ' + jsonFile);
70
+ }
71
+ return abs;
72
+ }
73
+
74
+ // writeFiles 段感知 glob 匹配:按 / 分段,`*` 只匹配段内任意字符(不跨段);
75
+ // 精确条目要求完全相等(不用前缀匹配——src/foo 不得匹配 src/foobar);
76
+ // 段内含 * 的部分通配(如 src/*.test.js、src/*.mjs)转锚定正则匹配
77
+ function matchWriteFilePattern(file, pattern) {
78
+ const f = String(file).replace(/\\/g, '/');
79
+ const p = String(pattern).replace(/\\/g, '/');
80
+ const fp = f.split('/');
81
+ const pp = p.split('/');
82
+ if (fp.length !== pp.length) return false;
83
+ for (let i = 0; i < pp.length; i++) {
84
+ if (pp[i] === '*') continue;
85
+ if (!pp[i].includes('*')) {
86
+ if (pp[i] !== fp[i]) return false;
87
+ continue;
88
+ }
89
+ // 段内 glob:`*` 匹配段内任意字符(不跨 /),其余字符字面匹配(锚定)
90
+ const seg = new RegExp('^' + pp[i].split('*')
91
+ .map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
92
+ .join('[^/]*') + '$');
93
+ if (!seg.test(fp[i])) return false;
94
+ }
95
+ return true;
96
+ }
97
+
98
+ async function readState() {
99
+ if (await fileExists(statePath)) return JSON.parse(await fs.readFile(statePath, 'utf8'));
100
+ return { activeChange: null, currentNode: null, completedNodes: [], evidence: {} };
101
+ }
102
+
103
+ async function writeState(state) {
104
+ // 内置节点常量: 与 workflow-state.mjs C6 同构——写入前校验已知字段类型(fail-closed),非法 → BLOCKED + exit 1
105
+ const bad = validateStateFields(state);
106
+ if (bad.length) {
107
+ console.error('BLOCKED: state 字段类型非法: ' + bad[0]);
108
+ process.exit(1);
109
+ }
110
+ await fs.mkdir(path.dirname(statePath), { recursive: true });
111
+ await fs.writeFile(statePath, JSON.stringify(state, null, 2) + '\n', 'utf8');
112
+ }
113
+
114
+ async function main() {
115
+ const action = process.argv[2] ?? 'status';
116
+ const state = await readState();
117
+
118
+ if (action === 'request') {
119
+ const taskId = process.argv[3];
120
+ const args = process.argv.slice(4);
121
+ if (!taskId) { console.error('Usage: workflow-handoff.mjs request <task-id> <description> [--write-files <files...>]'); process.exit(1); }
122
+ // 技能加载前置门(方案 A):发起委托前校验 execute/subagent-execute
123
+ // 本节点 skill-load 声明标记已存在(.skill-loads/<node>-*.json)——先加载节点技能(Skill 工具)
124
+ // 并 skill-load 声明,再发起委托。缺失 → 新 change BLOCK / 旧 change 渐进 WARN。
125
+ // 与零提交语义独立共存:本门只校验节点技能声明,不依赖任务 write_files 内容。
126
+ const requestNode = state.currentNode;
127
+ if (requestNode && (requestNode === 'execute' || requestNode === 'subagent-execute')) {
128
+ const declared = await nodeSkillDeclared(requestNode, state.activeChange);
129
+ if (!declared) {
130
+ const loadGuide = '先加载技能(用 Skill 工具,禁止跳过)并运行 workflow-state.mjs skill-load ' + requestNode + ' <skill> 再发起委托';
131
+ if (state.newChange === true) {
132
+ console.error('BLOCKED: 节点 ' + requestNode + ' 缺少技能加载声明标记(.skill-loads/' + requestNode + '-*.json)——' + loadGuide);
133
+ process.exit(1);
134
+ }
135
+ console.error('WARN: 节点 ' + requestNode + ' 缺少技能加载声明标记(.skill-loads/' + requestNode + '-*.json)——' + loadGuide + '(旧 change 渐进不阻断)');
136
+ }
137
+ }
138
+ // W2-D: 可选 --write-files 记录该 task 允许写入的文件列表(含 glob),供 result 的提交文件子集校验
139
+ let description = 'pending';
140
+ let writeFiles = [];
141
+ const wfIdx = args.indexOf('--write-files');
142
+ if (wfIdx >= 0) {
143
+ description = args.slice(0, wfIdx).join(' ') || 'pending';
144
+ writeFiles = args.slice(wfIdx + 1).filter(a => !a.startsWith('--')).flatMap(a => a.split(/[, ]+/)).filter(Boolean);
145
+ } else {
146
+ description = args.join(' ') || 'pending';
147
+ }
148
+ // 若未显式传 --write-files,从 TASK.md 自动解析(orchestrator 无需手动提取文件列表)。
149
+ // 解析三态(bot 评审收紧):① 匹配到任务块且 <write_files> 存在 → 按内容分类;
150
+ // ② 任务块缺失或块内无 <write_files> 元素 → 任务不可解析,新 change BLOCK,旧 change
151
+ // WARN 且不设 noCommit(防未解析任务静默变零提交逃逸口);③ TASK.md 读不到同 ②。
152
+ let taskResolved = false;
153
+ let emptyWriteFilesElement = false;
154
+ if (!writeFiles || writeFiles.length === 0) {
155
+ try {
156
+ const taskFile = path.join(runRoot, '.specs', state.activeChange, 'TASK.md');
157
+ const taskContent = await fs.readFile(taskFile, 'utf8');
158
+ const taskRegex = new RegExp(`<task[^>]*id="${taskId.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&')}"[\\s\\S]*?<write_files>([\\s\\S]*?)</write_files>`, 'i');
159
+ const match = taskContent.match(taskRegex);
160
+ if (match) {
161
+ taskResolved = true;
162
+ // 分号容错:与 workflow-guard.mjs 伪并行启发式同源实现(分号容错双点内联,与 workflow-guard.mjs 同源互锚)
163
+ // 先剥整块 HTML 注释再拆分——多行注释内容不得混入路径条目(与 workflow-guard 同口径)
164
+ const files = match[1].replace(/<!--[\s\S]*?-->/g, '').trim().split(/\s*\n\s*/).map(f => f.trim()).filter(Boolean)
165
+ .flatMap(f => f.split(';')).map(f => f.trim()).filter(Boolean);
166
+ if (files.length > 0) { writeFiles = files; }
167
+ else { emptyWriteFilesElement = true; }
168
+ }
169
+ } catch {}
170
+ if (wfIdx >= 0) { taskResolved = true; emptyWriteFilesElement = false; }
171
+ } else {
172
+ taskResolved = true;
173
+ }
174
+ if (!taskResolved) {
175
+ const msg = '委托任务不可解析:TASK.md 缺失、无匹配 <task id=' + taskId + '> 或任务缺 <write_files> 元素——无法判定零提交语义;修正 TASK.md 后重试';
176
+ if (state.newChange === true) {
177
+ console.error('BLOCKED: ' + msg);
178
+ process.exit(1);
179
+ }
180
+ console.error('WARN: ' + msg + '(旧 change 渐进,不阻断,不记录 noCommit)');
181
+ }
182
+ state.evidence = state.evidence || {};
183
+ state.evidence['subagent-execute'] = state.evidence['subagent-execute'] || {};
184
+ if (!state.evidence['subagent-execute'].handoffRequests) {
185
+ state.evidence['subagent-execute'].handoffRequests = {};
186
+ }
187
+ const zeroEligible = taskResolved && emptyWriteFilesElement && writeFiles.length === 0;
188
+ state.evidence['subagent-execute'].handoffRequests[taskId] = {
189
+ description, requestedAt: new Date().toISOString(),
190
+ ...(writeFiles.length ? { writeFiles } : {}),
191
+ ...(zeroEligible ? { noCommit: true } : {})
192
+ };
193
+ await writeState(state);
194
+ console.log('HANDOFF REQUEST: ' + taskId);
195
+ return;
196
+ }
197
+
198
+ if (action === 'result') {
199
+ const taskId = process.argv[3];
200
+ // --json-file <path>(或 --json-file=<path>):从文件读 JSON payload——与 record 对齐,
201
+ // 规避 Windows PowerShell 剥离内嵌双引号导致 JSON 损坏(存成脏字符串)
202
+ let jsonFile = null;
203
+ const resultArgs = [];
204
+ const rawArgs = process.argv.slice(4);
205
+ for (let i = 0; i < rawArgs.length; i++) {
206
+ const arg = rawArgs[i];
207
+ if (arg === '--json-file') { jsonFile = rawArgs[i + 1]; i += 1; continue; }
208
+ if (typeof arg === 'string' && arg.startsWith('--json-file=')) { jsonFile = arg.slice('--json-file='.length); continue; }
209
+ resultArgs.push(arg);
210
+ }
211
+ let raw = resultArgs.join(' ');
212
+ if (jsonFile !== null) {
213
+ raw = await fs.readFile(await resolveJsonFileWithinRunRoot(jsonFile), 'utf8');
214
+ }
215
+ if (!taskId) { console.error('Usage: workflow-handoff.mjs result <task-id> <result>'); process.exit(1); }
216
+ // W1-D: 尝试解析 JSON(Return Contract)——解析失败则存原始字符串
217
+ let parsed = raw;
218
+ try { parsed = JSON.parse(raw); } catch {
219
+ // 契约解析失败 fail-closed:payload 形似对象但 JSON.parse 失败 → 报错并
220
+ // process.exit(1),不写 handoffResult——Return Contract 应为合法 JSON
221
+ // (旧语义把不可解析 raw 静默存字符串 = 静默落脏,guard exit 误报
222
+ // "非 Return Contract"掩盖真因)
223
+ // 消息按参数来源分级(设计语义 / AC-3):--json-file 传入且文件内容损坏 →
224
+ // "文件内容不是合法 JSON" + 长度元数据;内联传参损坏 → 保留 --json-file 建议。
225
+ // 安全(bot 审查):错误消息与 workflow-state record 统一——只含固定前缀 +
226
+ // 长度元数据,绝不打印 raw 内容(含截断)。
227
+ if (looksLikeObjectLiteral(raw)) {
228
+ if (jsonFile !== null) {
229
+ console.error('文件内容不是合法 JSON (length=' + String(raw ?? '').length + ')');
230
+ } else {
231
+ console.error('payload looks like an object literal but is not valid JSON (length=' + String(raw ?? '').length + '); use --json-file <path> to pass the payload');
232
+ }
233
+ process.exit(1);
234
+ }
235
+ }
236
+ state.evidence = state.evidence || {};
237
+ state.evidence['subagent-execute'] = state.evidence['subagent-execute'] || {};
238
+ state.evidence['subagent-execute'].handoffResult = state.evidence['subagent-execute'].handoffResult || {};
239
+ // 零提交任务语义:已有 request 记录且其写文件列表为空(无 tracked 写意图)或带 noCommit
240
+ // 标记时,判定为零提交——跳过提交文件子集校验并输出可审计提示。契约侧 noCommit 声明仅作
241
+ // 审计线索:写文件列表非空的任务即使契约声称零提交,仍执行完整提交文件子集校验(不可借
242
+ // 零提交声明绕过真实提交检查)。无 request 记录的任务不适用零提交(保持既有完整校验)。
243
+ const handoffReq = state.evidence['subagent-execute'].handoffRequests?.[taskId];
244
+ const hasRequest = !!handoffReq && typeof handoffReq === 'object';
245
+ const reqWriteFiles = hasRequest ? (handoffReq.writeFiles || []) : [];
246
+ const reqNoCommit = hasRequest && handoffReq.noCommit === true;
247
+ const contractNoCommit = typeof parsed === 'object' && parsed !== null && parsed.noCommit === true;
248
+ const isZeroCommit = hasRequest && (reqWriteFiles.length === 0 || reqNoCommit);
249
+ if (isZeroCommit) {
250
+ console.error('HANDOFF 零提交: ' + taskId + ' — 无 tracked 写文件(write_files 为空),已跳过提交文件子集校验');
251
+ // 零提交边界收紧(bot 评审实证逃逸口):声明零提交的结果若携带含 tracked 文件的提交,
252
+ // 等于从「空 write_files」旁路逃逸——新 change BLOCK / 旧 change WARN。探测异常降级
253
+ // WARN 不阻断(对齐 M4 提交对象确认提示先例)。
254
+ const zeroHash = (typeof parsed === 'object' && parsed !== null && parsed.commitHash && /^[0-9a-f]{7,40}$/i.test(String(parsed.commitHash)))
255
+ ? String(parsed.commitHash) : null;
256
+ if (zeroHash) {
257
+ const { execSync } = await import('child_process');
258
+ let committed = null;
259
+ let probeFail = false;
260
+ try {
261
+ const out = execSync('git show ' + zeroHash + ' --name-only --format=', { cwd: runRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
262
+ committed = out.split('\n').map((s) => s.trim()).filter(Boolean);
263
+ } catch {
264
+ probeFail = true;
265
+ }
266
+ if (probeFail) {
267
+ console.error('HANDOFF WARN: ' + taskId + ' 零提交提交对象不可校验——按确认提示语义不阻断');
268
+ } else if (committed.length > 0) {
269
+ const msg = taskId + ' 声明零提交但提交携带 tracked 文件: ' + committed.join(', ');
270
+ if (state.newChange === true) {
271
+ console.error('BLOCKED: ' + msg + '——回退越界文件或改按常规任务申报 write_files');
272
+ process.exit(1);
273
+ }
274
+ console.error('HANDOFF WARN: ' + msg + '(旧 change 渐进,不阻断)');
275
+ } else {
276
+ console.error('HANDOFF 零提交: ' + taskId + ' — 提交为空,校验通过');
277
+ }
278
+ }
279
+ } else if (contractNoCommit) {
280
+ console.error('HANDOFF WARN: ' + taskId + ' — 契约声明零提交但 write_files 非空,仍执行完整提交文件子集校验(零提交声明不能绕过真实提交检查)');
281
+ }
282
+ // W2-D: 完整版 hash 校验——提交文件 ⊆ writeFiles 允许范围(子集,段感知匹配;越界仅 WARN)。
283
+ // 零提交任务已在上方跳过(并输出可审计提示),此处只处理有提交哈希的常规任务。
284
+ if (typeof parsed === 'object' && parsed !== null && parsed.commitHash && /^[0-9a-f]{7,40}$/i.test(String(parsed.commitHash))) {
285
+ const commitHash = String(parsed.commitHash);
286
+ if (!isZeroCommit) {
287
+ const { execSync } = await import('child_process');
288
+ try {
289
+ const out = execSync(`git show ${commitHash} --name-only --format=`, { cwd: runRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
290
+ const committedFiles = out.split('\n').map(s => s.trim()).filter(Boolean);
291
+ // 段感知精确匹配(writeFiles 条目按路径段 glob——src/foo 不匹配 src/foobar,
292
+ // src/*.test.js 只匹配 src/ 下一层);*-SUMMARY.md 豁免收窄为精确的任务摘要路径
293
+ // (.specs/<change-id>/<task-id>-SUMMARY.md——flow-comet 强制产物,非越界)
294
+ const summaryExact = '.specs/' + state.activeChange + '/' + taskId + '-SUMMARY.md';
295
+ const violations = committedFiles.filter(f => f !== summaryExact && !reqWriteFiles.some(a => matchWriteFilePattern(f, a)));
296
+ if (violations.length > 0) {
297
+ const currentState = await readState();
298
+ if (currentState?.newChange === true) {
299
+ console.error('BLOCKED: 提交文件超出 writeFiles 范围: ' + violations.join(', ') + '——新 change 强制委托边界;恢复: 回退越界文件或扩展 write_files');
300
+ process.exit(1);
301
+ }
302
+ console.error('HANDOFF WARN: 提交文件超出 writeFiles 范围: ' + violations.join(', '));
303
+ }
304
+ } catch {
305
+ console.error('HANDOFF ERROR: commitHash 无效或 git show 失败: ' + commitHash + '——协调者需确认原因(跨仓库 worktree 提交校验降级属预期,确认后继续)');
306
+ }
307
+ }
308
+ } else if (typeof parsed === 'object' && parsed !== null && parsed.commitHash) {
309
+ console.error('HANDOFF ERROR: commitHash 格式非法: ' + String(parsed.commitHash) + '——协调者需确认原因并记录(提交对象不可校验时,确认后继续)');
310
+ }
311
+ // redEvidence 时间顺序校验——重新 result 已存在 taskId 且该 task 已有 greenEvidence
312
+ // 而无 redEvidence 时,新增 redEvidence 属于事后补录(TDD 要求 RED 先于 GREEN)→ BLOCKED。
313
+ // 同批一次性回传 red+green 不受影响;已存在 redEvidence 的记录重录(补 green)同样不受影响
314
+ const existing = state.evidence['subagent-execute'].handoffResult[taskId];
315
+ if (existing && typeof existing.result === 'object' && existing.result !== null) {
316
+ const old = existing.result;
317
+ const hasGreen = !!(old.greenEvidence && typeof old.greenEvidence === 'object' && old.greenEvidence.command);
318
+ const hasRed = !!(old.redEvidence && typeof old.redEvidence === 'object' && old.redEvidence.command);
319
+ const newRed = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
320
+ && parsed.redEvidence && typeof parsed.redEvidence === 'object' && parsed.redEvidence.command;
321
+ if (hasGreen && !hasRed && newRed) {
322
+ console.error('BLOCKED: ' + taskId + ' redEvidence 事后补录(已记录 greenEvidence 而无 redEvidence——TDD 要求 RED 先于 GREEN,禁止事后补录掩盖缺 RED)');
323
+ process.exit(1);
324
+ }
325
+ }
326
+ // 解析 Return Contract 的 completedChecks 字段(数组),缺省记 []——规范化后随
327
+ // result 一起存储,status 输出自然包含 completedChecks;guard W1-D 对条目做严格校验(
328
+ // required-skill:subagent-execute.<skill>,无旧 change 豁免),此处不拦截只规范化
329
+ // redEvidence/greenEvidence 写入 evidence 时附带 recordedAt 时间戳(时间顺序可
330
+ // 审计;重录时保留同 key 首次记录时间,避免补录覆盖原始 RED/GREEN 时序)
331
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
332
+ parsed.completedChecks = Array.isArray(parsed.completedChecks) ? parsed.completedChecks : [];
333
+ const now = new Date().toISOString();
334
+ for (const key of ['redEvidence', 'greenEvidence']) {
335
+ const ev = parsed[key];
336
+ if (ev && typeof ev === 'object' && !Array.isArray(ev)) {
337
+ const prior = existing && typeof existing.result === 'object' && existing.result !== null
338
+ && existing.result[key] && typeof existing.result[key] === 'object'
339
+ && typeof existing.result[key].recordedAt === 'string'
340
+ ? existing.result[key].recordedAt
341
+ : null;
342
+ parsed[key] = { ...ev, recordedAt: prior ?? now };
343
+ }
344
+ }
345
+ }
346
+ // C8: Return Contract 渐进校验——缺 greenEvidence/redEvidence(或 command 非字符串)仅 WARN 仍记录,
347
+ // 不 BLOCK 不拒绝(避免卡死流程);commitHash 非法格式维持上方现有 HANDOFF ERROR 行为不变
348
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
349
+ if (!parsed.greenEvidence || typeof parsed.greenEvidence !== 'object' || typeof parsed.greenEvidence.command !== 'string') {
350
+ console.error('HANDOFF WARN: ' + taskId + ' 缺 greenEvidence(未执行 TDD GREEN?)');
351
+ }
352
+ if (!parsed.redEvidence || typeof parsed.redEvidence !== 'object' || typeof parsed.redEvidence.command !== 'string') {
353
+ console.error('HANDOFF WARN: ' + taskId + ' 缺 redEvidence(未执行 TDD RED?)');
354
+ }
355
+ }
356
+ state.evidence['subagent-execute'].handoffResult[taskId] = {
357
+ result: parsed, completedAt: new Date().toISOString()
358
+ };
359
+ await writeState(state);
360
+ console.log('HANDOFF RESULT: ' + taskId);
361
+ return;
362
+ }
363
+
364
+ if (action === 'status') {
365
+ const handoff = state.evidence?.['subagent-execute'] || {};
366
+ console.log(JSON.stringify({
367
+ activeChange: state.activeChange,
368
+ handoffRequests: handoff.handoffRequests || {},
369
+ handoffResults: handoff.handoffResult || {}
370
+ }, null, 2));
371
+ return;
372
+ }
373
+
374
+ console.error('Unknown action: ' + action + '. Use: request, result, status');
375
+ process.exit(1);
376
+ }
377
+
378
+ main().catch(e => { console.error(e.message); process.exit(1); });