dsh-hive-runner 0.6.7 → 0.8.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/CHANGELOG.md +100 -0
- package/README.md +331 -116
- package/README.zh-CN.md +236 -72
- package/SPEC.md +197 -60
- package/cordis.patch.yml +24 -4
- package/docs/DESIGN.md +88 -42
- package/index.js +682 -38
- package/lib/anomalies.js +216 -0
- package/lib/audit.js +134 -0
- package/lib/commands.js +389 -4
- package/lib/config.js +24 -0
- package/lib/events.js +249 -0
- package/lib/gates.js +103 -0
- package/lib/http.js +42 -4
- package/lib/notify.js +145 -0
- package/lib/patrol.js +218 -0
- package/lib/round.js +103 -6
- package/lib/runs.js +19 -0
- package/lib/supervisor.js +96 -1
- package/package.json +1 -1
package/lib/patrol.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Queen patrol: the periodic supervision tick.
|
|
3
|
+
*
|
|
4
|
+
* Every `intervalMs` (default 5 minutes) it re-reads the supervisor status and
|
|
5
|
+
* turns anything that needs a decision into anomaly entries — auto-paused
|
|
6
|
+
* repositories, deferred environment errors, a worker whose heartbeat stalled,
|
|
7
|
+
* a worker past its timeout. Then it delivers ONE digest to the queen.
|
|
8
|
+
*
|
|
9
|
+
* It is deliberately quiet: with nothing to report it delivers nothing, so a
|
|
10
|
+
* healthy swarm costs no model tokens. Immediate card events use
|
|
11
|
+
* `scheduleFlush` and are debounced into a single digest.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-hive-runner/patrol
|
|
14
|
+
*/
|
|
15
|
+
import { renderDigest } from './anomalies.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {{
|
|
19
|
+
* supervisor?: { status: () => object },
|
|
20
|
+
* feed: { push: Function, pending: Function, markDelivered: Function },
|
|
21
|
+
* notifier?: { deliver: (body: string) => { delivered: boolean, via?: string, reason?: string } },
|
|
22
|
+
* inspect?: () => Promise<void> | void,
|
|
23
|
+
* intervalMs?: number,
|
|
24
|
+
* debounceMs?: number,
|
|
25
|
+
* now?: () => number,
|
|
26
|
+
* setTimer?: typeof setTimeout,
|
|
27
|
+
* clearTimer?: typeof clearTimeout,
|
|
28
|
+
* setIntervalFn?: typeof setInterval,
|
|
29
|
+
* clearIntervalFn?: typeof clearInterval,
|
|
30
|
+
* log?: (level: string, ...args: unknown[]) => void,
|
|
31
|
+
* }} options
|
|
32
|
+
*/
|
|
33
|
+
export function createPatrol(options = {}) {
|
|
34
|
+
const feed = options.feed;
|
|
35
|
+
if (feed === undefined || typeof feed.push !== 'function' || typeof feed.pending !== 'function') {
|
|
36
|
+
throw new TypeError('createPatrol: an anomaly feed is required');
|
|
37
|
+
}
|
|
38
|
+
const supervisor = options.supervisor;
|
|
39
|
+
const notifier = options.notifier;
|
|
40
|
+
// Optional audit hook (arch review completeness) run on every patrol tick.
|
|
41
|
+
const inspect = typeof options.inspect === 'function' ? options.inspect : undefined;
|
|
42
|
+
const intervalMs = Number.isFinite(options.intervalMs) && options.intervalMs > 0 ? options.intervalMs : 5 * 60_000;
|
|
43
|
+
const debounceMs = Number.isFinite(options.debounceMs) && options.debounceMs >= 0 ? options.debounceMs : 3_000;
|
|
44
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
45
|
+
const setTimer = typeof options.setTimer === 'function' ? options.setTimer : setTimeout;
|
|
46
|
+
const clearTimer = typeof options.clearTimer === 'function' ? options.clearTimer : clearTimeout;
|
|
47
|
+
const setIntervalFn = typeof options.setIntervalFn === 'function' ? options.setIntervalFn : setInterval;
|
|
48
|
+
const clearIntervalFn = typeof options.clearIntervalFn === 'function' ? options.clearIntervalFn : clearInterval;
|
|
49
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
50
|
+
|
|
51
|
+
let patrolTimer = null;
|
|
52
|
+
let flushTimer = null;
|
|
53
|
+
let started = false;
|
|
54
|
+
|
|
55
|
+
function push(event) {
|
|
56
|
+
try {
|
|
57
|
+
return feed.push(event);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
log('warn', 'anomaly push failed', error);
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Deliver every pending entry as one digest; keep them when nobody listens. */
|
|
65
|
+
function flushPending() {
|
|
66
|
+
let pending;
|
|
67
|
+
try {
|
|
68
|
+
pending = feed.pending();
|
|
69
|
+
} catch (error) {
|
|
70
|
+
log('warn', 'reading pending anomalies failed', error);
|
|
71
|
+
return { delivered: false, count: 0, reason: 'read-failed' };
|
|
72
|
+
}
|
|
73
|
+
if (!Array.isArray(pending) || pending.length === 0) {
|
|
74
|
+
return { delivered: false, count: 0, reason: 'nothing-pending' };
|
|
75
|
+
}
|
|
76
|
+
if (notifier === undefined || typeof notifier.deliver !== 'function') {
|
|
77
|
+
return { delivered: false, count: pending.length, reason: 'no-notifier' };
|
|
78
|
+
}
|
|
79
|
+
let result;
|
|
80
|
+
try {
|
|
81
|
+
result = notifier.deliver(renderDigest(pending));
|
|
82
|
+
} catch (error) {
|
|
83
|
+
log('warn', 'queen digest delivery failed', error);
|
|
84
|
+
return { delivered: false, count: pending.length, reason: 'delivery-threw' };
|
|
85
|
+
}
|
|
86
|
+
if (result !== undefined && result.delivered === true) {
|
|
87
|
+
try {
|
|
88
|
+
feed.markDelivered(pending.map((entry) => entry.id));
|
|
89
|
+
} catch (error) {
|
|
90
|
+
log('warn', 'marking anomalies delivered failed', error);
|
|
91
|
+
}
|
|
92
|
+
return { delivered: true, count: pending.length, via: result.via ?? null, reason: null };
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
delivered: false,
|
|
96
|
+
count: pending.length,
|
|
97
|
+
via: null,
|
|
98
|
+
reason: result?.reason ?? 'not-delivered',
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Debounce card-level events into one digest. */
|
|
103
|
+
function scheduleFlush() {
|
|
104
|
+
if (debounceMs <= 0) return flushPending();
|
|
105
|
+
if (flushTimer !== null) return { delivered: false, count: 0, reason: 'scheduled' };
|
|
106
|
+
flushTimer = setTimer(() => {
|
|
107
|
+
flushTimer = null;
|
|
108
|
+
flushPending();
|
|
109
|
+
}, debounceMs);
|
|
110
|
+
flushTimer?.unref?.();
|
|
111
|
+
return { delivered: false, count: 0, reason: 'scheduled' };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Scan the supervisor status for conditions that need the queen. */
|
|
115
|
+
function inspectStatus() {
|
|
116
|
+
if (supervisor === undefined || typeof supervisor.status !== 'function') return;
|
|
117
|
+
let status;
|
|
118
|
+
try {
|
|
119
|
+
status = supervisor.status();
|
|
120
|
+
} catch (error) {
|
|
121
|
+
log('warn', 'patrol could not read supervisor status', error);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (status === null || typeof status !== 'object' || !Array.isArray(status.repos)) return;
|
|
125
|
+
const at = now();
|
|
126
|
+
for (const repo of status.repos) {
|
|
127
|
+
if (repo === null || typeof repo !== 'object') continue;
|
|
128
|
+
const name = typeof repo.repo === 'string' ? repo.repo : '';
|
|
129
|
+
if (repo.paused === true && repo.pausedBy === 'auto') {
|
|
130
|
+
push({
|
|
131
|
+
kind: 'auto-paused',
|
|
132
|
+
repo: name,
|
|
133
|
+
summary: 'repository auto-paused',
|
|
134
|
+
detail: String(repo.pausedReason ?? 'auto-paused after repeated round failures'),
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (typeof repo.environmentError === 'string' && repo.environmentError !== '') {
|
|
138
|
+
push({ kind: 'environment-error', repo: name, summary: 'environment error', detail: repo.environmentError });
|
|
139
|
+
}
|
|
140
|
+
if (!Array.isArray(repo.workers)) continue;
|
|
141
|
+
for (const worker of repo.workers) {
|
|
142
|
+
if (worker === null || typeof worker !== 'object') continue;
|
|
143
|
+
const cardId = typeof worker.cardId === 'string' ? worker.cardId : null;
|
|
144
|
+
const role = typeof worker.role === 'string' ? worker.role : null;
|
|
145
|
+
if (worker.heartbeat === 'warn') {
|
|
146
|
+
push({
|
|
147
|
+
kind: 'heartbeat-warn',
|
|
148
|
+
repo: name,
|
|
149
|
+
cardId,
|
|
150
|
+
role,
|
|
151
|
+
summary: 'worker heartbeat stalled',
|
|
152
|
+
detail: 'no commit observed since ' + String(worker.lastOutputAt ?? 'unknown'),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
const timeoutAt = typeof worker.timeoutAt === 'string' ? Date.parse(worker.timeoutAt) : Number.NaN;
|
|
156
|
+
if (Number.isFinite(timeoutAt) && timeoutAt <= at) {
|
|
157
|
+
push({
|
|
158
|
+
kind: 'card-timeout',
|
|
159
|
+
repo: name,
|
|
160
|
+
cardId,
|
|
161
|
+
role,
|
|
162
|
+
summary: 'worker past its card deadline',
|
|
163
|
+
detail: 'timeoutAt ' + String(worker.timeoutAt),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* One patrol tick: run the optional audit, scan the supervisor status, then
|
|
172
|
+
* deliver whatever is pending. Async because the audit reads the board.
|
|
173
|
+
*/
|
|
174
|
+
async function patrol() {
|
|
175
|
+
if (inspect !== undefined) {
|
|
176
|
+
try {
|
|
177
|
+
await inspect();
|
|
178
|
+
} catch (error) {
|
|
179
|
+
log('warn', 'patrol inspect hook failed', error);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
inspectStatus();
|
|
183
|
+
return flushPending();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
scheduleFlush,
|
|
188
|
+
flushPending,
|
|
189
|
+
patrol,
|
|
190
|
+
/** Whether the patrol timer is armed. */
|
|
191
|
+
isRunning() {
|
|
192
|
+
return started;
|
|
193
|
+
},
|
|
194
|
+
start() {
|
|
195
|
+
if (started) return;
|
|
196
|
+
started = true;
|
|
197
|
+
patrolTimer = setIntervalFn(() => {
|
|
198
|
+
void Promise.resolve()
|
|
199
|
+
.then(() => patrol())
|
|
200
|
+
.catch((error) => log('warn', 'patrol tick failed', error));
|
|
201
|
+
}, intervalMs);
|
|
202
|
+
patrolTimer?.unref?.();
|
|
203
|
+
},
|
|
204
|
+
stop() {
|
|
205
|
+
started = false;
|
|
206
|
+
if (patrolTimer !== null) {
|
|
207
|
+
clearIntervalFn(patrolTimer);
|
|
208
|
+
patrolTimer = null;
|
|
209
|
+
}
|
|
210
|
+
if (flushTimer !== null) {
|
|
211
|
+
clearTimer(flushTimer);
|
|
212
|
+
flushTimer = null;
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export default createPatrol;
|
package/lib/round.js
CHANGED
|
@@ -64,7 +64,9 @@ export function renderPrompt(card, lessons = [], claimAgent) {
|
|
|
64
64
|
lines.push('');
|
|
65
65
|
}
|
|
66
66
|
if (card.acceptance) lines.push('## Acceptance (the runner will run this)', ' ' + card.acceptance, '');
|
|
67
|
-
|
|
67
|
+
// Reopen reasons are the queen's guidance channel: they lead the prompt so a
|
|
68
|
+
// retried worker reads the diagnosis and the instruction before the goal.
|
|
69
|
+
if (card.reason) lines.push('## Queen guidance for this attempt (previous outcome)', card.reason, '');
|
|
68
70
|
lines.push('## Hive consensus rules (mandatory)');
|
|
69
71
|
lines.push('1. Before starting, announce the paths you will write: run `hive guard <path...> --agent <claim identity> --task ' + card.id + '` for every entry in the card scope, including `resource:` entries (they are announcements, not files). It always succeeds and publishes what you are doing on the board.'
|
|
70
72
|
+ (claimAgent ? ' Use the same claim identity as the claim, for example `hive guard <path...> --agent ' + claimAgent + ' --task ' + card.id + '`.' : ''));
|
|
@@ -170,6 +172,7 @@ export function createRoundRunner({
|
|
|
170
172
|
checkHook = assertMergeOnCommitHook,
|
|
171
173
|
writeRun = writeRunRecord,
|
|
172
174
|
parentProvider,
|
|
175
|
+
onAnomaly,
|
|
173
176
|
now = () => Date.now(),
|
|
174
177
|
log = () => {},
|
|
175
178
|
}) {
|
|
@@ -187,7 +190,19 @@ export function createRoundRunner({
|
|
|
187
190
|
// The record file is a convenience for the panel, not part of the verdict.
|
|
188
191
|
}
|
|
189
192
|
}
|
|
190
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* Emit one supervision event for the queen digest. Advisory only: a failing
|
|
195
|
+
* sink must never fail a card or a round.
|
|
196
|
+
*/
|
|
197
|
+
function emitAnomaly(event) {
|
|
198
|
+
if (typeof onAnomaly !== 'function') return;
|
|
199
|
+
try {
|
|
200
|
+
onAnomaly(event);
|
|
201
|
+
} catch {
|
|
202
|
+
// supervision is advisory
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/** repo -> Map(cardId, { run, abort }) for status and queen abort requests. */
|
|
191
206
|
const active = new Map();
|
|
192
207
|
function registerActive(repo, run) {
|
|
193
208
|
let runs = active.get(repo);
|
|
@@ -195,7 +210,28 @@ export function createRoundRunner({
|
|
|
195
210
|
runs = new Map();
|
|
196
211
|
active.set(repo, runs);
|
|
197
212
|
}
|
|
198
|
-
runs.set(run.cardId, run);
|
|
213
|
+
runs.set(run.cardId, { run, abort: null });
|
|
214
|
+
}
|
|
215
|
+
/** Attach the per-card abort handle once the worker controller exists. */
|
|
216
|
+
function setActiveAbort(repo, cardId, abort) {
|
|
217
|
+
const runs = active.get(repo);
|
|
218
|
+
const entry = runs?.get(cardId);
|
|
219
|
+
if (entry !== undefined) entry.abort = typeof abort === 'function' ? abort : null;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Abort one live card worker on request (the queen's "stop it now" path).
|
|
223
|
+
* The abort is delivered as a card failure carrying the reason; supervisor
|
|
224
|
+
* pause is the softer action that only stops new dispatch.
|
|
225
|
+
* @param {string} repo
|
|
226
|
+
* @param {string} cardId
|
|
227
|
+
* @param {string} [reason]
|
|
228
|
+
* @returns {{ aborted: boolean, cardId: string }}
|
|
229
|
+
*/
|
|
230
|
+
function abortCard(repo, cardId, reason = 'aborted by the queen') {
|
|
231
|
+
const entry = active.get(repo)?.get(cardId);
|
|
232
|
+
if (entry === undefined || entry.abort === null) return { aborted: false, cardId };
|
|
233
|
+
entry.abort(reason);
|
|
234
|
+
return { aborted: true, cardId };
|
|
199
235
|
}
|
|
200
236
|
function unregisterActive(repo, cardId) {
|
|
201
237
|
const runs = active.get(repo);
|
|
@@ -207,7 +243,7 @@ export function createRoundRunner({
|
|
|
207
243
|
function activeRuns(repo) {
|
|
208
244
|
const runs = active.get(repo);
|
|
209
245
|
if (runs === undefined) return [];
|
|
210
|
-
return [...runs.values()].map((run) => ({
|
|
246
|
+
return [...runs.values()].map((entry) => entry.run).filter((run) => run !== undefined).map((run) => ({
|
|
211
247
|
cardId: run.cardId,
|
|
212
248
|
role: run.role,
|
|
213
249
|
agent: run.agent,
|
|
@@ -446,11 +482,20 @@ export function createRoundRunner({
|
|
|
446
482
|
recordRun(repo, { ...run, ...patch, status, endedAt });
|
|
447
483
|
run.endedAt = endedAt;
|
|
448
484
|
run.status = status;
|
|
485
|
+
if (status === 'failed') {
|
|
486
|
+
const detail = typeof patch.reason === 'string' && patch.reason !== ''
|
|
487
|
+
? patch.reason
|
|
488
|
+
: String(patch.output ?? 'card failed');
|
|
489
|
+
emitAnomaly({ kind: 'card-failed', repo, cardId: id, role: card.role, detail });
|
|
490
|
+
}
|
|
449
491
|
unregisterActive(repo, id);
|
|
450
492
|
};
|
|
451
493
|
let activation;
|
|
452
494
|
let releaseEnv = () => {};
|
|
453
495
|
let timedOut = false;
|
|
496
|
+
// Set when the queen aborts this worker on request; the card is recorded as
|
|
497
|
+
// failed with her reason instead of turning into a round-level error.
|
|
498
|
+
let queenAbort = null;
|
|
454
499
|
let settled = false;
|
|
455
500
|
const controller = new AbortController();
|
|
456
501
|
const workerSignal = signal === undefined ? controller.signal : AbortSignal.any([signal, controller.signal]);
|
|
@@ -458,6 +503,11 @@ export function createRoundRunner({
|
|
|
458
503
|
if (controller.signal.aborted) resolve();
|
|
459
504
|
else controller.signal.addEventListener('abort', () => resolve(), { once: true });
|
|
460
505
|
});
|
|
506
|
+
setActiveAbort(repo, id, (reason) => {
|
|
507
|
+
if (queenAbort !== null) return;
|
|
508
|
+
queenAbort = typeof reason === 'string' && reason.trim() !== '' ? reason.trim() : 'aborted by the queen';
|
|
509
|
+
controller.abort();
|
|
510
|
+
});
|
|
461
511
|
let timeoutTimer;
|
|
462
512
|
let heartbeatTimer;
|
|
463
513
|
const clearMonitors = () => {
|
|
@@ -498,6 +548,13 @@ export function createRoundRunner({
|
|
|
498
548
|
if (settled) return;
|
|
499
549
|
timedOut = true;
|
|
500
550
|
controller.abort();
|
|
551
|
+
emitAnomaly({
|
|
552
|
+
kind: 'card-timeout',
|
|
553
|
+
repo,
|
|
554
|
+
cardId: id,
|
|
555
|
+
role: card.role,
|
|
556
|
+
detail: 'card timeout after ' + cardTimeoutMs + 'ms',
|
|
557
|
+
});
|
|
501
558
|
log('warn', 'card ' + id + ' in ' + repo + ' timed out after ' + cardTimeoutMs + 'ms');
|
|
502
559
|
}, cardTimeoutMs);
|
|
503
560
|
activation = await Promise.race([
|
|
@@ -553,6 +610,13 @@ export function createRoundRunner({
|
|
|
553
610
|
heartbeatWarned = true;
|
|
554
611
|
run.heartbeat = 'warn';
|
|
555
612
|
recordRun(repo, { ...run });
|
|
613
|
+
emitAnomaly({
|
|
614
|
+
kind: 'heartbeat-warn',
|
|
615
|
+
repo,
|
|
616
|
+
cardId: id,
|
|
617
|
+
role: card.role,
|
|
618
|
+
detail: 'no commit observed for ' + idle + 'ms (heartbeat warn)',
|
|
619
|
+
});
|
|
556
620
|
log('warn', 'card ' + id + ' in ' + repo + ' produced no output for ' + idle + 'ms (heartbeat warn)');
|
|
557
621
|
}
|
|
558
622
|
};
|
|
@@ -564,16 +628,45 @@ export function createRoundRunner({
|
|
|
564
628
|
settled = true;
|
|
565
629
|
clearMonitors();
|
|
566
630
|
if (timedOut) return await failCard(abortReason());
|
|
631
|
+
// A queen abort wins over whatever the provider reports afterwards: the
|
|
632
|
+
// card is failed with her reason, never a generic stopReason message.
|
|
633
|
+
if (queenAbort !== null) {
|
|
634
|
+
emitAnomaly({
|
|
635
|
+
kind: 'worker-aborted',
|
|
636
|
+
repo,
|
|
637
|
+
cardId: id,
|
|
638
|
+
role: card.role,
|
|
639
|
+
detail: 'aborted on queen request: ' + queenAbort,
|
|
640
|
+
});
|
|
641
|
+
return await failCard('aborted on request: ' + queenAbort);
|
|
642
|
+
}
|
|
567
643
|
if (outcome === null) {
|
|
644
|
+
if (queenAbort !== null) {
|
|
645
|
+
emitAnomaly({
|
|
646
|
+
kind: 'worker-aborted',
|
|
647
|
+
repo,
|
|
648
|
+
cardId: id,
|
|
649
|
+
role: card.role,
|
|
650
|
+
detail: 'aborted on queen request: ' + queenAbort,
|
|
651
|
+
});
|
|
652
|
+
return await failCard('aborted on request: ' + queenAbort);
|
|
653
|
+
}
|
|
568
654
|
// Aborted before the provider settled: report it as a round failure and
|
|
569
655
|
// let the supervisor decide (external cancellation/teardown).
|
|
656
|
+
emitAnomaly({
|
|
657
|
+
kind: 'worker-aborted',
|
|
658
|
+
repo,
|
|
659
|
+
cardId: id,
|
|
660
|
+
role: card.role,
|
|
661
|
+
detail: 'worker activation was aborted before it settled',
|
|
662
|
+
});
|
|
570
663
|
throw new RoundError('hive/round-aborted', 'worker activation was aborted before it settled');
|
|
571
664
|
}
|
|
572
665
|
if (outcome.stopReason !== 'completed') {
|
|
573
666
|
const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
|
|
574
667
|
const reason = 'subagent stopped: ' + outcome.stopReason + detail;
|
|
575
668
|
await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session });
|
|
576
|
-
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason) });
|
|
669
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason), reason });
|
|
577
670
|
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
578
671
|
return { id, state: 'failed', reason };
|
|
579
672
|
}
|
|
@@ -585,7 +678,7 @@ export function createRoundRunner({
|
|
|
585
678
|
return { id, state: 'done', sha: verdict.head };
|
|
586
679
|
}
|
|
587
680
|
await commands.fail(repo, id, { agent: claimAgent, instance, reason: verdict.reason, signal, session });
|
|
588
|
-
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason) });
|
|
681
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason), reason: verdict.reason });
|
|
589
682
|
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
590
683
|
return { id, state: 'failed', reason: verdict.reason };
|
|
591
684
|
} catch (error) {
|
|
@@ -594,6 +687,9 @@ export function createRoundRunner({
|
|
|
594
687
|
if (timedOut) {
|
|
595
688
|
return await failCard(abortReason(), messageOf(error) || abortReason());
|
|
596
689
|
}
|
|
690
|
+
if (queenAbort !== null) {
|
|
691
|
+
return await failCard('aborted on request: ' + queenAbort, messageOf(error) || 'aborted on request: ' + queenAbort);
|
|
692
|
+
}
|
|
597
693
|
if (!runFinished) finishRun('failed', { exitCode: 1, output: messageOf(error) });
|
|
598
694
|
if (isCapacityError(error)) {
|
|
599
695
|
// Capacity is a scheduling concern, not this card's failure: keep the
|
|
@@ -631,6 +727,7 @@ export function createRoundRunner({
|
|
|
631
727
|
return {
|
|
632
728
|
resolveParent,
|
|
633
729
|
activeRuns,
|
|
730
|
+
abortCard,
|
|
634
731
|
|
|
635
732
|
/**
|
|
636
733
|
* Round-start environment check: the repository must be Hive-initialised
|
package/lib/runs.js
CHANGED
|
@@ -163,6 +163,25 @@ function normalizeRecord(record) {
|
|
|
163
163
|
return normalized;
|
|
164
164
|
}
|
|
165
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Read one card's last-run record. Missing/invalid files return null; this is a
|
|
168
|
+
* read-only companion to {@link writeRunRecord} for the queen's failure triage.
|
|
169
|
+
* @param {string} repo - repository root.
|
|
170
|
+
* @param {string} cardId - Hive card id.
|
|
171
|
+
* @returns {object|null}
|
|
172
|
+
*/
|
|
173
|
+
export function readRunRecord(repo, cardId) {
|
|
174
|
+
try {
|
|
175
|
+
const { file } = runRecordPath(repo, cardId);
|
|
176
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
177
|
+
const parsed = JSON.parse(text);
|
|
178
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
179
|
+
return parsed;
|
|
180
|
+
} catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
166
185
|
/**
|
|
167
186
|
* Write (overwrite) the last-run record for one card. Best effort.
|
|
168
187
|
* @param {string} repo - repository root.
|
package/lib/supervisor.js
CHANGED
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
DEFAULT_ROLE_CONCURRENCY,
|
|
29
29
|
normalizeRepoKey,
|
|
30
30
|
} from './config.js';
|
|
31
|
+
import { filterDispatchable, gatePhase } from './gates.js';
|
|
31
32
|
import { RepoLimits, validateRoleLimits } from './limits.js';
|
|
32
33
|
import { drainQueue } from './queue.js';
|
|
33
34
|
|
|
@@ -102,12 +103,16 @@ export class HiveSupervisor {
|
|
|
102
103
|
* @param {number} [options.discoverIntervalMs]
|
|
103
104
|
* @param {() => number} [options.now]
|
|
104
105
|
* @param {(repo: string, options: object) => Promise<object[]>} [options.listReady]
|
|
106
|
+
* @param {(repo: string, options: object) => Promise<object[]>} [options.listAll] every card, for gate ordering
|
|
105
107
|
* @param {(request: object) => Promise<object>} [options.runCard]
|
|
106
108
|
* @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
|
|
107
109
|
* @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
|
|
108
110
|
* @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
|
|
109
111
|
* @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
|
|
110
112
|
* @param {() => Promise<string[]>} [options.discover]
|
|
113
|
+
* @param {(event: object) => void} [options.onAnomaly] supervision event sink (queen digest)
|
|
114
|
+
* @param {(sessionId: string) => void} [options.onQueenSession] called after a queen Session registers
|
|
115
|
+
* @param {() => number} [options.pendingAnomalies] undelivered queen anomalies reported in status
|
|
111
116
|
* @param {Console} [options.logger]
|
|
112
117
|
* @param {boolean} [options.debug]
|
|
113
118
|
*/
|
|
@@ -131,6 +136,9 @@ export class HiveSupervisor {
|
|
|
131
136
|
this.discoverIntervalMs = options.discoverIntervalMs ?? 10 * 60_000;
|
|
132
137
|
this.now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
133
138
|
this.listReady = options.listReady;
|
|
139
|
+
// Every card (any state) is the input to gate ordering; without it the
|
|
140
|
+
// supervisor dispatches everything (legacy behaviour, unit tests).
|
|
141
|
+
this.listAll = typeof options.listAll === 'function' ? options.listAll : undefined;
|
|
134
142
|
this.runCard = options.runCard;
|
|
135
143
|
this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
|
|
136
144
|
this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
|
|
@@ -138,6 +146,9 @@ export class HiveSupervisor {
|
|
|
138
146
|
// queen takes over. Nothing is dispatched until this is set.
|
|
139
147
|
this.queenSession = options.queenSession ?? { sessionId: null };
|
|
140
148
|
this.readMode = typeof options.readMode === 'function' ? options.readMode : undefined;
|
|
149
|
+
this.onAnomaly = typeof options.onAnomaly === 'function' ? options.onAnomaly : undefined;
|
|
150
|
+
this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
|
|
151
|
+
this.pendingAnomalies = typeof options.pendingAnomalies === 'function' ? options.pendingAnomalies : undefined;
|
|
141
152
|
this.discover = options.discover;
|
|
142
153
|
this.logger = options.logger === undefined ? console : options.logger;
|
|
143
154
|
this.debug = options.debug === true;
|
|
@@ -305,9 +316,60 @@ export class HiveSupervisor {
|
|
|
305
316
|
entry.nextAttemptAt = this.now();
|
|
306
317
|
}
|
|
307
318
|
this.#log('info', 'registered queen session', this.queenSession.sessionId);
|
|
319
|
+
// Let the plugin flush anomalies accumulated while no queen was live.
|
|
320
|
+
if (this.onQueenSession !== undefined) {
|
|
321
|
+
try {
|
|
322
|
+
this.onQueenSession(this.queenSession.sessionId);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
this.#log('warn', 'queen-session hook failed', messageOf(error));
|
|
325
|
+
}
|
|
326
|
+
}
|
|
308
327
|
return this.status();
|
|
309
328
|
}
|
|
310
329
|
|
|
330
|
+
/**
|
|
331
|
+
* Read every card of one repository and compute the gate phase that governs
|
|
332
|
+
* dispatch. Falls back to an explicit phase when the board read fails; a
|
|
333
|
+
* legacy configuration without `listAll` is `ungated` (no gate tags).
|
|
334
|
+
* @param {string} repo
|
|
335
|
+
* @param {AbortSignal} [signal]
|
|
336
|
+
* @returns {Promise<object>}
|
|
337
|
+
*/
|
|
338
|
+
async #gateFor(repo, signal) {
|
|
339
|
+
const entry = this.#entry(repo);
|
|
340
|
+
if (this.listAll === undefined) {
|
|
341
|
+
entry.gate = { phase: 'ungated', releaseReady: false, reason: 'gate ordering is not configured' };
|
|
342
|
+
return entry.gate;
|
|
343
|
+
}
|
|
344
|
+
try {
|
|
345
|
+
const tasks = await this.listAll(repo, { signal });
|
|
346
|
+
const gate = gatePhase(tasks);
|
|
347
|
+
entry.gate = gate;
|
|
348
|
+
return gate;
|
|
349
|
+
} catch (error) {
|
|
350
|
+
entry.gate = {
|
|
351
|
+
phase: 'unknown',
|
|
352
|
+
releaseReady: false,
|
|
353
|
+
reason: 'cannot read the full board: ' + messageOf(error),
|
|
354
|
+
};
|
|
355
|
+
this.#log('warn', 'gate phase for ' + repo + ' unavailable: ' + messageOf(error));
|
|
356
|
+
return entry.gate;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Filter a ready list through the current gate phase. Manual rounds use this
|
|
362
|
+
* so the queen's on-demand run obeys the same gate order as the resident one.
|
|
363
|
+
* @param {string} repo
|
|
364
|
+
* @param {object[]} cards ready cards from `listReady`
|
|
365
|
+
* @param {{ signal?: AbortSignal }} [options]
|
|
366
|
+
* @returns {Promise<{ cards: object[], gate: object }>}
|
|
367
|
+
*/
|
|
368
|
+
async filterDispatchable(repo, cards, options = {}) {
|
|
369
|
+
const gate = await this.#gateFor(repo, options.signal);
|
|
370
|
+
return { cards: filterDispatchable(cards, gate.phase), gate };
|
|
371
|
+
}
|
|
372
|
+
|
|
311
373
|
/** Arm the timer; the first tick runs immediately (asynchronously). */
|
|
312
374
|
start() {
|
|
313
375
|
if (this.started) return;
|
|
@@ -384,6 +446,8 @@ export class HiveSupervisor {
|
|
|
384
446
|
capacityRetryMs: this.capacityRetryMs,
|
|
385
447
|
lastTickAt: iso(this.lastTickAt),
|
|
386
448
|
lastDiscoverError: this.lastDiscoverError,
|
|
449
|
+
// Undelivered anomaly digests waiting for a live queen Session.
|
|
450
|
+
pendingAnomalies: this.#pendingAnomalyCount(),
|
|
387
451
|
repos: [...this.repos.values()]
|
|
388
452
|
.map((entry) => this.#snapshot(entry))
|
|
389
453
|
.sort((a, b) => a.repo.localeCompare(b.repo)),
|
|
@@ -457,8 +521,13 @@ export class HiveSupervisor {
|
|
|
457
521
|
const cards = await this.listReady(entry.repo, { signal });
|
|
458
522
|
entry.lastCheckAt = this.now();
|
|
459
523
|
if (entry.paused) return { repo: entry.repo, state: entry.state };
|
|
524
|
+
// Gate ordering: base work first, then gate:group, then gate:overall.
|
|
525
|
+
// A phase that is not all-green blocks the next gate; gate cards left in
|
|
526
|
+
// the ready list are simply not dispatched (they stay on the board).
|
|
527
|
+
const gate = await this.#gateFor(entry.repo, signal);
|
|
528
|
+
const dispatchable = filterDispatchable(cards, gate.phase);
|
|
460
529
|
const queuedIds = new Set(entry.queue.map((item) => item?.card?.id));
|
|
461
|
-
for (const card of Array.isArray(
|
|
530
|
+
for (const card of Array.isArray(dispatchable) ? dispatchable : []) {
|
|
462
531
|
if (typeof card?.id !== 'string' || queuedIds.has(card.id)) continue;
|
|
463
532
|
if (frozen && !(Array.isArray(card.tags) && card.tags.includes('fix'))) {
|
|
464
533
|
frozenSkipped += 1;
|
|
@@ -531,15 +600,18 @@ export class HiveSupervisor {
|
|
|
531
600
|
// failure budget (opening a session later must not be "3 failures").
|
|
532
601
|
entry.state = entry.paused ? STATES.PAUSED : STATES.BACKOFF;
|
|
533
602
|
entry.nextAttemptAt = this.now() + this.idleBackoffMs;
|
|
603
|
+
this.#anomaly({ kind: 'environment-error', repo: entry.repo, detail: entry.lastError });
|
|
534
604
|
this.#log('warn', 'deferred round for ' + entry.repo + ': ' + entry.lastError);
|
|
535
605
|
} else {
|
|
536
606
|
entry.consecutiveFailures += 1;
|
|
537
607
|
entry.lastRoundAt = this.now();
|
|
608
|
+
this.#anomaly({ kind: 'round-failed', repo: entry.repo, detail: entry.lastError });
|
|
538
609
|
if (entry.consecutiveFailures >= this.maxConsecutiveFailures) {
|
|
539
610
|
entry.paused = true;
|
|
540
611
|
entry.pausedBy = 'auto';
|
|
541
612
|
entry.pausedReason = 'auto-paused after ' + entry.consecutiveFailures + ' consecutive round failures: ' + entry.lastError;
|
|
542
613
|
entry.state = STATES.PAUSED;
|
|
614
|
+
this.#anomaly({ kind: 'auto-paused', repo: entry.repo, detail: entry.pausedReason });
|
|
543
615
|
this.#log('warn', entry.pausedReason);
|
|
544
616
|
} else {
|
|
545
617
|
entry.state = STATES.BACKOFF;
|
|
@@ -608,9 +680,32 @@ export class HiveSupervisor {
|
|
|
608
680
|
mode: entry.mode ?? null,
|
|
609
681
|
frozenSkipped: entry.frozenSkipped ?? 0,
|
|
610
682
|
lastSkipReason: entry.lastSkipReason ?? null,
|
|
683
|
+
// Gate pipeline: phase base -> group -> overall -> released, and whether
|
|
684
|
+
// a release/delivery is allowed (an overall gate exists and is all green).
|
|
685
|
+
gate: entry.gate ?? null,
|
|
611
686
|
};
|
|
612
687
|
}
|
|
613
688
|
|
|
689
|
+
/** Emit one supervision event without letting the sink break scheduling. */
|
|
690
|
+
#anomaly(event) {
|
|
691
|
+
if (this.onAnomaly === undefined) return;
|
|
692
|
+
try {
|
|
693
|
+
this.onAnomaly(event);
|
|
694
|
+
} catch (error) {
|
|
695
|
+
this.#log('warn', 'anomaly sink failed', messageOf(error));
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** Undelivered anomaly count for status; observability never throws. */
|
|
700
|
+
#pendingAnomalyCount() {
|
|
701
|
+
try {
|
|
702
|
+
const value = typeof this.pendingAnomalies === 'function' ? this.pendingAnomalies() : 0;
|
|
703
|
+
return Number.isInteger(value) && value >= 0 ? value : 0;
|
|
704
|
+
} catch {
|
|
705
|
+
return 0;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
614
709
|
/** Best-effort live worker list for status; observability never throws. */
|
|
615
710
|
#workers(repo) {
|
|
616
711
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-hive-runner",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "DSH host plugin for Hive: a resident supervisor that runs one DSH subagent per ready task card, with per-role worker limits, pause/resume and Hive tools.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|