flow-comet 1.6.2 → 1.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
- package/.flow-comet/skills/flow-comet/SKILL.md +64 -46
- package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +1 -1
- package/.flow-comet/skills/flow-comet/reference/commit-discipline.md +32 -0
- package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +1 -1
- package/.flow-comet/skills/flow-comet/{GUIDANCE.md → reference/entry-detail.md} +18 -28
- package/.flow-comet/skills/flow-comet/reference/fix-loop.md +57 -0
- package/.flow-comet/skills/flow-comet/reference/platform-facts.md +58 -0
- package/.flow-comet/skills/flow-comet/reference/replan.md +23 -0
- package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +5 -4
- package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +266 -25
- package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +2 -2
- package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +6 -6
- package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +67 -16325
- package/.flow-comet/skills/flow-comet/scripts/health.mjs +1 -1
- package/.flow-comet/skills/flow-comet/scripts/items/a.mjs +1030 -0
- package/.flow-comet/skills/flow-comet/scripts/items/b.mjs +830 -0
- package/.flow-comet/skills/flow-comet/scripts/items/c.mjs +781 -0
- package/.flow-comet/skills/flow-comet/scripts/items/d.mjs +99 -0
- package/.flow-comet/skills/flow-comet/scripts/items/e.mjs +185 -0
- package/.flow-comet/skills/flow-comet/scripts/items/f.mjs +90 -0
- package/.flow-comet/skills/flow-comet/scripts/items/g.mjs +59 -0
- package/.flow-comet/skills/flow-comet/scripts/items/h.mjs +815 -0
- package/.flow-comet/skills/flow-comet/scripts/items/i.mjs +77 -0
- package/.flow-comet/skills/flow-comet/scripts/items/j.mjs +75 -0
- package/.flow-comet/skills/flow-comet/scripts/items/k.mjs +1427 -0
- package/.flow-comet/skills/flow-comet/scripts/items/l.mjs +275 -0
- package/.flow-comet/skills/flow-comet/scripts/items/m.mjs +614 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/count-derivation.mjs +97 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/fix-loop-node.mjs +196 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/guard-evidence-gates.mjs +553 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/guard-gates.mjs +837 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/guard-routing.mjs +404 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/guard-state-io.mjs +404 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/guard-template-fidelity.mjs +302 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/guard-uidesign.mjs +133 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/reentry-node.mjs +237 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/replan-node.mjs +209 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-branch.mjs +49 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-bridgecheck.mjs +201 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-admin.mjs +141 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-flow.mjs +700 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-recovery.mjs +578 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-determine.mjs +52 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-evolve-hint.mjs +55 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-explain.mjs +106 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-intelscan.mjs +58 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-io.mjs +147 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/state-skillmarkers.mjs +189 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/system-fixtures.mjs +1441 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/task-graph.mjs +471 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/test-assertions.mjs +509 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/test-fixtures.mjs +1228 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/test-helpers.mjs +237 -0
- package/.flow-comet/skills/flow-comet/scripts/lib/text-anchor-checks.mjs +2484 -0
- package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +2 -2
- package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +73 -1077
- package/.flow-comet/skills/flow-comet/scripts/scenarios/a.mjs +966 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/b.mjs +1233 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/c.mjs +1382 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/d.mjs +483 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/e.mjs +1388 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/f.mjs +1466 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/g.mjs +1364 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/h.mjs +1287 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/i.mjs +1436 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/j.mjs +1384 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/k.mjs +1338 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/l.mjs +1484 -0
- package/.flow-comet/skills/flow-comet/scripts/scenarios/m.mjs +971 -0
- package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +14 -1
- package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +58 -6692
- package/.flow-comet/skills/flow-comet/scripts/time-utils.mjs +4 -4
- package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +151 -2428
- package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +116 -9
- package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +29 -2086
- package/.flow-comet/skills/flow-comet-archive/SKILL.md +10 -19
- package/.flow-comet/skills/flow-comet-change/SKILL.md +2 -3
- package/.flow-comet/skills/flow-comet-compose/SKILL.md +1 -1
- package/.flow-comet/skills/flow-comet-design/SKILL.md +6 -6
- package/.flow-comet/skills/flow-comet-execute/SKILL.md +58 -16
- package/.flow-comet/skills/flow-comet-integration/SKILL.md +8 -5
- package/.flow-comet/skills/flow-comet-open/SKILL.md +5 -1
- package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +1 -1
- package/.flow-comet/skills/flow-comet-plan/SKILL.md +8 -8
- package/.flow-comet/skills/flow-comet-review/SKILL.md +9 -12
- package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +59 -16
- package/.flow-comet/skills/flow-comet-task/SKILL.md +3 -2
- package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +3 -3
- package/.flow-comet/skills/flow-comet-verify/SKILL.md +8 -17
- package/README.md +53 -70
- package/package.json +3 -2
- package/scripts/dsh-bridge.mjs +59 -26
- package/scripts/lib/installer-cleanup.mjs +152 -0
- package/scripts/lib/installer-flowkit.mjs +119 -0
- package/scripts/lib/installer-hooks.mjs +363 -0
- package/scripts/lib/installer-loader.mjs +220 -0
- package/scripts/lib/installer-migrate.mjs +236 -0
- package/scripts/lib/installer-platforms.mjs +314 -0
- package/scripts/prepare-env.mjs +36 -1164
- package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +0 -116
- package/.flow-comet/skills/flow-comet/reference/composition-report.md +0 -65
- package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +0 -184
- package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +0 -661
- package/.flow-comet/skills/flow-comet/reference/skill-review.md +0 -13
- package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +0 -7
- package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +0 -70
|
@@ -1,806 +1,34 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { promises as fs } from 'fs';
|
|
5
|
-
import os from 'os';
|
|
2
|
+
// 状态机 CLI 入口(薄壳契约):只做 CLI 参数解析、命令分派与退出码/输出收口;命令实现与
|
|
3
|
+
// 判定族一律落在 lib/state-*.mjs(单一来源,入口零内联判据)。
|
|
6
4
|
import path from 'path';
|
|
7
5
|
import { fileURLToPath } from 'url';
|
|
8
|
-
import { resolveProtocol, readProtocolFile, validateProtocolSchema
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
6
|
+
import { resolveProtocol, readProtocolFile, validateProtocolSchema } from './protocol-utils.mjs';
|
|
7
|
+
import { initStateContext } from './lib/state-io.mjs';
|
|
8
|
+
import { runAdvance, runInit, runNext, runRecord, runSelect, runStatus } from './lib/state-commands-flow.mjs';
|
|
9
|
+
import { runConfig, runExecutionMode, runSkillLoad, runVerifyFail } from './lib/state-commands-admin.mjs';
|
|
10
|
+
import { runReenter, runReplan } from './lib/state-commands-recovery.mjs';
|
|
11
|
+
import { runBridgeCheck } from './lib/state-bridgecheck.mjs';
|
|
12
|
+
import { runExplain } from './lib/state-explain.mjs';
|
|
14
13
|
|
|
15
14
|
const command = process.argv[2] ?? 'status';
|
|
16
15
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
17
16
|
const packageRoot = path.resolve(__dirname, '..');
|
|
18
17
|
const runRoot = process.cwd();
|
|
18
|
+
// 路径上下文(runRoot / specsRoot / statePath)在分派前初始化一次——状态的读写与 .specs 路径
|
|
19
|
+
// 判定统一由 lib/state-io.mjs 承担
|
|
20
|
+
initStateContext(runRoot);
|
|
19
21
|
// 协议解析: 协议路径统一由 resolveProtocol 解析——优先级:--protocol CLI 参数 → FLOW_COMET_PROTOCOL
|
|
20
22
|
// 环境变量 → 内置默认 reference/workflow-protocol.json。--protocol 为全局参数(可放在 command
|
|
21
23
|
// 之后的任意位置);cliArgs = 去掉 command 后的剩余参数数组。
|
|
22
24
|
const protocolPath = resolveProtocol(packageRoot, runRoot, process.argv.slice(3));
|
|
23
|
-
// 状态文件路径(单一来源:state-schema.mjs 的运行时路径常量)
|
|
24
|
-
const statePath = path.join(runRoot, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME);
|
|
25
|
-
const specsRoot = path.join(runRoot, '.specs');
|
|
26
25
|
|
|
27
26
|
// 内置节点常量: 内置 8 节点常量(供其他用途参照——如 guard 的节点→协议映射对照;skill-load 的 node
|
|
28
27
|
// 参数校验已改为当前协议节点集合动态读取——compose 自定义协议节点可声明)
|
|
29
28
|
const BUILTIN_NODES = ['open', 'design', 'plan', 'execute', 'subagent-execute', 'review', 'verify', 'archive'];
|
|
30
29
|
|
|
31
|
-
// 节点协议映射(单一来源): NODE_PROTOCOL_FILES 来自 protocol-utils.mjs(M5 record 自动补声明标记的 protocol 归属)
|
|
32
|
-
|
|
33
|
-
async function readJson(file) {
|
|
34
|
-
// 容忍 UTF-8 BOM(外部写入如会话 Write 可能带 BOM)
|
|
35
|
-
return JSON.parse((await fs.readFile(file, 'utf8')).replace(/^/, ''));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// JSON 写盘统一走状态层单一来源的原子写(state-schema.mjs 的 writeJsonAtomic → writeFileAtomic):
|
|
39
|
-
// 先写同目录临时文件再 rename 覆盖目标——目标要么旧内容、要么新内容,不会出现被截断的半写状态;
|
|
40
|
-
// 写失败(磁盘满 / 权限 / 目标被占用)清理临时文件后抛出,调用方按 fail-closed 处理。mkdir recursive
|
|
41
|
-
// 由该实现承担(.skill-loads/ 等标记目录不存在时创建);状态下发是单写者形态(机器字段只由脚本通道写)。
|
|
42
|
-
|
|
43
|
-
async function fileExists(file) {
|
|
44
|
-
try { await fs.access(file); return true; } catch { return false; }
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// 契约解析失败判定(单一来源):looksLikeObjectLiteral 由 state-schema.mjs 导出——
|
|
48
|
-
// trim 后以 {/[ 开头 → 视作"形似对象字面量";若 JSON.parse 失败 → fail-closed。
|
|
49
|
-
|
|
50
|
-
// --json-file 路径校验:解析后必须位于项目根内(拒绝相对/绝对形式的越界路径,
|
|
51
|
-
// 如 ../..、其他盘符——防读取任意文件内容进 evidence)。runRoot 内的绝对路径合法
|
|
52
|
-
// (场景内文件常见写法,与 record/handoff 的既有用法一致)。符号链接解析后的实际路径
|
|
53
|
-
// 同样必须在项目根内(词法校验不防 symlink 穿越——realpath 后再次校验)。
|
|
54
|
-
// 非字符串/空值(如 --json-file 为最后一个参数)→ 用法错误,不落 path.resolve
|
|
55
|
-
// (修复前 undefined 抛 TypeError、空串解析为 runRoot 报 EISDIR——报类型错误而非用法错误)
|
|
56
|
-
async function resolveJsonFileWithinRunRoot(jsonFile) {
|
|
57
|
-
if (typeof jsonFile !== 'string' || jsonFile.trim() === '') {
|
|
58
|
-
throw new Error('--json-file requires a path argument');
|
|
59
|
-
}
|
|
60
|
-
const abs = path.resolve(runRoot, jsonFile);
|
|
61
|
-
const rel = path.relative(runRoot, abs);
|
|
62
|
-
if (path.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + path.sep)) {
|
|
63
|
-
throw new Error('--json-file 路径必须在项目根内: ' + jsonFile);
|
|
64
|
-
}
|
|
65
|
-
// 统一对 runRoot 也 realpath——Windows 上 runRoot 可能是 8.3 短路径(如 LONGYI~1),
|
|
66
|
-
// realpath 会展开为长路径,两者直接 relative 会误判越界
|
|
67
|
-
const realRoot = await fs.realpath(runRoot);
|
|
68
|
-
const real = await fs.realpath(abs);
|
|
69
|
-
const realRel = path.relative(realRoot, real);
|
|
70
|
-
if (path.isAbsolute(realRel) || realRel === '..' || realRel.startsWith('..' + path.sep)) {
|
|
71
|
-
throw new Error('--json-file 路径经符号链接解析后越出项目根: ' + jsonFile);
|
|
72
|
-
}
|
|
73
|
-
return abs;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
async function findActiveChange() {
|
|
77
|
-
// 1. Read from state file if exists
|
|
78
|
-
if (await fileExists(statePath)) {
|
|
79
|
-
const state = await readJson(statePath);
|
|
80
|
-
// completed 检查优先于 activeChange 分支——归档完成态(无论 activeChange 是否残留)
|
|
81
|
-
// 一律不识别为 active(防归档残留目录/残留字段误判, 主修复)
|
|
82
|
-
if (state.status === 'completed') return null;
|
|
83
|
-
if (state.activeChange) {
|
|
84
|
-
const changeDir = path.join(specsRoot, state.activeChange);
|
|
85
|
-
if (await fileExists(changeDir)) return state.activeChange;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
// 2. Scan .specs/ for directories with TASK.md (active flow-kit changes)
|
|
89
|
-
// 注: 曾尝试按 archive/ 对应归档跳过残留目录——但会误伤同名新 change(既有实证),已撤回。
|
|
90
|
-
// 「state 缺失 + 归档残留」为已知限制(对比报告已记录"捡残留桩"共性问题);归档后正常态由
|
|
91
|
-
// 上文 completed 分支覆盖( 主修复)
|
|
92
|
-
try {
|
|
93
|
-
const entries = await fs.readdir(specsRoot, { withFileTypes: true });
|
|
94
|
-
const candidates = [];
|
|
95
|
-
for (const entry of entries) {
|
|
96
|
-
if (!entry.isDirectory() || entry.name === 'archive' || entry.name === 'health' || entry.name === 'evolve' || entry.name === 'adr') continue;
|
|
97
|
-
const taskFile = path.join(specsRoot, entry.name, 'TASK.md');
|
|
98
|
-
if (await fileExists(taskFile)) candidates.push(entry.name);
|
|
99
|
-
}
|
|
100
|
-
if (candidates.length === 1) return candidates[0];
|
|
101
|
-
if (candidates.length > 1) {
|
|
102
|
-
// Return the most recently modified
|
|
103
|
-
const withTime = await Promise.all(candidates.map(async c => ({
|
|
104
|
-
name: c,
|
|
105
|
-
mtime: (await fs.stat(path.join(specsRoot, c, 'TASK.md'))).mtimeMs
|
|
106
|
-
})));
|
|
107
|
-
withTime.sort((a, b) => b.mtime - a.mtime);
|
|
108
|
-
return withTime[0].name;
|
|
109
|
-
}
|
|
110
|
-
} catch {}
|
|
111
|
-
return null;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// ---------- skill-load 声明标记(completedChecks 真实性校验配套) ----------
|
|
115
|
-
|
|
116
|
-
// --prompt 原始参数提取(skill-load 专用参数):--protocol 由 resolveProtocol 全局解析
|
|
117
|
-
// (CLI > env > 默认)为工作流协议 JSON——skill-load 曾用 --protocol 传 prompt 路径,主仓真实链路
|
|
118
|
-
// 必现撞车(markdown 被当协议 JSON 解析 → 启动报错「workflow protocol file is not valid JSON」,
|
|
119
|
-
// 已实证)。改名 --prompt 后与全局协议解析彻底解耦;此处仅取用户显式传入的原始值,供 skill-load
|
|
120
|
-
// 的 flow-kit/prompts/ 归属校验与标记记录。
|
|
121
|
-
function findPromptArg(cliArgs) {
|
|
122
|
-
for (let index = 0; index < cliArgs.length; index++) {
|
|
123
|
-
const arg = cliArgs[index];
|
|
124
|
-
if (arg === '--prompt') {
|
|
125
|
-
const value = cliArgs[index + 1];
|
|
126
|
-
if (typeof value !== 'string' || value === '') return null;
|
|
127
|
-
return value;
|
|
128
|
-
}
|
|
129
|
-
if (typeof arg === 'string' && arg.startsWith('--prompt=')) {
|
|
130
|
-
const value = arg.slice('--prompt='.length);
|
|
131
|
-
return value === '' ? null : value;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
return null;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// flow-kit/prompts/ 归属校验(相对或绝对路径,前缀校验)——flow-kit 为 vendored 上游,
|
|
138
|
-
// 协议提示只读引用;skill-load 声明的 --prompt 必须位于其 prompts 目录下。
|
|
139
|
-
// 相对路径:字符串前缀必须为 flow-kit/prompts/;绝对路径:路径段中必须含 flow-kit/prompts。
|
|
140
|
-
function protocolUnderFlowKitPrompts(value) {
|
|
141
|
-
const normalized = String(value).replaceAll('\\', '/');
|
|
142
|
-
if (!path.isAbsolute(value)) {
|
|
143
|
-
return normalized.startsWith('flow-kit/prompts/');
|
|
144
|
-
}
|
|
145
|
-
const segments = normalized.split('/').filter((s) => s !== '');
|
|
146
|
-
for (let index = 0; index <= segments.length - 2; index++) {
|
|
147
|
-
if (segments[index] === 'flow-kit' && segments[index + 1] === 'prompts') return true;
|
|
148
|
-
}
|
|
149
|
-
return false;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// requiredSkillCalls scope 分类——按协议 requiredSkillCalls 查 <node>.<skill> 绑定:
|
|
153
|
-
// main scope = 协调者加载(如 flow-comet-subagent-execute),要求协调者 skill-load 标记;
|
|
154
|
-
// handoff scope = 子代理加载(如 subagent-execute 节点的 flow-comet-dev),协调者不加载它。
|
|
155
|
-
// 协议外条目(无绑定 / 非 main / 非 handoff scope)→ null(fail-closed:仍按 main 处理要标记)。
|
|
156
|
-
function findRequiredSkillBinding(protocol, nodeId, skillName) {
|
|
157
|
-
const node = (protocol.nodes ?? []).find((n) => n.id === nodeId);
|
|
158
|
-
if (!node) return null;
|
|
159
|
-
return (node.requiredSkillCalls ?? []).find((binding) => binding.skill === skillName) ?? null;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// 标记目录解析——活动路径 .specs/<change-id>/.skill-loads/ 优先;归档路径兜底
|
|
163
|
-
// (archive 节点「先移目录后 record/exit」顺序下 change 目录已在 .specs/archive/<前缀>-<change-id>/,
|
|
164
|
-
// 标记只随目录移动——只查活动路径会误报缺失)。归档扫描匹配后缀 -<change-id>(前缀可含日期等,
|
|
165
|
-
// 与协议 flowkit.archive.v1 的 archive/*-<change-id> artifact 路径同构)。两者皆无 → null。
|
|
166
|
-
async function findSkillLoadsDir(changeName) {
|
|
167
|
-
const activeDir = path.join(specsRoot, changeName, '.skill-loads');
|
|
168
|
-
if (await fileExists(activeDir)) {
|
|
169
|
-
return { dir: activeDir, display: '.specs/' + changeName + '/.skill-loads/' };
|
|
170
|
-
}
|
|
171
|
-
const archiveRoot = path.join(specsRoot, 'archive');
|
|
172
|
-
const entries = await fs.readdir(archiveRoot).catch(() => []);
|
|
173
|
-
for (const entry of entries) {
|
|
174
|
-
if (!entry.endsWith('-' + changeName)) continue;
|
|
175
|
-
const candidate = path.join(archiveRoot, entry, '.skill-loads');
|
|
176
|
-
if (await fileExists(candidate)) {
|
|
177
|
-
return { dir: candidate, display: '.specs/archive/' + entry + '/.skill-loads/' };
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
return null;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// completedChecks 真实性校验。解析 completedChecks 的 required-skill:<node>.<skill>
|
|
184
|
-
// 条目 → 对应声明标记 .specs/<change-id>/.skill-loads/<node>-<skill>.json 必须存在(内置节点常量,缺失 →
|
|
185
|
-
// BLOCKED + 指引先加载 skill 并运行 skill-load);标记 at 必须 ≤ 本次记录时间(交叉自洽:
|
|
186
|
-
// 标记先于记录声明;ISO-8601 UTC 字符串字典序 = 时间序)。仅校验本次 record 写入的
|
|
187
|
-
// completedChecks(旧 change 兼容:旧 evidence 不追溯——由调用方只传本次 parsed.completedChecks)。
|
|
188
|
-
// 条目按协议 requiredSkillCalls scope 分类——handoff scope 条目(子代理加载的 skill,
|
|
189
|
-
// 如 subagent-execute 节点的 flow-comet-dev)豁免标记,以共用证据库 evidence['subagent-execute']
|
|
190
|
-
// 的 handoffResult(有委托记录即满足)为证据;main scope / 协议外条目仍要求标记(fail-closed)。
|
|
191
|
-
// 诚实边界:标记是"声明"而非物理证明——运行时没有 Skill 调用观察点,脚本无法确认执行者
|
|
192
|
-
// 真实加载过该 skill;标记仅证明"执行者主动声明已加载",由流程纪律兜底。handoff 条目的证据
|
|
193
|
-
// 同样不是物理证明——它是子代理回传的 Return Contract 委托声明(子代理自称已加载并执行),
|
|
194
|
-
// 由 handoff result 的 commitHash/greenEvidence 审计性兜底。
|
|
195
|
-
// 返回 { ok: true } 或 { ok: false, reason }(fail-closed:无 active change / 标记损坏同样 BLOCK)。
|
|
196
|
-
// 节点技能加载声明标记存在性(技能加载前置门·方案 A):校验 .skill-loads/ 下
|
|
197
|
-
// 是否有该节点的声明标记 <node>-*.json(任一 skill 标记即算已声明——与 guard exit 侧的
|
|
198
|
-
// 「exit 协议声明标记校验」同构:按 <node>- 前缀扫描;活动路径优先,归档路径兜底)。
|
|
199
|
-
// 记录/委托前置门在「先加载技能(Skill 工具)并 skill-load 声明」之前拦截"先干活后补声明"。
|
|
200
|
-
// 诚实边界:标记是执行者自我声明,非物理证明(与 verifySkillLoadMarkers 同语义)。
|
|
201
|
-
async function hasNodeSkillDeclaration(nodeId, changeName) {
|
|
202
|
-
if (!nodeId || !changeName) return false;
|
|
203
|
-
const activeDir = path.join(specsRoot, changeName, '.skill-loads');
|
|
204
|
-
const prefix = nodeId + '-';
|
|
205
|
-
const scan = async (dir) => {
|
|
206
|
-
try {
|
|
207
|
-
const entries = await fs.readdir(dir);
|
|
208
|
-
return entries.some((f) => f.startsWith(prefix) && f.endsWith('.json'));
|
|
209
|
-
} catch {
|
|
210
|
-
return false;
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
if (await scan(activeDir)) return true;
|
|
214
|
-
const archived = await findSkillLoadsDir(changeName);
|
|
215
|
-
if (archived !== null && archived.dir !== activeDir) return scan(archived.dir);
|
|
216
|
-
return false;
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
async function verifySkillLoadMarkers(completedChecks, changeName, recordTime, protocol, state) {
|
|
220
|
-
if (!Array.isArray(completedChecks)) return { ok: true };
|
|
221
|
-
const required = [];
|
|
222
|
-
for (const check of completedChecks) {
|
|
223
|
-
if (typeof check !== 'string' || !check.startsWith('required-skill:')) continue;
|
|
224
|
-
const spec = check.slice('required-skill:'.length);
|
|
225
|
-
const dot = spec.lastIndexOf('.');
|
|
226
|
-
if (dot <= 0 || dot === spec.length - 1) {
|
|
227
|
-
return { ok: false, reason: 'completedChecks 条目格式非法(应为 required-skill:<node>.<skill>): ' + check };
|
|
228
|
-
}
|
|
229
|
-
required.push({ raw: check, node: spec.slice(0, dot), skill: spec.slice(dot + 1) });
|
|
230
|
-
}
|
|
231
|
-
if (required.length === 0) return { ok: true };
|
|
232
|
-
if (!changeName) {
|
|
233
|
-
return { ok: false, reason: 'completedChecks 含 required-skill 条目但无 active change——无法定位声明标记(先运行 init <change-id>)' };
|
|
234
|
-
}
|
|
235
|
-
for (const item of required) {
|
|
236
|
-
// handoff scope 条目豁免标记——子代理加载的 skill(协调者不加载它,无法诚实
|
|
237
|
-
// 声明加载),以共用证据库 handoffResult 的委托记录为证据;无委托记录 → BLOCK(不静默
|
|
238
|
-
// 放行,指引先委托并回传 handoff result)
|
|
239
|
-
const binding = findRequiredSkillBinding(protocol, item.node, item.skill);
|
|
240
|
-
if (binding && binding.scope === 'handoff') {
|
|
241
|
-
const handoff = state?.evidence?.['subagent-execute']?.handoffResult;
|
|
242
|
-
const hasDelegation = !!(
|
|
243
|
-
handoff &&
|
|
244
|
-
typeof handoff === 'object' &&
|
|
245
|
-
!Array.isArray(handoff) &&
|
|
246
|
-
Object.keys(handoff).length > 0
|
|
247
|
-
);
|
|
248
|
-
if (!hasDelegation) {
|
|
249
|
-
return {
|
|
250
|
-
ok: false,
|
|
251
|
-
reason: 'completedChecks 条目 ' + item.raw + ' 为 handoff scope(' + item.node +
|
|
252
|
-
' 节点的 ' + item.skill + ' 由子代理加载,协调者无需 skill-load 标记)但共用证据库' +
|
|
253
|
-
' evidence[subagent-execute].handoffResult 无委托记录——先委托子代理并回传 Return Contract(workflow-handoff.mjs result <task-id> <contract>)',
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
// 标记路径解析——活动路径优先,归档路径兜底(archive 节点「先移目录后 record」
|
|
259
|
-
// 顺序下标记只在 .specs/archive/*-<change-id>/.skill-loads/);两处都找不到 → BLOCK + 指引
|
|
260
|
-
// (不静默放行)。展示路径补 .specs/ 前缀便于用户定位。
|
|
261
|
-
const markerName = item.node + '-' + item.skill + '.json';
|
|
262
|
-
const activeDisplay = '.specs/' + path.posix.join(changeName, '.skill-loads', markerName);
|
|
263
|
-
const activePath = path.join(specsRoot, changeName, '.skill-loads', markerName);
|
|
264
|
-
let markerPath = await fileExists(activePath) ? activePath : null;
|
|
265
|
-
let markerDisplay = activeDisplay;
|
|
266
|
-
if (!markerPath) {
|
|
267
|
-
const loadsDir = await findSkillLoadsDir(changeName);
|
|
268
|
-
if (loadsDir !== null) {
|
|
269
|
-
const altPath = path.join(loadsDir.dir, markerName);
|
|
270
|
-
if (await fileExists(altPath)) {
|
|
271
|
-
markerPath = altPath;
|
|
272
|
-
markerDisplay = loadsDir.display + markerName;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
if (!markerPath) {
|
|
277
|
-
return {
|
|
278
|
-
ok: false,
|
|
279
|
-
reason: 'completedChecks 条目 ' + item.raw + ' 缺少对应声明标记 ' + activeDisplay +
|
|
280
|
-
'(归档路径也未找到)——先加载该 skill 并运行 workflow-state.mjs skill-load ' + item.node + ' ' + item.skill,
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
let marker;
|
|
284
|
-
try {
|
|
285
|
-
marker = await readJson(markerPath);
|
|
286
|
-
} catch {
|
|
287
|
-
return { ok: false, reason: '声明标记损坏(非法 JSON,需重新运行 skill-load): ' + markerDisplay };
|
|
288
|
-
}
|
|
289
|
-
// 交叉自洽——标记 at 必须 ≤ 本次记录时间(标记先于记录声明)
|
|
290
|
-
if (typeof marker.at !== 'string' || marker.at > recordTime) {
|
|
291
|
-
return {
|
|
292
|
-
ok: false,
|
|
293
|
-
reason: '声明标记时间序非法(标记 at=' + JSON.stringify(marker.at) + ' 不早于本次记录时间 ' + recordTime +
|
|
294
|
-
')——标记必须先于记录声明(重新运行 skill-load)',
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
return { ok: true };
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// ---------- 节点完成判定 · determineNode 数据化:完成标志从协议 outputSchemas 推导 ----------
|
|
302
|
-
// (节点完成判定核心抽取 · 依赖感知路由): 节点完成判定核心已迁至共享模块 route-node.mjs——
|
|
303
|
-
// determineNode 保持既有签名与返回语义,仅改为委托 resolveNextNode(行为逐字等价,重构保持锚:
|
|
304
|
-
// 输出与抽取前 200 版一致)。route / buildNodeCompletionFlags / pathPatternExists / nodeFlagsComplete /
|
|
305
|
-
// protocolTaskFilePath / hasSubagentNode 已随抽取移至 route-node.mjs(单一实现,根治 guard 与
|
|
306
|
-
// 状态机双实现漂移的根治(单一实现决策)。
|
|
307
|
-
async function determineNode(changeName, protocol, completedNodes = []) {
|
|
308
|
-
return resolveNextNode({ runRoot, changeName, protocol, completedNodes });
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
// 正常推进豁免判定——exit --apply 会把 currentNode 推进到下一节点(如 open exit 后
|
|
312
|
-
// currentNode=design,该节点尚未开始故 evidence 无记录),随后按 SKILL 协议调 next(正常路径)
|
|
313
|
-
// 不应被 误拦为"疑似未 exit"。判定三条件:① completedNodes 非空;② 最后一个已完成节点
|
|
314
|
-
// 存在 evidence(exit --apply 必须带证据通过——证据存在证明该 exit 真实发生,排除伪造/漂移状态,
|
|
315
|
-
// 如 review 无 evidence);③ currentNode 是下一个合法路由目标——**路由后继优先**(exit --apply
|
|
316
|
-
// 把 currentNode 推进到共享路由判定 resolveNextNode 的结果,平行转换 plan→subagent-execute、
|
|
317
|
-
// 趟间回流 subagent-execute→execute 等即由此产生;next 正常推进豁免识别路由后继,与 guard
|
|
318
|
-
// NEXT 同源),静态直接后继兜底(串行推进原语义,旧态/序列流不回归)。与 回退豁免独立判断
|
|
319
|
-
// (回退 = TASK.md 有 pending 回退修复任务;本豁免 = 正常推进后继)。真乱序(currentNode
|
|
320
|
-
// 既非路由后继也非静态后继)仍维持 严格 BLOCK。
|
|
321
|
-
async function normalAdvanceExempt(state, protocol, completedNodes, currentNode, changeName) {
|
|
322
|
-
if (completedNodes.length === 0) return false;
|
|
323
|
-
const lastNodeId = completedNodes[completedNodes.length - 1];
|
|
324
|
-
const routeIds = route(protocol).map((node) => node.id);
|
|
325
|
-
const lastIdx = routeIds.indexOf(lastNodeId);
|
|
326
|
-
if (lastIdx < 0) return false;
|
|
327
|
-
const lastEvidence = state.evidence && typeof state.evidence === 'object'
|
|
328
|
-
? state.evidence[lastNodeId]
|
|
329
|
-
: null;
|
|
330
|
-
// 审查补充(2026-08-08):evidence 必须是对象且含非空 summary(空对象 {} 可绕过豁免,
|
|
331
|
-
// 真实流程 exit 强制 summary——此处严格化防止手动修改 state 绕过)
|
|
332
|
-
const hasExitEvidence = !!(
|
|
333
|
-
lastEvidence &&
|
|
334
|
-
typeof lastEvidence === 'object' &&
|
|
335
|
-
!Array.isArray(lastEvidence) &&
|
|
336
|
-
typeof lastEvidence.summary === 'string' &&
|
|
337
|
-
lastEvidence.summary.trim() !== ''
|
|
338
|
-
);
|
|
339
|
-
if (!hasExitEvidence) return false;
|
|
340
|
-
// 路由后继判定(与 guard 出口同源):currentNode === resolveNextNode(completedNodes) 即
|
|
341
|
-
// 正常推进后的下一路由目标(含平行转换与趟间回流);文件推导失败(异常态)不豁免。
|
|
342
|
-
try {
|
|
343
|
-
const routingNext = await determineNode(changeName, protocol, completedNodes);
|
|
344
|
-
if (routingNext === currentNode) return true;
|
|
345
|
-
} catch {
|
|
346
|
-
return false;
|
|
347
|
-
}
|
|
348
|
-
// 静态直接后继兜底(串行推进原语义,向后兼容旧态不回归)
|
|
349
|
-
return lastIdx + 1 < routeIds.length && routeIds[lastIdx + 1] === currentNode;
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
async function readState() {
|
|
353
|
-
if (await fileExists(statePath)) {
|
|
354
|
-
const st = await readJson(statePath);
|
|
355
|
-
// 兼容旧 state:无 executionMode / directOverride 时补默认(subagent 默认,direct 是显式逃生口)
|
|
356
|
-
if (st.executionMode === undefined) st.executionMode = 'subagent';
|
|
357
|
-
if (st.directOverride === undefined) st.directOverride = false;
|
|
358
|
-
// E1: branchMode 默认 true(git 仓库时 init 会判定为 true;非 git 仓库 init 纠正为 false;
|
|
359
|
-
// status/next 显示以实时 git 检测为准——非 git 仓库显示 BRANCH: none)
|
|
360
|
-
if (st.branchMode === undefined) st.branchMode = true;
|
|
361
|
-
if (st.enablePrReview === undefined) st.enablePrReview = false;
|
|
362
|
-
// 分支前缀(init --branch-prefix 记录;旧 state 缺省 'change/' 向后兼容)
|
|
363
|
-
if (st.branchPrefix === undefined) st.branchPrefix = 'change/';
|
|
364
|
-
return st;
|
|
365
|
-
}
|
|
366
|
-
return { activeChange: null, currentNode: null, completedNodes: [], evidence: {}, verifyFailures: 0, executionMode: 'subagent', directOverride: false, branchMode: true, enablePrReview: false };
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// ---------- E1 · 分支模式辅助(git 仓库检测 + 分支名) ----------
|
|
370
|
-
|
|
371
|
-
// git 仓库检测:`git rev-parse --is-inside-work-tree` 成功且输出 true
|
|
372
|
-
function isInsideWorkTree() {
|
|
373
|
-
try {
|
|
374
|
-
const out = execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' });
|
|
375
|
-
return String(out).trim() === 'true';
|
|
376
|
-
} catch {
|
|
377
|
-
return false;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// 当前分支名;非 git 仓库 / detached HEAD 失败 → null
|
|
382
|
-
function gitBranchName() {
|
|
383
|
-
try {
|
|
384
|
-
const out = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' });
|
|
385
|
-
return String(out).trim() || null;
|
|
386
|
-
} catch {
|
|
387
|
-
return null;
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// 分支是否存在(本地分支)
|
|
392
|
-
function branchExists(name) {
|
|
393
|
-
try {
|
|
394
|
-
const out = execFileSync('git', ['branch', '--format', '%(refname:short)'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' });
|
|
395
|
-
return String(out).split('\n').map(s => s.trim()).includes(name);
|
|
396
|
-
} catch {
|
|
397
|
-
return false;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
// E1: status/next 追加分支信息——BRANCH: <当前分支> | 一致性: ok|mismatch
|
|
402
|
-
// mismatch(activeChange 存在但当前分支不是 change/<activeChange>)→ WARN 不 BLOCK;非 git 仓库 → BRANCH: none
|
|
403
|
-
function printBranchLine(activeChange, branchPrefix = 'change/') {
|
|
404
|
-
const branch = gitBranchName();
|
|
405
|
-
if (branch === null) {
|
|
406
|
-
console.log('BRANCH: none');
|
|
407
|
-
return;
|
|
408
|
-
}
|
|
409
|
-
const expected = branchPrefix + activeChange;
|
|
410
|
-
const consistent = branch === expected;
|
|
411
|
-
console.log('BRANCH: ' + branch + ' | 一致性: ' + (consistent ? 'ok' : 'mismatch'));
|
|
412
|
-
if (!consistent) {
|
|
413
|
-
console.error('WARN: 分支与 activeChange 不一致——先 git checkout ' + expected + ' 再继续');
|
|
414
|
-
}
|
|
415
|
-
}
|
|
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
|
-
|
|
469
|
-
// C6: writeState 写入前校验已知字段类型(fail-closed:非法 → BLOCKED 拒绝写入,不修复不猜测)
|
|
470
|
-
// 未知字段允许(前向兼容);缺字段允许(readState 默认补);只校验存在字段的类型。
|
|
471
|
-
// 内置节点常量: 校验表已迁移到 state-schema.mjs(唯一来源),行为与迁移前的内联表完全一致(对第一个非法字段输出后退出)
|
|
472
|
-
async function writeState(state) {
|
|
473
|
-
const bad = validateStateFields(state);
|
|
474
|
-
if (bad.length) {
|
|
475
|
-
console.error('BLOCKED: state 字段类型非法: ' + bad[0]);
|
|
476
|
-
process.exit(1);
|
|
477
|
-
}
|
|
478
|
-
await writeJsonAtomic(statePath, state);
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
// .specs/ 下必须存在名字「逐字相等」的目录条目(change 名唯一性判据)。大小写不敏感文件系统
|
|
482
|
-
// (Windows / 默认 macOS)会把「CH」解析到 .specs/ch、「Archive」解析到归档区,但 activeChange
|
|
483
|
-
// 存的是变体字符串——轮次事件按 activeChange 精确匹配(配额被换键重置)、保留名检查按小写归一,
|
|
484
|
-
// 故 change 名必须等于真实目录名,大小写/空白变体一律拒绝(fail-closed)。
|
|
485
|
-
async function hasExactSpecsEntry(changeName) {
|
|
486
|
-
let entries = [];
|
|
487
|
-
try {
|
|
488
|
-
entries = await fs.readdir(specsRoot);
|
|
489
|
-
} catch {
|
|
490
|
-
return false;
|
|
491
|
-
}
|
|
492
|
-
return entries.includes(changeName);
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
// 受控重入路径边界(单一 helper:change 名形态 + realpath 直接子目录 + symlink/junction 逃逸)。
|
|
496
|
-
// change 名必须是单段目录名(形态单一权威在 route-node.mjs,与综合判定同源);目录必须真实存在、
|
|
497
|
-
// 非 symlink/junction、realpath 归一后仍在 .specs/ 内、且名字与真实目录条目逐字相等。物理包含性
|
|
498
|
-
// 判定复用 protocol-utils 的路径段扫描(单一权威,不写第二份路径判据);任何越界 / 链接形态 /
|
|
499
|
-
// 名字变体一律 BLOCK(fail-closed)。
|
|
500
|
-
async function inspectReentryChangeDir(changeName) {
|
|
501
|
-
if (typeof changeName !== 'string' || changeName.trim() === '') {
|
|
502
|
-
return { ok: false, reason: 'no-active-change' };
|
|
503
|
-
}
|
|
504
|
-
if (!isSingleSegmentChangeName(changeName)) {
|
|
505
|
-
return { ok: false, reason: 'change-name-invalid' };
|
|
506
|
-
}
|
|
507
|
-
const changeDir = path.join(specsRoot, changeName);
|
|
508
|
-
let inspection;
|
|
509
|
-
try {
|
|
510
|
-
inspection = await inspectWorkflowPathSegments(specsRoot, changeDir, 'reenter change dir', 'directory');
|
|
511
|
-
} catch (error) {
|
|
512
|
-
return { ok: false, reason: 'change-dir-escape', detail: error && error.message ? error.message : String(error) };
|
|
513
|
-
}
|
|
514
|
-
if (!inspection.exists) return { ok: false, reason: 'change-dir-missing' };
|
|
515
|
-
if (!(await hasExactSpecsEntry(changeName))) return { ok: false, reason: 'change-name-invalid' };
|
|
516
|
-
return { ok: true, changeDir };
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
function generatedNodeSkillName(protocol, nodeId) {
|
|
520
|
-
return protocol.name + '-' + nodeId;
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
function printNext(protocol, nodeId, executionMode = 'subagent') {
|
|
524
|
-
if (!nodeId) {
|
|
525
|
-
console.log('NEXT: done');
|
|
526
|
-
return;
|
|
527
|
-
}
|
|
528
|
-
console.log('NEXT: auto');
|
|
529
|
-
console.log('NODE: ' + nodeId);
|
|
530
|
-
console.log('SKILL: ' + generatedNodeSkillName(protocol, nodeId));
|
|
531
|
-
// 输出点名(机器点名下一节点技能):下一节点实现技能必须经 Skill 工具加载——
|
|
532
|
-
// skill 名取节点实现 skill(与 SKILL: 行一致;内置协议 = flow-comet-open 等)
|
|
533
|
-
const implNode = (protocol.nodes ?? []).find((n) => n.id === nodeId);
|
|
534
|
-
const implSkill = implNode && typeof implNode.implementation === 'object' && implNode.implementation !== null
|
|
535
|
-
? implNode.implementation.skill
|
|
536
|
-
: null;
|
|
537
|
-
if (implSkill) {
|
|
538
|
-
console.log('LOAD SKILL: ' + implSkill + '(用 Skill 工具,禁止跳过)');
|
|
539
|
-
}
|
|
540
|
-
if (EXECUTE_FAMILY_NODE_IDS.has(nodeId)) {
|
|
541
|
-
if (executionMode === 'direct' && nodeId === 'execute') {
|
|
542
|
-
console.log('EXECUTION-MODE: direct(主代理直接执行串行任务,必须加载 flow-comet-dev 完整协议;parallel 任务仍由 subagent-execute 委托)');
|
|
543
|
-
} else {
|
|
544
|
-
console.log('COORDINATOR: 你是协调者,不是执行者。禁止在主会话直接修改源码;只能通过 Agent 工具 worktree isolation 委托子代理;子代理回传后仅更新 TASK.md / SUMMARY / handoff evidence。');
|
|
545
|
-
console.log('EXECUTION-MODE: ' + (executionMode === 'direct' ? 'direct' : 'subagent'));
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
// ---------- bridge-check(只读 dsh 桥接健康检查 · 六判定态) ----------
|
|
551
|
-
|
|
552
|
-
// 版本戳锚点正则(契约定稿见 T02-SUMMARY「版本戳标记行格式契约」/ DESIGN §9.3):
|
|
553
|
-
// 独立整行、行首无缩进、冒号后恰一个空格、行尾无其它字符。格式禁动(§9.5)。
|
|
554
|
-
const BRIDGE_VERSION_RE = /^\/\/ BRIDGE_VERSION: ([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)$/m;
|
|
555
|
-
|
|
556
|
-
// dev 态后缀归一(bridge-check 版本比较):git describe 开发态形态为
|
|
557
|
-
// `<发布版本>-<领先提交数>-g<hash>`(例:`1.5.1-11-g93d96c0`,hash 十六进制、大小写不敏感)。
|
|
558
|
-
// 两侧仅在比较前剥这一种后缀、按基础版本比较——开发态载体与同基础版本的发布 loader 判健康;
|
|
559
|
-
// 语义化预发布标识(如 `1.5.0-rc.3`)不是 dev 态后缀、不得剥离(否则会把预发布放行成基础版本)。
|
|
560
|
-
// 归一仅用于比较,不改变读取到的原始值(失配报告需同时打印原始值与归一值)。
|
|
561
|
-
const BRIDGE_DEV_SUFFIX_RE = /-\d+-g[0-9a-f]+$/i;
|
|
562
|
-
function normalizeBridgeBaseVersion(version) {
|
|
563
|
-
return String(version).replace(BRIDGE_DEV_SUFFIX_RE, '');
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// $DSH_HOME 解析——与 prepare-env.mjs resolveDshHome 同语义(显式 DSH_HOME > ~/.dsh)。
|
|
567
|
-
// 安装器函数位于仓库根 scripts/,技能包脚本不能跨模块 import,语义复刻保持单点契约
|
|
568
|
-
// (套件断言保证双侧不漂移)。
|
|
569
|
-
function resolveDshHomeForBridgeCheck() {
|
|
570
|
-
if (process.env.DSH_HOME) return path.resolve(process.env.DSH_HOME);
|
|
571
|
-
return path.join(os.homedir(), '.dsh');
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
// cordis.patch.yml 托管块标记——与 prepare-env.mjs MANAGED_CORDIS_START/END 同值复刻
|
|
575
|
-
// (技能包自包含;标记为安装器读-合并-写幂等替换边界,格式禁动)。
|
|
576
|
-
const MANAGED_CORDIS_START = '# --- flow-comet managed ---';
|
|
577
|
-
const MANAGED_CORDIS_END = '# --- end flow-comet managed ---';
|
|
578
|
-
|
|
579
|
-
// 判定态:健康 / 不适用 / 文件缺失 / 未挂载 / 版本偏斜 / 重复注册。
|
|
580
|
-
// 严格只读零写入零网络;失配(FAIL)exit 非 0;无法识别形态 → 近似性声明告警(WARN)
|
|
581
|
-
// 不定论不误杀(行扫描对无法识别形态的手写极端 YAML 只告警不定论,不误判为失配;
|
|
582
|
-
// 仅明确失配才强制非零退出)。
|
|
583
|
-
async function runBridgeCheck() {
|
|
584
|
-
const report = { pass: [], warn: [], fail: [] };
|
|
585
|
-
// ⑥ 非 dsh 项目 →「不适用」exit 0(AC-11):会话项目根无 .dsh/skills/flow-comet
|
|
586
|
-
// (未安装 dsh 平台副本)即不适用,其余检查全部跳过。
|
|
587
|
-
if (!(await fileExists(path.join(runRoot, '.dsh', 'skills', 'flow-comet')))) {
|
|
588
|
-
console.log('[NA] bridge-check: 不适用(本项目未安装 dsh 平台副本)——项目根无 .dsh/skills/flow-comet');
|
|
589
|
-
console.log('bridge-check: 不适用(exit 0)');
|
|
590
|
-
return;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
const dshHome = resolveDshHomeForBridgeCheck();
|
|
594
|
-
const loaderPath = path.join(dshHome, 'plugins', 'dsh-flow-comet-bridge.mjs');
|
|
595
|
-
const patchPath = path.join(dshHome, 'cordis.patch.yml');
|
|
596
|
-
const installedVersionPath = path.join(__dirname, '..', 'INSTALLED_VERSION');
|
|
597
|
-
|
|
598
|
-
// ① loader 文件存在性($DSH_HOME/plugins/dsh-flow-comet-bridge.mjs)
|
|
599
|
-
const loaderExists = await fileExists(loaderPath);
|
|
600
|
-
if (loaderExists) {
|
|
601
|
-
report.pass.push('loader 文件存在: ' + loaderPath);
|
|
602
|
-
} else {
|
|
603
|
-
report.fail.push('loader 文件缺失: ' + loaderPath);
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
// ② cordis.patch.yml 托管块存在性与 insert 形态(含 - insert: 与 name: 'file://…';
|
|
607
|
-
// L-048:id-targeted patch 形态无 insert → 确认为错误形态失配)
|
|
608
|
-
// + ③ 块内 file:// 目标可达
|
|
609
|
-
let patchContent = null;
|
|
610
|
-
try {
|
|
611
|
-
patchContent = await fs.readFile(patchPath, 'utf8');
|
|
612
|
-
} catch {
|
|
613
|
-
patchContent = null;
|
|
614
|
-
}
|
|
615
|
-
if (patchContent === null) {
|
|
616
|
-
report.fail.push(
|
|
617
|
-
'未挂载: ' + patchPath + ' 不存在——' +
|
|
618
|
-
(loaderExists ? 'loader 存在但未挂载(不会监听任何项目)' : '托管块无从指向 loader')
|
|
619
|
-
);
|
|
620
|
-
} else {
|
|
621
|
-
const startIdx = patchContent.indexOf(MANAGED_CORDIS_START);
|
|
622
|
-
const endIdx = patchContent.indexOf(MANAGED_CORDIS_END);
|
|
623
|
-
if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {
|
|
624
|
-
report.fail.push(
|
|
625
|
-
'未挂载: ' + patchPath + ' 中不存在托管块(' + MANAGED_CORDIS_START + ' … ' + MANAGED_CORDIS_END +
|
|
626
|
-
')——' + (loaderExists ? 'loader 存在但未挂载(不会监听任何项目)' : '')
|
|
627
|
-
);
|
|
628
|
-
} else {
|
|
629
|
-
// 块内容 = 起始标记行尾之后、结束标记之前
|
|
630
|
-
let blockStart = patchContent.indexOf('\n', startIdx);
|
|
631
|
-
blockStart = blockStart === -1 ? endIdx : blockStart + 1;
|
|
632
|
-
const block = patchContent.slice(blockStart, endIdx);
|
|
633
|
-
const hasInsert = /^\s*- insert:\s*$/m.test(block);
|
|
634
|
-
const fileUrlMatch = /name:\s*'file:\/\/([^']+)'/.exec(block);
|
|
635
|
-
const hasIdLine = /^\s*- id:\s*dsh-flow-comet-bridge\s*$/m.test(block);
|
|
636
|
-
|
|
637
|
-
if (hasInsert && fileUrlMatch) {
|
|
638
|
-
report.pass.push('cordis.patch.yml 托管块: 存在且 insert 形态(含 - insert: 与 name: \'file://…\')');
|
|
639
|
-
// ③ file:// 目标可达性(捕获组含 file:// 后的整段——'file://' + 捕获即完整 URL;
|
|
640
|
-
// fileURLToPath 按平台归一 Windows 盘符与 POSIX 根路径)
|
|
641
|
-
let targetPath = null;
|
|
642
|
-
try {
|
|
643
|
-
targetPath = fileURLToPath('file://' + fileUrlMatch[1]);
|
|
644
|
-
} catch (error) {
|
|
645
|
-
targetPath = null;
|
|
646
|
-
}
|
|
647
|
-
if (targetPath === null) {
|
|
648
|
-
report.warn.push('近似性声明: 托管块 file:// 引用无法解析为本地路径(' + fileUrlMatch[0] + ')——无法核验目标可达性,不定论');
|
|
649
|
-
} else if (await fileExists(targetPath)) {
|
|
650
|
-
if (targetPath === loaderPath) {
|
|
651
|
-
report.pass.push('块内 file:// 目标可达且与期望 loader 路径一致: ' + targetPath);
|
|
652
|
-
} else {
|
|
653
|
-
report.fail.push('托管块 file:// 目标与期望 loader 路径不符: ' + targetPath + ' ≠ ' + loaderPath);
|
|
654
|
-
}
|
|
655
|
-
} else {
|
|
656
|
-
report.fail.push('托管块指向的 loader 文件缺失: ' + targetPath + '(file:// 目标不可达)');
|
|
657
|
-
}
|
|
658
|
-
} else if (hasInsert && !fileUrlMatch) {
|
|
659
|
-
// insert 形态在但无 name: 'file://…' 行——部分可识别、目标不可核验:
|
|
660
|
-
// 近似性声明告警,不定论不误杀(不 forced 非零)
|
|
661
|
-
report.warn.push('近似性声明: 托管块为 insert 形态但未识别到 name: \'file://…\' 行——无法核验 file:// 目标是否可达,不定论');
|
|
662
|
-
} else if (hasIdLine && !hasInsert) {
|
|
663
|
-
// L-048 确认形态:id-targeted patch(- id: ... 无 - insert:)——
|
|
664
|
-
// dsh applyEntryPatches 对不存在的 id 报 entry not found 并跳过,loader 不会加载
|
|
665
|
-
report.fail.push('托管块为 id-targeted patch 形态(含 - id: dsh-flow-comet-bridge 但无 - insert:)——确认为错误形态失配(dsh 不会加载该 loader)');
|
|
666
|
-
} else {
|
|
667
|
-
report.warn.push('近似性声明: 托管块内容无法识别为已知形态(未见 - insert: / - id: dsh-flow-comet-bridge / name: \'file://…\')——不判失配,不定论');
|
|
668
|
-
}
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
// ④ 托管块外同 id 重复注册(AC-10b;块内安装器写入的固有条目不计)
|
|
673
|
-
let outside = '';
|
|
674
|
-
if (patchContent !== null) {
|
|
675
|
-
if (patchContent.includes(MANAGED_CORDIS_START) && patchContent.includes(MANAGED_CORDIS_END)) {
|
|
676
|
-
const sIdx = patchContent.indexOf(MANAGED_CORDIS_START);
|
|
677
|
-
const eIdx = patchContent.indexOf(MANAGED_CORDIS_END);
|
|
678
|
-
outside = patchContent.slice(0, sIdx) + patchContent.slice(eIdx + MANAGED_CORDIS_END.length);
|
|
679
|
-
} else {
|
|
680
|
-
outside = patchContent; // 无托管块:全文件视为块外
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
const dupMatches = outside.match(/^\s*-\s+id:\s*['"]?dsh-flow-comet-bridge['"]?\s*$/gm) ?? [];
|
|
684
|
-
if (dupMatches.length > 0) {
|
|
685
|
-
report.fail.push('重复注册: cordis.patch.yml 托管块外另有 ' + dupMatches.length + ' 处同 id 注册行(dsh-flow-comet-bridge)——可能重复加载');
|
|
686
|
-
} else {
|
|
687
|
-
report.pass.push('重复注册检查: 托管块外无同 id(dsh-flow-comet-bridge)注册行');
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
// ⑤ loader BRIDGE_VERSION 戳 vs 项目 INSTALLED_VERSION 基础版本比较(两原始值都打印;
|
|
691
|
-
// 比较前剥离 dev 态后缀——见 normalizeBridgeBaseVersion;
|
|
692
|
-
// 契约锚点正则见 T02-SUMMARY「版本戳标记行格式契约」)
|
|
693
|
-
let loaderStamp = null;
|
|
694
|
-
let installedVersion = null;
|
|
695
|
-
if (loaderExists) {
|
|
696
|
-
try {
|
|
697
|
-
const loaderText = await fs.readFile(loaderPath, 'utf8');
|
|
698
|
-
const stampMatch = BRIDGE_VERSION_RE.exec(loaderText);
|
|
699
|
-
if (stampMatch) {
|
|
700
|
-
loaderStamp = stampMatch[1];
|
|
701
|
-
} else {
|
|
702
|
-
report.warn.push('近似性声明: loader 未提取到 BRIDGE_VERSION 戳(锚点正则 /^\\/\\/ BRIDGE_VERSION: ([0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)$/m 无命中——非语义化版本标记或缺失)——无法比对版本,不定论');
|
|
703
|
-
}
|
|
704
|
-
} catch {
|
|
705
|
-
report.warn.push('近似性声明: loader 文件读取失败——无法比对版本,不定论');
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
try {
|
|
709
|
-
installedVersion = (await fs.readFile(installedVersionPath, 'utf8')).trim();
|
|
710
|
-
} catch {
|
|
711
|
-
report.warn.push('近似性声明: 无法读取项目 INSTALLED_VERSION(' + installedVersionPath + ')——无法比对版本,不定论');
|
|
712
|
-
}
|
|
713
|
-
if (loaderStamp !== null && installedVersion !== null) {
|
|
714
|
-
// 比较前两侧按基础版本归一(剥离 git describe dev 态后缀;预发布标识不剥)。
|
|
715
|
-
// 原始值逐字相同 → 既有发布态严格一致报告保持不变;
|
|
716
|
-
// 原始值不同但归一基础版本一致 → dev 态同基础,判健康(同时打印两原始值与基础版本);
|
|
717
|
-
// 归一后仍不同 → 版本偏斜:保留原「loader 原始戳 != 项目原始戳」配对(兼容既有报告读取),
|
|
718
|
-
// 再补打印两侧归一基础版本,便于操作者识别 dev 态后缀。
|
|
719
|
-
const loaderBase = normalizeBridgeBaseVersion(loaderStamp);
|
|
720
|
-
const installedBase = normalizeBridgeBaseVersion(installedVersion);
|
|
721
|
-
if (loaderBase === installedBase) {
|
|
722
|
-
if (loaderStamp === installedVersion) {
|
|
723
|
-
report.pass.push('版本一致性: loader BRIDGE_VERSION=' + loaderStamp + ' == 项目 INSTALLED_VERSION=' + installedVersion);
|
|
724
|
-
} else {
|
|
725
|
-
report.pass.push('版本一致性: loader BRIDGE_VERSION=' + loaderStamp + ' ~= 项目 INSTALLED_VERSION=' + installedVersion + '(dev 态后缀归一后基础版本 ' + loaderBase + ' 一致)');
|
|
726
|
-
}
|
|
727
|
-
} else {
|
|
728
|
-
report.fail.push('版本偏斜: loader BRIDGE_VERSION=' + loaderStamp + ' != 项目 INSTALLED_VERSION=' + installedVersion + '(归一基础版本: loader=' + loaderBase + ' / installed=' + installedBase + ')——两值如上');
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
// 逐项人读报告(AC-7~10:全过 exit 0 / 任一失配 exit 非 0)
|
|
733
|
-
console.log('bridge-check: 只读检查(DSH_HOME=' + dshHome + ' · 项目根=' + runRoot + ')');
|
|
734
|
-
for (const line of report.pass) console.log('[OK] ' + line);
|
|
735
|
-
for (const line of report.warn) console.log('[WARN] ' + line);
|
|
736
|
-
for (const line of report.fail) console.log('[FAIL] ' + line);
|
|
737
|
-
if (report.fail.length > 0) {
|
|
738
|
-
console.log('bridge-check: 失配 ' + report.fail.length + ' 项——exit 1');
|
|
739
|
-
process.exitCode = 1;
|
|
740
|
-
} else if (report.warn.length > 0) {
|
|
741
|
-
console.log('bridge-check: 未发现明确失配,含 ' + report.warn.length + ' 项近似性声明告警(不定论,不误杀)——exit 0');
|
|
742
|
-
} else {
|
|
743
|
-
console.log('bridge-check: 健康(全部检查通过)——exit 0');
|
|
744
|
-
}
|
|
745
|
-
}
|
|
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
|
-
|
|
802
30
|
async function main() {
|
|
803
|
-
//
|
|
31
|
+
// 协议加载 = resolveProtocol 解析路径 + 受保护读取 + fail-closed schema 校验
|
|
804
32
|
// (读失败/校验失败直接 throw,沿用现有错误处理风格)
|
|
805
33
|
const protocol = await readProtocolFile(runRoot, protocolPath);
|
|
806
34
|
validateProtocolSchema(protocol);
|
|
@@ -808,1322 +36,37 @@ async function main() {
|
|
|
808
36
|
if (command === 'bridge-check') {
|
|
809
37
|
// 只读 dsh 桥接健康检查:零写入零网络;
|
|
810
38
|
// 不依赖协议/状态,直接执行后返回。
|
|
811
|
-
await runBridgeCheck();
|
|
39
|
+
await runBridgeCheck({ runRoot, packageRoot });
|
|
812
40
|
return;
|
|
813
41
|
}
|
|
814
42
|
|
|
815
|
-
if (command === 'init') {
|
|
816
|
-
const changeName = process.argv[3];
|
|
817
|
-
if (!changeName) throw new Error('init requires a change name.');
|
|
818
|
-
// trim 后校验:带前导/尾随空白的输入(如 " --help")不得绕过 flag 检测;
|
|
819
|
-
// 纯空白与缺参同义
|
|
820
|
-
const normalizedChangeName = changeName.trim();
|
|
821
|
-
if (!normalizedChangeName) throw new Error('init requires a change name.');
|
|
822
|
-
// 参数误用防护:以 -- 开头的参数(如 --help)是选项不是 change 名——报错并提示用法,
|
|
823
|
-
// 防止被当作 change id 执行(自动开 change、建分支、写状态——有破坏性)
|
|
824
|
-
if (normalizedChangeName.startsWith('--')) {
|
|
825
|
-
throw new Error('init: ' + normalizedChangeName + ' looks like a flag, not a change name. Usage: workflow-state.mjs init <change-id> [--branch-prefix <prefix>] [--init-context|--init-skip]');
|
|
826
|
-
}
|
|
827
|
-
// --branch-prefix <prefix>(缺省 'change/');--init-context / --init-skip(自动初始化检测授权)
|
|
828
|
-
let branchPrefix = 'change/';
|
|
829
|
-
let initContext = false;
|
|
830
|
-
let initSkip = false;
|
|
831
|
-
const initArgs = process.argv.slice(4);
|
|
832
|
-
for (let i = 0; i < initArgs.length; i++) {
|
|
833
|
-
if (initArgs[i] === '--branch-prefix') {
|
|
834
|
-
const value = initArgs[i + 1];
|
|
835
|
-
if (typeof value !== 'string' || value.trim() === '') {
|
|
836
|
-
throw new Error('--branch-prefix requires a non-empty prefix (e.g. feat/)');
|
|
837
|
-
}
|
|
838
|
-
branchPrefix = value.trim().endsWith('/') ? value.trim() : value.trim() + '/';
|
|
839
|
-
} else if (typeof initArgs[i] === 'string' && initArgs[i].startsWith('--branch-prefix=')) {
|
|
840
|
-
const value = initArgs[i].slice('--branch-prefix='.length);
|
|
841
|
-
if (value === '') {
|
|
842
|
-
throw new Error('--branch-prefix requires a non-empty prefix (e.g. feat/)');
|
|
843
|
-
}
|
|
844
|
-
branchPrefix = value.endsWith('/') ? value : value + '/';
|
|
845
|
-
} else if (initArgs[i] === '--init-context') {
|
|
846
|
-
initContext = true;
|
|
847
|
-
} else if (initArgs[i] === '--init-skip') {
|
|
848
|
-
initSkip = true;
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
// 自动初始化检测(前置步骤):读旧 state(项目级字段跨 change 保留)→ 探测 → 判决 → 提示/执行
|
|
852
|
-
// 生成职责:--init-context 时 CONTEXT 缺失 → 输出 INIT-GENERATE 指引,由 agent 全量阅读生成
|
|
853
|
-
// (intel-scan 语义);生成后重跑 → 脚本校验 7 段结构 → 通过写 last_intel_scan(确定性校验)。
|
|
854
|
-
let prevState = null;
|
|
855
|
-
try { prevState = await readState(); } catch { prevState = null; }
|
|
856
|
-
const probe = await probeProject(runRoot, prevState);
|
|
857
|
-
const verdict = classify(probe, prevState);
|
|
858
|
-
let ctxValid = null; // null=未进入校验(非 init-context 或已新鲜);true/false=校验结果
|
|
859
|
-
if (initContext || initSkip) {
|
|
860
|
-
// 显式授权路径:--init-context 生成协作(agent 生成 + 脚本校验);--init-skip 记 none
|
|
861
|
-
if (initContext) {
|
|
862
|
-
// 显式 --init-context 总是校验结构(含 verdict=skip 新鲜/记忆场景)——防 CONTEXT 损坏漏检
|
|
863
|
-
let ctxExists = false;
|
|
864
|
-
try { await fs.access(path.join(runRoot, '.specs', 'CONTEXT.md')); ctxExists = true; } catch { /* 文件不存在 */ }
|
|
865
|
-
if (ctxExists) {
|
|
866
|
-
const { missingSections, formatIssues } = await validateContext(runRoot);
|
|
867
|
-
if (missingSections.length === 0 && formatIssues.length === 0) {
|
|
868
|
-
ctxValid = true;
|
|
869
|
-
if (verdict === 'skip') {
|
|
870
|
-
console.log('INIT-DONE: 项目上下文已存在且新鲜,跳过生成。');
|
|
871
|
-
} else {
|
|
872
|
-
console.log('INIT-DONE: 项目上下文(CONTEXT.md)已就绪(7 段 + 模板格式校验通过)。');
|
|
873
|
-
}
|
|
874
|
-
} else {
|
|
875
|
-
// 存在但不满足模板(缺段/格式不符/损坏)——引导 agent 重写(保留既有累积内容)
|
|
876
|
-
const problems = [...formatIssues, ...missingSections.map((s) => '缺段 ' + s)];
|
|
877
|
-
await printGenerationGuide(runRoot, probe, { rewrite: true, problems });
|
|
878
|
-
}
|
|
879
|
-
} else if (verdict !== 'skip') {
|
|
880
|
-
await printGenerationGuide(runRoot, probe);
|
|
881
|
-
}
|
|
882
|
-
// verdict=skip(记忆 A 拒绝 / 新鲜 B)且 CONTEXT 缺失 → 尊重既有决策,不输出
|
|
883
|
-
}
|
|
884
|
-
if (initSkip && !initContext) {
|
|
885
|
-
console.log('INIT-SKIPPED: 已记录跳过初始化。');
|
|
886
|
-
}
|
|
887
|
-
} else {
|
|
888
|
-
await printDetection(runRoot, probe, verdict);
|
|
889
|
-
}
|
|
890
|
-
// F(2026-08-10):init 同 id 重跑防护——.specs/<id>/ 已存在或 activeChange 相同 → WARN 不阻断
|
|
891
|
-
//(向后兼容;正常流程 init 只在 open 前执行一次,防护针对误操作清空进度)
|
|
892
|
-
let specsDirExists = false;
|
|
893
|
-
try { await fs.access(path.join(specsRoot, changeName)); specsDirExists = true; } catch { /* 目录不存在 */ }
|
|
894
|
-
if (prevState?.activeChange === changeName || specsDirExists) {
|
|
895
|
-
console.error('WARN: change ' + changeName + ' 已存在——重跑 init 将重置节点状态(completedNodes/evidence 清空)。若需继续已有 change,请用 advance/select 而非重跑 init。');
|
|
896
|
-
}
|
|
897
|
-
// E1: branchMode 自动判定——git 仓库(cwd=runRoot)→ true;非 git 仓库 → false
|
|
898
|
-
const branchMode = isInsideWorkTree();
|
|
899
|
-
const state = {
|
|
900
|
-
activeChange: changeName,
|
|
901
|
-
// 协议来源绑定:init 解析出的协议路径持久化(项目根相对 POSIX;旧 state 缺字段 = 未绑定,
|
|
902
|
-
// 归属/节点门禁按渐进语义回退环境变量/默认协议)
|
|
903
|
-
protocolPath: toPersistedProtocolPath(runRoot, protocolPath),
|
|
904
|
-
// currentNode 取协议首节点(内置协议 = open,行为不变;自定义协议 = 首节点,如 brainstorm)
|
|
905
|
-
currentNode: route(protocol)[0]?.id ?? 'open',
|
|
906
|
-
completedNodes: [],
|
|
907
|
-
evidence: {},
|
|
908
|
-
verifyFailures: 0,
|
|
909
|
-
// verifyFailures 按 change 存储——init 新 change 从零计数(切换 change 不串扰)
|
|
910
|
-
verifyFailuresByChange: {},
|
|
911
|
-
// Fix 受控归位轮次按 change 存储——init 写空对象;旧 state 缺字段按 0 读取
|
|
912
|
-
fixRoundsByChange: {},
|
|
913
|
-
executionMode: 'subagent',
|
|
914
|
-
directOverride: false,
|
|
915
|
-
branchMode,
|
|
916
|
-
enablePrReview: false,
|
|
917
|
-
branchPrefix,
|
|
918
|
-
status: 'running',
|
|
919
|
-
// R6: 新 change 标记——init 即新 change(严格模式开启,不依赖 entry;旧 change 无此字段渐进兼容)
|
|
920
|
-
newChange: true,
|
|
921
|
-
// M1: 进入证据容器——entry 追加节点;R2 检测未 entry(新 change 强制)
|
|
922
|
-
enteredNodes: [],
|
|
923
|
-
createdAt: new Date().toISOString(),
|
|
924
|
-
// 项目级上下文字段跨 change 保留(迁移旧 state;--init-context 刷新扫描时间;--init-skip 记拒绝)
|
|
925
|
-
...(prevState?.ai_context_doc !== undefined ? { ai_context_doc: prevState.ai_context_doc } : {}),
|
|
926
|
-
...(initSkip ? { ai_context_doc: 'none' } : {}),
|
|
927
|
-
// last_intel_scan 仅在校验通过后写入(agent 生成 → 脚本校验 7 段 → 记录扫描时间);形态一律经
|
|
928
|
-
// time-utils 的 nowTimestamp()(本地时间 + 显式偏移)——与 context-scan 的落点形态同源,不在本
|
|
929
|
-
// 脚本内联第二份格式化。段侧**不在本命令的写面内**(该段行的改写与备份只有 context-scan 一份
|
|
930
|
-
// 实现):两处取值不一致由 reportIntelScanDrift 检出并给出可见提示,不静默漂移。
|
|
931
|
-
...(ctxValid === true
|
|
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 } : {})
|
|
938
|
-
};
|
|
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);
|
|
944
|
-
// init 创建 .specs/<id>/ 目录——文件即真相从 init 起成立,findActiveChange 立即可识别
|
|
945
|
-
//(此前 init 后 next/status 报 No active change,与 SKILL 启动协议 init → next 矛盾)
|
|
946
|
-
const specsChangeDir = path.join(specsRoot, changeName);
|
|
947
|
-
await fs.mkdir(specsChangeDir, { recursive: true });
|
|
948
|
-
// E1 + : 分支创建——branchMode && 当前分支 ≠ <prefix><id> && 分支不存在 → git checkout -b
|
|
949
|
-
// 前缀由 --branch-prefix 指定(缺省 'change/',向后兼容;可适配仓库自身分支规范如 feat/)
|
|
950
|
-
// 失败 → WARN 不 BLOCK,继续纯文件模式(向后兼容)
|
|
951
|
-
const expectedBranch = branchPrefix + changeName;
|
|
952
|
-
// 空仓库状态(带到 BRANCH 输出——声称与实际一致:空仓库无分支)
|
|
953
|
-
let emptyRepo = false;
|
|
954
|
-
if (branchMode) {
|
|
955
|
-
const currentBranch = gitBranchName();
|
|
956
|
-
// M8: 空仓库检测——无提交(git rev-parse HEAD 失败)时分支创建不可行,输出提示
|
|
957
|
-
// (不 BLOCK;纯文件模式继续)并跳过分支创建——警告与行为一致(修复前 BRANCH 行
|
|
958
|
-
// 仍声称分支已创建,与实际矛盾)
|
|
959
|
-
try {
|
|
960
|
-
execFileSync('git', ['rev-parse', 'HEAD'], { cwd: runRoot, stdio: 'pipe' });
|
|
961
|
-
} catch {
|
|
962
|
-
emptyRepo = true;
|
|
963
|
-
}
|
|
964
|
-
if (emptyRepo) {
|
|
965
|
-
console.error('INIT EMPTY-REPO WARN: 仓库无提交(git 空仓库),无法创建 ' + expectedBranch + ' 分支——先 git commit 初始提交再 init 启用分支模式,或继续纯文件模式');
|
|
966
|
-
} else if (currentBranch !== null && currentBranch !== expectedBranch && !branchExists(expectedBranch)) {
|
|
967
|
-
try {
|
|
968
|
-
execFileSync('git', ['checkout', '-b', expectedBranch], { cwd: runRoot, stdio: 'pipe' });
|
|
969
|
-
} catch {
|
|
970
|
-
console.error('WARN: 创建分支 ' + expectedBranch + ' 失败——继续纯文件模式(分支功能降级;可稍后手动 git checkout -b ' + expectedBranch + ')');
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
console.log('Initialized: ' + changeName);
|
|
975
|
-
console.log('BRANCH: ' + (branchMode && !emptyRepo ? expectedBranch : 'none(非 git 仓库或空仓库)'));
|
|
976
|
-
// init 输出取协议首节点(与 的 state.currentNode 一致——内置协议 = open,行为不变)
|
|
977
|
-
printNext(protocol, route(protocol)[0]?.id ?? 'open');
|
|
978
|
-
return;
|
|
979
|
-
}
|
|
43
|
+
if (command === 'init') { await runInit(protocol, process.argv, protocolPath); return; }
|
|
980
44
|
|
|
981
|
-
if (command === 'status') {
|
|
982
|
-
const changeName = await findActiveChange();
|
|
983
|
-
if (!changeName) {
|
|
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());
|
|
987
|
-
return;
|
|
988
|
-
}
|
|
989
|
-
const state = await readState();
|
|
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
|
-
}
|
|
1017
|
-
console.log(JSON.stringify({
|
|
1018
|
-
status: 'running',
|
|
1019
|
-
change: changeName,
|
|
1020
|
-
currentNode: detectedNode,
|
|
1021
|
-
stateCurrentNode: state.currentNode,
|
|
1022
|
-
completedNodes: state.completedNodes,
|
|
1023
|
-
forcedNodes,
|
|
1024
|
-
executionMode: state.executionMode ?? 'subagent',
|
|
1025
|
-
directOverride: state.directOverride ?? false,
|
|
1026
|
-
branchMode: isInsideWorkTree(),
|
|
1027
|
-
enablePrReview: state.enablePrReview ?? false,
|
|
1028
|
-
artifactRoot: '.specs/' + changeName,
|
|
1029
|
-
coordinatorMode: EXECUTE_FAMILY_NODE_IDS.has(detectedNode),
|
|
1030
|
-
// G14: 新旧 change 标记——newChange true = 新 change(严格模式);false/缺失 = 旧 change(渐进)
|
|
1031
|
-
newChange: state.newChange === true
|
|
1032
|
-
}, null, 2));
|
|
1033
|
-
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
1034
|
-
await printEvolveDueHint(state);
|
|
1035
|
-
return;
|
|
1036
|
-
}
|
|
45
|
+
if (command === 'status') { await runStatus(protocol); return; }
|
|
1037
46
|
|
|
1038
|
-
if (command === 'next') {
|
|
1039
|
-
const changeName = await findActiveChange();
|
|
1040
|
-
if (!changeName) {
|
|
1041
|
-
console.log('NEXT: done');
|
|
1042
|
-
console.log('MESSAGE: No active change. Run: node workflow-state.mjs init <change-name>');
|
|
1043
|
-
return;
|
|
1044
|
-
}
|
|
1045
|
-
const state = await readState();
|
|
1046
|
-
const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
|
|
1047
|
-
// Fix 回退显式分支——必须早于「疑似未 exit」门禁与进行中漂移保护:
|
|
1048
|
-
// review/verify 驻留 + TASK 有 pending 修复任务(串行/并行)或未闭合家族出口签名时,把工作
|
|
1049
|
-
// 归属受控归位共享谓词返回的 execute 家族目标(写盘)并显式输出 NODE: <目标>,不再依赖
|
|
1050
|
-
// inProgress 保护副作用(修复前并行任务 next 输出仍停在源节点)。判定复用 route-node 共享纯函数。
|
|
1051
|
-
const fixRollbackDecision = await resolveFixRollbackDecision({
|
|
1052
|
-
runRoot, changeName, protocol, completedNodes: completedArr, currentNode: state.currentNode,
|
|
1053
|
-
history: state.history,
|
|
1054
|
-
});
|
|
1055
|
-
if (fixRollbackDecision) {
|
|
1056
|
-
const sourceNode = state.currentNode;
|
|
1057
|
-
// 轮次计数与阈值/授权判定全部走共享 helper:分支②不计数;第 4 轮新 change 先 BLOCK
|
|
1058
|
-
// (此处尚未写盘,满足不写 currentNode),旧 change WARN 后照常归位。
|
|
1059
|
-
const rollbackRound = applyFixRollbackRound({ state, sourceNode, decision: fixRollbackDecision });
|
|
1060
|
-
if (rollbackRound.blocked) {
|
|
1061
|
-
console.error(rollbackRound.blockedMessage);
|
|
1062
|
-
process.exit(1);
|
|
1063
|
-
}
|
|
1064
|
-
if (rollbackRound.warn) console.error(rollbackRound.warnMessage);
|
|
1065
|
-
state.currentNode = fixRollbackDecision.target;
|
|
1066
|
-
await writeState(state);
|
|
1067
|
-
console.log('FIX-BATCH: 归位 ' + fixRollbackDecision.target + '(源节点 ' + sourceNode + ')' + rollbackRound.auditSuffix);
|
|
1068
|
-
printNext(protocol, fixRollbackDecision.target, state.executionMode ?? 'subagent');
|
|
1069
|
-
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
1070
|
-
return;
|
|
1071
|
-
}
|
|
1072
|
-
// Fix 回程豁免——exit execute --apply 二次完成把 currentNode 回推源节点后,
|
|
1073
|
-
// 源节点产物(REVIEW.md / TEST.md+UAT.md)已在场会让 resolveNextNode 跳过尚未 exit 的
|
|
1074
|
-
// 源节点;仅当源节点未完成、任务全 done、firstIncompletePostExecNode === currentNode
|
|
1075
|
-
// 且 resolveNextNode 确实会跳过该节点时显式放行(只读不改写 state)。artifactNext ===
|
|
1076
|
-
// currentNode 的形态落回既有正常逻辑(normalAdvanceExempt 覆盖),不放宽豁免面。
|
|
1077
|
-
const fixReturnNode = state.activeChange
|
|
1078
|
-
? await resolveFixReturnNode({ runRoot, changeName, protocol, completedNodes: completedArr })
|
|
1079
|
-
: null;
|
|
1080
|
-
if (fixReturnNode !== null && fixReturnNode === state.currentNode) {
|
|
1081
|
-
const artifactNext = await resolveNextNode({ runRoot, changeName, protocol, completedNodes: completedArr });
|
|
1082
|
-
const routeIds = route(protocol).map((node) => node.id);
|
|
1083
|
-
const artifactNextIdx = routeIds.indexOf(artifactNext);
|
|
1084
|
-
const currentIdx = routeIds.indexOf(state.currentNode);
|
|
1085
|
-
// 「跳过」必须是产物存在性把路由推到源节点之后;artifactNext 落在源节点之前(如 execute
|
|
1086
|
-
// 产物缺失时回退到 execute)不是合法回程态,落回既有门禁,防止越界放宽(既有门禁反例锚)。
|
|
1087
|
-
const skipsForward = artifactNext !== state.currentNode
|
|
1088
|
-
&& currentIdx >= 0
|
|
1089
|
-
&& artifactNextIdx > currentIdx;
|
|
1090
|
-
if (skipsForward) {
|
|
1091
|
-
console.log('RETURN: 回程源节点 ' + fixReturnNode + '(源节点产物在场且未出口;保留源节点跑出口)');
|
|
1092
|
-
printNext(protocol, state.currentNode, state.executionMode ?? 'subagent');
|
|
1093
|
-
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
1094
|
-
return;
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
// 节点顺序校验(严格模式)——state.currentNode 非 null、不在 completedNodes、
|
|
1098
|
-
// 且 evidence 无该节点记录 → 上一节点从未 exit 就推进 → BLOCKED(exit 1)。
|
|
1099
|
-
// 状态漂移校正保留:已完成节点(currentNode ∈ completedNodes,或 evidence 已记录——
|
|
1100
|
-
// 节点已被 record/exit 处理过)正常推进不受影响;本校验只拦"证据完全缺失的疑似跳阶段"。
|
|
1101
|
-
// 豁免(两种独立判断,任一成立即放行): 回退豁免(TASK.md 有 pending 回退修复任务 回 execute);
|
|
1102
|
-
// 正常推进豁免(currentNode 是 completedNodes 最后节点 exit 推进的正常下一节点,
|
|
1103
|
-
// 见 normalAdvanceExempt)——真乱序(跳节点)仍严格 BLOCK
|
|
1104
|
-
if (state.currentNode && !completedArr.includes(state.currentNode)) {
|
|
1105
|
-
const nodeEvidence = state.evidence && typeof state.evidence === 'object'
|
|
1106
|
-
? state.evidence[state.currentNode]
|
|
1107
|
-
: null;
|
|
1108
|
-
const hasEvidence = !!(nodeEvidence && typeof nodeEvidence === 'object' && !Array.isArray(nodeEvidence));
|
|
1109
|
-
if (!hasEvidence) {
|
|
1110
|
-
// 回退豁免(显式分支已先行;此处按共享谓词保留门禁层语义,不再内联第二份判定)——
|
|
1111
|
-
// review/verify 发现缺陷追加 pending 修复任务后回 execute 的修复任务标准回退路径放行
|
|
1112
|
-
// (否则被严格模式误拦为"未 exit 跳阶段");豁免条件不满足时维持严格 BLOCK
|
|
1113
|
-
const rollbackExempt = await resolveFixRollbackState({
|
|
1114
|
-
runRoot, changeName, protocol, completedNodes: completedArr, currentNode: state.currentNode,
|
|
1115
|
-
history: state.history,
|
|
1116
|
-
});
|
|
1117
|
-
// 正常推进豁免——exit --apply 推进 currentNode 到下一节点后按 SKILL 协议调 next
|
|
1118
|
-
// (正常路径)不拦截;与 回退豁免独立判断(详见 normalAdvanceExempt 注释)
|
|
1119
|
-
const advanceExempt = await normalAdvanceExempt(state, protocol, completedArr, state.currentNode, changeName);
|
|
1120
|
-
if (!rollbackExempt && !advanceExempt) {
|
|
1121
|
-
console.error('BLOCKED: 疑似未 exit 节点 ' + state.currentNode + ',先 workflow-guard.mjs exit ' + state.currentNode + ' --apply');
|
|
1122
|
-
console.error('恢复: 确认当前节点实际已完成 → 用 exit <节点> --apply 正常推进;节点状态漂移/卡死 → 用 workflow-state.mjs advance(强制推进)或 select(切换 change);禁止手改 state 机器字段');
|
|
1123
|
-
process.exit(1);
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
const detectedNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
1128
|
-
// 单趟零进展防呆(三重防呆决策之二·状态机侧):路由落在 execute/subagent-execute,但既无可委托的并行任务
|
|
1129
|
-
// (依赖已满足集合为空)又无串行 pending,且 TASK 未全 done——剩余 pending 全部是依赖无法满足的
|
|
1130
|
-
// 孤儿并行任务(数据异常:depends_on 引用不存在的任务 id 或执行期出现依赖环)→ BLOCKED,
|
|
1131
|
-
// 防止静默路由到无法推进的节点造成死循环/死等。协议无 subagent-execute 节点时不适用
|
|
1132
|
-
// (parallel 任务由 execute 直接消化,无孤儿语义)。依赖环的常规拦截点在 plan 出口(guard 前置),
|
|
1133
|
-
// 此处兜底执行期数据异常(如手改 TASK 绕过签名校验的极端态)。
|
|
1134
|
-
if (EXECUTE_FAMILY_NODE_IDS.has(detectedNode)) {
|
|
1135
|
-
if (hasSubagentNode(protocol)) {
|
|
1136
|
-
try {
|
|
1137
|
-
const zpBlocks = taskBlocks(await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8'));
|
|
1138
|
-
const zpAttrs = zpBlocks.map(taskOpeningAttrs).filter(Boolean);
|
|
1139
|
-
const zpPending = zpAttrs.filter((a) => a.status === 'pending');
|
|
1140
|
-
if (zpPending.length > 0) {
|
|
1141
|
-
const zpDoneIds = new Set(zpAttrs.filter((a) => a.status === 'done' && a.id).map((a) => a.id));
|
|
1142
|
-
const zpEligible = zpBlocks.filter((block) => {
|
|
1143
|
-
const a = taskOpeningAttrs(block);
|
|
1144
|
-
if (!a || !a.parallel || a.status !== 'pending') return false;
|
|
1145
|
-
const depsMatch = block.match(/<depends_on>([\s\S]*?)<\/depends_on>/);
|
|
1146
|
-
if (!depsMatch || !depsMatch[1].trim()) return true;
|
|
1147
|
-
return depsMatch[1].trim().split(/[,\s]+/).filter(Boolean).every((d) => zpDoneIds.has(d));
|
|
1148
|
-
});
|
|
1149
|
-
const zpSerial = zpPending.filter((a) => !a.parallel);
|
|
1150
|
-
if (zpEligible.length === 0 && zpSerial.length === 0) {
|
|
1151
|
-
console.error('BLOCKED: 路由零进展——既无可委托的并行任务(依赖已满足集合为空)也无串行 pending,但 TASK 尚有 ' + zpPending.length + ' 个未完成任务');
|
|
1152
|
-
console.error('疑似孤儿并行任务依赖无法满足(检查 depends_on):' + zpPending.map((a) => a.id).join(', ') + '——修正 depends_on 为真实存在且无环的任务 id 后重试;执行期出现此异常请核对 TASK.md 是否被手改');
|
|
1153
|
-
process.exit(1);
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
} catch {}
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
// 状态漂移自动校正——以文件产物为准(determineNode)校正 state.currentNode。
|
|
1160
|
-
// 进行中节点保护:currentNode 未 exit(不在 completedNodes)且已记录 evidence(record 过)
|
|
1161
|
-
// → 视为节点进行中(可能 exit 被内容级拦截后重跑),不校正推走——否则被拦截节点
|
|
1162
|
-
// 的 exit 前置校验(currentNode 匹配)无法重跑,advance/select 均不恢复 → 死结(实测教训)
|
|
1163
|
-
const currentNodeEvidence = state.currentNode && state.evidence && typeof state.evidence === 'object'
|
|
1164
|
-
? state.evidence[state.currentNode]
|
|
1165
|
-
: null;
|
|
1166
|
-
// 进行中节点保护扩展:保护从"已 record"扩展为"已 entry(enteredNodes 含该节点)且未 exit"。
|
|
1167
|
-
// 已 entry 但未 record 的节点(如刚进入、产物已齐、premature next)同样视为进行中——
|
|
1168
|
-
// 不校正推走(否则该节点 exit 前置 currentNode 校验无法重跑 → 死结)。旧 state 无
|
|
1169
|
-
// enteredNodes 时回退到 evidence 判定(既有语义不回归)。
|
|
1170
|
-
const currentNodeEntered = !!(
|
|
1171
|
-
state.enteredNodes && Array.isArray(state.enteredNodes) && state.enteredNodes.includes(state.currentNode)
|
|
1172
|
-
);
|
|
1173
|
-
const routeIds = route(protocol).map((n) => n.id);
|
|
1174
|
-
const currentNodeIdx = state.currentNode ? routeIds.indexOf(state.currentNode) : -1;
|
|
1175
|
-
// 推导为 currentNode 的**路由后继**(与 guard 出口同源:把 currentNode 视为已完成再加入
|
|
1176
|
-
// completedNodes 求 resolveNextNode)→ 该节点产物已齐待 exit、路由自然推进到 detectedNode
|
|
1177
|
-
// (平行转换 plan→subagent-execute、趟间回流 subagent-execute→execute 均属此形态)→ 保护。
|
|
1178
|
-
// 反过度修复锚(同族:产物全齐但无推进史形态):completedNodes 为空(无任何 exit 推进史,currentNode 仅是初始
|
|
1179
|
-
// 陈旧节点)时不做路由后继保护——产物推导继续生效推进到最终节点(自定义协议产物全齐的
|
|
1180
|
-
// 「部分完成但产物齐」形态仍路由到最后节点)。静态直接后继兜底(串行推进原语义)。
|
|
1181
|
-
// 推导跳跃/跨节点或回退 → 产物权威校正(漂移,防过度修复)。
|
|
1182
|
-
const routingSuccessorOfCurrent = state.currentNode
|
|
1183
|
-
? await determineNode(changeName, protocol, [...completedArr, state.currentNode])
|
|
1184
|
-
: null;
|
|
1185
|
-
const routingSuccessorProtects = !!(completedArr.length > 0
|
|
1186
|
-
&& routingSuccessorOfCurrent !== null
|
|
1187
|
-
&& routingSuccessorOfCurrent === detectedNode);
|
|
1188
|
-
const derivedIsDirectSuccessor = currentNodeIdx >= 0
|
|
1189
|
-
&& currentNodeIdx + 1 < routeIds.length
|
|
1190
|
-
&& routeIds[currentNodeIdx + 1] === detectedNode;
|
|
1191
|
-
const derivedIsSuccessor = routingSuccessorProtects || derivedIsDirectSuccessor;
|
|
1192
|
-
const inProgress = !!(
|
|
1193
|
-
state.currentNode
|
|
1194
|
-
&& !completedArr.includes(state.currentNode)
|
|
1195
|
-
&& (currentNodeEntered
|
|
1196
|
-
|| (currentNodeEvidence && typeof currentNodeEvidence === 'object' && !Array.isArray(currentNodeEvidence)))
|
|
1197
|
-
&& derivedIsSuccessor
|
|
1198
|
-
);
|
|
1199
|
-
if (!inProgress && state.currentNode !== detectedNode) {
|
|
1200
|
-
state.currentNode = detectedNode;
|
|
1201
|
-
await writeState(state);
|
|
1202
|
-
}
|
|
1203
|
-
// 进行中节点保护:不校正时输出也跟随 currentNode(而非产物推导的 detectedNode——
|
|
1204
|
-
// 否则 state 保持 review 但输出 NODE: verify,执行者按输出 action 仍然死结)
|
|
1205
|
-
const printNode = inProgress ? state.currentNode : detectedNode;
|
|
1206
|
-
printNext(protocol, printNode, state.executionMode ?? 'subagent');
|
|
1207
|
-
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
1208
|
-
return;
|
|
1209
|
-
}
|
|
47
|
+
if (command === 'next') { await runNext(protocol); return; }
|
|
1210
48
|
|
|
1211
|
-
if (command === 'select') {
|
|
1212
|
-
const changeName = process.argv[3];
|
|
1213
|
-
if (!changeName) throw new Error('select requires a change name.');
|
|
1214
|
-
// change 名必须是 .specs/ 下的单段目录名(形态单一权威在 route-node.mjs):拒绝路径分隔符、
|
|
1215
|
-
// . / .. 与保留目录 archive(归档区不是活跃 change)——多段路径会把归档目录等非 change
|
|
1216
|
-
// 目录选成 activeChange,进而污染后续命令的 change 归属与轮次派生。
|
|
1217
|
-
if (!isSingleSegmentChangeName(changeName)) {
|
|
1218
|
-
throw new Error('select change 名必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive): '
|
|
1219
|
-
+ JSON.stringify(changeName));
|
|
1220
|
-
}
|
|
1221
|
-
const changeDir = path.join(specsRoot, changeName);
|
|
1222
|
-
// 目录必须真实存在且不是 symlink/junction、realpath 归一后仍在 .specs/ 内(复用路径段扫描
|
|
1223
|
-
// 单一权威);越界 / 链接形态一律拒绝,不把非真实目录选为 activeChange。
|
|
1224
|
-
let inspection;
|
|
1225
|
-
try {
|
|
1226
|
-
inspection = await inspectWorkflowPathSegments(specsRoot, changeDir, 'select change dir', 'directory');
|
|
1227
|
-
} catch (error) {
|
|
1228
|
-
throw new Error('Change not found or path unsafe: ' + changeDir + '(' + (error && error.message ? error.message : error) + ')');
|
|
1229
|
-
}
|
|
1230
|
-
if (!inspection.exists) throw new Error('Change not found: ' + changeDir);
|
|
1231
|
-
// 名字必须与 .specs/ 下真实目录条目逐字相等:大小写/空白变体(如 .specs/ch 用 'CH' 选中)
|
|
1232
|
-
// 在大小写不敏感文件系统上同样可达,但会把 activeChange 存成变体字符串——轮次事件按
|
|
1233
|
-
// activeChange 精确匹配(配额被换键重置)。名字变体一律拒绝,不得改写 activeChange。
|
|
1234
|
-
if (!(await hasExactSpecsEntry(changeName))) {
|
|
1235
|
-
throw new Error('select change 名必须与 .specs/ 下真实目录名逐字相等(大小写/空白变体会使 activeChange 与实际目录不一致): '
|
|
1236
|
-
+ JSON.stringify(changeName));
|
|
1237
|
-
}
|
|
1238
|
-
const state = await readState();
|
|
1239
|
-
state.activeChange = changeName;
|
|
1240
|
-
if (!state.currentNode) state.currentNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
1241
|
-
await writeState(state);
|
|
1242
|
-
console.log('Selected: ' + changeName);
|
|
1243
|
-
return;
|
|
1244
|
-
}
|
|
49
|
+
if (command === 'select') { await runSelect(protocol, process.argv); return; }
|
|
1245
50
|
|
|
1246
|
-
if (command === 'skill-load') {
|
|
1247
|
-
// 协议解析: 执行者加载节点 skill 后运行 skill-load <node> <skill> [--prompt <path>],
|
|
1248
|
-
// 写入声明标记 .specs/<change-id>/.skill-loads/<node>-<skill>.json({ node, skill, protocol, at }),
|
|
1249
|
-
// record 校验 completedChecks 的 required-skill 条目以此为准(内置节点常量)。
|
|
1250
|
-
// 诚实边界:标记是"声明"而非物理证明——运行时没有 Skill 调用观察点,脚本无法确认执行者
|
|
1251
|
-
// 真实加载过该 skill;标记仅记录"执行者主动声明已加载",由流程纪律兜底。
|
|
1252
|
-
const nodeId = process.argv[3];
|
|
1253
|
-
const skillName = process.argv[4];
|
|
1254
|
-
if (!nodeId || !skillName) {
|
|
1255
|
-
throw new Error('skill-load requires <node> <skill>. 用法: workflow-state.mjs skill-load <node> <skill> [--prompt <path>]');
|
|
1256
|
-
}
|
|
1257
|
-
// 参数校验:node 为当前协议节点集合之一(动态读取协议 nodes[].id——内置 +
|
|
1258
|
-
// 自定义,compose 自定义协议节点可声明);协议外节点名依然非法(fail-closed)。
|
|
1259
|
-
// BUILTIN_NODES 仅作内置常量保留(其他用途参照),skill-load 校验不再依赖它。
|
|
1260
|
-
const protocolNodeIds = (protocol.nodes ?? []).map((n) => n.id);
|
|
1261
|
-
if (!protocolNodeIds.includes(nodeId)) {
|
|
1262
|
-
throw new Error('skill-load node 非法: ' + nodeId + '(协议节点: ' + protocolNodeIds.join('/') + ')');
|
|
1263
|
-
}
|
|
1264
|
-
if (!/^[A-Za-z0-9-]+$/.test(skillName)) {
|
|
1265
|
-
throw new Error('skill-load skill 名非法(仅允许字母数字连字符): ' + skillName);
|
|
1266
|
-
}
|
|
1267
|
-
// --prompt 归属校验:路径必须位于 flow-kit/prompts/ 下(相对或绝对,前缀校验;
|
|
1268
|
-
// flow-kit 为 vendored 上游,协议提示只读引用)。协议加载本身由 resolveProtocol 全局
|
|
1269
|
-
// 处理(含受保护读取)——--protocol 语义不变(工作流协议 JSON);此处仅校验用户显式传入的
|
|
1270
|
-
// --prompt 原始值(skill-load 专属参数,不再与全局协议解析共用 --protocol)。
|
|
1271
|
-
const promptArg = findPromptArg(process.argv.slice(3));
|
|
1272
|
-
if (promptArg !== null && !protocolUnderFlowKitPrompts(promptArg)) {
|
|
1273
|
-
throw new Error('skill-load --prompt 路径必须位于 flow-kit/prompts/ 下(flow-kit 为 vendored 上游,协议提示只读引用): ' + promptArg);
|
|
1274
|
-
}
|
|
1275
|
-
// 声明标记写入:.skill-loads/ 目录不存在时创建(writeJsonAtomic 自带 mkdir recursive);
|
|
1276
|
-
// 同 node-skill 重复调用覆盖(记录最新声明)
|
|
1277
|
-
const changeName = await findActiveChange();
|
|
1278
|
-
if (!changeName) {
|
|
1279
|
-
// 归档后场景:change 目录已移入 .specs/archive/(无活跃 change)——skill-load 不可用,
|
|
1280
|
-
// 但 record 的声明自动化(M5)仍可写归档路径标记——消息如实引导(真实运行实证反馈)
|
|
1281
|
-
throw new Error('skill-load requires an active change(先运行 init <change-id>;若该 change 已归档,声明标记由 record 自动补写——M5 会写入归档路径的 .skill-loads/)');
|
|
1282
|
-
}
|
|
1283
|
-
// 标记 protocol 字段 = --prompt 参数的 basename(如 0-change.md)——与 guard exit
|
|
1284
|
-
// 校验的 节点协议映射 表 basename 精确比对同值(真实链路 skill-load → exit 一致);未传 --prompt →
|
|
1285
|
-
// null(无协议声明,exit 校验 fail-closed)。修复前旧实现写 resolveProtocol 解析后的完整
|
|
1286
|
-
// 绝对路径,与 节点协议映射 表 basename 比对必然失败(真实链路必 BLOCKED——机制实际不可用)。
|
|
1287
|
-
const marker = { node: nodeId, skill: skillName, protocol: promptArg === null ? null : path.basename(promptArg), at: new Date().toISOString() };
|
|
1288
|
-
// specsRoot 已含 .specs/,相对路径为 <change-id>/.skill-loads/<node>-<skill>.json
|
|
1289
|
-
const markerRel = path.posix.join(changeName, '.skill-loads', nodeId + '-' + skillName + '.json');
|
|
1290
|
-
await writeJsonAtomic(path.join(specsRoot, markerRel), marker);
|
|
1291
|
-
console.log('SKILL-LOAD: ' + nodeId + ' ' + skillName + ' → .skill-loads/' + nodeId + '-' + skillName + '.json');
|
|
1292
|
-
return;
|
|
1293
|
-
}
|
|
51
|
+
if (command === 'skill-load') { await runSkillLoad(protocol, process.argv); return; }
|
|
1294
52
|
|
|
1295
|
-
if (command === 'record') {
|
|
1296
|
-
const nodeId = process.argv[3];
|
|
1297
|
-
if (!nodeId) throw new Error('record requires a Node id.');
|
|
1298
|
-
const state = await readState();
|
|
1299
|
-
state.evidence = state.evidence || {};
|
|
1300
|
-
// 解析 JSON 参数并展开到 evidence 顶层(summary/completedChecks/output-schema evidence 等);
|
|
1301
|
-
// 若不可解析则作为 summary 字符串
|
|
1302
|
-
// payload 解析前剥离 --protocol(及 --protocol=<p>)——resolveProtocol 已全局提取协议路径,
|
|
1303
|
-
// 此处仅防其拼入 payload 导致 JSON 解析失败(结构字段丢失)
|
|
1304
|
-
// --json-file <path>(或 --json-file=<path>):从文件读 JSON payload——规避 Windows
|
|
1305
|
-
// PowerShell 传参剥离内嵌双引号导致 JSON 损坏(record 存成 {summary:...} 脏数据)
|
|
1306
|
-
let parsed = {};
|
|
1307
|
-
let jsonFile = null;
|
|
1308
|
-
const payloadArgs = [];
|
|
1309
|
-
const recordArgs = process.argv.slice(4);
|
|
1310
|
-
for (let i = 0; i < recordArgs.length; i++) {
|
|
1311
|
-
const arg = recordArgs[i];
|
|
1312
|
-
if (arg === '--protocol') { i += 1; continue; }
|
|
1313
|
-
if (typeof arg === 'string' && arg.startsWith('--protocol=')) continue;
|
|
1314
|
-
if (arg === '--json-file') {
|
|
1315
|
-
jsonFile = recordArgs[i + 1];
|
|
1316
|
-
i += 1;
|
|
1317
|
-
continue;
|
|
1318
|
-
}
|
|
1319
|
-
if (typeof arg === 'string' && arg.startsWith('--json-file=')) {
|
|
1320
|
-
jsonFile = arg.slice('--json-file='.length);
|
|
1321
|
-
continue;
|
|
1322
|
-
}
|
|
1323
|
-
payloadArgs.push(arg);
|
|
1324
|
-
}
|
|
1325
|
-
const raw = jsonFile !== null
|
|
1326
|
-
? await fs.readFile(await resolveJsonFileWithinRunRoot(jsonFile), 'utf8')
|
|
1327
|
-
: payloadArgs.join(' ');
|
|
1328
|
-
try {
|
|
1329
|
-
parsed = raw ? JSON.parse(raw) : {};
|
|
1330
|
-
if (typeof parsed !== 'object' || Array.isArray(parsed)) parsed = { summary: String(parsed) };
|
|
1331
|
-
} catch {
|
|
1332
|
-
// 契约解析失败 fail-closed:payload 形似对象但 JSON.parse 失败 → 报错并
|
|
1333
|
-
// process.exit(1),不写 evidence——防状态污染(旧语义把不可解析 raw 静默作
|
|
1334
|
-
// summary 字符串落库 = 静默落脏)
|
|
1335
|
-
// 消息按参数来源分级(设计语义 / AC-3):--json-file 传入且文件内容损坏 →
|
|
1336
|
-
// "文件内容不是合法 JSON" + 长度元数据;内联传参损坏 → 保留 --json-file 建议。
|
|
1337
|
-
// 安全(bot 审查):错误消息只含固定前缀 + 长度元数据,绝不打印 raw 内容(含截断)。
|
|
1338
|
-
if (looksLikeObjectLiteral(raw)) {
|
|
1339
|
-
if (jsonFile !== null) {
|
|
1340
|
-
console.error('文件内容不是合法 JSON (length=' + String(raw ?? '').length + ')');
|
|
1341
|
-
} else {
|
|
1342
|
-
console.error('payload looks like an object literal but is not valid JSON (length=' + String(raw ?? '').length + '); use --json-file <path> to pass the payload');
|
|
1343
|
-
}
|
|
1344
|
-
process.exit(1);
|
|
1345
|
-
}
|
|
1346
|
-
parsed = { summary: raw || 'recorded' };
|
|
1347
|
-
}
|
|
1348
|
-
// completedChecks 真实性校验(skill-load 声明标记)——解析本次 record 写入的
|
|
1349
|
-
// completedChecks 的 required-skill:<node>.<skill> 条目 → 对应声明标记必须存在(内置节点常量,
|
|
1350
|
-
// 缺失 → BLOCKED + 指引先加载 skill 并运行 skill-load);标记 at 必须 ≤ 本次记录时间
|
|
1351
|
-
// (交叉自洽:标记先于记录声明)。仅校验本次写入的 payload,旧 evidence 不追溯(旧 change 兼容)。
|
|
1352
|
-
const recordedAt = new Date().toISOString();
|
|
1353
|
-
// 标记归属 change 与 evidence 一致:优先 state.activeChange,缺失时回退 findActiveChange(与
|
|
1354
|
-
// 下方 NEXT 推导同语义);两者皆无 → verifySkillLoadMarkers 内 fail-closed BLOCK。
|
|
1355
|
-
// 传入 protocol + state——按 requiredSkillCalls scope 分类条目(handoff scope 豁免标记,
|
|
1356
|
-
// 以共用证据库 handoffResult 为证据)
|
|
1357
|
-
const markerChange = state.activeChange || await findActiveChange();
|
|
1358
|
-
const markerCheck = await verifySkillLoadMarkers(parsed.completedChecks, markerChange, recordedAt, protocol, state);
|
|
1359
|
-
if (!markerCheck.ok) {
|
|
1360
|
-
console.error('BLOCKED: ' + markerCheck.reason);
|
|
1361
|
-
process.exit(1);
|
|
1362
|
-
}
|
|
1363
|
-
// 技能加载前置门(方案 A):节点完成记录必须先有本节点
|
|
1364
|
-
// skill-load 声明标记——无论 payload 是否含 completedChecks 都校验(堵"先干活后补
|
|
1365
|
-
// 声明"旁路):缺失 → 新 change BLOCK / 旧 change 渐进 WARN。指引先加载技能并运行
|
|
1366
|
-
// skill-load 再重试。handoff scope 技能(子代理加载)不要求协调者声明(与
|
|
1367
|
-
// verifySkillLoadMarkers 的 scope 豁免一致)——本门按 <node>-*.json 存在性判定,
|
|
1368
|
-
// 与 guard exit 侧协议声明标记校验同构。仅对存在于当前协议的节点生效(协议外节点名
|
|
1369
|
-
// 的记录不适用前置门),无 active change 时无法定位标记而不重复报错(遗留兼容)。
|
|
1370
|
-
const recordNodeDef = (protocol.nodes ?? []).find((n) => n.id === nodeId);
|
|
1371
|
-
if (recordNodeDef && markerChange) {
|
|
1372
|
-
const declaredForNode = await hasNodeSkillDeclaration(nodeId, markerChange);
|
|
1373
|
-
if (!declaredForNode) {
|
|
1374
|
-
const loadGuide = '先加载技能(用 Skill 工具,禁止跳过)并运行 workflow-state.mjs skill-load ' + nodeId + ' <skill> 再重试';
|
|
1375
|
-
if (state.newChange === true) {
|
|
1376
|
-
console.error('BLOCKED: 节点 ' + nodeId + ' 缺少技能加载声明标记(.skill-loads/' + nodeId + '-*.json)——' + loadGuide);
|
|
1377
|
-
process.exit(1);
|
|
1378
|
-
}
|
|
1379
|
-
console.error('WARN: 节点 ' + nodeId + ' 缺少技能加载声明标记(.skill-loads/' + nodeId + '-*.json)——' + loadGuide + '(旧 change 渐进不阻断,记录继续)');
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
// M5: 声明自动化——record 时按协议 requiredSkillCalls 自动补写缺失的声明标记
|
|
1383
|
-
// (执行者无需手动 skill-load;标记如实记录"节点完成即视为其实现/协议技能已加载",
|
|
1384
|
-
// 由 record 代记;与手动 skill-load 标记同体系,exit 协议声明校验共用)
|
|
1385
|
-
// 新 change 下 required 条目停用自动补写(手动声明唯一路径,否则抵消前置门);
|
|
1386
|
-
// 旧 change 保留 M5 兜底(渐进兼容)。
|
|
1387
|
-
if (recordNodeDef && markerChange && state.newChange !== true) {
|
|
1388
|
-
const recordProtoFiles = NODE_PROTOCOL_FILES[nodeId] ?? [];
|
|
1389
|
-
// M5 标记目录解析:活动路径优先;change 已归档(活动目录不存在但归档目录存在)
|
|
1390
|
-
// 时写归档路径——防重建已归档的活动目录(归档移动语义;与 findSkillLoadsDir 双路径一致)。
|
|
1391
|
-
// 跳过条件:活动与归档均无 .skill-loads **且活动 change 目录已不存在**(归档移动后)
|
|
1392
|
-
// ——此时 writeJsonAtomic 的 mkdir recursive 会把已归档的活动目录残留回来(修复前实测缺陷);
|
|
1393
|
-
// 活动 change 目录仍存在(正常流程)时创建 .skill-loads 子目录是 M5 的正常职责,不跳过
|
|
1394
|
-
const activeLoadsDir = path.join(specsRoot, markerChange, '.skill-loads');
|
|
1395
|
-
let targetLoadsDir = activeLoadsDir;
|
|
1396
|
-
if (!(await fileExists(activeLoadsDir))) {
|
|
1397
|
-
const archived = await findSkillLoadsDir(markerChange);
|
|
1398
|
-
if (archived !== null && archived.dir !== activeLoadsDir) {
|
|
1399
|
-
targetLoadsDir = archived.dir;
|
|
1400
|
-
} else if (archived === null && !(await fileExists(path.join(runRoot, '.specs', markerChange)))) {
|
|
1401
|
-
targetLoadsDir = null;
|
|
1402
|
-
}
|
|
1403
|
-
}
|
|
1404
|
-
if (targetLoadsDir !== null) {
|
|
1405
|
-
for (const binding of recordNodeDef.requiredSkillCalls ?? []) {
|
|
1406
|
-
// handoff scope 技能由子代理加载(协调者不声明)——不自动补协调者标记
|
|
1407
|
-
// (2026-08-16 修复:此前无条件写标记,与 verifySkillLoadMarkers 的 scope 豁免不一致)
|
|
1408
|
-
if (binding.scope === 'handoff') continue;
|
|
1409
|
-
const markerFile = path.join(targetLoadsDir, nodeId + '-' + binding.skill + '.json');
|
|
1410
|
-
let markerExists = false;
|
|
1411
|
-
try { await fs.access(markerFile); markerExists = true; } catch { /* 标记不存在 */ }
|
|
1412
|
-
if (!markerExists) {
|
|
1413
|
-
// 自动补的 protocol 字段按 skill 归属协议文件(如 open 的 requirement 标记应写
|
|
1414
|
-
// 1-requirement.md 而非节点首文件 0-change.md——修复前所有 skill 都写首文件,
|
|
1415
|
-
// 标记的协议归属语义错误;exit 校验只查归属集合故能通过,但标记不可信)
|
|
1416
|
-
const skillProtoFiles = SKILL_PROTOCOL_FILES[binding.skill] ?? [];
|
|
1417
|
-
await writeJsonAtomic(markerFile, {
|
|
1418
|
-
node: nodeId,
|
|
1419
|
-
skill: binding.skill,
|
|
1420
|
-
protocol: skillProtoFiles.length > 0 ? skillProtoFiles[0] : null,
|
|
1421
|
-
at: recordedAt,
|
|
1422
|
-
auto: true,
|
|
1423
|
-
});
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
|
-
state.evidence[nodeId] = {
|
|
1429
|
-
...(state.evidence[nodeId] || {}),
|
|
1430
|
-
...parsed,
|
|
1431
|
-
recordedAt,
|
|
1432
|
-
};
|
|
1433
|
-
await writeState(state);
|
|
1434
|
-
console.log('EVIDENCE: ' + nodeId);
|
|
1435
|
-
const changeName = state.activeChange || await findActiveChange();
|
|
1436
|
-
const nextNode = changeName ? await determineNode(changeName, protocol, state.completedNodes) : null;
|
|
1437
|
-
printNext(protocol, nextNode ?? null, state.executionMode ?? 'subagent');
|
|
1438
|
-
return;
|
|
1439
|
-
}
|
|
53
|
+
if (command === 'record') { await runRecord(protocol, process.argv); return; }
|
|
1440
54
|
|
|
1441
|
-
if (command === 'config') {
|
|
1442
|
-
// E1: 配置命令——config set <key> <value>;branchMode 只读(init 自动判定),enablePrReview 手动
|
|
1443
|
-
// 开关,last_evolve_at 为 evolve 元数据时刻(形态校验 fail-closed,写通道唯一)
|
|
1444
|
-
const sub = process.argv[3];
|
|
1445
|
-
const key = process.argv[4];
|
|
1446
|
-
const value = process.argv[5];
|
|
1447
|
-
if (sub !== 'set') throw new Error('config 仅支持 set 子命令。用法: workflow-state.mjs config set <key> <value>');
|
|
1448
|
-
if (!key || value === undefined) throw new Error('config set 需要 key 和 value。用法: workflow-state.mjs config set <key> <value>');
|
|
1449
|
-
if (key === 'branchMode') {
|
|
1450
|
-
console.error('BLOCKED: branchMode 由 init 自动判定,不可手动设置');
|
|
1451
|
-
process.exit(1);
|
|
1452
|
-
}
|
|
1453
|
-
if (key === 'enablePrReview') {
|
|
1454
|
-
if (value !== 'true' && value !== 'false') {
|
|
1455
|
-
console.error('BLOCKED: config set 值非法(enablePrReview 必须为 true 或 false): ' + value);
|
|
1456
|
-
process.exit(1);
|
|
1457
|
-
}
|
|
1458
|
-
const state = await readState();
|
|
1459
|
-
state.enablePrReview = value === 'true';
|
|
1460
|
-
await writeState(state);
|
|
1461
|
-
console.log('CONFIG: enablePrReview = ' + state.enablePrReview);
|
|
1462
|
-
return;
|
|
1463
|
-
}
|
|
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 自动判定)');
|
|
1479
|
-
process.exit(1);
|
|
1480
|
-
}
|
|
55
|
+
if (command === 'config') { await runConfig(process.argv); return; }
|
|
1481
56
|
|
|
1482
|
-
if (command === 'execution-mode') {
|
|
1483
|
-
const mode = process.argv[3];
|
|
1484
|
-
if (mode !== 'subagent' && mode !== 'direct') {
|
|
1485
|
-
console.error('BLOCKED: execution-mode 参数必须为 subagent 或 direct,收到: ' + String(mode));
|
|
1486
|
-
process.exit(1);
|
|
1487
|
-
}
|
|
1488
|
-
const state = await readState();
|
|
1489
|
-
state.executionMode = mode;
|
|
1490
|
-
// direct 是逃生口:必须用户显式调用,并记录 directOverride;切回 subagent 时清除
|
|
1491
|
-
// (directOverride 恒等于"当前是否处于用户确认的 direct"——再次切 direct 必须重新确认,无历史歧义)
|
|
1492
|
-
state.directOverride = mode === 'direct';
|
|
1493
|
-
if (mode === 'direct') {
|
|
1494
|
-
// 授权审计留痕:direct 是用户决策点不可自决——协调者显式调用本命令即授权事件,写入授权
|
|
1495
|
-
// 审计字段(guard 出口校验须存在授权记录;执行者绕过脚本手改 state 字段无授权记录 → BLOCK)。
|
|
1496
|
-
console.error('DIRECT-AUTH: direct=逃生口须用户显式授权——本命令即授权留痕(directOverrideAt 写入)');
|
|
1497
|
-
state.directOverrideAt = new Date().toISOString();
|
|
1498
|
-
state.directOverrideSource = 'execution-mode';
|
|
1499
|
-
} else {
|
|
1500
|
-
// 切回 subagent 清除授权留痕(directOverride 一并清除——既有语义保持)
|
|
1501
|
-
delete state.directOverrideAt;
|
|
1502
|
-
delete state.directOverrideSource;
|
|
1503
|
-
}
|
|
1504
|
-
await writeState(state);
|
|
1505
|
-
console.log('EXECUTION-MODE: ' + state.executionMode + (state.directOverride ? ' (directOverride)' : ''));
|
|
1506
|
-
return;
|
|
1507
|
-
}
|
|
57
|
+
if (command === 'execution-mode') { await runExecutionMode(process.argv); return; }
|
|
1508
58
|
|
|
1509
|
-
if (command === 'verify-fail') {
|
|
1510
|
-
const state = await readState();
|
|
1511
|
-
// W2-A: 机器计数——连续 3 次失败后(第 4 次)BLOCKED,要求用户决策(继续修 / 停止)
|
|
1512
|
-
// 计数按当前 change 存储(verifyFailuresByChange)——切换 change 后计数独立,互不串扰;
|
|
1513
|
-
// 旧顶层字段首次读取时迁移并入当前 change(旧 state 兼容)
|
|
1514
|
-
const count = verifyFailuresFor(state);
|
|
1515
|
-
if (count >= 3) {
|
|
1516
|
-
console.error('verify 失败超限,需用户决策(verifyFailures=' + count + ')。继续修 / 停止?');
|
|
1517
|
-
process.exit(1);
|
|
1518
|
-
}
|
|
1519
|
-
setVerifyFailuresFor(state, count + 1);
|
|
1520
|
-
await writeState(state);
|
|
1521
|
-
console.log('VERIFY-FAIL: ' + (count + 1) + '/3');
|
|
1522
|
-
return;
|
|
1523
|
-
}
|
|
59
|
+
if (command === 'verify-fail') { await runVerifyFail(); return; }
|
|
1524
60
|
|
|
1525
|
-
if (command === 'advance') {
|
|
1526
|
-
const state = await readState();
|
|
1527
|
-
if (!state.activeChange) {
|
|
1528
|
-
console.log('No active change. Use select first.');
|
|
1529
|
-
return;
|
|
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;
|
|
1536
|
-
if (!state.completedNodes.includes(state.currentNode)) {
|
|
1537
|
-
state.completedNodes.push(state.currentNode);
|
|
1538
|
-
}
|
|
1539
|
-
// Use determineNode to get the actual next node (reads TASK.md)
|
|
1540
|
-
const detected = await determineNode(state.activeChange, protocol, state.completedNodes);
|
|
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
|
-
}
|
|
1555
|
-
await writeState(state);
|
|
1556
|
-
console.log('Advanced to: ' + state.currentNode);
|
|
1557
|
-
if (forcedNodeId !== null) {
|
|
1558
|
-
console.log('ADVANCE-AUDIT: 跳过 ' + forcedNodeId + ' 的 exit 门禁;该节点无出口证据');
|
|
1559
|
-
}
|
|
1560
|
-
return;
|
|
1561
|
-
}
|
|
61
|
+
if (command === 'advance') { await runAdvance(protocol); return; }
|
|
1562
62
|
|
|
1563
|
-
if (command === 'reenter') {
|
|
1564
|
-
// 受控重入(archive 源回边):archive 已 entry 且归档移动尚未发生时,用户显式授权把工作归属
|
|
1565
|
-
// 退回执行家族 / review / verify 之一。命令形态:reenter <target> --authorized-by <source>
|
|
1566
|
-
// --reason <text> [--continue-round <n>]。编排顺序:参数防护 → 路径边界(change 名单段 +
|
|
1567
|
-
// realpath 直接子目录)→ 单一权威判定(目标 / change 名 / 上限 / 幂等 / 源 / 授权)→ 备份
|
|
1568
|
-
// (包含性复核)→ 转移 → 授权留痕 → 审计事件 → REENTRY 行。全部判定集中在 route-node.mjs
|
|
1569
|
-
// 纯函数(本命令只做编排与落盘,禁止内联第二份);BLOCK 与空操作路径一律在写盘前返回
|
|
1570
|
-
// (state 字节零改写)。
|
|
1571
|
-
const target = process.argv[3];
|
|
1572
|
-
const reentryTargetList = [...REENTRY_TARGET_NODE_IDS].join(', ');
|
|
1573
|
-
const reenterUsage = '用法: workflow-state.mjs reenter <target> --authorized-by <source> --reason <text>'
|
|
1574
|
-
+ ' [--continue-round <n>](target 白名单: ' + reentryTargetList + ')';
|
|
1575
|
-
if (typeof target !== 'string' || target === '' || target.startsWith('--')) {
|
|
1576
|
-
console.error('BLOCKED: reenter 缺少目标节点。' + reenterUsage);
|
|
1577
|
-
process.exit(1);
|
|
1578
|
-
}
|
|
1579
|
-
let authorizedBy = null;
|
|
1580
|
-
let reason = null;
|
|
1581
|
-
let continuationRound = null;
|
|
1582
|
-
const reenterArgs = process.argv.slice(4);
|
|
1583
|
-
for (let index = 0; index < reenterArgs.length; index += 1) {
|
|
1584
|
-
const arg = reenterArgs[index];
|
|
1585
|
-
// 支持 --name value 与 --name=value 两种形态;--protocol 为全局参数(协议路径已由
|
|
1586
|
-
// resolveProtocol 统一解析),命令面只做占位透传。
|
|
1587
|
-
let key = arg;
|
|
1588
|
-
let value = null;
|
|
1589
|
-
if (typeof arg === 'string' && arg.startsWith('--')) {
|
|
1590
|
-
const eq = arg.indexOf('=');
|
|
1591
|
-
if (eq > 0) {
|
|
1592
|
-
key = arg.slice(0, eq);
|
|
1593
|
-
value = arg.slice(eq + 1);
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
if (key === '--protocol') {
|
|
1597
|
-
if (value === null) index += 1;
|
|
1598
|
-
continue;
|
|
1599
|
-
}
|
|
1600
|
-
if (key === '--continue-round') {
|
|
1601
|
-
// 续轮授权只在达到轮次上限后生效:命令面收正整数,形态合法性与「是否已到上限」由
|
|
1602
|
-
// 单一权威综合判定裁决(本处只做数值形态防护,fail-closed,先于任何读盘)。
|
|
1603
|
-
let consumedNext = false;
|
|
1604
|
-
if (value === null) {
|
|
1605
|
-
value = reenterArgs[index + 1];
|
|
1606
|
-
consumedNext = true;
|
|
1607
|
-
}
|
|
1608
|
-
const parsedRound = typeof value === 'string' && value.trim() !== '' && !value.startsWith('--')
|
|
1609
|
-
? Number(value.trim())
|
|
1610
|
-
: Number.NaN;
|
|
1611
|
-
if (!Number.isInteger(parsedRound) || parsedRound <= 0) {
|
|
1612
|
-
console.error('BLOCKED: reenter --continue-round 需要正整数取值,实际 ' + JSON.stringify(value) + '。' + reenterUsage);
|
|
1613
|
-
process.exit(1);
|
|
1614
|
-
}
|
|
1615
|
-
continuationRound = parsedRound;
|
|
1616
|
-
if (consumedNext) index += 1;
|
|
1617
|
-
continue;
|
|
1618
|
-
}
|
|
1619
|
-
if (key === '--authorized-by' || key === '--reason') {
|
|
1620
|
-
let consumedNext = false;
|
|
1621
|
-
if (value === null) {
|
|
1622
|
-
value = reenterArgs[index + 1];
|
|
1623
|
-
consumedNext = true;
|
|
1624
|
-
}
|
|
1625
|
-
// 缺值 / 空值 / 纯空白 / 取下个选项名当值 → 一律用法错误(fail-closed,先于任何读盘)
|
|
1626
|
-
if (typeof value !== 'string' || value.trim() === '' || value.startsWith('--')) {
|
|
1627
|
-
console.error('BLOCKED: reenter ' + key + ' 需要非空取值。' + reenterUsage);
|
|
1628
|
-
process.exit(1);
|
|
1629
|
-
}
|
|
1630
|
-
if (key === '--authorized-by') authorizedBy = value.trim();
|
|
1631
|
-
else reason = value.trim();
|
|
1632
|
-
if (consumedNext) index += 1;
|
|
1633
|
-
continue;
|
|
1634
|
-
}
|
|
1635
|
-
console.error('BLOCKED: reenter 未知参数 ' + JSON.stringify(arg) + '。' + reenterUsage);
|
|
1636
|
-
process.exit(1);
|
|
1637
|
-
}
|
|
1638
|
-
if (authorizedBy === null) {
|
|
1639
|
-
console.error('BLOCKED: reenter 需要显式授权 --authorized-by <source>(授权不可自决)。' + reenterUsage);
|
|
1640
|
-
process.exit(1);
|
|
1641
|
-
}
|
|
1642
|
-
if (reason === null) {
|
|
1643
|
-
console.error('BLOCKED: reenter 需要 --reason <text> 说明重入原因。' + reenterUsage);
|
|
1644
|
-
process.exit(1);
|
|
1645
|
-
}
|
|
1646
|
-
const state = await readState();
|
|
1647
|
-
const badFields = validateStateFields(state);
|
|
1648
|
-
if (badFields.length > 0) {
|
|
1649
|
-
// history 存在但非数组等类型损坏在此 fail-closed:不得由本命令静默清空覆盖审计历史。
|
|
1650
|
-
console.error('BLOCKED: state 字段类型非法: ' + badFields[0]);
|
|
1651
|
-
process.exit(1);
|
|
1652
|
-
}
|
|
1653
|
-
// 原始 state(未经 readState 兼容默认值叠加):落盘时只写「原始键集 + 本次实际改动的字段」,
|
|
1654
|
-
// 兼容默认值不得随重入回写(最小旧 state 的键集保持逐项不变)。
|
|
1655
|
-
const rawState = (await fileExists(statePath)) ? await readJson(statePath) : null;
|
|
1656
|
-
// 路径边界:change 名必须是 .specs/ 下的单段真实目录(realpath 归一后是 .specs 直接子目录,
|
|
1657
|
-
// 且路径上无 symlink/junction)。归档移动已发生(目录不在原位)、change 已 completed、
|
|
1658
|
-
// change 名畸形(多段 / . / .. / 保留目录 archive)与链接逃逸一律 BLOCK。该边界先于综合
|
|
1659
|
-
// 判定执行——completed 与已移动形态必须无条件 BLOCK(不被空操作分支短路)。
|
|
1660
|
-
const changeName = typeof state.activeChange === 'string' ? state.activeChange : '';
|
|
1661
|
-
const changeBoundary = await inspectReentryChangeDir(changeName);
|
|
1662
|
-
const changeDirPresent = changeBoundary.ok
|
|
1663
|
-
? true
|
|
1664
|
-
: (changeBoundary.reason === 'change-dir-missing' ? false : null);
|
|
1665
|
-
const movedOrCompletedMessage = 'BLOCKED: 归档移动已发生或 change 已 completed(.specs/'
|
|
1666
|
-
+ (changeName || '<未知>') + '/ 在场=' + changeDirPresent + ',status=' + JSON.stringify(state.status)
|
|
1667
|
-
+ ')——受控重入只覆盖归档移动前的运行形态;请走人工处置、新 change 或 hotfix 路径。';
|
|
1668
|
-
if (state.status === 'completed' || changeDirPresent === false) {
|
|
1669
|
-
console.error(movedOrCompletedMessage);
|
|
1670
|
-
process.exit(1);
|
|
1671
|
-
}
|
|
1672
|
-
if (!changeBoundary.ok) {
|
|
1673
|
-
const boundaryMessages = {
|
|
1674
|
-
'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
|
|
1675
|
-
'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
|
|
1676
|
-
+ '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
|
|
1677
|
-
'change-dir-escape': 'change 目录路径越界或跨越符号链接 / junction(' + changeBoundary.detail
|
|
1678
|
-
+ ')——受控重入与备份只允许落在 .specs/<change-id>/ 真实目录内',
|
|
1679
|
-
};
|
|
1680
|
-
console.error('BLOCKED: ' + boundaryMessages[changeBoundary.reason]);
|
|
1681
|
-
process.exit(1);
|
|
1682
|
-
}
|
|
1683
|
-
const changeDir = changeBoundary.changeDir;
|
|
1684
|
-
// 授权形态的 round / at 由引擎派生(命令面只承载授权来源、原因与上限后的续轮轮次):普通轮次
|
|
1685
|
-
// 以合法占位值过形态门;落盘轮次一律取综合判定返回的 round(由本 change 历史事件派生),
|
|
1686
|
-
// 不在此内联第二份轮次推导。
|
|
1687
|
-
const authorizedAt = new Date().toISOString();
|
|
1688
|
-
const decision = resolveReentryDecision({
|
|
1689
|
-
protocol,
|
|
1690
|
-
state,
|
|
1691
|
-
target,
|
|
1692
|
-
authorization: { round: 1, at: authorizedAt, source: authorizedBy, target },
|
|
1693
|
-
continuationRound,
|
|
1694
|
-
});
|
|
1695
|
-
if (!decision.ok) {
|
|
1696
|
-
if (decision.reason === 'round-limit-reached') {
|
|
1697
|
-
console.error('BLOCKED: 本 change 受控重入已达上限(' + decision.used + '/' + decision.limit
|
|
1698
|
-
+ ' 轮)。需要人工裁决:继续(显式授权后在同一命令加 --continue-round <n>,n 为不小于第 '
|
|
1699
|
-
+ (decision.used + 1) + ' 轮的正整数,须与 --authorized-by / --reason 同次传入)/ 停止(保持归档态,不再重入)。');
|
|
1700
|
-
process.exit(1);
|
|
1701
|
-
}
|
|
1702
|
-
const guidance = {
|
|
1703
|
-
'target-not-allowed': '目标节点 ' + JSON.stringify(target) + ' 不在受控重入白名单('
|
|
1704
|
-
+ reentryTargetList + ')——请显式指定白名单内目标',
|
|
1705
|
-
'target-not-enabled': '目标节点 ' + JSON.stringify(target)
|
|
1706
|
-
+ ' 在当前协议中未启用(disabled)——请检查协议或改选已启用目标',
|
|
1707
|
-
'no-active-change': '当前没有活跃 change(activeChange 缺失或为空)——先 select <change-id>',
|
|
1708
|
-
'change-name-invalid': 'change 名非法 ' + JSON.stringify(changeName)
|
|
1709
|
-
+ '——必须是 .specs/ 下的单段目录名(拒绝路径分隔符、. / .. 与保留目录 archive)',
|
|
1710
|
-
'source-not-archive': '受控重入只覆盖 archive 源(当前节点 ' + JSON.stringify(state.currentNode)
|
|
1711
|
-
+ ')——正常推进请走 next / record / exit 既有通道',
|
|
1712
|
-
'continuation-not-required': '--continue-round 只在达到轮次上限后需要(当前 ' + decision.used + '/'
|
|
1713
|
-
+ decision.limit + ' 轮)——上限前请直接以 --authorized-by / --reason 发起',
|
|
1714
|
-
}[decision.reason] || ('授权形态不合法(' + decision.reason + ')——需要用户显式传入 --authorized-by <source>');
|
|
1715
|
-
console.error('BLOCKED: ' + guidance);
|
|
1716
|
-
process.exit(1);
|
|
1717
|
-
}
|
|
1718
|
-
if (decision.action === 'noop') {
|
|
1719
|
-
console.log('REENTRY: 空操作——workflow 已处于目标形态(' + target
|
|
1720
|
-
+ ',完成标记已是目标前驱交集);未备份、未计数、未改写 state。');
|
|
1721
|
-
return;
|
|
1722
|
-
}
|
|
1723
|
-
if (decision.action !== 'apply') {
|
|
1724
|
-
console.error('BLOCKED: 受控重入判定返回未知动作 ' + JSON.stringify(decision.action) + '——按 fail-closed 拒绝。');
|
|
1725
|
-
process.exit(1);
|
|
1726
|
-
}
|
|
1727
|
-
const round = decision.round;
|
|
1728
|
-
const source = decision.authorization.source;
|
|
1729
|
-
const at = decision.authorization.at;
|
|
1730
|
-
const continuationAuthorized = decision.continuationAuthorized === true;
|
|
1731
|
-
// 备份:重入前 state 全量快照(文件原始字节,UTF-8 BOM 按可解析形态落盘);文件名
|
|
1732
|
-
// <UTC ISO 净化>-pre-<target>.json;审计指纹 = 备份文件字节的 sha256(可核验)。
|
|
1733
|
-
const backupDir = path.join(changeDir, '.reentry-backups');
|
|
1734
|
-
const backupFile = at.replace(/:/g, '-') + '-pre-' + target + '.json';
|
|
1735
|
-
const backupPath = path.join(backupDir, backupFile);
|
|
1736
|
-
const backupRecord = path.relative(runRoot, backupPath).split(path.sep).join('/');
|
|
1737
|
-
const snapshotBytes = Buffer.from((await fs.readFile(statePath, 'utf8')).replace(/^\uFEFF/, ''), 'utf8');
|
|
1738
|
-
const fingerprint = createHash('sha256').update(snapshotBytes).digest('hex');
|
|
1739
|
-
const existingHistory = Array.isArray(rawState?.history) ? rawState.history : [];
|
|
1740
|
-
let backupWritten = false;
|
|
1741
|
-
try {
|
|
1742
|
-
if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
|
|
1743
|
-
throw new Error('state 文件缺失或形态非法,无法重入');
|
|
1744
|
-
}
|
|
1745
|
-
// 备份写入路径的物理包含性复核(单一权威路径段扫描):备份目录与备份文件逐段
|
|
1746
|
-
// lstat + realpath——任何 symlink/junction 逃出 .specs/ 一律拒绝,不写任何字节。
|
|
1747
|
-
await fs.mkdir(backupDir, { recursive: true });
|
|
1748
|
-
await inspectWorkflowPathSegments(specsRoot, backupDir, 'reenter backup dir', 'directory');
|
|
1749
|
-
await fs.writeFile(backupPath, snapshotBytes);
|
|
1750
|
-
backupWritten = true;
|
|
1751
|
-
await inspectWorkflowPathSegments(specsRoot, backupPath, 'reenter backup file', 'file');
|
|
1752
|
-
// 授权留痕:嵌套写入被重入目标节点的 evidence(授权记录 + 备份指针 + 指纹 + 原因 +
|
|
1753
|
-
// 续轮标记)。只改 evidence 的目标节点键,其余键按原始键集逐项保留。
|
|
1754
|
-
const existingEvidence = rawState.evidence && typeof rawState.evidence === 'object' && !Array.isArray(rawState.evidence)
|
|
1755
|
-
? rawState.evidence
|
|
1756
|
-
: {};
|
|
1757
|
-
const targetEvidence = existingEvidence[decision.target]
|
|
1758
|
-
&& typeof existingEvidence[decision.target] === 'object'
|
|
1759
|
-
&& !Array.isArray(existingEvidence[decision.target])
|
|
1760
|
-
? existingEvidence[decision.target]
|
|
1761
|
-
: {};
|
|
1762
|
-
const authorizationRecord = {
|
|
1763
|
-
round,
|
|
1764
|
-
at,
|
|
1765
|
-
source,
|
|
1766
|
-
target: decision.target,
|
|
1767
|
-
backup: backupRecord,
|
|
1768
|
-
fingerprint,
|
|
1769
|
-
reason,
|
|
1770
|
-
...(continuationAuthorized ? { continuationAuthorized: true } : {}),
|
|
1771
|
-
};
|
|
1772
|
-
// 落盘形态 = 原始 state 键集 + 本次实际改动的四类机器字段与审计字段——转移语义
|
|
1773
|
-
// (currentNode := target / completedNodes := 前驱交集 / status := running)与审计
|
|
1774
|
-
// (evidence 留痕 + history 追加事件)之外的字段逐项不变;readState 的兼容默认值不回写。
|
|
1775
|
-
const persisted = { ...rawState };
|
|
1776
|
-
persisted.currentNode = decision.target;
|
|
1777
|
-
persisted.completedNodes = decision.completedNodes.slice();
|
|
1778
|
-
persisted.status = 'running';
|
|
1779
|
-
persisted.evidence = {
|
|
1780
|
-
...existingEvidence,
|
|
1781
|
-
[decision.target]: { ...targetEvidence, reentryAuthorization: authorizationRecord },
|
|
1782
|
-
};
|
|
1783
|
-
// 审计事件:append-only 追加 reentry-applied;change 字段是跨 change 轮次隔离的唯一依据。
|
|
1784
|
-
persisted.history = existingHistory.concat([{
|
|
1785
|
-
event: 'reentry-applied',
|
|
1786
|
-
from: 'archive',
|
|
1787
|
-
to: decision.target,
|
|
1788
|
-
round,
|
|
1789
|
-
authorization: { round, at, source, target: decision.target },
|
|
1790
|
-
backup: backupRecord,
|
|
1791
|
-
fingerprint,
|
|
1792
|
-
at,
|
|
1793
|
-
change: changeName,
|
|
1794
|
-
reason,
|
|
1795
|
-
...(continuationAuthorized ? { continuationAuthorized: true } : {}),
|
|
1796
|
-
}]);
|
|
1797
|
-
const persistedBad = validateStateFields(persisted);
|
|
1798
|
-
if (persistedBad.length > 0) throw new Error('state 字段类型非法: ' + persistedBad[0]);
|
|
1799
|
-
await writeState(persisted);
|
|
1800
|
-
} catch (error) {
|
|
1801
|
-
// 写盘失败:回滚本次调用创建的孤儿备份(state 由原子写保证不被截断),原始错误照常上抛。
|
|
1802
|
-
if (backupWritten) {
|
|
1803
|
-
try { await fs.rm(backupPath, { force: true }); } catch { /* 清理失败不掩盖原始错误 */ }
|
|
1804
|
-
}
|
|
1805
|
-
throw error;
|
|
1806
|
-
}
|
|
1807
|
-
const roundLabel = continuationAuthorized
|
|
1808
|
-
? '第 ' + round + ' 轮(显式授权续轮,上限 ' + REENTRY_ROUND_LIMIT + ')'
|
|
1809
|
-
: '第 ' + round + '/' + REENTRY_ROUND_LIMIT + ' 轮';
|
|
1810
|
-
console.log('REENTRY: archive → ' + decision.target + '(授权源 ' + source + ';' + roundLabel
|
|
1811
|
-
+ ';备份 ' + backupRecord + ')');
|
|
1812
|
-
console.log('REASON: ' + reason);
|
|
1813
|
-
return;
|
|
1814
|
-
}
|
|
63
|
+
if (command === 'reenter') { await runReenter(protocol, process.argv); return; }
|
|
1815
64
|
|
|
1816
|
-
if (command === 'replan') {
|
|
1817
|
-
|
|
1818
|
-
|
|
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
|
-
}
|
|
65
|
+
if (command === 'replan') { await runReplan(protocol, process.argv); return; }
|
|
66
|
+
|
|
67
|
+
if (command === 'explain') { runExplain(protocol, process.argv, __dirname); return; }
|
|
2125
68
|
|
|
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');
|
|
69
|
+
throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check, reenter, replan, explain');
|
|
2127
70
|
}
|
|
2128
71
|
|
|
2129
72
|
main().catch(error => {
|