flow-comet 1.6.0 → 1.6.2

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 (43) hide show
  1. package/.flow-comet/skills/flow-comet/GUIDANCE.md +26 -5
  2. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  3. package/.flow-comet/skills/flow-comet/SKILL.md +51 -2
  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/workflow-protocol.json +1 -1
  9. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +21 -3
  10. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +129 -3
  11. package/.flow-comet/skills/flow-comet/scripts/context-scan.mjs +396 -0
  12. package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +41 -31
  13. package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +778 -0
  14. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +5499 -596
  15. package/.flow-comet/skills/flow-comet/scripts/health.mjs +664 -0
  16. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +1 -1
  17. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +459 -11
  18. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +58 -3
  19. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +1024 -11
  20. package/.flow-comet/skills/flow-comet/scripts/time-utils.mjs +133 -0
  21. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +285 -227
  22. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +6 -4
  23. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +515 -31
  24. package/.flow-comet/skills/flow-comet-archive/SKILL.md +2 -0
  25. package/.flow-comet/skills/flow-comet-change/SKILL.md +13 -1
  26. package/.flow-comet/skills/flow-comet-design/SKILL.md +6 -2
  27. package/.flow-comet/skills/flow-comet-dev/SKILL.md +3 -1
  28. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +46 -11
  29. package/.flow-comet/skills/flow-comet-execute/SKILL.md +6 -4
  30. package/.flow-comet/skills/flow-comet-health/SKILL.md +57 -16
  31. package/.flow-comet/skills/flow-comet-integration/SKILL.md +2 -0
  32. package/.flow-comet/skills/flow-comet-open/SKILL.md +2 -0
  33. package/.flow-comet/skills/flow-comet-plan/SKILL.md +17 -6
  34. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +2 -0
  35. package/.flow-comet/skills/flow-comet-review/SKILL.md +7 -5
  36. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +12 -9
  37. package/.flow-comet/skills/flow-comet-task/SKILL.md +7 -3
  38. package/.flow-comet/skills/flow-comet-test/SKILL.md +2 -0
  39. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +28 -3
  40. package/.flow-comet/skills/flow-comet-verify/SKILL.md +7 -5
  41. package/README.md +45 -119
  42. package/package.json +1 -1
  43. package/scripts/dsh-bridge.mjs +2 -2
@@ -6,10 +6,11 @@ import os from 'os';
6
6
  import path from 'path';
7
7
  import { fileURLToPath } from 'url';
8
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';
10
- import { probeProject, classify, printDetection, validateContext, printGenerationGuide, skipInit } from './context-init.mjs';
9
+ import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor, looksLikeObjectLiteral, writeJsonAtomic, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME, toPersistedProtocolPath } from './state-schema.mjs';
10
+ import { isValidTimestamp, daysSince, isArchivedAfterTimestamp, hasSection9, nowTimestamp, parseTimestamp, EVOLVE_STALE_DAYS, EVOLVE_DUE_NEW_ARCHIVE_CHANGES } from './time-utils.mjs';
11
+ import { probeProject, classify, printDetection, validateContext, printGenerationGuide, extractContextStructure, skipInit } from './context-init.mjs';
11
12
  import { taskOpeningAttrs, taskBlocks } from './task-parsing.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';
13
+ import { route, resolveNextNode, hasSubagentNode, protocolTaskFilePath, resolveFixRollbackDecision, resolveFixRollbackState, applyFixRollbackRound, resolveFixReturnNode, resolveReentryDecision, resolveReplanDecision, analyzeDependencyGraph, findParallelWriteConflicts, isSingleSegmentChangeName, REENTRY_ROUND_LIMIT, REENTRY_TARGET_NODE_IDS, REPLAN_ROUND_LIMIT, EXECUTE_FAMILY_NODE_IDS } from './route-node.mjs';
13
14
 
14
15
  const command = process.argv[2] ?? 'status';
15
16
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -34,21 +35,10 @@ async function readJson(file) {
34
35
  return JSON.parse((await fs.readFile(file, 'utf8')).replace(/^/, ''));
35
36
  }
36
37
 
37
- // JSON 写盘统一走原子写:先写同目录临时文件,再 rename 覆盖目标——目标文件要么是旧内容、
38
- // 要么是新内容,不会出现被截断的半写状态。写失败(磁盘满 / 权限 / 目标被占用)时清理临时文件
39
- // 后抛出,调用方按 fail-closed 处理。状态下发是单写者形态(机器字段只由脚本通道写),
40
- // 固定临时名与目标同目录,保证 rename 不跨卷。
41
- async function writeJson(file, value) {
42
- await fs.mkdir(path.dirname(file), { recursive: true });
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
- }
51
- }
38
+ // JSON 写盘统一走状态层单一来源的原子写(state-schema.mjs 的 writeJsonAtomic → writeFileAtomic):
39
+ // 先写同目录临时文件再 rename 覆盖目标——目标要么旧内容、要么新内容,不会出现被截断的半写状态;
40
+ // 写失败(磁盘满 / 权限 / 目标被占用)清理临时文件后抛出,调用方按 fail-closed 处理。mkdir recursive
41
+ // 由该实现承担(.skill-loads/ 等标记目录不存在时创建);状态下发是单写者形态(机器字段只由脚本通道写)。
52
42
 
53
43
  async function fileExists(file) {
54
44
  try { await fs.access(file); return true; } catch { return false; }
@@ -424,16 +414,68 @@ function printBranchLine(activeChange, branchPrefix = 'change/') {
424
414
  }
425
415
  }
426
416
 
