doukui 0.5.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 -99
  17. package/bin/commands/loop-server.js +0 -357
  18. package/bin/commands/loop.js +0 -1510
  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 -247
  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,604 +0,0 @@
1
- /**
2
- * Claude executor 共享 internals(WP-185 / WP-187 / v0.3.10 去死代码)
3
- *
4
- * @module executor-claude
5
- *
6
- * 定位:本模块原是完整的 claude executor;v0.3.10 起 `--executor=claude` 经
7
- * loop-executor 别名重定向到 executor-default(真实 Anthropic 与智谱/mimo 等统一
8
- * 走 default),执行器实现已并入 executor-default.js。本模块降级为**共享工具库**:
9
- * prompt 构造(buildPrompt / WP 文档读取 / retry 精读裁剪)、checklist 解析
10
- * (`json:machine-readable` 契约)、进展检测(工作树脏度)、stdout 元数据提取,
11
- * 供 executor-default 与 executor-sdk 经 `claudeInternals._*` 复用。
12
- *
13
- * ⚠️ 本模块不再导出 createExecutor——新增 executor 走 loop-executor.js REGISTRY。
14
- *
15
- * CheckResult 契约(reflection-evaluator.proximityFromChecklist /
16
- * failingDriversFromChecklist 消费,见 test-checklist-json-contract.js):
17
- *
18
- * CheckResult 契约(reflection-evaluator.proximityFromChecklist /
19
- * failingDriversFromChecklist 消费,见 test-checklist-json-contract.js):
20
- * {
21
- * wpId: string,
22
- * passed: boolean,
23
- * summary: { total:number, passed:number, failed:number },
24
- * categories: [{ name, passed, items:[{id,text,passed,reason?}] }],
25
- * failedItems: [{ category, id, reason }]
26
- * }
27
- *
28
- * 限流与超时(WP-185-impl,对齐 Ralph 模式):
29
- * - 单实例默认 100/h,超限返回 passed:false + failedItems:[{reason:'rate_limited'}]
30
- * - 单次默认 15min 超时(spawn timeout 选项 + 手动 kill),超时返回 passed:false
31
- *
32
- * 进展检测(WP-187 / WP-191-2-impl,对齐 Ralph 熔断判据):
33
- * - 判据改为**工作树脏度**(git status --porcelain):driver 不 git commit,claude
34
- * 子进程只改工作树,故 HEAD 恒不变——原 `git rev-parse HEAD` 检测恒判无进展(缺陷)。
35
- * - 执行前后读工作树脏度(porcelain 输出非空=有改动);passed=false 且工作树干净 →
36
- * noProgress=true(无进展)。该信号经 reflection-evaluator 累计 noProgressStreak,
37
- * 接入 engine _decide 发散判定(连续 N 轮无代码进展 → diverged)。
38
- * - git 不可用(非 git 仓库 / 无 git)→ 降级 noProgress=false(不阻断,不误判)。
39
- *
40
- * 可测性(遵循 codebase DI-over-mocking 哲学,见 executor-local / loop-actuator):
41
- * - createExecutor({ spawnFn }) 注入 spawn 实现,测试传 fake spawn,不真调 claude。
42
- */
43
-
44
- 'use strict';
45
-
46
- var fs = require('fs');
47
- var path = require('path');
48
- var { spawn } = require('child_process');
49
-
50
- // Phase D 校验层:schema 校验(谎报硬改判)+ 客观交叉验证(verify.command 实跑)
51
- var checkresultValidator = require('./checkresult-validator');
52
- var objectiveVerifier = require('./objective-verifier');
53
- // WP-S4:精读 retry 的共享分词(与 memory recall 同口径)
54
- var textTokenize = require('./text-tokenize');
55
-
56
- // ---------------------------------------------------------------------------
57
- // 默认配置
58
- // ---------------------------------------------------------------------------
59
-
60
- var DEFAULTS = {
61
- binary: 'claude', // Claude Code CLI 可执行名
62
- timeoutMs: 15 * 60 * 1000, // 单次执行超时 15min(对齐 executor-local)
63
- rateLimitPerHour: 100, // 单实例每小时调用上限
64
- wpDocsDir: 'docs/wp', // WP 文档目录(相对项目根;prompt 注入用)
65
- // model 占位(WP-191-1-impl-d,provider 零分支统一通道):
66
- // claude CLI 不显式 --model(走账号默认模型),这里仅暴露 config.model 字段供
67
- // driver 写 sidecar 时统一取值(executor.config.model),不引入 provider 分支。
68
- // coordinator 额度池仅对 glm 走高峰系数换算,claude 的 model 值不参与计量。
69
- model: 'claude-default',
70
- allowedTools: [
71
- // 白名单:允许 Claude 读写代码与跑测试,禁止改动 .claude/ 内部状态(防自篡改)
72
- 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash',
73
- ],
74
- };
75
-
76
- // ---------------------------------------------------------------------------
77
- // 工具函数
78
- // ---------------------------------------------------------------------------
79
-
80
- /**
81
- * ISO 时间戳。
82
- * @returns {string}
83
- */
84
- function nowIso() {
85
- return new Date().toISOString();
86
- }
87
-
88
- /**
89
- * 解析项目根目录(仿 loop-snapshot / loop-actuator:向上找 task.md / .claude)。
90
- * @returns {string}
91
- */
92
- function resolveProjectRoot() {
93
- var dir = process.cwd();
94
- for (var i = 0; i < 10; i++) {
95
- if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
96
- if (fs.existsSync(path.join(dir, '.claude'))) return dir;
97
- var parent = path.dirname(dir);
98
- if (parent === dir) break;
99
- dir = parent;
100
- }
101
- return process.cwd();
102
- }
103
-
104
- /**
105
- * 同步读 git HEAD(child_process.execFileSync)。失败返回空串。
106
- * 保留以兼容可能的外部引用与旧测试;进展检测已改用 readWorktreeDirty(见下)。
107
- * @param {string} projectRoot
108
- * @returns {string}
109
- */
110
- function readGitHead(projectRoot) {
111
- try {
112
- var { execFileSync } = require('child_process');
113
- var out = execFileSync('git', ['rev-parse', 'HEAD'], {
114
- cwd: projectRoot, encoding: 'utf8', timeout: 2000,
115
- stdio: ['ignore', 'pipe', 'pipe'],
116
- });
117
- return String(out).trim();
118
- } catch (_e) {
119
- return '';
120
- }
121
- }
122
-
123
- /**
124
- * 同步读工作树脏度(git status --porcelain)。
125
- * WP-191-2-impl 进展检测核心:driver 不 git commit,claude 子进程只改工作树,
126
- * 故以"工作树是否有改动"作为"本轮是否产生代码进展"的判据(替代恒判无进展的 HEAD 比对)。
127
- *
128
- * @param {string} projectRoot
129
- * @param {Function} [statusFn] 注入 git status 执行函数(测试用);默认 execFileSync。
130
- * 签名 (args, opts) => string;返回 porcelain 输出。
131
- * @returns {boolean|null} true=工作树脏(有进展) / false=干净(无进展) / null=无法判定(非 git 仓库降级)
132
- */
133
- function readWorktreeDirty(projectRoot, statusFn) {
134
- try {
135
- var out;
136
- if (typeof statusFn === 'function') {
137
- out = statusFn(['status', '--porcelain'], { cwd: projectRoot });
138
- } else {
139
- var { execFileSync } = require('child_process');
140
- out = execFileSync('git', ['status', '--porcelain'], {
141
- cwd: projectRoot, encoding: 'utf8', timeout: 2000,
142
- stdio: ['ignore', 'pipe', 'pipe'],
143
- });
144
- }
145
- // porcelain 输出非空(含空白行外的内容)= 工作树有改动
146
- return String(out).trim().length > 0;
147
- } catch (_e) {
148
- // 非 git 仓库 / 无 git / 超时 → 无法判定(降级,不误判无进展)
149
- return null;
150
- }
151
- }
152
-
153
- /**
154
- * 从 Claude stdout(--output-format json)提取 text 字段。
155
- * claude -p --output-format json 输出形如 { "type":"result", "result":"...", ... } 或
156
- * { "text":"..." }。兼容多种字段名:result / text / content。
157
- * @param {string} stdout
158
- * @returns {string} text 内容;无法解析时原样返回 stdout(降级)
159
- */
160
- function extractTextFromClaudeStdout(stdout) {
161
- if (!stdout) return '';
162
- var trimmed = stdout.trim();
163
- // 尝试整体 JSON 解析
164
- try {
165
- var parsed = JSON.parse(trimmed);
166
- if (parsed && typeof parsed === 'object') {
167
- // 优先 result(claude -p 的标准字段),回退 text / content
168
- if (typeof parsed.result === 'string') return parsed.result;
169
- if (typeof parsed.text === 'string') return parsed.text;
170
- if (typeof parsed.content === 'string') return parsed.content;
171
- // result 有时是对象(含 text)
172
- if (parsed.result && typeof parsed.result === 'object') {
173
- if (typeof parsed.result.text === 'string') return parsed.result.text;
174
- }
175
- }
176
- } catch (_e) {
177
- // 非 JSON:可能是纯文本输出(claude 未加 --output-format 时)
178
- }
179
- return trimmed;
180
- }
181
-
182
- /**
183
- * 从 Claude stdout(--output-format json)提取 usage / ttft_ms / duration_ms 等端点元数据。
184
- * 与 extractTextFromClaudeStdout 并列(不改其签名——已有调用方/测试断言返回 string),单独抽取
185
- * 顶层同层的 usage / ttft_ms / duration_ms。claude -p --output-format json 顶层结构:
186
- * { type:"result", result:"...", duration_ms, ttft_ms,
187
- * usage:{ input_tokens, cache_read_input_tokens, output_tokens } }
188
- * 缺失或解析失败时对应字段降级为 null(不抛)——限流/spawn_failed/timeout 路径不调用本函数(保持 null)。
189
- *
190
- * @param {string} stdout
191
- * @returns {{usage:{input:number,cacheRead:number,output:number}|null, ttftMs:number|null, durationMs:number|null}}
192
- */
193
- function extractMetaFromClaudeStdout(stdout) {
194
- var empty = { usage: null, ttftMs: null, durationMs: null };
195
- if (!stdout) return empty;
196
- var trimmed = stdout.trim();
197
- try {
198
- var parsed = JSON.parse(trimmed);
199
- if (!parsed || typeof parsed !== 'object') return empty;
200
- var usage = null;
201
- if (parsed.usage && typeof parsed.usage === 'object') {
202
- usage = {
203
- input: (typeof parsed.usage.input_tokens === 'number') ? parsed.usage.input_tokens : null,
204
- cacheRead: (typeof parsed.usage.cache_read_input_tokens === 'number')
205
- ? parsed.usage.cache_read_input_tokens : null,
206
- output: (typeof parsed.usage.output_tokens === 'number') ? parsed.usage.output_tokens : null,
207
- };
208
- }
209
- return {
210
- usage: usage,
211
- ttftMs: (typeof parsed.ttft_ms === 'number') ? parsed.ttft_ms : null,
212
- durationMs: (typeof parsed.duration_ms === 'number') ? parsed.duration_ms : null,
213
- };
214
- } catch (_e) {
215
- return empty;
216
- }
217
- }
218
-
219
- /**
220
- * 从 Report 文本提取 json:machine-readable fenced block 并 JSON.parse(skill-checklist 契约)。
221
- * 标记是 `json:machine-readable`(冒号,非连字符)—— 见 test-checklist-json-contract.js:68。
222
- * 解析失败返回 null(调用方降级为「无法解析」CheckResult)。
223
- * @param {string} text claude 输出文本
224
- * @returns {object|null} CheckResult
225
- */
226
- function parseCheckResult(text) {
227
- if (!text) return null;
228
- // 宽松:允许 ```json:machine-readable 与 ``` 之间任意内容(含换行)
229
- var m = text.match(/```json:machine-readable\s*\n([\s\S]*?)\n```/);
230
- if (!m) return null;
231
- try {
232
- var obj = JSON.parse(m[1]);
233
- if (obj && typeof obj === 'object') return obj;
234
- } catch (_e) {
235
- return null;
236
- }
237
- return null;
238
- }
239
-
240
- /**
241
- * 归一化为合法 CheckResult(补齐缺失字段,确保 reflection-evaluator 能消费)。
242
- * @param {object|null} chk 解析出的原始对象
243
- * @param {string} fallbackWpId 解析失败时的兜底 wpId
244
- * @returns {object} CheckResult(结构保证完整)
245
- */
246
- function normalizeCheckResult(chk, fallbackWpId) {
247
- if (!chk || typeof chk !== 'object') {
248
- return {
249
- wpId: fallbackWpId || 'unknown',
250
- passed: false,
251
- summary: { total: 0, passed: 0, failed: 0 },
252
- categories: [],
253
- failedItems: [{ id: 'parse-1', category: 'parse', text: 'checklist output', reason: 'no json:machine-readable block' }],
254
- };
255
- }
256
- var summary = chk.summary || {};
257
- var total = typeof summary.total === 'number' ? summary.total : 0;
258
- var passed = typeof summary.passed === 'number' ? summary.passed : 0;
259
- var failed = typeof summary.failed === 'number' ? summary.failed : (total - passed);
260
- return {
261
- wpId: chk.wpId || fallbackWpId || 'unknown',
262
- passed: chk.passed === true,
263
- summary: { total: total, passed: passed, failed: failed },
264
- categories: Array.isArray(chk.categories) ? chk.categories : [],
265
- failedItems: Array.isArray(chk.failedItems) ? chk.failedItems : [],
266
- };
267
- }
268
-
269
- /**
270
- * CheckResult 收尾链(Phase D 共享:claude/default/sdk 三 executor 统一走此函数):
271
- * 1. schema 校验(checkresult-validator):数值谎报(passed>total / passed+failed≠total /
272
- * 负数)→ 硬改判 failed + failedItems 注入 schema 失败项(B19 类问题的源头替代);
273
- * 结构瑕疵 → 仅附加 _schemaErrors(observability,不改判)
274
- * 2. normalizeCheckResult:结构归一
275
- * 3. objective verification(objective-verifier):items[].verify 声明的命令实跑,
276
- * 自报 passed 但客观不符 → 改判 fail + summary 重算(以客观为准)
277
- *
278
- * @param {object|null} raw parseCheckResult 的产物
279
- * @param {string} wpId fallback wpId
280
- * @param {object} [opts] { cwd } — verify 命令执行目录(runCwd,worktree 感知)
281
- * @returns {object} CheckResult
282
- */
283
- function finalizeCheckResult(raw, wpId, opts) {
284
- opts = opts || {};
285
- var validation = checkresultValidator.validateCheckResult(raw);
286
- if (validation.hard && raw && typeof raw === 'object') {
287
- raw.passed = false;
288
- raw.failedItems = (Array.isArray(raw.failedItems) ? raw.failedItems : []).concat([{
289
- id: 'schema-1',
290
- category: 'schema',
291
- text: 'checklist schema hard violation',
292
- reason: validation.errors.join('; ').slice(0, 500),
293
- }]);
294
- // summary 已证实谎报 → 不可信,重写为 failedItems 驱动(total=条目数、全 fail),
295
- // 保证下游 evaluator 的 failedCount(summary.failed 或 failedItems.length 两路口径)一致
296
- raw.summary = {
297
- total: raw.failedItems.length,
298
- passed: 0,
299
- failed: raw.failedItems.length,
300
- };
301
- }
302
- var chk = normalizeCheckResult(raw, wpId);
303
- if (validation.errors && validation.errors.length) {
304
- chk._schemaErrors = validation.errors.slice(0, 10);
305
- }
306
- if (raw && typeof raw === 'object' && Array.isArray(raw.categories)) {
307
- objectiveVerifier.applyObjectiveVerification(chk, { cwd: opts.cwd });
308
- }
309
- return chk;
310
- }
311
-
312
- /**
313
- * 生成「无法解析 / 超时 / 限流」的失败 CheckResult。
314
- * @param {string} wpId
315
- * @param {string} reason
316
- * @returns {object}
317
- */
318
- function buildFailedChecklist(wpId, reason) {
319
- return {
320
- wpId: wpId || 'unknown',
321
- passed: false,
322
- summary: { total: 1, passed: 0, failed: 1 },
323
- categories: [],
324
- failedItems: [{ id: 'exec-1', category: 'exec', text: 'executor failure', reason: reason }],
325
- };
326
- }
327
-
328
- /**
329
- * 进展检测:基于执行前后工作树脏度,标注 CheckResult 的 noProgress 信号(WP-191-2-impl)。
330
- *
331
- * 语义(对齐 Ralph 熔断判据,修复"恒判无进展"缺陷):
332
- * - passed=true → noProgress=false(达成即有进展,不进入发散累计)
333
- * - passed=false + 工作树脏(执行后有改动) → noProgress=false(本轮产出了代码,可能只是测试还没过)
334
- * - passed=false + 工作树干净 → noProgress=true(无代码进展,累计入发散)
335
- * - 工作树无法判定(非 git 仓库降级) → noProgress=false(不误判、不阻断)
336
- *
337
- * 公开字段:chk.noProgress(boolean,供 reflection-evaluator 累计 streak)。
338
- * 兼容:保留 chk._noProgress(旧字段,仅 true 时写入),向后兼容旧消费者/测试。
339
- *
340
- * 本函数提取自原 run() 内联逻辑,供 executor-glm 复用(消除两份重复代码,零漂移)。
341
- *
342
- * @param {object} chk CheckResult(会被原地补充 noProgress / _noProgress / 可能追加 progress failedItem)
343
- * @param {boolean|null} dirtyBefore 执行前工作树脏度(readWorktreeDirty 返回值)
344
- * @param {boolean|null} dirtyAfter 执行后工作树脏度
345
- * @returns {object} 同 chk(链式)
346
- */
347
- function applyProgressDetection(chk, dirtyBefore, dirtyAfter) {
348
- if (!chk) return chk;
349
- // passed=true:达成即有进展
350
- if (chk.passed === true) {
351
- chk.noProgress = false;
352
- return chk;
353
- }
354
- // 工作树脏度任一无法判定(非 git 仓库降级)→ 不误判无进展
355
- if (dirtyBefore === null || dirtyAfter === null) {
356
- chk.noProgress = false;
357
- return chk;
358
- }
359
- // 工作树由干净变脏,或保持脏 → 本轮产出了代码改动 → 有进展
360
- var producedChange = dirtyAfter || (!dirtyBefore && dirtyAfter);
361
- // 等价简化:dirtyAfter 为 true 即视为有进展(无论 before)
362
- if (dirtyAfter) {
363
- chk.noProgress = false;
364
- return chk;
365
- }
366
- // passed=false 且工作树干净(before/after 均不脏)→ 无代码进展
367
- chk.noProgress = true;
368
- chk._noProgress = true; // 向后兼容旧字段
369
- if (chk.failedItems && chk.failedItems.length) {
370
- chk.failedItems.push({
371
- id: 'progress-1', category: 'progress', text: 'no worktree change',
372
- reason: '工作树无改动且 passed=false(无代码进展,对齐 Ralph 熔断判据)',
373
- });
374
- }
375
- // 保留 producedChange 变量语义可读性(lint 友好):未直接使用仅作判定文档化
376
- void producedChange;
377
- return chk;
378
- }
379
-
380
- /**
381
- * 读取 WP 文档(docs/wp/{wpId}.md),注入 prompt。
382
- * 不存在时返回提示文本(不阻断;调用方决定是否提示用户先 task-creator)。
383
- * @param {string} wpId
384
- * @param {string} projectRoot
385
- * @returns {{ content:string|null, path:string }}
386
- */
387
- function readWpDoc(wpId, projectRoot) {
388
- // S4:校验 wpId 字符集,防止 path.join 拼出 docs/wp/ 之外的路径
389
- // (wpId 来自 plan.md 解析,做防御性消毒;非法时当作无文档处理)
390
- if (!wpId || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(wpId)) {
391
- return { content: null, path: path.join(projectRoot, 'docs', 'wp', '<invalid-id>.md') };
392
- }
393
- var docPath = path.join(projectRoot, 'docs', 'wp', wpId + '.md');
394
- if (!fs.existsSync(docPath)) {
395
- return { content: null, path: docPath };
396
- }
397
- try {
398
- return { content: fs.readFileSync(docPath, 'utf8'), path: docPath };
399
- } catch (_e) {
400
- return { content: null, path: docPath };
401
- }
402
- }
403
-
404
- /**
405
- * WP-S4 精读 retry:按失败项关键词裁剪 WP 文档,只注入相关段落。
406
- * 北极星②省 token:retry 是 token 大户(每轮全量重灌 55K input 级);
407
- * refine 反馈已有失败项明细——文档按段落打分只留相关块 + 头部(目标/验收)。
408
- *
409
- * @param {string} docContent WP 文档全文
410
- * @param {Array} failingDrivers [{ category, item, reason }]
411
- * @returns {{ pruned: string, mode: 'full'|'focused', keptBlocks: number, totalBlocks: number }}
412
- * mode=full 表示打分全零(关键词不命中任何段落)→ 全量注入安全网
413
- */
414
- function pruneDocForRetry(docContent, failingDrivers) {
415
- if (!docContent || !Array.isArray(failingDrivers) || failingDrivers.length === 0) {
416
- return { pruned: docContent || '', mode: 'full', keptBlocks: 0, totalBlocks: 0 };
417
- }
418
- var lines = String(docContent).split(/\r?\n/);
419
- // 按 '## ' 标题切块(块 0 = 文档头,总是保留——目标/验收标准所在)
420
- var blocks = [];
421
- var cur = null;
422
- for (var j = 0; j < lines.length; j++) {
423
- if (/^##\s+/.test(lines[j])) {
424
- if (cur) blocks.push(cur);
425
- cur = { title: lines[j], lines: [lines[j]] };
426
- } else {
427
- if (!cur) cur = { title: '__head__', lines: [] };
428
- cur.lines.push(lines[j]);
429
- }
430
- }
431
- if (cur) blocks.push(cur);
432
-
433
- var queryTokens = [];
434
- for (var f = 0; f < failingDrivers.length; f++) {
435
- var fd = failingDrivers[f];
436
- queryTokens = queryTokens.concat(textTokenize.tokenize(
437
- (fd.item || '') + ' ' + (fd.reason || '') + ' ' + (fd.category || '')));
438
- }
439
- var scored = [];
440
- for (var b = 1; b < blocks.length; b++) { // 块 0(文档头)不参与打分,总保留
441
- var blk = blocks[b];
442
- var blkTokens = textTokenize.tokenize(blk.lines.join('\n'));
443
- var score = 0;
444
- for (var q = 0; q < queryTokens.length; q++) {
445
- if (blkTokens.indexOf(queryTokens[q]) !== -1) score += 1;
446
- }
447
- scored.push({ index: b, score: score });
448
- }
449
- var hit = scored.filter(function (s) { return s.score > 0; });
450
- if (hit.length === 0) {
451
- return { pruned: docContent, mode: 'full', keptBlocks: blocks.length, totalBlocks: blocks.length };
452
- }
453
- // 保留:文档头 + 第一个 ## 段(目标/验收标准所在,语义上属于头)+ 命中块
454
- var kept = [blocks[0]];
455
- if (blocks.length > 1) kept.push(blocks[1]);
456
- for (var h = 0; h < hit.length; h++) kept.push(blocks[hit[h].index]);
457
- return {
458
- pruned: kept.map(function (k) { return k.lines.join('\n'); }).join('\n\n'),
459
- mode: 'focused',
460
- keptBlocks: kept.length,
461
- totalBlocks: blocks.length,
462
- };
463
- }
464
-
465
- /**
466
- * 构造 claude prompt(WP-187-impl;WP-S2 cache 友好重排)。
467
- *
468
- * 段落顺序按「稳定度递减」排列,吃满 provider prompt context cache
469
- * (GLM/DeepSeek/Anthropic 均按最长公共前缀命中——同一 loop 内固定不变
470
- * 的内容必须放最前,每轮变化的放最后):
471
- * [稳定] 身份 + 行为规则(完成要求)+ 窗口预算 —— 跨轮跨 WP 不变
472
- * [半稳定] WP 文档全文 —— 同一 WP 的 dispatch/retry 不变
473
- * [动态] 任务标识 / mode / 失败项反馈 / 执行锚点 —— 每轮变化
474
- * 注:禁止在此 prompt 加入时间戳/轮次号等每轮漂移字段(会打断 cache 前缀)。
475
- *
476
- * @param {object} pendingAction { wpId, mode, strategy, failingDrivers }
477
- * @param {string} projectRoot
478
- * @returns {string}
479
- */
480
- function buildPrompt(pendingAction, projectRoot, contextWindow) {
481
- pendingAction = pendingAction || {};
482
- var wpId = pendingAction.wpId || 'unknown';
483
- var mode = pendingAction.mode || 'dispatch';
484
- var strategy = pendingAction.strategy || 'full_restart';
485
-
486
- var lines = [];
487
- // ── [稳定前缀] 身份 + 行为规则(跨轮不变,cache 命中区)──
488
- lines.push('你是 doukui agentic loop 的执行单元(executor)。当前 loop 通过 Node driver 调度你完成一个工作包。');
489
- lines.push('');
490
- lines.push('## 完成要求');
491
- lines.push('1. 按下方 WP 文档实现/修改代码');
492
- lines.push('2. 跑相关单测验证(npm test 或针对性测试)');
493
- lines.push('3. 完成后**必须**在最终回复中产出 skill-checklist 的机器可读判定块,');
494
- lines.push(' 格式为 ```json:machine-readable 后跟 JSON,字段:');
495
- lines.push(' wpId / passed / summary{total,passed,failed} / categories[] / failedItems[]');
496
- lines.push(' (详见 skill-checklist skill)。未产出该块将被判定为执行失败。');
497
- lines.push('');
498
- // 上下文窗口预算(Phase B-2 分档:provider profile 显式声明 > 内置档位表 > 200K 保守默认)。
499
- // 供会话内分块读取策略(harness-config context_window 段)用对预算;缺省不注入(零回归)。
500
- if (typeof contextWindow === 'number' && contextWindow > 0) {
501
- lines.push('## 上下文窗口预算');
502
- lines.push(contextWindow + ' tokens(按 provider 分档自动解析;大文件按此预算分块读取)。');
503
- lines.push('');
504
- }
505
-
506
- // ── [半稳定] WP 文档(同一 WP 的多轮之间不变;retry 精读裁剪,WP-S4)──
507
- var doc = readWpDoc(wpId, projectRoot);
508
- if (doc.content) {
509
- var docBody = doc.content;
510
- var docMode = 'full';
511
- if (mode === 'retry' && pendingAction.failingDrivers && pendingAction.failingDrivers.length) {
512
- var pruned = pruneDocForRetry(doc.content, pendingAction.failingDrivers);
513
- if (pruned.mode === 'focused') {
514
- docBody = pruned.pruned;
515
- docMode = 'focused (' + pruned.keptBlocks + '/' + pruned.totalBlocks + ' 段,按失败项关联裁剪)';
516
- }
517
- }
518
- lines.push('## WP 文档(' + doc.path + (docMode !== 'full' ? ' · 精读模式' : '') + ')');
519
- lines.push('请严格依据下方文档的目标、关键文件、验收标准执行:');
520
- if (docMode !== 'full') {
521
- lines.push('(WP-S4 精读:仅注入与失败项相关段落;完整文档可 Read ' + doc.path + ')');
522
- }
523
- lines.push('');
524
- lines.push('---');
525
- lines.push(docBody);
526
- lines.push('---');
527
- lines.push('');
528
- } else {
529
- lines.push('## WP 文档');
530
- lines.push('⚠️ 未找到 ' + doc.path + '。请先用 task-creator 创建 WP 文档,或依据 loop 目标自行完成。');
531
- lines.push('');
532
- }
533
-
534
- // ── [动态尾巴] 任务标识 / mode / 失败项 / 执行锚点(每轮变化)──
535
- lines.push('## 当前任务');
536
- lines.push('- WP ID: ' + wpId);
537
- lines.push('- 模式: ' + mode + '(dispatch=新执行 / retry=针对失败项重做 / resplit=拆分后执行)');
538
- lines.push('- 策略: ' + strategy);
539
- lines.push('');
540
- if (mode === 'retry' && pendingAction.failingDrivers && pendingAction.failingDrivers.length) {
541
- lines.push('## 上轮失败项(refine 反馈,请针对性修复)');
542
- for (var i = 0; i < pendingAction.failingDrivers.length; i++) {
543
- var fd = pendingAction.failingDrivers[i];
544
- lines.push('- [' + (fd.category || '?') + '] ' + (fd.item || '') + ':' + (fd.reason || ''));
545
- }
546
- lines.push('');
547
- }
548
- lines.push('## 现在执行');
549
- lines.push('立即开始执行 WP-' + wpId.replace(/^WP-?/i, '') + '(' + mode + ')。完成后按「完成要求」产出机器可读判定块。');
550
- return lines.join('\n');
551
- }
552
-
553
- /**
554
- * 构造 claude CLI 参数(WP-185-impl)。
555
- *
556
- * SECURITY (S1):prompt **不**经 argv 传入——大 prompt 会触发
557
- * Windows 命令行 ARG_MAX(≈32767)截断 / spawn ENAMETOOLONG,
558
- * 且在 POSIX 上经 /proc/<pid>/cmdline 泄漏给同机其他用户。
559
- * prompt 改由 run() 写入子进程 stdin(claude -p 的标准 stdin 模式)。
560
- *
561
- * settingsPath(可选):透传 claude CLI 原生 `--settings <file-or-json>` flag,
562
- * 加载额外的 settings JSON(与 claude 默认发现机制叠加)。用途:动态切换
563
- * provider/套餐档位(如指定 ~/.claude/settings-glm-5.2[1m]max.json)。
564
- * SECURITY:settingsPath 是文件**路径**,非 prompt/密钥本身——密钥在文件内由
565
- * claude 自行读取,路径进 argv 安全(与 --allowedTools 等路径性质一致)。
566
- *
567
- * @param {string[]} allowedTools
568
- * @param {string} [settingsPath] 可选 claude settings 文件路径;非空时追加 --settings
569
- * @returns {string[]}
570
- */
571
- function buildClaudeArgs(allowedTools, settingsPath) {
572
- var args = [
573
- '-p', // --print:非交互,单次执行后退出
574
- '--output-format', 'json',
575
- '--allowedTools', allowedTools.join(','),
576
- ];
577
- if (settingsPath) {
578
- args.push('--settings', settingsPath);
579
- }
580
- return args;
581
- }
582
-
583
- // ---------------------------------------------------------------------------
584
- // 共享 internals 导出(executor-default / executor-sdk 复用;不再导出 createExecutor)
585
- // ---------------------------------------------------------------------------
586
-
587
- module.exports = {
588
- // 暴露内部工具便于单元测试
589
- _buildPrompt: buildPrompt,
590
- _buildClaudeArgs: buildClaudeArgs,
591
- _extractTextFromClaudeStdout: extractTextFromClaudeStdout,
592
- _extractMetaFromClaudeStdout: extractMetaFromClaudeStdout,
593
- _parseCheckResult: parseCheckResult,
594
- _normalizeCheckResult: normalizeCheckResult,
595
- _finalizeCheckResult: finalizeCheckResult,
596
- _buildFailedChecklist: buildFailedChecklist,
597
- _readGitHead: readGitHead,
598
- _readWorktreeDirty: readWorktreeDirty,
599
- _applyProgressDetection: applyProgressDetection,
600
- _pruneDocForRetry: pruneDocForRetry,
601
- _readWpDoc: readWpDoc,
602
- _resolveProjectRoot: resolveProjectRoot,
603
- _DEFAULTS: DEFAULTS,
604
- };