flow-comet 1.5.1 → 1.6.0

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.
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync } from 'child_process';
3
+ import { createHash } from 'crypto';
3
4
  import { promises as fs } from 'fs';
4
5
  import os from 'os';
5
6
  import path from 'path';
6
7
  import { fileURLToPath } from 'url';
7
- import { resolveProtocol, readProtocolFile, validateProtocolSchema, NODE_PROTOCOL_FILES, SKILL_PROTOCOL_FILES } from './protocol-utils.mjs';
8
- import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor, looksLikeObjectLiteral, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME } from './state-schema.mjs';
8
+ import { resolveProtocol, readProtocolFile, validateProtocolSchema, NODE_PROTOCOL_FILES, SKILL_PROTOCOL_FILES, inspectWorkflowPathSegments } from './protocol-utils.mjs';
9
+ import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor, looksLikeObjectLiteral, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME, toPersistedProtocolPath } from './state-schema.mjs';
9
10
  import { probeProject, classify, printDetection, validateContext, printGenerationGuide, skipInit } from './context-init.mjs';
10
11
  import { taskOpeningAttrs, taskBlocks } from './task-parsing.mjs';
11
- import { route, resolveNextNode, hasSubagentNode, protocolTaskFilePath } from './route-node.mjs';
12
+ import { route, resolveNextNode, hasSubagentNode, protocolTaskFilePath, resolveFixRollbackDecision, resolveFixRollbackState, applyFixRollbackRound, resolveFixReturnNode, resolveReentryDecision, isSingleSegmentChangeName, REENTRY_ROUND_LIMIT, REENTRY_TARGET_NODE_IDS, EXECUTE_FAMILY_NODE_IDS } from './route-node.mjs';
12
13
 
13
14
  const command = process.argv[2] ?? 'status';
14
15
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -33,9 +34,20 @@ async function readJson(file) {
33
34
  return JSON.parse((await fs.readFile(file, 'utf8')).replace(/^/, ''));
34
35
  }
35
36
 