417
+ // ---------- evolve 到期提示(AC-18:达阈值才输出,未达阈值零噪音) ----------
418
+
419
+ // 该时刻之后归档、且 DESIGN.md 带 §9 的 change 数。归档时刻取目录名日期前缀(flow-kit 约定
420
+ // archive/<YYYY-MM-DD>-<change-id>,该标签随提交固化、跨 clone 稳定);「归档于何时」与「§9 是否
421
+ // 在场」两个判定都走 time-utils 单一来源——不在本脚本内联第二份表达式(L-067)。
422
+ // 读取失败 / 非目录 / 无 DESIGN.md / 无 §9 一律不计入(不误报)。
423
+ async function countSection9ArchivesSince(timestamp) {
424
+ const archiveRoot = path.join(specsRoot, 'archive');
425
+ let entries = [];
426
+ try {
427
+ entries = await fs.readdir(archiveRoot, { withFileTypes: true });
428
+ } catch {
429
+ return 0;
430
+ }
431
+ let count = 0;
432
+ for (const entry of entries) {
433
+ if (!entry.isDirectory() || !isArchivedAfterTimestamp(entry.name, timestamp)) continue;
434
+ let design = '';
435
+ try {
436
+ design = await fs.readFile(path.join(archiveRoot, entry.name, 'DESIGN.md'), 'utf8');
437
+ } catch {
438
+ continue;
439
+ }
440
+ if (hasSection9(design)) count += 1;
441
+ }
442
+ return count;
443
+ }
444
+
445
+ // 到期提示:`last_evolve_at` 距今 > 60 天,或其后新增 ≥ 5 个带 §9 的归档 change → 输出一行;
446
+ // 否则**不打印任何行**(AC-18 反例锚:未达阈值零噪音)。旧 state 无该字段 = 从未跑过 evolve →
447
+ // 静默(本批不强制未接入 evolve 的项目补字段:无基线可判时不制造噪音)。提示行内不含花括号——
448
+ // status 的 JSON 块按「首个 { 到末个 }」截取(既有消费方 parseStatusJson 同形)。
449
+ async function printEvolveDueHint(state) {
450
+ const lastEvolveAt = state && typeof state.last_evolve_at === 'string' ? state.last_evolve_at : '';
451
+ if (!isValidTimestamp(lastEvolveAt)) return;
452
+ const elapsedDays = daysSince(lastEvolveAt);
453
+ if (Number.isNaN(elapsedDays)) return;
454
+ const staleByAge = elapsedDays > EVOLVE_STALE_DAYS;
455
+ const newArchives = await countSection9ArchivesSince(lastEvolveAt);
456
+ const staleByCount = newArchives >= EVOLVE_DUE_NEW_ARCHIVE_CHANGES;
457
+ if (!staleByAge && !staleByCount) return;
458
+ const reasons = [];
459
+ if (staleByAge) {
460
+ reasons.push('距今 ' + Math.floor(elapsedDays) + ' 天,超阈值 ' + EVOLVE_STALE_DAYS + ' 天');
461
+ }
462
+ if (staleByCount) {
463
+ reasons.push('其后新增 ' + newArchives + ' 个带 §9 的归档 change,达阈值 ' + EVOLVE_DUE_NEW_ARCHIVE_CHANGES + ' 个');
464
+ }
465
+ console.log('EVOLVE-DUE: 上次架构沉淀 ' + lastEvolveAt + '(' + reasons.join(';')
466
+ + ')——建议显式调用 evolve(/flow-comet-evolve)同步 CONTEXT.md');
467
+ }
468
+
427
469
  // C6: writeState 写入前校验已知字段类型(fail-closed:非法 → BLOCKED 拒绝写入,不修复不猜测)
428
470
  // 未知字段允许(前向兼容);缺字段允许(readState 默认补);只校验存在字段的类型。
429
- // 内置节点常量: 校验表已迁移到 state-schema.mjs(唯一来源),行为与批次 C C6 完全一致(对第一个非法字段输出后退出)
471
+ // 内置节点常量: 校验表已迁移到 state-schema.mjs(唯一来源),行为与迁移前的内联表完全一致(对第一个非法字段输出后退出)
430
472
  async function writeState(state) {
431
473
  const bad = validateStateFields(state);
432
474
  if (bad.length) {
433
475
  console.error('BLOCKED: state 字段类型非法: ' + bad[0]);
434
476
  process.exit(1);
435
477
  }
436
- await writeJson(statePath, state);
478
+ await writeJsonAtomic(statePath, state);
437
479
  }
438
480
 
439
481
  // .specs/ 下必须存在名字「逐字相等」的目录条目(change 名唯一性判据)。大小写不敏感文件系统
@@ -702,6 +744,61 @@ async function runBridgeCheck() {
702
744
  }
703
745
  }
704
746
 
