doukui 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1398 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1397 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +572 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +390 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-reader.js +763 -0
  118. package/plugins/runtime/plugin-loader.js +798 -0
  119. package/plugins/runtime/plugin-trust.js +182 -0
  120. package/plugins/runtime/plugin-validator.js +491 -0
  121. package/plugins/runtime/provider-failover.js +114 -0
  122. package/plugins/runtime/provider-resolver.js +342 -0
  123. package/plugins/runtime/reflection-evaluator.js +540 -0
  124. package/plugins/runtime/resolve-plugin-path.js +297 -0
  125. package/plugins/runtime/safe-path.js +119 -0
  126. package/plugins/runtime/sandbox-context.js +235 -0
  127. package/plugins/runtime/sandbox-manager.js +609 -0
  128. package/plugins/runtime/sandbox-worker.js +215 -0
  129. package/plugins/runtime/settings-merger.js +172 -0
  130. package/plugins/runtime/state-store.js +527 -0
  131. package/plugins/runtime/team-cleanup.js +497 -0
  132. package/plugins/runtime/text-tokenize.js +25 -0
  133. package/plugins/runtime/validator-pipeline.js +475 -0
  134. package/plugins/runtime/yaml-parser.js +692 -0
  135. package/templates/harness-config.yaml +388 -0
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * loop-server command — 全局 coordinator 守护进程 CLI(WP-190-impl)
5
+ *
6
+ * @module bin/commands/loop-server
7
+ *
8
+ * 把 loop-server-core(纯逻辑 + 文件 IO)包装为 CLI 子命令:
9
+ * doukui loop-server start [--state-dir=X] [--interval=N] [--no-circuit]
10
+ * doukui loop-server stop [--state-dir=X] 停止守护进程(跨平台 kill)
11
+ * doukui loop-server status [--state-dir=X]
12
+ * doukui loop-server list [--state-dir=X] (status 别名)
13
+ * doukui loop-server abort <loop-id> [--state-dir=X] [--reason=...]
14
+ *
15
+ * stop 实现说明(WP-191-1-impl-c):
16
+ * Windows 后台守护进程(detached)收不到 Ctrl+C,必须靠 PID 文件 + taskkill 停。
17
+ * start 写 PID 文件({stateDir}/loop-server.pid),stop 读 PID 后:
18
+ * - Windows:child_process.execSync('taskkill /PID <pid> /F /T')
19
+ * - Unix:process.kill(pid, 'SIGTERM')
20
+ * 降级(不变量 #4):PID 文件缺失 / 进程已死(ESRCH)→ 友好提示 + 清残留 PID + exit 0。
21
+ *
22
+ * 职责边界(docs/plan/agentic-loop-node-driver-m4m5.md WP-190,硬约束):
23
+ * - 只读聚合各 loop 状态(不写各 loop 的 .claude-state,硬约束 #7);
24
+ * 熔断只写 directive.json sidecar(单向通道,规避多进程并发写)。
25
+ * - 复用 loop-server-core 的全部逻辑,本文件仅做参数解析 + 轮询循环 + 输出。
26
+ * - 回退安全(硬约束 #5):不开 coordinator 时单 driver 仍独立跑。
27
+ *
28
+ * 合规边界(docs/wp/WP-188-research.md §4):glm 多 loop 并行仅限"订阅人本人本机 +
29
+ * claude CLI 客户端"场景,禁止跨机共享 API Key。本守护进程的额度池仅做本机单订阅人
30
+ * 的额度统筹,不涉及多账号。
31
+ */
32
+
33
+ var path = require('path');
34
+ var childProcess = require('child_process');
35
+ var core = require('../../plugins/runtime/loop-server-core');
36
+ var safePath = require('../../plugins/runtime/safe-path');
37
+
38
+ var IS_WIN = process.platform === 'win32';
39
+
40
+ module.exports = {
41
+ name: 'loop-server',
42
+ description: 'Global loop coordinator daemon (aggregate multi-loop view, quota pool, circuit break)',
43
+
44
+ /**
45
+ * Execute the loop-server command.
46
+ * @public
47
+ * @param {object} ctx CLI context(bin/context.js createContext 产出)
48
+ */
49
+ execute: async function (ctx) {
50
+ var log = (ctx && typeof ctx.log === 'function') ? ctx.log : function (m) { console.log(m); };
51
+ var argv = (ctx.argv || []).slice();
52
+
53
+ var subcommand = argv[0] && argv[0].indexOf('-') !== 0 ? argv[0] : 'status';
54
+ var rest = subcommand === argv[0] ? argv.slice(1) : argv;
55
+
56
+ // 解析公共 flag
57
+ var stateDir = '.doukui-state';
58
+ var intervalMs = 5000;
59
+ var noCircuit = false;
60
+ var reason = null;
61
+ var abortLoopId = null;
62
+ for (var i = 0; i < rest.length; i++) {
63
+ var a = rest[i];
64
+ if (a.indexOf('--state-dir=') === 0) stateDir = a.slice('--state-dir='.length);
65
+ else if (a.indexOf('--interval=') === 0) intervalMs = parseInt(a.slice('--interval='.length), 10);
66
+ else if (a === '--no-circuit') noCircuit = true;
67
+ else if (a.indexOf('--reason=') === 0) reason = a.slice('--reason='.length);
68
+ else if (a.indexOf('-') !== 0) abortLoopId = a; // abort 子命令的目标 loopId
69
+ }
70
+
71
+ var projectRoot = ctx.targetRoot || process.cwd();
72
+ var absStateDir = path.isAbsolute(stateDir) ? stateDir : path.resolve(projectRoot, stateDir);
73
+
74
+ switch (subcommand) {
75
+ case 'start':
76
+ await runDaemon(ctx, log, absStateDir, intervalMs, !noCircuit);
77
+ break;
78
+ case 'stop':
79
+ await runStop(ctx, log, absStateDir);
80
+ break;
81
+ case 'status':
82
+ case 'list':
83
+ await runSnapshot(ctx, log, absStateDir);
84
+ break;
85
+ case 'abort':
86
+ await runAbort(ctx, log, absStateDir, abortLoopId, reason);
87
+ break;
88
+ default:
89
+ log(ctx.colorize('Unknown subcommand: ' + subcommand, 'red'));
90
+ log('Usage: doukui loop-server <start|stop|status|list|abort> [options]');
91
+ log(' start [--state-dir=X] [--interval=N] [--no-circuit] 轮询守护进程');
92
+ log(' stop [--state-dir=X] 停止守护进程(跨平台 kill)');
93
+ log(' status [--state-dir=X] 单次全局快照');
94
+ log(' list status 别名');
95
+ log(' abort <loop-id> [--state-dir=X] [--reason=...] 下发熔断指令');
96
+ ctx.exit(2);
97
+ }
98
+ },
99
+
100
+ // 暴露供测试
101
+ _core: core,
102
+ };
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // status / list:单次快照
106
+ // ---------------------------------------------------------------------------
107
+
108
+ async function runSnapshot(ctx, log, stateDir) {
109
+ try {
110
+ var view = await core.aggregateGlobalView(stateDir);
111
+ var pool = core.applyQuotaPool(view);
112
+ log(core.formatGlobalView(view, pool));
113
+ ctx.exit(0);
114
+ } catch (e) {
115
+ log(ctx.colorize('Error: ' + (e && e.message ? e.message : String(e)), 'red'));
116
+ ctx.exit(1);
117
+ }
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // abort:下发熔断指令到指定 loop
122
+ // ---------------------------------------------------------------------------
123
+
124
+ async function runAbort(ctx, log, stateDir, loopId, reason) {
125
+ if (!loopId) {
126
+ log(ctx.colorize('Error: abort 需要指定 loop-id', 'red'));
127
+ log('Usage: doukui loop-server abort <loop-id> [--reason=...]');
128
+ ctx.exit(2);
129
+ return;
130
+ }
131
+ // S4:校验 loopId 字符集,防止 writeAbortDirective 用 path.join 逃逸出 stateDir
132
+ var v = safePath.validateSafeName(loopId);
133
+ if (!v.ok) {
134
+ log(ctx.colorize('Error: 非法 loop-id (' + v.reason + '): ' + loopId, 'red'));
135
+ log('仅允许字母/数字/_/-,1-64 字符。');
136
+ ctx.exit(2);
137
+ return;
138
+ }
139
+ try {
140
+ var p = core.writeAbortDirective(stateDir, loopId, reason);
141
+ log(ctx.colorize('✓ 已下发熔断指令', 'green'));
142
+ log(' loopId: ' + loopId);
143
+ log(' directive: ' + p);
144
+ log(' reason: ' + (reason || 'coordinator 全局熔断'));
145
+ log(' (driver 下一轮 step 后将读取并优雅退出)');
146
+ ctx.exit(0);
147
+ } catch (e) {
148
+ log(ctx.colorize('Error: ' + (e && e.message ? e.message : String(e)), 'red'));
149
+ ctx.exit(1);
150
+ }
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // stop:跨平台停止守护进程(WP-191-1-impl-c)
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /**
158
+ * 停止守护进程:读 PID 文件 → 跨平台 kill → 清理 PID 文件。
159
+ *
160
+ * 降级(不变量 #4 — stop 失败/守护不存在不阻断主流程):
161
+ * - PID 文件不存在(守护未启动)→ 友好提示 + exit 0
162
+ * - 进程已死(ESRCH)→ 视为已停止,清理残留 PID 文件 + exit 0
163
+ * - kill 抛其它异常 → 报错但清理 PID 文件 + exit 1
164
+ *
165
+ * 跨平台 kill:
166
+ * - Windows:taskkill /PID <pid> /F /T(/T 连带子进程;/F 强制)。
167
+ * 用 execSync 同步执行,taskkill 不存在时 execSync 抛错走降级。
168
+ * - Unix:process.kill(pid, 'SIGTERM'),配合守护进程的 SIGTERM handler 优雅退出。
169
+ *
170
+ * @param {object} ctx
171
+ * @param {Function} log
172
+ * @param {string} stateDir
173
+ */
174
+ async function runStop(ctx, log, stateDir) {
175
+ var pidInfo = core.readPidFile(stateDir);
176
+ if (!pidInfo) {
177
+ // 降级:PID 文件缺失视为守护未运行
178
+ log(ctx.colorize('未发现 loop-server 守护进程(无 PID 文件)', 'yellow'));
179
+ log(' state-dir: ' + stateDir);
180
+ ctx.exit(0);
181
+ return;
182
+ }
183
+
184
+ var pid = pidInfo.pid;
185
+ try {
186
+ killDaemonPid(pid);
187
+ log(ctx.colorize('✓ 已停止 loop-server 守护进程', 'green'));
188
+ log(' pid: ' + pid);
189
+ log(' state-dir: ' + stateDir);
190
+ } catch (e) {
191
+ var msg = e && e.message ? e.message : String(e);
192
+ // ESRCH(Unix process.kill)/ taskkill 退出码 128(进程不存在)→ 已死,降级成功
193
+ var alreadyDead = isAlreadyDeadError(e);
194
+ if (alreadyDead) {
195
+ log(ctx.colorize('loop-server 守护进程 (pid=' + pid + ') 已不在运行,清理残留 PID 文件', 'yellow'));
196
+ } else {
197
+ log(ctx.colorize('停止守护进程失败 (pid=' + pid + '): ' + msg, 'red'));
198
+ }
199
+ } finally {
200
+ // 无论 kill 成功/降级,都清理 PID 文件(守护若存活,其退出 handler 也会清,幂等)
201
+ core.clearPidFile(stateDir);
202
+ }
203
+
204
+ // 已死或成功都 exit 0;非"已死"的真异常已在上面打印,仍 exit 0(降级,不阻断主流程)
205
+ ctx.exit(0);
206
+ }
207
+
208
+ /**
209
+ * 跨平台 kill 守护进程 PID。
210
+ * @param {number} pid
211
+ * @throws 进程不存在(ESRCH / taskkill 报进程不存在)或其它 kill 错误
212
+ */
213
+ function killDaemonPid(pid) {
214
+ if (IS_WIN) {
215
+ // /F 强制终止;/T 连带子进程树。taskkill 对不存在的 PID 返回非零退出码(通常 128)。
216
+ childProcess.execSync('taskkill /PID ' + pid + ' /F /T', { stdio: 'ignore' });
217
+ } else {
218
+ process.kill(pid, 'SIGTERM');
219
+ }
220
+ }
221
+
222
+ /**
223
+ * 判断 kill 异常是否表示"进程已不存在"(已死),用于降级为友好提示。
224
+ * @param {Error} e
225
+ * @returns {boolean}
226
+ */
227
+ function isAlreadyDeadError(e) {
228
+ if (!e) return false;
229
+ // Unix process.kill 进程不存在抛 ESPIPE? 不:抛系统错误,code 'ESRCH'
230
+ if (e.code === 'ESRCH') return true;
231
+ var msg = e.message || '';
232
+ // Windows taskkill 进程不存在:exit code 128 + message 含 "not found" / "找不到"
233
+ if (/\b(128|ESRCH)\b/.test(msg)) return true;
234
+ if (/not\s+found|no\s+such|不存在|找不到/i.test(msg)) return true;
235
+ return false;
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // start:轮询守护进程
240
+ // ---------------------------------------------------------------------------
241
+
242
+ /**
243
+ * 轮询守护:每 intervalMs 聚合一次全局视图,打印 + 执行熔断策略。
244
+ * 熔断策略(docs/plan/agentic-loop-node-driver-m4m5.md WP-190):
245
+ * 1. 任一 loop circuit_broken/aborted → 对其它仍活跃的 loop 下发 abort(全局回退)
246
+ * 2. 某 provider 额度 ratio 超阈值 → 对该 provider 的活跃 loop 下发 abort(额度兜底)
247
+ * 3. --no-circuit 关闭自动熔断,仅观察(dry-run 守护)
248
+ * Ctrl+C / SIGINT 优雅退出。
249
+ */
250
+ async function runDaemon(ctx, log, stateDir, intervalMs, enableCircuit) {
251
+ log(ctx.colorize('=== Loop Coordinator Daemon ===', 'cyan'));
252
+ log('state-dir: ' + stateDir);
253
+ log('interval: ' + intervalMs + 'ms');
254
+ log('circuit: ' + (enableCircuit ? 'enabled' : 'disabled (--no-circuit)'));
255
+ log('按 Ctrl+C 退出,或用 `doukui loop-server stop` 跨平台停止');
256
+ log('');
257
+
258
+ // 写守护进程 PID 文件(WP-191-1-impl-c:供 stop 子命令跨平台 kill 用)
259
+ var pidFile;
260
+ try {
261
+ pidFile = core.writePidFile(stateDir, process.pid);
262
+ log('pid file: ' + pidFile + ' (pid=' + process.pid + ')');
263
+ } catch (e) {
264
+ // 降级(不变量 #4):PID 文件写失败不阻断守护启动,仅提示(此时 stop 不可用)
265
+ log(ctx.colorize('warn: 写 PID 文件失败,stop 子命令将不可用: ' +
266
+ (e && e.message ? e.message : String(e)), 'yellow'));
267
+ }
268
+
269
+ // 守护退出时清理自身 PID 文件(无论 SIGINT/SIGTERM/异常退出路径都应清理,幂等)
270
+ var cleanupPid = function () {
271
+ core.clearPidFile(stateDir);
272
+ };
273
+
274
+ var running = true;
275
+ var onExit = function () {
276
+ running = false;
277
+ };
278
+ process.on('SIGINT', onExit);
279
+ process.on('SIGTERM', onExit);
280
+ process.on('exit', cleanupPid);
281
+
282
+ // 首次立即跑一轮
283
+ await tick();
284
+ if (!running) {
285
+ log(ctx.colorize('coordinator 已停止', 'yellow'));
286
+ process.removeListener('SIGINT', onExit);
287
+ process.removeListener('SIGTERM', onExit);
288
+ process.removeListener('exit', cleanupPid);
289
+ cleanupPid();
290
+ ctx.exit(0);
291
+ return;
292
+ }
293
+
294
+ var timer = setInterval(function () {
295
+ tick().catch(function (e) {
296
+ log(ctx.colorize('tick error: ' + (e && e.message ? e.message : String(e)), 'red'));
297
+ });
298
+ }, intervalMs);
299
+ // setInterval 不阻止进程退出,但守护进程靠它保持存活;SIGINT 时 clear + exit
300
+
301
+ // 轮询保活:检测 running=false 后清理退出
302
+ var watchdog = setInterval(function () {
303
+ if (!running) {
304
+ clearInterval(timer);
305
+ clearInterval(watchdog);
306
+ log(ctx.colorize('coordinator 已停止', 'yellow'));
307
+ process.removeListener('SIGINT', onExit);
308
+ process.removeListener('SIGTERM', onExit);
309
+ process.removeListener('exit', cleanupPid);
310
+ cleanupPid();
311
+ ctx.exit(0);
312
+ }
313
+ }, 500);
314
+
315
+ async function tick() {
316
+ var view, pool;
317
+ try {
318
+ view = await core.aggregateGlobalView(stateDir);
319
+ pool = core.applyQuotaPool(view);
320
+ } catch (e) {
321
+ log(ctx.colorize('聚合失败: ' + (e && e.message ? e.message : String(e)), 'red'));
322
+ return;
323
+ }
324
+ var stamp = new Date().toISOString().slice(11, 19);
325
+ var g = view.global || {};
326
+ log('[' + stamp + '] ' + (g.verdict || '?') +
327
+ ' | loops=' + (view.total_loops || 0) +
328
+ ' (achieved=' + g.achievedCount + ' running=' + g.runningCount +
329
+ ' circuit=' + g.circuitCount + ' failed=' + g.failedCount + ' dc=' + g.disconnectedCount + ')');
330
+
331
+ if (!enableCircuit) return;
332
+
333
+ // 熔断策略 1:全局回退(任一 circuit_broken → 其它活跃 loop 也熔断)
334
+ var circuitTargets = core.selectLoopsForGlobalCircuitBreak(view);
335
+ for (var i = 0; i < circuitTargets.length; i++) {
336
+ core.writeAbortDirective(stateDir, circuitTargets[i], 'global_circuit_break: 伴生 loop 熔断');
337
+ log(ctx.colorize(' ⚠ 全局回退:对 ' + circuitTargets[i] + ' 下发熔断', 'yellow'));
338
+ }
339
+
340
+ // 熔断策略 2:额度兜底(provider 超阈值 → 该 provider 活跃 loop 熔断)
341
+ var quotaTargets = core.selectLoopsForQuotaExhaustion(view, pool);
342
+ for (var j = 0; j < quotaTargets.length; j++) {
343
+ var lid = quotaTargets[j];
344
+ var provider = (view.providers && view.providers[lid]) || '?';
345
+ core.writeAbortDirective(stateDir, lid, 'quota_exhausted: provider ' + provider + ' 额度触顶');
346
+ log(ctx.colorize(' ⚠ 额度兜底:对 ' + lid + ' (' + provider + ') 下发熔断', 'yellow'));
347
+ }
348
+
349
+ // WP-191-1-impl-b:清理已消费的熔断指令。对已终态的 loop 兜底删除残留 directive.json
350
+ // (driver 端 applyDirective 成功后已自行删除,本步兜底 driver crash/kill -9 来不及
351
+ // 删除的残留 + 防 `--loop-id` 恢复时二次熔断)。只清终态 loop,不影响活跃 loop 待消费指令。
352
+ var cleaned = core.cleanupConsumedDirectives(stateDir, view);
353
+ for (var k = 0; k < cleaned.length; k++) {
354
+ log(ctx.colorize(' · 清理终态 loop 残留熔断指令: ' + cleaned[k], 'gray'));
355
+ }
356
+ }
357
+ }