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.
- package/LICENSE +21 -0
- package/README.en.md +42 -0
- package/README.md +147 -2
- package/bin/commands/build.js +178 -0
- package/bin/commands/config.js +88 -0
- package/bin/commands/help.js +83 -0
- package/bin/commands/init.js +194 -0
- package/bin/commands/install.js +202 -0
- package/bin/commands/interactive.js +352 -0
- package/bin/commands/list.js +108 -0
- package/bin/commands/loop-server.js +357 -0
- package/bin/commands/loop.js +1443 -0
- package/bin/commands/migrate.js +120 -0
- package/bin/commands/setup-global.js +81 -0
- package/bin/commands/status.js +140 -0
- package/bin/commands/team-cleanup.js +190 -0
- package/bin/commands/validate-config.js +35 -0
- package/bin/commands/validate.js +21 -0
- package/bin/commands/version.js +22 -0
- package/bin/context.js +143 -0
- package/bin/doukui.js +216 -0
- package/package.json +47 -4
- package/plugins/contracts/capabilities.js +268 -0
- package/plugins/contracts/checkresult-schema.json +75 -0
- package/plugins/contracts/config-schema.json +179 -0
- package/plugins/contracts/plugin-interface.js +262 -0
- package/plugins/contracts/plugin-schema.json +104 -0
- package/plugins/core/hook-session-start/index.js +281 -0
- package/plugins/core/hook-session-start/plugin.json +7 -0
- package/plugins/core/hook-skill-gate/index.js +661 -0
- package/plugins/core/hook-skill-gate/plugin.json +12 -0
- package/plugins/core/provider-loop-engine/index.js +1411 -0
- package/plugins/core/provider-loop-engine/plugin.json +15 -0
- package/plugins/core/provider-memory-store/index.js +510 -0
- package/plugins/core/provider-memory-store/plugin.json +9 -0
- package/plugins/core/provider-role-registry/index.js +376 -0
- package/plugins/core/provider-role-registry/plugin.json +9 -0
- package/plugins/core/provider-state-store/index.js +244 -0
- package/plugins/core/provider-state-store/plugin.json +9 -0
- package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
- package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
- package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
- package/plugins/core/provider-watchdog/index.js +151 -0
- package/plugins/core/provider-watchdog/plugin.json +13 -0
- package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
- package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
- package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
- package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
- package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
- package/plugins/core/skill-agentic-loop/plugin.json +20 -0
- package/plugins/core/skill-agentic-loop/skill.md +588 -0
- package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
- package/plugins/core/skill-batch-task-creator/skill.md +620 -0
- package/plugins/core/skill-checklist/plugin.json +10 -0
- package/plugins/core/skill-checklist/skill.md +171 -0
- package/plugins/core/skill-completion-report/plugin.json +10 -0
- package/plugins/core/skill-completion-report/skill.md +331 -0
- package/plugins/core/skill-doukui-plan/plugin.json +15 -0
- package/plugins/core/skill-doukui-plan/skill.md +233 -0
- package/plugins/core/skill-doukui-sync/plugin.json +10 -0
- package/plugins/core/skill-doukui-sync/skill.md +76 -0
- package/plugins/core/skill-experience-logger/plugin.json +10 -0
- package/plugins/core/skill-experience-logger/skill.md +235 -0
- package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
- package/plugins/core/skill-human-checkpoint/skill.md +194 -0
- package/plugins/core/skill-progress-tracker/plugin.json +10 -0
- package/plugins/core/skill-progress-tracker/skill.md +228 -0
- package/plugins/core/skill-role-manager/plugin.json +10 -0
- package/plugins/core/skill-role-manager/skill.md +252 -0
- package/plugins/core/skill-split-work-package/plugin.json +15 -0
- package/plugins/core/skill-split-work-package/skill.md +441 -0
- package/plugins/core/skill-task-archive/plugin.json +10 -0
- package/plugins/core/skill-task-archive/skill.md +116 -0
- package/plugins/core/skill-task-creator/plugin.json +15 -0
- package/plugins/core/skill-task-creator/skill.md +886 -0
- package/plugins/core/skill-team-cleanup/plugin.json +10 -0
- package/plugins/core/skill-team-cleanup/skill.md +266 -0
- package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
- package/plugins/core/skill-watchdog-manager/skill.md +143 -0
- package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
- package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
- package/plugins/core/validator-doc-sync/index.js +248 -0
- package/plugins/core/validator-doc-sync/plugin.json +12 -0
- package/plugins/core/validator-work-package/index.js +300 -0
- package/plugins/core/validator-work-package/plugin.json +12 -0
- package/plugins/plugin-registry.json +186 -0
- package/plugins/runtime/agent-def-generator.js +150 -0
- package/plugins/runtime/audit-logger.js +311 -0
- package/plugins/runtime/build-cli.js +89 -0
- package/plugins/runtime/checkresult-validator.js +131 -0
- package/plugins/runtime/claude-md-injector.js +159 -0
- package/plugins/runtime/cleanup-utils.js +293 -0
- package/plugins/runtime/config-manager.js +317 -0
- package/plugins/runtime/config-validator.js +320 -0
- package/plugins/runtime/context-window.js +81 -0
- package/plugins/runtime/event-bus.js +207 -0
- package/plugins/runtime/executor-claude.js +828 -0
- package/plugins/runtime/executor-default.js +448 -0
- package/plugins/runtime/executor-local.js +178 -0
- package/plugins/runtime/executor-sdk.js +415 -0
- package/plugins/runtime/harness-build.js +1037 -0
- package/plugins/runtime/hook-dispatcher.js +315 -0
- package/plugins/runtime/logger.js +192 -0
- package/plugins/runtime/loop-actuator.js +292 -0
- package/plugins/runtime/loop-coordinator.js +347 -0
- package/plugins/runtime/loop-defaults.js +29 -0
- package/plugins/runtime/loop-dispatch-batch.js +247 -0
- package/plugins/runtime/loop-executor.js +120 -0
- package/plugins/runtime/loop-report.js +327 -0
- package/plugins/runtime/loop-server-core.js +750 -0
- package/plugins/runtime/loop-snapshot.js +581 -0
- package/plugins/runtime/loop-trace.js +242 -0
- package/plugins/runtime/loop-worktree.js +404 -0
- package/plugins/runtime/manifest-resolver.js +457 -0
- package/plugins/runtime/multi-window-coordinator.js +560 -0
- package/plugins/runtime/objective-verifier.js +136 -0
- package/plugins/runtime/plan-lint.js +100 -0
- package/plugins/runtime/plan-reader.js +763 -0
- package/plugins/runtime/plugin-loader.js +798 -0
- package/plugins/runtime/plugin-trust.js +182 -0
- package/plugins/runtime/plugin-validator.js +491 -0
- package/plugins/runtime/provider-failover.js +114 -0
- package/plugins/runtime/provider-resolver.js +342 -0
- package/plugins/runtime/reflection-evaluator.js +545 -0
- package/plugins/runtime/resolve-plugin-path.js +297 -0
- package/plugins/runtime/safe-path.js +119 -0
- package/plugins/runtime/sandbox-context.js +235 -0
- package/plugins/runtime/sandbox-manager.js +609 -0
- package/plugins/runtime/sandbox-worker.js +215 -0
- package/plugins/runtime/self-rescue-ladder.js +38 -0
- package/plugins/runtime/settings-merger.js +172 -0
- package/plugins/runtime/state-store.js +527 -0
- package/plugins/runtime/team-cleanup.js +497 -0
- package/plugins/runtime/text-tokenize.js +25 -0
- package/plugins/runtime/validator-pipeline.js +475 -0
- package/plugins/runtime/yaml-parser.js +692 -0
- package/templates/harness-config.yaml +394 -0
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Executor (claude) — Agentic Loop Act 层 provider 执行单元的 Claude Code 实现(WP-185 / WP-187)
|
|
3
|
+
*
|
|
4
|
+
* @module executor-claude
|
|
5
|
+
*
|
|
6
|
+
* 职责:实现 driver 期望的 `run(pendingAction) -> CheckResult` 契约的真实实现——
|
|
7
|
+
* spawn Claude Code CLI(`claude -p --output-format json --allowedTools ...`)逐轮写代码,
|
|
8
|
+
* 从其 stdout JSON 提取 text,再从 text 里的 `json:machine-readable` fenced block
|
|
9
|
+
* 解析出 CheckResult(skill-checklist 机器可读契约,design.md §5.4.2)。
|
|
10
|
+
*
|
|
11
|
+
* 设计约束(docs/plan/agentic-loop-node-driver.md 硬约束 #3):
|
|
12
|
+
* - provider 解耦点是 `executor.run()`:driver 不直接 spawn claude,
|
|
13
|
+
* 本模块与 executor-local.js 实现同一份接口契约,可互换(--executor=local|claude)。
|
|
14
|
+
* - 新增 executor-glm.js 接智谱 Coding Plan 时,driver 与 engine 零改动。
|
|
15
|
+
*
|
|
16
|
+
* 接口契约(与 executor-local.js 一致,createExecutor 返回 { name, run, config }):
|
|
17
|
+
* run(pendingAction: {wpId, mode, strategy, failingDrivers?, ...}) -> Promise<CheckResult>
|
|
18
|
+
*
|
|
19
|
+
* CheckResult 契约(reflection-evaluator.proximityFromChecklist /
|
|
20
|
+
* failingDriversFromChecklist 消费,见 test-checklist-json-contract.js):
|
|
21
|
+
* {
|
|
22
|
+
* wpId: string,
|
|
23
|
+
* passed: boolean,
|
|
24
|
+
* summary: { total:number, passed:number, failed:number },
|
|
25
|
+
* categories: [{ name, passed, items:[{id,text,passed,reason?}] }],
|
|
26
|
+
* failedItems: [{ category, id, reason }]
|
|
27
|
+
* }
|
|
28
|
+
*
|
|
29
|
+
* 限流与超时(WP-185-impl,对齐 Ralph 模式):
|
|
30
|
+
* - 单实例默认 100/h,超限返回 passed:false + failedItems:[{reason:'rate_limited'}]
|
|
31
|
+
* - 单次默认 15min 超时(spawn timeout 选项 + 手动 kill),超时返回 passed:false
|
|
32
|
+
*
|
|
33
|
+
* 进展检测(WP-187 / WP-191-2-impl,对齐 Ralph 熔断判据):
|
|
34
|
+
* - 判据改为**工作树脏度**(git status --porcelain):driver 不 git commit,claude
|
|
35
|
+
* 子进程只改工作树,故 HEAD 恒不变——原 `git rev-parse HEAD` 检测恒判无进展(缺陷)。
|
|
36
|
+
* - 执行前后读工作树脏度(porcelain 输出非空=有改动);passed=false 且工作树干净 →
|
|
37
|
+
* noProgress=true(无进展)。该信号经 reflection-evaluator 累计 noProgressStreak,
|
|
38
|
+
* 接入 engine _decide 发散判定(连续 N 轮无代码进展 → diverged)。
|
|
39
|
+
* - git 不可用(非 git 仓库 / 无 git)→ 降级 noProgress=false(不阻断,不误判)。
|
|
40
|
+
*
|
|
41
|
+
* 可测性(遵循 codebase DI-over-mocking 哲学,见 executor-local / loop-actuator):
|
|
42
|
+
* - createExecutor({ spawnFn }) 注入 spawn 实现,测试传 fake spawn,不真调 claude。
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
'use strict';
|
|
46
|
+
|
|
47
|
+
var fs = require('fs');
|
|
48
|
+
var path = require('path');
|
|
49
|
+
var { spawn } = require('child_process');
|
|
50
|
+
|
|
51
|
+
// Phase D 校验层:schema 校验(谎报硬改判)+ 客观交叉验证(verify.command 实跑)
|
|
52
|
+
var checkresultValidator = require('./checkresult-validator');
|
|
53
|
+
var objectiveVerifier = require('./objective-verifier');
|
|
54
|
+
// WP-S4:精读 retry 的共享分词(与 memory recall 同口径)
|
|
55
|
+
var textTokenize = require('./text-tokenize');
|
|
56
|
+
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
// 默认配置
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
var DEFAULTS = {
|
|
62
|
+
binary: 'claude', // Claude Code CLI 可执行名
|
|
63
|
+
timeoutMs: 15 * 60 * 1000, // 单次执行超时 15min(对齐 executor-local)
|
|
64
|
+
rateLimitPerHour: 100, // 单实例每小时调用上限
|
|
65
|
+
wpDocsDir: 'docs/wp', // WP 文档目录(相对项目根;prompt 注入用)
|
|
66
|
+
// model 占位(WP-191-1-impl-d,provider 零分支统一通道):
|
|
67
|
+
// claude CLI 不显式 --model(走账号默认模型),这里仅暴露 config.model 字段供
|
|
68
|
+
// driver 写 sidecar 时统一取值(executor.config.model),不引入 provider 分支。
|
|
69
|
+
// coordinator 额度池仅对 glm 走高峰系数换算,claude 的 model 值不参与计量。
|
|
70
|
+
model: 'claude-default',
|
|
71
|
+
allowedTools: [
|
|
72
|
+
// 白名单:允许 Claude 读写代码与跑测试,禁止改动 .claude/ 内部状态(防自篡改)
|
|
73
|
+
'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash',
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// 工具函数
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* ISO 时间戳。
|
|
83
|
+
* @returns {string}
|
|
84
|
+
*/
|
|
85
|
+
function nowIso() {
|
|
86
|
+
return new Date().toISOString();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 解析项目根目录(仿 loop-snapshot / loop-actuator:向上找 task.md / .claude)。
|
|
91
|
+
* @returns {string}
|
|
92
|
+
*/
|
|
93
|
+
function resolveProjectRoot() {
|
|
94
|
+
var dir = process.cwd();
|
|
95
|
+
for (var i = 0; i < 10; i++) {
|
|
96
|
+
if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
|
|
97
|
+
if (fs.existsSync(path.join(dir, '.claude'))) return dir;
|
|
98
|
+
var parent = path.dirname(dir);
|
|
99
|
+
if (parent === dir) break;
|
|
100
|
+
dir = parent;
|
|
101
|
+
}
|
|
102
|
+
return process.cwd();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 同步读 git HEAD(child_process.execFileSync)。失败返回空串。
|
|
107
|
+
* 保留以兼容可能的外部引用与旧测试;进展检测已改用 readWorktreeDirty(见下)。
|
|
108
|
+
* @param {string} projectRoot
|
|
109
|
+
* @returns {string}
|
|
110
|
+
*/
|
|
111
|
+
function readGitHead(projectRoot) {
|
|
112
|
+
try {
|
|
113
|
+
var { execFileSync } = require('child_process');
|
|
114
|
+
var out = execFileSync('git', ['rev-parse', 'HEAD'], {
|
|
115
|
+
cwd: projectRoot, encoding: 'utf8', timeout: 2000,
|
|
116
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
117
|
+
});
|
|
118
|
+
return String(out).trim();
|
|
119
|
+
} catch (_e) {
|
|
120
|
+
return '';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 同步读工作树脏度(git status --porcelain)。
|
|
126
|
+
* WP-191-2-impl 进展检测核心:driver 不 git commit,claude 子进程只改工作树,
|
|
127
|
+
* 故以"工作树是否有改动"作为"本轮是否产生代码进展"的判据(替代恒判无进展的 HEAD 比对)。
|
|
128
|
+
*
|
|
129
|
+
* @param {string} projectRoot
|
|
130
|
+
* @param {Function} [statusFn] 注入 git status 执行函数(测试用);默认 execFileSync。
|
|
131
|
+
* 签名 (args, opts) => string;返回 porcelain 输出。
|
|
132
|
+
* @returns {boolean|null} true=工作树脏(有进展) / false=干净(无进展) / null=无法判定(非 git 仓库降级)
|
|
133
|
+
*/
|
|
134
|
+
function readWorktreeDirty(projectRoot, statusFn) {
|
|
135
|
+
try {
|
|
136
|
+
var out;
|
|
137
|
+
if (typeof statusFn === 'function') {
|
|
138
|
+
out = statusFn(['status', '--porcelain'], { cwd: projectRoot });
|
|
139
|
+
} else {
|
|
140
|
+
var { execFileSync } = require('child_process');
|
|
141
|
+
out = execFileSync('git', ['status', '--porcelain'], {
|
|
142
|
+
cwd: projectRoot, encoding: 'utf8', timeout: 2000,
|
|
143
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
// porcelain 输出非空(含空白行外的内容)= 工作树有改动
|
|
147
|
+
return String(out).trim().length > 0;
|
|
148
|
+
} catch (_e) {
|
|
149
|
+
// 非 git 仓库 / 无 git / 超时 → 无法判定(降级,不误判无进展)
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 从 Claude stdout(--output-format json)提取 text 字段。
|
|
156
|
+
* claude -p --output-format json 输出形如 { "type":"result", "result":"...", ... } 或
|
|
157
|
+
* { "text":"..." }。兼容多种字段名:result / text / content。
|
|
158
|
+
* @param {string} stdout
|
|
159
|
+
* @returns {string} text 内容;无法解析时原样返回 stdout(降级)
|
|
160
|
+
*/
|
|
161
|
+
function extractTextFromClaudeStdout(stdout) {
|
|
162
|
+
if (!stdout) return '';
|
|
163
|
+
var trimmed = stdout.trim();
|
|
164
|
+
// 尝试整体 JSON 解析
|
|
165
|
+
try {
|
|
166
|
+
var parsed = JSON.parse(trimmed);
|
|
167
|
+
if (parsed && typeof parsed === 'object') {
|
|
168
|
+
// 优先 result(claude -p 的标准字段),回退 text / content
|
|
169
|
+
if (typeof parsed.result === 'string') return parsed.result;
|
|
170
|
+
if (typeof parsed.text === 'string') return parsed.text;
|
|
171
|
+
if (typeof parsed.content === 'string') return parsed.content;
|
|
172
|
+
// result 有时是对象(含 text)
|
|
173
|
+
if (parsed.result && typeof parsed.result === 'object') {
|
|
174
|
+
if (typeof parsed.result.text === 'string') return parsed.result.text;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
} catch (_e) {
|
|
178
|
+
// 非 JSON:可能是纯文本输出(claude 未加 --output-format 时)
|
|
179
|
+
}
|
|
180
|
+
return trimmed;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 从 Claude stdout(--output-format json)提取 usage / ttft_ms / duration_ms 等端点元数据。
|
|
185
|
+
* 与 extractTextFromClaudeStdout 并列(不改其签名——已有调用方/测试断言返回 string),单独抽取
|
|
186
|
+
* 顶层同层的 usage / ttft_ms / duration_ms。claude -p --output-format json 顶层结构:
|
|
187
|
+
* { type:"result", result:"...", duration_ms, ttft_ms,
|
|
188
|
+
* usage:{ input_tokens, cache_read_input_tokens, output_tokens } }
|
|
189
|
+
* 缺失或解析失败时对应字段降级为 null(不抛)——限流/spawn_failed/timeout 路径不调用本函数(保持 null)。
|
|
190
|
+
*
|
|
191
|
+
* @param {string} stdout
|
|
192
|
+
* @returns {{usage:{input:number,cacheRead:number,output:number}|null, ttftMs:number|null, durationMs:number|null}}
|
|
193
|
+
*/
|
|
194
|
+
function extractMetaFromClaudeStdout(stdout) {
|
|
195
|
+
var empty = { usage: null, ttftMs: null, durationMs: null };
|
|
196
|
+
if (!stdout) return empty;
|
|
197
|
+
var trimmed = stdout.trim();
|
|
198
|
+
try {
|
|
199
|
+
var parsed = JSON.parse(trimmed);
|
|
200
|
+
if (!parsed || typeof parsed !== 'object') return empty;
|
|
201
|
+
var usage = null;
|
|
202
|
+
if (parsed.usage && typeof parsed.usage === 'object') {
|
|
203
|
+
usage = {
|
|
204
|
+
input: (typeof parsed.usage.input_tokens === 'number') ? parsed.usage.input_tokens : null,
|
|
205
|
+
cacheRead: (typeof parsed.usage.cache_read_input_tokens === 'number')
|
|
206
|
+
? parsed.usage.cache_read_input_tokens : null,
|
|
207
|
+
output: (typeof parsed.usage.output_tokens === 'number') ? parsed.usage.output_tokens : null,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
usage: usage,
|
|
212
|
+
ttftMs: (typeof parsed.ttft_ms === 'number') ? parsed.ttft_ms : null,
|
|
213
|
+
durationMs: (typeof parsed.duration_ms === 'number') ? parsed.duration_ms : null,
|
|
214
|
+
};
|
|
215
|
+
} catch (_e) {
|
|
216
|
+
return empty;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 从 Report 文本提取 json:machine-readable fenced block 并 JSON.parse(skill-checklist 契约)。
|
|
222
|
+
* 标记是 `json:machine-readable`(冒号,非连字符)—— 见 test-checklist-json-contract.js:68。
|
|
223
|
+
* 解析失败返回 null(调用方降级为「无法解析」CheckResult)。
|
|
224
|
+
* @param {string} text claude 输出文本
|
|
225
|
+
* @returns {object|null} CheckResult
|
|
226
|
+
*/
|
|
227
|
+
function parseCheckResult(text) {
|
|
228
|
+
if (!text) return null;
|
|
229
|
+
// 宽松:允许 ```json:machine-readable 与 ``` 之间任意内容(含换行)
|
|
230
|
+
var m = text.match(/```json:machine-readable\s*\n([\s\S]*?)\n```/);
|
|
231
|
+
if (!m) return null;
|
|
232
|
+
try {
|
|
233
|
+
var obj = JSON.parse(m[1]);
|
|
234
|
+
if (obj && typeof obj === 'object') return obj;
|
|
235
|
+
} catch (_e) {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 归一化为合法 CheckResult(补齐缺失字段,确保 reflection-evaluator 能消费)。
|
|
243
|
+
* @param {object|null} chk 解析出的原始对象
|
|
244
|
+
* @param {string} fallbackWpId 解析失败时的兜底 wpId
|
|
245
|
+
* @returns {object} CheckResult(结构保证完整)
|
|
246
|
+
*/
|
|
247
|
+
function normalizeCheckResult(chk, fallbackWpId) {
|
|
248
|
+
if (!chk || typeof chk !== 'object') {
|
|
249
|
+
return {
|
|
250
|
+
wpId: fallbackWpId || 'unknown',
|
|
251
|
+
passed: false,
|
|
252
|
+
summary: { total: 0, passed: 0, failed: 0 },
|
|
253
|
+
categories: [],
|
|
254
|
+
failedItems: [{ id: 'parse-1', category: 'parse', text: 'checklist output', reason: 'no json:machine-readable block' }],
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
var summary = chk.summary || {};
|
|
258
|
+
var total = typeof summary.total === 'number' ? summary.total : 0;
|
|
259
|
+
var passed = typeof summary.passed === 'number' ? summary.passed : 0;
|
|
260
|
+
var failed = typeof summary.failed === 'number' ? summary.failed : (total - passed);
|
|
261
|
+
return {
|
|
262
|
+
wpId: chk.wpId || fallbackWpId || 'unknown',
|
|
263
|
+
passed: chk.passed === true,
|
|
264
|
+
summary: { total: total, passed: passed, failed: failed },
|
|
265
|
+
categories: Array.isArray(chk.categories) ? chk.categories : [],
|
|
266
|
+
failedItems: Array.isArray(chk.failedItems) ? chk.failedItems : [],
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* CheckResult 收尾链(Phase D 共享:claude/default/sdk 三 executor 统一走此函数):
|
|
272
|
+
* 1. schema 校验(checkresult-validator):数值谎报(passed>total / passed+failed≠total /
|
|
273
|
+
* 负数)→ 硬改判 failed + failedItems 注入 schema 失败项(B19 类问题的源头替代);
|
|
274
|
+
* 结构瑕疵 → 仅附加 _schemaErrors(observability,不改判)
|
|
275
|
+
* 2. normalizeCheckResult:结构归一
|
|
276
|
+
* 3. objective verification(objective-verifier):items[].verify 声明的命令实跑,
|
|
277
|
+
* 自报 passed 但客观不符 → 改判 fail + summary 重算(以客观为准)
|
|
278
|
+
*
|
|
279
|
+
* @param {object|null} raw parseCheckResult 的产物
|
|
280
|
+
* @param {string} wpId fallback wpId
|
|
281
|
+
* @param {object} [opts] { cwd } — verify 命令执行目录(runCwd,worktree 感知)
|
|
282
|
+
* @returns {object} CheckResult
|
|
283
|
+
*/
|
|
284
|
+
function finalizeCheckResult(raw, wpId, opts) {
|
|
285
|
+
opts = opts || {};
|
|
286
|
+
var validation = checkresultValidator.validateCheckResult(raw);
|
|
287
|
+
if (validation.hard && raw && typeof raw === 'object') {
|
|
288
|
+
raw.passed = false;
|
|
289
|
+
raw.failedItems = (Array.isArray(raw.failedItems) ? raw.failedItems : []).concat([{
|
|
290
|
+
id: 'schema-1',
|
|
291
|
+
category: 'schema',
|
|
292
|
+
text: 'checklist schema hard violation',
|
|
293
|
+
reason: validation.errors.join('; ').slice(0, 500),
|
|
294
|
+
}]);
|
|
295
|
+
// summary 已证实谎报 → 不可信,重写为 failedItems 驱动(total=条目数、全 fail),
|
|
296
|
+
// 保证下游 evaluator 的 failedCount(summary.failed 或 failedItems.length 两路口径)一致
|
|
297
|
+
raw.summary = {
|
|
298
|
+
total: raw.failedItems.length,
|
|
299
|
+
passed: 0,
|
|
300
|
+
failed: raw.failedItems.length,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
var chk = normalizeCheckResult(raw, wpId);
|
|
304
|
+
if (validation.errors && validation.errors.length) {
|
|
305
|
+
chk._schemaErrors = validation.errors.slice(0, 10);
|
|
306
|
+
}
|
|
307
|
+
if (raw && typeof raw === 'object' && Array.isArray(raw.categories)) {
|
|
308
|
+
objectiveVerifier.applyObjectiveVerification(chk, { cwd: opts.cwd });
|
|
309
|
+
}
|
|
310
|
+
return chk;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 生成「无法解析 / 超时 / 限流」的失败 CheckResult。
|
|
315
|
+
* @param {string} wpId
|
|
316
|
+
* @param {string} reason
|
|
317
|
+
* @returns {object}
|
|
318
|
+
*/
|
|
319
|
+
function buildFailedChecklist(wpId, reason) {
|
|
320
|
+
return {
|
|
321
|
+
wpId: wpId || 'unknown',
|
|
322
|
+
passed: false,
|
|
323
|
+
summary: { total: 1, passed: 0, failed: 1 },
|
|
324
|
+
categories: [],
|
|
325
|
+
failedItems: [{ id: 'exec-1', category: 'exec', text: 'executor failure', reason: reason }],
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 进展检测:基于执行前后工作树脏度,标注 CheckResult 的 noProgress 信号(WP-191-2-impl)。
|
|
331
|
+
*
|
|
332
|
+
* 语义(对齐 Ralph 熔断判据,修复"恒判无进展"缺陷):
|
|
333
|
+
* - passed=true → noProgress=false(达成即有进展,不进入发散累计)
|
|
334
|
+
* - passed=false + 工作树脏(执行后有改动) → noProgress=false(本轮产出了代码,可能只是测试还没过)
|
|
335
|
+
* - passed=false + 工作树干净 → noProgress=true(无代码进展,累计入发散)
|
|
336
|
+
* - 工作树无法判定(非 git 仓库降级) → noProgress=false(不误判、不阻断)
|
|
337
|
+
*
|
|
338
|
+
* 公开字段:chk.noProgress(boolean,供 reflection-evaluator 累计 streak)。
|
|
339
|
+
* 兼容:保留 chk._noProgress(旧字段,仅 true 时写入),向后兼容旧消费者/测试。
|
|
340
|
+
*
|
|
341
|
+
* 本函数提取自原 run() 内联逻辑,供 executor-glm 复用(消除两份重复代码,零漂移)。
|
|
342
|
+
*
|
|
343
|
+
* @param {object} chk CheckResult(会被原地补充 noProgress / _noProgress / 可能追加 progress failedItem)
|
|
344
|
+
* @param {boolean|null} dirtyBefore 执行前工作树脏度(readWorktreeDirty 返回值)
|
|
345
|
+
* @param {boolean|null} dirtyAfter 执行后工作树脏度
|
|
346
|
+
* @returns {object} 同 chk(链式)
|
|
347
|
+
*/
|
|
348
|
+
function applyProgressDetection(chk, dirtyBefore, dirtyAfter) {
|
|
349
|
+
if (!chk) return chk;
|
|
350
|
+
// passed=true:达成即有进展
|
|
351
|
+
if (chk.passed === true) {
|
|
352
|
+
chk.noProgress = false;
|
|
353
|
+
return chk;
|
|
354
|
+
}
|
|
355
|
+
// 工作树脏度任一无法判定(非 git 仓库降级)→ 不误判无进展
|
|
356
|
+
if (dirtyBefore === null || dirtyAfter === null) {
|
|
357
|
+
chk.noProgress = false;
|
|
358
|
+
return chk;
|
|
359
|
+
}
|
|
360
|
+
// 工作树由干净变脏,或保持脏 → 本轮产出了代码改动 → 有进展
|
|
361
|
+
var producedChange = dirtyAfter || (!dirtyBefore && dirtyAfter);
|
|
362
|
+
// 等价简化:dirtyAfter 为 true 即视为有进展(无论 before)
|
|
363
|
+
if (dirtyAfter) {
|
|
364
|
+
chk.noProgress = false;
|
|
365
|
+
return chk;
|
|
366
|
+
}
|
|
367
|
+
// passed=false 且工作树干净(before/after 均不脏)→ 无代码进展
|
|
368
|
+
chk.noProgress = true;
|
|
369
|
+
chk._noProgress = true; // 向后兼容旧字段
|
|
370
|
+
if (chk.failedItems && chk.failedItems.length) {
|
|
371
|
+
chk.failedItems.push({
|
|
372
|
+
id: 'progress-1', category: 'progress', text: 'no worktree change',
|
|
373
|
+
reason: '工作树无改动且 passed=false(无代码进展,对齐 Ralph 熔断判据)',
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
// 保留 producedChange 变量语义可读性(lint 友好):未直接使用仅作判定文档化
|
|
377
|
+
void producedChange;
|
|
378
|
+
return chk;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* 读取 WP 文档(docs/wp/{wpId}.md),注入 prompt。
|
|
383
|
+
* 不存在时返回提示文本(不阻断;调用方决定是否提示用户先 task-creator)。
|
|
384
|
+
* @param {string} wpId
|
|
385
|
+
* @param {string} projectRoot
|
|
386
|
+
* @returns {{ content:string|null, path:string }}
|
|
387
|
+
*/
|
|
388
|
+
function readWpDoc(wpId, projectRoot) {
|
|
389
|
+
// S4:校验 wpId 字符集,防止 path.join 拼出 docs/wp/ 之外的路径
|
|
390
|
+
// (wpId 来自 plan.md 解析,做防御性消毒;非法时当作无文档处理)
|
|
391
|
+
if (!wpId || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(wpId)) {
|
|
392
|
+
return { content: null, path: path.join(projectRoot, 'docs', 'wp', '<invalid-id>.md') };
|
|
393
|
+
}
|
|
394
|
+
var docPath = path.join(projectRoot, 'docs', 'wp', wpId + '.md');
|
|
395
|
+
if (!fs.existsSync(docPath)) {
|
|
396
|
+
return { content: null, path: docPath };
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
return { content: fs.readFileSync(docPath, 'utf8'), path: docPath };
|
|
400
|
+
} catch (_e) {
|
|
401
|
+
return { content: null, path: docPath };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* WP-S4 精读 retry:按失败项关键词裁剪 WP 文档,只注入相关段落。
|
|
407
|
+
* 北极星②省 token:retry 是 token 大户(每轮全量重灌 55K input 级);
|
|
408
|
+
* refine 反馈已有失败项明细——文档按段落打分只留相关块 + 头部(目标/验收)。
|
|
409
|
+
*
|
|
410
|
+
* @param {string} docContent WP 文档全文
|
|
411
|
+
* @param {Array} failingDrivers [{ category, item, reason }]
|
|
412
|
+
* @returns {{ pruned: string, mode: 'full'|'focused', keptBlocks: number, totalBlocks: number }}
|
|
413
|
+
* mode=full 表示打分全零(关键词不命中任何段落)→ 全量注入安全网
|
|
414
|
+
*/
|
|
415
|
+
function pruneDocForRetry(docContent, failingDrivers) {
|
|
416
|
+
if (!docContent || !Array.isArray(failingDrivers) || failingDrivers.length === 0) {
|
|
417
|
+
return { pruned: docContent || '', mode: 'full', keptBlocks: 0, totalBlocks: 0 };
|
|
418
|
+
}
|
|
419
|
+
var lines = String(docContent).split(/\r?\n/);
|
|
420
|
+
// 按 '## ' 标题切块(块 0 = 文档头,总是保留——目标/验收标准所在)
|
|
421
|
+
var blocks = [];
|
|
422
|
+
var cur = null;
|
|
423
|
+
for (var j = 0; j < lines.length; j++) {
|
|
424
|
+
if (/^##\s+/.test(lines[j])) {
|
|
425
|
+
if (cur) blocks.push(cur);
|
|
426
|
+
cur = { title: lines[j], lines: [lines[j]] };
|
|
427
|
+
} else {
|
|
428
|
+
if (!cur) cur = { title: '__head__', lines: [] };
|
|
429
|
+
cur.lines.push(lines[j]);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (cur) blocks.push(cur);
|
|
433
|
+
|
|
434
|
+
var queryTokens = [];
|
|
435
|
+
for (var f = 0; f < failingDrivers.length; f++) {
|
|
436
|
+
var fd = failingDrivers[f];
|
|
437
|
+
queryTokens = queryTokens.concat(textTokenize.tokenize(
|
|
438
|
+
(fd.item || '') + ' ' + (fd.reason || '') + ' ' + (fd.category || '')));
|
|
439
|
+
}
|
|
440
|
+
var scored = [];
|
|
441
|
+
for (var b = 1; b < blocks.length; b++) { // 块 0(文档头)不参与打分,总保留
|
|
442
|
+
var blk = blocks[b];
|
|
443
|
+
var blkTokens = textTokenize.tokenize(blk.lines.join('\n'));
|
|
444
|
+
var score = 0;
|
|
445
|
+
for (var q = 0; q < queryTokens.length; q++) {
|
|
446
|
+
if (blkTokens.indexOf(queryTokens[q]) !== -1) score += 1;
|
|
447
|
+
}
|
|
448
|
+
scored.push({ index: b, score: score });
|
|
449
|
+
}
|
|
450
|
+
var hit = scored.filter(function (s) { return s.score > 0; });
|
|
451
|
+
if (hit.length === 0) {
|
|
452
|
+
return { pruned: docContent, mode: 'full', keptBlocks: blocks.length, totalBlocks: blocks.length };
|
|
453
|
+
}
|
|
454
|
+
// 保留:文档头 + 第一个 ## 段(目标/验收标准所在,语义上属于头)+ 命中块
|
|
455
|
+
var kept = [blocks[0]];
|
|
456
|
+
if (blocks.length > 1) kept.push(blocks[1]);
|
|
457
|
+
for (var h = 0; h < hit.length; h++) kept.push(blocks[hit[h].index]);
|
|
458
|
+
return {
|
|
459
|
+
pruned: kept.map(function (k) { return k.lines.join('\n'); }).join('\n\n'),
|
|
460
|
+
mode: 'focused',
|
|
461
|
+
keptBlocks: kept.length,
|
|
462
|
+
totalBlocks: blocks.length,
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* 构造 claude prompt(WP-187-impl;WP-S2 cache 友好重排)。
|
|
468
|
+
*
|
|
469
|
+
* 段落顺序按「稳定度递减」排列,吃满 provider prompt context cache
|
|
470
|
+
* (GLM/DeepSeek/Anthropic 均按最长公共前缀命中——同一 loop 内固定不变
|
|
471
|
+
* 的内容必须放最前,每轮变化的放最后):
|
|
472
|
+
* [稳定] 身份 + 行为规则(完成要求)+ 窗口预算 —— 跨轮跨 WP 不变
|
|
473
|
+
* [半稳定] WP 文档全文 —— 同一 WP 的 dispatch/retry 不变
|
|
474
|
+
* [动态] 任务标识 / mode / 失败项反馈 / 执行锚点 —— 每轮变化
|
|
475
|
+
* 注:禁止在此 prompt 加入时间戳/轮次号等每轮漂移字段(会打断 cache 前缀)。
|
|
476
|
+
*
|
|
477
|
+
* @param {object} pendingAction { wpId, mode, strategy, failingDrivers }
|
|
478
|
+
* @param {string} projectRoot
|
|
479
|
+
* @returns {string}
|
|
480
|
+
*/
|
|
481
|
+
function buildPrompt(pendingAction, projectRoot, contextWindow) {
|
|
482
|
+
pendingAction = pendingAction || {};
|
|
483
|
+
var wpId = pendingAction.wpId || 'unknown';
|
|
484
|
+
var mode = pendingAction.mode || 'dispatch';
|
|
485
|
+
var strategy = pendingAction.strategy || 'full_restart';
|
|
486
|
+
|
|
487
|
+
var lines = [];
|
|
488
|
+
// ── [稳定前缀] 身份 + 行为规则(跨轮不变,cache 命中区)──
|
|
489
|
+
lines.push('你是 doukui agentic loop 的执行单元(executor)。当前 loop 通过 Node driver 调度你完成一个工作包。');
|
|
490
|
+
lines.push('');
|
|
491
|
+
lines.push('## 完成要求');
|
|
492
|
+
lines.push('1. 按下方 WP 文档实现/修改代码');
|
|
493
|
+
lines.push('2. 跑相关单测验证(npm test 或针对性测试)');
|
|
494
|
+
lines.push('3. 完成后**必须**在最终回复中产出 skill-checklist 的机器可读判定块,');
|
|
495
|
+
lines.push(' 格式为 ```json:machine-readable 后跟 JSON,字段:');
|
|
496
|
+
lines.push(' wpId / passed / summary{total,passed,failed} / categories[] / failedItems[]');
|
|
497
|
+
lines.push(' (详见 skill-checklist skill)。未产出该块将被判定为执行失败。');
|
|
498
|
+
lines.push('');
|
|
499
|
+
// 上下文窗口预算(Phase B-2 分档:provider profile 显式声明 > 内置档位表 > 200K 保守默认)。
|
|
500
|
+
// 供会话内分块读取策略(harness-config context_window 段)用对预算;缺省不注入(零回归)。
|
|
501
|
+
if (typeof contextWindow === 'number' && contextWindow > 0) {
|
|
502
|
+
lines.push('## 上下文窗口预算');
|
|
503
|
+
lines.push(contextWindow + ' tokens(按 provider 分档自动解析;大文件按此预算分块读取)。');
|
|
504
|
+
lines.push('');
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ── [半稳定] WP 文档(同一 WP 的多轮之间不变;retry 精读裁剪,WP-S4)──
|
|
508
|
+
var doc = readWpDoc(wpId, projectRoot);
|
|
509
|
+
if (doc.content) {
|
|
510
|
+
var docBody = doc.content;
|
|
511
|
+
var docMode = 'full';
|
|
512
|
+
if (mode === 'retry' && pendingAction.failingDrivers && pendingAction.failingDrivers.length) {
|
|
513
|
+
var pruned = pruneDocForRetry(doc.content, pendingAction.failingDrivers);
|
|
514
|
+
if (pruned.mode === 'focused') {
|
|
515
|
+
docBody = pruned.pruned;
|
|
516
|
+
docMode = 'focused (' + pruned.keptBlocks + '/' + pruned.totalBlocks + ' 段,按失败项关联裁剪)';
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
lines.push('## WP 文档(' + doc.path + (docMode !== 'full' ? ' · 精读模式' : '') + ')');
|
|
520
|
+
lines.push('请严格依据下方文档的目标、关键文件、验收标准执行:');
|
|
521
|
+
if (docMode !== 'full') {
|
|
522
|
+
lines.push('(WP-S4 精读:仅注入与失败项相关段落;完整文档可 Read ' + doc.path + ')');
|
|
523
|
+
}
|
|
524
|
+
lines.push('');
|
|
525
|
+
lines.push('---');
|
|
526
|
+
lines.push(docBody);
|
|
527
|
+
lines.push('---');
|
|
528
|
+
lines.push('');
|
|
529
|
+
} else {
|
|
530
|
+
lines.push('## WP 文档');
|
|
531
|
+
lines.push('⚠️ 未找到 ' + doc.path + '。请先用 task-creator 创建 WP 文档,或依据 loop 目标自行完成。');
|
|
532
|
+
lines.push('');
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ── [动态尾巴] 任务标识 / mode / 失败项 / 执行锚点(每轮变化)──
|
|
536
|
+
lines.push('## 当前任务');
|
|
537
|
+
lines.push('- WP ID: ' + wpId);
|
|
538
|
+
lines.push('- 模式: ' + mode + '(dispatch=新执行 / retry=针对失败项重做 / resplit=拆分后执行)');
|
|
539
|
+
lines.push('- 策略: ' + strategy);
|
|
540
|
+
lines.push('');
|
|
541
|
+
if (mode === 'retry' && pendingAction.failingDrivers && pendingAction.failingDrivers.length) {
|
|
542
|
+
lines.push('## 上轮失败项(refine 反馈,请针对性修复)');
|
|
543
|
+
for (var i = 0; i < pendingAction.failingDrivers.length; i++) {
|
|
544
|
+
var fd = pendingAction.failingDrivers[i];
|
|
545
|
+
lines.push('- [' + (fd.category || '?') + '] ' + (fd.item || '') + ':' + (fd.reason || ''));
|
|
546
|
+
}
|
|
547
|
+
lines.push('');
|
|
548
|
+
}
|
|
549
|
+
lines.push('## 现在执行');
|
|
550
|
+
lines.push('立即开始执行 WP-' + wpId.replace(/^WP-?/i, '') + '(' + mode + ')。完成后按「完成要求」产出机器可读判定块。');
|
|
551
|
+
return lines.join('\n');
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* 构造 claude CLI 参数(WP-185-impl)。
|
|
556
|
+
*
|
|
557
|
+
* SECURITY (S1):prompt **不**经 argv 传入——大 prompt 会触发
|
|
558
|
+
* Windows 命令行 ARG_MAX(≈32767)截断 / spawn ENAMETOOLONG,
|
|
559
|
+
* 且在 POSIX 上经 /proc/<pid>/cmdline 泄漏给同机其他用户。
|
|
560
|
+
* prompt 改由 run() 写入子进程 stdin(claude -p 的标准 stdin 模式)。
|
|
561
|
+
*
|
|
562
|
+
* settingsPath(可选):透传 claude CLI 原生 `--settings <file-or-json>` flag,
|
|
563
|
+
* 加载额外的 settings JSON(与 claude 默认发现机制叠加)。用途:动态切换
|
|
564
|
+
* provider/套餐档位(如指定 ~/.claude/settings-glm-5.2[1m]max.json)。
|
|
565
|
+
* SECURITY:settingsPath 是文件**路径**,非 prompt/密钥本身——密钥在文件内由
|
|
566
|
+
* claude 自行读取,路径进 argv 安全(与 --allowedTools 等路径性质一致)。
|
|
567
|
+
*
|
|
568
|
+
* @param {string[]} allowedTools
|
|
569
|
+
* @param {string} [settingsPath] 可选 claude settings 文件路径;非空时追加 --settings
|
|
570
|
+
* @returns {string[]}
|
|
571
|
+
*/
|
|
572
|
+
function buildClaudeArgs(allowedTools, settingsPath) {
|
|
573
|
+
var args = [
|
|
574
|
+
'-p', // --print:非交互,单次执行后退出
|
|
575
|
+
'--output-format', 'json',
|
|
576
|
+
'--allowedTools', allowedTools.join(','),
|
|
577
|
+
];
|
|
578
|
+
if (settingsPath) {
|
|
579
|
+
args.push('--settings', settingsPath);
|
|
580
|
+
}
|
|
581
|
+
return args;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ---------------------------------------------------------------------------
|
|
585
|
+
// 公开 API
|
|
586
|
+
// ---------------------------------------------------------------------------
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* 创建一个 claude executor 实例。
|
|
590
|
+
*
|
|
591
|
+
* @param {object} [opts]
|
|
592
|
+
* @param {Function} [opts.spawnFn] 注入 spawn(测试用);默认 child_process.spawn
|
|
593
|
+
* @param {string} [opts.binary] claude 可执行名
|
|
594
|
+
* @param {number} [opts.timeoutMs] 单次超时(ms)
|
|
595
|
+
* @param {number} [opts.rateLimitPerHour] 调用上限/h
|
|
596
|
+
* @param {string} [opts.model] 模型名占位(provider 零分支统一通道;claude 不显式 --model)
|
|
597
|
+
* @param {string[]} [opts.allowedTools] 工具白名单
|
|
598
|
+
* @param {string} [opts.projectRoot] 项目根覆盖(默认自动探测)
|
|
599
|
+
* @param {string} [opts.settingsPath] claude settings 文件路径(透传 --settings;切换 provider/套餐)
|
|
600
|
+
* @returns {{ name:string, run:Function, config:object }}
|
|
601
|
+
*/
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* 把 executor 打点 trace 附到 CheckResult 上(WP-196-1-impl,纯观测)。
|
|
605
|
+
* 下划线前缀 `_executorTrace` 表示内部观测字段,reflection-evaluator 不消费;
|
|
606
|
+
* driver 读取后聚合到 round record。全程 try/catch 降级。
|
|
607
|
+
* @param {object} checkResult
|
|
608
|
+
* @param {object} trace { spawnMs, exitCode, timedOut, rateLimited, tokenUsage, endpointMs }
|
|
609
|
+
* @returns {object} 原 checkResult(附 _executorTrace)
|
|
610
|
+
*/
|
|
611
|
+
function withExecutorTrace(checkResult, trace) {
|
|
612
|
+
try {
|
|
613
|
+
if (checkResult && typeof checkResult === 'object') {
|
|
614
|
+
checkResult._executorTrace = trace || null;
|
|
615
|
+
}
|
|
616
|
+
} catch (_e) { /* 降级:观测失败绝不阻断 */ }
|
|
617
|
+
return checkResult;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function createExecutor(opts) {
|
|
621
|
+
opts = opts || {};
|
|
622
|
+
var config = {
|
|
623
|
+
binary: opts.binary || DEFAULTS.binary,
|
|
624
|
+
timeoutMs: typeof opts.timeoutMs === 'number' ? opts.timeoutMs : DEFAULTS.timeoutMs,
|
|
625
|
+
rateLimitPerHour: typeof opts.rateLimitPerHour === 'number'
|
|
626
|
+
? opts.rateLimitPerHour : DEFAULTS.rateLimitPerHour,
|
|
627
|
+
model: opts.model || DEFAULTS.model,
|
|
628
|
+
allowedTools: (opts.allowedTools && opts.allowedTools.length)
|
|
629
|
+
? opts.allowedTools.slice() : DEFAULTS.allowedTools.slice(),
|
|
630
|
+
projectRoot: opts.projectRoot || resolveProjectRoot(),
|
|
631
|
+
settingsPath: opts.settingsPath || null,
|
|
632
|
+
// 上下文窗口预算 tokens(Phase B-2 分档;null=未知不注入 prompt)
|
|
633
|
+
contextWindow: typeof opts.contextWindow === 'number' && opts.contextWindow > 0
|
|
634
|
+
? opts.contextWindow : null,
|
|
635
|
+
};
|
|
636
|
+
var spawnFn = opts.spawnFn || spawn;
|
|
637
|
+
// 进展检测 git status 执行函数(DI 注入,测试用;默认走 readWorktreeDirty 内 execFileSync)
|
|
638
|
+
var gitStatusFn = typeof opts.gitStatusFn === 'function' ? opts.gitStatusFn : null;
|
|
639
|
+
|
|
640
|
+
// 限流状态
|
|
641
|
+
var callTimestamps = [];
|
|
642
|
+
var HOUR_MS = 60 * 60 * 1000;
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* 执行 pendingAction:spawn claude → 收集 stdout → 解析 json:machine-readable block。
|
|
646
|
+
* @param {object} pendingAction
|
|
647
|
+
* @returns {Promise<object>} CheckResult
|
|
648
|
+
*/
|
|
649
|
+
async function run(pendingAction) {
|
|
650
|
+
pendingAction = pendingAction || {};
|
|
651
|
+
var wpId = pendingAction.wpId || 'unknown';
|
|
652
|
+
|
|
653
|
+
// concurrent-dispatch Step 2(per-WP worktree 隔离):
|
|
654
|
+
// per-call projectRoot override。批内 N 个并发 run 各自走独立 worktree(loop.js
|
|
655
|
+
// 传入 pendingAction.projectRoot = wtPath),使 readWorktreeDirty 的 dirtyBefore/
|
|
656
|
+
// dirtyAfter per-WP 准确、互不串扰(修复 v0.4.0 noProgress 批级串扰)。
|
|
657
|
+
// 不传 → 走 config.projectRoot(零回归 = v0.4.0 行为)。
|
|
658
|
+
var runCwd = (typeof pendingAction.projectRoot === 'string' && pendingAction.projectRoot)
|
|
659
|
+
? pendingAction.projectRoot : config.projectRoot;
|
|
660
|
+
// noProgressForceZero(--no-progress-detect escape hatch,文档 §5.5):批模式强制
|
|
661
|
+
// 脏度降级(dirtyBefore/dirtyAfter=null → applyProgressDetection 走降级 noProgress=false),
|
|
662
|
+
// 牺牲发散检测精度换稳定性,~0 行内联(仅置 null,无需 worktree 基建)。
|
|
663
|
+
var forceZeroProgress = pendingAction.noProgressForceZero === true;
|
|
664
|
+
|
|
665
|
+
// WP-196-1-impl / token-usage:executor.run 打点(仅观测,不引入 provider 分支)。
|
|
666
|
+
// 采集 {spawnMs, exitCode, timedOut, rateLimited, tokenUsage, endpointMs} 附在 checkResult._executorTrace。
|
|
667
|
+
// tokenUsage/endpointMs 在 close 回调由 extractMetaFromClaudeStdout 填充;限流/失败路径保持 null。
|
|
668
|
+
var trace = { spawnMs: null, exitCode: null, timedOut: false, rateLimited: false, tokenUsage: null, endpointMs: null };
|
|
669
|
+
var spawnStartMs = Date.now();
|
|
670
|
+
|
|
671
|
+
// 限流
|
|
672
|
+
var now = Date.now();
|
|
673
|
+
callTimestamps = callTimestamps.filter(function (ts) { return now - ts < HOUR_MS; });
|
|
674
|
+
if (callTimestamps.length >= config.rateLimitPerHour) {
|
|
675
|
+
trace.rateLimited = true;
|
|
676
|
+
trace.spawnMs = Date.now() - spawnStartMs;
|
|
677
|
+
return withExecutorTrace(buildFailedChecklist(wpId, 'rate_limited'), trace);
|
|
678
|
+
}
|
|
679
|
+
callTimestamps.push(now);
|
|
680
|
+
|
|
681
|
+
// 进展检测基线(WP-191-2-impl):执行前工作树脏度(porcelain)
|
|
682
|
+
// forceZeroProgress → 跳过采样(置 null),applyProgressDetection 走降级 noProgress=false
|
|
683
|
+
var dirtyBefore = forceZeroProgress ? null : readWorktreeDirty(runCwd, gitStatusFn);
|
|
684
|
+
|
|
685
|
+
// 构造 prompt + args
|
|
686
|
+
// bug-003 fix:readWpDoc 用 config.projectRoot(主工作树 docs/wp/),非 runCwd(worktree,
|
|
687
|
+
// git worktree add 不含 gitignored docs/wp/)。spawn cwd 仍用 runCwd。无 override 等价。
|
|
688
|
+
var prompt = buildPrompt(pendingAction, config.projectRoot, config.contextWindow);
|
|
689
|
+
var args = buildClaudeArgs(config.allowedTools, config.settingsPath);
|
|
690
|
+
|
|
691
|
+
// spawn + 超时控制
|
|
692
|
+
var stdoutBuf = '';
|
|
693
|
+
var stderrBuf = '';
|
|
694
|
+
var timedOut = false;
|
|
695
|
+
var child;
|
|
696
|
+
try {
|
|
697
|
+
child = spawnFn(config.binary, args, {
|
|
698
|
+
cwd: runCwd,
|
|
699
|
+
encoding: 'utf8',
|
|
700
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
701
|
+
// WP-D1 dogfood 发现:Windows 下 claude 是 npm shim(claude.cmd),
|
|
702
|
+
// 无 shell 的 spawn 直接 ENOENT——win32 必须走 shell 解析 .cmd。
|
|
703
|
+
// args 均为无空格 token(--allowedTools 逗号串 / --settings 路径由
|
|
704
|
+
// Node shell:true 的引用处理覆盖常规空格路径)。
|
|
705
|
+
shell: process.platform === 'win32',
|
|
706
|
+
});
|
|
707
|
+
} catch (e) {
|
|
708
|
+
// spawn 立即失败(如 binary 不存在,ENOENT)
|
|
709
|
+
trace.spawnMs = Date.now() - spawnStartMs;
|
|
710
|
+
return withExecutorTrace(buildFailedChecklist(wpId, 'spawn_failed: ' + ((e && e.code) || (e && e.message) || String(e))), trace);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// prompt 走 stdin(S1):claude -p 从 stdin 读取,规避 argv 长度/泄漏问题。
|
|
714
|
+
// 子进程若早退或拒读 stdin,write 会触发 EPIPE——挂 error handler 吞掉,
|
|
715
|
+
// 由 child 'close'/'error' 统一收尾,避免 unhandled 异常。
|
|
716
|
+
if (child.stdin) {
|
|
717
|
+
child.stdin.on('error', function (_e) {});
|
|
718
|
+
try {
|
|
719
|
+
child.stdin.write(prompt);
|
|
720
|
+
child.stdin.end();
|
|
721
|
+
} catch (_writeErr) {
|
|
722
|
+
// 同步写失败(如 stdin 已关闭):忽略,等 close 事件裁决
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
return new Promise(function (resolve) {
|
|
727
|
+
// 超时计时器:到点 kill 子进程
|
|
728
|
+
var timer = setTimeout(function () {
|
|
729
|
+
timedOut = true;
|
|
730
|
+
try {
|
|
731
|
+
if (process.platform === 'win32' && child.pid) {
|
|
732
|
+
// WP-D1 dogfood 发现:win32 shell:true 时 SIGTERM 杀的是 cmd 包装层,
|
|
733
|
+
// claude 孙进程残留 → close 永不到达 → 挂满超时。用 taskkill 进程树击杀。
|
|
734
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
|
735
|
+
} else {
|
|
736
|
+
child.kill('SIGTERM');
|
|
737
|
+
// 宽限 2s 后 SIGKILL
|
|
738
|
+
setTimeout(function () {
|
|
739
|
+
try { child.kill('SIGKILL'); } catch (_e2) {}
|
|
740
|
+
}, 2000);
|
|
741
|
+
}
|
|
742
|
+
} catch (_e) {}
|
|
743
|
+
}, config.timeoutMs);
|
|
744
|
+
|
|
745
|
+
if (child.stdout) {
|
|
746
|
+
child.stdout.on('data', function (chunk) {
|
|
747
|
+
if (chunk) stdoutBuf += chunk.toString();
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
if (child.stderr) {
|
|
751
|
+
child.stderr.on('data', function (chunk) {
|
|
752
|
+
if (chunk) stderrBuf += chunk.toString();
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
child.on('error', function (err) {
|
|
757
|
+
clearTimeout(timer);
|
|
758
|
+
trace.spawnMs = Date.now() - spawnStartMs;
|
|
759
|
+
trace.exitCode = null;
|
|
760
|
+
resolve(withExecutorTrace(buildFailedChecklist(wpId, 'spawn_error: ' + (err && err.message ? err.message : String(err))), trace));
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
child.on('close', function (code) {
|
|
764
|
+
clearTimeout(timer);
|
|
765
|
+
trace.spawnMs = Date.now() - spawnStartMs;
|
|
766
|
+
trace.exitCode = (typeof code === 'number') ? code : null;
|
|
767
|
+
trace.timedOut = timedOut === true;
|
|
768
|
+
if (timedOut) {
|
|
769
|
+
resolve(withExecutorTrace(buildFailedChecklist(wpId, 'timeout'), trace));
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
// 提取 text → 解析 checklist block
|
|
773
|
+
var text = extractTextFromClaudeStdout(stdoutBuf);
|
|
774
|
+
// token-usage:提取端点元数据(usage/ttft/duration),失败降级 null(不阻断解析)
|
|
775
|
+
try {
|
|
776
|
+
var meta = extractMetaFromClaudeStdout(stdoutBuf);
|
|
777
|
+
trace.tokenUsage = meta.usage;
|
|
778
|
+
// 仅当提取到至少一个端点时序时才设 endpointMs,否则保持 null(语义:无端点数据)
|
|
779
|
+
if (meta.ttftMs !== null || meta.durationMs !== null) {
|
|
780
|
+
trace.endpointMs = { ttft: meta.ttftMs, duration: meta.durationMs };
|
|
781
|
+
}
|
|
782
|
+
} catch (_me) { /* 元数据提取降级:保持 null */ }
|
|
783
|
+
// Phase D 收尾链:schema 校验(谎报硬改判)→ normalize → 客观交叉验证
|
|
784
|
+
var raw = parseCheckResult(text);
|
|
785
|
+
var chk = finalizeCheckResult(raw, wpId, { cwd: runCwd });
|
|
786
|
+
|
|
787
|
+
// 进展检测(WP-191-2-impl):执行后工作树脏度 → 标注 noProgress
|
|
788
|
+
// 语义见 applyProgressDetection:工作树有改动=有进展;干净+passed=false=无进展
|
|
789
|
+
// forceZeroProgress → 置 null 走降级(与 dirtyBefore 对称)
|
|
790
|
+
var dirtyAfter = forceZeroProgress ? null : readWorktreeDirty(runCwd, gitStatusFn);
|
|
791
|
+
applyProgressDetection(chk, dirtyBefore, dirtyAfter);
|
|
792
|
+
// 非 0 退出码但解析出结果:仍用解析结果(claude 可能正常输出后非 0 退出)
|
|
793
|
+
// 非 0 退出码且无解析结果:视为失败
|
|
794
|
+
if (code !== 0 && !raw) {
|
|
795
|
+
resolve(withExecutorTrace(buildFailedChecklist(wpId, 'claude_exit_' + code + ': ' + stderrBuf.slice(0, 200)), trace));
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
resolve(withExecutorTrace(chk, trace));
|
|
799
|
+
});
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
return {
|
|
804
|
+
name: 'claude',
|
|
805
|
+
run: run,
|
|
806
|
+
config: config,
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
module.exports = {
|
|
811
|
+
createExecutor: createExecutor,
|
|
812
|
+
// 暴露内部工具便于单元测试
|
|
813
|
+
_buildPrompt: buildPrompt,
|
|
814
|
+
_buildClaudeArgs: buildClaudeArgs,
|
|
815
|
+
_extractTextFromClaudeStdout: extractTextFromClaudeStdout,
|
|
816
|
+
_extractMetaFromClaudeStdout: extractMetaFromClaudeStdout,
|
|
817
|
+
_parseCheckResult: parseCheckResult,
|
|
818
|
+
_normalizeCheckResult: normalizeCheckResult,
|
|
819
|
+
_finalizeCheckResult: finalizeCheckResult,
|
|
820
|
+
_buildFailedChecklist: buildFailedChecklist,
|
|
821
|
+
_readGitHead: readGitHead,
|
|
822
|
+
_readWorktreeDirty: readWorktreeDirty,
|
|
823
|
+
_applyProgressDetection: applyProgressDetection,
|
|
824
|
+
_pruneDocForRetry: pruneDocForRetry,
|
|
825
|
+
_readWpDoc: readWpDoc,
|
|
826
|
+
_resolveProjectRoot: resolveProjectRoot,
|
|
827
|
+
_DEFAULTS: DEFAULTS,
|
|
828
|
+
};
|