flow-comet 1.5.1 → 1.6.1

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 (37) hide show
  1. package/.flow-comet/rules/flow-comet-orchestration.md +1 -2
  2. package/.flow-comet/skills/flow-comet/GUIDANCE.md +22 -3
  3. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  4. package/.flow-comet/skills/flow-comet/SKILL.md +40 -3
  5. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +3 -3
  6. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +18 -17
  7. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +27 -12
  8. package/.flow-comet/skills/flow-comet/reference/recovery.md +1 -7
  9. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +21 -3
  10. package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +41 -31
  11. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +6687 -330
  12. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +25 -5
  13. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +1145 -15
  14. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +72 -3
  15. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +2077 -14
  16. package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +13 -0
  17. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +568 -501
  18. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +331 -14
  19. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +783 -40
  20. package/.flow-comet/skills/flow-comet-archive/SKILL.md +17 -0
  21. package/.flow-comet/skills/flow-comet-change/SKILL.md +2 -0
  22. package/.flow-comet/skills/flow-comet-design/SKILL.md +2 -0
  23. package/.flow-comet/skills/flow-comet-dev/SKILL.md +3 -1
  24. package/.flow-comet/skills/flow-comet-execute/SKILL.md +21 -1
  25. package/.flow-comet/skills/flow-comet-integration/SKILL.md +2 -0
  26. package/.flow-comet/skills/flow-comet-open/SKILL.md +2 -0
  27. package/.flow-comet/skills/flow-comet-plan/SKILL.md +17 -6
  28. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +2 -0
  29. package/.flow-comet/skills/flow-comet-review/SKILL.md +23 -3
  30. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +23 -11
  31. package/.flow-comet/skills/flow-comet-task/SKILL.md +7 -3
  32. package/.flow-comet/skills/flow-comet-test/SKILL.md +2 -0
  33. package/.flow-comet/skills/flow-comet-verify/SKILL.md +21 -4
  34. package/README.md +45 -115
  35. package/package.json +1 -1
  36. package/scripts/dsh-bridge.mjs +2 -2
  37. package/scripts/prepare-env.mjs +77 -46
@@ -8,7 +8,9 @@
8
8
  // specsRoot 由 runRoot 派生为 path.join(runRoot, '.specs')(与两侧调用方各自 .specs 根语义一致)。
9
9
  import { promises as fs } from 'fs';
10
10
  import path from 'path';
11
+ import { createHash } from 'crypto';
11
12
  import { taskBlocks, taskOpeningAttrs } from './task-parsing.mjs';
13
+ import { fixRoundsFor, setFixRoundsFor } from './state-schema.mjs';
12
14
 
13
15
  // 节点顺序 = 协议 nodes 顺序(disabled 过滤)。两侧路由排序共用同一实现(单一来源)。
