flow-comet 1.6.3 → 1.6.4

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