doukui 0.6.0 → 0.9.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/README.en.md +85 -18
- package/README.md +32 -72
- package/bin/commands/help.js +2 -25
- package/bin/commands/plan-lint.js +105 -0
- package/bin/commands/verify.js +263 -0
- package/bin/doukui.js +3 -3
- package/package.json +2 -3
- package/plugins/core/hook-session-start/index.js +1 -1
- package/plugins/core/hook-skill-gate/index.js +64 -15
- package/plugins/core/hook-skill-gate/plugin.json +1 -1
- package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +7 -28
- package/plugins/core/skill-agent-dispatcher/monitoring-reference.md +89 -0
- package/plugins/core/skill-agent-dispatcher/plugin.json +1 -1
- package/plugins/core/skill-agent-dispatcher/recovery-reference.md +132 -0
- package/plugins/core/skill-agent-dispatcher/roles-reference.md +9 -22
- package/plugins/core/skill-agent-dispatcher/skill.md +124 -796
- package/plugins/core/skill-agentic-loop/mirror-rules.md +95 -24
- package/plugins/core/skill-agentic-loop/plugin.json +2 -7
- package/plugins/core/skill-agentic-loop/skill.md +125 -354
- package/plugins/core/skill-batch-task-creator/plugin.json +1 -1
- package/plugins/core/skill-checklist/skill.md +15 -141
- package/plugins/core/skill-completion-report/plugin.json +1 -1
- package/plugins/core/skill-completion-report/skill.md +7 -1
- package/plugins/core/skill-doukui-plan/plugin.json +1 -1
- package/plugins/core/skill-doukui-plan/skill.md +24 -21
- package/plugins/core/skill-experience-logger/plugin.json +1 -1
- package/plugins/core/skill-human-checkpoint/skill.md +1 -0
- package/plugins/core/skill-split-work-package/plugin.json +1 -1
- package/plugins/core/skill-task-creator/plugin.json +1 -1
- package/plugins/core/skill-task-creator/skill.md +1 -139
- package/plugins/core/skill-workflow-orchestrator/plugin.json +1 -1
- package/plugins/plugin-registry.json +0 -48
- package/plugins/runtime/harness-build.js +5 -5
- package/plugins/runtime/plan-reader.js +54 -21
- package/plugins/runtime/resolve-plugin-path.js +2 -2
- package/templates/harness-config.yaml +0 -100
- package/bin/commands/loop-server.js +0 -357
- package/bin/commands/loop.js +0 -1508
- package/plugins/contracts/capabilities.js +0 -268
- package/plugins/contracts/checkresult-schema.json +0 -75
- package/plugins/core/provider-loop-engine/index.js +0 -1411
- package/plugins/core/provider-loop-engine/plugin.json +0 -15
- package/plugins/core/provider-memory-store/index.js +0 -510
- package/plugins/core/provider-memory-store/plugin.json +0 -9
- package/plugins/core/provider-state-store/index.js +0 -244
- package/plugins/core/provider-state-store/plugin.json +0 -9
- package/plugins/core/provider-watchdog/assets/daemon-config.template.json +0 -32
- package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +0 -676
- package/plugins/core/provider-watchdog/assets/watchdog.js +0 -754
- package/plugins/core/provider-watchdog/index.js +0 -151
- package/plugins/core/provider-watchdog/plugin.json +0 -13
- package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +0 -249
- package/plugins/core/skill-watchdog-manager/plugin.json +0 -10
- package/plugins/core/skill-watchdog-manager/skill.md +0 -143
- package/plugins/core/validator-doc-sync/index.js +0 -248
- package/plugins/core/validator-doc-sync/plugin.json +0 -12
- package/plugins/core/validator-work-package/index.js +0 -300
- package/plugins/core/validator-work-package/plugin.json +0 -12
- package/plugins/runtime/audit-logger.js +0 -311
- package/plugins/runtime/build-cli.js +0 -89
- package/plugins/runtime/checkresult-validator.js +0 -131
- package/plugins/runtime/context-window.js +0 -81
- package/plugins/runtime/event-bus.js +0 -207
- package/plugins/runtime/executor-claude.js +0 -604
- package/plugins/runtime/executor-default.js +0 -448
- package/plugins/runtime/executor-local.js +0 -178
- package/plugins/runtime/executor-sdk.js +0 -415
- package/plugins/runtime/hook-dispatcher.js +0 -315
- package/plugins/runtime/loop-actuator.js +0 -292
- package/plugins/runtime/loop-coordinator.js +0 -347
- package/plugins/runtime/loop-defaults.js +0 -29
- package/plugins/runtime/loop-dispatch-batch.js +0 -351
- package/plugins/runtime/loop-executor.js +0 -120
- package/plugins/runtime/loop-report.js +0 -395
- package/plugins/runtime/loop-server-core.js +0 -750
- package/plugins/runtime/loop-snapshot.js +0 -581
- package/plugins/runtime/loop-trace.js +0 -242
- package/plugins/runtime/loop-worktree.js +0 -404
- package/plugins/runtime/multi-window-coordinator.js +0 -560
- package/plugins/runtime/objective-verifier.js +0 -136
- package/plugins/runtime/plan-lint.js +0 -106
- package/plugins/runtime/plugin-loader.js +0 -798
- package/plugins/runtime/plugin-trust.js +0 -182
- package/plugins/runtime/provider-failover.js +0 -114
- package/plugins/runtime/provider-resolver.js +0 -342
- package/plugins/runtime/reflection-evaluator.js +0 -545
- package/plugins/runtime/sandbox-context.js +0 -235
- package/plugins/runtime/sandbox-manager.js +0 -609
- package/plugins/runtime/sandbox-worker.js +0 -215
- package/plugins/runtime/self-rescue-ladder.js +0 -51
- package/plugins/runtime/text-tokenize.js +0 -25
- package/plugins/runtime/validator-pipeline.js +0 -475
|
@@ -1,1411 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Provider: Loop Engine
|
|
3
|
-
*
|
|
4
|
-
* Agentic Loop 决策状态机核心(WP-174-2)。
|
|
5
|
-
* 实现 Observe → Think → Act → Reflect → Decide 五阶段循环。
|
|
6
|
-
*
|
|
7
|
-
* 设计依据:docs/reports/agentic-loop-design.md 第 5.1 节(接口契约)。
|
|
8
|
-
*
|
|
9
|
-
* 关键约定:
|
|
10
|
-
* - 状态持久化复用 state-store(key: "loop.{loopId}"),不自写文件 IO。
|
|
11
|
-
* - 每 phase 完成后调 persist(),防上下文压缩丢失(对照 dispatcher-state.json)。
|
|
12
|
-
* - init() 先读 state-store,status==="running" 则从断点恢复。
|
|
13
|
-
* - observe/reflect 委托 loop-snapshot / reflection-evaluator(WP-174-3);
|
|
14
|
-
* 未注入 delegate 时降级为最小可用实现,保证状态流转完整。
|
|
15
|
-
* - act 委托 agent-dispatcher(WP-174-4 注入),此处留占位接口。
|
|
16
|
-
* - decide 实现三类终止判定优先级:熔断 > 发散 > 达成 > 上限 > 继续(design.md §6)。
|
|
17
|
-
*
|
|
18
|
-
* Capabilities(factory 返回):
|
|
19
|
-
* - init(opts) 初始化/恢复 loop 运行
|
|
20
|
-
* - observe(loopId) 聚合环境快照
|
|
21
|
-
* - think(loopId, snapshot) 基于快照决策下一步
|
|
22
|
-
* - act(loopId, decision) 执行决策(占位,委托 dispatcher)
|
|
23
|
-
* - reflect(loopId, snapshot) 评分(委托 reflection-evaluator)
|
|
24
|
-
* - decide(loopId, evalResult) 三类终止判定
|
|
25
|
-
* - step(loopId) 单步编排(observe→think→act→reflect→decide)
|
|
26
|
-
* - persist(loopId) 持久化当前状态
|
|
27
|
-
* - getState(loopId) 查询 loop 状态
|
|
28
|
-
* - applyDirective(loopId, d) 外部指令(pause/abort/abort_all)
|
|
29
|
-
* - inject(delegate) 依赖注入(loop-snapshot / reflection-evaluator / actuator)
|
|
30
|
-
*/
|
|
31
|
-
|
|
32
|
-
'use strict';
|
|
33
|
-
|
|
34
|
-
var path = require('path');
|
|
35
|
-
var fs = require('fs');
|
|
36
|
-
var { ProviderPlugin } = require('../../contracts/plugin-interface');
|
|
37
|
-
var { StateStore, FileSystemAdapter } = require('../../runtime/state-store');
|
|
38
|
-
|
|
39
|
-
// loop-report 触顶总结报告生成器(WP-177-1-impl-c)。require 失败降级为 null,
|
|
40
|
-
// _generateTerminalReport 会据此产出降级报告(report=null + 告警),保证 engine 不崩。
|
|
41
|
-
var loopReport = null;
|
|
42
|
-
try {
|
|
43
|
-
loopReport = require('../../runtime/loop-report');
|
|
44
|
-
} catch (_e) {
|
|
45
|
-
loopReport = null;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// 三类终态 verdict(触发报告生成的判定集合,WP-177-2-impl-c)。
|
|
49
|
-
// achieved 不在内 —— achieved 走 completion(skill-completion-report),不产终态报告。
|
|
50
|
-
var TERMINAL_REPORT_VERDICTS = { timeout: true, diverged: true, circuit_broken: true };
|
|
51
|
-
|
|
52
|
-
// ---------------------------------------------------------------------------
|
|
53
|
-
// 默认配置(单源化 Phase B-1:唯一默认源 = plugins/runtime/loop-defaults.js;
|
|
54
|
-
// 与 plugin.json config 的静态镜像对齐,design.md §5.3.3)
|
|
55
|
-
// ---------------------------------------------------------------------------
|
|
56
|
-
|
|
57
|
-
var DEFAULT_CONFIG = require('../../runtime/loop-defaults');
|
|
58
|
-
|
|
59
|
-
// ---------------------------------------------------------------------------
|
|
60
|
-
// 工具函数
|
|
61
|
-
// ---------------------------------------------------------------------------
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* 生成 loop 唯一 ID。
|
|
65
|
-
* @returns {string} e.g. "loop-20260612-143000-abc123"
|
|
66
|
-
*/
|
|
67
|
-
function generateLoopId() {
|
|
68
|
-
var d = new Date();
|
|
69
|
-
var pad = function (n) { return n < 10 ? '0' + n : '' + n; };
|
|
70
|
-
var stamp =
|
|
71
|
-
d.getUTCFullYear() +
|
|
72
|
-
pad(d.getUTCMonth() + 1) +
|
|
73
|
-
pad(d.getUTCDate()) +
|
|
74
|
-
'-' +
|
|
75
|
-
pad(d.getUTCHours()) +
|
|
76
|
-
pad(d.getUTCMinutes()) +
|
|
77
|
-
pad(d.getUTCSeconds());
|
|
78
|
-
var rand = Math.random().toString(36).slice(2, 8);
|
|
79
|
-
return 'loop-' + stamp + '-' + rand;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* ISO 时间戳。
|
|
84
|
-
* @returns {string}
|
|
85
|
-
*/
|
|
86
|
-
function nowIso() {
|
|
87
|
-
return new Date().toISOString();
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* 浅合并配置:默认值 <- plugin.json config <- 用户 override。
|
|
92
|
-
* @param {object} base
|
|
93
|
-
* @param {object} override
|
|
94
|
-
* @returns {object}
|
|
95
|
-
*/
|
|
96
|
-
function mergeConfig(base, override) {
|
|
97
|
-
var out = {};
|
|
98
|
-
var baseKeys = Object.keys(base);
|
|
99
|
-
for (var i = 0; i < baseKeys.length; i++) {
|
|
100
|
-
var k = baseKeys[i];
|
|
101
|
-
out[k] = base[k];
|
|
102
|
-
}
|
|
103
|
-
if (override && typeof override === 'object') {
|
|
104
|
-
var ok = Object.keys(override);
|
|
105
|
-
for (var j = 0; j < ok.length; j++) {
|
|
106
|
-
var kk = ok[j];
|
|
107
|
-
out[kk] = override[kk];
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
return out;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* 构造一个新的 LoopState(design.md §5.1.1)。
|
|
115
|
-
* @param {object} opts - { loopId, teamName, goal }
|
|
116
|
-
* @returns {object}
|
|
117
|
-
*/
|
|
118
|
-
function createLoopState(opts) {
|
|
119
|
-
opts = opts || {};
|
|
120
|
-
var ts = nowIso();
|
|
121
|
-
return {
|
|
122
|
-
loopId: opts.loopId || generateLoopId(),
|
|
123
|
-
teamName: opts.teamName || '',
|
|
124
|
-
goal: opts.goal || {
|
|
125
|
-
wpIds: [],
|
|
126
|
-
checklistSpec: 'default',
|
|
127
|
-
successCriteria: 'all_pass_and_proximity>=goal',
|
|
128
|
-
},
|
|
129
|
-
iteration: 0,
|
|
130
|
-
phase: 'init',
|
|
131
|
-
startedAt: ts,
|
|
132
|
-
lastUpdatedAt: ts,
|
|
133
|
-
status: 'running', // running|achieved|timeout|diverged|circuit_broken|aborted|paused
|
|
134
|
-
history: [],
|
|
135
|
-
divergenceStreak: 0,
|
|
136
|
-
checkpoints: {},
|
|
137
|
-
lastSnapshot: null,
|
|
138
|
-
lastDecision: null,
|
|
139
|
-
lastEval: null,
|
|
140
|
-
lastVerdict: null,
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// ---------------------------------------------------------------------------
|
|
145
|
-
// Provider
|
|
146
|
-
// ---------------------------------------------------------------------------
|
|
147
|
-
|
|
148
|
-
class LoopEngineProvider extends ProviderPlugin {
|
|
149
|
-
constructor() {
|
|
150
|
-
super();
|
|
151
|
-
this.name = 'provider-loop-engine';
|
|
152
|
-
this.version = '1.0.0';
|
|
153
|
-
this.description = 'Agentic Loop 决策状态机 Provider';
|
|
154
|
-
this.provides = 'provider:loop-engine';
|
|
155
|
-
this.dependencies = ['provider:state-store', 'provider:watchdog'];
|
|
156
|
-
|
|
157
|
-
/** @type {StateStore|null} */
|
|
158
|
-
this._store = null;
|
|
159
|
-
/** @type {string} */
|
|
160
|
-
this._projectRoot = '';
|
|
161
|
-
/** @type {object} 合并后的运行时配置 */
|
|
162
|
-
this._config = mergeConfig(DEFAULT_CONFIG, {});
|
|
163
|
-
/**
|
|
164
|
-
* 注入的依赖(loop-snapshot / reflection-evaluator / actuator)。
|
|
165
|
-
* 由 WP-174-3 / WP-174-4 注入;未注入时 engine 走降级路径。
|
|
166
|
-
* @type {object}
|
|
167
|
-
*/
|
|
168
|
-
this._delegates = {
|
|
169
|
-
snapshot: null, // { aggregate(context, loopId) -> LoopSnapshot }
|
|
170
|
-
evaluator: null, // { score(context, loopId, snapshot, state) -> EvalResult }
|
|
171
|
-
actuator: null, // { execute(context, loopId, decision, state) -> {dispatched, checklistResult?} }
|
|
172
|
-
};
|
|
173
|
-
/** @type {object|null} onActivate 注入的 context */
|
|
174
|
-
this._context = null;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* 激活时初始化 state-store 句柄与配置。
|
|
179
|
-
* @param {PluginContext} context
|
|
180
|
-
*/
|
|
181
|
-
async onActivate(context) {
|
|
182
|
-
this._context = context;
|
|
183
|
-
this._projectRoot = this._resolveProjectRoot();
|
|
184
|
-
var stateFilePath = path.join(this._projectRoot, '.claude-state');
|
|
185
|
-
this._store = new StateStore({ filePath: stateFilePath });
|
|
186
|
-
|
|
187
|
-
// 从 plugin.json / registry config 合并配置(若 context 提供)
|
|
188
|
-
if (context && context.config && typeof context.config.get === 'function') {
|
|
189
|
-
try {
|
|
190
|
-
var pluginCfg = context.config.get('plugins.provider-loop-engine');
|
|
191
|
-
if (pluginCfg && typeof pluginCfg === 'object') {
|
|
192
|
-
this._config = mergeConfig(this._config, pluginCfg);
|
|
193
|
-
}
|
|
194
|
-
} catch (e) {
|
|
195
|
-
// 配置读取失败,沿用默认
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// 自动注入 loop-actuator(WP-177-2-impl-b):
|
|
200
|
-
// loop-actuator 是 runtime 模块(非 provider),不走 context.getProvider,直接 require。
|
|
201
|
-
// 幂等:仅当未注入 actuator 时才注入,允许外部 inject({actuator}) 覆盖(mock 优先)。
|
|
202
|
-
// require 失败(项目结构变化)降级为占位 + console.warn,保证 engine 不崩。
|
|
203
|
-
this._autoInjectLoopActuator();
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
* 自动注入 loop-actuator 作为 actuator delegate(WP-177-2-impl-b)。
|
|
208
|
-
*
|
|
209
|
-
* 设计约束(docs/wp/WP-177.md「技术方案 actuator 注入架构」):
|
|
210
|
-
* - loop-actuator 是 runtime 模块(非 provider),不走 context.getProvider,直接 require
|
|
211
|
-
* - 幂等:仅当 _delegates.actuator 为 null 时才注入(多次 onActivate / factory 不重复注入)
|
|
212
|
-
* - 外部 inject({actuator}) 优先:若已显式注入则不覆盖(mock/e2e 测试路径优先)
|
|
213
|
-
* - require 失败降级:console.warn 但不抛,保留 engine 可用性(act() 走降级占位分支)
|
|
214
|
-
*
|
|
215
|
-
* @private
|
|
216
|
-
*/
|
|
217
|
-
_autoInjectLoopActuator() {
|
|
218
|
-
if (this._delegates.actuator) return; // 幂等:已注入(含外部 mock)则不覆盖
|
|
219
|
-
try {
|
|
220
|
-
var loopActuator = require('../../runtime/loop-actuator');
|
|
221
|
-
if (loopActuator && typeof loopActuator.createActuator === 'function') {
|
|
222
|
-
this._delegates.actuator = loopActuator.createActuator();
|
|
223
|
-
}
|
|
224
|
-
} catch (e) {
|
|
225
|
-
// 降级:保留 _delegates.actuator=null,act() 走占位分支(dispatched:false)
|
|
226
|
-
// 不抛异常,保证 engine 主流程不崩(design.md §5.1.3 降级语义)
|
|
227
|
-
try {
|
|
228
|
-
console.warn('[provider-loop-engine] auto-inject loop-actuator failed: ' +
|
|
229
|
-
(e && e.message ? e.message : String(e)) + ';act() 将走降级占位');
|
|
230
|
-
} catch (_warnErr) {
|
|
231
|
-
// console 不可用时静默
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/**
|
|
237
|
-
* 生成触顶/发散/熔断终态报告并写入 state.terminalReport(WP-177-2-impl-c)。
|
|
238
|
-
*
|
|
239
|
-
* 出口行为改造:verdict ∈ {timeout, diverged, circuit_broken} 时不再依赖外部
|
|
240
|
-
* 「回 P1 human-checkpoint」,engine 自主调 loop-report 生成总结报告写 state,
|
|
241
|
-
* 供 skill.md Step 5(outputTerminalReport)直接读取输出。
|
|
242
|
-
*
|
|
243
|
-
* 内聚设计:所有终态出口(decide 写终态 status / step 提前 timeout 出口)统一经此,
|
|
244
|
-
* 保证无论哪条路径触顶,state.terminalReport 都被填充。
|
|
245
|
-
*
|
|
246
|
-
* 降级语义:loop-report require 失败 → terminalReport 置为 { degraded:true, verdict,
|
|
247
|
-
* markdown:null } 并 console.warn(不抛、不阻断终态流转);state 仍标记终态 status。
|
|
248
|
-
*
|
|
249
|
-
* @private
|
|
250
|
-
* @param {object} state 当前 loop state(已含 history/iteration/failingDrivers)
|
|
251
|
-
* @param {{verdict:string, reason?:string}} verdict 终态判定对象(取 .verdict)
|
|
252
|
-
* @returns {object} 写入 state.terminalReport 的报告对象(含 verdict/markdown/degraded)
|
|
253
|
-
*/
|
|
254
|
-
_generateTerminalReport(state, verdict) {
|
|
255
|
-
var verdictStr = (verdict && verdict.verdict) ? verdict.verdict : '';
|
|
256
|
-
if (!TERMINAL_REPORT_VERDICTS[verdictStr]) {
|
|
257
|
-
// 非三类终态(achieved/continue 等)不产报告
|
|
258
|
-
return null;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// 降级:loop-report 模块不可用,仍标记终态但报告为降级占位
|
|
262
|
-
if (!loopReport || typeof loopReport.generateTerminalReport !== 'function') {
|
|
263
|
-
var degraded = {
|
|
264
|
-
degraded: true,
|
|
265
|
-
verdict: verdictStr,
|
|
266
|
-
loopId: state ? state.loopId : '',
|
|
267
|
-
markdown: null,
|
|
268
|
-
summary: '终态报告生成降级:loop-report 模块不可用',
|
|
269
|
-
reason: 'require ../../runtime/loop-report 失败',
|
|
270
|
-
};
|
|
271
|
-
try {
|
|
272
|
-
console.warn('[provider-loop-engine] loop-report unavailable; terminal report degraded');
|
|
273
|
-
} catch (_warnErr) { /* console 不可用时静默 */ }
|
|
274
|
-
if (state) state.terminalReport = degraded;
|
|
275
|
-
return degraded;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// 主路径:纯函数生成报告(state 内含 history/failingDrivers/lastEval/loopId/iteration)
|
|
279
|
-
try {
|
|
280
|
-
var report = loopReport.generateTerminalReport(state, {
|
|
281
|
-
loopId: state ? state.loopId : '',
|
|
282
|
-
verdict: verdictStr,
|
|
283
|
-
});
|
|
284
|
-
if (state) state.terminalReport = report;
|
|
285
|
-
return report;
|
|
286
|
-
} catch (e) {
|
|
287
|
-
// generateTerminalReport 内部已对 state 缺失做容错,理论上不抛;防御性兜底
|
|
288
|
-
var fallback = {
|
|
289
|
-
degraded: true,
|
|
290
|
-
verdict: verdictStr,
|
|
291
|
-
loopId: state ? state.loopId : '',
|
|
292
|
-
markdown: null,
|
|
293
|
-
summary: '终态报告生成异常:' + (e && e.message ? e.message : String(e)),
|
|
294
|
-
};
|
|
295
|
-
if (state) state.terminalReport = fallback;
|
|
296
|
-
return fallback;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/**
|
|
301
|
-
* 构造传给 actuator.execute() 的 context(WP-177-2-impl-b)。
|
|
302
|
-
*
|
|
303
|
-
* 在原 context(onActivate 注入 / factory 形参)上叠加 getStateStore(),
|
|
304
|
-
* 返回 engine 自身的 _store 句柄。目的是让 loop-actuator.resolveStore 命中
|
|
305
|
-
* 优先级 1(context.getStateStore()),复用同一 StateStore 实例,避免
|
|
306
|
-
* actuator 自建实例与 engine _store 缓存不共享(pendingAction/lastChecklist
|
|
307
|
-
* 跨实例读写丢失)。
|
|
308
|
-
*
|
|
309
|
-
* 透传原 context 的所有字段(getProvider / config 等),仅追加 getStateStore。
|
|
310
|
-
* @private
|
|
311
|
-
* @param {PluginContext} context 原 context(可能为 null)
|
|
312
|
-
* @returns {object} 带 getStateStore() 的增强 context
|
|
313
|
-
*/
|
|
314
|
-
_buildActuatorContext(context) {
|
|
315
|
-
var base = context || {};
|
|
316
|
-
var store = this._store;
|
|
317
|
-
return Object.assign({}, base, {
|
|
318
|
-
getStateStore: function () { return store; },
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* factory 返回 loop-engine API。
|
|
324
|
-
* @param {PluginContext} context
|
|
325
|
-
* @returns {Promise<object>}
|
|
326
|
-
*/
|
|
327
|
-
async factory(context) {
|
|
328
|
-
var self = this;
|
|
329
|
-
|
|
330
|
-
// 确保 state-store 已初始化(factory 可能先于 onActivate 调用)
|
|
331
|
-
self._ensureStore();
|
|
332
|
-
|
|
333
|
-
// ---- 私有辅助 ----
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
* state-store key 前缀。
|
|
337
|
-
* @param {string} loopId
|
|
338
|
-
* @returns {string}
|
|
339
|
-
*/
|
|
340
|
-
function stateKey(loopId) {
|
|
341
|
-
return 'loop.' + loopId;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/**
|
|
345
|
-
* 读取 loop 状态(state-store)。
|
|
346
|
-
* @param {string} loopId
|
|
347
|
-
* @returns {Promise<object|undefined>}
|
|
348
|
-
*/
|
|
349
|
-
function loadState(loopId) {
|
|
350
|
-
return self._store.get(stateKey(loopId));
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
/**
|
|
354
|
-
* 写入完整 loop 状态并更新 lastUpdatedAt。
|
|
355
|
-
* @param {object} state
|
|
356
|
-
* @returns {Promise<void>}
|
|
357
|
-
*/
|
|
358
|
-
async function saveState(state) {
|
|
359
|
-
state.lastUpdatedAt = nowIso();
|
|
360
|
-
await self._store.set(stateKey(state.loopId), state);
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
/**
|
|
364
|
-
* 记录一轮判定到 history(防丢失写回,design.md §8.3 不变量)。
|
|
365
|
-
* @param {object} state
|
|
366
|
-
* @param {object} entry
|
|
367
|
-
*/
|
|
368
|
-
function pushHistory(state, entry) {
|
|
369
|
-
state.history.push(entry);
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* 获取快照聚合 delegate(注入或降级)。
|
|
374
|
-
* @returns {object}
|
|
375
|
-
*/
|
|
376
|
-
function getSnapshotDelegate() {
|
|
377
|
-
return self._delegates.snapshot;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
/**
|
|
381
|
-
* 获取评分 delegate(注入或降级)。
|
|
382
|
-
* @returns {object}
|
|
383
|
-
*/
|
|
384
|
-
function getEvaluatorDelegate() {
|
|
385
|
-
return self._delegates.evaluator;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
/**
|
|
389
|
-
* 获取执行器 delegate(注入或占位)。
|
|
390
|
-
* @returns {object}
|
|
391
|
-
*/
|
|
392
|
-
function getActuatorDelegate() {
|
|
393
|
-
return self._delegates.actuator;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
// ---- 公开 API ----
|
|
397
|
-
|
|
398
|
-
/**
|
|
399
|
-
* loop-engine API 对象。step() 通过此引用调用 observe/think/act/reflect/decide,
|
|
400
|
-
* 保证单步编排顺序与每个 phase 的 persist 写回都走同一份实现。
|
|
401
|
-
* @type {object}
|
|
402
|
-
*/
|
|
403
|
-
var factoryApi = {
|
|
404
|
-
/**
|
|
405
|
-
* 初始化/恢复一次 loop 运行。
|
|
406
|
-
* 若 state-store 已有 loopId 且 status==="running",从断点恢复(防上下文压缩)。
|
|
407
|
-
* @param {object} opts - { loopId?, teamName, goal }
|
|
408
|
-
* @returns {Promise<{ loopId: string, restored: boolean, state: object }>}
|
|
409
|
-
*/
|
|
410
|
-
init: async function (opts) {
|
|
411
|
-
opts = opts || {};
|
|
412
|
-
var loopId = opts.loopId || generateLoopId();
|
|
413
|
-
|
|
414
|
-
// 运行时阈值 override(WP-177-2-impl-a):
|
|
415
|
-
// init(opts) 传入的 maxIterations / maxRoundTimeMs / maxWallTimeMs /
|
|
416
|
-
// divergenceThreshold / proximityGoal 优先级最高(默认 ← plugin.json ← override)。
|
|
417
|
-
// 仅当传入且为合法数值时覆盖,避免污染默认配置;其他 loopId/teamName
|
|
418
|
-
// 共享同一份 self._config,故 override 累积到 engine 实例(单 loop 场景
|
|
419
|
-
// 足够;多 loop 并发共享阈值符合「同一 engine 一套阈值」语义)。
|
|
420
|
-
var override = {};
|
|
421
|
-
if (typeof opts.maxIterations === 'number') override.max_iterations = opts.maxIterations;
|
|
422
|
-
if (typeof opts.maxRoundTimeMs === 'number') override.max_round_time_ms = opts.maxRoundTimeMs;
|
|
423
|
-
if (typeof opts.maxWallTimeMs === 'number') override.max_wall_time_ms = opts.maxWallTimeMs;
|
|
424
|
-
if (typeof opts.divergenceThreshold === 'number') override.divergence_threshold = opts.divergenceThreshold;
|
|
425
|
-
if (typeof opts.proximityGoal === 'number') override.proximity_goal = opts.proximityGoal;
|
|
426
|
-
if (Object.keys(override).length > 0) {
|
|
427
|
-
self._config = mergeConfig(self._config, override);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
var existing = await loadState(loopId);
|
|
431
|
-
|
|
432
|
-
if (existing && existing.status === 'running') {
|
|
433
|
-
// 从断点恢复(design.md §8.2 / 5.1.3)
|
|
434
|
-
// 保持 iteration/history/phase 不回退(不变量 §8.3)
|
|
435
|
-
// WP-S1:恢复时应用自救预算 bonus(extendBudget 的持久化回读——
|
|
436
|
-
// restore 后 _config 重算会丢 bonus,这里补回,_decide 零改动)
|
|
437
|
-
if (existing.selfRescue && existing.selfRescue.budgetBonus) {
|
|
438
|
-
self._config.max_iterations += existing.selfRescue.budgetBonus.iterations || 0;
|
|
439
|
-
self._config.max_wall_time_ms += existing.selfRescue.budgetBonus.wallMs || 0;
|
|
440
|
-
}
|
|
441
|
-
existing.lastUpdatedAt = nowIso();
|
|
442
|
-
return { loopId: loopId, restored: true, state: existing };
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
var state = createLoopState({
|
|
446
|
-
loopId: loopId,
|
|
447
|
-
teamName: opts.teamName,
|
|
448
|
-
goal: opts.goal,
|
|
449
|
-
});
|
|
450
|
-
await saveState(state);
|
|
451
|
-
return { loopId: loopId, restored: false, state: state };
|
|
452
|
-
},
|
|
453
|
-
|
|
454
|
-
/**
|
|
455
|
-
* Observe 阶段:聚合环境快照。
|
|
456
|
-
* 委托 loop-snapshot(WP-174-3);未注入时降级为最小快照(仅 loop 自身状态)。
|
|
457
|
-
* @param {string} loopId
|
|
458
|
-
* @returns {Promise<object>} LoopSnapshot(design.md §5.2.2)
|
|
459
|
-
*/
|
|
460
|
-
observe: async function (loopId) {
|
|
461
|
-
var state = await loadState(loopId);
|
|
462
|
-
if (!state) {
|
|
463
|
-
throw new Error('loop-engine.observe: unknown loopId ' + loopId);
|
|
464
|
-
}
|
|
465
|
-
state.phase = 'observe';
|
|
466
|
-
|
|
467
|
-
var snapshot;
|
|
468
|
-
var snapDelegate = getSnapshotDelegate();
|
|
469
|
-
if (snapDelegate && typeof snapDelegate.aggregate === 'function') {
|
|
470
|
-
snapshot = await snapDelegate.aggregate(self._context || context, loopId);
|
|
471
|
-
} else {
|
|
472
|
-
// 降级:最小可用快照(loop 自身上下文,不含外部源)
|
|
473
|
-
snapshot = self._fallbackSnapshot(loopId, state);
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
state.lastSnapshot = snapshot;
|
|
477
|
-
await saveState(state); // observe 后 persist(design.md §5.1.3)
|
|
478
|
-
return snapshot;
|
|
479
|
-
},
|
|
480
|
-
|
|
481
|
-
/**
|
|
482
|
-
* Think 阶段:基于快照决策下一步。
|
|
483
|
-
* 决策类型:dispatch / retry / resplit / noop。
|
|
484
|
-
* @param {string} loopId
|
|
485
|
-
* @param {object} snapshot
|
|
486
|
-
* @returns {Promise<object>} { action, targetWp?, strategy?, reason }
|
|
487
|
-
*/
|
|
488
|
-
think: async function (loopId, snapshot) {
|
|
489
|
-
var state = await loadState(loopId);
|
|
490
|
-
if (!state) {
|
|
491
|
-
throw new Error('loop-engine.think: unknown loopId ' + loopId);
|
|
492
|
-
}
|
|
493
|
-
state.phase = 'think';
|
|
494
|
-
|
|
495
|
-
var decision = self._think(state, snapshot || state.lastSnapshot);
|
|
496
|
-
|
|
497
|
-
state.lastDecision = decision;
|
|
498
|
-
await saveState(state); // think 后 persist
|
|
499
|
-
return decision;
|
|
500
|
-
},
|
|
501
|
-
|
|
502
|
-
/**
|
|
503
|
-
* Act 阶段:执行决策(驱动 agent-dispatcher + checklist)。
|
|
504
|
-
* 委托注入的 actuator(WP-177-2-impl-b:默认自动注入 loop-actuator)。
|
|
505
|
-
* actuator 不可用时降级记录决策(不返回 placeholder,保留 dispatched:false 兜底)。
|
|
506
|
-
* @param {string} loopId
|
|
507
|
-
* @param {object} decision
|
|
508
|
-
* @returns {Promise<{ dispatched: boolean, checklistResult?: object }>}
|
|
509
|
-
*/
|
|
510
|
-
act: async function (loopId, decision) {
|
|
511
|
-
var state = await loadState(loopId);
|
|
512
|
-
if (!state) {
|
|
513
|
-
throw new Error('loop-engine.act: unknown loopId ' + loopId);
|
|
514
|
-
}
|
|
515
|
-
state.phase = 'act';
|
|
516
|
-
|
|
517
|
-
// 单轮时长基线(WP-177-2-impl-a/b):act 是单轮执行主体,记录开始时间供
|
|
518
|
-
// step() 在 act 完成后校验单轮耗时是否超 max_round_time_ms。
|
|
519
|
-
var actStartedAt = Date.now();
|
|
520
|
-
|
|
521
|
-
var actuator = getActuatorDelegate();
|
|
522
|
-
var result;
|
|
523
|
-
if (actuator && typeof actuator.execute === 'function') {
|
|
524
|
-
// 主路径:调用注入的 actuator(默认 loop-actuator),序列化 decision 为
|
|
525
|
-
// dispatcher 待执行指令写入 state-store,返回 {dispatched:true, checklistResult?}。
|
|
526
|
-
//
|
|
527
|
-
// 传入增强 context(actuatorContext):在原 context 上叠加 getStateStore(),
|
|
528
|
-
// 使 loop-actuator.resolveStore 复用 engine 的 _store 实例(避免两个 StateStore
|
|
529
|
-
// 实例缓存不共享导致 pendingAction/lastChecklist 读写不一致,WP-177-2-impl-b)。
|
|
530
|
-
var actuatorContext = self._buildActuatorContext(context);
|
|
531
|
-
result = await actuator.execute(actuatorContext, loopId, decision, state);
|
|
532
|
-
} else {
|
|
533
|
-
// 降级兜底(actuator require 失败 / 显式置空):不执行副作用,仅记录决策。
|
|
534
|
-
// 注意:不再返回 placeholder:true(WP-177-2-impl-b 移除占位语义);
|
|
535
|
-
// dispatched:false 表示本轮无指令产出,step() 仍可继续流转。
|
|
536
|
-
result = { dispatched: false, checklistResult: undefined, degraded: true };
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
// 将 checklist 结果写入独立子 key(供 reflection-evaluator 消费,design.md §5.4.4)
|
|
540
|
-
if (result && result.checklistResult) {
|
|
541
|
-
await self._store.set(stateKey(loopId) + '.lastChecklist', result.checklistResult);
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
// 单轮耗时记录(供 step() 校验 max_round_time_ms,WP-177-2-impl-a/b)
|
|
545
|
-
if (result) {
|
|
546
|
-
result.roundElapsedMs = Date.now() - actStartedAt;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
state.lastActResult = result;
|
|
550
|
-
await saveState(state); // act 后 persist
|
|
551
|
-
return result;
|
|
552
|
-
},
|
|
553
|
-
|
|
554
|
-
/**
|
|
555
|
-
* Reflect 阶段:评分(委托 reflection-evaluator,WP-174-3)。
|
|
556
|
-
* @param {string} loopId
|
|
557
|
-
* @param {object} snapshot
|
|
558
|
-
* @returns {Promise<object>} EvalResult(design.md §5.3.2)
|
|
559
|
-
*/
|
|
560
|
-
reflect: async function (loopId, snapshot) {
|
|
561
|
-
var state = await loadState(loopId);
|
|
562
|
-
if (!state) {
|
|
563
|
-
throw new Error('loop-engine.reflect: unknown loopId ' + loopId);
|
|
564
|
-
}
|
|
565
|
-
state.phase = 'reflect';
|
|
566
|
-
|
|
567
|
-
var evalDelegate = getEvaluatorDelegate();
|
|
568
|
-
var evalResult;
|
|
569
|
-
if (evalDelegate && typeof evalDelegate.score === 'function') {
|
|
570
|
-
evalResult = await evalDelegate.score(
|
|
571
|
-
self._context || context,
|
|
572
|
-
loopId,
|
|
573
|
-
snapshot || state.lastSnapshot,
|
|
574
|
-
state
|
|
575
|
-
);
|
|
576
|
-
} else {
|
|
577
|
-
// 降级:基于 lastChecklist 的最小评分
|
|
578
|
-
evalResult = self._fallbackEval(loopId, state, snapshot || state.lastSnapshot);
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
// 同步发散计数 + 失败驱动到 state(decide / 下轮 Think 依赖,修复点 B / 偏差1)
|
|
582
|
-
// - divergenceStreak:发散判定输入(design.md §6.3.1)
|
|
583
|
-
// - failingDrivers:失败项明细,回填后供下轮 Think 的 retry decision 携带、
|
|
584
|
-
// 以及运行时 Claude 从 state 直接读取(偏差1:engine 原先只回填 streak,
|
|
585
|
-
// 失败明细未进 state,retry 反馈链路在 engine 路径断裂)
|
|
586
|
-
state.divergenceStreak = evalResult.divergenceStreak || 0;
|
|
587
|
-
state.failingDrivers = evalResult.failingDrivers || [];
|
|
588
|
-
state.lastEval = evalResult;
|
|
589
|
-
await saveState(state); // reflect 后 persist
|
|
590
|
-
return evalResult;
|
|
591
|
-
},
|
|
592
|
-
|
|
593
|
-
/**
|
|
594
|
-
* Decide 阶段:三类终止判定(design.md §6,优先级 熔断>发散>达成>上限>继续)。
|
|
595
|
-
* @param {string} loopId
|
|
596
|
-
* @param {object} evalResult
|
|
597
|
-
* @returns {Promise<{ verdict: string, reason: string }>}
|
|
598
|
-
*/
|
|
599
|
-
decide: async function (loopId, evalResult) {
|
|
600
|
-
var state = await loadState(loopId);
|
|
601
|
-
if (!state) {
|
|
602
|
-
throw new Error('loop-engine.decide: unknown loopId ' + loopId);
|
|
603
|
-
}
|
|
604
|
-
state.phase = 'decide';
|
|
605
|
-
|
|
606
|
-
// 优先查询 watchdog 健康(熔断判定),失败降级为健康
|
|
607
|
-
var watchdogHealth = await self._queryWatchdogHealth(context);
|
|
608
|
-
|
|
609
|
-
var verdict = self._decide(state, evalResult || state.lastEval, watchdogHealth);
|
|
610
|
-
|
|
611
|
-
state.lastVerdict = verdict;
|
|
612
|
-
// 终止类 verdict 写终态 status(design.md §6.1-6.3)
|
|
613
|
-
if (verdict.verdict === 'achieved') state.status = 'achieved';
|
|
614
|
-
else if (verdict.verdict === 'timeout') state.status = 'timeout';
|
|
615
|
-
else if (verdict.verdict === 'diverged') state.status = 'diverged';
|
|
616
|
-
else if (verdict.verdict === 'circuit_broken') state.status = 'circuit_broken';
|
|
617
|
-
|
|
618
|
-
// WP-177-2-impl-c:三类终态(timeout/diverged/circuit_broken)自主生成报告写 state,
|
|
619
|
-
// 不再依赖外部「回 P1」;achieved 不产报告(走 completion)。
|
|
620
|
-
// decide 是 timeout/diverged/circuit_broken 的主要产出点(_decide 主体判定),
|
|
621
|
-
// 故在此内聚生成。step() 的提前 timeout 出口另调 _generateTerminalReport 补报告。
|
|
622
|
-
if (TERMINAL_REPORT_VERDICTS[verdict.verdict]) {
|
|
623
|
-
self._generateTerminalReport(state, verdict);
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
await saveState(state); // decide 后 persist
|
|
627
|
-
return verdict;
|
|
628
|
-
},
|
|
629
|
-
|
|
630
|
-
/**
|
|
631
|
-
* 单步推进:observe→think→act→reflect→decide 一轮。
|
|
632
|
-
* skill-agentic-loop 在 while 循环中调用(design.md §4.1)。
|
|
633
|
-
* @param {string} loopId
|
|
634
|
-
* @returns {Promise<{ verdict: string, iteration: number, state: object }>}
|
|
635
|
-
*/
|
|
636
|
-
step: async function (loopId) {
|
|
637
|
-
var state = await loadState(loopId);
|
|
638
|
-
if (!state) {
|
|
639
|
-
throw new Error('loop-engine.step: unknown loopId ' + loopId);
|
|
640
|
-
}
|
|
641
|
-
// 已终止则直接返回,不推进
|
|
642
|
-
if (state.status !== 'running' && state.status !== 'paused') {
|
|
643
|
-
return {
|
|
644
|
-
verdict: state.lastVerdict ? state.lastVerdict.verdict : state.status,
|
|
645
|
-
iteration: state.iteration,
|
|
646
|
-
state: state,
|
|
647
|
-
// 透传已生成的终态报告(终态已在前次出口写入 state.terminalReport)
|
|
648
|
-
report: state.terminalReport || null,
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
// 单轮开始前先检查墙钟硬上限。
|
|
653
|
-
// iteration 上限改由 _decide 在轮末统一判定(修复末轮达成被误判 timeout 的 bug):
|
|
654
|
-
// 预检在 iteration 递增前、拿不到本轮 evalResult,无法判本轮是否达成;放行让 _decide
|
|
655
|
-
// 用最新 evalResult 判——达成则 achieved、未达成才 timeout(兜底)。max_iterations 硬上限
|
|
656
|
-
// 由 _decide + driver safetyMax 双兜底,不会死循环。
|
|
657
|
-
var wallElapsed = Date.now() - new Date(state.startedAt).getTime();
|
|
658
|
-
if (wallElapsed >= self._config.max_wall_time_ms) {
|
|
659
|
-
var wallVerdict = { verdict: 'timeout', reason: '墙钟上限已达 max_wall_time_ms' };
|
|
660
|
-
state.status = 'timeout';
|
|
661
|
-
state.lastVerdict = wallVerdict;
|
|
662
|
-
self._generateTerminalReport(state, wallVerdict);
|
|
663
|
-
await saveState(state);
|
|
664
|
-
return {
|
|
665
|
-
verdict: 'timeout',
|
|
666
|
-
iteration: state.iteration,
|
|
667
|
-
state: state,
|
|
668
|
-
report: state.terminalReport || null,
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
// iteration 单调递增(不变量 §8.3)
|
|
673
|
-
state.iteration = state.iteration + 1;
|
|
674
|
-
await saveState(state);
|
|
675
|
-
|
|
676
|
-
// Observe → Think → Act → Reflect → Decide(显式顺序,每个 phase 各自 persist)
|
|
677
|
-
// WP-196-1-impl:五段式阶段级耗时打点(仅观测,决策逻辑零改动)。
|
|
678
|
-
// 各阶段前后用 Date.now() 包裹记 {phase, startMs, endMs, elapsedMs, summary},
|
|
679
|
-
// 全程 try/catch 降级——观测异常绝不阻断 loop 主流程(承袭 WP-191 心跳降级纪律)。
|
|
680
|
-
var phaseTimings = [];
|
|
681
|
-
function timePhase(name, fn) {
|
|
682
|
-
// 返回 Promise<value>;计时失败时仍返回 fn 结果,仅丢失 timing。
|
|
683
|
-
var startMs = Date.now();
|
|
684
|
-
var p;
|
|
685
|
-
try {
|
|
686
|
-
p = Promise.resolve(fn());
|
|
687
|
-
} catch (e) {
|
|
688
|
-
p = Promise.reject(e);
|
|
689
|
-
}
|
|
690
|
-
return p.then(function (value) {
|
|
691
|
-
try {
|
|
692
|
-
phaseTimings.push({
|
|
693
|
-
phase: name,
|
|
694
|
-
startMs: startMs,
|
|
695
|
-
endMs: Date.now(),
|
|
696
|
-
elapsedMs: Date.now() - startMs,
|
|
697
|
-
});
|
|
698
|
-
} catch (_te) { /* 计时降级:忽略 */ }
|
|
699
|
-
return value;
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
var snapshot = await timePhase('observe', function () { return factoryApi.observe(loopId); });
|
|
704
|
-
var decision = await timePhase('think', function () { return factoryApi.think(loopId, snapshot); });
|
|
705
|
-
var actResult = await timePhase('act', function () { return factoryApi.act(loopId, decision); });
|
|
706
|
-
|
|
707
|
-
// 单轮时长校验(WP-177-2-impl-a/b):act 完成后若本轮耗时超过
|
|
708
|
-
// max_round_time_ms,直接判 timeout 终止,跳过 reflect/decide。
|
|
709
|
-
// act() 已在 lastActResult.roundElapsedMs 记录单轮耗时;这里读取校验。
|
|
710
|
-
// 超时语义:单轮 act 拖过最长时间视为「本轮卡死」,提前终止避免无限挂起。
|
|
711
|
-
var roundMs = (actResult && typeof actResult.roundElapsedMs === 'number')
|
|
712
|
-
? actResult.roundElapsedMs : 0;
|
|
713
|
-
if (roundMs >= self._config.max_round_time_ms) {
|
|
714
|
-
var stateTimeout = await loadState(loopId);
|
|
715
|
-
stateTimeout.status = 'timeout';
|
|
716
|
-
stateTimeout.lastVerdict = {
|
|
717
|
-
verdict: 'timeout',
|
|
718
|
-
reason: '单轮耗时 ' + roundMs + 'ms 已达上限 max_round_time_ms ' +
|
|
719
|
-
self._config.max_round_time_ms,
|
|
720
|
-
};
|
|
721
|
-
pushHistory(stateTimeout, {
|
|
722
|
-
iteration: stateTimeout.iteration,
|
|
723
|
-
snapshotSummary: self._summarizeSnapshot(snapshot),
|
|
724
|
-
decision: decision,
|
|
725
|
-
eval: { roundTimeout: true, roundElapsedMs: roundMs },
|
|
726
|
-
verdict: 'timeout',
|
|
727
|
-
timestamp: nowIso(),
|
|
728
|
-
});
|
|
729
|
-
// WP-177-2-impl-c:单轮超时出口自主生成报告(history 已写入,报告含本轮趋势)
|
|
730
|
-
self._generateTerminalReport(stateTimeout, stateTimeout.lastVerdict);
|
|
731
|
-
await saveState(stateTimeout);
|
|
732
|
-
return {
|
|
733
|
-
verdict: 'timeout',
|
|
734
|
-
iteration: stateTimeout.iteration,
|
|
735
|
-
state: stateTimeout,
|
|
736
|
-
report: stateTimeout.terminalReport || null,
|
|
737
|
-
// WP-196-1-impl:单轮超时出口已跑完 observe/think/act,附已采集的阶段耗时
|
|
738
|
-
// (reflect/decide 未执行故缺)。纯观测,driver 落盘用。
|
|
739
|
-
phaseTimings: phaseTimings,
|
|
740
|
-
};
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
var evalResult = await timePhase('reflect', function () { return factoryApi.reflect(loopId, snapshot); });
|
|
744
|
-
var verdict = await timePhase('decide', function () { return factoryApi.decide(loopId, evalResult); });
|
|
745
|
-
|
|
746
|
-
// 写本轮历史(防丢失,发散检测依赖完整 history)
|
|
747
|
-
var stateFinal = await loadState(loopId);
|
|
748
|
-
pushHistory(stateFinal, {
|
|
749
|
-
iteration: stateFinal.iteration,
|
|
750
|
-
snapshotSummary: self._summarizeSnapshot(snapshot),
|
|
751
|
-
decision: decision,
|
|
752
|
-
eval: {
|
|
753
|
-
proximity: evalResult.proximity,
|
|
754
|
-
converged: evalResult.converged,
|
|
755
|
-
diverged: evalResult.diverged,
|
|
756
|
-
// 本轮失败项数(WP-176-5):下轮 reflection-evaluator 经
|
|
757
|
-
// prevFailedCountFromHistory 读取,驱动发散宽容(部分改进不计入 streak)。
|
|
758
|
-
failedCount: (typeof evalResult.failedCount === 'number')
|
|
759
|
-
? evalResult.failedCount : null,
|
|
760
|
-
// 无代码进展信号(WP-191-2-impl):下轮 reflection-evaluator 经
|
|
761
|
-
// noProgressStreakFromHistory 读取,累计 noProgressStreak 驱动发散熔断。
|
|
762
|
-
noProgress: evalResult.noProgress === true,
|
|
763
|
-
},
|
|
764
|
-
verdict: verdict.verdict,
|
|
765
|
-
timestamp: nowIso(),
|
|
766
|
-
});
|
|
767
|
-
// WP-177-2-impl-c:decide() 已生成报告,但那时 history 缺本轮记录;
|
|
768
|
-
// 此处 history 完整后对三类终态重新生成(覆盖),使 proximityTrend 含末轮。
|
|
769
|
-
// achieved/continue 不产报告(achieved 走 completion)。
|
|
770
|
-
var finalReport = null;
|
|
771
|
-
if (TERMINAL_REPORT_VERDICTS[verdict.verdict]) {
|
|
772
|
-
finalReport = self._generateTerminalReport(stateFinal, verdict);
|
|
773
|
-
}
|
|
774
|
-
await saveState(stateFinal);
|
|
775
|
-
|
|
776
|
-
// WP-196-1-impl:补各阶段产出摘要(仅读取已采集局部变量,不新增决策分支),
|
|
777
|
-
// 并把 phaseTimings 附到返回值供 driver 落盘/可见性输出。全程 try/catch 降级。
|
|
778
|
-
var phaseTimingsWithSummary = phaseTimings;
|
|
779
|
-
try {
|
|
780
|
-
var summaries = self._buildPhaseSummaries({
|
|
781
|
-
snapshot: snapshot,
|
|
782
|
-
decision: decision,
|
|
783
|
-
actResult: actResult,
|
|
784
|
-
evalResult: evalResult,
|
|
785
|
-
verdict: verdict,
|
|
786
|
-
});
|
|
787
|
-
phaseTimingsWithSummary = phaseTimings.map(function (pt) {
|
|
788
|
-
var enriched = Object.assign({}, pt);
|
|
789
|
-
if (summaries[pt.phase] !== undefined) enriched.summary = summaries[pt.phase];
|
|
790
|
-
return enriched;
|
|
791
|
-
});
|
|
792
|
-
} catch (_se) { /* 摘要降级:保留无 summary 的 timings */ }
|
|
793
|
-
|
|
794
|
-
return {
|
|
795
|
-
verdict: verdict.verdict,
|
|
796
|
-
iteration: stateFinal.iteration,
|
|
797
|
-
state: stateFinal,
|
|
798
|
-
report: finalReport,
|
|
799
|
-
// WP-196-1-impl:per-round 五段式阶段级耗时(observe/think/act/reflect/decide),
|
|
800
|
-
// 纯观测字段,driver 聚合落盘 .doukui/loop-{loopId}/trace.jsonl。
|
|
801
|
-
phaseTimings: phaseTimingsWithSummary,
|
|
802
|
-
};
|
|
803
|
-
},
|
|
804
|
-
|
|
805
|
-
/**
|
|
806
|
-
* 持久化当前 loop 状态(委托 state-store.set)。
|
|
807
|
-
* @param {string} loopId
|
|
808
|
-
* @returns {Promise<void>}
|
|
809
|
-
*/
|
|
810
|
-
persist: async function (loopId) {
|
|
811
|
-
var state = await loadState(loopId);
|
|
812
|
-
if (!state) {
|
|
813
|
-
throw new Error('loop-engine.persist: unknown loopId ' + loopId);
|
|
814
|
-
}
|
|
815
|
-
await saveState(state);
|
|
816
|
-
},
|
|
817
|
-
|
|
818
|
-
/**
|
|
819
|
-
* 查询 loop 状态。
|
|
820
|
-
* @param {string} loopId
|
|
821
|
-
* @returns {Promise<object>}
|
|
822
|
-
*/
|
|
823
|
-
getState: async function (loopId) {
|
|
824
|
-
var state = await loadState(loopId);
|
|
825
|
-
if (!state) {
|
|
826
|
-
throw new Error('loop-engine.getState: unknown loopId ' + loopId);
|
|
827
|
-
}
|
|
828
|
-
return state;
|
|
829
|
-
},
|
|
830
|
-
|
|
831
|
-
/**
|
|
832
|
-
* 外部指令(回 P1 人介入触发路径,参考 dispatcher daemon-actions)。
|
|
833
|
-
* action: "pause" | "abort" | "abort_all"
|
|
834
|
-
* @param {string} loopId
|
|
835
|
-
* @param {object} directive - { action, reason }
|
|
836
|
-
* @returns {Promise<boolean>}
|
|
837
|
-
*/
|
|
838
|
-
applyDirective: async function (loopId, directive) {
|
|
839
|
-
directive = directive || {};
|
|
840
|
-
var state = await loadState(loopId);
|
|
841
|
-
if (!state) {
|
|
842
|
-
throw new Error('loop-engine.applyDirective: unknown loopId ' + loopId);
|
|
843
|
-
}
|
|
844
|
-
var action = directive.action;
|
|
845
|
-
if (action === 'pause') {
|
|
846
|
-
state.status = 'paused';
|
|
847
|
-
state.lastDirective = directive;
|
|
848
|
-
await saveState(state);
|
|
849
|
-
return true;
|
|
850
|
-
}
|
|
851
|
-
if (action === 'abort' || action === 'abort_all') {
|
|
852
|
-
state.status = 'aborted';
|
|
853
|
-
state.lastDirective = directive;
|
|
854
|
-
state.lastVerdict = {
|
|
855
|
-
verdict: action === 'abort_all' ? 'circuit_broken' : 'aborted',
|
|
856
|
-
reason: directive.reason || ('外部指令 ' + action),
|
|
857
|
-
};
|
|
858
|
-
await saveState(state);
|
|
859
|
-
return true;
|
|
860
|
-
}
|
|
861
|
-
return false; // 未知指令
|
|
862
|
-
},
|
|
863
|
-
|
|
864
|
-
/**
|
|
865
|
-
* 依赖注入:注入 loop-snapshot / reflection-evaluator / actuator。
|
|
866
|
-
* 由 WP-174-3 / WP-174-4 调用,未注入时 engine 走降级路径。
|
|
867
|
-
* @param {object} delegate - { snapshot?, evaluator?, actuator? }
|
|
868
|
-
*/
|
|
869
|
-
inject: function (delegate) {
|
|
870
|
-
delegate = delegate || {};
|
|
871
|
-
if (delegate.snapshot) self._delegates.snapshot = delegate.snapshot;
|
|
872
|
-
if (delegate.evaluator) self._delegates.evaluator = delegate.evaluator;
|
|
873
|
-
if (delegate.actuator) self._delegates.actuator = delegate.actuator;
|
|
874
|
-
return true;
|
|
875
|
-
},
|
|
876
|
-
|
|
877
|
-
/**
|
|
878
|
-
* WP-S1 终态前自救链:发散自救——重置发散信号并标记自救级别,让 loop
|
|
879
|
-
* 以「新评估起点」继续(换 provider/模型由 driver 在调用前后处理)。
|
|
880
|
-
*
|
|
881
|
-
* 为什么清空 history:divergenceStreak 由 evaluator 从 history 尾部回数
|
|
882
|
-
* 「proximity 严格不增」连续轮——只清 state.divergenceStreak 会被 evaluator
|
|
883
|
-
* 重新数出来。自救的语义就是「换了执行手段,重新评估」,趋势历史作废。
|
|
884
|
-
* lastChecklist 保留(失败项仍驱动 retry/refine)。
|
|
885
|
-
*
|
|
886
|
-
* @param {string} loopId
|
|
887
|
-
* @param {object} [meta] { level, reason } 写入 state.selfRescue 供终态报告
|
|
888
|
-
* @returns {Promise<boolean>} 是否实际重置(loop 不存在 → false)
|
|
889
|
-
*/
|
|
890
|
-
prepareSelfRescue: async function (loopId, meta) {
|
|
891
|
-
var state = await loadState(loopId);
|
|
892
|
-
if (!state) return false;
|
|
893
|
-
state.divergenceStreak = 0;
|
|
894
|
-
// WP-S1 边界修复(v0.3.1 深审):清 history 会丢失末轮 failedCount,
|
|
895
|
-
// 自救后首轮的「部分改进宽容」(computeRefineProgress 读上轮 failedCount)
|
|
896
|
-
// 退化为不可宽容。快照到 selfRescue.prevFailedCount,evaluator 降级读它。
|
|
897
|
-
var lastEntry = (state.history && state.history.length)
|
|
898
|
-
? state.history[state.history.length - 1] : null;
|
|
899
|
-
var prevFailed = (lastEntry && lastEntry.eval && typeof lastEntry.eval.failedCount === 'number')
|
|
900
|
-
? lastEntry.eval.failedCount : null;
|
|
901
|
-
state.history = [];
|
|
902
|
-
state.selfRescue = {
|
|
903
|
-
level: (meta && meta.level) || 'unknown',
|
|
904
|
-
reason: (meta && meta.reason) || '',
|
|
905
|
-
at: nowIso(),
|
|
906
|
-
prevFailedCount: prevFailed,
|
|
907
|
-
};
|
|
908
|
-
await saveState(state);
|
|
909
|
-
return true;
|
|
910
|
-
},
|
|
911
|
-
|
|
912
|
-
/**
|
|
913
|
-
* WP-S1 终态前自救链:timeout 自救——追加迭代/墙钟预算。
|
|
914
|
-
* 直接调整 engine 运行时 _config(等价 init override 的运行时延续,
|
|
915
|
-
* 不改 _decide 决策逻辑);bonus 持久化到 state.selfRescue.budgetBonus,
|
|
916
|
-
* --loop-id 恢复路径 init() 读回应用(防 restore 后预算回退)。
|
|
917
|
-
*
|
|
918
|
-
* @param {string} loopId
|
|
919
|
-
* @param {object} [opts] { extraIterations=3, extraWallMs=1800000 }
|
|
920
|
-
* @param {object} [meta] { level, reason }
|
|
921
|
-
* @returns {Promise<{ maxIterations:number, maxWallTimeMs:number }>} 调整后的值
|
|
922
|
-
*/
|
|
923
|
-
extendBudget: async function (loopId, opts, meta) {
|
|
924
|
-
opts = opts || {};
|
|
925
|
-
var state = await loadState(loopId);
|
|
926
|
-
if (!state) return null;
|
|
927
|
-
var extraIter = (typeof opts.extraIterations === 'number' && opts.extraIterations > 0)
|
|
928
|
-
? Math.floor(opts.extraIterations) : 3;
|
|
929
|
-
var extraWall = (typeof opts.extraWallMs === 'number' && opts.extraWallMs > 0)
|
|
930
|
-
? opts.extraWallMs : 30 * 60 * 1000;
|
|
931
|
-
self._config.max_iterations += extraIter;
|
|
932
|
-
self._config.max_wall_time_ms += extraWall;
|
|
933
|
-
// WP-S1 边界修复(v0.3.1 深审):timeout 自救若不清发散计数,streak 已满时
|
|
934
|
-
// 续跑第一轮不改进会被 _decide 立即判 diverged(发散判定优先于上限)——
|
|
935
|
-
// 一次自救级别被白白烧掉。extendBudget 语义 = 「换了手段重新评估」,
|
|
936
|
-
// 与 prepareSelfRescue 同样需要清 streak + history。
|
|
937
|
-
state.divergenceStreak = 0;
|
|
938
|
-
state.history = [];
|
|
939
|
-
var prevBonus = (state.selfRescue && state.selfRescue.budgetBonus) || { iterations: 0, wallMs: 0 };
|
|
940
|
-
state.selfRescue = {
|
|
941
|
-
level: (meta && meta.level) || 'extend_budget',
|
|
942
|
-
reason: (meta && meta.reason) || '',
|
|
943
|
-
at: nowIso(),
|
|
944
|
-
budgetBonus: {
|
|
945
|
-
iterations: prevBonus.iterations + extraIter,
|
|
946
|
-
wallMs: prevBonus.wallMs + extraWall,
|
|
947
|
-
},
|
|
948
|
-
};
|
|
949
|
-
await saveState(state);
|
|
950
|
-
return { maxIterations: self._config.max_iterations, maxWallTimeMs: self._config.max_wall_time_ms };
|
|
951
|
-
},
|
|
952
|
-
|
|
953
|
-
/**
|
|
954
|
-
* 获取运行时配置(调试用)。
|
|
955
|
-
* @returns {object}
|
|
956
|
-
*/
|
|
957
|
-
getConfig: function () {
|
|
958
|
-
return mergeConfig(self._config, {});
|
|
959
|
-
},
|
|
960
|
-
};
|
|
961
|
-
|
|
962
|
-
return factoryApi;
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
// -------------------------------------------------------------------------
|
|
966
|
-
// 私有:状态机核心逻辑
|
|
967
|
-
// -------------------------------------------------------------------------
|
|
968
|
-
|
|
969
|
-
/**
|
|
970
|
-
* 确保 state-store 已初始化。
|
|
971
|
-
* @private
|
|
972
|
-
*/
|
|
973
|
-
_ensureStore() {
|
|
974
|
-
if (this._store) return;
|
|
975
|
-
this._projectRoot = this._resolveProjectRoot();
|
|
976
|
-
var stateFilePath = path.join(this._projectRoot, '.claude-state');
|
|
977
|
-
this._store = new StateStore({ filePath: stateFilePath });
|
|
978
|
-
// factory 可能先于 onActivate 调用:兜底自动注入 loop-actuator(幂等,已注入则跳过)
|
|
979
|
-
this._autoInjectLoopActuator();
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
/**
|
|
983
|
-
* Think 核心逻辑:基于快照产出决策。
|
|
984
|
-
* 优先级:失败项重试 > 待执行调度 > 被阻塞 noop。
|
|
985
|
-
* @private
|
|
986
|
-
* @param {object} state
|
|
987
|
-
* @param {object} snapshot
|
|
988
|
-
* @returns {object} { action, targetWp?, strategy?, reason }
|
|
989
|
-
*/
|
|
990
|
-
_think(state, snapshot) {
|
|
991
|
-
if (!snapshot) {
|
|
992
|
-
return { action: 'noop', reason: '无快照,等待 observe' };
|
|
993
|
-
}
|
|
994
|
-
var wp = snapshot.workPackages || {};
|
|
995
|
-
var goal = state.goal || {};
|
|
996
|
-
var goalWps = (goal.wpIds && goal.wpIds.length ? goal.wpIds : null);
|
|
997
|
-
|
|
998
|
-
// 1) 失败项优先重试(evaluator-refine 反馈驱动,design.md §3.3)
|
|
999
|
-
// retry 分支命中的真实数据流(修复偏差1 + engine/运行时落差):
|
|
1000
|
-
// wp.failed 由 loop-snapshot.buildWorkPackages 从 lastChecklist.failedItems
|
|
1001
|
-
// 聚合填充(WP-176-2),不再写死空数组;retry decision 携带 failingDrivers
|
|
1002
|
-
// 明细(Reflect 回填自 EvalResult.failingDrivers,供运行时 Step 4.2 /
|
|
1003
|
-
// WP-176-4 下发给承接重做的 Teamee 作为 refine 反馈)。
|
|
1004
|
-
if (wp.failed && wp.failed.length > 0) {
|
|
1005
|
-
var retryWp = wp.failed[0];
|
|
1006
|
-
var strategy = (state.checkpoints && state.checkpoints[retryWp])
|
|
1007
|
-
? 'checkpoint_resume'
|
|
1008
|
-
: 'full_restart';
|
|
1009
|
-
// failingDrivers 明细:优先 Reflect 回填的 state.failingDrivers,
|
|
1010
|
-
// 回退最近一次 EvalResult(state.lastEval),二者均为空时降级为空数组
|
|
1011
|
-
var failingDrivers = (state.failingDrivers && state.failingDrivers.length)
|
|
1012
|
-
? state.failingDrivers
|
|
1013
|
-
: ((state.lastEval && state.lastEval.failingDrivers) || []);
|
|
1014
|
-
return {
|
|
1015
|
-
action: 'retry',
|
|
1016
|
-
targetWp: retryWp,
|
|
1017
|
-
strategy: strategy,
|
|
1018
|
-
failingDrivers: failingDrivers,
|
|
1019
|
-
reason: 'checklist 失败项,执行 refine 重试',
|
|
1020
|
-
};
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
// 2) 上轮 checklist 失败(failed 为空但 lastChecklist.passed=false)→ resplit 候选
|
|
1024
|
-
if (snapshot.lastChecklist && snapshot.lastChecklist.passed === false) {
|
|
1025
|
-
return {
|
|
1026
|
-
action: 'resplit',
|
|
1027
|
-
targetWp: snapshot.lastChecklist.wpId,
|
|
1028
|
-
strategy: 'resplit',
|
|
1029
|
-
reason: '上轮 checklist 失败且无显式 failed 项,建议拆分当前 WP',
|
|
1030
|
-
};
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
// 3) 待执行调度(仅在 goal 范围内,不越界 P0,design.md §7.1)
|
|
1034
|
-
// Step 0 拓扑接线(next-dev-plan Batch 1):第一道保留原越界保护(scope 过滤,
|
|
1035
|
-
// 明确 noop reason);第二道加 readyWave 过滤(candidate 依赖须全 completed)。
|
|
1036
|
-
// 降级:dependencyGraph 缺失时跳过第二道,candidate = 越界保护后的 pending[0],
|
|
1037
|
-
// 行为 = v0.3.15。不改 _decide / DEFAULT_CONFIG(Step 0 硬约束)。
|
|
1038
|
-
if (wp.pending && wp.pending.length > 0) {
|
|
1039
|
-
// 第一道:越界保护(原 scope 过滤,保留「不在 goal 范围」明确 reason)
|
|
1040
|
-
var candidate = wp.pending[0];
|
|
1041
|
-
if (goalWps && goalWps.indexOf(candidate) === -1) {
|
|
1042
|
-
var inScope = null;
|
|
1043
|
-
for (var i = 0; i < wp.pending.length; i++) {
|
|
1044
|
-
if (goalWps.indexOf(wp.pending[i]) !== -1) { inScope = wp.pending[i]; break; }
|
|
1045
|
-
}
|
|
1046
|
-
if (!inScope) {
|
|
1047
|
-
return { action: 'noop', reason: 'pending WP 不在 goal 范围内,不越界调度' };
|
|
1048
|
-
}
|
|
1049
|
-
candidate = inScope;
|
|
1050
|
-
}
|
|
1051
|
-
// 第二道:readyWave 过滤——candidate 依赖须全 completed(仅 dependencyGraph 存在时)
|
|
1052
|
-
var depNodes = (goal.dependencyGraph && goal.dependencyGraph.nodes)
|
|
1053
|
-
? goal.dependencyGraph.nodes : null;
|
|
1054
|
-
if (depNodes) {
|
|
1055
|
-
var completedSet = wp.completed || [];
|
|
1056
|
-
var isDepsReady = function (wid) {
|
|
1057
|
-
var node = depNodes[wid];
|
|
1058
|
-
if (!node) return true; // 节点缺失,视为无依赖
|
|
1059
|
-
var deps = node.dependencies || [];
|
|
1060
|
-
for (var d = 0; d < deps.length; d++) {
|
|
1061
|
-
if (completedSet.indexOf(deps[d]) === -1) return false; // 依赖未完成
|
|
1062
|
-
}
|
|
1063
|
-
return true;
|
|
1064
|
-
};
|
|
1065
|
-
if (!isDepsReady(candidate)) {
|
|
1066
|
-
// readyWave[0]:遍历 pending 找首个「goal 范围内 + 依赖就绪」的(拓扑序下通常
|
|
1067
|
-
// 即 pending[0],此分支为 pending 排序异常/环的防御兜底)
|
|
1068
|
-
var ready = null;
|
|
1069
|
-
for (var j = 0; j < wp.pending.length; j++) {
|
|
1070
|
-
var pw = wp.pending[j];
|
|
1071
|
-
if (goalWps && goalWps.indexOf(pw) === -1) continue; // 跳过越界
|
|
1072
|
-
if (isDepsReady(pw)) { ready = pw; break; }
|
|
1073
|
-
}
|
|
1074
|
-
if (!ready) {
|
|
1075
|
-
return { action: 'noop', reason: 'pending WP 依赖未就绪,等待依赖完成(拓扑)' };
|
|
1076
|
-
}
|
|
1077
|
-
candidate = ready;
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
return {
|
|
1081
|
-
action: 'dispatch',
|
|
1082
|
-
targetWp: candidate,
|
|
1083
|
-
strategy: 'full_restart',
|
|
1084
|
-
reason: '调度下一个就绪 WP(goal 范围内,依赖就绪)',
|
|
1085
|
-
};
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
// 4) 全部被阻塞 → noop(等依赖;持续 noop 会由发散/上限判定兜底)
|
|
1089
|
-
return { action: 'noop', reason: '无可执行项(pending/failed 均空或全阻塞)' };
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
/**
|
|
1093
|
-
* Decide 核心逻辑:三类终止判定。
|
|
1094
|
-
* 优先级:熔断 > 发散 > 达成 > 上限 > 继续。
|
|
1095
|
-
* (「达成」上提到「上限」之前——修复末轮 iteration==max_iterations 时 proximity 已达标
|
|
1096
|
-
* 却被 max_iterations 抢判 timeout 的 bug;末轮达成本轮应判 achieved。)
|
|
1097
|
-
* @private
|
|
1098
|
-
* @param {object} state
|
|
1099
|
-
* @param {object} evalResult
|
|
1100
|
-
* @param {{health:string, running:boolean}} watchdogHealth
|
|
1101
|
-
* @returns {{ verdict: string, reason: string }}
|
|
1102
|
-
*/
|
|
1103
|
-
_decide(state, evalResult, watchdogHealth) {
|
|
1104
|
-
evalResult = evalResult || {};
|
|
1105
|
-
|
|
1106
|
-
// ① 熔断(watchdog terminated / 不运行 / 持续 degraded)
|
|
1107
|
-
if (watchdogHealth) {
|
|
1108
|
-
if (watchdogHealth.health === 'terminated' || watchdogHealth.running === false) {
|
|
1109
|
-
return { verdict: 'circuit_broken', reason: 'watchdog 守护已终止/未运行' };
|
|
1110
|
-
}
|
|
1111
|
-
if (watchdogHealth.health === 'degraded') {
|
|
1112
|
-
return { verdict: 'circuit_broken', reason: 'watchdog 持续 degraded' };
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
// ② 发散(连续 N 轮无进展,design.md §6.3.1)
|
|
1117
|
-
// 协同判据(WP-191-2-impl,对齐 Ralph 熔断):proximity 不升 OR 无代码进展,
|
|
1118
|
-
// 任一连续 divergence_threshold 轮 → diverged。保留现有 proximity streak 语义,
|
|
1119
|
-
// 并列消费 evaluator 计算的 noProgressStreak(来自 executor 工作树脏度信号)。
|
|
1120
|
-
var streak = evalResult.divergenceStreak;
|
|
1121
|
-
if (streak === undefined || streak === null) streak = state.divergenceStreak || 0;
|
|
1122
|
-
var noProgressStreak = (typeof evalResult.noProgressStreak === 'number')
|
|
1123
|
-
? evalResult.noProgressStreak : 0;
|
|
1124
|
-
// 阈值统一取 engine 运行时 _config(含 init override),不直接采信 evaluator 的
|
|
1125
|
-
// diverged 字段——evaluator 用 DEFAULT_THRESHOLDS,会让其默认阈值 3 绕过 engine
|
|
1126
|
-
// 的 override(如测试 configOverride divergence_threshold=99)。两类 streak 都按
|
|
1127
|
-
// engine 阈值判定,与原版 proximity-only 行为一致,noProgress 协同同此阈值。
|
|
1128
|
-
if (streak >= this._config.divergence_threshold ||
|
|
1129
|
-
noProgressStreak >= this._config.divergence_threshold) {
|
|
1130
|
-
return {
|
|
1131
|
-
verdict: 'diverged',
|
|
1132
|
-
reason: '发散:proximity 连续 ' + streak + ' 轮无进展 / 无代码进展连续 ' +
|
|
1133
|
-
noProgressStreak + ' 轮(>= divergence_threshold ' +
|
|
1134
|
-
this._config.divergence_threshold + ')',
|
|
1135
|
-
};
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
// ③ 目标达成(checklist 全过 + proximity 达标 + 无 pending/failed,design.md §6.1)
|
|
1139
|
-
// 优先级上提到「上限」之前(修复末轮达成被误判 timeout 的 bug):末轮
|
|
1140
|
-
// iteration==max_iterations 时若 proximity 已达标,应判 achieved 而非 timeout——
|
|
1141
|
-
// 目标已达成却报失败违背「目标驱动 self-closing loop」根本语义。
|
|
1142
|
-
// noFailed 现真实生效(修复偏差1 + 落差):wp.failed 由 WP-176-2 填充,
|
|
1143
|
-
// evalResult.failingDrivers 由 evaluator 从 lastChecklist.failedItems 算出。
|
|
1144
|
-
// 二者任一非空都意味着仍有失败项 → 不能判 achieved。
|
|
1145
|
-
var proximity = (typeof evalResult.proximity === 'number') ? evalResult.proximity : 0;
|
|
1146
|
-
var allPassed = evalResult.allPassed === true ||
|
|
1147
|
-
(evalResult.failingDrivers && evalResult.failingDrivers.length === 0 && proximity >= this._config.proximity_goal);
|
|
1148
|
-
var snapshot = state.lastSnapshot || {};
|
|
1149
|
-
var wp = snapshot.workPackages || {};
|
|
1150
|
-
var noPending = (!wp.pending || wp.pending.length === 0);
|
|
1151
|
-
var noFailed = (!wp.failed || wp.failed.length === 0) &&
|
|
1152
|
-
(!evalResult.failingDrivers || evalResult.failingDrivers.length === 0);
|
|
1153
|
-
if (allPassed && proximity >= this._config.proximity_goal && noPending && noFailed) {
|
|
1154
|
-
return { verdict: 'achieved', reason: 'checklist 全过且 proximity ' + proximity.toFixed(3) +
|
|
1155
|
-
' >= goal ' + this._config.proximity_goal };
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
// ④ 迭代上限 / 墙钟上限(design.md §6.2)—— 兜底:本轮未达成才判 timeout
|
|
1159
|
-
if (state.iteration >= this._config.max_iterations) {
|
|
1160
|
-
return { verdict: 'timeout', reason: '迭代已达上限 max_iterations ' + this._config.max_iterations };
|
|
1161
|
-
}
|
|
1162
|
-
var wallElapsed = Date.now() - new Date(state.startedAt).getTime();
|
|
1163
|
-
if (wallElapsed >= this._config.max_wall_time_ms) {
|
|
1164
|
-
return { verdict: 'timeout', reason: '墙钟已达上限 max_wall_time_ms ' + this._config.max_wall_time_ms };
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
// ⑤ 继续
|
|
1168
|
-
return { verdict: 'continue', reason: '迭代 ' + state.iteration + ' 继续' };
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
/**
|
|
1172
|
-
* 查询 watchdog 健康(熔断判定输入,design.md §6.3.2)。
|
|
1173
|
-
*
|
|
1174
|
-
* 优先调用 WP-174-5 新增的 watchdog.getHealth()(三态:healthy/degraded/terminated,
|
|
1175
|
-
* 可区分 degraded),将其 state 字段映射为 engine 内部 health。
|
|
1176
|
-
* 若 provider 未提供 getHealth(旧版/降级),回退到 isRunning() 二态判定。
|
|
1177
|
-
* 任何异常降级为 healthy(不阻断 loop 主流程)。
|
|
1178
|
-
* @private
|
|
1179
|
-
* @param {PluginContext} context
|
|
1180
|
-
* @returns {Promise<{health:string, running:boolean, stale?:boolean}>}
|
|
1181
|
-
*/
|
|
1182
|
-
async _queryWatchdogHealth(context) {
|
|
1183
|
-
try {
|
|
1184
|
-
if (!context || typeof context.getProvider !== 'function') {
|
|
1185
|
-
return { health: 'healthy', running: true };
|
|
1186
|
-
}
|
|
1187
|
-
var watchdog = await context.getProvider('provider:watchdog');
|
|
1188
|
-
if (!watchdog) {
|
|
1189
|
-
return { health: 'healthy', running: true };
|
|
1190
|
-
}
|
|
1191
|
-
// 优先用三态 getHealth(WP-174-5)
|
|
1192
|
-
if (typeof watchdog.getHealth === 'function') {
|
|
1193
|
-
var h = watchdog.getHealth();
|
|
1194
|
-
if (h && (h.state === 'healthy' || h.state === 'degraded' || h.state === 'terminated')) {
|
|
1195
|
-
return { health: h.state, running: h.running === true, stale: h.stale === true };
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
// 降级:isRunning() 二态(health !== 'terminated')
|
|
1199
|
-
if (typeof watchdog.isRunning === 'function') {
|
|
1200
|
-
var running = watchdog.isRunning();
|
|
1201
|
-
return { health: running ? 'healthy' : 'terminated', running: running };
|
|
1202
|
-
}
|
|
1203
|
-
return { health: 'healthy', running: true };
|
|
1204
|
-
} catch (e) {
|
|
1205
|
-
return { health: 'healthy', running: true };
|
|
1206
|
-
}
|
|
1207
|
-
}
|
|
1208
|
-
|
|
1209
|
-
/**
|
|
1210
|
-
* 降级快照(无 loop-snapshot 注入时):仅 loop 自身上下文 + state-store 中的 lastChecklist。
|
|
1211
|
-
* @private
|
|
1212
|
-
* @param {string} loopId
|
|
1213
|
-
* @param {object} state
|
|
1214
|
-
* @returns {object}
|
|
1215
|
-
*/
|
|
1216
|
-
_fallbackSnapshot(loopId, state) {
|
|
1217
|
-
var goal = state.goal || {};
|
|
1218
|
-
return {
|
|
1219
|
-
loopId: loopId,
|
|
1220
|
-
iteration: state.iteration,
|
|
1221
|
-
capturedAt: nowIso(),
|
|
1222
|
-
workPackages: {
|
|
1223
|
-
total: (goal.wpIds || []).length,
|
|
1224
|
-
pending: (goal.wpIds || []).slice(),
|
|
1225
|
-
completed: [],
|
|
1226
|
-
failed: [],
|
|
1227
|
-
blocked: [],
|
|
1228
|
-
},
|
|
1229
|
-
lastChecklist: null,
|
|
1230
|
-
watchdog: { deployed: false, running: true, health: 'healthy' },
|
|
1231
|
-
gitDiff: { changedFiles: 0, insertions: 0, deletions: 0, filesByWp: {} },
|
|
1232
|
-
signals: { pendingDirectives: [] },
|
|
1233
|
-
_fallback: true,
|
|
1234
|
-
};
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
/**
|
|
1238
|
-
* 降级评分(无 reflection-evaluator 注入时):基于 lastChecklist 算 proximity。
|
|
1239
|
-
* @private
|
|
1240
|
-
* @param {string} loopId
|
|
1241
|
-
* @param {object} state
|
|
1242
|
-
* @param {object} snapshot
|
|
1243
|
-
* @returns {object}
|
|
1244
|
-
*/
|
|
1245
|
-
_fallbackEval(loopId, state, snapshot) {
|
|
1246
|
-
var proximity = 0;
|
|
1247
|
-
var allPassed = false;
|
|
1248
|
-
var failingDrivers = [];
|
|
1249
|
-
|
|
1250
|
-
var chk = state.lastChecklist ||
|
|
1251
|
-
(snapshot && snapshot.lastChecklist) ||
|
|
1252
|
-
null;
|
|
1253
|
-
if (chk) {
|
|
1254
|
-
var summary = chk.summary || {};
|
|
1255
|
-
var total = summary.total || 0;
|
|
1256
|
-
var passed = summary.passed || 0;
|
|
1257
|
-
proximity = total > 0 ? 1 - ((total - passed) / total) : (chk.passed ? 1 : 0);
|
|
1258
|
-
allPassed = chk.passed === true;
|
|
1259
|
-
if (chk.failedItems) {
|
|
1260
|
-
for (var i = 0; i < chk.failedItems.length; i++) {
|
|
1261
|
-
var fi = chk.failedItems[i];
|
|
1262
|
-
failingDrivers.push({
|
|
1263
|
-
wpId: chk.wpId,
|
|
1264
|
-
category: fi.category,
|
|
1265
|
-
item: fi.id || fi.text,
|
|
1266
|
-
reason: fi.reason,
|
|
1267
|
-
});
|
|
1268
|
-
}
|
|
1269
|
-
}
|
|
1270
|
-
} else if (snapshot && snapshot.workPackages) {
|
|
1271
|
-
// 无 checklist 时按 WP 完成度近似
|
|
1272
|
-
var wp = snapshot.workPackages;
|
|
1273
|
-
var totalWp = (wp.total || 0);
|
|
1274
|
-
var doneWp = (wp.completed ? wp.completed.length : 0);
|
|
1275
|
-
proximity = totalWp > 0 ? doneWp / totalWp : 0;
|
|
1276
|
-
}
|
|
1277
|
-
|
|
1278
|
-
// 收敛/发散(基于 history 末尾 proximity)
|
|
1279
|
-
var converged = false;
|
|
1280
|
-
var prevProximity = null;
|
|
1281
|
-
if (state.history && state.history.length > 0) {
|
|
1282
|
-
var last = state.history[state.history.length - 1];
|
|
1283
|
-
if (last && last.eval && typeof last.eval.proximity === 'number') {
|
|
1284
|
-
prevProximity = last.eval.proximity;
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
if (prevProximity !== null) {
|
|
1288
|
-
converged = proximity > prevProximity;
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
var streak = state.divergenceStreak || 0;
|
|
1292
|
-
if (prevProximity !== null && proximity <= prevProximity) {
|
|
1293
|
-
streak = streak + 1;
|
|
1294
|
-
} else {
|
|
1295
|
-
streak = 0;
|
|
1296
|
-
}
|
|
1297
|
-
|
|
1298
|
-
return {
|
|
1299
|
-
loopId: loopId,
|
|
1300
|
-
iteration: state.iteration,
|
|
1301
|
-
proximity: proximity,
|
|
1302
|
-
converged: converged,
|
|
1303
|
-
diverged: streak >= this._config.divergence_threshold,
|
|
1304
|
-
divergenceStreak: streak,
|
|
1305
|
-
trend: converged ? 'improving' : (prevProximity === null ? 'flat' : 'regressing'),
|
|
1306
|
-
categoryScores: [],
|
|
1307
|
-
failingDrivers: failingDrivers,
|
|
1308
|
-
allPassed: allPassed,
|
|
1309
|
-
recommendation: failingDrivers.length > 0
|
|
1310
|
-
? 'retry_' + (failingDrivers[0].wpId || '')
|
|
1311
|
-
: (proximity >= this._config.proximity_goal ? 'achieved' : 'continue'),
|
|
1312
|
-
scoredAt: nowIso(),
|
|
1313
|
-
_fallback: true,
|
|
1314
|
-
};
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
/**
|
|
1318
|
-
* 压缩快照为 history 摘要(design.md §5.1.1 snapshotSummary)。
|
|
1319
|
-
* @private
|
|
1320
|
-
* @param {object} snapshot
|
|
1321
|
-
* @returns {object}
|
|
1322
|
-
*/
|
|
1323
|
-
_summarizeSnapshot(snapshot) {
|
|
1324
|
-
if (!snapshot) return null;
|
|
1325
|
-
var wp = snapshot.workPackages || {};
|
|
1326
|
-
return {
|
|
1327
|
-
pendingWps: (wp.pending || []).length,
|
|
1328
|
-
failedChecks: snapshot.lastChecklist && snapshot.lastChecklist.summary
|
|
1329
|
-
? snapshot.lastChecklist.summary.failed
|
|
1330
|
-
: 0,
|
|
1331
|
-
watchdogHealthy: !!(snapshot.watchdog && snapshot.watchdog.running),
|
|
1332
|
-
};
|
|
1333
|
-
}
|
|
1334
|
-
|
|
1335
|
-
/**
|
|
1336
|
-
* 构建五段式各阶段产出摘要(WP-196-1-impl,纯观测)。
|
|
1337
|
-
* 仅读取 step() 已采集的局部变量,不新增任何决策分支;任一字段缺失返回 undefined(driver 据此省略)。
|
|
1338
|
-
* @private
|
|
1339
|
-
* @param {object} ctx { snapshot, decision, actResult, evalResult, verdict }
|
|
1340
|
-
* @returns {object} phase → summary(值可为 string/number/object)
|
|
1341
|
-
*/
|
|
1342
|
-
_buildPhaseSummaries(ctx) {
|
|
1343
|
-
ctx = ctx || {};
|
|
1344
|
-
var out = {};
|
|
1345
|
-
try {
|
|
1346
|
-
// observe:pending WP 计数(复用 _summarizeSnapshot 口径,不重复造轮子)
|
|
1347
|
-
if (ctx.snapshot) {
|
|
1348
|
-
var ss = this._summarizeSnapshot(ctx.snapshot) || {};
|
|
1349
|
-
out.observe = { pendingWps: ss.pendingWps, failedChecks: ss.failedChecks };
|
|
1350
|
-
}
|
|
1351
|
-
} catch (_e) { /* 降级 */ }
|
|
1352
|
-
try {
|
|
1353
|
-
// think:本轮 decision 的 action + 目标 WP(若有)
|
|
1354
|
-
if (ctx.decision) {
|
|
1355
|
-
out.think = {
|
|
1356
|
-
action: ctx.decision.action || null,
|
|
1357
|
-
targetWp: ctx.decision.targetWp || (ctx.decision.wpId) || null,
|
|
1358
|
-
};
|
|
1359
|
-
}
|
|
1360
|
-
} catch (_e) { /* 降级 */ }
|
|
1361
|
-
try {
|
|
1362
|
-
// act:复用 actResult.roundElapsedMs(act 内部口径,单轮总耗时)+ dispatch WP
|
|
1363
|
-
if (ctx.actResult) {
|
|
1364
|
-
out.act = {
|
|
1365
|
-
roundElapsedMs: (typeof ctx.actResult.roundElapsedMs === 'number')
|
|
1366
|
-
? ctx.actResult.roundElapsedMs : null,
|
|
1367
|
-
dispatchedWp: ctx.actResult.wpId || (ctx.decision && (ctx.decision.targetWp || ctx.decision.wpId)) || null,
|
|
1368
|
-
};
|
|
1369
|
-
}
|
|
1370
|
-
} catch (_e) { /* 降级 */ }
|
|
1371
|
-
try {
|
|
1372
|
-
// reflect:proximity + 发散/收敛信号(history 已记 eval,这里仅复述供 trace 一行可读)
|
|
1373
|
-
if (ctx.evalResult) {
|
|
1374
|
-
out.reflect = {
|
|
1375
|
-
proximity: (typeof ctx.evalResult.proximity === 'number')
|
|
1376
|
-
? ctx.evalResult.proximity : null,
|
|
1377
|
-
diverged: ctx.evalResult.diverged === true,
|
|
1378
|
-
converged: ctx.evalResult.converged === true,
|
|
1379
|
-
failedCount: (typeof ctx.evalResult.failedCount === 'number')
|
|
1380
|
-
? ctx.evalResult.failedCount : null,
|
|
1381
|
-
};
|
|
1382
|
-
}
|
|
1383
|
-
} catch (_e) { /* 降级 */ }
|
|
1384
|
-
try {
|
|
1385
|
-
// decide:verdict(多数终态出口在提前 return 路径,正常路径 verdict 由 _decide 产出)
|
|
1386
|
-
if (ctx.verdict) {
|
|
1387
|
-
out.decide = { verdict: ctx.verdict.verdict || null };
|
|
1388
|
-
}
|
|
1389
|
-
} catch (_e) { /* 降级 */ }
|
|
1390
|
-
return out;
|
|
1391
|
-
}
|
|
1392
|
-
|
|
1393
|
-
/**
|
|
1394
|
-
* 解析项目根目录(仿 provider-state-store)。
|
|
1395
|
-
* @private
|
|
1396
|
-
* @returns {string}
|
|
1397
|
-
*/
|
|
1398
|
-
_resolveProjectRoot() {
|
|
1399
|
-
var dir = process.cwd();
|
|
1400
|
-
for (var i = 0; i < 10; i++) {
|
|
1401
|
-
if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
|
|
1402
|
-
if (fs.existsSync(path.join(dir, '.claude'))) return dir;
|
|
1403
|
-
var parent = path.dirname(dir);
|
|
1404
|
-
if (parent === dir) break;
|
|
1405
|
-
dir = parent;
|
|
1406
|
-
}
|
|
1407
|
-
return process.cwd();
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
|
|
1411
|
-
module.exports = LoopEngineProvider;
|