flow-comet 1.5.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.flow-comet/rules/flow-comet-orchestration.md +13 -0
- package/.flow-comet/skills/flow-comet/GUIDANCE.md +196 -0
- package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -0
- package/.flow-comet/skills/flow-comet/SKILL.md +196 -0
- package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +19 -0
- package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +115 -0
- package/.flow-comet/skills/flow-comet/reference/authoring-lanes.json +33 -0
- package/.flow-comet/skills/flow-comet/reference/composition-report.md +65 -0
- package/.flow-comet/skills/flow-comet/reference/decision-points.md +64 -0
- package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +30 -0
- package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +169 -0
- package/.flow-comet/skills/flow-comet/reference/init-detection.md +58 -0
- package/.flow-comet/skills/flow-comet/reference/recovery.md +20 -0
- package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +661 -0
- package/.flow-comet/skills/flow-comet/reference/skill-review.md +13 -0
- package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +7 -0
- package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +681 -0
- package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +52 -0
- package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +61 -0
- package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +909 -0
- package/.flow-comet/skills/flow-comet/scripts/comet-plan.mjs +2 -0
- package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +312 -0
- package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +136 -0
- package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +7331 -0
- package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +376 -0
- package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +230 -0
- package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +99 -0
- package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +4017 -0
- package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +28 -0
- package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +2396 -0
- package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +378 -0
- package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +1263 -0
- package/.flow-comet/skills/flow-comet-archive/SKILL.md +195 -0
- package/.flow-comet/skills/flow-comet-change/SKILL.md +29 -0
- package/.flow-comet/skills/flow-comet-compose/SKILL.md +249 -0
- package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +23 -0
- package/.flow-comet/skills/flow-comet-design/SKILL.md +161 -0
- package/.flow-comet/skills/flow-comet-dev/SKILL.md +51 -0
- package/.flow-comet/skills/flow-comet-evolve/SKILL.md +26 -0
- package/.flow-comet/skills/flow-comet-execute/SKILL.md +182 -0
- package/.flow-comet/skills/flow-comet-health/SKILL.md +31 -0
- package/.flow-comet/skills/flow-comet-integration/SKILL.md +45 -0
- package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +36 -0
- package/.flow-comet/skills/flow-comet-open/SKILL.md +161 -0
- package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +33 -0
- package/.flow-comet/skills/flow-comet-plan/SKILL.md +169 -0
- package/.flow-comet/skills/flow-comet-requirement/SKILL.md +27 -0
- package/.flow-comet/skills/flow-comet-review/SKILL.md +204 -0
- package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +29 -0
- package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +214 -0
- package/.flow-comet/skills/flow-comet-task/SKILL.md +33 -0
- package/.flow-comet/skills/flow-comet-test/SKILL.md +41 -0
- package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +26 -0
- package/.flow-comet/skills/flow-comet-verify/SKILL.md +164 -0
- package/LICENSE +21 -0
- package/README.md +255 -0
- package/package.json +27 -0
- package/scripts/dsh-bridge.mjs +461 -0
- package/scripts/prepare-env.mjs +1526 -0
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFileSync } from 'child_process';
|
|
3
|
+
import { promises as fs } from 'fs';
|
|
4
|
+
import os from 'os';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
7
|
+
import { resolveProtocol, readProtocolFile, validateProtocolSchema, NODE_PROTOCOL_FILES, SKILL_PROTOCOL_FILES } from './protocol-utils.mjs';
|
|
8
|
+
import { validateStateFields, verifyFailuresFor, setVerifyFailuresFor, looksLikeObjectLiteral, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME } from './state-schema.mjs';
|
|
9
|
+
import { probeProject, classify, printDetection, validateContext, printGenerationGuide, skipInit } from './context-init.mjs';
|
|
10
|
+
import { taskOpeningAttrs, taskBlocks } from './task-parsing.mjs';
|
|
11
|
+
import { route, resolveNextNode, hasSubagentNode, protocolTaskFilePath } from './route-node.mjs';
|
|
12
|
+
|
|
13
|
+
const command = process.argv[2] ?? 'status';
|
|
14
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
15
|
+
const packageRoot = path.resolve(__dirname, '..');
|
|
16
|
+
const runRoot = process.cwd();
|
|
17
|
+
// 协议解析: 协议路径统一由 resolveProtocol 解析——优先级:--protocol CLI 参数 → FLOW_COMET_PROTOCOL
|
|
18
|
+
// 环境变量 → 内置默认 reference/workflow-protocol.json。--protocol 为全局参数(可放在 command
|
|
19
|
+
// 之后的任意位置);cliArgs = 去掉 command 后的剩余参数数组。
|
|
20
|
+
const protocolPath = resolveProtocol(packageRoot, runRoot, process.argv.slice(3));
|
|
21
|
+
// 状态文件路径(单一来源:state-schema.mjs 的运行时路径常量)
|
|
22
|
+
const statePath = path.join(runRoot, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME);
|
|
23
|
+
const specsRoot = path.join(runRoot, '.specs');
|
|
24
|
+
|
|
25
|
+
// 内置节点常量: 内置 8 节点常量(供其他用途参照——如 guard 的节点→协议映射对照;skill-load 的 node
|
|
26
|
+
// 参数校验已改为当前协议节点集合动态读取——compose 自定义协议节点可声明)
|
|
27
|
+
const BUILTIN_NODES = ['open', 'design', 'plan', 'execute', 'subagent-execute', 'review', 'verify', 'archive'];
|
|
28
|
+
|
|
29
|
+
// 节点协议映射(单一来源): NODE_PROTOCOL_FILES 来自 protocol-utils.mjs(M5 record 自动补声明标记的 protocol 归属)
|
|
30
|
+
|
|
31
|
+
async function readJson(file) {
|
|
32
|
+
// 容忍 UTF-8 BOM(外部写入如会话 Write 可能带 BOM)
|
|
33
|
+
return JSON.parse((await fs.readFile(file, 'utf8')).replace(/^/, ''));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function writeJson(file, value) {
|
|
37
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
38
|
+
await fs.writeFile(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function fileExists(file) {
|
|
42
|
+
try { await fs.access(file); return true; } catch { return false; }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// 契约解析失败判定(单一来源):looksLikeObjectLiteral 由 state-schema.mjs 导出——
|
|
46
|
+
// trim 后以 {/[ 开头 → 视作"形似对象字面量";若 JSON.parse 失败 → fail-closed。
|
|
47
|
+
|
|
48
|
+
// --json-file 路径校验:解析后必须位于项目根内(拒绝相对/绝对形式的越界路径,
|
|
49
|
+
// 如 ../..、其他盘符——防读取任意文件内容进 evidence)。runRoot 内的绝对路径合法
|
|
50
|
+
// (场景内文件常见写法,与 record/handoff 的既有用法一致)。符号链接解析后的实际路径
|
|
51
|
+
// 同样必须在项目根内(词法校验不防 symlink 穿越——realpath 后再次校验)。
|
|
52
|
+
// 非字符串/空值(如 --json-file 为最后一个参数)→ 用法错误,不落 path.resolve
|
|
53
|
+
// (修复前 undefined 抛 TypeError、空串解析为 runRoot 报 EISDIR——报类型错误而非用法错误)
|
|
54
|
+
async function resolveJsonFileWithinRunRoot(jsonFile) {
|
|
55
|
+
if (typeof jsonFile !== 'string' || jsonFile.trim() === '') {
|
|
56
|
+
throw new Error('--json-file requires a path argument');
|
|
57
|
+
}
|
|
58
|
+
const abs = path.resolve(runRoot, jsonFile);
|
|
59
|
+
const rel = path.relative(runRoot, abs);
|
|
60
|
+
if (path.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + path.sep)) {
|
|
61
|
+
throw new Error('--json-file 路径必须在项目根内: ' + jsonFile);
|
|
62
|
+
}
|
|
63
|
+
// 统一对 runRoot 也 realpath——Windows 上 runRoot 可能是 8.3 短路径(如 LONGYI~1),
|
|
64
|
+
// realpath 会展开为长路径,两者直接 relative 会误判越界
|
|
65
|
+
const realRoot = await fs.realpath(runRoot);
|
|
66
|
+
const real = await fs.realpath(abs);
|
|
67
|
+
const realRel = path.relative(realRoot, real);
|
|
68
|
+
if (path.isAbsolute(realRel) || realRel === '..' || realRel.startsWith('..' + path.sep)) {
|
|
69
|
+
throw new Error('--json-file 路径经符号链接解析后越出项目根: ' + jsonFile);
|
|
70
|
+
}
|
|
71
|
+
return abs;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function findActiveChange() {
|
|
75
|
+
// 1. Read from state file if exists
|
|
76
|
+
if (await fileExists(statePath)) {
|
|
77
|
+
const state = await readJson(statePath);
|
|
78
|
+
// completed 检查优先于 activeChange 分支——归档完成态(无论 activeChange 是否残留)
|
|
79
|
+
// 一律不识别为 active(防归档残留目录/残留字段误判, 主修复)
|
|
80
|
+
if (state.status === 'completed') return null;
|
|
81
|
+
if (state.activeChange) {
|
|
82
|
+
const changeDir = path.join(specsRoot, state.activeChange);
|
|
83
|
+
if (await fileExists(changeDir)) return state.activeChange;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// 2. Scan .specs/ for directories with TASK.md (active flow-kit changes)
|
|
87
|
+
// 注: 曾尝试按 archive/ 对应归档跳过残留目录——但会误伤同名新 change(既有实证),已撤回。
|
|
88
|
+
// 「state 缺失 + 归档残留」为已知限制(对比报告已记录"捡残留桩"共性问题);归档后正常态由
|
|
89
|
+
// 上文 completed 分支覆盖( 主修复)
|
|
90
|
+
try {
|
|
91
|
+
const entries = await fs.readdir(specsRoot, { withFileTypes: true });
|
|
92
|
+
const candidates = [];
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
if (!entry.isDirectory() || entry.name === 'archive' || entry.name === 'health' || entry.name === 'evolve' || entry.name === 'adr') continue;
|
|
95
|
+
const taskFile = path.join(specsRoot, entry.name, 'TASK.md');
|
|
96
|
+
if (await fileExists(taskFile)) candidates.push(entry.name);
|
|
97
|
+
}
|
|
98
|
+
if (candidates.length === 1) return candidates[0];
|
|
99
|
+
if (candidates.length > 1) {
|
|
100
|
+
// Return the most recently modified
|
|
101
|
+
const withTime = await Promise.all(candidates.map(async c => ({
|
|
102
|
+
name: c,
|
|
103
|
+
mtime: (await fs.stat(path.join(specsRoot, c, 'TASK.md'))).mtimeMs
|
|
104
|
+
})));
|
|
105
|
+
withTime.sort((a, b) => b.mtime - a.mtime);
|
|
106
|
+
return withTime[0].name;
|
|
107
|
+
}
|
|
108
|
+
} catch {}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---------- skill-load 声明标记(completedChecks 真实性校验配套) ----------
|
|
113
|
+
|
|
114
|
+
// --prompt 原始参数提取(skill-load 专用参数):--protocol 由 resolveProtocol 全局解析
|
|
115
|
+
// (CLI > env > 默认)为工作流协议 JSON——skill-load 曾用 --protocol 传 prompt 路径,主仓真实链路
|
|
116
|
+
// 必现撞车(markdown 被当协议 JSON 解析 → 启动报错「workflow protocol file is not valid JSON」,
|
|
117
|
+
// 已实证)。改名 --prompt 后与全局协议解析彻底解耦;此处仅取用户显式传入的原始值,供 skill-load
|
|
118
|
+
// 的 flow-kit/prompts/ 归属校验与标记记录。
|
|
119
|
+
function findPromptArg(cliArgs) {
|
|
120
|
+
for (let index = 0; index < cliArgs.length; index++) {
|
|
121
|
+
const arg = cliArgs[index];
|
|
122
|
+
if (arg === '--prompt') {
|
|
123
|
+
const value = cliArgs[index + 1];
|
|
124
|
+
if (typeof value !== 'string' || value === '') return null;
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
if (typeof arg === 'string' && arg.startsWith('--prompt=')) {
|
|
128
|
+
const value = arg.slice('--prompt='.length);
|
|
129
|
+
return value === '' ? null : value;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// flow-kit/prompts/ 归属校验(相对或绝对路径,前缀校验)——flow-kit 为 vendored 上游,
|
|
136
|
+
// 协议提示只读引用;skill-load 声明的 --prompt 必须位于其 prompts 目录下。
|
|
137
|
+
// 相对路径:字符串前缀必须为 flow-kit/prompts/;绝对路径:路径段中必须含 flow-kit/prompts。
|
|
138
|
+
function protocolUnderFlowKitPrompts(value) {
|
|
139
|
+
const normalized = String(value).replaceAll('\\', '/');
|
|
140
|
+
if (!path.isAbsolute(value)) {
|
|
141
|
+
return normalized.startsWith('flow-kit/prompts/');
|
|
142
|
+
}
|
|
143
|
+
const segments = normalized.split('/').filter((s) => s !== '');
|
|
144
|
+
for (let index = 0; index <= segments.length - 2; index++) {
|
|
145
|
+
if (segments[index] === 'flow-kit' && segments[index + 1] === 'prompts') return true;
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// requiredSkillCalls scope 分类——按协议 requiredSkillCalls 查 <node>.<skill> 绑定:
|
|
151
|
+
// main scope = 协调者加载(如 flow-comet-subagent-execute),要求协调者 skill-load 标记;
|
|
152
|
+
// handoff scope = 子代理加载(如 subagent-execute 节点的 flow-comet-dev),协调者不加载它。
|
|
153
|
+
// 协议外条目(无绑定 / 非 main / 非 handoff scope)→ null(fail-closed:仍按 main 处理要标记)。
|
|
154
|
+
function findRequiredSkillBinding(protocol, nodeId, skillName) {
|
|
155
|
+
const node = (protocol.nodes ?? []).find((n) => n.id === nodeId);
|
|
156
|
+
if (!node) return null;
|
|
157
|
+
return (node.requiredSkillCalls ?? []).find((binding) => binding.skill === skillName) ?? null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 标记目录解析——活动路径 .specs/<change-id>/.skill-loads/ 优先;归档路径兜底
|
|
161
|
+
// (archive 节点「先移目录后 record/exit」顺序下 change 目录已在 .specs/archive/<前缀>-<change-id>/,
|
|
162
|
+
// 标记只随目录移动——只查活动路径会误报缺失)。归档扫描匹配后缀 -<change-id>(前缀可含日期等,
|
|
163
|
+
// 与协议 flowkit.archive.v1 的 archive/*-<change-id> artifact 路径同构)。两者皆无 → null。
|
|
164
|
+
async function findSkillLoadsDir(changeName) {
|
|
165
|
+
const activeDir = path.join(specsRoot, changeName, '.skill-loads');
|
|
166
|
+
if (await fileExists(activeDir)) {
|
|
167
|
+
return { dir: activeDir, display: '.specs/' + changeName + '/.skill-loads/' };
|
|
168
|
+
}
|
|
169
|
+
const archiveRoot = path.join(specsRoot, 'archive');
|
|
170
|
+
const entries = await fs.readdir(archiveRoot).catch(() => []);
|
|
171
|
+
for (const entry of entries) {
|
|
172
|
+
if (!entry.endsWith('-' + changeName)) continue;
|
|
173
|
+
const candidate = path.join(archiveRoot, entry, '.skill-loads');
|
|
174
|
+
if (await fileExists(candidate)) {
|
|
175
|
+
return { dir: candidate, display: '.specs/archive/' + entry + '/.skill-loads/' };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// completedChecks 真实性校验。解析 completedChecks 的 required-skill:<node>.<skill>
|
|
182
|
+
// 条目 → 对应声明标记 .specs/<change-id>/.skill-loads/<node>-<skill>.json 必须存在(内置节点常量,缺失 →
|
|
183
|
+
// BLOCKED + 指引先加载 skill 并运行 skill-load);标记 at 必须 ≤ 本次记录时间(交叉自洽:
|
|
184
|
+
// 标记先于记录声明;ISO-8601 UTC 字符串字典序 = 时间序)。仅校验本次 record 写入的
|
|
185
|
+
// completedChecks(旧 change 兼容:旧 evidence 不追溯——由调用方只传本次 parsed.completedChecks)。
|
|
186
|
+
// 条目按协议 requiredSkillCalls scope 分类——handoff scope 条目(子代理加载的 skill,
|
|
187
|
+
// 如 subagent-execute 节点的 flow-comet-dev)豁免标记,以共用证据库 evidence['subagent-execute']
|
|
188
|
+
// 的 handoffResult(有委托记录即满足)为证据;main scope / 协议外条目仍要求标记(fail-closed)。
|
|
189
|
+
// 诚实边界:标记是"声明"而非物理证明——运行时没有 Skill 调用观察点,脚本无法确认执行者
|
|
190
|
+
// 真实加载过该 skill;标记仅证明"执行者主动声明已加载",由流程纪律兜底。handoff 条目的证据
|
|
191
|
+
// 同样不是物理证明——它是子代理回传的 Return Contract 委托声明(子代理自称已加载并执行),
|
|
192
|
+
// 由 handoff result 的 commitHash/greenEvidence 审计性兜底。
|
|
193
|
+
// 返回 { ok: true } 或 { ok: false, reason }(fail-closed:无 active change / 标记损坏同样 BLOCK)。
|
|
194
|
+
// 节点技能加载声明标记存在性(技能加载前置门·方案 A):校验 .skill-loads/ 下
|
|
195
|
+
// 是否有该节点的声明标记 <node>-*.json(任一 skill 标记即算已声明——与 guard exit 侧的
|
|
196
|
+
// 「exit 协议声明标记校验」同构:按 <node>- 前缀扫描;活动路径优先,归档路径兜底)。
|
|
197
|
+
// 记录/委托前置门在「先加载技能(Skill 工具)并 skill-load 声明」之前拦截"先干活后补声明"。
|
|
198
|
+
// 诚实边界:标记是执行者自我声明,非物理证明(与 verifySkillLoadMarkers 同语义)。
|
|
199
|
+
async function hasNodeSkillDeclaration(nodeId, changeName) {
|
|
200
|
+
if (!nodeId || !changeName) return false;
|
|
201
|
+
const activeDir = path.join(specsRoot, changeName, '.skill-loads');
|
|
202
|
+
const prefix = nodeId + '-';
|
|
203
|
+
const scan = async (dir) => {
|
|
204
|
+
try {
|
|
205
|
+
const entries = await fs.readdir(dir);
|
|
206
|
+
return entries.some((f) => f.startsWith(prefix) && f.endsWith('.json'));
|
|
207
|
+
} catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
if (await scan(activeDir)) return true;
|
|
212
|
+
const archived = await findSkillLoadsDir(changeName);
|
|
213
|
+
if (archived !== null && archived.dir !== activeDir) return scan(archived.dir);
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function verifySkillLoadMarkers(completedChecks, changeName, recordTime, protocol, state) {
|
|
218
|
+
if (!Array.isArray(completedChecks)) return { ok: true };
|
|
219
|
+
const required = [];
|
|
220
|
+
for (const check of completedChecks) {
|
|
221
|
+
if (typeof check !== 'string' || !check.startsWith('required-skill:')) continue;
|
|
222
|
+
const spec = check.slice('required-skill:'.length);
|
|
223
|
+
const dot = spec.lastIndexOf('.');
|
|
224
|
+
if (dot <= 0 || dot === spec.length - 1) {
|
|
225
|
+
return { ok: false, reason: 'completedChecks 条目格式非法(应为 required-skill:<node>.<skill>): ' + check };
|
|
226
|
+
}
|
|
227
|
+
required.push({ raw: check, node: spec.slice(0, dot), skill: spec.slice(dot + 1) });
|
|
228
|
+
}
|
|
229
|
+
if (required.length === 0) return { ok: true };
|
|
230
|
+
if (!changeName) {
|
|
231
|
+
return { ok: false, reason: 'completedChecks 含 required-skill 条目但无 active change——无法定位声明标记(先运行 init <change-id>)' };
|
|
232
|
+
}
|
|
233
|
+
for (const item of required) {
|
|
234
|
+
// handoff scope 条目豁免标记——子代理加载的 skill(协调者不加载它,无法诚实
|
|
235
|
+
// 声明加载),以共用证据库 handoffResult 的委托记录为证据;无委托记录 → BLOCK(不静默
|
|
236
|
+
// 放行,指引先委托并回传 handoff result)
|
|
237
|
+
const binding = findRequiredSkillBinding(protocol, item.node, item.skill);
|
|
238
|
+
if (binding && binding.scope === 'handoff') {
|
|
239
|
+
const handoff = state?.evidence?.['subagent-execute']?.handoffResult;
|
|
240
|
+
const hasDelegation = !!(
|
|
241
|
+
handoff &&
|
|
242
|
+
typeof handoff === 'object' &&
|
|
243
|
+
!Array.isArray(handoff) &&
|
|
244
|
+
Object.keys(handoff).length > 0
|
|
245
|
+
);
|
|
246
|
+
if (!hasDelegation) {
|
|
247
|
+
return {
|
|
248
|
+
ok: false,
|
|
249
|
+
reason: 'completedChecks 条目 ' + item.raw + ' 为 handoff scope(' + item.node +
|
|
250
|
+
' 节点的 ' + item.skill + ' 由子代理加载,协调者无需 skill-load 标记)但共用证据库' +
|
|
251
|
+
' evidence[subagent-execute].handoffResult 无委托记录——先委托子代理并回传 Return Contract(workflow-handoff.mjs result <task-id> <contract>)',
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
// 标记路径解析——活动路径优先,归档路径兜底(archive 节点「先移目录后 record」
|
|
257
|
+
// 顺序下标记只在 .specs/archive/*-<change-id>/.skill-loads/);两处都找不到 → BLOCK + 指引
|
|
258
|
+
// (不静默放行)。展示路径补 .specs/ 前缀便于用户定位。
|
|
259
|
+
const markerName = item.node + '-' + item.skill + '.json';
|
|
260
|
+
const activeDisplay = '.specs/' + path.posix.join(changeName, '.skill-loads', markerName);
|
|
261
|
+
const activePath = path.join(specsRoot, changeName, '.skill-loads', markerName);
|
|
262
|
+
let markerPath = await fileExists(activePath) ? activePath : null;
|
|
263
|
+
let markerDisplay = activeDisplay;
|
|
264
|
+
if (!markerPath) {
|
|
265
|
+
const loadsDir = await findSkillLoadsDir(changeName);
|
|
266
|
+
if (loadsDir !== null) {
|
|
267
|
+
const altPath = path.join(loadsDir.dir, markerName);
|
|
268
|
+
if (await fileExists(altPath)) {
|
|
269
|
+
markerPath = altPath;
|
|
270
|
+
markerDisplay = loadsDir.display + markerName;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (!markerPath) {
|
|
275
|
+
return {
|
|
276
|
+
ok: false,
|
|
277
|
+
reason: 'completedChecks 条目 ' + item.raw + ' 缺少对应声明标记 ' + activeDisplay +
|
|
278
|
+
'(归档路径也未找到)——先加载该 skill 并运行 workflow-state.mjs skill-load ' + item.node + ' ' + item.skill,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
let marker;
|
|
282
|
+
try {
|
|
283
|
+
marker = await readJson(markerPath);
|
|
284
|
+
} catch {
|
|
285
|
+
return { ok: false, reason: '声明标记损坏(非法 JSON,需重新运行 skill-load): ' + markerDisplay };
|
|
286
|
+
}
|
|
287
|
+
// 交叉自洽——标记 at 必须 ≤ 本次记录时间(标记先于记录声明)
|
|
288
|
+
if (typeof marker.at !== 'string' || marker.at > recordTime) {
|
|
289
|
+
return {
|
|
290
|
+
ok: false,
|
|
291
|
+
reason: '声明标记时间序非法(标记 at=' + JSON.stringify(marker.at) + ' 不早于本次记录时间 ' + recordTime +
|
|
292
|
+
')——标记必须先于记录声明(重新运行 skill-load)',
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return { ok: true };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ---------- 节点完成判定 · determineNode 数据化:完成标志从协议 outputSchemas 推导 ----------
|
|
300
|
+
// (节点完成判定核心抽取 · 依赖感知路由): 节点完成判定核心已迁至共享模块 route-node.mjs——
|
|
301
|
+
// determineNode 保持既有签名与返回语义,仅改为委托 resolveNextNode(行为逐字等价,重构保持锚:
|
|
302
|
+
// 输出与抽取前 200 版一致)。route / buildNodeCompletionFlags / pathPatternExists / nodeFlagsComplete /
|
|
303
|
+
// protocolTaskFilePath / hasSubagentNode 已随抽取移至 route-node.mjs(单一实现,根治 guard 与
|
|
304
|
+
// 状态机双实现漂移的根治(单一实现决策)。
|
|
305
|
+
async function determineNode(changeName, protocol, completedNodes = []) {
|
|
306
|
+
return resolveNextNode({ runRoot, changeName, protocol, completedNodes });
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// 回退修复豁免判定——回退修复标准路径:review/verify 阶段发现缺陷 → TASK.md 追加
|
|
310
|
+
// pending 回退任务 → next 回 execute。三条件全满足才豁免(否则维持严格 BLOCK):
|
|
311
|
+
// ① currentNode 为 review/verify(回退修复源节点);② TASK.md 存在 status="pending" 任务块;
|
|
312
|
+
// ③ determineNode 推导为 execute(回退目标)。任一不满足 → 不豁免,保持严格拦截。
|
|
313
|
+
async function tFixRollbackExempt(changeName, protocol, currentNode, completedNodes) {
|
|
314
|
+
if (currentNode !== 'review' && currentNode !== 'verify') return false;
|
|
315
|
+
const taskPath = path.join(specsRoot, changeName, 'TASK.md');
|
|
316
|
+
try {
|
|
317
|
+
const taskContent = await fs.readFile(taskPath, 'utf8');
|
|
318
|
+
// 开标签解析(与 determineNode 同一语义):存在任一 status="pending" 任务块
|
|
319
|
+
if (!taskBlocks(taskContent).some((b) => {
|
|
320
|
+
const a = taskOpeningAttrs(b);
|
|
321
|
+
return a && a.status === 'pending';
|
|
322
|
+
})) return false;
|
|
323
|
+
return (await determineNode(changeName, protocol, completedNodes)) === 'execute';
|
|
324
|
+
} catch {
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// 正常推进豁免判定——exit --apply 会把 currentNode 推进到下一节点(如 open exit 后
|
|
330
|
+
// currentNode=design,该节点尚未开始故 evidence 无记录),随后按 SKILL 协议调 next(正常路径)
|
|
331
|
+
// 不应被 误拦为"疑似未 exit"。判定三条件:① completedNodes 非空;② 最后一个已完成节点
|
|
332
|
+
// 存在 evidence(exit --apply 必须带证据通过——证据存在证明该 exit 真实发生,排除伪造/漂移状态,
|
|
333
|
+
// 如 review 无 evidence);③ currentNode 是下一个合法路由目标——**路由后继优先**(exit --apply
|
|
334
|
+
// 把 currentNode 推进到共享路由判定 resolveNextNode 的结果,平行转换 plan→subagent-execute、
|
|
335
|
+
// 趟间回流 subagent-execute→execute 等即由此产生;next 正常推进豁免识别路由后继,与 guard
|
|
336
|
+
// NEXT 同源),静态直接后继兜底(串行推进原语义,旧态/序列流不回归)。与 回退豁免独立判断
|
|
337
|
+
// (回退 = TASK.md 有 pending 回退修复任务;本豁免 = 正常推进后继)。真乱序(currentNode
|
|
338
|
+
// 既非路由后继也非静态后继)仍维持 严格 BLOCK。
|
|
339
|
+
async function normalAdvanceExempt(state, protocol, completedNodes, currentNode, changeName) {
|
|
340
|
+
if (completedNodes.length === 0) return false;
|
|
341
|
+
const lastNodeId = completedNodes[completedNodes.length - 1];
|
|
342
|
+
const routeIds = route(protocol).map((node) => node.id);
|
|
343
|
+
const lastIdx = routeIds.indexOf(lastNodeId);
|
|
344
|
+
if (lastIdx < 0) return false;
|
|
345
|
+
const lastEvidence = state.evidence && typeof state.evidence === 'object'
|
|
346
|
+
? state.evidence[lastNodeId]
|
|
347
|
+
: null;
|
|
348
|
+
// 审查补充(2026-08-08):evidence 必须是对象且含非空 summary(空对象 {} 可绕过豁免,
|
|
349
|
+
// 真实流程 exit 强制 summary——此处严格化防止手动修改 state 绕过)
|
|
350
|
+
const hasExitEvidence = !!(
|
|
351
|
+
lastEvidence &&
|
|
352
|
+
typeof lastEvidence === 'object' &&
|
|
353
|
+
!Array.isArray(lastEvidence) &&
|
|
354
|
+
typeof lastEvidence.summary === 'string' &&
|
|
355
|
+
lastEvidence.summary.trim() !== ''
|
|
356
|
+
);
|
|
357
|
+
if (!hasExitEvidence) return false;
|
|
358
|
+
// 路由后继判定(与 guard 出口同源):currentNode === resolveNextNode(completedNodes) 即
|
|
359
|
+
// 正常推进后的下一路由目标(含平行转换与趟间回流);文件推导失败(异常态)不豁免。
|
|
360
|
+
try {
|
|
361
|
+
const routingNext = await determineNode(changeName, protocol, completedNodes);
|
|
362
|
+
if (routingNext === currentNode) return true;
|
|
363
|
+
} catch {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
// 静态直接后继兜底(串行推进原语义,向后兼容旧态不回归)
|
|
367
|
+
return lastIdx + 1 < routeIds.length && routeIds[lastIdx + 1] === currentNode;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async function readState() {
|
|
371
|
+
if (await fileExists(statePath)) {
|
|
372
|
+
const st = await readJson(statePath);
|
|
373
|
+
// 兼容旧 state:无 executionMode / directOverride 时补默认(subagent 默认,direct 是显式逃生口)
|
|
374
|
+
if (st.executionMode === undefined) st.executionMode = 'subagent';
|
|
375
|
+
if (st.directOverride === undefined) st.directOverride = false;
|
|
376
|
+
// E1: branchMode 默认 true(git 仓库时 init 会判定为 true;非 git 仓库 init 纠正为 false;
|
|
377
|
+
// status/next 显示以实时 git 检测为准——非 git 仓库显示 BRANCH: none)
|
|
378
|
+
if (st.branchMode === undefined) st.branchMode = true;
|
|
379
|
+
if (st.enablePrReview === undefined) st.enablePrReview = false;
|
|
380
|
+
// 分支前缀(init --branch-prefix 记录;旧 state 缺省 'change/' 向后兼容)
|
|
381
|
+
if (st.branchPrefix === undefined) st.branchPrefix = 'change/';
|
|
382
|
+
return st;
|
|
383
|
+
}
|
|
384
|
+
return { activeChange: null, currentNode: null, completedNodes: [], evidence: {}, verifyFailures: 0, executionMode: 'subagent', directOverride: false, branchMode: true, enablePrReview: false };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// ---------- E1 · 分支模式辅助(git 仓库检测 + 分支名) ----------
|
|
388
|
+
|
|
389
|
+
// git 仓库检测:`git rev-parse --is-inside-work-tree` 成功且输出 true
|
|
390
|
+
function isInsideWorkTree() {
|
|
391
|
+
try {
|
|
392
|
+
const out = execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' });
|
|
393
|
+
return String(out).trim() === 'true';
|
|
394
|
+
} catch {
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// 当前分支名;非 git 仓库 / detached HEAD 失败 → null
|
|
400
|
+
function gitBranchName() {
|
|
401
|
+
try {
|
|
402
|
+
const out = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' });
|
|
403
|
+
return String(out).trim() || null;
|
|
404
|
+
} catch {
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// 分支是否存在(本地分支)
|
|
410
|
+
function branchExists(name) {
|
|
411
|
+
try {
|
|
412
|
+
const out = execFileSync('git', ['branch', '--format', '%(refname:short)'], { cwd: runRoot, stdio: 'pipe', encoding: 'utf8' });
|
|
413
|
+
return String(out).split('\n').map(s => s.trim()).includes(name);
|
|
414
|
+
} catch {
|
|
415
|
+
return false;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// E1: status/next 追加分支信息——BRANCH: <当前分支> | 一致性: ok|mismatch
|
|
420
|
+
// mismatch(activeChange 存在但当前分支不是 change/<activeChange>)→ WARN 不 BLOCK;非 git 仓库 → BRANCH: none
|
|
421
|
+
function printBranchLine(activeChange, branchPrefix = 'change/') {
|
|
422
|
+
const branch = gitBranchName();
|
|
423
|
+
if (branch === null) {
|
|
424
|
+
console.log('BRANCH: none');
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const expected = branchPrefix + activeChange;
|
|
428
|
+
const consistent = branch === expected;
|
|
429
|
+
console.log('BRANCH: ' + branch + ' | 一致性: ' + (consistent ? 'ok' : 'mismatch'));
|
|
430
|
+
if (!consistent) {
|
|
431
|
+
console.error('WARN: 分支与 activeChange 不一致——先 git checkout ' + expected + ' 再继续');
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// C6: writeState 写入前校验已知字段类型(fail-closed:非法 → BLOCKED 拒绝写入,不修复不猜测)
|
|
436
|
+
// 未知字段允许(前向兼容);缺字段允许(readState 默认补);只校验存在字段的类型。
|
|
437
|
+
// 内置节点常量: 校验表已迁移到 state-schema.mjs(唯一来源),行为与批次 C C6 完全一致(对第一个非法字段输出后退出)
|
|
438
|
+
async function writeState(state) {
|
|
439
|
+
const bad = validateStateFields(state);
|
|
440
|
+
if (bad.length) {
|
|
441
|
+
console.error('BLOCKED: state 字段类型非法: ' + bad[0]);
|
|
442
|
+
process.exit(1);
|
|
443
|
+
}
|
|
444
|
+
await writeJson(statePath, state);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function generatedNodeSkillName(protocol, nodeId) {
|
|
448
|
+
return protocol.name + '-' + nodeId;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function printNext(protocol, nodeId, executionMode = 'subagent') {
|
|
452
|
+
if (!nodeId) {
|
|
453
|
+
console.log('NEXT: done');
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
console.log('NEXT: auto');
|
|
457
|
+
console.log('NODE: ' + nodeId);
|
|
458
|
+
console.log('SKILL: ' + generatedNodeSkillName(protocol, nodeId));
|
|
459
|
+
// 输出点名(机器点名下一节点技能):下一节点实现技能必须经 Skill 工具加载——
|
|
460
|
+
// skill 名取节点实现 skill(与 SKILL: 行一致;内置协议 = flow-comet-open 等)
|
|
461
|
+
const implNode = (protocol.nodes ?? []).find((n) => n.id === nodeId);
|
|
462
|
+
const implSkill = implNode && typeof implNode.implementation === 'object' && implNode.implementation !== null
|
|
463
|
+
? implNode.implementation.skill
|
|
464
|
+
: null;
|
|
465
|
+
if (implSkill) {
|
|
466
|
+
console.log('LOAD SKILL: ' + implSkill + '(用 Skill 工具,禁止跳过)');
|
|
467
|
+
}
|
|
468
|
+
if (nodeId === 'execute' || nodeId === 'subagent-execute') {
|
|
469
|
+
if (executionMode === 'direct' && nodeId === 'execute') {
|
|
470
|
+
console.log('EXECUTION-MODE: direct(主代理直接执行串行任务,必须加载 flow-comet-dev 完整协议;parallel 任务仍由 subagent-execute 委托)');
|
|
471
|
+
} else {
|
|
472
|
+
console.log('COORDINATOR: 你是协调者,不是执行者。禁止在主会话直接修改源码;只能通过 Agent 工具 worktree isolation 委托子代理;子代理回传后仅更新 TASK.md / SUMMARY / handoff evidence。');
|
|
473
|
+
console.log('EXECUTION-MODE: ' + (executionMode === 'direct' ? 'direct' : 'subagent'));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ---------- bridge-check(只读 dsh 桥接健康检查 · 六判定态) ----------
|
|
479
|
+
|
|
480
|
+
// 版本戳锚点正则(契约定稿见 T02-SUMMARY「版本戳标记行格式契约」/ DESIGN §9.3):
|
|
481
|
+
// 独立整行、行首无缩进、冒号后恰一个空格、行尾无其它字符。格式禁动(§9.5)。
|
|
482
|
+
const BRIDGE_VERSION_RE = /^\/\/ BRIDGE_VERSION: ([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)$/m;
|
|
483
|
+
|
|
484
|
+
// $DSH_HOME 解析——与 prepare-env.mjs resolveDshHome 同语义(显式 DSH_HOME > ~/.dsh)。
|
|
485
|
+
// 安装器函数位于仓库根 scripts/,技能包脚本不能跨模块 import,语义复刻保持单点契约
|
|
486
|
+
// (套件断言保证双侧不漂移)。
|
|
487
|
+
function resolveDshHomeForBridgeCheck() {
|
|
488
|
+
if (process.env.DSH_HOME) return path.resolve(process.env.DSH_HOME);
|
|
489
|
+
return path.join(os.homedir(), '.dsh');
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// cordis.patch.yml 托管块标记——与 prepare-env.mjs MANAGED_CORDIS_START/END 同值复刻
|
|
493
|
+
// (技能包自包含;标记为安装器读-合并-写幂等替换边界,格式禁动)。
|
|
494
|
+
const MANAGED_CORDIS_START = '# --- flow-comet managed ---';
|
|
495
|
+
const MANAGED_CORDIS_END = '# --- end flow-comet managed ---';
|
|
496
|
+
|
|
497
|
+
// 判定态:健康 / 不适用 / 文件缺失 / 未挂载 / 版本偏斜 / 重复注册。
|
|
498
|
+
// 严格只读零写入零网络;失配(FAIL)exit 非 0;无法识别形态 → 近似性声明告警(WARN)
|
|
499
|
+
// 不定论不误杀(行扫描对无法识别形态的手写极端 YAML 只告警不定论,不误判为失配;
|
|
500
|
+
// 仅明确失配才强制非零退出)。
|
|
501
|
+
async function runBridgeCheck() {
|
|
502
|
+
const report = { pass: [], warn: [], fail: [] };
|
|
503
|
+
// ⑥ 非 dsh 项目 →「不适用」exit 0(AC-11):会话项目根无 .dsh/skills/flow-comet
|
|
504
|
+
// (未安装 dsh 平台副本)即不适用,其余检查全部跳过。
|
|
505
|
+
if (!(await fileExists(path.join(runRoot, '.dsh', 'skills', 'flow-comet')))) {
|
|
506
|
+
console.log('[NA] bridge-check: 不适用(本项目未安装 dsh 平台副本)——项目根无 .dsh/skills/flow-comet');
|
|
507
|
+
console.log('bridge-check: 不适用(exit 0)');
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const dshHome = resolveDshHomeForBridgeCheck();
|
|
512
|
+
const loaderPath = path.join(dshHome, 'plugins', 'dsh-flow-comet-bridge.mjs');
|
|
513
|
+
const patchPath = path.join(dshHome, 'cordis.patch.yml');
|
|
514
|
+
const installedVersionPath = path.join(__dirname, '..', 'INSTALLED_VERSION');
|
|
515
|
+
|
|
516
|
+
// ① loader 文件存在性($DSH_HOME/plugins/dsh-flow-comet-bridge.mjs)
|
|
517
|
+
const loaderExists = await fileExists(loaderPath);
|
|
518
|
+
if (loaderExists) {
|
|
519
|
+
report.pass.push('loader 文件存在: ' + loaderPath);
|
|
520
|
+
} else {
|
|
521
|
+
report.fail.push('loader 文件缺失: ' + loaderPath);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// ② cordis.patch.yml 托管块存在性与 insert 形态(含 - insert: 与 name: 'file://…';
|
|
525
|
+
// L-048:id-targeted patch 形态无 insert → 确认为错误形态失配)
|
|
526
|
+
// + ③ 块内 file:// 目标可达
|
|
527
|
+
let patchContent = null;
|
|
528
|
+
try {
|
|
529
|
+
patchContent = await fs.readFile(patchPath, 'utf8');
|
|
530
|
+
} catch {
|
|
531
|
+
patchContent = null;
|
|
532
|
+
}
|
|
533
|
+
if (patchContent === null) {
|
|
534
|
+
report.fail.push(
|
|
535
|
+
'未挂载: ' + patchPath + ' 不存在——' +
|
|
536
|
+
(loaderExists ? 'loader 存在但未挂载(不会监听任何项目)' : '托管块无从指向 loader')
|
|
537
|
+
);
|
|
538
|
+
} else {
|
|
539
|
+
const startIdx = patchContent.indexOf(MANAGED_CORDIS_START);
|
|
540
|
+
const endIdx = patchContent.indexOf(MANAGED_CORDIS_END);
|
|
541
|
+
if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {
|
|
542
|
+
report.fail.push(
|
|
543
|
+
'未挂载: ' + patchPath + ' 中不存在托管块(' + MANAGED_CORDIS_START + ' … ' + MANAGED_CORDIS_END +
|
|
544
|
+
')——' + (loaderExists ? 'loader 存在但未挂载(不会监听任何项目)' : '')
|
|
545
|
+
);
|
|
546
|
+
} else {
|
|
547
|
+
// 块内容 = 起始标记行尾之后、结束标记之前
|
|
548
|
+
let blockStart = patchContent.indexOf('\n', startIdx);
|
|
549
|
+
blockStart = blockStart === -1 ? endIdx : blockStart + 1;
|
|
550
|
+
const block = patchContent.slice(blockStart, endIdx);
|
|
551
|
+
const hasInsert = /^\s*- insert:\s*$/m.test(block);
|
|
552
|
+
const fileUrlMatch = /name:\s*'file:\/\/([^']+)'/.exec(block);
|
|
553
|
+
const hasIdLine = /^\s*- id:\s*dsh-flow-comet-bridge\s*$/m.test(block);
|
|
554
|
+
|
|
555
|
+
if (hasInsert && fileUrlMatch) {
|
|
556
|
+
report.pass.push('cordis.patch.yml 托管块: 存在且 insert 形态(含 - insert: 与 name: \'file://…\')');
|
|
557
|
+
// ③ file:// 目标可达性(捕获组含 file:// 后的整段——'file://' + 捕获即完整 URL;
|
|
558
|
+
// fileURLToPath 按平台归一 Windows 盘符与 POSIX 根路径)
|
|
559
|
+
let targetPath = null;
|
|
560
|
+
try {
|
|
561
|
+
targetPath = fileURLToPath('file://' + fileUrlMatch[1]);
|
|
562
|
+
} catch (error) {
|
|
563
|
+
targetPath = null;
|
|
564
|
+
}
|
|
565
|
+
if (targetPath === null) {
|
|
566
|
+
report.warn.push('近似性声明: 托管块 file:// 引用无法解析为本地路径(' + fileUrlMatch[0] + ')——无法核验目标可达性,不定论');
|
|
567
|
+
} else if (await fileExists(targetPath)) {
|
|
568
|
+
if (targetPath === loaderPath) {
|
|
569
|
+
report.pass.push('块内 file:// 目标可达且与期望 loader 路径一致: ' + targetPath);
|
|
570
|
+
} else {
|
|
571
|
+
report.fail.push('托管块 file:// 目标与期望 loader 路径不符: ' + targetPath + ' ≠ ' + loaderPath);
|
|
572
|
+
}
|
|
573
|
+
} else {
|
|
574
|
+
report.fail.push('托管块指向的 loader 文件缺失: ' + targetPath + '(file:// 目标不可达)');
|
|
575
|
+
}
|
|
576
|
+
} else if (hasInsert && !fileUrlMatch) {
|
|
577
|
+
// insert 形态在但无 name: 'file://…' 行——部分可识别、目标不可核验:
|
|
578
|
+
// 近似性声明告警,不定论不误杀(不 forced 非零)
|
|
579
|
+
report.warn.push('近似性声明: 托管块为 insert 形态但未识别到 name: \'file://…\' 行——无法核验 file:// 目标是否可达,不定论');
|
|
580
|
+
} else if (hasIdLine && !hasInsert) {
|
|
581
|
+
// L-048 确认形态:id-targeted patch(- id: ... 无 - insert:)——
|
|
582
|
+
// dsh applyEntryPatches 对不存在的 id 报 entry not found 并跳过,loader 不会加载
|
|
583
|
+
report.fail.push('托管块为 id-targeted patch 形态(含 - id: dsh-flow-comet-bridge 但无 - insert:)——确认为错误形态失配(dsh 不会加载该 loader)');
|
|
584
|
+
} else {
|
|
585
|
+
report.warn.push('近似性声明: 托管块内容无法识别为已知形态(未见 - insert: / - id: dsh-flow-comet-bridge / name: \'file://…\')——不判失配,不定论');
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// ④ 托管块外同 id 重复注册(AC-10b;块内安装器写入的固有条目不计)
|
|
591
|
+
let outside = '';
|
|
592
|
+
if (patchContent !== null) {
|
|
593
|
+
if (patchContent.includes(MANAGED_CORDIS_START) && patchContent.includes(MANAGED_CORDIS_END)) {
|
|
594
|
+
const sIdx = patchContent.indexOf(MANAGED_CORDIS_START);
|
|
595
|
+
const eIdx = patchContent.indexOf(MANAGED_CORDIS_END);
|
|
596
|
+
outside = patchContent.slice(0, sIdx) + patchContent.slice(eIdx + MANAGED_CORDIS_END.length);
|
|
597
|
+
} else {
|
|
598
|
+
outside = patchContent; // 无托管块:全文件视为块外
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const dupMatches = outside.match(/^\s*-\s+id:\s*['"]?dsh-flow-comet-bridge['"]?\s*$/gm) ?? [];
|
|
602
|
+
if (dupMatches.length > 0) {
|
|
603
|
+
report.fail.push('重复注册: cordis.patch.yml 托管块外另有 ' + dupMatches.length + ' 处同 id 注册行(dsh-flow-comet-bridge)——可能重复加载');
|
|
604
|
+
} else {
|
|
605
|
+
report.pass.push('重复注册检查: 托管块外无同 id(dsh-flow-comet-bridge)注册行');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// ⑤ loader BRIDGE_VERSION 戳 vs 项目 INSTALLED_VERSION 偏斜(两值都打印;
|
|
609
|
+
// 契约锚点正则见 T02-SUMMARY「版本戳标记行格式契约」)
|
|
610
|
+
let loaderStamp = null;
|
|
611
|
+
let installedVersion = null;
|
|
612
|
+
if (loaderExists) {
|
|
613
|
+
try {
|
|
614
|
+
const loaderText = await fs.readFile(loaderPath, 'utf8');
|
|
615
|
+
const stampMatch = BRIDGE_VERSION_RE.exec(loaderText);
|
|
616
|
+
if (stampMatch) {
|
|
617
|
+
loaderStamp = stampMatch[1];
|
|
618
|
+
} else {
|
|
619
|
+
report.warn.push('近似性声明: loader 未提取到 BRIDGE_VERSION 戳(锚点正则 /^\\/\\/ BRIDGE_VERSION: ([0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)$/m 无命中——非语义化版本标记或缺失)——无法比对版本,不定论');
|
|
620
|
+
}
|
|
621
|
+
} catch {
|
|
622
|
+
report.warn.push('近似性声明: loader 文件读取失败——无法比对版本,不定论');
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
try {
|
|
626
|
+
installedVersion = (await fs.readFile(installedVersionPath, 'utf8')).trim();
|
|
627
|
+
} catch {
|
|
628
|
+
report.warn.push('近似性声明: 无法读取项目 INSTALLED_VERSION(' + installedVersionPath + ')——无法比对版本,不定论');
|
|
629
|
+
}
|
|
630
|
+
if (loaderStamp !== null && installedVersion !== null) {
|
|
631
|
+
if (loaderStamp === installedVersion) {
|
|
632
|
+
report.pass.push('版本一致性: loader BRIDGE_VERSION=' + loaderStamp + ' == 项目 INSTALLED_VERSION=' + installedVersion);
|
|
633
|
+
} else {
|
|
634
|
+
report.fail.push('版本偏斜: loader BRIDGE_VERSION=' + loaderStamp + ' != 项目 INSTALLED_VERSION=' + installedVersion + '(两值如上)');
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// 逐项人读报告(AC-7~10:全过 exit 0 / 任一失配 exit 非 0)
|
|
639
|
+
console.log('bridge-check: 只读检查(DSH_HOME=' + dshHome + ' · 项目根=' + runRoot + ')');
|
|
640
|
+
for (const line of report.pass) console.log('[OK] ' + line);
|
|
641
|
+
for (const line of report.warn) console.log('[WARN] ' + line);
|
|
642
|
+
for (const line of report.fail) console.log('[FAIL] ' + line);
|
|
643
|
+
if (report.fail.length > 0) {
|
|
644
|
+
console.log('bridge-check: 失配 ' + report.fail.length + ' 项——exit 1');
|
|
645
|
+
process.exitCode = 1;
|
|
646
|
+
} else if (report.warn.length > 0) {
|
|
647
|
+
console.log('bridge-check: 未发现明确失配,含 ' + report.warn.length + ' 项近似性声明告警(不定论,不误杀)——exit 0');
|
|
648
|
+
} else {
|
|
649
|
+
console.log('bridge-check: 健康(全部检查通过)——exit 0');
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function main() {
|
|
654
|
+
// 协议解析: 协议加载 = resolveProtocol 解析路径 + 受保护读取 + fail-closed schema 校验
|
|
655
|
+
// (读失败/校验失败直接 throw,沿用现有错误处理风格)
|
|
656
|
+
const protocol = await readProtocolFile(runRoot, protocolPath);
|
|
657
|
+
validateProtocolSchema(protocol);
|
|
658
|
+
|
|
659
|
+
if (command === 'bridge-check') {
|
|
660
|
+
// 只读 dsh 桥接健康检查:零写入零网络;
|
|
661
|
+
// 不依赖协议/状态,直接执行后返回。
|
|
662
|
+
await runBridgeCheck();
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
if (command === 'init') {
|
|
667
|
+
const changeName = process.argv[3];
|
|
668
|
+
if (!changeName) throw new Error('init requires a change name.');
|
|
669
|
+
// trim 后校验:带前导/尾随空白的输入(如 " --help")不得绕过 flag 检测;
|
|
670
|
+
// 纯空白与缺参同义
|
|
671
|
+
const normalizedChangeName = changeName.trim();
|
|
672
|
+
if (!normalizedChangeName) throw new Error('init requires a change name.');
|
|
673
|
+
// 参数误用防护:以 -- 开头的参数(如 --help)是选项不是 change 名——报错并提示用法,
|
|
674
|
+
// 防止被当作 change id 执行(自动开 change、建分支、写状态——有破坏性)
|
|
675
|
+
if (normalizedChangeName.startsWith('--')) {
|
|
676
|
+
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]');
|
|
677
|
+
}
|
|
678
|
+
// --branch-prefix <prefix>(缺省 'change/');--init-context / --init-skip(自动初始化检测授权)
|
|
679
|
+
let branchPrefix = 'change/';
|
|
680
|
+
let initContext = false;
|
|
681
|
+
let initSkip = false;
|
|
682
|
+
const initArgs = process.argv.slice(4);
|
|
683
|
+
for (let i = 0; i < initArgs.length; i++) {
|
|
684
|
+
if (initArgs[i] === '--branch-prefix') {
|
|
685
|
+
const value = initArgs[i + 1];
|
|
686
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
687
|
+
throw new Error('--branch-prefix requires a non-empty prefix (e.g. feat/)');
|
|
688
|
+
}
|
|
689
|
+
branchPrefix = value.trim().endsWith('/') ? value.trim() : value.trim() + '/';
|
|
690
|
+
} else if (typeof initArgs[i] === 'string' && initArgs[i].startsWith('--branch-prefix=')) {
|
|
691
|
+
const value = initArgs[i].slice('--branch-prefix='.length);
|
|
692
|
+
if (value === '') {
|
|
693
|
+
throw new Error('--branch-prefix requires a non-empty prefix (e.g. feat/)');
|
|
694
|
+
}
|
|
695
|
+
branchPrefix = value.endsWith('/') ? value : value + '/';
|
|
696
|
+
} else if (initArgs[i] === '--init-context') {
|
|
697
|
+
initContext = true;
|
|
698
|
+
} else if (initArgs[i] === '--init-skip') {
|
|
699
|
+
initSkip = true;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
// 自动初始化检测(前置步骤):读旧 state(项目级字段跨 change 保留)→ 探测 → 判决 → 提示/执行
|
|
703
|
+
// 生成职责:--init-context 时 CONTEXT 缺失 → 输出 INIT-GENERATE 指引,由 agent 全量阅读生成
|
|
704
|
+
// (intel-scan 语义);生成后重跑 → 脚本校验 7 段结构 → 通过写 last_intel_scan(确定性校验)。
|
|
705
|
+
let prevState = null;
|
|
706
|
+
try { prevState = await readState(); } catch { prevState = null; }
|
|
707
|
+
const probe = await probeProject(runRoot, prevState);
|
|
708
|
+
const verdict = classify(probe, prevState);
|
|
709
|
+
let ctxValid = null; // null=未进入校验(非 init-context 或已新鲜);true/false=校验结果
|
|
710
|
+
if (initContext || initSkip) {
|
|
711
|
+
// 显式授权路径:--init-context 生成协作(agent 生成 + 脚本校验);--init-skip 记 none
|
|
712
|
+
if (initContext) {
|
|
713
|
+
// 显式 --init-context 总是校验结构(含 verdict=skip 新鲜/记忆场景)——防 CONTEXT 损坏漏检
|
|
714
|
+
let ctxExists = false;
|
|
715
|
+
try { await fs.access(path.join(runRoot, '.specs', 'CONTEXT.md')); ctxExists = true; } catch { /* 文件不存在 */ }
|
|
716
|
+
if (ctxExists) {
|
|
717
|
+
const { missingSections, formatIssues } = await validateContext(runRoot);
|
|
718
|
+
if (missingSections.length === 0 && formatIssues.length === 0) {
|
|
719
|
+
ctxValid = true;
|
|
720
|
+
if (verdict === 'skip') {
|
|
721
|
+
console.log('INIT-DONE: 项目上下文已存在且新鲜,跳过生成。');
|
|
722
|
+
} else {
|
|
723
|
+
console.log('INIT-DONE: 项目上下文(CONTEXT.md)已就绪(7 段 + 模板格式校验通过)。');
|
|
724
|
+
}
|
|
725
|
+
} else {
|
|
726
|
+
// 存在但不满足模板(缺段/格式不符/损坏)——引导 agent 重写(保留既有累积内容)
|
|
727
|
+
const problems = [...formatIssues, ...missingSections.map((s) => '缺段 ' + s)];
|
|
728
|
+
await printGenerationGuide(runRoot, probe, { rewrite: true, problems });
|
|
729
|
+
}
|
|
730
|
+
} else if (verdict !== 'skip') {
|
|
731
|
+
await printGenerationGuide(runRoot, probe);
|
|
732
|
+
}
|
|
733
|
+
// verdict=skip(记忆 A 拒绝 / 新鲜 B)且 CONTEXT 缺失 → 尊重既有决策,不输出
|
|
734
|
+
}
|
|
735
|
+
if (initSkip && !initContext) {
|
|
736
|
+
console.log('INIT-SKIPPED: 已记录跳过初始化。');
|
|
737
|
+
}
|
|
738
|
+
} else {
|
|
739
|
+
await printDetection(runRoot, probe, verdict);
|
|
740
|
+
}
|
|
741
|
+
// F(2026-08-10):init 同 id 重跑防护——.specs/<id>/ 已存在或 activeChange 相同 → WARN 不阻断
|
|
742
|
+
//(向后兼容;正常流程 init 只在 open 前执行一次,防护针对误操作清空进度)
|
|
743
|
+
let specsDirExists = false;
|
|
744
|
+
try { await fs.access(path.join(specsRoot, changeName)); specsDirExists = true; } catch { /* 目录不存在 */ }
|
|
745
|
+
if (prevState?.activeChange === changeName || specsDirExists) {
|
|
746
|
+
console.error('WARN: change ' + changeName + ' 已存在——重跑 init 将重置节点状态(completedNodes/evidence 清空)。若需继续已有 change,请用 advance/select 而非重跑 init。');
|
|
747
|
+
}
|
|
748
|
+
// E1: branchMode 自动判定——git 仓库(cwd=runRoot)→ true;非 git 仓库 → false
|
|
749
|
+
const branchMode = isInsideWorkTree();
|
|
750
|
+
const state = {
|
|
751
|
+
activeChange: changeName,
|
|
752
|
+
// currentNode 取协议首节点(内置协议 = open,行为不变;自定义协议 = 首节点,如 brainstorm)
|
|
753
|
+
currentNode: route(protocol)[0]?.id ?? 'open',
|
|
754
|
+
completedNodes: [],
|
|
755
|
+
evidence: {},
|
|
756
|
+
verifyFailures: 0,
|
|
757
|
+
// verifyFailures 按 change 存储——init 新 change 从零计数(切换 change 不串扰)
|
|
758
|
+
verifyFailuresByChange: {},
|
|
759
|
+
executionMode: 'subagent',
|
|
760
|
+
directOverride: false,
|
|
761
|
+
branchMode,
|
|
762
|
+
enablePrReview: false,
|
|
763
|
+
branchPrefix,
|
|
764
|
+
status: 'running',
|
|
765
|
+
// R6: 新 change 标记——init 即新 change(严格模式开启,不依赖 entry;旧 change 无此字段渐进兼容)
|
|
766
|
+
newChange: true,
|
|
767
|
+
// M1: 进入证据容器——entry 追加节点;R2 检测未 entry(新 change 强制)
|
|
768
|
+
enteredNodes: [],
|
|
769
|
+
createdAt: new Date().toISOString(),
|
|
770
|
+
// 项目级上下文字段跨 change 保留(迁移旧 state;--init-context 刷新扫描时间;--init-skip 记拒绝)
|
|
771
|
+
...(prevState?.ai_context_doc !== undefined ? { ai_context_doc: prevState.ai_context_doc } : {}),
|
|
772
|
+
...(initSkip ? { ai_context_doc: 'none' } : {}),
|
|
773
|
+
// last_intel_scan 仅在校验通过后写入(agent 生成 → 脚本校验 7 段 → 记录扫描时间)
|
|
774
|
+
...(ctxValid === true
|
|
775
|
+
? { last_intel_scan: new Date().toISOString() }
|
|
776
|
+
: (prevState?.last_intel_scan !== undefined ? { last_intel_scan: prevState.last_intel_scan } : {}))
|
|
777
|
+
};
|
|
778
|
+
await writeState(state);
|
|
779
|
+
// init 创建 .specs/<id>/ 目录——文件即真相从 init 起成立,findActiveChange 立即可识别
|
|
780
|
+
//(此前 init 后 next/status 报 No active change,与 SKILL 启动协议 init → next 矛盾)
|
|
781
|
+
const specsChangeDir = path.join(specsRoot, changeName);
|
|
782
|
+
await fs.mkdir(specsChangeDir, { recursive: true });
|
|
783
|
+
// E1 + : 分支创建——branchMode && 当前分支 ≠ <prefix><id> && 分支不存在 → git checkout -b
|
|
784
|
+
// 前缀由 --branch-prefix 指定(缺省 'change/',向后兼容;可适配仓库自身分支规范如 feat/)
|
|
785
|
+
// 失败 → WARN 不 BLOCK,继续纯文件模式(向后兼容)
|
|
786
|
+
const expectedBranch = branchPrefix + changeName;
|
|
787
|
+
// 空仓库状态(带到 BRANCH 输出——声称与实际一致:空仓库无分支)
|
|
788
|
+
let emptyRepo = false;
|
|
789
|
+
if (branchMode) {
|
|
790
|
+
const currentBranch = gitBranchName();
|
|
791
|
+
// M8: 空仓库检测——无提交(git rev-parse HEAD 失败)时分支创建不可行,输出提示
|
|
792
|
+
// (不 BLOCK;纯文件模式继续)并跳过分支创建——警告与行为一致(修复前 BRANCH 行
|
|
793
|
+
// 仍声称分支已创建,与实际矛盾)
|
|
794
|
+
try {
|
|
795
|
+
execFileSync('git', ['rev-parse', 'HEAD'], { cwd: runRoot, stdio: 'pipe' });
|
|
796
|
+
} catch {
|
|
797
|
+
emptyRepo = true;
|
|
798
|
+
}
|
|
799
|
+
if (emptyRepo) {
|
|
800
|
+
console.error('INIT EMPTY-REPO WARN: 仓库无提交(git 空仓库),无法创建 ' + expectedBranch + ' 分支——先 git commit 初始提交再 init 启用分支模式,或继续纯文件模式');
|
|
801
|
+
} else if (currentBranch !== null && currentBranch !== expectedBranch && !branchExists(expectedBranch)) {
|
|
802
|
+
try {
|
|
803
|
+
execFileSync('git', ['checkout', '-b', expectedBranch], { cwd: runRoot, stdio: 'pipe' });
|
|
804
|
+
} catch {
|
|
805
|
+
console.error('WARN: 创建分支 ' + expectedBranch + ' 失败——继续纯文件模式(分支功能降级;可稍后手动 git checkout -b ' + expectedBranch + ')');
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
console.log('Initialized: ' + changeName);
|
|
810
|
+
console.log('BRANCH: ' + (branchMode && !emptyRepo ? expectedBranch : 'none(非 git 仓库或空仓库)'));
|
|
811
|
+
// init 输出取协议首节点(与 的 state.currentNode 一致——内置协议 = open,行为不变)
|
|
812
|
+
printNext(protocol, route(protocol)[0]?.id ?? 'open');
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
if (command === 'status') {
|
|
817
|
+
const changeName = await findActiveChange();
|
|
818
|
+
if (!changeName) {
|
|
819
|
+
console.log(JSON.stringify({ status: 'no-change', message: 'No active change in .specs/' }, null, 2));
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
const state = await readState();
|
|
823
|
+
const detectedNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
824
|
+
console.log(JSON.stringify({
|
|
825
|
+
status: 'running',
|
|
826
|
+
change: changeName,
|
|
827
|
+
currentNode: detectedNode,
|
|
828
|
+
stateCurrentNode: state.currentNode,
|
|
829
|
+
completedNodes: state.completedNodes,
|
|
830
|
+
executionMode: state.executionMode ?? 'subagent',
|
|
831
|
+
directOverride: state.directOverride ?? false,
|
|
832
|
+
branchMode: isInsideWorkTree(),
|
|
833
|
+
enablePrReview: state.enablePrReview ?? false,
|
|
834
|
+
artifactRoot: '.specs/' + changeName,
|
|
835
|
+
coordinatorMode: ['execute', 'subagent-execute'].includes(detectedNode),
|
|
836
|
+
// G14: 新旧 change 标记——newChange true = 新 change(严格模式);false/缺失 = 旧 change(渐进)
|
|
837
|
+
newChange: state.newChange === true
|
|
838
|
+
}, null, 2));
|
|
839
|
+
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
if (command === 'next') {
|
|
844
|
+
const changeName = await findActiveChange();
|
|
845
|
+
if (!changeName) {
|
|
846
|
+
console.log('NEXT: done');
|
|
847
|
+
console.log('MESSAGE: No active change. Run: node workflow-state.mjs init <change-name>');
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
const state = await readState();
|
|
851
|
+
// 节点顺序校验(严格模式)——state.currentNode 非 null、不在 completedNodes、
|
|
852
|
+
// 且 evidence 无该节点记录 → 上一节点从未 exit 就推进 → BLOCKED(exit 1)。
|
|
853
|
+
// 状态漂移校正保留:已完成节点(currentNode ∈ completedNodes,或 evidence 已记录——
|
|
854
|
+
// 节点已被 record/exit 处理过)正常推进不受影响;本校验只拦"证据完全缺失的疑似跳阶段"。
|
|
855
|
+
// 豁免(两种独立判断,任一成立即放行): 回退豁免(TASK.md 有 pending 回退修复任务 回 execute);
|
|
856
|
+
// 正常推进豁免(currentNode 是 completedNodes 最后节点 exit 推进的正常下一节点,
|
|
857
|
+
// 见 normalAdvanceExempt)——真乱序(跳节点)仍严格 BLOCK
|
|
858
|
+
const completedArr = Array.isArray(state.completedNodes) ? state.completedNodes : [];
|
|
859
|
+
if (state.currentNode && !completedArr.includes(state.currentNode)) {
|
|
860
|
+
const nodeEvidence = state.evidence && typeof state.evidence === 'object'
|
|
861
|
+
? state.evidence[state.currentNode]
|
|
862
|
+
: null;
|
|
863
|
+
const hasEvidence = !!(nodeEvidence && typeof nodeEvidence === 'object' && !Array.isArray(nodeEvidence));
|
|
864
|
+
if (!hasEvidence) {
|
|
865
|
+
// 回退豁免——review/verify 发现缺陷追加 pending 修复任务后回 execute 的
|
|
866
|
+
// 修复任务标准回退路径放行(否则被 严格模式误拦为"未 exit 跳阶段");
|
|
867
|
+
// 豁免条件不满足时维持严格 BLOCK
|
|
868
|
+
const rollbackExempt = await tFixRollbackExempt(changeName, protocol, state.currentNode, completedArr);
|
|
869
|
+
// 正常推进豁免——exit --apply 推进 currentNode 到下一节点后按 SKILL 协议调 next
|
|
870
|
+
// (正常路径)不拦截;与 回退豁免独立判断(详见 normalAdvanceExempt 注释)
|
|
871
|
+
const advanceExempt = await normalAdvanceExempt(state, protocol, completedArr, state.currentNode, changeName);
|
|
872
|
+
if (!rollbackExempt && !advanceExempt) {
|
|
873
|
+
console.error('BLOCKED: 疑似未 exit 节点 ' + state.currentNode + ',先 workflow-guard.mjs exit ' + state.currentNode + ' --apply');
|
|
874
|
+
console.error('恢复: 确认当前节点实际已完成 → 用 exit <节点> --apply 正常推进;节点状态漂移/卡死 → 用 workflow-state.mjs advance(强制推进)或 select(切换 change);禁止手改 state 机器字段');
|
|
875
|
+
process.exit(1);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
const detectedNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
880
|
+
// 单趟零进展防呆(三重防呆决策之二·状态机侧):路由落在 execute/subagent-execute,但既无可委托的并行任务
|
|
881
|
+
// (依赖已满足集合为空)又无串行 pending,且 TASK 未全 done——剩余 pending 全部是依赖无法满足的
|
|
882
|
+
// 孤儿并行任务(数据异常:depends_on 引用不存在的任务 id 或执行期出现依赖环)→ BLOCKED,
|
|
883
|
+
// 防止静默路由到无法推进的节点造成死循环/死等。协议无 subagent-execute 节点时不适用
|
|
884
|
+
// (parallel 任务由 execute 直接消化,无孤儿语义)。依赖环的常规拦截点在 plan 出口(guard 前置),
|
|
885
|
+
// 此处兜底执行期数据异常(如手改 TASK 绕过签名校验的极端态)。
|
|
886
|
+
if (detectedNode === 'execute' || detectedNode === 'subagent-execute') {
|
|
887
|
+
if (hasSubagentNode(protocol)) {
|
|
888
|
+
try {
|
|
889
|
+
const zpBlocks = taskBlocks(await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8'));
|
|
890
|
+
const zpAttrs = zpBlocks.map(taskOpeningAttrs).filter(Boolean);
|
|
891
|
+
const zpPending = zpAttrs.filter((a) => a.status === 'pending');
|
|
892
|
+
if (zpPending.length > 0) {
|
|
893
|
+
const zpDoneIds = new Set(zpAttrs.filter((a) => a.status === 'done' && a.id).map((a) => a.id));
|
|
894
|
+
const zpEligible = zpBlocks.filter((block) => {
|
|
895
|
+
const a = taskOpeningAttrs(block);
|
|
896
|
+
if (!a || !a.parallel || a.status !== 'pending') return false;
|
|
897
|
+
const depsMatch = block.match(/<depends_on>([\s\S]*?)<\/depends_on>/);
|
|
898
|
+
if (!depsMatch || !depsMatch[1].trim()) return true;
|
|
899
|
+
return depsMatch[1].trim().split(/[,\s]+/).filter(Boolean).every((d) => zpDoneIds.has(d));
|
|
900
|
+
});
|
|
901
|
+
const zpSerial = zpPending.filter((a) => !a.parallel);
|
|
902
|
+
if (zpEligible.length === 0 && zpSerial.length === 0) {
|
|
903
|
+
console.error('BLOCKED: 路由零进展——既无可委托的并行任务(依赖已满足集合为空)也无串行 pending,但 TASK 尚有 ' + zpPending.length + ' 个未完成任务');
|
|
904
|
+
console.error('疑似孤儿并行任务依赖无法满足(检查 depends_on):' + zpPending.map((a) => a.id).join(', ') + '——修正 depends_on 为真实存在且无环的任务 id 后重试;执行期出现此异常请核对 TASK.md 是否被手改');
|
|
905
|
+
process.exit(1);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
} catch {}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
// 状态漂移自动校正——以文件产物为准(determineNode)校正 state.currentNode。
|
|
912
|
+
// 进行中节点保护:currentNode 未 exit(不在 completedNodes)且已记录 evidence(record 过)
|
|
913
|
+
// → 视为节点进行中(可能 exit 被内容级拦截后重跑),不校正推走——否则被拦截节点
|
|
914
|
+
// 的 exit 前置校验(currentNode 匹配)无法重跑,advance/select 均不恢复 → 死结(实测教训)
|
|
915
|
+
const currentNodeEvidence = state.currentNode && state.evidence && typeof state.evidence === 'object'
|
|
916
|
+
? state.evidence[state.currentNode]
|
|
917
|
+
: null;
|
|
918
|
+
// 进行中节点保护扩展:保护从"已 record"扩展为"已 entry(enteredNodes 含该节点)且未 exit"。
|
|
919
|
+
// 已 entry 但未 record 的节点(如刚进入、产物已齐、premature next)同样视为进行中——
|
|
920
|
+
// 不校正推走(否则该节点 exit 前置 currentNode 校验无法重跑 → 死结)。旧 state 无
|
|
921
|
+
// enteredNodes 时回退到 evidence 判定(既有语义不回归)。
|
|
922
|
+
const currentNodeEntered = !!(
|
|
923
|
+
state.enteredNodes && Array.isArray(state.enteredNodes) && state.enteredNodes.includes(state.currentNode)
|
|
924
|
+
);
|
|
925
|
+
const routeIds = route(protocol).map((n) => n.id);
|
|
926
|
+
const currentNodeIdx = state.currentNode ? routeIds.indexOf(state.currentNode) : -1;
|
|
927
|
+
// 推导为 currentNode 的**路由后继**(与 guard 出口同源:把 currentNode 视为已完成再加入
|
|
928
|
+
// completedNodes 求 resolveNextNode)→ 该节点产物已齐待 exit、路由自然推进到 detectedNode
|
|
929
|
+
// (平行转换 plan→subagent-execute、趟间回流 subagent-execute→execute 均属此形态)→ 保护。
|
|
930
|
+
// 反过度修复锚(同族:产物全齐但无推进史形态):completedNodes 为空(无任何 exit 推进史,currentNode 仅是初始
|
|
931
|
+
// 陈旧节点)时不做路由后继保护——产物推导继续生效推进到最终节点(自定义协议产物全齐的
|
|
932
|
+
// 「部分完成但产物齐」形态仍路由到最后节点)。静态直接后继兜底(串行推进原语义)。
|
|
933
|
+
// 推导跳跃/跨节点或回退 → 产物权威校正(漂移,防过度修复)。
|
|
934
|
+
const routingSuccessorOfCurrent = state.currentNode
|
|
935
|
+
? await determineNode(changeName, protocol, [...completedArr, state.currentNode])
|
|
936
|
+
: null;
|
|
937
|
+
const routingSuccessorProtects = !!(completedArr.length > 0
|
|
938
|
+
&& routingSuccessorOfCurrent !== null
|
|
939
|
+
&& routingSuccessorOfCurrent === detectedNode);
|
|
940
|
+
const derivedIsDirectSuccessor = currentNodeIdx >= 0
|
|
941
|
+
&& currentNodeIdx + 1 < routeIds.length
|
|
942
|
+
&& routeIds[currentNodeIdx + 1] === detectedNode;
|
|
943
|
+
const derivedIsSuccessor = routingSuccessorProtects || derivedIsDirectSuccessor;
|
|
944
|
+
const inProgress = !!(
|
|
945
|
+
state.currentNode
|
|
946
|
+
&& !completedArr.includes(state.currentNode)
|
|
947
|
+
&& (currentNodeEntered
|
|
948
|
+
|| (currentNodeEvidence && typeof currentNodeEvidence === 'object' && !Array.isArray(currentNodeEvidence)))
|
|
949
|
+
&& derivedIsSuccessor
|
|
950
|
+
);
|
|
951
|
+
if (!inProgress && state.currentNode !== detectedNode) {
|
|
952
|
+
state.currentNode = detectedNode;
|
|
953
|
+
await writeState(state);
|
|
954
|
+
}
|
|
955
|
+
// 进行中节点保护:不校正时输出也跟随 currentNode(而非产物推导的 detectedNode——
|
|
956
|
+
// 否则 state 保持 review 但输出 NODE: verify,执行者按输出 action 仍然死结)
|
|
957
|
+
const printNode = inProgress ? state.currentNode : detectedNode;
|
|
958
|
+
printNext(protocol, printNode, state.executionMode ?? 'subagent');
|
|
959
|
+
printBranchLine(changeName, state.branchPrefix ?? 'change/');
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
if (command === 'select') {
|
|
964
|
+
const changeName = process.argv[3];
|
|
965
|
+
if (!changeName) throw new Error('select requires a change name.');
|
|
966
|
+
const changeDir = path.join(specsRoot, changeName);
|
|
967
|
+
if (!(await fileExists(changeDir))) throw new Error('Change not found: ' + changeDir);
|
|
968
|
+
const state = await readState();
|
|
969
|
+
state.activeChange = changeName;
|
|
970
|
+
if (!state.currentNode) state.currentNode = await determineNode(changeName, protocol, state.completedNodes);
|
|
971
|
+
await writeState(state);
|
|
972
|
+
console.log('Selected: ' + changeName);
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
if (command === 'skill-load') {
|
|
977
|
+
// 协议解析: 执行者加载节点 skill 后运行 skill-load <node> <skill> [--prompt <path>],
|
|
978
|
+
// 写入声明标记 .specs/<change-id>/.skill-loads/<node>-<skill>.json({ node, skill, protocol, at }),
|
|
979
|
+
// record 校验 completedChecks 的 required-skill 条目以此为准(内置节点常量)。
|
|
980
|
+
// 诚实边界:标记是"声明"而非物理证明——运行时没有 Skill 调用观察点,脚本无法确认执行者
|
|
981
|
+
// 真实加载过该 skill;标记仅记录"执行者主动声明已加载",由流程纪律兜底。
|
|
982
|
+
const nodeId = process.argv[3];
|
|
983
|
+
const skillName = process.argv[4];
|
|
984
|
+
if (!nodeId || !skillName) {
|
|
985
|
+
throw new Error('skill-load requires <node> <skill>. 用法: workflow-state.mjs skill-load <node> <skill> [--prompt <path>]');
|
|
986
|
+
}
|
|
987
|
+
// 参数校验:node 为当前协议节点集合之一(动态读取协议 nodes[].id——内置 +
|
|
988
|
+
// 自定义,compose 自定义协议节点可声明);协议外节点名依然非法(fail-closed)。
|
|
989
|
+
// BUILTIN_NODES 仅作内置常量保留(其他用途参照),skill-load 校验不再依赖它。
|
|
990
|
+
const protocolNodeIds = (protocol.nodes ?? []).map((n) => n.id);
|
|
991
|
+
if (!protocolNodeIds.includes(nodeId)) {
|
|
992
|
+
throw new Error('skill-load node 非法: ' + nodeId + '(协议节点: ' + protocolNodeIds.join('/') + ')');
|
|
993
|
+
}
|
|
994
|
+
if (!/^[A-Za-z0-9-]+$/.test(skillName)) {
|
|
995
|
+
throw new Error('skill-load skill 名非法(仅允许字母数字连字符): ' + skillName);
|
|
996
|
+
}
|
|
997
|
+
// --prompt 归属校验:路径必须位于 flow-kit/prompts/ 下(相对或绝对,前缀校验;
|
|
998
|
+
// flow-kit 为 vendored 上游,协议提示只读引用)。协议加载本身由 resolveProtocol 全局
|
|
999
|
+
// 处理(含受保护读取)——--protocol 语义不变(工作流协议 JSON);此处仅校验用户显式传入的
|
|
1000
|
+
// --prompt 原始值(skill-load 专属参数,不再与全局协议解析共用 --protocol)。
|
|
1001
|
+
const promptArg = findPromptArg(process.argv.slice(3));
|
|
1002
|
+
if (promptArg !== null && !protocolUnderFlowKitPrompts(promptArg)) {
|
|
1003
|
+
throw new Error('skill-load --prompt 路径必须位于 flow-kit/prompts/ 下(flow-kit 为 vendored 上游,协议提示只读引用): ' + promptArg);
|
|
1004
|
+
}
|
|
1005
|
+
// 声明标记写入:.skill-loads/ 目录不存在时创建(writeJson 自带 mkdir recursive);
|
|
1006
|
+
// 同 node-skill 重复调用覆盖(记录最新声明)
|
|
1007
|
+
const changeName = await findActiveChange();
|
|
1008
|
+
if (!changeName) {
|
|
1009
|
+
// 归档后场景:change 目录已移入 .specs/archive/(无活跃 change)——skill-load 不可用,
|
|
1010
|
+
// 但 record 的声明自动化(M5)仍可写归档路径标记——消息如实引导(级 4 实证反馈)
|
|
1011
|
+
throw new Error('skill-load requires an active change(先运行 init <change-id>;若该 change 已归档,声明标记由 record 自动补写——M5 会写入归档路径的 .skill-loads/)');
|
|
1012
|
+
}
|
|
1013
|
+
// 标记 protocol 字段 = --prompt 参数的 basename(如 0-change.md)——与 guard exit
|
|
1014
|
+
// 校验的 节点协议映射 表 basename 精确比对同值(真实链路 skill-load → exit 一致);未传 --prompt →
|
|
1015
|
+
// null(无协议声明,exit 校验 fail-closed)。修复前旧实现写 resolveProtocol 解析后的完整
|
|
1016
|
+
// 绝对路径,与 节点协议映射 表 basename 比对必然失败(真实链路必 BLOCKED——机制实际不可用)。
|
|
1017
|
+
const marker = { node: nodeId, skill: skillName, protocol: promptArg === null ? null : path.basename(promptArg), at: new Date().toISOString() };
|
|
1018
|
+
// specsRoot 已含 .specs/,相对路径为 <change-id>/.skill-loads/<node>-<skill>.json
|
|
1019
|
+
const markerRel = path.posix.join(changeName, '.skill-loads', nodeId + '-' + skillName + '.json');
|
|
1020
|
+
await writeJson(path.join(specsRoot, markerRel), marker);
|
|
1021
|
+
console.log('SKILL-LOAD: ' + nodeId + ' ' + skillName + ' → .skill-loads/' + nodeId + '-' + skillName + '.json');
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
if (command === 'record') {
|
|
1026
|
+
const nodeId = process.argv[3];
|
|
1027
|
+
if (!nodeId) throw new Error('record requires a Node id.');
|
|
1028
|
+
const state = await readState();
|
|
1029
|
+
state.evidence = state.evidence || {};
|
|
1030
|
+
// 解析 JSON 参数并展开到 evidence 顶层(summary/completedChecks/output-schema evidence 等);
|
|
1031
|
+
// 若不可解析则作为 summary 字符串
|
|
1032
|
+
// payload 解析前剥离 --protocol(及 --protocol=<p>)——resolveProtocol 已全局提取协议路径,
|
|
1033
|
+
// 此处仅防其拼入 payload 导致 JSON 解析失败(结构字段丢失)
|
|
1034
|
+
// --json-file <path>(或 --json-file=<path>):从文件读 JSON payload——规避 Windows
|
|
1035
|
+
// PowerShell 传参剥离内嵌双引号导致 JSON 损坏(record 存成 {summary:...} 脏数据)
|
|
1036
|
+
let parsed = {};
|
|
1037
|
+
let jsonFile = null;
|
|
1038
|
+
const payloadArgs = [];
|
|
1039
|
+
const recordArgs = process.argv.slice(4);
|
|
1040
|
+
for (let i = 0; i < recordArgs.length; i++) {
|
|
1041
|
+
const arg = recordArgs[i];
|
|
1042
|
+
if (arg === '--protocol') { i += 1; continue; }
|
|
1043
|
+
if (typeof arg === 'string' && arg.startsWith('--protocol=')) continue;
|
|
1044
|
+
if (arg === '--json-file') {
|
|
1045
|
+
jsonFile = recordArgs[i + 1];
|
|
1046
|
+
i += 1;
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
if (typeof arg === 'string' && arg.startsWith('--json-file=')) {
|
|
1050
|
+
jsonFile = arg.slice('--json-file='.length);
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
payloadArgs.push(arg);
|
|
1054
|
+
}
|
|
1055
|
+
const raw = jsonFile !== null
|
|
1056
|
+
? await fs.readFile(await resolveJsonFileWithinRunRoot(jsonFile), 'utf8')
|
|
1057
|
+
: payloadArgs.join(' ');
|
|
1058
|
+
try {
|
|
1059
|
+
parsed = raw ? JSON.parse(raw) : {};
|
|
1060
|
+
if (typeof parsed !== 'object' || Array.isArray(parsed)) parsed = { summary: String(parsed) };
|
|
1061
|
+
} catch {
|
|
1062
|
+
// 契约解析失败 fail-closed:payload 形似对象但 JSON.parse 失败 → 报错并
|
|
1063
|
+
// process.exit(1),不写 evidence——防状态污染(旧语义把不可解析 raw 静默作
|
|
1064
|
+
// summary 字符串落库 = 静默落脏)
|
|
1065
|
+
// 消息按参数来源分级(设计语义 / AC-3):--json-file 传入且文件内容损坏 →
|
|
1066
|
+
// "文件内容不是合法 JSON" + 长度元数据;内联传参损坏 → 保留 --json-file 建议。
|
|
1067
|
+
// 安全(bot 审查):错误消息只含固定前缀 + 长度元数据,绝不打印 raw 内容(含截断)。
|
|
1068
|
+
if (looksLikeObjectLiteral(raw)) {
|
|
1069
|
+
if (jsonFile !== null) {
|
|
1070
|
+
console.error('文件内容不是合法 JSON (length=' + String(raw ?? '').length + ')');
|
|
1071
|
+
} else {
|
|
1072
|
+
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');
|
|
1073
|
+
}
|
|
1074
|
+
process.exit(1);
|
|
1075
|
+
}
|
|
1076
|
+
parsed = { summary: raw || 'recorded' };
|
|
1077
|
+
}
|
|
1078
|
+
// completedChecks 真实性校验(skill-load 声明标记)——解析本次 record 写入的
|
|
1079
|
+
// completedChecks 的 required-skill:<node>.<skill> 条目 → 对应声明标记必须存在(内置节点常量,
|
|
1080
|
+
// 缺失 → BLOCKED + 指引先加载 skill 并运行 skill-load);标记 at 必须 ≤ 本次记录时间
|
|
1081
|
+
// (交叉自洽:标记先于记录声明)。仅校验本次写入的 payload,旧 evidence 不追溯(旧 change 兼容)。
|
|
1082
|
+
const recordedAt = new Date().toISOString();
|
|
1083
|
+
// 标记归属 change 与 evidence 一致:优先 state.activeChange,缺失时回退 findActiveChange(与
|
|
1084
|
+
// 下方 NEXT 推导同语义);两者皆无 → verifySkillLoadMarkers 内 fail-closed BLOCK。
|
|
1085
|
+
// 传入 protocol + state——按 requiredSkillCalls scope 分类条目(handoff scope 豁免标记,
|
|
1086
|
+
// 以共用证据库 handoffResult 为证据)
|
|
1087
|
+
const markerChange = state.activeChange || await findActiveChange();
|
|
1088
|
+
const markerCheck = await verifySkillLoadMarkers(parsed.completedChecks, markerChange, recordedAt, protocol, state);
|
|
1089
|
+
if (!markerCheck.ok) {
|
|
1090
|
+
console.error('BLOCKED: ' + markerCheck.reason);
|
|
1091
|
+
process.exit(1);
|
|
1092
|
+
}
|
|
1093
|
+
// 技能加载前置门(方案 A):节点完成记录必须先有本节点
|
|
1094
|
+
// skill-load 声明标记——无论 payload 是否含 completedChecks 都校验(堵"先干活后补
|
|
1095
|
+
// 声明"旁路):缺失 → 新 change BLOCK / 旧 change 渐进 WARN。指引先加载技能并运行
|
|
1096
|
+
// skill-load 再重试。handoff scope 技能(子代理加载)不要求协调者声明(与
|
|
1097
|
+
// verifySkillLoadMarkers 的 scope 豁免一致)——本门按 <node>-*.json 存在性判定,
|
|
1098
|
+
// 与 guard exit 侧协议声明标记校验同构。仅对存在于当前协议的节点生效(协议外节点名
|
|
1099
|
+
// 的记录不适用前置门),无 active change 时无法定位标记而不重复报错(遗留兼容)。
|
|
1100
|
+
const recordNodeDef = (protocol.nodes ?? []).find((n) => n.id === nodeId);
|
|
1101
|
+
if (recordNodeDef && markerChange) {
|
|
1102
|
+
const declaredForNode = await hasNodeSkillDeclaration(nodeId, markerChange);
|
|
1103
|
+
if (!declaredForNode) {
|
|
1104
|
+
const loadGuide = '先加载技能(用 Skill 工具,禁止跳过)并运行 workflow-state.mjs skill-load ' + nodeId + ' <skill> 再重试';
|
|
1105
|
+
if (state.newChange === true) {
|
|
1106
|
+
console.error('BLOCKED: 节点 ' + nodeId + ' 缺少技能加载声明标记(.skill-loads/' + nodeId + '-*.json)——' + loadGuide);
|
|
1107
|
+
process.exit(1);
|
|
1108
|
+
}
|
|
1109
|
+
console.error('WARN: 节点 ' + nodeId + ' 缺少技能加载声明标记(.skill-loads/' + nodeId + '-*.json)——' + loadGuide + '(旧 change 渐进不阻断,记录继续)');
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
// M5: 声明自动化——record 时按协议 requiredSkillCalls 自动补写缺失的声明标记
|
|
1113
|
+
// (执行者无需手动 skill-load;标记如实记录"节点完成即视为其实现/协议技能已加载",
|
|
1114
|
+
// 由 record 代记;与手动 skill-load 标记同体系,exit 协议声明校验共用)
|
|
1115
|
+
// 新 change 下 required 条目停用自动补写(手动声明唯一路径,否则抵消前置门);
|
|
1116
|
+
// 旧 change 保留 M5 兜底(渐进兼容)。
|
|
1117
|
+
if (recordNodeDef && markerChange && state.newChange !== true) {
|
|
1118
|
+
const recordProtoFiles = NODE_PROTOCOL_FILES[nodeId] ?? [];
|
|
1119
|
+
// M5 标记目录解析:活动路径优先;change 已归档(活动目录不存在但归档目录存在)
|
|
1120
|
+
// 时写归档路径——防重建已归档的活动目录(归档移动语义;与 findSkillLoadsDir 双路径一致)。
|
|
1121
|
+
// 跳过条件:活动与归档均无 .skill-loads **且活动 change 目录已不存在**(归档移动后)
|
|
1122
|
+
// ——此时 writeJson 的 mkdir recursive 会把已归档的活动目录残留回来(修复前实测缺陷);
|
|
1123
|
+
// 活动 change 目录仍存在(正常流程)时创建 .skill-loads 子目录是 M5 的正常职责,不跳过
|
|
1124
|
+
const activeLoadsDir = path.join(specsRoot, markerChange, '.skill-loads');
|
|
1125
|
+
let targetLoadsDir = activeLoadsDir;
|
|
1126
|
+
if (!(await fileExists(activeLoadsDir))) {
|
|
1127
|
+
const archived = await findSkillLoadsDir(markerChange);
|
|
1128
|
+
if (archived !== null && archived.dir !== activeLoadsDir) {
|
|
1129
|
+
targetLoadsDir = archived.dir;
|
|
1130
|
+
} else if (archived === null && !(await fileExists(path.join(runRoot, '.specs', markerChange)))) {
|
|
1131
|
+
targetLoadsDir = null;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
if (targetLoadsDir !== null) {
|
|
1135
|
+
for (const binding of recordNodeDef.requiredSkillCalls ?? []) {
|
|
1136
|
+
// handoff scope 技能由子代理加载(协调者不声明)——不自动补协调者标记
|
|
1137
|
+
// (2026-08-16 修复:此前无条件写标记,与 verifySkillLoadMarkers 的 scope 豁免不一致)
|
|
1138
|
+
if (binding.scope === 'handoff') continue;
|
|
1139
|
+
const markerFile = path.join(targetLoadsDir, nodeId + '-' + binding.skill + '.json');
|
|
1140
|
+
let markerExists = false;
|
|
1141
|
+
try { await fs.access(markerFile); markerExists = true; } catch { /* 标记不存在 */ }
|
|
1142
|
+
if (!markerExists) {
|
|
1143
|
+
// 自动补的 protocol 字段按 skill 归属协议文件(如 open 的 requirement 标记应写
|
|
1144
|
+
// 1-requirement.md 而非节点首文件 0-change.md——修复前所有 skill 都写首文件,
|
|
1145
|
+
// 标记的协议归属语义错误;exit 校验只查归属集合故能通过,但标记不可信)
|
|
1146
|
+
const skillProtoFiles = SKILL_PROTOCOL_FILES[binding.skill] ?? [];
|
|
1147
|
+
await writeJson(markerFile, {
|
|
1148
|
+
node: nodeId,
|
|
1149
|
+
skill: binding.skill,
|
|
1150
|
+
protocol: skillProtoFiles.length > 0 ? skillProtoFiles[0] : null,
|
|
1151
|
+
at: recordedAt,
|
|
1152
|
+
auto: true,
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
state.evidence[nodeId] = {
|
|
1159
|
+
...(state.evidence[nodeId] || {}),
|
|
1160
|
+
...parsed,
|
|
1161
|
+
recordedAt,
|
|
1162
|
+
};
|
|
1163
|
+
await writeState(state);
|
|
1164
|
+
console.log('EVIDENCE: ' + nodeId);
|
|
1165
|
+
const changeName = state.activeChange || await findActiveChange();
|
|
1166
|
+
const nextNode = changeName ? await determineNode(changeName, protocol, state.completedNodes) : null;
|
|
1167
|
+
printNext(protocol, nextNode ?? null, state.executionMode ?? 'subagent');
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
if (command === 'config') {
|
|
1172
|
+
// E1: 配置命令——config set <key> <value>;branchMode 只读(init 自动判定),enablePrReview 手动开关
|
|
1173
|
+
const sub = process.argv[3];
|
|
1174
|
+
const key = process.argv[4];
|
|
1175
|
+
const value = process.argv[5];
|
|
1176
|
+
if (sub !== 'set') throw new Error('config 仅支持 set 子命令。用法: workflow-state.mjs config set <key> <value>');
|
|
1177
|
+
if (!key || value === undefined) throw new Error('config set 需要 key 和 value。用法: workflow-state.mjs config set <key> <value>');
|
|
1178
|
+
if (key === 'branchMode') {
|
|
1179
|
+
console.error('BLOCKED: branchMode 由 init 自动判定,不可手动设置');
|
|
1180
|
+
process.exit(1);
|
|
1181
|
+
}
|
|
1182
|
+
if (key === 'enablePrReview') {
|
|
1183
|
+
if (value !== 'true' && value !== 'false') {
|
|
1184
|
+
console.error('BLOCKED: config set 值非法(enablePrReview 必须为 true 或 false): ' + value);
|
|
1185
|
+
process.exit(1);
|
|
1186
|
+
}
|
|
1187
|
+
const state = await readState();
|
|
1188
|
+
state.enablePrReview = value === 'true';
|
|
1189
|
+
await writeState(state);
|
|
1190
|
+
console.log('CONFIG: enablePrReview = ' + state.enablePrReview);
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
console.error('BLOCKED: 未知配置键: ' + key + '(支持: enablePrReview;branchMode 由 init 自动判定)');
|
|
1194
|
+
process.exit(1);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
if (command === 'execution-mode') {
|
|
1198
|
+
const mode = process.argv[3];
|
|
1199
|
+
if (mode !== 'subagent' && mode !== 'direct') {
|
|
1200
|
+
console.error('BLOCKED: execution-mode 参数必须为 subagent 或 direct,收到: ' + String(mode));
|
|
1201
|
+
process.exit(1);
|
|
1202
|
+
}
|
|
1203
|
+
const state = await readState();
|
|
1204
|
+
state.executionMode = mode;
|
|
1205
|
+
// direct 是逃生口:必须用户显式调用,并记录 directOverride;切回 subagent 时清除
|
|
1206
|
+
// (directOverride 恒等于"当前是否处于用户确认的 direct"——再次切 direct 必须重新确认,无历史歧义)
|
|
1207
|
+
state.directOverride = mode === 'direct';
|
|
1208
|
+
if (mode === 'direct') {
|
|
1209
|
+
// 授权审计留痕:direct 是用户决策点不可自决——协调者显式调用本命令即授权事件,写入授权
|
|
1210
|
+
// 审计字段(guard 出口校验须存在授权记录;执行者绕过脚本手改 state 字段无授权记录 → BLOCK)。
|
|
1211
|
+
console.error('DIRECT-AUTH: direct=逃生口须用户显式授权——本命令即授权留痕(directOverrideAt 写入)');
|
|
1212
|
+
state.directOverrideAt = new Date().toISOString();
|
|
1213
|
+
state.directOverrideSource = 'execution-mode';
|
|
1214
|
+
} else {
|
|
1215
|
+
// 切回 subagent 清除授权留痕(directOverride 一并清除——既有语义保持)
|
|
1216
|
+
delete state.directOverrideAt;
|
|
1217
|
+
delete state.directOverrideSource;
|
|
1218
|
+
}
|
|
1219
|
+
await writeState(state);
|
|
1220
|
+
console.log('EXECUTION-MODE: ' + state.executionMode + (state.directOverride ? ' (directOverride)' : ''));
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
if (command === 'verify-fail') {
|
|
1225
|
+
const state = await readState();
|
|
1226
|
+
// W2-A: 机器计数——连续 3 次失败后(第 4 次)BLOCKED,要求用户决策(继续修 / 停止)
|
|
1227
|
+
// 计数按当前 change 存储(verifyFailuresByChange)——切换 change 后计数独立,互不串扰;
|
|
1228
|
+
// 旧顶层字段首次读取时迁移并入当前 change(旧 state 兼容)
|
|
1229
|
+
const count = verifyFailuresFor(state);
|
|
1230
|
+
if (count >= 3) {
|
|
1231
|
+
console.error('verify 失败超限,需用户决策(verifyFailures=' + count + ')。继续修 / 停止?');
|
|
1232
|
+
process.exit(1);
|
|
1233
|
+
}
|
|
1234
|
+
setVerifyFailuresFor(state, count + 1);
|
|
1235
|
+
await writeState(state);
|
|
1236
|
+
console.log('VERIFY-FAIL: ' + (count + 1) + '/3');
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
if (command === 'advance') {
|
|
1241
|
+
const state = await readState();
|
|
1242
|
+
if (!state.activeChange) {
|
|
1243
|
+
console.log('No active change. Use select first.');
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
if (!state.completedNodes.includes(state.currentNode)) {
|
|
1247
|
+
state.completedNodes.push(state.currentNode);
|
|
1248
|
+
}
|
|
1249
|
+
// Use determineNode to get the actual next node (reads TASK.md)
|
|
1250
|
+
const detected = await determineNode(state.activeChange, protocol, state.completedNodes);
|
|
1251
|
+
state.currentNode = detected;
|
|
1252
|
+
await writeState(state);
|
|
1253
|
+
console.log('Advanced to: ' + state.currentNode);
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
throw new Error('Unknown command: ' + command + '. Use: init, status, next, select, record, verify-fail, advance, execution-mode, config, skill-load, bridge-check');
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
main().catch(error => {
|
|
1261
|
+
console.error(error.message);
|
|
1262
|
+
process.exit(1);
|
|
1263
|
+
});
|