flow-comet 1.5.1 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.flow-comet/rules/flow-comet-orchestration.md +1 -2
- package/.flow-comet/skills/flow-comet/GUIDANCE.md +22 -3
- package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
- package/.flow-comet/skills/flow-comet/SKILL.md +40 -3
- package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +3 -3
- package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +18 -17
- package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +27 -12
- package/.flow-comet/skills/flow-comet/reference/recovery.md +1 -7
- package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +21 -3
- package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +41 -31
- package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +6687 -330
- package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +25 -5
- package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +1145 -15
- package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +72 -3
- package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +2077 -14
- package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +13 -0
- package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +568 -501
- package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +331 -14
- package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +783 -40
- package/.flow-comet/skills/flow-comet-archive/SKILL.md +17 -0
- package/.flow-comet/skills/flow-comet-change/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-design/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-dev/SKILL.md +3 -1
- package/.flow-comet/skills/flow-comet-execute/SKILL.md +21 -1
- package/.flow-comet/skills/flow-comet-integration/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-open/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-plan/SKILL.md +17 -6
- package/.flow-comet/skills/flow-comet-requirement/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-review/SKILL.md +23 -3
- package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +23 -11
- package/.flow-comet/skills/flow-comet-task/SKILL.md +7 -3
- package/.flow-comet/skills/flow-comet-test/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-verify/SKILL.md +21 -4
- package/README.md +45 -115
- package/package.json +1 -1
- package/scripts/dsh-bridge.mjs +2 -2
- package/scripts/prepare-env.mjs +77 -46
|
@@ -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, resolveReplanDecision, analyzeDependencyGraph, findParallelWriteConflicts, isSingleSegmentChangeName, REENTRY_ROUND_LIMIT, REENTRY_TARGET_NODE_IDS, REPLAN_ROUND_LIMIT, 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
|
-
|
|
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 非空;② 最后一个已完成节点
|
|
@@ -434,7 +426,7 @@ function printBranchLine(activeChange, branchPrefix = 'change/') {
|
|
|
434
426
|
|
|
435
427
|
// C6: writeState 写入前校验已知字段类型(fail-closed:非法 → BLOCKED 拒绝写入,不修复不猜测)
|
|
436
428
|
// 未知字段允许(前向兼容);缺字段允许(readState 默认补);只校验存在字段的类型。
|
|
437
|
-
// 内置节点常量: 校验表已迁移到 state-schema.mjs
|
|
429
|
+
// 内置节点常量: 校验表已迁移到 state-schema.mjs(唯一来源),行为与迁移前的内联表完全一致(对第一个非法字段输出后退出)
|
|
438
430
|
async function writeState(state) {
|
|
439
431
|
const bad = validateStateFields(state);
|
|
440
432
|
if (bad.length) {
|
|
@@ -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
|
|
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
|
-
|
|
632
|
-
|
|
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,
|
|
@@ -821,18 +878,45 @@ async function main() {
|
|
|
821
878
|
}
|
|
822
879
|
const state = await readState();
|
|
823
880
|
const detectedNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
881
|
+
// 派生视图(ADR-013 决策 11;2026-09-28 PR 审查采纳改为事件为准):被强制推进的节点以
|
|
882
|
+
// state.history 中本 change 的 advance-forced 事件为唯一判据——按 change 过滤(兼容旧事件
|
|
883
|
+
// 无 change 字段),取 e.node 集合后与 completedNodes 求交。旧「completedNodes 含而 evidence
|
|
884
|
+
// 不含」推断会漏报两类真实反例:① record 后被 advance;② replan/reenter 写授权留痕
|
|
885
|
+
// (evidence.<node>.replanAuthorization)后被 advance。state.history === undefined 的旧 state
|
|
886
|
+
// 无事件可依(advance 当时无痕)→ 回退本「缺 evidence」判据。
|
|
887
|
+
const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
|
|
888
|
+
let forcedNodes;
|
|
889
|
+
if (state.history === undefined) {
|
|
890
|
+
const evidenceMap = state.evidence && typeof state.evidence === 'object' && !Array.isArray(state.evidence)
|
|
891
|
+
? state.evidence
|
|
892
|
+
: {};
|
|
893
|
+
forcedNodes = completedArr.filter((id) => {
|
|
894
|
+
const record = evidenceMap[id];
|
|
895
|
+
return !(record && typeof record === 'object' && !Array.isArray(record));
|
|
896
|
+
});
|
|
897
|
+
} else {
|
|
898
|
+
const forcedSet = new Set(
|
|
899
|
+
(Array.isArray(state.history) ? state.history : [])
|
|
900
|
+
.filter((e) => e
|
|
901
|
+
&& e.event === 'advance-forced'
|
|
902
|
+
&& (typeof e.change !== 'string' || e.change === changeName))
|
|
903
|
+
.map((e) => e.node)
|
|
904
|
+
);
|
|
905
|
+
forcedNodes = completedArr.filter((id) => forcedSet.has(id));
|
|
906
|
+
}
|
|
824
907
|
console.log(JSON.stringify({
|
|
825
908
|
status: 'running',
|
|
826
909
|
change: changeName,
|
|
827
910
|
currentNode: detectedNode,
|
|
828
911
|
stateCurrentNode: state.currentNode,
|
|
829
912
|
completedNodes: state.completedNodes,
|
|
913
|
+
forcedNodes,
|
|
830
914
|
executionMode: state.executionMode ?? 'subagent',
|
|
831
915
|
directOverride: state.directOverride ?? false,
|
|
832
916
|
branchMode: isInsideWorkTree(),
|
|
833
917
|
enablePrReview: state.enablePrReview ?? false,
|
|
834
918
|
artifactRoot: '.specs/' + changeName,
|
|
835
|
-
coordinatorMode:
|
|
919
|
+
coordinatorMode: EXECUTE_FAMILY_NODE_IDS.has(detectedNode),
|
|
836
920
|
// G14: 新旧 change 标记——newChange true = 新 change(严格模式);false/缺失 = 旧 change(渐进)
|
|
837
921
|
newChange: state.newChange === true
|
|
838
922
|
}, null, 2));
|
|
@@ -848,6 +932,57 @@ async function main() {
|
|
|
848
932
|
return;
|
|
849
933
|
}
|
|
850
934
|
const state = await readState();
|
|
935
|
+
const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
|
|
936
|
+
// Fix 回退显式分支——必须早于「疑似未 exit」门禁与进行中漂移保护:
|
|
937
|
+
// review/verify 驻留 + TASK 有 pending 修复任务(串行/并行)或未闭合家族出口签名时,把工作
|
|
938
|
+
// 归属受控归位共享谓词返回的 execute 家族目标(写盘)并显式输出 NODE: <目标>,不再依赖
|
|
939
|
+
// inProgress 保护副作用(修复前并行任务 next 输出仍停在源节点)。判定复用 route-node 共享纯函数。
|
|
940
|
+
const fixRollbackDecision = await resolveFixRollbackDecision({
|
|
941
|
+
runRoot, changeName, protocol, completedNodes: completedArr, currentNode: state.currentNode,
|
|
942
|
+
history: state.history,
|
|
943
|
+
});
|
|
944
|
+
if (fixRollbackDecision) {
|
|
945
|
+
const sourceNode = state.currentNode;
|
|
946
|
+
// 轮次计数与阈值/授权判定全部走共享 helper:分支②不计数;第 4 轮新 change 先 BLOCK
|
|
947
|
+
// (此处尚未写盘,满足不写 currentNode),旧 change WARN 后照常归位。
|
|
948
|
+
const rollbackRound = applyFixRollbackRound({ state, sourceNode, decision: fixRollbackDecision });
|
|
949
|
+
if (rollbackRound.blocked) {
|
|
950
|
+
console.error(rollbackRound.blockedMessage);
|
|
951
|
+
process.exit(1);
|
|
952
|
+
}
|
|
953
|
+
if (rollbackRound.warn) console.error(rollbackRound.warnMessage);
|
|
954
|
+
state.currentNode = fixRollbackDecision.target;
|
|
955
|
+
await writeState(state);
|
|
956
|
+
console.log('FIX-BATCH: 归位 ' + fixRollbackDecision.target + '(源节点 ' + sourceNode + ')' + rollbackRound.auditSuffix);
|
|
957
|
+
printNext(protocol, fixRollbackDecision.target, state.executionMode ?? 'subagent');
|
|
958
|
+
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
// Fix 回程豁免——exit execute --apply 二次完成把 currentNode 回推源节点后,
|
|
962
|
+
// 源节点产物(REVIEW.md / TEST.md+UAT.md)已在场会让 resolveNextNode 跳过尚未 exit 的
|
|
963
|
+
// 源节点;仅当源节点未完成、任务全 done、firstIncompletePostExecNode === currentNode
|
|
964
|
+
// 且 resolveNextNode 确实会跳过该节点时显式放行(只读不改写 state)。artifactNext ===
|
|
965
|
+
// currentNode 的形态落回既有正常逻辑(normalAdvanceExempt 覆盖),不放宽豁免面。
|
|
966
|
+
const fixReturnNode = state.activeChange
|
|
967
|
+
? await resolveFixReturnNode({ runRoot, changeName, protocol, completedNodes: completedArr })
|
|
968
|
+
: null;
|
|
969
|
+
if (fixReturnNode !== null && fixReturnNode === state.currentNode) {
|
|
970
|
+
const artifactNext = await resolveNextNode({ runRoot, changeName, protocol, completedNodes: completedArr });
|
|
971
|
+
const routeIds = route(protocol).map((node) => node.id);
|
|
972
|
+
const artifactNextIdx = routeIds.indexOf(artifactNext);
|
|
973
|
+
const currentIdx = routeIds.indexOf(state.currentNode);
|
|
974
|
+
// 「跳过」必须是产物存在性把路由推到源节点之后;artifactNext 落在源节点之前(如 execute
|
|
975
|
+
// 产物缺失时回退到 execute)不是合法回程态,落回既有门禁,防止越界放宽(既有门禁反例锚)。
|
|
976
|
+
const skipsForward = artifactNext !== state.currentNode
|
|
977
|
+
&& currentIdx >= 0
|
|
978
|
+
&& artifactNextIdx > currentIdx;
|
|
979
|
+
if (skipsForward) {
|
|
980
|
+
console.log('RETURN: 回程源节点 ' + fixReturnNode + '(源节点产物在场且未出口;保留源节点跑出口)');
|
|
981
|
+
printNext(protocol, state.currentNode, state.executionMode ?? 'subagent');
|
|
982
|
+
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
851
986
|
// 节点顺序校验(严格模式)——state.currentNode 非 null、不在 completedNodes、
|
|
852
987
|
// 且 evidence 无该节点记录 → 上一节点从未 exit 就推进 → BLOCKED(exit 1)。
|
|
853
988
|
// 状态漂移校正保留:已完成节点(currentNode ∈ completedNodes,或 evidence 已记录——
|
|
@@ -855,17 +990,19 @@ async function main() {
|
|
|
855
990
|
// 豁免(两种独立判断,任一成立即放行): 回退豁免(TASK.md 有 pending 回退修复任务 回 execute);
|
|
856
991
|
// 正常推进豁免(currentNode 是 completedNodes 最后节点 exit 推进的正常下一节点,
|
|
857
992
|
// 见 normalAdvanceExempt)——真乱序(跳节点)仍严格 BLOCK
|
|
858
|
-
const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
|
|
859
993
|
if (state.currentNode && !completedArr.includes(state.currentNode)) {
|
|
860
994
|
const nodeEvidence = state.evidence && typeof state.evidence === 'object'
|
|
861
995
|
? state.evidence[state.currentNode]
|
|
862
996
|
: null;
|
|
863
997
|
const hasEvidence = !!(nodeEvidence && typeof nodeEvidence === 'object' && !Array.isArray(nodeEvidence));
|
|
864
998
|
if (!hasEvidence) {
|
|
865
|
-
//
|
|
866
|
-
//
|
|
867
|
-
//
|
|
868
|
-
const rollbackExempt = await
|
|
999
|
+
// 回退豁免(显式分支已先行;此处按共享谓词保留门禁层语义,不再内联第二份判定)——
|
|
1000
|
+
// review/verify 发现缺陷追加 pending 修复任务后回 execute 的修复任务标准回退路径放行
|
|
1001
|
+
// (否则被严格模式误拦为"未 exit 跳阶段");豁免条件不满足时维持严格 BLOCK
|
|
1002
|
+
const rollbackExempt = await resolveFixRollbackState({
|
|
1003
|
+
runRoot, changeName, protocol, completedNodes: completedArr, currentNode: state.currentNode,
|
|
1004
|
+
history: state.history,
|
|
1005
|
+
});
|
|
869
1006
|
// 正常推进豁免——exit --apply 推进 currentNode 到下一节点后按 SKILL 协议调 next
|
|
870
1007
|
// (正常路径)不拦截;与 回退豁免独立判断(详见 normalAdvanceExempt 注释)
|
|
871
1008
|
const advanceExempt = await normalAdvanceExempt(state, protocol, completedArr, state.currentNode, changeName);
|
|
@@ -883,7 +1020,7 @@ async function main() {
|
|
|
883
1020
|
// 防止静默路由到无法推进的节点造成死循环/死等。协议无 subagent-execute 节点时不适用
|
|
884
1021
|
// (parallel 任务由 execute 直接消化,无孤儿语义)。依赖环的常规拦截点在 plan 出口(guard 前置),
|
|
885
1022
|
// 此处兜底执行期数据异常(如手改 TASK 绕过签名校验的极端态)。
|
|
886
|
-
if (detectedNode
|
|
1023
|
+
if (EXECUTE_FAMILY_NODE_IDS.has(detectedNode)) {
|
|
887
1024
|
if (hasSubagentNode(protocol)) {
|
|
888
1025
|
try {
|
|
889
1026
|
const zpBlocks = taskBlocks(await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8'));
|
|
@@ -963,8 +1100,30 @@ async function main() {
|
|
|
963
1100
|
if (command === 'select') {
|
|
964
1101
|
const changeName = process.argv[3];
|
|
965
1102
|
if (!changeName) throw new Error('select requires a change name.');
|
|
1103
|
+
// change 名必须是 .specs/ 下的单段目录名(形态单一权威在 route-node.mjs):拒绝路径分隔符、
|
|
1104
|
+
// . / .. 与保留目录 archive(归档区不是活跃 change)——多段路径会把归档目录等非 change
|
|
1105
|
+
// 目录选成 activeChange,进而污染后续命令的 change 归属与轮次派生。
|
|
1106
|
+
if (!isSingleSegmentChangeName(changeName)) {
|
|
1107
|
+
throw new Error('select change 名必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive): '
|
|
1108
|
+
+ JSON.stringify(changeName));
|
|
1109
|
+
}
|
|
966
1110
|
const changeDir = path.join(specsRoot, changeName);
|
|
967
|
-
|
|
1111
|
+
// 目录必须真实存在且不是 symlink/junction、realpath 归一后仍在 .specs/ 内(复用路径段扫描
|
|
1112
|
+
// 单一权威);越界 / 链接形态一律拒绝,不把非真实目录选为 activeChange。
|
|
1113
|
+
let inspection;
|
|
1114
|
+
try {
|
|
1115
|
+
inspection = await inspectWorkflowPathSegments(specsRoot, changeDir, 'select change dir', 'directory');
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
throw new Error('Change not found or path unsafe: ' + changeDir + '(' + (error && error.message ? error.message : error) + ')');
|
|
1118
|
+
}
|
|
1119
|
+
if (!inspection.exists) throw new Error('Change not found: ' + changeDir);
|
|
1120
|
+
// 名字必须与 .specs/ 下真实目录条目逐字相等:大小写/空白变体(如 .specs/ch 用 'CH' 选中)
|
|
1121
|
+
// 在大小写不敏感文件系统上同样可达,但会把 activeChange 存成变体字符串——轮次事件按
|
|
1122
|
+
// activeChange 精确匹配(配额被换键重置)。名字变体一律拒绝,不得改写 activeChange。
|
|
1123
|
+
if (!(await hasExactSpecsEntry(changeName))) {
|
|
1124
|
+
throw new Error('select change 名必须与 .specs/ 下真实目录名逐字相等(大小写/空白变体会使 activeChange 与实际目录不一致): '
|
|
1125
|
+
+ JSON.stringify(changeName));
|
|
1126
|
+
}
|
|
968
1127
|
const state = await readState();
|
|
969
1128
|
state.activeChange = changeName;
|
|
970
1129
|
if (!state.currentNode) state.currentNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
@@ -1007,7 +1166,7 @@ async function main() {
|
|
|
1007
1166
|
const changeName = await findActiveChange();
|
|
1008
1167
|
if (!changeName) {
|
|
1009
1168
|
// 归档后场景:change 目录已移入 .specs/archive/(无活跃 change)——skill-load 不可用,
|
|
1010
|
-
// 但 record 的声明自动化(M5)
|
|
1169
|
+
// 但 record 的声明自动化(M5)仍可写归档路径标记——消息如实引导(真实运行实证反馈)
|
|
1011
1170
|
throw new Error('skill-load requires an active change(先运行 init <change-id>;若该 change 已归档,声明标记由 record 自动补写——M5 会写入归档路径的 .skill-loads/)');
|
|
1012
1171
|
}
|
|
1013
1172
|
// 标记 protocol 字段 = --prompt 参数的 basename(如 0-change.md)——与 guard exit
|
|
@@ -1243,18 +1402,602 @@ async function main() {
|
|
|
1243
1402
|
console.log('No active change. Use select first.');
|
|
1244
1403
|
return;
|
|
1245
1404
|
}
|
|
1405
|
+
// 被强制推进的节点 = 推进前的 currentNode:exit 门禁未跑(无出口证据),这正是留痕与
|
|
1406
|
+
// 可见性的依据(ADR-013 决策 10/11)。advance 的推进语义保持不变,但每次使用都必须写
|
|
1407
|
+
// 审计事件并在输出显式列出被跳过的出口门禁。
|
|
1408
|
+
const forcedNode = state.currentNode;
|
|
1409
|
+
const forcedNodeId = typeof forcedNode === 'string' && forcedNode !== '' ? forcedNode : null;
|
|
1246
1410
|
if (!state.completedNodes.includes(state.currentNode)) {
|
|
1247
1411
|
state.completedNodes.push(state.currentNode);
|
|
1248
1412
|
}
|
|
1249
1413
|
// Use determineNode to get the actual next node (reads TASK.md)
|
|
1250
1414
|
const detected = await determineNode(state.activeChange, protocol, state.completedNodes);
|
|
1251
1415
|
state.currentNode = detected;
|
|
1416
|
+
if (forcedNodeId !== null) {
|
|
1417
|
+
// append-only 审计事件:change 供跨 change 检索,skipped 标识被跳过的出口门禁
|
|
1418
|
+
// (exit:<node>),reason 固定 'advance'(本 CLI 无其它原因面)。
|
|
1419
|
+
const existingHistory = Array.isArray(state.history) ? state.history : [];
|
|
1420
|
+
state.history = existingHistory.concat([{
|
|
1421
|
+
event: 'advance-forced',
|
|
1422
|
+
change: state.activeChange,
|
|
1423
|
+
node: forcedNode,
|
|
1424
|
+
skipped: ['exit:' + forcedNode],
|
|
1425
|
+
reason: 'advance',
|
|
1426
|
+
at: new Date().toISOString(),
|
|
1427
|
+
}]);
|
|
1428
|
+
}
|
|
1252
1429
|
await writeState(state);
|
|
1253
1430
|
console.log('Advanced to: ' + state.currentNode);
|
|
1431
|
+
if (forcedNodeId !== null) {
|
|
1432
|
+
console.log('ADVANCE-AUDIT: 跳过 ' + forcedNodeId + ' 的 exit 门禁;该节点无出口证据');
|
|
1433
|
+
}
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
if (command === 'reenter') {
|
|
1438
|
+
// 受控重入(archive 源回边):archive 已 entry 且归档移动尚未发生时,用户显式授权把工作归属
|
|
1439
|
+
// 退回执行家族 / review / verify 之一。命令形态:reenter <target> --authorized-by <source>
|
|
1440
|
+
// --reason <text> [--continue-round <n>]。编排顺序:参数防护 → 路径边界(change 名单段 +
|
|
1441
|
+
// realpath 直接子目录)→ 单一权威判定(目标 / change 名 / 上限 / 幂等 / 源 / 授权)→ 备份
|
|
1442
|
+
// (包含性复核)→ 转移 → 授权留痕 → 审计事件 → REENTRY 行。全部判定集中在 route-node.mjs
|
|
1443
|
+
// 纯函数(本命令只做编排与落盘,禁止内联第二份);BLOCK 与空操作路径一律在写盘前返回
|
|
1444
|
+
// (state 字节零改写)。
|
|
1445
|
+
const target = process.argv[3];
|
|
1446
|
+
const reentryTargetList = [...REENTRY_TARGET_NODE_IDS].join(', ');
|
|
1447
|
+
const reenterUsage = '用法: workflow-state.mjs reenter <target> --authorized-by <source> --reason <text>'
|
|
1448
|
+
+ ' [--continue-round <n>](target 白名单: ' + reentryTargetList + ')';
|
|
1449
|
+
if (typeof target !== 'string' || target === '' || target.startsWith('--')) {
|
|
1450
|
+
console.error('BLOCKED: reenter 缺少目标节点。' + reenterUsage);
|
|
1451
|
+
process.exit(1);
|
|
1452
|
+
}
|
|
1453
|
+
let authorizedBy = null;
|
|
1454
|
+
let reason = null;
|
|
1455
|
+
let continuationRound = null;
|
|
1456
|
+
const reenterArgs = process.argv.slice(4);
|
|
1457
|
+
for (let index = 0; index < reenterArgs.length; index += 1) {
|
|
1458
|
+
const arg = reenterArgs[index];
|
|
1459
|
+
// 支持 --name value 与 --name=value 两种形态;--protocol 为全局参数(协议路径已由
|
|
1460
|
+
// resolveProtocol 统一解析),命令面只做占位透传。
|
|
1461
|
+
let key = arg;
|
|
1462
|
+
let value = null;
|
|
1463
|
+
if (typeof arg === 'string' && arg.startsWith('--')) {
|
|
1464
|
+
const eq = arg.indexOf('=');
|
|
1465
|
+
if (eq > 0) {
|
|
1466
|
+
key = arg.slice(0, eq);
|
|
1467
|
+
value = arg.slice(eq + 1);
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
if (key === '--protocol') {
|
|
1471
|
+
if (value === null) index += 1;
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
if (key === '--continue-round') {
|
|
1475
|
+
// 续轮授权只在达到轮次上限后生效:命令面收正整数,形态合法性与「是否已到上限」由
|
|
1476
|
+
// 单一权威综合判定裁决(本处只做数值形态防护,fail-closed,先于任何读盘)。
|
|
1477
|
+
let consumedNext = false;
|
|
1478
|
+
if (value === null) {
|
|
1479
|
+
value = reenterArgs[index + 1];
|
|
1480
|
+
consumedNext = true;
|
|
1481
|
+
}
|
|
1482
|
+
const parsedRound = typeof value === 'string' && value.trim() !== '' && !value.startsWith('--')
|
|
1483
|
+
? Number(value.trim())
|
|
1484
|
+
: Number.NaN;
|
|
1485
|
+
if (!Number.isInteger(parsedRound) || parsedRound <= 0) {
|
|
1486
|
+
console.error('BLOCKED: reenter --continue-round 需要正整数取值,实际 ' + JSON.stringify(value) + '。' + reenterUsage);
|
|
1487
|
+
process.exit(1);
|
|
1488
|
+
}
|
|
1489
|
+
continuationRound = parsedRound;
|
|
1490
|
+
if (consumedNext) index += 1;
|
|
1491
|
+
continue;
|
|
1492
|
+
}
|
|
1493
|
+
if (key === '--authorized-by' || key === '--reason') {
|
|
1494
|
+
let consumedNext = false;
|
|
1495
|
+
if (value === null) {
|
|
1496
|
+
value = reenterArgs[index + 1];
|
|
1497
|
+
consumedNext = true;
|
|
1498
|
+
}
|
|
1499
|
+
// 缺值 / 空值 / 纯空白 / 取下个选项名当值 → 一律用法错误(fail-closed,先于任何读盘)
|
|
1500
|
+
if (typeof value !== 'string' || value.trim() === '' || value.startsWith('--')) {
|
|
1501
|
+
console.error('BLOCKED: reenter ' + key + ' 需要非空取值。' + reenterUsage);
|
|
1502
|
+
process.exit(1);
|
|
1503
|
+
}
|
|
1504
|
+
if (key === '--authorized-by') authorizedBy = value.trim();
|
|
1505
|
+
else reason = value.trim();
|
|
1506
|
+
if (consumedNext) index += 1;
|
|
1507
|
+
continue;
|
|
1508
|
+
}
|
|
1509
|
+
console.error('BLOCKED: reenter 未知参数 ' + JSON.stringify(arg) + '。' + reenterUsage);
|
|
1510
|
+
process.exit(1);
|
|
1511
|
+
}
|
|
1512
|
+
if (authorizedBy === null) {
|
|
1513
|
+
console.error('BLOCKED: reenter 需要显式授权 --authorized-by <source>(授权不可自决)。' + reenterUsage);
|
|
1514
|
+
process.exit(1);
|
|
1515
|
+
}
|
|
1516
|
+
if (reason === null) {
|
|
1517
|
+
console.error('BLOCKED: reenter 需要 --reason <text> 说明重入原因。' + reenterUsage);
|
|
1518
|
+
process.exit(1);
|
|
1519
|
+
}
|
|
1520
|
+
const state = await readState();
|
|
1521
|
+
const badFields = validateStateFields(state);
|
|
1522
|
+
if (badFields.length > 0) {
|
|
1523
|
+
// history 存在但非数组等类型损坏在此 fail-closed:不得由本命令静默清空覆盖审计历史。
|
|
1524
|
+
console.error('BLOCKED: state 字段类型非法: ' + badFields[0]);
|
|
1525
|
+
process.exit(1);
|
|
1526
|
+
}
|
|
1527
|
+
// 原始 state(未经 readState 兼容默认值叠加):落盘时只写「原始键集 + 本次实际改动的字段」,
|
|
1528
|
+
// 兼容默认值不得随重入回写(最小旧 state 的键集保持逐项不变)。
|
|
1529
|
+
const rawState = (await fileExists(statePath)) ? await readJson(statePath) : null;
|
|
1530
|
+
// 路径边界:change 名必须是 .specs/ 下的单段真实目录(realpath 归一后是 .specs 直接子目录,
|
|
1531
|
+
// 且路径上无 symlink/junction)。归档移动已发生(目录不在原位)、change 已 completed、
|
|
1532
|
+
// change 名畸形(多段 / . / .. / 保留目录 archive)与链接逃逸一律 BLOCK。该边界先于综合
|
|
1533
|
+
// 判定执行——completed 与已移动形态必须无条件 BLOCK(不被空操作分支短路)。
|
|
1534
|
+
const changeName = typeof state.activeChange === 'string' ? state.activeChange : '';
|
|
1535
|
+
const changeBoundary = await inspectReentryChangeDir(changeName);
|
|
1536
|
+
const changeDirPresent = changeBoundary.ok
|
|
1537
|
+
? true
|
|
1538
|
+
: (changeBoundary.reason === 'change-dir-missing' ? false : null);
|
|
1539
|
+
const movedOrCompletedMessage = 'BLOCKED: 归档移动已发生或 change 已 completed(.specs/'
|
|
1540
|
+
+ (changeName || '<未知>') + '/ 在场=' + changeDirPresent + ',status=' + JSON.stringify(state.status)
|
|
1541
|
+
+ ')——受控重入只覆盖归档移动前的运行形态;请走人工处置、新 change 或 hotfix 路径。';
|
|
1542
|
+
if (state.status === 'completed' || changeDirPresent === false) {
|
|
1543
|
+
console.error(movedOrCompletedMessage);
|
|
1544
|
+
process.exit(1);
|
|
1545
|
+
}
|
|
1546
|
+
if (!changeBoundary.ok) {
|
|
1547
|
+
const boundaryMessages = {
|
|
1548
|
+
'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
|
|
1549
|
+
'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
|
|
1550
|
+
+ '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
|
|
1551
|
+
'change-dir-escape': 'change 目录路径越界或跨越符号链接 / junction(' + changeBoundary.detail
|
|
1552
|
+
+ ')——受控重入与备份只允许落在 .specs/<change-id>/ 真实目录内',
|
|
1553
|
+
};
|
|
1554
|
+
console.error('BLOCKED: ' + boundaryMessages[changeBoundary.reason]);
|
|
1555
|
+
process.exit(1);
|
|
1556
|
+
}
|
|
1557
|
+
const changeDir = changeBoundary.changeDir;
|
|
1558
|
+
// 授权形态的 round / at 由引擎派生(命令面只承载授权来源、原因与上限后的续轮轮次):普通轮次
|
|
1559
|
+
// 以合法占位值过形态门;落盘轮次一律取综合判定返回的 round(由本 change 历史事件派生),
|
|
1560
|
+
// 不在此内联第二份轮次推导。
|
|
1561
|
+
const authorizedAt = new Date().toISOString();
|
|
1562
|
+
const decision = resolveReentryDecision({
|
|
1563
|
+
protocol,
|
|
1564
|
+
state,
|
|
1565
|
+
target,
|
|
1566
|
+
authorization: { round: 1, at: authorizedAt, source: authorizedBy, target },
|
|
1567
|
+
continuationRound,
|
|
1568
|
+
});
|
|
1569
|
+
if (!decision.ok) {
|
|
1570
|
+
if (decision.reason === 'round-limit-reached') {
|
|
1571
|
+
console.error('BLOCKED: 本 change 受控重入已达上限(' + decision.used + '/' + decision.limit
|
|
1572
|
+
+ ' 轮)。需要人工裁决:继续(显式授权后在同一命令加 --continue-round <n>,n 为不小于第 '
|
|
1573
|
+
+ (decision.used + 1) + ' 轮的正整数,须与 --authorized-by / --reason 同次传入)/ 停止(保持归档态,不再重入)。');
|
|
1574
|
+
process.exit(1);
|
|
1575
|
+
}
|
|
1576
|
+
const guidance = {
|
|
1577
|
+
'target-not-allowed': '目标节点 ' + JSON.stringify(target) + ' 不在受控重入白名单('
|
|
1578
|
+
+ reentryTargetList + ')——请显式指定白名单内目标',
|
|
1579
|
+
'target-not-enabled': '目标节点 ' + JSON.stringify(target)
|
|
1580
|
+
+ ' 在当前协议中未启用(disabled)——请检查协议或改选已启用目标',
|
|
1581
|
+
'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
|
|
1582
|
+
'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
|
|
1583
|
+
+ '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
|
|
1584
|
+
'source-not-archive': '受控重入只覆盖 archive 源(当前节点 ' + JSON.stringify(state.currentNode)
|
|
1585
|
+
+ ')——正常推进请走 next / record / exit 既有通道',
|
|
1586
|
+
'continuation-not-required': '--continue-round 只在达到轮次上限后需要(当前 ' + decision.used + '/'
|
|
1587
|
+
+ decision.limit + ' 轮)——上限前请直接以 --authorized-by / --reason 发起',
|
|
1588
|
+
}[decision.reason] || ('授权形态不合法(' + decision.reason + ')——需要用户显式传入 --authorized-by <source>');
|
|
1589
|
+
console.error('BLOCKED: ' + guidance);
|
|
1590
|
+
process.exit(1);
|
|
1591
|
+
}
|
|
1592
|
+
if (decision.action === 'noop') {
|
|
1593
|
+
console.log('REENTRY: 空操作——workflow 已处于目标形态(' + target
|
|
1594
|
+
+ ',完成标记已是目标前驱交集);未备份、未计数、未改写 state。');
|
|
1595
|
+
return;
|
|
1596
|
+
}
|
|
1597
|
+
if (decision.action !== 'apply') {
|
|
1598
|
+
console.error('BLOCKED: 受控重入判定返回未知动作 ' + JSON.stringify(decision.action) + '——按 fail-closed 拒绝。');
|
|
1599
|
+
process.exit(1);
|
|
1600
|
+
}
|
|
1601
|
+
const round = decision.round;
|
|
1602
|
+
const source = decision.authorization.source;
|
|
1603
|
+
const at = decision.authorization.at;
|
|
1604
|
+
const continuationAuthorized = decision.continuationAuthorized === true;
|
|
1605
|
+
// 备份:重入前 state 全量快照(文件原始字节,UTF-8 BOM 按可解析形态落盘);文件名
|
|
1606
|
+
// <UTC ISO 净化>-pre-<target>.json;审计指纹 = 备份文件字节的 sha256(可核验)。
|
|
1607
|
+
const backupDir = path.join(changeDir, '.reentry-backups');
|
|
1608
|
+
const backupFile = at.replace(/:/g, '-') + '-pre-' + target + '.json';
|
|
1609
|
+
const backupPath = path.join(backupDir, backupFile);
|
|
1610
|
+
const backupRecord = path.relative(runRoot, backupPath).split(path.sep).join('/');
|
|
1611
|
+
const snapshotBytes = Buffer.from((await fs.readFile(statePath, 'utf8')).replace(/^\uFEFF/, ''), 'utf8');
|
|
1612
|
+
const fingerprint = createHash('sha256').update(snapshotBytes).digest('hex');
|
|
1613
|
+
const existingHistory = Array.isArray(rawState?.history) ? rawState.history : [];
|
|
1614
|
+
let backupWritten = false;
|
|
1615
|
+
try {
|
|
1616
|
+
if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
|
|
1617
|
+
throw new Error('state 文件缺失或形态非法,无法重入');
|
|
1618
|
+
}
|
|
1619
|
+
// 备份写入路径的物理包含性复核(单一权威路径段扫描):备份目录与备份文件逐段
|
|
1620
|
+
// lstat + realpath——任何 symlink/junction 逃出 .specs/ 一律拒绝,不写任何字节。
|
|
1621
|
+
await fs.mkdir(backupDir, { recursive: true });
|
|
1622
|
+
await inspectWorkflowPathSegments(specsRoot, backupDir, 'reenter backup dir', 'directory');
|
|
1623
|
+
await fs.writeFile(backupPath, snapshotBytes);
|
|
1624
|
+
backupWritten = true;
|
|
1625
|
+
await inspectWorkflowPathSegments(specsRoot, backupPath, 'reenter backup file', 'file');
|
|
1626
|
+
// 授权留痕:嵌套写入被重入目标节点的 evidence(授权记录 + 备份指针 + 指纹 + 原因 +
|
|
1627
|
+
// 续轮标记)。只改 evidence 的目标节点键,其余键按原始键集逐项保留。
|
|
1628
|
+
const existingEvidence = rawState.evidence && typeof rawState.evidence === 'object' && !Array.isArray(rawState.evidence)
|
|
1629
|
+
? rawState.evidence
|
|
1630
|
+
: {};
|
|
1631
|
+
const targetEvidence = existingEvidence[decision.target]
|
|
1632
|
+
&& typeof existingEvidence[decision.target] === 'object'
|
|
1633
|
+
&& !Array.isArray(existingEvidence[decision.target])
|
|
1634
|
+
? existingEvidence[decision.target]
|
|
1635
|
+
: {};
|
|
1636
|
+
const authorizationRecord = {
|
|
1637
|
+
round,
|
|
1638
|
+
at,
|
|
1639
|
+
source,
|
|
1640
|
+
target: decision.target,
|
|
1641
|
+
backup: backupRecord,
|
|
1642
|
+
fingerprint,
|
|
1643
|
+
reason,
|
|
1644
|
+
...(continuationAuthorized ? { continuationAuthorized: true } : {}),
|
|
1645
|
+
};
|
|
1646
|
+
// 落盘形态 = 原始 state 键集 + 本次实际改动的四类机器字段与审计字段——转移语义
|
|
1647
|
+
// (currentNode := target / completedNodes := 前驱交集 / status := running)与审计
|
|
1648
|
+
// (evidence 留痕 + history 追加事件)之外的字段逐项不变;readState 的兼容默认值不回写。
|
|
1649
|
+
const persisted = { ...rawState };
|
|
1650
|
+
persisted.currentNode = decision.target;
|
|
1651
|
+
persisted.completedNodes = decision.completedNodes.slice();
|
|
1652
|
+
persisted.status = 'running';
|
|
1653
|
+
persisted.evidence = {
|
|
1654
|
+
...existingEvidence,
|
|
1655
|
+
[decision.target]: { ...targetEvidence, reentryAuthorization: authorizationRecord },
|
|
1656
|
+
};
|
|
1657
|
+
// 审计事件:append-only 追加 reentry-applied;change 字段是跨 change 轮次隔离的唯一依据。
|
|
1658
|
+
persisted.history = existingHistory.concat([{
|
|
1659
|
+
event: 'reentry-applied',
|
|
1660
|
+
from: 'archive',
|
|
1661
|
+
to: decision.target,
|
|
1662
|
+
round,
|
|
1663
|
+
authorization: { round, at, source, target: decision.target },
|
|
1664
|
+
backup: backupRecord,
|
|
1665
|
+
fingerprint,
|
|
1666
|
+
at,
|
|
1667
|
+
change: changeName,
|
|
1668
|
+
reason,
|
|
1669
|
+
...(continuationAuthorized ? { continuationAuthorized: true } : {}),
|
|
1670
|
+
}]);
|
|
1671
|
+
const persistedBad = validateStateFields(persisted);
|
|
1672
|
+
if (persistedBad.length > 0) throw new Error('state 字段类型非法: ' + persistedBad[0]);
|
|
1673
|
+
await writeState(persisted);
|
|
1674
|
+
} catch (error) {
|
|
1675
|
+
// 写盘失败:回滚本次调用创建的孤儿备份(state 由原子写保证不被截断),原始错误照常上抛。
|
|
1676
|
+
if (backupWritten) {
|
|
1677
|
+
try { await fs.rm(backupPath, { force: true }); } catch { /* 清理失败不掩盖原始错误 */ }
|
|
1678
|
+
}
|
|
1679
|
+
throw error;
|
|
1680
|
+
}
|
|
1681
|
+
const roundLabel = continuationAuthorized
|
|
1682
|
+
? '第 ' + round + ' 轮(显式授权续轮,上限 ' + REENTRY_ROUND_LIMIT + ')'
|
|
1683
|
+
: '第 ' + round + '/' + REENTRY_ROUND_LIMIT + ' 轮';
|
|
1684
|
+
console.log('REENTRY: archive → ' + decision.target + '(授权源 ' + source + ';' + roundLabel
|
|
1685
|
+
+ ';备份 ' + backupRecord + ')');
|
|
1686
|
+
console.log('REASON: ' + reason);
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
if (command === 'replan') {
|
|
1691
|
+
// 受控计划重校重签(ADR-013):计划在执行中被证明有缺陷时,唯一合规的重签入口——只在
|
|
1692
|
+
// execute / subagent-execute 相位可用、停原位(不跳节点、不改 completedNodes),先把任务集
|
|
1693
|
+
// 重新校验(依赖图 + 任务字段,绝不豁免)再重录 state.taskHash。命令形态:
|
|
1694
|
+
// replan <reason> --authorized-by <source> [--continue-round <n>]。
|
|
1695
|
+
// 编排顺序与 reenter 同构:参数防护 → 读 state → 单一权威判定(相位/change → 授权 →
|
|
1696
|
+
// 上限与续轮 → 幂等空操作)→ 重校 → 备份(sha256)→ 重签 → 双写留痕 → REPLAN/REASON 行;
|
|
1697
|
+
// 全部判定集中在 route-node.mjs 纯函数族,BLOCK 与空操作路径一律在写盘前返回(字节零改写)。
|
|
1698
|
+
const replanUsage = '用法: workflow-state.mjs replan <reason> --authorized-by <source> [--continue-round <n>]';
|
|
1699
|
+
const replanReason = process.argv[3];
|
|
1700
|
+
if (typeof replanReason !== 'string' || replanReason.trim() === '' || replanReason.startsWith('--')) {
|
|
1701
|
+
console.error('BLOCKED: replan 缺少原因(位置参数 <reason> 必填且非空)。' + replanUsage);
|
|
1702
|
+
process.exit(1);
|
|
1703
|
+
}
|
|
1704
|
+
const reason = replanReason.trim();
|
|
1705
|
+
let authorizedBy = null;
|
|
1706
|
+
let continuationRound = null;
|
|
1707
|
+
const replanArgs = process.argv.slice(4);
|
|
1708
|
+
for (let index = 0; index < replanArgs.length; index += 1) {
|
|
1709
|
+
const arg = replanArgs[index];
|
|
1710
|
+
// 支持 --name value 与 --name=value 两种形态;--protocol 为全局参数(协议路径已由
|
|
1711
|
+
// resolveProtocol 统一解析),命令面只做占位透传。
|
|
1712
|
+
let key = arg;
|
|
1713
|
+
let value = null;
|
|
1714
|
+
if (typeof arg === 'string' && arg.startsWith('--')) {
|
|
1715
|
+
const eq = arg.indexOf('=');
|
|
1716
|
+
if (eq > 0) {
|
|
1717
|
+
key = arg.slice(0, eq);
|
|
1718
|
+
value = arg.slice(eq + 1);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
if (key === '--protocol') {
|
|
1722
|
+
if (value === null) index += 1;
|
|
1723
|
+
continue;
|
|
1724
|
+
}
|
|
1725
|
+
if (key === '--continue-round') {
|
|
1726
|
+
// 续轮授权只在达到轮次上限后生效:命令面收正整数,形态合法性与「是否已到上限」由
|
|
1727
|
+
// 单一权威综合判定裁决(本处只做数值形态防护,fail-closed,先于任何读盘)。
|
|
1728
|
+
let consumedNext = false;
|
|
1729
|
+
if (value === null) {
|
|
1730
|
+
value = replanArgs[index + 1];
|
|
1731
|
+
consumedNext = true;
|
|
1732
|
+
}
|
|
1733
|
+
const parsedRound = typeof value === 'string' && value.trim() !== '' && !value.startsWith('--')
|
|
1734
|
+
? Number(value.trim())
|
|
1735
|
+
: Number.NaN;
|
|
1736
|
+
if (!Number.isInteger(parsedRound) || parsedRound <= 0) {
|
|
1737
|
+
console.error('BLOCKED: replan --continue-round 需要正整数取值,实际 ' + JSON.stringify(value) + '。' + replanUsage);
|
|
1738
|
+
process.exit(1);
|
|
1739
|
+
}
|
|
1740
|
+
continuationRound = parsedRound;
|
|
1741
|
+
if (consumedNext) index += 1;
|
|
1742
|
+
continue;
|
|
1743
|
+
}
|
|
1744
|
+
if (key === '--authorized-by') {
|
|
1745
|
+
let consumedNext = false;
|
|
1746
|
+
if (value === null) {
|
|
1747
|
+
value = replanArgs[index + 1];
|
|
1748
|
+
consumedNext = true;
|
|
1749
|
+
}
|
|
1750
|
+
// 缺值 / 空值 / 纯空白 / 取下个选项名当值 → 一律用法错误(fail-closed,先于任何读盘)
|
|
1751
|
+
if (typeof value !== 'string' || value.trim() === '' || value.startsWith('--')) {
|
|
1752
|
+
console.error('BLOCKED: replan --authorized-by 需要非空取值。' + replanUsage);
|
|
1753
|
+
process.exit(1);
|
|
1754
|
+
}
|
|
1755
|
+
authorizedBy = value.trim();
|
|
1756
|
+
if (consumedNext) index += 1;
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
console.error('BLOCKED: replan 未知参数 ' + JSON.stringify(arg) + '。' + replanUsage);
|
|
1760
|
+
process.exit(1);
|
|
1761
|
+
}
|
|
1762
|
+
if (authorizedBy === null) {
|
|
1763
|
+
console.error('BLOCKED: replan 需要显式授权 --authorized-by <source>(授权不可自决)。' + replanUsage);
|
|
1764
|
+
process.exit(1);
|
|
1765
|
+
}
|
|
1766
|
+
const state = await readState();
|
|
1767
|
+
const badFields = validateStateFields(state);
|
|
1768
|
+
if (badFields.length > 0) {
|
|
1769
|
+
// history 存在但非数组等类型损坏在此 fail-closed:不得由本命令静默清空覆盖审计历史。
|
|
1770
|
+
console.error('BLOCKED: state 字段类型非法: ' + badFields[0]);
|
|
1771
|
+
process.exit(1);
|
|
1772
|
+
}
|
|
1773
|
+
// 原始 state(未经 readState 兼容默认值叠加):备份取文件原始字节,落盘只写「原始键集 +
|
|
1774
|
+
// 本次实际改动的字段」——兼容默认值不得随重校回写(与受控重入同纪律)。
|
|
1775
|
+
const rawState = (await fileExists(statePath)) ? await readJson(statePath) : null;
|
|
1776
|
+
const changeName = typeof state.activeChange === 'string' ? state.activeChange : '';
|
|
1777
|
+
// 任务内容读取(fail-closed):不可读 / 为空 → 交由综合判定返回 task-content-missing
|
|
1778
|
+
// block(缺 TASK.md 时不得以「空任务集签名」判幂等空操作放行,L-079)。
|
|
1779
|
+
let taskContent = null;
|
|
1780
|
+
try {
|
|
1781
|
+
taskContent = await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8');
|
|
1782
|
+
} catch { taskContent = null; }
|
|
1783
|
+
// 授权形态的 round / at 由引擎派生(命令面只承载授权来源、原因与上限后的续轮轮次):普通
|
|
1784
|
+
// 轮次以合法占位值过形态门;落盘轮次一律取综合判定返回的 round(由本 change 历史事件派生),
|
|
1785
|
+
// 不在此内联第二份轮次推导。
|
|
1786
|
+
const authorizedAt = new Date().toISOString();
|
|
1787
|
+
const decision = resolveReplanDecision({
|
|
1788
|
+
protocol,
|
|
1789
|
+
state,
|
|
1790
|
+
authorization: { round: 1, at: authorizedAt, source: authorizedBy, reason, node: state.currentNode },
|
|
1791
|
+
continuationRound,
|
|
1792
|
+
taskContent,
|
|
1793
|
+
});
|
|
1794
|
+
if (!decision.ok) {
|
|
1795
|
+
if (decision.reason === 'round-limit-reached') {
|
|
1796
|
+
console.error('BLOCKED: 本 change 计划重校已达上限(' + decision.used + '/' + decision.limit
|
|
1797
|
+
+ ' 轮)。需要人工裁决:继续(显式授权后在同一命令加 --continue-round <n>,n 为不小于第 '
|
|
1798
|
+
+ (decision.used + 1) + ' 轮的正整数,须与 --authorized-by / <reason> 同次传入)/ 停止(保持现状,不再重校)。');
|
|
1799
|
+
process.exit(1);
|
|
1800
|
+
}
|
|
1801
|
+
const replanGuidance = {
|
|
1802
|
+
'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
|
|
1803
|
+
'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
|
|
1804
|
+
+ '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
|
|
1805
|
+
'phase-not-allowed': 'replan 只在 execute / subagent-execute 相位可用(当前节点 '
|
|
1806
|
+
+ JSON.stringify(state.currentNode) + ')——其余相位请走既有推进 / 受控重入通道',
|
|
1807
|
+
'continuation-not-required': '--continue-round 只在达到轮次上限后需要(当前 ' + decision.used + '/'
|
|
1808
|
+
+ decision.limit + ' 轮)——上限前请直接以 --authorized-by / <reason> 发起',
|
|
1809
|
+
'task-content-missing': '任务内容缺失或不可读(.specs/<change>/TASK.md 不存在 / 为空)——按 fail-closed 拒绝重签',
|
|
1810
|
+
}[decision.reason] || ('授权形态不合法(' + decision.reason + ')——需要用户显式传入 --authorized-by <source>');
|
|
1811
|
+
console.error('BLOCKED: ' + replanGuidance);
|
|
1812
|
+
process.exit(1);
|
|
1813
|
+
}
|
|
1814
|
+
if (decision.action === 'noop') {
|
|
1815
|
+
console.log('REPLAN: 空操作——state.taskHash 已与当前 TASK.md 同签(' + decision.node
|
|
1816
|
+
+ '),无需重校;未备份、未计数、未写事件、未改写 state。');
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
if (decision.action !== 'apply') {
|
|
1820
|
+
console.error('BLOCKED: replan 判定返回未知动作 ' + JSON.stringify(decision.action) + '——按 fail-closed 拒绝。');
|
|
1821
|
+
process.exit(1);
|
|
1822
|
+
}
|
|
1823
|
+
// 重校(ADR-013 决策 3:replan 绝不做校验豁免):任务块 / <verify> / 任务图(依赖环与
|
|
1824
|
+
// 缺失依赖——analyzeDependencyGraph 单一实现,与 plan 出口同源)/ 7 字段完整性。任一失败
|
|
1825
|
+
// → BLOCK,状态零改写(本段全部先于备份与写盘)。
|
|
1826
|
+
const taskList = taskBlocks(taskContent);
|
|
1827
|
+
if (taskList.length === 0) {
|
|
1828
|
+
console.error('BLOCKED: TASK.md 无 <task> 块——replan 不做校验豁免,拒绝重签(状态零改写)。');
|
|
1829
|
+
process.exit(1);
|
|
1830
|
+
}
|
|
1831
|
+
const missingVerify = taskList.filter((block) => !/<verify>/.test(block));
|
|
1832
|
+
if (missingVerify.length > 0) {
|
|
1833
|
+
console.error('BLOCKED: TASK.md 中 ' + missingVerify.length
|
|
1834
|
+
+ ' 个 task 缺 <verify> 字段——replan 不做校验豁免,拒绝重签(状态零改写)。');
|
|
1835
|
+
process.exit(1);
|
|
1836
|
+
}
|
|
1837
|
+
const depGraph = analyzeDependencyGraph(taskList);
|
|
1838
|
+
if (depGraph.cyclic || depGraph.missing.length > 0) {
|
|
1839
|
+
const detail = depGraph.cyclic
|
|
1840
|
+
? '依赖环(拓扑排序无解,涉及任务: ' + depGraph.cycleIds.join(', ') + ')'
|
|
1841
|
+
: '依赖不存在的任务: ' + depGraph.missing.map((m) => m.id + '→' + m.dep).join(', ');
|
|
1842
|
+
console.error('BLOCKED: TASK.md ' + detail
|
|
1843
|
+
+ '——依赖图不可满足(任务的依赖链必须存在且无环);replan 不做校验豁免,拒绝重签(状态零改写)'
|
|
1844
|
+
+ ';恢复: 调整任务 depends_on——移除成环引用或改为真实存在的任务 id 后重试');
|
|
1845
|
+
process.exit(1);
|
|
1846
|
+
}
|
|
1847
|
+
// 任务字段完整性(与 plan 出口同一判据):新模板形态(含 <name>)且新 change → BLOCK;
|
|
1848
|
+
// 旧式一字段形态 / 旧 change 保持渐进 WARN(不放大既有语义)。
|
|
1849
|
+
const replanTask7Required = ['name', 'read_files', 'write_files', 'action', 'verify', 'done', 'depends_on'];
|
|
1850
|
+
const replanTask7NewFormat = taskList.some((block) => /<name\b/i.test(block));
|
|
1851
|
+
const replanTask7Broken = [];
|
|
1852
|
+
for (const block of taskList) {
|
|
1853
|
+
const missing = replanTask7Required.filter((field) => !new RegExp('</?' + field + '\\b', 'i').test(block));
|
|
1854
|
+
if (missing.length > 0) {
|
|
1855
|
+
const idAttr = (taskOpeningAttrs(block) || {}).id || '?';
|
|
1856
|
+
replanTask7Broken.push((idAttr !== '?' ? idAttr + ' ' : '') + '缺 ' + missing.join('/'));
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
if (replanTask7Broken.length > 0) {
|
|
1860
|
+
if (replanTask7NewFormat && state.newChange === true) {
|
|
1861
|
+
console.error('BLOCKED: TASK.md 任务缺 7 字段(name/read_files/write_files/action/verify/done/depends_on): '
|
|
1862
|
+
+ replanTask7Broken.join('; ') + ';恢复: 对照 flow-kit/templates/TASK.md 补齐每个 <task> 的缺字段后重试;replan 不做校验豁免');
|
|
1863
|
+
process.exit(1);
|
|
1864
|
+
}
|
|
1865
|
+
console.error('TASK-7FIELD WARN: TASK.md ' + replanTask7Broken.join('; ')
|
|
1866
|
+
+ (replanTask7NewFormat ? '(旧 change 渐进,不阻断)' : '(旧式一字段模板形态,渐进不阻断)'));
|
|
1867
|
+
}
|
|
1868
|
+
// 路径边界:change 名必须是 .specs/ 下的单段真实目录(realpath 归一后仍在 .specs/ 内、
|
|
1869
|
+
// 无 symlink/junction 逃逸;复用受控路径边界实现)——备份落点必须先通过该边界。
|
|
1870
|
+
const changeBoundary = await inspectReentryChangeDir(changeName);
|
|
1871
|
+
if (!changeBoundary.ok) {
|
|
1872
|
+
const boundaryMessages = {
|
|
1873
|
+
'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
|
|
1874
|
+
'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
|
|
1875
|
+
+ '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
|
|
1876
|
+
'change-dir-missing': '.specs/' + (changeName || '<未知>') + '/ 目录不存在——重校备份必须具备真实 change 目录落点',
|
|
1877
|
+
'change-dir-escape': 'change 目录路径越界或跨越符号链接 / junction(' + changeBoundary.detail
|
|
1878
|
+
+ ')——受控重校与备份只允许落在 .specs/<change-id>/ 真实目录内',
|
|
1879
|
+
};
|
|
1880
|
+
console.error('BLOCKED: ' + (boundaryMessages[changeBoundary.reason] || ('change 目录边界异常(' + changeBoundary.reason + ')')));
|
|
1881
|
+
process.exit(1);
|
|
1882
|
+
}
|
|
1883
|
+
const changeDir = changeBoundary.changeDir;
|
|
1884
|
+
// 并行写冲突校验(2026-09-28 PR 审查采纳):replan 不做校验豁免——重校后的任务集若含
|
|
1885
|
+
// 本趟可运行(依赖已满足)的并行任务且 write_files 重叠,与 plan 出口使用同一实现
|
|
1886
|
+
// (route-node.findParallelWriteConflicts 单一来源)在此 BLOCK;必须早于备份与任何写盘,
|
|
1887
|
+
// BLOCK 路径 state 字节零改写。read∩write 弱判与 plan 出口同风格——仅 WARN 不阻断。
|
|
1888
|
+
// 同文件跨任务且无依赖路径(第三族)同样在此消费:与 plan 出口同判据、同分级(新 change
|
|
1889
|
+
// BLOCKED / 旧 change WARN),消息同族(任务对 `a×b(files)` + 恢复指引「补显式 depends_on 或
|
|
1890
|
+
// 合并为一个任务」)——replan 是执行期唯一合法的任务集修订通道,不得成为该形态的豁免口。
|
|
1891
|
+
const { writeConflicts, crossTaskConflicts, readWarnings } = await findParallelWriteConflicts(path.join(runRoot, '.specs', changeName));
|
|
1892
|
+
if (writeConflicts.length > 0) {
|
|
1893
|
+
console.error('BLOCKED: replan 检测到并行写冲突('
|
|
1894
|
+
+ writeConflicts.map((c) => c.a + '↔' + c.b + ': ' + c.files.join(',')).join('; ')
|
|
1895
|
+
+ ')——replan 不做校验豁免,状态零改写;恢复: 调整 write_files 消除重叠后重试');
|
|
1896
|
+
process.exit(1);
|
|
1897
|
+
}
|
|
1898
|
+
if (crossTaskConflicts.length > 0) {
|
|
1899
|
+
const crossDetail = crossTaskConflicts.map((c) => c.a + '×' + c.b + '(' + c.files.join(',') + ')').join('; ');
|
|
1900
|
+
const crossGuide = ';恢复: 补显式 depends_on 或合并为一个任务后重试';
|
|
1901
|
+
if (state.newChange === true) {
|
|
1902
|
+
console.error('BLOCKED: TASK.md 同文件跨任务且无依赖路径: ' + crossDetail
|
|
1903
|
+
+ '——replan 不做校验豁免,状态零改写' + crossGuide);
|
|
1904
|
+
process.exit(1);
|
|
1905
|
+
}
|
|
1906
|
+
console.error('WARN: TASK.md 同文件跨任务且无依赖路径(旧 change 渐进不阻断): ' + crossDetail + crossGuide);
|
|
1907
|
+
}
|
|
1908
|
+
if (readWarnings.length > 0) {
|
|
1909
|
+
console.error('WARN: TASK.md 并行任务 read∩write 隐式依赖嫌疑(一方读取对方写路径,建议补显式 depends_on 声明): '
|
|
1910
|
+
+ readWarnings.map((c) => c.a + '×' + c.b + '(' + c.files.join(',') + ')').join('; '));
|
|
1911
|
+
}
|
|
1912
|
+
const round = decision.round;
|
|
1913
|
+
const source = decision.authorization.source;
|
|
1914
|
+
const at = decision.authorization.at;
|
|
1915
|
+
const continuationAuthorized = decision.continuationAuthorized === true;
|
|
1916
|
+
const taskSetSignatureValue = decision.taskSetSignature;
|
|
1917
|
+
if (typeof taskSetSignatureValue !== 'string' || taskSetSignatureValue === '') {
|
|
1918
|
+
console.error('BLOCKED: replan 未能派生当前任务集签名——按 fail-closed 拒绝(状态零改写)。');
|
|
1919
|
+
process.exit(1);
|
|
1920
|
+
}
|
|
1921
|
+
// 备份:重签前 state 全量快照(文件原始字节,UTF-8 BOM 按可解析形态落盘);文件名
|
|
1922
|
+
// <UTC ISO 净化>-pre-replan.json;审计指纹 = 备份文件字节的 sha256(可核验)。
|
|
1923
|
+
const backupDir = path.join(changeDir, 'replan-backups');
|
|
1924
|
+
const backupFile = at.replace(/:/g, '-') + '-pre-replan.json';
|
|
1925
|
+
const backupPath = path.join(backupDir, backupFile);
|
|
1926
|
+
const backupRecord = path.relative(runRoot, backupPath).split(path.sep).join('/');
|
|
1927
|
+
const snapshotBytes = Buffer.from((await fs.readFile(statePath, 'utf8')).replace(/^\uFEFF/, ''), 'utf8');
|
|
1928
|
+
const fingerprint = createHash('sha256').update(snapshotBytes).digest('hex');
|
|
1929
|
+
const existingHistory = Array.isArray(rawState?.history) ? rawState.history : [];
|
|
1930
|
+
let backupWritten = false;
|
|
1931
|
+
try {
|
|
1932
|
+
if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
|
|
1933
|
+
throw new Error('state 文件缺失或形态非法,无法重校重签');
|
|
1934
|
+
}
|
|
1935
|
+
// 备份写入路径的物理包含性复核(单一权威路径段扫描):备份目录与备份文件逐段
|
|
1936
|
+
// lstat + realpath——任何 symlink/junction 逃出 .specs/ 一律拒绝,不写任何字节。
|
|
1937
|
+
await fs.mkdir(backupDir, { recursive: true });
|
|
1938
|
+
await inspectWorkflowPathSegments(specsRoot, backupDir, 'replan backup dir', 'directory');
|
|
1939
|
+
await fs.writeFile(backupPath, snapshotBytes);
|
|
1940
|
+
backupWritten = true;
|
|
1941
|
+
await inspectWorkflowPathSegments(specsRoot, backupPath, 'replan backup file', 'file');
|
|
1942
|
+
// 双写留痕(ADR-013 决策 8):① evidence.<node>.replanAuthorization(节点级授权 + 备份
|
|
1943
|
+
// 指纹);② history 追加 replan-applied(跨 change 审计检索)。落盘形态 = 原始 state
|
|
1944
|
+
// 键集 + 本次实际改动的三处(taskHash / evidence / history),其余字段逐项不变。
|
|
1945
|
+
const existingEvidence = rawState.evidence && typeof rawState.evidence === 'object' && !Array.isArray(rawState.evidence)
|
|
1946
|
+
? rawState.evidence
|
|
1947
|
+
: {};
|
|
1948
|
+
const nodeEvidence = existingEvidence[decision.node]
|
|
1949
|
+
&& typeof existingEvidence[decision.node] === 'object'
|
|
1950
|
+
&& !Array.isArray(existingEvidence[decision.node])
|
|
1951
|
+
? existingEvidence[decision.node]
|
|
1952
|
+
: {};
|
|
1953
|
+
const authorizationRecord = {
|
|
1954
|
+
round,
|
|
1955
|
+
at,
|
|
1956
|
+
source,
|
|
1957
|
+
reason,
|
|
1958
|
+
backup: backupRecord,
|
|
1959
|
+
fingerprint,
|
|
1960
|
+
...(continuationAuthorized ? { continuationAuthorized: true } : {}),
|
|
1961
|
+
};
|
|
1962
|
+
const persisted = { ...rawState };
|
|
1963
|
+
persisted.taskHash = taskSetSignatureValue;
|
|
1964
|
+
persisted.evidence = {
|
|
1965
|
+
...existingEvidence,
|
|
1966
|
+
[decision.node]: { ...nodeEvidence, replanAuthorization: authorizationRecord },
|
|
1967
|
+
};
|
|
1968
|
+
persisted.history = existingHistory.concat([{
|
|
1969
|
+
event: 'replan-applied',
|
|
1970
|
+
change: changeName,
|
|
1971
|
+
node: decision.node,
|
|
1972
|
+
round,
|
|
1973
|
+
reason,
|
|
1974
|
+
authorizedBy: source,
|
|
1975
|
+
taskSetSignature: taskSetSignatureValue,
|
|
1976
|
+
backup: backupRecord,
|
|
1977
|
+
fingerprint,
|
|
1978
|
+
at,
|
|
1979
|
+
...(continuationAuthorized ? { continuationAuthorized: true } : {}),
|
|
1980
|
+
}]);
|
|
1981
|
+
const persistedBad = validateStateFields(persisted);
|
|
1982
|
+
if (persistedBad.length > 0) throw new Error('state 字段类型非法: ' + persistedBad[0]);
|
|
1983
|
+
await writeState(persisted);
|
|
1984
|
+
} catch (error) {
|
|
1985
|
+
// 写盘失败:回滚本次调用创建的孤儿备份(state 由原子写保证不被截断),原始错误照常上抛。
|
|
1986
|
+
if (backupWritten) {
|
|
1987
|
+
try { await fs.rm(backupPath, { force: true }); } catch { /* 清理失败不掩盖原始错误 */ }
|
|
1988
|
+
}
|
|
1989
|
+
throw error;
|
|
1990
|
+
}
|
|
1991
|
+
const roundLabel = continuationAuthorized
|
|
1992
|
+
? '第 ' + round + ' 轮(显式授权续轮,上限 ' + REPLAN_ROUND_LIMIT + ')'
|
|
1993
|
+
: '第 ' + round + '/' + REPLAN_ROUND_LIMIT + ' 轮';
|
|
1994
|
+
console.log('REPLAN: ' + decision.node + ' 重新校验通过(授权源 ' + source + ';' + roundLabel
|
|
1995
|
+
+ ';备份 ' + backupRecord + ')');
|
|
1996
|
+
console.log('REASON: ' + reason);
|
|
1254
1997
|
return;
|
|
1255
1998
|
}
|
|
1256
1999
|
|
|
1257
|
-
throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check');
|
|
2000
|
+
throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check, reenter, replan');
|
|
1258
2001
|
}
|
|
1259
2002
|
|
|
1260
2003
|
main().catch(error => {
|