dsh-hive-runner 0.1.0 → 0.6.1
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 +66 -0
- package/LICENSE +21 -0
- package/README.md +274 -10
- package/README.zh-CN.md +206 -0
- package/SPEC.md +212 -0
- package/cordis.patch.yml +80 -2
- package/docs/DESIGN.md +181 -0
- package/index.js +182 -64
- package/lib/commands.js +280 -0
- package/lib/config.js +264 -0
- package/lib/discover.js +96 -0
- package/lib/hooks.js +92 -0
- package/lib/http.js +120 -0
- package/lib/limits.js +184 -0
- package/lib/queue.js +156 -0
- package/lib/round.js +380 -0
- package/lib/shell.js +72 -0
- package/lib/supervisor.js +574 -0
- package/package.json +45 -10
package/lib/limits.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-repository runtime concurrency limits persisted on disk.
|
|
3
|
+
*
|
|
4
|
+
* File: `<repo>/.hive/limits.json` (a plain `{ role: n }` map).
|
|
5
|
+
* Precedence for one role in one repository:
|
|
6
|
+
* persisted file entry > config.roleConcurrency (repo override) >
|
|
7
|
+
* config.roleConcurrency (global role entry) > config.defaultRoleConcurrency.
|
|
8
|
+
*
|
|
9
|
+
* The config map is the initial/fallback value; the file is runtime state
|
|
10
|
+
* written by `POST /api/hive-runner?op=limits` and re-read whenever its
|
|
11
|
+
* mtime/size changes (hot reload at the start of every drain).
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { ROLE_RE, roleLimitForRepo, roleNamesForRepo } from './config.js';
|
|
16
|
+
|
|
17
|
+
/** Path of the per-repository limits file, relative to the repository root. */
|
|
18
|
+
export const LIMITS_FILE = path.join('.hive', 'limits.json');
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Validate a role -> limit object (0 pauses the role, 999 is the maximum).
|
|
22
|
+
* @param {unknown} value
|
|
23
|
+
* @returns {Record<string, number>}
|
|
24
|
+
*/
|
|
25
|
+
export function validateRoleLimits(value) {
|
|
26
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
27
|
+
throw new TypeError('roleLimits must be an object of role -> integer');
|
|
28
|
+
}
|
|
29
|
+
const limits = {};
|
|
30
|
+
for (const [role, limit] of Object.entries(value)) {
|
|
31
|
+
if (!ROLE_RE.test(role)) throw new TypeError('roleLimits role ' + JSON.stringify(role) + ' must match ' + ROLE_RE);
|
|
32
|
+
if (!Number.isInteger(limit) || limit < 0 || limit > 999) {
|
|
33
|
+
throw new TypeError('roleLimits.' + role + ' must be an integer in 0..999');
|
|
34
|
+
}
|
|
35
|
+
limits[role] = limit;
|
|
36
|
+
}
|
|
37
|
+
return limits;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Synchronous limits store with mtime-based hot reload.
|
|
42
|
+
*/
|
|
43
|
+
export class RepoLimits {
|
|
44
|
+
/**
|
|
45
|
+
* @param {object} [options]
|
|
46
|
+
* @param {Record<string, number>} [options.roleConcurrency] global role caps
|
|
47
|
+
* @param {Record<string, Record<string, number>>} [options.repoRoleConcurrency] config repo overrides
|
|
48
|
+
* @param {number} [options.defaultRoleConcurrency] fallback for unlisted roles
|
|
49
|
+
* @param {typeof fs} [options.io] injectable fs for tests
|
|
50
|
+
*/
|
|
51
|
+
constructor(options = {}) {
|
|
52
|
+
this.config = {
|
|
53
|
+
roleConcurrency: options.roleConcurrency ?? {},
|
|
54
|
+
repoRoleConcurrency: options.repoRoleConcurrency ?? {},
|
|
55
|
+
defaultRoleConcurrency: options.defaultRoleConcurrency ?? 5,
|
|
56
|
+
};
|
|
57
|
+
this.io = options.io ?? fs;
|
|
58
|
+
/** @type {Map<string, { mtimeMs: number | null, size: number, limits: Record<string, number>, loaded: boolean, error: string | null }>} */
|
|
59
|
+
this.cache = new Map();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** @param {string} repo */
|
|
63
|
+
filePath(repo) {
|
|
64
|
+
return path.join(repo, LIMITS_FILE);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
configuredLimit(repo, role) {
|
|
68
|
+
return roleLimitForRepo(this.config, repo, role);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
#entry(repo) {
|
|
72
|
+
let entry = this.cache.get(repo);
|
|
73
|
+
if (entry === undefined) {
|
|
74
|
+
entry = { mtimeMs: null, size: -1, limits: {}, loaded: false, error: null };
|
|
75
|
+
this.cache.set(repo, entry);
|
|
76
|
+
}
|
|
77
|
+
return entry;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Reload the limits file when its mtime/size changed. Keeps the previous
|
|
82
|
+
* known values on a parse/validation error and records `error`.
|
|
83
|
+
* @param {string} repo
|
|
84
|
+
* @returns {{ limits: Record<string, number>, error: string | null }}
|
|
85
|
+
*/
|
|
86
|
+
refresh(repo) {
|
|
87
|
+
const entry = this.#entry(repo);
|
|
88
|
+
let stat;
|
|
89
|
+
try {
|
|
90
|
+
stat = this.io.statSync(this.filePath(repo));
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error?.code === 'ENOENT') {
|
|
93
|
+
entry.mtimeMs = null;
|
|
94
|
+
entry.size = -1;
|
|
95
|
+
entry.limits = {};
|
|
96
|
+
entry.loaded = true;
|
|
97
|
+
entry.error = null;
|
|
98
|
+
return { limits: {}, error: null };
|
|
99
|
+
}
|
|
100
|
+
entry.loaded = true;
|
|
101
|
+
entry.error = 'cannot stat limits file: ' + String(error?.message ?? error);
|
|
102
|
+
return { limits: entry.limits, error: entry.error };
|
|
103
|
+
}
|
|
104
|
+
if (entry.loaded && entry.mtimeMs === stat.mtimeMs && entry.size === stat.size) {
|
|
105
|
+
return { limits: entry.limits, error: entry.error };
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const parsed = JSON.parse(this.io.readFileSync(this.filePath(repo), 'utf8'));
|
|
109
|
+
const limits = validateRoleLimits(parsed);
|
|
110
|
+
entry.mtimeMs = stat.mtimeMs;
|
|
111
|
+
entry.size = stat.size;
|
|
112
|
+
entry.limits = limits;
|
|
113
|
+
entry.loaded = true;
|
|
114
|
+
entry.error = null;
|
|
115
|
+
return { limits, error: null };
|
|
116
|
+
} catch (error) {
|
|
117
|
+
entry.mtimeMs = stat.mtimeMs;
|
|
118
|
+
entry.size = stat.size;
|
|
119
|
+
entry.loaded = true;
|
|
120
|
+
entry.error = 'invalid limits file: ' + String(error?.message ?? error);
|
|
121
|
+
return { limits: entry.limits, error: entry.error };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Persisted values only (after a refresh). */
|
|
126
|
+
fileLimits(repo) {
|
|
127
|
+
return this.refresh(repo).limits;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Current reload error, if any. */
|
|
131
|
+
errorFor(repo) {
|
|
132
|
+
return this.#entry(repo).error;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Effective limit for one role: persisted file > config > default.
|
|
137
|
+
* @param {string} repo
|
|
138
|
+
* @param {string} role
|
|
139
|
+
* @returns {number}
|
|
140
|
+
*/
|
|
141
|
+
limitFor(repo, role) {
|
|
142
|
+
const entry = this.#entry(repo);
|
|
143
|
+
if (!entry.loaded) this.refresh(repo);
|
|
144
|
+
const current = this.#entry(repo);
|
|
145
|
+
if (Object.hasOwn(current.limits, role)) return current.limits[role];
|
|
146
|
+
return this.configuredLimit(repo, role);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Roles worth reporting for a repository: config roles, file keys, extras. */
|
|
150
|
+
rolesFor(repo, extra = []) {
|
|
151
|
+
const names = new Set([
|
|
152
|
+
...roleNamesForRepo(this.config, repo, extra),
|
|
153
|
+
...Object.keys(this.fileLimits(repo)),
|
|
154
|
+
]);
|
|
155
|
+
return [...names];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Merge role limits into the persisted file (atomic write) and return the
|
|
160
|
+
* new persisted map. Callers use `limitFor` for the effective values.
|
|
161
|
+
* @param {string} repo
|
|
162
|
+
* @param {Record<string, number>} roleLimits
|
|
163
|
+
* @returns {Record<string, number>}
|
|
164
|
+
*/
|
|
165
|
+
write(repo, roleLimits) {
|
|
166
|
+
const validated = validateRoleLimits(roleLimits);
|
|
167
|
+
const current = this.fileLimits(repo);
|
|
168
|
+
const merged = { ...current, ...validated };
|
|
169
|
+
const file = this.filePath(repo);
|
|
170
|
+
this.io.mkdirSync(path.dirname(file), { recursive: true });
|
|
171
|
+
const temporary = file + '.' + process.pid + '.tmp';
|
|
172
|
+
this.io.writeFileSync(temporary, JSON.stringify(merged, null, 2) + '\n');
|
|
173
|
+
this.io.renameSync(temporary, file);
|
|
174
|
+
const stat = this.io.statSync(file);
|
|
175
|
+
this.cache.set(repo, {
|
|
176
|
+
mtimeMs: stat.mtimeMs,
|
|
177
|
+
size: stat.size,
|
|
178
|
+
limits: merged,
|
|
179
|
+
loaded: true,
|
|
180
|
+
error: null,
|
|
181
|
+
});
|
|
182
|
+
return merged;
|
|
183
|
+
}
|
|
184
|
+
}
|
package/lib/queue.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-repository work queue with finite, user-set per-role concurrency.
|
|
3
|
+
*
|
|
4
|
+
* Concurrency is a user setting, not "one worker per ready card": for each role
|
|
5
|
+
* at most `limitFor(role)` card workers are **live** at the same time. Only
|
|
6
|
+
* live workers occupy a slot; cards waiting in the queue do not. When a worker
|
|
7
|
+
* finishes a card, it immediately picks the next queued card of the same role
|
|
8
|
+
* (a completion frees its slot at once).
|
|
9
|
+
*
|
|
10
|
+
* Real subagent capacity is still owned by DSH
|
|
11
|
+
* (`subagent.maxActiveSubagents`). When the harness rejects a start with
|
|
12
|
+
* `ACTIVATION_LIMIT_REACHED`, the card goes back to its role queue, the worker
|
|
13
|
+
* waits `capacityRetryMs`, and retries; nothing is dropped.
|
|
14
|
+
*
|
|
15
|
+
* `limitFor(role) === 0` pauses that role: its queued cards are left on the
|
|
16
|
+
* Hive board and never dispatched.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Error code DSH's subagent activation pool uses when it is full. */
|
|
20
|
+
export const CAPACITY_ERROR_CODE = 'ACTIVATION_LIMIT_REACHED';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether an error means "DSH subagent capacity is temporarily exhausted".
|
|
24
|
+
* These are queue-and-retry events, not round failures.
|
|
25
|
+
* @param {unknown} error
|
|
26
|
+
* @returns {boolean}
|
|
27
|
+
*/
|
|
28
|
+
export function isCapacityError(error) {
|
|
29
|
+
if (error === null || typeof error !== 'object') return false;
|
|
30
|
+
if (error.code === CAPACITY_ERROR_CODE) return true;
|
|
31
|
+
if (error.capacity === true) return true;
|
|
32
|
+
return typeof error.message === 'string' && /subagent limit reached/i.test(error.message);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Drain a multi-role queue into card workers with live-only accounting.
|
|
39
|
+
*
|
|
40
|
+
* @param {object} options
|
|
41
|
+
* @param {Array<{ role?: string, card?: object, claimed?: boolean }>} options.queue work items (mutated during the drain)
|
|
42
|
+
* @param {(item: object) => Promise<object>} options.runCard runs one item
|
|
43
|
+
* @param {(role: string) => number} [options.limitFor] per-role live-worker limit (0 = paused)
|
|
44
|
+
* @param {string[]} [options.roleNames] additional roles to report in `state`
|
|
45
|
+
* @param {number} [options.capacityRetryMs] delay before retrying capacity-rejected items
|
|
46
|
+
* @param {AbortSignal} [options.signal]
|
|
47
|
+
* @param {(state: object) => void} [options.onState] live per-role status callback
|
|
48
|
+
* @param {(ms: number) => Promise<void>} [options.sleep]
|
|
49
|
+
* @returns {Promise<{ results: object[], queue: object[], state: object, error?: unknown }>}
|
|
50
|
+
*/
|
|
51
|
+
export async function drainQueue({
|
|
52
|
+
queue,
|
|
53
|
+
runCard,
|
|
54
|
+
limitFor = () => 5,
|
|
55
|
+
roleNames = [],
|
|
56
|
+
capacityRetryMs = 2_000,
|
|
57
|
+
signal,
|
|
58
|
+
onState,
|
|
59
|
+
sleep = defaultSleep,
|
|
60
|
+
} = {}) {
|
|
61
|
+
if (!Array.isArray(queue)) throw new TypeError('drainQueue: queue must be an array');
|
|
62
|
+
if (typeof runCard !== 'function') throw new TypeError('drainQueue: runCard must be a function');
|
|
63
|
+
if (typeof limitFor !== 'function') throw new TypeError('drainQueue: limitFor must be a function');
|
|
64
|
+
|
|
65
|
+
/** @type {Map<string, object[]>} */
|
|
66
|
+
const buckets = new Map();
|
|
67
|
+
for (const item of queue) {
|
|
68
|
+
const role = typeof item?.role === 'string' && item.role !== '' ? item.role : 'worker';
|
|
69
|
+
if (!buckets.has(role)) buckets.set(role, []);
|
|
70
|
+
buckets.get(role).push(item);
|
|
71
|
+
}
|
|
72
|
+
const knownRoles = new Set([...roleNames.filter((role) => typeof role === 'string' && role !== ''), ...buckets.keys()]);
|
|
73
|
+
const liveByRole = new Map();
|
|
74
|
+
const results = [];
|
|
75
|
+
let completed = 0;
|
|
76
|
+
let error;
|
|
77
|
+
|
|
78
|
+
function snapshot() {
|
|
79
|
+
const roles = {};
|
|
80
|
+
let live = 0;
|
|
81
|
+
let queued = 0;
|
|
82
|
+
for (const role of knownRoles) {
|
|
83
|
+
const liveCount = liveByRole.get(role) ?? 0;
|
|
84
|
+
const queuedCount = buckets.get(role)?.length ?? 0;
|
|
85
|
+
roles[role] = { limit: limitFor(role), live: liveCount, queued: queuedCount };
|
|
86
|
+
live += liveCount;
|
|
87
|
+
queued += queuedCount;
|
|
88
|
+
}
|
|
89
|
+
return { roles, live, queued, completed };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const report = () => onState?.(snapshot());
|
|
93
|
+
|
|
94
|
+
// A paused role (limit 0) leaves its cards on the Hive board.
|
|
95
|
+
for (const [role, bucket] of buckets) {
|
|
96
|
+
if (!(limitFor(role) > 0)) bucket.length = 0;
|
|
97
|
+
}
|
|
98
|
+
report();
|
|
99
|
+
|
|
100
|
+
async function workRole(role) {
|
|
101
|
+
const bucket = buckets.get(role) ?? [];
|
|
102
|
+
const limit = limitFor(role);
|
|
103
|
+
if (!(limit > 0) || bucket.length === 0) return;
|
|
104
|
+
|
|
105
|
+
async function worker() {
|
|
106
|
+
while (bucket.length > 0 && error === undefined && !signal?.aborted) {
|
|
107
|
+
const item = bucket.shift();
|
|
108
|
+
liveByRole.set(role, (liveByRole.get(role) ?? 0) + 1);
|
|
109
|
+
report();
|
|
110
|
+
let result;
|
|
111
|
+
let failure;
|
|
112
|
+
try {
|
|
113
|
+
result = await runCard(item);
|
|
114
|
+
} catch (caught) {
|
|
115
|
+
failure = caught;
|
|
116
|
+
}
|
|
117
|
+
// A settled worker frees its live slot immediately; the next card below
|
|
118
|
+
// is started before this worker waits/continues.
|
|
119
|
+
liveByRole.set(role, Math.max(0, (liveByRole.get(role) ?? 1) - 1));
|
|
120
|
+
report();
|
|
121
|
+
|
|
122
|
+
if (failure === undefined) {
|
|
123
|
+
results.push(result);
|
|
124
|
+
completed += 1;
|
|
125
|
+
report();
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (isCapacityError(failure)) {
|
|
129
|
+
const retry = failure.item ?? { ...item, claimed: true };
|
|
130
|
+
bucket.unshift(retry);
|
|
131
|
+
report();
|
|
132
|
+
await sleep(capacityRetryMs);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (error === undefined) error = failure;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const workers = [];
|
|
141
|
+
const count = Math.min(Math.floor(limit), bucket.length);
|
|
142
|
+
for (let index = 0; index < count; index += 1) workers.push(worker());
|
|
143
|
+
await Promise.all(workers);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
await Promise.all([...knownRoles].map((role) => workRole(role)));
|
|
147
|
+
|
|
148
|
+
const leftover = [];
|
|
149
|
+
for (const role of knownRoles) {
|
|
150
|
+
const bucket = buckets.get(role);
|
|
151
|
+
if (bucket !== undefined && bucket.length > 0) leftover.push(...bucket);
|
|
152
|
+
}
|
|
153
|
+
const state = snapshot();
|
|
154
|
+
report();
|
|
155
|
+
return { results, queue: leftover, state, error };
|
|
156
|
+
}
|