dsh-hive-runner 0.6.7 → 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 +67 -0
- package/README.md +284 -116
- package/README.zh-CN.md +197 -72
- package/SPEC.md +162 -60
- package/cordis.patch.yml +24 -4
- package/docs/DESIGN.md +88 -42
- package/index.js +595 -37
- package/lib/anomalies.js +216 -0
- package/lib/audit.js +134 -0
- package/lib/commands.js +266 -3
- package/lib/config.js +24 -0
- package/lib/events.js +249 -0
- package/lib/gates.js +101 -0
- package/lib/http.js +42 -4
- package/lib/notify.js +145 -0
- package/lib/patrol.js +218 -0
- package/lib/round.js +45 -3
- package/lib/runs.js +19 -0
- package/lib/supervisor.js +96 -1
- package/package.json +1 -1
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/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;
|
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,6 +190,18 @@ export function createRoundRunner({
|
|
|
187
190
|
// The record file is a convenience for the panel, not part of the verdict.
|
|
188
191
|
}
|
|
189
192
|
}
|
|
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
|
+
}
|
|
190
205
|
/** repo -> Map(cardId, active run descriptor) for the status endpoint. */
|
|
191
206
|
const active = new Map();
|
|
192
207
|
function registerActive(repo, run) {
|
|
@@ -446,6 +461,12 @@ export function createRoundRunner({
|
|
|
446
461
|
recordRun(repo, { ...run, ...patch, status, endedAt });
|
|
447
462
|
run.endedAt = endedAt;
|
|
448
463
|
run.status = status;
|
|
464
|
+
if (status === 'failed') {
|
|
465
|
+
const detail = typeof patch.reason === 'string' && patch.reason !== ''
|
|
466
|
+
? patch.reason
|
|
467
|
+
: String(patch.output ?? 'card failed');
|
|
468
|
+
emitAnomaly({ kind: 'card-failed', repo, cardId: id, role: card.role, detail });
|
|
469
|
+
}
|
|
449
470
|
unregisterActive(repo, id);
|
|
450
471
|
};
|
|
451
472
|
let activation;
|
|
@@ -498,6 +519,13 @@ export function createRoundRunner({
|
|
|
498
519
|
if (settled) return;
|
|
499
520
|
timedOut = true;
|
|
500
521
|
controller.abort();
|
|
522
|
+
emitAnomaly({
|
|
523
|
+
kind: 'card-timeout',
|
|
524
|
+
repo,
|
|
525
|
+
cardId: id,
|
|
526
|
+
role: card.role,
|
|
527
|
+
detail: 'card timeout after ' + cardTimeoutMs + 'ms',
|
|
528
|
+
});
|
|
501
529
|
log('warn', 'card ' + id + ' in ' + repo + ' timed out after ' + cardTimeoutMs + 'ms');
|
|
502
530
|
}, cardTimeoutMs);
|
|
503
531
|
activation = await Promise.race([
|
|
@@ -553,6 +581,13 @@ export function createRoundRunner({
|
|
|
553
581
|
heartbeatWarned = true;
|
|
554
582
|
run.heartbeat = 'warn';
|
|
555
583
|
recordRun(repo, { ...run });
|
|
584
|
+
emitAnomaly({
|
|
585
|
+
kind: 'heartbeat-warn',
|
|
586
|
+
repo,
|
|
587
|
+
cardId: id,
|
|
588
|
+
role: card.role,
|
|
589
|
+
detail: 'no commit observed for ' + idle + 'ms (heartbeat warn)',
|
|
590
|
+
});
|
|
556
591
|
log('warn', 'card ' + id + ' in ' + repo + ' produced no output for ' + idle + 'ms (heartbeat warn)');
|
|
557
592
|
}
|
|
558
593
|
};
|
|
@@ -567,13 +602,20 @@ export function createRoundRunner({
|
|
|
567
602
|
if (outcome === null) {
|
|
568
603
|
// Aborted before the provider settled: report it as a round failure and
|
|
569
604
|
// let the supervisor decide (external cancellation/teardown).
|
|
605
|
+
emitAnomaly({
|
|
606
|
+
kind: 'worker-aborted',
|
|
607
|
+
repo,
|
|
608
|
+
cardId: id,
|
|
609
|
+
role: card.role,
|
|
610
|
+
detail: 'worker activation was aborted before it settled',
|
|
611
|
+
});
|
|
570
612
|
throw new RoundError('hive/round-aborted', 'worker activation was aborted before it settled');
|
|
571
613
|
}
|
|
572
614
|
if (outcome.stopReason !== 'completed') {
|
|
573
615
|
const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
|
|
574
616
|
const reason = 'subagent stopped: ' + outcome.stopReason + detail;
|
|
575
617
|
await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session });
|
|
576
|
-
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason) });
|
|
618
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason), reason });
|
|
577
619
|
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
578
620
|
return { id, state: 'failed', reason };
|
|
579
621
|
}
|
|
@@ -585,7 +627,7 @@ export function createRoundRunner({
|
|
|
585
627
|
return { id, state: 'done', sha: verdict.head };
|
|
586
628
|
}
|
|
587
629
|
await commands.fail(repo, id, { agent: claimAgent, instance, reason: verdict.reason, signal, session });
|
|
588
|
-
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason) });
|
|
630
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason), reason: verdict.reason });
|
|
589
631
|
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
590
632
|
return { id, state: 'failed', reason: verdict.reason };
|
|
591
633
|
} catch (error) {
|
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.
|