doukui 0.6.0 → 0.8.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 (44) hide show
  1. package/README.md +27 -67
  2. package/bin/commands/help.js +0 -25
  3. package/bin/doukui.js +1 -3
  4. package/package.json +2 -3
  5. package/plugins/core/skill-agent-dispatcher/monitoring-reference.md +261 -0
  6. package/plugins/core/skill-agent-dispatcher/recovery-reference.md +91 -0
  7. package/plugins/core/skill-agent-dispatcher/skill.md +39 -299
  8. package/plugins/core/skill-agentic-loop/mirror-rules.md +82 -23
  9. package/plugins/core/skill-agentic-loop/plugin.json +2 -7
  10. package/plugins/core/skill-agentic-loop/skill.md +49 -77
  11. package/plugins/core/skill-completion-report/skill.md +7 -1
  12. package/plugins/core/skill-doukui-plan/skill.md +3 -0
  13. package/plugins/plugin-registry.json +0 -12
  14. package/plugins/runtime/plan-reader.js +33 -18
  15. package/plugins/runtime/text-tokenize.js +1 -2
  16. package/templates/harness-config.yaml +0 -100
  17. package/bin/commands/loop-server.js +0 -357
  18. package/bin/commands/loop.js +0 -1508
  19. package/plugins/contracts/checkresult-schema.json +0 -75
  20. package/plugins/core/provider-loop-engine/index.js +0 -1411
  21. package/plugins/core/provider-loop-engine/plugin.json +0 -15
  22. package/plugins/runtime/checkresult-validator.js +0 -131
  23. package/plugins/runtime/context-window.js +0 -81
  24. package/plugins/runtime/executor-claude.js +0 -604
  25. package/plugins/runtime/executor-default.js +0 -448
  26. package/plugins/runtime/executor-local.js +0 -178
  27. package/plugins/runtime/executor-sdk.js +0 -415
  28. package/plugins/runtime/loop-actuator.js +0 -292
  29. package/plugins/runtime/loop-coordinator.js +0 -347
  30. package/plugins/runtime/loop-defaults.js +0 -29
  31. package/plugins/runtime/loop-dispatch-batch.js +0 -351
  32. package/plugins/runtime/loop-executor.js +0 -120
  33. package/plugins/runtime/loop-report.js +0 -395
  34. package/plugins/runtime/loop-server-core.js +0 -750
  35. package/plugins/runtime/loop-snapshot.js +0 -581
  36. package/plugins/runtime/loop-trace.js +0 -242
  37. package/plugins/runtime/loop-worktree.js +0 -404
  38. package/plugins/runtime/multi-window-coordinator.js +0 -560
  39. package/plugins/runtime/objective-verifier.js +0 -136
  40. package/plugins/runtime/plan-lint.js +0 -106
  41. package/plugins/runtime/provider-failover.js +0 -114
  42. package/plugins/runtime/provider-resolver.js +0 -342
  43. package/plugins/runtime/reflection-evaluator.js +0 -545
  44. package/plugins/runtime/self-rescue-ladder.js +0 -51
