dsh-hive-runner 0.6.7 → 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/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,12 +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)
107
109
  * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
108
110
  * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
109
111
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
110
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
111
116
  * @param {Console} [options.logger]
112
117
  * @param {boolean} [options.debug]
113
118
  */
@@ -131,6 +136,9 @@ export class HiveSupervisor {
131
136
  this.discoverIntervalMs = options.discoverIntervalMs ?? 10 * 60_000;
132
137
  this.now = typeof options.now === 'function' ? options.now : () => Date.now();
133
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;
134
142
  this.runCard = options.runCard;
135
143
  this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
136
144
  this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
@@ -138,6 +146,9 @@ export class HiveSupervisor {
138
146
  // queen takes over. Nothing is dispatched until this is set.
139
147
  this.queenSession = options.queenSession ?? { sessionId: null };
140
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;
141
152
  this.discover = options.discover;
142
153
  this.logger = options.logger === undefined ? console : options.logger;
143
154
  this.debug = options.debug === true;
@@ -305,9 +316,60 @@ export class HiveSupervisor {
305
316
  entry.nextAttemptAt = this.now();
306
317
  }
307
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
+ }
308
327
  return this.status();
309
328
  }
310
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
+
311
373
  /** Arm the timer; the first tick runs immediately (asynchronously). */
312
374
  start() {
313
375
  if (this.started) return;
@@ -384,6 +446,8 @@ export class HiveSupervisor {
384
446
  capacityRetryMs: this.capacityRetryMs,
385
447
  lastTickAt: iso(this.lastTickAt),
386
448
  lastDiscoverError: this.lastDiscoverError,
449
+ // Undelivered anomaly digests waiting for a live queen Session.
450
+ pendingAnomalies: this.#pendingAnomalyCount(),
387
451
  repos: [...this.repos.values()]
388
452
  .map((entry) => this.#snapshot(entry))
389
453
  .sort((a, b) => a.repo.localeCompare(b.repo)),
@@ -457,8 +521,13 @@ export class HiveSupervisor {
457
521
  const cards = await this.listReady(entry.repo, { signal });
458
522
  entry.lastCheckAt = this.now();
459
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);
460
529
  const queuedIds = new Set(entry.queue.map((item) => item?.card?.id));
461
- for (const card of Array.isArray(cards) ? cards : []) {
530
+ for (const card of Array.isArray(dispatchable) ? dispatchable : []) {
462
531
  if (typeof card?.id !== 'string' || queuedIds.has(card.id)) continue;
463
532
  if (frozen && !(Array.isArray(card.tags) && card.tags.includes('fix'))) {
464
533
  frozenSkipped += 1;
@@ -531,15 +600,18 @@ export class HiveSupervisor {
531
600
  // failure budget (opening a session later must not be "3 failures").
532
601
  entry.state = entry.paused ? STATES.PAUSED : STATES.BACKOFF;
533
602
  entry.nextAttemptAt = this.now() + this.idleBackoffMs;
603
+ this.#anomaly({ kind: 'environment-error', repo: entry.repo, detail: entry.lastError });
534
604
  this.#log('warn', 'deferred round for ' + entry.repo + ': ' + entry.lastError);
535
605
  } else {
536
606
  entry.consecutiveFailures += 1;
537
607
  entry.lastRoundAt = this.now();
608
+ this.#anomaly({ kind: 'round-failed', repo: entry.repo, detail: entry.lastError });
538
609
  if (entry.consecutiveFailures >= this.maxConsecutiveFailures) {
539
610
  entry.paused = true;
540
611
  entry.pausedBy = 'auto';
541
612
  entry.pausedReason = 'auto-paused after ' + entry.consecutiveFailures + ' consecutive round failures: ' + entry.lastError;
542
613
  entry.state = STATES.PAUSED;
614
+ this.#anomaly({ kind: 'auto-paused', repo: entry.repo, detail: entry.pausedReason });
543
615
  this.#log('warn', entry.pausedReason);
544
616
  } else {
545
617
  entry.state = STATES.BACKOFF;
@@ -608,9 +680,32 @@ export class HiveSupervisor {
608
680
  mode: entry.mode ?? null,
609
681
  frozenSkipped: entry.frozenSkipped ?? 0,
610
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,
611
686
  };
612
687
  }
613
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
+
614
709
  /** Best-effort live worker list for status; observability never throws. */
615
710
  #workers(repo) {
616
711
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "0.6.7",
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",