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/round.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
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
21
|
import { acquireHiveAgentEnv } from './host-env.js';
|
|
@@ -47,6 +47,16 @@ export function renderPrompt(card, lessons = [], claimAgent) {
|
|
|
47
47
|
'You are working as: ' + (card.role || 'worker') + '.',
|
|
48
48
|
'',
|
|
49
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
|
+
}
|
|
50
60
|
if (card.goal) lines.push('## Goal', card.goal, '');
|
|
51
61
|
if (card.scope && card.scope.length) {
|
|
52
62
|
lines.push('## Scope (edit only these paths)');
|
|
@@ -54,34 +64,26 @@ export function renderPrompt(card, lessons = [], claimAgent) {
|
|
|
54
64
|
lines.push('');
|
|
55
65
|
}
|
|
56
66
|
if (card.acceptance) lines.push('## Acceptance (the runner will run this)', ' ' + card.acceptance, '');
|
|
57
|
-
|
|
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, '');
|
|
58
70
|
lines.push('## Hive consensus rules (mandatory)');
|
|
59
|
-
lines.push('1.
|
|
60
|
-
+ (claimAgent ? ' Use the same claim identity, for example `hive guard <path...> --agent ' + claimAgent + '
|
|
61
|
-
lines.push('2.
|
|
62
|
-
lines.push('3. Your
|
|
63
|
-
lines.push('4. Before finishing,
|
|
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.'
|
|
72
|
+
+ (claimAgent ? ' Use the same claim identity as the claim, for example `hive guard <path...> --agent ' + claimAgent + ' --task ' + card.id + '`.' : ''));
|
|
73
|
+
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.');
|
|
74
|
+
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.');
|
|
75
|
+
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.');
|
|
64
76
|
if (lessons.length > 0) {
|
|
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; 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.');
|
|
66
78
|
} else {
|
|
67
|
-
lines.push('5. The runner already
|
|
79
|
+
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.');
|
|
68
80
|
}
|
|
69
81
|
lines.push('');
|
|
70
82
|
lines.push('## Commit rules (mandatory)');
|
|
71
|
-
lines.push('
|
|
72
|
-
lines.push('0b. If the pre-commit hook prints "HIVE_AGENT is not set" or "lease enforcement skipped", the commit is NOT protected: stop, do not treat the work as done, and report that line as an environment error.');
|
|
73
|
-
lines.push('1. Commit with a plain `git commit`. The repository pre-commit hook runs merge-on-commit (moc) and performs a three-way merge automatically.');
|
|
83
|
+
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.');
|
|
74
84
|
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.');
|
|
75
|
-
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.');
|
|
85
|
+
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.');
|
|
76
86
|
lines.push('');
|
|
77
|
-
if (lessons.length > 0) {
|
|
78
|
-
lines.push('## Recalled experience (hive recall)');
|
|
79
|
-
for (const lesson of lessons) {
|
|
80
|
-
const status = lesson.status ? '[' + lesson.status + '] ' : '';
|
|
81
|
-
lines.push('- ' + status + String(lesson.text ?? '').trim());
|
|
82
|
-
}
|
|
83
|
-
lines.push('');
|
|
84
|
-
}
|
|
85
87
|
lines.push('## How to finish');
|
|
86
88
|
lines.push('1. Edit only the scope paths.');
|
|
87
89
|
lines.push('2. Commit before you exit: the runner checks that HEAD moved through the hook.');
|
|
@@ -93,32 +95,87 @@ function messageOf(error) {
|
|
|
93
95
|
return error instanceof Error ? error.message : String(error);
|
|
94
96
|
}
|
|
95
97
|
|
|
96
|
-
/**
|
|
97
|
-
|
|
98
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Advisory announcement overlaps parsed from `hive guard --json` stdout.
|
|
100
|
+
*
|
|
101
|
+
* hive-consensus 1.5.0 never blocks an announcement, so the guard document may
|
|
102
|
+
* carry an `overlaps` array describing other agents on the same or a related
|
|
103
|
+
* path. Parsing is tolerant by design: empty output, invalid JSON and a missing
|
|
104
|
+
* array all mean "no overlaps", and none of them fail the card.
|
|
105
|
+
* @param {string} stdout
|
|
106
|
+
* @returns {object[]}
|
|
107
|
+
*/
|
|
108
|
+
export function parseOverlaps(stdout) {
|
|
109
|
+
const text = String(stdout ?? '').trim();
|
|
110
|
+
if (text === '') return [];
|
|
111
|
+
let document;
|
|
112
|
+
try {
|
|
113
|
+
document = JSON.parse(text);
|
|
114
|
+
} catch {
|
|
115
|
+
return [];
|
|
116
|
+
}
|
|
117
|
+
return document !== null && typeof document === 'object' && Array.isArray(document.overlaps)
|
|
118
|
+
? document.overlaps
|
|
119
|
+
: [];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One content block's text, or null when it carries none. */
|
|
123
|
+
function blockText(block) {
|
|
124
|
+
if (block === null || typeof block !== 'object') return null;
|
|
125
|
+
return typeof block.text === 'string' ? block.text : null;
|
|
99
126
|
}
|
|
100
127
|
|
|
101
|
-
/**
|
|
102
|
-
|
|
128
|
+
/**
|
|
129
|
+
* The worker's final result message, and nothing else.
|
|
130
|
+
*
|
|
131
|
+
* DSH hands the runner the last non-empty assistant message as a list of content
|
|
132
|
+
* blocks. Only `type: 'text'` blocks are the model's answer: reasoning/thinking,
|
|
133
|
+
* tool calls and any other process block are dropped, so the last-run record never
|
|
134
|
+
* carries the chain of thought or the narration around tool use. The provider
|
|
135
|
+
* diagnostic is deliberately not appended either — it describes the deployment,
|
|
136
|
+
* not the worker's result, and the card verdict already carries the failure reason.
|
|
137
|
+
*
|
|
138
|
+
* Fallback: a provider that returned blocks without a typed text block still gets
|
|
139
|
+
* its last non-empty text stored, matching the previous transcription behaviour.
|
|
140
|
+
*/
|
|
141
|
+
function finalAssistantText(outcome) {
|
|
103
142
|
const blocks = Array.isArray(outcome?.output) ? outcome.output : [];
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
143
|
+
const answers = [];
|
|
144
|
+
for (const block of blocks) {
|
|
145
|
+
if (block === null || typeof block !== 'object' || block.type !== 'text') continue;
|
|
146
|
+
const text = blockText(block);
|
|
147
|
+
if (text !== null && text.trim() !== '') answers.push(text);
|
|
148
|
+
}
|
|
149
|
+
if (answers.length > 0) return answers.join('\n').trim();
|
|
150
|
+
for (let index = blocks.length - 1; index >= 0; index -= 1) {
|
|
151
|
+
const text = blockText(blocks[index]);
|
|
152
|
+
if (text !== null && text.trim() !== '') return text.trim();
|
|
153
|
+
}
|
|
154
|
+
return '';
|
|
109
155
|
}
|
|
110
156
|
|
|
111
157
|
/** Worker output for the last-run record, falling back to the card verdict. */
|
|
112
158
|
export function workerOutput(outcome, fallback = '') {
|
|
113
|
-
const text =
|
|
114
|
-
return text
|
|
159
|
+
const text = finalAssistantText(outcome);
|
|
160
|
+
return text === '' ? String(fallback) : text;
|
|
115
161
|
}
|
|
116
162
|
|
|
117
163
|
/**
|
|
118
164
|
* Bind the Hive round helpers to the DSH runtime and the Hive command layer.
|
|
119
165
|
* @param {{ ctx: object, config: object, commands: object }} options
|
|
120
166
|
*/
|
|
121
|
-
export function createRoundRunner({
|
|
167
|
+
export function createRoundRunner({
|
|
168
|
+
ctx,
|
|
169
|
+
config,
|
|
170
|
+
commands,
|
|
171
|
+
limitFor,
|
|
172
|
+
checkHook = assertMergeOnCommitHook,
|
|
173
|
+
writeRun = writeRunRecord,
|
|
174
|
+
parentProvider,
|
|
175
|
+
onAnomaly,
|
|
176
|
+
now = () => Date.now(),
|
|
177
|
+
log = () => {},
|
|
178
|
+
}) {
|
|
122
179
|
if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
|
|
123
180
|
throw new TypeError('createRoundRunner: ctx with ctx.get() is required');
|
|
124
181
|
}
|
|
@@ -133,6 +190,53 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
133
190
|
// The record file is a convenience for the panel, not part of the verdict.
|
|
134
191
|
}
|
|
135
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
|
+
}
|
|
205
|
+
/** repo -> Map(cardId, active run descriptor) for the status endpoint. */
|
|
206
|
+
const active = new Map();
|
|
207
|
+
function registerActive(repo, run) {
|
|
208
|
+
let runs = active.get(repo);
|
|
209
|
+
if (runs === undefined) {
|
|
210
|
+
runs = new Map();
|
|
211
|
+
active.set(repo, runs);
|
|
212
|
+
}
|
|
213
|
+
runs.set(run.cardId, run);
|
|
214
|
+
}
|
|
215
|
+
function unregisterActive(repo, cardId) {
|
|
216
|
+
const runs = active.get(repo);
|
|
217
|
+
if (runs === undefined) return;
|
|
218
|
+
runs.delete(cardId);
|
|
219
|
+
if (runs.size === 0) active.delete(repo);
|
|
220
|
+
}
|
|
221
|
+
/** Snapshot of the workers currently running in one repository. */
|
|
222
|
+
function activeRuns(repo) {
|
|
223
|
+
const runs = active.get(repo);
|
|
224
|
+
if (runs === undefined) return [];
|
|
225
|
+
return [...runs.values()].map((run) => ({
|
|
226
|
+
cardId: run.cardId,
|
|
227
|
+
role: run.role,
|
|
228
|
+
agent: run.agent,
|
|
229
|
+
sessionId: run.sessionId ?? null,
|
|
230
|
+
agentName: run.agentName ?? null,
|
|
231
|
+
parentSource: run.parentSource ?? 'queen',
|
|
232
|
+
startedAt: run.startedAt,
|
|
233
|
+
lastOutputAt: run.lastOutputAt ?? null,
|
|
234
|
+
heartbeat: run.heartbeat ?? 'ok',
|
|
235
|
+
claimDeadline: run.claimDeadline ?? null,
|
|
236
|
+
timeoutAt: run.timeoutAt ?? null,
|
|
237
|
+
}));
|
|
238
|
+
}
|
|
239
|
+
|
|
136
240
|
/** Effective live-worker cap for (repo, role). The plugin passes the persisted-limits store. */
|
|
137
241
|
const capFor = typeof limitFor === 'function'
|
|
138
242
|
? limitFor
|
|
@@ -171,6 +275,21 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
171
275
|
);
|
|
172
276
|
}
|
|
173
277
|
|
|
278
|
+
/**
|
|
279
|
+
* Resolve the parent for a worker: the plugin supplies the registered queen
|
|
280
|
+
* Session; direct unit tests without a provider keep the legacy resolution.
|
|
281
|
+
* @param {object} [explicit] caller agent (tool-triggered rounds)
|
|
282
|
+
* @returns {Promise<{ agent: object, source: string, sessionId?: string }>}
|
|
283
|
+
*/
|
|
284
|
+
async function parentFor(explicit) {
|
|
285
|
+
if (typeof parentProvider === 'function') {
|
|
286
|
+
const provided = await parentProvider(explicit);
|
|
287
|
+
if (provided !== undefined && provided !== null && provided.agent !== undefined) return provided;
|
|
288
|
+
}
|
|
289
|
+
const agent = resolveParent(explicit);
|
|
290
|
+
return { agent, source: 'fallback', sessionId: agent?.session?.id ?? agent?.id };
|
|
291
|
+
}
|
|
292
|
+
|
|
174
293
|
function assertProvider(providerName) {
|
|
175
294
|
const service = subagents();
|
|
176
295
|
const provider = typeof service.getProvider === 'function' ? service.getProvider(providerName) : undefined;
|
|
@@ -196,7 +315,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
196
315
|
return { ok: true, head };
|
|
197
316
|
}
|
|
198
317
|
|
|
199
|
-
/** Scope entries of one card (files and `resource:`
|
|
318
|
+
/** Scope entries of one card (files and `resource:` announcement keys alike). */
|
|
200
319
|
function scopeOf(card) {
|
|
201
320
|
return Array.isArray(card.scope)
|
|
202
321
|
? card.scope.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
|
|
@@ -204,159 +323,319 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
204
323
|
}
|
|
205
324
|
|
|
206
325
|
/**
|
|
207
|
-
* Recall lessons for the card scope
|
|
208
|
-
*
|
|
326
|
+
* Recall lessons for the whole card scope: one `hive recall <query>` per scope
|
|
327
|
+
* entry plus one for the repository root (`.`), deduplicated by lesson.
|
|
328
|
+
*
|
|
329
|
+
* Every scope entry is queried (no sampling) so a lesson recorded against any
|
|
330
|
+
* card path is recalled by the next card that touches it. A recall error does
|
|
331
|
+
* not throw: the caller records it on the last-run record, logs a warning and
|
|
332
|
+
* continues the card with no lessons.
|
|
333
|
+
* @returns {Promise<{ lessons: object[], scopes: string[], error?: string }>}
|
|
209
334
|
*/
|
|
210
335
|
async function recallLessons(repo, scope, { agent, signal, session }) {
|
|
336
|
+
const scopes = [...new Set([...scope, '.'])];
|
|
211
337
|
const seen = new Map();
|
|
212
|
-
|
|
213
|
-
|
|
338
|
+
try {
|
|
339
|
+
for (const query of scopes) {
|
|
214
340
|
const items = await commands.recall(repo, query, { agent, signal, session });
|
|
215
341
|
for (const item of items) {
|
|
216
342
|
if (item === null || typeof item !== 'object' || typeof item.text !== 'string') continue;
|
|
217
343
|
seen.set(item.id ?? item.text, item);
|
|
218
344
|
}
|
|
219
|
-
} catch {
|
|
220
|
-
// Lessons are advisory; continue without them.
|
|
221
345
|
}
|
|
222
|
-
|
|
346
|
+
} catch (error) {
|
|
347
|
+
return { lessons: [], scopes, error: messageOf(error) };
|
|
223
348
|
}
|
|
224
|
-
return [...seen.values()]
|
|
349
|
+
return { lessons: [...seen.values()], scopes };
|
|
225
350
|
}
|
|
226
351
|
|
|
227
|
-
/** Best-effort release of the
|
|
228
|
-
async function releaseScope(repo, scope, { signal, session, agent }) {
|
|
352
|
+
/** Best-effort release of the announcements we own for this card scope. */
|
|
353
|
+
async function releaseScope(repo, scope, { signal, session, agent, instance }) {
|
|
229
354
|
if (scope.length === 0) return;
|
|
230
355
|
try {
|
|
231
|
-
await commands.release(repo, scope, { signal, session, agent });
|
|
356
|
+
await commands.release(repo, scope, { signal, session, agent, instance });
|
|
232
357
|
} catch {
|
|
233
|
-
// done/fail already
|
|
358
|
+
// done/fail already clear the announcements; this is only orphan cleanup.
|
|
234
359
|
}
|
|
235
360
|
}
|
|
236
361
|
|
|
237
|
-
/**
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
362
|
+
/**
|
|
363
|
+
* Announce the card scope on the consensus board (`hive guard --json`).
|
|
364
|
+
*
|
|
365
|
+
* hive-consensus 1.5.0 announcements never block anything: the guard always
|
|
366
|
+
* exits 0 and only reports advisory overlaps. A non-zero exit is therefore an
|
|
367
|
+
* unexpected CLI problem, logged as a warning and otherwise ignored; an
|
|
368
|
+
* exception is handled the same way. This function never fails a card.
|
|
369
|
+
* @returns {Promise<object[]>} raw overlap entries from the guard document
|
|
370
|
+
*/
|
|
371
|
+
async function announceScope(repo, id, scope, { agent, instance, signal, session }) {
|
|
372
|
+
if (scope.length === 0) return [];
|
|
373
|
+
try {
|
|
374
|
+
const guard = await commands.guard(repo, scope, {
|
|
375
|
+
agent,
|
|
376
|
+
instance,
|
|
377
|
+
taskId: id,
|
|
378
|
+
ttl: config.ttl,
|
|
379
|
+
signal,
|
|
380
|
+
session,
|
|
381
|
+
});
|
|
382
|
+
if (guard.exitCode !== 0) {
|
|
383
|
+
log('warn', 'card ' + id + ' in ' + repo + ' hive guard exited ' + String(guard.exitCode) + ' (continuing): ' + tail(guard.stderr || guard.stdout));
|
|
384
|
+
}
|
|
385
|
+
const overlaps = parseOverlaps(guard.stdout);
|
|
386
|
+
if (overlaps.length > 0) {
|
|
387
|
+
const agents = [];
|
|
388
|
+
for (const entry of overlaps) {
|
|
389
|
+
const name = entry !== null && typeof entry === 'object' && typeof entry.agent === 'string'
|
|
390
|
+
? entry.agent.trim()
|
|
391
|
+
: '';
|
|
392
|
+
if (name !== '' && !agents.includes(name)) agents.push(name);
|
|
393
|
+
}
|
|
394
|
+
log('info', 'card ' + id + ' in ' + repo + ' overlaps: ' + (agents.length > 0 ? agents.join(', ') : String(overlaps.length) + ' announcement(s)'));
|
|
395
|
+
}
|
|
396
|
+
return overlaps;
|
|
397
|
+
} catch (error) {
|
|
398
|
+
log('warn', 'card ' + id + ' in ' + repo + ' hive guard failed (continuing): ' + tail(messageOf(error)));
|
|
399
|
+
return [];
|
|
400
|
+
}
|
|
243
401
|
}
|
|
244
402
|
|
|
245
403
|
/** Best-effort release of a claim when the worker could not run at all. */
|
|
246
404
|
async function releaseClaim(repo, id, error, signal, session) {
|
|
247
405
|
await commands.fail(repo, id, {
|
|
248
406
|
reason: 'runner error: ' + tail(messageOf(error)),
|
|
407
|
+
instance: id,
|
|
249
408
|
signal,
|
|
250
409
|
session,
|
|
251
410
|
}).catch(() => {});
|
|
252
411
|
}
|
|
253
412
|
|
|
254
|
-
async function executeCard({ repo, card, before, owner, agent, signal, session }) {
|
|
413
|
+
async function executeCard({ repo, card, before, owner, agent, parentSource = 'queen', claimDeadline, signal, session }) {
|
|
255
414
|
const id = card.id;
|
|
256
415
|
const service = assertProvider(config.provider);
|
|
257
416
|
const scope = scopeOf(card);
|
|
258
417
|
const claimAgent = agent ?? config.agent;
|
|
418
|
+
// Per-card consensus instance: several cards of one runner share the same
|
|
419
|
+
// HIVE_AGENT, so the card id is what makes their announcements distinct and
|
|
420
|
+
// lets `hive guard --json` report overlaps instead of treating every
|
|
421
|
+
// announcement as its own.
|
|
422
|
+
const instance = id;
|
|
423
|
+
const cardTimeoutMs = config.cardTimeoutMs ?? 15 * 60_000;
|
|
424
|
+
const heartbeatWarnMs = config.heartbeatWarnMs ?? 5 * 60_000;
|
|
425
|
+
const heartbeatIntervalMs = config.heartbeatIntervalMs ?? 30_000;
|
|
426
|
+
// Announce the card scope before anything starts. This never fails the
|
|
427
|
+
// card: on hive-consensus 1.5.0 the guard always succeeds, overlaps are
|
|
428
|
+
// advisory and an unexpected CLI error is only logged.
|
|
429
|
+
const overlaps = await announceScope(repo, id, scope, {
|
|
430
|
+
agent: claimAgent,
|
|
431
|
+
instance,
|
|
432
|
+
signal,
|
|
433
|
+
session,
|
|
434
|
+
});
|
|
435
|
+
const startedAt = new Date(now()).toISOString();
|
|
259
436
|
// One last-run record per card: write `running` when the attempt starts and
|
|
260
|
-
// overwrite it with the terminal state before returning/raising.
|
|
437
|
+
// overwrite it with the terminal state before returning/raising. The record
|
|
438
|
+
// carries the worker Session id as soon as the activation is accepted, and
|
|
439
|
+
// the guard's advisory overlaps on both writes.
|
|
261
440
|
const run = {
|
|
262
441
|
cardId: id,
|
|
263
442
|
agent: claimAgent,
|
|
264
|
-
|
|
443
|
+
role: card.role,
|
|
444
|
+
parentSource,
|
|
445
|
+
startedAt,
|
|
446
|
+
lastOutputAt: startedAt,
|
|
447
|
+
heartbeat: 'ok',
|
|
265
448
|
endedAt: null,
|
|
266
449
|
status: 'running',
|
|
267
450
|
output: '',
|
|
451
|
+
timeoutAt: new Date(now() + cardTimeoutMs).toISOString(),
|
|
452
|
+
...(Number.isFinite(claimDeadline) ? { claimDeadline: new Date(claimDeadline).toISOString() } : {}),
|
|
453
|
+
...(overlaps.length > 0 ? { overlaps } : {}),
|
|
268
454
|
};
|
|
269
455
|
let runFinished = false;
|
|
270
456
|
recordRun(repo, run);
|
|
457
|
+
registerActive(repo, run);
|
|
271
458
|
const finishRun = (status, patch = {}) => {
|
|
272
459
|
runFinished = true;
|
|
273
|
-
|
|
460
|
+
const endedAt = new Date(now()).toISOString();
|
|
461
|
+
recordRun(repo, { ...run, ...patch, status, endedAt });
|
|
462
|
+
run.endedAt = endedAt;
|
|
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
|
+
}
|
|
470
|
+
unregisterActive(repo, id);
|
|
274
471
|
};
|
|
275
472
|
let activation;
|
|
276
473
|
let releaseEnv = () => {};
|
|
474
|
+
let timedOut = false;
|
|
475
|
+
let settled = false;
|
|
476
|
+
const controller = new AbortController();
|
|
477
|
+
const workerSignal = signal === undefined ? controller.signal : AbortSignal.any([signal, controller.signal]);
|
|
478
|
+
const abortWait = new Promise((resolve) => {
|
|
479
|
+
if (controller.signal.aborted) resolve();
|
|
480
|
+
else controller.signal.addEventListener('abort', () => resolve(), { once: true });
|
|
481
|
+
});
|
|
482
|
+
let timeoutTimer;
|
|
483
|
+
let heartbeatTimer;
|
|
484
|
+
const clearMonitors = () => {
|
|
485
|
+
if (timeoutTimer !== undefined) clearTimeout(timeoutTimer);
|
|
486
|
+
if (heartbeatTimer !== undefined) clearInterval(heartbeatTimer);
|
|
487
|
+
timeoutTimer = undefined;
|
|
488
|
+
heartbeatTimer = undefined;
|
|
489
|
+
};
|
|
490
|
+
const abortReason = () => 'card timeout after ' + cardTimeoutMs + 'ms';
|
|
491
|
+
const failCard = async (reason, output = reason) => {
|
|
492
|
+
await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session }).catch(() => {});
|
|
493
|
+
finishRun('failed', { exitCode: 1, output });
|
|
494
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
495
|
+
return { id, state: 'failed', reason };
|
|
496
|
+
};
|
|
277
497
|
try {
|
|
278
|
-
//
|
|
279
|
-
//
|
|
280
|
-
//
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
session,
|
|
288
|
-
});
|
|
289
|
-
if (guard.exitCode === 2) {
|
|
290
|
-
const holders = deniedHolders(guard.stderr);
|
|
291
|
-
const selfHeld = holders.length > 0 && holders.every((holder) => holder === claimAgent);
|
|
292
|
-
if (selfHeld) {
|
|
293
|
-
// Our own earlier lease (for example after a retry): allow the card
|
|
294
|
-
// and extend the leases instead of failing it.
|
|
295
|
-
await commands.renew(repo, scope, { agent: claimAgent, ttl: config.ttl, signal, session }).catch(() => {});
|
|
296
|
-
} else {
|
|
297
|
-
const reason = 'guard denied: ' + tail(guard.stderr || guard.stdout || 'scope held by another agent');
|
|
298
|
-
await commands.fail(repo, id, { agent: claimAgent, reason, signal, session });
|
|
299
|
-
finishRun('failed', { exitCode: guard.exitCode, output: guard.stderr || guard.stdout });
|
|
300
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent });
|
|
301
|
-
return { id, state: 'failed', reason };
|
|
302
|
-
}
|
|
303
|
-
} else if (guard.exitCode !== 0) {
|
|
304
|
-
throw new RoundError(
|
|
305
|
-
'hive/guard-failed',
|
|
306
|
-
'hive guard exited ' + String(guard.exitCode) + ': ' + tail(guard.stderr || guard.stdout),
|
|
307
|
-
);
|
|
308
|
-
}
|
|
498
|
+
// Recall lessons for every scope path plus the repository root before the
|
|
499
|
+
// worker starts. A recall error is recorded on the run record and logged,
|
|
500
|
+
// never a card failure: the work continues without lessons.
|
|
501
|
+
const recall = await recallLessons(repo, scope, { agent: claimAgent, signal, session });
|
|
502
|
+
if (recall.error !== undefined) {
|
|
503
|
+
log('warn', 'card ' + id + ' in ' + repo + ' reading lessons failed (continuing): ' + tail(recall.error));
|
|
504
|
+
run.lessons = { count: 0, scopes: recall.scopes, error: recall.error };
|
|
505
|
+
} else {
|
|
506
|
+
run.lessons = { count: recall.lessons.length, scopes: recall.scopes };
|
|
309
507
|
}
|
|
310
|
-
|
|
508
|
+
// Rewrite the opening running record now that recall finished, so the
|
|
509
|
+
// panel can show "recalled N lessons / no lesson matched" while the card
|
|
510
|
+
// is still running.
|
|
511
|
+
recordRun(repo, run);
|
|
512
|
+
const lessons = recall.lessons;
|
|
311
513
|
// Workers run in-process; DSH's bash tool inherits ambient env. Inject the
|
|
312
|
-
// claim identity
|
|
313
|
-
// hive
|
|
314
|
-
releaseEnv = acquireHiveAgentEnv(claimAgent);
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
514
|
+
// claim identity and this card's instance while the worker is alive, so
|
|
515
|
+
// its own `hive guard` / `hive release` calls agree with the runner's.
|
|
516
|
+
releaseEnv = acquireHiveAgentEnv(claimAgent, instance);
|
|
517
|
+
// Hard per-card timeout: abort the worker at the deadline.
|
|
518
|
+
timeoutTimer = setTimeout(() => {
|
|
519
|
+
if (settled) return;
|
|
520
|
+
timedOut = true;
|
|
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
|
+
});
|
|
529
|
+
log('warn', 'card ' + id + ' in ' + repo + ' timed out after ' + cardTimeoutMs + 'ms');
|
|
530
|
+
}, cardTimeoutMs);
|
|
531
|
+
activation = await Promise.race([
|
|
532
|
+
service.startActivation({
|
|
533
|
+
provider: config.provider,
|
|
534
|
+
label: 'hive:' + id,
|
|
535
|
+
prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent) }],
|
|
536
|
+
cwd: repo,
|
|
537
|
+
parent: owner,
|
|
538
|
+
signal: workerSignal,
|
|
539
|
+
delivery: 'caller',
|
|
540
|
+
}),
|
|
541
|
+
abortWait.then(() => null),
|
|
542
|
+
]);
|
|
543
|
+
if (activation === null) {
|
|
544
|
+
settled = true;
|
|
545
|
+
clearMonitors();
|
|
546
|
+
return await failCard(abortReason());
|
|
547
|
+
}
|
|
324
548
|
// Keep the worker's Session identity on the run record: the panel opens
|
|
325
549
|
// that conversation exactly like one click in the header's subagent list.
|
|
326
550
|
// A provider without an accepted child (none in practice) leaves it out.
|
|
327
551
|
if (typeof activation.childId === 'string' && activation.childId !== '') run.sessionId = activation.childId;
|
|
328
552
|
if (typeof activation.name === 'string' && activation.name !== '') run.agentName = activation.name;
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
553
|
+
// Persist the still-running record as soon as the child is accepted, not only
|
|
554
|
+
// at the terminal write: the panel must be able to open the worker chat while
|
|
555
|
+
// the card is still in progress.
|
|
556
|
+
if (run.sessionId !== undefined || run.agentName !== undefined) recordRun(repo, run);
|
|
557
|
+
|
|
558
|
+
// Heartbeat: during the run, watch the repository HEAD as the observable
|
|
559
|
+
// "output" signal. If it does not move for heartbeatWarnMs, mark the
|
|
560
|
+
// worker as heartbeat=warn in the run record and in supervisor status.
|
|
561
|
+
let lastHead = before;
|
|
562
|
+
let heartbeatWarned = false;
|
|
563
|
+
const heartbeatEvery = Math.max(1, Math.min(heartbeatIntervalMs, Math.max(1, Math.floor(heartbeatWarnMs / 2))));
|
|
564
|
+
const checkHeartbeat = async () => {
|
|
565
|
+
if (settled) return;
|
|
566
|
+
try {
|
|
567
|
+
const head = await commands.head(repo, { agent: claimAgent, signal, session });
|
|
568
|
+
if (head !== lastHead) {
|
|
569
|
+
lastHead = head;
|
|
570
|
+
run.lastOutputAt = new Date(now()).toISOString();
|
|
571
|
+
run.heartbeat = 'ok';
|
|
572
|
+
heartbeatWarned = false;
|
|
573
|
+
recordRun(repo, { ...run });
|
|
574
|
+
}
|
|
575
|
+
} catch {
|
|
576
|
+
// Heartbeat checks are advisory; a failed HEAD probe is not a verdict.
|
|
577
|
+
}
|
|
578
|
+
if (settled || heartbeatWarned) return;
|
|
579
|
+
const idle = now() - Date.parse(run.lastOutputAt);
|
|
580
|
+
if (idle >= heartbeatWarnMs) {
|
|
581
|
+
heartbeatWarned = true;
|
|
582
|
+
run.heartbeat = 'warn';
|
|
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
|
+
});
|
|
591
|
+
log('warn', 'card ' + id + ' in ' + repo + ' produced no output for ' + idle + 'ms (heartbeat warn)');
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
heartbeatTimer = setInterval(() => {
|
|
595
|
+
void checkHeartbeat();
|
|
596
|
+
}, heartbeatEvery);
|
|
597
|
+
|
|
598
|
+
const outcome = await Promise.race([activation.result, abortWait.then(() => null)]);
|
|
599
|
+
settled = true;
|
|
600
|
+
clearMonitors();
|
|
601
|
+
if (timedOut) return await failCard(abortReason());
|
|
602
|
+
if (outcome === null) {
|
|
603
|
+
// Aborted before the provider settled: report it as a round failure and
|
|
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
|
+
});
|
|
612
|
+
throw new RoundError('hive/round-aborted', 'worker activation was aborted before it settled');
|
|
339
613
|
}
|
|
340
614
|
if (outcome.stopReason !== 'completed') {
|
|
341
615
|
const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
|
|
342
616
|
const reason = 'subagent stopped: ' + outcome.stopReason + detail;
|
|
343
|
-
await commands.fail(repo, id, { agent: claimAgent, reason, signal, session });
|
|
344
|
-
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason) });
|
|
345
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent });
|
|
617
|
+
await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session });
|
|
618
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason), reason });
|
|
619
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
346
620
|
return { id, state: 'failed', reason };
|
|
347
621
|
}
|
|
348
622
|
const verdict = await verify({ repo, before, card, agent: claimAgent, signal, session });
|
|
349
623
|
if (verdict.ok) {
|
|
350
|
-
await commands.done(repo, id, { agent: claimAgent, sha: verdict.head, verdict: 'pass', signal, session });
|
|
624
|
+
await commands.done(repo, id, { agent: claimAgent, instance, sha: verdict.head, verdict: 'pass', signal, session });
|
|
351
625
|
finishRun('done', { exitCode: 0, commit: verdict.head, output: workerOutput(outcome) });
|
|
352
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent });
|
|
626
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
353
627
|
return { id, state: 'done', sha: verdict.head };
|
|
354
628
|
}
|
|
355
|
-
await commands.fail(repo, id, { agent: claimAgent, reason: verdict.reason, signal, session });
|
|
356
|
-
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason) });
|
|
357
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent });
|
|
629
|
+
await commands.fail(repo, id, { agent: claimAgent, instance, reason: verdict.reason, signal, session });
|
|
630
|
+
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason), reason: verdict.reason });
|
|
631
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
358
632
|
return { id, state: 'failed', reason: verdict.reason };
|
|
359
633
|
} catch (error) {
|
|
634
|
+
settled = true;
|
|
635
|
+
clearMonitors();
|
|
636
|
+
if (timedOut) {
|
|
637
|
+
return await failCard(abortReason(), messageOf(error) || abortReason());
|
|
638
|
+
}
|
|
360
639
|
if (!runFinished) finishRun('failed', { exitCode: 1, output: messageOf(error) });
|
|
361
640
|
if (isCapacityError(error)) {
|
|
362
641
|
// Capacity is a scheduling concern, not this card's failure: keep the
|
|
@@ -371,13 +650,16 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
371
650
|
const environment = error?.deferrable === true
|
|
372
651
|
|| (typeof error?.code === 'string' && error.code.startsWith('hive/no-'));
|
|
373
652
|
if (!environment) await releaseClaim(repo, id, error, signal, session);
|
|
374
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent });
|
|
653
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
375
654
|
throw error instanceof RoundError
|
|
376
655
|
? error
|
|
377
656
|
: environment
|
|
378
657
|
? error
|
|
379
658
|
: new RoundError('hive/round-failed', messageOf(error), { cause: error });
|
|
380
659
|
} finally {
|
|
660
|
+
settled = true;
|
|
661
|
+
clearMonitors();
|
|
662
|
+
unregisterActive(repo, id);
|
|
381
663
|
try {
|
|
382
664
|
if (activation !== undefined) {
|
|
383
665
|
await Promise.resolve(activation.dispose?.()).catch(() => {});
|
|
@@ -390,6 +672,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
390
672
|
|
|
391
673
|
return {
|
|
392
674
|
resolveParent,
|
|
675
|
+
activeRuns,
|
|
393
676
|
|
|
394
677
|
/**
|
|
395
678
|
* Round-start environment check: the repository must be Hive-initialised
|
|
@@ -422,7 +705,8 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
422
705
|
return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
|
|
423
706
|
}
|
|
424
707
|
const id = card.id;
|
|
425
|
-
const
|
|
708
|
+
const ownerInfo = await parentFor(parent);
|
|
709
|
+
const owner = ownerInfo.agent;
|
|
426
710
|
let fresh = card;
|
|
427
711
|
try {
|
|
428
712
|
const shown = await commands.show(repo, id, { agent: agent ?? config.agent, signal, session });
|
|
@@ -442,17 +726,39 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
|
|
|
442
726
|
return { id, state: 'skipped', reason: 'claim held by ' + String(fresh.owner) };
|
|
443
727
|
}
|
|
444
728
|
|
|
729
|
+
const ttlMs = parseTtlMs(ttl ?? config.ttl);
|
|
445
730
|
if (!alreadyClaimed) {
|
|
446
731
|
const before = await commands.head(repo, { agent: agentId, signal, session });
|
|
447
|
-
const claim = await commands.claim(repo, id, { signal, session, agent, ttl });
|
|
732
|
+
const claim = await commands.claim(repo, id, { signal, session, agent, instance: id, ttl });
|
|
448
733
|
if (claim.exitCode !== 0) {
|
|
449
734
|
return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
|
|
450
735
|
}
|
|
451
|
-
return await executeCard({
|
|
736
|
+
return await executeCard({
|
|
737
|
+
repo,
|
|
738
|
+
card: fresh,
|
|
739
|
+
before,
|
|
740
|
+
owner,
|
|
741
|
+
agent: agentId,
|
|
742
|
+
parentSource: ownerInfo.source,
|
|
743
|
+
claimDeadline: now() + ttlMs,
|
|
744
|
+
signal,
|
|
745
|
+
session,
|
|
746
|
+
});
|
|
452
747
|
}
|
|
453
748
|
|
|
454
749
|
const before = await commands.head(repo, { agent: agentId, signal, session });
|
|
455
|
-
|
|
750
|
+
const claimDeadline = Number.isFinite(claimedUntil) ? claimedUntil : now() + ttlMs;
|
|
751
|
+
return await executeCard({
|
|
752
|
+
repo,
|
|
753
|
+
card: fresh,
|
|
754
|
+
before,
|
|
755
|
+
owner,
|
|
756
|
+
agent: agentId,
|
|
757
|
+
parentSource: ownerInfo.source,
|
|
758
|
+
claimDeadline,
|
|
759
|
+
signal,
|
|
760
|
+
session,
|
|
761
|
+
});
|
|
456
762
|
},
|
|
457
763
|
};
|
|
458
764
|
}
|