dsh-hive-runner 0.6.4 → 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/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)');
@@ -56,32 +66,22 @@ export function renderPrompt(card, lessons = [], claimAgent) {
56
66
  if (card.acceptance) lines.push('## Acceptance (the runner will run this)', ' ' + card.acceptance, '');
57
67
  if (card.reason) lines.push('## Previous attempt failed with', card.reason, '');
58
68
  lines.push('## Hive consensus rules (mandatory)');
59
- lines.push('1. At the start, run `hive guard <path...>` for every entry in the card scope (including `resource:` entries, which are leases, not files). It co-signs your leases and marks the board working.'
60
- + (claimAgent ? ' Use the same claim identity, for example `hive guard <path...> --agent ' + claimAgent + '`; a different identity would collide with your own leases.' : ''));
61
- lines.push('2. If `hive guard` exits 2, stop immediately and report the holder information (stderr) as the failure reason. NEVER bypass it: do not edit files outside the scope, do not `git checkout` files owned by someone else, and do not delete lease refs.');
62
- lines.push('3. Your claim already marks the board working with this task id; guard keeps it current.');
63
- lines.push('4. Before finishing, release your own leases (`hive release <scope...>`); done/fail normally release them, but verify nothing is left behind.');
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.');
64
74
  if (lessons.length > 0) {
65
- lines.push('5. The runner already ran `hive recall <scope>` for this card; the relevant experience is injected below. Only if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path); do not write a lesson just to write one.');
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.');
66
76
  } else {
67
- lines.push('5. The runner already ran `hive recall <scope>`; if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path); do not write a lesson just to write one.');
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.');
68
78
  }
69
79
  lines.push('');
70
80
  lines.push('## Commit rules (mandatory)');
71
- lines.push('0. Every command you run, especially `git commit`, MUST carry `HIVE_AGENT` in its environment: use the claim identity, for example `HIVE_AGENT=' + (claimAgent || '<claim identity>') + ' git commit -m "..."` or export it first. Never rely on the host environment being set.');
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.');
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.');
74
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.');
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.');
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.');
76
84
  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
85
  lines.push('## How to finish');
86
86
  lines.push('1. Edit only the scope paths.');
87
87
  lines.push('2. Commit before you exit: the runner checks that HEAD moved through the hook.');
@@ -93,32 +93,86 @@ function messageOf(error) {
93
93
  return error instanceof Error ? error.message : String(error);
94
94
  }
95
95
 
96
- /** Hook output that means the commit skipped lease enforcement. */
97
- export function hasHookEnvWarning(text) {
98
- return /HIVE_AGENT is not set|lease enforcement skipped/i.test(String(text ?? ''));
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;
99
124
  }
100
125
 
101
- /** Text the worker produced (final assistant output plus provider diagnostic). */
102
- function workerText(outcome) {
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) {
103
140
  const blocks = Array.isArray(outcome?.output) ? outcome.output : [];
104
- const text = blocks
105
- .filter((block) => block !== null && typeof block === 'object' && typeof block.text === 'string')
106
- .map((block) => block.text)
107
- .join('\n');
108
- return text + '\n' + String(outcome?.diagnostic ?? '');
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 '';
109
153
  }
110
154
 
111
155
  /** Worker output for the last-run record, falling back to the card verdict. */
112
156
  export function workerOutput(outcome, fallback = '') {
113
- const text = workerText(outcome);
114
- return text.trim() === '' ? String(fallback) : text;
157
+ const text = finalAssistantText(outcome);
158
+ return text === '' ? String(fallback) : text;
115
159
  }
116
160
 
117
161
  /**
118
162
  * Bind the Hive round helpers to the DSH runtime and the Hive command layer.
119
163
  * @param {{ ctx: object, config: object, commands: object }} options
120
164
  */
121
- export function createRoundRunner({ ctx, config, commands, limitFor, checkHook = assertMergeOnCommitHook, writeRun = writeRunRecord }) {
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
+ }) {
122
176
  if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
123
177
  throw new TypeError('createRoundRunner: ctx with ctx.get() is required');
124
178
  }
