flow-comet 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.flow-comet/rules/flow-comet-orchestration.md +1 -2
- package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
- package/.flow-comet/skills/flow-comet/SKILL.md +21 -3
- package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +9 -8
- package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +9 -2
- package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +4233 -94
- package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +24 -4
- package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +697 -15
- package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +69 -0
- package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +1718 -5
- package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +13 -0
- package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +429 -276
- package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +330 -13
- package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +423 -38
- package/.flow-comet/skills/flow-comet-archive/SKILL.md +15 -0
- package/.flow-comet/skills/flow-comet-execute/SKILL.md +19 -1
- package/.flow-comet/skills/flow-comet-review/SKILL.md +21 -3
- package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +12 -3
- package/.flow-comet/skills/flow-comet-verify/SKILL.md +19 -4
- package/README.md +7 -3
- package/package.json +1 -1
- package/scripts/dsh-bridge.mjs +2 -2
- package/scripts/prepare-env.mjs +102 -54
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
// specsRoot 由 runRoot 派生为 path.join(runRoot, '.specs')(与两侧调用方各自 .specs 根语义一致)。
|
|
9
9
|
import { promises as fs } from 'fs';
|
|
10
10
|
import path from 'path';
|
|
11
|
+
import { createHash } from 'crypto';
|
|
11
12
|
import { taskBlocks, taskOpeningAttrs } from './task-parsing.mjs';
|
|
13
|
+
import { fixRoundsFor, setFixRoundsFor } from './state-schema.mjs';
|
|
12
14
|
|
|
13
15
|
// 节点顺序 = 协议 nodes 顺序(disabled 过滤)。两侧路由排序共用同一实现(单一来源)。
|
|
14
16
|
function route(protocol) {
|
|
@@ -112,15 +114,67 @@ function protocolTaskFilePath(protocol, changeName, specsRoot) {
|
|
|
112
114
|
return path.join(specsRoot, changeName, taskFile);
|
|
113
115
|
}
|
|
114
116
|
|
|
117
|
+
// 协议节点是否 enabled:route 顺序中存在且未 disabled。协议 enabled 语义以本函数为唯一来源,
|
|
118
|
+
// hasSubagentNode 与各消费方(含请求归属门禁)一律复用,不各自过滤。
|
|
119
|
+
export function protocolNodeEnabled(protocol, nodeId) {
|
|
120
|
+
return route(protocol).some((node) => node.id === nodeId);
|
|
121
|
+
}
|
|
122
|
+
|
|
115
123
|
// 协议是否含 subagent-execute 委托节点(自定义协议可不含——此时 parallel 任务由 execute 直接消化)
|
|
116
124
|
function hasSubagentNode(protocol) {
|
|
117
|
-
return
|
|
125
|
+
return protocolNodeEnabled(protocol, 'subagent-execute');
|
|
118
126
|
}
|
|
119
127
|
|
|
120
128
|
async function fileExists(file) {
|
|
121
129
|
try { await fs.access(file); return true; } catch { return false; }
|
|
122
130
|
}
|
|
123
131
|
|
|
132
|
+
// ---------- 委托归属共享判定(纯函数 · 单一权威) ----------
|
|
133
|
+
// 任务属性、依赖资格、协议 enabled → 归属目标 / 不可委托原因。resolveNextNode 的下一节点
|
|
134
|
+
// 判定与请求归属门禁共用本段实现,禁止任一侧再内联「parallel → 目标节点」映射。
|
|
135
|
+
// 本段无 fs / console / process.exit / state 写入,只做确定性推导。
|
|
136
|
+
|
|
137
|
+
// 依赖资格:解析任务块的 <depends_on> 并与已完成任务 id 集合比较。依赖文本解析只此一处,
|
|
138
|
+
// resolveNextNode 的可委托并行过滤与消费方一律调用本函数。返回 { eligible, deps, unmet };
|
|
139
|
+
// 无 <depends_on> 元素或内容为空视为无依赖(eligible=true)。
|
|
140
|
+
export function taskDependencyEligibility(block, doneIds = new Set()) {
|
|
141
|
+
const depsMatch = String(block ?? '').match(/<depends_on>([\s\S]*?)<\/depends_on>/);
|
|
142
|
+
if (!depsMatch || !depsMatch[1].trim()) return { eligible: true, deps: [], unmet: [] };
|
|
143
|
+
const deps = depsMatch[1].trim().split(/[,\s]+/).filter(Boolean);
|
|
144
|
+
const unmet = deps.filter((dep) => !doneIds.has(dep));
|
|
145
|
+
return { eligible: unmet.length === 0, deps, unmet };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 归属判定:输入 taskAttrs(task-parsing 开标签属性)、依赖资格、协议 enabled。
|
|
149
|
+
// 返回 { targetNode, delegable, reason },reason 取值:
|
|
150
|
+
// not-pending 任务非 pending,归属门禁不适用;
|
|
151
|
+
// serial pending 串行 → 归属 execute;
|
|
152
|
+
// no-delegation-node pending 并行但协议无 enabled 委托节点 → 门禁不适用;
|
|
153
|
+
// dependencies-unmet pending 并行但依赖未满足 → 当前不可委托(路由按串行消化走 execute);
|
|
154
|
+
// parallel-eligible pending 并行且依赖满足 → 归属 subagent-execute。
|
|
155
|
+
export function resolveDelegationTarget({
|
|
156
|
+
taskAttrs = null,
|
|
157
|
+
dependencyEligible = false,
|
|
158
|
+
subagentNodeEnabled = false,
|
|
159
|
+
executeNodeEnabled = true,
|
|
160
|
+
} = {}) {
|
|
161
|
+
if (!taskAttrs || taskAttrs.status !== 'pending') {
|
|
162
|
+
return { targetNode: null, delegable: false, reason: 'not-pending' };
|
|
163
|
+
}
|
|
164
|
+
if (taskAttrs.parallel !== true) {
|
|
165
|
+
return executeNodeEnabled
|
|
166
|
+
? { targetNode: 'execute', delegable: true, reason: 'serial' }
|
|
167
|
+
: { targetNode: null, delegable: false, reason: 'no-delegation-node' };
|
|
168
|
+
}
|
|
169
|
+
if (!subagentNodeEnabled) {
|
|
170
|
+
return { targetNode: null, delegable: false, reason: 'no-delegation-node' };
|
|
171
|
+
}
|
|
172
|
+
if (!dependencyEligible) {
|
|
173
|
+
return { targetNode: null, delegable: false, reason: 'dependencies-unmet' };
|
|
174
|
+
}
|
|
175
|
+
return { targetNode: 'subagent-execute', delegable: true, reason: 'parallel-eligible' };
|
|
176
|
+
}
|
|
177
|
+
|
|
124
178
|
// 判定核心(抽取自 workflow-state.mjs determineNode,行为逐字等价——重构保持锚):
|
|
125
179
|
// 输入 { runRoot, changeName, protocol, completedNodes = [] } → 输出节点 id 或 null(完成态)。
|
|
126
180
|
// 判定顺序:① completedNodes 全齐 → null;② execute 家族之前的节点产物门控;③ 无 execute 家族 →
|
|
@@ -150,12 +204,12 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
|
|
|
150
204
|
// 按协议顺序拆分:execute/subagent-execute 之前的节点走产物门控(内置 = open → design → plan),
|
|
151
205
|
// 之后的节点在任务全部 done 后按序门控(内置 = review → verify → archive)。
|
|
152
206
|
const orderedNodes = route(protocol);
|
|
153
|
-
const hasExecuteFamily = orderedNodes.some((n) =>
|
|
207
|
+
const hasExecuteFamily = orderedNodes.some((n) => EXECUTE_FAMILY_NODE_IDS.has(n.id));
|
|
154
208
|
const preExecNodes = [];
|
|
155
209
|
const postExecNodes = [];
|
|
156
210
|
let sawExecuteFamily = false;
|
|
157
211
|
for (const node of orderedNodes) {
|
|
158
|
-
if (
|
|
212
|
+
if (EXECUTE_FAMILY_NODE_IDS.has(node.id)) {
|
|
159
213
|
sawExecuteFamily = true;
|
|
160
214
|
continue;
|
|
161
215
|
}
|
|
@@ -193,18 +247,19 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
|
|
|
193
247
|
if (hasSubagentNode(protocol)) {
|
|
194
248
|
// 收集所有 done 任务的 id(开标签属性序无关)
|
|
195
249
|
const doneIds = new Set(attrsList.filter((a) => a.status === 'done' && a.id).map((a) => a.id));
|
|
196
|
-
// 检查 pending parallel 任务中是否有依赖已满足的(开标签 parallel="true" 且 status="pending"
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
250
|
+
// 检查 pending parallel 任务中是否有依赖已满足的(开标签 parallel="true" 且 status="pending")——
|
|
251
|
+
// 依赖资格与归属目标一律走共享纯函数,不在本函数内联第二份判定。
|
|
252
|
+
const hasDelegableParallel = taskList.some((block) => {
|
|
253
|
+
const attrs = taskOpeningAttrs(block);
|
|
254
|
+
if (!attrs || attrs.parallel !== true || attrs.status !== 'pending') return false;
|
|
255
|
+
const dependencyEligible = taskDependencyEligibility(block, doneIds).eligible;
|
|
256
|
+
return resolveDelegationTarget({
|
|
257
|
+
taskAttrs: attrs,
|
|
258
|
+
dependencyEligible,
|
|
259
|
+
subagentNodeEnabled: true,
|
|
260
|
+
}).delegable;
|
|
206
261
|
});
|
|
207
|
-
if (
|
|
262
|
+
if (hasDelegableParallel) return 'subagent-execute';
|
|
208
263
|
}
|
|
209
264
|
return 'execute';
|
|
210
265
|
}
|
|
@@ -228,4 +283,631 @@ export async function resolveNextNode({ runRoot, changeName, protocol, completed
|
|
|
228
283
|
return 'execute';
|
|
229
284
|
}
|
|
230
285
|
|
|
231
|
-
|
|
286
|
+
// ---------- Fix 批次共享判定(单一权威 · 纯函数) ----------
|
|
287
|
+
// workflow-guard 与 workflow-state 的 Fix 两态一律复用本段实现,禁止任一侧内联第二份
|
|
288
|
+
// (L-058 路由单一权威 / L-067 同判据两份实现必然分叉)。判定本身只读 TASK.md 与协议/产物
|
|
289
|
+
// 推导,无副作用、无 console 输出、无 process.exit;唯一允许写 state 的是受控归位轮次计数
|
|
290
|
+
// helper——它只被两个归位入口在目标命中后调用,轮次字段的读写经 state-schema 单一来源。
|
|
291
|
+
// execute 家族节点:协议 route 顺序中由任务状态特判的节点(与 resolveNextNode 同一划分)。
|
|
292
|
+
const EXECUTE_FAMILY_NODE_IDS = new Set(['execute', 'subagent-execute']);
|
|
293
|
+
|
|
294
|
+
// execute 家族之后第一个未完成节点:按协议 route 顺序跳过全部 execute 家族节点,返回其后
|
|
295
|
+
// 首个不在 completedNodes 中的节点 id;协议无 execute 家族或后置节点全部完成 → null。
|
|
296
|
+
// 这里只做通用推导(内置协议 = review → verify → archive);是否可作为 Fix 回程源由调用方
|
|
297
|
+
// (resolveFixReturnNode / exit apply)再用 review / verify 收窄(只覆盖内置源节点)。
|
|
298
|
+
function firstIncompletePostExecNode({ protocol, completedNodes = [] }) {
|
|
299
|
+
let sawExecuteFamily = false;
|
|
300
|
+
for (const node of route(protocol)) {
|
|
301
|
+
if (EXECUTE_FAMILY_NODE_IDS.has(node.id)) {
|
|
302
|
+
sawExecuteFamily = true;
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (sawExecuteFamily && !completedNodes.includes(node.id)) return node.id;
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// 协议任务文件内容读取(taskFile 语义唯一来源):不存在 / 不可读 → null;调用方各自按
|
|
311
|
+
// fail-closed 语义处理(回退判定 → false,回程推导 → null),不把访问类故障当成空任务集。
|
|
312
|
+
async function readProtocolTaskContent(protocol, changeName, specsRoot) {
|
|
313
|
+
try {
|
|
314
|
+
return await fs.readFile(protocolTaskFilePath(protocol, changeName, specsRoot), 'utf8');
|
|
315
|
+
} catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// TASK.md 任务集签名(唯一实现:guard 的入口记录 / 出口比对与 Fix 回退判定共用)——提取全部
|
|
321
|
+
// <task> 块,剥离开标签上的标记类属性(仅保留 id/parallel),排序防顺序漂移,拼接后 sha256。
|
|
322
|
+
// 行尾规范化——Windows 下 bash heredoc 写 LF、python 写 CRLF(os.linesep),跨工具编辑
|
|
323
|
+
// 导致"任务集逻辑未变但字节变"的误报 BLOCK;签名前统一 CRLF → LF(仅归一化行尾,不改变内容语义)。
|
|
324
|
+
// 标记类属性白名单——子代理标记 task done 会在开标签追加 completed_at/started_at/finished_at/
|
|
325
|
+
// assigned_to/updated_at 等属性(纯状态标记),仅剥离 status 仍误报 BLOCK;改为开标签只保留
|
|
326
|
+
// 影响路由语义的 id/parallel,其余属性一律剥离(含未来新增标记属性,无需再改);
|
|
327
|
+
// 任务内容(name/action/write_files/verify/depends_on)保持签名敏感。
|
|
328
|
+
//
|
|
329
|
+
// 算法版本元数据:值格式 <算法版本>:<digest>(如 v1:<sha256 hex>)。签名算法实现变更时必须同步
|
|
330
|
+
// 提升版本常量——冻结锚据此判别;新 state 的 taskHash 与 exit-applied 事件的 taskSetSignature
|
|
331
|
+
// 都写版本前缀,事件另带 signatureAlgo 字段;legacy 裸 hex 一律按 v1 解析;消费点只做同版本比较,
|
|
332
|
+
// 版本不同视为不可比(不判发散、不误归位、不误拦任务集)。
|
|
333
|
+
export const TASK_SET_SIGNATURE_ALGO = 'v1';
|
|
334
|
+
const TASK_SET_SIGNATURE_PREFIX = /^(v\d+):([0-9a-f]{64})$/u;
|
|
335
|
+
const TASK_SET_SIGNATURE_BARE_HEX = /^[0-9a-f]{64}$/u;
|
|
336
|
+
const LEGACY_TASK_SET_SIGNATURE_ALGO = 'v1';
|
|
337
|
+
|
|
338
|
+
// 内容 digest(保持既有归一化与属性剥离语义逐字不变)
|
|
339
|
+
function digestTaskSetContent(taskContent) {
|
|
340
|
+
const normalized = String(taskContent).replace(/\r\n/g, '\n');
|
|
341
|
+
const blocks = (normalized.match(/<task[\s\S]*?<\/task>/g) || [])
|
|
342
|
+
.map((block) =>
|
|
343
|
+
block.replace(/<task[^>]*>/, (open) =>
|
|
344
|
+
open.replace(/\s+[a-zA-Z_][\w-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'))?/g, (attr) =>
|
|
345
|
+
/^\s*(?:id|parallel)(?=[\s=>])/.test(attr) ? attr : ''
|
|
346
|
+
)
|
|
347
|
+
)
|
|
348
|
+
)
|
|
349
|
+
.sort();
|
|
350
|
+
return createHash('sha256').update(blocks.join('\n'), 'utf8').digest('hex');
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// 计算签名:返回 <算法版本>:<digest>;algo 缺省为当前版本(供跨版本夹具显式传入旧版本)。
|
|
354
|
+
export function taskSetSignature(taskContent, algo = TASK_SET_SIGNATURE_ALGO) {
|
|
355
|
+
const version = String(algo ?? '').trim() || TASK_SET_SIGNATURE_ALGO;
|
|
356
|
+
return version + ':' + digestTaskSetContent(taskContent);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// 解析签名值:新格式 <vN>:<64 hex>;legacy 裸 64 hex 按 v1;空值 / 非字符串 / 其它形态 → null。
|
|
360
|
+
export function parseTaskSetSignature(value) {
|
|
361
|
+
if (typeof value !== 'string' || value === '') return null;
|
|
362
|
+
const prefixed = TASK_SET_SIGNATURE_PREFIX.exec(value);
|
|
363
|
+
if (prefixed) return { algo: prefixed[1], digest: prefixed[2] };
|
|
364
|
+
if (TASK_SET_SIGNATURE_BARE_HEX.test(value)) {
|
|
365
|
+
return { algo: LEGACY_TASK_SET_SIGNATURE_ALGO, digest: value };
|
|
366
|
+
}
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// 同版本且同 digest = 一致;任一不可解析 / 版本不同 = false(调用方必须按不可比语义处理)。
|
|
371
|
+
export function sameTaskSetSignature(left, right) {
|
|
372
|
+
const a = parseTaskSetSignature(left);
|
|
373
|
+
const b = parseTaskSetSignature(right);
|
|
374
|
+
if (a === null || b === null) return false;
|
|
375
|
+
return a.algo === b.algo && a.digest === b.digest;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// 两侧均可解析但算法版本不同 → true(需要「跳过比对」而非「判为发散」的消费点使用)。
|
|
379
|
+
export function taskSetSignatureVersionSkew(left, right) {
|
|
380
|
+
const a = parseTaskSetSignature(left);
|
|
381
|
+
const b = parseTaskSetSignature(right);
|
|
382
|
+
return a !== null && b !== null && a.algo !== b.algo;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// history 事件 change 归属(单一权威 · L-067):state.history 跨 change 保留(select 只切
|
|
386
|
+
// activeChange),带 change 字段的事件只在 change 名一致时参与;无 change 字段的旧 state 事件
|
|
387
|
+
// 保持兼容(legacy 参与)。execute 家族出口签名读取 / Fix 回因分类 / 受控重入轮次三处一律调用
|
|
388
|
+
// 本函数,禁止再内联同一过滤判据(注释互指同源不是同步机制)。
|
|
389
|
+
function historyEventBelongsToChange(event, changeName) {
|
|
390
|
+
return typeof event?.change !== 'string' || event.change === changeName;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// 「未闭合 execute 生命周期」信号派生:取 history 中最后一次 exit-applied execute 家族事件
|
|
394
|
+
// 记录的 { signature, algo, node };无家族出口事件 / 该事件无签名字段(旧 state)→ null(调用方按
|
|
395
|
+
// 旧 change 渐进放行)。只认最新一次家族出口——更早的签名被后续闭合覆盖。
|
|
396
|
+
// change 归属:state.history 跨 change 保留(select 只切 activeChange),因此带 change 的事件
|
|
397
|
+
// 只在 change 名一致时参与判定;无 change 字段的旧 state 事件保持兼容(legacy 可参与)。
|
|
398
|
+
// 算法版本:事件可带 signatureAlgo(新写形态),缺省按签名值解析出的版本(legacy 裸 hex = v1);
|
|
399
|
+
// 声明版本与值版本不一致的畸形事件 → null(fail-closed,不参与闭合判定)。
|
|
400
|
+
function latestExecuteExitEvent(history, changeName) {
|
|
401
|
+
if (!Array.isArray(history)) return null;
|
|
402
|
+
for (let i = history.length - 1; i >= 0; i -= 1) {
|
|
403
|
+
const event = history[i];
|
|
404
|
+
if (!event || event.event !== 'exit-applied' || !EXECUTE_FAMILY_NODE_IDS.has(event.node)) continue;
|
|
405
|
+
if (!historyEventBelongsToChange(event, changeName)) continue;
|
|
406
|
+
if (typeof event.taskSetSignature !== 'string' || event.taskSetSignature === '') return null;
|
|
407
|
+
const parsed = parseTaskSetSignature(event.taskSetSignature);
|
|
408
|
+
if (parsed === null) return null;
|
|
409
|
+
if (typeof event.signatureAlgo === 'string' && event.signatureAlgo !== '' && event.signatureAlgo !== parsed.algo) return null;
|
|
410
|
+
return { signature: event.taskSetSignature, algo: parsed.algo, digest: parsed.digest, node: event.node };
|
|
411
|
+
}
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ---------- Fix 回因分类(共享纯函数 · 单一权威 · 展示层派生) ----------
|
|
416
|
+
// guard exit 回程分支在写本次 exit-applied 事件之前调用本分类器:只用既有字段派生证据(history
|
|
417
|
+
// 的 execute 家族出口签名 + TASK 内容结构标记),零新增 state 字段 / 事件类型。判据(DESIGN 决策 1):
|
|
418
|
+
// divergence = 历史任一 execute 家族 exit-applied 事件记录的 taskSetSignature ≠ 当前任务集签名;
|
|
419
|
+
// marker = 模板派生的 Fix 段内含 <task> 块,或全文任一任务 id 匹配 /^[TP]-FIX-/i;
|
|
420
|
+
// divergence ∨ marker → 'fix';有签名且不发散 → 'normal';无签名且无标记 → 'unknown'
|
|
421
|
+
// (旧 state 证据不足:中性输出、不 BLOCK,由调用方渲染)。
|
|
422
|
+
// Fix 段标题由调用方传入(guard 从 flow-kit/templates/TASK.md 的 H2 派生);缺失 / 空串
|
|
423
|
+
// 回退内置常量(FIX_SECTION_TITLE_FALLBACK)。history 过滤与 latestExecuteExitEvent 同语义
|
|
424
|
+
// (change 归属:有 change 字段且不匹配则跳过,无 change 的 legacy 事件参与);签名事件全量参与、
|
|
425
|
+
// 不做「只看最新」短路——多波次场景最新签名已被闭合写成当前签名,只看最新会漏判 fix。
|
|
426
|
+
const FIX_SECTION_TITLE_FALLBACK = 'Fix 任务';
|
|
427
|
+
|
|
428
|
+
// 共享 heading 归一(单一权威):去 ATX 标记 / 闭合 ATX 标记 / 尾部括号内容 / 编号前缀后比较,
|
|
429
|
+
// 让 Fix 任务、Fix 任务(来自 REVIEW / INTEGRATION)、## Fix 任务 ## 等合法写法命中同一段;
|
|
430
|
+
// Fix 段标题匹配与 guard 的模板段名归一均委托本实现,禁止另起第二份。
|
|
431
|
+
function normalizeHeading(raw) {
|
|
432
|
+
return String(raw ?? '')
|
|
433
|
+
.replace(/\r/g, '')
|
|
434
|
+
.replace(/^#{1,6}\s*/, '')
|
|
435
|
+
.replace(/\s+#+\s*$/, '')
|
|
436
|
+
.replace(/[((][^))\n]*[))]\s*$/u, '')
|
|
437
|
+
.replace(/^\d+(?:\.\d+)?\.?\s*/u, '')
|
|
438
|
+
.trim()
|
|
439
|
+
.toLowerCase();
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Fix 段正文切片:首个同级(##)标题命中 → 返回标题行之后、下一个同级标题(或 EOF)之前的正文;
|
|
443
|
+
// 无命中标题 → null。只认二级标题(### 不闭合本段);CRLF / LF 归一后按行定位。
|
|
444
|
+
function fixSectionBody(taskContent, fixSectionTitle) {
|
|
445
|
+
const lines = String(taskContent ?? '').replace(/\r\n?/g, '\n').split('\n');
|
|
446
|
+
const wanted = normalizeHeading(fixSectionTitle);
|
|
447
|
+
if (wanted === '') return null;
|
|
448
|
+
let start = -1;
|
|
449
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
450
|
+
const m = lines[i].match(/^##\s+(.+?)\s*$/);
|
|
451
|
+
if (!m) continue;
|
|
452
|
+
const heading = normalizeHeading(m[1]);
|
|
453
|
+
if (heading === wanted || heading.startsWith(wanted)) { start = i; break; }
|
|
454
|
+
}
|
|
455
|
+
if (start < 0) return null;
|
|
456
|
+
let end = lines.length;
|
|
457
|
+
for (let i = start + 1; i < lines.length; i += 1) {
|
|
458
|
+
if (/^##\s/.test(lines[i])) { end = i; break; }
|
|
459
|
+
}
|
|
460
|
+
return lines.slice(start + 1, end).join('\n');
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Fix 任务结构标记:全文任一任务 id 匹配 /^[TP]-FIX-/i(覆盖文件尾追加等非规范落点)→ true;
|
|
464
|
+
// 否则 Fix 段内出现 <task> 块(标题与任务需同段,段内无任务不误报)→ true;两者皆无 → false。
|
|
465
|
+
// 解析复用 taskBlocks / taskOpeningAttrs(与路由、guard 校验共享同一 <task> 解析语义)。
|
|
466
|
+
function fixTaskMarker(taskContent, fixSectionTitle) {
|
|
467
|
+
const content = String(taskContent ?? '');
|
|
468
|
+
const title = (typeof fixSectionTitle === 'string' && fixSectionTitle.trim() !== '')
|
|
469
|
+
? fixSectionTitle
|
|
470
|
+
: FIX_SECTION_TITLE_FALLBACK;
|
|
471
|
+
const hasFixTaskId = taskBlocks(content).some((block) => {
|
|
472
|
+
const attrs = taskOpeningAttrs(block);
|
|
473
|
+
return Boolean(attrs && typeof attrs.id === 'string' && /^[TP]-FIX-/i.test(attrs.id));
|
|
474
|
+
});
|
|
475
|
+
if (hasFixTaskId) return true;
|
|
476
|
+
const section = fixSectionBody(content, title);
|
|
477
|
+
return section !== null && taskBlocks(section).length > 0;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// 回因分类唯一入口。签名:classifyFixReturnCause({ history, changeName, taskContent, fixSectionTitle })
|
|
481
|
+
// → 'fix' | 'normal' | 'unknown'。纯函数:无 fs/console/process.exit,不改既有路由判定语义。
|
|
482
|
+
// 算法版本:只让与当前任务集签名同版本的历史事件参与「signatureKnown / divergence」判定;跨版本
|
|
483
|
+
// 事件跳过(不可比),避免引擎升级后把正常多趟误判成 Fix。
|
|
484
|
+
function classifyFixReturnCause({ history, changeName, taskContent, fixSectionTitle } = {}) {
|
|
485
|
+
const current = parseTaskSetSignature(taskSetSignature(taskContent));
|
|
486
|
+
let signatureKnown = false;
|
|
487
|
+
let divergence = false;
|
|
488
|
+
if (Array.isArray(history)) {
|
|
489
|
+
for (const event of history) {
|
|
490
|
+
if (!event || event.event !== 'exit-applied' || !EXECUTE_FAMILY_NODE_IDS.has(event.node)) continue;
|
|
491
|
+
if (!historyEventBelongsToChange(event, changeName)) continue;
|
|
492
|
+
if (typeof event.taskSetSignature !== 'string' || event.taskSetSignature === '') continue;
|
|
493
|
+
const recorded = parseTaskSetSignature(event.taskSetSignature);
|
|
494
|
+
if (recorded === null) continue;
|
|
495
|
+
if (typeof event.signatureAlgo === 'string' && event.signatureAlgo !== '' && event.signatureAlgo !== recorded.algo) continue;
|
|
496
|
+
if (current === null || recorded.algo !== current.algo) continue;
|
|
497
|
+
signatureKnown = true;
|
|
498
|
+
if (recorded.digest !== current.digest) divergence = true;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
if (divergence || fixTaskMarker(taskContent, fixSectionTitle)) return 'fix';
|
|
502
|
+
return signatureKnown ? 'normal' : 'unknown';
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Fix 回退态决策(单一权威——guard 入口/出口与 state 的 next 分支一律复用本段):currentNode
|
|
506
|
+
// ∈ {review, verify} ∧ TASK.md 可解析出任务块 ∧ 以下任一:
|
|
507
|
+
// ① 存在 status="pending" 任务 ∧ resolveNextNode(completedNodes) ∈ execute 家族
|
|
508
|
+
// (串行 pending → execute;可委托 parallel pending → subagent-execute)
|
|
509
|
+
// → 返回 { target: 目标节点, kind: 'pending' }(受控归位的计数分支);
|
|
510
|
+
// ② 全任务 done ∧ execute 家族至少一个节点已在 completedNodes ∧ history 最新家族出口事件记录的
|
|
511
|
+
// 任务集签名与当前 TASK.md 签名不一致 → 返回 { target: 记录节点, kind: 'unclosed' }
|
|
512
|
+
// (done-but-unclosed:追加/修改修复任务后从未重跑家族出口;lazy entry 只刷新 taskHash、
|
|
513
|
+
// 不写 exit 事件,签名保持不一致)。
|
|
514
|
+
// 旧 state 无签名记录 / 签名不可解析 / 算法版本不同 → ② 不成立(旧 change 渐进放行,跨版本不比对)。
|
|
515
|
+
// TASK.md 缺失 / 不可读 / 零任务块 / 当前节点非 review|verify → null(fail-closed)。
|
|
516
|
+
// 路由复用唯一权威 resolveNextNode,不复制判定。
|
|
517
|
+
async function resolveFixRollbackDecision({ runRoot, changeName, protocol, completedNodes = [], currentNode, history = [] }) {
|
|
518
|
+
if (currentNode !== 'review' && currentNode !== 'verify') return null;
|
|
519
|
+
const taskContent = await readProtocolTaskContent(protocol, changeName, path.join(runRoot, '.specs'));
|
|
520
|
+
if (taskContent === null) return null;
|
|
521
|
+
const attrsList = taskBlocks(taskContent).map(taskOpeningAttrs).filter(Boolean);
|
|
522
|
+
if (attrsList.length === 0) return null;
|
|
523
|
+
if (attrsList.some((attrs) => attrs.status === 'pending')) {
|
|
524
|
+
try {
|
|
525
|
+
const next = await resolveNextNode({ runRoot, changeName, protocol, completedNodes });
|
|
526
|
+
return EXECUTE_FAMILY_NODE_IDS.has(next) ? { target: next, kind: 'pending' } : null;
|
|
527
|
+
} catch {
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (!attrsList.every((attrs) => attrs.status === 'done')) return null;
|
|
532
|
+
if (![...EXECUTE_FAMILY_NODE_IDS].some((id) => completedNodes.includes(id))) return null;
|
|
533
|
+
const recorded = latestExecuteExitEvent(history, changeName);
|
|
534
|
+
if (recorded === null) return null;
|
|
535
|
+
const current = parseTaskSetSignature(taskSetSignature(taskContent));
|
|
536
|
+
if (current === null || recorded.algo !== current.algo) return null;
|
|
537
|
+
return recorded.digest !== current.digest ? { target: recorded.node, kind: 'unclosed' } : null;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// 兼容入口:只取目标节点(既有调用方语义逐字不变);新增消费点应优先用决策形态。
|
|
541
|
+
async function resolveFixRollbackState(args) {
|
|
542
|
+
const decision = await resolveFixRollbackDecision(args);
|
|
543
|
+
return decision === null ? null : decision.target;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// ---------- Fix 受控归位轮次(单一权威 · 唯一写点) ----------
|
|
547
|
+
// 仅两个受控归位入口在目标命中后调用本 helper,且只对决策 kind='pending'(分支①)计数;
|
|
548
|
+
// 分支② done-but-unclosed、回因分类、verify 命令失败都不经此,也不得在调用方另行累加。
|
|
549
|
+
// 阈值语义:从第 4 轮起,新 change 返回 blocked(调用方必须先于任何 state 写盘退出,不得写入
|
|
550
|
+
// currentNode);旧 change 返回 warn 后照常归位。用户显式授权记录为
|
|
551
|
+
// state.evidence[源节点].fixRoundOverride = { round, at, source },覆盖到该轮即放行(不新增第二个顶层字段)。
|
|
552
|
+
// 完整授权形态:round 为正整数、at/source 均为非空字符串;任一缺失/类型非法/空串(含纯空白)
|
|
553
|
+
// 一律视为未授权 fail-closed——第 4 轮继续 BLOCK,调用方不写 currentNode、state 字节零改写。
|
|
554
|
+
// 审计行后缀由本 helper 统一给出,两个入口禁止各自拼装。
|
|
555
|
+
|
|
556
|
+
function readFixRoundOverride(state, sourceNode) {
|
|
557
|
+
if (typeof sourceNode !== 'string' || sourceNode === '') return null;
|
|
558
|
+
const sourceEvidence = state && state.evidence && typeof state.evidence === 'object' && !Array.isArray(state.evidence)
|
|
559
|
+
? state.evidence[sourceNode]
|
|
560
|
+
: null;
|
|
561
|
+
const override = sourceEvidence && typeof sourceEvidence === 'object' && !Array.isArray(sourceEvidence)
|
|
562
|
+
? sourceEvidence.fixRoundOverride
|
|
563
|
+
: null;
|
|
564
|
+
if (!override || typeof override !== 'object' || Array.isArray(override)) return null;
|
|
565
|
+
if (typeof override.round !== 'number' || !Number.isInteger(override.round) || override.round <= 0) return null;
|
|
566
|
+
if (typeof override.at !== 'string' || override.at.trim() === '') return null;
|
|
567
|
+
if (typeof override.source !== 'string' || override.source.trim() === '') return null;
|
|
568
|
+
return { round: override.round };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
const FIX_ROLLBACK_ROUND_LIMIT = 3;
|
|
572
|
+
|
|
573
|
+
const EMPTY_FIX_ROLLBACK_ROUND = Object.freeze({
|
|
574
|
+
counted: false,
|
|
575
|
+
blocked: false,
|
|
576
|
+
warn: false,
|
|
577
|
+
round: null,
|
|
578
|
+
overrideUsed: false,
|
|
579
|
+
auditSuffix: '',
|
|
580
|
+
blockedMessage: null,
|
|
581
|
+
warnMessage: null,
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
function fixRoundAuditSuffix(round) {
|
|
585
|
+
return '(第 ' + round + '/' + FIX_ROLLBACK_ROUND_LIMIT + ' 轮)';
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function fixRoundBlockedMessage(sourceNode, round) {
|
|
589
|
+
return [
|
|
590
|
+
'BLOCKED: Fix 批次受控归位已达 ' + FIX_ROLLBACK_ROUND_LIMIT + ' 轮上限,第 ' + round + ' 轮需用户决策(继续修/停止)——源节点 ' + sourceNode + '。',
|
|
591
|
+
'恢复: 继续修 → 由用户显式授权后在 state.evidence.' + sourceNode + '.fixRoundOverride 记录 {"round":' + round + ',"at":"<时间>","source":"<授权来源>"} 再重试;停止 → 结束 Fix 批次并按流程处理(禁止手改 state 机器字段)。',
|
|
592
|
+
].join('\n');
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function applyFixRollbackRound({ state, sourceNode, decision }) {
|
|
596
|
+
if (!state || !decision) return EMPTY_FIX_ROLLBACK_ROUND;
|
|
597
|
+
if (decision.kind !== 'pending') return EMPTY_FIX_ROLLBACK_ROUND;
|
|
598
|
+
const round = fixRoundsFor(state) + 1;
|
|
599
|
+
const auditSuffix = fixRoundAuditSuffix(round);
|
|
600
|
+
if (round <= FIX_ROLLBACK_ROUND_LIMIT) {
|
|
601
|
+
setFixRoundsFor(state, round);
|
|
602
|
+
return { ...EMPTY_FIX_ROLLBACK_ROUND, counted: true, round, auditSuffix };
|
|
603
|
+
}
|
|
604
|
+
const override = readFixRoundOverride(state, sourceNode);
|
|
605
|
+
if (override !== null && override.round >= round) {
|
|
606
|
+
setFixRoundsFor(state, round);
|
|
607
|
+
return { ...EMPTY_FIX_ROLLBACK_ROUND, counted: true, round, overrideUsed: true, auditSuffix };
|
|
608
|
+
}
|
|
609
|
+
if (state.newChange === true) {
|
|
610
|
+
return { ...EMPTY_FIX_ROLLBACK_ROUND, blocked: true, round, auditSuffix, blockedMessage: fixRoundBlockedMessage(sourceNode, round) };
|
|
611
|
+
}
|
|
612
|
+
setFixRoundsFor(state, round);
|
|
613
|
+
return {
|
|
614
|
+
...EMPTY_FIX_ROLLBACK_ROUND,
|
|
615
|
+
counted: true,
|
|
616
|
+
warn: true,
|
|
617
|
+
round,
|
|
618
|
+
auditSuffix,
|
|
619
|
+
warnMessage: 'FIX-BATCH WARN: Fix 批次受控归位已达 ' + FIX_ROLLBACK_ROUND_LIMIT + ' 轮上限,第 ' + round + ' 轮在旧 change 上渐进放行(建议用户显式授权并在 evidence 记录 fixRoundOverride)。',
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// Fix 回程节点推导(共享基础):TASK.md 存在、至少一个任务块且全部 status="done" 时,
|
|
624
|
+
// 取 firstIncompletePostExecNode;仅当其 ∈ {review, verify}(内置回程源)才返回,否则 null。
|
|
625
|
+
// 仍有 pending / 零任务块 / TASK.md 缺失 → null(fail-closed)。「execute 本次 exit 前已在
|
|
626
|
+
// completedNodes」的二次完成条件由 exit apply 推进点判定,本函数只做 TASK + 路由推导。
|
|
627
|
+
async function resolveFixReturnNode({ runRoot, changeName, protocol, completedNodes = [] }) {
|
|
628
|
+
const taskContent = await readProtocolTaskContent(protocol, changeName, path.join(runRoot, '.specs'));
|
|
629
|
+
if (taskContent === null) return null;
|
|
630
|
+
const attrsList = taskBlocks(taskContent).map(taskOpeningAttrs).filter(Boolean);
|
|
631
|
+
if (attrsList.length === 0) return null;
|
|
632
|
+
if (!attrsList.every((attrs) => attrs.status === 'done')) return null;
|
|
633
|
+
const node = firstIncompletePostExecNode({ protocol, completedNodes });
|
|
634
|
+
return node === 'review' || node === 'verify' ? node : null;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// ---------- archive 源受控重入判定(单一权威 · 纯函数:目标白名单 / 前驱转移语义 / 授权形态 / 轮次上限 / 审计事件 / 空操作) ----------
|
|
638
|
+
// archive 已 entry 且归档移动尚未发生时,用户显式授权把工作归属退到 execute 家族 / review /
|
|
639
|
+
// verify 的受控回边。本段只做确定性推导(无 fs / console / process.exit / state 写入):全部
|
|
640
|
+
// 判定集中在这里,reenter 子命令只做编排与落盘,禁止内联第二份(L-058 路由单一权威 /
|
|
641
|
+
// L-067 同判据两份实现必然分叉)。信号统一用 structured result:非法 / 未授权返回
|
|
642
|
+
// { ok: false, reason: '<machine-code>' },不抛异常。
|
|
643
|
+
|
|
644
|
+
// 受控重入目标白名单:显式目标必须 ∈ 本集合 ∩ 协议 enabled 节点。
|
|
645
|
+
const REENTRY_TARGET_NODE_IDS = new Set(['execute', 'subagent-execute', 'review', 'verify']);
|
|
646
|
+
|
|
647
|
+
// 每 change 轮次上限:3 轮;调用方禁止内联阈值,必须引用本常量。
|
|
648
|
+
const REENTRY_ROUND_LIMIT = 3;
|
|
649
|
+
|
|
650
|
+
// change 名形态(单一权威 · 受控重入判定与 select 入口共用):change-id 必须是 .specs/ 下的
|
|
651
|
+
// 单段目录名——拒绝空串、路径分隔符与「.」「..」,并保留目录名 archive(归档区)不得作为
|
|
652
|
+
// change 名。本判据只做字符串形态判定(纯函数);「realpath 归一后仍是 .specs 真实直接子目录」
|
|
653
|
+
// 的物理包含性由调用方的路径段扫描(protocol-utils 单一权威)负责。
|
|
654
|
+
function isSingleSegmentChangeName(value) {
|
|
655
|
+
if (typeof value !== 'string') return false;
|
|
656
|
+
const name = value.trim();
|
|
657
|
+
if (name === '' || name === '.' || name === '..') return false;
|
|
658
|
+
// 原始值必须与 trim 后逐字相等:Windows 与部分文件系统忽略首尾空白/尾点,放行「空白变体」
|
|
659
|
+
// 会让 path.join 指到真实目录、而 activeChange 存的是变体字符串——轮次事件按 activeChange
|
|
660
|
+
// 精确匹配(配额被换键重置),事件归属随即失真。
|
|
661
|
+
if (value !== name) return false;
|
|
662
|
+
if (name.includes('/') || name.includes('\\')) return false;
|
|
663
|
+
// 保留目录名按大小写归一判定:Windows 与默认 macOS 的路径解析不区分大小写,「ARCHIVE」
|
|
664
|
+
// 「Archive」同样指向归档区,逐字比较会漏判。
|
|
665
|
+
if (name.toLowerCase() === 'archive') return false;
|
|
666
|
+
return true;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// 源判定(① · AC-5):currentNode === 'archive' 且 activeChange 是合法的单段 change 名。
|
|
670
|
+
// 源不是 archive / 没有活跃 change / change 名形态非法 → 未授权来源,返回 machine-code,不抛异常。
|
|
671
|
+
function reentrySourceDecision({ currentNode, activeChange } = {}) {
|
|
672
|
+
if (typeof activeChange !== 'string' || activeChange.trim() === '') {
|
|
673
|
+
return { ok: false, reason: 'no-active-change' };
|
|
674
|
+
}
|
|
675
|
+
if (!isSingleSegmentChangeName(activeChange)) {
|
|
676
|
+
return { ok: false, reason: 'change-name-invalid' };
|
|
677
|
+
}
|
|
678
|
+
if (currentNode !== 'archive') {
|
|
679
|
+
return { ok: false, reason: 'source-not-archive' };
|
|
680
|
+
}
|
|
681
|
+
return { ok: true, reason: 'archive-source' };
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// 目标判定(② · AC-5):target ∈ 白名单 ∩ 协议 enabled 节点。enabled 判定复用
|
|
685
|
+
// protocolNodeEnabled(协议 enabled 语义唯一来源),本函数不写第二份解析;协议缺失 /
|
|
686
|
+
// 非对象按 fail-closed 返回未启用(L-079:解析失败不得静默放行)。
|
|
687
|
+
function resolveReentryTarget({ protocol, target } = {}) {
|
|
688
|
+
if (typeof target !== 'string' || !REENTRY_TARGET_NODE_IDS.has(target)) {
|
|
689
|
+
return { ok: false, reason: 'target-not-allowed' };
|
|
690
|
+
}
|
|
691
|
+
if (!protocol || typeof protocol !== 'object' || !protocolNodeEnabled(protocol, target)) {
|
|
692
|
+
return { ok: false, reason: 'target-not-enabled' };
|
|
693
|
+
}
|
|
694
|
+
return { ok: true, reason: 'target-allowed', target };
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// 授权形态 fail-closed 解析(③ · AC-2):round 为正整数、at / source 均为非空(去空白)
|
|
698
|
+
// 字符串、authorization.target 与本次调用 target 一致;任一项非法 → 未授权,不抛异常。
|
|
699
|
+
// 形态与既有 Fix 轮次授权(workflow-guard readFixRoundOverride)同源,禁止第二份校验。
|
|
700
|
+
function parseReentryAuthorization({ authorization, target } = {}) {
|
|
701
|
+
if (!authorization || typeof authorization !== 'object' || Array.isArray(authorization)) {
|
|
702
|
+
return { ok: false, reason: 'authorization-missing' };
|
|
703
|
+
}
|
|
704
|
+
if (typeof authorization.round !== 'number' || !Number.isInteger(authorization.round) || authorization.round <= 0) {
|
|
705
|
+
return { ok: false, reason: 'round-invalid' };
|
|
706
|
+
}
|
|
707
|
+
if (typeof authorization.at !== 'string' || authorization.at.trim() === '') {
|
|
708
|
+
return { ok: false, reason: 'at-invalid' };
|
|
709
|
+
}
|
|
710
|
+
if (typeof authorization.source !== 'string' || authorization.source.trim() === '') {
|
|
711
|
+
return { ok: false, reason: 'source-invalid' };
|
|
712
|
+
}
|
|
713
|
+
if (typeof target !== 'string' || target === '' || authorization.target !== target) {
|
|
714
|
+
return { ok: false, reason: 'target-mismatch' };
|
|
715
|
+
}
|
|
716
|
+
return {
|
|
717
|
+
ok: true,
|
|
718
|
+
reason: 'authorized',
|
|
719
|
+
authorization: {
|
|
720
|
+
round: authorization.round,
|
|
721
|
+
at: authorization.at.trim(),
|
|
722
|
+
source: authorization.source.trim(),
|
|
723
|
+
target,
|
|
724
|
+
},
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// 上限后的续轮授权形态(AC-7 后半句):达到上限后,用户可显式授权把轮次推进到下一轮。
|
|
729
|
+
// 授权三元组形态复用 parseReentryAuthorization(单一权威——不复制第二份字段校验);本函数只
|
|
730
|
+
// 追加续轮特有约束:round 必须覆盖即将执行的轮次(已用轮次 + 1,与既有 Fix 轮次授权的
|
|
731
|
+
// 「覆盖即将执行轮次」语义同型),否则视为未授权 fail-closed。未达上限时调用方不得传续轮授权
|
|
732
|
+
// (续轮只在人工裁决点需要)。本函数只做形态判定,不读 history。
|
|
733
|
+
function parseReentryContinuationAuthorization({ authorization, target, used } = {}) {
|
|
734
|
+
const parsed = parseReentryAuthorization({ authorization, target });
|
|
735
|
+
if (!parsed.ok) return parsed;
|
|
736
|
+
if (typeof used !== 'number' || !Number.isInteger(used) || used < 0
|
|
737
|
+
|| parsed.authorization.round < used + 1) {
|
|
738
|
+
return { ok: false, reason: 'round-below-required' };
|
|
739
|
+
}
|
|
740
|
+
return { ok: true, reason: 'continuation-authorized', authorization: parsed.authorization };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// 轮次派生(④ · AC-7):统计 state.history 中本 change 的 reentry-applied 事件数,
|
|
744
|
+
// change 归属过滤调用 historyEventBelongsToChange(单一权威——不在此内联第二份,L-067)。
|
|
745
|
+
// 跨 change 隔离依赖事件的 change 字段:写入方(reenter 子命令)必须带 change;无 change 的
|
|
746
|
+
// 旧事件按 legacy 形态参与(reentry-applied 为新事件类型,实际不会出现)。history 缺失 /
|
|
747
|
+
// 非数组 = 无事件(旧 state 形态,0 轮)。轮次只按事件条数派生,不读事件里的 round 字段。
|
|
748
|
+
function reentryRoundCount({ history, changeName } = {}) {
|
|
749
|
+
if (!Array.isArray(history)) return 0;
|
|
750
|
+
let count = 0;
|
|
751
|
+
for (const event of history) {
|
|
752
|
+
if (!event || event.event !== 'reentry-applied') continue;
|
|
753
|
+
if (!historyEventBelongsToChange(event, changeName)) continue;
|
|
754
|
+
count += 1;
|
|
755
|
+
}
|
|
756
|
+
return count;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// 上限判定(⑤ · AC-7):已用轮次 < REENTRY_ROUND_LIMIT 或持有合法续轮授权 → 放行并给出本轮
|
|
760
|
+
// 序号(nextRound = 已用 + 1,供审计事件与 REENTRY 行使用);否则 blocked(调用方必须先于
|
|
761
|
+
// 任何 state 写盘返回,保证字节零改写)。阈值只从 REENTRY_ROUND_LIMIT 取。
|
|
762
|
+
function reentryRoundDecision({ history, changeName, continuationAuthorized = false } = {}) {
|
|
763
|
+
const used = reentryRoundCount({ history, changeName });
|
|
764
|
+
if (used < REENTRY_ROUND_LIMIT) {
|
|
765
|
+
return { ok: true, reason: 'round-available', used, nextRound: used + 1, limit: REENTRY_ROUND_LIMIT };
|
|
766
|
+
}
|
|
767
|
+
if (continuationAuthorized === true) {
|
|
768
|
+
return { ok: true, reason: 'round-available-continuation', used, nextRound: used + 1, limit: REENTRY_ROUND_LIMIT };
|
|
769
|
+
}
|
|
770
|
+
return { ok: false, reason: 'round-limit-reached', used, limit: REENTRY_ROUND_LIMIT };
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// 协议前驱推导(⑦ 的输入):沿协议 success 边反向可达的全部祖先节点(传递闭包——对应
|
|
774
|
+
// 前驱语义「清掉目标及其后继」),按协议 route 顺序(disabled 过滤)排序;failure / pause 自环、
|
|
775
|
+
// target 自身与协议外节点不参与。顺序唯一来源是 route(protocol),不另写节点排序。
|
|
776
|
+
function reentryPredecessors(protocol, target) {
|
|
777
|
+
if (!protocol || typeof protocol !== 'object') return [];
|
|
778
|
+
const order = route(protocol).map((node) => node.id);
|
|
779
|
+
const ancestors = new Set();
|
|
780
|
+
const queue = [target];
|
|
781
|
+
while (queue.length > 0) {
|
|
782
|
+
const current = queue.shift();
|
|
783
|
+
for (const edge of protocol.edges ?? []) {
|
|
784
|
+
if (!edge || edge.condition !== 'success' || edge.to !== current) continue;
|
|
785
|
+
if (typeof edge.from !== 'string' || edge.from === '' || edge.from === target || ancestors.has(edge.from)) continue;
|
|
786
|
+
ancestors.add(edge.from);
|
|
787
|
+
queue.push(edge.from);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
return order.filter((id) => ancestors.has(id));
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// 前驱交集(⑦ · AC-8):completedNodes ∩ predecessors(target),按协议节点顺序保留原顺序。
|
|
794
|
+
// completedNodes 中的协议外 / 重复项自然被过滤与去重;target 未知 / 未启用 → 空交集(fail-closed)。
|
|
795
|
+
function reentryPredecessorIntersection({ protocol, target, completedNodes = [] } = {}) {
|
|
796
|
+
const completed = Array.isArray(completedNodes) ? completedNodes : [];
|
|
797
|
+
return reentryPredecessors(protocol, target).filter((id) => completed.includes(id));
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// 空操作判定(⑥ · 幂等锚):currentNode === target 且 completedNodes 已等于前驱交集结果
|
|
801
|
+
// (同序逐项相等)→ noop(调用方不备份 / 不计数 / 不写事件);否则返回待落地的交集,调用方按
|
|
802
|
+
// 前驱语义覆盖 completedNodes。判定本身不改写输入。
|
|
803
|
+
function reentryNoOpDecision({ currentNode, target, protocol, completedNodes = [] } = {}) {
|
|
804
|
+
const completed = Array.isArray(completedNodes) ? completedNodes : [];
|
|
805
|
+
const intersection = reentryPredecessorIntersection({ protocol, target, completedNodes: completed });
|
|
806
|
+
const same = currentNode === target
|
|
807
|
+
&& completed.length === intersection.length
|
|
808
|
+
&& intersection.every((id, index) => completed[index] === id);
|
|
809
|
+
return same
|
|
810
|
+
? { noop: true, reason: 'noop-target-satisfied', completedNodes: intersection }
|
|
811
|
+
: { noop: false, reason: 'target-state-not-satisfied', completedNodes: intersection };
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// 受控重入综合判定(单一权威聚合判定 · 供 reenter 子命令单点调用),返回三态 action:
|
|
815
|
+
// 'block'(ok:false,调用方零写盘返回)、
|
|
816
|
+
// 'noop' (目标形态已成立,调用方零写盘提示)、
|
|
817
|
+
// 'apply'(ok:true,携带 changeName / target / 待落地 completedNodes / 本轮 round / 归一授权)。
|
|
818
|
+
// 判定顺序:目标合法性(越界即使处于重复态也 BLOCK · AC-5)→ change 名形态 → 上限 →
|
|
819
|
+
// 幂等短路 → 源 → 授权。
|
|
820
|
+
// 幂等短路必须先于源判定:目标形态已成立时 currentNode === target ≠ 'archive',先判源会让
|
|
821
|
+
// 空操作判定永远不可达;但幂等短路不得越过上限判定——达到上限的 change 即使处于同目标形态也
|
|
822
|
+
// 必须走人工裁决路径(不得以空操作退出 0),也不得越过 change 名形态判定(畸形 change 名
|
|
823
|
+
// 一律 BLOCK,不因形态巧合而短路)。短路分支零写盘。调用方不得内联重排或复制其中任何一条判据。
|
|
824
|
+
function resolveReentryDecision({ protocol, state, target, authorization, continuationRound } = {}) {
|
|
825
|
+
const targetDecision = resolveReentryTarget({ protocol, target });
|
|
826
|
+
if (!targetDecision.ok) return { ok: false, action: 'block', reason: targetDecision.reason };
|
|
827
|
+
const activeChange = state?.activeChange;
|
|
828
|
+
if (typeof activeChange !== 'string' || activeChange.trim() === '') {
|
|
829
|
+
return { ok: false, action: 'block', reason: 'no-active-change' };
|
|
830
|
+
}
|
|
831
|
+
if (!isSingleSegmentChangeName(activeChange)) {
|
|
832
|
+
return { ok: false, action: 'block', reason: 'change-name-invalid' };
|
|
833
|
+
}
|
|
834
|
+
const used = reentryRoundCount({ history: state?.history, changeName: activeChange });
|
|
835
|
+
const atLimit = used >= REENTRY_ROUND_LIMIT;
|
|
836
|
+
let continuationAuthorized = false;
|
|
837
|
+
if (atLimit) {
|
|
838
|
+
const continuation = parseReentryContinuationAuthorization({
|
|
839
|
+
authorization: continuationRound === undefined || continuationRound === null
|
|
840
|
+
? null
|
|
841
|
+
: {
|
|
842
|
+
...(authorization && typeof authorization === 'object' && !Array.isArray(authorization) ? authorization : {}),
|
|
843
|
+
round: continuationRound,
|
|
844
|
+
},
|
|
845
|
+
target,
|
|
846
|
+
used,
|
|
847
|
+
});
|
|
848
|
+
if (!continuation.ok) {
|
|
849
|
+
return { ok: false, action: 'block', reason: 'round-limit-reached', used, limit: REENTRY_ROUND_LIMIT };
|
|
850
|
+
}
|
|
851
|
+
continuationAuthorized = true;
|
|
852
|
+
} else if (continuationRound !== undefined && continuationRound !== null) {
|
|
853
|
+
return { ok: false, action: 'block', reason: 'continuation-not-required', used, limit: REENTRY_ROUND_LIMIT };
|
|
854
|
+
}
|
|
855
|
+
const noop = reentryNoOpDecision({
|
|
856
|
+
currentNode: state?.currentNode,
|
|
857
|
+
target,
|
|
858
|
+
protocol,
|
|
859
|
+
completedNodes: state?.completedNodes,
|
|
860
|
+
});
|
|
861
|
+
if (noop.noop && !atLimit) {
|
|
862
|
+
return { ok: true, action: 'noop', reason: noop.reason, target, completedNodes: noop.completedNodes };
|
|
863
|
+
}
|
|
864
|
+
const source = reentrySourceDecision({
|
|
865
|
+
currentNode: state?.currentNode,
|
|
866
|
+
activeChange,
|
|
867
|
+
});
|
|
868
|
+
if (!source.ok) return { ok: false, action: 'block', reason: source.reason };
|
|
869
|
+
const parsed = parseReentryAuthorization({ authorization, target });
|
|
870
|
+
if (!parsed.ok) return { ok: false, action: 'block', reason: parsed.reason };
|
|
871
|
+
const round = reentryRoundDecision({ history: state?.history, changeName: activeChange, continuationAuthorized });
|
|
872
|
+
if (!round.ok) {
|
|
873
|
+
return { ok: false, action: 'block', reason: round.reason, used: round.used, limit: round.limit };
|
|
874
|
+
}
|
|
875
|
+
return {
|
|
876
|
+
ok: true,
|
|
877
|
+
action: 'apply',
|
|
878
|
+
reason: 'reentry-authorized',
|
|
879
|
+
changeName: activeChange,
|
|
880
|
+
target,
|
|
881
|
+
completedNodes: noop.completedNodes,
|
|
882
|
+
round: round.nextRound,
|
|
883
|
+
continuationAuthorized,
|
|
884
|
+
authorization: parsed.authorization,
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
export {
|
|
889
|
+
route,
|
|
890
|
+
protocolTaskFilePath,
|
|
891
|
+
hasSubagentNode,
|
|
892
|
+
firstIncompletePostExecNode,
|
|
893
|
+
EXECUTE_FAMILY_NODE_IDS,
|
|
894
|
+
FIX_SECTION_TITLE_FALLBACK,
|
|
895
|
+
normalizeHeading,
|
|
896
|
+
classifyFixReturnCause,
|
|
897
|
+
resolveFixRollbackDecision,
|
|
898
|
+
resolveFixRollbackState,
|
|
899
|
+
applyFixRollbackRound,
|
|
900
|
+
resolveFixReturnNode,
|
|
901
|
+
REENTRY_TARGET_NODE_IDS,
|
|
902
|
+
REENTRY_ROUND_LIMIT,
|
|
903
|
+
isSingleSegmentChangeName,
|
|
904
|
+
reentrySourceDecision,
|
|
905
|
+
resolveReentryTarget,
|
|
906
|
+
parseReentryAuthorization,
|
|
907
|
+
parseReentryContinuationAuthorization,
|
|
908
|
+
reentryRoundCount,
|
|
909
|
+
reentryRoundDecision,
|
|
910
|
+
reentryPredecessorIntersection,
|
|
911
|
+
reentryNoOpDecision,
|
|
912
|
+
resolveReentryDecision,
|
|
913
|
+
};
|