14
16
  function route(protocol) {
@@ -112,15 +114,67 @@ function protocolTaskFilePath(protocol, changeName, specsRoot) {
112
114
  return path.join(specsRoot, changeName, taskFile);
113
115
  }
114
116
 
117
+ // 协议节点是否 enabled:route 顺序中存在且未 disabled。协议 enabled 语义以本函数为唯一来源,
118
+ // hasSubagentNode 与各消费方(含请求归属门禁)一律复用,不各自过滤。
119
+ export function protocolNodeEnabled(protocol, nodeId) {
120
+ return route(protocol).some((node) => node.id === nodeId);
121
+ }
122
+
115
123
  // 协议是否含 subagent-execute 委托节点(自定义协议可不含——此时 parallel 任务由 execute 直接消化)
116
124
  function hasSubagentNode(protocol) {
117
- return route(protocol).some((n) => n.id === 'subagent-execute');
125
+ return protocolNodeEnabled(protocol, 'subagent-execute');
118
126
  }
119
127
 
120
128
  async function fileExists(file) {
121
129
  try { await fs.access(file); return true; } catch { return false; }
122
130
  }
123
131
 
132
+ // ---------- 委托归属共享判定(纯函数 · 单一权威) ----------
133
+ // 任务属性、依赖资格、协议 enabled → 归属目标 / 不可委托原因。resolveNextNode 的下一节点
134
+ // 判定与请求归属门禁共用本段实现,禁止任一侧再内联「parallel → 目标节点」映射。
135
+ // 本段无 fs / console / process.exit / state 写入,只做确定性推导。
136
+
137
+ // 依赖资格:解析任务块的 <depends_on> 并与已完成任务 id 集合比较。依赖文本解析只此一处,
138
+ // resolveNextNode 的可委托并行过滤与消费方一律调用本函数。返回 { eligible, deps, unmet };
139
+ // 无 <depends_on> 元素或内容为空视为无依赖(eligible=true)。
140
+ export function taskDependencyEligibility(block, doneIds = new Set()) {
141
+ const depsMatch = String(block ?? '').match(/<depends_on>([\s\S]*?)<\/depends_on>/);
142
+ if (!depsMatch || !depsMatch[1].trim()) return { eligible: true, deps: [], unmet: [] };
143
+ const deps = depsMatch[1].trim().split(/[,\s]+/).filter(Boolean);
144
+ const unmet = deps.filter((dep) => !doneIds.has(dep));
145
+ return { eligible: unmet.length === 0, deps, unmet };
146
+ }
147
+
148
+ // 归属判定:输入 taskAttrs(task-parsing 开标签属性)、依赖资格、协议 enabled。
149
+ // 返回 { targetNode, delegable, reason },reason 取值:
150
+ // not-pending 任务非 pending,归属门禁不适用;
151
+ // serial pending 串行 → 归属 execute;
152
+ // no-delegation-node pending 并行但协议无 enabled 委托节点 → 门禁不适用;
153
+ // dependencies-unmet pending 并行但依赖未满足 → 当前不可委托(路由按串行消化走 execute);
154
+ // parallel-eligible pending 并行且依赖满足 → 归属 subagent-execute。
155
+ export function resolveDelegationTarget({
156
+ taskAttrs = null,
157
+ dependencyEligible = false,
158
+ subagentNodeEnabled = false,
159
+ executeNodeEnabled = true,
160
+ } = {}) {
161
+ if (!taskAttrs || taskAttrs.status !== 'pending') {
162
+ return { targetNode: null, delegable: false, reason: 'not-pending' };
163
+ }
164
+ if (taskAttrs.parallel !== true) {
165
+ return executeNodeEnabled
166
+ ? { targetNode: 'execute', delegable: true, reason: 'serial' }
167
+ : { targetNode: null, delegable: false, reason: 'no-delegation-node' };
168
+ }
169
+ if (!subagentNodeEnabled) {
170
+ return { targetNode: null, delegable: false, reason: 'no-delegation-node' };
171
+ }
172
+ if (!dependencyEligible) {
173
+ return { targetNode: null, delegable: false, reason: 'dependencies-unmet' };
174
+ }
175
+ return { targetNode: 'subagent-execute', delegable: true, reason: 'parallel-eligible' };
176
+ }
177
+
124
178
  // 判定核心(抽取自 workflow-state.mjs determineNode,行为逐字等价——重构保持锚):
125
179
  // 输入 { runRoot, changeName, protocol, completedNodes = [] } → 输出节点 id 或 null(完成态)。
126
180
  // 判定顺序:① completedNodes 全齐 → null;② execute 家族之前的节点产物门控;③ 无 execute 家族 →
@@ -150,12 +204,12 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
150
204
  // 按协议顺序拆分:execute/subagent-execute 之前的节点走产物门控(内置 = open → design → plan),
151
205
  // 之后的节点在任务全部 done 后按序门控(内置 = review → verify → archive)。
152
206
  const orderedNodes = route(protocol);
153
- const hasExecuteFamily = orderedNodes.some((n) => n.id === 'execute' || n.id === 'subagent-execute');
207
+ const hasExecuteFamily = orderedNodes.some((n) => EXECUTE_FAMILY_NODE_IDS.has(n.id));
154
208
  const preExecNodes = [];
155
209
  const postExecNodes = [];
156
210
  let sawExecuteFamily = false;
157
211
  for (const node of orderedNodes) {
158
- if (node.id === 'execute' || node.id === 'subagent-execute') {
212
+ if (EXECUTE_FAMILY_NODE_IDS.has(node.id)) {
159
213
  sawExecuteFamily = true;
160
214
  continue;
161
215
  }
@@ -193,18 +247,19 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
193
247
  if (hasSubagentNode(protocol)) {
194
248
  // 收集所有 done 任务的 id(开标签属性序无关)
195
249
  const doneIds = new Set(attrsList.filter((a) => a.status === 'done' && a.id).map((a) => a.id));
196
- // 检查 pending parallel 任务中是否有依赖已满足的(开标签 parallel="true" 且 status="pending")
197
- const parallelBlocks = taskList.filter((block) => {
198
- const a = taskOpeningAttrs(block);
199
- return a && a.parallel && a.status === 'pending';
200
- });
201
- const eligibleParallel = parallelBlocks.filter((block) => {
202
- const depsMatch = block.match(/<depends_on>([\s\S]*?)<\/depends_on>/);
203
- if (!depsMatch || !depsMatch[1].trim()) return true; // 无依赖
204
- const deps = depsMatch[1].trim().split(/[,\s]+/).filter(Boolean);
205
- return deps.every((d) => doneIds.has(d));
250
+ // 检查 pending parallel 任务中是否有依赖已满足的(开标签 parallel="true" 且 status="pending")——
251
+ // 依赖资格与归属目标一律走共享纯函数,不在本函数内联第二份判定。
252
+ const hasDelegableParallel = taskList.some((block) => {
253
+ const attrs = taskOpeningAttrs(block);
254
+ if (!attrs || attrs.parallel !== true || attrs.status !== 'pending') return false;
255
+ const dependencyEligible = taskDependencyEligibility(block, doneIds).eligible;
256
+ return resolveDelegationTarget({
257
+ taskAttrs: attrs,
258
+ dependencyEligible,
259
+ subagentNodeEnabled: true,
260
+ }).delegable;
206
261
  });
207
- if (eligibleParallel.length > 0) return 'subagent-execute';
262
+ if (hasDelegableParallel) return 'subagent-execute';
208
263
  }
209
264
  return 'execute';
210
265
  }
@@ -228,4 +283,1079 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
228
283
  return 'execute';
229
284
  }
230
285
 
231
- export { route, protocolTaskFilePath, hasSubagentNode };
286
+ // ---------- 任务依赖图分析(自 workflow-guard.mjs 迁入 · 单一权威) ----------
287
+ // 依赖图分析:对全部 <task> 块建依赖图(deps 边),Kahn 拓扑排序判环 + 缺失依赖收集。
288
+ // 返回 { ids, depsById, missing: [{id, dep}], cyclic, cycleIds }(cycleIds = 拓扑排序无解的
289
+ // 任务集合,含被环传递拖累的下游任务)。plan 出口波次校验、subagent-execute 出口孤儿检测与
290
+ // replan 重校共用同一实现(单一语义:依赖图无环 + 依赖链可满足)。
291
+ // 等价移动:判据 / 分级 / 文案零变化;依赖文本解析复用本模块 taskDependencyEligibility
292
+ // (依赖解析单一权威——不再另起第二份正则;与 guard 侧 taskDependsOn 正则逐字同语义)。
293
+ function analyzeDependencyGraph(blocks) {
294
+ const parsed = blocks
295
+ .map((block) => ({ block, attrs: taskOpeningAttrs(block) }))
296
+ .filter((x) => x.attrs && x.attrs.id);
297
+ const ids = new Set(parsed.map((x) => x.attrs.id));
298
+ const depsById = new Map();
299
+ const missing = [];
300
+ for (const x of parsed) {
301
+ const deps = [...new Set(taskDependencyEligibility(x.block).deps)];
302
+ depsById.set(x.attrs.id, deps);
303
+ for (const d of deps) {
304
+ if (!ids.has(d)) missing.push({ id: x.attrs.id, dep: d });
305
+ }
306
+ }
307
+ const indegree = new Map([...ids].map((id) => [id, 0]));
308
+ const dependents = new Map([...ids].map((id) => [id, []]));
309
+ for (const [id, deps] of depsById) {
310
+ for (const d of deps) {
311
+ if (!ids.has(d)) continue;
312
+ indegree.set(id, indegree.get(id) + 1);
313
+ dependents.get(d).push(id);
314
+ }
315
+ }
316
+ let queue = [...ids].filter((id) => indegree.get(id) === 0);
317
+ const sorted = [];
318
+ while (queue.length > 0) {
319
+ const n = queue.shift();
320
+ sorted.push(n);
321
+ for (const m of dependents.get(n)) {
322
+ indegree.set(m, indegree.get(m) - 1);
323
+ if (indegree.get(m) === 0) queue.push(m);
324
+ }
325
+ }
326
+ const cyclic = sorted.length < ids.size;
327
+ const cycleIds = cyclic ? [...ids].filter((id) => !sorted.includes(id)) : [];
328
+ return { ids, depsById, missing, cyclic, cycleIds };
329
+ }
330
+
331
+ // ---------- 并行文件依赖检测(单源:workflow-guard 门禁与 replan 重校共用) ----------
332
+ // 文件依赖检测——解析 TASK.md 的任务 read/write_files 声明,分三族返回:
333
+ // ① writeConflicts(写写强判):本趟可运行的 parallel=pending 任务间 write∩write 非空——同波次
334
+ // 并行写同一路径必竞态覆盖;
335
+ // ② readWarnings(读写弱判):并行对一方读取对方写路径——仅对彼此无显式 depends_on 关联的并行对
336
+ // 探测,有显式关联=依赖已声明,跳过→合法拓扑零新增告警;
337
+ // ③ crossTaskConflicts(同文件跨任务且无依赖路径):两个未完成任务(status 非 done)写入面重叠
338
+ // 且两任务间不存在依赖路径(depends_on 传递闭包,双向任一可达即视为已显式排序 → 放行)——
339
+ // 串行拆分出的同文件任务同样命中(未显式排序的同文件多任务);修复任务族不参与本族(族谓词
340
+ // 复用唯一权威 fixTaskClassifier,见该函数处)——其顺序由修复生命周期保证,回修同一文件是
341
+ // 必然形态;与①按任务对去重(同一对已计入写写强判则不再计入本族)。
342
+ // 编排与判定分离:族③计算抽为具名纯函数 collectCrossTaskConflicts(只做集合推导,无 fs / console /
343
+ // process.exit / 入参改写),findParallelWriteConflicts 只负责读文件、解析、族①②与去重键的组织。
344
+ // 路径解析 / 归一(parsePaths / normalizeTaskPath)为本模块单份实现,族①②③共用;依赖文本解析
345
+ // 复用本模块 taskDependencyEligibility(依赖解析单一权威——不再另起第二份正则)。
346
+ // 开标签属性解析与 workflow-state 路由共享 taskOpeningAttrs(属性序无关;不读块内文本)。
347
+ // 2026-09-28 PR 审查采纳:由 workflow-guard.mjs 抽到本模块——plan 出口与 replan 重校消费同一实现,
348
+ // 两侧各自决定强判(BLOCK)/弱判(WARN),判定本身只此一处(L-067 单一判据)。
349
+
350
+ // 任务对键(无序——不依赖任务书写顺序;NUL 分隔,任务 id 不含 NUL):同文件跨任务族与写写强判族
351
+ // 按任务对去重时使用(同一对已计入写写强判则不再计入第三族)。
352
+ function taskPairKey(a, b) {
353
+ return a < b ? a + '\u0000' + b : b + '\u0000' + a;
354
+ }
355
+
356
+ // 依赖可达集(depends_on 传递闭包):从 start 沿依赖边可达的全部任务 id(含经由其它任务中转的
357
+ // 路径)。判定语义 = 双向任一可达即视为两任务已显式排序 → 第三族放行(见上方族说明)。
358
+ function reachableTaskIds(depsById, start) {
359
+ const seen = new Set();
360
+ const stack = [...(depsById.get(start) ?? [])];
361
+ while (stack.length > 0) {
362
+ const cur = stack.pop();
363
+ if (seen.has(cur)) continue;
364
+ seen.add(cur);
365
+ for (const next of depsById.get(cur) ?? []) stack.push(next);
366
+ }
367
+ return seen;
368
+ }
369
+
370
+ // 路径归一化(CodeRabbit 采纳):分隔符统一 '/'、解 '.' 段(`./` / `a/./b`)、`..` 逃出项目根
371
+ // 按越界处理(返回 null 不参与重叠比较)——`src/a.mjs` vs `src/./a.mjs` / `src\a.mjs` 变体不再
372
+ // 绕过写写强判与读写弱判;与委托入口共用同一函数(两侧同语义)。族①②③共用本实现。
373
+ function normalizeTaskPath(raw) {
374
+ const p = String(raw).trim();
375
+ if (p === '') return null;
376
+ const segments = p.replace(/\\/g, '/').split('/').filter((s) => s !== '' && s !== '.');
377
+ const out = [];
378
+ for (const seg of segments) {
379
+ if (seg === '..') {
380
+ if (out.length === 0) return null; // 逃出项目根 → 越界(不参与比较)
381
+ out.pop();
382
+ } else {
383
+ out.push(seg);
384
+ }
385
+ }
386
+ return out.join('/');
387
+ }
388
+
389
+ // 路径解析与既有自动解析同源:剥 HTML 注释 → 换行切分 → 分号二次切分 → trim → 滤空 → 归一。
390
+ // 按声明实际内容解析,不做扩展名白名单过滤——txt/log/无扩展名路径同等检出(链式重命名的 .txt
391
+ // 事故面闭合)。族①②③共用本实现,不另起第二份。
392
+ function parsePaths(matchText) {
393
+ return String(matchText ?? '')
394
+ .replace(/<!--[\s\S]*?-->/g, '')
395
+ .trim().split(/\s*\n\s*/).map((l) => l.trim()).filter(Boolean)
396
+ .flatMap((l) => l.split(';')).map((l) => l.trim()).filter(Boolean)
397
+ .map(normalizeTaskPath)
398
+ .filter((p) => p !== null && p !== '');
399
+ }
400
+
401
+ // 第三族(同文件跨任务且无依赖路径)计算——同模块具名纯函数:输入任务块 / 依赖图 / 既有族去重键,
402
+ // 输出冲突对数组({ a, b, files });无 fs / console / process.exit,不改任何入参。
403
+ // taskContent 与 allBlocks 须同源(taskContent = 产出 allBlocks 的 TASK.md 文本)——修复任务族
404
+ // 谓词需要全文以定位 Fix 段(段标题取该谓词的缺省回退常量,与 fixTaskMarker 的缺省一致)。
405
+ function collectCrossTaskConflicts({ taskContent = '', allBlocks = [], depsById = new Map(), excludedPairKeys = new Set() } = {}) {
406
+ const isFixTask = fixTaskClassifier(taskContent);
407
+ const reachCache = new Map();
408
+ const reachableFrom = (id) => {
409
+ if (!reachCache.has(id)) reachCache.set(id, reachableTaskIds(depsById, id));
410
+ return reachCache.get(id);
411
+ };
412
+ const participants = [];
413
+ for (const block of allBlocks) {
414
+ const attrs = taskOpeningAttrs(block);
415
+ if (!attrs || !attrs.id || attrs.status === 'done' || isFixTask(block)) continue;
416
+ const wf = block.match(/<write_files>([\s\S]*?)<\/write_files>/);
417
+ if (!wf) continue;
418
+ const writes = new Set(parsePaths(wf[1]));
419
+ if (writes.size === 0) continue;
420
+ participants.push({ id: attrs.id, writes });
421
+ }
422
+ const conflicts = [];
423
+ for (let i = 0; i < participants.length; i++) {
424
+ for (let j = i + 1; j < participants.length; j++) {
425
+ if (excludedPairKeys.has(taskPairKey(participants[i].id, participants[j].id))) continue;
426
+ const overlap = [...participants[i].writes].filter((f) => participants[j].writes.has(f));
427
+ if (overlap.length === 0) continue;
428
+ if (reachableFrom(participants[i].id).has(participants[j].id)
429
+ || reachableFrom(participants[j].id).has(participants[i].id)) continue;
430
+ conflicts.push({ a: participants[i].id, b: participants[j].id, files: overlap });
431
+ }
432
+ }
433
+ return conflicts;
434
+ }
435
+
436
+ async function findParallelWriteConflicts(changeDir) {
437
+ const taskFile = path.join(changeDir, 'TASK.md');
438
+ let text;
439
+ try { text = await fs.readFile(taskFile, 'utf8'); } catch { return { writeConflicts: [], readWarnings: [], crossTaskConflicts: [] }; }
440
+ const allBlocks = taskBlocks(text);
441
+ // 依赖资格收窄:仅统计「本趟可运行」的并行任务——deps ⊆ doneIds;
442
+ // 等待后续趟次的并行任务(依赖未满足)与已交付任务不参与同趟冲突判定,
443
+ // 使 A→B 同写路径的跨趟合法计划不再被首趟误拦(与路由谓词同一口径)。
444
+ // 依赖文本解析与资格判定一律走 taskDependencyEligibility(依赖解析单一权威)——本函数不再自持
445
+ // 第二份 <depends_on> 解析,候选集过滤与读写弱判的「显式关联」判定同源。
446
+ const doneIds = new Set(allBlocks
447
+ .map((b) => taskOpeningAttrs(b))
448
+ .filter((a) => a && a.id && a.status === 'done')
449
+ .map((a) => a.id));
450
+ const blocks = allBlocks.filter((b) => {
451
+ const a = taskOpeningAttrs(b);
452
+ if (!a || !a.parallel || a.status !== 'pending') return false;
453
+ return taskDependencyEligibility(b, doneIds).eligible;
454
+ });
455
+ const perTask = [];
456
+ for (const b of blocks) {
457
+ const a = taskOpeningAttrs(b);
458
+ if (!a || !a.id) continue;
459
+ const wf = b.match(/<write_files>([\s\S]*?)<\/write_files>/);
460
+ const rf = b.match(/<read_files>([\s\S]*?)<\/read_files>/);
461
+ if (!wf && !rf) continue;
462
+ perTask.push({
463
+ id: a.id,
464
+ deps: new Set(taskDependencyEligibility(b).deps),
465
+ writes: new Set(parsePaths(wf && wf[1])),
466
+ reads: new Set(parsePaths(rf && rf[1])),
467
+ });
468
+ }
469
+ const writeConflicts = [];
470
+ const readWarnings = [];
471
+ for (let i = 0; i < perTask.length; i++) {
472
+ for (let j = i + 1; j < perTask.length; j++) {
473
+ const overlap = [...perTask[i].writes].filter((f) => perTask[j].writes.has(f));
474
+ if (overlap.length) writeConflicts.push({ a: perTask[i].id, b: perTask[j].id, files: overlap });
475
+ // 读写弱判触发面:仅无显式 depends_on 关联的并行对(有显式关联=依赖已声明,跳过)
476
+ const associated = perTask[i].deps.has(perTask[j].id) || perTask[j].deps.has(perTask[i].id);
477
+ if (associated) continue;
478
+ const readOverlap = [...perTask[i].reads].filter((f) => perTask[j].writes.has(f));
479
+ if (readOverlap.length) readWarnings.push({ a: perTask[i].id, b: perTask[j].id, files: readOverlap });
480
+ const readOverlap2 = [...perTask[j].reads].filter((f) => perTask[i].writes.has(f));
481
+ if (readOverlap2.length) readWarnings.push({ a: perTask[j].id, b: perTask[i].id, files: readOverlap2 });
482
+ }
483
+ }
484
+ // 第三族:同文件跨任务且无依赖路径(族语义见上方块注释)。编排只做三件事——族①任务对去重键、
485
+ // 依赖图(analyzeDependencyGraph 单一权威,其依赖解析走 taskDependencyEligibility)、调用具名
486
+ // 纯函数 collectCrossTaskConflicts;参与者规则(status 非 done 且非修复任务族)与依赖闭包判定
487
+ // 全在该纯函数内,此处不内联第二份。
488
+ const writePairKeys = new Set(writeConflicts.map((c) => taskPairKey(c.a, c.b)));
489
+ const { depsById } = analyzeDependencyGraph(allBlocks);
490
+ const crossTaskConflicts = collectCrossTaskConflicts({
491
+ taskContent: text,
492
+ allBlocks,
493
+ depsById,
494
+ excludedPairKeys: writePairKeys,
495
+ });
496
+ return { writeConflicts, readWarnings, crossTaskConflicts };
497
+ }
498
+
499
+ // ---------- Fix 批次共享判定(单一权威 · 纯函数) ----------
500
+ // workflow-guard 与 workflow-state 的 Fix 两态一律复用本段实现,禁止任一侧内联第二份
501
+ // (L-058 路由单一权威 / L-067 同判据两份实现必然分叉)。判定本身只读 TASK.md 与协议/产物
502
+ // 推导,无副作用、无 console 输出、无 process.exit;唯一允许写 state 的是受控归位轮次计数
503
+ // helper——它只被两个归位入口在目标命中后调用,轮次字段的读写经 state-schema 单一来源。
504
+ // execute 家族节点:协议 route 顺序中由任务状态特判的节点(与 resolveNextNode 同一划分)。
505
+ const EXECUTE_FAMILY_NODE_IDS = new Set(['execute', 'subagent-execute']);
506
+
507
+ // execute 家族之后第一个未完成节点:按协议 route 顺序跳过全部 execute 家族节点,返回其后
508
+ // 首个不在 completedNodes 中的节点 id;协议无 execute 家族或后置节点全部完成 → null。
509
+ // 这里只做通用推导(内置协议 = review → verify → archive);是否可作为 Fix 回程源由调用方
510
+ // (resolveFixReturnNode / exit apply)再用 review / verify 收窄(只覆盖内置源节点)。
511
+ function firstIncompletePostExecNode({ protocol, completedNodes = [] }) {
512
+ let sawExecuteFamily = false;
513
+ for (const node of route(protocol)) {
514
+ if (EXECUTE_FAMILY_NODE_IDS.has(node.id)) {
515
+ sawExecuteFamily = true;
516
+ continue;
517
+ }
518
+ if (sawExecuteFamily && !completedNodes.includes(node.id)) return node.id;
519
+ }
520
+ return null;
521
+ }
522
+
523
+ // 协议任务文件内容读取(taskFile 语义唯一来源):不存在 / 不可读 → null;调用方各自按
524
+ // fail-closed 语义处理(回退判定 → false,回程推导 → null),不把访问类故障当成空任务集。
525
+ async function readProtocolTaskContent(protocol, changeName, specsRoot) {
526
+ try {
527
+ return await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8');
528
+ } catch {
529
+ return null;
530
+ }
531
+ }
532
+
533
+ // TASK.md 任务集签名(唯一实现:guard 的入口记录 / 出口比对与 Fix 回退判定共用)——提取全部
534
+ // <task> 块,剥离开标签上的标记类属性(仅保留 id/parallel),排序防顺序漂移,拼接后 sha256。
535
+ // 行尾规范化——Windows 下 bash heredoc 写 LF、python 写 CRLF(os.linesep),跨工具编辑
536
+ // 导致"任务集逻辑未变但字节变"的误报 BLOCK;签名前统一 CRLF → LF(仅归一化行尾,不改变内容语义)。
537
+ // 标记类属性白名单——子代理标记 task done 会在开标签追加 completed_at/started_at/finished_at/
538
+ // assigned_to/updated_at 等属性(纯状态标记),仅剥离 status 仍误报 BLOCK;改为开标签只保留
539
+ // 影响路由语义的 id/parallel,其余属性一律剥离(含未来新增标记属性,无需再改);
540
+ // 任务内容(name/action/write_files/verify/depends_on)保持签名敏感。
541
+ //
542
+ // 算法版本元数据:值格式 <算法版本>:<digest>(如 v1:<sha256 hex>)。签名算法实现变更时必须同步
543
+ // 提升版本常量——冻结锚据此判别;新 state 的 taskHash 与 exit-applied 事件的 taskSetSignature
544
+ // 都写版本前缀,事件另带 signatureAlgo 字段;legacy 裸 hex 一律按 v1 解析;消费点只做同版本比较,
545
+ // 版本不同视为不可比(不判发散、不误归位、不误拦任务集)。
546
+ export const TASK_SET_SIGNATURE_ALGO = 'v1';
547
+ const TASK_SET_SIGNATURE_PREFIX = /^(v\d+):([0-9a-f]{64})$/u;
548
+ const TASK_SET_SIGNATURE_BARE_HEX = /^[0-9a-f]{64}$/u;
549
+ const LEGACY_TASK_SET_SIGNATURE_ALGO = 'v1';
550
+
551
+ // 内容 digest(保持既有归一化与属性剥离语义逐字不变)
552
+ function digestTaskSetContent(taskContent) {
553
+ const normalized = String(taskContent).replace(/\r\n/g, '\n');
554
+ const blocks = (normalized.match(/<task[\s\S]*?<\/task>/g) || [])
555
+ .map((block) =>
556
+ block.replace(/<task[^>]*>/, (open) =>
557
+ open.replace(/\s+[a-zA-Z_][\w-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'))?/g, (attr) =>
558
+ /^\s*(?:id|parallel)(?=[\s=>])/.test(attr) ? attr : ''
559
+ )
560
+ )
561
+ )
562
+ .sort();
563
+ return createHash('sha256').update(blocks.join('\n'), 'utf8').digest('hex');
564
+ }
565
+
566
+ // 计算签名:返回 <算法版本>:<digest>;algo 缺省为当前版本(供跨版本夹具显式传入旧版本)。
567
+ export function taskSetSignature(taskContent, algo = TASK_SET_SIGNATURE_ALGO) {
568
+ const version = String(algo ?? '').trim() || TASK_SET_SIGNATURE_ALGO;
569
+ return version + ':' + digestTaskSetContent(taskContent);
570
+ }
571
+
572
+ // 解析签名值:新格式 <vN>:<64 hex>;legacy 裸 64 hex 按 v1;空值 / 非字符串 / 其它形态 → null。
573
+ export function parseTaskSetSignature(value) {
574
+ if (typeof value !== 'string' || value === '') return null;
575
+ const prefixed = TASK_SET_SIGNATURE_PREFIX.exec(value);
576
+ if (prefixed) return { algo: prefixed[1], digest: prefixed[2] };
577
+ if (TASK_SET_SIGNATURE_BARE_HEX.test(value)) {
578
+ return { algo: LEGACY_TASK_SET_SIGNATURE_ALGO, digest: value };
579
+ }
580
+ return null;
581
+ }
582
+
583
+ // 同版本且同 digest = 一致;任一不可解析 / 版本不同 = false(调用方必须按不可比语义处理)。
584
+ export function sameTaskSetSignature(left, right) {
585
+ const a = parseTaskSetSignature(left);
586
+ const b = parseTaskSetSignature(right);
587
+ if (a === null || b === null) return false;
588
+ return a.algo === b.algo && a.digest === b.digest;
589
+ }
590
+
591
+ // 两侧均可解析但算法版本不同 → true(需要「跳过比对」而非「判为发散」的消费点使用)。
592
+ export function taskSetSignatureVersionSkew(left, right) {
593
+ const a = parseTaskSetSignature(left);
594
+ const b = parseTaskSetSignature(right);
595
+ return a !== null && b !== null && a.algo !== b.algo;
596
+ }
597
+
598
+ // history 事件 change 归属(单一权威 · L-067):state.history 跨 change 保留(select 只切
599
+ // activeChange),带 change 字段的事件只在 change 名一致时参与;无 change 字段的旧 state 事件
600
+ // 保持兼容(legacy 参与)。execute 家族出口签名读取 / Fix 回因分类 / 受控重入轮次三处一律调用
601
+ // 本函数,禁止再内联同一过滤判据(注释互指同源不是同步机制)。
602
+ function historyEventBelongsToChange(event, changeName) {
603
+ return typeof event?.change !== 'string' || event.change === changeName;
604
+ }
605
+
606
+ // 「未闭合 execute 生命周期」信号派生:取 history 中最后一次 exit-applied execute 家族事件
607
+ // 记录的 { signature, algo, node };无家族出口事件 / 该事件无签名字段(旧 state)→ null(调用方按
608
+ // 旧 change 渐进放行)。只认最新一次家族出口——更早的签名被后续闭合覆盖。
609
+ // change 归属:state.history 跨 change 保留(select 只切 activeChange),因此带 change 的事件
610
+ // 只在 change 名一致时参与判定;无 change 字段的旧 state 事件保持兼容(legacy 可参与)。
611
+ // 算法版本:事件可带 signatureAlgo(新写形态),缺省按签名值解析出的版本(legacy 裸 hex = v1);
612
+ // 声明版本与值版本不一致的畸形事件 → null(fail-closed,不参与闭合判定)。
613
+ function latestExecuteExitEvent(history, changeName) {
614
+ if (!Array.isArray(history)) return null;
615
+ for (let i = history.length - 1; i >= 0; i -= 1) {
616
+ const event = history[i];
617
+ if (!event || event.event !== 'exit-applied' || !EXECUTE_FAMILY_NODE_IDS.has(event.node)) continue;
618
+ if (!historyEventBelongsToChange(event, changeName)) continue;
619
+ if (typeof event.taskSetSignature !== 'string' || event.taskSetSignature === '') return null;
620
+ const parsed = parseTaskSetSignature(event.taskSetSignature);
621
+ if (parsed === null) return null;
622
+ if (typeof event.signatureAlgo === 'string' && event.signatureAlgo !== '' && event.signatureAlgo !== parsed.algo) return null;
623
+ return { signature: event.taskSetSignature, algo: parsed.algo, digest: parsed.digest, node: event.node };
624
+ }
625
+ return null;
626
+ }
627
+
628
+ // ---------- Fix 回因分类(共享纯函数 · 单一权威 · 展示层派生) ----------
629
+ // guard exit 回程分支在写本次 exit-applied 事件之前调用本分类器:只用既有字段派生证据(history
630
+ // 的 execute 家族出口签名 + TASK 内容结构标记),零新增 state 字段 / 事件类型。判据(DESIGN 决策 1):
631
+ // divergence = 历史任一 execute 家族 exit-applied 事件记录的 taskSetSignature ≠ 当前任务集签名;
632
+ // marker = 模板派生的 Fix 段内含 <task> 块,或全文任一任务 id 命中修复族前缀(唯一谓词
633
+ // fixTaskClassifier / 其 id 边界常量 FIX_TASK_ID_PREFIX);
634
+ // divergence ∨ marker → 'fix';有签名且不发散 → 'normal';无签名且无标记 → 'unknown'
635
+ // (旧 state 证据不足:中性输出、不 BLOCK,由调用方渲染)。
636
+ // Fix 段标题由调用方传入(guard 从 flow-kit/templates/TASK.md 的 H2 派生);缺失 / 空串
637
+ // 回退内置常量(FIX_SECTION_TITLE_FALLBACK)。history 过滤与 latestExecuteExitEvent 同语义
638
+ // (change 归属:有 change 字段且不匹配则跳过,无 change 的 legacy 事件参与);签名事件全量参与、
639
+ // 不做「只看最新」短路——多波次场景最新签名已被闭合写成当前签名,只看最新会漏判 fix。
640
+ const FIX_SECTION_TITLE_FALLBACK = 'Fix 任务';
641
+
642
+ // 共享 heading 归一(单一权威):去 ATX 标记 / 闭合 ATX 标记 / 尾部括号内容 / 编号前缀后比较,
643
+ // 让 Fix 任务、Fix 任务(来自 REVIEW / INTEGRATION)、## Fix 任务 ## 等合法写法命中同一段;
644
+ // Fix 段标题匹配与 guard 的模板段名归一均委托本实现,禁止另起第二份。
645
+ function normalizeHeading(raw) {
646
+ return String(raw ?? '')
647
+ .replace(/\r/g, '')
648
+ .replace(/^#{1,6}\s*/, '')
649
+ .replace(/\s+#+\s*$/, '')
650
+ .replace(/[((][^))\n]*[))]\s*$/u, '')
651
+ .replace(/^\d+(?:\.\d+)?\.?\s*/u, '')
652
+ .trim()
653
+ .toLowerCase();
654
+ }
655
+
656
+ // Fix 段正文切片:首个同级(##)标题命中 → 返回标题行之后、下一个同级标题(或 EOF)之前的正文;
657
+ // 无命中标题 → null。只认二级标题(### 不闭合本段);CRLF / LF 归一后按行定位。
658
+ function fixSectionBody(taskContent, fixSectionTitle) {
659
+ const lines = String(taskContent ?? '').replace(/\r\n?/g, '\n').split('\n');
660
+ const wanted = normalizeHeading(fixSectionTitle);
661
+ if (wanted === '') return null;
662
+ let start = -1;
663
+ for (let i = 0; i < lines.length; i += 1) {
664
+ const m = lines[i].match(/^##\s+(.+?)\s*$/);
665
+ if (!m) continue;
666
+ const heading = normalizeHeading(m[1]);
667
+ if (heading === wanted || heading.startsWith(wanted)) { start = i; break; }
668
+ }
669
+ if (start < 0) return null;
670
+ let end = lines.length;
671
+ for (let i = start + 1; i < lines.length; i += 1) {
672
+ if (/^##\s/.test(lines[i])) { end = i; break; }
673
+ }
674
+ return lines.slice(start + 1, end).join('\n');
675
+ }
676
+
677
+ // 修复任务族 id 前缀(唯一谓词的 id 边界,全模块只此一处定义):含尾连字符——形似编号(前缀
678
+ // 之后缺连字符的形态)不属该族;宽松前缀会把非修复编号整族放过(边界只在这里表达一次)。
679
+ const FIX_TASK_ID_PREFIX = /^[TP]-FIX-/i;
680
+
681
+ // 修复任务族唯一谓词(单一权威):返回 (block) => boolean 的判定函数——命中 id 前缀,或任务块
682
+ // 位于 Fix 段内(段定位复用 fixSectionBody / normalizeHeading 的既有标题语义,标题缺省回退
683
+ // FIX_SECTION_TITLE_FALLBACK)。fixTaskMarker 与并行文件依赖第三族的参与者排除一律调用本函数,
684
+ // 禁止任何消费方另起一套边界——id 前缀与「位于 Fix 段内」两条边界只在此处表达一次。
685
+ function fixTaskClassifier(taskContent, fixSectionTitle) {
686
+ const content = String(taskContent ?? '');
687
+ const title = (typeof fixSectionTitle === 'string' && fixSectionTitle.trim() !== '')
688
+ ? fixSectionTitle
689
+ : FIX_SECTION_TITLE_FALLBACK;
690
+ const section = fixSectionBody(content, title);
691
+ const sectionBlocks = new Set(section === null ? [] : taskBlocks(section));
692
+ return (block) => {
693
+ const attrs = taskOpeningAttrs(block);
694
+ if (!attrs || typeof attrs.id !== 'string') return false;
695
+ if (FIX_TASK_ID_PREFIX.test(attrs.id)) return true;
696
+ // 行尾归一(与任务集签名的归一纪律同源):fixSectionBody 产出 LF,而待判 block 来自原文
697
+ // (Windows 下可能是 CRLF)。不归一会让「Fix 段内非前缀 id」任务匹配失败——第三族把它当
698
+ // 普通参与者误拦,且 fixTaskMarker 同时失效。
699
+ return sectionBlocks.has(String(block ?? '').replace(/\r\n/g, '\n'));
700
+ };
701
+ }
702
+
703
+ // Fix 任务结构标记:全文存在修复任务(id 命中修复族前缀——覆盖文件尾追加等非规范落点;或 Fix 段
704
+ // 内出现 <task> 块——标题与任务需同段,段内无任务不误报)→ true;否则 false。判定一律经唯一谓词
705
+ // fixTaskClassifier,本函数只做「是否存在」的聚合,不再自持边界。
706
+ // 解析复用 taskBlocks / taskOpeningAttrs(与路由、guard 校验共享同一 <task> 解析语义)。
707
+ function fixTaskMarker(taskContent, fixSectionTitle) {
708
+ const isFixTask = fixTaskClassifier(taskContent, fixSectionTitle);
709
+ return taskBlocks(String(taskContent ?? '')).some((block) => isFixTask(block));
710
+ }
711
+
712
+ // 回因分类唯一入口。签名:classifyFixReturnCause({ history, changeName, taskContent, fixSectionTitle })
713
+ // → 'fix' | 'normal' | 'unknown'。纯函数:无 fs/console/process.exit,不改既有路由判定语义。
714
+ // 算法版本:只让与当前任务集签名同版本的历史事件参与「signatureKnown / divergence」判定;跨版本
715
+ // 事件跳过(不可比),避免引擎升级后把正常多趟误判成 Fix。
716
+ function classifyFixReturnCause({ history, changeName, taskContent, fixSectionTitle } = {}) {
717
+ const current = parseTaskSetSignature(taskSetSignature(taskContent));
718
+ let signatureKnown = false;
719
+ let divergence = false;
720
+ if (Array.isArray(history)) {
721
+ for (const event of history) {
722
+ if (!event || event.event !== 'exit-applied' || !EXECUTE_FAMILY_NODE_IDS.has(event.node)) continue;
723
+ if (!historyEventBelongsToChange(event, changeName)) continue;
724
+ if (typeof event.taskSetSignature !== 'string' || event.taskSetSignature === '') continue;
725
+ const recorded = parseTaskSetSignature(event.taskSetSignature);
726
+ if (recorded === null) continue;
727
+ if (typeof event.signatureAlgo === 'string' && event.signatureAlgo !== '' && event.signatureAlgo !== recorded.algo) continue;
728
+ if (current === null || recorded.algo !== current.algo) continue;
729
+ signatureKnown = true;
730
+ if (recorded.digest !== current.digest) divergence = true;
731
+ }
732
+ }
733
+ if (divergence || fixTaskMarker(taskContent, fixSectionTitle)) return 'fix';
734
+ return signatureKnown ? 'normal' : 'unknown';
735
+ }
736
+
737
+ // Fix 回退态决策(单一权威——guard 入口/出口与 state 的 next 分支一律复用本段):currentNode
738
+ // ∈ {review, verify} ∧ TASK.md 可解析出任务块 ∧ 以下任一:
739
+ // ① 存在 status="pending" 任务 ∧ resolveNextNode(completedNodes) ∈ execute 家族
740
+ // (串行 pending → execute;可委托 parallel pending → subagent-execute)
741
+ // → 返回 { target: 目标节点, kind: 'pending' }(受控归位的计数分支);
742
+ // ② 全任务 done ∧ execute 家族至少一个节点已在 completedNodes ∧ history 最新家族出口事件记录的
743
+ // 任务集签名与当前 TASK.md 签名不一致 → 返回 { target: 记录节点, kind: 'unclosed' }
744
+ // (done-but-unclosed:追加/修改修复任务后从未重跑家族出口;lazy entry 只刷新 taskHash、
745
+ // 不写 exit 事件,签名保持不一致)。
746
+ // 旧 state 无签名记录 / 签名不可解析 / 算法版本不同 → ② 不成立(旧 change 渐进放行,跨版本不比对)。
747
+ // TASK.md 缺失 / 不可读 / 零任务块 / 当前节点非 review|verify → null(fail-closed)。
748
+ // 路由复用唯一权威 resolveNextNode,不复制判定。
749
+ async function resolveFixRollbackDecision({ runRoot, changeName, protocol, completedNodes = [], currentNode, history = [] }) {
750
+ if (currentNode !== 'review' && currentNode !== 'verify') return null;
751
+ const taskContent = await readProtocolTaskContent(protocol, changeName, path.join(runRoot, '.specs'));
752
+ if (taskContent === null) return null;
753
+ const attrsList = taskBlocks(taskContent).map(taskOpeningAttrs).filter(Boolean);
754
+ if (attrsList.length === 0) return null;
755
+ if (attrsList.some((attrs) => attrs.status === 'pending')) {
756
+ try {
757
+ const next = await resolveNextNode({ runRoot, changeName, protocol, completedNodes });
758
+ return EXECUTE_FAMILY_NODE_IDS.has(next) ? { target: next, kind: 'pending' } : null;
759
+ } catch {
760
+ return null;
761
+ }
762
+ }
763
+ if (!attrsList.every((attrs) => attrs.status === 'done')) return null;
764
+ if (![...EXECUTE_FAMILY_NODE_IDS].some((id) => completedNodes.includes(id))) return null;
765
+ const recorded = latestExecuteExitEvent(history, changeName);
766
+ if (recorded === null) return null;
767
+ const current = parseTaskSetSignature(taskSetSignature(taskContent));
768
+ if (current === null || recorded.algo !== current.algo) return null;
769
+ return recorded.digest !== current.digest ? { target: recorded.node, kind: 'unclosed' } : null;
770
+ }
771
+
772
+ // 兼容入口:只取目标节点(既有调用方语义逐字不变);新增消费点应优先用决策形态。
773
+ async function resolveFixRollbackState(args) {
774
+ const decision = await resolveFixRollbackDecision(args);
775
+ return decision === null ? null : decision.target;
776
+ }
777
+
778
+ // ---------- Fix 受控归位轮次(单一权威 · 唯一写点) ----------
779
+ // 仅两个受控归位入口在目标命中后调用本 helper,且只对决策 kind='pending'(分支①)计数;
780
+ // 分支② done-but-unclosed、回因分类、verify 命令失败都不经此,也不得在调用方另行累加。
781
+ // 阈值语义:从第 4 轮起,新 change 返回 blocked(调用方必须先于任何 state 写盘退出,不得写入
782
+ // currentNode);旧 change 返回 warn 后照常归位。用户显式授权记录为
783
+ // state.evidence[源节点].fixRoundOverride = { round, at, source },覆盖到该轮即放行(不新增第二个顶层字段)。
784
+ // 完整授权形态:round 为正整数、at/source 均为非空字符串;任一缺失/类型非法/空串(含纯空白)
785
+ // 一律视为未授权 fail-closed——第 4 轮继续 BLOCK,调用方不写 currentNode、state 字节零改写。
786
+ // 审计行后缀由本 helper 统一给出,两个入口禁止各自拼装。
787
+
788
+ function readFixRoundOverride(state, sourceNode) {
789
+ if (typeof sourceNode !== 'string' || sourceNode === '') return null;
790
+ const sourceEvidence = state && state.evidence && typeof state.evidence === 'object' && !Array.isArray(state.evidence)
791
+ ? state.evidence[sourceNode]
792
+ : null;
793
+ const override = sourceEvidence && typeof sourceEvidence === 'object' && !Array.isArray(sourceEvidence)
794
+ ? sourceEvidence.fixRoundOverride
795
+ : null;
796
+ if (!override || typeof override !== 'object' || Array.isArray(override)) return null;
797
+ if (typeof override.round !== 'number' || !Number.isInteger(override.round) || override.round <= 0) return null;
798
+ if (typeof override.at !== 'string' || override.at.trim() === '') return null;
799
+ if (typeof override.source !== 'string' || override.source.trim() === '') return null;
800
+ return { round: override.round };
801
+ }
802
+
803
+ const FIX_ROLLBACK_ROUND_LIMIT = 3;
804
+
805
+ const EMPTY_FIX_ROLLBACK_ROUND = Object.freeze({
806
+ counted: false,
807
+ blocked: false,
808
+ warn: false,
809
+ round: null,
810
+ overrideUsed: false,
811
+ auditSuffix: '',
812
+ blockedMessage: null,
813
+ warnMessage: null,
814
+ });
815
+
816
+ function fixRoundAuditSuffix(round) {
817
+ return '(第 ' + round + '/' + FIX_ROLLBACK_ROUND_LIMIT + ' 轮)';
818
+ }
819
+
820
+ function fixRoundBlockedMessage(sourceNode, round) {
821
+ return [
822
+ 'BLOCKED: Fix 批次受控归位已达 ' + FIX_ROLLBACK_ROUND_LIMIT + ' 轮上限,第 ' + round + ' 轮需用户决策(继续修/停止)——源节点 ' + sourceNode + '。',
823
+ '恢复: 继续修 → 由用户显式授权后在 state.evidence.' + sourceNode + '.fixRoundOverride 记录 {"round":' + round + ',"at":"<时间>","source":"<授权来源>"} 再重试;停止 → 结束 Fix 批次并按流程处理(禁止手改 state 机器字段)。',
824
+ ].join('\n');
825
+ }
826
+
827
+ function applyFixRollbackRound({ state, sourceNode, decision }) {
828
+ if (!state || !decision) return EMPTY_FIX_ROLLBACK_ROUND;
829
+ if (decision.kind !== 'pending') return EMPTY_FIX_ROLLBACK_ROUND;
830
+ const round = fixRoundsFor(state) + 1;
831
+ const auditSuffix = fixRoundAuditSuffix(round);
832
+ if (round <= FIX_ROLLBACK_ROUND_LIMIT) {
833
+ setFixRoundsFor(state, round);
834
+ return { ...EMPTY_FIX_ROLLBACK_ROUND, counted: true, round, auditSuffix };
835
+ }
836
+ const override = readFixRoundOverride(state, sourceNode);
837
+ if (override !== null && override.round >= round) {
838
+ setFixRoundsFor(state, round);
839
+ return { ...EMPTY_FIX_ROLLBACK_ROUND, counted: true, round, overrideUsed: true, auditSuffix };
840
+ }
841
+ if (state.newChange === true) {
842
+ return { ...EMPTY_FIX_ROLLBACK_ROUND, blocked: true, round, auditSuffix, blockedMessage: fixRoundBlockedMessage(sourceNode, round) };
843
+ }
844
+ setFixRoundsFor(state, round);
845
+ return {
846
+ ...EMPTY_FIX_ROLLBACK_ROUND,
847
+ counted: true,
848
+ warn: true,
849
+ round,
850
+ auditSuffix,
851
+ warnMessage: 'FIX-BATCH WARN: Fix 批次受控归位已达 ' + FIX_ROLLBACK_ROUND_LIMIT + ' 轮上限,第 ' + round + ' 轮在旧 change 上渐进放行(建议用户显式授权并在 evidence 记录 fixRoundOverride)。',
852
+ };
853
+ }
854
+
855
+ // Fix 回程节点推导(共享基础):TASK.md 存在、至少一个任务块且全部 status="done" 时,
856
+ // 取 firstIncompletePostExecNode;仅当其 ∈ {review, verify}(内置回程源)才返回,否则 null。
857
+ // 仍有 pending / 零任务块 / TASK.md 缺失 → null(fail-closed)。「execute 本次 exit 前已在
858
+ // completedNodes」的二次完成条件由 exit apply 推进点判定,本函数只做 TASK + 路由推导。
859
+ async function resolveFixReturnNode({ runRoot, changeName, protocol, completedNodes = [] }) {
860
+ const taskContent = await readProtocolTaskContent(protocol, changeName, path.join(runRoot, '.specs'));
861
+ if (taskContent === null) return null;
862
+ const attrsList = taskBlocks(taskContent).map(taskOpeningAttrs).filter(Boolean);
863
+ if (attrsList.length === 0) return null;
864
+ if (!attrsList.every((attrs) => attrs.status === 'done')) return null;
865
+ const node = firstIncompletePostExecNode({ protocol, completedNodes });
866
+ return node === 'review' || node === 'verify' ? node : null;
867
+ }
868
+
869
+ // ---------- archive 源受控重入判定(单一权威 · 纯函数:目标白名单 / 前驱转移语义 / 授权形态 / 轮次上限 / 审计事件 / 空操作) ----------
870
+ // archive 已 entry 且归档移动尚未发生时,用户显式授权把工作归属退到 execute 家族 / review /
871
+ // verify 的受控回边。本段只做确定性推导(无 fs / console / process.exit / state 写入):全部
872
+ // 判定集中在这里,reenter 子命令只做编排与落盘,禁止内联第二份(L-058 路由单一权威 /
873
+ // L-067 同判据两份实现必然分叉)。信号统一用 structured result:非法 / 未授权返回
874
+ // { ok: false, reason: '<machine-code>' },不抛异常。
875
+
876
+ // 受控重入目标白名单:显式目标必须 ∈ 本集合 ∩ 协议 enabled 节点。
877
+ const REENTRY_TARGET_NODE_IDS = new Set(['execute', 'subagent-execute', 'review', 'verify']);
878
+
879
+ // 每 change 轮次上限:3 轮;调用方禁止内联阈值,必须引用本常量。
880
+ const REENTRY_ROUND_LIMIT = 3;
881
+
882
+ // change 名形态(单一权威 · 受控重入判定与 select 入口共用):change-id 必须是 .specs/ 下的
883
+ // 单段目录名——拒绝空串、路径分隔符与「.」「..」,并保留目录名 archive(归档区)不得作为
884
+ // change 名。本判据只做字符串形态判定(纯函数);「realpath 归一后仍是 .specs 真实直接子目录」
885
+ // 的物理包含性由调用方的路径段扫描(protocol-utils 单一权威)负责。
886
+ function isSingleSegmentChangeName(value) {
887
+ if (typeof value !== 'string') return false;
888
+ const name = value.trim();
889
+ if (name === '' || name === '.' || name === '..') return false;
890
+ // 原始值必须与 trim 后逐字相等:Windows 与部分文件系统忽略首尾空白/尾点,放行「空白变体」
891
+ // 会让 path.join 指到真实目录、而 activeChange 存的是变体字符串——轮次事件按 activeChange
892
+ // 精确匹配(配额被换键重置),事件归属随即失真。
893
+ if (value !== name) return false;
894
+ if (name.includes('/') || name.includes('\\')) return false;
895
+ // 保留目录名按大小写归一判定:Windows 与默认 macOS 的路径解析不区分大小写,「ARCHIVE」
896
+ // 「Archive」同样指向归档区,逐字比较会漏判。
897
+ if (name.toLowerCase() === 'archive') return false;
898
+ return true;
899
+ }
900
+
901
+ // 源判定(① · AC-5):currentNode === 'archive' 且 activeChange 是合法的单段 change 名。
902
+ // 源不是 archive / 没有活跃 change / change 名形态非法 → 未授权来源,返回 machine-code,不抛异常。
903
+ function reentrySourceDecision({ currentNode, activeChange } = {}) {
904
+ if (typeof activeChange !== 'string' || activeChange.trim() === '') {
905
+ return { ok: false, reason: 'no-active-change' };
906
+ }
907
+ if (!isSingleSegmentChangeName(activeChange)) {
908
+ return { ok: false, reason: 'change-name-invalid' };
909
+ }
910
+ if (currentNode !== 'archive') {
911
+ return { ok: false, reason: 'source-not-archive' };
912
+ }
913
+ return { ok: true, reason: 'archive-source' };
914
+ }
915
+
916
+ // 目标判定(② · AC-5):target ∈ 白名单 ∩ 协议 enabled 节点。enabled 判定复用
917
+ // protocolNodeEnabled(协议 enabled 语义唯一来源),本函数不写第二份解析;协议缺失 /
918
+ // 非对象按 fail-closed 返回未启用(L-079:解析失败不得静默放行)。
919
+ function resolveReentryTarget({ protocol, target } = {}) {
920
+ if (typeof target !== 'string' || !REENTRY_TARGET_NODE_IDS.has(target)) {
921
+ return { ok: false, reason: 'target-not-allowed' };
922
+ }
923
+ if (!protocol || typeof protocol !== 'object' || !protocolNodeEnabled(protocol, target)) {
924
+ return { ok: false, reason: 'target-not-enabled' };
925
+ }
926
+ return { ok: true, reason: 'target-allowed', target };
927
+ }
928
+
929
+ // 授权形态 fail-closed 解析(③ · AC-2):round 为正整数、at / source 均为非空(去空白)
930
+ // 字符串、authorization.target 与本次调用 target 一致;任一项非法 → 未授权,不抛异常。
931
+ // 形态与既有 Fix 轮次授权(workflow-guard readFixRoundOverride)同源,禁止第二份校验。
932
+ function parseReentryAuthorization({ authorization, target } = {}) {
933
+ if (!authorization || typeof authorization !== 'object' || Array.isArray(authorization)) {
934
+ return { ok: false, reason: 'authorization-missing' };
935
+ }
936
+ if (typeof authorization.round !== 'number' || !Number.isInteger(authorization.round) || authorization.round <= 0) {
937
+ return { ok: false, reason: 'round-invalid' };
938
+ }
939
+ if (typeof authorization.at !== 'string' || authorization.at.trim() === '') {
940
+ return { ok: false, reason: 'at-invalid' };
941
+ }
942
+ if (typeof authorization.source !== 'string' || authorization.source.trim() === '') {
943
+ return { ok: false, reason: 'source-invalid' };
944
+ }
945
+ if (typeof target !== 'string' || target === '' || authorization.target !== target) {
946
+ return { ok: false, reason: 'target-mismatch' };
947
+ }
948
+ return {
949
+ ok: true,
950
+ reason: 'authorized',
951
+ authorization: {
952
+ round: authorization.round,
953
+ at: authorization.at.trim(),
954
+ source: authorization.source.trim(),
955
+ target,
956
+ },
957
+ };
958
+ }
959
+
960
+ // 上限后的续轮授权形态(AC-7 后半句):达到上限后,用户可显式授权把轮次推进到下一轮。
961
+ // 授权三元组形态复用 parseReentryAuthorization(单一权威——不复制第二份字段校验);本函数只
962
+ // 追加续轮特有约束:round 必须覆盖即将执行的轮次(已用轮次 + 1,与既有 Fix 轮次授权的
963
+ // 「覆盖即将执行轮次」语义同型),否则视为未授权 fail-closed。未达上限时调用方不得传续轮授权
964
+ // (续轮只在人工裁决点需要)。本函数只做形态判定,不读 history。
965
+ function parseReentryContinuationAuthorization({ authorization, target, used } = {}) {
966
+ const parsed = parseReentryAuthorization({ authorization, target });
967
+ if (!parsed.ok) return parsed;
968
+ if (typeof used !== 'number' || !Number.isInteger(used) || used < 0
969
+ || parsed.authorization.round < used + 1) {
970
+ return { ok: false, reason: 'round-below-required' };
971
+ }
972
+ return { ok: true, reason: 'continuation-authorized', authorization: parsed.authorization };
973
+ }
974
+
975
+ // 轮次派生(④ · AC-7):统计 state.history 中本 change 的 reentry-applied 事件数,
976
+ // change 归属过滤调用 historyEventBelongsToChange(单一权威——不在此内联第二份,L-067)。
977
+ // 跨 change 隔离依赖事件的 change 字段:写入方(reenter 子命令)必须带 change;无 change 的
978
+ // 旧事件按 legacy 形态参与(reentry-applied 为新事件类型,实际不会出现)。history 缺失 /
979
+ // 非数组 = 无事件(旧 state 形态,0 轮)。轮次只按事件条数派生,不读事件里的 round 字段。
980
+ function reentryRoundCount({ history, changeName } = {}) {
981
+ if (!Array.isArray(history)) return 0;
982
+ let count = 0;
983
+ for (const event of history) {
984
+ if (!event || event.event !== 'reentry-applied') continue;
985
+ if (!historyEventBelongsToChange(event, changeName)) continue;
986
+ count += 1;
987
+ }
988
+ return count;
989
+ }
990
+
991
+ // 上限判定(⑤ · AC-7):已用轮次 < REENTRY_ROUND_LIMIT 或持有合法续轮授权 → 放行并给出本轮
992
+ // 序号(nextRound = 已用 + 1,供审计事件与 REENTRY 行使用);否则 blocked(调用方必须先于
993
+ // 任何 state 写盘返回,保证字节零改写)。阈值只从 REENTRY_ROUND_LIMIT 取。
994
+ function reentryRoundDecision({ history, changeName, continuationAuthorized = false } = {}) {
995
+ const used = reentryRoundCount({ history, changeName });
996
+ if (used < REENTRY_ROUND_LIMIT) {
997
+ return { ok: true, reason: 'round-available', used, nextRound: used + 1, limit: REENTRY_ROUND_LIMIT };
998
+ }
999
+ if (continuationAuthorized === true) {
1000
+ return { ok: true, reason: 'round-available-continuation', used, nextRound: used + 1, limit: REENTRY_ROUND_LIMIT };
1001
+ }
1002
+ return { ok: false, reason: 'round-limit-reached', used, limit: REENTRY_ROUND_LIMIT };
1003
+ }
1004
+
1005
+ // 协议前驱推导(⑦ 的输入):沿协议 success 边反向可达的全部祖先节点(传递闭包——对应
1006
+ // 前驱语义「清掉目标及其后继」),按协议 route 顺序(disabled 过滤)排序;failure / pause 自环、
1007
+ // target 自身与协议外节点不参与。顺序唯一来源是 route(protocol),不另写节点排序。
1008
+ function reentryPredecessors(protocol, target) {
1009
+ if (!protocol || typeof protocol !== 'object') return [];
1010
+ const order = route(protocol).map((node) => node.id);
1011
+ const ancestors = new Set();
1012
+ const queue = [target];
1013
+ while (queue.length > 0) {
1014
+ const current = queue.shift();
1015
+ for (const edge of protocol.edges ?? []) {
1016
+ if (!edge || edge.condition !== 'success' || edge.to !== current) continue;
1017
+ if (typeof edge.from !== 'string' || edge.from === '' || edge.from === target || ancestors.has(edge.from)) continue;
1018
+ ancestors.add(edge.from);
1019
+ queue.push(edge.from);
1020
+ }
1021
+ }
1022
+ return order.filter((id) => ancestors.has(id));
1023
+ }
1024
+
1025
+ // 前驱交集(⑦ · AC-8):completedNodes ∩ predecessors(target),按协议节点顺序保留原顺序。
1026
+ // completedNodes 中的协议外 / 重复项自然被过滤与去重;target 未知 / 未启用 → 空交集(fail-closed)。
1027
+ function reentryPredecessorIntersection({ protocol, target, completedNodes = [] } = {}) {
1028
+ const completed = Array.isArray(completedNodes) ? completedNodes : [];
1029
+ return reentryPredecessors(protocol, target).filter((id) => completed.includes(id));
1030
+ }
1031
+
1032
+ // 空操作判定(⑥ · 幂等锚):currentNode === target 且 completedNodes 已等于前驱交集结果
1033
+ // (同序逐项相等)→ noop(调用方不备份 / 不计数 / 不写事件);否则返回待落地的交集,调用方按
1034
+ // 前驱语义覆盖 completedNodes。判定本身不改写输入。
1035
+ function reentryNoOpDecision({ currentNode, target, protocol, completedNodes = [] } = {}) {
1036
+ const completed = Array.isArray(completedNodes) ? completedNodes : [];
1037
+ const intersection = reentryPredecessorIntersection({ protocol, target, completedNodes: completed });
1038
+ const same = currentNode === target
1039
+ && completed.length === intersection.length
1040
+ && intersection.every((id, index) => completed[index] === id);
1041
+ return same
1042
+ ? { noop: true, reason: 'noop-target-satisfied', completedNodes: intersection }
1043
+ : { noop: false, reason: 'target-state-not-satisfied', completedNodes: intersection };
1044
+ }
1045
+
1046
+ // 受控重入综合判定(单一权威聚合判定 · 供 reenter 子命令单点调用),返回三态 action:
1047
+ // 'block'(ok:false,调用方零写盘返回)、
1048
+ // 'noop' (目标形态已成立,调用方零写盘提示)、
1049
+ // 'apply'(ok:true,携带 changeName / target / 待落地 completedNodes / 本轮 round / 归一授权)。
1050
+ // 判定顺序:目标合法性(越界即使处于重复态也 BLOCK · AC-5)→ change 名形态 → 上限 →
1051
+ // 幂等短路 → 源 → 授权。
1052
+ // 幂等短路必须先于源判定:目标形态已成立时 currentNode === target ≠ 'archive',先判源会让
1053
+ // 空操作判定永远不可达;但幂等短路不得越过上限判定——达到上限的 change 即使处于同目标形态也
1054
+ // 必须走人工裁决路径(不得以空操作退出 0),也不得越过 change 名形态判定(畸形 change 名
1055
+ // 一律 BLOCK,不因形态巧合而短路)。短路分支零写盘。调用方不得内联重排或复制其中任何一条判据。
1056
+ function resolveReentryDecision({ protocol, state, target, authorization, continuationRound } = {}) {
1057
+ const targetDecision = resolveReentryTarget({ protocol, target });
1058
+ if (!targetDecision.ok) return { ok: false, action: 'block', reason: targetDecision.reason };
1059
+ const activeChange = state?.activeChange;
1060
+ if (typeof activeChange !== 'string' || activeChange.trim() === '') {
1061
+ return { ok: false, action: 'block', reason: 'no-active-change' };
1062
+ }
1063
+ if (!isSingleSegmentChangeName(activeChange)) {
1064
+ return { ok: false, action: 'block', reason: 'change-name-invalid' };
1065
+ }
1066
+ const used = reentryRoundCount({ history: state?.history, changeName: activeChange });
1067
+ const atLimit = used >= REENTRY_ROUND_LIMIT;
1068
+ let continuationAuthorized = false;
1069
+ if (atLimit) {
1070
+ const continuation = parseReentryContinuationAuthorization({
1071
+ authorization: continuationRound === undefined || continuationRound === null
1072
+ ? null
1073
+ : {
1074
+ ...(authorization && typeof authorization === 'object' && !Array.isArray(authorization) ? authorization : {}),
1075
+ round: continuationRound,
1076
+ },
1077
+ target,
1078
+ used,
1079
+ });
1080
+ if (!continuation.ok) {
1081
+ return { ok: false, action: 'block', reason: 'round-limit-reached', used, limit: REENTRY_ROUND_LIMIT };
1082
+ }
1083
+ continuationAuthorized = true;
1084
+ } else if (continuationRound !== undefined && continuationRound !== null) {
1085
+ return { ok: false, action: 'block', reason: 'continuation-not-required', used, limit: REENTRY_ROUND_LIMIT };
1086
+ }
1087
+ const noop = reentryNoOpDecision({
1088
+ currentNode: state?.currentNode,
1089
+ target,
1090
+ protocol,
1091
+ completedNodes: state?.completedNodes,
1092
+ });
1093
+ if (noop.noop && !atLimit) {
1094
+ return { ok: true, action: 'noop', reason: noop.reason, target, completedNodes: noop.completedNodes };
1095
+ }
1096
+ const source = reentrySourceDecision({
1097
+ currentNode: state?.currentNode,
1098
+ activeChange,
1099
+ });
1100
+ if (!source.ok) return { ok: false, action: 'block', reason: source.reason };
1101
+ const parsed = parseReentryAuthorization({ authorization, target });
1102
+ if (!parsed.ok) return { ok: false, action: 'block', reason: parsed.reason };
1103
+ const round = reentryRoundDecision({ history: state?.history, changeName: activeChange, continuationAuthorized });
1104
+ if (!round.ok) {
1105
+ return { ok: false, action: 'block', reason: round.reason, used: round.used, limit: round.limit };
1106
+ }
1107
+ return {
1108
+ ok: true,
1109
+ action: 'apply',
1110
+ reason: 'reentry-authorized',
1111
+ changeName: activeChange,
1112
+ target,
1113
+ completedNodes: noop.completedNodes,
1114
+ round: round.nextRound,
1115
+ continuationAuthorized,
1116
+ authorization: parsed.authorization,
1117
+ };
1118
+ }
1119
+
1120
+ // ---------- 受控计划重校重签判定(replan · 与 reentry 族同构 · 纯函数) ----------
1121
+ // 计划在执行中被证明有缺陷时的受控通道(ADR-013):仅 execute / subagent-execute 相位可用,
1122
+ // 停原位重校重签(不跳节点、不改 completedNodes)。本段只做确定性推导(无 fs / console /
1123
+ // process.exit / state 写入):相位与 change 名 / 授权形态 / 轮次上限 / 幂等空操作的唯一权威
1124
+ // 集中在这里,replan 子命令只做编排与落盘,禁止内联第二份(L-058 / L-067)。信号统一用
1125
+ // structured result:非法 / 未授权返回 { ok:false, action:'block', reason:'<machine-code>' },
1126
+ // 不抛异常。
1127
+
1128
+ // 可调用相位白名单(ADR-013 决策 2):execute 家族两个节点;调用方不得内联。
1129
+ const REPLAN_PHASE_NODE_IDS = new Set(['execute', 'subagent-execute']);
1130
+
1131
+ // 每 change 轮次上限(ADR-013 决策 6):与 reentry 的 REENTRY_ROUND_LIMIT 同值、语义独立;
1132
+ // 调用方禁止内联阈值,必须引用本常量。
1133
+ const REPLAN_ROUND_LIMIT = 3;
1134
+
1135
+ // 相位 / change 名判定(步骤 1):currentNode ∈ execute 家族 ∩ 协议 enabled;activeChange 必须
1136
+ // 是合法单段 change 名(复用 isSingleSegmentChangeName)。协议缺失 / 非对象 / 节点未启用一律
1137
+ // fail-closed(L-079:解析失败不得静默放行)。
1138
+ function replanSourceDecision({ protocol, currentNode, activeChange } = {}) {
1139
+ if (typeof activeChange !== 'string' || activeChange.trim() === '') {
1140
+ return { ok: false, reason: 'no-active-change' };
1141
+ }
1142
+ if (!isSingleSegmentChangeName(activeChange)) {
1143
+ return { ok: false, reason: 'change-name-invalid' };
1144
+ }
1145
+ if (!REPLAN_PHASE_NODE_IDS.has(currentNode)
1146
+ || !protocol || typeof protocol !== 'object'
1147
+ || !protocolNodeEnabled(protocol, currentNode)) {
1148
+ return { ok: false, reason: 'phase-not-allowed' };
1149
+ }
1150
+ return { ok: true, reason: 'replan-phase' };
1151
+ }
1152
+
1153
+ // 授权形态 fail-closed 解析(步骤 2 · ADR-013 决策 5):round 为正整数,at / source / reason
1154
+ // 均为非空(去空白)字符串,authorization.node 与调用相位一致;任一项非法 → 未授权,不抛异常。
1155
+ // 形态与 reentry 授权(parseReentryAuthorization)同族,禁止第二份字段校验。
1156
+ function parseReplanAuthorization({ authorization, node } = {}) {
1157
+ if (!authorization || typeof authorization !== 'object' || Array.isArray(authorization)) {
1158
+ return { ok: false, reason: 'authorization-missing' };
1159
+ }
1160
+ if (typeof authorization.round !== 'number' || !Number.isInteger(authorization.round) || authorization.round <= 0) {
1161
+ return { ok: false, reason: 'round-invalid' };
1162
+ }
1163
+ if (typeof authorization.at !== 'string' || authorization.at.trim() === '') {
1164
+ return { ok: false, reason: 'at-invalid' };
1165
+ }
1166
+ if (typeof authorization.source !== 'string' || authorization.source.trim() === '') {
1167
+ return { ok: false, reason: 'source-invalid' };
1168
+ }
1169
+ if (typeof authorization.reason !== 'string' || authorization.reason.trim() === '') {
1170
+ return { ok: false, reason: 'reason-invalid' };
1171
+ }
1172
+ if (typeof node !== 'string' || node === '' || authorization.node !== node) {
1173
+ return { ok: false, reason: 'node-mismatch' };
1174
+ }
1175
+ return {
1176
+ ok: true,
1177
+ reason: 'authorized',
1178
+ authorization: {
1179
+ round: authorization.round,
1180
+ at: authorization.at.trim(),
1181
+ source: authorization.source.trim(),
1182
+ reason: authorization.reason.trim(),
1183
+ node,
1184
+ },
1185
+ };
1186
+ }
1187
+
1188
+ // 上限后的续轮授权形态(步骤 3 · ADR-013 决策 6):授权形态复用 parseReplanAuthorization
1189
+ // (单一权威——不复制第二份字段校验);本函数只追加续轮特有约束:round 必须覆盖即将执行的
1190
+ // 轮次(已用轮次 + 1,与 reentry 续轮同语义),否则视为未授权 fail-closed。未达上限时调用方
1191
+ // 不得传续轮授权。本函数只做形态判定,不读 history。
1192
+ function parseReplanContinuationAuthorization({ authorization, node, used } = {}) {
1193
+ const parsed = parseReplanAuthorization({ authorization, node });
1194
+ if (!parsed.ok) return parsed;
1195
+ if (typeof used !== 'number' || !Number.isInteger(used) || used < 0
1196
+ || parsed.authorization.round < used + 1) {
1197
+ return { ok: false, reason: 'round-below-required' };
1198
+ }
1199
+ return { ok: true, reason: 'continuation-authorized', authorization: parsed.authorization };
1200
+ }
1201
+
1202
+ // 轮次派生(步骤 3 · ADR-013 决策 6/8):统计 state.history 中本 change 的 replan-applied
1203
+ // 事件数;change 归属过滤复用 historyEventBelongsToChange(单一权威,L-067)。跨 change 隔离
1204
+ // 依赖事件 change 字段;无 change 字段的旧事件按 legacy 形态参与(replan-applied 为新事件
1205
+ // 类型,实际不会出现)。history 缺失 / 非数组 = 无事件(旧 state 形态,0 轮)。
1206
+ function replanRoundCount({ history, changeName } = {}) {
1207
+ if (!Array.isArray(history)) return 0;
1208
+ let count = 0;
1209
+ for (const event of history) {
1210
+ if (!event || event.event !== 'replan-applied') continue;
1211
+ if (!historyEventBelongsToChange(event, changeName)) continue;
1212
+ count += 1;
1213
+ }
1214
+ return count;
1215
+ }
1216
+
1217
+ // 上限判定(步骤 3):已用轮次 < REPLAN_ROUND_LIMIT 或持有合法续轮授权 → 放行并给出本轮
1218
+ // 序号(nextRound = 已用 + 1,供审计事件与 REPLAN 行使用);否则 blocked(调用方必须先于任何
1219
+ // state 写盘返回,保证字节零改写)。阈值只从 REPLAN_ROUND_LIMIT 取。
1220
+ function replanRoundDecision({ history, changeName, continuationAuthorized = false } = {}) {
1221
+ const used = replanRoundCount({ history, changeName });
1222
+ if (used < REPLAN_ROUND_LIMIT) {
1223
+ return { ok: true, reason: 'round-available', used, nextRound: used + 1, limit: REPLAN_ROUND_LIMIT };
1224
+ }
1225
+ if (continuationAuthorized === true) {
1226
+ return { ok: true, reason: 'round-available-continuation', used, nextRound: used + 1, limit: REPLAN_ROUND_LIMIT };
1227
+ }
1228
+ return { ok: false, reason: 'round-limit-reached', used, limit: REPLAN_ROUND_LIMIT };
1229
+ }
1230
+
1231
+ // 空操作判定(步骤 4 · ADR-013 决策 9):目标形态已成立 = state.taskHash 已与当前 TASK.md
1232
+ // 签名同签(复用 sameTaskSetSignature / taskSetSignature 既有版本语义——算法版本偏斜按不可比
1233
+ // 处理,不误拦)→ noop(调用方零备份 / 零轮次 / 零事件 / 零改写)。判定本身不改写输入;
1234
+ // 返回 taskSetSignature 供调用方重签 / 写审计事件(避免第二份签名计算导致漂移,L-067)。
1235
+ // 依赖缺失 fail-closed(L-079):taskContent 缺失 / 非字符串 / 空串 → 不允许判空操作
1236
+ // (缺 TASK.md 时签名退化为空任务集,放行会掩盖"文件不可读"),由调用方按重校失败 BLOCK。
1237
+ function replanNoOpDecision({ state, taskContent } = {}) {
1238
+ if (typeof taskContent !== 'string' || taskContent === '') {
1239
+ return { noop: false, reason: 'task-content-missing', taskSetSignature: null };
1240
+ }
1241
+ const signature = taskSetSignature(taskContent);
1242
+ const same = sameTaskSetSignature(state?.taskHash, signature);
1243
+ return same
1244
+ ? { noop: true, reason: 'noop-target-satisfied', taskSetSignature: signature }
1245
+ : { noop: false, reason: 'target-state-not-satisfied', taskSetSignature: signature };
1246
+ }
1247
+
1248
+ // 受控重校综合判定(单一权威聚合判定 · 供 replan 子命令单点调用),返回三态 action:
1249
+ // 'block'(ok:false,调用方零写盘返回)、
1250
+ // 'noop' (目标形态已成立,调用方零写盘提示;仅当调用方传入 taskContent 时参与聚合)、
1251
+ // 'apply'(ok:true,携带 changeName / node / 本轮 round / 归一授权;taskContent 在场时附带
1252
+ // 当前任务集签名,供调用方直接重签 / 写事件)。
1253
+ // 判定顺序(DESIGN 数据流):相位与 change 名(步骤 1)→ 授权形态(步骤 2)→ 上限与续轮
1254
+ // (步骤 3)→ 幂等短路(步骤 4);任何 block 分支都先于 state 写盘,保证字节零改写。
1255
+ // 注意:幂等短路不得越过上限判定——达到上限的 change 未持显式续轮授权时一律走人工裁决路径
1256
+ // (与 reentry 族判定顺序同构)。
1257
+ // taskContent 为可选入参:提供时在授权 / 轮次通过后聚合空操作判定(缺失 / 非字符串 / 空串
1258
+ // → block,fail-closed,L-079);未提供时返回 apply/block 两态,由调用方单独调用
1259
+ // replanNoOpDecision(两处判定同源,调用方不得复制判据)。
1260
+ function resolveReplanDecision({ protocol, state, authorization, continuationRound, taskContent } = {}) {
1261
+ const currentChange = state?.activeChange;
1262
+ const node = state?.currentNode;
1263
+ const source = replanSourceDecision({ protocol, currentNode: node, activeChange: currentChange });
1264
+ if (!source.ok) return { ok: false, action: 'block', reason: source.reason };
1265
+ const parsed = parseReplanAuthorization({ authorization, node });
1266
+ if (!parsed.ok) return { ok: false, action: 'block', reason: parsed.reason };
1267
+ const used = replanRoundCount({ history: state?.history, changeName: currentChange });
1268
+ const atLimit = used >= REPLAN_ROUND_LIMIT;
1269
+ let continuationAuthorized = false;
1270
+ if (atLimit) {
1271
+ const continuation = parseReplanContinuationAuthorization({
1272
+ authorization: continuationRound === undefined || continuationRound === null
1273
+ ? null
1274
+ : {
1275
+ ...(authorization && typeof authorization === 'object' && !Array.isArray(authorization) ? authorization : {}),
1276
+ round: continuationRound,
1277
+ },
1278
+ node,
1279
+ used,
1280
+ });
1281
+ if (!continuation.ok) {
1282
+ return { ok: false, action: 'block', reason: 'round-limit-reached', used, limit: REPLAN_ROUND_LIMIT };
1283
+ }
1284
+ continuationAuthorized = true;
1285
+ } else if (continuationRound !== undefined && continuationRound !== null) {
1286
+ return { ok: false, action: 'block', reason: 'continuation-not-required', used, limit: REPLAN_ROUND_LIMIT };
1287
+ }
1288
+ if (taskContent !== undefined) {
1289
+ if (typeof taskContent !== 'string' || taskContent === '') {
1290
+ return { ok: false, action: 'block', reason: 'task-content-missing' };
1291
+ }
1292
+ const noop = replanNoOpDecision({ state, taskContent });
1293
+ if (noop.noop) {
1294
+ return {
1295
+ ok: true,
1296
+ action: 'noop',
1297
+ reason: noop.reason,
1298
+ changeName: currentChange,
1299
+ node,
1300
+ taskSetSignature: noop.taskSetSignature,
1301
+ };
1302
+ }
1303
+ }
1304
+ const round = replanRoundDecision({
1305
+ history: state?.history,
1306
+ changeName: currentChange,
1307
+ continuationAuthorized,
1308
+ });
1309
+ if (!round.ok) {
1310
+ return { ok: false, action: 'block', reason: round.reason, used: round.used, limit: round.limit };
1311
+ }
1312
+ return {
1313
+ ok: true,
1314
+ action: 'apply',
1315
+ reason: 'replan-authorized',
1316
+ changeName: currentChange,
1317
+ node,
1318
+ round: round.nextRound,
1319
+ continuationAuthorized,
1320
+ authorization: parsed.authorization,
1321
+ ...(taskContent !== undefined ? { taskSetSignature: taskSetSignature(taskContent) } : {}),
1322
+ };
1323
+ }
1324
+
1325
+ export {
1326
+ route,
1327
+ protocolTaskFilePath,
1328
+ hasSubagentNode,
1329
+ firstIncompletePostExecNode,
1330
+ EXECUTE_FAMILY_NODE_IDS,
1331
+ FIX_SECTION_TITLE_FALLBACK,
1332
+ analyzeDependencyGraph,
1333
+ findParallelWriteConflicts,
1334
+ normalizeHeading,
1335
+ classifyFixReturnCause,
1336
+ resolveFixRollbackDecision,
1337
+ resolveFixRollbackState,
1338
+ applyFixRollbackRound,
1339
+ resolveFixReturnNode,
1340
+ REENTRY_TARGET_NODE_IDS,
1341
+ REENTRY_ROUND_LIMIT,
1342
+ isSingleSegmentChangeName,
1343
+ reentrySourceDecision,
1344
+ resolveReentryTarget,
1345
+ parseReentryAuthorization,
1346
+ parseReentryContinuationAuthorization,
1347
+ reentryRoundCount,
1348
+ reentryRoundDecision,
1349
+ reentryPredecessorIntersection,
1350
+ reentryNoOpDecision,
1351
+ resolveReentryDecision,
1352
+ REPLAN_PHASE_NODE_IDS,
1353
+ REPLAN_ROUND_LIMIT,
1354
+ replanSourceDecision,
1355
+ parseReplanAuthorization,
1356
+ parseReplanContinuationAuthorization,
1357
+ replanRoundCount,
1358
+ replanRoundDecision,
1359
+ replanNoOpDecision,
1360
+ resolveReplanDecision,
1361
+ };