dsh-hive-runner 0.6.1 → 0.6.7

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/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-hive-runner — protocol specification
2
2
 
3
- Status: 0.6.1, verified against DSH 0.2.2-rc.5.
3
+ Status: 0.6.7, verified against DSH 0.2.2-rc.5.
4
4
 
5
5
  This document is normative for the host contract of the plugin. It is written for
6
6
  maintainers: user documentation is [README.md](README.md) and
@@ -53,6 +53,8 @@ wrong method -> `405` (`hive/method-not-allowed`).
53
53
  "repoRoleConcurrency": {},
54
54
  "defaultRoleConcurrency": 5,
55
55
  "capacityRetryMs": 2000,
56
+ "queenSessionId": "queen-session-id",
57
+ "waiting": null,
56
58
  "lastTickAt": "2026-12-04T00:00:00.000Z",
57
59
  "lastDiscoverError": null,
58
60
  "repos": [
@@ -70,11 +72,27 @@ wrong method -> `405` (`hive/method-not-allowed`).
70
72
  "consecutiveFailures": 0,
71
73
  "lastCards": 0,
72
74
  "lastResults": 0,
75
+ "waiting": null,
73
76
  "backlog": { "queued": 3, "inFlight": 5, "completed": 12 },
74
77
  "roles": {
75
78
  "coder": { "limit": 5, "live": 5, "queued": 3 },
76
79
  "tester": { "limit": 5, "live": 0, "queued": 0 }
77
80
  },
81
+ "workers": [
82
+ {
83
+ "cardId": "readme-89ab",
84
+ "role": "coder",
85
+ "agent": "dsh",
86
+ "sessionId": "session-id",
87
+ "agentName": "agent-1",
88
+ "parentSource": "queen",
89
+ "startedAt": "2026-12-04T00:00:03.000Z",
90
+ "lastOutputAt": "2026-12-04T00:02:00.000Z",
91
+ "heartbeat": "ok",
92
+ "claimDeadline": "2026-12-04T00:05:03.000Z",
93
+ "timeoutAt": "2026-12-04T00:15:03.000Z"
94
+ }
95
+ ],
78
96
  "limitsError": null,
79
97
  "environmentError": null,
80
98
  "mode": null,
@@ -91,6 +109,15 @@ wrong method -> `405` (`hive/method-not-allowed`).
91
109
  immediately.
92
110
  - `roles[role].queued` — fetched cards waiting for a slot; they do not count as live.
93
111
  - `backlog` — aggregate `{ queued, inFlight, completed }` for the current or last drain.
112
+ - `queenSessionId` — the queen conversation registered by the panel; every worker is
113
+ parented to it. `waiting` is `"no-queen-session"` until that registration happens.
114
+ - `waiting` — per repository (and top level) `"no-queen-session"` before the queen
115
+ Session is registered; then `null`. It is a startup-order hint, never an error.
116
+ - `workers` — the cards currently running in this repository, each with
117
+ `cardId`, `role`, `agent`, `sessionId`, `agentName`, `parentSource` (`queen`),
118
+ `startedAt`, `lastOutputAt`,
119
+ `heartbeat` (`ok` | `warn`), `claimDeadline` and `timeoutAt`; the panel uses the
120
+ Session id to open the worker chat.
94
121
  - `state` — `idle` | `running` | `backoff` | `paused`.
95
122
 
96
123
  ### 3.2 `POST ?op=pause` / `POST ?op=resume`
@@ -171,6 +198,17 @@ deployment policy with the repository pinned as the workspace root.
171
198
 
172
199
  ## 8. Round preconditions and worker protocol
173
200
 
201
+ Every card worker is parented to the **queen conversation**: the Session where the
202
+ panel was initialised and the queen took over. The panel registers that Session id
203
+ with the supervisor (`POST /api/hive-runner?op=queen { sessionId }` or
204
+ `hiveSupervisor.setQueenSession()`); the registration lives in plugin memory and the
205
+ next panel access re-registers it after a restart. Before registration the supervisor
206
+ does not dispatch: the round is skipped and status reports
207
+ `waiting: "no-queen-session"` (a startup-order hint, not an error). The supervisor
208
+ always uses exactly the registered queen Session and never falls back to another
209
+ Session or an arbitrary live agent. Once registered, dispatch does not depend on any
210
+ other user session being live.
211
+
174
212
  Before every drain the supervisor requires a Hive-initialised repository whose
175
213
  `<repo>/.git/hooks/pre-commit` runs merge-on-commit (it mentions merge-on-commit or moc).
176
214
  A missing hook is a deferrable environment error: the repository backs off,
@@ -178,19 +216,64 @@ A missing hook is a deferrable environment error: the repository backs off,
178
216
 
179
217
  Per card:
180
218
 
181
- 1. `hive guard <scope...> --agent <claim identity>` co-signs the card's leases before
182
- the worker starts, using the SAME identity as `hive claim` (a different identity would
183
- be denied by the claim's own leases). Exit 2 with our own identity as the holder is
184
- allowed and renewed; exit 2 means another agent holds the scope: that card fails with
185
- the holder information and
186
- no worker or commit happens.
187
- 2. `hive recall <scope>` lessons are injected into the worker prompt (best effort).
188
- 3. The worker prompt hard-codes the consensus rules (guard every scope entry including
189
- `resource:` keys, stop and report on exit 2, never edit out of scope or drop lease
190
- refs) and the commit rules (plain `git commit` only, never `--no-verify`/history
191
- rewrites, resolve hook conflicts in place).
192
- 4. Done verification requires HEAD to have moved and the merge-on-commit hook to still be
193
- present; leases for the scope are best-effort released after done or fail.
219
+ 1. `hive guard <scope...> --task <id> --ttl <ttl> --json` announces the card's scope
220
+ before the worker starts, using the claim agent and a per-card `HIVE_INSTANCE` (the
221
+ card id) so concurrent workers of one runner are distinct announcers. hive-consensus
222
+ 1.5.0 announcements never block: `hive guard` always exits 0 and publishes the
223
+ announced paths on the board. The runner parses the JSON document's advisory
224
+ `overlaps` array, logs the agent names and keeps the entries on the run record. A
225
+ non-zero exit (an unexpected CLI problem) and malformed or empty JSON are tolerated:
226
+ they are logged or ignored and never fail the card.
227
+ 2. `hive recall` runs once for every scope entry and once for the repository root (query
228
+ `.`); the deduplicated lessons are injected at the top of the worker prompt (after
229
+ the title/role, before the goal) under `## Recalled experience (hive recall)`. A read
230
+ error is logged and recorded on the run record's `lessons.error`, and never blocks
231
+ the card. Writing lessons (`hive lesson add`) and reading them at the start are a
232
+ pair: a lesson nobody reads does not compound.
233
+ 3. The worker prompt hard-codes the consensus rules (announce every scope entry
234
+ including `resource:` keys with `--task <card id>` and the runner's claim identity,
235
+ so the worker's announcement belongs to this card and can never be mistaken for
236
+ another writer's; treat overlaps as information only, keep working and do not shrink
237
+ the scope; clear your own announcements before finishing; never delete another
238
+ agent's announcements) and the commit rules (plain `git commit` only, never
239
+ `--no-verify`/history rewrites, resolve hook conflicts in place keeping both sides).
240
+ 4. Every Hive/git shell command carries `HIVE_AGENT=<claim identity>` in its
241
+ environment; every per-card Hive command (`claim`, `guard`, `done`, `fail`,
242
+ `release`, `renew`) also carries `HIVE_INSTANCE=<card id>`. Worker subagent
243
+ activations inject both variables into the
244
+ in-process worker environment for their lifetime (DSH's model-facing bash tool
245
+ inherits ambient env) and restore the previous values afterwards.
246
+ 5. Done verification requires HEAD to have moved and the merge-on-commit hook to still be
247
+ present; announcements for the scope are best-effort released after done or fail.
248
+ 6. Every attempt writes `<repo>/.hive/runs/<cardId>.json`: `running` when the attempt
249
+ starts, a second `running` write after the lesson read (now carrying `lessons`), then
250
+ the terminal state for done, failed and exceptional endings. The record carries
251
+ `cardId`, `agent`, `startedAt`, `endedAt`, `status`, optional
252
+ `exitCode`/`commit`, optional `overlaps` (`[{ key, agent, task, expiresAt }]`, only
253
+ entries with a non-empty string agent, capped at 100, omitted when empty), `lessons`
254
+ (`{ count, scopes, error? }`: the number of deduplicated lessons read, the queries
255
+ used and the read error when one occurred), and `output` (the worker's final
256
+ result message only: the text blocks of its last assistant message, with
257
+ reasoning/thinking, tool calls and the narration around them stripped; a provider
258
+ that returned no typed text block falls back to the last non-empty text, and a run
259
+ with no text at all falls back to the card verdict; capped to the smaller of the
260
+ last 200 lines and the last 32 KiB of UTF-8). A started worker activation
261
+ also adds `sessionId` (the child Session id returned by `startActivation`) and
262
+ `agentName` (its model-facing child name); both keys are omitted when no activation
263
+ was accepted (for example an activation that threw, or a deferrable environment
264
+ error), so consumers can distinguish "no worker chat" from an empty value. The
265
+ running record is rewritten as soon as the activation is accepted, so a card that is
266
+ still in progress already exposes its worker Session and name. The file is
267
+ overwritten per attempt, so only the most recent run is kept; read failures and
268
+ write failures are ignored by the round and never change the card verdict. While the
269
+ worker runs, the record also carries `heartbeat` (`ok`/`warn`) and
270
+ `lastOutputAt`, advanced when the repository HEAD moves.
271
+ 7. Every card has a hard wall-clock limit `cardTimeoutMs` (default 15 min). At the
272
+ deadline the worker signal is aborted, the card is recorded failed with a timeout
273
+ reason, and the scope announcements are released. The claim TTL never aborts a
274
+ running card. A running worker whose HEAD has not moved for `heartbeatWarnMs`
275
+ (default 5 min) is marked `heartbeat: "warn"` in status and the run record;
276
+ heartbeat polling uses `heartbeatIntervalMs` (default 30 s).
194
277
 
195
278
  The supervisor reads the Hive mode every round: in freeze mode only fix cards are
196
279
  dispatched, other ready cards stay on the board and are reported through `mode`,
package/cordis.patch.yml CHANGED
@@ -43,9 +43,12 @@
43
43
  maxConsecutiveFailures: 3
44
44
  # Repositories paused at startup (absolute paths). Manual resume works.
45
45
  paused: []
46
- # Claim identity / claim TTL.
46
+ # Claim identity / claim TTL. Every card also runs its consensus calls
47
+ # with HIVE_INSTANCE=<card id>, so concurrent workers of this runner are
48
+ # distinct announcers on the board. The claim TTL never aborts a running
49
+ # card (cardTimeoutMs does that); raise ttl for very large queues.
47
50
  agent: dsh
48
- ttl: 5m
51
+ ttl: 20m
49
52
  # Per-role LIVE-worker limits, per repository. Default five workers per
50
53
  # role; 0 pauses a role (its ready cards stay on the board). These are
51
54
  # the config defaults/fallbacks — each repository can persist its own
@@ -62,6 +65,15 @@
62
65
  # Delay (ms) before retrying queued cards when DSH subagent capacity is
63
66
  # exhausted (ACTIVATION_LIMIT_REACHED).
64
67
  capacityRetryMs: 2000
68
+ # Hard per-card wall-clock limit (ms). At the deadline the worker is
69
+ # aborted, the card is recorded failed and its announcements are released.
70
+ cardTimeoutMs: 900000
71
+ # Heartbeat: while a worker runs, watch the repository HEAD as the
72
+ # observable output signal. No movement for heartbeatWarnMs marks the
73
+ # worker heartbeat=warn in status/run record; heartbeatIntervalMs is the
74
+ # poll cadence.
75
+ heartbeatWarnMs: 300000
76
+ heartbeatIntervalMs: 30000
65
77
  # Subagent provider used to run card workers (spawn is the shipped
66
78
  # in-process fresh-child backend).
67
79
  provider: spawn
@@ -72,6 +84,9 @@
72
84
  # Tool default repository when a tool call does not pass `repo`.
73
85
  cwd: null
74
86
  # Binaries (absolute path or PATH name); the HIVE_*_BIN env vars win.
87
+ # Default null means the PATH name (hive-tasks / hive); a missing PATH
88
+ # name is retried once through npx (-y -p hive-tasks / -p hive-consensus).
89
+ # An explicit absolute path is used as-is and never replaced.
75
90
  tasksBin: null
76
91
  hiveBin: null
77
92
  gitBin: git
package/docs/DESIGN.md CHANGED
@@ -39,6 +39,8 @@ Response:
39
39
  "repoRoleConcurrency": {},
40
40
  "defaultRoleConcurrency": 5,
41
41
  "capacityRetryMs": 2000,
42
+ "queenSessionId": "queen-session-id",
43
+ "waiting": null,
42
44
  "lastTickAt": "2026-12-04T00:00:00.000Z",
43
45
  "lastDiscoverError": null,
44
46
  "repos": [
@@ -56,11 +58,26 @@ Response:
56
58
  "consecutiveFailures": 0,
57
59
  "lastCards": 0,
58
60
  "lastResults": 0,
61
+ "waiting": null,
59
62
  "backlog": { "queued": 3, "inFlight": 5, "completed": 12 },
60
63
  "roles": {
61
64
  "coder": { "limit": 5, "live": 5, "queued": 3 },
62
65
  "tester": { "limit": 5, "live": 0, "queued": 0 }
63
66
  },
67
+ "workers": [
68
+ {
69
+ "cardId": "readme-89ab",
70
+ "role": "coder",
71
+ "agent": "dsh",
72
+ "sessionId": "session-id",
73
+ "agentName": "agent-1",
74
+ "startedAt": "2026-12-04T00:00:03.000Z",
75
+ "lastOutputAt": "2026-12-04T00:02:00.000Z",
76
+ "heartbeat": "ok",
77
+ "claimDeadline": "2026-12-04T00:05:03.000Z",
78
+ "timeoutAt": "2026-12-04T00:15:03.000Z"
79
+ }
80
+ ],
64
81
  "limitsError": null
65
82
  }
66
83
  ]
@@ -75,8 +92,22 @@ Response:
75
92
  against `live`).
