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/lib/round.js ADDED
@@ -0,0 +1,380 @@
1
+ /**
2
+ * One Hive round for one repository: fetch every ready card and run one card
3
+ * end to end.
4
+ *
5
+ * The default policy is one subagent per ready card (the number of workers
6
+ * equals the current ready-task count). `roleConcurrency` is only an optional
7
+ * operations cap; the real ceiling is DSH's `subagent.maxActiveSubagents` and
8
+ * the model provider's rate limits. Capacity rejections are turned into
9
+ * queueable work items by `lib/queue.js` instead of failing the round.
10
+ *
11
+ * All Hive/git commands go through the allowlisted `lib/commands.js` layer,
12
+ * hence through `ctx.shell`. Card workers are DSH subagents, not processes.
13
+ *
14
+ * Merge-on-commit is mandatory: a drain preflights `<repo>/.git/hooks/pre-commit`
15
+ * (missing hook = deferrable environment error, run `hive init`) and a card is
16
+ * only recorded done when HEAD moved through that hook-equipped commit path.
17
+ */
18
+ import { roleLimitForRepo } from './config.js';
19
+ import { HiveCommandError, tail } from './commands.js';
20
+ import { assertMergeOnCommitHook } from './hooks.js';
21
+ import { isCapacityError } from './queue.js';
22
+
23
+ /** A round-level failure. `hive/capacity` is retried from the queue. */
24
+ export class RoundError extends Error {
25
+ constructor(code, message, options = {}) {
26
+ super(message);
27
+ this.name = 'RoundError';
28
+ this.code = code;
29
+ this.deferrable = options.deferrable === true;
30
+ if (options.capacity === true) this.capacity = true;
31
+ if (options.cause !== undefined) this.cause = options.cause;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Render the worker prompt for one card.
37
+ * @param {object} card Hive task card
38
+ * @param {Array<{ text: string, status?: string, scope?: string }>} [lessons] recalled hive lessons
39
+ * @returns {string}
40
+ */
41
+ export function renderPrompt(card, lessons = [], claimAgent) {
42
+ const lines = [
43
+ '# Task ' + card.id + ': ' + card.title,
44
+ '',
45
+ 'You are working as: ' + (card.role || 'worker') + '.',
46
+ '',
47
+ ];
48
+ if (card.goal) lines.push('## Goal', card.goal, '');
49
+ if (card.scope && card.scope.length) {
50
+ lines.push('## Scope (edit only these paths)');
51
+ for (const entry of card.scope) lines.push('- ' + entry);
52
+ lines.push('');
53
+ }
54
+ if (card.acceptance) lines.push('## Acceptance (the runner will run this)', ' ' + card.acceptance, '');
55
+ if (card.reason) lines.push('## Previous attempt failed with', card.reason, '');
56
+ lines.push('## Hive consensus rules (mandatory)');
57
+ lines.push('1. At the start, run `hive guard <path...>` for every entry in the card scope (including `resource:` entries, which are leases, not files). It co-signs your leases and marks the board working.'
58
+ + (claimAgent ? ' Use the same claim identity, for example `hive guard <path...> --agent ' + claimAgent + '`; a different identity would collide with your own leases.' : ''));
59
+ lines.push('2. If `hive guard` exits 2, stop immediately and report the holder information (stderr) as the failure reason. NEVER bypass it: do not edit files outside the scope, do not `git checkout` files owned by someone else, and do not delete lease refs.');
60
+ lines.push('3. Your claim already marks the board working with this task id; guard keeps it current.');
61
+ lines.push('4. Before finishing, release your own leases (`hive release <scope...>`); done/fail normally release them, but verify nothing is left behind.');
62
+ if (lessons.length > 0) {
63
+ lines.push('5. The runner already ran `hive recall <scope>` for this card; the relevant experience is injected below. Only if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path); do not write a lesson just to write one.');
64
+ } else {
65
+ lines.push('5. The runner already ran `hive recall <scope>`; if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path); do not write a lesson just to write one.');
66
+ }
67
+ lines.push('');
68
+ lines.push('## Commit rules (mandatory)');
69
+ lines.push('1. Commit with a plain `git commit`. The repository pre-commit hook runs merge-on-commit (moc) and performs a three-way merge automatically.');
70
+ lines.push('2. NEVER bypass the hook: do not use `git commit --no-verify`, do not use `git commit --amend` to skip it, and do not use `git update-ref` or `git reset` to rewrite history that others already committed.');
71
+ lines.push('3. If the hook reports merge conflicts, resolve them in place using the conflict markers, then commit again. Never discard the other side\'s changes.');
72
+ lines.push('');
73
+ if (lessons.length > 0) {
74
+ lines.push('## Recalled experience (hive recall)');
75
+ for (const lesson of lessons) {
76
+ const status = lesson.status ? '[' + lesson.status + '] ' : '';
77
+ lines.push('- ' + status + String(lesson.text ?? '').trim());
78
+ }
79
+ lines.push('');
80
+ }
81
+ lines.push('## How to finish');
82
+ lines.push('1. Edit only the scope paths.');
83
+ lines.push('2. Commit before you exit: the runner checks that HEAD moved through the hook.');
84
+ lines.push('3. Do not run hive-tasks done; the runner records it.');
85
+ return lines.join('\n');
86
+ }
87
+
88
+ function messageOf(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+
92
+ /**
93
+ * Bind the Hive round helpers to the DSH runtime and the Hive command layer.
94
+ * @param {{ ctx: object, config: object, commands: object }} options
95
+ */
96
+ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook = assertMergeOnCommitHook }) {
97
+ if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
98
+ throw new TypeError('createRoundRunner: ctx with ctx.get() is required');
99
+ }
100
+ if (commands === undefined || commands === null) throw new TypeError('createRoundRunner: commands are required');
101
+ /** Effective live-worker cap for (repo, role). The plugin passes the persisted-limits store. */
102
+ const capFor = typeof limitFor === 'function'
103
+ ? limitFor
104
+ : (repo, role) => roleLimitForRepo(config, repo, role);
105
+
106
+ function subagents() {
107
+ const service = ctx.get('subagents');
108
+ if (service === undefined || service === null) {
109
+ throw new RoundError('hive/no-subagents', 'ctx.subagents is unavailable; the Hive supervisor cannot start card subagents');
110
+ }
111
+ return service;
112
+ }
113
+
114
+ /**
115
+ * Resolve the Agent that owns subagent runs. Prefer the caller's agent (tool
116
+ * calls); otherwise the explicitly pinned session, then any live agent.
117
+ */
118
+ function resolveParent(explicit) {
119
+ if (explicit !== undefined && explicit !== null) return explicit;
120
+ const agents = ctx.get('agents');
121
+ if (config.parentSession) {
122
+ const pinned = typeof agents?.get === 'function' ? agents.get(config.parentSession) : undefined;
123
+ if (pinned !== undefined) return pinned;
124
+ throw new RoundError(
125
+ 'hive/no-parent-agent',
126
+ 'parentSession ' + JSON.stringify(config.parentSession) + ' is not live; open that session or remove parentSession',
127
+ { deferrable: true },
128
+ );
129
+ }
130
+ const live = typeof agents?.list === 'function' ? agents.list() : [];
131
+ if (live.length > 0) return live[0];
132
+ throw new RoundError(
133
+ 'hive/no-parent-agent',
134
+ 'no live DSH agent to parent Hive subagent runs; open a session or set parentSession (deferred, not counted as a failure)',
135
+ { deferrable: true },
136
+ );
137
+ }
138
+
139
+ function assertProvider(providerName) {
140
+ const service = subagents();
141
+ const provider = typeof service.getProvider === 'function' ? service.getProvider(providerName) : undefined;
142
+ if (provider === undefined) {
143
+ throw new RoundError('hive/no-provider', 'no subagent provider named ' + JSON.stringify(providerName) + ' is registered');
144
+ }
145
+ return service;
146
+ }
147
+
148
+ async function verify({ repo, before, card, signal, session }) {
149
+ const head = await commands.head(repo, { signal, session });
150
+ if (head === before) return { ok: false, reason: 'no commit produced' };
151
+ // The commit must have landed through the merge-on-commit path: if the hook
152
+ // vanished the commit may have bypassed it, so this is an environment error.
153
+ checkHook(repo);
154
+ if (card.acceptance) {
155
+ const result = await commands.acceptance(repo, card.acceptance, { signal, session });
156
+ if (result.exitCode !== 0) {
157
+ const detail = result.stderr.trim() !== '' ? result.stderr : result.stdout;
158
+ return { ok: false, reason: 'acceptance failed: ' + tail(detail) };
159
+ }
160
+ }
161
+ return { ok: true, head };
162
+ }
163
+
164
+ /** Scope entries of one card (files and `resource:` lease keys alike). */
165
+ function scopeOf(card) {
166
+ return Array.isArray(card.scope)
167
+ ? card.scope.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
168
+ : [];
169
+ }
170
+
171
+ /**
172
+ * Recall lessons for the card scope. Best effort: a recall failure never
173
+ * blocks the card (the runner already has the environment churn signal).
174
+ */
175
+ async function recallLessons(repo, scope, { signal, session }) {
176
+ const seen = new Map();
177
+ for (const query of scope.slice(0, 3)) {
178
+ try {
179
+ const items = await commands.recall(repo, query, { signal, session });
180
+ for (const item of items) {
181
+ if (item === null || typeof item !== 'object' || typeof item.text !== 'string') continue;
182
+ seen.set(item.id ?? item.text, item);
183
+ }
184
+ } catch {
185
+ // Lessons are advisory; continue without them.
186
+ }
187
+ if (seen.size >= 5) break;
188
+ }
189
+ return [...seen.values()].slice(0, 5);
190
+ }
191
+
192
+ /** Best-effort release of the leases we own for this card scope. */
193
+ async function releaseScope(repo, scope, { signal, session, agent }) {
194
+ if (scope.length === 0) return;
195
+ try {
196
+ await commands.release(repo, scope, { signal, session, agent });
197
+ } catch {
198
+ // done/fail already release leases; this is only orphan cleanup.
199
+ }
200
+ }
201
+
202
+ /** Holder agent names parsed from `hive guard` denial stderr. */
203
+ function deniedHolders(stderr) {
204
+ const holders = new Set();
205
+ const pattern = /([^\s]+)\s+holds it/g;
206
+ for (const match of String(stderr ?? '').matchAll(pattern)) holders.add(match[1]);
207
+ return [...holders];
208
+ }
209
+
210
+ /** Best-effort release of a claim when the worker could not run at all. */
211
+ async function releaseClaim(repo, id, error, signal, session) {
212
+ await commands.fail(repo, id, {
213
+ reason: 'runner error: ' + tail(messageOf(error)),
214
+ signal,
215
+ session,
216
+ }).catch(() => {});
217
+ }
218
+
219
+ async function executeCard({ repo, card, before, owner, agent, signal, session }) {
220
+ const id = card.id;
221
+ const service = assertProvider(config.provider);
222
+ const scope = scopeOf(card);
223
+ const claimAgent = agent ?? config.agent;
224
+ let activation;
225
+ try {
226
+ // hive-consensus: co-sign the card's leases (guard) with the SAME identity
227
+ // used for the claim. A different identity would collide with the claim's
228
+ // own leases and deny itself.
229
+ if (scope.length > 0) {
230
+ const guard = await commands.guard(repo, scope, {
231
+ agent: claimAgent,
232
+ taskId: id,
233
+ ttl: config.ttl,
234
+ signal,
235
+ session,
236
+ });
237
+ if (guard.exitCode === 2) {
238
+ const holders = deniedHolders(guard.stderr);
239
+ const selfHeld = holders.length > 0 && holders.every((holder) => holder === claimAgent);
240
+ if (selfHeld) {
241
+ // Our own earlier lease (for example after a retry): allow the card
242
+ // and extend the leases instead of failing it.
243
+ await commands.renew(repo, scope, { agent: claimAgent, ttl: config.ttl, signal, session }).catch(() => {});
244
+ } else {
245
+ const reason = 'guard denied: ' + tail(guard.stderr || guard.stdout || 'scope held by another agent');
246
+ await commands.fail(repo, id, { reason, signal, session });
247
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent });
248
+ return { id, state: 'failed', reason };
249
+ }
250
+ } else if (guard.exitCode !== 0) {
251
+ throw new RoundError(
252
+ 'hive/guard-failed',
253
+ 'hive guard exited ' + String(guard.exitCode) + ': ' + tail(guard.stderr || guard.stdout),
254
+ );
255
+ }
256
+ }
257
+ const lessons = scope.length > 0 ? await recallLessons(repo, scope, { signal, session }) : [];
258
+ activation = await service.startActivation({
259
+ provider: config.provider,
260
+ label: 'hive:' + id,
261
+ prompt: [{ type: 'text', text: renderPrompt(card, lessons, claimAgent) }],
262
+ cwd: repo,
263
+ parent: owner,
264
+ signal,
265
+ delivery: 'caller',
266
+ });
267
+ const outcome = await activation.result;
268
+ if (outcome.stopReason !== 'completed') {
269
+ const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
270
+ const reason = 'subagent stopped: ' + outcome.stopReason + detail;
271
+ await commands.fail(repo, id, { reason, signal, session });
272
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent });
273
+ return { id, state: 'failed', reason };
274
+ }
275
+ const verdict = await verify({ repo, before, card, signal, session });
276
+ if (verdict.ok) {
277
+ await commands.done(repo, id, { sha: verdict.head, verdict: 'pass', signal, session });
278
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent });
279
+ return { id, state: 'done', sha: verdict.head };
280
+ }
281
+ await commands.fail(repo, id, { reason: verdict.reason, signal, session });
282
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent });
283
+ return { id, state: 'failed', reason: verdict.reason };
284
+ } catch (error) {
285
+ if (isCapacityError(error)) {
286
+ // Capacity is a scheduling concern, not this card's failure: keep the
287
+ // claimed item and let the dispatcher retry it.
288
+ const capacity = new RoundError('hive/capacity', messageOf(error), { capacity: true });
289
+ capacity.item = { role: card.role, card, claimed: true };
290
+ throw capacity;
291
+ }
292
+ // Deferrable environment errors (missing merge-on-commit hook, no live
293
+ // parent agent) are not the card's failure: leave the claim to expire /
294
+ // retry later instead of recording a card failure.
295
+ const environment = error?.deferrable === true
296
+ || (typeof error?.code === 'string' && error.code.startsWith('hive/no-'));
297
+ if (!environment) await releaseClaim(repo, id, error, signal, session);
298
+ await releaseScope(repo, scope, { signal, session, agent: claimAgent });
299
+ throw error instanceof RoundError
300
+ ? error
301
+ : environment
302
+ ? error
303
+ : new RoundError('hive/round-failed', messageOf(error), { cause: error });
304
+ } finally {
305
+ if (activation !== undefined) {
306
+ await Promise.resolve(activation.dispose?.()).catch(() => {});
307
+ }
308
+ }
309
+ }
310
+
311
+ return {
312
+ resolveParent,
313
+
314
+ /**
315
+ * Round-start environment check: the repository must be Hive-initialised
316
+ * with the merge-on-commit pre-commit hook. Throws a deferrable error.
317
+ * @param {string} repo
318
+ */
319
+ preflight(repo) {
320
+ checkHook(repo);
321
+ },
322
+
323
+ /**
324
+ * All ready cards in one repository. Roles configured with a 0 cap are
325
+ * filtered out; otherwise every card becomes one work item.
326
+ * @returns {Promise<object[]>}
327
+ */
328
+ async listReady(repo, { signal, session } = {}) {
329
+ const cards = await commands.ready(repo, { signal, session });
330
+ return cards.filter((card) => capFor(repo, card?.role) > 0);
331
+ },
332
+
333
+ /**
334
+ * Run one card end to end. Fresh items are claimed here; retried items
335
+ * arrive with `claimed: true` and reuse the claim if it survived the wait.
336
+ * @param {{ repo: string, card: object, claimed?: boolean, signal?: AbortSignal, parent?: object, session?: object, agent?: string, ttl?: string }} request
337
+ * @returns {Promise<object>} card result
338
+ */
339
+ async runCard({ repo, card, claimed = false, signal, parent, session, agent, ttl }) {
340
+ if (typeof repo !== 'string' || repo === '') throw new TypeError('runCard: repo is required');
341
+ if (card === null || typeof card !== 'object' || typeof card.id !== 'string' || card.id === '') {
342
+ return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
343
+ }
344
+ const id = card.id;
345
+ const owner = resolveParent(parent);
346
+ let fresh = card;
347
+ try {
348
+ const shown = await commands.show(repo, id, { signal, session });
349
+ if (shown !== null && typeof shown === 'object') fresh = shown;
350
+ } catch {
351
+ // The ready snapshot is enough to render the prompt.
352
+ }
353
+ const agentId = agent ?? config.agent;
354
+ const claimedUntil = fresh.claimedUntil === undefined || fresh.claimedUntil === null
355
+ ? Infinity
356
+ : Date.parse(fresh.claimedUntil);
357
+ const claimValid = fresh.state === 'claimed'
358
+ && fresh.owner === agentId
359
+ && (Number.isNaN(claimedUntil) || claimedUntil > Date.now());
360
+ const alreadyClaimed = claimed === true && claimValid;
361
+ if (claimed === true && !alreadyClaimed && fresh.state === 'claimed' && fresh.owner !== agentId) {
362
+ return { id, state: 'skipped', reason: 'claim held by ' + String(fresh.owner) };
363
+ }
364
+
365
+ if (!alreadyClaimed) {
366
+ const before = await commands.head(repo, { signal, session });
367
+ const claim = await commands.claim(repo, id, { signal, session, agent, ttl });
368
+ if (claim.exitCode !== 0) {
369
+ return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
370
+ }
371
+ return await executeCard({ repo, card: fresh, before, owner, agent: agentId, signal, session });
372
+ }
373
+
374
+ const before = await commands.head(repo, { signal, session });
375
+ return await executeCard({ repo, card: fresh, before, owner, agent: agentId, signal, session });
376
+ },
377
+ };
378
+ }
379
+
380
+ export { HiveCommandError };
package/lib/shell.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * One thin adapter over DSH's shell seam (`ctx.shell.resolve` + `execute`).
3
+ *
4
+ * The shell seam is the only execution path this plugin uses. Deliberately no
5
+ * `node:child_process`: spawning directly would bypass the sandbox, the session
6
+ * sandbox policy, credential scrubbing, output caps and cancellation (see
7
+ * dsh-hive-panel/docs/RESEARCH.md §1).
8
+ *
9
+ * Agent-triggered calls (a tool run) pass the calling `session` so the session's
10
+ * resolved sandbox policy applies. Agentless calls from the supervisor have no
11
+ * session; the deployment default mode is kept, but the resolved policy's
12
+ * workspace root is pinned to the repository being driven, otherwise
13
+ * `workspace-write` would only allow writes under the DSH host cwd.
14
+ */
15
+
16
+ /** Trusted in-process caller: parse a complete `--json` document, not a tool-sized tail. */
17
+ export const DEFAULT_STDOUT_MAX_BYTES = 4 * 1024 * 1024;
18
+
19
+ /**
20
+ * @param {{ ctx: object, config: { cliTimeoutMs?: number } }} options
21
+ * @returns {(command: string, options?: object) => Promise<object>}
22
+ */
23
+ export function createShellRunner({ ctx, config = {} }) {
24
+ if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
25
+ throw new TypeError('createShellRunner: ctx with ctx.get() is required');
26
+ }
27
+ const shell = ctx.get('shell');
28
+ if (shell === undefined || shell === null) {
29
+ throw new Error(
30
+ 'hive-runner: ctx.shell is unavailable; mount a bash executor (dsh-bash-sandbox / dsh-bash-local). '
31
+ + 'Refusing to fall back to child_process because that bypasses the sandbox.',
32
+ );
33
+ }
34
+ const sandboxPolicy = ctx.get('sandboxPolicy');
35
+ const defaultTimeoutMs = config.cliTimeoutMs ?? 120_000;
36
+
37
+ /**
38
+ * Run one already-allowlisted command through the shell seam.
39
+ * @param {string} command shell command string (the seam executes it with bash -c)
40
+ * @param {{ workdir?: string, session?: object, signal?: AbortSignal, timeoutMs?: number, stdoutMaxBytes?: number }} [options]
41
+ * @returns {Promise<{ command: string, exitCode: number | null, signal: string | null, timedOut: boolean, aborted: boolean, stdout: string, stderr: string, sandbox?: object }>}
42
+ */
43
+ return async function run(command, options = {}) {
44
+ const { workdir, session, signal } = options;
45
+ const request = {
46
+ command,
47
+ timeoutMs: options.timeoutMs ?? defaultTimeoutMs,
48
+ stdoutMaxBytes: options.stdoutMaxBytes ?? DEFAULT_STDOUT_MAX_BYTES,
49
+ };
50
+ if (workdir !== undefined) request.workdir = workdir;
51
+ if (signal !== undefined) request.signal = signal;
52
+ if (sandboxPolicy !== undefined && sandboxPolicy !== null) {
53
+ const base = sandboxPolicy.resolve(session === undefined ? {} : { session });
54
+ request.sandboxPolicy = session === undefined && workdir !== undefined
55
+ ? { ...base, workspaceRoot: workdir }
56
+ : base;
57
+ }
58
+ const spec = shell.resolve(request);
59
+ const execution = await shell.execute(spec);
60
+ const result = await execution.result();
61
+ return {
62
+ command: spec.command,
63
+ exitCode: result.exitCode,
64
+ signal: result.signal,
65
+ timedOut: result.timedOut,
66
+ aborted: result.aborted,
67
+ stdout: result.stdout?.text ?? '',
68
+ stderr: result.stderr?.text ?? '',
69
+ sandbox: result.sandbox,
70
+ };
71
+ };
72
+ }