747
+ // ---------- intel-scan 双落点一致性(init 的检测侧) ----------
748
+ // `last_intel_scan` 是**双落点**字段:引擎 state(机器真相、schema 校验)与 `.specs/CONTEXT.md` 的
749
+ // `## intel-scan 元数据` 段(项目可见)。段行的改写——含改写前备份与结构校验——只有 context-scan
750
+ // 一条通道一份实现;init 侧因此**不写段**(在第二处复制段行改写判据必然与前者分叉),只承担两条:
751
+ // ① 形态对齐:state 侧取值一律经 time-utils 的 nowTimestamp()(本地时间 + 显式偏移),与
752
+ // context-scan 写入的形态同源;历史 `Z` 形态继续可解析(不迁移)。
753
+ // ② 漂移可见:写完后与段侧取值比对(口径 = **取值词元**,与段行写通道替换的那个词元同口径)——
754
+ // 不一致(含**同一时刻的两种形态**、段内取值不可解析)即输出可见提示并点名收敛命令;一致则
755
+ // 静默(不误报);带行尾说明的段行不构成差异(说明由写通道原样保留,不是取值的一部分)。
756
+ const INTEL_SECTION_NAME = 'intel-scan 元数据';
757
+ const INTEL_FIELD_NAME = 'last_intel_scan';
758
+
759
+ // 段侧取值词元的归一:`extractContextStructure` 返回的是字段行冒号后的**整行剩余文本**
760
+ // (取值词元 + 可选的 markdown 引号 + 可选的行尾说明),而段行的写通道 `context-scan` 按
761
+ // `INTEL_FIELD_LINE = (…)(\S+)([\s\S]*)` 只替换**首个取值词元**、行尾说明原样保留(首次接入的
762
+ // CONTEXT 生成物即「词元 + 说明」形态)。读侧因此必须取同一口径的词元再比对:按整行剩余文本比对时,
763
+ // 带说明的段行与 state 永不相等 ⇒ 同刻同形态也恒亮「不一致」、类别退化成「段内取值不是合法时间戳」,
764
+ // 提示点名的 `context-scan` 收敛承诺不可达(提示噪声化 = 没人看的行)。
765
+ // 空白切分与写侧正则的 `\S+` 同一字符类语义;行结构(段名 / 字段行形态)仍唯一来自
766
+ // extractContextStructure——本函数只做「词元 + 引号」归一,不解析段行(L-067 单一来源)。
767
+ function normalizeIntelFieldValue(value) {
768
+ return String(value).trim().split(/\s+/)[0].replace(/^`+/, '').replace(/`+$/, '').trim();
769
+ }
770
+
771
+ // 漂移判定(纯函数):两侧取值不一致时返回差异类别,一致(或任一侧缺席)返回 null(不误报)。
772
+ function intelScanDriftKind(stateValue, sectionValue) {
773
+ if (typeof stateValue !== 'string' || typeof sectionValue !== 'string') return null;
774
+ if (stateValue === sectionValue) return null;
775
+ const atSection = parseTimestamp(sectionValue);
776
+ if (Number.isNaN(atSection)) return '段内取值不是合法时间戳';
777
+ const atState = parseTimestamp(stateValue);
778
+ if (!Number.isNaN(atState) && atState === atSection) return '同刻不同形态';
779
+ return '刻与形态均不一致';
780
+ }
781
+
782
+ // 双落点比对(读盘 + 输出):段侧文档缺席 / 段或缺字段不在场 = 无可比对面 → 静默(不无中生有);
783
+ // 检出漂移 → 可见提示(stdout,与 INIT-* 提示同族且不阻断 init),点名两侧取值与收敛命令。
784
+ async function reportIntelScanDrift(contextFile, stateValue) {
785
+ let contextText;
786
+ try {
787
+ contextText = await fs.readFile(contextFile, 'utf8');
788
+ } catch {
789
+ return; // 段侧文档不可读 = 无可比对面
790
+ }
791
+ const fields = extractContextStructure(contextText).metadata[INTEL_SECTION_NAME];
792
+ if (!fields || !fields[INTEL_FIELD_NAME]) return; // 段或缺字段不在场 = 无可比对面
793
+ const landed = normalizeIntelFieldValue(fields[INTEL_FIELD_NAME].value);
794
+ const kind = intelScanDriftKind(stateValue, landed);
795
+ if (kind === null) return;
796
+ console.log('INIT-NOTICE: ' + INTEL_FIELD_NAME + ' 双落点不一致(' + kind + ')——引擎 state = '
797
+ + stateValue + ';`.specs/CONTEXT.md` 的 `## ' + INTEL_SECTION_NAME + '` 段 = ' + landed
798
+ + '。本命令只写 state(该段行的写通道是 context-scan);运行 context-scan 即把两处收敛为'
799
+ + '同刻同形态(冲突时以 state 为准)。');
800
+ }
801
+
705
802
  async function main() {
706
803
  // 协议解析: 协议加载 = resolveProtocol 解析路径 + 受保护读取 + fail-closed schema 校验
707
804
  // (读失败/校验失败直接 throw,沿用现有错误处理风格)
@@ -827,12 +924,23 @@ async function main() {
827
924
  // 项目级上下文字段跨 change 保留(迁移旧 state;--init-context 刷新扫描时间;--init-skip 记拒绝)
828
925
  ...(prevState?.ai_context_doc !== undefined ? { ai_context_doc: prevState.ai_context_doc } : {}),
829
926
  ...(initSkip ? { ai_context_doc: 'none' } : {}),
830
- // last_intel_scan 仅在校验通过后写入(agent 生成 → 脚本校验 7 段 → 记录扫描时间)
927
+ // last_intel_scan 仅在校验通过后写入(agent 生成 → 脚本校验 7 段 → 记录扫描时间);形态一律经
928
+ // time-utils 的 nowTimestamp()(本地时间 + 显式偏移)——与 context-scan 的落点形态同源,不在本
929
+ // 脚本内联第二份格式化。段侧**不在本命令的写面内**(该段行的改写与备份只有 context-scan 一份
930
+ // 实现):两处取值不一致由 reportIntelScanDrift 检出并给出可见提示,不静默漂移。
831
931
  ...(ctxValid === true
832
- ? { last_intel_scan: new Date().toISOString() }
833
- : (prevState?.last_intel_scan !== undefined ? { last_intel_scan: prevState.last_intel_scan } : {}))
932
+ ? { last_intel_scan: nowTimestamp() }
933
+ : (prevState?.last_intel_scan !== undefined ? { last_intel_scan: prevState.last_intel_scan } : {})),
934
+ // last_evolve_at 同为**项目级**字段(evolve 的跨 change 基线,写通道 = config set)——init 换
935
+ // change 必须原样保留:丢了它,增量窗口静默退化为全量扫描、到期提示从此不再触发(保留判据与
936
+ // 上一行同形:字段缺席 = 从未跑过 evolve,不得凭空制造该字段——state-schema 不接受 null)
937
+ ...(prevState?.last_evolve_at !== undefined ? { last_evolve_at: prevState.last_evolve_at } : {})
834
938
  };
835
939
  await writeState(state);
940
+ // 扫描时刻的双落点一致性(state ↔ `.specs/CONTEXT.md` 的 `## intel-scan 元数据` 段):本命令写
941
+ // state 后即比对段侧取值——不一致(含同一时刻的两种形态)输出可见提示并点名收敛命令;一致或
942
+ // 无可比对面则静默(不误报)。段行的写通道只有 context-scan,故此处是检测、不是第二份改写实现。
943
+ await reportIntelScanDrift(path.join(specsRoot, 'CONTEXT.md'), state.last_intel_scan);
836
944
  // init 创建 .specs/<id>/ 目录——文件即真相从 init 起成立,findActiveChange 立即可识别
837
945
  //(此前 init 后 next/status 报 No active change,与 SKILL 启动协议 init → next 矛盾)
838
946
  const specsChangeDir = path.join(specsRoot, changeName);
