dsh-hive-runner 0.1.0 → 0.6.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
@@ -1,77 +1,195 @@
1
1
  /**
2
- * DSH host half for Hive.
2
+ * dsh-hive-runner — DSH host half for Hive.
3
3
  *
4
- * Two tools, both thin wrappers over the hive CLIs:
5
- * hive_run_round -> hive-run --once (triage, claim, spawn, verify, record)
6
- * hive_tasks_ready -> hive-tasks ready --json
4
+ * Owns:
5
+ * - `HiveSupervisor`: a resident, repository-scoped scheduler (Cordis service +
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
11
  *
8
- * The heavy lifting stays in the CLI packages; this plugin only makes them reachable
9
- * from a DSH agent without leaving the harness.
12
+ * 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.
10
18
  */
11
- import { execFile } from "node:child_process";
12
- import { promisify } from "node:util";
13
- import { defineTool } from "@deepseek-ai/dsh-tools";
19
+ import { defineTool } from '@deepseek-ai/dsh-tools';
14
20
 
15
- const exec = promisify(execFile);
21
+ import { createCommands } from './lib/commands.js';
22
+ import { normalizeRepoKey, resolveConfig } from './lib/config.js';
23
+ import { discoverRepos } from './lib/discover.js';
24
+ import { createHiveRunnerRoute } from './lib/http.js';
25
+ import { RepoLimits } from './lib/limits.js';
26
+ import { drainQueue } from './lib/queue.js';
27
+ import { createRoundRunner } from './lib/round.js';
28
+ import { HiveSupervisor } from './lib/supervisor.js';
16
29
 
17
- export const name = "hive-runner";
18
- export const inject = ["tools"];
30
+ export const name = 'hive-runner';
31
+ /** Host services that must exist before the plugin loads. */
32
+ export const inject = ['tools', 'shell', 'subagents'];
19
33
 