@@ -133,6 +187,41 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
133
187
  // The record file is a convenience for the panel, not part of the verdict.
134
188
  }
135
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
+
136
225
  /** Effective live-worker cap for (repo, role). The plugin passes the persisted-limits store. */
137
226
  const capFor = typeof limitFor === 'function'
138
227
  ? limitFor
@@ -171,6 +260,21 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
171
260
  );
172
261
  }
173
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
+
174
278
  function assertProvider(providerName) {
175
279
  const service = subagents();
176
280
  const provider = typeof service.getProvider === 'function' ? service.getProvider(providerName) : undefined;
@@ -196,7 +300,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
196
300
  return { ok: true, head };
197
301
  }
198
302
 
199
- /** Scope entries of one card (files and `resource:` lease keys alike). */
303
+ /** Scope entries of one card (files and `resource:` announcement keys alike). */
200
304
  function scopeOf(card) {
201
305
  return Array.isArray(card.scope)
202
306
  ? card.scope.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
@@ -204,159 +308,292 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
204
308
  }
205
309
 
206
310
  /**
207
- * Recall lessons for the card scope. Best effort: a recall failure never
208
- * blocks the card (the runner already has the environment churn signal).
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 }>}
209
319
  */
210
320
  async function recallLessons(repo, scope, { agent, signal, session }) {
321
+ const scopes = [...new Set([...scope, '.'])];
211
322
  const seen = new Map();
212
- for (const query of scope.slice(0, 3)) {
213
- try {
323
+ try {
324
+ for (const query of scopes) {
214
325
  const items = await commands.recall(repo, query, { agent, signal, session });
215
326
  for (const item of items) {
216
327
  if (item === null || typeof item !== 'object' || typeof item.text !== 'string') continue;
217
328
  seen.set(item.id ?? item.text, item);
218
329
  }
219
- } catch {
220
- // Lessons are advisory; continue without them.
221
330
  }
222
- if (seen.size >= 5) break;
331
+ } catch (error) {
332
+ return { lessons: [], scopes, error: messageOf(error) };
223
333
  }
224
- return [...seen.values()].slice(0, 5);
334
+ return { lessons: [...seen.values()], scopes };
225
335
  }
226
336
 
227
- /** Best-effort release of the leases we own for this card scope. */
228
- 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 }) {
229
339
  if (scope.length === 0) return;
230
340
  try {
231
- await commands.release(repo, scope, { signal, session, agent });
341
+ await commands.release(repo, scope, { signal, session, agent, instance });
232
342
  } catch {
233
- // done/fail already release leases; this is only orphan cleanup.
343
+ // done/fail already clear the announcements; this is only orphan cleanup.
234
344
  }
235
345
  }
236
346
 
237
- /** Holder agent names parsed from `hive guard` denial stderr. */
238
- function deniedHolders(stderr) {
239
- const holders = new Set();
240
- const pattern = /([^\s]+)\s+holds it/g;
241
- for (const match of String(stderr ?? '').matchAll(pattern)) holders.add(match[1]);
242
- return [...holders];
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
+ }
243
386
  }
244
387
 
245
388
  /** Best-effort release of a claim when the worker could not run at all. */
246
389
  async function releaseClaim(repo, id, error, signal, session) {
247
390
  await commands.fail(repo, id, {
248
391
  reason: 'runner error: ' + tail(messageOf(error)),
392
+ instance: id,
249
393
  signal,
250
394
  session,
251
395
  }).catch(() => {});
252
396
  }
253
397
 
