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/lib/runs.js CHANGED
@@ -9,12 +9,18 @@
9
9
  * A record produced by a worker activation also carries the child Session id
10
10
  * (`sessionId`) and the model-facing child name (`agentName`), so the panel can
11
11
  * open that worker's conversation; both keys are omitted when the attempt never
12
- * reached an activation (for example a guard denial).
12
+ * reached an activation (for example an activation that threw before returning
13
+ * a child). An attempt whose `hive guard` announcement found another agent on
14
+ * the same or a related path carries an `overlaps` array (see
15
+ * `normalizeOverlaps`) on the opening `running` write and on the terminal write.
13
16
  * The path is derived from the card id after `ID_RE` validation, which rejects
14
17
  * path separators, so a card id can never escape `.hive/runs`.
15
18
  *
16
- * `output` keeps the *smaller* of the last 200 lines and the last 32 KiB of
17
- * UTF-8, which bounds the file on disk no matter how chatty the worker is.
19
+ * `output` is the worker's final result message, not its process: the text blocks
20
+ * of the last assistant message only (lib/round.js strips reasoning/thinking, tool
21
+ * calls and narration; a provider without a typed text block falls back to the last
22
+ * non-empty text). It keeps the *smaller* of the last 200 lines and the last 32 KiB
23
+ * of UTF-8, which bounds the file on disk no matter how chatty the worker is.
18
24
  */
19
25
  import fs from 'node:fs';
20
26
  import path from 'node:path';
@@ -27,6 +33,8 @@ export const RUNS_DIR = path.join('.hive', 'runs');
27
33
  export const RUN_OUTPUT_MAX_BYTES = 32 * 1024;
28
34
  /** Hard cap on the stored `output` lines. */
29
35
  export const RUN_OUTPUT_MAX_LINES = 200;
36
+ /** Hard cap on the stored `overlaps` entries. */
37
+ export const RUN_OVERLAPS_MAX = 100;
30
38
 
31
39
  /** Valid record statuses. */
32
40
  export const RUN_STATUSES = Object.freeze(['done', 'failed', 'running']);
