dsh-hive-runner 0.6.7 → 0.8.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]
@@ -59,6 +109,7 @@ export function apply(ctx, config = {}) {
59
109
  commands,
60
110
  limitFor: (repo, role) => limits.limitFor(repo, role),
61
111
  parentProvider: (explicit) => parentProviderImpl(explicit),
112
+ onAnomaly: (event) => recordAnomaly(event),
62
113
  log,
63
114
  });
64
115
  parentProviderImpl = async (explicit) => {
@@ -67,6 +118,30 @@ export function apply(ctx, config = {}) {
67
118
  return { agent, source: 'queen', sessionId };
68
119
  };
69
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,
143
+ });
144
+
70
145
  const supervisor = new HiveSupervisor({
71
146
  repos: resolved.repos,
72
147
  paused: resolved.paused,
@@ -85,26 +160,63 @@ export function apply(ctx, config = {}) {
85
160
  ? () => discoverRepos({ roots: resolved.discoverRoots, depth: resolved.discoverDepth })
86
161
  : undefined,
87
162
  listReady: runner.listReady,
163
+ listAll: (repo, options = {}) => commands.list(repo, {}, options),
88
164
  runCard: runner.runCard,
89
165
  preflight: runner.preflight,
90
166
  activeRuns: (repo) => runner.activeRuns(repo),
91
167
  queenSession,
92
168
  readMode: (repo) => commands.mode(repo),
169
+ onAnomaly: (event) => recordAnomaly(event),
170
+ onQueenSession: () => {
171
+ if (patrol !== undefined) patrol.flushPending();
172
+ },
173
+ pendingAnomalies: () => anomalies.pendingCount(),
93
174
  logger: console,
94
175
  debug: resolved.debug,
95
176
  });
96
177
 
97
- // Cordis service + effect-owned timer: the supervisor follows the plugin's
98
- // 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.
99
205
  ctx.provide('hiveSupervisor', supervisor);
100
206
  ctx.effect(() => {
101
207
  supervisor.start();
102
- return () => supervisor.stop();
208
+ patrol.start();
209
+ return () => {
210
+ patrol.stop();
211
+ supervisor.stop();
212
+ };
103
213
  });
104
214
 
105
215
  // Optional: the Web/desktop composition provides `connection`. In a headless
106
216
  // CLI composition without it the supervisor still runs and the tools work.
107
- ctx.inject(['connection'], (scope) => scope.connection.fetch.register(createHiveRunnerRoute(supervisor)));
217
+ ctx.inject(['connection'], (scope) => scope.connection.fetch.register(
218
+ createHiveRunnerRoute(supervisor, { anomalies }),
219
+ ));
108
220
 
109
221
  if (resolved.debug) {
110
222
  console.info('[hive-runner] repositories:', resolved.repos.length, 'autoDiscover:', resolved.autoDiscover);
@@ -121,7 +233,23 @@ export function apply(ctx, config = {}) {
121
233
  );
122
234
  }
123
235
 
124
- 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({
125
253
  name: 'hive_run_round',
126
254
  description:
127
255
  'Run one Hive round now in one repository: fetch every ready card and run card workers bounded by the '
@@ -129,11 +257,10 @@ export function apply(ctx, config = {}) {
129
257
  + 'then record done or fail. DSH subagent capacity rejections stay queued and are retried, not dropped. '
130
258
  + 'Returns per-card results and per-role state as JSON. The resident supervisor runs these rounds on its own schedule.',
131
259
  parameters: {
132
- repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
260
+ repo: repoParameter,
133
261
  ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
134
262
  agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
135
263
  },
136
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
137
264
  execute: async (args = {}, exec) => {
138
265
  const repo = repoOf(args);
139
266
  const signal = exec?.signal;
@@ -143,8 +270,11 @@ export function apply(ctx, config = {}) {
143
270
  }
144
271
  runner.preflight(repo);
145
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;
146
276
  const outcome = await drainQueue({
147
- queue: cards.map((card) => ({ role: card.role, card, claimed: false })),
277
+ queue: dispatchable.map((card) => ({ role: card.role, card, claimed: false })),
148
278
  roleNames: limits.rolesFor(repo, cards.map((card) => card.role)),
149
279
  limitFor: (role) => limits.limitFor(repo, role),
150
280
  runCard: (item) => runner.runCard({
@@ -161,24 +291,24 @@ export function apply(ctx, config = {}) {
161
291
  signal,
162
292
  });
163
293
  if (outcome.error !== undefined) throw outcome.error;
164
- return JSON.stringify({
294
+ return jsonText({
165
295
  repo,
296
+ gate: gateResult.gate,
166
297
  results: outcome.results,
167
298
  state: outcome.state,
168
299
  queued: outcome.queue.length,
169
- }, null, 2);
300
+ });
170
301
  },
171
- }));
302
+ });
172
303
 
173
- ctx.tools.register(defineTool({
304
+ registerTextTool({
174
305
  name: 'hive_tasks_ready',
175
306
  description: 'List the Hive task cards that are ready right now in one repository, best first.',
176
307
  parameters: {
177
- repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
308
+ repo: repoParameter,
178
309
  role: { type: 'string', description: 'Filter by Hive role, for example coder or tester.' },
179
310
  limit: { type: 'number', description: 'Maximum number of cards.' },
180
311
  },
181
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
182
312
  execute: async (args = {}, exec) => {
183
313
  const repo = repoOf(args);
184
314
  const cards = await commands.ready(repo, {
@@ -187,31 +317,545 @@ export function apply(ctx, config = {}) {
187
317
  signal: exec?.signal,
188
318
  session: exec?.agent?.session,
189
319
  });
190
- return JSON.stringify(cards, null, 2);
320
+ return jsonText(cards);
191
321
  },
192
- }));
322
+ });
193
323
 
194
- ctx.tools.register(defineTool({
324
+ registerTextTool({
195
325
  name: 'hive_board',
196
326
  description: 'Show which agents are on the Hive board right now in one repository.',
197
- parameters: {
198
- repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
199
- },
200
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
327
+ parameters: { repo: repoParameter },
201
328
  execute: async (args = {}, exec) => {
202
329
  const repo = repoOf(args);
203
330
  const board = await commands.board(repo, { signal: exec?.signal, session: exec?.agent?.session });
204
- return JSON.stringify(board, null, 2);
331
+ return jsonText(board);
205
332
  },
206
- }));
333
+ });
207
334
 
208
- ctx.tools.register(defineTool({
335
+ registerTextTool({
209
336
  name: 'hive_supervisor_status',
210
337
  description:
211
338
  'Show the resident Hive supervisor state: per-repository state (idle/running/backoff/paused), '
212
- + '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.',
213
342
  parameters: {},
214
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
215
- execute: async () => JSON.stringify(supervisor.status(), null, 2),
216
- }));
217
- }
343
+ execute: async () => jsonText(supervisor.status()),
344
+ });
345
+
346
+ registerTextTool({
347
+ name: 'hive_tasks',
348
+ description:
349
+ 'Manage the Hive task tree without claiming tasks. action=list|show|add|edit|split|supersede|reopen|retry|rm. '
350
+ + 'list/show return the task plus its last-run record (status, heartbeat, output tail, overlaps) for triage; '
351
+ + 'add creates a task (title required; acceptance required unless draft=true; scope, after, priority, tags, reviewOf optional); '
352
+ + 'edit partially updates a pending/failed task — title, role, priority, acceptance, scope, after, tags and the superseded flag (goal and draft cannot be edited; hive-tasks 1.9 requires pending/failed) — the queen adjusts the tree as the goal evolves; '
353
+ + 'split atomically replaces a pending/failed task with at least two fine-grained tasks and marks the original superseded (replacedBy = first child); '
354
+ + 'supersede marks a task (including a claimed/running one) as superseded without changing its state and requires a reason; '
355
+ + 'reopen resets any task to pending with an attempt+1 and an optional reason; retry moves a failed task back to pending; '
356
+ + 'rm deletes a task (the CLI refuses a claimed task — reopen or wait for the claim to expire first). '
357
+ + 'The queen uses these for ordering, splitting, goal evolution and remediation; workers alone claim and finish tasks.',
358
+ parameters: {
359
+ repo: repoParameter,
360
+ action: {
361
+ type: 'string',
362
+ enum: ['list', 'show', 'add', 'edit', 'split', 'supersede', 'reopen', 'retry', 'rm'],
363
+ description: 'What to do. list/show read; add/edit/split/supersede/reopen/retry/rm change the board.',
364
+ },
365
+ id: { type: 'string', description: 'Task id (show/edit/split/supersede/reopen/retry/rm).' },
366
+ state: { type: 'string', enum: ['pending', 'claimed', 'done', 'failed'], description: 'list: state filter.' },
367
+ role: { type: 'string', description: 'list/add/edit: role filter or new role for the task(s).' },
368
+ title: { type: 'string', description: 'add/edit: task title.' },
369
+ goal: { type: 'string', description: 'add: goal of the task (hive-tasks 1.9 edit cannot change it).' },
370
+ scope: { type: 'array', items: { type: 'string' }, description: 'add/edit: paths or resource keys (edit replaces the list; the runner translates it to scope add/remove).' },
371
+ after: { type: 'array', items: { type: 'string' }, description: 'add/edit: task ids that must be done first (edit replaces the list).' },
372
+ priority: { type: 'number', description: 'add/edit: higher runs first (-1000..1000).' },
373
+ tags: { type: 'array', items: { type: 'string' }, description: 'add: initial tags. edit: tags to add.' },
374
+ removeTags: { type: 'array', items: { type: 'string' }, description: 'edit: tags to remove.' },
375
+ clearScope: { type: 'boolean', description: 'edit: clear the scope list.' },
376
+ clearAfter: { type: 'boolean', description: 'edit: clear the dependency list.' },
377
+ acceptance: { type: 'string', description: 'add/edit: shell command/assertion that proves the task (required unless draft).' },
378
+ reviewOf: { type: 'string', description: 'add: the task id this task reviews.' },
379
+ draft: { type: 'boolean', description: 'add: create a draft (no acceptance needed, never dispatched). Not editable afterwards.' },
380
+ superseded: { type: 'boolean', description: 'edit: mark/unmark superseded (superseded tasks are never dispatched).' },
381
+ cards: {
382
+ type: 'array',
383
+ items: { type: 'object', additionalProperties: true, description: 'New task: { title, role?, scope?, acceptance?, after? }' },
384
+ description: 'split: at least two fine-grained replacement tasks; each inherits the parent scope/role/priority/tags/acceptance unless overridden.',
385
+ },
386
+ replacedBy: { type: 'string', description: 'supersede: the task id that replaces this one.' },
387
+ reason: { type: 'string', description: 'reopen/split/supersede: why the task changes (supersede requires it).' },
388
+ },
389
+ execute: async (args = {}, exec) => {
390
+ const repo = repoOf(args);
391
+ const options = { signal: exec?.signal, session: exec?.agent?.session };
392
+ const action = String(args.action ?? '');
393
+ if (action === 'list') {
394
+ const cards = await commands.list(repo, { state: args.state, role: args.role }, options);
395
+ return jsonText(cards.map((card) => withLastRun(repo, card)));
396
+ }
397
+ if (action === 'show') {
398
+ if (typeof args.id !== 'string') throw new Error('hive_tasks show needs an id');
399
+ const card = await commands.show(repo, args.id, options);
400
+ if (card === null || card === undefined) throw new Error('no such card: ' + args.id);
401
+ return jsonText(withLastRun(repo, card));
402
+ }
403
+ if (action === 'add') {
404
+ const card = await commands.add(repo, {
405
+ title: args.title,
406
+ role: args.role,
407
+ scope: args.scope,
408
+ after: args.after,
409
+ priority: args.priority,
410
+ goal: args.goal,
411
+ acceptance: args.acceptance,
412
+ tags: args.tags,
413
+ reviewOf: args.reviewOf,
414
+ draft: args.draft,
415
+ }, options);
416
+ return jsonText({ ok: true, card });
417
+ }
418
+ if (action === 'edit') {
419
+ if (typeof args.id !== 'string') throw new Error('hive_tasks edit needs an id');
420
+ if (args.goal !== undefined && args.goal !== null && args.goal !== '') {
421
+ throw new Error('hive-tasks 1.9 edit cannot change goal; split or recreate the task instead');
422
+ }
423
+ if (args.draft === true || args.draft === false) {
424
+ throw new Error('hive-tasks 1.9 edit cannot change the draft flag; draft is set at creation');
425
+ }
426
+ const patch = {
427
+ title: args.title,
428
+ role: args.role,
429
+ priority: args.priority,
430
+ acceptance: args.acceptance,
431
+ superseded: args.superseded,
432
+ reason: args.reason,
433
+ };
434
+ // Scope is replace-style at the tool level: read the current card and
435
+ // translate into the CLI's incremental --scope-add/--scope-remove.
436
+ if (args.clearScope === true || Array.isArray(args.scope)) {
437
+ const current = await commands.show(repo, args.id, options);
438
+ if (current === null || current === undefined) throw new Error('no such task: ' + args.id);
439
+ const before = Array.isArray(current.scope) ? current.scope : [];
440
+ const desired = args.clearScope === true ? [] : args.scope;
441
+ patch.scopeAdd = desired.filter((path) => !before.includes(path));
442
+ patch.scopeRemove = before.filter((path) => !desired.includes(path));
443
+ }
444
+ if (args.clearAfter === true || Array.isArray(args.after)) {
445
+ patch.afterSet = args.clearAfter === true ? [] : args.after;
446
+ }
447
+ const addTags = Array.isArray(args.tags) ? args.tags.map((tag) => '+' + String(tag).trim()) : [];
448
+ const removeTags = Array.isArray(args.removeTags) ? args.removeTags.map((tag) => '-' + String(tag).trim()) : [];
449
+ if (addTags.length > 0 || removeTags.length > 0) patch.tagMutations = [...addTags, ...removeTags];
450
+ const card = await commands.edit(repo, args.id, patch, options);
451
+ return jsonText({ ok: true, card });
452
+ }
453
+ if (action === 'split') {
454
+ if (typeof args.id !== 'string') throw new Error('hive_tasks split needs an id');
455
+ if (!Array.isArray(args.cards) || args.cards.length < 2) {
456
+ throw new Error('hive_tasks split needs cards: at least two fine-grained card drafts');
457
+ }
458
+ return jsonText(await commands.split(repo, args.id, args.cards, { reason: args.reason, ...options }));
459
+ }
460
+ if (action === 'supersede') {
461
+ if (typeof args.id !== 'string') throw new Error('hive_tasks supersede needs an id');
462
+ if (typeof args.reason !== 'string' || args.reason.trim() === '') {
463
+ throw new Error('hive_tasks supersede needs a reason (the CLI requires it)');
464
+ }
465
+ return jsonText({
466
+ ok: true,
467
+ card: await commands.supersede(repo, args.id, { reason: args.reason, replacedBy: args.replacedBy }, options),
468
+ });
469
+ }
470
+ if (action === 'reopen') {
471
+ if (typeof args.id !== 'string') throw new Error('hive_tasks reopen needs an id');
472
+ return jsonText({ ok: true, card: await commands.reopen(repo, args.id, { reason: args.reason }, options) });
473
+ }
474
+ if (action === 'retry') {
475
+ if (typeof args.id !== 'string') throw new Error('hive_tasks retry needs an id');
476
+ return jsonText({ ok: true, card: await commands.retry(repo, args.id, options) });
477
+ }
478
+ if (action === 'rm') {
479
+ if (typeof args.id !== 'string') throw new Error('hive_tasks rm needs an id');
480
+ return jsonText({ ok: true, deleted: args.id, output: await commands.remove(repo, args.id, options) });
481
+ }
482
+ throw new Error('hive_tasks action must be one of list, show, add, edit, split, supersede, reopen, retry, rm');
483
+ },
484
+ });
485
+
486
+ registerTextTool({
487
+ name: 'hive_arch_review',
488
+ description:
489
+ 'Record the queen architecture review of one accepted (done) card. Appends an arch_review event '
490
+ + '{ card, verdict, findings } to .hive/events.jsonl — never edits the card. '
491
+ + 'verdict=pass|reject; a reject needs at least one actionable finding naming the file and what to change. '
492
+ + 'On reject, do not delete the card: reopen it with a reason and add one or more fine-grained fix cards.',
493
+ parameters: {
494
+ repo: repoParameter,
495
+ card: { type: 'string', description: 'Card id being reviewed (must be done).' },
496
+ verdict: { type: 'string', enum: ['pass', 'reject'], description: 'Review verdict.' },
497
+ findings: {
498
+ type: 'array',
499
+ items: { type: 'string' },
500
+ description: 'Actionable findings: which file/module and what to change. Required for reject.',
501
+ },
502
+ summary: { type: 'string', description: 'One-line summary of the review.' },
503
+ },
504
+ execute: async (args = {}, exec) => {
505
+ const repo = repoOf(args);
506
+ if (typeof args.card !== 'string' || args.card.trim() === '') throw new Error('hive_arch_review needs card');
507
+ const card = await commands.show(repo, args.card.trim(), {
508
+ signal: exec?.signal,
509
+ session: exec?.agent?.session,
510
+ });
511
+ if (card === null || card === undefined) throw new Error('no such card: ' + args.card);
512
+ if (card.state !== 'done') {
513
+ throw new Error('architecture review runs after acceptance: card ' + card.id + ' is ' + card.state + ', not done');
514
+ }
515
+ const event = appendArchReview(repo, {
516
+ card: card.id,
517
+ verdict: args.verdict,
518
+ findings: args.findings,
519
+ summary: args.summary,
520
+ });
521
+ return jsonText({ ok: true, event });
522
+ },
523
+ });
524
+
525
+ registerTextTool({
526
+ name: 'hive_events',
527
+ description:
528
+ 'Read the tail of .hive/events.jsonl (newest first), optionally filtered by kind or card. '
529
+ + 'Use kind=arch_review to see which accepted cards were reviewed and with what findings.',
530
+ parameters: {
531
+ repo: repoParameter,
532
+ kind: { type: 'string', description: 'Filter by event kind, for example arch_review.' },
533
+ task: { type: 'string', description: 'Filter by card id.' },
534
+ limit: { type: 'number', description: 'Maximum number of events (default 50).' },
535
+ },
536
+ execute: async (args = {}) => {
537
+ const repo = repoOf(args);
538
+ return jsonText(readEvents(repo, { kind: args.kind, task: args.task, limit: args.limit }));
539
+ },
540
+ });
541
+
542
+ registerTextTool({
543
+ name: 'hive_lesson_add',
544
+ description:
545
+ 'Record one Hive lesson in the shared consensus memory (hive lesson add). '
546
+ + 'Write a lesson at the end of an episode; before planning, read them with hive_recall. '
547
+ + 'status=hypothesis|confirmed|superseded; scope is a path glob or resource key.',
548
+ parameters: {
549
+ repo: repoParameter,
550
+ text: { type: 'string', description: 'What was learned, in one or two sentences.' },
551
+ scope: { type: 'string', description: 'Path glob or scope key the lesson applies to (default *).' },
552
+ evidence: { type: 'string', description: 'A commit sha, card id, or command that proves it.' },
553
+ status: { type: 'string', enum: ['hypothesis', 'confirmed', 'superseded'], description: 'Lesson confidence.' },
554
+ },
555
+ execute: async (args = {}, exec) => {
556
+ const repo = repoOf(args);
557
+ const output = await commands.lessonAdd(repo, {
558
+ text: args.text,
559
+ scope: args.scope,
560
+ evidence: args.evidence,
561
+ status: args.status,
562
+ }, { signal: exec?.signal, session: exec?.agent?.session });
563
+ return jsonText({ ok: true, output });
564
+ },
565
+ });
566
+
567
+ registerTextTool({
568
+ name: 'hive_recall',
569
+ description: 'Read the Hive lessons that apply to a path or query (hive recall --json).',
570
+ parameters: {
571
+ repo: repoParameter,
572
+ query: { type: 'string', description: 'Path, glob or free-text query.' },
573
+ },
574
+ execute: async (args = {}, exec) => {
575
+ const repo = repoOf(args);
576
+ if (typeof args.query !== 'string' || args.query.trim() === '') throw new Error('hive_recall needs query');
577
+ return jsonText(await commands.recall(repo, args.query, {
578
+ signal: exec?.signal,
579
+ session: exec?.agent?.session,
580
+ }));
581
+ },
582
+ });
583
+
584
+ registerTextTool({
585
+ name: 'hive_roles',
586
+ description:
587
+ 'Inspect or change Hive roles in .hive/roles.yaml: action=list|add|rm. '
588
+ + 'add validates the name and writes .hive/roles/<name>.md; force=true updates an existing role. '
589
+ + 'Role changes are configuration, not code — the queen may make them, but they are durable decisions worth a lesson.',
590
+ parameters: {
591
+ repo: repoParameter,
592
+ action: { type: 'string', enum: ['list', 'add', 'rm'], description: 'list | add | rm.' },
593
+ name: { type: 'string', description: 'Role name (add/rm), e.g. architect or reviewer.' },
594
+ adapter: { type: 'string', enum: ['dsh', 'claude', 'codex'], description: 'add: coding host.' },
595
+ model: { type: 'string', description: 'add: model id passed to the adapter.' },
596
+ prompt: { type: 'string', description: 'add: contract file path.' },
597
+ description: { type: 'string', description: 'add: replaces the ## Contract placeholder in the new role file.' },
598
+ force: { type: 'boolean', description: 'add: update an existing role and rewrite its contract.' },
599
+ },
600
+ execute: async (args = {}, exec) => {
601
+ const repo = repoOf(args);
602
+ const options = { signal: exec?.signal, session: exec?.agent?.session };
603
+ const action = String(args.action ?? '');
604
+ if (action === 'list') return jsonText(await commands.rolesList(repo, options));
605
+ if (action === 'add') {
606
+ return jsonText({
607
+ ok: true,
608
+ output: await commands.rolesAdd(repo, {
609
+ name: args.name,
610
+ adapter: args.adapter,
611
+ model: args.model,
612
+ prompt: args.prompt,
613
+ description: args.description,
614
+ force: args.force,
615
+ }, options),
616
+ });
617
+ }
618
+ if (action === 'rm') {
619
+ if (typeof args.name !== 'string') throw new Error('hive_roles rm needs name');
620
+ return jsonText({ ok: true, output: await commands.rolesRemove(repo, args.name, options) });
621
+ }
622
+ throw new Error('hive_roles action must be list, add or rm');
623
+ },
624
+ });
625
+
626
+ registerTextTool({
627
+ name: 'hive_supervisor_control',
628
+ description:
629
+ 'Control the resident Hive supervisor in one repository: action=status|pause|resume|limits. '
630
+ + 'pause/resume throttle dispatch for that repository; limits sets persisted per-role worker caps '
631
+ + '({ role: n }, 0 pauses the role) in <repo>/.hive/limits.json. The queen uses these instead of editing the board.',
632
+ parameters: {
633
+ repo: repoParameter,
634
+ action: { type: 'string', enum: ['status', 'pause', 'resume', 'limits'], description: 'status | pause | resume | limits.' },
635
+ reason: { type: 'string', description: 'pause: why dispatch is throttled.' },
636
+ roleLimits: {
637
+ type: 'object',
638
+ additionalProperties: { type: 'number' },
639
+ description: 'limits: role -> integer 0..999 (0 pauses the role).',
640
+ },
641
+ },
642
+ execute: async (args = {}) => {
643
+ const action = String(args.action ?? '');
644
+ if (action === 'status') return jsonText(supervisor.status());
645
+ const repo = repoOf(args);
646
+ const key = normalizeRepoKey(repo);
647
+ if (!supervisor.hasRepo(key)) throw new Error('unknown repository ' + JSON.stringify(key));
648
+ if (action === 'pause') return jsonText({ ok: true, repo: supervisor.pause(key, args.reason ?? 'paused by the queen') });
649
+ if (action === 'resume') return jsonText({ ok: true, repo: supervisor.resume(key) });
650
+ if (action === 'limits') {
651
+ const roleLimits = args.roleLimits;
652
+ if (roleLimits === null || typeof roleLimits !== 'object' || Array.isArray(roleLimits)) {
653
+ throw new Error('hive_supervisor_control limits needs roleLimits { role: n }');
654
+ }
655
+ return jsonText({ ok: true, repo: supervisor.setRoleLimits(key, roleLimits) });
656
+ }
657
+ throw new Error('hive_supervisor_control action must be status, pause, resume or limits');
658
+ },
659
+ });
660
+
661
+ registerTextTool({
662
+ name: 'hive_intervene',
663
+ description:
664
+ 'Act on a stuck card and record the decision as a queen_intervention event { card, action, reason }. '
665
+ + 'action=reopen|split|reassign|pause|abort|fail|guide|supersede|remove|rebuild|escalate. '
666
+ + 'reopen writes the guidance into the card reason, which the next worker prompt carries verbatim — the main guidance channel. '
667
+ + 'split atomically replaces a pending/failed task with at least two fine-grained cards from `cards` and marks the original superseded; reassign creates cards for another role and reopens the original. '
668
+ + 'abort stops one live worker on request (the card is recorded failed with the reason); pause is the softer repository-level throttle. '
669
+ + 'supersede marks a card — including a claimed/running one — as superseded without changing its state, so it is never dispatched again. '
670
+ + 'remove deletes a card whose content has no value, recording its title/state/scope in the event first — a deleted card never disappears silently. '
671
+ + '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. '
672
+ + '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). '
673
+ + 'guide delivers a guidance message to a live worker Session (see hive_tasks show lastRun.sessionId). escalate records that a human decision is needed. '
674
+ + '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.',
675
+ parameters: {
676
+ repo: repoParameter,
677
+ action: {
678
+ type: 'string',
679
+ enum: ['reopen', 'split', 'reassign', 'pause', 'abort', 'fail', 'guide', 'supersede', 'remove', 'rebuild', 'escalate'],
680
+ description: 'What the queen decides to do.',
681
+ },
682
+ card: { type: 'string', description: 'The stuck card id.' },
683
+ reason: { type: 'string', description: 'Required: the diagnosis, the evidence, and the guidance for the next attempt or the decision.' },
684
+ cards: {
685
+ type: 'array',
686
+ items: { type: 'object', additionalProperties: true, description: 'New card: { title, acceptance, role?, scope?, after?, priority?, tags?, goal? }' },
687
+ description: 'split/reassign/rebuild: fine-grained replacement cards (acceptance required in each).',
688
+ },
689
+ role: { type: 'string', description: 'reassign: role for the replacement cards when a card does not name one.' },
690
+ sessionId: { type: 'string', description: 'guide: live worker Session id to deliver the guidance to.' },
691
+ },
692
+ execute: async (args = {}, exec) => {
693
+ const repo = repoOf(args);
694
+ const options = { signal: exec?.signal, session: exec?.agent?.session };
695
+ const action = String(args.action ?? '');
696
+ const cardId = typeof args.card === 'string' ? args.card.trim() : '';
697
+ if (cardId === '') throw new Error('hive_intervene needs card');
698
+ if (typeof args.reason !== 'string' || args.reason.trim() === '') {
699
+ throw new Error('hive_intervene needs reason: the diagnosis and the guidance');
700
+ }
701
+ const card = await commands.show(repo, cardId, options);
702
+ if (card === null || card === undefined) throw new Error('no such card: ' + cardId);
703
+ const eventsBefore = readEvents(repo, { limit: 500 });
704
+ const newCards = [];
705
+ let delivery;
706
+ let removed = null;
707
+ if (action === 'reopen') {
708
+ await commands.reopen(repo, cardId, { reason: args.reason }, options);
709
+ } else if (action === 'split') {
710
+ if (!Array.isArray(args.cards) || args.cards.length === 0) {
711
+ throw new Error('split needs at least two fine-grained cards: [{ title, acceptance, ... }, ...]');
712
+ }
713
+ const split = await commands.split(repo, cardId, args.cards, { reason: args.reason, ...options });
714
+ const created = Array.isArray(split?.cards) ? split.cards : [];
715
+ for (const entry of created) {
716
+ const id = entry !== null && typeof entry === 'object' && typeof entry.id === 'string'
717
+ ? entry.id
718
+ : (typeof entry === 'string' ? entry : null);
719
+ if (id !== null) newCards.push(id);
720
+ }
721
+ } else if (action === 'reassign' || action === 'rebuild') {
722
+ if (action === 'rebuild' && (rebuildCounts(eventsBefore).get(cardId) ?? 0) >= REBUILD_LIMIT) {
723
+ throw new Error('card ' + cardId + ' was already rebuilt ' + String(REBUILD_LIMIT) + ' times; escalate it to a human decision instead');
724
+ }
725
+ if (!Array.isArray(args.cards) || args.cards.length === 0) {
726
+ throw new Error(action + ' needs cards: a non-empty array of { title, acceptance, ... }');
727
+ }
728
+ for (const draft of args.cards) {
729
+ if (draft === null || typeof draft !== 'object') throw new Error(action + ' cards must be objects');
730
+ const created = await commands.add(repo, {
731
+ title: draft.title,
732
+ role: draft.role ?? (action === 'reassign' ? args.role : undefined),
733
+ scope: draft.scope,
734
+ after: draft.after,
735
+ priority: draft.priority,
736
+ goal: draft.goal,
737
+ acceptance: draft.acceptance,
738
+ tags: draft.tags,
739
+ }, options);
740
+ if (created !== null && typeof created === 'object' && typeof created.id === 'string') newCards.push(created.id);
741
+ }
742
+ removed = { title: card.title, state: card.state, scope: card.scope };
743
+ if (action === 'rebuild') {
744
+ await commands.remove(repo, cardId, options);
745
+ } else {
746
+ await commands.reopen(repo, cardId, {
747
+ reason: args.reason + ' | replacement cards: ' + newCards.join(', '),
748
+ }, options);
749
+ }
750
+ } else if (action === 'remove') {
751
+ removed = { title: card.title, state: card.state, scope: card.scope };
752
+ await commands.remove(repo, cardId, options);
753
+ } else if (action === 'pause') {
754
+ const key = normalizeRepoKey(repo);
755
+ if (!supervisor.hasRepo(key)) throw new Error('unknown repository ' + JSON.stringify(key));
756
+ supervisor.pause(key, args.reason);
757
+ } else if (action === 'abort') {
758
+ const result = runner.abortCard(repo, cardId, args.reason);
759
+ if (result.aborted !== true) {
760
+ throw new Error('no live worker for card ' + cardId + ' (it may already have finished; use reopen/supersede)');
761
+ }
762
+ } else if (action === 'supersede') {
763
+ await commands.supersede(repo, cardId, { reason: args.reason }, options);
764
+ } else if (action === 'fail') {
765
+ if (card.state !== 'failed') {
766
+ throw new Error(
767
+ 'hive_intervene fail only confirms a card a worker already failed; card ' + cardId + ' is ' + card.state
768
+ + ' (the queen never transitions card states)',
769
+ );
770
+ }
771
+ } else if (action === 'guide') {
772
+ if (typeof args.sessionId !== 'string' || args.sessionId === '') {
773
+ throw new Error('hive_intervene guide needs sessionId (see hive_tasks show lastRun.sessionId)');
774
+ }
775
+ delivery = deliverToSession({ ctx }, args.sessionId, '[hive queen guidance]' + NL + NL + args.reason, { prefer: 'steer' });
776
+ if (delivery.delivered !== true) {
777
+ throw new Error('cannot deliver guidance: ' + String(delivery.reason ?? 'unknown'));
778
+ }
779
+ } else if (action !== 'escalate') {
780
+ throw new Error('hive_intervene action must be reopen, split, reassign, pause, abort, fail, guide, supersede, remove, rebuild or escalate');
781
+ }
782
+ const event = appendIntervention(repo, {
783
+ card: cardId,
784
+ action,
785
+ reason: args.reason,
786
+ newCards,
787
+ removed,
788
+ sessionId: args.sessionId,
789
+ });
790
+ const events = readEvents(repo, { limit: 500 });
791
+ const count = interventionCounts(events).get(cardId) ?? 1;
792
+ let escalated = false;
793
+ if (count > INTERVENTION_ESCALATE_AFTER && card.state !== 'done' && !escalatedCards(events).has(cardId)) {
794
+ try {
795
+ appendEscalation(repo, {
796
+ card: cardId,
797
+ reason: 'queen intervened ' + count + ' times without progress; needs a human decision (state ' + card.state + ')',
798
+ interventions: count,
799
+ });
800
+ escalated = true;
801
+ } catch (error) {
802
+ log('warn', 'escalation write failed: ' + (error instanceof Error ? error.message : String(error)));
803
+ }
804
+ if (escalated) {
805
+ anomalies.push({
806
+ kind: ESCALATION_KIND,
807
+ repo,
808
+ cardId,
809
+ role: typeof card.role === 'string' ? card.role : null,
810
+ summary: 'card needs a human decision',
811
+ detail: 'intervened ' + count + ' times: ' + args.reason,
812
+ });
813
+ if (resolved.notifyQueen) patrol.scheduleFlush();
814
+ }
815
+ }
816
+ return jsonText({
817
+ ok: true,
818
+ action,
819
+ card: cardId,
820
+ event,
821
+ newCards,
822
+ interventions: count,
823
+ escalated,
824
+ delivery: delivery ?? null,
825
+ ...(escalated
826
+ ? { message: 'This card needs a human decision: more than ' + String(INTERVENTION_ESCALATE_AFTER) + ' interventions without progress. Report it to the human.' }
827
+ : {}),
828
+ });
829
+ },
830
+ });
831
+ registerTextTool({
832
+ name: 'hive_anomalies',
833
+ description:
834
+ 'Read or acknowledge the supervisor anomaly digest queue. action=list returns the pending items '
835
+ + '(kind, repo, card, detail, count, deliveredAt); action=ack marks ids delivered; '
836
+ + 'action=patrol runs one audit tick now (reports auto-paused repositories, stalled heartbeats, '
837
+ + 'workers past their deadline) and returns the delivery result. The supervisor injects the same digest '
838
+ + 'into the registered queen Session; entries stay pending while no queen Session is live.',
839
+ parameters: {
840
+ action: { type: 'string', enum: ['list', 'ack', 'patrol'], description: 'list | ack | patrol.' },
841
+ ids: { type: 'array', items: { type: 'string' }, description: 'ack: anomaly ids to mark delivered.' },
842
+ all: { type: 'boolean', description: 'list: include already delivered items.' },
843
+ limit: { type: 'number', description: 'list: maximum entries.' },
844
+ },
845
+ execute: async (args = {}) => {
846
+ const action = String(args.action ?? 'list');
847
+ if (action === 'list') {
848
+ return jsonText({
849
+ pending: anomalies.pendingCount(),
850
+ items: anomalies.list({ pendingOnly: args.all !== true, limit: args.limit }),
851
+ });
852
+ }
853
+ if (action === 'ack') {
854
+ if (!Array.isArray(args.ids) || args.ids.length === 0) throw new Error('hive_anomalies ack needs ids');
855
+ return jsonText({ ok: true, changed: anomalies.markDelivered(args.ids) });
856
+ }
857
+ if (action === 'patrol') return jsonText({ ok: true, ...(await patrol.patrol()) });
858
+ throw new Error('hive_anomalies action must be list, ack or patrol');
859
+ },
860
+ });
861
+ }