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,676 +0,0 @@
1
- /**
2
- * Watchdog Multi-Window Extension
3
- *
4
- * Extends the Watchdog daemon with multi-session monitoring capabilities:
5
- * - L4 Cross-Window Detection: monitors all windows in multi-window-session.json
6
- * - L5 Stage-Level Detection: detects when all windows in a stage are stalled
7
- * - Global Circuit Breaker: consecutive failure threshold -> abort_all
8
- * - Cross-Window Command Dispatch: writes commands to target windows' daemon-actions.json
9
- *
10
- * Design doc: docs/reports/multi-window-monitoring-design.html (Section 6.2)
11
- * Work package: WP-172-1-impl-c
12
- */
13
-
14
- 'use strict';
15
-
16
- var fs = require('fs');
17
- var path = require('path');
18
-
19
- // ─────────────────────────────────────────────
20
- // Section 1: Utilities
21
- // ─────────────────────────────────────────────
22
-
23
- /**
24
- * Read and parse a JSON file. Returns null on any error.
25
- * @param {string} filePath
26
- * @returns {object|null}
27
- */
28
- function readJsonSafe(filePath) {
29
- try {
30
- var content = fs.readFileSync(filePath, 'utf-8');
31
- return JSON.parse(content);
32
- } catch (_e) {
33
- return null;
34
- }
35
- }
36
-
37
- /**
38
- * Write a JSON file with atomic-style write (write to temp then rename).
39
- * Falls back to direct write if rename fails.
40
- * @param {string} filePath
41
- * @param {object} data
42
- */
43
- function writeJsonSafe(filePath, data) {
44
- var dir = path.dirname(filePath);
45
- if (!fs.existsSync(dir)) {
46
- fs.mkdirSync(dir, { recursive: true });
47
- }
48
- var content = JSON.stringify(data, null, 2);
49
- fs.writeFileSync(filePath, content, 'utf-8');
50
- }
51
-
52
- // ─────────────────────────────────────────────
53
- // Section 2: Multi-Window Mode Detection
54
- // ─────────────────────────────────────────────
55
-
56
- /**
57
- * Check if multi-window session file exists.
58
- * @param {string} daemonDir - Path to .claude-daemon/ directory
59
- * @returns {boolean}
60
- */
61
- function isMultiWindowMode(daemonDir) {
62
- var sessionPath = path.join(daemonDir, 'multi-window-session.json');
63
- return fs.existsSync(sessionPath);
64
- }
65
-
66
- /**
67
- * Read multi-window-session.json. Returns null if not found or invalid.
68
- * @param {string} daemonDir
69
- * @returns {object|null}
70
- */
71
- function readSession(daemonDir) {
72
- var sessionPath = path.join(daemonDir, 'multi-window-session.json');
73
- return readJsonSafe(sessionPath);
74
- }
75
-
76
- // ─────────────────────────────────────────────
77
- // Section 3: L4 Cross-Window Detection
78
- // ─────────────────────────────────────────────
79
-
80
- /**
81
- * Default multi-window config values.
82
- */
83
- var MW_DEFAULTS = {
84
- heartbeat_timeout_sec: 120, // 2 minutes — matches coordinator STALE_THRESHOLD_MS
85
- stage_stall_timeout_sec: 600, // 10 minutes — all windows idle in a stage
86
- circuit_breaker: {
87
- consecutive_failures_threshold: 3,
88
- cooldown_after_break_sec: 900 // 15 minutes
89
- }
90
- };
91
-
92
- /**
93
- * Load multi-window config from daemon config, merging with defaults.
94
- * @param {object} daemonConfig - Full daemon-config.json content
95
- * @returns {object} Multi-window config section
96
- */
97
- function loadMultiWindowConfig(daemonConfig) {
98
- var mw = (daemonConfig && daemonConfig.multi_window) || {};
99
- var cb = mw.circuit_breaker || {};
100
-
101
- return {
102
- heartbeat_timeout_sec: mw.heartbeat_timeout_sec || MW_DEFAULTS.heartbeat_timeout_sec,
103
- stage_stall_timeout_sec: mw.stage_stall_timeout_sec || MW_DEFAULTS.stage_stall_timeout_sec,
104
- circuit_breaker: {
105
- consecutive_failures_threshold: cb.consecutive_failures_threshold || MW_DEFAULTS.circuit_breaker.consecutive_failures_threshold,
106
- cooldown_after_break_sec: cb.cooldown_after_break_sec || MW_DEFAULTS.circuit_breaker.cooldown_after_break_sec
107
- }
108
- };
109
- }
110
-
111
- /**
112
- * L4 Cross-Window Detection: identify windows that are disconnected or failed.
113
- *
114
- * A window is considered disconnected if:
115
- * - Its heartbeat.last_update is older than heartbeat_timeout_sec
116
- * - Or it has no heartbeat data at all
117
- *
118
- * A window is considered failed if:
119
- * - Its status in session.windows is 'failed'
120
- *
121
- * @param {object} session - multi-window-session.json content
122
- * @param {object} config - Multi-window config (from loadMultiWindowConfig)
123
- * @returns {object} { alerts: Array<{window_id, level, type, message, timestamp}>, summary: {total, active, disconnected, failed} }
124
- */
125
- function detectCrossWindowIssues(session, config) {
126
- var alerts = [];
127
- var summary = { total: 0, active: 0, disconnected: 0, failed: 0 };
128
- var now = Date.now();
129
- var timeoutMs = (config.heartbeat_timeout_sec || MW_DEFAULTS.heartbeat_timeout_sec) * 1000;
130
-
131
- if (!session || !session.windows) {
132
- return { alerts: alerts, summary: summary };
133
- }
134
-
135
- var winIds = Object.keys(session.windows);
136
- summary.total = winIds.length;
137
-
138
- for (var i = 0; i < winIds.length; i++) {
139
- var winId = winIds[i];
140
- var win = session.windows[winId];
141
-
142
- if (win.status === 'failed') {
143
- summary.failed++;
144
- alerts.push({
145
- window_id: winId,
146
- level: 'L4',
147
- type: 'window_failed',
148
- message: 'Window ' + winId + ' reported as failed',
149
- timestamp: new Date().toISOString()
150
- });
151
- continue;
152
- }
153
-
154
- if (win.status === 'disconnected') {
155
- summary.disconnected++;
156
- alerts.push({
157
- window_id: winId,
158
- level: 'L4',
159
- type: 'window_disconnected',
160
- message: 'Window ' + winId + ' is disconnected (no recent heartbeat)',
161
- timestamp: new Date().toISOString()
162
- });
163
- continue;
164
- }
165
-
166
- // Also check heartbeat staleness directly (defense in depth)
167
- if (win.heartbeat && win.heartbeat.last_update) {
168
- var heartbeatAge = now - new Date(win.heartbeat.last_update).getTime();
169
- if (heartbeatAge > timeoutMs) {
170
- summary.disconnected++;
171
- alerts.push({
172
- window_id: winId,
173
- level: 'L4',
174
- type: 'heartbeat_stale',
175
- message: 'Window ' + winId + ' heartbeat is stale (' + Math.round(heartbeatAge / 1000) + 's old)',
176
- timestamp: new Date().toISOString()
177
- });
178
- continue;
179
- }
180
- } else if (!win.heartbeat) {
181
- summary.disconnected++;
182
- alerts.push({
183
- window_id: winId,
184
- level: 'L4',
185
- type: 'no_heartbeat',
186
- message: 'Window ' + winId + ' has no heartbeat data',
187
- timestamp: new Date().toISOString()
188
- });
189
- continue;
190
- }
191
-
192
- summary.active++;
193
- }
194
-
195
- return { alerts: alerts, summary: summary };
196
- }
197
-
198
- // ─────────────────────────────────────────────
199
- // Section 4: L5 Stage-Level Detection
200
- // ─────────────────────────────────────────────
201
-
202
- /**
203
- * L5 Stage-Level Detection: check if all windows in the active stage are stalled.
204
- *
205
- * A window is considered "stalled" if:
206
- * - Its heartbeat shows in_progress=0 AND pending=0 (idle/completed), OR
207
- * - Its heartbeat is stale (older than heartbeat_timeout_sec), OR
208
- * - Its status is 'disconnected'
209
- *
210
- * A stage is considered "stalled" if ALL windows in the active stage are stalled
211
- * AND the stall duration exceeds stage_stall_timeout_sec.
212
- *
213
- * @param {object} session - multi-window-session.json content
214
- * @param {object} config - Multi-window config
215
- * @returns {object} { stalled: boolean, stage_id: number|null, reason: string, stalled_windows: string[], duration_sec: number }
216
- */
217
- function detectStageStall(session, config) {
218
- var result = {
219
- stalled: false,
220
- stage_id: null,
221
- reason: '',
222
- stalled_windows: [],
223
- duration_sec: 0
224
- };
225
-
226
- if (!session || !session.stages || !session.windows) {
227
- return result;
228
- }
229
-
230
- // Find active stage
231
- var activeStage = null;
232
- for (var i = 0; i < session.stages.length; i++) {
233
- if (session.stages[i].status === 'active') {
234
- activeStage = session.stages[i];
235
- break;
236
- }
237
- }
238
-
239
- if (!activeStage) {
240
- return result;
241
- }
242
-
243
- result.stage_id = activeStage.stage_id;
244
-
245
- var stageWindows = activeStage.windows || [];
246
- if (stageWindows.length === 0) {
247
- return result;
248
- }
249
-
250
- var now = Date.now();
251
- var heartbeatTimeoutMs = (config.heartbeat_timeout_sec || MW_DEFAULTS.heartbeat_timeout_sec) * 1000;
252
- var stallTimeoutMs = (config.stage_stall_timeout_sec || MW_DEFAULTS.stage_stall_timeout_sec) * 1000;
253
-
254
- // Check each window in the stage
255
- var allStalled = true;
256
- var stalledWindows = [];
257
- var oldestStallStart = now;
258
-
259
- for (var j = 0; j < stageWindows.length; j++) {
260
- var winId = stageWindows[j];
261
- var win = session.windows[winId];
262
-
263
- if (!win) {
264
- // Window not in session — treat as stalled
265
- stalledWindows.push(winId);
266
- continue;
267
- }
268
-
269
- var isWindowStalled = false;
270
-
271
- // Check if disconnected
272
- if (win.status === 'disconnected' || win.status === 'failed') {
273
- isWindowStalled = true;
274
- }
275
-
276
- // Check heartbeat staleness
277
- if (!isWindowStalled && win.heartbeat && win.heartbeat.last_update) {
278
- var heartbeatAge = now - new Date(win.heartbeat.last_update).getTime();
279
- if (heartbeatAge > heartbeatTimeoutMs) {
280
- isWindowStalled = true;
281
- }
282
- } else if (!isWindowStalled && !win.heartbeat) {
283
- isWindowStalled = true;
284
- }
285
-
286
- // Check if window has no work (idle but not completed)
287
- if (!isWindowStalled && win.heartbeat) {
288
- var hb = win.heartbeat;
289
- if (hb.in_progress === 0 && hb.pending === 0 && win.status !== 'completed') {
290
- // Window is idle — check how long it's been idle
291
- // Use last_update as proxy for when it became idle
292
- if (hb.last_update) {
293
- var idleTime = now - new Date(hb.last_update).getTime();
294
- if (idleTime > stallTimeoutMs) {
295
- isWindowStalled = true;
296
- } else {
297
- // Not stalled long enough yet — but not all windows need to be stalled
298
- // for the same duration. We use the oldest stall start.
299
- if (idleTime < oldestStallStart) {
300
- oldestStallStart = idleTime;
301
- }
302
- allStalled = false;
303
- }
304
- }
305
- } else if (hb.in_progress > 0 || hb.pending > 0) {
306
- // Window has active work — not stalled
307
- allStalled = false;
308
- }
309
- }
310
-
311
- if (isWindowStalled) {
312
- stalledWindows.push(winId);
313
- } else {
314
- allStalled = false;
315
- }
316
- }
317
-
318
- // Determine if stage is stalled
319
- if (allStalled && stalledWindows.length === stageWindows.length) {
320
- // Calculate stall duration based on the oldest heartbeat among stalled windows
321
- var maxStallDuration = 0;
322
- for (var k = 0; k < stalledWindows.length; k++) {
323
- var sWin = session.windows[stalledWindows[k]];
324
- if (sWin && sWin.heartbeat && sWin.heartbeat.last_update) {
325
- var duration = now - new Date(sWin.heartbeat.last_update).getTime();
326
- if (duration > maxStallDuration) {
327
- maxStallDuration = duration;
328
- }
329
- } else {
330
- // No heartbeat at all — assume stalled since session start
331
- maxStallDuration = stallTimeoutMs + 1;
332
- }
333
- }
334
-
335
- if (maxStallDuration >= stallTimeoutMs) {
336
- result.stalled = true;
337
- result.stalled_windows = stalledWindows;
338
- result.duration_sec = Math.round(maxStallDuration / 1000);
339
- result.reason = 'All windows in stage ' + activeStage.stage_id + ' have been stalled for ' + result.duration_sec + 's';
340
- }
341
- }
342
-
343
- return result;
344
- }
345
-
346
- // ─────────────────────────────────────────────
347
- // Section 5: Global Circuit Breaker
348
- // ─────────────────────────────────────────────
349
-
350
- /**
351
- * Create initial circuit breaker state.
352
- * @returns {object}
353
- */
354
- function createCircuitBreakerState() {
355
- return {
356
- tripped: false,
357
- consecutive_failures: 0,
358
- total_failures: 0,
359
- tripped_at: null,
360
- last_failure_at: null,
361
- cooldown_until: null,
362
- history: []
363
- };
364
- }
365
-
366
- /**
367
- * Record a failure in the circuit breaker state.
368
- *
369
- * @param {object} breakerState - Mutable circuit breaker state
370
- * @param {string} reason - Failure reason
371
- * @param {object} config - Multi-window config
372
- * @returns {object} Updated breakerState (same reference, mutated in place)
373
- */
374
- function recordFailure(breakerState, reason, config) {
375
- var now = new Date().toISOString();
376
- var threshold = (config.circuit_breaker && config.circuit_breaker.consecutive_failures_threshold)
377
- || MW_DEFAULTS.circuit_breaker.consecutive_failures_threshold;
378
-
379
- breakerState.consecutive_failures++;
380
- breakerState.total_failures++;
381
- breakerState.last_failure_at = now;
382
-
383
- breakerState.history.push({
384
- type: 'failure',
385
- reason: reason,
386
- timestamp: now,
387
- consecutive_failures: breakerState.consecutive_failures
388
- });
389
-
390
- // Keep history bounded (last 50 entries)
391
- if (breakerState.history.length > 50) {
392
- breakerState.history = breakerState.history.slice(-50);
393
- }
394
-
395
- // Check if threshold reached
396
- if (breakerState.consecutive_failures >= threshold && !breakerState.tripped) {
397
- breakerState.tripped = true;
398
- breakerState.tripped_at = now;
399
-
400
- var cooldownSec = (config.circuit_breaker && config.circuit_breaker.cooldown_after_break_sec)
401
- || MW_DEFAULTS.circuit_breaker.cooldown_after_break_sec;
402
- breakerState.cooldown_until = new Date(Date.now() + cooldownSec * 1000).toISOString();
403
-
404
- breakerState.history.push({
405
- type: 'tripped',
406
- message: 'Circuit breaker tripped after ' + breakerState.consecutive_failures + ' consecutive failures',
407
- timestamp: now
408
- });
409
- }
410
-
411
- return breakerState;
412
- }
413
-
414
- /**
415
- * Record a success (resets consecutive failures counter).
416
- *
417
- * @param {object} breakerState - Mutable circuit breaker state
418
- * @returns {object} Updated breakerState
419
- */
420
- function recordSuccess(breakerState) {
421
- if (breakerState.consecutive_failures > 0) {
422
- breakerState.history.push({
423
- type: 'recovered',
424
- message: 'Consecutive failures reset from ' + breakerState.consecutive_failures + ' to 0',
425
- timestamp: new Date().toISOString()
426
- });
427
- }
428
- breakerState.consecutive_failures = 0;
429
-
430
- // If tripped and cooldown has passed, reset
431
- if (breakerState.tripped && breakerState.cooldown_until) {
432
- if (new Date() >= new Date(breakerState.cooldown_until)) {
433
- breakerState.tripped = false;
434
- breakerState.tripped_at = null;
435
- breakerState.cooldown_until = null;
436
- breakerState.history.push({
437
- type: 'reset',
438
- message: 'Circuit breaker reset after cooldown',
439
- timestamp: new Date().toISOString()
440
- });
441
- }
442
- }
443
-
444
- return breakerState;
445
- }
446
-
447
- /**
448
- * Check if the circuit breaker should trigger an abort_all.
449
- *
450
- * @param {object} breakerState
451
- * @returns {boolean} true if abort_all should be triggered
452
- */
453
- function shouldAbortAll(breakerState) {
454
- return breakerState.tripped === true;
455
- }
456
-
457
- // ─────────────────────────────────────────────
458
- // Section 6: Cross-Window Command Dispatch
459
- // ─────────────────────────────────────────────
460
-
461
- /**
462
- * Dispatch a command to a specific window's daemon-actions.json.
463
- *
464
- * @param {string} daemonDir - Path to .claude-daemon/ directory
465
- * @param {string} targetWindowId - Target window ID (e.g. 'win-1')
466
- * @param {object} command - Command object to append to actions
467
- * @param {string} command.action - Action type: 'restart' | 'abort' | 'abort_all' | 'pause'
468
- * @param {string} [command.reason] - Reason for the command
469
- * @param {string} [command.target_task] - Specific task ID (for restart)
470
- * @param {string} [command.strategy] - Restart strategy
471
- * @returns {object} { success: boolean, action_id: string, error: string|null }
472
- */
473
- function dispatchCommand(daemonDir, targetWindowId, command) {
474
- var actionsPath = path.join(daemonDir, 'windows', targetWindowId, 'daemon-actions.json');
475
-
476
- var actionsData;
477
- try {
478
- actionsData = readJsonSafe(actionsPath);
479
- if (!actionsData) {
480
- actionsData = { actions: [], last_updated: null };
481
- }
482
- } catch (_e) {
483
- actionsData = { actions: [], last_updated: null };
484
- }
485
-
486
- if (!Array.isArray(actionsData.actions)) {
487
- actionsData.actions = [];
488
- }
489
-
490
- var actionId = 'act-mw-' + command.action + '-' + targetWindowId + '-' + Date.now();
491
-
492
- var action = {
493
- id: actionId,
494
- action: command.action,
495
- target_task: command.target_task || null,
496
- reason: command.reason || 'cross-window dispatch',
497
- strategy: command.strategy || null,
498
- timestamp: new Date().toISOString(),
499
- source: 'watchdog-multi-window',
500
- context: command.context || {}
501
- };
502
-
503
- actionsData.actions.push(action);
504
- actionsData.last_updated = new Date().toISOString();
505
-
506
- try {
507
- writeJsonSafe(actionsPath, actionsData);
508
- return { success: true, action_id: actionId, error: null };
509
- } catch (e) {
510
- return { success: false, action_id: actionId, error: e.message };
511
- }
512
- }
513
-
514
- /**
515
- * Dispatch abort_all to all windows in the session.
516
- *
517
- * @param {string} daemonDir - Path to .claude-daemon/ directory
518
- * @param {object} session - multi-window-session.json content
519
- * @param {string} reason - Reason for abort
520
- * @returns {object} { results: Array<{window_id, success, action_id, error}> }
521
- */
522
- function dispatchAbortAll(daemonDir, session, reason) {
523
- var results = [];
524
-
525
- if (!session || !session.windows) {
526
- return { results: results };
527
- }
528
-
529
- var winIds = Object.keys(session.windows);
530
- for (var i = 0; i < winIds.length; i++) {
531
- var winId = winIds[i];
532
- var result = dispatchCommand(daemonDir, winId, {
533
- action: 'abort_all',
534
- reason: reason,
535
- context: { global_abort: true }
536
- });
537
- results.push({
538
- window_id: winId,
539
- success: result.success,
540
- action_id: result.action_id,
541
- error: result.error
542
- });
543
- }
544
-
545
- return { results: results };
546
- }
547
-
548
- // ─────────────────────────────────────────────
549
- // Section 7: Main Multi-Window Check Loop
550
- // ─────────────────────────────────────────────
551
-
552
- /**
553
- * Run a complete multi-window monitoring check.
554
- *
555
- * This is the main entry point called by the Watchdog daemon on each cycle
556
- * when multi-window mode is detected.
557
- *
558
- * @param {string} daemonDir - Path to .claude-daemon/ directory
559
- * @param {object} daemonConfig - Full daemon-config.json content
560
- * @param {object} [breakerState] - Existing circuit breaker state (mutated in place)
561
- * @returns {object} { session, crossWindow, stageStall, breakerState, actions: Array }
562
- */
563
- function runMultiWindowCheck(daemonDir, daemonConfig, breakerState) {
564
- var config = loadMultiWindowConfig(daemonConfig);
565
- var session = readSession(daemonDir);
566
-
567
- if (!session) {
568
- return {
569
- session: null,
570
- crossWindow: { alerts: [], summary: { total: 0, active: 0, disconnected: 0, failed: 0 } },
571
- stageStall: { stalled: false, stage_id: null, reason: '', stalled_windows: [], duration_sec: 0 },
572
- breakerState: breakerState || createCircuitBreakerState(),
573
- actions: []
574
- };
575
- }
576
-
577
- if (!breakerState) {
578
- breakerState = createCircuitBreakerState();
579
- }
580
-
581
- // L4: Cross-window detection
582
- var crossWindow = detectCrossWindowIssues(session, config);
583
-
584
- // L5: Stage stall detection
585
- var stageStall = detectStageStall(session, config);
586
-
587
- // Determine actions based on detections
588
- var actions = [];
589
-
590
- // Consolidate failures: record one failure per check cycle to avoid
591
- // double-counting when L4 (window-level) and L5 (stage-level) detect
592
- // the same underlying issue.
593
- var hasIssues = false;
594
- var failureReasons = [];
595
-
596
- if (crossWindow.alerts.length > 0) {
597
- var failedOrDisconnected = crossWindow.alerts.filter(function (a) {
598
- return a.type === 'window_failed' || a.type === 'window_disconnected' || a.type === 'heartbeat_stale' || a.type === 'no_heartbeat';
599
- });
600
-
601
- if (failedOrDisconnected.length > 0) {
602
- hasIssues = true;
603
- failureReasons.push(failedOrDisconnected.map(function (a) { return a.message; }).join('; '));
604
- }
605
- }
606
-
607
- if (stageStall.stalled) {
608
- hasIssues = true;
609
- failureReasons.push(stageStall.reason);
610
- }
611
-
612
- if (hasIssues) {
613
- recordFailure(breakerState, failureReasons.join(' | '), config);
614
- } else {
615
- recordSuccess(breakerState);
616
- }
617
-
618
- // Check circuit breaker
619
- if (shouldAbortAll(breakerState)) {
620
- var abortReason = 'Global circuit breaker tripped: ' + (breakerState.history.length > 0
621
- ? breakerState.history[breakerState.history.length - 1].message
622
- : 'consecutive failures exceeded threshold');
623
-
624
- var abortResult = dispatchAbortAll(daemonDir, session, abortReason);
625
- actions.push({
626
- type: 'abort_all',
627
- reason: abortReason,
628
- dispatched: abortResult
629
- });
630
- }
631
-
632
- return {
633
- session: session,
634
- crossWindow: crossWindow,
635
- stageStall: stageStall,
636
- breakerState: breakerState,
637
- actions: actions
638
- };
639
- }
640
-
641
- // ─────────────────────────────────────────────
642
- // Exports
643
- // ─────────────────────────────────────────────
644
-
645
- module.exports = {
646
- // Utilities
647
- readJsonSafe: readJsonSafe,
648
- writeJsonSafe: writeJsonSafe,
649
-
650
- // Multi-window mode detection
651
- isMultiWindowMode: isMultiWindowMode,
652
- readSession: readSession,
653
- loadMultiWindowConfig: loadMultiWindowConfig,
654
-
655
- // L4: Cross-window detection
656
- detectCrossWindowIssues: detectCrossWindowIssues,
657
-
658
- // L5: Stage-level detection
659
- detectStageStall: detectStageStall,
660
-
661
- // Global circuit breaker
662
- createCircuitBreakerState: createCircuitBreakerState,
663
- recordFailure: recordFailure,
664
- recordSuccess: recordSuccess,
665
- shouldAbortAll: shouldAbortAll,
666
-
667
- // Cross-window command dispatch
668
- dispatchCommand: dispatchCommand,
669
- dispatchAbortAll: dispatchAbortAll,
670
-
671
- // Main entry point
672
- runMultiWindowCheck: runMultiWindowCheck,
673
-
674
- // Constants
675
- MW_DEFAULTS: MW_DEFAULTS
676
- };