dsh-hive-runner 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -4,33 +4,83 @@
4
4
  * Owns:
5
5
  * - `HiveSupervisor`: a resident, repository-scoped scheduler (Cordis service +
6
6
  * effect-owned timer) that keeps taking Hive cards while the Web UI is closed;
7
- * - `GET /api/hive-runner?op=status`, `POST ?op=pause|resume`: observability and
8
- * manual control over the same-origin Connection Fetch route;
9
- * - four model-facing tools: run one round now, read ready cards, read the
10
- * board, read supervisor status.
7
+ * - the queen's tool surface: board, task cards (list/show/add/reopen/retry/rm),
8
+ * lessons, roles, supervisor pause/resume/limits, anomaly digest and the
9
+ * architecture-review gate;
10
+ * - the anomaly pipeline: supervisor/runner supervision events -> coalesced
11
+ * digest -> message injection into the registered queen Session, with a
12
+ * pending list for the periods without a live queen;
13
+ * - `GET|POST /api/hive-runner`: observability and manual control over the
14
+ * same-origin Connection Fetch route.
11
15
  *
12
16
  * Everything the supervisor/tool does with a shell goes through `ctx.shell`
13
- * (allowlisted `hive-tasks ready|claim|show|done|fail`, fixed `git rev-parse
14
- * HEAD`, and a card's own acceptance command). This plugin never imports
15
- * `node:child_process`: direct spawning would bypass the sandbox, the session
16
- * sandbox policy, credential scrubbing, output caps and cancellation.
17
- * Card workers are DSH subagents (`ctx.subagents`), not child processes.
17
+ * (allowlisted hive/hive-tasks/git verbs and a card's own acceptance command).
18
+ * This plugin never imports `node:child_process`: direct spawning would bypass
19
+ * the sandbox, the session sandbox policy, credential scrubbing, output caps and
20
+ * cancellation. Card workers are DSH subagents (`ctx.subagents`), not processes.
18
21
  */
19
22
  import { defineTool } from '@deepseek-ai/dsh-tools';
20
23
 
21
24
  import { createCommands } from './lib/commands.js';
22
25
  import { normalizeRepoKey, resolveConfig } from './lib/config.js';
23
26
  import { discoverRepos } from './lib/discover.js';
27
+ import {
28
+ appendArchReview,
29
+ appendEscalation,
30
+ appendIntervention,
31
+ ESCALATION_KIND,
32
+ escalatedCards,
33
+ INTERVENTION_ESCALATE_AFTER,
34
+ interventionCounts,
35
+ readEvents,
36
+ REBUILD_LIMIT,
37
+ rebuildCounts,
38
+ } from './lib/events.js';
39
+ import { createArchReviewAudit } from './lib/audit.js';
24
40
  import { createHiveRunnerRoute } from './lib/http.js';
25
41
  import { RepoLimits } from './lib/limits.js';
42
+ import { createAnomalyFeed } from './lib/anomalies.js';
43
+ import { createQueenNotifier, deliverToSession } from './lib/notify.js';
44
+ import { createPatrol } from './lib/patrol.js';
26
45
  import { drainQueue } from './lib/queue.js';
27
46
  import { createRoundRunner } from './lib/round.js';
47
+ import { readRunRecord } from './lib/runs.js';
28
48
  import { HiveSupervisor } from './lib/supervisor.js';
29
49
 
30
50
  export const name = 'hive-runner';
31
51
  /** Host services that must exist before the plugin loads. */
32
52
  export const inject = ['tools', 'shell', 'subagents'];
33
53
 
54
+ /** Keep one tool result bounded; the run records on disk stay complete. */
55
+ const RUN_OUTPUT_TAIL = 4000;
56
+
57
+ /** A compact last-run view for failure triage (not the raw file). */
58
+ function summarizeRun(record) {
59
+ if (record === null || typeof record !== 'object') return null;
60
+ const summary = {
61
+ status: record.status ?? null,
62
+ startedAt: record.startedAt ?? null,
63
+ endedAt: record.endedAt ?? null,
64
+ heartbeat: record.heartbeat ?? null,
65
+ sessionId: typeof record.sessionId === 'string' ? record.sessionId : null,
66
+ };
67
+ const output = typeof record.output === 'string' ? record.output : '';
68
+ if (output !== '') summary.output = output.length <= RUN_OUTPUT_TAIL ? output : output.slice(-RUN_OUTPUT_TAIL);
69
+ if (Array.isArray(record.overlaps) && record.overlaps.length > 0) summary.overlaps = record.overlaps;
70
+ if (record.lessons !== undefined) summary.lessons = record.lessons;
71
+ return summary;
72
+ }
73
+
74
+ /** Attach the last-run summary to a card, keeping the raw record on disk. */
75
+ function withLastRun(repo, card) {
76
+ if (card === null || typeof card !== 'object' || typeof card.id !== 'string') return card;
77
+ return { ...card, lastRun: summarizeRun(readRunRecord(repo, card.id)) };
78
+ }
79
+
80
+ function jsonText(value) {
81
+ return JSON.stringify(value, null, 2);
82
+ }
83
+
34
84
  /**
35
85
  * @param {import('@deepseek-ai/cordis').Context} ctx
36
86
  * @param {Record<string, unknown>} [config]
@@ -43,11 +93,53 @@ export function apply(ctx, config = {}) {
43
93
  repoRoleConcurrency: resolved.repoRoleConcurrency,
44
94
  defaultRoleConcurrency: resolved.defaultRoleConcurrency,
45
95
  });
96
+ const log = (level, ...args) => {
97
+ const write = console[level];
98
+ if (typeof write === 'function') write.call(console, '[hive-runner]', ...args);
99
+ else console.warn('[hive-runner]', ...args);
100
+ };
101
+ // The panel registers the queen conversation here (setQueenSession, also via
102
+ // POST ?op=queen). Every worker is parented to exactly that Session; before
103
+ // registration the supervisor does not dispatch at all.
104
+ const queenSession = { sessionId: null };
105
+ let parentProviderImpl;
46
106
  const runner = createRoundRunner({
47
107
  ctx,
48
108
  config: resolved,
49
109
  commands,
50
110
  limitFor: (repo, role) => limits.limitFor(repo, role),
111
+ parentProvider: (explicit) => parentProviderImpl(explicit),
112
+ onAnomaly: (event) => recordAnomaly(event),
113
+ log,
114
+ });
115
+ parentProviderImpl = async (explicit) => {
116
+ const sessionId = queenSession.sessionId;
117
+ const agent = sessionId === null ? undefined : ctx.get('agents')?.get?.(sessionId);
118
+ return { agent, source: 'queen', sessionId };
119
+ };
120
+
121
+ // Anomaly feed: supervision events for the queen, coalesced and delivered as
122
+ // one digest. `patrol` is assigned after the supervisor exists.
123
+ const anomalies = createAnomalyFeed({ max: resolved.anomalyMax });
124
+ /** @type {ReturnType<typeof createPatrol> | undefined} */
125
+ let patrol;
126
+ function recordAnomaly(event) {
127
+ try {
128
+ anomalies.push(event);
129
+ } catch (error) {
130
+ log('warn', 'anomaly push failed', error);
131
+ return;
132
+ }
133
+ if (patrol !== undefined && resolved.notifyQueen) patrol.scheduleFlush();
134
+ }
135
+ const notifier = createQueenNotifier({ ctx, queenSession, log });
136
+ // Done cards must carry an arch_review event; the patrol audits the board and
137
+ // turns a missing review into an arch-review-missing anomaly.
138
+ const archReviewAudit = createArchReviewAudit({
139
+ commands,
140
+ feed: anomalies,
141
+ graceMs: resolved.archReviewGraceMs,
142
+ log,
51
143
  });
52
144
 
53
145
  const supervisor = new HiveSupervisor({
@@ -68,24 +160,63 @@ export function apply(ctx, config = {}) {
68
160
  ? () => discoverRepos({ roots: resolved.discoverRoots, depth: resolved.discoverDepth })
69
161
  : undefined,
70
162
  listReady: runner.listReady,
163
+ listAll: (repo, options = {}) => commands.list(repo, {}, options),
71
164
  runCard: runner.runCard,
72
165
  preflight: runner.preflight,
166
+ activeRuns: (repo) => runner.activeRuns(repo),
167
+ queenSession,
73
168
  readMode: (repo) => commands.mode(repo),
169
+ onAnomaly: (event) => recordAnomaly(event),
170
+ onQueenSession: () => {
171
+ if (patrol !== undefined) patrol.flushPending();
172
+ },
173
+ pendingAnomalies: () => anomalies.pendingCount(),
74
174
  logger: console,
75
175
  debug: resolved.debug,
76
176
  });
77
177
 
78
- // Cordis service + effect-owned timer: the supervisor follows the plugin's
79
- // lifecycle (host composition), not any browser tab.
178
+ patrol = createPatrol({
179
+ supervisor,
180
+ feed: anomalies,
181
+ notifier: resolved.notifyQueen ? notifier : undefined,
182
+ intervalMs: resolved.patrolMs,
183
+ debounceMs: resolved.anomalyDebounceMs,
184
+ // Every patrol also audits done cards for a missing architecture review.
185
+ inspect: async () => {
186
+ let repos = [];
187
+ try {
188
+ repos = supervisor.status().repos.map((entry) => entry.repo);
189
+ } catch {
190
+ return;
191
+ }
192
+ for (const repo of repos) {
193
+ try {
194
+ await archReviewAudit.audit(repo);
195
+ } catch (error) {
196
+ log('warn', 'arch review audit failed for ' + repo + ': ' + (error instanceof Error ? error.message : String(error)));
197
+ }
198
+ }
199
+ },
200
+ log,
201
+ });
202
+
203
+ // Cordis service + effect-owned timers: the supervisor and the queen patrol
204
+ // follow the plugin's lifecycle (host composition), not any browser tab.
80
205
  ctx.provide('hiveSupervisor', supervisor);
81
206
  ctx.effect(() => {
82
207
  supervisor.start();
83
- return () => supervisor.stop();
208
+ patrol.start();
209
+ return () => {
210
+ patrol.stop();
211
+ supervisor.stop();
212
+ };
84
213
  });
85
214
 
86
215
  // Optional: the Web/desktop composition provides `connection`. In a headless
87
216
  // CLI composition without it the supervisor still runs and the tools work.
88
- ctx.inject(['connection'], (scope) => scope.connection.fetch.register(createHiveRunnerRoute(supervisor)));
217
+ ctx.inject(['connection'], (scope) => scope.connection.fetch.register(
218
+ createHiveRunnerRoute(supervisor, { anomalies }),
219
+ ));
89
220
 
90
221
  if (resolved.debug) {
91
222
  console.info('[hive-runner] repositories:', resolved.repos.length, 'autoDiscover:', resolved.autoDiscover);
@@ -102,7 +233,23 @@ export function apply(ctx, config = {}) {
102
233
  );
103
234
  }
104
235
 
105
- ctx.tools.register(defineTool({
236
+ /** Register one model-facing tool whose result is rendered as one text block. */
237
+ function registerTextTool({ name, description, parameters = {}, execute }) {
238
+ ctx.tools.register(defineTool({
239
+ name,
240
+ description,
241
+ parameters,
242
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
243
+ execute,
244
+ }));
245
+ }
246
+
247
+ const repoParameter = {
248
+ type: 'string',
249
+ description: 'Repository path. Default: the configured cwd.',
250
+ };
251
+
252
+ registerTextTool({
106
253
  name: 'hive_run_round',
107
254
  description:
108
255
  'Run one Hive round now in one repository: fetch every ready card and run card workers bounded by the '
@@ -110,19 +257,24 @@ export function apply(ctx, config = {}) {
110
257
  + 'then record done or fail. DSH subagent capacity rejections stay queued and are retried, not dropped. '
111
258
  + 'Returns per-card results and per-role state as JSON. The resident supervisor runs these rounds on its own schedule.',
112
259
  parameters: {
113
- repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
260
+ repo: repoParameter,
114
261
  ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
115
262
  agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
116
263
  },
117
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
118
264
  execute: async (args = {}, exec) => {
119
265
  const repo = repoOf(args);
120
266
  const signal = exec?.signal;
121
267
  const session = exec?.agent?.session;
268
+ if (supervisor.queenSession.sessionId === null) {
269
+ throw new Error('waiting: no-queen-session — open the Hive panel and initialise the repository first');
270
+ }
122
271
  runner.preflight(repo);
123
272
  const cards = await runner.listReady(repo, { signal, session });
273
+ // The manual round obeys the same gate order as the resident supervisor.
274
+ const gateResult = await supervisor.filterDispatchable(repo, cards, { signal });
275
+ const dispatchable = gateResult.cards;
124
276
  const outcome = await drainQueue({
125
- queue: cards.map((card) => ({ role: card.role, card, claimed: false })),
277
+ queue: dispatchable.map((card) => ({ role: card.role, card, claimed: false })),
126
278
  roleNames: limits.rolesFor(repo, cards.map((card) => card.role)),
127
279
  limitFor: (role) => limits.limitFor(repo, role),
128
280
  runCard: (item) => runner.runCard({
@@ -139,24 +291,24 @@ export function apply(ctx, config = {}) {
139
291
  signal,
140
292
  });
141
293
  if (outcome.error !== undefined) throw outcome.error;
142
- return JSON.stringify({
294
+ return jsonText({
143
295
  repo,
296
+ gate: gateResult.gate,
144
297
  results: outcome.results,
145
298
  state: outcome.state,
146
299
  queued: outcome.queue.length,
147
- }, null, 2);
300
+ });
148
301
  },
149
- }));
302
+ });
150
303
 
151
- ctx.tools.register(defineTool({
304
+ registerTextTool({
152
305
  name: 'hive_tasks_ready',
153
306
  description: 'List the Hive task cards that are ready right now in one repository, best first.',
154
307
  parameters: {
155
- repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
308
+ repo: repoParameter,
156
309
  role: { type: 'string', description: 'Filter by Hive role, for example coder or tester.' },
157
310
  limit: { type: 'number', description: 'Maximum number of cards.' },
158
311
  },
159
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
160
312
  execute: async (args = {}, exec) => {
161
313
  const repo = repoOf(args);
162
314
  const cards = await commands.ready(repo, {
@@ -165,31 +317,459 @@ export function apply(ctx, config = {}) {
165
317
  signal: exec?.signal,
166
318
  session: exec?.agent?.session,
167
319
  });
168
- return JSON.stringify(cards, null, 2);
320
+ return jsonText(cards);
169
321
  },
170
- }));
322
+ });
171
323
 
172
- ctx.tools.register(defineTool({
324
+ registerTextTool({
173
325
  name: 'hive_board',
174
326
  description: 'Show which agents are on the Hive board right now in one repository.',
175
- parameters: {
176
- repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
177
- },
178
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
327
+ parameters: { repo: repoParameter },
179
328
  execute: async (args = {}, exec) => {
180
329
  const repo = repoOf(args);
181
330
  const board = await commands.board(repo, { signal: exec?.signal, session: exec?.agent?.session });
182
- return JSON.stringify(board, null, 2);
331
+ return jsonText(board);
183
332
  },
184
- }));
333
+ });
185
334
 
186
- ctx.tools.register(defineTool({
335
+ registerTextTool({
187
336
  name: 'hive_supervisor_status',
188
337
  description:
189
338
  'Show the resident Hive supervisor state: per-repository state (idle/running/backoff/paused), '
190
- + 'last round time, last error, in-flight flag and pause reason. Same data as GET /api/hive-runner?op=status.',
339
+ + 'last round time, last error, in-flight workers, role limits, the pending queen anomaly count, '
340
+ + 'and the gate pipeline (phase base|group|overall|released, releaseReady, reason). '
341
+ + 'Same data as GET /api/hive-runner?op=status.',
191
342
  parameters: {},
192
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
193
- execute: async () => JSON.stringify(supervisor.status(), null, 2),
194
- }));
343
+ execute: async () => jsonText(supervisor.status()),
344
+ });
345
+
346
+ registerTextTool({
347
+ name: 'hive_tasks',
348
+ description:
349
+ 'Manage Hive task cards without claiming them. action=list|show|add|reopen|retry|rm. '
350
+ + 'list/show return the card plus its last-run record (status, heartbeat, output tail, overlaps) for triage; '
351
+ + 'add creates a card (title required; acceptance required unless draft=true; scope, after, priority, tags, reviewOf optional); '
352
+ + 'reopen resets any card to pending with an attempt+1 and an optional reason; retry moves a failed card back to pending; '
353
+ + 'rm deletes a card (the CLI refuses a claimed card — reopen or wait for the claim to expire first). '
354
+ + 'The queen uses these for ordering, splitting and remediation; workers alone claim and finish cards.',
355
+ parameters: {
356
+ repo: repoParameter,
357
+ action: {
358
+ type: 'string',
359
+ enum: ['list', 'show', 'add', 'reopen', 'retry', 'rm'],
360
+ description: 'What to do. list/show read; add/reopen/retry/rm change the board.',
361
+ },
362
+ id: { type: 'string', description: 'Card id (show/reopen/retry/rm).' },
363
+ state: { type: 'string', enum: ['pending', 'claimed', 'done', 'failed'], description: 'list: state filter.' },
364
+ role: { type: 'string', description: 'list/add: role filter or role of the new card.' },
365
+ title: { type: 'string', description: 'add: card title (required).' },
366
+ goal: { type: 'string', description: 'add: goal of the card.' },
367
+ scope: { type: 'array', items: { type: 'string' }, description: 'add: paths or resource keys the card may touch.' },
368
+ after: { type: 'array', items: { type: 'string' }, description: 'add: card ids that must be done first.' },
369
+ priority: { type: 'number', description: 'add: higher runs first (-1000..1000).' },
370
+ tags: { type: 'array', items: { type: 'string' }, description: 'add: tags, e.g. fix, review.' },
371
+ acceptance: { type: 'string', description: 'add: shell command/assertion that proves the card (required by the queen contract).' },
372
+ reviewOf: { type: 'string', description: 'add: the card id this card reviews.' },
373
+ draft: { type: 'boolean', description: 'add: create a draft card (no acceptance needed, never dispatched, not counted as ready).' },
374
+ reason: { type: 'string', description: 'reopen: why the card is being sent back.' },
375
+ },
376
+ execute: async (args = {}, exec) => {
377
+ const repo = repoOf(args);
378
+ const options = { signal: exec?.signal, session: exec?.agent?.session };
379
+ const action = String(args.action ?? '');
380
+ if (action === 'list') {
381
+ const cards = await commands.list(repo, { state: args.state, role: args.role }, options);
382
+ return jsonText(cards.map((card) => withLastRun(repo, card)));
383
+ }
384
+ if (action === 'show') {
385
+ if (typeof args.id !== 'string') throw new Error('hive_tasks show needs an id');
386
+ const card = await commands.show(repo, args.id, options);
387
+ if (card === null || card === undefined) throw new Error('no such card: ' + args.id);
388
+ return jsonText(withLastRun(repo, card));
389
+ }
390
+ if (action === 'add') {
391
+ const card = await commands.add(repo, {
392
+ title: args.title,
393
+ role: args.role,
394
+ scope: args.scope,
395
+ after: args.after,
396
+ priority: args.priority,
397
+ goal: args.goal,
398
+ acceptance: args.acceptance,
399
+ tags: args.tags,
400
+ reviewOf: args.reviewOf,
401
+ draft: args.draft,
402
+ }, options);
403
+ return jsonText({ ok: true, card });
404
+ }
405
+ if (action === 'reopen') {
406
+ if (typeof args.id !== 'string') throw new Error('hive_tasks reopen needs an id');
407
+ return jsonText({ ok: true, card: await commands.reopen(repo, args.id, { reason: args.reason }, options) });
408
+ }
409
+ if (action === 'retry') {
410
+ if (typeof args.id !== 'string') throw new Error('hive_tasks retry needs an id');
411
+ return jsonText({ ok: true, card: await commands.retry(repo, args.id, options) });
412
+ }
413
+ if (action === 'rm') {
414
+ if (typeof args.id !== 'string') throw new Error('hive_tasks rm needs an id');
415
+ return jsonText({ ok: true, deleted: args.id, output: await commands.remove(repo, args.id, options) });
416
+ }
417
+ throw new Error('hive_tasks action must be one of list, show, add, reopen, retry, rm');
418
+ },
419
+ });
420
+
421
+ registerTextTool({
422
+ name: 'hive_arch_review',
423
+ description:
424
+ 'Record the queen architecture review of one accepted (done) card. Appends an arch_review event '
425
+ + '{ card, verdict, findings } to .hive/events.jsonl — never edits the card. '
426
+ + 'verdict=pass|reject; a reject needs at least one actionable finding naming the file and what to change. '
427
+ + 'On reject, do not delete the card: reopen it with a reason and add one or more fine-grained fix cards.',
428
+ parameters: {
429
+ repo: repoParameter,
430
+ card: { type: 'string', description: 'Card id being reviewed (must be done).' },
431
+ verdict: { type: 'string', enum: ['pass', 'reject'], description: 'Review verdict.' },
432
+ findings: {
433
+ type: 'array',
434
+ items: { type: 'string' },
435
+ description: 'Actionable findings: which file/module and what to change. Required for reject.',
436
+ },
437
+ summary: { type: 'string', description: 'One-line summary of the review.' },
438
+ },
439
+ execute: async (args = {}, exec) => {
440
+ const repo = repoOf(args);
441
+ if (typeof args.card !== 'string' || args.card.trim() === '') throw new Error('hive_arch_review needs card');
442
+ const card = await commands.show(repo, args.card.trim(), {
443
+ signal: exec?.signal,
444
+ session: exec?.agent?.session,
445
+ });
446
+ if (card === null || card === undefined) throw new Error('no such card: ' + args.card);
447
+ if (card.state !== 'done') {
448
+ throw new Error('architecture review runs after acceptance: card ' + card.id + ' is ' + card.state + ', not done');
449
+ }
450
+ const event = appendArchReview(repo, {
451
+ card: card.id,
452
+ verdict: args.verdict,
453
+ findings: args.findings,
454
+ summary: args.summary,
455
+ });
456
+ return jsonText({ ok: true, event });
457
+ },
458
+ });
459
+
460
+ registerTextTool({
461
+ name: 'hive_events',
462
+ description:
463
+ 'Read the tail of .hive/events.jsonl (newest first), optionally filtered by kind or card. '
464
+ + 'Use kind=arch_review to see which accepted cards were reviewed and with what findings.',
465
+ parameters: {
466
+ repo: repoParameter,
467
+ kind: { type: 'string', description: 'Filter by event kind, for example arch_review.' },
468
+ task: { type: 'string', description: 'Filter by card id.' },
469
+ limit: { type: 'number', description: 'Maximum number of events (default 50).' },
470
+ },
471
+ execute: async (args = {}) => {
472
+ const repo = repoOf(args);
473
+ return jsonText(readEvents(repo, { kind: args.kind, task: args.task, limit: args.limit }));
474
+ },
475
+ });
476
+
477
+ registerTextTool({
478
+ name: 'hive_lesson_add',
479
+ description:
480
+ 'Record one Hive lesson in the shared consensus memory (hive lesson add). '
481
+ + 'Write a lesson at the end of an episode; before planning, read them with hive_recall. '
482
+ + 'status=hypothesis|confirmed|superseded; scope is a path glob or resource key.',
483
+ parameters: {
484
+ repo: repoParameter,
485
+ text: { type: 'string', description: 'What was learned, in one or two sentences.' },
486
+ scope: { type: 'string', description: 'Path glob or scope key the lesson applies to (default *).' },
487
+ evidence: { type: 'string', description: 'A commit sha, card id, or command that proves it.' },
488
+ status: { type: 'string', enum: ['hypothesis', 'confirmed', 'superseded'], description: 'Lesson confidence.' },
489
+ },
490
+ execute: async (args = {}, exec) => {
491
+ const repo = repoOf(args);
492
+ const output = await commands.lessonAdd(repo, {
493
+ text: args.text,
494
+ scope: args.scope,
495
+ evidence: args.evidence,
496
+ status: args.status,
497
+ }, { signal: exec?.signal, session: exec?.agent?.session });
498
+ return jsonText({ ok: true, output });
499
+ },
500
+ });
501
+
502
+ registerTextTool({
503
+ name: 'hive_recall',
504
+ description: 'Read the Hive lessons that apply to a path or query (hive recall --json).',
505
+ parameters: {
506
+ repo: repoParameter,
507
+ query: { type: 'string', description: 'Path, glob or free-text query.' },
508
+ },
509
+ execute: async (args = {}, exec) => {
510
+ const repo = repoOf(args);
511
+ if (typeof args.query !== 'string' || args.query.trim() === '') throw new Error('hive_recall needs query');
512
+ return jsonText(await commands.recall(repo, args.query, {
513
+ signal: exec?.signal,
514
+ session: exec?.agent?.session,
515
+ }));
516
+ },
517
+ });
518
+
519
+ registerTextTool({
520
+ name: 'hive_roles',
521
+ description:
522
+ 'Inspect or change Hive roles in .hive/roles.yaml: action=list|add|rm. '
523
+ + 'add validates the name and writes .hive/roles/<name>.md; force=true updates an existing role. '
524
+ + 'Role changes are configuration, not code — the queen may make them, but they are durable decisions worth a lesson.',
525
+ parameters: {
526
+ repo: repoParameter,
527
+ action: { type: 'string', enum: ['list', 'add', 'rm'], description: 'list | add | rm.' },
528
+ name: { type: 'string', description: 'Role name (add/rm), e.g. architect or reviewer.' },
529
+ adapter: { type: 'string', enum: ['dsh', 'claude', 'codex'], description: 'add: coding host.' },
530
+ model: { type: 'string', description: 'add: model id passed to the adapter.' },
531
+ prompt: { type: 'string', description: 'add: contract file path.' },
532
+ description: { type: 'string', description: 'add: replaces the ## Contract placeholder in the new role file.' },
533
+ force: { type: 'boolean', description: 'add: update an existing role and rewrite its contract.' },
534
+ },
535
+ execute: async (args = {}, exec) => {
536
+ const repo = repoOf(args);
537
+ const options = { signal: exec?.signal, session: exec?.agent?.session };
538
+ const action = String(args.action ?? '');
539
+ if (action === 'list') return jsonText(await commands.rolesList(repo, options));
540
+ if (action === 'add') {
541
+ return jsonText({
542
+ ok: true,
543
+ output: await commands.rolesAdd(repo, {
544
+ name: args.name,
545
+ adapter: args.adapter,
546
+ model: args.model,
547
+ prompt: args.prompt,
548
+ description: args.description,
549
+ force: args.force,
550
+ }, options),
551
+ });
552
+ }
553
+ if (action === 'rm') {
554
+ if (typeof args.name !== 'string') throw new Error('hive_roles rm needs name');
555
+ return jsonText({ ok: true, output: await commands.rolesRemove(repo, args.name, options) });
556
+ }
557
+ throw new Error('hive_roles action must be list, add or rm');
558
+ },
559
+ });
560
+
561
+ registerTextTool({
562
+ name: 'hive_supervisor_control',
563
+ description:
564
+ 'Control the resident Hive supervisor in one repository: action=status|pause|resume|limits. '
565
+ + 'pause/resume throttle dispatch for that repository; limits sets persisted per-role worker caps '
566
+ + '({ role: n }, 0 pauses the role) in <repo>/.hive/limits.json. The queen uses these instead of editing the board.',
567
+ parameters: {
568
+ repo: repoParameter,
569
+ action: { type: 'string', enum: ['status', 'pause', 'resume', 'limits'], description: 'status | pause | resume | limits.' },
570
+ reason: { type: 'string', description: 'pause: why dispatch is throttled.' },
571
+ roleLimits: {
572
+ type: 'object',
573
+ additionalProperties: { type: 'number' },
574
+ description: 'limits: role -> integer 0..999 (0 pauses the role).',
575
+ },
576
+ },
577
+ execute: async (args = {}) => {
578
+ const action = String(args.action ?? '');
579
+ if (action === 'status') return jsonText(supervisor.status());
580
+ const repo = repoOf(args);
581
+ const key = normalizeRepoKey(repo);
582
+ if (!supervisor.hasRepo(key)) throw new Error('unknown repository ' + JSON.stringify(key));
583
+ if (action === 'pause') return jsonText({ ok: true, repo: supervisor.pause(key, args.reason ?? 'paused by the queen') });
584
+ if (action === 'resume') return jsonText({ ok: true, repo: supervisor.resume(key) });
585
+ if (action === 'limits') {
586
+ const roleLimits = args.roleLimits;
587
+ if (roleLimits === null || typeof roleLimits !== 'object' || Array.isArray(roleLimits)) {
588
+ throw new Error('hive_supervisor_control limits needs roleLimits { role: n }');
589
+ }
590
+ return jsonText({ ok: true, repo: supervisor.setRoleLimits(key, roleLimits) });
591
+ }
592
+ throw new Error('hive_supervisor_control action must be status, pause, resume or limits');
593
+ },
594
+ });
595
+
596
+ registerTextTool({
597
+ name: 'hive_intervene',
598
+ description:
599
+ 'Act on a stuck card and record the decision as a queen_intervention event { card, action, reason }. '
600
+ + 'action=reopen|split|reassign|pause|fail|guide|remove|rebuild|escalate. '
601
+ + 'reopen writes the guidance into the card reason, which the next worker prompt carries verbatim — the main guidance channel. '
602
+ + 'split/reassign create fine-grained cards from `cards` (each needs title + acceptance) and reopen the original with the new ids. '
603
+ + 'remove deletes a card whose content has no value, recording its title/state/scope in the event first — a deleted card never disappears silently. '
604
+ + 'rebuild deletes and recreates a card whose title/scope/acceptance/dependencies were wrong; the new cards reference the old id in reason/after and the old id is recorded in the event. '
605
+ + 'pause pauses dispatch for the repository (external dependency missing). fail only confirms a card a worker already failed (the queen never changes a card state). '
606
+ + 'guide delivers a guidance message to a live worker Session (see hive_tasks show lastRun.sessionId). escalate records that a human decision is needed. '
607
+ + 'A reason is mandatory. After more than ' + String(INTERVENTION_ESCALATE_AFTER) + ' interventions on one card the runner records a queen_escalation and raises the red-flag anomaly; a card may be rebuilt at most ' + String(REBUILD_LIMIT) + ' times.',
608
+ parameters: {
609
+ repo: repoParameter,
610
+ action: {
611
+ type: 'string',
612
+ enum: ['reopen', 'split', 'reassign', 'pause', 'fail', 'guide', 'remove', 'rebuild', 'escalate'],
613
+ description: 'What the queen decides to do.',
614
+ },
615
+ card: { type: 'string', description: 'The stuck card id.' },
616
+ reason: { type: 'string', description: 'Required: the diagnosis, the evidence, and the guidance for the next attempt or the decision.' },
617
+ cards: {
618
+ type: 'array',
619
+ items: { type: 'object', additionalProperties: true, description: 'New card: { title, acceptance, role?, scope?, after?, priority?, tags?, goal? }' },
620
+ description: 'split/reassign/rebuild: fine-grained replacement cards (acceptance required in each).',
621
+ },
622
+ role: { type: 'string', description: 'reassign: role for the replacement cards when a card does not name one.' },
623
+ sessionId: { type: 'string', description: 'guide: live worker Session id to deliver the guidance to.' },
624
+ },
625
+ execute: async (args = {}, exec) => {
626
+ const repo = repoOf(args);
627
+ const options = { signal: exec?.signal, session: exec?.agent?.session };
628
+ const action = String(args.action ?? '');
629
+ const cardId = typeof args.card === 'string' ? args.card.trim() : '';
630
+ if (cardId === '') throw new Error('hive_intervene needs card');
631
+ if (typeof args.reason !== 'string' || args.reason.trim() === '') {
632
+ throw new Error('hive_intervene needs reason: the diagnosis and the guidance');
633
+ }
634
+ const card = await commands.show(repo, cardId, options);
635
+ if (card === null || card === undefined) throw new Error('no such card: ' + cardId);
636
+ const eventsBefore = readEvents(repo, { limit: 500 });
637
+ const newCards = [];
638
+ let delivery;
639
+ let removed = null;
640
+ if (action === 'reopen') {
641
+ await commands.reopen(repo, cardId, { reason: args.reason }, options);
642
+ } else if (action === 'split' || action === 'reassign' || action === 'rebuild') {
643
+ if (action === 'rebuild' && (rebuildCounts(eventsBefore).get(cardId) ?? 0) >= REBUILD_LIMIT) {
644
+ throw new Error('card ' + cardId + ' was already rebuilt ' + String(REBUILD_LIMIT) + ' times; escalate it to a human decision instead');
645
+ }
646
+ if (!Array.isArray(args.cards) || args.cards.length === 0) {
647
+ throw new Error(action + ' needs cards: a non-empty array of { title, acceptance, ... }');
648
+ }
649
+ for (const draft of args.cards) {
650
+ if (draft === null || typeof draft !== 'object') throw new Error(action + ' cards must be objects');
651
+ const created = await commands.add(repo, {
652
+ title: draft.title,
653
+ role: draft.role ?? (action === 'reassign' ? args.role : undefined),
654
+ scope: draft.scope,
655
+ after: draft.after,
656
+ priority: draft.priority,
657
+ goal: draft.goal,
658
+ acceptance: draft.acceptance,
659
+ tags: draft.tags,
660
+ }, options);
661
+ if (created !== null && typeof created === 'object' && typeof created.id === 'string') newCards.push(created.id);
662
+ }
663
+ removed = { title: card.title, state: card.state, scope: card.scope };
664
+ if (action === 'rebuild') {
665
+ await commands.remove(repo, cardId, options);
666
+ } else {
667
+ await commands.reopen(repo, cardId, {
668
+ reason: args.reason + ' | replacement cards: ' + newCards.join(', '),
669
+ }, options);
670
+ }
671
+ } else if (action === 'remove') {
672
+ removed = { title: card.title, state: card.state, scope: card.scope };
673
+ await commands.remove(repo, cardId, options);
674
+ } else if (action === 'pause') {
675
+ const key = normalizeRepoKey(repo);
676
+ if (!supervisor.hasRepo(key)) throw new Error('unknown repository ' + JSON.stringify(key));
677
+ supervisor.pause(key, args.reason);
678
+ } else if (action === 'fail') {
679
+ if (card.state !== 'failed') {
680
+ throw new Error(
681
+ 'hive_intervene fail only confirms a card a worker already failed; card ' + cardId + ' is ' + card.state
682
+ + ' (the queen never transitions card states)',
683
+ );
684
+ }
685
+ } else if (action === 'guide') {
686
+ if (typeof args.sessionId !== 'string' || args.sessionId === '') {
687
+ throw new Error('hive_intervene guide needs sessionId (see hive_tasks show lastRun.sessionId)');
688
+ }
689
+ delivery = deliverToSession({ ctx }, args.sessionId, '[hive queen guidance]' + NL + NL + args.reason, { prefer: 'steer' });
690
+ if (delivery.delivered !== true) {
691
+ throw new Error('cannot deliver guidance: ' + String(delivery.reason ?? 'unknown'));
692
+ }
693
+ } else if (action !== 'escalate') {
694
+ throw new Error('hive_intervene action must be reopen, split, reassign, pause, fail, guide, remove, rebuild or escalate');
695
+ }
696
+ const event = appendIntervention(repo, {
697
+ card: cardId,
698
+ action,
699
+ reason: args.reason,
700
+ newCards,
701
+ removed,
702
+ sessionId: args.sessionId,
703
+ });
704
+ const events = readEvents(repo, { limit: 500 });
705
+ const count = interventionCounts(events).get(cardId) ?? 1;
706
+ let escalated = false;
707
+ if (count > INTERVENTION_ESCALATE_AFTER && card.state !== 'done' && !escalatedCards(events).has(cardId)) {
708
+ try {
709
+ appendEscalation(repo, {
710
+ card: cardId,
711
+ reason: 'queen intervened ' + count + ' times without progress; needs a human decision (state ' + card.state + ')',
712
+ interventions: count,
713
+ });
714
+ escalated = true;
715
+ } catch (error) {
716
+ log('warn', 'escalation write failed: ' + (error instanceof Error ? error.message : String(error)));
717
+ }
718
+ if (escalated) {
719
+ anomalies.push({
720
+ kind: ESCALATION_KIND,
721
+ repo,
722
+ cardId,
723
+ role: typeof card.role === 'string' ? card.role : null,
724
+ summary: 'card needs a human decision',
725
+ detail: 'intervened ' + count + ' times: ' + args.reason,
726
+ });
727
+ if (resolved.notifyQueen) patrol.scheduleFlush();
728
+ }
729
+ }
730
+ return jsonText({
731
+ ok: true,
732
+ action,
733
+ card: cardId,
734
+ event,
735
+ newCards,
736
+ interventions: count,
737
+ escalated,
738
+ delivery: delivery ?? null,
739
+ ...(escalated
740
+ ? { message: 'This card needs a human decision: more than ' + String(INTERVENTION_ESCALATE_AFTER) + ' interventions without progress. Report it to the human.' }
741
+ : {}),
742
+ });
743
+ },
744
+ });
745
+ registerTextTool({
746
+ name: 'hive_anomalies',
747
+ description:
748
+ 'Read or acknowledge the supervisor anomaly digest queue. action=list returns the pending items '
749
+ + '(kind, repo, card, detail, count, deliveredAt); action=ack marks ids delivered; '
750
+ + 'action=patrol runs one audit tick now (reports auto-paused repositories, stalled heartbeats, '
751
+ + 'workers past their deadline) and returns the delivery result. The supervisor injects the same digest '
752
+ + 'into the registered queen Session; entries stay pending while no queen Session is live.',
753
+ parameters: {
754
+ action: { type: 'string', enum: ['list', 'ack', 'patrol'], description: 'list | ack | patrol.' },
755
+ ids: { type: 'array', items: { type: 'string' }, description: 'ack: anomaly ids to mark delivered.' },
756
+ all: { type: 'boolean', description: 'list: include already delivered items.' },
757
+ limit: { type: 'number', description: 'list: maximum entries.' },
758
+ },
759
+ execute: async (args = {}) => {
760
+ const action = String(args.action ?? 'list');
761
+ if (action === 'list') {
762
+ return jsonText({
763
+ pending: anomalies.pendingCount(),
764
+ items: anomalies.list({ pendingOnly: args.all !== true, limit: args.limit }),
765
+ });
766
+ }
767
+ if (action === 'ack') {
768
+ if (!Array.isArray(args.ids) || args.ids.length === 0) throw new Error('hive_anomalies ack needs ids');
769
+ return jsonText({ ok: true, changed: anomalies.markDelivered(args.ids) });
770
+ }
771
+ if (action === 'patrol') return jsonText({ ok: true, ...(await patrol.patrol()) });
772
+ throw new Error('hive_anomalies action must be list, ack or patrol');
773
+ },
774
+ });
195
775
  }