doukui 0.6.0 → 0.9.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 (92) hide show
  1. package/README.en.md +85 -18
  2. package/README.md +32 -72
  3. package/bin/commands/help.js +2 -25
  4. package/bin/commands/plan-lint.js +105 -0
  5. package/bin/commands/verify.js +263 -0
  6. package/bin/doukui.js +3 -3
  7. package/package.json +2 -3
  8. package/plugins/core/hook-session-start/index.js +1 -1
  9. package/plugins/core/hook-skill-gate/index.js +64 -15
  10. package/plugins/core/hook-skill-gate/plugin.json +1 -1
  11. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +7 -28
  12. package/plugins/core/skill-agent-dispatcher/monitoring-reference.md +89 -0
  13. package/plugins/core/skill-agent-dispatcher/plugin.json +1 -1
  14. package/plugins/core/skill-agent-dispatcher/recovery-reference.md +132 -0
  15. package/plugins/core/skill-agent-dispatcher/roles-reference.md +9 -22
  16. package/plugins/core/skill-agent-dispatcher/skill.md +124 -796
  17. package/plugins/core/skill-agentic-loop/mirror-rules.md +95 -24
  18. package/plugins/core/skill-agentic-loop/plugin.json +2 -7
  19. package/plugins/core/skill-agentic-loop/skill.md +125 -354
  20. package/plugins/core/skill-batch-task-creator/plugin.json +1 -1
  21. package/plugins/core/skill-checklist/skill.md +15 -141
  22. package/plugins/core/skill-completion-report/plugin.json +1 -1
  23. package/plugins/core/skill-completion-report/skill.md +7 -1
  24. package/plugins/core/skill-doukui-plan/plugin.json +1 -1
  25. package/plugins/core/skill-doukui-plan/skill.md +24 -21
  26. package/plugins/core/skill-experience-logger/plugin.json +1 -1
  27. package/plugins/core/skill-human-checkpoint/skill.md +1 -0
  28. package/plugins/core/skill-split-work-package/plugin.json +1 -1
  29. package/plugins/core/skill-task-creator/plugin.json +1 -1
  30. package/plugins/core/skill-task-creator/skill.md +1 -139
  31. package/plugins/core/skill-workflow-orchestrator/plugin.json +1 -1
  32. package/plugins/plugin-registry.json +0 -48
  33. package/plugins/runtime/harness-build.js +5 -5
  34. package/plugins/runtime/plan-reader.js +54 -21
  35. package/plugins/runtime/resolve-plugin-path.js +2 -2
  36. package/templates/harness-config.yaml +0 -100
  37. package/bin/commands/loop-server.js +0 -357
  38. package/bin/commands/loop.js +0 -1508
  39. package/plugins/contracts/capabilities.js +0 -268
  40. package/plugins/contracts/checkresult-schema.json +0 -75
  41. package/plugins/core/provider-loop-engine/index.js +0 -1411
  42. package/plugins/core/provider-loop-engine/plugin.json +0 -15
  43. package/plugins/core/provider-memory-store/index.js +0 -510
  44. package/plugins/core/provider-memory-store/plugin.json +0 -9
  45. package/plugins/core/provider-state-store/index.js +0 -244
  46. package/plugins/core/provider-state-store/plugin.json +0 -9
  47. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +0 -32
  48. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +0 -676
  49. package/plugins/core/provider-watchdog/assets/watchdog.js +0 -754
  50. package/plugins/core/provider-watchdog/index.js +0 -151
  51. package/plugins/core/provider-watchdog/plugin.json +0 -13
  52. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +0 -249
  53. package/plugins/core/skill-watchdog-manager/plugin.json +0 -10
  54. package/plugins/core/skill-watchdog-manager/skill.md +0 -143
  55. package/plugins/core/validator-doc-sync/index.js +0 -248
  56. package/plugins/core/validator-doc-sync/plugin.json +0 -12
  57. package/plugins/core/validator-work-package/index.js +0 -300
  58. package/plugins/core/validator-work-package/plugin.json +0 -12
  59. package/plugins/runtime/audit-logger.js +0 -311
  60. package/plugins/runtime/build-cli.js +0 -89
  61. package/plugins/runtime/checkresult-validator.js +0 -131
  62. package/plugins/runtime/context-window.js +0 -81
  63. package/plugins/runtime/event-bus.js +0 -207
  64. package/plugins/runtime/executor-claude.js +0 -604
  65. package/plugins/runtime/executor-default.js +0 -448
  66. package/plugins/runtime/executor-local.js +0 -178
  67. package/plugins/runtime/executor-sdk.js +0 -415
  68. package/plugins/runtime/hook-dispatcher.js +0 -315
  69. package/plugins/runtime/loop-actuator.js +0 -292
  70. package/plugins/runtime/loop-coordinator.js +0 -347
  71. package/plugins/runtime/loop-defaults.js +0 -29
  72. package/plugins/runtime/loop-dispatch-batch.js +0 -351
  73. package/plugins/runtime/loop-executor.js +0 -120
  74. package/plugins/runtime/loop-report.js +0 -395
  75. package/plugins/runtime/loop-server-core.js +0 -750
  76. package/plugins/runtime/loop-snapshot.js +0 -581
  77. package/plugins/runtime/loop-trace.js +0 -242
  78. package/plugins/runtime/loop-worktree.js +0 -404
  79. package/plugins/runtime/multi-window-coordinator.js +0 -560
  80. package/plugins/runtime/objective-verifier.js +0 -136
  81. package/plugins/runtime/plan-lint.js +0 -106
  82. package/plugins/runtime/plugin-loader.js +0 -798
  83. package/plugins/runtime/plugin-trust.js +0 -182
  84. package/plugins/runtime/provider-failover.js +0 -114
  85. package/plugins/runtime/provider-resolver.js +0 -342
  86. package/plugins/runtime/reflection-evaluator.js +0 -545
  87. package/plugins/runtime/sandbox-context.js +0 -235
  88. package/plugins/runtime/sandbox-manager.js +0 -609
  89. package/plugins/runtime/sandbox-worker.js +0 -215
  90. package/plugins/runtime/self-rescue-ladder.js +0 -51
  91. package/plugins/runtime/text-tokenize.js +0 -25
  92. package/plugins/runtime/validator-pipeline.js +0 -475