20
- function bin(envName, fallback) {
21
- return process.env[envName] || fallback;
22
- }
34
+ /**
35
+ * @param {import('@deepseek-ai/cordis').Context} ctx
36
+ * @param {Record<string, unknown>} [config]
37
+ */
38
+ export function apply(ctx, config = {}) {
39
+ const resolved = resolveConfig(config);
40
+ const commands = createCommands({ ctx, config: resolved });
41
+ const limits = new RepoLimits({
42
+ roleConcurrency: resolved.roleConcurrency,
43
+ repoRoleConcurrency: resolved.repoRoleConcurrency,
44
+ defaultRoleConcurrency: resolved.defaultRoleConcurrency,
45
+ });
46
+ const runner = createRoundRunner({
47
+ ctx,
48
+ config: resolved,
49
+ commands,
50
+ limitFor: (repo, role) => limits.limitFor(repo, role),
51
+ });
23
52
 
24
- async function runJson(file, args, cwd) {
25
- const { stdout } = await exec(file, args, { cwd, timeout: 120000, maxBuffer: 16 * 1024 * 1024 });
26
- return stdout;
27
- }
53
+ const supervisor = new HiveSupervisor({
54
+ repos: resolved.repos,
55
+ paused: resolved.paused,
56
+ intervalMs: resolved.intervalMs,
57
+ idleBackoffMs: resolved.idleBackoffMs,
58
+ maxConcurrentRepos: resolved.maxConcurrentRepos,
59
+ maxConsecutiveFailures: resolved.maxConsecutiveFailures,
60
+ roleConcurrency: resolved.roleConcurrency,
61
+ repoRoleConcurrency: resolved.repoRoleConcurrency,
62
+ defaultRoleConcurrency: resolved.defaultRoleConcurrency,
63
+ limits,
64
+ capacityRetryMs: resolved.capacityRetryMs,
65
+ autoDiscover: resolved.autoDiscover,
66
+ discoverIntervalMs: resolved.discoverIntervalMs,
67
+ discover: resolved.autoDiscover
68
+ ? () => discoverRepos({ roots: resolved.discoverRoots, depth: resolved.discoverDepth })
69
+ : undefined,
70
+ listReady: runner.listReady,
71
+ runCard: runner.runCard,
72
+ preflight: runner.preflight,
73
+ readMode: (repo) => commands.mode(repo),
74
+ logger: console,
75
+ debug: resolved.debug,
76
+ });
28
77
 
29
- export function apply(ctx, config = {}) {
30
- const cwd = config.cwd || process.cwd();
78
+ // Cordis service + effect-owned timer: the supervisor follows the plugin's
79
+ // lifecycle (host composition), not any browser tab.
80
+ ctx.provide('hiveSupervisor', supervisor);
81
+ ctx.effect(() => {
82
+ supervisor.start();
83
+ return () => supervisor.stop();
84
+ });
85
+
86
+ // Optional: the Web/desktop composition provides `connection`. In a headless
87
+ // CLI composition without it the supervisor still runs and the tools work.
88
+ ctx.inject(['connection'], (scope) => scope.connection.fetch.register(createHiveRunnerRoute(supervisor)));
89
+
90
+ if (resolved.debug) {
91
+ console.info('[hive-runner] repositories:', resolved.repos.length, 'autoDiscover:', resolved.autoDiscover);
92
+ }
93
+
94
+ /** Resolve the repository a tool call should act on. */
95
+ function repoOf(args = {}) {
96
+ if (args.repo === undefined || args.repo === null || args.repo === '') return resolved.cwd;
97
+ const key = normalizeRepoKey(String(args.repo));
98
+ if (supervisor.hasRepo(key) || key === resolved.cwd) return key;
99
+ throw new Error(
100
+ 'repo ' + JSON.stringify(key) + ' is not a configured Hive repository; '
101
+ + 'add it to config.repos or use the configured cwd ' + JSON.stringify(resolved.cwd),
102
+ );
103
+ }
104
+
105
+ ctx.tools.register(defineTool({
106
+ name: 'hive_run_round',
107
+ description:
108
+ 'Run one Hive round now in one repository: fetch every ready card and run card workers bounded by the '
109
+ + 'effective per-role limits (config + <repo>/.hive/limits.json), verify the commit and the card acceptance, '
110
+ + 'then record done or fail. DSH subagent capacity rejections stay queued and are retried, not dropped. '
111
+ + 'Returns per-card results and per-role state as JSON. The resident supervisor runs these rounds on its own schedule.',
112
+ parameters: {
113
+ repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
114
+ ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
115
+ agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
116
+ },
117
+ output: { schema: { type: 'string' } },
118
+ execute: async (args = {}, exec) => {
119
+ const repo = repoOf(args);
120
+ const signal = exec?.signal;
121
+ const session = exec?.agent?.session;
122
+ runner.preflight(repo);
123
+ const cards = await runner.listReady(repo, { signal, session });
124
+ const outcome = await drainQueue({
125
+ queue: cards.map((card) => ({ role: card.role, card, claimed: false })),
126
+ roleNames: limits.rolesFor(repo, cards.map((card) => card.role)),
127
+ limitFor: (role) => limits.limitFor(repo, role),
128
+ runCard: (item) => runner.runCard({
129
+ repo,
130
+ card: item.card,
131
+ claimed: item.claimed === true,
132
+ signal,
133
+ session,
134
+ parent: exec?.agent,
135
+ agent: args.agent,
136
+ ttl: args.ttl,
137
+ }),
138
+ capacityRetryMs: resolved.capacityRetryMs,
139
+ signal,
140
+ });
141
+ if (outcome.error !== undefined) throw outcome.error;
142
+ return JSON.stringify({
143
+ repo,
144
+ results: outcome.results,
145
+ state: outcome.state,
146
+ queued: outcome.queue.length,
147
+ }, null, 2);
148
+ },
149
+ }));
31
150
 
32
- ctx.tools.register(
33
- defineTool({
34
- name: "hive_run_round",
35
- description:
36
- "Run one round of Hive work in this repository: triage recorded conflicts, take ready task cards, spawn one agent per card, verify each commit, record done or fail, then stop. Returns the per-card result lines.",
37
- parameters: {
38
- concurrency: { type: "number", description: "How many agents may run at once. Default 3." },
39
- timeout: { type: "string", description: "Hard limit per agent, for example 15m. Default 15m." },
40
- agent: { type: "string", description: "Identity used for claims. Defaults to HIVE_AGENT or hive-runner." }
41
- },
42
- output: { schema: { type: "string" } },
43
- execute: async (args = {}) => {
44
- const argv = ["--once", "--agent", args.agent || process.env.HIVE_AGENT || "hive-runner"];
45
- if (args.concurrency) argv.push("--concurrency", String(args.concurrency));
46
- if (args.timeout) argv.push("--timeout", String(args.timeout));
47
- const { stdout } = await exec(bin("HIVE_RUN_BIN", "hive-run"), argv, {
48
- cwd,
49
- timeout: 30 * 60 * 1000,
50
- maxBuffer: 16 * 1024 * 1024,
51
- });
52
- return stdout.trim() || "round finished with no output";
53
- },
54
- }),
55
- );
151
+ ctx.tools.register(defineTool({
152
+ name: 'hive_tasks_ready',
153
+ description: 'List the Hive task cards that are ready right now in one repository, best first.',
154
+ parameters: {
155
+ repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
156
+ role: { type: 'string', description: 'Filter by Hive role, for example coder or tester.' },
157
+ limit: { type: 'number', description: 'Maximum number of cards.' },
158
+ },
159
+ output: { schema: { type: 'string' } },
160
+ execute: async (args = {}, exec) => {
161
+ const repo = repoOf(args);
162
+ const cards = await commands.ready(repo, {
163
+ limit: args.limit,
164
+ role: args.role,
165
+ signal: exec?.signal,
166
+ session: exec?.agent?.session,
167
+ });
168
+ return JSON.stringify(cards, null, 2);
169
+ },
170
+ }));
56
171
 
57
- ctx.tools.register(
58
- defineTool({
59
- name: "hive_tasks_ready",
60
- description:
61
- "List the task cards that are ready to be claimed right now, best first (dependencies done, mode allows them). Returns the raw JSON array.",
62
- parameters: {},
63
- output: { schema: { type: "string" } },
64
- execute: async () => runJson(bin("HIVE_TASKS_BIN", "hive-tasks"), ["ready", "--json"], cwd),
65
- }),
66
- );
172
+ ctx.tools.register(defineTool({
173
+ name: 'hive_board',
174
+ 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' } },
179
+ execute: async (args = {}, exec) => {
180
+ const repo = repoOf(args);
181
+ const board = await commands.board(repo, { signal: exec?.signal, session: exec?.agent?.session });
182
+ return JSON.stringify(board, null, 2);
183
+ },
184
+ }));
67
185
 
68
- ctx.tools.register(
69
- defineTool({
70
- name: "hive_board",
71
- description: "Show which agents are on the board right now: who is working, on which card, with which paths.",
72
- parameters: {},
73
- output: { schema: { type: "string" } },
74
- execute: async () => runJson(bin("HIVE_BIN", "hive"), ["board", "--json"], cwd),
75
- }),
76
- );
186
+ ctx.tools.register(defineTool({
187
+ name: 'hive_supervisor_status',
188
+ description:
189
+ '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.',
191
+ parameters: {},
192
+ output: { schema: { type: 'string' } },
193
+ execute: async () => JSON.stringify(supervisor.status(), null, 2),
194
+ }));
77
195
  }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Allowlisted Hive CLI commands.
3
+ *
4
+ * Every command is built from fixed argv templates; user/card-controlled values
5
+ * are validated by regular expression and shell-quoted before they enter the
6
+ * `bash -c` string the shell seam takes. The supervisor only ever runs
7
+ * `hive-tasks ready|claim|show|done|fail`, the hive-consensus
8
+ * `hive guard|release|mode|recall` verbs (plus fixed `git rev-parse HEAD` and a
9
+ * card's own acceptance command).
10
+ *
11
+ * No `node:child_process` here: execution goes through `lib/shell.js`.
12
+ */
13
+ import { ROLE_RE } from './config.js';
14
+ import { createShellRunner } from './shell.js';
15
+
16
+ /** A coded failure from the Hive command layer. */
17
+ export class HiveCommandError extends Error {
18
+ constructor(code, message, details = {}) {
19
+ super(message);
20
+ this.name = 'HiveCommandError';
21
+ this.code = code;
22
+ this.details = details;
23
+ }
24
+ }
25
+
26
+ export const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
27
+ export const AGENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
28
+ export const TTL_RE = /^\d{1,4}[smhd]$/;
29
+ export const SHA_RE = /^[0-9a-f]{7,64}$/;
30
+
31
+ /** POSIX single-quote one argv token. */
32
+ export function quote(value) {
33
+ return "'" + String(value).replaceAll("'", "'\\''") + "'";
34
+ }
35
+
36
+ /** Last `max` characters of command output, collapsed to one line. */
37
+ export function tail(text, max = 300) {
38
+ const normalized = String(text ?? '').replace(/\s+/g, ' ').trim();
39
+ return normalized.length <= max ? normalized : '…' + normalized.slice(-max);
40
+ }
41
+
42
+ function needMatch(re, value, name) {
43
+ if (typeof value !== 'string' || !re.test(value)) {
44
+ throw new HiveCommandError('hive/invalid-argument', name + ' must match ' + re);
45
+ }
46
+ return value;
47
+ }
48
+
49
+ /** Non-empty, shell-quoted path / scope-key list for hive-consensus verbs. */
50
+ function scopeArgs(paths, name) {
51
+ if (!Array.isArray(paths) || paths.length === 0) {
52
+ throw new HiveCommandError('hive/invalid-argument', name + ' needs at least one path/scope key');
53
+ }
54
+ const keys = paths
55
+ .filter((entry) => typeof entry === 'string' && entry.trim() !== '')
56
+ .map((entry) => entry.trim());
57
+ if (keys.length === 0) throw new HiveCommandError('hive/invalid-argument', name + ' needs a non-empty path/scope key');
58
+ return keys.map(quote).join(' ');
59
+ }
60
+
61
+ /**
62
+ * Build one allowlisted shell command string.
63
+ * @param {'ready'|'claim'|'show'|'done'|'fail'|'board'|'head'|'acceptance'|'guard'|'release'|'mode'|'recall'} verb
64
+ * @param {Record<string, unknown>} [args]
65
+ * @param {{ tasks?: string, hive?: string, git?: string }} [bins]
66
+ * @returns {string}
67
+ */
68
+ export function buildCommand(verb, args = {}, bins = {}) {
69
+ const tasks = bins.tasks ?? 'hive-tasks';
70
+ const hive = bins.hive ?? 'hive';
71
+ const git = bins.git ?? 'git';
72
+ switch (verb) {
73
+ case 'ready': {
74
+ const limit = args.limit;
75
+ if (limit !== undefined && limit !== null && (!Number.isInteger(limit) || limit <= 0 || limit > 10_000)) {
76
+ throw new HiveCommandError('hive/invalid-argument', 'ready.limit must be an integer in 1..10000');
77
+ }
78
+ const role = args.role === undefined || args.role === null ? null : needMatch(ROLE_RE, args.role, 'ready.role');
79
+ const limitFlag = limit === undefined || limit === null ? '' : ' --limit ' + String(limit);
80
+ return tasks + ' ready --json' + limitFlag + (role === null ? '' : ' --role ' + quote(role));
81
+ }
82
+ case 'claim': {
83
+ const id = needMatch(ID_RE, args.id, 'claim.id');
84
+ const agent = needMatch(AGENT_RE, args.agent, 'claim.agent');
85
+ const ttl = needMatch(TTL_RE, args.ttl, 'claim.ttl');
86
+ return tasks + ' claim ' + quote(id) + ' --agent ' + quote(agent) + ' --ttl ' + quote(ttl);
87
+ }
88
+ case 'show': {
89
+ const id = needMatch(ID_RE, args.id, 'show.id');
90
+ return tasks + ' show ' + quote(id) + ' --json';
91
+ }
92
+ case 'done': {
93
+ const id = needMatch(ID_RE, args.id, 'done.id');
94
+ const sha = needMatch(SHA_RE, args.sha, 'done.sha');
95
+ const verdict = args.verdict ?? 'pass';
96
+ if (verdict !== 'pass' && verdict !== 'fail') {
97
+ throw new HiveCommandError('hive/invalid-argument', 'done.verdict must be pass or fail');
98
+ }
99
+ return tasks + ' done ' + quote(id) + ' --sha ' + quote(sha) + ' --verdict ' + quote(verdict);
100
+ }
101
+ case 'fail': {
102
+ const id = needMatch(ID_RE, args.id, 'fail.id');
103
+ const reason = args.reason === undefined || args.reason === null ? 'runner failure' : String(args.reason);
104
+ return tasks + ' fail ' + quote(id) + ' --reason ' + quote(reason.slice(0, 1000));
105
+ }
106
+ case 'board':
107
+ return hive + ' board --json';
108
+ case 'guard': {
109
+ const keys = scopeArgs(args.paths, 'guard.paths');
110
+ const task = args.id === undefined || args.id === null ? '' : ' --task ' + quote(needMatch(ID_RE, args.id, 'guard.id'));
111
+ const ttl = args.ttl === undefined || args.ttl === null ? '' : ' --ttl ' + quote(needMatch(TTL_RE, args.ttl, 'guard.ttl'));
112
+ return hive + ' guard ' + keys + task + ttl;
113
+ }
114
+ case 'release':
115
+ return hive + ' release ' + scopeArgs(args.paths, 'release.paths');
116
+ case 'mode':
117
+ return hive + ' mode';
118
+ case 'recall': {
119
+ if (typeof args.query !== 'string' || args.query.trim() === '') {
120
+ throw new HiveCommandError('hive/invalid-argument', 'recall.query must be a non-empty string');
121
+ }
122
+ return hive + ' recall ' + quote(args.query.trim()) + ' --json';
123
+ }
124
+ case 'head':
125
+ return git + ' rev-parse HEAD';
126
+ case 'acceptance': {
127
+ if (typeof args.command !== 'string' || args.command.trim() === '') {
128
+ throw new HiveCommandError('hive/invalid-argument', 'acceptance.command must be a non-empty string');
129
+ }
130
+ return 'sh -c ' + quote(args.command);
131
+ }
132
+ default:
133
+ throw new HiveCommandError('hive/unknown-command', 'unknown Hive command ' + JSON.stringify(verb));
134
+ }
135
+ }
136
+
137
+ function parseJson(text, label) {
138
+ const trimmed = String(text ?? '').trim();
139
+ if (trimmed === '') return null;
140
+ try {
141
+ return JSON.parse(trimmed);
142
+ } catch {
143
+ throw new HiveCommandError('hive/bad-json', label + ' did not return JSON: ' + tail(trimmed));
144
+ }
145
+ }
146
+
147
+ function failure(result, label) {
148
+ const detail = result.stderr.trim() !== '' ? result.stderr : result.stdout;
149
+ return new HiveCommandError(
150
+ 'hive/exec-failed',
151
+ label + ' exited ' + String(result.exitCode) + (result.timedOut ? ' (timed out)' : '') + ': ' + tail(detail),
152
+ { command: result.command, exitCode: result.exitCode, timedOut: result.timedOut, stdout: result.stdout, stderr: result.stderr },
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Bind the command allowlist to one shell runner and one config.
158
+ * @param {{ ctx: object, config: object }} options
159
+ */
160
+ export function createCommands({ ctx, config }) {
161
+ const run = createShellRunner({ ctx, config });
162
+ const bins = { tasks: config.tasksBin, hive: config.hiveBin, git: config.gitBin };
163
+
164
+ /** Execute one allowlisted verb. @returns {Promise<object>} the raw shell result */
165
+ function execute(verb, args, options = {}) {
166
+ const command = buildCommand(verb, args, bins);
167
+ return run(command, {
168
+ workdir: options.repo,
169
+ signal: options.signal,
170
+ session: options.session,
171
+ timeoutMs: options.timeoutMs ?? config.cliTimeoutMs,
172
+ });
173
+ }
174
+
175
+ return {
176
+ /** Raw shell runner (used by tests and diagnostics). */
177
+ run,
178
+ /** `hive-tasks ready --json [--limit N] [--role R]` -> parsed card array. */
179
+ async ready(repo, options = {}) {
180
+ const result = await execute('ready', { limit: options.limit, role: options.role }, { ...options, repo });
181
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks ready');
182
+ const cards = parseJson(result.stdout, 'hive-tasks ready');
183
+ if (cards === null) return [];
184
+ if (!Array.isArray(cards)) throw new HiveCommandError('hive/bad-json', 'hive-tasks ready returned a non-array');
185
+ return cards;
186
+ },
187
+ /** Raw claim result: a non-zero exit means the card is contended/stale, not a supervisor failure. */
188
+ async claim(repo, id, options = {}) {
189
+ return execute('claim', {
190
+ id,
191
+ agent: options.agent ?? config.agent,
192
+ ttl: options.ttl ?? config.ttl,
193
+ }, { ...options, repo });
194
+ },
195
+ /** `hive-tasks show <id> --json` -> parsed card (null when the CLI prints nothing). */
196
+ async show(repo, id, options = {}) {
197
+ const result = await execute('show', { id }, { ...options, repo });
198
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks show ' + id);
199
+ return parseJson(result.stdout, 'hive-tasks show');
200
+ },
201
+ async done(repo, id, options = {}) {
202
+ const result = await execute('done', { id, sha: options.sha, verdict: options.verdict ?? 'pass' }, { ...options, repo });
203
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks done ' + id);
204
+ return result;
205
+ },
206
+ async fail(repo, id, options = {}) {
207
+ const result = await execute('fail', { id, reason: options.reason }, { ...options, repo });
208
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks fail ' + id);
209
+ return result;
210
+ },
211
+ /** Current commit sha of the repository. */
212
+ async head(repo, options = {}) {
213
+ const result = await execute('head', {}, { ...options, repo, timeoutMs: options.timeoutMs ?? config.headTimeoutMs });
214
+ if (result.exitCode !== 0) throw failure(result, 'git rev-parse HEAD');
215
+ const sha = result.stdout.trim();
216
+ if (!SHA_RE.test(sha)) throw new HiveCommandError('hive/bad-head', 'git rev-parse HEAD returned ' + JSON.stringify(sha));
217
+ return sha;
218
+ },
219
+ /** Card acceptance command; returns the raw result because a non-zero exit is a card verdict, not an error. */
220
+ async acceptance(repo, command, options = {}) {
221
+ return execute('acceptance', { command }, { ...options, repo, timeoutMs: options.timeoutMs ?? config.acceptanceTimeoutMs });
222
+ },
223
+ /** `hive board --json` -> parsed array. */
224
+ async board(repo, options = {}) {
225
+ const result = await execute('board', {}, { ...options, repo });
226
+ if (result.exitCode !== 0) throw failure(result, 'hive board');
227
+ const value = parseJson(result.stdout, 'hive board');
228
+ return value ?? [];
229
+ },
230
+ /**
231
+ * `hive guard <scope...> --task <id> --ttl <ttl>`: auto-sign the card's
232
+ * leases and publish the board as working. Returns the raw result so the
233
+ * caller can map exit 2 to a claim-conflict card failure.
234
+ */
235
+ async guard(repo, paths, options = {}) {
236
+ return execute('guard', { paths, id: options.taskId, ttl: options.ttl ?? config.ttl }, { ...options, repo });
237
+ },
238
+ /** `hive release <scope...>`: drop our leases for the given scope keys (best effort). */
239
+ async release(repo, paths, options = {}) {
240
+ return execute('release', { paths }, { ...options, repo });
241
+ },
242
+ /** `hive mode` -> `{ mode: 'free' | 'freeze' | ..., reason }`. */
243
+ async mode(repo, options = {}) {
244
+ const result = await execute('mode', {}, { ...options, repo });
245
+ if (result.exitCode !== 0) throw failure(result, 'hive mode');
246
+ const text = result.stdout.trim();
247
+ const match = /^([a-z_-]+)(?:\s*\((.*)\))?/i.exec(text);
248
+ if (match === null) throw new HiveCommandError('hive/bad-mode', 'hive mode returned ' + JSON.stringify(text));
249
+ return { mode: match[1].toLowerCase(), reason: match[2] ?? '' };
250
+ },
251
+ /** `hive recall <query> --json` -> parsed lesson array. */
252
+ async recall(repo, query, options = {}) {
253
+ const result = await execute('recall', { query }, { ...options, repo });
254
+ if (result.exitCode !== 0) throw failure(result, 'hive recall');
255
+ const value = parseJson(result.stdout, 'hive recall');
256
+ return Array.isArray(value) ? value : [];
257
+ },
258
+ };
259
+ }
260
+
261
+ export { createShellRunner };