flow-comet 1.6.0 → 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 (34) hide show
  1. package/.flow-comet/skills/flow-comet/GUIDANCE.md +22 -3
  2. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  3. package/.flow-comet/skills/flow-comet/SKILL.md +20 -1
  4. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +3 -3
  5. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +15 -15
  6. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +19 -11
  7. package/.flow-comet/skills/flow-comet/reference/recovery.md +1 -7
  8. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +21 -3
  9. package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +41 -31
  10. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +2513 -295
  11. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +1 -1
  12. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +459 -11
  13. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +3 -3
  14. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +422 -10
  15. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +140 -226
  16. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +1 -1
  17. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +362 -4
  18. package/.flow-comet/skills/flow-comet-archive/SKILL.md +2 -0
  19. package/.flow-comet/skills/flow-comet-change/SKILL.md +2 -0
  20. package/.flow-comet/skills/flow-comet-design/SKILL.md +2 -0
  21. package/.flow-comet/skills/flow-comet-dev/SKILL.md +3 -1
  22. package/.flow-comet/skills/flow-comet-execute/SKILL.md +6 -4
  23. package/.flow-comet/skills/flow-comet-integration/SKILL.md +2 -0
  24. package/.flow-comet/skills/flow-comet-open/SKILL.md +2 -0
  25. package/.flow-comet/skills/flow-comet-plan/SKILL.md +17 -6
  26. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +2 -0
  27. package/.flow-comet/skills/flow-comet-review/SKILL.md +7 -5
  28. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +12 -9
  29. package/.flow-comet/skills/flow-comet-task/SKILL.md +7 -3
  30. package/.flow-comet/skills/flow-comet-test/SKILL.md +2 -0
  31. package/.flow-comet/skills/flow-comet-verify/SKILL.md +7 -5
  32. package/README.md +45 -119
  33. package/package.json +1 -1
  34. package/scripts/dsh-bridge.mjs +2 -2
@@ -1,5 +1,5 @@
1
1
  // protocol-utils.mjs: 工作流协议文件(workflow-protocol.json)的统一解析 / 受保护读取 / schema 校验模块
2
- // 批次 D T01:供 workflow-state.mjs / workflow-guard.mjs / comet-hook-guard.mjs 三脚本共用,
2
+ // 供 workflow-state.mjs / workflow-guard.mjs / comet-hook-guard.mjs 三脚本共用,
3
3
  // 替代各脚本内联的 protocolPath 硬编码,统一协议解析优先级、受保护读取与 fail-closed 校验。
4
4
  // 纯 ESM(.mjs),仅依赖 node 内置模块(fs/path),零 npm 依赖。
5
5
  //
@@ -283,6 +283,219 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
283
283
  return 'execute';
284
284
  }
285
285
 
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
+
286
499
  // ---------- Fix 批次共享判定(单一权威 · 纯函数) ----------
287
500
  // workflow-guard 与 workflow-state 的 Fix 两态一律复用本段实现,禁止任一侧内联第二份
288
501
  // (L-058 路由单一权威 / L-067 同判据两份实现必然分叉)。判定本身只读 TASK.md 与协议/产物