@@ -874,16 +982,45 @@ async function main() {
874
982
  const changeName = await findActiveChange();
875
983
  if (!changeName) {
876
984
  console.log(JSON.stringify({ status: 'no-change', message: 'No active change in .specs/' }, null, 2));
985
+ // 到期提示属**项目级**元数据(与是否有 active change 无关):无活跃 change 时同样按阈值输出
986
+ await printEvolveDueHint(await readState());
877
987
  return;
878
988
  }
879
989
  const state = await readState();
880
990
  const detectedNode = await determineNode(changeName, protocol, state.completedNodes);
991
+ // 派生视图(ADR-013 决策 11;2026-09-28 PR 审查采纳改为事件为准):被强制推进的节点以
992
+ // state.history 中本 change 的 advance-forced 事件为唯一判据——按 change 过滤(兼容旧事件
993
+ // 无 change 字段),取 e.node 集合后与 completedNodes 求交。旧「completedNodes 含而 evidence
994
+ // 不含」推断会漏报两类真实反例:① record 后被 advance;② replan/reenter 写授权留痕
995
+ // (evidence.<node>.replanAuthorization)后被 advance。state.history === undefined 的旧 state
996
+ // 无事件可依(advance 当时无痕)→ 回退本「缺 evidence」判据。
997
+ const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
998
+ let forcedNodes;
999
+ if (state.history === undefined) {
1000
+ const evidenceMap = state.evidence && typeof state.evidence === 'object' && !Array.isArray(state.evidence)
1001
+ ? state.evidence
1002
+ : {};
1003
+ forcedNodes = completedArr.filter((id) => {
1004
+ const record = evidenceMap[id];
1005
+ return !(record && typeof record === 'object' && !Array.isArray(record));
1006
+ });
1007
+ } else {
1008
+ const forcedSet = new Set(
1009
+ (Array.isArray(state.history) ? state.history : [])
1010
+ .filter((e) => e
1011
+ && e.event === 'advance-forced'
1012
+ && (typeof e.change !== 'string' || e.change === changeName))
1013
+ .map((e) => e.node)
1014
+ );
1015
+ forcedNodes = completedArr.filter((id) => forcedSet.has(id));
1016
+ }
881
1017
  console.log(JSON.stringify({
882
1018
  status: 'running',
883
1019
  change: changeName,
884
1020
  currentNode: detectedNode,
885
1021
  stateCurrentNode: state.currentNode,
886
1022
  completedNodes: state.completedNodes,
1023
+ forcedNodes,
887
1024
  executionMode: state.executionMode ?? 'subagent',
888
1025
  directOverride: state.directOverride ?? false,
889
1026
  branchMode: isInsideWorkTree(),
@@ -894,6 +1031,7 @@ async function main() {
894
1031
  newChange: state.newChange === true
895
1032
  }, null, 2));
896
1033
  printBranchLine(changeName, state.branchPrefix ?? 'change/');
1034
+ await printEvolveDueHint(state);
897
1035
  return;
898
1036
  }
899
1037
 
@@ -1134,12 +1272,12 @@ async function main() {
1134
1272
  if (promptArg !== null && !protocolUnderFlowKitPrompts(promptArg)) {
1135
1273
  throw new Error('skill-load --prompt 路径必须位于 flow-kit/prompts/ 下(flow-kit 为 vendored 上游,协议提示只读引用): ' + promptArg);
1136
1274
  }
1137
- // 声明标记写入:.skill-loads/ 目录不存在时创建(writeJson 自带 mkdir recursive);
1275
+ // 声明标记写入:.skill-loads/ 目录不存在时创建(writeJsonAtomic 自带 mkdir recursive);
1138
1276
  // 同 node-skill 重复调用覆盖(记录最新声明)
1139
1277
  const changeName = await findActiveChange();
1140
1278
  if (!changeName) {
1141
1279
  // 归档后场景:change 目录已移入 .specs/archive/(无活跃 change)——skill-load 不可用,
1142
- // 但 record 的声明自动化(M5)仍可写归档路径标记——消息如实引导(级 4 实证反馈)
1280
+ // 但 record 的声明自动化(M5)仍可写归档路径标记——消息如实引导(真实运行实证反馈)
1143
1281
  throw new Error('skill-load requires an active change(先运行 init <change-id>;若该 change 已归档,声明标记由 record 自动补写——M5 会写入归档路径的 .skill-loads/)');
1144
1282
  }
1145
1283
  // 标记 protocol 字段 = --prompt 参数的 basename(如 0-change.md)——与 guard exit
@@ -1149,7 +1287,7 @@ async function main() {
1149
1287
  const marker = { node: nodeId, skill: skillName, protocol: promptArg === null ? null : path.basename(promptArg), at: new Date().toISOString() };
1150
1288
  // specsRoot 已含 .specs/,相对路径为 <change-id>/.skill-loads/<node>-<skill>.json
1151
1289
  const markerRel = path.posix.join(changeName, '.skill-loads', nodeId + '-' + skillName + '.json');
1152
- await writeJson(path.join(specsRoot, markerRel), marker);
1290
+ await writeJsonAtomic(path.join(specsRoot, markerRel), marker);
1153
1291
  console.log('SKILL-LOAD: ' + nodeId + ' ' + skillName + ' → .skill-loads/' + nodeId + '-' + skillName + '.json');
1154
1292
  return;
1155
1293
  }
@@ -1251,7 +1389,7 @@ async function main() {
1251
1389
  // M5 标记目录解析:活动路径优先;change 已归档(活动目录不存在但归档目录存在)
1252
1390
  // 时写归档路径——防重建已归档的活动目录(归档移动语义;与 findSkillLoadsDir 双路径一致)。
1253
1391
  // 跳过条件:活动与归档均无 .skill-loads **且活动 change 目录已不存在**(归档移动后)
1254
- // ——此时 writeJson 的 mkdir recursive 会把已归档的活动目录残留回来(修复前实测缺陷);
1392
+ // ——此时 writeJsonAtomic 的 mkdir recursive 会把已归档的活动目录残留回来(修复前实测缺陷);
1255
1393
  // 活动 change 目录仍存在(正常流程)时创建 .skill-loads 子目录是 M5 的正常职责,不跳过
1256
1394
  const activeLoadsDir = path.join(specsRoot, markerChange, '.skill-loads');
1257
1395
  let targetLoadsDir = activeLoadsDir;
@@ -1276,7 +1414,7 @@ async function main() {
1276
1414
  // 1-requirement.md 而非节点首文件 0-change.md——修复前所有 skill 都写首文件,
1277
1415
  // 标记的协议归属语义错误;exit 校验只查归属集合故能通过,但标记不可信)
1278
1416
  const skillProtoFiles = SKILL_PROTOCOL_FILES[binding.skill] ?? [];
1279
- await writeJson(markerFile, {
1417
+ await writeJsonAtomic(markerFile, {
1280
1418
  node: nodeId,
1281
1419
  skill: binding.skill,
1282
1420
  protocol: skillProtoFiles.length > 0 ? skillProtoFiles[0] : null,
@@ -1301,7 +1439,8 @@ async function main() {
1301
1439
  }
1302
1440
 
1303
1441
  if (command === 'config') {
1304
- // E1: 配置命令——config set <key> <value>;branchMode 只读(init 自动判定),enablePrReview 手动开关
1442
+ // E1: 配置命令——config set <key> <value>;branchMode 只读(init 自动判定),enablePrReview 手动
1443
+ // 开关,last_evolve_at 为 evolve 元数据时刻(形态校验 fail-closed,写通道唯一)
1305
1444
  const sub = process.argv[3];
1306
1445
  const key = process.argv[4];
1307
1446
  const value = process.argv[5];
@@ -1322,7 +1461,21 @@ async function main() {
1322
1461
  console.log('CONFIG: enablePrReview = ' + state.enablePrReview);
1323
1462
  return;
1324
1463
  }
1325
- console.error('BLOCKED: 未知配置键: ' + key + '(支持: enablePrReview;branchMode 由 init 自动判定)');
1464
+ // evolve 元数据时间戳(脚本不直写 state,项目级字段一律经本通道)。形态非法 → BLOCK
1465
+ // 且**零改写**(校验先于读 state 与写盘;writeState 侧的字段校验表是第二道闸,同一判据)。
1466
+ if (key === 'last_evolve_at') {
1467
+ if (!isValidTimestamp(value)) {
1468
+ console.error('BLOCKED: config set 值非法(last_evolve_at 必须为本地时间 + 显式偏移形态 '
1469
+ + 'YYYY-MM-DDTHH:mm:ss±HH:mm,兼容历史 Z 形态): ' + value);
1470
+ process.exit(1);
1471
+ }
1472
+ const state = await readState();
1473
+ state.last_evolve_at = value;
1474
+ await writeState(state);
1475
+ console.log('CONFIG: last_evolve_at = ' + state.last_evolve_at);
1476
+ return;
1477
+ }
1478
+ console.error('BLOCKED: 未知配置键: ' + key + '(支持: enablePrReview, last_evolve_at;branchMode 由 init 自动判定)');
1326
1479
  process.exit(1);
1327
1480
  }
1328
1481
 
@@ -1375,14 +1528,35 @@ async function main() {
1375
1528
  console.log('No active change. Use select first.');
1376
1529
  return;
1377
1530
  }
1531
+ // 被强制推进的节点 = 推进前的 currentNode:exit 门禁未跑(无出口证据),这正是留痕与
1532
+ // 可见性的依据(ADR-013 决策 10/11)。advance 的推进语义保持不变,但每次使用都必须写
1533
+ // 审计事件并在输出显式列出被跳过的出口门禁。
1534
+ const forcedNode = state.currentNode;
1535
+ const forcedNodeId = typeof forcedNode === 'string' && forcedNode !== '' ? forcedNode : null;
1378
1536
  if (!state.completedNodes.includes(state.currentNode)) {
1379
1537
  state.completedNodes.push(state.currentNode);
1380
1538
  }
1381
1539
  // Use determineNode to get the actual next node (reads TASK.md)
1382
1540
  const detected = await determineNode(state.activeChange, protocol, state.completedNodes);
1383
1541
  state.currentNode = detected;
1542
+ if (forcedNodeId !== null) {
1543
+ // append-only 审计事件:change 供跨 change 检索,skipped 标识被跳过的出口门禁
1544
+ // (exit:<node>),reason 固定 'advance'(本 CLI 无其它原因面)。
1545
+ const existingHistory = Array.isArray(state.history) ? state.history : [];
1546
+ state.history = existingHistory.concat([{
1547
+ event: 'advance-forced',
1548
+ change: state.activeChange,
1549
+ node: forcedNode,
1550
+ skipped: ['exit:' + forcedNode],
1551
+ reason: 'advance',
1552
+ at: new Date().toISOString(),
1553
+ }]);
1554
+ }
1384
1555
  await writeState(state);
1385
1556
  console.log('Advanced to: ' + state.currentNode);
1557
+ if (forcedNodeId !== null) {
1558
+ console.log('ADVANCE-AUDIT: 跳过 ' + forcedNodeId + ' 的 exit 门禁;该节点无出口证据');
1559
+ }
1386
1560
  return;
1387
1561
  }
1388
1562
 
@@ -1639,7 +1813,317 @@ async function main() {
1639
1813
  return;
1640
1814
  }
1641
1815
 
1642
- throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check, reenter');
1816
+ if (command === 'replan') {
1817
+ // 受控计划重校重签(ADR-013):计划在执行中被证明有缺陷时,唯一合规的重签入口——只在
1818
+ // execute / subagent-execute 相位可用、停原位(不跳节点、不改 completedNodes),先把任务集
1819
+ // 重新校验(依赖图 + 任务字段,绝不豁免)再重录 state.taskHash。命令形态:
1820
+ // replan <reason> --authorized-by <source> [--continue-round <n>]。
1821
+ // 编排顺序与 reenter 同构:参数防护 → 读 state → 单一权威判定(相位/change → 授权 →
1822
+ // 上限与续轮 → 幂等空操作)→ 重校 → 备份(sha256)→ 重签 → 双写留痕 → REPLAN/REASON 行;
1823
+ // 全部判定集中在 route-node.mjs 纯函数族,BLOCK 与空操作路径一律在写盘前返回(字节零改写)。
1824
+ const replanUsage = '用法: workflow-state.mjs replan <reason> --authorized-by <source> [--continue-round <n>]';
1825
+ const replanReason = process.argv[3];
1826
+ if (typeof replanReason !== 'string' || replanReason.trim() === '' || replanReason.startsWith('--')) {
1827
+ console.error('BLOCKED: replan 缺少原因(位置参数 <reason> 必填且非空)。' + replanUsage);
1828
+ process.exit(1);
1829
+ }
1830
+ const reason = replanReason.trim();
1831
+ let authorizedBy = null;
1832
+ let continuationRound = null;
1833
+ const replanArgs = process.argv.slice(4);
1834
+ for (let index = 0; index < replanArgs.length; index += 1) {
1835
+ const arg = replanArgs[index];
1836
+ // 支持 --name value 与 --name=value 两种形态;--protocol 为全局参数(协议路径已由
1837
+ // resolveProtocol 统一解析),命令面只做占位透传。
1838
+ let key = arg;
1839
+ let value = null;
1840
+ if (typeof arg === 'string' && arg.startsWith('--')) {
1841
+ const eq = arg.indexOf('=');
1842
+ if (eq > 0) {
1843
+ key = arg.slice(0, eq);
1844
+ value = arg.slice(eq + 1);
1845
+ }
1846
+ }
1847
+ if (key === '--protocol') {
1848
+ if (value === null) index += 1;
1849
+ continue;
1850
+ }
1851
+ if (key === '--continue-round') {
1852
+ // 续轮授权只在达到轮次上限后生效:命令面收正整数,形态合法性与「是否已到上限」由
1853
+ // 单一权威综合判定裁决(本处只做数值形态防护,fail-closed,先于任何读盘)。
1854
+ let consumedNext = false;
1855
+ if (value === null) {
1856
+ value = replanArgs[index + 1];
1857
+ consumedNext = true;
1858
+ }
1859
+ const parsedRound = typeof value === 'string' && value.trim() !== '' && !value.startsWith('--')
1860
+ ? Number(value.trim())
1861
+ : Number.NaN;
1862
+ if (!Number.isInteger(parsedRound) || parsedRound <= 0) {
1863
+ console.error('BLOCKED: replan --continue-round 需要正整数取值,实际 ' + JSON.stringify(value) + '。' + replanUsage);
1864
+ process.exit(1);
1865
+ }
1866
+ continuationRound = parsedRound;
1867
+ if (consumedNext) index += 1;
1868
+ continue;
1869
+ }
1870
+ if (key === '--authorized-by') {
1871
+ let consumedNext = false;
1872
+ if (value === null) {
1873
+ value = replanArgs[index + 1];
1874
+ consumedNext = true;
1875
+ }
1876
+ // 缺值 / 空值 / 纯空白 / 取下个选项名当值 → 一律用法错误(fail-closed,先于任何读盘)
1877
+ if (typeof value !== 'string' || value.trim() === '' || value.startsWith('--')) {
1878
+ console.error('BLOCKED: replan --authorized-by 需要非空取值。' + replanUsage);
1879
+ process.exit(1);
1880
+ }
1881
+ authorizedBy = value.trim();
1882
+ if (consumedNext) index += 1;
1883
+ continue;
1884
+ }
1885
+ console.error('BLOCKED: replan 未知参数 ' + JSON.stringify(arg) + '。' + replanUsage);
1886
+ process.exit(1);
1887
+ }
1888
+ if (authorizedBy === null) {
1889
+ console.error('BLOCKED: replan 需要显式授权 --authorized-by <source>(授权不可自决)。' + replanUsage);
1890
+ process.exit(1);
1891
+ }
1892
+ const state = await readState();
1893
+ const badFields = validateStateFields(state);
1894
+ if (badFields.length > 0) {
1895
+ // history 存在但非数组等类型损坏在此 fail-closed:不得由本命令静默清空覆盖审计历史。
1896
+ console.error('BLOCKED: state 字段类型非法: ' + badFields[0]);
1897
+ process.exit(1);
1898
+ }
1899
+ // 原始 state(未经 readState 兼容默认值叠加):备份取文件原始字节,落盘只写「原始键集 +
1900
+ // 本次实际改动的字段」——兼容默认值不得随重校回写(与受控重入同纪律)。
1901
+ const rawState = (await fileExists(statePath)) ? await readJson(statePath) : null;
1902
+ const changeName = typeof state.activeChange === 'string' ? state.activeChange : '';
1903
+ // 任务内容读取(fail-closed):不可读 / 为空 → 交由综合判定返回 task-content-missing
1904
+ // block(缺 TASK.md 时不得以「空任务集签名」判幂等空操作放行,L-079)。
1905
+ let taskContent = null;
1906
+ try {
1907
+ taskContent = await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8');
1908
+ } catch { taskContent = null; }
1909
+ // 授权形态的 round / at 由引擎派生(命令面只承载授权来源、原因与上限后的续轮轮次):普通
1910
+ // 轮次以合法占位值过形态门;落盘轮次一律取综合判定返回的 round(由本 change 历史事件派生),
1911
+ // 不在此内联第二份轮次推导。
1912
+ const authorizedAt = new Date().toISOString();
1913
+ const decision = resolveReplanDecision({
1914
+ protocol,
1915
+ state,
1916
+ authorization: { round: 1, at: authorizedAt, source: authorizedBy, reason, node: state.currentNode },
1917
+ continuationRound,
1918
+ taskContent,
1919
+ });
1920
+ if (!decision.ok) {
1921
+ if (decision.reason === 'round-limit-reached') {
1922
+ console.error('BLOCKED: 本 change 计划重校已达上限(' + decision.used + '/' + decision.limit
1923
+ + ' 轮)。需要人工裁决:继续(显式授权后在同一命令加 --continue-round <n>,n 为不小于第 '
1924
+ + (decision.used + 1) + ' 轮的正整数,须与 --authorized-by / <reason> 同次传入)/ 停止(保持现状,不再重校)。');
1925
+ process.exit(1);
1926
+ }
1927
+ const replanGuidance = {
1928
+ 'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
1929
+ 'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
1930
+ + '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
1931
+ 'phase-not-allowed': 'replan 只在 execute / subagent-execute 相位可用(当前节点 '
1932
+ + JSON.stringify(state.currentNode) + ')——其余相位请走既有推进 / 受控重入通道',
1933
+ 'continuation-not-required': '--continue-round 只在达到轮次上限后需要(当前 ' + decision.used + '/'
1934
+ + decision.limit + ' 轮)——上限前请直接以 --authorized-by / <reason> 发起',
1935
+ 'task-content-missing': '任务内容缺失或不可读(.specs/<change>/TASK.md 不存在 / 为空)——按 fail-closed 拒绝重签',
1936
+ }[decision.reason] || ('授权形态不合法(' + decision.reason + ')——需要用户显式传入 --authorized-by <source>');
1937
+ console.error('BLOCKED: ' + replanGuidance);
1938
+ process.exit(1);
1939
+ }
1940
+ if (decision.action === 'noop') {
1941
+ console.log('REPLAN: 空操作——state.taskHash 已与当前 TASK.md 同签(' + decision.node
1942
+ + '),无需重校;未备份、未计数、未写事件、未改写 state。');
1943
+ return;
1944
+ }
1945
+ if (decision.action !== 'apply') {
1946
+ console.error('BLOCKED: replan 判定返回未知动作 ' + JSON.stringify(decision.action) + '——按 fail-closed 拒绝。');
1947
+ process.exit(1);
1948
+ }
1949
+ // 重校(ADR-013 决策 3:replan 绝不做校验豁免):任务块 / <verify> / 任务图(依赖环与
1950
+ // 缺失依赖——analyzeDependencyGraph 单一实现,与 plan 出口同源)/ 7 字段完整性。任一失败
1951
+ // → BLOCK,状态零改写(本段全部先于备份与写盘)。
1952
+ const taskList = taskBlocks(taskContent);
1953
+ if (taskList.length === 0) {
1954
+ console.error('BLOCKED: TASK.md 无 <task> 块——replan 不做校验豁免,拒绝重签(状态零改写)。');
1955
+ process.exit(1);
1956
+ }
1957
+ const missingVerify = taskList.filter((block) => !/<verify>/.test(block));
1958
+ if (missingVerify.length > 0) {
1959
+ console.error('BLOCKED: TASK.md 中 ' + missingVerify.length
1960
+ + ' 个 task 缺 <verify> 字段——replan 不做校验豁免,拒绝重签(状态零改写)。');
1961
+ process.exit(1);
1962
+ }
1963
+ const depGraph = analyzeDependencyGraph(taskList);
1964
+ if (depGraph.cyclic || depGraph.missing.length > 0) {
1965
+ const detail = depGraph.cyclic
1966
+ ? '依赖环(拓扑排序无解,涉及任务: ' + depGraph.cycleIds.join(', ') + ')'
1967
+ : '依赖不存在的任务: ' + depGraph.missing.map((m) => m.id + '→' + m.dep).join(', ');
1968
+ console.error('BLOCKED: TASK.md ' + detail
1969
+ + '——依赖图不可满足(任务的依赖链必须存在且无环);replan 不做校验豁免,拒绝重签(状态零改写)'
1970
+ + ';恢复: 调整任务 depends_on——移除成环引用或改为真实存在的任务 id 后重试');
1971
+ process.exit(1);
1972
+ }
1973
+ // 任务字段完整性(与 plan 出口同一判据):新模板形态(含 <name>)且新 change → BLOCK;
1974
+ // 旧式一字段形态 / 旧 change 保持渐进 WARN(不放大既有语义)。
1975
+ const replanTask7Required = ['name', 'read_files', 'write_files', 'action', 'verify', 'done', 'depends_on'];
1976
+ const replanTask7NewFormat = taskList.some((block) => /<name\b/i.test(block));
1977
+ const replanTask7Broken = [];
1978
+ for (const block of taskList) {
1979
+ const missing = replanTask7Required.filter((field) => !new RegExp('</?' + field + '\\b', 'i').test(block));
1980
+ if (missing.length > 0) {
1981
+ const idAttr = (taskOpeningAttrs(block) || {}).id || '?';
1982
+ replanTask7Broken.push((idAttr !== '?' ? idAttr + ' ' : '') + '缺 ' + missing.join('/'));
1983
+ }
1984
+ }
1985
+ if (replanTask7Broken.length > 0) {
1986
+ if (replanTask7NewFormat && state.newChange === true) {
1987
+ console.error('BLOCKED: TASK.md 任务缺 7 字段(name/read_files/write_files/action/verify/done/depends_on): '
1988
+ + replanTask7Broken.join('; ') + ';恢复: 对照 flow-kit/templates/TASK.md 补齐每个 <task> 的缺字段后重试;replan 不做校验豁免');
1989
+ process.exit(1);
1990
+ }
1991
+ console.error('TASK-7FIELD WARN: TASK.md ' + replanTask7Broken.join('; ')
1992
+ + (replanTask7NewFormat ? '(旧 change 渐进,不阻断)' : '(旧式一字段模板形态,渐进不阻断)'));
1993
+ }
1994
+ // 路径边界:change 名必须是 .specs/ 下的单段真实目录(realpath 归一后仍在 .specs/ 内、
1995
+ // 无 symlink/junction 逃逸;复用受控路径边界实现)——备份落点必须先通过该边界。
1996
+ const changeBoundary = await inspectReentryChangeDir(changeName);
1997
+ if (!changeBoundary.ok) {
1998
+ const boundaryMessages = {
1999
+ 'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
2000
+ 'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
2001
+ + '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
2002
+ 'change-dir-missing': '.specs/' + (changeName || '<未知>') + '/ 目录不存在——重校备份必须具备真实 change 目录落点',
2003
+ 'change-dir-escape': 'change 目录路径越界或跨越符号链接 / junction(' + changeBoundary.detail
2004
+ + ')——受控重校与备份只允许落在 .specs/<change-id>/ 真实目录内',
2005
+ };
2006
+ console.error('BLOCKED: ' + (boundaryMessages[changeBoundary.reason] || ('change 目录边界异常(' + changeBoundary.reason + ')')));
2007
+ process.exit(1);
2008
+ }
2009
+ const changeDir = changeBoundary.changeDir;
2010
+ // 并行写冲突校验(2026-09-28 PR 审查采纳):replan 不做校验豁免——重校后的任务集若含
2011
+ // 本趟可运行(依赖已满足)的并行任务且 write_files 重叠,与 plan 出口使用同一实现
2012
+ // (route-node.findParallelWriteConflicts 单一来源)在此 BLOCK;必须早于备份与任何写盘,
2013
+ // BLOCK 路径 state 字节零改写。read∩write 弱判与 plan 出口同风格——仅 WARN 不阻断。
2014
+ // 同文件跨任务且无依赖路径(第三族)同样在此消费:与 plan 出口同判据、同分级(新 change
2015
+ // BLOCKED / 旧 change WARN),消息同族(任务对 `a×b(files)` + 恢复指引「补显式 depends_on 或
2016
+ // 合并为一个任务」)——replan 是执行期唯一合法的任务集修订通道,不得成为该形态的豁免口。
2017
+ const { writeConflicts, crossTaskConflicts, readWarnings } = await findParallelWriteConflicts(path.join(runRoot, '.specs', changeName));
2018
+ if (writeConflicts.length > 0) {
2019
+ console.error('BLOCKED: replan 检测到并行写冲突('
2020
+ + writeConflicts.map((c) => c.a + '↔' + c.b + ': ' + c.files.join(',')).join('; ')
2021
+ + ')——replan 不做校验豁免,状态零改写;恢复: 调整 write_files 消除重叠后重试');
2022
+ process.exit(1);
2023
+ }
2024
+ if (crossTaskConflicts.length > 0) {
2025
+ const crossDetail = crossTaskConflicts.map((c) => c.a + '×' + c.b + '(' + c.files.join(',') + ')').join('; ');
2026
+ const crossGuide = ';恢复: 补显式 depends_on 或合并为一个任务后重试';
2027
+ if (state.newChange === true) {
2028
+ console.error('BLOCKED: TASK.md 同文件跨任务且无依赖路径: ' + crossDetail
2029
+ + '——replan 不做校验豁免,状态零改写' + crossGuide);
2030
+ process.exit(1);
2031
+ }
2032
+ console.error('WARN: TASK.md 同文件跨任务且无依赖路径(旧 change 渐进不阻断): ' + crossDetail + crossGuide);
2033
+ }
2034
+ if (readWarnings.length > 0) {
2035
+ console.error('WARN: TASK.md 并行任务 read∩write 隐式依赖嫌疑(一方读取对方写路径,建议补显式 depends_on 声明): '
2036
+ + readWarnings.map((c) => c.a + '×' + c.b + '(' + c.files.join(',') + ')').join('; '));
2037
+ }
2038
+ const round = decision.round;
2039
+ const source = decision.authorization.source;
2040
+ const at = decision.authorization.at;
2041
+ const continuationAuthorized = decision.continuationAuthorized === true;
2042
+ const taskSetSignatureValue = decision.taskSetSignature;
2043
+ if (typeof taskSetSignatureValue !== 'string' || taskSetSignatureValue === '') {
2044
+ console.error('BLOCKED: replan 未能派生当前任务集签名——按 fail-closed 拒绝(状态零改写)。');
2045
+ process.exit(1);
2046
+ }
2047
+ // 备份:重签前 state 全量快照(文件原始字节,UTF-8 BOM 按可解析形态落盘);文件名
2048
+ // <UTC ISO 净化>-pre-replan.json;审计指纹 = 备份文件字节的 sha256(可核验)。
2049
+ const backupDir = path.join(changeDir, 'replan-backups');
2050
+ const backupFile = at.replace(/:/g, '-') + '-pre-replan.json';
2051
+ const backupPath = path.join(backupDir, backupFile);
2052
+ const backupRecord = path.relative(runRoot, backupPath).split(path.sep).join('/');
2053
+ const snapshotBytes = Buffer.from((await fs.readFile(statePath, 'utf8')).replace(/^\uFEFF/, ''), 'utf8');
2054
+ const fingerprint = createHash('sha256').update(snapshotBytes).digest('hex');
2055
+ const existingHistory = Array.isArray(rawState?.history) ? rawState.history : [];
2056
+ let backupWritten = false;
2057
+ try {
2058
+ if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
2059
+ throw new Error('state 文件缺失或形态非法,无法重校重签');
2060
+ }
2061
+ // 备份写入路径的物理包含性复核(单一权威路径段扫描):备份目录与备份文件逐段
2062
+ // lstat + realpath——任何 symlink/junction 逃出 .specs/ 一律拒绝,不写任何字节。
2063
+ await fs.mkdir(backupDir, { recursive: true });
2064
+ await inspectWorkflowPathSegments(specsRoot, backupDir, 'replan backup dir', 'directory');
2065
+ await fs.writeFile(backupPath, snapshotBytes);
2066
+ backupWritten = true;
2067
+ await inspectWorkflowPathSegments(specsRoot, backupPath, 'replan backup file', 'file');
2068
+ // 双写留痕(ADR-013 决策 8):① evidence.<node>.replanAuthorization(节点级授权 + 备份
2069
+ // 指纹);② history 追加 replan-applied(跨 change 审计检索)。落盘形态 = 原始 state
2070
+ // 键集 + 本次实际改动的三处(taskHash / evidence / history),其余字段逐项不变。
2071
+ const existingEvidence = rawState.evidence && typeof rawState.evidence === 'object' && !Array.isArray(rawState.evidence)
2072
+ ? rawState.evidence
2073
+ : {};
2074
+ const nodeEvidence = existingEvidence[decision.node]
2075
+ && typeof existingEvidence[decision.node] === 'object'
2076
+ && !Array.isArray(existingEvidence[decision.node])
2077
+ ? existingEvidence[decision.node]
2078
+ : {};
2079
+ const authorizationRecord = {
2080
+ round,
2081
+ at,
2082
+ source,
2083
+ reason,
2084
+ backup: backupRecord,
2085
+ fingerprint,
2086
+ ...(continuationAuthorized ? { continuationAuthorized: true } : {}),
2087
+ };
2088
+ const persisted = { ...rawState };
2089
+ persisted.taskHash = taskSetSignatureValue;
2090
+ persisted.evidence = {
2091
+ ...existingEvidence,
2092
+ [decision.node]: { ...nodeEvidence, replanAuthorization: authorizationRecord },
2093
+ };
2094
+ persisted.history = existingHistory.concat([{
2095
+ event: 'replan-applied',
2096
+ change: changeName,
2097
+ node: decision.node,
2098
+ round,
2099
+ reason,
2100
+ authorizedBy: source,
2101
+ taskSetSignature: taskSetSignatureValue,
2102
+ backup: backupRecord,
2103
+ fingerprint,
2104
+ at,
2105
+ ...(continuationAuthorized ? { continuationAuthorized: true } : {}),
2106
+ }]);
2107
+ const persistedBad = validateStateFields(persisted);
2108
+ if (persistedBad.length > 0) throw new Error('state 字段类型非法: ' + persistedBad[0]);
2109
+ await writeState(persisted);
2110
+ } catch (error) {
2111
+ // 写盘失败:回滚本次调用创建的孤儿备份(state 由原子写保证不被截断),原始错误照常上抛。
2112
+ if (backupWritten) {
2113
+ try { await fs.rm(backupPath, { force: true }); } catch { /* 清理失败不掩盖原始错误 */ }
2114
+ }
2115
+ throw error;
2116
+ }
2117
+ const roundLabel = continuationAuthorized
2118
+ ? '第 ' + round + ' 轮(显式授权续轮,上限 ' + REPLAN_ROUND_LIMIT + ')'
2119
+ : '第 ' + round + '/' + REPLAN_ROUND_LIMIT + ' 轮';
2120
+ console.log('REPLAN: ' + decision.node + ' 重新校验通过(授权源 ' + source + ';' + roundLabel
2121
+ + ';备份 ' + backupRecord + ')');
2122
+ console.log('REASON: ' + reason);
2123
+ return;
2124
+ }
2125
+
2126
+ throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check, reenter, replan');
1643
2127
  }
1644
2128
 
1645
2129
  main().catch(error => {