@@ -1,581 +0,0 @@
1
- /**
2
- * Loop Snapshot — Agentic Loop 环境感知聚合器(WP-174-3,Observe 层)
3
- *
4
- * @module loop-snapshot
5
- *
6
- * 聚合四类输入源为统一 LoopSnapshot 对象(design.md §5.2):
7
- * 1. state-store - loop 上下文 + 目标工作包(key: "loop.{loopId}")
8
- * 2. progress-tracker - PROGRESS.md 中的 WP 完成标记(降级解析,失败不影响整体)
9
- * 3. watchdog - context.getProvider('provider:watchdog'),isRunning/isDeployed
10
- * 4. git diff - child_process 'git diff --stat',本轮变更范围
11
- * 外加 lastChecklist - state-store.get("loop.{loopId}.lastChecklist")(Act 阶段写入)
12
- *
13
- * 韧性约定(design.md §10 WP-174-3 提示):任一输入源失败降级(try/catch + warning),
14
- * 不阻断聚合;缺失的源返回空字段,整体 LoopSnapshot 仍结构完整。
15
- *
16
- * 接入契约(必须匹配 provider-loop-engine/index.js inject 期望):
17
- * loopEngine.inject({ snapshot: thisModule })
18
- * engine 在 observe 阶段调用:snapshot.aggregate(context, loopId) → LoopSnapshot
19
- *
20
- * 设计依据:docs/reports/agentic-loop-design.md §5.2
21
- */
22
-
23
- 'use strict';
24
-
25
- var fs = require('fs');
26
- var path = require('path');
27
- var crypto = require('crypto');
28
- var { execFileSync } = require('child_process');
29
- var { StateStore } = require('./state-store');
30
-
31
- // 复用 reflection-evaluator 的失败项归一化(WP-176-1 的 _failingWpsFromChecklist)。
32
- // 该辅助产出"从 checklist 失败项 → 去重 wpId 候选集"的统一口径;snapshot 在此基础上
33
- // 排除 completed、限定 goal 范围。evaluator 不可用时退化为本地等价实现。
34
- var evaluatorNormalize;
35
- try {
36
- evaluatorNormalize = require('./reflection-evaluator');
37
- } catch (_e) {
38
- evaluatorNormalize = null;
39
- }
40
-
41
- // ---------------------------------------------------------------------------
42
- // 默认配置
43
- // ---------------------------------------------------------------------------
44
-
45
- /**
46
- * watchdog 状态查询超时(ms)。仅用于 fail-fast,watchdog 查询本身是同步的。
47
- */
48
- var WATCHDOG_QUERY_TIMEOUT_MS = 2000;
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-engine:向上找 task.md / .claude)。
64
- * @returns {string}
65
- */
66
- function resolveProjectRoot() {
67
- var dir = process.cwd();
68
- for (var i = 0; i < 10; i++) {
69
- if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
70
- if (fs.existsSync(path.join(dir, '.claude'))) return dir;
71
- var parent = path.dirname(dir);
72
- if (parent === dir) break;
73
- dir = parent;
74
- }
75
- return process.cwd();
76
- }
77
-
78
- /**
79
- * 确定一个可用的 state-store 句柄。
80
- * 优先复用 context 注入的 provider:state-store;否则用本地 StateStore(.claude-state)。
81
- * @param {PluginContext} context
82
- * @returns {{ store: StateStore, injected: boolean }}
83
- */
84
- function resolveStore(context) {
85
- // 1) 优先 context 注入的 state-store provider(factory 返回的 API 含 get/set)
86
- if (context && typeof context.getProvider === 'function') {
87
- try {
88
- // getProvider 可能是 async(返回 Promise),也可能是同步;两种都兼容
89
- var maybe = context.getProvider('provider:state-store');
90
- if (maybe && typeof maybe.then === 'function') {
91
- // B18/A1:async getProvider 无法在同步 resolveStore 内 await。
92
- // 之前只是"靠巧合工作"——降级注释之后没有真正处理。这里明确:
93
- // 降级到本地 store(path 由调用方决定),同时通过微任务把 Promise 的
94
- // rejection 静默吞掉,避免 unhandledRejection 终止进程。
95
- maybe.then(function () { /* provider resolved after fallback; ignore */ },
96
- function (_e) { /* provider rejected; fallback already in use */ });
97
- } else if (maybe && (typeof maybe.get === 'function' || typeof maybe.getState === 'function')) {
98
- // provider:state-store 的 factory API 直接暴露 get/set
99
- return { store: wrapProviderStore(maybe), injected: true };
100
- }
101
- } catch (e) {
102
- // 注入失败,降级
103
- }
104
- }
105
- // 2) 降级:本地 StateStore
106
- // A1 NOTE:跨 loop 物理隔离由调用方负责——bin/commands/loop.js 的
107
- // resolveLoopWorkspace 已在 <stateDir>/<loopId>/ 下为每个 loop 建立独立
108
- // workspaceRoot,engine 的 StateStore({filePath: workspaceRoot/'.claude-state'})
109
- // 即天然分桶。此处保持扁平回退以与 engine 的 StateStore 路径一致,避免
110
- // snapshot/actuator 与 engine 写入不同文件造成"状态分裂"。
111
- var root = resolveProjectRoot();
112
- return {
113
- store: new StateStore({ filePath: path.join(root, '.claude-state') }),
114
- injected: false,
115
- };
116
- }
117
-
118
- /**
119
- * 包装 provider:state-store 的 factory API 为统一 { get/set } 接口。
120
- * provider:state-store factory 返回 get(key)/set(key,val)/getState() 等。
121
- * @param {object} providerApi
122
- * @returns {{ get: Function, set: Function }}
123
- */
124
- function wrapProviderStore(providerApi) {
125
- return {
126
- get: function (key) {
127
- return providerApi.get(key);
128
- },
129
- set: function (key, value) {
130
- return providerApi.set(key, value);
131
- },
132
- };
133
- }
134
-
135
- /**
136
- * 查询 watchdog 健康(design.md §5.2.1 watchdog 源 / §6.3.2)。
137
- * 委托 context.getProvider('provider:watchdog');失败降级为 { deployed:false, health:'unknown' }。
138
- * @param {PluginContext} context
139
- * @returns {{ deployed: boolean, running: boolean, health: string }}
140
- */
141
- function queryWatchdog(context) {
142
- var fallback = { deployed: false, running: false, health: 'unknown' };
143
- if (!context || typeof context.getProvider !== 'function') {
144
- return fallback;
145
- }
146
- var watchdog;
147
- try {
148
- watchdog = context.getProvider('provider:watchdog');
149
- } catch (e) {
150
- return fallback;
151
- }
152
- // getProvider 可能返回 Promise(async provider)
153
- if (watchdog && typeof watchdog.then === 'function') {
154
- // 同步上下文无法 await,降级;watchdog 健康非关键路径(engine.decide 也会查)
155
- return fallback;
156
- }
157
- if (!watchdog || typeof watchdog !== 'object') {
158
- return fallback;
159
- }
160
- var deployed = typeof watchdog.isDeployed === 'function' ? !!watchdog.isDeployed() : false;
161
- var running = typeof watchdog.isRunning === 'function' ? !!watchdog.isRunning() : false;
162
- var health;
163
- if (!deployed) {
164
- health = 'undeployed';
165
- } else if (!running) {
166
- health = 'terminated';
167
- } else {
168
- health = 'healthy'; // isRunning 只能区分 terminated vs 非 terminated,无法区分 degraded
169
- }
170
- return { deployed: deployed, running: running, health: health };
171
- }
172
-
173
- /**
174
- * 解析 git diff 统计(design.md §5.2.1 git diff 源)。
175
- * 用 execFileSync 同步执行 'git diff --stat'(HEAD 相对未提交变更)。
176
- * 失败降级为零变更。
177
- * @param {string} projectRoot
178
- * @returns {{ changedFiles: number, insertions: number, deletions: number, filesByWp: object }}
179
- */
180
- function queryGitDiff(projectRoot) {
181
- var empty = { changedFiles: 0, insertions: 0, deletions: 0, filesByWp: {} };
182
- var out;
183
- try {
184
- // --numstat 输出 "added\tdeleted\tpath",便于聚合 insertions/deletions
185
- // stdio 显式 pipe 子进程 stderr:失败时(无 git/无 HEAD/非仓库)捕获到 e.stderr
186
- // 而不泄露到父进程 stderr(避免 `fatal: ambiguous argument 'HEAD'` 刷屏污染输出)
187
- out = execFileSync(
188
- 'git',
189
- ['diff', '--numstat', 'HEAD'],
190
- { cwd: projectRoot, encoding: 'utf8', timeout: WATCHDOG_QUERY_TIMEOUT_MS,
191
- stdio: ['ignore', 'pipe', 'pipe'] }
192
- );
193
- } catch (e) {
194
- // 无 git / 无 HEAD / 非仓库:静默降级(e.stderr 已被管道捕获,不打印)
195
- return empty;
196
- }
197
- if (!out) return empty;
198
-
199
- var changedFiles = 0;
200
- var insertions = 0;
201
- var deletions = 0;
202
- var lines = out.split(/\r?\n/);
203
- for (var i = 0; i < lines.length; i++) {
204
- var line = lines[i];
205
- if (!line) continue;
206
- var parts = line.split('\t');
207
- if (parts.length < 3) continue;
208
- var add = parts[0];
209
- var del = parts[1];
210
- var filePath = parts.slice(2).join('\t');
211
- // 二进制文件显示 "-\t-",按 0 处理
212
- insertions += (add === '-' || isNaN(parseInt(add, 10))) ? 0 : parseInt(add, 10);
213
- deletions += (del === '-' || isNaN(parseInt(del, 10))) ? 0 : parseInt(del, 10);
214
- changedFiles += 1;
215
- // filesByWp:尝试从路径提取 WP-XXX 前缀(如 docs/wp/WP-174.md → "WP-174")
216
- // WP-186 / WP-192-6:正则严格化为 WP-?([A-Za-z0-9][\w-]*),与 plan-reader
217
- // extractExplicitWpId / parseProgressMarkdown 口径完全一致(首字符必须字母/数字,
218
- // 杜绝 WP-- / WP-_ 这类下划线/连字符开头编号),支持字母/混合编号。
219
- var wpMatch = String(filePath).match(/WP-?([A-Za-z0-9][\w-]*)/i);
220
- if (wpMatch) {
221
- var wpKey = 'WP-' + wpMatch[1];
222
- if (!empty.filesByWp[wpKey]) empty.filesByWp[wpKey] = [];
223
- empty.filesByWp[wpKey].push(filePath);
224
- }
225
- }
226
- return {
227
- changedFiles: changedFiles,
228
- insertions: insertions,
229
- deletions: deletions,
230
- filesByWp: empty.filesByWp,
231
- };
232
- }
233
-
234
- /**
235
- * 判断 wpId 是否落在 goalWps 集合内(WP-186 抽取为独立函数,供完成态兜底与 failed 越界保护共用)。
236
- * @param {string[]} goalWps
237
- * @param {string} wpId
238
- * @returns {boolean}
239
- */
240
- function inGoalStatic(goalWps, wpId) {
241
- for (var i = 0; i < goalWps.length; i++) {
242
- if (goalWps[i] === wpId) return true;
243
- }
244
- return false;
245
- }
246
-
247
- /**
248
- * 从 PROGRESS.md 解析 WP 完成状态(progress-tracker 源,降级解析)。
249
- * progress-tracker 没有标准 JSON 输出,仅维护 PROGRESS.md;这里做宽松正则匹配。
250
- * 匹配形如 "- [x] WP-175 ..." / "- [ ] WP-176 ..." 的行。
251
- * 失败返回 null(不阻断)。
252
- * @param {string} projectRoot
253
- * @returns {{ completed: string[], incomplete: string[] } | null}
254
- */
255
- function parseProgressMarkdown(projectRoot) {
256
- var progressPath = path.join(projectRoot, 'PROGRESS.md');
257
- if (!fs.existsSync(progressPath)) return null;
258
- var content;
259
- try {
260
- content = fs.readFileSync(progressPath, 'utf8');
261
- } catch (e) {
262
- return null;
263
- }
264
- var completed = [];
265
- var incomplete = [];
266
- var lines = content.split(/\r?\n/);
267
- // WP-186 / WP-192-6: 正则从 WP-?\d+ 放宽到 WP-?([A-Za-z0-9][\w-]*),支持字母/混合编号
268
- // (如 WP-A / WP-101 / WP-175),与 plan-reader extractExplicitWpId 口径完全一致
269
- // (首字符必须字母/数字,杜绝 WP-- / WP-_ 这类下划线/连字符开头编号),
270
- // 且与 engine `_think` 用 goal.wpIds 比较的口径一致。否则字母编号 WP 的完成态
271
- // 永远流转不回 engine。
272
- var reDone = /^\s*[-*]\s*\[[xX✓✔]\]\s*(WP-?[A-Za-z0-9][\w-]*)/i;
273
- var reTodo = /^\s*[-*]\s*\[\s\]\s*(WP-?[A-Za-z0-9][\w-]*)/i;
274
- // 注:捕获组 m[1] 形如 "WP-175" / "WPA"(含可选 WP 前缀),下游统一用
275
- // m[1].replace(/^WP-?/i,'') 去前缀后规整为 "WP-" + token,与 plan-reader 口径一致。
276
- for (var i = 0; i < lines.length; i++) {
277
- var line = lines[i];
278
- var mDone = line.match(reDone);
279
- if (mDone) {
280
- completed.push('WP-' + mDone[1].replace(/^WP-?/i, ''));
281
- continue;
282
- }
283
- var mTodo = line.match(reTodo);
284
- if (mTodo) {
285
- incomplete.push('WP-' + mTodo[1].replace(/^WP-?/i, ''));
286
- }
287
- }
288
- return { completed: completed, incomplete: incomplete };
289
- }
290
-
291
- // ---------------------------------------------------------------------------
292
- // Plan 指纹(WP-D9:completedSet 跨 plan 误判防护)
293
- // ---------------------------------------------------------------------------
294
- // 已知限制(v0.1.0 验收发现):PROGRESS.md 的 `- [x] WP-NNN` 完成标记不区分 plan
295
- // 来源——同项目根先后跑两个 plan 且 WP 编号重叠时,后一个 plan 的同名 WP 会被
296
- // completedSet 恢复逻辑误判已完成直接跳过。防护方案:PROGRESS.md 头部落 plan
297
- // 内容指纹(sha1 前 10 位),driver 恢复 completedSet 前比对——指纹不一致(或
298
- // 文件来自旧版无指纹)→ 忽略旧条目从零开始。写入侧:appendProgressLine 首次
299
- // 创建/迁移时补写指纹头。
300
- // ---------------------------------------------------------------------------
301
-
302
- var PROGRESS_FP_RE = /^<!--\s*doukui:progress\s+plan=([0-9a-f]{10})\s*-->/m;
303
-
304
- /**
305
- * 计算 plan 内容指纹(sha1 前 10 位)。
306
- * @param {string} planContent plan.md 原始文本
307
- * @returns {string|null} 指纹;空内容返回 null
308
- */
309
- function buildPlanFingerprint(planContent) {
310
- if (typeof planContent !== 'string' || planContent.length === 0) return null;
311
- return crypto.createHash('sha1').update(planContent, 'utf8').digest('hex').slice(0, 10);
312
- }
313
-
314
- /**
315
- * 读取 PROGRESS.md 头部的 plan 指纹。
316
- * @param {string} projectRoot 项目根(PROGRESS.md 所在目录)
317
- * @returns {string|null} 指纹;文件不存在 / 无指纹行(旧版产物)返回 null
318
- */
319
- function readProgressFingerprint(projectRoot) {
320
- var progressPath = path.join(projectRoot, 'PROGRESS.md');
321
- var content;
322
- try {
323
- content = fs.readFileSync(progressPath, 'utf8');
324
- } catch (_e) {
325
- return null;
326
- }
327
- var m = content.match(PROGRESS_FP_RE);
328
- return m ? m[1] : null;
329
- }
330
-
331
- /**
332
- * 构建/迁移 PROGRESS.md 头部的 plan 指纹(幂等:已有相同指纹 no-op)。
333
- * 纯字符串处理(不落盘)——落盘由 appendProgressLine 的原子写统一负责。
334
- * @param {string} existingContent PROGRESS.md 当前全文(空串 = 新文件)
335
- * @param {string} planFp 当前 plan 指纹
336
- * @returns {{ content: string, changed: boolean, mismatch: string|null }}
337
- * mismatch = 已有指纹且与 planFp 不同时返回旧指纹(调用方决定是否告警)
338
- */
339
- function ensureProgressFingerprint(existingContent, planFp) {
340
- var fpLine = '<!-- doukui:progress plan=' + planFp + ' -->';
341
- var m = (existingContent || '').match(PROGRESS_FP_RE);
342
- if (m) {
343
- if (m[1] === planFp) return { content: existingContent, changed: false, mismatch: null };
344
- return { content: existingContent, changed: false, mismatch: m[1] };
345
- }
346
- if (!existingContent || existingContent.length === 0) {
347
- return { content: fpLine + '\n\n# Progress\n\n', changed: true, mismatch: null };
348
- }
349
- // 旧版文件迁移:头部插入指纹行(保留原条目)
350
- return { content: fpLine + '\n' + existingContent, changed: true, mismatch: null };
351
- }
352
-
353
- /**
354
- * 从 loop state.goal.wpIds + progress 解析构建 workPackages 视图(design.md §5.2.2)。
355
- * 规则:
356
- * - goal.wpIds 为目标全集(来源 truth);progress.completed 为已完成的子集
357
- * - pending = goalWps 中未在 completed 内的
358
- * - failed = 上轮 checklist 失败项聚合出的 wpId(排除 completed、限定 goal 范围)
359
- * - blocked 当前来源不足,留空数组(由后续 WP 填充)
360
- *
361
- * failed 推导(WP-176-2,修复偏差1):
362
- * 从 lastChecklist.failedItems 经 evaluator 归一化得到失败驱动,按 wpId 去重;
363
- * 再排除已 completed(已通过的不算 failed)、限定 goal.wpIds 范围(越界保护)。
364
- * 这让 engine `_think` 的 retry 分支(wp.failed.length > 0)有真实数据支撑。
365
- *
366
- * @param {object} state loop state
367
- * @param {{completed:string[],incomplete:string[]}|null} progress
368
- * @param {object|null} [lastChecklist] 上轮 CheckResult(含 failedItems / wpId)
369
- * @returns {{total:number,pending:string[],completed:string[],failed:string[],blocked:string[]}}
370
- */
371
- function buildWorkPackages(state, progress, lastChecklist) {
372
- var goal = (state && state.goal) || {};
373
- var goalWps = (goal.wpIds && goal.wpIds.length) ? goal.wpIds.slice() : [];
374
- var completed = (progress && progress.completed) ? progress.completed.slice() : [];
375
- // WP-186: 兜底完成态推导 —— 当 lastChecklist.passed===true 且其 wpId 在 goal 范围内时,
376
- // 即使 PROGRESS.md 未写(写入与 checklist 回填的时序竞态)也视为 completed。
377
- // 防止 driver 回填 lastChecklist 后、PROGRESS.md 同步前的快照误把已过 WP 留在 pending。
378
- if (lastChecklist && lastChecklist.passed === true && lastChecklist.wpId) {
379
- var chkWpId = lastChecklist.wpId;
380
- if (goalWps.length === 0 || inGoalStatic(goalWps, chkWpId)) {
381
- if (completed.indexOf(chkWpId) === -1) completed.push(chkWpId);
382
- }
383
- }
384
- var hasCompletion = function (wpId) {
385
- for (var i = 0; i < completed.length; i++) {
386
- if (completed[i] === wpId) return true;
387
- }
388
- return false;
389
- };
390
- // goal 范围集合(越界保护:failed 必须落在 goal.wpIds 内)
391
- var inGoal = function (wpId) {
392
- return inGoalStatic(goalWps, wpId);
393
- };
394
- // Step 0 拓扑接线(next-dev-plan Batch 1):pending 按 dependencyGraph.order(Kahn 拓扑
395
- // 序)排序,让有依赖关系的 WP 按拓扑序串行(依赖在前),engine _think 取 pending[0]
396
- // 即 readyWave[0]。降级:dependencyGraph 缺失/空时按 goalWps 原序(= v0.3.15)。
397
- // order 可能含 goal 外的 WP(plan 全集),故限定 goalWps 范围(inGoalStatic 越界保护)。
398
- var depOrder = (goal.dependencyGraph && goal.dependencyGraph.order && goal.dependencyGraph.order.length)
399
- ? goal.dependencyGraph.order : null;
400
- var pending = [];
401
- var seq = depOrder || goalWps;
402
- for (var i = 0; i < seq.length; i++) {
403
- var wid = seq[i];
404
- if (inGoalStatic(goalWps, wid) && !hasCompletion(wid)) pending.push(wid);
405
- }
406
- // failed:从 lastChecklist.failedItems 聚合 wpId(WP-176-1 的归一化产候选集,
407
- // snapshot 再排除 completed + 限定 goal 范围)。这让 engine `_think` retry 分支
408
- // (wp.failed.length > 0)有真实数据支撑(修复偏差1)。
409
- var failed = [];
410
- if (lastChecklist) {
411
- var candidates = [];
412
- if (evaluatorNormalize && typeof evaluatorNormalize._failingWpsFromChecklist === 'function') {
413
- candidates = evaluatorNormalize._failingWpsFromChecklist(lastChecklist);
414
- } else {
415
- candidates = failingWpsFromChecklistInline(lastChecklist);
416
- }
417
- for (var d = 0; d < candidates.length; d++) {
418
- var wid = candidates[d];
419
- if (!wid) continue;
420
- // 排除已 completed(已通过的不算 failed);限定 goal 范围(越界保护)
421
- if (hasCompletion(wid)) continue;
422
- if (goalWps.length > 0 && !inGoal(wid)) continue;
423
- failed.push(wid);
424
- }
425
- }
426
- return {
427
- total: goalWps.length,
428
- pending: pending,
429
- completed: completed,
430
- failed: failed,
431
- blocked: [],
432
- };
433
- }
434
-
435
- /**
436
- * 内联的 failedItems → 失败 WP id 列表归一化(evaluator 不可用时的等价兜底)。
437
- * 与 reflection-evaluator.failingWpsFromChecklist 口径一致:wpId 优先取 fi.wpId,
438
- * 回退 chk.wpId;空 wpId 丢弃;按首次出现顺序去重。仅产候选集,不排除 completed/范围。
439
- * @param {object} chk CheckResult
440
- * @returns {string[]}
441
- */
442
- function failingWpsFromChecklistInline(chk) {
443
- if (!chk || !chk.failedItems || !chk.failedItems.length) return [];
444
- var defaultWpId = chk.wpId || '';
445
- var seen = {};
446
- var out = [];
447
- for (var i = 0; i < chk.failedItems.length; i++) {
448
- var fi = chk.failedItems[i];
449
- if (!fi) continue;
450
- var wid = (typeof fi.wpId === 'string' && fi.wpId) ? fi.wpId : defaultWpId;
451
- if (!wid || seen[wid]) continue;
452
- seen[wid] = true;
453
- out.push(wid);
454
- }
455
- return out;
456
- }
457
-
458
- /**
459
- * 读取 loop state(state-store key "loop.{loopId}"),降级为 null。
460
- * @param {object} store { get, set }
461
- * @param {string} loopId
462
- * @returns {Promise<object|null>}
463
- */
464
- async function loadLoopState(store, loopId) {
465
- try {
466
- var state = await store.get('loop.' + loopId);
467
- return state || null;
468
- } catch (e) {
469
- return null;
470
- }
471
- }
472
-
473
- /**
474
- * 读取上轮 checklist 结果(state-store key "loop.{loopId}.lastChecklist",design.md §5.4.4)。
475
- * @param {object} store { get, set }
476
- * @param {string} loopId
477
- * @returns {Promise<object|null>}
478
- */
479
- async function loadLastChecklist(store, loopId) {
480
- try {
481
- var chk = await store.get('loop.' + loopId + '.lastChecklist');
482
- return chk || null;
483
- } catch (e) {
484
- return null;
485
- }
486
- }
487
-
488
- // ---------------------------------------------------------------------------
489
- // 公开 API
490
- // ---------------------------------------------------------------------------
491
-
492
- module.exports = {
493
- /**
494
- * 聚合所有输入源为 LoopSnapshot(design.md §5.2.2)。
495
- *
496
- * 任一输入源失败降级(不阻断聚合):
497
- * - state-store 读失败 → workPackages 退化为空集
498
- * - progress 解析失败 → completed 为空
499
- * - watchdog 不可用 → health='unknown'
500
- * - git diff 不可用 → 零变更
501
- *
502
- * @param {PluginContext} context - loop-engine 注入的 context(含 getProvider)
503
- * @param {string} loopId - loop 运行唯一 ID
504
- * @returns {Promise<object>} LoopSnapshot
505
- */
506
- aggregate: async function (context, loopId) {
507
- if (!loopId) {
508
- throw new Error('loop-snapshot.aggregate: loopId is required');
509
- }
510
-
511
- var projectRoot = resolveProjectRoot();
512
- var storeRes = resolveStore(context);
513
- var store = storeRes.store;
514
-
515
- // 1) loop state(含 goal.wpIds)+ lastChecklist
516
- var state = await loadLoopState(store, loopId);
517
- var lastChecklist = await loadLastChecklist(store, loopId);
518
-
519
- // 2) progress(降级解析 PROGRESS.md)
520
- var progress = null;
521
- try {
522
- progress = parseProgressMarkdown(projectRoot);
523
- } catch (e) {
524
- progress = null;
525
- }
526
-
527
- // 3) workPackages 视图
528
- var workPackages;
529
- try {
530
- workPackages = buildWorkPackages(state, progress, lastChecklist);
531
- } catch (e) {
532
- workPackages = { total: 0, pending: [], completed: [], failed: [], blocked: [] };
533
- }
534
-
535
- // 4) watchdog 健康
536
- var watchdog;
537
- try {
538
- watchdog = queryWatchdog(context);
539
- } catch (e) {
540
- watchdog = { deployed: false, running: false, health: 'unknown' };
541
- }
542
-
543
- // 5) git diff
544
- var gitDiff;
545
- try {
546
- gitDiff = queryGitDiff(projectRoot);
547
- } catch (e) {
548
- gitDiff = { changedFiles: 0, insertions: 0, deletions: 0, filesByWp: {} };
549
- }
550
-
551
- // 6) signals(外部指令通道,当前从 loop state 间接推断;预留 daemon-actions 读取)
552
- var pendingDirectives = [];
553
- if (state && state.lastDirective && state.lastDirective.action === 'pause') {
554
- pendingDirectives.push('pause');
555
- }
556
-
557
- var iteration = (state && typeof state.iteration === 'number') ? state.iteration : 0;
558
-
559
- return {
560
- loopId: loopId,
561
- iteration: iteration,
562
- capturedAt: nowIso(),
563
- workPackages: workPackages,
564
- lastChecklist: lastChecklist,
565
- watchdog: watchdog,
566
- gitDiff: gitDiff,
567
- signals: { pendingDirectives: pendingDirectives },
568
- _storeInjected: storeRes.injected,
569
- };
570
- },
571
-
572
- // 暴露内部工具便于单元测试(WP-174-6)
573
- _resolveProjectRoot: resolveProjectRoot,
574
- _queryGitDiff: queryGitDiff,
575
- _parseProgressMarkdown: parseProgressMarkdown,
576
- _buildPlanFingerprint: buildPlanFingerprint,
577
- _readProgressFingerprint: readProgressFingerprint,
578
- _ensureProgressFingerprint: ensureProgressFingerprint,
579
- _buildWorkPackages: buildWorkPackages,
580
- _queryWatchdog: queryWatchdog,
581
- };