dsh-hive-runner 0.6.4 → 0.7.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 +179 -0
- package/README.md +297 -100
- package/README.zh-CN.md +203 -63
- package/SPEC.md +227 -61
- package/cordis.patch.yml +38 -6
- package/docs/DESIGN.md +122 -31
- package/index.js +617 -37
- package/lib/anomalies.js +216 -0
- package/lib/audit.js +134 -0
- package/lib/commands.js +282 -12
- package/lib/config.js +51 -1
- package/lib/events.js +249 -0
- package/lib/gates.js +101 -0
- package/lib/host-env.js +51 -22
- package/lib/http.js +59 -4
- package/lib/notify.js +145 -0
- package/lib/patrol.js +218 -0
- package/lib/round.js +430 -124
- package/lib/runs.js +96 -4
- package/lib/supervisor.js +152 -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,101 @@
|
|
|
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 cards are notes, not work (hive-tasks 1.8+): they never gate progress.
|
|
55
|
+
const cards = Array.isArray(tasks)
|
|
56
|
+
? tasks.filter((card) => card !== null && typeof card === 'object' && card.draft !== true)
|
|
57
|
+
: [];
|
|
58
|
+
const base = cards.filter((card) => gateOf(card) === null);
|
|
59
|
+
const group = cards.filter((card) => gateOf(card) === 'group');
|
|
60
|
+
const overall = cards.filter((card) => gateOf(card) === 'overall');
|
|
61
|
+
const state = {
|
|
62
|
+
base: progressOf(base),
|
|
63
|
+
group: progressOf(group),
|
|
64
|
+
overall: progressOf(overall),
|
|
65
|
+
releaseReady: false,
|
|
66
|
+
reason: '',
|
|
67
|
+
};
|
|
68
|
+
if (state.base.outstanding > 0) {
|
|
69
|
+
return { ...state, phase: 'base', reason: 'waiting for ' + state.base.outstanding + ' base card(s) to finish' };
|
|
70
|
+
}
|
|
71
|
+
if (state.group.outstanding > 0) {
|
|
72
|
+
return { ...state, phase: 'group', reason: 'waiting for ' + state.group.outstanding + ' group gate card(s)' };
|
|
73
|
+
}
|
|
74
|
+
if (state.overall.total === 0) {
|
|
75
|
+
return {
|
|
76
|
+
...state,
|
|
77
|
+
phase: 'no-overall',
|
|
78
|
+
reason: 'no overall gate card: add cards tagged ' + GATE_OVERALL_TAG + ' (smoke/e2e/regression/...) before release',
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
if (state.overall.outstanding > 0) {
|
|
82
|
+
return { ...state, phase: 'overall', reason: 'waiting for ' + state.overall.outstanding + ' overall gate card(s)' };
|
|
83
|
+
}
|
|
84
|
+
return { ...state, phase: 'released', releaseReady: true, reason: 'all gates green; release is allowed' };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Whether one card may be dispatched in the current phase. */
|
|
88
|
+
export function gateAllows(card, phase) {
|
|
89
|
+
const gate = gateOf(card);
|
|
90
|
+
if (gate === null) return phase === 'base' || phase === 'ungated' || phase === 'unknown';
|
|
91
|
+
if (gate === 'group') return phase === 'group';
|
|
92
|
+
return phase === 'overall';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Filter a ready list down to the cards the current phase allows. */
|
|
96
|
+
export function filterDispatchable(cards, phase) {
|
|
97
|
+
const list = Array.isArray(cards) ? cards : [];
|
|
98
|
+
return list.filter((card) => gateAllows(card, phase));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export default gatePhase;
|
package/lib/host-env.js
CHANGED
|
@@ -1,45 +1,74 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Scoped `HIVE_AGENT` injection for worker subagents.
|
|
2
|
+
* Scoped `HIVE_AGENT` / `HIVE_INSTANCE` injection for worker subagents.
|
|
3
3
|
*
|
|
4
4
|
* DSH's subagent seam runs workers in the host process and the model-facing
|
|
5
5
|
* bash tool inherits ambient environment variables (grep/subprocess scrub only
|
|
6
|
-
* credential-shaped and DSH_* names). The plugin therefore injects
|
|
7
|
-
*
|
|
8
|
-
* `
|
|
9
|
-
*
|
|
6
|
+
* credential-shaped and DSH_* names). The plugin therefore injects the identity
|
|
7
|
+
* explicitly while a worker is alive, so the worker's `hive guard`,
|
|
8
|
+
* `hive release`, `hive recall` and `git commit` commands agree with the
|
|
9
|
+
* runner's own consensus calls.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* `HIVE_AGENT` is the shared runner identity; `HIVE_INSTANCE` distinguishes
|
|
12
|
+
* the concurrent workers of one runner. hive-consensus falls back to the agent
|
|
13
|
+
* name when `HIVE_INSTANCE` is unset, which would make two workers of the same
|
|
14
|
+
* runner look like the same announcer and hide every overlap — so the runner
|
|
15
|
+
* passes the card id as the per-card instance.
|
|
16
|
+
*
|
|
17
|
+
* The values are reference-counted; the previous environment is restored when
|
|
18
|
+
* the last worker finishes. Several workers can be alive at once in one drain,
|
|
19
|
+
* so the most recently acquired identity is the one visible to the model-facing
|
|
20
|
+
* bash tool (the runner's own Hive commands always pass the identity explicitly).
|
|
14
21
|
*/
|
|
15
22
|
|
|
16
|
-
|
|
23
|
+
const holders = [];
|
|
17
24
|
let saved;
|
|
18
25
|
|
|
26
|
+
function remember() {
|
|
27
|
+
return { agent: process.env.HIVE_AGENT, instance: process.env.HIVE_INSTANCE };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function apply(holder) {
|
|
31
|
+
process.env.HIVE_AGENT = holder.agent;
|
|
32
|
+
process.env.HIVE_INSTANCE = holder.instance;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function restore(values) {
|
|
36
|
+
if (values === undefined) return;
|
|
37
|
+
if (values.agent === undefined) delete process.env.HIVE_AGENT;
|
|
38
|
+
else process.env.HIVE_AGENT = values.agent;
|
|
39
|
+
if (values.instance === undefined) delete process.env.HIVE_INSTANCE;
|
|
40
|
+
else process.env.HIVE_INSTANCE = values.instance;
|
|
41
|
+
}
|
|
42
|
+
|
|
19
43
|
/**
|
|
20
|
-
* Set `
|
|
44
|
+
* Set `HIVE_AGENT` and `HIVE_INSTANCE` for the duration of one worker.
|
|
21
45
|
* @param {string} agent claim identity
|
|
46
|
+
* @param {string} [instance] per-card instance (the card id); defaults to the agent
|
|
22
47
|
* @returns {() => void} idempotent release
|
|
23
48
|
*/
|
|
24
|
-
export function acquireHiveAgentEnv(agent) {
|
|
49
|
+
export function acquireHiveAgentEnv(agent, instance) {
|
|
25
50
|
if (typeof agent !== 'string' || agent.trim() === '') return () => {};
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
51
|
+
const agentName = agent.trim();
|
|
52
|
+
const instanceName = typeof instance === 'string' && instance.trim() !== '' ? instance.trim() : agentName;
|
|
53
|
+
if (holders.length === 0) saved = remember();
|
|
54
|
+
const holder = { agent: agentName, instance: instanceName, released: false };
|
|
55
|
+
holders.push(holder);
|
|
56
|
+
apply(holder);
|
|
30
57
|
return () => {
|
|
31
|
-
if (released) return;
|
|
32
|
-
released = true;
|
|
33
|
-
|
|
34
|
-
if (
|
|
35
|
-
|
|
36
|
-
|
|
58
|
+
if (holder.released) return;
|
|
59
|
+
holder.released = true;
|
|
60
|
+
const index = holders.indexOf(holder);
|
|
61
|
+
if (index !== -1) holders.splice(index, 1);
|
|
62
|
+
if (holders.length === 0) {
|
|
63
|
+
restore(saved);
|
|
37
64
|
saved = undefined;
|
|
65
|
+
} else {
|
|
66
|
+
apply(holders[holders.length - 1]);
|
|
38
67
|
}
|
|
39
68
|
};
|
|
40
69
|
}
|
|
41
70
|
|
|
42
71
|
/** Current number of active worker env holders (diagnostics/tests). */
|
|
43
72
|
export function activeHiveAgentHolders() {
|
|
44
|
-
return
|
|
73
|
+
return holders.length;
|
|
45
74
|
}
|
package/lib/http.js
CHANGED
|
@@ -6,9 +6,12 @@
|
|
|
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 } }
|
|
14
|
+
* POST /api/hive-runner?op=queen { sessionId }
|
|
12
15
|
*/
|
|
13
16
|
import { normalizeRepoKey } from './config.js';
|
|
14
17
|
import { UnknownRepoError } from './supervisor.js';
|
|
@@ -40,9 +43,10 @@ async function readPayload(request) {
|
|
|
40
43
|
* Handle one request against a supervisor instance.
|
|
41
44
|
* @param {Request} request
|
|
42
45
|
* @param {import('./supervisor.js').HiveSupervisor} supervisor
|
|
46
|
+
* @param {{ list: Function, pendingCount: Function, markDelivered: Function }} [anomalies] anomaly feed (optional)
|
|
43
47
|
* @returns {Promise<Response>}
|
|
44
48
|
*/
|
|
45
|
-
export async function handleHiveRunnerRequest(request, supervisor) {
|
|
49
|
+
export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
46
50
|
const url = new URL(request.url);
|
|
47
51
|
const payload = await readPayload(request);
|
|
48
52
|
const op = url.searchParams.get('op') ?? (typeof payload.op === 'string' ? payload.op : null);
|
|
@@ -51,6 +55,35 @@ export async function handleHiveRunnerRequest(request, supervisor) {
|
|
|
51
55
|
if (op === 'status') {
|
|
52
56
|
return json({ ok: true, op: 'status', ...supervisor.status() });
|
|
53
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
|
+
}
|
|
54
87
|
if (op === 'pause' || op === 'resume') {
|
|
55
88
|
if (typeof repo !== 'string' || repo.trim() === '') {
|
|
56
89
|
return failure(op, 'hive/missing-repo', 'repo is required (query parameter or JSON body field)', 400);
|
|
@@ -74,6 +107,22 @@ export async function handleHiveRunnerRequest(request, supervisor) {
|
|
|
74
107
|
return failure(op, 'hive/internal', error instanceof Error ? error.message : String(error), 500);
|
|
75
108
|
}
|
|
76
109
|
}
|
|
110
|
+
if (op === 'queen') {
|
|
111
|
+
if (request.method !== 'POST') {
|
|
112
|
+
return failure(op, 'hive/method-not-allowed', 'op=queen requires POST', 405);
|
|
113
|
+
}
|
|
114
|
+
const sessionId = typeof payload.sessionId === 'string'
|
|
115
|
+
? payload.sessionId
|
|
116
|
+
: url.searchParams.get('sessionId');
|
|
117
|
+
if (typeof sessionId !== 'string' || sessionId.trim() === '') {
|
|
118
|
+
return failure(op, 'hive/missing-session-id', 'sessionId is required (JSON body field)', 400);
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return json({ ok: true, op: 'queen', ...supervisor.setQueenSession(sessionId) });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
return failure(op, 'hive/invalid-session-id', error instanceof Error ? error.message : String(error), 400);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
77
126
|
if (op === 'limits') {
|
|
78
127
|
if (request.method !== 'POST') {
|
|
79
128
|
return failure(op, 'hive/method-not-allowed', 'op=limits requires POST', 405);
|
|
@@ -103,18 +152,24 @@ export async function handleHiveRunnerRequest(request, supervisor) {
|
|
|
103
152
|
return failure(op, 'hive/internal', error instanceof Error ? error.message : String(error), 500);
|
|
104
153
|
}
|
|
105
154
|
}
|
|
106
|
-
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
|
+
);
|
|
107
161
|
}
|
|
108
162
|
|
|
109
163
|
/**
|
|
110
164
|
* Build the Connection Fetch route descriptor.
|
|
111
165
|
* @param {import('./supervisor.js').HiveSupervisor} supervisor
|
|
166
|
+
* @param {{ anomalies?: object }} [options]
|
|
112
167
|
*/
|
|
113
|
-
export function createHiveRunnerRoute(supervisor) {
|
|
168
|
+
export function createHiveRunnerRoute(supervisor, options = {}) {
|
|
114
169
|
return {
|
|
115
170
|
path: HIVE_RUNNER_PATH,
|
|
116
171
|
methods: ['GET', 'POST'],
|
|
117
172
|
requestBody: 'buffered',
|
|
118
|
-
fetch: (request) => handleHiveRunnerRequest(request, supervisor),
|
|
173
|
+
fetch: (request) => handleHiveRunnerRequest(request, supervisor, options.anomalies),
|
|
119
174
|
};
|
|
120
175
|
}
|