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/events.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Queen action log: appends review decisions to `<repo>/.hive/events.jsonl`.
|
|
3
|
+
*
|
|
4
|
+
* The queen is a coordinator, not a worker: when it reviews an accepted card it
|
|
5
|
+
* records a durable `arch_review` event `{ card, verdict, findings }` instead of
|
|
6
|
+
* editing the card (the four card states stay untouched). The panel already
|
|
7
|
+
* tails `.hive/events.jsonl`, so the review is visible there and to every later
|
|
8
|
+
* patrol; `hive events` (read side) exposes the same file to the model.
|
|
9
|
+
*
|
|
10
|
+
* Append-only: records are never rewritten. A rejected review is a fact; the
|
|
11
|
+
* remediation is one or more new cards plus a `reopen --reason`.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-hive-runner/events
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
|
|
18
|
+
import { ID_RE } from './commands.js';
|
|
19
|
+
|
|
20
|
+
/** Repository-relative event log. */
|
|
21
|
+
export const EVENTS_FILE = path.join('.hive', 'events.jsonl');
|
|
22
|
+
/** Event kind written by the architecture-review gate. */
|
|
23
|
+
export const ARCH_REVIEW_KIND = 'arch_review';
|
|
24
|
+
/** Review verdicts. */
|
|
25
|
+
export const ARCH_VERDICTS = Object.freeze(['pass', 'reject']);
|
|
26
|
+
/** Maximum findings per review. */
|
|
27
|
+
export const FINDINGS_MAX = 20;
|
|
28
|
+
/** Maximum length of one finding. */
|
|
29
|
+
export const FINDING_MAX = 500;
|
|
30
|
+
/** Default read limit. */
|
|
31
|
+
export const EVENTS_READ_MAX = 200;
|
|
32
|
+
|
|
33
|
+
function text(value, max) {
|
|
34
|
+
return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Resolve the event log path, rejecting a repo that is not a usable directory path. */
|
|
38
|
+
export function eventsPath(repo) {
|
|
39
|
+
if (typeof repo !== 'string' || repo.trim() === '') throw new TypeError('eventsPath: repo is required');
|
|
40
|
+
return path.resolve(repo, EVENTS_FILE);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Normalize the review findings: an array of actionable strings.
|
|
45
|
+
* Reject decisions must have at least one finding — "不符合架构" is not a review.
|
|
46
|
+
* @param {unknown} value
|
|
47
|
+
* @param {string} verdict
|
|
48
|
+
* @returns {string[]}
|
|
49
|
+
*/
|
|
50
|
+
export function normalizeFindings(value, verdict) {
|
|
51
|
+
if (!Array.isArray(value)) throw new TypeError('findings must be an array of strings');
|
|
52
|
+
if (value.length > FINDINGS_MAX) throw new TypeError('findings must have at most ' + FINDINGS_MAX + ' entries');
|
|
53
|
+
const findings = [];
|
|
54
|
+
for (const entry of value) {
|
|
55
|
+
if (typeof entry !== 'string') throw new TypeError('every finding must be a string');
|
|
56
|
+
if (entry.includes('\u0000')) throw new TypeError('a finding must not contain NUL bytes');
|
|
57
|
+
const finding = text(entry, FINDING_MAX + 1);
|
|
58
|
+
if (finding.length > FINDING_MAX) throw new TypeError('a finding must be at most ' + FINDING_MAX + ' characters');
|
|
59
|
+
if (finding === '') continue;
|
|
60
|
+
findings.push(finding);
|
|
61
|
+
}
|
|
62
|
+
if (verdict === 'reject' && findings.length === 0) {
|
|
63
|
+
throw new TypeError('a reject review needs at least one actionable finding (file + what to change)');
|
|
64
|
+
}
|
|
65
|
+
return findings;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Append one validated event; returns the stored record. */
|
|
69
|
+
export function appendEvent(repo, event) {
|
|
70
|
+
if (event === null || typeof event !== 'object' || Array.isArray(event)) {
|
|
71
|
+
throw new TypeError('appendEvent: event must be an object');
|
|
72
|
+
}
|
|
73
|
+
const file = eventsPath(repo);
|
|
74
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
75
|
+
fs.appendFileSync(file, JSON.stringify(event) + '\n');
|
|
76
|
+
return event;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Build and append one architecture-review event.
|
|
81
|
+
* @param {string} repo
|
|
82
|
+
* @param {{ card: string, verdict: string, findings?: string[], summary?: string, actor?: string, at?: number }} review
|
|
83
|
+
* @returns {{ ts: string, actor: string, kind: string, task: string, verdict: string, findings: string[], summary?: string }}
|
|
84
|
+
*/
|
|
85
|
+
export function appendArchReview(repo, review = {}) {
|
|
86
|
+
const card = typeof review.card === 'string' ? review.card.trim() : '';
|
|
87
|
+
if (!ID_RE.test(card)) throw new TypeError('card must be a task id matching ' + String(ID_RE));
|
|
88
|
+
const verdict = typeof review.verdict === 'string' ? review.verdict.trim() : '';
|
|
89
|
+
if (!ARCH_VERDICTS.includes(verdict)) throw new TypeError('verdict must be pass or reject');
|
|
90
|
+
const findings = normalizeFindings(review.findings ?? [], verdict);
|
|
91
|
+
const event = {
|
|
92
|
+
ts: new Date(Number.isFinite(review.at) ? review.at : Date.now()).toISOString(),
|
|
93
|
+
actor: text(review.actor ?? 'queen', 64) || 'queen',
|
|
94
|
+
kind: ARCH_REVIEW_KIND,
|
|
95
|
+
task: card,
|
|
96
|
+
verdict,
|
|
97
|
+
findings,
|
|
98
|
+
};
|
|
99
|
+
const summary = text(review.summary ?? '', 300);
|
|
100
|
+
if (summary !== '') event.summary = summary;
|
|
101
|
+
return appendEvent(repo, event);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Event kind written by every queen intervention. */
|
|
105
|
+
export const INTERVENTION_KIND = 'queen_intervention';
|
|
106
|
+
/** Event kind written when a card needs a human decision. */
|
|
107
|
+
export const ESCALATION_KIND = 'queen_escalation';
|
|
108
|
+
/** Intervention actions the queen may record. */
|
|
109
|
+
export const INTERVENTION_ACTIONS = Object.freeze([
|
|
110
|
+
'reopen', 'split', 'reassign', 'pause', 'fail', 'guide', 'remove', 'rebuild', 'escalate',
|
|
111
|
+
]);
|
|
112
|
+
/** A card is escalated after this many recorded interventions without progress. */
|
|
113
|
+
export const INTERVENTION_ESCALATE_AFTER = 3;
|
|
114
|
+
/** The same card may be rebuilt (deleted + recreated) at most this many times. */
|
|
115
|
+
export const REBUILD_LIMIT = 2;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Append one `queen_intervention` event: `{ card, action, reason }` plus the
|
|
119
|
+
* extra action-specific fields (for example `newCards` for a split).
|
|
120
|
+
* @param {string} repo
|
|
121
|
+
* @param {{ card: string, action: string, reason?: string, actor?: string, at?: number } & Record<string, unknown>} intervention
|
|
122
|
+
* @returns {object} the stored event
|
|
123
|
+
*/
|
|
124
|
+
export function appendIntervention(repo, intervention = {}) {
|
|
125
|
+
const card = typeof intervention.card === 'string' ? intervention.card.trim() : '';
|
|
126
|
+
if (!ID_RE.test(card)) throw new TypeError('card must be a task id matching ' + String(ID_RE));
|
|
127
|
+
const action = typeof intervention.action === 'string' ? intervention.action.trim() : '';
|
|
128
|
+
if (!INTERVENTION_ACTIONS.includes(action)) {
|
|
129
|
+
throw new TypeError('action must be one of ' + INTERVENTION_ACTIONS.join(', '));
|
|
130
|
+
}
|
|
131
|
+
const reason = typeof intervention.reason === 'string' ? intervention.reason.trim() : '';
|
|
132
|
+
if (reason === '') throw new TypeError('a queen intervention must record a reason (the guidance for the next attempt)');
|
|
133
|
+
const event = {
|
|
134
|
+
ts: new Date(Number.isFinite(intervention.at) ? intervention.at : Date.now()).toISOString(),
|
|
135
|
+
actor: text(intervention.actor ?? 'queen', 64) || 'queen',
|
|
136
|
+
kind: INTERVENTION_KIND,
|
|
137
|
+
task: card,
|
|
138
|
+
action,
|
|
139
|
+
reason: reason.slice(0, 2000),
|
|
140
|
+
};
|
|
141
|
+
if (Array.isArray(intervention.newCards) && intervention.newCards.length > 0) {
|
|
142
|
+
event.newCards = intervention.newCards.filter((id) => typeof id === 'string' && ID_RE.test(id));
|
|
143
|
+
}
|
|
144
|
+
if (typeof intervention.sessionId === 'string' && intervention.sessionId !== '') {
|
|
145
|
+
event.sessionId = intervention.sessionId;
|
|
146
|
+
}
|
|
147
|
+
// Deleting a card must never make it disappear silently: the event carries
|
|
148
|
+
// the card's title, state and scope so the panel's event tail (and the queen's
|
|
149
|
+
// later report) still show what was removed and why.
|
|
150
|
+
const removed = intervention.removed;
|
|
151
|
+
if (removed !== null && typeof removed === 'object' && !Array.isArray(removed)) {
|
|
152
|
+
const snapshot = {};
|
|
153
|
+
if (typeof removed.title === 'string') snapshot.title = text(removed.title, 300);
|
|
154
|
+
if (typeof removed.state === 'string') snapshot.state = text(removed.state, 32);
|
|
155
|
+
if (Array.isArray(removed.scope)) {
|
|
156
|
+
snapshot.scope = removed.scope.filter((entry) => typeof entry === 'string').slice(0, 64).map((entry) => text(entry, 512));
|
|
157
|
+
}
|
|
158
|
+
if (typeof removed.reason === 'string' && removed.reason !== '') snapshot.reason = text(removed.reason, 600);
|
|
159
|
+
if (Object.keys(snapshot).length > 0) event.removed = snapshot;
|
|
160
|
+
}
|
|
161
|
+
return appendEvent(repo, event);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Append one `queen_escalation` event: the card needs a human decision.
|
|
166
|
+
* @param {string} repo
|
|
167
|
+
* @param {{ card: string, reason: string, interventions?: number, actor?: string, at?: number }} escalation
|
|
168
|
+
* @returns {object}
|
|
169
|
+
*/
|
|
170
|
+
export function appendEscalation(repo, escalation = {}) {
|
|
171
|
+
const card = typeof escalation.card === 'string' ? escalation.card.trim() : '';
|
|
172
|
+
if (!ID_RE.test(card)) throw new TypeError('card must be a task id matching ' + String(ID_RE));
|
|
173
|
+
const reason = text(escalation.reason ?? '', 2000);
|
|
174
|
+
if (reason === '') throw new TypeError('an escalation must explain where the card is stuck');
|
|
175
|
+
const event = {
|
|
176
|
+
ts: new Date(Number.isFinite(escalation.at) ? escalation.at : Date.now()).toISOString(),
|
|
177
|
+
actor: text(escalation.actor ?? 'queen', 64) || 'queen',
|
|
178
|
+
kind: ESCALATION_KIND,
|
|
179
|
+
task: card,
|
|
180
|
+
reason,
|
|
181
|
+
};
|
|
182
|
+
if (Number.isInteger(escalation.interventions) && escalation.interventions > 0) {
|
|
183
|
+
event.interventions = escalation.interventions;
|
|
184
|
+
}
|
|
185
|
+
return appendEvent(repo, event);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Count queen_intervention events per card id. */
|
|
189
|
+
export function interventionCounts(events) {
|
|
190
|
+
const counts = new Map();
|
|
191
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
192
|
+
if (event === null || typeof event !== 'object' || event.kind !== INTERVENTION_KIND) continue;
|
|
193
|
+
if (typeof event.task !== 'string') continue;
|
|
194
|
+
counts.set(event.task, (counts.get(event.task) ?? 0) + 1);
|
|
195
|
+
}
|
|
196
|
+
return counts;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Count `rebuild` interventions per card id (the same-card rebuild budget). */
|
|
200
|
+
export function rebuildCounts(events) {
|
|
201
|
+
const counts = new Map();
|
|
202
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
203
|
+
if (event === null || typeof event !== 'object' || event.kind !== INTERVENTION_KIND) continue;
|
|
204
|
+
if (event.action !== 'rebuild' || typeof event.task !== 'string') continue;
|
|
205
|
+
counts.set(event.task, (counts.get(event.task) ?? 0) + 1);
|
|
206
|
+
}
|
|
207
|
+
return counts;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Set of card ids that already have a queen_escalation event. */
|
|
211
|
+
export function escalatedCards(events) {
|
|
212
|
+
const cards = new Set();
|
|
213
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
214
|
+
if (event === null || typeof event !== 'object' || event.kind !== ESCALATION_KIND) continue;
|
|
215
|
+
if (typeof event.task === 'string') cards.add(event.task);
|
|
216
|
+
}
|
|
217
|
+
return cards;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Read the tail of the event log, newest first.
|
|
222
|
+
* @param {string} repo
|
|
223
|
+
* @param {{ limit?: number, kind?: string, task?: string }} [options]
|
|
224
|
+
* @returns {object[]}
|
|
225
|
+
*/
|
|
226
|
+
export function readEvents(repo, options = {}) {
|
|
227
|
+
const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : EVENTS_READ_MAX;
|
|
228
|
+
let text;
|
|
229
|
+
try {
|
|
230
|
+
text = fs.readFileSync(eventsPath(repo), 'utf8');
|
|
231
|
+
} catch {
|
|
232
|
+
return [];
|
|
233
|
+
}
|
|
234
|
+
const events = [];
|
|
235
|
+
for (const line of text.split('\n')) {
|
|
236
|
+
if (line === '') continue;
|
|
237
|
+
let parsed;
|
|
238
|
+
try {
|
|
239
|
+
parsed = JSON.parse(line);
|
|
240
|
+
} catch {
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
|
|
244
|
+
if (typeof options.kind === 'string' && parsed.kind !== options.kind) continue;
|
|
245
|
+
if (typeof options.task === 'string' && parsed.task !== options.task) continue;
|
|
246
|
+
events.push(parsed);
|
|
247
|
+
}
|
|
248
|
+
return events.slice(-limit).reverse();
|
|
249
|
+
}
|
package/lib/gates.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gate ordering: two labels turn the board into a release pipeline.
|
|
3
|
+
*
|
|
4
|
+
* base cards ordinary work cards (no gate tag)
|
|
5
|
+
* gate:group module/functional-group test cards
|
|
6
|
+
* gate:overall overall (smoke/e2e/regression/performance/compat/security/docs) test cards
|
|
7
|
+
*
|
|
8
|
+
* The supervisor dispatches a gate only when the previous gate is ALL GREEN:
|
|
9
|
+
*
|
|
10
|
+
* phase 'base' some base card is not done -> no gate card runs
|
|
11
|
+
* phase 'group' base all done, some group gate open -> only gate:group cards run
|
|
12
|
+
* phase 'overall' group gates all done -> only gate:overall cards run
|
|
13
|
+
* phase 'released' every overall gate card done -> releaseReady = true
|
|
14
|
+
* phase 'no-overall' base+group done but NO overall gate card exists
|
|
15
|
+
* -> release block: the repository must declare its overall gate
|
|
16
|
+
*
|
|
17
|
+
* A failed card is not green, so it blocks the next gate: the queen reopens it or
|
|
18
|
+
* removes it, or the gate stays closed. The four card states are unchanged —
|
|
19
|
+
* gates are tags plus ordinary dependencies.
|
|
20
|
+
*
|
|
21
|
+
* @module dsh-hive-runner/gates
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Tag marking a functional-group test card. */
|
|
25
|
+
export const GATE_GROUP_TAG = 'gate:group';
|
|
26
|
+
/** Tag marking an overall (release) test card. */
|
|
27
|
+
export const GATE_OVERALL_TAG = 'gate:overall';
|
|
28
|
+
|
|
29
|
+
/** The gate a card participates in, or null for an ordinary work card. */
|
|
30
|
+
export function gateOf(card) {
|
|
31
|
+
const tags = Array.isArray(card?.tags) ? card.tags : [];
|
|
32
|
+
if (tags.includes(GATE_OVERALL_TAG)) return 'overall';
|
|
33
|
+
if (tags.includes(GATE_GROUP_TAG)) return 'group';
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Compact progress of one group of cards. */
|
|
38
|
+
function progressOf(cards) {
|
|
39
|
+
const done = cards.filter((card) => card.state === 'done').length;
|
|
40
|
+
return {
|
|
41
|
+
total: cards.length,
|
|
42
|
+
done,
|
|
43
|
+
outstanding: cards.length - done,
|
|
44
|
+
failed: cards.filter((card) => card.state === 'failed').length,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Compute the current gate phase and whether a release is allowed.
|
|
50
|
+
* @param {object[]} tasks all cards of one repository (any state)
|
|
51
|
+
* @returns {{ phase: string, base: object, group: object, overall: object, releaseReady: boolean, reason: string }}
|
|
52
|
+
*/
|
|
53
|
+
export function gatePhase(tasks) {
|
|
54
|
+
// Draft and superseded cards are not work: they never gate progress.
|
|
55
|
+
// (Both are flags on a four-state card, never states.)
|
|
56
|
+
const cards = Array.isArray(tasks)
|
|
57
|
+
? tasks.filter((card) => card !== null && typeof card === 'object'
|
|
58
|
+
&& card.draft !== true && card.superseded !== true)
|
|
59
|
+
: [];
|
|
60
|
+
const base = cards.filter((card) => gateOf(card) === null);
|
|
61
|
+
const group = cards.filter((card) => gateOf(card) === 'group');
|
|
62
|
+
const overall = cards.filter((card) => gateOf(card) === 'overall');
|
|
63
|
+
const state = {
|
|
64
|
+
base: progressOf(base),
|
|
65
|
+
group: progressOf(group),
|
|
66
|
+
overall: progressOf(overall),
|
|
67
|
+
releaseReady: false,
|
|
68
|
+
reason: '',
|
|
69
|
+
};
|
|
70
|
+
if (state.base.outstanding > 0) {
|
|
71
|
+
return { ...state, phase: 'base', reason: 'waiting for ' + state.base.outstanding + ' base card(s) to finish' };
|
|
72
|
+
}
|
|
73
|
+
if (state.group.outstanding > 0) {
|
|
74
|
+
return { ...state, phase: 'group', reason: 'waiting for ' + state.group.outstanding + ' group gate card(s)' };
|
|
75
|
+
}
|
|
76
|
+
if (state.overall.total === 0) {
|
|
77
|
+
return {
|
|
78
|
+
...state,
|
|
79
|
+
phase: 'no-overall',
|
|
80
|
+
reason: 'no overall gate card: add cards tagged ' + GATE_OVERALL_TAG + ' (smoke/e2e/regression/...) before release',
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (state.overall.outstanding > 0) {
|
|
84
|
+
return { ...state, phase: 'overall', reason: 'waiting for ' + state.overall.outstanding + ' overall gate card(s)' };
|
|
85
|
+
}
|
|
86
|
+
return { ...state, phase: 'released', releaseReady: true, reason: 'all gates green; release is allowed' };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Whether one card may be dispatched in the current phase. */
|
|
90
|
+
export function gateAllows(card, phase) {
|
|
91
|
+
const gate = gateOf(card);
|
|
92
|
+
if (gate === null) return phase === 'base' || phase === 'ungated' || phase === 'unknown';
|
|
93
|
+
if (gate === 'group') return phase === 'group';
|
|
94
|
+
return phase === 'overall';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Filter a ready list down to the cards the current phase allows. */
|
|
98
|
+
export function filterDispatchable(cards, phase) {
|
|
99
|
+
const list = Array.isArray(cards) ? cards : [];
|
|
100
|
+
return list.filter((card) => gateAllows(card, phase));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export default gatePhase;
|
package/lib/http.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* (RESEARCH.md §3.2). JSON in, JSON out.
|
|
7
7
|
*
|
|
8
8
|
* GET /api/hive-runner?op=status
|
|
9
|
+
* GET /api/hive-runner?op=pending undelivered queen anomalies
|
|
10
|
+
* POST /api/hive-runner?op=ack { ids } mark anomalies as delivered
|
|
9
11
|
* POST /api/hive-runner?op=pause { repo }
|
|
10
12
|
* POST /api/hive-runner?op=resume { repo }
|
|
11
13
|
* POST /api/hive-runner?op=limits { repo, roleLimits: { role: number } }
|
|
@@ -41,9 +43,10 @@ async function readPayload(request) {
|
|
|
41
43
|
* Handle one request against a supervisor instance.
|
|
42
44
|
* @param {Request} request
|
|
43
45
|
* @param {import('./supervisor.js').HiveSupervisor} supervisor
|
|
46
|
+
* @param {{ list: Function, pendingCount: Function, markDelivered: Function }} [anomalies] anomaly feed (optional)
|
|
44
47
|
* @returns {Promise<Response>}
|
|
45
48
|
*/
|
|
46
|
-
export async function handleHiveRunnerRequest(request, supervisor) {
|
|
49
|
+
export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
47
50
|
const url = new URL(request.url);
|
|
48
51
|
const payload = await readPayload(request);
|
|
49
52
|
const op = url.searchParams.get('op') ?? (typeof payload.op === 'string' ? payload.op : null);
|
|
@@ -52,6 +55,35 @@ export async function handleHiveRunnerRequest(request, supervisor) {
|
|
|
52
55
|
if (op === 'status') {
|
|
53
56
|
return json({ ok: true, op: 'status', ...supervisor.status() });
|
|
54
57
|
}
|
|
58
|
+
if (op === 'pending') {
|
|
59
|
+
const pendingOnly = url.searchParams.get('all') !== '1';
|
|
60
|
+
let items = [];
|
|
61
|
+
let count = 0;
|
|
62
|
+
try {
|
|
63
|
+
items = anomalies === undefined ? [] : anomalies.list({ pendingOnly });
|
|
64
|
+
count = anomalies === undefined ? 0 : anomalies.pendingCount();
|
|
65
|
+
} catch {
|
|
66
|
+
items = [];
|
|
67
|
+
count = 0;
|
|
68
|
+
}
|
|
69
|
+
return json({ ok: true, op: 'pending', count, items });
|
|
70
|
+
}
|
|
71
|
+
if (op === 'ack') {
|
|
72
|
+
if (request.method !== 'POST') {
|
|
73
|
+
return failure(op, 'hive/method-not-allowed', 'op=ack requires POST', 405);
|
|
74
|
+
}
|
|
75
|
+
const ids = Array.isArray(payload.ids) ? payload.ids.filter((id) => typeof id === 'string' && id !== '') : [];
|
|
76
|
+
if (ids.length === 0) {
|
|
77
|
+
return failure(op, 'hive/missing-ids', 'ids is required (JSON array of anomaly ids)', 400);
|
|
78
|
+
}
|
|
79
|
+
let changed = 0;
|
|
80
|
+
try {
|
|
81
|
+
changed = anomalies === undefined ? 0 : anomalies.markDelivered(ids);
|
|
82
|
+
} catch {
|
|
83
|
+
changed = 0;
|
|
84
|
+
}
|
|
85
|
+
return json({ ok: true, op: 'ack', changed });
|
|
86
|
+
}
|
|
55
87
|
if (op === 'pause' || op === 'resume') {
|
|
56
88
|
if (typeof repo !== 'string' || repo.trim() === '') {
|
|
57
89
|
return failure(op, 'hive/missing-repo', 'repo is required (query parameter or JSON body field)', 400);
|
|
@@ -120,18 +152,24 @@ export async function handleHiveRunnerRequest(request, supervisor) {
|
|
|
120
152
|
return failure(op, 'hive/internal', error instanceof Error ? error.message : String(error), 500);
|
|
121
153
|
}
|
|
122
154
|
}
|
|
123
|
-
return failure(
|
|
155
|
+
return failure(
|
|
156
|
+
op,
|
|
157
|
+
'hive/unknown-op',
|
|
158
|
+
'unknown op ' + JSON.stringify(op) + '; use status, pending, ack, queen, pause, resume or limits',
|
|
159
|
+
400,
|
|
160
|
+
);
|
|
124
161
|
}
|
|
125
162
|
|
|
126
163
|
/**
|
|
127
164
|
* Build the Connection Fetch route descriptor.
|
|
128
165
|
* @param {import('./supervisor.js').HiveSupervisor} supervisor
|
|
166
|
+
* @param {{ anomalies?: object }} [options]
|
|
129
167
|
*/
|
|
130
|
-
export function createHiveRunnerRoute(supervisor) {
|
|
168
|
+
export function createHiveRunnerRoute(supervisor, options = {}) {
|
|
131
169
|
return {
|
|
132
170
|
path: HIVE_RUNNER_PATH,
|
|
133
171
|
methods: ['GET', 'POST'],
|
|
134
172
|
requestBody: 'buffered',
|
|
135
|
-
fetch: (request) => handleHiveRunnerRequest(request, supervisor),
|
|
173
|
+
fetch: (request) => handleHiveRunnerRequest(request, supervisor, options.anomalies),
|
|
136
174
|
};
|
|
137
175
|
}
|
package/lib/notify.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deliver a queen-facing message through the live DSH Agent.
|
|
3
|
+
*
|
|
4
|
+
* A host plugin may inject user-role messages into a live Session through the
|
|
5
|
+
* public `Agent` API (`followup`, `steer`, `inject`). The message is an ordinary
|
|
6
|
+
* identified UserMessage: `{ id, role: 'user', content, source }`. Its source
|
|
7
|
+
* kind is this plugin's name — the session log only requires a non-empty string
|
|
8
|
+
* kind and consumers fall through unknown producers, so no DSH change is needed.
|
|
9
|
+
*
|
|
10
|
+
* Delivery policy:
|
|
11
|
+
* - `followup` — queue an ordinary next-turn prompt and wake the driver. This
|
|
12
|
+
* is what an anomaly digest wants: the queen should act even when idle;
|
|
13
|
+
* - `steer` — only if a future Agent lacks `followup`; consumed at the next
|
|
14
|
+
* step boundary of the running turn;
|
|
15
|
+
* - `inject` — last resort; context without waking (the next patrol retries).
|
|
16
|
+
*
|
|
17
|
+
* No live Session (panel closed, agent disposed, DSH headless): delivery reports
|
|
18
|
+
* `no-live-queen-session` and the caller keeps the digest in the pending list.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-hive-runner/notify
|
|
21
|
+
*/
|
|
22
|
+
import { randomUUID } from 'node:crypto';
|
|
23
|
+
|
|
24
|
+
/** Message source kind recorded in the Session log. */
|
|
25
|
+
export const QUEEN_NOTICE_SOURCE = 'hive-runner';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* One identified user-role message. Mirrors `createUserMessage` from
|
|
29
|
+
* `@deepseek-ai/dsh-llm` without importing the package (the runner must stay a
|
|
30
|
+
* one-peer-dependency plugin): identity is a fresh UUID, content is one text
|
|
31
|
+
* block, and the source kind marks the producer.
|
|
32
|
+
* @param {string} body
|
|
33
|
+
* @param {string} [source]
|
|
34
|
+
* @returns {{ id: string, role: 'user', content: Array<{ type: 'text', text: string }>, source: { kind: string } }}
|
|
35
|
+
*/
|
|
36
|
+
export function createQueenMessage(body, source = QUEEN_NOTICE_SOURCE) {
|
|
37
|
+
return {
|
|
38
|
+
id: randomUUID(),
|
|
39
|
+
role: 'user',
|
|
40
|
+
content: [{ type: 'text', text: String(body) }],
|
|
41
|
+
source: { kind: typeof source === 'string' && source !== '' ? source : QUEEN_NOTICE_SOURCE },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Resolve the live Agent for the registered queen Session, if any. */
|
|
46
|
+
export function resolveQueenAgent(ctx, queenSession) {
|
|
47
|
+
const sessionId = queenSession?.sessionId;
|
|
48
|
+
if (typeof sessionId !== 'string' || sessionId === '') return undefined;
|
|
49
|
+
try {
|
|
50
|
+
const agents = typeof ctx?.get === 'function' ? ctx.get('agents') : undefined;
|
|
51
|
+
const agent = typeof agents?.get === 'function' ? agents.get(sessionId) : undefined;
|
|
52
|
+
return agent === null ? undefined : agent;
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Resolve one live Agent by Session id (worker guidance uses this too). */
|
|
59
|
+
export function resolveAgent(ctx, sessionId) {
|
|
60
|
+
if (typeof sessionId !== 'string' || sessionId === '') return undefined;
|
|
61
|
+
try {
|
|
62
|
+
const agents = typeof ctx?.get === 'function' ? ctx.get('agents') : undefined;
|
|
63
|
+
const agent = typeof agents?.get === 'function' ? agents.get(sessionId) : undefined;
|
|
64
|
+
return agent === null ? undefined : agent;
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Deliver one user-role message to an arbitrary live Session (worker guidance).
|
|
72
|
+
* A running agent gets `steer` (next step boundary); an idle agent gets
|
|
73
|
+
* `followup` (starts a turn). Falls back through the available inbox methods.
|
|
74
|
+
* @param {{ ctx: object }} options
|
|
75
|
+
* @param {string} sessionId
|
|
76
|
+
* @param {string} body
|
|
77
|
+
* @param {{ prefer?: 'steer' | 'followup' | 'inject' }} [delivery]
|
|
78
|
+
* @returns {{ delivered: boolean, via?: string, reason?: string, error?: string }}
|
|
79
|
+
*/
|
|
80
|
+
export function deliverToSession({ ctx } = {}, sessionId, body, delivery = {}) {
|
|
81
|
+
if (typeof body !== 'string' || body.trim() === '') return { delivered: false, reason: 'empty-message' };
|
|
82
|
+
const agent = resolveAgent(ctx, sessionId);
|
|
83
|
+
if (agent === undefined) return { delivered: false, reason: 'no-live-session' };
|
|
84
|
+
const message = createQueenMessage(body);
|
|
85
|
+
const prefer = delivery.prefer;
|
|
86
|
+
const order = prefer === 'followup'
|
|
87
|
+
? ['followup', 'steer', 'inject']
|
|
88
|
+
: prefer === 'inject'
|
|
89
|
+
? ['inject', 'followup', 'steer']
|
|
90
|
+
: ['steer', 'followup', 'inject'];
|
|
91
|
+
for (const method of order) {
|
|
92
|
+
if (typeof agent[method] !== 'function') continue;
|
|
93
|
+
try {
|
|
94
|
+
agent[method](message);
|
|
95
|
+
return { delivered: true, via: method };
|
|
96
|
+
} catch (error) {
|
|
97
|
+
return { delivered: false, reason: 'delivery-failed', error: error instanceof Error ? error.message : String(error) };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { delivered: false, reason: 'no-inbox-api' };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Create the delivery facade.
|
|
105
|
+
* @param {{ ctx: object, queenSession: { sessionId: string|null }, log?: (level: string, ...args: unknown[]) => void }} options
|
|
106
|
+
* @returns {{ deliver: (body: string) => { delivered: boolean, via?: string, reason?: string }, hasLiveQueen: () => boolean }}
|
|
107
|
+
*/
|
|
108
|
+
export function createQueenNotifier({ ctx, queenSession, log = () => {} } = {}) {
|
|
109
|
+
const target = () => resolveQueenAgent(ctx, queenSession);
|
|
110
|
+
|
|
111
|
+
function deliver(body) {
|
|
112
|
+
if (typeof body !== 'string' || body.trim() === '') {
|
|
113
|
+
return { delivered: false, reason: 'empty-digest' };
|
|
114
|
+
}
|
|
115
|
+
const agent = target();
|
|
116
|
+
if (agent === undefined) return { delivered: false, reason: 'no-live-queen-session' };
|
|
117
|
+
const message = createQueenMessage(body);
|
|
118
|
+
try {
|
|
119
|
+
if (typeof agent.followup === 'function') {
|
|
120
|
+
agent.followup(message);
|
|
121
|
+
return { delivered: true, via: 'followup' };
|
|
122
|
+
}
|
|
123
|
+
if (typeof agent.steer === 'function') {
|
|
124
|
+
agent.steer(message);
|
|
125
|
+
return { delivered: true, via: 'steer' };
|
|
126
|
+
}
|
|
127
|
+
if (typeof agent.inject === 'function') {
|
|
128
|
+
agent.inject(message);
|
|
129
|
+
return { delivered: true, via: 'inject' };
|
|
130
|
+
}
|
|
131
|
+
return { delivered: false, reason: 'no-inbox-api' };
|
|
132
|
+
} catch (error) {
|
|
133
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
134
|
+
log('warn', 'queen message delivery failed: ' + reason);
|
|
135
|
+
return { delivered: false, reason: 'delivery-failed', error: reason };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
deliver,
|
|
141
|
+
hasLiveQueen: () => target() !== undefined,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export default createQueenNotifier;
|