doukui 0.0.0-stage → 0.3.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.
Files changed (135) 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 +1398 -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 +1397 -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 +572 -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 +390 -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-reader.js +763 -0
  118. package/plugins/runtime/plugin-loader.js +798 -0
  119. package/plugins/runtime/plugin-trust.js +182 -0
  120. package/plugins/runtime/plugin-validator.js +491 -0
  121. package/plugins/runtime/provider-failover.js +114 -0
  122. package/plugins/runtime/provider-resolver.js +342 -0
  123. package/plugins/runtime/reflection-evaluator.js +540 -0
  124. package/plugins/runtime/resolve-plugin-path.js +297 -0
  125. package/plugins/runtime/safe-path.js +119 -0
  126. package/plugins/runtime/sandbox-context.js +235 -0
  127. package/plugins/runtime/sandbox-manager.js +609 -0
  128. package/plugins/runtime/sandbox-worker.js +215 -0
  129. package/plugins/runtime/settings-merger.js +172 -0
  130. package/plugins/runtime/state-store.js +527 -0
  131. package/plugins/runtime/team-cleanup.js +497 -0
  132. package/plugins/runtime/text-tokenize.js +25 -0
  133. package/plugins/runtime/validator-pipeline.js +475 -0
  134. package/plugins/runtime/yaml-parser.js +692 -0
  135. package/templates/harness-config.yaml +388 -0
