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/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,26 @@ 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
 
93
166
  /**
94
167
  * Write (overwrite) the last-run record for one card. Best effort.
95
168
  * @param {string} repo - repository root.
96
- * @param {object} record - `{ cardId, agent, startedAt, endedAt, status, exitCode?, commit?, sessionId?, agentName?, output }`.
169
+ * @param {object} record - `{ cardId, agent, startedAt, endedAt, status, exitCode?, commit?, sessionId?, agentName?, overlaps?, lessons?, output }`.
97
170
  * @returns {boolean} true when the file was written.
98
171
  */
99
172
  export function writeRunRecord(repo, record) {
package/lib/supervisor.js CHANGED
@@ -104,6 +104,8 @@ export class HiveSupervisor {
104
104
  * @param {(repo: string, options: object) => Promise<object[]>} [options.listReady]
105
105
  * @param {(request: object) => Promise<object>} [options.runCard]
106
106
  * @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
107
+ * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
108
+ * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
107
109
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
108
110
  * @param {() => Promise<string[]>} [options.discover]
109
111
  * @param {Console} [options.logger]
@@ -131,6 +133,10 @@ export class HiveSupervisor {
131
133
  this.listReady = options.listReady;
132
134
  this.runCard = options.runCard;
133
135
  this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
136
+ this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
137
+ // Shared with the round runner: the Session registered by the panel when the
138
+ // queen takes over. Nothing is dispatched until this is set.
139
+ this.queenSession = options.queenSession ?? { sessionId: null };
134
140
  this.readMode = typeof options.readMode === 'function' ? options.readMode : undefined;
135
141
  this.discover = options.discover;
136
142
  this.logger = options.logger === undefined ? console : options.logger;
@@ -283,6 +289,25 @@ export class HiveSupervisor {
283
289
  return this.#snapshot(entry);
284
290
  }
285
291
 
292
+ /**
293
+ * Register the queen Session that owns every worker. The panel calls this when
294
+ * its init/queen activation succeeds; until then no card is dispatched.
295
+ * @param {string} sessionId live DSH Session id of the queen conversation
296
+ * @returns {object} supervisor status
297
+ */
298
+ setQueenSession(sessionId) {
299
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') {
300
+ throw new TypeError('setQueenSession: sessionId must be a non-empty string');
301
+ }
302
+ this.queenSession.sessionId = sessionId.trim();
303
+ for (const entry of this.repos.values()) {
304
+ entry.waiting = null;
305
+ entry.nextAttemptAt = this.now();
306
+ }
307
+ this.#log('info', 'registered queen session', this.queenSession.sessionId);
308
+ return this.status();
309
+ }
310
+
286
311
  /** Arm the timer; the first tick runs immediately (asynchronously). */
287
312
  start() {
288
313
  if (this.started) return;
@@ -340,8 +365,15 @@ export class HiveSupervisor {
340
365
 
341
366
  /** Serializable supervisor + per-repository status. */
342
367
  status() {
368
+ const waiting = this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
369
+ ? 'no-queen-session'
370
+ : null;
343
371
  return {
344
372
  started: this.started,
373
+ // The queen Session registered by the panel; every card worker is parented
374
+ // to it. Until it is registered nothing is dispatched.
375
+ queenSessionId: this.queenSession.sessionId ?? null,
376
+ waiting,
345
377
  intervalMs: this.intervalMs,
346
378
  idleBackoffMs: this.idleBackoffMs,
347
379
  maxConcurrentRepos: this.maxConcurrentRepos,
@@ -384,6 +416,15 @@ export class HiveSupervisor {
384
416
  const signal = this.abortController?.signal;
385
417
  try {
386
418
  if (entry.paused) return { repo: entry.repo, state: entry.state };
419
+ // One parent only: the queen Session registered by the panel. Before that
420
+ // registration the supervisor waits; it never picks another Session.
421
+ if (this.queenSession.sessionId === null || this.queenSession.sessionId === undefined) {
422
+ entry.state = STATES.IDLE;
423
+ entry.lastError = null;
424
+ entry.lastCheckAt = this.now();
425
+ entry.nextAttemptAt = this.now() + this.intervalMs;
426
+ return { repo: entry.repo, state: entry.state, waiting: 'no-queen-session' };
427
+ }
387
428
  if (typeof this.listReady !== 'function') throw new Error('supervisor has no listReady implementation');
388
429
  if (typeof this.runCard !== 'function') throw new Error('supervisor has no runCard implementation');
389
430
 
@@ -556,6 +597,12 @@ export class HiveSupervisor {
556
597
  lastResults: entry.lastResults,
557
598
  backlog: { ...entry.backlog },
558
599
  roles: copyRoles(entry.roles),
600
+ // Live workers currently running in this repository: sessionId/start time
601
+ // let the panel jump to the conversation or diagnose a stuck card.
602
+ workers: this.#workers(entry.repo),
603
+ waiting: this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
604
+ ? 'no-queen-session'
605
+ : null,
559
606
  limitsError: entry.limitsError ?? null,
560
607
  environmentError: entry.environmentError ?? null,
561
608
  mode: entry.mode ?? null,
@@ -564,6 +611,15 @@ export class HiveSupervisor {
564
611
  };
565
612
  }
566
613
 
614
+ /** Best-effort live worker list for status; observability never throws. */
615
+ #workers(repo) {
616
+ try {
617
+ return typeof this.activeRuns === 'function' ? this.activeRuns(repo) : [];
618
+ } catch {
619
+ return [];
620
+ }
621
+ }
622
+
567
623
  #log(level, ...args) {
568
624
  if (this.logger === false || this.logger === null) return;
569
625
  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.6.7",
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",