doukui 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1443 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1411 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +588 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +415 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-lint.js +100 -0
  118. package/plugins/runtime/plan-reader.js +763 -0
  119. package/plugins/runtime/plugin-loader.js +798 -0
  120. package/plugins/runtime/plugin-trust.js +182 -0
  121. package/plugins/runtime/plugin-validator.js +491 -0
  122. package/plugins/runtime/provider-failover.js +114 -0
  123. package/plugins/runtime/provider-resolver.js +342 -0
  124. package/plugins/runtime/reflection-evaluator.js +545 -0
  125. package/plugins/runtime/resolve-plugin-path.js +297 -0
  126. package/plugins/runtime/safe-path.js +119 -0
  127. package/plugins/runtime/sandbox-context.js +235 -0
  128. package/plugins/runtime/sandbox-manager.js +609 -0
  129. package/plugins/runtime/sandbox-worker.js +215 -0
  130. package/plugins/runtime/self-rescue-ladder.js +38 -0
  131. package/plugins/runtime/settings-merger.js +172 -0
  132. package/plugins/runtime/state-store.js +527 -0
  133. package/plugins/runtime/team-cleanup.js +497 -0
  134. package/plugins/runtime/text-tokenize.js +25 -0
  135. package/plugins/runtime/validator-pipeline.js +475 -0
  136. package/plugins/runtime/yaml-parser.js +692 -0
  137. package/templates/harness-config.yaml +394 -0
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Loop Actuator — Agentic Loop Act 层执行器(WP-177-1-impl-b)
3
+ *
4
+ * @module loop-actuator
5
+ *
6
+ * 职责:实现 engine `act()` 期望的 actuator 接口
7
+ * `execute(context, loopId, decision, state) -> { dispatched, checklistResult? }`。
8
+ *
9
+ * 把 engine 的 decision(dispatch / retry / resplit)序列化为「dispatcher 待执行指令」
10
+ * 写入 state-store 子 key `loop.{loopId}.pendingAction`,并注入 failingDrivers,
11
+ * 支持 checklistResult 回填。这是让 `engine.step()` 端到端可跑、移除 `placeholder:true`
12
+ * 占位的核心。
13
+ *
14
+ * 设计约束(docs/wp/WP-177.md「技术方案 actuator 注入架构」):
15
+ * - actuator 只产出「指令 + 标记已派发」,不直接 spawn Teamee / 不调 Claude
16
+ * - pendingAction 是「待 Claude 消费」的指令,不是「已执行结果」
17
+ * - execute 返回 dispatched:true 表示「指令已就绪」,不代表子代理已跑完
18
+ * - 实际子代理执行由 Claude 按 skill.md 读取 pendingAction → 调 skill-agent-dispatcher 完成
19
+ * - dispatcher 执行后回填 CheckResult 到 loop.{loopId}.lastChecklist(由 engine.act 写入)
20
+ *
21
+ * 接入契约(必须匹配 provider-loop-engine/index.js inject 期望,见 :582 / :362-365):
22
+ * loopEngine.inject({ actuator: createActuator() })
23
+ * engine 在 act 阶段调用:actuator.execute(context, loopId, decision, state)
24
+ *
25
+ * failingDrivers 结构(透传 reflection-evaluator.failingDriversFromChecklist 产出):
26
+ * [{ wpId, category, item, reason }]
27
+ * 来源是 decision.failingDrivers(engine Think 阶段携带,WP-176 已打通
28
+ * Reflect→state→Think 链路),本模块只透传不重新计算。
29
+ */
30
+
31
+ 'use strict';
32
+
33
+ var path = require('path');
34
+ var { StateStore } = require('./state-store');
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // 默认配置
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /**
41
+ * decision.action → dispatcher 指令 mode 映射表。
42
+ * 仅这三种 action 会被序列化为 pendingAction;noop(无可执行项)跳过派发。
43
+ */
44
+ var ACTION_TO_MODE = {
45
+ dispatch: 'dispatch',
46
+ retry: 'retry',
47
+ resplit: 'resplit',
48
+ };
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // 工具函数
52
+ // ---------------------------------------------------------------------------
53
+
54
+ /**
55
+ * ISO 时间戳。
56
+ * @returns {string}
57
+ */
58
+ function nowIso() {
59
+ return new Date().toISOString();
60
+ }
61
+
62
+ /**
63
+ * 解析项目根目录(仿 provider-state-store / loop-snapshot:向上找 task.md / .claude)。
64
+ * @returns {string}
65
+ */
66
+ function resolveProjectRoot() {
67
+ var dir = process.cwd();
68
+ // 同步向上查找,最多 10 层
69
+ for (var i = 0; i < 10; i++) {
70
+ try {
71
+ var fs = require('fs');
72
+ if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
73
+ if (fs.existsSync(path.join(dir, '.claude'))) return dir;
74
+ } catch (_e) {
75
+ // fs 访问异常:继续向上
76
+ }
77
+ var parent = path.dirname(dir);
78
+ if (parent === dir) break;
79
+ dir = parent;
80
+ }
81
+ return process.cwd();
82
+ }
83
+
84
+ /**
85
+ * 包装 provider:state-store 的 factory API 为统一 { get/set } 接口。
86
+ * provider:state-store factory 返回 get(key)/set(key,val) 等。
87
+ * @param {object} providerApi
88
+ * @returns {{ get: Function, set: Function }}
89
+ */
90
+ function wrapProviderStore(providerApi) {
91
+ return {
92
+ get: function (key) {
93
+ return providerApi.get(key);
94
+ },
95
+ set: function (key, value) {
96
+ return providerApi.set(key, value);
97
+ },
98
+ };
99
+ }
100
+
101
+ /**
102
+ * 确定一个可用的 state-store 句柄。
103
+ * 优先级:
104
+ * 1. context.getStateStore()(engine 注入的便捷方法,若存在)
105
+ * 2. context.getProvider('provider:state-store')(同步返回的 factory API)
106
+ * 3. 本地 StateStore(.claude-state)
107
+ * @param {PluginContext} context
108
+ * @returns {{ store: object, injected: boolean } | null} 不可用时返回 null
109
+ */
110
+ function resolveStore(context) {
111
+ // 1) context.getStateStore() 便捷方法
112
+ if (context && typeof context.getStateStore === 'function') {
113
+ try {
114
+ var direct = context.getStateStore();
115
+ if (direct && (typeof direct.get === 'function' || typeof direct.set === 'function')) {
116
+ return { store: direct, injected: true };
117
+ }
118
+ } catch (_e) {
119
+ // 降级
120
+ }
121
+ }
122
+
123
+ // 2) context.getProvider('provider:state-store')(同步)
124
+ if (context && typeof context.getProvider === 'function') {
125
+ try {
126
+ var maybe = context.getProvider('provider:state-store');
127
+ // B18/A1:async getProvider(返回 Promise)无法在同步 resolveStore 内消费。
128
+ // 明确吞掉 rejection 避免 unhandledRejection,然后降级。
129
+ if (maybe && typeof maybe.then === 'function') {
130
+ maybe.then(function () { /* provider resolved after fallback; ignore */ },
131
+ function (_e) { /* provider rejected; fallback in use */ });
132
+ } else if (maybe && (typeof maybe.get === 'function' || typeof maybe.set === 'function')) {
133
+ return { store: wrapProviderStore(maybe), injected: true };
134
+ }
135
+ } catch (_e) {
136
+ // 降级
137
+ }
138
+ }
139
+
140
+ // 3) 本地 StateStore
141
+ // A1 NOTE:跨 loop 物理隔离由调用方负责(bin/commands/loop.js 的
142
+ // resolveLoopWorkspace 在 <stateDir>/<loopId>/ 下建立独立 workspaceRoot,
143
+ // engine 的 StateStore 即用 workspaceRoot/'.claude-state',天然分桶)。
144
+ // 此处保持扁平回退以与 engine 写入同一文件,避免状态分裂。
145
+ try {
146
+ var root = resolveProjectRoot();
147
+ return {
148
+ store: new StateStore({ filePath: path.join(root, '.claude-state') }),
149
+ injected: false,
150
+ };
151
+ } catch (_e) {
152
+ return null; // state-store 完全不可用
153
+ }
154
+ }
155
+
156
+ /**
157
+ * 读取 loop state 下已回填的 lastChecklist(dispatcher 执行后由 engine.act 写入,
158
+ * 见 index.js:372-374;此处用于回填路径——若 actuator 被调用时上一轮结果已就绪)。
159
+ * @param {object} store { get }
160
+ * @param {string} loopId
161
+ * @returns {Promise<object|null>}
162
+ */
163
+ async function loadLastChecklist(store, loopId) {
164
+ try {
165
+ var chk = await store.get('loop.' + loopId + '.lastChecklist');
166
+ return chk || null;
167
+ } catch (_e) {
168
+ return null;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * 把 engine decision 序列化为 dispatcher 待执行指令(pendingAction)。
174
+ *
175
+ * @param {string} loopId
176
+ * @param {object} decision engine _think 产出:
177
+ * { action:'dispatch|retry|resplit|noop', targetWp?, strategy?, context?, failingDrivers?, reason }
178
+ * @returns {object} pendingAction(写入 state-store 子 key loop.{loopId}.pendingAction)
179
+ */
180
+ function buildPendingAction(loopId, decision) {
181
+ decision = decision || {};
182
+ var mode = ACTION_TO_MODE[decision.action];
183
+ return {
184
+ wpId: decision.targetWp || '',
185
+ mode: mode, // dispatch | retry | resplit
186
+ strategy: decision.strategy || (mode === 'retry' ? 'checkpoint_resume' : 'full_restart'),
187
+ // checkpoint_resume(retry)时携带 context(如恢复点信息);其余场景透传
188
+ context: decision.context || null,
189
+ // retry 时重点修复项(承接 WP-176 refine 通道;dispatcher 读取此字段注入 Teamee prompt)
190
+ failingDrivers: (decision.failingDrivers && decision.failingDrivers.length)
191
+ ? decision.failingDrivers.slice()
192
+ : [],
193
+ createdAt: nowIso(),
194
+ loopId: loopId,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * 计算幂等键(按 wpId+mode 去重/覆盖)。
200
+ * 同一 decision 重复 execute 不产生重复 pendingAction——只要 key 相同即覆盖。
201
+ * @param {object} pendingAction
202
+ * @returns {string}
203
+ */
204
+ function idempotencyKey(pendingAction) {
205
+ return [pendingAction.mode || '', pendingAction.wpId || ''].join('::');
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // 公开 API
210
+ // ---------------------------------------------------------------------------
211
+
212
+ /**
213
+ * 创建一个 actuator 实例(注入 engine.inject({ actuator }))。
214
+ *
215
+ * @param {object} [opts] 可选配置
216
+ * @param {object} [opts.store] 外部预置的 state-store 句柄(测试注入用)
217
+ * @returns {{ execute: Function }}
218
+ */
219
+ function createActuator(opts) {
220
+ opts = opts || {};
221
+
222
+ return {
223
+ /**
224
+ * 执行 decision:序列化为 dispatcher 指令写入 state-store,并回填 checklistResult。
225
+ *
226
+ * 签名严格匹配 engine act() 调用(index.js:364-365):
227
+ * execute(context, loopId, decision, state) -> Promise<{dispatched, checklistResult?}>
228
+ *
229
+ * @param {PluginContext} context loop-engine 注入的 context(含 getProvider / getStateStore)
230
+ * @param {string} loopId loop 运行唯一 ID
231
+ * @param {object} decision engine _think 产出
232
+ * @param {object} state loop state(engine.act 传入)
233
+ * @returns {Promise<{dispatched:boolean, checklistResult?:object, error?:string, placeholder?:boolean}>}
234
+ */
235
+ execute: async function (context, loopId, decision, state) {
236
+ // 容错:state-store 不可用时降级返回,不抛异常中断 step()
237
+ var storeRes = (opts.store)
238
+ ? { store: opts.store, injected: true }
239
+ : resolveStore(context);
240
+ if (!storeRes || !storeRes.store || typeof storeRes.store.set !== 'function') {
241
+ return { dispatched: false, checklistResult: undefined, error: 'state-store unavailable' };
242
+ }
243
+ var store = storeRes.store;
244
+
245
+ // decision.action 不在派发集合(如 noop)→ 不产出指令,但仍可回填已就绪的 checklist
246
+ if (!loopId || !decision || !ACTION_TO_MODE[decision.action]) {
247
+ var fallbackChk = await loadLastChecklist(store, loopId);
248
+ return {
249
+ dispatched: false,
250
+ checklistResult: fallbackChk || undefined,
251
+ };
252
+ }
253
+
254
+ // 1) 序列化 decision 为 dispatcher 指令(含 failingDrivers)
255
+ var pendingAction = buildPendingAction(loopId, decision);
256
+
257
+ // 2) 幂等:按 wpId+mode 覆盖(同一 decision 重复 execute 不产生重复指令)
258
+ // state-store 的 set 对同一 key 直接覆盖,天然满足幂等;这里显式构造 key。
259
+ var pendingKey = 'loop.' + loopId + '.pendingAction';
260
+ try {
261
+ await store.set(pendingKey, pendingAction);
262
+ } catch (e) {
263
+ return {
264
+ dispatched: false,
265
+ checklistResult: undefined,
266
+ error: 'state-store set failed: ' + (e && e.message ? e.message : String(e)),
267
+ };
268
+ }
269
+
270
+ // 3) 回填支持:若 state/已存在 lastChecklist,返回 checklistResult 供 engine 写入
271
+ // engine.act 在 result.checklistResult 存在时另行写入 lastChecklist(index.js:372-374)。
272
+ // 这里优先 state.lastChecklist(engine 透传),否则读 store 子 key。
273
+ var backfill = (state && state.lastChecklist) || (await loadLastChecklist(store, loopId));
274
+
275
+ return {
276
+ dispatched: true,
277
+ checklistResult: backfill || undefined,
278
+ _mode: pendingAction.mode,
279
+ _idempotencyKey: idempotencyKey(pendingAction),
280
+ _storeInjected: storeRes.injected,
281
+ };
282
+ },
283
+ };
284
+ }
285
+
286
+ module.exports = {
287
+ createActuator: createActuator,
288
+ // 暴露内部工具便于单元测试
289
+ _buildPendingAction: buildPendingAction,
290
+ _idempotencyKey: idempotencyKey,
291
+ _ACTION_TO_MODE: ACTION_TO_MODE,
292
+ };
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Loop Coordinator — 多 Agentic Loop 实例全局协调
3
+ *
4
+ * @module loop-coordinator
5
+ *
6
+ * 复用 multi-window-coordinator.aggregateWindowStates 的聚合模式(design.md §2.1.5、
7
+ * §10 WP-174-5 提示),把每个 loop 实例当作"逻辑窗口",聚合各 loop 的
8
+ * iteration/proximity/verdict/health,产出全局收敛视角。
9
+ *
10
+ * 职责边界(design.md §6.5 / §7.1):
11
+ * - 只读聚合各 loop 状态(不写各 loop 自身状态,避免多进程并发写——state-store.js:19-23
12
+ * 明确不支持多进程并发写)。
13
+ * - 提供全局 verdict:所有 loop achieved → global_achieved(可进 P4);
14
+ * 任一 loop circuit_broken/terminated → global_circuit_broken(全局回退);
15
+ * 任一 loop diverged/timeout → global_failed(回 P1);否则 global_running。
16
+ * - 不越界:coordinator 不调度、不拆分、不干预各 loop 内部状态机;仅作全局判定与汇总。
17
+ *
18
+ * 并发策略(design.md §8.3 / state-store CONCURRENCY NOTES):
19
+ * - 每 loop 独立 namespace `loop.{loopId}`,由各 loop 进程单写。
20
+ * - coordinator 通过注入的 store 查询多 loop 状态(listKeys 前缀扫描 + get),
21
+ * 读取失败的单 loop 降级为 disconnected,不阻断聚合。
22
+ *
23
+ * Work package: WP-174-5-impl-converge
24
+ * Design ref: docs/reports/agentic-loop-design.md §2.1.5、§6、§10
25
+ */
26
+
27
+ 'use strict';
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // 常量
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /**
34
+ * 终止类 verdict(design.md §6.1-6.3)。running/continue 视为仍在迭代。
35
+ * 状态字符串与 loop-engine createLoopState().status 对齐。
36
+ */
37
+ var TERMINAL_VERDICTS = {
38
+ achieved: true,
39
+ timeout: true,
40
+ diverged: true,
41
+ circuit_broken: true,
42
+ aborted: true,
43
+ };
44
+
45
+ /**
46
+ * 熔断类 verdict(任一出现即触发全局回退,最高优先级)。
47
+ */
48
+ var CIRCUIT_VERDICTS = {
49
+ circuit_broken: true,
50
+ aborted: true,
51
+ };
52
+
53
+ /**
54
+ * 失败回退类 verdict(回 P1 人介入,但非熔断)。
55
+ */
56
+ var FAILED_VERDICTS = {
57
+ timeout: true,
58
+ diverged: true,
59
+ };
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // 工具函数
63
+ // ---------------------------------------------------------------------------
64
+
65
+ /**
66
+ * ISO 时间戳。
67
+ * @returns {string}
68
+ */
69
+ function nowIso() {
70
+ return new Date().toISOString();
71
+ }
72
+
73
+ /**
74
+ * 从单个 loop 状态提取协调器所需摘要视图(仿 multi-window aggregateSingleWindow)。
75
+ *
76
+ * @param {string} loopId
77
+ * @param {object|null} state - loop-engine 的 LoopState(state-store 中 loop.{loopId})
78
+ * @returns {object} 单 loop 协调摘要
79
+ */
80
+ function summarizeLoop(loopId, state) {
81
+ if (!state) {
82
+ return {
83
+ loopId: loopId,
84
+ status: 'disconnected',
85
+ iteration: 0,
86
+ proximity: 0,
87
+ verdict: null,
88
+ health: 'unknown',
89
+ diverged: false,
90
+ updatedAt: null,
91
+ error: 'state-missing',
92
+ };
93
+ }
94
+
95
+ var verdict = state.lastVerdict && state.lastVerdict.verdict
96
+ ? state.lastVerdict.verdict
97
+ : null;
98
+ var evalResult = state.lastEval || {};
99
+ var snapshot = state.lastSnapshot || {};
100
+ var watchdog = snapshot.watchdog || {};
101
+
102
+ // health 优先取 watchdog 健康字段,回退 status 推断
103
+ var health = watchdog.health || (state.status === 'circuit_broken' ? 'terminated' : 'healthy');
104
+
105
+ return {
106
+ loopId: loopId,
107
+ status: state.status || 'unknown',
108
+ iteration: state.iteration || 0,
109
+ proximity: typeof evalResult.proximity === 'number' ? evalResult.proximity : 0,
110
+ verdict: verdict,
111
+ health: health,
112
+ diverged: !!(evalResult.diverged),
113
+ divergenceStreak: evalResult.divergenceStreak || state.divergenceStreak || 0,
114
+ updatedAt: state.lastUpdatedAt || null,
115
+ error: null,
116
+ };
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // 聚合器
121
+ // ---------------------------------------------------------------------------
122
+
123
+ /**
124
+ * 聚合多 loop 实例状态为全局协调视图(复用 aggregateWindowStates 模式)。
125
+ *
126
+ * 数据来源:
127
+ * - 首选 `loopStates` 数组(调用方已通过 state-store.get('loop.{loopId}') 拉取,
128
+ * 适用于明确知道 loopId 集合的场景,跨进程读最安全)。
129
+ * - 若传入 `store`(state-store 实例)且未提供 loopStates,则尝试前缀扫描
130
+ * `loop.` 开头的 key 聚合(依赖 store.listKeys/listByPrefix 能力,能力缺失时
131
+ * 返回空聚合,不报错)。
132
+ *
133
+ * @param {object} opts
134
+ * @param {Array<object>} [opts.loopStates] - 各 loop 的 LoopState 数组(loopId 字段必填)
135
+ * @param {object} [opts.store] - state-store 实例(提供 listKeys/get)
136
+ * @param {string} [opts.sessionId] - 可选会话 ID(多 loop 会话标识)
137
+ * @returns {Promise<object>} 全局协调视图(global verdict + 各 loop 摘要 + 全局计数)
138
+ */
139
+ async function aggregateLoopStates(opts) {
140
+ opts = opts || {};
141
+ var now = nowIso();
142
+
143
+ // 收集 loopState 列表
144
+ var states = [];
145
+ if (Array.isArray(opts.loopStates)) {
146
+ states = opts.loopStates;
147
+ } else if (opts.store) {
148
+ states = await collectLoopStatesFromStore(opts.store);
149
+ }
150
+
151
+ // 构建 loop 摘要映射
152
+ var loops = {};
153
+ var loopIds = [];
154
+ for (var i = 0; i < states.length; i++) {
155
+ var st = states[i] || {};
156
+ var lid = st.loopId;
157
+ if (!lid) continue; // 无 loopId 的脏数据跳过
158
+ loops[lid] = summarizeLoop(lid, st);
159
+ loopIds.push(lid);
160
+ }
161
+
162
+ // 全局计数
163
+ var global = computeGlobalState(loops, loopIds);
164
+
165
+ return {
166
+ session_id: opts.sessionId || ('loop-session-' + now.replace(/[:.]/g, '').slice(0, 15)),
167
+ aggregated_at: now,
168
+ total_loops: loopIds.length,
169
+ loops: loops,
170
+ global: global,
171
+ };
172
+ }
173
+
174
+ /**
175
+ * 从 state-store 收集所有 `loop.` 前缀的 loop 状态(跨 loop 进程的只读聚合)。
176
+ *
177
+ * state-store 不支持 listKeys 时返回空数组(降级,不阻断)。
178
+ * @private
179
+ * @param {object} store
180
+ * @returns {Promise<Array<object>>}
181
+ */
182
+ async function collectLoopStatesFromStore(store) {
183
+ if (!store) return [];
184
+ // 优先用显式 listByPrefix(若 store 提供),否则尝试通用 listKeys 过滤
185
+ var keys = [];
186
+ try {
187
+ if (typeof store.listByPrefix === 'function') {
188
+ keys = await store.listByPrefix('loop.');
189
+ } else if (typeof store.listKeys === 'function') {
190
+ var all = await store.listKeys();
191
+ keys = (all || []).filter(function (k) { return String(k).indexOf('loop.') === 0; });
192
+ } else {
193
+ return [];
194
+ }
195
+ } catch (_e) {
196
+ return [];
197
+ }
198
+
199
+ var states = [];
200
+ for (var i = 0; i < keys.length; i++) {
201
+ try {
202
+ var st = await store.get(keys[i]);
203
+ if (st && st.loopId) states.push(st);
204
+ } catch (_e2) {
205
+ // 单 loop 读取失败,跳过(不阻断聚合)
206
+ }
207
+ }
208
+ return states;
209
+ }
210
+
211
+ /**
212
+ * 计算全局协调状态(仿 multi-window computeSessionStatus,但语义对齐 loop 终止判定)。
213
+ *
214
+ * 全局 verdict 优先级(与 design.md §6.5 单 loop 优先级一致:熔断 > 失败 > 达成 > 运行):
215
+ * 1) 任一 loop circuit_broken/aborted/health=terminated → 'global_circuit_broken'
216
+ * 2) 任一 loop timeout/diverged → 'global_failed'
217
+ * 3) 全部 loop achieved → 'global_achieved'
218
+ * 4) 否则 → 'global_running'
219
+ *
220
+ * @param {object} loops - { loopId: summary }
221
+ * @param {string[]} loopIds
222
+ * @returns {object} { verdict, reason, achievedCount, circuitCount, failedCount, runningCount, minProximity, maxIteration }
223
+ */
224
+ function computeGlobalState(loops, loopIds) {
225
+ var achievedCount = 0;
226
+ var circuitCount = 0;
227
+ var failedCount = 0;
228
+ var runningCount = 0;
229
+ var disconnectedCount = 0;
230
+ var minProximity = 1;
231
+ var maxIteration = 0;
232
+ var minProximitySet = false;
233
+
234
+ for (var i = 0; i < loopIds.length; i++) {
235
+ var s = loops[loopIds[i]];
236
+ if (!s) continue;
237
+
238
+ if (s.status === 'disconnected') {
239
+ disconnectedCount++;
240
+ continue;
241
+ }
242
+
243
+ // 熔断判定(health terminated 优先,其次 verdict)
244
+ var isCircuit = CIRCUIT_VERDICTS[s.verdict] || s.health === 'terminated' || s.status === 'circuit_broken' || s.status === 'aborted';
245
+ var isFailed = FAILED_VERDICTS[s.verdict] || s.verdict === 'timeout' || s.verdict === 'diverged' || s.status === 'timeout' || s.status === 'diverged';
246
+ var isAchieved = s.verdict === 'achieved' || s.status === 'achieved';
247
+
248
+ if (isCircuit) circuitCount++;
249
+ else if (isFailed) failedCount++;
250
+ else if (isAchieved) achievedCount++;
251
+ else runningCount++;
252
+
253
+ if (typeof s.proximity === 'number') {
254
+ if (!minProximitySet || s.proximity < minProximity) {
255
+ minProximity = s.proximity;
256
+ minProximitySet = true;
257
+ }
258
+ }
259
+ if (s.iteration > maxIteration) maxIteration = s.iteration;
260
+ }
261
+
262
+ if (!minProximitySet) minProximity = 0;
263
+
264
+ // 全局 verdict(优先级:熔断 > 失败 > 达成 > 运行)
265
+ var verdict;
266
+ var reason;
267
+ if (circuitCount > 0) {
268
+ verdict = 'global_circuit_broken';
269
+ reason = circuitCount + ' 个 loop 熔断/终止,全局回退';
270
+ } else if (failedCount > 0) {
271
+ verdict = 'global_failed';
272
+ reason = failedCount + ' 个 loop 触顶/发散,回 P1 人介入';
273
+ } else if (loopIds.length > 0 && achievedCount === (loopIds.length - disconnectedCount) && achievedCount > 0) {
274
+ // 所有非 disconnected 的 loop 均达成
275
+ verdict = 'global_achieved';
276
+ reason = '全部 ' + achievedCount + ' 个 loop 达成,可进 P4';
277
+ } else {
278
+ verdict = 'global_running';
279
+ reason = runningCount + ' 个 loop 迭代中';
280
+ }
281
+
282
+ return {
283
+ verdict: verdict,
284
+ reason: reason,
285
+ achievedCount: achievedCount,
286
+ circuitCount: circuitCount,
287
+ failedCount: failedCount,
288
+ runningCount: runningCount,
289
+ disconnectedCount: disconnectedCount,
290
+ minProximity: minProximity,
291
+ maxIteration: maxIteration,
292
+ };
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // 全局判定辅助
297
+ // ---------------------------------------------------------------------------
298
+
299
+ /**
300
+ * 判定全局是否达成(所有 loop achieved,可进 P4)。
301
+ * @param {object} aggregated - aggregateLoopStates 返回值
302
+ * @returns {boolean}
303
+ */
304
+ function isGlobalAchieved(aggregated) {
305
+ return !!(aggregated && aggregated.global && aggregated.global.verdict === 'global_achieved');
306
+ }
307
+
308
+ /**
309
+ * 判定全局是否熔断(任一 loop 熔断,应全局回退)。
310
+ * @param {object} aggregated
311
+ * @returns {boolean}
312
+ */
313
+ function isGlobalCircuitBroken(aggregated) {
314
+ return !!(aggregated && aggregated.global && aggregated.global.verdict === 'global_circuit_broken');
315
+ }
316
+
317
+ /**
318
+ * 判定全局是否需要回 P1(熔断或失败)。
319
+ * @param {object} aggregated
320
+ * @returns {boolean}
321
+ */
322
+ function needsHumanIntervention(aggregated) {
323
+ if (!aggregated || !aggregated.global) return false;
324
+ var v = aggregated.global.verdict;
325
+ return v === 'global_circuit_broken' || v === 'global_failed';
326
+ }
327
+
328
+ // ---------------------------------------------------------------------------
329
+ // Exports
330
+ // ---------------------------------------------------------------------------
331
+
332
+ module.exports = {
333
+ // 常量(暴露供测试)
334
+ TERMINAL_VERDICTS: TERMINAL_VERDICTS,
335
+ CIRCUIT_VERDICTS: CIRCUIT_VERDICTS,
336
+ FAILED_VERDICTS: FAILED_VERDICTS,
337
+
338
+ // 聚合
339
+ aggregateLoopStates: aggregateLoopStates,
340
+ summarizeLoop: summarizeLoop,
341
+ computeGlobalState: computeGlobalState,
342
+
343
+ // 全局判定
344
+ isGlobalAchieved: isGlobalAchieved,
345
+ isGlobalCircuitBroken: isGlobalCircuitBroken,
346
+ needsHumanIntervention: needsHumanIntervention,
347
+ };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Agentic Loop 决策阈值 —— 唯一默认源(单源化,Phase B-1)
5
+ // ---------------------------------------------------------------------------
6
+ // 历史问题:同一组阈值曾在两处独立定义——provider-loop-engine 的 DEFAULT_CONFIG
7
+ // (5 个全量)与 reflection-evaluator 的 DEFAULT_THRESHOLDS(2 个子集)。engine
8
+ // 内部曾因此出现「evaluator 用自己的默认阈值绕过 engine init() override」的漂移
9
+ // bug(见 engine _decide 历史注释)。本文件即唯一真相源,两处一律 require 此表。
10
+ //
11
+ // 注意:plugins/core/skill-agentic-loop/plugin.json 的 config 段是本表的**静态
12
+ // 镜像**(JSON 无法 require JS);修改任一默认值时必须同步该镜像,否则
13
+ // plugin loader 传入的旧值会覆盖 init() 前的默认路径。
14
+ // ---------------------------------------------------------------------------
15
+
16
+ var LOOP_DEFAULTS = Object.freeze({
17
+ // 迭代硬上限 → 超时终止(WP-177 由 10 改为 6)
18
+ max_iterations: 6,
19
+ // 单轮最长时间(ms)→ act 完成后即时校验(WP-177 新增)
20
+ max_round_time_ms: 600000,
21
+ // 总墙钟上限(ms)→ step() 开头与 _decide 校验
22
+ max_wall_time_ms: 3600000,
23
+ // 连续 N 轮无进展 → 发散终止
24
+ divergence_threshold: 3,
25
+ // proximity ≥ 此值且 checklist 全过 → 目标达成
26
+ proximity_goal: 0.9,
27
+ });
28
+
29
+ module.exports = LOOP_DEFAULTS;