254
- async function executeCard({ repo, card, before, owner, agent, signal, session }) {
398
+ async function executeCard({ repo, card, before, owner, agent, parentSource = 'queen', claimDeadline, signal, session }) {
255
399
  const id = card.id;
256
400
  const service = assertProvider(config.provider);
257
401
  const scope = scopeOf(card);
258
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();
259
421
  // One last-run record per card: write `running` when the attempt starts and
260
- // overwrite it with the terminal state before returning/raising.
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.
261
425
  const run = {
262
426
  cardId: id,
263
427
  agent: claimAgent,
264
- startedAt: new Date().toISOString(),
428
+ role: card.role,
429
+ parentSource,
430
+ startedAt,
431
+ lastOutputAt: startedAt,
432
+ heartbeat: 'ok',
265
433
  endedAt: null,
266
434
  status: 'running',
267
435
  output: '',
436
+ timeoutAt: new Date(now() + cardTimeoutMs).toISOString(),
437
+ ...(Number.isFinite(claimDeadline) ? { claimDeadline: new Date(claimDeadline).toISOString() } : {}),
438
+ ...(overlaps.length > 0 ? { overlaps } : {}),
268
439
  };
269
440
  let runFinished = false;
270
441
  recordRun(repo, run);
442
+ registerActive(repo, run);
271
443
  const finishRun = (status, patch = {}) => {
272
444
  runFinished = true;
273
- recordRun(repo, { ...run, ...patch, status, endedAt: new Date().toISOString() });
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);
274
450
  };
275
451
  let activation;
276
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
+ };
277
476
  try {
278
- // hive-consensus: co-sign the card's leases (guard) with the SAME identity
279
- // used for the claim. A different identity would collide with the claim's
280
- // own leases and deny itself.
281
- if (scope.length > 0) {
282
- const guard = await commands.guard(repo, scope, {
283
- agent: claimAgent,
284
- taskId: id,
285
- ttl: config.ttl,
286
- signal,
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
- }
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 };
309
486
  }
310
- const lessons = scope.length > 0 ? await recallLessons(repo, scope, { agent: claimAgent, signal, session }) : [];
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;
311
492
  // Workers run in-process; DSH's bash tool inherits ambient env. Inject the
312
- // claim identity while this worker is alive so its git commit passes the
313
- // hive pre-commit lease check ("HIVE_AGENT is not set" must never happen).
314
- releaseEnv = acquireHiveAgentEnv(claimAgent);
315
- activation = await service.startActivation({
316
- provider: config.provider,
317
- label: 'hive:' + id,
318
- prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent) }],
319
- cwd: repo,
320
- parent: owner,
321
- signal,
322
- delivery: 'caller',
323
- });
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
+ }
324
520
  // Keep the worker's Session identity on the run record: the panel opens
325
521
  // that conversation exactly like one click in the header's subagent list.
326
522
  // A provider without an accepted child (none in practice) leaves it out.
327
523
  if (typeof activation.childId === 'string' && activation.childId !== '') run.sessionId = activation.childId;
328
524
  if (typeof activation.name === 'string' && activation.name !== '') run.agentName = activation.name;
329
- const outcome = await activation.result;
330
- if (outcome.stopReason === 'completed' && hasHookEnvWarning(workerText(outcome))) {
331
- // The worker reported that the hook skipped lease enforcement: the
332
- // commit did not pass the consensus check. Defer, do not mark it done.
333
- throw new RoundError(
334
- 'hive/no-hive-agent-env',
335
- 'pre-commit reported "HIVE_AGENT is not set": lease enforcement skipped; '
336
- + 'the environment injection did not reach the worker commit',
337
- { deferrable: true },
338
- );
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 });
546
+ }
547
+ } catch {
548
+ // Heartbeat checks are advisory; a failed HEAD probe is not a verdict.
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');
339
571
  }
340
572
  if (outcome.stopReason !== 'completed') {
341
573
  const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
342
574
  const reason = 'subagent stopped: ' + outcome.stopReason + detail;
343
- await commands.fail(repo, id, { agent: claimAgent, reason, signal, session });
575
+ await commands.fail(repo, id, { agent: claimAgent, instance, reason, signal, session });
344
576
  finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason) });
345
- await releaseScope(repo, scope, { signal, session, agent: claimAgent });
577
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
346
578
  return { id, state: 'failed', reason };