@@ -54,6 +62,58 @@ export function truncateRunOutput(text, { maxBytes = RUN_OUTPUT_MAX_BYTES, maxLi
54
62
  return Buffer.byteLength(byBytes) < Buffer.byteLength(byLines) ? byBytes : byLines;
55
63
  }
56
64
 
65
+ /**
66
+ * Normalize the optional announcement overlaps of one attempt.
67
+ *
68
+ * The consensus board reports `{ key, agent, task, expiresAt }` entries. Only
69
+ * entries with a non-empty string `agent` survive; `key`, `task` and
70
+ * `expiresAt` are copied when they are non-empty strings, and everything else
71
+ * is dropped. The list is capped at `RUN_OVERLAPS_MAX` entries.
72
+ * @param {unknown} value
73
+ * @returns {Array<{ agent: string, key?: string, task?: string, expiresAt?: string }>}
74
+ */
75
+ export function normalizeOverlaps(value) {
76
+ if (!Array.isArray(value)) return [];
77
+ const overlaps = [];
78
+ for (const entry of value) {
79
+ if (overlaps.length >= RUN_OVERLAPS_MAX) break;
80
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue;
81
+ if (typeof entry.agent !== 'string' || entry.agent.trim() === '') continue;
82
+ const overlap = { agent: entry.agent };
83
+ for (const key of ['key', 'task', 'expiresAt']) {
84
+ if (typeof entry[key] === 'string' && entry[key].trim() !== '') overlap[key] = entry[key];
85
+ }
86
+ overlaps.push(overlap);
87
+ }
88
+ return overlaps;
89
+ }
90
+
91
+ /** Hard cap on the stored `lessons.scopes` entries. */
92
+ export const RUN_LESSON_SCOPES_MAX = 100;
93
+
94
+ /**
95
+ * Normalize the optional recall summary of one attempt.
96
+ *
97
+ * The runner always writes it after recall finishes: `{ count, scopes }` on a
98
+ * successful recall, `{ count: 0, scopes, error }` when recall failed. The
99
+ * panel reads `lessons.count` to show "recalled N lessons / no lesson matched",
100
+ * so the three keys are fixed.
101
+ * @param {unknown} value
102
+ * @returns {{ count: number, scopes: string[], error?: string } | null}
103
+ */
104
+ export function normalizeLessons(value) {
105
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
106
+ const count = Number.isInteger(value.count) && value.count >= 0 ? value.count : 0;
107
+ const scopes = Array.isArray(value.scopes)
108
+ ? value.scopes
109
+ .filter((scope) => typeof scope === 'string' && scope.trim() !== '')
110
+ .slice(0, RUN_LESSON_SCOPES_MAX)
111
+ : [];
112
+ const lessons = { count, scopes };
113
+ if (typeof value.error === 'string' && value.error.trim() !== '') lessons.error = value.error;
114
+ return lessons;
115
+ }
116
+
57
117
  /**
58
118
  * Resolve the record file for one card, validating the id and containment.
59
119
  * @param {string} repo - repository root.
@@ -87,13 +147,45 @@ function normalizeRecord(record) {
87
147
  // Durable child identity: present exactly when a worker activation started.
88
148
  if (typeof record.sessionId === 'string' && record.sessionId !== '') normalized.sessionId = record.sessionId;
89
149
  if (typeof record.agentName === 'string' && record.agentName !== '') normalized.agentName = record.agentName;
150
+ // Announcement overlaps: advisory information from `hive guard --json`, kept
151
+ // on both the running and the terminal write. Omitted when empty.
152
+ const overlaps = normalizeOverlaps(record.overlaps);
153
+ if (overlaps.length > 0) normalized.overlaps = overlaps;
154
+ // Recall summary: fixed keys consumed by the panel (lessons.count/.scopes/.error).
155
+ const lessons = normalizeLessons(record.lessons);
156
+ if (lessons !== null) normalized.lessons = lessons;
157
+ // Liveness telemetry: heartbeat turns to warn when the worker produced no new
158
+ // output for heartbeatWarnMs while still running.
159
+ if (record.heartbeat === 'ok' || record.heartbeat === 'warn') normalized.heartbeat = record.heartbeat;
160
+ if (typeof record.lastOutputAt === 'string' && record.lastOutputAt !== '') normalized.lastOutputAt = record.lastOutputAt;
161
+ // Which Agent was used as the worker's parent (the registered queen Session).
162
+ if (record.parentSource === 'queen') normalized.parentSource = record.parentSource;
90
163
  return normalized;
91
164
  }
92
165
 
166
+ /**
167
+ * Read one card's last-run record. Missing/invalid files return null; this is a
168
+ * read-only companion to {@link writeRunRecord} for the queen's failure triage.
169
+ * @param {string} repo - repository root.
170
+ * @param {string} cardId - Hive card id.
171
+ * @returns {object|null}
172
+ */
173
+ export function readRunRecord(repo, cardId) {
174
+ try {
175
+ const { file } = runRecordPath(repo, cardId);
176
+ const text = fs.readFileSync(file, 'utf8');
177
+ const parsed = JSON.parse(text);
178
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
179
+ return parsed;
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
184
+
93
185
  /**
94
186
  * Write (overwrite) the last-run record for one card. Best effort.
95
187
  * @param {string} repo - repository root.
96
- * @param {object} record - `{ cardId, agent, startedAt, endedAt, status, exitCode?, commit?, sessionId?, agentName?, output }`.
188
+ * @param {object} record - `{ cardId, agent, startedAt, endedAt, status, exitCode?, commit?, sessionId?, agentName?, overlaps?, lessons?, output }`.
97
189
  * @returns {boolean} true when the file was written.
98
190
  */
99
191
  export function writeRunRecord(repo, record) {
package/lib/supervisor.js CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  DEFAULT_ROLE_CONCURRENCY,
29
29
  normalizeRepoKey,
30
30
  } from './config.js';
31
+ import { filterDispatchable, gatePhase } from './gates.js';
31
32
  import { RepoLimits, validateRoleLimits } from './limits.js';
32
33
  import { drainQueue } from './queue.js';
33
34
 
@@ -102,10 +103,16 @@ export class HiveSupervisor {
102
103
  * @param {number} [options.discoverIntervalMs]
103
104
  * @param {() => number} [options.now]
104
105
  * @param {(repo: string, options: object) => Promise<object[]>} [options.listReady]
106
+ * @param {(repo: string, options: object) => Promise<object[]>} [options.listAll] every card, for gate ordering
105
107
  * @param {(request: object) => Promise<object>} [options.runCard]
106
108
  * @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
109
+ * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
110
+ * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
107
111
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
108
112
  * @param {() => Promise<string[]>} [options.discover]
113
+ * @param {(event: object) => void} [options.onAnomaly] supervision event sink (queen digest)
114
+ * @param {(sessionId: string) => void} [options.onQueenSession] called after a queen Session registers
115
+ * @param {() => number} [options.pendingAnomalies] undelivered queen anomalies reported in status
109
116
  * @param {Console} [options.logger]
110
117
  * @param {boolean} [options.debug]
111
118
  */
@@ -129,9 +136,19 @@ export class HiveSupervisor {
129
136
  this.discoverIntervalMs = options.discoverIntervalMs ?? 10 * 60_000;
130
137
  this.now = typeof options.now === 'function' ? options.now : () => Date.now();
131
138
  this.listReady = options.listReady;
139
+ // Every card (any state) is the input to gate ordering; without it the
140
+ // supervisor dispatches everything (legacy behaviour, unit tests).
141
+ this.listAll = typeof options.listAll === 'function' ? options.listAll : undefined;
132
142
  this.runCard = options.runCard;
133
143
  this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
144
+ this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
145
+ // Shared with the round runner: the Session registered by the panel when the
146
+ // queen takes over. Nothing is dispatched until this is set.
147
+ this.queenSession = options.queenSession ?? { sessionId: null };
134
148
  this.readMode = typeof options.readMode === 'function' ? options.readMode : undefined;
149
+ this.onAnomaly = typeof options.onAnomaly === 'function' ? options.onAnomaly : undefined;
150
+ this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
151
+ this.pendingAnomalies = typeof options.pendingAnomalies === 'function' ? options.pendingAnomalies : undefined;
135
152
  this.discover = options.discover;
136
153
  this.logger = options.logger === undefined ? console : options.logger;
137
154
  this.debug = options.debug === true;
@@ -283,6 +300,76 @@ export class HiveSupervisor {
283
300
  return this.#snapshot(entry);
284
301
  }
285
302
 
303
+ /**
304
+ * Register the queen Session that owns every worker. The panel calls this when
305
+ * its init/queen activation succeeds; until then no card is dispatched.
306
+ * @param {string} sessionId live DSH Session id of the queen conversation
307
+ * @returns {object} supervisor status
308
+ */
309
+ setQueenSession(sessionId) {
310
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') {
311
+ throw new TypeError('setQueenSession: sessionId must be a non-empty string');
312
+ }
313
+ this.queenSession.sessionId = sessionId.trim();
314
+ for (const entry of this.repos.values()) {
315
+ entry.waiting = null;
316
+ entry.nextAttemptAt = this.now();
317
+ }
318
+ this.#log('info', 'registered queen session', this.queenSession.sessionId);
319
+ // Let the plugin flush anomalies accumulated while no queen was live.
320
+ if (this.onQueenSession !== undefined) {
321
+ try {
322
+ this.onQueenSession(this.queenSession.sessionId);
323
+ } catch (error) {
324
+ this.#log('warn', 'queen-session hook failed', messageOf(error));
325
+ }
326
+ }
327
+ return this.status();
328
+ }
329
+
330
+ /**
331
+ * Read every card of one repository and compute the gate phase that governs
332
+ * dispatch. Falls back to an explicit phase when the board read fails; a
333
+ * legacy configuration without `listAll` is `ungated` (no gate tags).
334
+ * @param {string} repo
335
+ * @param {AbortSignal} [signal]
336
+ * @returns {Promise<object>}
337
+ */
338
+ async #gateFor(repo, signal) {
339
+ const entry = this.#entry(repo);
340
+ if (this.listAll === undefined) {
341
+ entry.gate = { phase: 'ungated', releaseReady: false, reason: 'gate ordering is not configured' };
342
+ return entry.gate;
343
+ }
344
+ try {
345
+ const tasks = await this.listAll(repo, { signal });
346
+ const gate = gatePhase(tasks);
347
+ entry.gate = gate;
348
+ return gate;
349
+ } catch (error) {
350
+ entry.gate = {
351
+ phase: 'unknown',
352
+ releaseReady: false,
353
+ reason: 'cannot read the full board: ' + messageOf(error),
354
+ };
355
+ this.#log('warn', 'gate phase for ' + repo + ' unavailable: ' + messageOf(error));
356
+ return entry.gate;
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Filter a ready list through the current gate phase. Manual rounds use this
362
+ * so the queen's on-demand run obeys the same gate order as the resident one.
363
+ * @param {string} repo
364
+ * @param {object[]} cards ready cards from `listReady`
365
+ * @param {{ signal?: AbortSignal }} [options]
366
+ * @returns {Promise<{ cards: object[], gate: object }>}
367
+ */
368
+ async filterDispatchable(repo, cards, options = {}) {
369
+ const gate = await this.#gateFor(repo, options.signal);
370
+ return { cards: filterDispatchable(cards, gate.phase), gate };
371
+ }
372
+
286
373
  /** Arm the timer; the first tick runs immediately (asynchronously). */
287
374
  start() {
288
375
  if (this.started) return;
@@ -340,8 +427,15 @@ export class HiveSupervisor {
340
427
 
341
428
  /** Serializable supervisor + per-repository status. */
342
429
  status() {
430
+ const waiting = this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
431
+ ? 'no-queen-session'
432
+ : null;
343
433
  return {
344
434
  started: this.started,
435
+ // The queen Session registered by the panel; every card worker is parented
436
+ // to it. Until it is registered nothing is dispatched.
437
+ queenSessionId: this.queenSession.sessionId ?? null,
438
+ waiting,
345
439
  intervalMs: this.intervalMs,
346
440
  idleBackoffMs: this.idleBackoffMs,
347
441
  maxConcurrentRepos: this.maxConcurrentRepos,
@@ -352,6 +446,8 @@ export class HiveSupervisor {
352
446
  capacityRetryMs: this.capacityRetryMs,
353
447
  lastTickAt: iso(this.lastTickAt),
354
448
  lastDiscoverError: this.lastDiscoverError,
449
+ // Undelivered anomaly digests waiting for a live queen Session.
450
+ pendingAnomalies: this.#pendingAnomalyCount(),
355
451
  repos: [...this.repos.values()]
356
452
  .map((entry) => this.#snapshot(entry))
357
453
  .sort((a, b) => a.repo.localeCompare(b.repo)),
@@ -384,6 +480,15 @@ export class HiveSupervisor {
384
480
  const signal = this.abortController?.signal;
385
481
  try {
386
482
  if (entry.paused) return { repo: entry.repo, state: entry.state };
483
+ // One parent only: the queen Session registered by the panel. Before that
484
+ // registration the supervisor waits; it never picks another Session.
485
+ if (this.queenSession.sessionId === null || this.queenSession.sessionId === undefined) {
486
+ entry.state = STATES.IDLE;
487
+ entry.lastError = null;
488
+ entry.lastCheckAt = this.now();
489
+ entry.nextAttemptAt = this.now() + this.intervalMs;
490
+ return { repo: entry.repo, state: entry.state, waiting: 'no-queen-session' };
491
+ }
387
492
  if (typeof this.listReady !== 'function') throw new Error('supervisor has no listReady implementation');
388
493
  if (typeof this.runCard !== 'function') throw new Error('supervisor has no runCard implementation');
389
494
 
@@ -416,8 +521,13 @@ export class HiveSupervisor {
416
521
  const cards = await this.listReady(entry.repo, { signal });
417
522
  entry.lastCheckAt = this.now();
418
523
  if (entry.paused) return { repo: entry.repo, state: entry.state };
524
+ // Gate ordering: base work first, then gate:group, then gate:overall.
525
+ // A phase that is not all-green blocks the next gate; gate cards left in
526
+ // the ready list are simply not dispatched (they stay on the board).
527
+ const gate = await this.#gateFor(entry.repo, signal);
528
+ const dispatchable = filterDispatchable(cards, gate.phase);
419
529
  const queuedIds = new Set(entry.queue.map((item) => item?.card?.id));
420
- for (const card of Array.isArray(cards) ? cards : []) {
530
+ for (const card of Array.isArray(dispatchable) ? dispatchable : []) {
421
531
  if (typeof card?.id !== 'string' || queuedIds.has(card.id)) continue;
422
532
  if (frozen && !(Array.isArray(card.tags) && card.tags.includes('fix'))) {
423
533
  frozenSkipped += 1;
@@ -490,15 +600,18 @@ export class HiveSupervisor {
490
600
  // failure budget (opening a session later must not be "3 failures").
491
601
  entry.state = entry.paused ? STATES.PAUSED : STATES.BACKOFF;
492
602
  entry.nextAttemptAt = this.now() + this.idleBackoffMs;
603
+ this.#anomaly({ kind: 'environment-error', repo: entry.repo, detail: entry.lastError });
493
604
  this.#log('warn', 'deferred round for ' + entry.repo + ': ' + entry.lastError);
494
605
  } else {
495
606
  entry.consecutiveFailures += 1;
496
607
  entry.lastRoundAt = this.now();
608
+ this.#anomaly({ kind: 'round-failed', repo: entry.repo, detail: entry.lastError });
497
609
  if (entry.consecutiveFailures >= this.maxConsecutiveFailures) {
498
610
  entry.paused = true;
499
611
  entry.pausedBy = 'auto';
500
612
  entry.pausedReason = 'auto-paused after ' + entry.consecutiveFailures + ' consecutive round failures: ' + entry.lastError;
501
613
  entry.state = STATES.PAUSED;
614
+ this.#anomaly({ kind: 'auto-paused', repo: entry.repo, detail: entry.pausedReason });
502
615
  this.#log('warn', entry.pausedReason);
503
616
  } else {
504
617
  entry.state = STATES.BACKOFF;
@@ -556,14 +669,52 @@ export class HiveSupervisor {
556
669
  lastResults: entry.lastResults,
557
670
  backlog: { ...entry.backlog },
558
671
  roles: copyRoles(entry.roles),
672
+ // Live workers currently running in this repository: sessionId/start time
673
+ // let the panel jump to the conversation or diagnose a stuck card.
674
+ workers: this.#workers(entry.repo),
675
+ waiting: this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
676
+ ? 'no-queen-session'
677
+ : null,
559
678
  limitsError: entry.limitsError ?? null,
560
679
  environmentError: entry.environmentError ?? null,
561
680
  mode: entry.mode ?? null,
562
681
  frozenSkipped: entry.frozenSkipped ?? 0,
563
682
  lastSkipReason: entry.lastSkipReason ?? null,
683
+ // Gate pipeline: phase base -> group -> overall -> released, and whether
684
+ // a release/delivery is allowed (an overall gate exists and is all green).
685
+ gate: entry.gate ?? null,
564
686
  };
565
687
  }
566
688
 
689
+ /** Emit one supervision event without letting the sink break scheduling. */
690
+ #anomaly(event) {
691
+ if (this.onAnomaly === undefined) return;
692
+ try {
693
+ this.onAnomaly(event);
694
+ } catch (error) {
695
+ this.#log('warn', 'anomaly sink failed', messageOf(error));
696
+ }
697
+ }
698
+
699
+ /** Undelivered anomaly count for status; observability never throws. */
700
+ #pendingAnomalyCount() {
701
+ try {
702
+ const value = typeof this.pendingAnomalies === 'function' ? this.pendingAnomalies() : 0;
703
+ return Number.isInteger(value) && value >= 0 ? value : 0;
704
+ } catch {
705
+ return 0;
706
+ }
707
+ }
708
+
709
+ /** Best-effort live worker list for status; observability never throws. */
710
+ #workers(repo) {
711
+ try {
712
+ return typeof this.activeRuns === 'function' ? this.activeRuns(repo) : [];
713
+ } catch {
714
+ return [];
715
+ }
716
+ }
717
+
567
718
  #log(level, ...args) {
568
719
  if (this.logger === false || this.logger === null) return;
569
720
  const write = this.logger?.[level];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "0.6.4",
3
+ "version": "0.7.0",
4
4
  "description": "DSH host plugin for Hive: a resident supervisor that runs one DSH subagent per ready task card, with per-role worker limits, pause/resume and Hive tools.",
5
5
  "type": "module",
6
6
  "main": "./index.js",