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.
- 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 +1398 -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 +1397 -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 +572 -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 +390 -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-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 +540 -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/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 +388 -0
|
@@ -0,0 +1,754 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { spawn } = require('child_process');
|
|
6
|
+
const config = require('./lib/config');
|
|
7
|
+
const Logger = require('./lib/logger');
|
|
8
|
+
const StateFileManager = require('./lib/state-files');
|
|
9
|
+
const ProcessManager = require('./lib/process-manager');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 帮助信息
|
|
13
|
+
*/
|
|
14
|
+
const HELP_TEXT = `
|
|
15
|
+
Watchdog Daemon — Claude Code Agent Teams 守护进程
|
|
16
|
+
|
|
17
|
+
用法:
|
|
18
|
+
node watchdog.js <command> [options]
|
|
19
|
+
|
|
20
|
+
命令:
|
|
21
|
+
init 初始化守护进程配置目录
|
|
22
|
+
start 启动守护进程
|
|
23
|
+
status 查看守护进程状态
|
|
24
|
+
restart 手动触发任务重启
|
|
25
|
+
pause 暂停守护进程检测
|
|
26
|
+
stop 停止守护进程
|
|
27
|
+
|
|
28
|
+
选项:
|
|
29
|
+
--config <path> 指定配置文件路径 (默认: .claude-daemon/daemon-config.json)
|
|
30
|
+
--help, -h 显示帮助信息
|
|
31
|
+
|
|
32
|
+
start 命令选项:
|
|
33
|
+
--foreground 前台模式运行
|
|
34
|
+
--background 后台模式运行 (默认)
|
|
35
|
+
|
|
36
|
+
restart 命令选项:
|
|
37
|
+
--task <id> 指定要重启的任务 ID
|
|
38
|
+
|
|
39
|
+
pause 命令选项:
|
|
40
|
+
--resume 恢复守护进程检测
|
|
41
|
+
|
|
42
|
+
示例:
|
|
43
|
+
node watchdog.js init
|
|
44
|
+
node watchdog.js start --foreground
|
|
45
|
+
node watchdog.js status
|
|
46
|
+
node watchdog.js restart --task 3
|
|
47
|
+
node watchdog.js stop
|
|
48
|
+
`;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 解析命令行参数
|
|
52
|
+
* @param {string[]} args - process.argv.slice(2)
|
|
53
|
+
* @returns {Object} 解析结果 { command, options, args }
|
|
54
|
+
*/
|
|
55
|
+
function parseArgs(args) {
|
|
56
|
+
const result = {
|
|
57
|
+
command: null,
|
|
58
|
+
options: {
|
|
59
|
+
config: '.claude-daemon/daemon-config.json'
|
|
60
|
+
},
|
|
61
|
+
args: {}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
let i = 0;
|
|
65
|
+
|
|
66
|
+
while (i < args.length) {
|
|
67
|
+
const arg = args[i];
|
|
68
|
+
|
|
69
|
+
// 全局选项
|
|
70
|
+
if (arg === '--help' || arg === '-h') {
|
|
71
|
+
result.command = 'help';
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (arg === '--config') {
|
|
76
|
+
result.options.config = args[++i];
|
|
77
|
+
i++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// start 命令选项
|
|
82
|
+
if (arg === '--foreground' || arg === '--background') {
|
|
83
|
+
result.args.mode = arg.replace('--', '');
|
|
84
|
+
i++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// restart 命令选项
|
|
89
|
+
if (arg === '--task') {
|
|
90
|
+
result.args.task = args[++i];
|
|
91
|
+
i++;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// pause 命令选项
|
|
96
|
+
if (arg === '--resume') {
|
|
97
|
+
result.args.resume = true;
|
|
98
|
+
i++;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 子命令
|
|
103
|
+
if (!arg.startsWith('--')) {
|
|
104
|
+
result.command = arg;
|
|
105
|
+
i++;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 未知选项
|
|
110
|
+
console.warn(`警告: 未知选项 ${arg}`);
|
|
111
|
+
i++;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 执行 init 命令
|
|
119
|
+
*/
|
|
120
|
+
function cmdInit(options) {
|
|
121
|
+
const daemonDir = '.claude-daemon';
|
|
122
|
+
const tasksDir = path.join(daemonDir, 'tasks');
|
|
123
|
+
const configFile = path.join(daemonDir, 'daemon-config.json');
|
|
124
|
+
const templatePath = config.getTemplatePath();
|
|
125
|
+
|
|
126
|
+
// 检查是否已初始化
|
|
127
|
+
if (fs.existsSync(daemonDir)) {
|
|
128
|
+
console.log(`目录 ${daemonDir} 已存在,跳过创建`);
|
|
129
|
+
} else {
|
|
130
|
+
fs.mkdirSync(tasksDir, { recursive: true });
|
|
131
|
+
console.log(`创建目录: ${daemonDir}/`);
|
|
132
|
+
console.log(`创建目录: ${tasksDir}/`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 检查配置文件是否已存在
|
|
136
|
+
if (fs.existsSync(configFile)) {
|
|
137
|
+
console.log(`配置文件 ${configFile} 已存在,跳过创建`);
|
|
138
|
+
} else {
|
|
139
|
+
const template = fs.readFileSync(templatePath, 'utf8');
|
|
140
|
+
fs.writeFileSync(configFile, template, 'utf8');
|
|
141
|
+
console.log(`创建配置文件: ${configFile}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
console.log('\n初始化完成!');
|
|
145
|
+
console.log(`配置文件: ${configFile}`);
|
|
146
|
+
console.log('可以运行 "node watchdog.js start" 启动守护进程');
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 执行 start 命令
|
|
152
|
+
*/
|
|
153
|
+
async function cmdStart(options, args) {
|
|
154
|
+
// 加载配置
|
|
155
|
+
const loadedConfig = config.loadConfig(options.config);
|
|
156
|
+
const mode = args.mode || loadedConfig.daemon.mode;
|
|
157
|
+
loadedConfig.daemon.mode = process.env.WATCHDOG_MODE || mode;
|
|
158
|
+
|
|
159
|
+
// 创建状态管理器
|
|
160
|
+
const stateManager = new StateFileManager({
|
|
161
|
+
heartbeatDir: loadedConfig.heartbeat_dir
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// 检查是否已有实例在运行
|
|
165
|
+
const existingStatus = stateManager.readDaemonStatus();
|
|
166
|
+
if (existingStatus && existingStatus.pid) {
|
|
167
|
+
const procManager = new ProcessManager({
|
|
168
|
+
killTimeoutSec: loadedConfig.process.kill_timeout_sec
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
if (procManager.isProcessAlive(existingStatus.pid)) {
|
|
172
|
+
console.error(`错误: 守护进程已在运行 (PID: ${existingStatus.pid})`);
|
|
173
|
+
console.error('如需重启,请先运行 "node watchdog.js stop"');
|
|
174
|
+
return 1;
|
|
175
|
+
} else {
|
|
176
|
+
// PID 文件存在但进程已不存在,清理旧状态
|
|
177
|
+
console.log('检测到旧的守护进程状态文件,清理中...');
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// 前台模式
|
|
182
|
+
if (mode === 'foreground') {
|
|
183
|
+
console.log('启动守护进程(前台模式)...');
|
|
184
|
+
console.log('配置文件:', options.config);
|
|
185
|
+
|
|
186
|
+
// 创建前台日志器
|
|
187
|
+
const logger = new Logger({
|
|
188
|
+
logDir: loadedConfig.heartbeat_dir,
|
|
189
|
+
level: loadedConfig.logging.level,
|
|
190
|
+
maxFileSizeMB: loadedConfig.logging.max_file_size_mb,
|
|
191
|
+
maxFiles: loadedConfig.logging.max_files,
|
|
192
|
+
foreground: true
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// 导入并运行 Watchdog
|
|
196
|
+
const { Watchdog } = require('./lib/daemon');
|
|
197
|
+
const watchdog = new Watchdog(loadedConfig, logger);
|
|
198
|
+
|
|
199
|
+
// 处理退出信号
|
|
200
|
+
process.on('SIGINT', () => {
|
|
201
|
+
console.log('\n收到 SIGINT,正在停止守护进程...');
|
|
202
|
+
watchdog.stop();
|
|
203
|
+
process.exit(0);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
process.on('SIGTERM', () => {
|
|
207
|
+
console.log('\n收到 SIGTERM,正在停止守护进程...');
|
|
208
|
+
watchdog.stop();
|
|
209
|
+
process.exit(0);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
// 初始化并启动
|
|
213
|
+
watchdog.init();
|
|
214
|
+
watchdog.start();
|
|
215
|
+
|
|
216
|
+
// 保持进程运行
|
|
217
|
+
console.log('守护进程已启动,按 Ctrl+C 退出');
|
|
218
|
+
return new Promise(() => {});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// 后台模式
|
|
222
|
+
console.log('启动守护进程(后台模式)...');
|
|
223
|
+
|
|
224
|
+
// 日志文件路径
|
|
225
|
+
const logDir = path.resolve(loadedConfig.heartbeat_dir);
|
|
226
|
+
const stdoutLog = path.join(logDir, 'daemon-stdout.log');
|
|
227
|
+
const stderrLog = path.join(logDir, 'daemon-stderr.log');
|
|
228
|
+
|
|
229
|
+
// 确保 log 目录存在
|
|
230
|
+
if (!fs.existsSync(logDir)) {
|
|
231
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// 打开文件描述符用于子进程输出重定向
|
|
235
|
+
const stdoutFd = fs.openSync(stdoutLog, 'a');
|
|
236
|
+
const stderrFd = fs.openSync(stderrLog, 'a');
|
|
237
|
+
|
|
238
|
+
// 创建 detached 子进程,使用 fd 直接重定向输出
|
|
239
|
+
const child = spawn(process.argv[0], [process.argv[1], 'start', '--config', options.config, '--foreground'], {
|
|
240
|
+
detached: true,
|
|
241
|
+
stdio: ['ignore', stdoutFd, stderrFd],
|
|
242
|
+
cwd: process.cwd(),
|
|
243
|
+
env: { ...process.env, WATCHDOG_MODE: 'background' }
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
// 取消父进程引用,使子进程成为守护进程
|
|
247
|
+
child.unref();
|
|
248
|
+
|
|
249
|
+
// 关闭父进程中的文件描述符(子进程已继承)
|
|
250
|
+
fs.closeSync(stdoutFd);
|
|
251
|
+
fs.closeSync(stderrFd);
|
|
252
|
+
|
|
253
|
+
// 轮询等待子进程自行写入状态文件(最多 3 秒)
|
|
254
|
+
const procManager = new ProcessManager({
|
|
255
|
+
killTimeoutSec: loadedConfig.process.kill_timeout_sec
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
const maxWaitMs = 3000;
|
|
259
|
+
const pollStart = Date.now();
|
|
260
|
+
let childStarted = false;
|
|
261
|
+
|
|
262
|
+
while (Date.now() - pollStart < maxWaitMs) {
|
|
263
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
264
|
+
const childStatus = stateManager.readDaemonStatus();
|
|
265
|
+
if (childStatus && childStatus.pid === child.pid && childStatus.state === 'running') {
|
|
266
|
+
childStarted = true;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (childStarted) {
|
|
272
|
+
console.log(`守护进程已启动 (PID: ${child.pid})`);
|
|
273
|
+
console.log(`标准输出: ${stdoutLog}`);
|
|
274
|
+
console.log(`错误输出: ${stderrLog}`);
|
|
275
|
+
return 0;
|
|
276
|
+
} else if (procManager.isProcessAlive(child.pid)) {
|
|
277
|
+
console.log(`守护进程已启动 (PID: ${child.pid})`);
|
|
278
|
+
console.log(`标准输出: ${stdoutLog}`);
|
|
279
|
+
console.log(`错误输出: ${stderrLog}`);
|
|
280
|
+
return 0;
|
|
281
|
+
} else {
|
|
282
|
+
console.error('守护进程启动失败,请查看日志文件');
|
|
283
|
+
return 1;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 执行 status 命令
|
|
289
|
+
*/
|
|
290
|
+
function cmdStatus(options) {
|
|
291
|
+
// 加载配置
|
|
292
|
+
const loadedConfig = config.loadConfig(options.config);
|
|
293
|
+
|
|
294
|
+
// 创建状态管理器
|
|
295
|
+
const stateManager = new StateFileManager({
|
|
296
|
+
heartbeatDir: loadedConfig.heartbeat_dir
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// 创建进程管理器
|
|
300
|
+
const procManager = new ProcessManager({
|
|
301
|
+
killTimeoutSec: loadedConfig.process.kill_timeout_sec
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
// 读取守护进程状态
|
|
305
|
+
const daemonStatus = stateManager.readDaemonStatus();
|
|
306
|
+
|
|
307
|
+
if (!daemonStatus) {
|
|
308
|
+
console.log('守护进程未运行');
|
|
309
|
+
console.log('提示: 运行 "node watchdog.js start" 启动守护进程');
|
|
310
|
+
return 0;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// 检查进程是否存活
|
|
314
|
+
const isAlive = procManager.isProcessAlive(daemonStatus.pid);
|
|
315
|
+
|
|
316
|
+
// 输出守护进程信息
|
|
317
|
+
console.log('\n' + '='.repeat(50));
|
|
318
|
+
console.log('守护进程状态');
|
|
319
|
+
console.log('='.repeat(50));
|
|
320
|
+
console.log(`PID: ${daemonStatus.pid}`);
|
|
321
|
+
console.log(`模式: ${daemonStatus.mode}`);
|
|
322
|
+
console.log(`状态: ${_formatStateStatus(daemonStatus.state, isAlive)}`);
|
|
323
|
+
console.log(`健康: ${_formatHealthStatus(daemonStatus.health)}`);
|
|
324
|
+
console.log(`启动时间: ${daemonStatus.started_at ? new Date(daemonStatus.started_at).toLocaleString('zh-CN') : '未知'}`);
|
|
325
|
+
console.log(`最后检查: ${daemonStatus.last_check ? new Date(daemonStatus.last_check).toLocaleString('zh-CN') : '未知'}`);
|
|
326
|
+
|
|
327
|
+
// 会话信息
|
|
328
|
+
if (daemonStatus.session) {
|
|
329
|
+
const session = daemonStatus.session;
|
|
330
|
+
console.log('\n会话信息:');
|
|
331
|
+
console.log(` 会话 ID: ${session.session_id || '未知'}`);
|
|
332
|
+
console.log(` 状态: ${session.status || '未知'}`);
|
|
333
|
+
console.log(` 迭代次数: ${session.heartbeat_iteration || 0}`);
|
|
334
|
+
console.log(` 任务统计:`);
|
|
335
|
+
console.log(` 总计: ${session.total_tasks || 0}`);
|
|
336
|
+
console.log(` 已完成: ${session.completed || 0}`);
|
|
337
|
+
console.log(` 进行中: ${session.in_progress || 0}`);
|
|
338
|
+
console.log(` 待处理: ${session.pending || 0}`);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 任务状态表格
|
|
342
|
+
const tasks = stateManager.readAllTaskFiles();
|
|
343
|
+
if (tasks.length > 0) {
|
|
344
|
+
console.log('\n任务状态:');
|
|
345
|
+
console.log(' ID | 状态 | 工作包 | 最后更新');
|
|
346
|
+
console.log(' ' + '-'.repeat(55));
|
|
347
|
+
for (const task of tasks) {
|
|
348
|
+
const status = _formatTaskStatus(task.status);
|
|
349
|
+
const wpId = task.wp_id || 'N/A';
|
|
350
|
+
const lastUpdate = task.last_update
|
|
351
|
+
? new Date(task.last_update).toLocaleString('zh-CN', { hour12: false })
|
|
352
|
+
: '未知';
|
|
353
|
+
console.log(` ${task.task_id.padEnd(5)} | ${_visiblePadEnd(status, 10)} | ${wpId.padEnd(9)} | ${lastUpdate}`);
|
|
354
|
+
}
|
|
355
|
+
} else {
|
|
356
|
+
console.log('\n任务状态: 无任务');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// 重启历史
|
|
360
|
+
if (daemonStatus.restarts && daemonStatus.restarts.length > 0) {
|
|
361
|
+
console.log('\n重启历史:');
|
|
362
|
+
console.log(' 任务 ID | 次数 | 策略 | 最后重启时间');
|
|
363
|
+
console.log(' ' + '-'.repeat(65));
|
|
364
|
+
for (const restart of daemonStatus.restarts) {
|
|
365
|
+
const taskId = String(restart.task_id).padEnd(7);
|
|
366
|
+
const attempts = String(restart.attempts).padEnd(4);
|
|
367
|
+
const strategy = (restart.strategy || 'unknown').padEnd(18);
|
|
368
|
+
const lastTime = restart.last_restart_at
|
|
369
|
+
? new Date(restart.last_restart_at).toLocaleString('zh-CN', { hour12: false })
|
|
370
|
+
: '未知';
|
|
371
|
+
console.log(` ${taskId} | ${attempts} | ${strategy} | ${lastTime}`);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// 熔断状态
|
|
376
|
+
if (daemonStatus.circuit_breaker) {
|
|
377
|
+
const cb = daemonStatus.circuit_breaker;
|
|
378
|
+
console.log('\n熔断状态:');
|
|
379
|
+
if (cb.tripped) {
|
|
380
|
+
console.log(` \u001b[31m已触发\u001b[0m - 连续失败次数: ${cb.consecutive_failures || 0}`);
|
|
381
|
+
if (cb.tripped_at) {
|
|
382
|
+
console.log(` 触发时间: ${new Date(cb.tripped_at).toLocaleString('zh-CN')}`);
|
|
383
|
+
}
|
|
384
|
+
} else if (cb.consecutive_failures > 0) {
|
|
385
|
+
console.log(` \u001b[33m警告\u001b[0m - 连续失败次数: ${cb.consecutive_failures}`);
|
|
386
|
+
} else {
|
|
387
|
+
console.log(' \u001b[32m正常\u001b[0m');
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
console.log('='.repeat(50) + '\n');
|
|
392
|
+
|
|
393
|
+
return 0;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* 格式化健康状态
|
|
398
|
+
* @private
|
|
399
|
+
*/
|
|
400
|
+
function _formatHealthStatus(health) {
|
|
401
|
+
const colorMap = {
|
|
402
|
+
healthy: '[32m',
|
|
403
|
+
degraded: '[33m',
|
|
404
|
+
critical: '[31m',
|
|
405
|
+
terminated: '[90m'
|
|
406
|
+
};
|
|
407
|
+
const labelMap = {
|
|
408
|
+
healthy: '健康',
|
|
409
|
+
degraded: '降级',
|
|
410
|
+
critical: '严重',
|
|
411
|
+
terminated: '已终止'
|
|
412
|
+
};
|
|
413
|
+
const label = labelMap[health] || health || '未知';
|
|
414
|
+
const color = colorMap[health] || '';
|
|
415
|
+
return color ? color + label + '[0m' : label;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 格式化守护进程状态
|
|
420
|
+
* @private
|
|
421
|
+
*/
|
|
422
|
+
function _formatStateStatus(state, isAlive) {
|
|
423
|
+
if (!isAlive) {
|
|
424
|
+
return '\x1b[31m已停止\x1b[0m';
|
|
425
|
+
}
|
|
426
|
+
const colorMap = {
|
|
427
|
+
running: '\x1b[32m',
|
|
428
|
+
paused: '\x1b[33m'
|
|
429
|
+
};
|
|
430
|
+
const labelMap = {
|
|
431
|
+
running: '运行中',
|
|
432
|
+
paused: '已暂停'
|
|
433
|
+
};
|
|
434
|
+
const label = labelMap[state] || state || '未知';
|
|
435
|
+
const color = colorMap[state] || '';
|
|
436
|
+
return color ? color + label + '\x1b[0m' : label;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* 格式化任务状态
|
|
441
|
+
* @private
|
|
442
|
+
*/
|
|
443
|
+
function _formatTaskStatus(status) {
|
|
444
|
+
const colorMap = {
|
|
445
|
+
pending: '[36m',
|
|
446
|
+
in_progress: '[33m',
|
|
447
|
+
completed: '[32m',
|
|
448
|
+
failed: '[31m'
|
|
449
|
+
};
|
|
450
|
+
const labelMap = {
|
|
451
|
+
pending: '待处理',
|
|
452
|
+
in_progress: '进行中',
|
|
453
|
+
completed: '已完成',
|
|
454
|
+
failed: '已失败'
|
|
455
|
+
};
|
|
456
|
+
const label = labelMap[status] || status || '未知';
|
|
457
|
+
const color = colorMap[status] || '';
|
|
458
|
+
return color ? color + label + '[0m' : label;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* 按可见宽度(剥离 ANSI 转义码后)填充字符串
|
|
463
|
+
* @private
|
|
464
|
+
*/
|
|
465
|
+
function _visiblePadEnd(str, targetLen) {
|
|
466
|
+
const visibleLen = str.replace(/\x1b\[[0-9;]*m/g, '').length;
|
|
467
|
+
return str + ' '.repeat(Math.max(0, targetLen - visibleLen));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* 执行 restart 命令
|
|
472
|
+
*/
|
|
473
|
+
async function cmdRestart(options, args) {
|
|
474
|
+
if (!args.task) {
|
|
475
|
+
console.error('错误: restart 命令需要 --task 选项');
|
|
476
|
+
console.error('示例: node watchdog.js restart --task 3');
|
|
477
|
+
return 1;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const taskId = args.task;
|
|
481
|
+
|
|
482
|
+
// 加载配置
|
|
483
|
+
const loadedConfig = config.loadConfig(options.config);
|
|
484
|
+
|
|
485
|
+
// 创建状态管理器
|
|
486
|
+
const stateManager = new StateFileManager({
|
|
487
|
+
heartbeatDir: loadedConfig.heartbeat_dir
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
// 检查守护进程是否运行
|
|
491
|
+
const daemonStatus = stateManager.readDaemonStatus();
|
|
492
|
+
if (!daemonStatus) {
|
|
493
|
+
console.error('错误: 守护进程未运行');
|
|
494
|
+
console.error('提示: 运行 "node watchdog.js start" 启动守护进程');
|
|
495
|
+
return 1;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const procManager = new ProcessManager({
|
|
499
|
+
killTimeoutSec: loadedConfig.process.kill_timeout_sec
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
if (!procManager.isProcessAlive(daemonStatus.pid)) {
|
|
503
|
+
console.error('错误: 守护进程未运行');
|
|
504
|
+
console.error('提示: 运行 "node watchdog.js start" 启动守护进程');
|
|
505
|
+
return 1;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// 读取任务文件
|
|
509
|
+
const task = stateManager.readTaskFile(taskId);
|
|
510
|
+
if (!task) {
|
|
511
|
+
console.error(`错误: 任务 #${taskId} 不存在`);
|
|
512
|
+
return 1;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// 检查任务状态
|
|
516
|
+
if (task.status === 'completed') {
|
|
517
|
+
console.warn(`警告: 任务 #${taskId} 已完成,无需重启`);
|
|
518
|
+
return 0;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// 读取现有动作
|
|
522
|
+
const actionsData = stateManager.readDaemonActions();
|
|
523
|
+
|
|
524
|
+
// 检查是否已有待处理的 restart 动作
|
|
525
|
+
const hasPendingRestart = actionsData.actions.some(
|
|
526
|
+
a => a.target_task === taskId && a.action === 'restart'
|
|
527
|
+
);
|
|
528
|
+
|
|
529
|
+
if (hasPendingRestart) {
|
|
530
|
+
console.warn(`警告: 任务 #${taskId} 已有待处理的重启动作`);
|
|
531
|
+
return 0;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// 根据 complexity_score 选择策略
|
|
535
|
+
const complexityScore = task.complexity_score || 0;
|
|
536
|
+
const strategy = complexityScore > 6 ? 'checkpoint_resume' : 'full_restart';
|
|
537
|
+
|
|
538
|
+
// 创建 restart 动作
|
|
539
|
+
const action = {
|
|
540
|
+
id: `act-manual-restart-${taskId}-${Date.now()}`,
|
|
541
|
+
target_task: taskId,
|
|
542
|
+
action: 'restart',
|
|
543
|
+
reason: 'manual_restart: triggered by CLI',
|
|
544
|
+
strategy: strategy,
|
|
545
|
+
timestamp: new Date().toISOString(),
|
|
546
|
+
context: {
|
|
547
|
+
retry_count: (task.retry_count || 0) + 1,
|
|
548
|
+
complexity_score: complexityScore,
|
|
549
|
+
manual: true
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
// 写入动作
|
|
554
|
+
const combinedActions = [...actionsData.actions, action];
|
|
555
|
+
stateManager.writeDaemonActions(
|
|
556
|
+
combinedActions,
|
|
557
|
+
daemonStatus.session ? daemonStatus.session.heartbeat_iteration : 0
|
|
558
|
+
);
|
|
559
|
+
|
|
560
|
+
console.log(`已提交任务 #${taskId} 重启请求`);
|
|
561
|
+
console.log(`策略: ${strategy}`);
|
|
562
|
+
console.log('守护进程将在下次循环中处理此请求');
|
|
563
|
+
return 0;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* 执行 pause 命令
|
|
568
|
+
*/
|
|
569
|
+
async function cmdPause(options, args) {
|
|
570
|
+
const isResume = args.resume || false;
|
|
571
|
+
const action = isResume ? '恢复' : '暂停';
|
|
572
|
+
|
|
573
|
+
// 加载配置
|
|
574
|
+
const loadedConfig = config.loadConfig(options.config);
|
|
575
|
+
|
|
576
|
+
// 创建状态管理器
|
|
577
|
+
const stateManager = new StateFileManager({
|
|
578
|
+
heartbeatDir: loadedConfig.heartbeat_dir
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
// 创建进程管理器
|
|
582
|
+
const procManager = new ProcessManager({
|
|
583
|
+
killTimeoutSec: loadedConfig.process.kill_timeout_sec
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
// 读取守护进程状态
|
|
587
|
+
const daemonStatus = stateManager.readDaemonStatus();
|
|
588
|
+
|
|
589
|
+
if (!daemonStatus) {
|
|
590
|
+
console.error('错误: 守护进程未运行');
|
|
591
|
+
console.error('提示: 运行 "node watchdog.js start" 启动守护进程');
|
|
592
|
+
return 1;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// 检查进程是否存活
|
|
596
|
+
if (!procManager.isProcessAlive(daemonStatus.pid)) {
|
|
597
|
+
console.error(`错误: 守护进程 (PID: ${daemonStatus.pid}) 未运行`);
|
|
598
|
+
return 1;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// 检查当前状态
|
|
602
|
+
if (daemonStatus.state === 'paused' && !isResume) {
|
|
603
|
+
console.warn('守护进程已处于暂停状态');
|
|
604
|
+
return 0;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
if (daemonStatus.state === 'running' && isResume) {
|
|
608
|
+
console.warn('守护进程正在运行,无需恢复');
|
|
609
|
+
return 0;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// 通过写入状态文件触发 pause/resume
|
|
613
|
+
daemonStatus.state = isResume ? 'running' : 'paused';
|
|
614
|
+
daemonStatus.last_check = new Date().toISOString();
|
|
615
|
+
stateManager.writeDaemonStatus(daemonStatus);
|
|
616
|
+
|
|
617
|
+
console.log(`${action}指令已发送 (PID: ${daemonStatus.pid})`);
|
|
618
|
+
console.log('守护进程将在下次循环中响应此指令');
|
|
619
|
+
return 0;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* 执行 stop 命令
|
|
624
|
+
*/
|
|
625
|
+
async function cmdStop(options) {
|
|
626
|
+
// 加载配置
|
|
627
|
+
const loadedConfig = config.loadConfig(options.config);
|
|
628
|
+
|
|
629
|
+
// 创建状态管理器
|
|
630
|
+
const stateManager = new StateFileManager({
|
|
631
|
+
heartbeatDir: loadedConfig.heartbeat_dir
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
// 创建进程管理器
|
|
635
|
+
const procManager = new ProcessManager({
|
|
636
|
+
killTimeoutSec: loadedConfig.process.kill_timeout_sec
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
// 读取守护进程状态
|
|
640
|
+
const daemonStatus = stateManager.readDaemonStatus();
|
|
641
|
+
|
|
642
|
+
if (!daemonStatus) {
|
|
643
|
+
console.log('守护进程未运行');
|
|
644
|
+
return 0;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const pid = daemonStatus.pid;
|
|
648
|
+
|
|
649
|
+
// 检查进程是否存活
|
|
650
|
+
if (!procManager.isProcessAlive(pid)) {
|
|
651
|
+
console.log(`守护进程 (PID: ${pid}) 未运行`);
|
|
652
|
+
// 清理状态文件
|
|
653
|
+
_clearDaemonStatus(stateManager);
|
|
654
|
+
return 0;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
console.log(`正在停止守护进程 (PID: ${pid})...`);
|
|
658
|
+
|
|
659
|
+
// 尝试优雅终止
|
|
660
|
+
const success = await procManager.killProcess(pid);
|
|
661
|
+
|
|
662
|
+
if (success) {
|
|
663
|
+
console.log('守护进程已停止');
|
|
664
|
+
// 清理状态文件
|
|
665
|
+
_clearDaemonStatus(stateManager);
|
|
666
|
+
return 0;
|
|
667
|
+
} else {
|
|
668
|
+
console.error('守护进程停止失败');
|
|
669
|
+
return 1;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* 清理守护进程状态文件
|
|
675
|
+
* @private
|
|
676
|
+
*/
|
|
677
|
+
function _clearDaemonStatus(stateManager) {
|
|
678
|
+
try {
|
|
679
|
+
const status = stateManager.readDaemonStatus();
|
|
680
|
+
if (status) {
|
|
681
|
+
status.health = 'terminated';
|
|
682
|
+
status.state = 'stopped';
|
|
683
|
+
status.last_check = new Date().toISOString();
|
|
684
|
+
stateManager.writeDaemonStatus(status);
|
|
685
|
+
}
|
|
686
|
+
} catch (err) {
|
|
687
|
+
// 忽略清理错误
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* 主入口
|
|
693
|
+
*/
|
|
694
|
+
async function main() {
|
|
695
|
+
const args = process.argv.slice(2);
|
|
696
|
+
const parsed = parseArgs(args);
|
|
697
|
+
|
|
698
|
+
// 处理 help 命令
|
|
699
|
+
if (parsed.command === 'help' || !parsed.command) {
|
|
700
|
+
console.log(HELP_TEXT);
|
|
701
|
+
return 0;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// 加载配置(如果命令需要)
|
|
705
|
+
let loadedConfig = null;
|
|
706
|
+
if (['start', 'status', 'restart', 'pause', 'stop'].includes(parsed.command)) {
|
|
707
|
+
try {
|
|
708
|
+
loadedConfig = config.loadConfig(parsed.options.config);
|
|
709
|
+
} catch (err) {
|
|
710
|
+
console.error(`配置加载失败: ${err.message}`);
|
|
711
|
+
console.error('\n提示: 请先运行 "node watchdog.js init" 初始化配置');
|
|
712
|
+
return 1;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// 分发到具体命令处理
|
|
717
|
+
let exitCode = 0;
|
|
718
|
+
switch (parsed.command) {
|
|
719
|
+
case 'init':
|
|
720
|
+
exitCode = cmdInit(parsed.options);
|
|
721
|
+
break;
|
|
722
|
+
case 'start':
|
|
723
|
+
exitCode = await cmdStart(parsed.options, parsed.args);
|
|
724
|
+
break;
|
|
725
|
+
case 'status':
|
|
726
|
+
exitCode = cmdStatus(parsed.options);
|
|
727
|
+
break;
|
|
728
|
+
case 'restart':
|
|
729
|
+
exitCode = await cmdRestart(parsed.options, parsed.args);
|
|
730
|
+
break;
|
|
731
|
+
case 'pause':
|
|
732
|
+
exitCode = await cmdPause(parsed.options, parsed.args);
|
|
733
|
+
break;
|
|
734
|
+
case 'stop':
|
|
735
|
+
exitCode = await cmdStop(parsed.options);
|
|
736
|
+
break;
|
|
737
|
+
default:
|
|
738
|
+
console.error(`错误: 未知命令 "${parsed.command}"`);
|
|
739
|
+
console.log(HELP_TEXT);
|
|
740
|
+
exitCode = 1;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
return exitCode;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// 运行主程序
|
|
747
|
+
if (require.main === module) {
|
|
748
|
+
(async () => {
|
|
749
|
+
const exitCode = await main();
|
|
750
|
+
process.exit(exitCode);
|
|
751
|
+
})();
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
module.exports = { main, parseArgs };
|