76
93
  - `backlog` — aggregate `{ queued, inFlight, completed }` for the current or
77
94
  last drain.
95
+ - `queenSessionId` — the queen conversation registered by the panel; every worker is
96
+ parented to exactly this Session. `waiting` is `"no-queen-session"` until the
97
+ registration arrives (startup-order hint, not an error); the supervisor never
98
+ falls back to another Session. Workers/run records carry `parentSource: "queen"`.
99
+ - `workers` — live workers in this repository: `cardId`, `role`, `agent`,
100
+ `sessionId`, `agentName`, `startedAt`, `lastOutputAt`, `heartbeat`
101
+ (`ok`/`warn`), `claimDeadline`, `timeoutAt`. The Session id is written into the
102
+ `.hive/runs/<cardId>.json` record as soon as the activation is accepted.
78
103
  - `state` — `idle` | `running` | `backoff` | `paused`.
79
104
 
105
+ Every card has a hard `cardTimeoutMs` deadline (default 15 min); when it expires
106
+ the worker is aborted, the card is recorded failed and its announcements are released.
107
+ The claim TTL is observability only (`claimDeadline` in status) and never aborts a
108
+ running card. While a worker runs, the repository HEAD is polled as the output signal;
109
+ no movement for `heartbeatWarnMs` marks `heartbeat: "warn"` in status/run record.
110
+
80
111
  ### `POST ?op=pause` / `POST ?op=resume`
