dsh-hive-runner 1.0.22 → 1.0.26
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 +86 -0
- package/index.js +36 -3
- package/lib/anomalies.js +18 -2
- package/lib/bins.js +74 -0
- package/lib/checkpoint.js +17 -0
- package/lib/commands.js +3 -0
- package/lib/config.js +10 -0
- package/lib/host-env.js +12 -3
- package/lib/http.js +30 -4
- package/lib/patrol.js +90 -3
- package/lib/round.js +80 -27
- package/lib/supervisor.js +148 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,88 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
7
7
|
Version 0.6.0 is the first public snapshot; 0.1.0-0.5.0 were local development
|
|
8
8
|
iterations of the plugin before this repository was published.
|
|
9
9
|
|
|
10
|
+
## [1.0.25] - 2026-12-06
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Rolls up the unpublished 1.0.23 and 1.0.24 fixes: pause aborts workers but keeps
|
|
15
|
+
claimed cards and their announcements (freezing orphan reclamation), resume
|
|
16
|
+
continues claimed cards from the interruption point without re-claiming, a worker
|
|
17
|
+
whose card disappears (deleted/superseded) is aborted immediately, `/queen off`
|
|
18
|
+
unregisters the queen idempotently, and event actors/bin resolution are hardened.
|
|
19
|
+
|
|
20
|
+
### Tests
|
|
21
|
+
|
|
22
|
+
- 304 tests pass.
|
|
23
|
+
|
|
24
|
+
### Published
|
|
25
|
+
|
|
26
|
+
- npm: `dsh-hive-runner@1.0.25` on 2026-12-06.
|
|
27
|
+
|
|
28
|
+
## [1.0.26] - 2026-12-06
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- Supervision digest de-duplication: the stable anomaly-id-set hash is persisted
|
|
33
|
+
with `deliveredAt`; an unchanged set is acknowledged silently (never re-sent),
|
|
34
|
+
so restarting the plugin cannot replay old digests. A changed set is rate-limited
|
|
35
|
+
to one digest per repo per 10 minutes and new items wait for the next window.
|
|
36
|
+
- `arch-review-missing` folds into one digest line with count and at most three
|
|
37
|
+
example cards; the digest stays bounded by the 50-entry pending cap.
|
|
38
|
+
- Delivery remains ack-immediate (`deliveredAt` written after a successful send).
|
|
39
|
+
|
|
40
|
+
### Tests
|
|
41
|
+
|
|
42
|
+
- same-set no repeat and silent ack, changed-set rate limit + later flush, restart
|
|
43
|
+
persistence, arch-review folding with 3 examples, and 50-entry backlog cap;
|
|
44
|
+
309 tests pass.
|
|
45
|
+
|
|
46
|
+
## [1.0.24] - 2026-12-06
|
|
47
|
+
|
|
48
|
+
### Fixed
|
|
49
|
+
|
|
50
|
+
- Pause keeps the claim: aborting a worker interrupts the Session but leaves the
|
|
51
|
+
card claimed and its announcements in place. Resume re-launches claimed cards
|
|
52
|
+
with `claimed:true`/`resumed:true` (no re-claim) and a 'continue from the
|
|
53
|
+
interruption point' prompt. Orphan recovery is frozen while paused.
|
|
54
|
+
- Every tick reconciles live workers against the board: a worker whose card was
|
|
55
|
+
deleted or superseded is aborted immediately with a `worker-aborted` event
|
|
56
|
+
(reason task missing/superseded). `hive_intervene remove`/`supersede` and
|
|
57
|
+
`hive_tasks rm`/`supersede` abort and wait for a live worker first.
|
|
58
|
+
- `/queen off` host capability: `clearQueenSession(repo, sessionId)`/`queenOff(repo)`
|
|
59
|
+
idempotently unregisters the queen, marks the repository unmanaged and stops
|
|
60
|
+
delivering checkpoints/anomalies to that Session; re-registration works. Exposed
|
|
61
|
+
as HTTP `op=queen-off` and `hive_supervisor_control action=queen-off`.
|
|
62
|
+
|
|
63
|
+
### Tests
|
|
64
|
+
|
|
65
|
+
- pause keeps claimed / no orphan recovery / resume continues without re-claim,
|
|
66
|
+
worker reconciliation for deleted and superseded cards, queen-off/status/re-register
|
|
67
|
+
HTTP, and existing suite; 304 tests pass.
|
|
68
|
+
|
|
69
|
+
## [1.0.23] - 2026-12-06
|
|
70
|
+
|
|
71
|
+
### Fixed
|
|
72
|
+
|
|
73
|
+
- Pause is now a real stop: `supervisor.pause()` aborts every live worker in the
|
|
74
|
+
repository via `runner.pauseWorkers()`, records `worker_aborted`, releases the
|
|
75
|
+
claim and leaves the card `pending`; `resume()` does not auto-run it. Panel
|
|
76
|
+
`action=pause`/`repoPath` (and freeze aliases) reach the supervisor route.
|
|
77
|
+
- No checkpoint or anomaly digest is delivered for a manually paused repository;
|
|
78
|
+
entries stay pending until resume. Auto-paused anomalies still flow.
|
|
79
|
+
- Worker event attribution is decoupled from the claim owner: worker CLI calls carry
|
|
80
|
+
`HIVE_EVENT_ACTOR=worker:<role>` while `HIVE_AGENT`/claim owner stays the runner
|
|
81
|
+
identity (claim, guard, commit_announce and release events show the role).
|
|
82
|
+
- Hive binaries are probed once at startup, cached and exposed in status `bins` with
|
|
83
|
+
their source (`config`/`env`/`probe`/`fallback`); only a genuinely missing binary
|
|
84
|
+
reaches the npx fallback.
|
|
85
|
+
|
|
86
|
+
### Tests
|
|
87
|
+
|
|
88
|
+
- panel pause route, pause abort/pending card, paused delivery suppression,
|
|
89
|
+
worker claim/guard/release event actors with runner owner, host env restore,
|
|
90
|
+
binary probing/status, and existing suite; 299 tests pass.
|
|
91
|
+
|
|
10
92
|
## [1.0.22] - 2026-12-05
|
|
11
93
|
|
|
12
94
|
### Fixed
|
|
@@ -25,6 +107,10 @@ iterations of the plugin before this repository was published.
|
|
|
25
107
|
- worker=5 running + coder=6 ready during the same in-flight batch: all six coder
|
|
26
108
|
cards start in parallel and status reports `roles.coder.live = 6`; 289 tests pass.
|
|
27
109
|
|
|
110
|
+
### Published
|
|
111
|
+
|
|
112
|
+
- npm: `dsh-hive-runner@1.0.22` on 2026-12-05.
|
|
113
|
+
|
|
28
114
|
## [1.0.21] - 2026-12-05
|
|
29
115
|
|
|
30
116
|
### Fixed
|
package/index.js
CHANGED
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
* the sandbox, the session sandbox policy, credential scrubbing, output caps and
|
|
20
20
|
* cancellation. Card workers are DSH subagents (`ctx.subagents`), not processes.
|
|
21
21
|
*/
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import os from 'node:os';
|
|
24
|
+
import path from 'node:path';
|
|
25
|
+
|
|
22
26
|
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
23
27
|
|
|
24
28
|
import { createCommands } from './lib/commands.js';
|
|
@@ -41,6 +45,7 @@ import { createArchReviewAudit } from './lib/audit.js';
|
|
|
41
45
|
import { createHiveRunnerRoute } from './lib/http.js';
|
|
42
46
|
import { RepoLimits } from './lib/limits.js';
|
|
43
47
|
import { createAnomalyFeed } from './lib/anomalies.js';
|
|
48
|
+
import { resolveBins } from './lib/bins.js';
|
|
44
49
|
import { createCheckpointController } from './lib/checkpoint.js';
|
|
45
50
|
import { createQueenNotifier, deliverToSession, resolveAgent } from './lib/notify.js';
|
|
46
51
|
import { createPatrol } from './lib/patrol.js';
|
|
@@ -99,6 +104,9 @@ function jsonText(value) {
|
|
|
99
104
|
*/
|
|
100
105
|
export function apply(ctx, config = {}) {
|
|
101
106
|
const resolved = resolveConfig(config);
|
|
107
|
+
// Probe PATH once at startup and cache the absolute paths; per-command PATH
|
|
108
|
+
// lookups/npx fallbacks happen only when the binary is actually missing.
|
|
109
|
+
const binStatus = resolveBins(resolved);
|
|
102
110
|
const commands = createCommands({ ctx, config: resolved });
|
|
103
111
|
const limits = new RepoLimits({
|
|
104
112
|
roleConcurrency: resolved.roleConcurrency,
|
|
@@ -337,8 +345,13 @@ export function apply(ctx, config = {}) {
|
|
|
337
345
|
},
|
|
338
346
|
queenBoundary,
|
|
339
347
|
queenTools: () => queenTools,
|
|
348
|
+
bins: () => binStatus,
|
|
340
349
|
crossRepoBlocked: () => crossRepoBlocked,
|
|
341
350
|
archReview: (repo, review) => recordArchReviewHost(repo, review),
|
|
351
|
+
pauseWorkers: (repo, reason) => runner.pauseWorkers(repo, reason),
|
|
352
|
+
abortWorker: (repo, cardId, reason) => runner.abortCard(repo, cardId, reason),
|
|
353
|
+
claimAgent: resolved.agent,
|
|
354
|
+
listClaimed: (repo, options) => commands.list(repo, { state: 'claimed' }, options),
|
|
342
355
|
readMode: (repo) => commands.mode(repo),
|
|
343
356
|
onAnomaly: (event) => recordAnomaly(event),
|
|
344
357
|
onGateChange: (event) => {
|
|
@@ -363,6 +376,10 @@ export function apply(ctx, config = {}) {
|
|
|
363
376
|
notifier: resolved.notifyQueen ? notifier : undefined,
|
|
364
377
|
intervalMs: resolved.patrolIntervalMs,
|
|
365
378
|
debounceMs: resolved.anomalyDebounceMs,
|
|
379
|
+
// Persist delivered digest signatures so a restart does not re-send the
|
|
380
|
+
// same supervision digest; the file is host-level, not repository data.
|
|
381
|
+
statePath: path.join(os.homedir(), '.dsh', 'hive-runner', 'supervision-state.json'),
|
|
382
|
+
digestRateLimitMs: 10 * 60_000,
|
|
366
383
|
// Every patrol also audits done cards for a missing architecture review.
|
|
367
384
|
inspect: async () => {
|
|
368
385
|
let repos = [];
|
|
@@ -705,6 +722,9 @@ export function apply(ctx, config = {}) {
|
|
|
705
722
|
if (typeof args.reason !== 'string' || args.reason.trim() === '') {
|
|
706
723
|
throw new Error('hive_tasks supersede needs a reason (the CLI requires it)');
|
|
707
724
|
}
|
|
725
|
+
if (runner.activeRuns(repo).some((run) => run.cardId === args.id)) {
|
|
726
|
+
await runner.abortCardAndWait(repo, args.id, 'task superseded by queen');
|
|
727
|
+
}
|
|
708
728
|
return jsonText({
|
|
709
729
|
ok: true,
|
|
710
730
|
card: await commands.supersede(repo, args.id, { reason: args.reason, replacedBy: args.replacedBy }, options),
|
|
@@ -720,6 +740,9 @@ export function apply(ctx, config = {}) {
|
|
|
720
740
|
}
|
|
721
741
|
if (action === 'rm') {
|
|
722
742
|
if (typeof args.id !== 'string') throw new Error('hive_tasks rm needs an id');
|
|
743
|
+
if (runner.activeRuns(repo).some((run) => run.cardId === args.id)) {
|
|
744
|
+
await runner.abortCardAndWait(repo, args.id, 'task removed by queen');
|
|
745
|
+
}
|
|
723
746
|
return jsonText({ ok: true, deleted: args.id, output: await commands.remove(repo, args.id, options) });
|
|
724
747
|
}
|
|
725
748
|
throw new Error('hive_tasks action must be one of list, show, add, edit, split, supersede, reopen, retry, rm');
|
|
@@ -1002,12 +1025,13 @@ export function apply(ctx, config = {}) {
|
|
|
1002
1025
|
registerTextTool({
|
|
1003
1026
|
name: 'hive_supervisor_control',
|
|
1004
1027
|
description:
|
|
1005
|
-
'Control the resident Hive supervisor in one repository: action=status|pause|resume|limits. '
|
|
1028
|
+
'Control the resident Hive supervisor in one repository: action=status|pause|resume|queen-off|limits. '
|
|
1029
|
+
+ 'queen-off idempotently clears the registered queen Session; the repository becomes unmanaged and stops delivering checkpoints/anomalies until it is registered again. '
|
|
1006
1030
|
+ 'pause/resume throttle dispatch for that repository; limits sets persisted per-role worker caps '
|
|
1007
1031
|
+ '({ role: n }, 0 pauses the role) in <repo>/.hive/limits.json. The queen uses these instead of editing the board.',
|
|
1008
1032
|
parameters: {
|
|
1009
1033
|
repo: repoParameter,
|
|
1010
|
-
action: { type: 'string', enum: ['status', 'pause', 'resume', 'limits'], description: 'status | pause | resume | limits.' },
|
|
1034
|
+
action: { type: 'string', enum: ['status', 'pause', 'resume', 'queen-off', 'limits'], description: 'status | pause | resume | queen-off | limits.' },
|
|
1011
1035
|
reason: { type: 'string', description: 'pause: why dispatch is throttled.' },
|
|
1012
1036
|
roleLimits: {
|
|
1013
1037
|
type: 'object',
|
|
@@ -1025,6 +1049,7 @@ export function apply(ctx, config = {}) {
|
|
|
1025
1049
|
if (!supervisor.hasRepo(key)) throw new Error('unknown repository ' + JSON.stringify(key));
|
|
1026
1050
|
if (action === 'pause') return jsonText({ ok: true, repo: supervisor.pause(key, args.reason ?? 'paused by the queen') });
|
|
1027
1051
|
if (action === 'resume') return jsonText({ ok: true, repo: supervisor.resume(key) });
|
|
1052
|
+
if (action === 'queen-off') return jsonText({ ok: true, ...supervisor.queenOff(key) });
|
|
1028
1053
|
if (action === 'limits') {
|
|
1029
1054
|
const roleLimits = args.roleLimits;
|
|
1030
1055
|
if (roleLimits === null || typeof roleLimits !== 'object' || Array.isArray(roleLimits)) {
|
|
@@ -1032,7 +1057,7 @@ export function apply(ctx, config = {}) {
|
|
|
1032
1057
|
}
|
|
1033
1058
|
return jsonText({ ok: true, repo: supervisor.setRoleLimits(key, roleLimits) });
|
|
1034
1059
|
}
|
|
1035
|
-
throw new Error('hive_supervisor_control action must be status, pause, resume or limits');
|
|
1060
|
+
throw new Error('hive_supervisor_control action must be status, pause, resume, queen-off or limits');
|
|
1036
1061
|
},
|
|
1037
1062
|
});
|
|
1038
1063
|
|
|
@@ -1128,6 +1153,11 @@ export function apply(ctx, config = {}) {
|
|
|
1128
1153
|
}
|
|
1129
1154
|
} else if (action === 'remove') {
|
|
1130
1155
|
removed = { title: card.title, state: card.state, scope: card.scope };
|
|
1156
|
+
// A claimed/live card must be aborted (and its worker gone) before the
|
|
1157
|
+
// delete, so no ownerless worker survives the removal.
|
|
1158
|
+
if (runner.activeRuns(repo).some((run) => run.cardId === cardId)) {
|
|
1159
|
+
await runner.abortCardAndWait(repo, cardId, args.reason ?? 'task removed by queen');
|
|
1160
|
+
}
|
|
1131
1161
|
await commands.remove(repo, cardId, options);
|
|
1132
1162
|
} else if (action === 'pause') {
|
|
1133
1163
|
const key = normalizeRepoKey(repo);
|
|
@@ -1139,6 +1169,9 @@ export function apply(ctx, config = {}) {
|
|
|
1139
1169
|
throw new Error('no live worker for card ' + cardId + ' (it may already have finished; use reopen/supersede)');
|
|
1140
1170
|
}
|
|
1141
1171
|
} else if (action === 'supersede') {
|
|
1172
|
+
if (runner.activeRuns(repo).some((run) => run.cardId === cardId)) {
|
|
1173
|
+
await runner.abortCardAndWait(repo, cardId, 'task superseded by queen');
|
|
1174
|
+
}
|
|
1142
1175
|
await commands.supersede(repo, cardId, { reason: args.reason }, options);
|
|
1143
1176
|
} else if (action === 'fail') {
|
|
1144
1177
|
if (card.state !== 'failed') {
|
package/lib/anomalies.js
CHANGED
|
@@ -204,13 +204,29 @@ export function renderDigest(items, options = {}) {
|
|
|
204
204
|
const repos = [...new Set(list.map((entry) => entry.repo).filter((repo) => typeof repo === 'string' && repo !== ''))];
|
|
205
205
|
if (repos.length === 1) lines.push('repo: ' + repos[0]);
|
|
206
206
|
else if (repos.length > 1) lines.push('repos: ' + repos.join(', '));
|
|
207
|
-
|
|
207
|
+
// Fold identical review-missing items into one line with at most three
|
|
208
|
+
// examples: the queen needs the count and a sample, not one row per card.
|
|
209
|
+
const archMissing = list.filter((entry) => entry.kind === 'arch-review-missing');
|
|
210
|
+
const others = list.filter((entry) => entry.kind !== 'arch-review-missing');
|
|
211
|
+
let shown = 0;
|
|
212
|
+
if (archMissing.length > 0) {
|
|
213
|
+
const cards = [...new Set(archMissing.map((entry) => entry.cardId).filter((cardId) => typeof cardId === 'string' && cardId !== ''))];
|
|
214
|
+
const occurrences = archMissing.reduce((count, entry) => count + (Number.isInteger(entry.count) ? entry.count : 1), 0);
|
|
215
|
+
const examples = cards.slice(0, 3).join(', ');
|
|
216
|
+
lines.push('- arch-review-missing ×' + String(occurrences) + ': ' + String(cards.length)
|
|
217
|
+
+ ' done task(s) without arch_review' + (examples !== '' ? ' (e.g. ' + examples + ')' : ''));
|
|
218
|
+
shown += 1;
|
|
219
|
+
}
|
|
220
|
+
for (const entry of others.slice(-Math.max(0, max - shown))) {
|
|
208
221
|
const tag = labelOf(entry);
|
|
209
222
|
const count = Number.isInteger(entry.count) && entry.count > 1 ? ' ×' + String(entry.count) : '';
|
|
210
223
|
const detail = typeof entry.detail === 'string' && entry.detail !== '' ? ': ' + entry.detail : '';
|
|
211
224
|
lines.push('- ' + tag + count + detail);
|
|
225
|
+
shown += 1;
|
|
226
|
+
}
|
|
227
|
+
if (others.length + archMissing.length > shown) {
|
|
228
|
+
lines.push('- … and ' + String(others.length + archMissing.length - shown) + ' more (hive_anomalies lists all)');
|
|
212
229
|
}
|
|
213
|
-
if (list.length > max) lines.push('- … and ' + String(list.length - max) + ' more (hive_anomalies lists all)');
|
|
214
230
|
lines.push('');
|
|
215
231
|
lines.push('Next: read the board and supervisor status, then decide — reopen/retry/split/remove a card, '
|
|
216
232
|
+ 'pause or resume the repository, adjust role limits, add a fix card, or ask the human. '
|
package/lib/bins.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Resolve the hive-tasks/hive/git commands to absolute paths once at plugin
|
|
6
|
+
* startup. A configured absolute path is used as-is; a configured/derived name
|
|
7
|
+
* is searched on PATH once and cached. Per-command `which` plus the first failed
|
|
8
|
+
* spawn are thus avoided; npx remains only the last-resort fallback.
|
|
9
|
+
*
|
|
10
|
+
* @param {string} command configured value (path or name)
|
|
11
|
+
* @param {{ env?: NodeJS.ProcessEnv, accessSync?: Function, constants?: object }} [options]
|
|
12
|
+
* @returns {{ configured: string, path: string, source: "config"|"env"|"probe"|"fallback", found: boolean }}
|
|
13
|
+
*/
|
|
14
|
+
export function probeBin(command, options = {}) {
|
|
15
|
+
const env = options.env ?? process.env;
|
|
16
|
+
const accessSync = options.accessSync ?? fs.accessSync;
|
|
17
|
+
const constants = options.constants ?? fs.constants;
|
|
18
|
+
const configured = typeof command === "string" && command.trim() !== "" ? command.trim() : "hive";
|
|
19
|
+
const executable = (candidate) => {
|
|
20
|
+
try {
|
|
21
|
+
accessSync(candidate, constants.X_OK);
|
|
22
|
+
return true;
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
if (configured.includes("/") || configured.includes("\\")) {
|
|
28
|
+
const absolute = path.isAbsolute(configured) ? configured : path.resolve(configured);
|
|
29
|
+
return { configured, path: absolute, source: "config", found: executable(absolute) };
|
|
30
|
+
}
|
|
31
|
+
const dirs = String(env.PATH ?? "").split(path.delimiter).filter(Boolean);
|
|
32
|
+
for (const dir of dirs) {
|
|
33
|
+
const candidate = path.join(dir, configured);
|
|
34
|
+
if (executable(candidate)) return { configured, path: candidate, source: "probe", found: true };
|
|
35
|
+
}
|
|
36
|
+
return { configured, path: configured, source: "fallback", found: false };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Resolve every configured binary once and mutate the resolved config to the
|
|
41
|
+
* actual absolute path when one was found. The returned map is the status view.
|
|
42
|
+
* @param {object} config resolved config (mutated)
|
|
43
|
+
* @param {{ env?: NodeJS.ProcessEnv, probe?: Function }} [options]
|
|
44
|
+
*/
|
|
45
|
+
export function resolveBins(config, options = {}) {
|
|
46
|
+
const probe = options.probe ?? probeBin;
|
|
47
|
+
const env = options.env ?? process.env;
|
|
48
|
+
const baseSources = config.binSources ?? {};
|
|
49
|
+
const keys = [
|
|
50
|
+
["tasksBin", "tasks"],
|
|
51
|
+
["hiveBin", "hive"],
|
|
52
|
+
["rolesBin", "roles"],
|
|
53
|
+
["gitBin", "git"],
|
|
54
|
+
];
|
|
55
|
+
const bins = {};
|
|
56
|
+
for (const [configKey, statusKey] of keys) {
|
|
57
|
+
const configured = config[configKey];
|
|
58
|
+
const probed = probe(configured, { env });
|
|
59
|
+
const baseSource = baseSources[configKey] ?? "default";
|
|
60
|
+
let source;
|
|
61
|
+
if (baseSource === "config" || baseSource === "env") source = baseSource;
|
|
62
|
+
else source = probed.found ? "probe" : "fallback";
|
|
63
|
+
if (probed.found && (source === "probe" || source === "config" || source === "env")) {
|
|
64
|
+
config[configKey] = probed.path;
|
|
65
|
+
}
|
|
66
|
+
bins[statusKey] = {
|
|
67
|
+
configured: probed.configured,
|
|
68
|
+
path: config[configKey],
|
|
69
|
+
source,
|
|
70
|
+
found: probed.found,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
return bins;
|
|
74
|
+
}
|
package/lib/checkpoint.js
CHANGED
|
@@ -247,6 +247,13 @@ export function createCheckpointController({
|
|
|
247
247
|
const phase = typeof gate?.phase === 'string' ? gate.phase : null;
|
|
248
248
|
const releaseReady = gate?.releaseReady === true;
|
|
249
249
|
const state = stateFor(repo);
|
|
250
|
+
// A paused repository must not emit checkpoints (and pending ones wait for
|
|
251
|
+
// resume). Keep trigger state frozen rather than accumulating idle timers.
|
|
252
|
+
if (repoStatus.paused === true && repoStatus.pausedBy === 'manual') {
|
|
253
|
+
state.noReadySince = null;
|
|
254
|
+
state.drainedSince = null;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
250
257
|
|
|
251
258
|
// "No ready work while goals remain" needs the ready count; a loader may
|
|
252
259
|
// not provide it (legacy/test), in which case this trigger is skipped.
|
|
@@ -331,7 +338,17 @@ export function createCheckpointController({
|
|
|
331
338
|
|
|
332
339
|
function flushPending() {
|
|
333
340
|
let delivered = 0;
|
|
341
|
+
let paused = new Set();
|
|
342
|
+
try {
|
|
343
|
+
const status = typeof supervisor?.status === 'function' ? supervisor.status() : null;
|
|
344
|
+
if (Array.isArray(status?.repos)) {
|
|
345
|
+
paused = new Set(status.repos.filter((repo) => repo?.paused === true && repo?.pausedBy === 'manual').map((repo) => repo.repo));
|
|
346
|
+
}
|
|
347
|
+
} catch {
|
|
348
|
+
paused = new Set();
|
|
349
|
+
}
|
|
334
350
|
for (const entry of [...pending]) {
|
|
351
|
+
if (paused.has(entry.repo)) continue;
|
|
335
352
|
if (typeof queenForRepo === 'function') {
|
|
336
353
|
const target = queenForRepo(entry.repo);
|
|
337
354
|
if (typeof target !== 'string' || target === '') continue;
|
package/lib/commands.js
CHANGED
|
@@ -547,6 +547,9 @@ export function createCommands({ ctx, config }) {
|
|
|
547
547
|
// concurrent workers of one runner are distinct announcers on the consensus
|
|
548
548
|
// board instead of looking like the same instance.
|
|
549
549
|
const env = { HIVE_AGENT: options.agent ?? config.agent };
|
|
550
|
+
if (typeof options.eventActor === 'string' && options.eventActor.trim() !== '') {
|
|
551
|
+
env.HIVE_EVENT_ACTOR = options.eventActor.trim();
|
|
552
|
+
}
|
|
550
553
|
const instance = typeof options.instance === 'string' ? options.instance.trim() : '';
|
|
551
554
|
if (instance !== '') env.HIVE_INSTANCE = instance;
|
|
552
555
|
const shellOptions = {
|
package/lib/config.js
CHANGED
|
@@ -318,6 +318,16 @@ export function resolveConfig(config = {}) {
|
|
|
318
318
|
cfg.anomalyDebounceMs = positiveNumber(cfg.anomalyDebounceMs, 'anomalyDebounceMs');
|
|
319
319
|
cfg.anomalyMax = positiveInteger(cfg.anomalyMax, 'anomalyMax', 1000);
|
|
320
320
|
cfg.archReviewGraceMs = positiveNumber(cfg.archReviewGraceMs, 'archReviewGraceMs');
|
|
321
|
+
/** Where each bin value came from, before startup PATH probing. */
|
|
322
|
+
const binSource = (value, envName) => (value !== undefined && value !== null && value !== ''
|
|
323
|
+
? 'config'
|
|
324
|
+
: (typeof process.env[envName] === 'string' && process.env[envName].trim() !== '' ? 'env' : 'default'));
|
|
325
|
+
cfg.binSources = {
|
|
326
|
+
tasksBin: binSource(config.tasksBin, 'HIVE_TASKS_BIN'),
|
|
327
|
+
hiveBin: binSource(config.hiveBin, 'HIVE_BIN'),
|
|
328
|
+
rolesBin: binSource(config.rolesBin, 'HIVE_ROLES_BIN'),
|
|
329
|
+
gitBin: binSource(config.gitBin, 'HIVE_GIT_BIN'),
|
|
330
|
+
};
|
|
321
331
|
cfg.tasksBin = bin(cfg.tasksBin, 'tasksBin', 'HIVE_TASKS_BIN', 'hive-tasks');
|
|
322
332
|
cfg.hiveBin = bin(cfg.hiveBin, 'hiveBin', 'HIVE_BIN', 'hive');
|
|
323
333
|
cfg.rolesBin = bin(cfg.rolesBin, 'rolesBin', 'HIVE_ROLES_BIN', cfg.hiveBin);
|
package/lib/host-env.js
CHANGED
|
@@ -24,12 +24,14 @@ const holders = [];
|
|
|
24
24
|
let saved;
|
|
25
25
|
|
|
26
26
|
function remember() {
|
|
27
|
-
return { agent: process.env.HIVE_AGENT, instance: process.env.HIVE_INSTANCE };
|
|
27
|
+
return { agent: process.env.HIVE_AGENT, instance: process.env.HIVE_INSTANCE, eventActor: process.env.HIVE_EVENT_ACTOR };
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
function apply(holder) {
|
|
31
31
|
process.env.HIVE_AGENT = holder.agent;
|
|
32
32
|
process.env.HIVE_INSTANCE = holder.instance;
|
|
33
|
+
if (holder.eventActor === undefined) delete process.env.HIVE_EVENT_ACTOR;
|
|
34
|
+
else process.env.HIVE_EVENT_ACTOR = holder.eventActor;
|
|
33
35
|
}
|
|
34
36
|
|
|
35
37
|
function restore(values) {
|
|
@@ -38,6 +40,8 @@ function restore(values) {
|
|
|
38
40
|
else process.env.HIVE_AGENT = values.agent;
|
|
39
41
|
if (values.instance === undefined) delete process.env.HIVE_INSTANCE;
|
|
40
42
|
else process.env.HIVE_INSTANCE = values.instance;
|
|
43
|
+
if (values.eventActor === undefined) delete process.env.HIVE_EVENT_ACTOR;
|
|
44
|
+
else process.env.HIVE_EVENT_ACTOR = values.eventActor;
|
|
41
45
|
}
|
|
42
46
|
|
|
43
47
|
/**
|
|
@@ -46,12 +50,17 @@ function restore(values) {
|
|
|
46
50
|
* @param {string} [instance] per-card instance (the card id); defaults to the agent
|
|
47
51
|
* @returns {() => void} idempotent release
|
|
48
52
|
*/
|
|
49
|
-
export function acquireHiveAgentEnv(agent, instance) {
|
|
53
|
+
export function acquireHiveAgentEnv(agent, instance, eventActor) {
|
|
50
54
|
if (typeof agent !== 'string' || agent.trim() === '') return () => {};
|
|
51
55
|
const agentName = agent.trim();
|
|
52
56
|
const instanceName = typeof instance === 'string' && instance.trim() !== '' ? instance.trim() : agentName;
|
|
53
57
|
if (holders.length === 0) saved = remember();
|
|
54
|
-
const holder = {
|
|
58
|
+
const holder = {
|
|
59
|
+
agent: agentName,
|
|
60
|
+
instance: instanceName,
|
|
61
|
+
eventActor: typeof eventActor === 'string' && eventActor.trim() !== '' ? eventActor.trim() : undefined,
|
|
62
|
+
released: false,
|
|
63
|
+
};
|
|
55
64
|
holders.push(holder);
|
|
56
65
|
apply(holder);
|
|
57
66
|
return () => {
|
package/lib/http.js
CHANGED
|
@@ -49,8 +49,14 @@ async function readPayload(request) {
|
|
|
49
49
|
export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
50
50
|
const url = new URL(request.url);
|
|
51
51
|
const payload = await readPayload(request);
|
|
52
|
-
const op = url.searchParams.get('op')
|
|
53
|
-
|
|
52
|
+
const op = url.searchParams.get('op')
|
|
53
|
+
?? (typeof payload.op === 'string' ? payload.op : null)
|
|
54
|
+
?? (typeof payload.action === 'string' ? payload.action : null);
|
|
55
|
+
const repo = typeof payload.repo === 'string'
|
|
56
|
+
? payload.repo
|
|
57
|
+
: (typeof payload.repoPath === 'string'
|
|
58
|
+
? payload.repoPath
|
|
59
|
+
: (typeof payload.cwd === 'string' ? payload.cwd : url.searchParams.get('repo')));
|
|
54
60
|
|
|
55
61
|
if (op === 'status') {
|
|
56
62
|
return json({ ok: true, op: 'status', ...supervisor.status() });
|
|
@@ -84,7 +90,8 @@ export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
|
84
90
|
}
|
|
85
91
|
return json({ ok: true, op: 'ack', changed });
|
|
86
92
|
}
|
|
87
|
-
if (op === 'pause' || op === 'resume') {
|
|
93
|
+
if (op === 'pause' || op === 'resume' || op === 'freeze' || op === 'unfreeze') {
|
|
94
|
+
const pause = op === 'pause' || op === 'freeze';
|
|
88
95
|
if (typeof repo !== 'string' || repo.trim() === '') {
|
|
89
96
|
return failure(op, 'hive/missing-repo', 'repo is required (query parameter or JSON body field)', 400);
|
|
90
97
|
}
|
|
@@ -98,7 +105,7 @@ export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
|
98
105
|
return failure(op, 'hive/unknown-repo', 'unknown repository ' + JSON.stringify(key), 404);
|
|
99
106
|
}
|
|
100
107
|
try {
|
|
101
|
-
const snapshot =
|
|
108
|
+
const snapshot = pause ? supervisor.pause(key, payload.reason) : supervisor.resume(key);
|
|
102
109
|
return json({ ok: true, op, repo: snapshot });
|
|
103
110
|
} catch (error) {
|
|
104
111
|
if (error instanceof UnknownRepoError) {
|
|
@@ -107,6 +114,25 @@ export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
|
107
114
|
return failure(op, 'hive/internal', error instanceof Error ? error.message : String(error), 500);
|
|
108
115
|
}
|
|
109
116
|
}
|
|
117
|
+
if (op === 'queen-off' || op === 'queenOff' || op === 'queen_off') {
|
|
118
|
+
if (request.method !== 'POST') {
|
|
119
|
+
return failure(op, 'hive/method-not-allowed', 'op=queen-off requires POST', 405);
|
|
120
|
+
}
|
|
121
|
+
if (typeof repo !== 'string' || repo.trim() === '') {
|
|
122
|
+
return failure(op, 'hive/missing-repo', 'repo is required (JSON body field)', 400);
|
|
123
|
+
}
|
|
124
|
+
let key;
|
|
125
|
+
try {
|
|
126
|
+
key = normalizeRepoKey(repo);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
return failure(op, 'hive/invalid-repo', error instanceof Error ? error.message : String(error), 400);
|
|
129
|
+
}
|
|
130
|
+
if (!supervisor.hasRepo(key)) {
|
|
131
|
+
return failure(op, 'hive/unknown-repo', 'unknown repository ' + JSON.stringify(key), 404);
|
|
132
|
+
}
|
|
133
|
+
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : null;
|
|
134
|
+
return json({ ok: true, op: 'queen-off', ...supervisor.queenOff(key, sessionId) });
|
|
135
|
+
}
|
|
110
136
|
if (op === 'queen') {
|
|
111
137
|
if (request.method !== 'POST') {
|
|
112
138
|
return failure(op, 'hive/method-not-allowed', 'op=queen requires POST', 405);
|
package/lib/patrol.js
CHANGED
|
@@ -12,6 +12,9 @@
|
|
|
12
12
|
*
|
|
13
13
|
* @module dsh-hive-runner/patrol
|
|
14
14
|
*/
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
|
|
15
18
|
import { renderDigest } from './anomalies.js';
|
|
16
19
|
|
|
17
20
|
/**
|
|
@@ -47,6 +50,48 @@ export function createPatrol(options = {}) {
|
|
|
47
50
|
const setIntervalFn = typeof options.setIntervalFn === 'function' ? options.setIntervalFn : setInterval;
|
|
48
51
|
const clearIntervalFn = typeof options.clearIntervalFn === 'function' ? options.clearIntervalFn : clearInterval;
|
|
49
52
|
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
53
|
+
// A signature is the stable anomaly-id set: kind/repo/card/scope, not the
|
|
54
|
+
// volatile feed ids. Persisting it is what stops a restart from re-delivering
|
|
55
|
+
// the same digest.
|
|
56
|
+
const statePath = typeof options.statePath === 'string' && options.statePath !== '' ? options.statePath : null;
|
|
57
|
+
const rateLimitMs = Number.isFinite(options.digestRateLimitMs) && options.digestRateLimitMs >= 0
|
|
58
|
+
? options.digestRateLimitMs
|
|
59
|
+
: 10 * 60_000;
|
|
60
|
+
let deliveryState = loadState();
|
|
61
|
+
|
|
62
|
+
function loadState() {
|
|
63
|
+
if (statePath === null) return { repos: {} };
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
|
66
|
+
return parsed !== null && typeof parsed === 'object' && parsed.repos !== null && typeof parsed.repos === 'object'
|
|
67
|
+
? { repos: parsed.repos }
|
|
68
|
+
: { repos: {} };
|
|
69
|
+
} catch {
|
|
70
|
+
return { repos: {} };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function saveState() {
|
|
75
|
+
if (statePath === null) return;
|
|
76
|
+
try {
|
|
77
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true });
|
|
78
|
+
fs.writeFileSync(statePath, JSON.stringify({ ...deliveryState, updatedAt: new Date(now()).toISOString() }, null, 2) + '\n');
|
|
79
|
+
} catch (error) {
|
|
80
|
+
log('warn', 'saving patrol delivery state failed', error);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Stable hash of the anomaly id set (independent of feed ids/counts). */
|
|
85
|
+
function signatureOf(entries) {
|
|
86
|
+
const keys = entries.map((entry) => [entry.kind, entry.repo, entry.cardId, entry.summary, entry.detail]
|
|
87
|
+
.map((value) => String(value ?? '')).join('\u0000')).sort();
|
|
88
|
+
let hash = 2166136261;
|
|
89
|
+
for (const key of keys.join('\n')) {
|
|
90
|
+
hash ^= key.codePointAt(0);
|
|
91
|
+
hash = Math.imul(hash, 16777619);
|
|
92
|
+
}
|
|
93
|
+
return (hash >>> 0).toString(16) + ':' + String(keys.length);
|
|
94
|
+
}
|
|
50
95
|
|
|
51
96
|
let patrolTimer = null;
|
|
52
97
|
let flushTimer = null;
|
|
@@ -79,17 +124,53 @@ export function createPatrol(options = {}) {
|
|
|
79
124
|
// Hard repo isolation: group by repository and deliver each digest only to
|
|
80
125
|
// that repo's queen. Entries without a repository stay pending; a digest
|
|
81
126
|
// never reaches a queen registered for another repository.
|
|
127
|
+
let pausedRepos = new Set();
|
|
128
|
+
try {
|
|
129
|
+
const status = supervisor !== undefined && typeof supervisor.status === 'function' ? supervisor.status() : null;
|
|
130
|
+
if (Array.isArray(status?.repos)) {
|
|
131
|
+
pausedRepos = new Set(status.repos.filter((repo) => repo?.paused === true && repo?.pausedBy === 'manual').map((repo) => repo.repo));
|
|
132
|
+
}
|
|
133
|
+
} catch {
|
|
134
|
+
pausedRepos = new Set();
|
|
135
|
+
}
|
|
82
136
|
const groups = new Map();
|
|
83
137
|
for (const entry of pending) {
|
|
138
|
+
if (pausedRepos.has(entry.repo)) continue;
|
|
84
139
|
const repo = typeof entry.repo === 'string' && entry.repo !== '' ? entry.repo : '';
|
|
85
140
|
if (repo === '') continue;
|
|
86
141
|
if (!groups.has(repo)) groups.set(repo, []);
|
|
87
142
|
groups.get(repo).push(entry);
|
|
88
143
|
}
|
|
89
144
|
let deliveredCount = 0;
|
|
145
|
+
let dedupedCount = 0;
|
|
146
|
+
let throttledCount = 0;
|
|
147
|
+
let stateChanged = false;
|
|
90
148
|
let via = null;
|
|
91
149
|
let lastReason = null;
|
|
92
150
|
for (const [repo, entries] of groups) {
|
|
151
|
+
const ids = entries.map((entry) => entry.id);
|
|
152
|
+
const signature = signatureOf(entries);
|
|
153
|
+
const previous = deliveryState.repos[repo];
|
|
154
|
+
const at = now();
|
|
155
|
+
// Same anomaly-id set as the last delivered digest: acknowledge the new
|
|
156
|
+
// feed ids silently and update the count, never re-send the digest.
|
|
157
|
+
if (previous !== undefined && previous.signature === signature) {
|
|
158
|
+
try {
|
|
159
|
+
feed.markDelivered(ids);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
log('warn', 'marking duplicate anomalies delivered failed', error);
|
|
162
|
+
}
|
|
163
|
+
deliveryState.repos[repo] = { ...previous, count: entries.length, lastSeenAt: at };
|
|
164
|
+
stateChanged = true;
|
|
165
|
+
dedupedCount += entries.length;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
// Rate limit a changing repository state to one digest per window.
|
|
169
|
+
if (previous !== undefined && Number.isFinite(previous.deliveredAt) && at - previous.deliveredAt < rateLimitMs) {
|
|
170
|
+
lastReason = 'rate-limited';
|
|
171
|
+
throttledCount += entries.length;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
93
174
|
let result;
|
|
94
175
|
try {
|
|
95
176
|
result = notifier.deliver(renderDigest(entries), repo);
|
|
@@ -100,16 +181,19 @@ export function createPatrol(options = {}) {
|
|
|
100
181
|
}
|
|
101
182
|
if (result !== undefined && result.delivered === true) {
|
|
102
183
|
try {
|
|
103
|
-
feed.markDelivered(
|
|
184
|
+
feed.markDelivered(ids);
|
|
104
185
|
} catch (error) {
|
|
105
186
|
log('warn', 'marking anomalies delivered failed', error);
|
|
106
187
|
}
|
|
188
|
+
deliveryState.repos[repo] = { signature, deliveredAt: at, lastSeenAt: at, count: entries.length };
|
|
189
|
+
stateChanged = true;
|
|
107
190
|
deliveredCount += entries.length;
|
|
108
191
|
via = result.via ?? via;
|
|
109
192
|
} else {
|
|
110
193
|
lastReason = result?.reason ?? 'not-delivered';
|
|
111
194
|
}
|
|
112
195
|
}
|
|
196
|
+
if (stateChanged) saveState();
|
|
113
197
|
let stillPending = 0;
|
|
114
198
|
try {
|
|
115
199
|
const rest = feed.pending();
|
|
@@ -118,14 +202,16 @@ export function createPatrol(options = {}) {
|
|
|
118
202
|
stillPending = pending.length - deliveredCount;
|
|
119
203
|
}
|
|
120
204
|
if (deliveredCount > 0) {
|
|
121
|
-
return { delivered: true, count: deliveredCount, pending: stillPending, via, reason: null };
|
|
205
|
+
return { delivered: true, count: deliveredCount, pending: stillPending, via, reason: null, deduped: dedupedCount, throttled: throttledCount };
|
|
122
206
|
}
|
|
123
207
|
return {
|
|
124
208
|
delivered: false,
|
|
125
209
|
count: deliveredCount,
|
|
126
210
|
pending: stillPending,
|
|
127
211
|
via: null,
|
|
128
|
-
reason: lastReason ?? 'no-live-queen-session',
|
|
212
|
+
reason: lastReason ?? (dedupedCount > 0 ? 'deduped' : 'no-live-queen-session'),
|
|
213
|
+
deduped: dedupedCount,
|
|
214
|
+
throttled: throttledCount,
|
|
129
215
|
};
|
|
130
216
|
}
|
|
131
217
|
|
|
@@ -155,6 +241,7 @@ export function createPatrol(options = {}) {
|
|
|
155
241
|
const at = now();
|
|
156
242
|
for (const repo of status.repos) {
|
|
157
243
|
if (repo === null || typeof repo !== 'object') continue;
|
|
244
|
+
if (repo.paused === true && repo.pausedBy === 'manual') continue;
|
|
158
245
|
const name = typeof repo.repo === 'string' ? repo.repo : '';
|
|
159
246
|
if (repo.paused === true && repo.pausedBy === 'auto') {
|
|
160
247
|
push({
|
package/lib/round.js
CHANGED
|
@@ -51,13 +51,18 @@ export class RoundError extends Error {
|
|
|
51
51
|
* @param {Array<{ text: string, status?: string, scope?: string }>} [lessons] recalled hive lessons
|
|
52
52
|
* @returns {string}
|
|
53
53
|
*/
|
|
54
|
-
export function renderPrompt(card, lessons = [], claimAgent, serviceInfo = null) {
|
|
54
|
+
export function renderPrompt(card, lessons = [], claimAgent, serviceInfo = null, resumed = false) {
|
|
55
55
|
const lines = [
|
|
56
56
|
'# Task ' + card.id + ': ' + card.title,
|
|
57
57
|
'',
|
|
58
58
|
'You are working as: ' + (card.role || 'worker') + '.',
|
|
59
59
|
'',
|
|
60
60
|
];
|
|
61
|
+
if (resumed === true) {
|
|
62
|
+
lines.push('## Resumed after a supervisor pause');
|
|
63
|
+
lines.push('Your claim is still held and the card is still claimed. The worker was interrupted; continue from the point where it stopped. Do not re-claim the card, do not redo work whose result is already on disk, and do not release the scope announcements.');
|
|
64
|
+
lines.push('');
|
|
65
|
+
}
|
|
61
66
|
// Recalled experience leads the prompt: the worker sees what earlier cards
|
|
62
67
|
// learned before it reads the goal, so the lessons shape the whole attempt.
|
|
63
68
|
if (lessons.length > 0) {
|
|
@@ -256,12 +261,33 @@ export function createRoundRunner({
|
|
|
256
261
|
* @param {string} [reason]
|
|
257
262
|
* @returns {{ aborted: boolean, cardId: string }}
|
|
258
263
|
*/
|
|
259
|
-
function abortCard(repo, cardId, reason = 'aborted by the queen') {
|
|
264
|
+
function abortCard(repo, cardId, reason = 'aborted by the queen', options = {}) {
|
|
260
265
|
const entry = active.get(repo)?.get(cardId);
|
|
261
266
|
if (entry === undefined || entry.abort === null) return { aborted: false, cardId };
|
|
262
|
-
entry.abort(reason);
|
|
267
|
+
entry.abort(reason, options);
|
|
263
268
|
return { aborted: true, cardId };
|
|
264
269
|
}
|
|
270
|
+
|
|
271
|
+
/** Abort every live worker in a repository (supervisor pause path). */
|
|
272
|
+
function pauseWorkers(repo, reason = 'paused by the supervisor') {
|
|
273
|
+
const cardIds = activeRuns(repo).map((run) => run.cardId);
|
|
274
|
+
const aborted = [];
|
|
275
|
+
for (const cardId of cardIds) {
|
|
276
|
+
if (abortCard(repo, cardId, reason, { pause: true }).aborted) aborted.push(cardId);
|
|
277
|
+
}
|
|
278
|
+
return { aborted };
|
|
279
|
+
}
|
|
280
|
+
/** Abort one card worker and wait until its active run is gone (bounded). */
|
|
281
|
+
async function abortCardAndWait(repo, cardId, reason = 'aborted by the queen', options = {}, timeoutMs = 5_000) {
|
|
282
|
+
const result = abortCard(repo, cardId, reason, options);
|
|
283
|
+
if (!result.aborted) return { ...result, exited: true };
|
|
284
|
+
const deadline = now() + timeoutMs;
|
|
285
|
+
while (now() < deadline) {
|
|
286
|
+
if (!activeRuns(repo).some((run) => run.cardId === cardId)) return { ...result, exited: true };
|
|
287
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
288
|
+
}
|
|
289
|
+
return { ...result, exited: false };
|
|
290
|
+
}
|
|
265
291
|
function unregisterActive(repo, cardId) {
|
|
266
292
|
const runs = active.get(repo);
|
|
267
293
|
if (runs === undefined) return;
|
|
@@ -400,10 +426,10 @@ export function createRoundRunner({
|
|
|
400
426
|
}
|
|
401
427
|
|
|
402
428
|
/** Best-effort release of the announcements we own for this card scope. */
|
|
403
|
-
async function releaseScope(repo, scope, { signal, session, agent, instance }) {
|
|
429
|
+
async function releaseScope(repo, scope, { signal, session, agent, eventActor, instance }) {
|
|
404
430
|
if (scope.length === 0) return;
|
|
405
431
|
try {
|
|
406
|
-
await commands.release(repo, scope, { signal, session, agent, instance });
|
|
432
|
+
await commands.release(repo, scope, { signal, session, agent, eventActor, instance });
|
|
407
433
|
} catch {
|
|
408
434
|
// done/fail already clear the announcements; this is only orphan cleanup.
|
|
409
435
|
}
|
|
@@ -418,11 +444,12 @@ export function createRoundRunner({
|
|
|
418
444
|
* exception is handled the same way. This function never fails a card.
|
|
419
445
|
* @returns {Promise<object[]>} raw overlap entries from the guard document
|
|
420
446
|
*/
|
|
421
|
-
async function announceScope(repo, id, scope, { agent, instance, signal, session }) {
|
|
447
|
+
async function announceScope(repo, id, scope, { agent, eventActor, instance, signal, session }) {
|
|
422
448
|
if (scope.length === 0) return [];
|
|
423
449
|
try {
|
|
424
450
|
const guard = await commands.guard(repo, scope, {
|
|
425
451
|
agent,
|
|
452
|
+
eventActor,
|
|
426
453
|
instance,
|
|
427
454
|
taskId: id,
|
|
428
455
|
ttl: config.ttl,
|
|
@@ -461,7 +488,7 @@ export function createRoundRunner({
|
|
|
461
488
|
}).catch(() => {});
|
|
462
489
|
}
|
|
463
490
|
|
|
464
|
-
async function executeCard({ repo, card, before, owner, agent, parentSource = 'queen', claimDeadline, signal, session }) {
|
|
491
|
+
async function executeCard({ repo, card, before, owner, agent, parentSource = 'queen', claimDeadline, resumed = false, signal, session }) {
|
|
465
492
|
const id = card.id;
|
|
466
493
|
const service = assertProvider(config.provider);
|
|
467
494
|
const scope = scopeOf(card);
|
|
@@ -482,6 +509,7 @@ export function createRoundRunner({
|
|
|
482
509
|
// advisory and an unexpected CLI error is only logged.
|
|
483
510
|
const overlaps = await announceScope(repo, id, scope, {
|
|
484
511
|
agent: claimAgent,
|
|
512
|
+
eventActor,
|
|
485
513
|
instance,
|
|
486
514
|
signal,
|
|
487
515
|
session,
|
|
@@ -543,9 +571,12 @@ export function createRoundRunner({
|
|
|
543
571
|
if (controller.signal.aborted) resolve();
|
|
544
572
|
else controller.signal.addEventListener('abort', () => resolve(), { once: true });
|
|
545
573
|
});
|
|
546
|
-
setActiveAbort(repo, id, (reason) => {
|
|
574
|
+
setActiveAbort(repo, id, (reason, options = {}) => {
|
|
547
575
|
if (queenAbort !== null) return;
|
|
548
|
-
queenAbort =
|
|
576
|
+
queenAbort = {
|
|
577
|
+
reason: typeof reason === 'string' && reason.trim() !== '' ? reason.trim() : 'aborted by the queen',
|
|
578
|
+
pause: options.pause === true,
|
|
579
|
+
};
|
|
549
580
|
controller.abort();
|
|
550
581
|
});
|
|
551
582
|
let timeoutTimer;
|
|
@@ -558,11 +589,18 @@ export function createRoundRunner({
|
|
|
558
589
|
};
|
|
559
590
|
const abortReason = () => 'card timeout after ' + cardTimeoutMs + 'ms';
|
|
560
591
|
const failCard = async (reason, output = reason) => {
|
|
561
|
-
await commands.fail(repo, id, { agent: eventActor, instance, reason, signal, session }).catch(() => {});
|
|
592
|
+
await commands.fail(repo, id, { agent: claimAgent, eventActor, instance, reason, signal, session }).catch(() => {});
|
|
562
593
|
finishRun('failed', { exitCode: 1, output });
|
|
563
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
594
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, eventActor, instance });
|
|
564
595
|
return { id, state: 'failed', reason };
|
|
565
596
|
};
|
|
597
|
+
const pauseCard = async (reason) => {
|
|
598
|
+
const detail = 'paused by supervisor: ' + reason;
|
|
599
|
+
// Pause interrupts the session but keeps the claim and announcements: the
|
|
600
|
+
// card stays claimed, and resume will continue from the interruption point.
|
|
601
|
+
finishRun('paused', { exitCode: null, output: detail, reason: detail });
|
|
602
|
+
return { id, state: 'claimed', reason: detail };
|
|
603
|
+
};
|
|
566
604
|
try {
|
|
567
605
|
// Recall lessons for every scope path plus the repository root before the
|
|
568
606
|
// worker starts. A recall error is recorded on the run record and logged,
|
|
@@ -604,7 +642,7 @@ export function createRoundRunner({
|
|
|
604
642
|
// Workers run in-process; DSH's bash tool inherits ambient env. Inject the
|
|
605
643
|
// claim identity and this card's instance while the worker is alive, so
|
|
606
644
|
// its own `hive guard` / `hive release` calls agree with the runner's.
|
|
607
|
-
releaseEnv = acquireHiveAgentEnv(claimAgent, instance);
|
|
645
|
+
releaseEnv = acquireHiveAgentEnv(claimAgent, instance, eventActor);
|
|
608
646
|
// Local providers can reserve the child Session id before activation.
|
|
609
647
|
// Recording it on the active run closes the window where a just-started
|
|
610
648
|
// worker calls a tool before the provider-reported id reaches activeRuns
|
|
@@ -639,7 +677,7 @@ export function createRoundRunner({
|
|
|
639
677
|
service.startActivation({
|
|
640
678
|
provider: config.provider,
|
|
641
679
|
label: 'hive:' + id,
|
|
642
|
-
prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent, serviceInfo) }],
|
|
680
|
+
prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent, serviceInfo, resumed) }],
|
|
643
681
|
cwd: repo,
|
|
644
682
|
parent: owner,
|
|
645
683
|
signal: workerSignal,
|
|
@@ -715,9 +753,10 @@ export function createRoundRunner({
|
|
|
715
753
|
repo,
|
|
716
754
|
cardId: id,
|
|
717
755
|
role: card.role,
|
|
718
|
-
detail: 'aborted on queen request: ' + queenAbort,
|
|
756
|
+
detail: (queenAbort.pause ? 'aborted by supervisor pause: ' : 'aborted on queen request: ') + queenAbort.reason,
|
|
719
757
|
});
|
|
720
|
-
return await
|
|
758
|
+
if (queenAbort.pause) return await pauseCard(queenAbort.reason);
|
|
759
|
+
return await failCard('aborted on request: ' + queenAbort.reason);
|
|
721
760
|
}
|
|
722
761
|
if (outcome === null) {
|
|
723
762
|
if (queenAbort !== null) {
|
|
@@ -726,9 +765,10 @@ export function createRoundRunner({
|
|
|
726
765
|
repo,
|
|
727
766
|
cardId: id,
|
|
728
767
|
role: card.role,
|
|
729
|
-
detail: 'aborted on queen request: ' + queenAbort,
|
|
768
|
+
detail: (queenAbort.pause ? 'aborted by supervisor pause: ' : 'aborted on queen request: ') + queenAbort.reason,
|
|
730
769
|
});
|
|
731
|
-
return await
|
|
770
|
+
if (queenAbort.pause) return await pauseCard(queenAbort.reason);
|
|
771
|
+
return await failCard('aborted on request: ' + queenAbort.reason);
|
|
732
772
|
}
|
|
733
773
|
// Aborted before the provider settled: report it as a round failure and
|
|
734
774
|
// let the supervisor decide (external cancellation/teardown).
|
|
@@ -744,21 +784,21 @@ export function createRoundRunner({
|
|
|
744
784
|
if (outcome.stopReason !== 'completed') {
|
|
745
785
|
const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
|
|
746
786
|
const reason = 'subagent stopped: ' + outcome.stopReason + detail;
|
|
747
|
-
await commands.fail(repo, id, { agent: eventActor, instance, reason, signal, session });
|
|
787
|
+
await commands.fail(repo, id, { agent: claimAgent, eventActor, instance, reason, signal, session });
|
|
748
788
|
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason), reason });
|
|
749
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
789
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, eventActor, instance });
|
|
750
790
|
return { id, state: 'failed', reason };
|
|
751
791
|
}
|
|
752
792
|
const verdict = await verify({ repo, before, card, agent: claimAgent, signal, session });
|
|
753
793
|
if (verdict.ok) {
|
|
754
|
-
await commands.done(repo, id, { agent: eventActor, instance, sha: verdict.head, verdict: 'pass', signal, session });
|
|
794
|
+
await commands.done(repo, id, { agent: claimAgent, eventActor, instance, sha: verdict.head, verdict: 'pass', signal, session });
|
|
755
795
|
finishRun('done', { exitCode: 0, commit: verdict.head, output: workerOutput(outcome) });
|
|
756
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
796
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, eventActor, instance });
|
|
757
797
|
return { id, state: 'done', sha: verdict.head };
|
|
758
798
|
}
|
|
759
|
-
await commands.fail(repo, id, { agent: eventActor, instance, reason: verdict.reason, signal, session });
|
|
799
|
+
await commands.fail(repo, id, { agent: claimAgent, eventActor, instance, reason: verdict.reason, signal, session });
|
|
760
800
|
finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason), reason: verdict.reason });
|
|
761
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
801
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, eventActor, instance });
|
|
762
802
|
return { id, state: 'failed', reason: verdict.reason };
|
|
763
803
|
} catch (error) {
|
|
764
804
|
settled = true;
|
|
@@ -767,7 +807,9 @@ export function createRoundRunner({
|
|
|
767
807
|
return await failCard(abortReason(), messageOf(error) || abortReason());
|
|
768
808
|
}
|
|
769
809
|
if (queenAbort !== null) {
|
|
770
|
-
|
|
810
|
+
const reason = queenAbort.pause ? queenAbort.reason : 'aborted on request: ' + queenAbort.reason;
|
|
811
|
+
if (queenAbort.pause) return await pauseCard(reason);
|
|
812
|
+
return await failCard(reason, messageOf(error) || reason);
|
|
771
813
|
}
|
|
772
814
|
if (!runFinished) finishRun('failed', { exitCode: 1, output: messageOf(error) });
|
|
773
815
|
if (isCapacityError(error)) {
|
|
@@ -783,7 +825,7 @@ export function createRoundRunner({
|
|
|
783
825
|
const environment = error?.deferrable === true
|
|
784
826
|
|| (typeof error?.code === 'string' && error.code.startsWith('hive/no-'));
|
|
785
827
|
if (!environment) await releaseClaim(repo, id, error, signal, session);
|
|
786
|
-
await releaseScope(repo, scope, { signal, session, agent: claimAgent, instance });
|
|
828
|
+
await releaseScope(repo, scope, { signal, session, agent: claimAgent, eventActor, instance });
|
|
787
829
|
throw error instanceof RoundError
|
|
788
830
|
? error
|
|
789
831
|
: environment
|
|
@@ -807,6 +849,8 @@ export function createRoundRunner({
|
|
|
807
849
|
resolveParent,
|
|
808
850
|
activeRuns,
|
|
809
851
|
abortCard,
|
|
852
|
+
abortCardAndWait,
|
|
853
|
+
pauseWorkers,
|
|
810
854
|
|
|
811
855
|
/**
|
|
812
856
|
* Round-start environment check: the repository must be Hive-initialised
|
|
@@ -891,7 +935,7 @@ export function createRoundRunner({
|
|
|
891
935
|
* @param {{ repo: string, card: object, claimed?: boolean, signal?: AbortSignal, parent?: object, session?: object, agent?: string, ttl?: string }} request
|
|
892
936
|
* @returns {Promise<object>} card result
|
|
893
937
|
*/
|
|
894
|
-
async runCard({ repo, card, claimed = false, signal, parent, session, agent, ttl }) {
|
|
938
|
+
async runCard({ repo, card, claimed = false, resumed = false, signal, parent, session, agent, ttl }) {
|
|
895
939
|
if (typeof repo !== 'string' || repo === '') throw new TypeError('runCard: repo is required');
|
|
896
940
|
if (card === null || typeof card !== 'object' || typeof card.id !== 'string' || card.id === '') {
|
|
897
941
|
return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
|
|
@@ -921,7 +965,14 @@ export function createRoundRunner({
|
|
|
921
965
|
const ttlMs = parseTtlMs(ttl ?? config.ttl);
|
|
922
966
|
if (!alreadyClaimed) {
|
|
923
967
|
const before = await commands.head(repo, { agent: agentId, signal, session });
|
|
924
|
-
const claim = await commands.claim(repo, id, {
|
|
968
|
+
const claim = await commands.claim(repo, id, {
|
|
969
|
+
signal,
|
|
970
|
+
session,
|
|
971
|
+
agent: agentId,
|
|
972
|
+
eventActor: workerActor(fresh.role || card.role),
|
|
973
|
+
instance: id,
|
|
974
|
+
ttl,
|
|
975
|
+
});
|
|
925
976
|
if (claim.exitCode !== 0) {
|
|
926
977
|
return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
|
|
927
978
|
}
|
|
@@ -932,6 +983,7 @@ export function createRoundRunner({
|
|
|
932
983
|
owner,
|
|
933
984
|
agent: agentId,
|
|
934
985
|
parentSource: ownerInfo.source,
|
|
986
|
+
resumed,
|
|
935
987
|
claimDeadline: now() + ttlMs,
|
|
936
988
|
signal,
|
|
937
989
|
session,
|
|
@@ -947,6 +999,7 @@ export function createRoundRunner({
|
|
|
947
999
|
owner,
|
|
948
1000
|
agent: agentId,
|
|
949
1001
|
parentSource: ownerInfo.source,
|
|
1002
|
+
resumed,
|
|
950
1003
|
claimDeadline,
|
|
951
1004
|
signal,
|
|
952
1005
|
session,
|
package/lib/supervisor.js
CHANGED
|
@@ -143,7 +143,12 @@ export class HiveSupervisor {
|
|
|
143
143
|
* @param {(sessionId: string) => void} [options.onQueenSession] called after a queen Session registers
|
|
144
144
|
* @param {() => { names?: string[], sessionId?: string | null, listedAt?: string | null, error?: string | null }} [options.queenTools] diagnostic: tools visible to the queen agent
|
|
145
145
|
* @param {(repo: string, review: object) => Promise<object>} [options.archReview] host-side arch_review fallback
|
|
146
|
+
* @param {(repo: string, reason: string) => object} [options.pauseWorkers] abort live workers when paused
|
|
147
|
+
* @param {(repo: string, cardId: string, reason: string) => object} [options.abortWorker] abort one live worker
|
|
148
|
+
* @param {(repo: string, options: object) => Promise<object[]>} [options.listClaimed] claimed cards used to resume after pause
|
|
149
|
+
* @param {string} [options.claimAgent] runner claim identity used to filter claimed cards
|
|
146
150
|
* @param {() => { count?: number, last?: object | null }} [options.crossRepoBlocked] queen cross-repo rejection counter
|
|
151
|
+
* @param {() => object} [options.bins] resolved hive-tasks/hive/git/roles command paths and sources
|
|
147
152
|
* @param {() => number} [options.pendingAnomalies] undelivered queen anomalies reported in status
|
|
148
153
|
* @param {() => number} [options.pendingCheckpoints] undelivered progress checkpoints reported in status
|
|
149
154
|
* @param {Console} [options.logger]
|
|
@@ -191,7 +196,12 @@ export class HiveSupervisor {
|
|
|
191
196
|
this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
|
|
192
197
|
this.queenTools = typeof options.queenTools === 'function' ? options.queenTools : undefined;
|
|
193
198
|
this.archReview = typeof options.archReview === 'function' ? options.archReview : undefined;
|
|
199
|
+
this.pauseWorkers = typeof options.pauseWorkers === 'function' ? options.pauseWorkers : undefined;
|
|
200
|
+
this.abortWorker = typeof options.abortWorker === 'function' ? options.abortWorker : undefined;
|
|
201
|
+
this.listClaimed = typeof options.listClaimed === 'function' ? options.listClaimed : undefined;
|
|
202
|
+
this.claimAgent = typeof options.claimAgent === 'string' && options.claimAgent !== '' ? options.claimAgent : 'dsh';
|
|
194
203
|
this.crossRepoBlocked = typeof options.crossRepoBlocked === 'function' ? options.crossRepoBlocked : undefined;
|
|
204
|
+
this.bins = typeof options.bins === 'function' ? options.bins : undefined;
|
|
195
205
|
this.pendingAnomalies = typeof options.pendingAnomalies === 'function' ? options.pendingAnomalies : undefined;
|
|
196
206
|
this.pendingCheckpoints = typeof options.pendingCheckpoints === 'function' ? options.pendingCheckpoints : undefined;
|
|
197
207
|
this.discover = options.discover;
|
|
@@ -296,8 +306,10 @@ export class HiveSupervisor {
|
|
|
296
306
|
// Roles actually present on the board, even if roles.yaml/config omit them.
|
|
297
307
|
taskRoles: new Set(),
|
|
298
308
|
wakeRequested: false,
|
|
309
|
+
resumeClaimed: false,
|
|
299
310
|
topUpInFlight: false,
|
|
300
311
|
topUps: new Set(),
|
|
312
|
+
abortRequested: new Set(),
|
|
301
313
|
limitsError: this.limits.errorFor(key),
|
|
302
314
|
environmentError: null,
|
|
303
315
|
mode: null,
|
|
@@ -314,6 +326,8 @@ export class HiveSupervisor {
|
|
|
314
326
|
entry.pausedBy = 'config';
|
|
315
327
|
entry.pausedReason = 'paused by config (remove it from config.paused and restart, or POST ?op=resume)';
|
|
316
328
|
entry.state = STATES.PAUSED;
|
|
329
|
+
// Preserve claims across a paused restart: resume must continue them.
|
|
330
|
+
entry.orphanRecoveryDone = true;
|
|
317
331
|
}
|
|
318
332
|
this.repos.set(key, entry);
|
|
319
333
|
if (this.debug) this.#log('info', 'registered repository', key);
|
|
@@ -374,6 +388,20 @@ export class HiveSupervisor {
|
|
|
374
388
|
entry.pausedBy = 'manual';
|
|
375
389
|
entry.pausedReason = reason;
|
|
376
390
|
entry.state = STATES.PAUSED;
|
|
391
|
+
entry.wakeRequested = false;
|
|
392
|
+
// Freeze orphan recovery while paused: a claimed card interrupted by pause
|
|
393
|
+
// must stay claimed for resume, never be treated as an orphan.
|
|
394
|
+
entry.orphanRecoveryDone = true;
|
|
395
|
+
// Pause is a stop, not just a dispatch gate: terminate the workers that are
|
|
396
|
+
// already running. The runner aborts their sessions and leaves the cards
|
|
397
|
+
// pending so resume does not silently rerun them as a fresh attempt.
|
|
398
|
+
if (typeof this.pauseWorkers === 'function') {
|
|
399
|
+
try {
|
|
400
|
+
this.pauseWorkers(entry.repo, reason);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
this.#log('warn', 'pausing live workers failed for ' + entry.repo, messageOf(error));
|
|
403
|
+
}
|
|
404
|
+
}
|
|
377
405
|
this.#log('info', 'paused repository', entry.repo);
|
|
378
406
|
return this.#snapshot(entry);
|
|
379
407
|
}
|
|
@@ -387,6 +415,7 @@ export class HiveSupervisor {
|
|
|
387
415
|
entry.consecutiveFailures = 0;
|
|
388
416
|
entry.lastError = null;
|
|
389
417
|
entry.state = STATES.IDLE;
|
|
418
|
+
entry.resumeClaimed = true;
|
|
390
419
|
entry.nextAttemptAt = this.now();
|
|
391
420
|
this.#log('info', 'resumed repository', entry.repo);
|
|
392
421
|
return this.#snapshot(entry);
|
|
@@ -451,6 +480,45 @@ export class HiveSupervisor {
|
|
|
451
480
|
return this.status();
|
|
452
481
|
}
|
|
453
482
|
|
|
483
|
+
/**
|
|
484
|
+
* Idempotently unregister a repository's queen (the host `/queen off` path).
|
|
485
|
+
* After this the repo is unmanaged until a new registration arrives; pending
|
|
486
|
+
* checkpoints/anomalies for it wait instead of going to the old Session.
|
|
487
|
+
* @param {string} repo
|
|
488
|
+
* @param {string} [sessionId] only clear when this is the current queen
|
|
489
|
+
* @returns {object} supervisor status
|
|
490
|
+
*/
|
|
491
|
+
clearQueenSession(repo, sessionId) {
|
|
492
|
+
let key;
|
|
493
|
+
try {
|
|
494
|
+
key = normalizeRepoKey(repo);
|
|
495
|
+
} catch {
|
|
496
|
+
return this.status();
|
|
497
|
+
}
|
|
498
|
+
const current = this.queenSessions.get(key);
|
|
499
|
+
const matches = typeof sessionId !== 'string' || sessionId === '' || current === sessionId;
|
|
500
|
+
if (current !== undefined && matches) {
|
|
501
|
+
this.queenSessions.delete(key);
|
|
502
|
+
if (this.queenSession?.repo === key) this.queenSession.sessionId = null;
|
|
503
|
+
const entry = this.repos.get(key);
|
|
504
|
+
if (entry !== undefined) {
|
|
505
|
+
entry.waiting = 'no-queen-session';
|
|
506
|
+
entry.nextAttemptAt = this.now();
|
|
507
|
+
}
|
|
508
|
+
this.#log('info', 'cleared queen session for ' + key);
|
|
509
|
+
} else if (this.legacyQueen && (sessionId === undefined || sessionId === this.queenSession?.sessionId)) {
|
|
510
|
+
this.legacyQueen = false;
|
|
511
|
+
this.queenSession.sessionId = null;
|
|
512
|
+
for (const entry of this.repos.values()) entry.waiting = 'no-queen-session';
|
|
513
|
+
this.#log('info', 'cleared legacy queen session');
|
|
514
|
+
}
|
|
515
|
+
return this.status();
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** Alias used by native transport/panel for `/queen off`. */
|
|
519
|
+
queenOff(repo, sessionId) {
|
|
520
|
+
return this.clearQueenSession(repo, sessionId);
|
|
521
|
+
}
|
|
454
522
|
/** Latest queen Session for one repository (explicit map, then legacy wildcard). */
|
|
455
523
|
queenFor(repo) {
|
|
456
524
|
let key;
|
|
@@ -644,11 +712,69 @@ export class HiveSupervisor {
|
|
|
644
712
|
* @param {number} [at] epoch ms (tests may pin the clock)
|
|
645
713
|
* @returns {Promise<Array<{ repo: string, state: string }>>}
|
|
646
714
|
*/
|
|
715
|
+
/**
|
|
716
|
+
* Reconcile live workers against the board every tick: a worker whose card was
|
|
717
|
+
* deleted or superseded must be aborted immediately, never left as an ownerless
|
|
718
|
+
* session. Emits one worker-aborted anomaly with the reason.
|
|
719
|
+
* @param {object} entry
|
|
720
|
+
*/
|
|
721
|
+
async #reconcileWorkers(entry) {
|
|
722
|
+
if (typeof this.abortWorker !== 'function' || typeof this.listAll !== 'function') return;
|
|
723
|
+
const active = this.#workers(entry.repo);
|
|
724
|
+
const activeIds = new Set(active.map((worker) => worker.cardId).filter(Boolean));
|
|
725
|
+
if (!(entry.abortRequested instanceof Set)) entry.abortRequested = new Set();
|
|
726
|
+
for (const cardId of [...entry.abortRequested]) {
|
|
727
|
+
if (!activeIds.has(cardId)) entry.abortRequested.delete(cardId);
|
|
728
|
+
}
|
|
729
|
+
const pending = active.filter((worker) => worker.cardId && !entry.abortRequested.has(worker.cardId));
|
|
730
|
+
if (pending.length === 0) return;
|
|
731
|
+
let tasks;
|
|
732
|
+
try {
|
|
733
|
+
tasks = await this.listAll(entry.repo, { signal: this.abortController?.signal });
|
|
734
|
+
} catch (error) {
|
|
735
|
+
this.#log('warn', 'worker reconciliation could not read the board for ' + entry.repo + ': ' + messageOf(error));
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const byId = new Map();
|
|
739
|
+
for (const task of Array.isArray(tasks) ? tasks : []) {
|
|
740
|
+
if (task !== null && typeof task === 'object' && typeof task.id === 'string') byId.set(task.id, task);
|
|
741
|
+
}
|
|
742
|
+
for (const worker of pending) {
|
|
743
|
+
const task = byId.get(worker.cardId);
|
|
744
|
+
let reason = null;
|
|
745
|
+
if (task === undefined) reason = 'task missing';
|
|
746
|
+
else if (task.superseded === true) reason = 'task superseded';
|
|
747
|
+
if (reason === null) continue;
|
|
748
|
+
entry.abortRequested.add(worker.cardId);
|
|
749
|
+
try {
|
|
750
|
+
this.abortWorker(entry.repo, worker.cardId, reason);
|
|
751
|
+
this.#anomaly({
|
|
752
|
+
kind: 'worker-aborted',
|
|
753
|
+
repo: entry.repo,
|
|
754
|
+
cardId: worker.cardId,
|
|
755
|
+
role: worker.role ?? null,
|
|
756
|
+
detail: reason,
|
|
757
|
+
});
|
|
758
|
+
this.#log('warn', 'aborted worker for ' + reason + ': ' + worker.cardId + ' in ' + entry.repo);
|
|
759
|
+
} catch (error) {
|
|
760
|
+
entry.abortRequested.delete(worker.cardId);
|
|
761
|
+
this.#log('warn', 'aborting worker for missing/superseded card failed: ' + worker.cardId, messageOf(error));
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
647
765
|
async tick(at = this.now()) {
|
|
648
766
|
this.lastTickAt = at;
|
|
649
767
|
if (this.autoDiscover && typeof this.discover === 'function' && at >= this.nextDiscoverAt) {
|
|
650
768
|
await this.#refreshDiscovery(at);
|
|
651
769
|
}
|
|
770
|
+
for (const entry of this.repos.values()) {
|
|
771
|
+
// Run reconciliation without an extra await: an idle repo must not shift
|
|
772
|
+
// the dispatch microtask timing (the tests and the tick contract rely on
|
|
773
|
+
// the first drain starting in the same turn).
|
|
774
|
+
void this.#reconcileWorkers(entry).catch((error) => {
|
|
775
|
+
this.#log('warn', 'worker reconciliation failed for ' + entry.repo + ': ' + messageOf(error));
|
|
776
|
+
});
|
|
777
|
+
}
|
|
652
778
|
const due = [...this.repos.values()]
|
|
653
779
|
.filter((entry) => !entry.paused && !entry.inFlight && entry.nextAttemptAt <= at)
|
|
654
780
|
.sort((a, b) => a.nextAttemptAt - b.nextAttemptAt);
|
|
@@ -722,6 +848,8 @@ export class HiveSupervisor {
|
|
|
722
848
|
// Mechanical cross-repository rejections of queen hive_* calls.
|
|
723
849
|
crossRepoBlocked: this.#crossRepoBlockedCount(),
|
|
724
850
|
lastCrossRepoBlocked: this.crossRepoBlocked?.()?.last ?? null,
|
|
851
|
+
// Actual binary paths resolved once at startup, with their source.
|
|
852
|
+
bins: typeof this.bins === 'function' ? this.bins() : {},
|
|
725
853
|
intervalMs: this.intervalMs,
|
|
726
854
|
idleBackoffMs: this.idleBackoffMs,
|
|
727
855
|
maxConcurrentRepos: this.maxConcurrentRepos,
|
|
@@ -928,6 +1056,25 @@ export class HiveSupervisor {
|
|
|
928
1056
|
if (typeof card.role === 'string' && card.role !== '') entry.taskRoles.add(card.role);
|
|
929
1057
|
queuedIds.add(card.id);
|
|
930
1058
|
}
|
|
1059
|
+
// Resume after a pause: cards that stayed claimed must be re-launched
|
|
1060
|
+
// without re-claiming; they continue from the interruption point.
|
|
1061
|
+
if (entry.resumeClaimed === true && typeof this.listClaimed === 'function') {
|
|
1062
|
+
entry.resumeClaimed = false;
|
|
1063
|
+
try {
|
|
1064
|
+
const claimedCards = await this.listClaimed(entry.repo, { signal });
|
|
1065
|
+
const activeIds = new Set(this.#workers(entry.repo).map((worker) => worker.cardId).filter(Boolean));
|
|
1066
|
+
for (const card of Array.isArray(claimedCards) ? claimedCards : []) {
|
|
1067
|
+
if (card === null || typeof card !== 'object' || typeof card.id !== 'string') continue;
|
|
1068
|
+
if (card.owner !== this.claimAgent || activeIds.has(card.id) || queuedIds.has(card.id)) continue;
|
|
1069
|
+
entry.queue.push({ role: card.role, card, claimed: true, resumed: true });
|
|
1070
|
+
if (typeof card.role === 'string' && card.role !== '') entry.taskRoles.add(card.role);
|
|
1071
|
+
queuedIds.add(card.id);
|
|
1072
|
+
}
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
entry.resumeClaimed = true;
|
|
1075
|
+
this.#log('warn', 'resuming claimed cards failed for ' + entry.repo + ': ' + messageOf(error));
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
931
1078
|
entry.frozenSkipped = frozenSkipped;
|
|
932
1079
|
entry.lastSkipReason = frozen && frozenSkipped > 0
|
|
933
1080
|
? 'mode=freeze: skipped ' + frozenSkipped + ' non-fix card(s); only fix-tagged cards are dispatched'
|
|
@@ -954,6 +1101,7 @@ export class HiveSupervisor {
|
|
|
954
1101
|
repo: entry.repo,
|
|
955
1102
|
card: item.card,
|
|
956
1103
|
claimed: item.claimed === true,
|
|
1104
|
+
resumed: item.resumed === true,
|
|
957
1105
|
signal,
|
|
958
1106
|
}),
|
|
959
1107
|
onState: (state) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-hive-runner",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.26",
|
|
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",
|