dsh-hive-runner 0.6.1 → 0.6.7
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 +162 -0
- package/README.md +76 -38
- package/README.zh-CN.md +48 -29
- package/SPEC.md +97 -14
- package/cordis.patch.yml +17 -2
- package/docs/DESIGN.md +48 -2
- package/index.js +26 -4
- package/lib/commands.js +101 -9
- package/lib/config.js +28 -1
- package/lib/host-env.js +74 -0
- package/lib/http.js +18 -1
- package/lib/round.js +444 -100
- package/lib/runs.js +184 -0
- package/lib/shell.js +3 -1
- package/lib/supervisor.js +56 -0
- package/package.json +2 -2
package/lib/round.js
CHANGED
|
@@ -15,10 +15,12 @@
|
|
|
15
15
|
* (missing hook = deferrable environment error, run `hive init`) and a card is
|
|
16
16
|
* only recorded done when HEAD moved through that hook-equipped commit path.
|
|
17
17
|
*/
|
|
18
|
-
import { roleLimitForRepo } from './config.js';
|
|
18
|
+
import { parseTtlMs, roleLimitForRepo } from './config.js';
|
|
19
19
|
import { HiveCommandError, tail } from './commands.js';
|
|
20
20
|
import { assertMergeOnCommitHook } from './hooks.js';
|
|
21
|
+
import { acquireHiveAgentEnv } from './host-env.js';
|
|
21
22
|
import { isCapacityError } from './queue.js';
|
|
23
|
+
import { writeRunRecord } from './runs.js';
|
|
22
24
|
|
|
23
25
|
/** A round-level failure. `hive/capacity` is retried from the queue. */
|
|
24
26
|
export class RoundError extends Error {
|
|
@@ -45,6 +47,16 @@ export function renderPrompt(card, lessons = [], claimAgent) {
|
|
|
45
47
|
'You are working as: ' + (card.role || 'worker') + '.',
|
|
46
48
|
'',
|
|
47
49
|
];
|
|
50
|
+
// Recalled experience leads the prompt: the worker sees what earlier cards
|
|
51
|
+
// learned before it reads the goal, so the lessons shape the whole attempt.
|
|
52
|
+
if (lessons.length > 0) {
|
|
53
|
+
lines.push('## Recalled experience (hive recall)');
|
|
54
|
+
for (const lesson of lessons) {
|
|
55
|
+
const status = lesson.status ? '[' + lesson.status + '] ' : '';
|
|
56
|
+
lines.push('- ' + status + String(lesson.text ?? '').trim());
|
|
57
|
+
}
|
|
58
|
+
lines.push('');
|
|
59
|
+
}
|
|
48
60
|
if (card.goal) lines.push('## Goal', card.goal, '');
|
|
49
61
|
if (card.scope && card.scope.length) {
|
|
50
62
|
lines.push('## Scope (edit only these paths)');
|
|
@@ -54,30 +66,22 @@ export function renderPrompt(card, lessons = [], claimAgent) {
|
|
|
54
66
|
if (card.acceptance) lines.push('## Acceptance (the runner will run this)', ' ' + card.acceptance, '');
|
|
55
67
|
if (card.reason) lines.push('## Previous attempt failed with', card.reason, '');
|
|
56
68
|
lines.push('## Hive consensus rules (mandatory)');
|
|
57
|
-
lines.push('1.
|
|
58
|
-
+ (claimAgent ? ' Use the same claim identity, for example `hive guard <path...> --agent ' + claimAgent + '
|
|
59
|
-
lines.push('2.
|
|
60
|
-
lines.push('3. Your
|
|
61
|
-
lines.push('4. Before finishing,
|
|
69
|
+
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
|
+
+ (claimAgent ? ' Use the same claim identity as the claim, for example `hive guard <path...> --agent ' + claimAgent + ' --task ' + card.id + '`.' : ''));
|
|
71
|
+
lines.push('2. `hive guard` may report overlaps: another agent announced the same or a related path. Overlaps are INFORMATION ONLY: do not stop, do not give up or shrink the scope, and do not ask permission. Keep working. Several agents may write the same file; merge-on-commit performs the three-way merge at commit time and preserves unresolved conflicts as markers. Showing a conflict is normal work, not a failure.');
|
|
72
|
+
lines.push('3. Your card is claimed in your name; `hive guard` marks the board working with task ' + card.id + '. Keep the same claim identity and task while the card is running, so the announcement is not mistaken for someone else\'s work.');
|
|
73
|
+
lines.push('4. Before finishing, clear your announcements (`hive release <scope...>`); done/fail normally clears them, but verify nothing is left behind. Only remove what you announced; never delete another agent\'s announcements.');
|
|
62
74
|
if (lessons.length > 0) {
|
|
63
|
-
lines.push('5. The runner already
|
|
75
|
+
lines.push('5. The runner already read lessons with `hive recall` for every scope path and the repository root; the deduplicated matches are injected at the top of this prompt. Only if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path) so the next card can read it; do not write a lesson just to write one. Writing lessons and reading them at the start are a pair: a lesson nobody reads is wasted work.');
|
|
64
76
|
} else {
|
|
65
|
-
lines.push('5. The runner already
|
|
77
|
+
lines.push('5. The runner already read lessons with `hive recall` for every scope path and the repository root; no match was found. If you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path) so the next card can read it; do not write a lesson just to write one. Writing lessons and reading them at the start are a pair: a lesson nobody reads is wasted work.');
|
|
66
78
|
}
|
|
67
79
|
lines.push('');
|
|
68
80
|
lines.push('## Commit rules (mandatory)');
|
|
69
|
-
lines.push('1. Commit with a plain `git commit`. The repository pre-commit hook runs merge-on-commit (moc)
|
|
81
|
+
lines.push('1. Commit with a plain `git commit`. The repository pre-commit hook runs merge-on-commit (moc), which performs a three-way merge automatically. The hook is owned by merge-on-commit: hive-consensus installs no blocking hook and the commit needs no special environment variable.');
|
|
70
82
|
lines.push('2. NEVER bypass the hook: do not use `git commit --no-verify`, do not use `git commit --amend` to skip it, and do not use `git update-ref` or `git reset` to rewrite history that others already committed.');
|
|
71
|
-
lines.push('3. If the hook reports merge conflicts, resolve them in place using the conflict markers, then commit again. Never discard the other side\'s changes.');
|
|
83
|
+
lines.push('3. If the hook reports merge conflicts, resolve them in place using the conflict markers, then commit again. Never discard the other side\'s changes: keep BOTH sides.');
|
|
72
84
|
lines.push('');
|
|
73
|
-
if (lessons.length > 0) {
|
|
74
|
-
lines.push('## Recalled experience (hive recall)');
|
|
75
|
-
for (const lesson of lessons) {
|
|
76
|
-
const status = lesson.status ? '[' + lesson.status + '] ' : '';
|
|
77
|
-
lines.push('- ' + status + String(lesson.text ?? '').trim());
|
|
78
|
-
}
|
|
79
|
-
lines.push('');
|
|
80
|
-
}
|
|
81
85
|
lines.push('## How to finish');
|
|
82
86
|
lines.push('1. Edit only the scope paths.');
|
|
83
87
|
lines.push('2. Commit before you exit: the runner checks that HEAD moved through the hook.');
|
|
@@ -89,15 +93,135 @@ function messageOf(error) {
|
|
|
89
93
|
return error instanceof Error ? error.message : String(error);
|
|
90
94
|
}
|
|
91
95
|
|
|
96
|
+
/**
|
|
97
|
+
* Advisory announcement overlaps parsed from `hive guard --json` stdout.
|
|
98
|
+
*
|
|
99
|
+
* hive-consensus 1.5.0 never blocks an announcement, so the guard document may
|
|
100
|
+
* carry an `overlaps` array describing other agents on the same or a related
|
|
101
|
+
* path. Parsing is tolerant by design: empty output, invalid JSON and a missing
|
|
102
|
+
* array all mean "no overlaps", and none of them fail the card.
|
|
103
|
+
* @param {string} stdout
|
|
104
|
+
* @returns {object[]}
|
|
105
|
+
*/
|
|
106
|
+
export function parseOverlaps(stdout) {
|
|
107
|
+
const text = String(stdout ?? '').trim();
|
|
108
|
+
if (text === '') return [];
|
|
109
|
+
let document;
|
|
110
|
+
try {
|
|
111
|
+
document = JSON.parse(text);
|
|
112
|
+
} catch {
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
return document !== null && typeof document === 'object' && Array.isArray(document.overlaps)
|
|
116
|
+
? document.overlaps
|
|
117
|
+
: [];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** One content block's text, or null when it carries none. */
|
|
121
|
+
function blockText(block) {
|
|
122
|
+
if (block === null || typeof block !== 'object') return null;
|
|
123
|
+
return typeof block.text === 'string' ? block.text : null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The worker's final result message, and nothing else.
|
|
128
|
+
*
|
|
129
|
+
* DSH hands the runner the last non-empty assistant message as a list of content
|
|
130
|
+
* blocks. Only `type: 'text'` blocks are the model's answer: reasoning/thinking,
|
|
131
|
+
* tool calls and any other process block are dropped, so the last-run record never
|
|
132
|
+
* carries the chain of thought or the narration around tool use. The provider
|
|
133
|
+
* diagnostic is deliberately not appended either — it describes the deployment,
|
|
134
|
+
* not the worker's result, and the card verdict already carries the failure reason.
|
|
135
|
+
*
|
|
136
|
+
* Fallback: a provider that returned blocks without a typed text block still gets
|
|
137
|
+
* its last non-empty text stored, matching the previous transcription behaviour.
|
|
138
|
+
*/
|
|
139
|
+
function finalAssistantText(outcome) {
|
|
140
|
+
const blocks = Array.isArray(outcome?.output) ? outcome.output : [];
|
|
141
|
+
const answers = [];
|
|
142
|
+
for (const block of blocks) {
|
|
143
|
+
if (block === null || typeof block !== 'object' || block.type !== 'text') continue;
|
|
144
|
+
const text = blockText(block);
|
|
145
|
+
if (text !== null && text.trim() !== '') answers.push(text);
|
|
146
|
+
}
|
|
147
|
+
if (answers.length > 0) return answers.join('\n').trim();
|
|
148
|
+
for (let index = blocks.length - 1; index >= 0; index -= 1) {
|
|
149
|
+
const text = blockText(blocks[index]);
|
|
150
|
+
if (text !== null && text.trim() !== '') return text.trim();
|
|
151
|
+
}
|
|
152
|
+
return '';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Worker output for the last-run record, falling back to the card verdict. */
|
|
156
|
+
export function workerOutput(outcome, fallback = '') {
|
|
157
|
+
const text = finalAssistantText(outcome);
|
|
158
|
+
return text === '' ? String(fallback) : text;
|
|
159
|
+
}
|
|
160
|
+
|
|
92
161
|
/**
|
|
93
162
|
* Bind the Hive round helpers to the DSH runtime and the Hive command layer.
|
|
94
163
|
* @param {{ ctx: object, config: object, commands: object }} options
|
|
95
164
|
*/
|
|
96
|
-
export function createRoundRunner({
|
|
165
|
+
export function createRoundRunner({
|
|
166
|
+
ctx,
|
|
167
|
+
config,
|
|
168
|
+
commands,
|
|
169
|
+
limitFor,
|
|
170
|
+
checkHook = assertMergeOnCommitHook,
|
|
171
|
+
writeRun = writeRunRecord,
|
|
172
|
+
parentProvider,
|
|
173
|
+
now = () => Date.now(),
|
|
174
|
+
log = () => {},
|
|
175
|
+
}) {
|
|
97
176
|
if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
|
|
98
177
|
throw new TypeError('createRoundRunner: ctx with ctx.get() is required');
|
|
99
178
|
}
|
|
100
179
|
if (commands === undefined || commands === null) throw new TypeError('createRoundRunner: commands are required');
|
|
180
|
+
if (typeof writeRun !== 'function') throw new TypeError('createRoundRunner: writeRun must be a function');
|
|
181
|
+
|
|
182
|
+
/** Record one last-run snapshot; observability failures never fail the card. */
|
|
183
|
+
function recordRun(repo, record) {
|
|
184
|
+
try {
|
|
185
|
+
writeRun(repo, record);
|
|
186
|
+
} catch {
|
|
187
|
+
// The record file is a convenience for the panel, not part of the verdict.
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** repo -> Map(cardId, active run descriptor) for the status endpoint. */
|
|
191
|
+
const active = new Map();
|
|
192
|
+
function registerActive(repo, run) {
|
|
193
|
+
let runs = active.get(repo);
|
|
194
|
+
if (runs === undefined) {
|
|
195
|
+
runs = new Map();
|
|
196
|
+
active.set(repo, runs);
|
|
197
|
+
}
|
|
198
|
+
runs.set(run.cardId, run);
|
|
199
|
+
}
|
|
200
|
+
function unregisterActive(repo, cardId) {
|
|
201
|
+
const runs = active.get(repo);
|
|
202
|
+
if (runs === undefined) return;
|
|
203
|
+
runs.delete(cardId);
|
|
204
|
+
if (runs.size === 0) active.delete(repo);
|
|
205
|
+
}
|
|
206
|
+
/** Snapshot of the workers currently running in one repository. */
|
|
207
|
+
function activeRuns(repo) {
|
|
208
|
+
const runs = active.get(repo);
|
|
209
|
+
if (runs === undefined) return [];
|
|
210
|
+
return [...runs.values()].map((run) => ({
|
|
211
|
+
cardId: run.cardId,
|
|
212
|
+
role: run.role,
|
|
213
|
+
agent: run.agent,
|
|
214
|
+
sessionId: run.sessionId ?? null,
|
|
215
|
+
agentName: run.agentName ?? null,
|
|
216
|
+
parentSource: run.parentSource ?? 'queen',
|
|
217
|
+
startedAt: run.startedAt,
|
|
218
|
+
lastOutputAt: run.lastOutputAt ?? null,
|
|
219
|
+
heartbeat: run.heartbeat ?? 'ok',
|
|
220
|
+
claimDeadline: run.claimDeadline ?? null,
|
|
221
|
+
timeoutAt: run.timeoutAt ?? null,
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
|
|
101
225
|
/** Effective live-worker cap for (repo, role). The plugin passes the persisted-limits store. */
|
|
102
226
|
const capFor = typeof limitFor === 'function'
|
|
103
227
|
? limitFor
|
|
@@ -136,6 +260,21 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
136
260
|
);
|
|
137
261
|
}
|
|
138
262
|
|
|
263
|
+
/**
|
|
264
|
+
* Resolve the parent for a worker: the plugin supplies the registered queen
|
|
265
|
+
* Session; direct unit tests without a provider keep the legacy resolution.
|
|
266
|
+
* @param {object} [explicit] caller agent (tool-triggered rounds)
|
|
267
|
+
* @returns {Promise<{ agent: object, source: string, sessionId?: string }>}
|
|
268
|
+
*/
|
|
269
|
+
async function parentFor(explicit) {
|
|
270
|
+
if (typeof parentProvider === 'function') {
|
|
271
|
+
const provided = await parentProvider(explicit);
|
|
272
|
+
if (provided !== undefined && provided !== null && provided.agent !== undefined) return provided;
|
|
273
|
+
}
|
|
274
|
+
const agent = resolveParent(explicit);
|
|
275
|
+
return { agent, source: 'fallback', sessionId: agent?.session?.id ?? agent?.id };
|
|
276
|
+
}
|
|
277
|
+
|
|
139
278
|
function assertProvider(providerName) {
|
|
140
279
|
const service = subagents();
|
|
141
280
|
const provider = typeof service.getProvider === 'function' ? service.getProvider(providerName) : undefined;
|
|
@@ -145,14 +284,14 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
145
284
|
return service;
|
|
146
285
|
}
|
|
147
286
|
|
|
148
|
-
async function verify({ repo, before, card, signal, session }) {
|
|
149
|
-
const head = await commands.head(repo, { signal, session });
|
|
287
|
+
async function verify({ repo, before, card, agent, signal, session }) {
|
|
288
|
+
const head = await commands.head(repo, { agent, signal, session });
|
|
150
289
|
if (head === before) return { ok: false, reason: 'no commit produced' };
|
|
151
290
|
// The commit must have landed through the merge-on-commit path: if the hook
|
|
152
291
|
// vanished the commit may have bypassed it, so this is an environment error.
|
|
153
292
|
checkHook(repo);
|
|
154
293
|
if (card.acceptance) {
|
|
155
|
-
const result = await commands.acceptance(repo, card.acceptance, { signal, session });
|
|
294
|
+
const result = await commands.acceptance(repo, card.acceptance, { agent, signal, session });
|
|
156
295
|
if (result.exitCode !== 0) {
|
|
157
296
|
const detail = result.stderr.trim() !== '' ? result.stderr : result.stdout;
|
|
158
297
|
return { ok: false, reason: 'acceptance failed: ' + tail(detail) };
|
|
@@ -161,7 +300,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
161
300
|
return { ok: true, head };
|
|
162
301
|
}
|
|
163
302
|
|
|
164
|
-
/** Scope entries of one card (files and `resource:`
|
|
303
|
+
/** Scope entries of one card (files and `resource:` announcement keys alike). */
|
|
165
304
|
function scopeOf(card) {
|
|
166
305
|
return Array.isArray(card.scope)
|
|
167
306
|
? card.scope.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
|
|
@@ -169,119 +308,293 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
169
308
|
}
|
|
170
309
|
|
|
171
310
|
/**
|
|
172
|
-
* Recall lessons for the card scope
|
|
173
|
-
*
|
|
311
|
+
* Recall lessons for the whole card scope: one `hive recall <query>` per scope
|
|
312
|
+
* entry plus one for the repository root (`.`), deduplicated by lesson.
|
|
313
|
+
*
|
|
314
|
+
* Every scope entry is queried (no sampling) so a lesson recorded against any
|
|
315
|
+
* card path is recalled by the next card that touches it. A recall error does
|
|
316
|
+
* not throw: the caller records it on the last-run record, logs a warning and
|
|
317
|
+
* continues the card with no lessons.
|
|
318
|
+
* @returns {Promise<{ lessons: object[], scopes: string[], error?: string }>}
|
|
174
319
|
*/
|
|
175
|
-
async function recallLessons(repo, scope, { signal, session }) {
|
|
320
|
+
async function recallLessons(repo, scope, { agent, signal, session }) {
|
|
321
|
+
const scopes = [...new Set([...scope, '.'])];
|
|
176
322
|
const seen = new Map();
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const items = await commands.recall(repo, query, { signal, session });
|
|
323
|
+
try {
|
|
324
|
+
for (const query of scopes) {
|
|
325
|
+
const items = await commands.recall(repo, query, { agent, signal, session });
|
|
180
326
|
for (const item of items) {
|
|
181
327
|
if (item === null || typeof item !== 'object' || typeof item.text !== 'string') continue;
|
|
182
328
|
seen.set(item.id ?? item.text, item);
|
|
183
329
|
}
|
|
184
|
-
} catch {
|
|
185
|
-
// Lessons are advisory; continue without them.
|
|
186
330
|
}
|
|
187
|
-
|
|
331
|
+
} catch (error) {
|
|
332
|
+
return { lessons: [], scopes, error: messageOf(error) };
|
|
188
333
|
}
|
|
189
|
-
return [...seen.values()]
|
|
334
|
+
return { lessons: [...seen.values()], scopes };
|
|
190
335
|
}
|
|
191
336
|
|
|
192
|
-
/** Best-effort release of the
|
|
193
|
-
async function releaseScope(repo, scope, { signal, session, agent }) {
|
|
337
|
+
/** Best-effort release of the announcements we own for this card scope. */
|
|
338
|
+
async function releaseScope(repo, scope, { signal, session, agent, instance }) {
|
|
194
339
|
if (scope.length === 0) return;
|
|
195
340
|
try {
|
|
196
|
-
await commands.release(repo, scope, { signal, session, agent });
|
|
341
|
+
await commands.release(repo, scope, { signal, session, agent, instance });
|
|
197
342
|
} catch {
|
|
198
|
-
// done/fail already
|
|
343
|
+
// done/fail already clear the announcements; this is only orphan cleanup.
|
|
199
344
|
}
|
|
200
345
|
}
|
|
201
346
|
|
|
202
|
-
/**
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
347
|
+
/**
|
|
348
|
+
* Announce the card scope on the consensus board (`hive guard --json`).
|
|
349
|
+
*
|
|
350
|
+
* hive-consensus 1.5.0 announcements never block anything: the guard always
|
|
351
|
+
* exits 0 and only reports advisory overlaps. A non-zero exit is therefore an
|
|
352
|
+
* unexpected CLI problem, logged as a warning and otherwise ignored; an
|
|
353
|
+
* exception is handled the same way. This function never fails a card.
|
|
354
|
+
* @returns {Promise<object[]>} raw overlap entries from the guard document
|
|
355
|
+
*/
|
|
356
|
+
async function announceScope(repo, id, scope, { agent, instance, signal, session }) {
|
|
357
|
+
if (scope.length === 0) return [];
|
|
358
|
+
try {
|
|
359
|
+
const guard = await commands.guard(repo, scope, {
|
|
360
|
+
agent,
|
|
361
|
+
instance,
|
|
362
|
+
taskId: id,
|
|
363
|
+
ttl: config.ttl,
|
|
364
|
+
signal,
|
|
365
|
+
session,
|
|
366
|
+
});
|
|
367
|
+
if (guard.exitCode !== 0) {
|
|
368
|
+
log('warn', 'card ' + id + ' in ' + repo + ' hive guard exited ' + String(guard.exitCode) + ' (continuing): ' + tail(guard.stderr || guard.stdout));
|
|
369
|
+
}
|
|
370
|
+
const overlaps = parseOverlaps(guard.stdout);
|
|
371
|
+
if (overlaps.length > 0) {
|
|
372
|
+
const agents = [];
|
|
373
|
+
for (const entry of overlaps) {
|
|
374
|
+
const name = entry !== null && typeof entry === 'object' && typeof entry.agent === 'string'
|
|
375
|
+
? entry.agent.trim()
|
|
376
|
+
: '';
|
|
377
|
+
if (name !== '' && !agents.includes(name)) agents.push(name);
|
|
378
|
+
}
|
|
379
|
+
log('info', 'card ' + id + ' in ' + repo + ' overlaps: ' + (agents.length > 0 ? agents.join(', ') : String(overlaps.length) + ' announcement(s)'));
|
|
380
|
+
}
|
|
381
|
+
return overlaps;
|
|
382
|
+
} catch (error) {
|
|
383
|
+
log('warn', 'card ' + id + ' in ' + repo + ' hive guard failed (continuing): ' + tail(messageOf(error)));
|
|
384
|
+
return [];
|
|
385
|
+
}
|
|
208
386
|
}
|
|
209
387
|
|
|
210
388
|
/** Best-effort release of a claim when the worker could not run at all. */
|
|
211
389
|
async function releaseClaim(repo, id, error, signal, session) {
|
|
212
390
|
await commands.fail(repo, id, {
|
|
213
391
|
reason: 'runner error: ' + tail(messageOf(error)),
|
|
392
|
+
instance: id,
|
|
214
393
|
signal,
|
|
215
394
|
session,
|
|
216
395
|
}).catch(() => {});
|
|
217
396
|
}
|
|
218
397
|
|
|
219
|
-
async function executeCard({ repo, card, before, owner, agent, signal, session }) {
|
|
398
|
+
async function executeCard({ repo, card, before, owner, agent, parentSource = 'queen', claimDeadline, signal, session }) {
|
|
220
399
|
const id = card.id;
|
|
221
400
|
const service = assertProvider(config.provider);
|
|
222
401
|
const scope = scopeOf(card);
|
|
223
402
|
const claimAgent = agent ?? config.agent;
|
|
403
|
+
// Per-card consensus instance: several cards of one runner share the same
|
|
404
|
+
// HIVE_AGENT, so the card id is what makes their announcements distinct and
|
|
405
|
+
// lets `hive guard --json` report overlaps instead of treating every
|
|
406
|
+
// announcement as its own.
|
|
407
|
+
const instance = id;
|
|
408
|
+
const cardTimeoutMs = config.cardTimeoutMs ?? 15 * 60_000;
|
|
409
|
+
const heartbeatWarnMs = config.heartbeatWarnMs ?? 5 * 60_000;
|
|
410
|
+
const heartbeatIntervalMs = config.heartbeatIntervalMs ?? 30_000;
|
|
411
|
+
// Announce the card scope before anything starts. This never fails the
|
|
412
|
+
// card: on hive-consensus 1.5.0 the guard always succeeds, overlaps are
|
|
413
|
+
// advisory and an unexpected CLI error is only logged.
|
|
414
|
+
const overlaps = await announceScope(repo, id, scope, {
|
|
415
|
+
agent: claimAgent,
|
|
416
|
+
instance,
|
|
417
|
+
signal,
|
|
418
|
+
session,
|
|
419
|
+
});
|
|
420
|
+
const startedAt = new Date(now()).toISOString();
|
|
421
|
+
// One last-run record per card: write `running` when the attempt starts and
|
|
422
|
+
// overwrite it with the terminal state before returning/raising. The record
|
|
423
|
+
// carries the worker Session id as soon as the activation is accepted, and
|
|
424
|
+
// the guard's advisory overlaps on both writes.
|
|
425
|
+
const run = {
|
|
426
|
+
cardId: id,
|
|
427
|
+
agent: claimAgent,
|
|
428
|
+
role: card.role,
|
|
429
|
+
parentSource,
|
|
430
|
+
startedAt,
|
|
431
|
+
lastOutputAt: startedAt,
|
|
432
|
+
heartbeat: 'ok',
|
|
433
|
+
endedAt: null,
|
|
434
|
+
status: 'running',
|
|
435
|
+
output: '',
|
|
436
|
+
timeoutAt: new Date(now() + cardTimeoutMs).toISOString(),
|
|
437
|
+
...(Number.isFinite(claimDeadline) ? { claimDeadline: new Date(claimDeadline).toISOString() } : {}),
|
|
438
|
+
...(overlaps.length > 0 ? { overlaps } : {}),
|
|
439
|
+
};
|
|
440
|
+
let runFinished = false;
|
|
441
|
+
recordRun(repo, run);
|
|
442
|
+
registerActive(repo, run);
|
|
443
|
+
const finishRun = (status, patch = {}) => {
|
|
444
|
+
runFinished = true;
|
|
445
|
+
const endedAt = new Date(now()).toISOString();
|
|
446
|
+
recordRun(repo, { ...run, ...patch, status, endedAt });
|
|
447
|
+
run.endedAt = endedAt;
|
|
448
|
+
run.status = status;
|
|
449
|
+
unregisterActive(repo, id);
|
|
450
|
+
};
|
|
224
451
|
let activation;
|
|
452
|
+
let releaseEnv = () => {};
|
|
453
|
+
let timedOut = false;
|
|
454
|
+
let settled = false;
|
|
455
|
+
const controller = new AbortController();
|
|
456
|
+
const workerSignal = signal === undefined ? controller.signal : AbortSignal.any([signal, controller.signal]);
|
|
457
|
+
const abortWait = new Promise((resolve) => {
|
|
458
|
+
if (controller.signal.aborted) resolve();
|
|
459
|
+
else controller.signal.addEventListener('abort', () => resolve(), { once: true });
|
|
460
|
+
});
|
|
461
|
+
let timeoutTimer;
|
|
462
|
+
let heartbeatTimer;
|
|
463
|
+
const clearMonitors = () => {
|
|
464
|
+
if (timeoutTimer !== undefined) clearTimeout(timeoutTimer);
|
|
465
|
+
if (heartbeatTimer !== undefined) clearInterval(heartbeatTimer);
|
|
466
|
+
timeoutTimer = undefined;
|
|
467
|
+
heartbeatTimer = undefined;
|
|
468
|
+
};
|
|
469
|
+
const abortReason = () => 'card timeout after ' + cardTimeoutMs + 'ms';
|
|
470
|
+
const failCard = async (reason, output = reason) => {
|
|
471
|
+
await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session }).catch(() => {});
|
|
472
|
+
finishRun('failed', { exitCode: 1, output });
|
|
473
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
474
|
+
return { id, state: 'failed', reason };
|
|
475
|
+
};
|
|
225
476
|
try {
|
|
226
|
-
//
|
|
227
|
-
//
|
|
228
|
-
//
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
477
|
+
// Recall lessons for every scope path plus the repository root before the
|
|
478
|
+
// worker starts. A recall error is recorded on the run record and logged,
|
|
479
|
+
// never a card failure: the work continues without lessons.
|
|
480
|
+
const recall = await recallLessons(repo, scope, { agent: claimAgent, signal, session });
|
|
481
|
+
if (recall.error !== undefined) {
|
|
482
|
+
log('warn', 'card ' + id + ' in ' + repo + ' reading lessons failed (continuing): ' + tail(recall.error));
|
|
483
|
+
run.lessons = { count: 0, scopes: recall.scopes, error: recall.error };
|
|
484
|
+
} else {
|
|
485
|
+
run.lessons = { count: recall.lessons.length, scopes: recall.scopes };
|
|
486
|
+
}
|
|
487
|
+
// Rewrite the opening running record now that recall finished, so the
|
|
488
|
+
// panel can show "recalled N lessons / no lesson matched" while the card
|
|
489
|
+
// is still running.
|
|
490
|
+
recordRun(repo, run);
|
|
491
|
+
const lessons = recall.lessons;
|
|
492
|
+
// Workers run in-process; DSH's bash tool inherits ambient env. Inject the
|
|
493
|
+
// claim identity and this card's instance while the worker is alive, so
|
|
494
|
+
// its own `hive guard` / `hive release` calls agree with the runner's.
|
|
495
|
+
releaseEnv = acquireHiveAgentEnv(claimAgent, instance);
|
|
496
|
+
// Hard per-card timeout: abort the worker at the deadline.
|
|
497
|
+
timeoutTimer = setTimeout(() => {
|
|
498
|
+
if (settled) return;
|
|
499
|
+
timedOut = true;
|
|
500
|
+
controller.abort();
|
|
501
|
+
log('warn', 'card ' + id + ' in ' + repo + ' timed out after ' + cardTimeoutMs + 'ms');
|
|
502
|
+
}, cardTimeoutMs);
|
|
503
|
+
activation = await Promise.race([
|
|
504
|
+
service.startActivation({
|
|
505
|
+
provider: config.provider,
|
|
506
|
+
label: 'hive:' + id,
|
|
507
|
+
prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent) }],
|
|
508
|
+
cwd: repo,
|
|
509
|
+
parent: owner,
|
|
510
|
+
signal: workerSignal,
|
|
511
|
+
delivery: 'caller',
|
|
512
|
+
}),
|
|
513
|
+
abortWait.then(() => null),
|
|
514
|
+
]);
|
|
515
|
+
if (activation === null) {
|
|
516
|
+
settled = true;
|
|
517
|
+
clearMonitors();
|
|
518
|
+
return await failCard(abortReason());
|
|
519
|
+
}
|
|
520
|
+
// Keep the worker's Session identity on the run record: the panel opens
|
|
521
|
+
// that conversation exactly like one click in the header's subagent list.
|
|
522
|
+
// A provider without an accepted child (none in practice) leaves it out.
|
|
523
|
+
if (typeof activation.childId === 'string' && activation.childId !== '') run.sessionId = activation.childId;
|
|
524
|
+
if (typeof activation.name === 'string' && activation.name !== '') run.agentName = activation.name;
|
|
525
|
+
// Persist the still-running record as soon as the child is accepted, not only
|
|
526
|
+
// at the terminal write: the panel must be able to open the worker chat while
|
|
527
|
+
// the card is still in progress.
|
|
528
|
+
if (run.sessionId !== undefined || run.agentName !== undefined) recordRun(repo, run);
|
|
529
|
+
|
|
530
|
+
// Heartbeat: during the run, watch the repository HEAD as the observable
|
|
531
|
+
// "output" signal. If it does not move for heartbeatWarnMs, mark the
|
|
532
|
+
// worker as heartbeat=warn in the run record and in supervisor status.
|
|
533
|
+
let lastHead = before;
|
|
534
|
+
let heartbeatWarned = false;
|
|
535
|
+
const heartbeatEvery = Math.max(1, Math.min(heartbeatIntervalMs, Math.max(1, Math.floor(heartbeatWarnMs / 2))));
|
|
536
|
+
const checkHeartbeat = async () => {
|
|
537
|
+
if (settled) return;
|
|
538
|
+
try {
|
|
539
|
+
const head = await commands.head(repo, { agent: claimAgent, signal, session });
|
|
540
|
+
if (head !== lastHead) {
|
|
541
|
+
lastHead = head;
|
|
542
|
+
run.lastOutputAt = new Date(now()).toISOString();
|
|
543
|
+
run.heartbeat = 'ok';
|
|
544
|
+
heartbeatWarned = false;
|
|
545
|
+
recordRun(repo, { ...run });
|
|
249
546
|
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
'hive/guard-failed',
|
|
253
|
-
'hive guard exited ' + String(guard.exitCode) + ': ' + tail(guard.stderr || guard.stdout),
|
|
254
|
-
);
|
|
547
|
+
} catch {
|
|
548
|
+
// Heartbeat checks are advisory; a failed HEAD probe is not a verdict.
|
|
255
549
|
}
|
|
550
|
+
if (settled || heartbeatWarned) return;
|
|
551
|
+
const idle = now() - Date.parse(run.lastOutputAt);
|
|
552
|
+
if (idle >= heartbeatWarnMs) {
|
|
553
|
+
heartbeatWarned = true;
|
|
554
|
+
run.heartbeat = 'warn';
|
|
555
|
+
recordRun(repo, { ...run });
|
|
556
|
+
log('warn', 'card ' + id + ' in ' + repo + ' produced no output for ' + idle + 'ms (heartbeat warn)');
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
heartbeatTimer = setInterval(() => {
|
|
560
|
+
void checkHeartbeat();
|
|
561
|
+
}, heartbeatEvery);
|
|
562
|
+
|
|
563
|
+
const outcome = await Promise.race([activation.result, abortWait.then(() => null)]);
|
|
564
|
+
settled = true;
|
|
565
|
+
clearMonitors();
|
|
566
|
+
if (timedOut) return await failCard(abortReason());
|
|
567
|
+
if (outcome === null) {
|
|
568
|
+
// Aborted before the provider settled: report it as a round failure and
|
|
569
|
+
// let the supervisor decide (external cancellation/teardown).
|
|
570
|
+
throw new RoundError('hive/round-aborted', 'worker activation was aborted before it settled');
|
|
256
571
|
}
|
|
257
|
-
const lessons = scope.length > 0 ? await recallLessons(repo, scope, { signal, session }) : [];
|
|
258
|
-
activation = await service.startActivation({
|
|
259
|
-
provider: config.provider,
|
|
260
|
-
label: 'hive:' + id,
|
|
261
|
-
prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent) }],
|
|
262
|
-
cwd: repo,
|
|
263
|
-
parent: owner,
|
|
264
|
-
signal,
|
|
265
|
-
delivery: 'caller',
|
|
266
|
-
});
|
|
267
|
-
const outcome = await activation.result;
|
|
268
572
|
if (outcome.stopReason !== 'completed') {
|
|
269
573
|
const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
|
|
270
574
|
const reason = 'subagent stopped: ' + outcome.stopReason + detail;
|
|
271
|
-
await commands.fail(repo, id, { reason, signal, session });
|
|
272
|
-
|
|
575
|
+
await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session });
|
|
576
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason) });
|
|
577
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
273
578
|
return { id, state: 'failed', reason };
|
|
274
579
|
}
|
|
275
|
-
const verdict = await verify({ repo, before, card, signal, session });
|
|
580
|
+
const verdict = await verify({ repo, before, card, agent: claimAgent, signal, session });
|
|
276
581
|
if (verdict.ok) {
|
|
277
|
-
await commands.done(repo, id, { sha: verdict.head, verdict: 'pass', signal, session });
|
|
278
|
-
|
|
582
|
+
await commands.done(repo, id, { agent: claimAgent, instance, sha: verdict.head, verdict: 'pass', signal, session });
|
|
583
|
+
finishRun('done', { exitCode: 0, commit: verdict.head, output: workerOutput(outcome) });
|
|
584
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
279
585
|
return { id, state: 'done', sha: verdict.head };
|
|
280
586
|
}
|
|
281
|
-
await commands.fail(repo, id, { reason: verdict.reason, signal, session });
|
|
282
|
-
|
|
587
|
+
await commands.fail(repo, id, { agent: claimAgent, instance, reason: verdict.reason, signal, session });
|
|
588
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason) });
|
|
589
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
283
590
|
return { id, state: 'failed', reason: verdict.reason };
|
|
284
591
|
} catch (error) {
|
|
592
|
+
settled = true;
|
|
593
|
+
clearMonitors();
|
|
594
|
+
if (timedOut) {
|
|
595
|
+
return await failCard(abortReason(), messageOf(error) || abortReason());
|
|
596
|
+
}
|
|
597
|
+
if (!runFinished) finishRun('failed', { exitCode: 1, output: messageOf(error) });
|
|
285
598
|
if (isCapacityError(error)) {
|
|
286
599
|
// Capacity is a scheduling concern, not this card's failure: keep the
|
|
287
600
|
// claimed item and let the dispatcher retry it.
|
|
@@ -295,21 +608,29 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
295
608
|
const environment = error?.deferrable === true
|
|
296
609
|
|| (typeof error?.code === 'string' && error.code.startsWith('hive/no-'));
|
|
297
610
|
if (!environment) await releaseClaim(repo, id, error, signal, session);
|
|
298
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent });
|
|
611
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
299
612
|
throw error instanceof RoundError
|
|
300
613
|
? error
|
|
301
614
|
: environment
|
|
302
615
|
? error
|
|
303
616
|
: new RoundError('hive/round-failed', messageOf(error), { cause: error });
|
|
304
617
|
} finally {
|
|
305
|
-
|
|
306
|
-
|
|
618
|
+
settled = true;
|
|
619
|
+
clearMonitors();
|
|
620
|
+
unregisterActive(repo, id);
|
|
621
|
+
try {
|
|
622
|
+
if (activation !== undefined) {
|
|
623
|
+
await Promise.resolve(activation.dispose?.()).catch(() => {});
|
|
624
|
+
}
|
|
625
|
+
} finally {
|
|
626
|
+
releaseEnv();
|
|
307
627
|
}
|
|
308
628
|
}
|
|
309
629
|
}
|
|
310
630
|
|
|
311
631
|
return {
|
|
312
632
|
resolveParent,
|
|
633
|
+
activeRuns,
|
|
313
634
|
|
|
314
635
|
/**
|
|
315
636
|
* Round-start environment check: the repository must be Hive-initialised
|
|
@@ -342,10 +663,11 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
342
663
|
return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
|
|
343
664
|
}
|
|
344
665
|
const id = card.id;
|
|
345
|
-
const
|
|
666
|
+
const ownerInfo = await parentFor(parent);
|
|
667
|
+
const owner = ownerInfo.agent;
|
|
346
668
|
let fresh = card;
|
|
347
669
|
try {
|
|
348
|
-
const shown = await commands.show(repo, id, { signal, session });
|
|
670
|
+
const shown = await commands.show(repo, id, { agent: agent ?? config.agent, signal, session });
|
|
349
671
|
if (shown !== null && typeof shown === 'object') fresh = shown;
|
|
350
672
|
} catch {
|
|
351
673
|
// The ready snapshot is enough to render the prompt.
|
|
@@ -362,17 +684,39 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
362
684
|
return { id, state: 'skipped', reason: 'claim held by ' + String(fresh.owner) };
|
|
363
685
|
}
|
|
364
686
|
|
|
687
|
+
const ttlMs = parseTtlMs(ttl ?? config.ttl);
|
|
365
688
|
if (!alreadyClaimed) {
|
|
366
|
-
const before = await commands.head(repo, { signal, session });
|
|
367
|
-
const claim = await commands.claim(repo, id, { signal, session, agent, ttl });
|
|
689
|
+
const before = await commands.head(repo, { agent: agentId, signal, session });
|
|
690
|
+
const claim = await commands.claim(repo, id, { signal, session, agent, instance: id, ttl });
|
|
368
691
|
if (claim.exitCode !== 0) {
|
|
369
692
|
return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
|
|
370
693
|
}
|
|
371
|
-
return await executeCard({
|
|
694
|
+
return await executeCard({
|
|
695
|
+
repo,
|
|
696
|
+
card: fresh,
|
|
697
|
+
before,
|
|
698
|
+
owner,
|
|
699
|
+
agent: agentId,
|
|
700
|
+
parentSource: ownerInfo.source,
|
|
701
|
+
claimDeadline: now() + ttlMs,
|
|
702
|
+
signal,
|
|
703
|
+
session,
|
|
704
|
+
});
|
|
372
705
|
}
|
|
373
706
|
|
|
374
|
-
const before = await commands.head(repo, { signal, session });
|
|
375
|
-
|
|
707
|
+
const before = await commands.head(repo, { agent: agentId, signal, session });
|
|
708
|
+
const claimDeadline = Number.isFinite(claimedUntil) ? claimedUntil : now() + ttlMs;
|
|
709
|
+
return await executeCard({
|
|
710
|
+
repo,
|
|
711
|
+
card: fresh,
|
|
712
|
+
before,
|
|
713
|
+
owner,
|
|
714
|
+
agent: agentId,
|
|
715
|
+
parentSource: ownerInfo.source,
|
|
716
|
+
claimDeadline,
|
|
717
|
+
signal,
|
|
718
|
+
session,
|
|
719
|
+
});
|
|
376
720
|
},
|
|
377
721
|
};
|
|
378
722
|
}
|