@@ -0,0 +1,540 @@
1
+ /**
2
+ * Reflection Evaluator — Agentic Loop 反思评分器(WP-174-3,Reflect 层)
3
+ *
4
+ * @module reflection-evaluator
5
+ *
6
+ * 对当前快照评分,产出 EvalResult(design.md §5.3.2):
7
+ * - proximity 接近度 [0,1],1 - (未通过项数 / 总检查项数)
8
+ * - converged 本轮 proximity 严格大于上一轮(单调改进检测)
9
+ * - diverged 是否触发发散(连续 divergence_threshold 轮无进展)
10
+ * - divergenceStreak 连续无进展轮数(engine 在 reflect 后同步到 state)
11
+ * - trend improving | flat | regressing
12
+ * - categoryScores 按 checklist 类别细分
13
+ * - failingDrivers 失败项 → refine 驱动(evaluator-refine 反馈)
14
+ * - allPassed checklist 是否全过(decide §6.1 达成判定依赖)
15
+ * - recommendation 给 Think 的建议
16
+ *
17
+ * 发散检测(design.md §5.3.1):读 state.history 末尾 proximity 序列,
18
+ * 连续 divergence_threshold 轮 proximity 不增(含回退)则 diverged=true。
19
+ *
20
+ * 接入契约(必须匹配 provider-loop-engine/index.js inject 期望):
21
+ * loopEngine.inject({ evaluator: thisModule })
22
+ * engine 在 reflect 阶段调用:evaluator.score(context, loopId, snapshot, state) → EvalResult
23
+ *
24
+ * 判定阈值默认值与 design.md §5.3.3 / loop-engine DEFAULT_CONFIG 一致:
25
+ * proximity_goal=0.9, divergence_threshold=3
26
+ *
27
+ * 设计依据:docs/reports/agentic-loop-design.md §5.3 / §5.4
28
+ */
29
+
30
+ 'use strict';
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // 默认阈值(单源化 Phase B-1:唯一默认源 = ./loop-defaults.js,与
34
+ // provider-loop-engine 的 DEFAULT_CONFIG 同源,design.md §5.3.3)
35
+ // ---------------------------------------------------------------------------
36
+
37
+ var DEFAULT_THRESHOLDS = require('./loop-defaults');
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // 工具函数
41
+ // ---------------------------------------------------------------------------
42
+
43
+ /**
44
+ * ISO 时间戳。
45
+ * @returns {string}
46
+ */
47
+ function nowIso() {
48
+ return new Date().toISOString();
49
+ }
50
+
51
+ /**
52
+ * 从 state.history 提取按迭代排序的 proximity 序列(design.md §5.3.1 趋势/发散依赖)。
53
+ * history 每项形如 { iteration, eval: { proximity, converged, diverged }, ... }。
54
+ * @param {object} state
55
+ * @returns {number[]} proximity 序列(升序迭代)
56
+ */
57
+ function extractProximityHistory(state) {
58
+ if (!state || !state.history || !state.history.length) return [];
59
+ var seq = [];
60
+ // history 通常按追加顺序,但保险起见按 iteration 排序
61
+ var sorted = state.history.slice().sort(function (a, b) {
62
+ var ia = (a && typeof a.iteration === 'number') ? a.iteration : 0;
63
+ var ib = (b && typeof b.iteration === 'number') ? b.iteration : 0;
64
+ return ia - ib;
65
+ });
66
+ for (var i = 0; i < sorted.length; i++) {
67
+ var entry = sorted[i];
68
+ if (entry && entry.eval && typeof entry.eval.proximity === 'number') {
69
+ seq.push(entry.eval.proximity);
70
+ }
71
+ }
72
+ return seq;
73
+ }
74
+
75
+ /**
76
+ * 计算连续无进展轮数(divergenceStreak)。
77
+ * 从序列末尾向前数:连续多少个 proximity 严格不大于其前驱。
78
+ * design.md §5.3.1:连续 N 轮 proximity 不增(含回退)。
79
+ *
80
+ * 注意:当前轮 proximity 由本函数入参 curProximity 提供(尚未写入 history),
81
+ * seq 为"截至上一轮"的历史。我们把 curProximity 追加到末尾再计算。
82
+ *
83
+ * @param {number[]} seq 历史 proximity(不含当前轮)
84
+ * @param {number} curProximity 当前轮 proximity
85
+ * @returns {number}
86
+ */
87
+ function computeDivergenceStreak(seq, curProximity) {
88
+ var all = seq.slice();
89
+ all.push(curProximity);
90
+ if (all.length < 2) return 0;
91
+ var streak = 0;
92
+ // 从末尾向前:若 all[i] <= all[i-1] 则 streak+1,遇到首个严格递增即停
93
+ for (var i = all.length - 1; i >= 1; i--) {
94
+ if (all[i] <= all[i - 1]) {
95
+ streak += 1;
96
+ } else {
97
+ break;
98
+ }
99
+ }
100
+ return streak;
101
+ }
102
+
103
+ /**
104
+ * 从 lastChecklist 提取"本轮失败项数"(WP-176-5 / 偏差3 发散宽容信号)。
105
+ * 优先用 summary.failed;缺失时回退 failedItems.length。无 checklist → null(无法判定)。
106
+ *
107
+ * 这是发散宽容判定的"本轮"输入:与上轮 failedCount 对比,判定 retry 是否部分改进。
108
+ *
109
+ * @param {object} chk CheckResult
110
+ * @returns {number|null} 失败项数;无 checklist 时 null(调用方降级为 proximity 判定)
111
+ */
112
+ function failedCountFromChecklist(chk) {
113
+ if (!chk) return null;
114
+ var summary = chk.summary || {};
115
+ if (typeof summary.failed === 'number') return _clampFailed(summary.failed);
116
+ if (chk.failedItems && typeof chk.failedItems.length === 'number') {
117
+ return _clampFailed(chk.failedItems.length);
118
+ }
119
+ // summary 仅有 total/passed → 推导
120
+ var total = typeof summary.total === 'number' ? summary.total : 0;
121
+ var passed = typeof summary.passed === 'number' ? summary.passed : 0;
122
+ if (total > 0) return _clampFailed(total - passed);
123
+ return null;
124
+ }
125
+
126
+ /**
127
+ * Clamp a derived failed count to a non-negative integer.
128
+ * B19: when a buggy/lying checklist reports passed > total, total - passed
129
+ * goes negative, which corrupts computeRefineProgress. Floor at 0.
130
+ * @internal
131
+ * @param {number} n
132
+ * @returns {number}
133
+ */
134
+ function _clampFailed(n) {
135
+ if (typeof n !== 'number' || isNaN(n)) return 0;
136
+ return n < 0 ? 0 : Math.floor(n);
137
+ }
138
+
139
+ /**
140
+ * 从 state.history 末轮 eval 提取"上轮失败项数"(WP-176-5 / 偏差3)。
141
+ * history 末轮 eval 由 step() 写入;若含 failedCount 字段直接取,否则降级返回 null。
142
+ *
143
+ * @param {object} state
144
+ * @returns {number|null} 上轮失败项数;无 history 或末轮无 failedCount 时 null
145
+ */
146
+ function prevFailedCountFromHistory(state) {
147
+ if (!state || !state.history || !state.history.length) return null;
148
+ var last = state.history[state.history.length - 1];
149
+ if (last && last.eval && typeof last.eval.failedCount === 'number') {
150
+ return last.eval.failedCount;
151
+ }
152
+ return null;
153
+ }
154
+
155
+ /**
156
+ * 计算连续"无代码进展"轮数(noProgressStreak,WP-191-2-impl)。
157
+ *
158
+ * 与 proximity-based divergenceStreak 协同构成发散判据(对齐 Ralph 熔断):
159
+ * - proximity 不升 OR 无代码进展,任一连续 N 轮 → diverged
160
+ *
161
+ * 从 history 末尾向前数:连续多少轮 eval.noProgress === true。当前轮 noProgress
162
+ * 由入参 curNoProgress 提供(尚未写入 history),seq 为"截至上一轮"的历史。
163
+ *
164
+ * 向后兼容:旧 history 无 noProgress 字段(首轮 / 降级 / executor 未产信号)→
165
+ * 该轮视为 noProgress=false(不累计),避免误判。
166
+ *
167
+ * @param {object} state 含 history(每项 eval.noProgress 可选)
168
+ * @param {boolean} [curNoProgress] 当前轮 noProgress(默认 false)
169
+ * @returns {number} 连续无进展轮数
170
+ */
171
+ function noProgressStreakFromHistory(state, curNoProgress) {
172
+ // 当前轮有进展(noProgress=false)→ 打断累计,streak 归零
173
+ // (与 proximity streak "末尾连续不增"语义一致:本轮改善即断链)
174
+ if (curNoProgress !== true) return 0;
175
+ var streak = 1; // 当前轮计入
176
+ if (!state || !state.history || !state.history.length) return streak;
177
+ // 从末尾(最近一轮)向前数连续 true;遇到首个非 true 即停
178
+ for (var i = state.history.length - 1; i >= 0; i--) {
179
+ var entry = state.history[i];
180
+ if (entry && entry.eval && entry.eval.noProgress === true) {
181
+ streak += 1;
182
+ } else {
183
+ break;
184
+ }
185
+ }
186
+ return streak;
187
+ }
188
+
189
+ /**
190
+ * 判定本轮 retry 是否"部分改进"(WP-176-5 / 修复点 D,修复偏差3)。
191
+ *
192
+ * 发散宽容核心:retry 后失败项数**减少**(部分改进)视为有进展,本轮不计入
193
+ * divergenceStreak;失败项数**不变/增多**(无效 retry)才累计发散。
194
+ *
195
+ * 这区分了"针对性 refine 起作用(每轮修掉一些失败项)"与"原样重做(失败项纹丝不动)"。
196
+ * 前者不应被误判发散回退 P1。
197
+ *
198
+ * 向后兼容:任一输入为 null(无 checklist / 无上轮 failedCount,如首轮或降级路径)
199
+ * → 返回 false(无法判定部分改进),调用方降级为现有 proximity-based 累计逻辑。
200
+ *
201
+ * @param {number|null} curFailedCount 本轮失败项数
202
+ * @param {number|null} prevFailedCount 上轮失败项数
203
+ * @returns {boolean} true=部分改进(失败项严格减少)
204
+ */
205
+ function computeRefineProgress(curFailedCount, prevFailedCount) {
206
+ if (curFailedCount === null || prevFailedCount === null) return false;
207
+ if (typeof curFailedCount !== 'number' || typeof prevFailedCount !== 'number') {
208
+ return false;
209
+ }
210
+ // 部分改进:本轮失败项严格少于上轮
211
+ return curFailedCount < prevFailedCount;
212
+ }
213
+
214
+ /**
215
+ * 计算最近 N 轮 proximity 趋势(design.md §5.3.1 trend)。
216
+ * 基于当前轮与上一轮的对比(含当前轮):
217
+ * - improving curProximity > prevProximity
218
+ * - regressing curProximity < prevProximity
219
+ * - flat 相等,或无历史
220
+ * @param {number[]} seq 历史 proximity(不含当前轮)
221
+ * @param {number} curProximity 当前轮
222
+ * @returns {'improving'|'flat'|'regressing'}
223
+ */
224
+ function computeTrend(seq, curProximity) {
225
+ if (!seq.length) return 'flat';
226
+ var prev = seq[seq.length - 1];
227
+ if (curProximity > prev) return 'improving';
228
+ if (curProximity < prev) return 'regressing';
229
+ return 'flat';
230
+ }
231
+
232
+ /**
233
+ * 从 lastChecklist(CheckResult,design.md §5.4.2)计算 proximity。
234
+ * proximity = 1 - (failed / total),区间 [0,1]。total=0 时无检查项 → null(交由调用方兜底)。
235
+ * @param {object} chk CheckResult
236
+ * @returns {number|null}
237
+ */
238
+ function proximityFromChecklist(chk) {
239
+ if (!chk) return null;
240
+ var summary = chk.summary || {};
241
+ var total = typeof summary.total === 'number' ? summary.total : 0;
242
+ var passed = typeof summary.passed === 'number' ? summary.passed : 0;
243
+ var failed = typeof summary.failed === 'number' ? summary.failed : (total - passed);
244
+ if (total <= 0) {
245
+ // 无检查项:passed 视为全过 → 1;否则 0
246
+ return chk.passed === true ? 1 : 0;
247
+ }
248
+ if (failed < 0) failed = 0;
249
+ if (failed > total) failed = total;
250
+ var prox = 1 - (failed / total);
251
+ // 钳到 [0,1]
252
+ if (prox < 0) prox = 0;
253
+ if (prox > 1) prox = 1;
254
+ return prox;
255
+ }
256
+
257
+ /**
258
+ * 从 lastChecklist 的 categories 计算按类别细分得分(design.md §5.3.2 categoryScores)。
259
+ * @param {object} chk CheckResult
260
+ * @returns {Array<{category:string,passed:number,total:number,ratio:number}>}
261
+ */
262
+ function categoryScoresFromChecklist(chk) {
263
+ if (!chk || !chk.categories || !chk.categories.length) return [];
264
+ var out = [];
265
+ for (var i = 0; i < chk.categories.length; i++) {
266
+ var cat = chk.categories[i];
267
+ if (!cat) continue;
268
+ var items = cat.items || [];
269
+ var total = items.length;
270
+ var passed = 0;
271
+ for (var j = 0; j < items.length; j++) {
272
+ if (items[j] && items[j].passed === true) passed += 1;
273
+ }
274
+ var ratio = total > 0 ? passed / total : (cat.passed === true ? 1 : 0);
275
+ out.push({
276
+ category: cat.name || ('category-' + (i + 1)),
277
+ passed: passed,
278
+ total: total,
279
+ ratio: ratio,
280
+ });
281
+ }
282
+ return out;
283
+ }
284
+
285
+ /**
286
+ * 从 lastChecklist.failedItems 构建 failingDrivers(design.md §5.3.2 / §5.4.4)。
287
+ * 映射:{ wpId, category, item, reason }
288
+ * @param {object} chk CheckResult
289
+ * @returns {Array<{wpId:string,category:string,item:string,reason:string}>}
290
+ */
291
+ function failingDriversFromChecklist(chk) {
292
+ if (!chk || !chk.failedItems || !chk.failedItems.length) return [];
293
+ var wpId = chk.wpId || '';
294
+ var out = [];
295
+ for (var i = 0; i < chk.failedItems.length; i++) {
296
+ var fi = chk.failedItems[i];
297
+ if (!fi) continue;
298
+ out.push({
299
+ wpId: wpId,
300
+ category: fi.category || '',
301
+ item: fi.id || fi.text || '',
302
+ reason: fi.reason || '',
303
+ });
304
+ }
305
+ return out;
306
+ }
307
+
308
+ /**
309
+ * 从 lastChecklist.failedItems 按 wpId 聚合,得到去重的失败 WP id 列表(WP-176-1)。
310
+ *
311
+ * 这是 retry 反馈链路的源头归一化(Layer 0):为 loop-snapshot.buildWorkPackages
312
+ * 推导 `workPackages.failed`(WP-176-2)、engine retry 分支(WP-176-3)提供统一的
313
+ * "从 checklist 失败项 → 失败 WP 列表"推导口径,避免三处重复实现。
314
+ *
315
+ * 聚合规则:
316
+ * - 每个 failedItem 的 wpId 优先取其自带 `fi.wpId`,否则回退到 CheckResult 顶层 `chk.wpId`
317
+ * - 空 wpId(无来源)的失败项被丢弃(无法定位到具体 WP)
318
+ * - 结果按 wpId 去重,保持首次出现顺序
319
+ *
320
+ * 注意:本函数只做 wpId 聚合去重,**不负责**排除 completed WP / 限定 goal 范围——
321
+ * 这些是下游 snapshot 基于完整 workPackages 视图才能判断的职责(WP-176-2)。
322
+ * 这里产出的纯失败 WP 候选集,由 snapshot 再过滤。
323
+ *
324
+ * @param {object} chk CheckResult(design.md §5.4.2),含 failedItems 与 wpId
325
+ * @returns {string[]} 去重后的失败 WP id 列表(如 ['WP-5']);边界(null chk /
326
+ * 无 failedItems / 无可定位 wpId)返回 []
327
+ */
328
+ function failingWpsFromChecklist(chk) {
329
+ if (!chk || !chk.failedItems || !chk.failedItems.length) return [];
330
+ var defaultWpId = chk.wpId || '';
331
+ var seen = {};
332
+ var out = [];
333
+ for (var i = 0; i < chk.failedItems.length; i++) {
334
+ var fi = chk.failedItems[i];
335
+ if (!fi) continue;
336
+ // 优先 failedItem 自带 wpId,回退 CheckResult 顶层 wpId
337
+ var wid = (typeof fi.wpId === 'string' && fi.wpId) ? fi.wpId : defaultWpId;
338
+ if (!wid) continue; // 无来源的失败项无法定位到 WP,丢弃
339
+ if (seen[wid]) continue;
340
+ seen[wid] = true;
341
+ out.push(wid);
342
+ }
343
+ return out;
344
+ }
345
+
346
+ /**
347
+ * 从 snapshot.workPackages 计算基于 WP 完成度的 proximity(无 checklist 时的降级)。
348
+ * proximity = completed / total。
349
+ * @param {object} workPackages
350
+ * @returns {number}
351
+ */
352
+ function proximityFromWorkPackages(workPackages) {
353
+ if (!workPackages) return 0;
354
+ var total = typeof workPackages.total === 'number' ? workPackages.total : 0;
355
+ var completed = (workPackages.completed || []).length;
356
+ if (total <= 0) return 0;
357
+ var prox = completed / total;
358
+ if (prox < 0) prox = 0;
359
+ if (prox > 1) prox = 1;
360
+ return prox;
361
+ }
362
+
363
+ /**
364
+ * 生成给 Think 的建议(recommendation,design.md §5.3.2)。
365
+ * 优先级:失败项重试 > 达成 > 继续。
366
+ * @param {object} opts { failingDrivers, proximity, proximityGoal, allPassed, snapshot }
367
+ * @returns {string}
368
+ */
369
+ function buildRecommendation(opts) {
370
+ if (opts.failingDrivers && opts.failingDrivers.length > 0) {
371
+ var firstWp = opts.failingDrivers[0].wpId || '';
372
+ var category = opts.failingDrivers[0].category || '';
373
+ // 同一 WP 多类失败 → resplit;单类 → retry
374
+ if (firstWp) {
375
+ var sameWpCats = {};
376
+ var dup = false;
377
+ for (var i = 0; i < opts.failingDrivers.length; i++) {
378
+ if (opts.failingDrivers[i].wpId === firstWp && opts.failingDrivers[i].category) {
379
+ if (sameWpCats[opts.failingDrivers[i].category]) { dup = true; break; }
380
+ sameWpCats[opts.failingDrivers[i].category] = true;
381
+ }
382
+ }
383
+ var prefix = dup ? 'resplit_' : 'retry_';
384
+ var tag = category ? (prefix + firstWp + '_(' + category + ')') : (prefix + firstWp);
385
+ return tag;
386
+ }
387
+ return 'retry_failed_items';
388
+ }
389
+ if (opts.allPassed && opts.proximity >= opts.proximityGoal) {
390
+ return 'achieved';
391
+ }
392
+ return 'continue';
393
+ }
394
+
395
+ // ---------------------------------------------------------------------------
396
+ // 公开 API
397
+ // ---------------------------------------------------------------------------
398
+
399
+ module.exports = {
400
+ /**
401
+ * 对当前快照评分(design.md §5.3.4 评分 API)。
402
+ *
403
+ * @param {PluginContext} context - loop-engine 注入的 context(保留参数,兼容 engine 调用签名)
404
+ * @param {string} loopId
405
+ * @param {object} snapshot - LoopSnapshot(design.md §5.2.2),含 lastChecklist / workPackages
406
+ * @param {object} state - LoopState(design.md §5.1.1),取 history 算趋势/发散;
407
+ * engine 已在 reflect 中传入最新 state(含 divergenceStreak 历史)
408
+ * @returns {Promise<object>} EvalResult(design.md §5.3.2)
409
+ */
410
+ score: async function (context, loopId, snapshot, state) {
411
+ if (!loopId) {
412
+ throw new Error('reflection-evaluator.score: loopId is required');
413
+ }
414
+ snapshot = snapshot || {};
415
+ state = state || {};
416
+
417
+ // 阈值:优先 engine config(若 context 提供),否则默认
418
+ var thresholds = DEFAULT_THRESHOLDS;
419
+ try {
420
+ if (context && typeof context.getConfig === 'function') {
421
+ var cfg = context.getConfig();
422
+ if (cfg && typeof cfg === 'object') {
423
+ thresholds = {
424
+ proximity_goal: typeof cfg.proximity_goal === 'number'
425
+ ? cfg.proximity_goal : DEFAULT_THRESHOLDS.proximity_goal,
426
+ divergence_threshold: typeof cfg.divergence_threshold === 'number'
427
+ ? cfg.divergence_threshold : DEFAULT_THRESHOLDS.divergence_threshold,
428
+ };
429
+ }
430
+ }
431
+ } catch (e) {
432
+ thresholds = DEFAULT_THRESHOLDS;
433
+ }
434
+
435
+ // ---- proximity 计算(优先 checklist,降级 WP 完成度)----
436
+ var chk = snapshot.lastChecklist || null;
437
+ var proximity = proximityFromChecklist(chk);
438
+ var allPassed = chk ? (chk.passed === true) : false;
439
+ var categoryScores = categoryScoresFromChecklist(chk);
440
+ var failingDrivers = failingDriversFromChecklist(chk);
441
+
442
+ if (proximity === null) {
443
+ // 无 checklist:基于 WP 完成度降级
444
+ proximity = proximityFromWorkPackages(snapshot.workPackages);
445
+ // 无 checklist 时无法判定 allPassed,仅在 pending/failed 全空且 proximity 满分时近似
446
+ var wp = snapshot.workPackages || {};
447
+ var noPending = !wp.pending || wp.pending.length === 0;
448
+ var noFailed = !wp.failed || wp.failed.length === 0;
449
+ allPassed = noPending && noFailed && proximity >= 1;
450
+ }
451
+
452
+ // ---- 趋势 / 收敛 / 发散(基于 state.history)----
453
+ var seq = extractProximityHistory(state);
454
+ var prevProximity = seq.length ? seq[seq.length - 1] : null;
455
+ var converged = prevProximity !== null ? proximity > prevProximity : false;
456
+ var trend = computeTrend(seq, proximity);
457
+ var streak = computeDivergenceStreak(seq, proximity);
458
+ // 若 proximity 持续为满分(已达成),不算发散
459
+ if (proximity >= thresholds.proximity_goal && allPassed) {
460
+ streak = 0;
461
+ }
462
+ // 发散宽容(WP-176-5 / 修复点 D,修复偏差3):
463
+ // retry 后失败项数减少(部分改进)→ 视为有进展,本轮不计入 divergenceStreak。
464
+ // 仅失败项不变/增多(无效 retry)才累计发散。
465
+ // 这区分"针对性 refine 起作用(每轮修掉一些失败项)"与"原样重做(纹丝不动)",
466
+ // 防止偏差1/2 打通后的有效 refine 被误判发散回退 P1。
467
+ // 向后兼容:无 checklist / 无上轮 failedCount(首轮或降级)→ refineProgressed=false,
468
+ // 沿用上方 proximity-based streak,行为不变。
469
+ var curFailedCount = failedCountFromChecklist(chk);
470
+ var prevFailedCount = prevFailedCountFromHistory(state);
471
+ var refineProgressed = computeRefineProgress(curFailedCount, prevFailedCount);
472
+ if (refineProgressed) {
473
+ streak = 0;
474
+ }
475
+
476
+ // ---- 无代码进展信号(WP-191-2-impl,对齐 Ralph 熔断判据)----
477
+ // curNoProgress 取自 executor 写入的 chk.noProgress(工作树脏度判定,见
478
+ // executor-claude.applyProgressDetection);缺字段时视为 false(不误判)。
479
+ var curNoProgress = !!(chk && chk.noProgress === true);
480
+ var noProgressStreak = noProgressStreakFromHistory(state, curNoProgress);
481
+ // 已达成态不累计无进展(与 proximity streak 一致的宽容)
482
+ if (proximity >= thresholds.proximity_goal && allPassed) {
483
+ noProgressStreak = 0;
484
+ }
485
+
486
+ // ---- 发散判定(协同:proximity 不升 OR 无进展,任一连续 N 轮 → diverged)----
487
+ // proximityStreak:连续 proximity 不增(含 refineProgressed 宽容归零)
488
+ // noProgressStreak:连续无代码进展
489
+ // 两者并行累计,任一达阈值即发散——保留现有 proximity-based 语义不破坏。
490
+ var diverged = streak >= thresholds.divergence_threshold ||
491
+ noProgressStreak >= thresholds.divergence_threshold;
492
+
493
+ var iteration = typeof state.iteration === 'number' ? state.iteration : 0;
494
+
495
+ return {
496
+ loopId: loopId,
497
+ iteration: iteration,
498
+ proximity: proximity,
499
+ converged: converged,
500
+ diverged: diverged,
501
+ divergenceStreak: streak,
502
+ // 无代码进展信号(WP-191-2-impl):curNoProgress 来自 chk.noProgress,
503
+ // noProgressStreak 来自 history 累计;engine step() 写回 history.eval.noProgress
504
+ // 闭合反馈环。diverged = proximity 发散 OR noProgress 发散(任一连续 N 轮)。
505
+ noProgress: curNoProgress,
506
+ noProgressStreak: noProgressStreak,
507
+ trend: trend,
508
+ categoryScores: categoryScores,
509
+ failingDrivers: failingDrivers,
510
+ allPassed: allPassed,
511
+ // 本轮失败项数(WP-176-5):供 step() 写入 history.eval.failedCount,
512
+ // 下轮 score 经 prevFailedCountFromHistory 读取,驱动发散宽容判定。
513
+ failedCount: curFailedCount,
514
+ recommendation: buildRecommendation({
515
+ failingDrivers: failingDrivers,
516
+ proximity: proximity,
517
+ proximityGoal: thresholds.proximity_goal,
518
+ allPassed: allPassed,
519
+ snapshot: snapshot,
520
+ }),
521
+ scoredAt: nowIso(),
522
+ };
523
+ },
524
+
525
+ // 暴露内部工具便于单元测试(WP-174-6)
526
+ _extractProximityHistory: extractProximityHistory,
527
+ _computeDivergenceStreak: computeDivergenceStreak,
528
+ _computeTrend: computeTrend,
529
+ _failedCountFromChecklist: failedCountFromChecklist,
530
+ _prevFailedCountFromHistory: prevFailedCountFromHistory,
531
+ _noProgressStreakFromHistory: noProgressStreakFromHistory,
532
+ _computeRefineProgress: computeRefineProgress,
533
+ _proximityFromChecklist: proximityFromChecklist,
534
+ _categoryScoresFromChecklist: categoryScoresFromChecklist,
535
+ _failingDriversFromChecklist: failingDriversFromChecklist,
536
+ _failingWpsFromChecklist: failingWpsFromChecklist,
537
+ _proximityFromWorkPackages: proximityFromWorkPackages,
538
+ _buildRecommendation: buildRecommendation,
539
+ _DEFAULT_THRESHOLDS: DEFAULT_THRESHOLDS,
540
+ };