81
112
 
82
113
  Body or query: `{ "repo": "/abs/repo" }`. Returns
@@ -98,6 +129,19 @@ Body:
98
129
  - Malformed values → `400` `hive/invalid-role-limits`; non-POST → `405`
99
130
  `hive/method-not-allowed`; unknown repo → `404`.
100
131
 
132
+ ### `POST ?op=queen`
133
+
134
+ Body: `{ "sessionId": "<live queen Session id>" }`.
135
+
136
+ - Registers the queen conversation that owns every worker. The panel calls this
137
+ when its init/queen activation succeeds (or calls the `hiveSupervisor`
138
+ service's `setQueenSession()` from the host side). Registration is in-memory;
139
+ after a plugin restart the next panel access re-registers it.
140
+ - Until registration the supervisor does not dispatch: `status` reports
141
+ `waiting: "no-queen-session"` per repository and at the top level. This is a
142
+ startup-order hint, not an error; the supervisor never picks another Session.
143
+ - Returns `{ ok: true, op: "queen", queenSessionId, waiting: null, repos: ... }`.
144
+ - Missing `sessionId` -> `400` `hive/missing-session-id`; non-POST -> `405`.
101
145
  ## 3. Per-repository limits
102
146
 
103
147
  Precedence for one role in one repository:
@@ -155,7 +199,8 @@ consuming the failure budget.
155
199
  | `index.js` | Cordis plugin entry: config, limits store, supervisor service/timer, Fetch route, tools |
156
200
  | `lib/supervisor.js` | Repository registry + state machine + per-repo queue/backlog/roles; exposes `setRoleLimits` |
157
201
  | `lib/queue.js` | Live-only per-role worker pools, immediate slot refill, capacity requeue, per-role state callback |
158
- | `lib/round.js` | One card end to end: claim → subagent activation → commit/acceptance verify → done/fail |
202
+ | `lib/round.js` | One card end to end: claim → announcement/timeout guard (`hive guard` overlaps) + lesson read (`hive recall`) → subagent activation → commit/acceptance verify → done/fail + last-run record |
203
+ | `lib/runs.js` | `<repo>/.hive/runs/<cardId>.json` last-run records: path validation, 200-line/32-KiB output truncation, optional worker `sessionId`/`agentName`, advisory `overlaps`, `lessons` read summary, best-effort write |
159
204
  | `lib/limits.js` | `<repo>/.hive/limits.json` read/write/hot-reload and precedence helpers |
160
205
  | `lib/config.js` | Config defaults/validation, role map parsing, effective-limit helpers |
161
206
  | `lib/commands.js` | Allowlisted `hive-tasks` / `git` / acceptance commands with shell quoting |
@@ -176,6 +221,7 @@ consuming the failure budget.
176
221
  ## 8. Tests
177
222
 
178
223
  `node --test test/*.test.js`. Suites: supervisor state machine and limits
179
- persistence/hot reload, live-only role queue, single-card round paths, config,
224
+ persistence/hot reload, live-only role queue, single-card round paths (announcement
225
+ overlaps, lesson reads, timeouts), config,
180
226
  HTTP protocol (including `op=limits` validation), discovery, command allowlist,
181
227
  and an architecture guard (no child processes; README protocol hygiene).
package/index.js CHANGED
@@ -43,12 +43,29 @@ export function apply(ctx, config = {}) {
43
43
  repoRoleConcurrency: resolved.repoRoleConcurrency,
44
44
  defaultRoleConcurrency: resolved.defaultRoleConcurrency,
45
45
  });