@@ -1,315 +0,0 @@
1
- /**
2
- * HookDispatcher - Dual-mode hook execution dispatcher for AI Agent Harness
3
- *
4
- * Two execution modes:
5
- * - External: Command-based execution via settings.json (default, backward compatible)
6
- * - Internal: Programmatic execution by calling HookPlugin.handle() directly
7
- *
8
- * Features:
9
- * - Route hook events to appropriate hooks based on trigger configuration
10
- * - Support PreToolUse, PostToolUse, SessionStart event types
11
- * - Priority-based hook execution (lower priority = earlier execution)
12
- * - Graceful handling of unregistered events
13
- * - Integration with PluginLoader for internal mode
14
- *
15
- * Usage:
16
- * const dispatcher = new HookDispatcher({ pluginLoader, logger });
17
- * await dispatcher.dispatch({ event: 'PreToolUse', tool: 'Edit', ... });
18
- */
19
-
20
- 'use strict';
21
-
22
- var { PluginType, PluginState } = require('../contracts/plugin-interface');
23
-
24
- /**
25
- * Execution mode constants.
26
- * @public
27
- */
28
- var ExecutionMode = Object.freeze({
29
- EXTERNAL: 'external', // Command-based via settings.json (default)
30
- INTERNAL: 'internal', // Programmatic via HookPlugin.handle()
31
- });
32
-
33
- /**
34
- * Default configuration.
35
- */
36
- var DEFAULT_CONFIG = {
37
- mode: ExecutionMode.EXTERNAL,
38
- priorityThreshold: 1000,
39
- };
40
-
41
- /**
42
- * HookDispatcher class.
43
- * @public
44
- */
45
- class HookDispatcher {
46
- /**
47
- * @public
48
- * @param {object} options
49
- * @param {object} options.pluginLoader - PluginLoader instance (required for internal mode)
50
- * @param {object} options.logger - Logger instance (optional)
51
- * @param {string} [options.mode] - default execution mode
52
- */
53
- constructor(options) {
54
- options = options || {};
55
- this._pluginLoader = options.pluginLoader || null;
56
- this._logger = options.logger || null;
57
- this._mode = options.mode || DEFAULT_CONFIG.mode;
58
- this._priorityThreshold = options.priorityThreshold || DEFAULT_CONFIG.priorityThreshold;
59
- }
60
-
61
- /**
62
- * Dispatch a hook event to appropriate hooks.
63
- *
64
- * @public
65
- * @param {object} context
66
- * @param {string} context.event - Event type: 'PreToolUse', 'PostToolUse', 'SessionStart'
67
- * @param {string} [context.tool] - Tool name (for PreToolUse/PostToolUse)
68
- * @param {string} [context.skill] - Skill name (for PostToolUse)
69
- * @param {string} [context.mode] - Override execution mode for this call
70
- * @returns {Promise<{ allowed: boolean, results?: object[], reason?: string }>}
71
- */
72
- async dispatch(context) {
73
- if (!context || !context.event) {
74
- this._log('warn', 'dispatch() called with invalid context');
75
- return { allowed: true, results: [] };
76
- }
77
-
78
- var mode = context.mode || this._mode;
79
- this._log('debug', 'Dispatching event "' + context.event + '" in ' + mode + ' mode');
80
-
81
- if (mode === ExecutionMode.INTERNAL) {
82
- return await this._dispatchInternal(context);
83
- }
84
-
85
- // External mode: no-op (hooks are executed via settings.json commands)
86
- return { allowed: true, results: [], mode: 'external' };
87
- }
88
-
89
- /**
90
- * Internal mode dispatch: call loaded HookPlugin.handle() directly.
91
- *
92
- * @param {object} context
93
- * @returns {Promise<{ allowed: boolean, results: object[], reason?: string }>}
94
- * @private
95
- */
96
- async _dispatchInternal(context) {
97
- if (!this._pluginLoader) {
98
- this._log('warn', 'Internal mode requested but no pluginLoader provided');
99
- return { allowed: true, results: [], mode: 'internal' };
100
- }
101
-
102
- var matchingHooks = this._findMatchingHooks(context);
103
- if (matchingHooks.length === 0) {
104
- this._log('debug', 'No matching hooks found for event "' + context.event + '"');
105
- return { allowed: true, results: [], mode: 'internal' };
106
- }
107
-
108
- // Sort by priority (lower = earlier execution)
109
- matchingHooks.sort(function (a, b) {
110
- var pa = (a.plugin && a.plugin.priority) || 100;
111
- var pb = (b.plugin && b.plugin.priority) || 100;
112
- return pa - pb;
113
- });
114
-
115
- this._log('debug', 'Found ' + matchingHooks.length + ' matching hook(s)');
116
-
117
- var results = [];
118
- var overallAllowed = true;
119
- var blockReason = null;
120
-
121
- for (var i = 0; i < matchingHooks.length; i++) {
122
- var item = matchingHooks[i];
123
- var plugin = item.plugin;
124
-
125
- // Skip inactive plugins
126
- if (plugin.state !== PluginState.ACTIVATED) {
127
- this._log('debug', 'Hook "' + plugin.name + '" is not activated, skipping');
128
- continue;
129
- }
130
-
131
- try {
132
- this._log('debug', 'Executing hook "' + plugin.name + '" (priority: ' + plugin.priority + ')');
133
- var result = await plugin.handle(context);
134
- results.push({
135
- hook: plugin.name,
136
- result: result,
137
- });
138
-
139
- // If any hook disallows, set overall allowed to false
140
- if (result && result.allowed === false) {
141
- overallAllowed = false;
142
- blockReason = result.reason || ('Blocked by hook: ' + plugin.name);
143
- this._log('info', 'Hook "' + plugin.name + '" disallowed action: ' + blockReason);
144
- // Continue executing remaining hooks for side effects
145
- }
146
- } catch (err) {
147
- this._log('error', 'Hook "' + plugin.name + '" threw error: ' + err.message);
148
- results.push({
149
- hook: plugin.name,
150
- error: err.message,
151
- });
152
- }
153
- }
154
-
155
- var response = {
156
- allowed: overallAllowed,
157
- results: results,
158
- mode: 'internal',
159
- };
160
-
161
- if (blockReason) {
162
- response.reason = blockReason;
163
- }
164
-
165
- return response;
166
- }
167
-
168
- /**
169
- * Find all loaded hooks that match the event context.
170
- *
171
- * @param {object} context
172
- * @returns {Array<{ plugin: HookPlugin, trigger: object }>}
173
- * @private
174
- */
175
- _findMatchingHooks(context) {
176
- var matches = [];
177
- var loadedNames = this._pluginLoader.getLoadedNames();
178
-
179
- for (var i = 0; i < loadedNames.length; i++) {
180
- var plugin = this._pluginLoader.getPlugin(loadedNames[i]);
181
-
182
- if (!plugin || plugin.type !== PluginType.HOOK) {
183
- continue;
184
- }
185
-
186
- var trigger = plugin.trigger || {};
187
-
188
- // Check event type match
189
- if (trigger.event !== context.event) {
190
- continue;
191
- }
192
-
193
- // Check tool filter (for PreToolUse/PostToolUse)
194
- if (trigger.tools && trigger.tools.length > 0) {
195
- var tool = context.tool || '';
196
- var toolMatched = false;
197
- for (var j = 0; j < trigger.tools.length; j++) {
198
- if (trigger.tools[j] === tool) {
199
- toolMatched = true;
200
- break;
201
- }
202
- }
203
- if (!toolMatched) continue;
204
- }
205
-
206
- // Check skill filter (for PostToolUse)
207
- if (trigger.skills && trigger.skills.length > 0) {
208
- var skill = context.skill || '';
209
- var skillMatched = false;
210
- for (var k = 0; k < trigger.skills.length; k++) {
211
- if (trigger.skills[k] === skill) {
212
- skillMatched = true;
213
- break;
214
- }
215
- }
216
- if (!skillMatched) continue;
217
- }
218
-
219
- matches.push({
220
- plugin: plugin,
221
- trigger: trigger,
222
- });
223
- }
224
-
225
- return matches;
226
- }
227
-
228
- /**
229
- * Set the default execution mode.
230
- * @public
231
- * @param {string} mode - 'external' or 'internal'
232
- */
233
- setMode(mode) {
234
- if (mode !== ExecutionMode.EXTERNAL && mode !== ExecutionMode.INTERNAL) {
235
- throw new Error('Invalid mode: ' + mode + '. Use "external" or "internal"');
236
- }
237
- this._mode = mode;
238
- this._log('info', 'Execution mode set to "' + mode + '"');
239
- }
240
-
241
- /**
242
- * Get the current default execution mode.
243
- * @public
244
- * @returns {string}
245
- */
246
- getMode() {
247
- return this._mode;
248
- }
249
-
250
- /**
251
- * Check if internal mode is available (requires pluginLoader).
252
- * @public
253
- * @returns {boolean}
254
- */
255
- canUseInternalMode() {
256
- return this._pluginLoader !== null;
257
- }
258
-
259
- /**
260
- * Get statistics about loaded hooks.
261
- * @public
262
- * @returns {{ total: number, byEvent: object, byPriority: object[] }}
263
- */
264
- getHookStats() {
265
- if (!this._pluginLoader) {
266
- return { total: 0, byEvent: {}, byPriority: [] };
267
- }
268
-
269
- var stats = {
270
- total: 0,
271
- byEvent: {},
272
- byPriority: [],
273
- };
274
-
275
- var loadedNames = this._pluginLoader.getLoadedNames();
276
- for (var i = 0; i < loadedNames.length; i++) {
277
- var plugin = this._pluginLoader.getPlugin(loadedNames[i]);
278
- if (!plugin || plugin.type !== PluginType.HOOK) continue;
279
-
280
- stats.total++;
281
-
282
- var event = (plugin.trigger && plugin.trigger.event) || 'unknown';
283
- stats.byEvent[event] = (stats.byEvent[event] || 0) + 1;
284
-
285
- stats.byPriority.push({
286
- name: plugin.name,
287
- event: event,
288
- priority: plugin.priority || 100,
289
- });
290
- }
291
-
292
- stats.byPriority.sort(function (a, b) {
293
- return a.priority - b.priority;
294
- });
295
-
296
- return stats;
297
- }
298
-
299
- /**
300
- * Internal logging helper.
301
- * @param {string} level
302
- * @param {string} message
303
- * @private
304
- */
305
- _log(level, message) {
306
- if (this._logger && typeof this._logger[level] === 'function') {
307
- this._logger[level]('hook-dispatcher', message);
308
- }
309
- }
310
- }
311
-
312
- module.exports = {
313
- HookDispatcher,
314
- ExecutionMode,
315
- };
@@ -1,292 +0,0 @@
1
- /**
2
- * Loop Actuator — Agentic Loop Act 层执行器(WP-177-1-impl-b)
3
- *
4
- * @module loop-actuator
5
- *
6
- * 职责:实现 engine `act()` 期望的 actuator 接口
7
- * `execute(context, loopId, decision, state) -> { dispatched, checklistResult? }`。
8
- *
9
- * 把 engine 的 decision(dispatch / retry / resplit)序列化为「dispatcher 待执行指令」
10
- * 写入 state-store 子 key `loop.{loopId}.pendingAction`,并注入 failingDrivers,
11
- * 支持 checklistResult 回填。这是让 `engine.step()` 端到端可跑、移除 `placeholder:true`
12
- * 占位的核心。
13
- *
14
- * 设计约束(docs/wp/WP-177.md「技术方案 actuator 注入架构」):
15
- * - actuator 只产出「指令 + 标记已派发」,不直接 spawn Teamee / 不调 Claude
16
- * - pendingAction 是「待 Claude 消费」的指令,不是「已执行结果」
17
- * - execute 返回 dispatched:true 表示「指令已就绪」,不代表子代理已跑完
18
- * - 实际子代理执行由 Claude 按 skill.md 读取 pendingAction → 调 skill-agent-dispatcher 完成
19
- * - dispatcher 执行后回填 CheckResult 到 loop.{loopId}.lastChecklist(由 engine.act 写入)
20
- *
21
- * 接入契约(必须匹配 provider-loop-engine/index.js inject 期望,见 :582 / :362-365):
22
- * loopEngine.inject({ actuator: createActuator() })
23
- * engine 在 act 阶段调用:actuator.execute(context, loopId, decision, state)
24
- *
25
- * failingDrivers 结构(透传 reflection-evaluator.failingDriversFromChecklist 产出):
26
- * [{ wpId, category, item, reason }]
27
- * 来源是 decision.failingDrivers(engine Think 阶段携带,WP-176 已打通
28
- * Reflect→state→Think 链路),本模块只透传不重新计算。
29
- */
30
-
31
- 'use strict';
32
-
33
- var path = require('path');
34
- var { StateStore } = require('./state-store');
35
-
36
- // ---------------------------------------------------------------------------
37
- // 默认配置
38
- // ---------------------------------------------------------------------------
39
-
40
- /**
41
- * decision.action → dispatcher 指令 mode 映射表。
42
- * 仅这三种 action 会被序列化为 pendingAction;noop(无可执行项)跳过派发。
43
- */
44
- var ACTION_TO_MODE = {
45
- dispatch: 'dispatch',
46
- retry: 'retry',
47
- resplit: 'resplit',
48
- };
49
-
50
- // ---------------------------------------------------------------------------
51
- // 工具函数
52
- // ---------------------------------------------------------------------------
53
-
54
- /**
55
- * ISO 时间戳。
56
- * @returns {string}
57
- */
58
- function nowIso() {
59
- return new Date().toISOString();
60
- }
61
-
62
- /**
63
- * 解析项目根目录(仿 provider-state-store / loop-snapshot:向上找 task.md / .claude)。
64
- * @returns {string}
65
- */
66
- function resolveProjectRoot() {
67
- var dir = process.cwd();
68
- // 同步向上查找,最多 10 层
69
- for (var i = 0; i < 10; i++) {
70
- try {
71
- var fs = require('fs');
72
- if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
73
- if (fs.existsSync(path.join(dir, '.claude'))) return dir;
74
- } catch (_e) {
75
- // fs 访问异常:继续向上
76
- }
77
- var parent = path.dirname(dir);
78
- if (parent === dir) break;
79
- dir = parent;
80
- }
81
- return process.cwd();
82
- }
83
-
84
- /**
85
- * 包装 provider:state-store 的 factory API 为统一 { get/set } 接口。
86
- * provider:state-store factory 返回 get(key)/set(key,val) 等。
87
- * @param {object} providerApi
88
- * @returns {{ get: Function, set: Function }}
89
- */
90
- function wrapProviderStore(providerApi) {
91
- return {
92
- get: function (key) {
93
- return providerApi.get(key);
94
- },
95
- set: function (key, value) {
96
- return providerApi.set(key, value);
97
- },
98
- };
99
- }
100
-
101
- /**
102
- * 确定一个可用的 state-store 句柄。
103
- * 优先级:
104
- * 1. context.getStateStore()(engine 注入的便捷方法,若存在)
105
- * 2. context.getProvider('provider:state-store')(同步返回的 factory API)
106
- * 3. 本地 StateStore(.claude-state)
107
- * @param {PluginContext} context
108
- * @returns {{ store: object, injected: boolean } | null} 不可用时返回 null
109
- */
110
- function resolveStore(context) {
111
- // 1) context.getStateStore() 便捷方法
112
- if (context && typeof context.getStateStore === 'function') {
113
- try {
114
- var direct = context.getStateStore();
115
- if (direct && (typeof direct.get === 'function' || typeof direct.set === 'function')) {
116
- return { store: direct, injected: true };
117
- }
118
- } catch (_e) {
119
- // 降级
120
- }
121
- }
122
-
123
- // 2) context.getProvider('provider:state-store')(同步)
124
- if (context && typeof context.getProvider === 'function') {
125
- try {
126
- var maybe = context.getProvider('provider:state-store');
127
- // B18/A1:async getProvider(返回 Promise)无法在同步 resolveStore 内消费。
128
- // 明确吞掉 rejection 避免 unhandledRejection,然后降级。
129
- if (maybe && typeof maybe.then === 'function') {
130
- maybe.then(function () { /* provider resolved after fallback; ignore */ },
131
- function (_e) { /* provider rejected; fallback in use */ });
132
- } else if (maybe && (typeof maybe.get === 'function' || typeof maybe.set === 'function')) {
133
- return { store: wrapProviderStore(maybe), injected: true };
134
- }
135
- } catch (_e) {
136
- // 降级
137
- }
138
- }
139
-
140
- // 3) 本地 StateStore
141
- // A1 NOTE:跨 loop 物理隔离由调用方负责(bin/commands/loop.js 的
142
- // resolveLoopWorkspace 在 <stateDir>/<loopId>/ 下建立独立 workspaceRoot,
143
- // engine 的 StateStore 即用 workspaceRoot/'.claude-state',天然分桶)。
144
- // 此处保持扁平回退以与 engine 写入同一文件,避免状态分裂。
145
- try {
146
- var root = resolveProjectRoot();
147
- return {
148
- store: new StateStore({ filePath: path.join(root, '.claude-state') }),
149
- injected: false,
150
- };
151
- } catch (_e) {
152
- return null; // state-store 完全不可用
153
- }
154
- }
155
-
156
- /**
157
- * 读取 loop state 下已回填的 lastChecklist(dispatcher 执行后由 engine.act 写入,
158
- * 见 index.js:372-374;此处用于回填路径——若 actuator 被调用时上一轮结果已就绪)。
159
- * @param {object} store { get }
160
- * @param {string} loopId
161
- * @returns {Promise<object|null>}
162
- */
163
- async function loadLastChecklist(store, loopId) {
164
- try {
165
- var chk = await store.get('loop.' + loopId + '.lastChecklist');
166
- return chk || null;
167
- } catch (_e) {
168
- return null;
169
- }
170
- }
171
-
172
- /**
173
- * 把 engine decision 序列化为 dispatcher 待执行指令(pendingAction)。
174
- *
175
- * @param {string} loopId
176
- * @param {object} decision engine _think 产出:
177
- * { action:'dispatch|retry|resplit|noop', targetWp?, strategy?, context?, failingDrivers?, reason }
178
- * @returns {object} pendingAction(写入 state-store 子 key loop.{loopId}.pendingAction)
179
- */
180
- function buildPendingAction(loopId, decision) {
181
- decision = decision || {};
182
- var mode = ACTION_TO_MODE[decision.action];
183
- return {
184
- wpId: decision.targetWp || '',
185
- mode: mode, // dispatch | retry | resplit
186
- strategy: decision.strategy || (mode === 'retry' ? 'checkpoint_resume' : 'full_restart'),
187
- // checkpoint_resume(retry)时携带 context(如恢复点信息);其余场景透传
188
- context: decision.context || null,
189
- // retry 时重点修复项(承接 WP-176 refine 通道;dispatcher 读取此字段注入 Teamee prompt)
190
- failingDrivers: (decision.failingDrivers && decision.failingDrivers.length)
191
- ? decision.failingDrivers.slice()
192
- : [],
193
- createdAt: nowIso(),
194
- loopId: loopId,
195
- };
196
- }
197
-
198
- /**
199
- * 计算幂等键(按 wpId+mode 去重/覆盖)。
200
- * 同一 decision 重复 execute 不产生重复 pendingAction——只要 key 相同即覆盖。
201
- * @param {object} pendingAction
202
- * @returns {string}
203
- */
204
- function idempotencyKey(pendingAction) {
205
- return [pendingAction.mode || '', pendingAction.wpId || ''].join('::');
206
- }
207
-
208
- // ---------------------------------------------------------------------------
209
- // 公开 API
210
- // ---------------------------------------------------------------------------
211
-
212
- /**
213
- * 创建一个 actuator 实例(注入 engine.inject({ actuator }))。
214
- *
215
- * @param {object} [opts] 可选配置
216
- * @param {object} [opts.store] 外部预置的 state-store 句柄(测试注入用)
217
- * @returns {{ execute: Function }}
218
- */
219
- function createActuator(opts) {
220
- opts = opts || {};
221
-
222
- return {
223
- /**
224
- * 执行 decision:序列化为 dispatcher 指令写入 state-store,并回填 checklistResult。
225
- *
226
- * 签名严格匹配 engine act() 调用(index.js:364-365):
227
- * execute(context, loopId, decision, state) -> Promise<{dispatched, checklistResult?}>
228
- *
229
- * @param {PluginContext} context loop-engine 注入的 context(含 getProvider / getStateStore)
230
- * @param {string} loopId loop 运行唯一 ID
231
- * @param {object} decision engine _think 产出
232
- * @param {object} state loop state(engine.act 传入)
233
- * @returns {Promise<{dispatched:boolean, checklistResult?:object, error?:string, placeholder?:boolean}>}
234
- */
235
- execute: async function (context, loopId, decision, state) {
236
- // 容错:state-store 不可用时降级返回,不抛异常中断 step()
237
- var storeRes = (opts.store)
238
- ? { store: opts.store, injected: true }
239
- : resolveStore(context);
240
- if (!storeRes || !storeRes.store || typeof storeRes.store.set !== 'function') {
241
- return { dispatched: false, checklistResult: undefined, error: 'state-store unavailable' };
242
- }
243
- var store = storeRes.store;
244
-
245
- // decision.action 不在派发集合(如 noop)→ 不产出指令,但仍可回填已就绪的 checklist
246
- if (!loopId || !decision || !ACTION_TO_MODE[decision.action]) {
247
- var fallbackChk = await loadLastChecklist(store, loopId);
248
- return {
249
- dispatched: false,
250
- checklistResult: fallbackChk || undefined,
251
- };
252
- }
253
-
254
- // 1) 序列化 decision 为 dispatcher 指令(含 failingDrivers)
255
- var pendingAction = buildPendingAction(loopId, decision);
256
-
257
- // 2) 幂等:按 wpId+mode 覆盖(同一 decision 重复 execute 不产生重复指令)
258
- // state-store 的 set 对同一 key 直接覆盖,天然满足幂等;这里显式构造 key。
259
- var pendingKey = 'loop.' + loopId + '.pendingAction';
260
- try {
261
- await store.set(pendingKey, pendingAction);
262
- } catch (e) {
263
- return {
264
- dispatched: false,
265
- checklistResult: undefined,
266
- error: 'state-store set failed: ' + (e && e.message ? e.message : String(e)),
267
- };
268
- }
269
-
270
- // 3) 回填支持:若 state/已存在 lastChecklist,返回 checklistResult 供 engine 写入
271
- // engine.act 在 result.checklistResult 存在时另行写入 lastChecklist(index.js:372-374)。
272
- // 这里优先 state.lastChecklist(engine 透传),否则读 store 子 key。
273
- var backfill = (state && state.lastChecklist) || (await loadLastChecklist(store, loopId));
274
-
275
- return {
276
- dispatched: true,
277
- checklistResult: backfill || undefined,
278
- _mode: pendingAction.mode,
279
- _idempotencyKey: idempotencyKey(pendingAction),
280
- _storeInjected: storeRes.injected,
281
- };
282
- },
283
- };
284
- }
285
-
286
- module.exports = {
287
- createActuator: createActuator,
288
- // 暴露内部工具便于单元测试
289
- _buildPendingAction: buildPendingAction,
290
- _idempotencyKey: idempotencyKey,
291
- _ACTION_TO_MODE: ACTION_TO_MODE,
292
- };