347
579
  }
348
580
  const verdict = await verify({ repo, before, card, agent: claimAgent, signal, session });
349
581
  if (verdict.ok) {
350
- await commands.done(repo, id, { agent: claimAgent, sha: verdict.head, verdict: 'pass', signal, session });
582
+ await commands.done(repo, id, { agent: claimAgent, instance, sha: verdict.head, verdict: 'pass', signal, session });
351
583
  finishRun('done', { exitCode: 0, commit: verdict.head, output: workerOutput(outcome) });
352
- await releaseScope(repo, scope, { signal, session, agent: claimAgent });
584
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
353
585
  return { id, state: 'done', sha: verdict.head };
354
586
  }
355
- await commands.fail(repo, id, { agent: claimAgent, reason: verdict.reason, signal, session });
587
+ await commands.fail(repo, id, { agent: claimAgent, instance, reason: verdict.reason, signal, session });
356
588
  finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason) });
357
- await releaseScope(repo, scope, { signal, session, agent: claimAgent });
589
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
358
590
  return { id, state: 'failed', reason: verdict.reason };
359
591
  } catch (error) {
592
+ settled = true;
593
+ clearMonitors();
594
+ if (timedOut) {
595
+ return await failCard(abortReason(), messageOf(error) || abortReason());
596
+ }
360
597
  if (!runFinished) finishRun('failed', { exitCode: 1, output: messageOf(error) });
361
598
  if (isCapacityError(error)) {
362
599
  // Capacity is a scheduling concern, not this card's failure: keep the
@@ -371,13 +608,16 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
371
608
  const environment = error?.deferrable === true
372
609
  || (typeof error?.code === 'string' && error.code.startsWith('hive/no-'));
373
610
  if (!environment) await releaseClaim(repo, id, error, signal, session);
374
- await releaseScope(repo, scope, { signal, session, agent: claimAgent });
611
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
375
612
  throw error instanceof RoundError
376
613
  ? error
377
614
  : environment
378
615
  ? error
379
616
  : new RoundError('hive/round-failed', messageOf(error), { cause: error });
380
617
  } finally {
618
+ settled = true;
619
+ clearMonitors();
620
+ unregisterActive(repo, id);
381
621
  try {
382
622
  if (activation !== undefined) {
383
623
  await Promise.resolve(activation.dispose?.()).catch(() => {});
@@ -390,6 +630,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
390
630
 
391
631
  return {
392
632
  resolveParent,
633
+ activeRuns,
393
634
 
394
635
  /**
395
636
  * Round-start environment check: the repository must be Hive-initialised
@@ -422,7 +663,8 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
422
663
  return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
423
664
  }
424
665
  const id = card.id;
425
- const owner = resolveParent(parent);
666
+ const ownerInfo = await parentFor(parent);
667
+ const owner = ownerInfo.agent;
426
668
  let fresh = card;
427
669
  try {
428
670
  const shown = await commands.show(repo, id, { agent: agent ?? config.agent, signal, session });
@@ -442,17 +684,39 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
442
684
  return { id, state: 'skipped', reason: 'claim held by ' + String(fresh.owner) };
443
685
  }
444
686
 
687
+ const ttlMs = parseTtlMs(ttl ?? config.ttl);
445
688
  if (!alreadyClaimed) {
446
689
  const before = await commands.head(repo, { agent: agentId, signal, session });
447
- const claim = await commands.claim(repo, id, { signal, session, agent, ttl });
690
+ const claim = await commands.claim(repo, id, { signal, session, agent, instance: id, ttl });
448
691
  if (claim.exitCode !== 0) {
449
692
  return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
450
693
  }
451
- return await executeCard({ repo, card: fresh, before, owner, agent: agentId, signal, session });
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
+ });
452
705
  }
453
706
 
454
707
  const before = await commands.head(repo, { agent: agentId, signal, session });
455
- return await executeCard({ repo, card: fresh, before, owner, 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
+ });
456
720
  },
457
721
  };
458
722
  }