46
+ const log = (level, ...args) => {
47
+ const write = console[level];
48
+ if (typeof write === 'function') write.call(console, '[hive-runner]', ...args);
49
+ else console.warn('[hive-runner]', ...args);
50
+ };
51
+ // The panel registers the queen conversation here (setQueenSession, also via
52
+ // POST ?op=queen). Every worker is parented to exactly that Session; before
53
+ // registration the supervisor does not dispatch at all.
54
+ const queenSession = { sessionId: null };
55
+ let parentProviderImpl;
46
56
  const runner = createRoundRunner({
47
57
  ctx,
48
58
  config: resolved,
49
59
  commands,
50
60
  limitFor: (repo, role) => limits.limitFor(repo, role),
61
+ parentProvider: (explicit) => parentProviderImpl(explicit),
62
+ log,
51
63
  });
64
+ parentProviderImpl = async (explicit) => {
65
+ const sessionId = queenSession.sessionId;
66
+ const agent = sessionId === null ? undefined : ctx.get('agents')?.get?.(sessionId);
67
+ return { agent, source: 'queen', sessionId };
68
+ };
52
69
 
53
70
  const supervisor = new HiveSupervisor({
54
71
  repos: resolved.repos,
@@ -70,6 +87,8 @@ export function apply(ctx, config = {}) {
70
87
  listReady: runner.listReady,
71
88
  runCard: runner.runCard,
72
89
  preflight: runner.preflight,
90
+ activeRuns: (repo) => runner.activeRuns(repo),
91
+ queenSession,
73
92
  readMode: (repo) => commands.mode(repo),
74
93
  logger: console,
75
94
  debug: resolved.debug,
@@ -114,11 +133,14 @@ export function apply(ctx, config = {}) {
114
133
  ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
115
134
  agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
116
135
  },
117
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
136
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
118
137
  execute: async (args = {}, exec) => {
119
138
  const repo = repoOf(args);
120
139
  const signal = exec?.signal;
121
140
  const session = exec?.agent?.session;
141
+ if (supervisor.queenSession.sessionId === null) {
142
+ throw new Error('waiting: no-queen-session — open the Hive panel and initialise the repository first');
143
+ }
122
144
  runner.preflight(repo);
123
145
  const cards = await runner.listReady(repo, { signal, session });
124
146
  const outcome = await drainQueue({
@@ -156,7 +178,7 @@ export function apply(ctx, config = {}) {
156
178
  role: { type: 'string', description: 'Filter by Hive role, for example coder or tester.' },
157
179
  limit: { type: 'number', description: 'Maximum number of cards.' },
158
180
  },
159
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
181
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
160
182
  execute: async (args = {}, exec) => {
161
183
  const repo = repoOf(args);
162
184
  const cards = await commands.ready(repo, {
@@ -175,7 +197,7 @@ export function apply(ctx, config = {}) {
175
197
  parameters: {
176
198
  repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
177
199
  },
178
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
200
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
179
201
  execute: async (args = {}, exec) => {
180
202
  const repo = repoOf(args);
181
203
  const board = await commands.board(repo, { signal: exec?.signal, session: exec?.agent?.session });
@@ -189,7 +211,7 @@ export function apply(ctx, config = {}) {
189
211
  'Show the resident Hive supervisor state: per-repository state (idle/running/backoff/paused), '
190
212
  + 'last round time, last error, in-flight flag and pause reason. Same data as GET /api/hive-runner?op=status.',
191
213
  parameters: {},
192
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
214
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
193
215
  execute: async () => JSON.stringify(supervisor.status(), null, 2),
194
216
  }));
195
217
  }
package/lib/commands.js CHANGED
@@ -28,6 +28,32 @@ export const AGENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
28
28
  export const TTL_RE = /^\d{1,4}[smhd]$/;
29
29
  export const SHA_RE = /^[0-9a-f]{7,64}$/;
30
30
 
31
+ /** npm package(s) behind each Hive bin; used only when the PATH name is missing. */
32
+ export const BIN_PACKAGES = Object.freeze({
33
+ tasks: Object.freeze(['hive-tasks']),
34
+ hive: Object.freeze(['hive-consensus']),
35
+ });
36
+
37
+ /** The executable name inside each published package. */
38
+ const BIN_EXECUTABLES = Object.freeze({ tasks: 'hive-tasks', hive: 'hive' });
39
+
40
+ /** Which Hive bin a verb uses; null verbs (git, the card's own acceptance) cap no fallback. */
41
+ const VERB_BINS = Object.freeze({
42
+ ready: 'tasks',
43
+ claim: 'tasks',
44
+ show: 'tasks',
45
+ done: 'tasks',
46
+ fail: 'tasks',
47
+ board: 'hive',
48
+ guard: 'hive',
49
+ release: 'hive',
50
+ renew: 'hive',
51
+ mode: 'hive',
52
+ recall: 'hive',
53
+ head: null,
54
+ acceptance: null,
55
+ });
56
+
31
57
  /** POSIX single-quote one argv token. */
32
58
  export function quote(value) {
33
59
  return "'" + String(value).replaceAll("'", "'\\''") + "'";
@@ -110,7 +136,7 @@ export function buildCommand(verb, args = {}, bins = {}) {
110
136
  const agent = ' --agent ' + quote(needMatch(AGENT_RE, args.agent, 'guard.agent'));
111
137
  const task = args.id === undefined || args.id === null ? '' : ' --task ' + quote(needMatch(ID_RE, args.id, 'guard.id'));
112
138
  const ttl = args.ttl === undefined || args.ttl === null ? '' : ' --ttl ' + quote(needMatch(TTL_RE, args.ttl, 'guard.ttl'));
113
- return hive + ' guard ' + keys + agent + task + ttl;
139
+ return hive + ' guard ' + keys + agent + task + ttl + ' --json';
114
140
  }
115
141
  case 'release':
116
142
  return hive + ' release ' + scopeArgs(args.paths, 'release.paths')
@@ -140,6 +166,51 @@ export function buildCommand(verb, args = {}, bins = {}) {
140
166
  }
141
167
  }
142
168
 
169
+ /**
170
+ * The npx fallback for one allowlisted command: the same argv, prefixed with
171
+ * `npx -y -p <published package> ... <bin>`. Only a bare PATH name gets a
172
+ * fallback; an explicitly configured absolute path is the operator's choice.
173
+ * @param {'ready'|'claim'|'show'|'done'|'fail'|'board'|'head'|'acceptance'|'guard'|'release'|'renew'|'mode'|'recall'} verb
174
+ * @param {Record<string, unknown>} [args]
175
+ * @param {{ tasks?: string, hive?: string, git?: string }} [bins]
176
+ * @returns {string | null} the fallback command string, or null when none applies.
177
+ */
178
+ export function npxFallbackCommand(verb, args = {}, bins = {}) {
179
+ const key = VERB_BINS[verb];
180
+ if (key === undefined || key === null) return null;
181
+ const executable = typeof bins[key] === 'string' && bins[key] !== '' ? bins[key] : BIN_EXECUTABLES[key];
182
+ if (executable.includes('/') || executable.includes('\\')) return null;
183
+ const packages = BIN_PACKAGES[key];
184
+ if (packages === undefined) return null;
185
+ const prefix = ['npx', '-y', ...packages.flatMap((pkg) => ['-p', pkg]), BIN_EXECUTABLES[key]].map(quote).join(' ');
186
+ const command = buildCommand(verb, args, bins);
187
+ return prefix + command.slice(executable.length);
188
+ }
189
+
190
+ /** True when a shell result means the executable itself was missing. */
191
+ export function missingBinary(result) {
192
+ if (result === undefined || result === null) return false;
193
+ if (result.exitCode === 127) return true;
194
+ return /command not found|: not found|No such file or directory/i.test(String(result.stderr ?? ''));
195
+ }
196
+
197
+ /** Actionable install hint for a bin whose PATH name and npx fallback both failed. */
198
+ export function missingBinaryHint(verb, bins = {}) {
199
+ const key = VERB_BINS[verb];
200
+ if (key === undefined || key === null) return null;
201
+ const configured = typeof bins[key] === 'string' && bins[key] !== '' ? bins[key] : BIN_EXECUTABLES[key];
202
+ const packages = BIN_PACKAGES[key];
203
+ const configKey = key === 'tasks' ? 'tasksBin' : 'hiveBin';
204
+ return '[hive-runner] ' + configured + ' was not found on the shell PATH and the npx fallback did not run it; '
205
+ + 'install it with "npm i -g ' + packages.join(' ') + '" or set ' + configKey + '.';
206
+ }
207
+
208
+ /** Append one diagnostic line to a result's stderr without dropping the CLI output. */
209
+ export function appendStderr(result, line) {
210
+ const stderr = String(result.stderr ?? '');
211
+ return { ...result, stderr: stderr === '' ? line : stderr.replace(/\s+$/, '') + '\n' + line };
212
+ }
213
+
143
214
  function parseJson(text, label) {
144
215
  const trimmed = String(text ?? '').trim();
145
216
  if (trimmed === '') return null;
@@ -168,14 +239,33 @@ export function createCommands({ ctx, config }) {
168
239
  const bins = { tasks: config.tasksBin, hive: config.hiveBin, git: config.gitBin };
169
240
 
170
241
  /** Execute one allowlisted verb. @returns {Promise<object>} the raw shell result */
171
- function execute(verb, args, options = {}) {
242
+ async function execute(verb, args, options = {}) {
172
243
  const command = buildCommand(verb, args, bins);
173
- return run(command, {
244
+ // Every Hive/git command carries the claim identity explicitly. Per-card
245
+ // Hive calls also carry a per-card `HIVE_INSTANCE` (the card id), so
246
+ // concurrent workers of one runner are distinct announcers on the consensus
247
+ // board instead of looking like the same instance.
248
+ const env = { HIVE_AGENT: options.agent ?? config.agent };
249
+ const instance = typeof options.instance === 'string' ? options.instance.trim() : '';
250
+ if (instance !== '') env.HIVE_INSTANCE = instance;
251
+ const shellOptions = {
174
252
  workdir: options.repo,
175
253
  signal: options.signal,
176
254
  session: options.session,
177
255
  timeoutMs: options.timeoutMs ?? config.cliTimeoutMs,
178
- });
256
+ env: { ...env, ...(options.env ?? {}) },
257
+ };
258
+ let result = await run(command, shellOptions);
259
+ if (!missingBinary(result)) return result;
260
+ const fallback = npxFallbackCommand(verb, args, bins);
261
+ if (fallback === null) {
262
+ const hint = missingBinaryHint(verb, bins);
263
+ return hint === null ? result : appendStderr(result, hint);
264
+ }
265
+ result = await run(fallback, shellOptions);
266
+ if (!missingBinary(result)) return result;
267
+ const hint = missingBinaryHint(verb, bins);
268
+ return hint === null ? result : appendStderr(result, hint);
179
269
  }
180
270
 
181
271
  return {
@@ -234,9 +324,11 @@ export function createCommands({ ctx, config }) {
234
324
  return value ?? [];
235
325
  },
236
326
  /**
237
- * `hive guard <scope...> --task <id> --ttl <ttl>`: auto-sign the card's
238
- * leases and publish the board as working. Returns the raw result so the
239
- * caller can map exit 2 to a claim-conflict card failure.
327
+ * `hive guard <scope...> --task <id> --ttl <ttl> --json`: announce the
328
+ * card's scope and publish the board as working. hive-consensus 1.5.0 never
329
+ * blocks on an announcement, so the raw result is returned as-is; the
330
+ * `--json` document carries the advisory `overlaps` array the runner
331
+ * records, and a non-zero exit is only an unexpected CLI problem.
240
332
  */
241
333
  async guard(repo, paths, options = {}) {
242
334
  return execute('guard', {
@@ -246,11 +338,11 @@ export function createCommands({ ctx, config }) {
246
338
  ttl: options.ttl ?? config.ttl,
247
339
  }, { ...options, repo });
248
340
  },
249
- /** `hive release <scope...> --agent A`: drop our leases (best effort). */
341
+ /** `hive release <scope...> --agent A`: clear our announcements (best effort). */
250
342
  async release(repo, paths, options = {}) {
251
343
  return execute('release', { paths, agent: options.agent ?? config.agent }, { ...options, repo });
252
344
  },
253
- /** `hive renew <scope...> --agent A --ttl T`: extend leases we already hold. */
345
+ /** `hive renew <scope...> --agent A --ttl T`: refresh announcements we already published. */
254
346
  async renew(repo, paths, options = {}) {
255
347
  return execute('renew', {
256
348
  paths,
package/lib/config.js CHANGED
@@ -18,6 +18,12 @@ export const DEFAULT_MAX_CONCURRENT_REPOS = 2;
18
18
  export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
19
19
  /** Default capacity retry delay when DSH's subagent capacity is exhausted. */
20
20
  export const DEFAULT_CAPACITY_RETRY_MS = 2_000;
21
+ /** Hard per-card wall-clock limit: abort the worker and fail the card at the deadline. */
22
+ export const DEFAULT_CARD_TIMEOUT_MS = 15 * 60_000;
23
+ /** Warn when a running worker produced no new commit/output for this long. */
24
+ export const DEFAULT_HEARTBEAT_WARN_MS = 5 * 60_000;
25
+ /** How often heartbeat/liveness is checked while a worker runs. */
26
+ export const DEFAULT_HEARTBEAT_INTERVAL_MS = 30_000;
21
27
  /** Default role -> concurrent live-worker cap, per repository. */
22
28
  export const DEFAULT_ROLE_CONCURRENCY = Object.freeze({ coder: 5, tester: 5 });
23
29
  /** Fallback cap for roles not listed in `roleConcurrency` (also finite). */
@@ -37,7 +43,10 @@ const DEFAULTS = Object.freeze({
37
43
  maxConsecutiveFailures: DEFAULT_MAX_CONSECUTIVE_FAILURES,
38
44
  paused: [],
39
45
  agent: 'dsh',
40
- ttl: '5m',
46
+ // Claim TTL: bounds how long a claim survives while a card waits for a worker
47
+ // slot. It never aborts a running card (the hard cardTimeoutMs does that);
48
+ // raise it for very large queues.
49
+ ttl: '20m',
41
50
  // Finite, user-set default: five live workers per role per repository
42
51
  // (repo-level .hive/limits.json overrides this at runtime). Repository
43
52
  // overrides use absolute-path keys with a role-cap object, e.g.
@@ -46,9 +55,13 @@ const DEFAULTS = Object.freeze({
46
55
  // Fallback cap for roles not listed in roleConcurrency (also finite).
47
56
  defaultRoleConcurrency: DEFAULT_DEFAULT_ROLE_CONCURRENCY,
48
57
  capacityRetryMs: DEFAULT_CAPACITY_RETRY_MS,
58
+ cardTimeoutMs: DEFAULT_CARD_TIMEOUT_MS,
59
+ heartbeatWarnMs: DEFAULT_HEARTBEAT_WARN_MS,
60
+ heartbeatIntervalMs: DEFAULT_HEARTBEAT_INTERVAL_MS,
49
61
  provider: 'spawn',
50
62
  parentSession: null,
51
63
  cwd: null,
64
+ // null = the PATH name; commands.js retries a missing PATH name through npx.
52
65
  tasksBin: null,
53
66
  hiveBin: null,
54
67
  gitBin: 'git',
@@ -201,6 +214,17 @@ function bin(value, name, env, fallback) {
201
214
  return nonEmptyString(value, name);
202
215
  }
203
216
 
217
+ /**
218
+ * Parse a claim TTL string ("30s", "5m", "2h", "1d") to milliseconds.
219
+ * @param {string} ttl
220
+ * @returns {number}
221
+ */
222
+ export function parseTtlMs(ttl) {
223
+ const match = /^(\d{1,4})([smhd])$/.exec(String(ttl ?? ''));
224
+ if (match === null) return 5 * 60_000;
225
+ return Number(match[1]) * ({ s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[match[2]] ?? 60_000);
226
+ }
227
+
204
228
  /**
205
229
  * Normalize one repository key. Configuration requires absolute paths; HTTP and
206
230
  * tool callers may send any string, resolved against the host working directory.
@@ -240,6 +264,9 @@ export function resolveConfig(config = {}) {
240
264
  fail('defaultRoleConcurrency must be an integer in 0..999 (0 pauses unlisted roles)');
241
265
  }
242
266
  cfg.capacityRetryMs = positiveNumber(cfg.capacityRetryMs, 'capacityRetryMs');
267
+ cfg.cardTimeoutMs = positiveNumber(cfg.cardTimeoutMs, 'cardTimeoutMs');
268
+ cfg.heartbeatWarnMs = positiveNumber(cfg.heartbeatWarnMs, 'heartbeatWarnMs');
269
+ cfg.heartbeatIntervalMs = positiveNumber(cfg.heartbeatIntervalMs, 'heartbeatIntervalMs');
243
270
  cfg.cliTimeoutMs = positiveNumber(cfg.cliTimeoutMs, 'cliTimeoutMs');
244
271
  cfg.headTimeoutMs = positiveNumber(cfg.headTimeoutMs, 'headTimeoutMs');
245
272
  cfg.acceptanceTimeoutMs = positiveNumber(cfg.acceptanceTimeoutMs, 'acceptanceTimeoutMs');