@@ -416,7 +629,8 @@ function latestExecuteExitEvent(history, changeName) {
416
629
  // guard exit 回程分支在写本次 exit-applied 事件之前调用本分类器:只用既有字段派生证据(history
417
630
  // 的 execute 家族出口签名 + TASK 内容结构标记),零新增 state 字段 / 事件类型。判据(DESIGN 决策 1):
418
631
  // divergence = 历史任一 execute 家族 exit-applied 事件记录的 taskSetSignature ≠ 当前任务集签名;
419
- // marker = 模板派生的 Fix 段内含 <task> 块,或全文任一任务 id 匹配 /^[TP]-FIX-/i;
632
+ // marker = 模板派生的 Fix 段内含 <task> 块,或全文任一任务 id 命中修复族前缀(唯一谓词
633
+ // fixTaskClassifier / 其 id 边界常量 FIX_TASK_ID_PREFIX);
420
634
  // divergence ∨ marker → 'fix';有签名且不发散 → 'normal';无签名且无标记 → 'unknown'
421
635
  // (旧 state 证据不足:中性输出、不 BLOCK,由调用方渲染)。
422
636
  // Fix 段标题由调用方传入(guard 从 flow-kit/templates/TASK.md 的 H2 派生);缺失 / 空串
@@ -460,21 +674,39 @@ function fixSectionBody(taskContent, fixSectionTitle) {
460
674
  return lines.slice(start + 1, end).join('\n');
461
675
  }
462
676
 
463
- // Fix 任务结构标记:全文任一任务 id 匹配 /^[TP]-FIX-/i(覆盖文件尾追加等非规范落点)→ true;
464
- // 否则 Fix 段内出现 <task> 块(标题与任务需同段,段内无任务不误报)→ true;两者皆无 → false。
465
- // 解析复用 taskBlocks / taskOpeningAttrs(与路由、guard 校验共享同一 <task> 解析语义)。
466
- function fixTaskMarker(taskContent, fixSectionTitle) {
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) {
467
686
  const content = String(taskContent ?? '');
468
687
  const title = (typeof fixSectionTitle === 'string' && fixSectionTitle.trim() !== '')
469
688
  ? fixSectionTitle
470
689
  : FIX_SECTION_TITLE_FALLBACK;
471
- const hasFixTaskId = taskBlocks(content).some((block) => {
472
- const attrs = taskOpeningAttrs(block);
473
- return Boolean(attrs && typeof attrs.id === 'string' && /^[TP]-FIX-/i.test(attrs.id));
474
- });
475
- if (hasFixTaskId) return true;
476
690
  const section = fixSectionBody(content, title);
477
- return section !== null && taskBlocks(section).length > 0;
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));
478
710
  }
479
711
 
480
712
  // 回因分类唯一入口。签名:classifyFixReturnCause({ history, changeName, taskContent, fixSectionTitle })
@@ -885,6 +1117,211 @@ function resolveReentryDecision({ protocol, state, target, authorization, contin
885
1117
  };
886
1118
  }
887
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
+
888
1325
  export {
889
1326
  route,
890
1327
  protocolTaskFilePath,
@@ -892,6 +1329,8 @@ export {
892
1329
  firstIncompletePostExecNode,
893
1330
  EXECUTE_FAMILY_NODE_IDS,
894
1331
  FIX_SECTION_TITLE_FALLBACK,
1332
+ analyzeDependencyGraph,
1333
+ findParallelWriteConflicts,
895
1334
  normalizeHeading,
896
1335
  classifyFixReturnCause,
897
1336
  resolveFixRollbackDecision,
@@ -910,4 +1349,13 @@ export {
910
1349
  reentryPredecessorIntersection,
911
1350
  reentryNoOpDecision,
912
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,
913
1361
  };
@@ -1,6 +1,6 @@
1
1
  // state-schema.mjs: state 字段类型校验表(唯一来源)
2
- // 批次 D 内置节点常量:自 workflow-state.mjs C6 内联表原样迁移,供 workflow-state / workflow-guard / workflow-handoff 三脚本共用。
3
- // 语义(与批次 C C6 完全一致):存在字段逐一校验;未知字段放行(前向兼容);缺字段放行(readState 默认补);
2
+ // 内置节点常量:自 workflow-state.mjs 的内联表原样迁移,供 workflow-state / workflow-guard / workflow-handoff 三脚本共用。
3
+ // 语义(与迁移前的内联表完全一致):存在字段逐一校验;未知字段放行(前向兼容);缺字段放行(readState 默认补);
4
4
  // 只校验存在字段的类型。调用方负责 BLOCKED / exit(1) 处理。
5
5
  import path from 'path';
6
6
  import { resolveProtocol } from './protocol-utils.mjs';
@@ -86,7 +86,7 @@ export const STATE_FIELD_VALIDATORS = [
86
86
  { field: 'enteredNodes', check: (v) => (Array.isArray(v) && v.every((x) => typeof x === 'string')) || v === undefined || v === null },
87
87
  // R6: 新 change 标记(init 写入 true——新旧判定的确定性依据,不依赖 entry;旧 state 缺失 = 旧 change 渐进兼容)
88
88
  { field: 'newChange', check: (v) => v === true || v === undefined || v === null },
89
- // E5: 批次 E 新增字段(readState 默认补后类型校验;旧 state 缺失字段放行)
89
+ // 分支模式与 PR 审查开关字段(readState 默认补后类型校验;旧 state 缺失字段放行)
90
90
  { field: 'branchMode', check: (v) => typeof v === 'boolean' },
91
91
  { field: 'enablePrReview', check: (v) => typeof v === 'boolean' },
92
92
  // 机制说明-14: 分支前缀(init --branch-prefix 可配置,适配仓库自身分支规范;缺省 'change/')