37
+ // JSON 写盘统一走原子写:先写同目录临时文件,再 rename 覆盖目标——目标文件要么是旧内容、
38
+ // 要么是新内容,不会出现被截断的半写状态。写失败(磁盘满 / 权限 / 目标被占用)时清理临时文件
39
+ // 后抛出,调用方按 fail-closed 处理。状态下发是单写者形态(机器字段只由脚本通道写),
40
+ // 固定临时名与目标同目录,保证 rename 不跨卷。
36
41
  async function writeJson(file, value) {
37
42
  await fs.mkdir(path.dirname(file), { recursive: true });
38
- await fs.writeFile(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
43
+ const temporary = file + '.tmp';
44
+ try {
45
+ await fs.writeFile(temporary, JSON.stringify(value, null, 2) + '\n', 'utf8');
46
+ await fs.rename(temporary, file);
47
+ } catch (error) {
48
+ try { await fs.rm(temporary, { force: true }); } catch { /* 清理失败不掩盖原始写错误 */ }
49
+ throw error;
50
+ }
39
51
  }
40
52
 
41
53
  async function fileExists(file) {
@@ -306,26 +318,6 @@ async function determineNode(changeName, protocol, completedNodes = []) {
306
318
  return resolveNextNode({ runRoot, changeName, protocol, completedNodes });
307
319
  }
308
320
 
309
- // 回退修复豁免判定——回退修复标准路径:review/verify 阶段发现缺陷 → TASK.md 追加
310
- // pending 回退任务 → next 回 execute。三条件全满足才豁免(否则维持严格 BLOCK):
311
- // ① currentNode 为 review/verify(回退修复源节点);② TASK.md 存在 status="pending" 任务块;
312
- // ③ determineNode 推导为 execute(回退目标)。任一不满足 → 不豁免,保持严格拦截。
313
- async function tFixRollbackExempt(changeName, protocol, currentNode, completedNodes) {
314
- if (currentNode !== 'review' && currentNode !== 'verify') return false;
315
- const taskPath = path.join(specsRoot, changeName, 'TASK.md');
316
- try {
317
- const taskContent = await fs.readFile(taskPath, 'utf8');
318
- // 开标签解析(与 determineNode 同一语义):存在任一 status="pending" 任务块
319
- if (!taskBlocks(taskContent).some((b) => {
320
- const a = taskOpeningAttrs(b);
321
- return a && a.status === 'pending';
322
- })) return false;
323
- return (await determineNode(changeName, protocol, completedNodes)) === 'execute';
324
- } catch {
325
- return false;
326
- }
327
- }
328
-
329
321
  // 正常推进豁免判定——exit --apply 会把 currentNode 推进到下一节点(如 open exit 后
330
322
  // currentNode=design,该节点尚未开始故 evidence 无记录),随后按 SKILL 协议调 next(正常路径)
331
323
  // 不应被 误拦为"疑似未 exit"。判定三条件:① completedNodes 非空;② 最后一个已完成节点
@@ -444,6 +436,44 @@ async function writeState(state) {
444
436
  await writeJson(statePath, state);
445
437
  }
446
438
 
439
+ // .specs/ 下必须存在名字「逐字相等」的目录条目(change 名唯一性判据)。大小写不敏感文件系统
440
+ // (Windows / 默认 macOS)会把「CH」解析到 .specs/ch、「Archive」解析到归档区,但 activeChange
441
+ // 存的是变体字符串——轮次事件按 activeChange 精确匹配(配额被换键重置)、保留名检查按小写归一,
442
+ // 故 change 名必须等于真实目录名,大小写/空白变体一律拒绝(fail-closed)。
443
+ async function hasExactSpecsEntry(changeName) {
444
+ let entries = [];
445
+ try {
446
+ entries = await fs.readdir(specsRoot);
447
+ } catch {
448
+ return false;
449
+ }
450
+ return entries.includes(changeName);
451
+ }
452
+
453
+ // 受控重入路径边界(单一 helper:change 名形态 + realpath 直接子目录 + symlink/junction 逃逸)。
454
+ // change 名必须是单段目录名(形态单一权威在 route-node.mjs,与综合判定同源);目录必须真实存在、
455
+ // 非 symlink/junction、realpath 归一后仍在 .specs/ 内、且名字与真实目录条目逐字相等。物理包含性
456
+ // 判定复用 protocol-utils 的路径段扫描(单一权威,不写第二份路径判据);任何越界 / 链接形态 /
457
+ // 名字变体一律 BLOCK(fail-closed)。
458
+ async function inspectReentryChangeDir(changeName) {
459
+ if (typeof changeName !== 'string' || changeName.trim() === '') {
460
+ return { ok: false, reason: 'no-active-change' };
461
+ }
462
+ if (!isSingleSegmentChangeName(changeName)) {
463
+ return { ok: false, reason: 'change-name-invalid' };
464
+ }
465
+ const changeDir = path.join(specsRoot, changeName);
466
+ let inspection;
467
+ try {
468
+ inspection = await inspectWorkflowPathSegments(specsRoot, changeDir, 'reenter change dir', 'directory');
469
+ } catch (error) {
470
+ return { ok: false, reason: 'change-dir-escape', detail: error && error.message ? error.message : String(error) };
471
+ }
472
+ if (!inspection.exists) return { ok: false, reason: 'change-dir-missing' };
473
+ if (!(await hasExactSpecsEntry(changeName))) return { ok: false, reason: 'change-name-invalid' };
474
+ return { ok: true, changeDir };
475
+ }
476
+
447
477
  function generatedNodeSkillName(protocol, nodeId) {
448
478
  return protocol.name + '-' + nodeId;
449
479
  }
@@ -465,7 +495,7 @@ function printNext(protocol, nodeId, executionMode = 'subagent') {
465
495
  if (implSkill) {
466
496
  console.log('LOAD SKILL: ' + implSkill + '(用 Skill 工具,禁止跳过)');
467
497
  }
468
- if (nodeId === 'execute' || nodeId === 'subagent-execute') {
498
+ if (EXECUTE_FAMILY_NODE_IDS.has(nodeId)) {
469
499
  if (executionMode === 'direct' && nodeId === 'execute') {
470
500
  console.log('EXECUTION-MODE: direct(主代理直接执行串行任务,必须加载 flow-comet-dev 完整协议;parallel 任务仍由 subagent-execute 委托)');
471
501
  } else {
@@ -481,6 +511,16 @@ function printNext(protocol, nodeId, executionMode = 'subagent') {
481
511
  // 独立整行、行首无缩进、冒号后恰一个空格、行尾无其它字符。格式禁动(§9.5)。
482
512
  const BRIDGE_VERSION_RE = /^\/\/ BRIDGE_VERSION: ([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)$/m;
483
513
 
514
+ // dev 态后缀归一(bridge-check 版本比较):git describe 开发态形态为
515
+ // `<发布版本>-<领先提交数>-g<hash>`(例:`1.5.1-11-g93d96c0`,hash 十六进制、大小写不敏感)。
516
+ // 两侧仅在比较前剥这一种后缀、按基础版本比较——开发态载体与同基础版本的发布 loader 判健康;
517
+ // 语义化预发布标识(如 `1.5.0-rc.3`)不是 dev 态后缀、不得剥离(否则会把预发布放行成基础版本)。
518
+ // 归一仅用于比较,不改变读取到的原始值(失配报告需同时打印原始值与归一值)。
519
+ const BRIDGE_DEV_SUFFIX_RE = /-\d+-g[0-9a-f]+$/i;
520
+ function normalizeBridgeBaseVersion(version) {
521
+ return String(version).replace(BRIDGE_DEV_SUFFIX_RE, '');
522
+ }
523
+
484
524
  // $DSH_HOME 解析——与 prepare-env.mjs resolveDshHome 同语义(显式 DSH_HOME > ~/.dsh)。
485
525
  // 安装器函数位于仓库根 scripts/,技能包脚本不能跨模块 import,语义复刻保持单点契约
486
526
  // (套件断言保证双侧不漂移)。
@@ -605,7 +645,8 @@ async function runBridgeCheck() {
605
645
  report.pass.push('重复注册检查: 托管块外无同 id(dsh-flow-comet-bridge)注册行');
606
646
  }
607
647
 
608
- // ⑤ loader BRIDGE_VERSION 戳 vs 项目 INSTALLED_VERSION 偏斜(两值都打印;
648
+ // ⑤ loader BRIDGE_VERSION 戳 vs 项目 INSTALLED_VERSION 基础版本比较(两原始值都打印;
649
+ // 比较前剥离 dev 态后缀——见 normalizeBridgeBaseVersion;
609
650
  // 契约锚点正则见 T02-SUMMARY「版本戳标记行格式契约」)
610
651
  let loaderStamp = null;
611
652
  let installedVersion = null;
@@ -628,10 +669,21 @@ async function runBridgeCheck() {
628
669
  report.warn.push('近似性声明: 无法读取项目 INSTALLED_VERSION(' + installedVersionPath + ')——无法比对版本,不定论');
629
670
  }
630
671
  if (loaderStamp !== null && installedVersion !== null) {
631
- if (loaderStamp === installedVersion) {
632
- report.pass.push('版本一致性: loader BRIDGE_VERSION=' + loaderStamp + ' == 项目 INSTALLED_VERSION=' + installedVersion);
672
+ // 比较前两侧按基础版本归一(剥离 git describe dev 态后缀;预发布标识不剥)。
673
+ // 原始值逐字相同 → 既有发布态严格一致报告保持不变;
674
+ // 原始值不同但归一基础版本一致 → dev 态同基础,判健康(同时打印两原始值与基础版本);
675
+ // 归一后仍不同 → 版本偏斜:保留原「loader 原始戳 != 项目原始戳」配对(兼容既有报告读取),
676
+ // 再补打印两侧归一基础版本,便于操作者识别 dev 态后缀。
677
+ const loaderBase = normalizeBridgeBaseVersion(loaderStamp);
678
+ const installedBase = normalizeBridgeBaseVersion(installedVersion);
679
+ if (loaderBase === installedBase) {
680
+ if (loaderStamp === installedVersion) {
681
+ report.pass.push('版本一致性: loader BRIDGE_VERSION=' + loaderStamp + ' == 项目 INSTALLED_VERSION=' + installedVersion);
682
+ } else {
683
+ report.pass.push('版本一致性: loader BRIDGE_VERSION=' + loaderStamp + ' ~= 项目 INSTALLED_VERSION=' + installedVersion + '(dev 态后缀归一后基础版本 ' + loaderBase + ' 一致)');
684
+ }
633
685
  } else {
634
- report.fail.push('版本偏斜: loader BRIDGE_VERSION=' + loaderStamp + ' != 项目 INSTALLED_VERSION=' + installedVersion + '(两值如上)');
686
+ report.fail.push('版本偏斜: loader BRIDGE_VERSION=' + loaderStamp + ' != 项目 INSTALLED_VERSION=' + installedVersion + '(归一基础版本: loader=' + loaderBase + ' / installed=' + installedBase + ')——两值如上');
635
687
  }
636
688
  }
637
689
 
@@ -749,6 +801,9 @@ async function main() {
749
801
  const branchMode = isInsideWorkTree();
750
802
  const state = {
751
803
  activeChange: changeName,
804
+ // 协议来源绑定:init 解析出的协议路径持久化(项目根相对 POSIX;旧 state 缺字段 = 未绑定,
805
+ // 归属/节点门禁按渐进语义回退环境变量/默认协议)
806
+ protocolPath: toPersistedProtocolPath(runRoot, protocolPath),
752
807
  // currentNode 取协议首节点(内置协议 = open,行为不变;自定义协议 = 首节点,如 brainstorm)
753
808
  currentNode: route(protocol)[0]?.id ?? 'open',
754
809
  completedNodes: [],
@@ -756,6 +811,8 @@ async function main() {
756
811
  verifyFailures: 0,
757
812
  // verifyFailures 按 change 存储——init 新 change 从零计数(切换 change 不串扰)
758
813
  verifyFailuresByChange: {},
814
+ // Fix 受控归位轮次按 change 存储——init 写空对象;旧 state 缺字段按 0 读取
815
+ fixRoundsByChange: {},
759
816
  executionMode: 'subagent',
760
817
  directOverride: false,
761
818
  branchMode,
@@ -832,7 +889,7 @@ async function main() {
832
889
  branchMode: isInsideWorkTree(),
833
890
  enablePrReview: state.enablePrReview ?? false,
834
891
  artifactRoot: '.specs/' + changeName,
835
- coordinatorMode: ['execute', 'subagent-execute'].includes(detectedNode),
892
+ coordinatorMode: EXECUTE_FAMILY_NODE_IDS.has(detectedNode),
836
893
  // G14: 新旧 change 标记——newChange true = 新 change(严格模式);false/缺失 = 旧 change(渐进)
837
894
  newChange: state.newChange === true
838
895
  }, null, 2));
@@ -848,6 +905,57 @@ async function main() {
848
905
  return;
849
906
  }
850
907
  const state = await readState();
908
+ const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
909
+ // Fix 回退显式分支——必须早于「疑似未 exit」门禁与进行中漂移保护:
910
+ // review/verify 驻留 + TASK 有 pending 修复任务(串行/并行)或未闭合家族出口签名时,把工作
911
+ // 归属受控归位共享谓词返回的 execute 家族目标(写盘)并显式输出 NODE: <目标>,不再依赖
912
+ // inProgress 保护副作用(修复前并行任务 next 输出仍停在源节点)。判定复用 route-node 共享纯函数。
913
+ const fixRollbackDecision = await resolveFixRollbackDecision({
914
+ runRoot, changeName, protocol, completedNodes: completedArr, currentNode: state.currentNode,
915
+ history: state.history,
916
+ });
917
+ if (fixRollbackDecision) {
918
+ const sourceNode = state.currentNode;
919
+ // 轮次计数与阈值/授权判定全部走共享 helper:分支②不计数;第 4 轮新 change 先 BLOCK
920
+ // (此处尚未写盘,满足不写 currentNode),旧 change WARN 后照常归位。
921
+ const rollbackRound = applyFixRollbackRound({ state, sourceNode, decision: fixRollbackDecision });
922
+ if (rollbackRound.blocked) {
923
+ console.error(rollbackRound.blockedMessage);
924
+ process.exit(1);
925
+ }
926
+ if (rollbackRound.warn) console.error(rollbackRound.warnMessage);
927
+ state.currentNode = fixRollbackDecision.target;
928
+ await writeState(state);
929
+ console.log('FIX-BATCH: 归位 ' + fixRollbackDecision.target + '(源节点 ' + sourceNode + ')' + rollbackRound.auditSuffix);
930
+ printNext(protocol, fixRollbackDecision.target, state.executionMode ?? 'subagent');
931
+ printBranchLine(changeName, state.branchPrefix ?? 'change/');
932
+ return;
933
+ }
934
+ // Fix 回程豁免——exit execute --apply 二次完成把 currentNode 回推源节点后,
935
+ // 源节点产物(REVIEW.md / TEST.md+UAT.md)已在场会让 resolveNextNode 跳过尚未 exit 的
936
+ // 源节点;仅当源节点未完成、任务全 done、firstIncompletePostExecNode === currentNode
937
+ // 且 resolveNextNode 确实会跳过该节点时显式放行(只读不改写 state)。artifactNext ===
938
+ // currentNode 的形态落回既有正常逻辑(normalAdvanceExempt 覆盖),不放宽豁免面。
939
+ const fixReturnNode = state.activeChange
940
+ ? await resolveFixReturnNode({ runRoot, changeName, protocol, completedNodes: completedArr })
941
+ : null;
942
+ if (fixReturnNode !== null && fixReturnNode === state.currentNode) {
943
+ const artifactNext = await resolveNextNode({ runRoot, changeName, protocol, completedNodes: completedArr });
944
+ const routeIds = route(protocol).map((node) => node.id);
945
+ const artifactNextIdx = routeIds.indexOf(artifactNext);
946
+ const currentIdx = routeIds.indexOf(state.currentNode);
947
+ // 「跳过」必须是产物存在性把路由推到源节点之后;artifactNext 落在源节点之前(如 execute
948
+ // 产物缺失时回退到 execute)不是合法回程态,落回既有门禁,防止越界放宽(既有门禁反例锚)。
949
+ const skipsForward = artifactNext !== state.currentNode
950
+ && currentIdx >= 0
951
+ && artifactNextIdx > currentIdx;
952
+ if (skipsForward) {
953
+ console.log('RETURN: 回程源节点 ' + fixReturnNode + '(源节点产物在场且未出口;保留源节点跑出口)');
954
+ printNext(protocol, state.currentNode, state.executionMode ?? 'subagent');
955
+ printBranchLine(changeName, state.branchPrefix ?? 'change/');
956
+ return;
957
+ }
958
+ }
851
959
  // 节点顺序校验(严格模式)——state.currentNode 非 null、不在 completedNodes、
852
960
  // 且 evidence 无该节点记录 → 上一节点从未 exit 就推进 → BLOCKED(exit 1)。
853
961
  // 状态漂移校正保留:已完成节点(currentNode ∈ completedNodes,或 evidence 已记录——
@@ -855,17 +963,19 @@ async function main() {
855
963
  // 豁免(两种独立判断,任一成立即放行): 回退豁免(TASK.md 有 pending 回退修复任务 回 execute);
856
964
  // 正常推进豁免(currentNode 是 completedNodes 最后节点 exit 推进的正常下一节点,
857
965
  // 见 normalAdvanceExempt)——真乱序(跳节点)仍严格 BLOCK
858
- const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
859
966
  if (state.currentNode && !completedArr.includes(state.currentNode)) {
860
967
  const nodeEvidence = state.evidence && typeof state.evidence === 'object'
861
968
  ? state.evidence[state.currentNode]
862
969
  : null;
863
970
  const hasEvidence = !!(nodeEvidence && typeof nodeEvidence === 'object' && !Array.isArray(nodeEvidence));
864
971
  if (!hasEvidence) {
865
- // 回退豁免——review/verify 发现缺陷追加 pending 修复任务后回 execute 的
866
- // 修复任务标准回退路径放行(否则被 严格模式误拦为"未 exit 跳阶段");
867
- // 豁免条件不满足时维持严格 BLOCK
868
- const rollbackExempt = await tFixRollbackExempt(changeName, protocol, state.currentNode, completedArr);
972
+ // 回退豁免(显式分支已先行;此处按共享谓词保留门禁层语义,不再内联第二份判定)——
973
+ // review/verify 发现缺陷追加 pending 修复任务后回 execute 的修复任务标准回退路径放行
974
+ // (否则被严格模式误拦为"未 exit 跳阶段");豁免条件不满足时维持严格 BLOCK
975
+ const rollbackExempt = await resolveFixRollbackState({
976
+ runRoot, changeName, protocol, completedNodes: completedArr, currentNode: state.currentNode,
977
+ history: state.history,
978
+ });
869
979
  // 正常推进豁免——exit --apply 推进 currentNode 到下一节点后按 SKILL 协议调 next
870
980
  // (正常路径)不拦截;与 回退豁免独立判断(详见 normalAdvanceExempt 注释)
871
981
  const advanceExempt = await normalAdvanceExempt(state, protocol, completedArr, state.currentNode, changeName);
@@ -883,7 +993,7 @@ async function main() {
883
993
  // 防止静默路由到无法推进的节点造成死循环/死等。协议无 subagent-execute 节点时不适用
884
994
  // (parallel 任务由 execute 直接消化,无孤儿语义)。依赖环的常规拦截点在 plan 出口(guard 前置),
885
995
  // 此处兜底执行期数据异常(如手改 TASK 绕过签名校验的极端态)。
886
- if (detectedNode === 'execute' || detectedNode === 'subagent-execute') {
996
+ if (EXECUTE_FAMILY_NODE_IDS.has(detectedNode)) {
887
997
  if (hasSubagentNode(protocol)) {
888
998
  try {
889
999
  const zpBlocks = taskBlocks(await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8'));
@@ -963,8 +1073,30 @@ async function main() {
963
1073
  if (command === 'select') {
964
1074
  const changeName = process.argv[3];
965
1075
  if (!changeName) throw new Error('select requires a change name.');
1076
+ // change 名必须是 .specs/ 下的单段目录名(形态单一权威在 route-node.mjs):拒绝路径分隔符、
1077
+ // . / .. 与保留目录 archive(归档区不是活跃 change)——多段路径会把归档目录等非 change
1078
+ // 目录选成 activeChange,进而污染后续命令的 change 归属与轮次派生。
1079
+ if (!isSingleSegmentChangeName(changeName)) {
1080
+ throw new Error('select change 名必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive): '
1081
+ + JSON.stringify(changeName));
1082
+ }
966
1083
  const changeDir = path.join(specsRoot, changeName);
967
- if (!(await fileExists(changeDir))) throw new Error('Change not found: ' + changeDir);
1084
+ // 目录必须真实存在且不是 symlink/junction、realpath 归一后仍在 .specs/ 内(复用路径段扫描
1085
+ // 单一权威);越界 / 链接形态一律拒绝,不把非真实目录选为 activeChange。
1086
+ let inspection;
1087
+ try {
1088
+ inspection = await inspectWorkflowPathSegments(specsRoot, changeDir, 'select change dir', 'directory');
1089
+ } catch (error) {
1090
+ throw new Error('Change not found or path unsafe: ' + changeDir + '(' + (error && error.message ? error.message : error) + ')');
1091
+ }
1092
+ if (!inspection.exists) throw new Error('Change not found: ' + changeDir);
1093
+ // 名字必须与 .specs/ 下真实目录条目逐字相等:大小写/空白变体(如 .specs/ch 用 'CH' 选中)
1094
+ // 在大小写不敏感文件系统上同样可达,但会把 activeChange 存成变体字符串——轮次事件按
1095
+ // activeChange 精确匹配(配额被换键重置)。名字变体一律拒绝,不得改写 activeChange。
1096
+ if (!(await hasExactSpecsEntry(changeName))) {
1097
+ throw new Error('select change 名必须与 .specs/ 下真实目录名逐字相等(大小写/空白变体会使 activeChange 与实际目录不一致): '
1098
+ + JSON.stringify(changeName));
1099
+ }
968
1100
  const state = await readState();
969
1101
  state.activeChange = changeName;
970
1102
  if (!state.currentNode) state.currentNode = await determineNode(changeName, protocol, state.completedNodes);
@@ -1254,7 +1386,260 @@ async function main() {
1254
1386
  return;
1255
1387
  }
1256
1388
 
1257
- throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check');
1389
+ if (command === 'reenter') {
1390
+ // 受控重入(archive 源回边):archive 已 entry 且归档移动尚未发生时,用户显式授权把工作归属
1391
+ // 退回执行家族 / review / verify 之一。命令形态:reenter <target> --authorized-by <source>
1392
+ // --reason <text> [--continue-round <n>]。编排顺序:参数防护 → 路径边界(change 名单段 +
1393
+ // realpath 直接子目录)→ 单一权威判定(目标 / change 名 / 上限 / 幂等 / 源 / 授权)→ 备份
1394
+ // (包含性复核)→ 转移 → 授权留痕 → 审计事件 → REENTRY 行。全部判定集中在 route-node.mjs
1395
+ // 纯函数(本命令只做编排与落盘,禁止内联第二份);BLOCK 与空操作路径一律在写盘前返回
1396
+ // (state 字节零改写)。
1397
+ const target = process.argv[3];
1398
+ const reentryTargetList = [...REENTRY_TARGET_NODE_IDS].join(', ');
1399
+ const reenterUsage = '用法: workflow-state.mjs reenter <target> --authorized-by <source> --reason <text>'
1400
+ + ' [--continue-round <n>](target 白名单: ' + reentryTargetList + ')';
1401
+ if (typeof target !== 'string' || target === '' || target.startsWith('--')) {
1402
+ console.error('BLOCKED: reenter 缺少目标节点。' + reenterUsage);
1403
+ process.exit(1);
1404
+ }
1405
+ let authorizedBy = null;
1406
+ let reason = null;
1407
+ let continuationRound = null;
1408
+ const reenterArgs = process.argv.slice(4);
1409
+ for (let index = 0; index < reenterArgs.length; index += 1) {
1410
+ const arg = reenterArgs[index];
1411
+ // 支持 --name value 与 --name=value 两种形态;--protocol 为全局参数(协议路径已由
1412
+ // resolveProtocol 统一解析),命令面只做占位透传。
1413
+ let key = arg;
1414
+ let value = null;
1415
+ if (typeof arg === 'string' && arg.startsWith('--')) {
1416
+ const eq = arg.indexOf('=');
1417
+ if (eq > 0) {
1418
+ key = arg.slice(0, eq);
1419
+ value = arg.slice(eq + 1);
1420
+ }
1421
+ }
1422
+ if (key === '--protocol') {
1423
+ if (value === null) index += 1;
1424
+ continue;
1425
+ }
1426
+ if (key === '--continue-round') {
1427
+ // 续轮授权只在达到轮次上限后生效:命令面收正整数,形态合法性与「是否已到上限」由
1428
+ // 单一权威综合判定裁决(本处只做数值形态防护,fail-closed,先于任何读盘)。
1429
+ let consumedNext = false;
1430
+ if (value === null) {
1431
+ value = reenterArgs[index + 1];
1432
+ consumedNext = true;
1433
+ }
1434
+ const parsedRound = typeof value === 'string' && value.trim() !== '' && !value.startsWith('--')
1435
+ ? Number(value.trim())
1436
+ : Number.NaN;
1437
+ if (!Number.isInteger(parsedRound) || parsedRound <= 0) {
1438
+ console.error('BLOCKED: reenter --continue-round 需要正整数取值,实际 ' + JSON.stringify(value) + '。' + reenterUsage);
1439
+ process.exit(1);
1440
+ }
1441
+ continuationRound = parsedRound;
1442
+ if (consumedNext) index += 1;
1443
+ continue;
1444
+ }
1445
+ if (key === '--authorized-by' || key === '--reason') {
1446
+ let consumedNext = false;
1447
+ if (value === null) {
1448
+ value = reenterArgs[index + 1];
1449
+ consumedNext = true;
1450
+ }
1451
+ // 缺值 / 空值 / 纯空白 / 取下个选项名当值 → 一律用法错误(fail-closed,先于任何读盘)
1452
+ if (typeof value !== 'string' || value.trim() === '' || value.startsWith('--')) {
1453
+ console.error('BLOCKED: reenter ' + key + ' 需要非空取值。' + reenterUsage);
1454
+ process.exit(1);
1455
+ }
1456
+ if (key === '--authorized-by') authorizedBy = value.trim();
1457
+ else reason = value.trim();
1458
+ if (consumedNext) index += 1;
1459
+ continue;
1460
+ }
1461
+ console.error('BLOCKED: reenter 未知参数 ' + JSON.stringify(arg) + '。' + reenterUsage);
1462
+ process.exit(1);
1463
+ }
1464
+ if (authorizedBy === null) {
1465
+ console.error('BLOCKED: reenter 需要显式授权 --authorized-by <source>(授权不可自决)。' + reenterUsage);
1466
+ process.exit(1);
1467
+ }
1468
+ if (reason === null) {
1469
+ console.error('BLOCKED: reenter 需要 --reason <text> 说明重入原因。' + reenterUsage);
1470
+ process.exit(1);
1471
+ }
1472
+ const state = await readState();
1473
+ const badFields = validateStateFields(state);
1474
+ if (badFields.length > 0) {
1475
+ // history 存在但非数组等类型损坏在此 fail-closed:不得由本命令静默清空覆盖审计历史。
1476
+ console.error('BLOCKED: state 字段类型非法: ' + badFields[0]);
1477
+ process.exit(1);
1478
+ }
1479
+ // 原始 state(未经 readState 兼容默认值叠加):落盘时只写「原始键集 + 本次实际改动的字段」,
1480
+ // 兼容默认值不得随重入回写(最小旧 state 的键集保持逐项不变)。
1481
+ const rawState = (await fileExists(statePath)) ? await readJson(statePath) : null;
1482
+ // 路径边界:change 名必须是 .specs/ 下的单段真实目录(realpath 归一后是 .specs 直接子目录,
1483
+ // 且路径上无 symlink/junction)。归档移动已发生(目录不在原位)、change 已 completed、
1484
+ // change 名畸形(多段 / . / .. / 保留目录 archive)与链接逃逸一律 BLOCK。该边界先于综合
1485
+ // 判定执行——completed 与已移动形态必须无条件 BLOCK(不被空操作分支短路)。
1486
+ const changeName = typeof state.activeChange === 'string' ? state.activeChange : '';
1487
+ const changeBoundary = await inspectReentryChangeDir(changeName);
1488
+ const changeDirPresent = changeBoundary.ok
1489
+ ? true
1490
+ : (changeBoundary.reason === 'change-dir-missing' ? false : null);
1491
+ const movedOrCompletedMessage = 'BLOCKED: 归档移动已发生或 change 已 completed(.specs/'
1492
+ + (changeName || '<未知>') + '/ 在场=' + changeDirPresent + ',status=' + JSON.stringify(state.status)
1493
+ + ')——受控重入只覆盖归档移动前的运行形态;请走人工处置、新 change 或 hotfix 路径。';
1494
+ if (state.status === 'completed' || changeDirPresent === false) {
1495
+ console.error(movedOrCompletedMessage);
1496
+ process.exit(1);
1497
+ }
1498
+ if (!changeBoundary.ok) {
1499
+ const boundaryMessages = {
1500
+ 'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
1501
+ 'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
1502
+ + '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
1503
+ 'change-dir-escape': 'change 目录路径越界或跨越符号链接 / junction(' + changeBoundary.detail
1504
+ + ')——受控重入与备份只允许落在 .specs/<change-id>/ 真实目录内',
1505
+ };
1506
+ console.error('BLOCKED: ' + boundaryMessages[changeBoundary.reason]);
1507
+ process.exit(1);
1508
+ }
1509
+ const changeDir = changeBoundary.changeDir;
1510
+ // 授权形态的 round / at 由引擎派生(命令面只承载授权来源、原因与上限后的续轮轮次):普通轮次
1511
+ // 以合法占位值过形态门;落盘轮次一律取综合判定返回的 round(由本 change 历史事件派生),
1512
+ // 不在此内联第二份轮次推导。
1513
+ const authorizedAt = new Date().toISOString();
1514
+ const decision = resolveReentryDecision({
1515
+ protocol,
1516
+ state,
1517
+ target,
1518
+ authorization: { round: 1, at: authorizedAt, source: authorizedBy, target },
1519
+ continuationRound,
1520
+ });
1521
+ if (!decision.ok) {
1522
+ if (decision.reason === 'round-limit-reached') {
1523
+ console.error('BLOCKED: 本 change 受控重入已达上限(' + decision.used + '/' + decision.limit
1524
+ + ' 轮)。需要人工裁决:继续(显式授权后在同一命令加 --continue-round <n>,n 为不小于第 '
1525
+ + (decision.used + 1) + ' 轮的正整数,须与 --authorized-by / --reason 同次传入)/ 停止(保持归档态,不再重入)。');
1526
+ process.exit(1);
1527
+ }
1528
+ const guidance = {
1529
+ 'target-not-allowed': '目标节点 ' + JSON.stringify(target) + ' 不在受控重入白名单('
1530
+ + reentryTargetList + ')——请显式指定白名单内目标',
1531
+ 'target-not-enabled': '目标节点 ' + JSON.stringify(target)
1532
+ + ' 在当前协议中未启用(disabled)——请检查协议或改选已启用目标',
1533
+ 'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
1534
+ 'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
1535
+ + '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
1536
+ 'source-not-archive': '受控重入只覆盖 archive 源(当前节点 ' + JSON.stringify(state.currentNode)
1537
+ + ')——正常推进请走 next / record / exit 既有通道',
1538
+ 'continuation-not-required': '--continue-round 只在达到轮次上限后需要(当前 ' + decision.used + '/'
1539
+ + decision.limit + ' 轮)——上限前请直接以 --authorized-by / --reason 发起',
1540
+ }[decision.reason] || ('授权形态不合法(' + decision.reason + ')——需要用户显式传入 --authorized-by <source>');
1541
+ console.error('BLOCKED: ' + guidance);
1542
+ process.exit(1);
1543
+ }
1544
+ if (decision.action === 'noop') {
1545
+ console.log('REENTRY: 空操作——workflow 已处于目标形态(' + target
1546
+ + ',完成标记已是目标前驱交集);未备份、未计数、未改写 state。');
1547
+ return;
1548
+ }
1549
+ if (decision.action !== 'apply') {
1550
+ console.error('BLOCKED: 受控重入判定返回未知动作 ' + JSON.stringify(decision.action) + '——按 fail-closed 拒绝。');
1551
+ process.exit(1);
1552
+ }
1553
+ const round = decision.round;
1554
+ const source = decision.authorization.source;
1555
+ const at = decision.authorization.at;
1556
+ const continuationAuthorized = decision.continuationAuthorized === true;
1557
+ // 备份:重入前 state 全量快照(文件原始字节,UTF-8 BOM 按可解析形态落盘);文件名
1558
+ // <UTC ISO 净化>-pre-<target>.json;审计指纹 = 备份文件字节的 sha256(可核验)。
1559
+ const backupDir = path.join(changeDir, '.reentry-backups');
1560
+ const backupFile = at.replace(/:/g, '-') + '-pre-' + target + '.json';
1561
+ const backupPath = path.join(backupDir, backupFile);
1562
+ const backupRecord = path.relative(runRoot, backupPath).split(path.sep).join('/');
1563
+ const snapshotBytes = Buffer.from((await fs.readFile(statePath, 'utf8')).replace(/^\uFEFF/, ''), 'utf8');
1564
+ const fingerprint = createHash('sha256').update(snapshotBytes).digest('hex');
1565
+ const existingHistory = Array.isArray(rawState?.history) ? rawState.history : [];
1566
+ let backupWritten = false;
1567
+ try {
1568
+ if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
1569
+ throw new Error('state 文件缺失或形态非法,无法重入');
1570
+ }
1571
+ // 备份写入路径的物理包含性复核(单一权威路径段扫描):备份目录与备份文件逐段
1572
+ // lstat + realpath——任何 symlink/junction 逃出 .specs/ 一律拒绝,不写任何字节。
1573
+ await fs.mkdir(backupDir, { recursive: true });
1574
+ await inspectWorkflowPathSegments(specsRoot, backupDir, 'reenter backup dir', 'directory');
1575
+ await fs.writeFile(backupPath, snapshotBytes);
1576
+ backupWritten = true;
1577
+ await inspectWorkflowPathSegments(specsRoot, backupPath, 'reenter backup file', 'file');
1578
+ // 授权留痕:嵌套写入被重入目标节点的 evidence(授权记录 + 备份指针 + 指纹 + 原因 +
1579
+ // 续轮标记)。只改 evidence 的目标节点键,其余键按原始键集逐项保留。
1580
+ const existingEvidence = rawState.evidence && typeof rawState.evidence === 'object' && !Array.isArray(rawState.evidence)
1581
+ ? rawState.evidence
1582
+ : {};
1583
+ const targetEvidence = existingEvidence[decision.target]
1584
+ && typeof existingEvidence[decision.target] === 'object'
1585
+ && !Array.isArray(existingEvidence[decision.target])
1586
+ ? existingEvidence[decision.target]
1587
+ : {};
1588
+ const authorizationRecord = {
1589
+ round,
1590
+ at,
1591
+ source,
1592
+ target: decision.target,
1593
+ backup: backupRecord,
1594
+ fingerprint,
1595
+ reason,
1596
+ ...(continuationAuthorized ? { continuationAuthorized: true } : {}),
1597
+ };
1598
+ // 落盘形态 = 原始 state 键集 + 本次实际改动的四类机器字段与审计字段——转移语义
1599
+ // (currentNode := target / completedNodes := 前驱交集 / status := running)与审计
1600
+ // (evidence 留痕 + history 追加事件)之外的字段逐项不变;readState 的兼容默认值不回写。
1601
+ const persisted = { ...rawState };
1602
+ persisted.currentNode = decision.target;
1603
+ persisted.completedNodes = decision.completedNodes.slice();
1604
+ persisted.status = 'running';
1605
+ persisted.evidence = {
1606
+ ...existingEvidence,
1607
+ [decision.target]: { ...targetEvidence, reentryAuthorization: authorizationRecord },
1608
+ };
1609
+ // 审计事件:append-only 追加 reentry-applied;change 字段是跨 change 轮次隔离的唯一依据。
1610
+ persisted.history = existingHistory.concat([{
1611
+ event: 'reentry-applied',
1612
+ from: 'archive',
1613
+ to: decision.target,
1614
+ round,
1615
+ authorization: { round, at, source, target: decision.target },
1616
+ backup: backupRecord,
1617
+ fingerprint,
1618
+ at,
1619
+ change: changeName,
1620
+ reason,
1621
+ ...(continuationAuthorized ? { continuationAuthorized: true } : {}),
1622
+ }]);
1623
+ const persistedBad = validateStateFields(persisted);
1624
+ if (persistedBad.length > 0) throw new Error('state 字段类型非法: ' + persistedBad[0]);
1625
+ await writeState(persisted);
1626
+ } catch (error) {
1627
+ // 写盘失败:回滚本次调用创建的孤儿备份(state 由原子写保证不被截断),原始错误照常上抛。
1628
+ if (backupWritten) {
1629
+ try { await fs.rm(backupPath, { force: true }); } catch { /* 清理失败不掩盖原始错误 */ }
1630
+ }
1631
+ throw error;
1632
+ }
1633
+ const roundLabel = continuationAuthorized
1634
+ ? '第 ' + round + ' 轮(显式授权续轮,上限 ' + REENTRY_ROUND_LIMIT + ')'
1635
+ : '第 ' + round + '/' + REENTRY_ROUND_LIMIT + ' 轮';
1636
+ console.log('REENTRY: archive → ' + decision.target + '(授权源 ' + source + ';' + roundLabel
1637
+ + ';备份 ' + backupRecord + ')');
1638
+ console.log('REASON: ' + reason);
1639
+ return;
1640
+ }
1641
+
1642
+ throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check, reenter');
1258
1643
  }
1259
1644
 
1260
1645
  main().catch(error => {
@@ -69,6 +69,21 @@ This node finalizes a completed change by extracting reusable lessons from the d
69
69
 
70
70
  11. **Exit check**: Run exit check.
71
71
 
72
+ ### 归档后发现缺陷(受控重入)
73
+
74
+ 归档已 entry 但归档移动尚未发生(`.specs/<change-id>/` 仍在原位、`status !== 'completed'`)时,review / verify / 执行阶段发现的新缺陷按下列边界处置:
75
+
76
+ - **未移动** → 受控重入:由用户显式授权后运行
77
+
78
+ ```bash
79
+ node .claude/skills/flow-comet/scripts/workflow-state.mjs reenter <target> --authorized-by <source> --reason <text> [--continue-round <n>]
80
+ ```
81
+
82
+ 目标限 `execute` / `subagent-execute` / `review` / `verify` 之一;每次调用都需要用户显式授权,每 change 上限 3 轮(达上限后凭显式续轮授权 `--continue-round <n>`(n ≥ 已用轮次 + 1)可继续并计入下一轮);命令先自动落 state 备份快照(`.specs/<change-id>/.reentry-backups/`),再转移工作归属,并打印 `REENTRY: archive → <target>(授权源 <source>;第 n/3 轮;备份 <file>)` 与 `REASON: <text>` 行(续轮审计行为 `第 n 轮(显式授权续轮,上限 3)`)。缺授权、目标越界、超上限或归档移动已发生一律 BLOCKED(state 字节零改写),不会静默跳过。
83
+ - **已移动 / 已合并** → 人工处置或新 change:归档移动已发生(`.specs/archive/<日期>-<change-id>/`)或 change 已 `completed` / 已合并时,受控重入不适用(不承诺把文件搬回原位);走人工处置,或把修复放进新 change / hotfix,并在遗留清单里登记指针。
84
+
85
+ **写权限顺序(先转移后写 TASK)**:archive 阶段 hook 对 change 目录只放行 `KNOWN-ISSUES.md` 这一个精确文件(另有 `.specs/archive/`、`.specs/CHANGELOG.md`、`.specs/LESSONS.md`、`STATE.md`),TASK.md 的修复任务写入不在放行面内。顺序固定为:先跑 `reenter` 完成转移(写入权限随即跟随目标节点),再在目标节点权限内追加 Fix 任务 / 修改工件——不要试图在 archive 阶段先写 TASK.md。若重入成功后追加任务失败,用 `next` / `status` 核对归属;重复调用同一目标为空操作(不备份、不计数、不改写 state)。
86
+
72
87
  ### 归档提交(R4.1 交付闭环)
73
88
 
74
89
  1. 用显式路径 stage:只 stage 本 change 可归属路径(原活动路径、实际归档路径、改过的主 spec)