dsh-hive-runner 1.0.9 → 1.0.11

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/CHANGELOG.md CHANGED
@@ -7,6 +7,41 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  Version 0.6.0 is the first public snapshot; 0.1.0-0.5.0 were local development
8
8
  iterations of the plugin before this repository was published.
9
9
 
10
+ ## [1.0.11] - 2026-12-05
11
+
12
+ ### Fixed
13
+
14
+ - Worker Sessions are no longer mistaken for the queen. The supervisor exposes
15
+ `isWorkerSession(sessionId)` / `workerSessionIds()` (backed by `activeRuns`, with
16
+ status top-level `workerSessionIds` for the panel); local providers reserve the
17
+ child Session id before activation and put it in `activeRuns`, closing the
18
+ just-activated window. The queen tool guard returns before any classification for
19
+ worker Sessions, with `origin: "subagent"`, positive `delegationDepth`, or
20
+ `parentSession === queenSessionId` as the restart/provider fallback, so a worker's
21
+ write/edit/bash and subagent tools keep working while the queen is still denied.
22
+
23
+ ## [1.0.10] - 2026-12-05
24
+
25
+ ### Fixed
26
+
27
+ - On the first tick after a (re)start, the supervisor recovers claims left by the
28
+ previous process: for each registered repository it lists claimed tasks, handles
29
+ only those whose owner is `config.agent` and whose id is not in the current live
30
+ workers, releases their scope announcements and reopens them with reason
31
+ `orphaned by supervisor restart` (attempt+1), then continues normal dispatch in the
32
+ same tick. Claims owned by other agents are never touched, and a recovery failure
33
+ backs off without consuming the auto-pause failure budget.
34
+
35
+ ### Added
36
+
37
+ - Status exposes `claimedButOrphaned` / `orphanRecovered` / `orphanRecoveryAt` per
38
+ repository (plus an aggregate `claimedButOrphaned` at the top level), so a panel
39
+ can distinguish recovered stale claims from real in-flight work.
40
+
41
+ ### Published
42
+
43
+ - npm: `dsh-hive-runner@1.0.10` on 2026-12-05.
44
+
10
45
  ## [1.0.9] - 2026-12-05
11
46
 
12
47
  ### Removed
@@ -17,6 +52,10 @@ iterations of the plugin before this repository was published.
17
52
  temporary diagnostic wrapper never swallowed them) and real runtime errors keep
18
53
  being logged through `console` / the plugin logger.
19
54
 
55
+ ### Published
56
+
57
+ - npm: `dsh-hive-runner@1.0.9` on 2026-12-05.
58
+
20
59
  ## [1.0.8] - 2026-12-05
21
60
 
22
61
  ### Added
package/README.md CHANGED
@@ -114,9 +114,13 @@ is a Hive-initialized repository (`.hive/roles/queen.md`), so it works without t
114
114
  panel; `/queen off` explicitly exempts that Session, and detection registers it
115
115
  idempotently so the panel can show it. Task
116
116
  metadata (add/reopen/retry/rm), roles and lessons are coordination state, not code.
117
- The veto covers only the queen's own tool calls: supervisor dispatch
118
- (`ctx.subagents.startActivation`) and a worker's own subagent calls are not tool
119
- calls and remain allowed.
117
+ Worker Sessions are exempt first: the guard asks the supervisor's
118
+ `isWorkerSession(sessionId)` registry (activeRuns, including a child id reserved
119
+ before activation) and falls back to `parentSession === queenSessionId` or
120
+ `origin: "subagent"`, so a card worker keeps write/edit/bash even when its cwd is
121
+ the initialized repository. The veto covers only the queen's own tool calls;
122
+ supervisor dispatch (`ctx.subagents.startActivation`) and a worker's own subagent
123
+ calls are not tool calls and remain allowed.
120
124
 
121
125
  ### When the queen hears from the supervisor
122
126
 
@@ -521,9 +525,11 @@ repository; treat the repository as trusted input. A read-only deployment cannot
521
525
  write tasks.
522
526
 
523
527
  **What survives a DSH restart?** Per-role limits (in `.hive/limits.json`) and the Hive
524
- state (in git refs) survive. In-memory queues and the queen registration do not: claimed
525
- tasks return to the board after their claim TTL, and the panel re-registers the queen
526
- Session on its next access.
528
+ state (in git refs) survive. In-memory queues and the queen registration do not, and
529
+ the panel re-registers the queen Session on its next access. Claims left by the previous
530
+ supervisor process itself are recovered on the first tick: their announcements are
531
+ released and the tasks are reopened (`orphaned by supervisor restart`), so they do not
532
+ look in-progress for the whole claim TTL. Claims owned by other agents are left alone.
527
533
 
528
534
  **Do I need the Hive panel?** Yes. The supervisor itself starts from `cordis.patch.yml`
529
535
  alone, but nothing is dispatched until a live Session registers as the queen; the panel
package/README.zh-CN.md CHANGED
@@ -69,6 +69,10 @@
69
69
  智能体和 supervisor),也没有改代码或 commit 的工具;女王契约同样禁止改代码。任务元数据
70
70
  (add/reopen/retry/rm)、角色和经验属于协调状态,不是代码。
71
71
 
72
+ worker 会话优先豁免:guard 先查 supervisor 的 `isWorkerSession(sessionId)`(activeRuns,含
73
+ activation 前预留的 child id),再用 `parentSession === queenSessionId` 或 `origin: "subagent"`
74
+ 兜底,因此 worker 的 write/edit/bash 不会被当成女王越界,即使它的 cwd 是已初始化的仓库。
75
+
72
76
  ### supervisor 什么时候找女王
73
77
 
74
78
  runner 把监督事件——`card-failed`、`card-timeout`、`heartbeat-warn`、
@@ -368,7 +372,7 @@ DSH 宿主进程(应用开着就一直在)
368
372
 
369
373
  **它会不问就写吗?** 它通过仓库正常的 Hive 和 git 流程认领任务、提交。验收命令来自任务,也就是来自仓库——把仓库当作可信输入。只读部署无法 claim/写任务。
370
374
 
371
- **DSH 重启后什么还在?** 每角色上限(`.hive/limits.json`)和 Hive 状态(git refs)都在;内存队列和女王登记不在,已 claim 的任务会在 claim TTL 后回到看板,面板下次访问会重新登记女王会话。
375
+ **DSH 重启后什么还在?** 每角色上限(`.hive/limits.json`)和 Hive 状态(git refs)都在;内存队列和女王登记不在,面板下次访问会重新登记女王会话。上一个 supervisor 进程自己留下的 claim 会在重启后的第一个 tick 被回收:释放路径公告并把任务 reopen(`orphaned by supervisor restart`),不会让面板白等整个 claim TTL;其他 agent 的 claim 不会被碰。
372
376
 
373
377
  **必须要装 Hive 面板吗?** 必须。supervisor 本身只靠 `cordis.patch.yml` 就能启动,但在有在线 Session 登记为女王之前什么都不会派发;登记由面板完成(初始化/女王模式),上限和恢复控件也在面板里。
374
378
 
package/SPEC.md CHANGED
@@ -62,6 +62,8 @@ wrong method -> `405` (`hive/method-not-allowed`).
62
62
  "lastDiscoverError": null,
63
63
  "pendingAnomalies": 0,
64
64
  "repoCount": 1,
65
+ "claimedButOrphaned": 0,
66
+ "workerSessionIds": ["worker-session-id"],
65
67
  "repos": [
66
68
  {
67
69
  "repo": "/abs/repo",
@@ -78,6 +80,9 @@ wrong method -> `405` (`hive/method-not-allowed`).
78
80
  "lastCards": 0,
79
81
  "lastResults": 0,
80
82
  "waiting": null,
83
+ "claimedButOrphaned": 0,
84
+ "orphanRecovered": 0,
85
+ "orphanRecoveryAt": null,
81
86
  "backlog": { "queued": 3, "inFlight": 5, "completed": 12 },
82
87
  "roles": {
83
88
  "coder": { "limit": 5, "live": 5, "queued": 3 },
@@ -123,6 +128,14 @@ wrong method -> `405` (`hive/method-not-allowed`).
123
128
  `"no-queen-session"` until that registration happens.
124
129
  - `waiting` — per repository (and top level) `"no-queen-session"` before the queen
125
130
  Session is registered; then `null`. It is a startup-order hint, never an error.
131
+ - `claimedButOrphaned` / `orphanRecovered` / `orphanRecoveryAt` — after a supervisor
132
+ restart, the first tick releases announcements for claims owned by this runner
133
+ identity (not by another agent) and not backed by a live worker, then reopens them
134
+ with reason `orphaned by supervisor restart`; the values are the detected and
135
+ reopened counts and the recovery time. The top-level status aggregates the counts.
136
+ - `workerSessionIds` — worker Session ids across repositories, also available via
137
+ `hiveSupervisor.isWorkerSession(sessionId)` / `workerSessionIds()`; the panel uses
138
+ this to keep worker conversations out of queen mode.
126
139
  - `workers` — the agents currently running in this repository, each with
127
140
  `cardId`, `role`, `agent`, `sessionId`, `agentName`, `parentSource` (`queen`),
128
141
  `startedAt`, `lastOutputAt`,
@@ -247,6 +260,15 @@ registered Session is live, every activation uses exactly its Agent. There is no
247
260
  fallback to another Session or to the first live Agent; once registered, dispatch
248
261
  does not depend on any other user session being live.
249
262
 
263
+ On the first tick for each registered repository the supervisor also recovers this
264
+ runner's own orphaned claims: claimed tasks whose owner is `config.agent` and whose
265
+ id is not in the current live workers are treated as left by the previous process.
266
+ Their scope announcements are released, the tasks are reopened with reason
267
+ `orphaned by supervisor restart` (attempt+1), and the same tick continues to normal
268
+ dispatch. Claims owned by other agents are never touched. Status exposes
269
+ `claimedButOrphaned` / `orphanRecovered` / `orphanRecoveryAt` per repository (and the
270
+ aggregate count).
271
+
250
272
  Before every drain the supervisor requires a Hive-initialised repository whose
251
273
  `<repo>/.git/hooks/pre-commit` runs merge-on-commit (it mentions merge-on-commit or moc).
252
274
  A missing hook is a deferrable environment error: the repository backs off,
@@ -367,7 +389,12 @@ fails with `女王不改代码,请用 hive_tasks 建任务,执行交给 supe
367
389
  pushed as a `queen-boundary-violation` anomaly so the digest reaches the queen, and
368
390
  counted in status (`queenBoundaryViolations`, `lastQueenBoundaryViolation`). A cwd-
369
391
  recognized queen is also registered through `setQueenSession()` (idempotent) so the
370
- panel can display it. The guard sees model-requested tool executions only; supervisor dispatch through
392
+ panel can display it. Worker Sessions are exempt from the whole boundary: the guard
393
+ first asks `hiveSupervisor.isWorkerSession(sessionId)` (activeRuns, including the
394
+ reserved child id before activation) and falls back to header lineage
395
+ (`origin: "subagent"`, positive `delegationDepth`, or `parentSession === queenSessionId`),
396
+ returning before any queen classification so write/edit/bash work normally. The guard
397
+ sees model-requested tool executions only; supervisor dispatch through
371
398
  `ctx.subagents.startActivation` and a worker's own subagent calls do not pass through
372
399
  it, so the swarm and worker delegation keep working.
373
400
 
package/docs/DESIGN.md CHANGED
@@ -51,6 +51,8 @@ Response:
51
51
  "lastDiscoverError": null,
52
52
  "pendingAnomalies": 0,
53
53
  "repoCount": 1,
54
+ "claimedButOrphaned": 0,
55
+ "workerSessionIds": ["worker-session-id"],
54
56
  "repos": [
55
57
  {
56
58
  "repo": "/abs/repo",
@@ -67,6 +69,9 @@ Response:
67
69
  "lastCards": 0,
68
70
  "lastResults": 0,
69
71
  "waiting": null,
72
+ "claimedButOrphaned": 0,
73
+ "orphanRecovered": 0,
74
+ "orphanRecoveryAt": null,
70
75
  "backlog": { "queued": 3, "inFlight": 5, "completed": 12 },
71
76
  "roles": {
72
77
  "coder": { "limit": 5, "live": 5, "queued": 3 },
@@ -117,6 +122,18 @@ Response:
117
122
  - `queenBoundaryViolations` — how many direct `subagent`/`subagent_fork`/
118
123
  `subagent_claude_code` calls from the queen Session the tool guard has vetoed;
119
124
  `lastQueenBoundaryViolation` is `{ tool, sessionId, at, repo }` for the most recent.
125
+ - `claimedButOrphaned` / `orphanRecovered` / `orphanRecoveryAt` — claims left by
126
+ this runner identity when the process restarted. The first tick releases their
127
+ announcements and reopens the cards (attempt+1, reason
128
+ `orphaned by supervisor restart`) before normal dispatch; `claimedButOrphaned`
129
+ is the count found, `orphanRecovered` the count reopened. Claims owned by other
130
+ agents are not touched. Top-level status aggregates the per-repo counts.
131
+ - `workerSessionIds` — all live worker Session ids across repositories. The panel
132
+ reads this (or calls the `hiveSupervisor.isWorkerSession(sessionId)` /
133
+ `workerSessionIds()` service methods) to exempt worker conversations from queen
134
+ prompt injection and the queen tool guard. A local provider's child id is reserved
135
+ and placed in `activeRuns` before activation, so the just-activated window is
136
+ covered too.
120
137
  - `workers` — live agents in this repository: `cardId`, `role`, `agent`,
121
138
  `sessionId`, `agentName`, `startedAt`, `lastOutputAt`, `heartbeat`
122
139
  (`ok`/`warn`), `claimDeadline`, `timeoutAt`. The Session id is written into the
@@ -218,6 +235,21 @@ Environmental errors (no live parent Agent, no subagent provider) are
218
235
  deferrable: they set `lastError` and back off for `idleBackoffMs` without
219
236
  consuming the failure budget.
220
237
 
238
+ ### Restart claim recovery
239
+
240
+ On the first tick for each registered repository, the supervisor calls
241
+ `runner.recoverOrphans`. It lists claimed cards and handles only claims whose
242
+ `owner` equals `config.agent` and whose id is not in the current `activeRuns` (a
243
+ worker from this process). For each such orphan it best-effort releases the card
244
+ scope announcements (`hive release <scope>`), then reopens the card with
245
+ `reason = "orphaned by supervisor restart"` (the Hive CLI increments `attempt`).
246
+ The same tick continues with the normal ready-card fetch, so reopened cards are
247
+ dispatched immediately instead of waiting for the 20-minute claim TTL. Claims owned
248
+ by other agents are never read past the filter: no release, no reopen. A failed
249
+ scan/reopen backs off and retries on the next tick without consuming the
250
+ auto-pause failure budget; status exposes `claimedButOrphaned`,
251
+ `orphanRecovered` and `orphanRecoveryAt` per repository (and an aggregate count).
252
+
221
253
  ## 6. Module layout
222
254
 
223
255
  | File | Responsibility |
@@ -323,11 +355,14 @@ needed and is not implemented.
323
355
  - it also becomes a `queen-boundary-violation` anomaly, so the coalesced anomaly digest
324
356
  tells the queen to self-correct; `status` exposes `queenBoundaryViolations` and
325
357
  `lastQueenBoundaryViolation`;
326
- - it only vetoes **model-requested tool calls from the queen Session**. The
327
- supervisor's swarm dispatch (`ctx.subagents.startActivation`) is a service call,
328
- not a tool execution, so it bypasses `tools.guard` and keeps working from the same
329
- queen Session; worker/child Sessions and their own subagent tools are unaffected
330
- (PTC nested tool calls share the same pipeline and are covered by the predicate).
358
+ - it only vetoes **model-requested tool calls from the queen Session**. Worker
359
+ Sessions are checked first and get **every tool back** (write/edit/bash/...) so a
360
+ card can actually run: the supervisor's `isWorkerSession(sessionId)` registry
361
+ (activeRuns, including a locally reserved child id before activation) is
362
+ authoritative; the Session header (`origin: "subagent"`, positive
363
+ `delegationDepth`, or `parentSession === queenSessionId`) is the restart/provider
364
+ fallback. The supervisor's swarm dispatch (`ctx.subagents.startActivation`) is a
365
+ service call, not a tool execution, so it bypasses `tools.guard` as well.
331
366
 
332
367
  Tests: `test/queen-boundary.test.js` covers all three delegation tools and the
333
368
  mutation tools (write/edit/bash/notebook/run_code denied; read/grep/web/hive allowed),
package/index.js CHANGED
@@ -197,6 +197,8 @@ export function apply(ctx, config = {}) {
197
197
  onViolation: recordQueenBoundaryViolation,
198
198
  onQueenDetected: registerDetectedQueen,
199
199
  resolveCwd: resolveQueenBoundaryCwd,
200
+ // Authoritative worker registry (activeRuns, incl. reserved child ids).
201
+ isWorkerSession: (sessionId) => supervisor.isWorkerSession(sessionId),
200
202
  log,
201
203
  })));
202
204
 
@@ -229,6 +231,7 @@ export function apply(ctx, config = {}) {
229
231
  : undefined,
230
232
  listReady: runner.listReady,
231
233
  listAll: (repo, options = {}) => commands.list(repo, {}, options),
234
+ recoverOrphans: runner.recoverOrphans,
232
235
  runCard: runner.runCard,
233
236
  preflight: runner.preflight,
234
237
  activeRuns: (repo) => runner.activeRuns(repo),
@@ -180,12 +180,23 @@ export function isQueenSuppressed(session) {
180
180
  return latestQueenCommand(session) === 'off';
181
181
  }
182
182
 
183
- /** Whether a Session is a card worker / delegation child, never the queen. */
184
- export function isWorkerSession(session) {
183
+ /**
184
+ * Session-header heuristic for a card worker / delegation child, never the
185
+ * queen. The authoritative check is the supervisor's activeRuns registry; this
186
+ * covers the window before a provider-reported child id reaches it and worker
187
+ * Sessions that survive a plugin restart.
188
+ * @param {object} session
189
+ * @param {string | null} [queenSessionId]
190
+ * @returns {boolean}
191
+ */
192
+ export function isWorkerSession(session, queenSessionId) {
185
193
  const header = session?.header;
186
194
  if (header === null || typeof header !== 'object') return false;
187
- return header.origin === 'subagent'
188
- || (Number.isInteger(header.delegationDepth) && header.delegationDepth > 0);
195
+ if (header.origin === 'subagent') return true;
196
+ if (Number.isInteger(header.delegationDepth) && header.delegationDepth > 0) return true;
197
+ return typeof queenSessionId === 'string'
198
+ && queenSessionId !== ''
199
+ && header.parentSession === queenSessionId;
189
200
  }
190
201
 
191
202
  /** Structured error identity recorded on the failed tool result. */
@@ -203,6 +214,7 @@ export const QUEEN_BOUNDARY_ERROR = Object.freeze({
203
214
  * resolveCwd?: (agent: object, session: object) => string | null,
204
215
  * hasRole?: (cwd: string) => boolean,
205
216
  * isSuppressed?: (session: object) => boolean,
217
+ * isWorkerSession?: (sessionId: string, session: object) => boolean,
206
218
  * log?: (level: string, ...args: unknown[]) => void,
207
219
  * }} options
208
220
  * @returns {(exec: { name: string, agent?: { session?: object } }) => object | undefined}
@@ -214,21 +226,34 @@ export function createQueenBoundaryGuard({
214
226
  resolveCwd,
215
227
  hasRole = hasQueenRole,
216
228
  isSuppressed = isQueenSuppressed,
229
+ isWorkerSession: isKnownWorkerSession,
217
230
  log = () => {},
218
231
  } = {}) {
219
232
  return function queenBoundaryGuard(exec) {
220
233
  if (exec === null || typeof exec !== 'object') return undefined;
221
- const toolClass = queenBoundaryToolClass(exec.name);
222
- if (toolClass === null) return undefined;
223
234
  const session = exec.agent?.session;
224
235
  const sessionId = session?.id;
225
236
  if (typeof sessionId !== 'string' || sessionId === '') return undefined;
226
237
 
227
238
  const queenSessionId = queenSession?.sessionId;
228
239
  const registered = typeof queenSessionId === 'string' && queenSessionId !== '' && sessionId === queenSessionId;
229
- // Worker/child Sessions never need the (possibly long) log scan and are
230
- // outside the queen boundary.
231
- if (!registered && isWorkerSession(session)) return undefined;
240
+ // Workers are never the queen: the supervisor's activeRuns registry is
241
+ // authoritative (including a child id reserved before activation), and
242
+ // the Session header covers the provider/restart window. A worker gets
243
+ // every tool back, before any queen recognition or log scan.
244
+ let worker = false;
245
+ try {
246
+ worker = typeof isKnownWorkerSession === 'function'
247
+ ? isKnownWorkerSession(sessionId, session) === true
248
+ : false;
249
+ } catch {
250
+ worker = false;
251
+ }
252
+ if (!worker) worker = isWorkerSession(session, queenSessionId);
253
+ if (worker) return undefined;
254
+
255
+ const toolClass = queenBoundaryToolClass(exec.name);
256
+ if (toolClass === null) return undefined;
232
257
 
233
258
  // `/queen off` wins over both recognition paths.
234
259
  let suppressed = false;
@@ -246,7 +271,7 @@ export function createQueenBoundaryGuard({
246
271
  } catch {
247
272
  cwd = null;
248
273
  }
249
- const initialised = !isWorkerSession(session) && hasRole(cwd);
274
+ const initialised = hasRole(cwd);
250
275
  if (!registered && !initialised) return undefined;
251
276
 
252
277
  if (!registered && initialised && typeof onQueenDetected === 'function') {
package/lib/round.js CHANGED
@@ -15,6 +15,8 @@
15
15
  * (missing hook = deferrable environment error, run `hive init`) and a card is
16
16
  * only recorded done when HEAD moved through that hook-equipped commit path.
17
17
  */
18
+ import { randomUUID } from 'node:crypto';
19
+
18
20
  import { parseTtlMs, roleLimitForRepo } from './config.js';
19
21
  import { HiveCommandError, tail } from './commands.js';
20
22
  import { assertMergeOnCommitHook } from './hooks.js';
@@ -22,6 +24,9 @@ import { acquireHiveAgentEnv } from './host-env.js';
22
24
  import { isCapacityError } from './queue.js';
23
25
  import { writeRunRecord } from './runs.js';
24
26
 
27
+ /** Reopen reason used when the supervisor recovers a claim after a restart. */
28
+ export const ORPHAN_REOPEN_REASON = 'orphaned by supervisor restart';
29
+
25
30
  /** A round-level failure. `hive/capacity` is retried from the queue. */
26
31
  export class RoundError extends Error {
27
32
  constructor(code, message, options = {}) {
@@ -543,6 +548,22 @@ export function createRoundRunner({
543
548
  // claim identity and this card's instance while the worker is alive, so
544
549
  // its own `hive guard` / `hive release` calls agree with the runner's.
545
550
  releaseEnv = acquireHiveAgentEnv(claimAgent, instance);
551
+ // Local providers can reserve the child Session id before activation.
552
+ // Recording it on the active run closes the window where a just-started
553
+ // worker calls a tool before the provider-reported id reaches activeRuns
554
+ // (the guard consults that registry to exempt worker Sessions).
555
+ let reservedChildId;
556
+ try {
557
+ const provider = typeof service.getProvider === 'function' ? service.getProvider(config.provider) : undefined;
558
+ if (provider !== undefined && typeof provider.prepareContinuable === 'function') reservedChildId = randomUUID();
559
+ } catch {
560
+ reservedChildId = undefined;
561
+ }
562
+ if (typeof reservedChildId === 'string') {
563
+ run.sessionId = reservedChildId;
564
+ recordRun(repo, run);
565
+ }
566
+
546
567
  // Hard per-card timeout: abort the worker at the deadline.
547
568
  timeoutTimer = setTimeout(() => {
548
569
  if (settled) return;
@@ -566,6 +587,7 @@ export function createRoundRunner({
566
587
  parent: owner,
567
588
  signal: workerSignal,
568
589
  delivery: 'caller',
590
+ ...(reservedChildId === undefined ? {} : { childId: reservedChildId }),
569
591
  }),
570
592
  abortWait.then(() => null),
571
593
  ]);
@@ -748,6 +770,64 @@ export function createRoundRunner({
748
770
  return cards.filter((card) => capFor(repo, card?.role) > 0);
749
771
  },
750
772
 
773
+ /**
774
+ * Recover claims left behind by a previous supervisor process. Only cards
775
+ * claimed by this runner identity and not represented by a live worker are
776
+ * touched: their scope announcements are released and the card is reopened
777
+ * with an attempt+1 for normal dispatch. Claims of other agents are never
778
+ * touched.
779
+ * @param {string} repo
780
+ * @param {{ signal?: AbortSignal, session?: object, activeCardIds?: Iterable<string> }} [options]
781
+ * @returns {Promise<{ checked: number, orphans: string[], recovered: string[], failed: object[] }>}
782
+ */
783
+ async recoverOrphans(repo, { signal, session, activeCardIds } = {}) {
784
+ if (typeof repo !== 'string' || repo === '') throw new TypeError('recoverOrphans: repo is required');
785
+ const agentId = config.agent;
786
+ const claimed = await commands.list(repo, { state: 'claimed', agent: agentId, signal, session });
787
+ const active = new Set();
788
+ if (activeCardIds !== undefined && activeCardIds !== null) {
789
+ for (const id of activeCardIds) active.add(id);
790
+ }
791
+ const cards = Array.isArray(claimed) ? claimed : [];
792
+ const orphans = cards.filter((card) => card !== null
793
+ && typeof card === 'object'
794
+ && card.state === 'claimed'
795
+ && card.owner === agentId
796
+ && typeof card.id === 'string'
797
+ && !active.has(card.id));
798
+ const recovered = [];
799
+ const failed = [];
800
+ for (const card of orphans) {
801
+ const scope = scopeOf(card);
802
+ if (scope.length > 0) {
803
+ try {
804
+ await commands.release(repo, scope, { agent: agentId, signal, session });
805
+ } catch (error) {
806
+ // Announcement release is best-effort; reopen still recovers the card.
807
+ log('warn', 'orphan claim release failed for ' + card.id + ': ' + messageOf(error));
808
+ }
809
+ }
810
+ try {
811
+ await commands.reopen(repo, card.id, {
812
+ reason: ORPHAN_REOPEN_REASON,
813
+ agent: agentId,
814
+ signal,
815
+ session,
816
+ });
817
+ recovered.push(card.id);
818
+ log('warn', 'recovered orphaned claim', card.id, 'in', repo);
819
+ } catch (error) {
820
+ failed.push({ id: card.id, error: messageOf(error) });
821
+ log('warn', 'orphan claim reopen failed for ' + card.id + ': ' + messageOf(error));
822
+ }
823
+ }
824
+ return {
825
+ checked: cards.length,
826
+ orphans: orphans.map((card) => card.id),
827
+ recovered,
828
+ failed,
829
+ };
830
+ },
751
831
  /**
752
832
  * Run one card end to end. Fresh items are claimed here; retried items
753
833
  * arrive with `claimed: true` and reuse the claim if it survived the wait.
package/lib/supervisor.js CHANGED
@@ -133,6 +133,7 @@ export class HiveSupervisor {
133
133
  * @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
134
134
  * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
135
135
  * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
136
+ * @param {(repo: string, options: object) => Promise<object>} [options.recoverOrphans] first-tick orphan claim recovery
136
137
  * @param {{ count: number, last: object | null }} [options.queenBoundary] queen boundary violation counters
137
138
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
138
139
  * @param {() => Promise<string[]>} [options.discover]
@@ -171,6 +172,7 @@ export class HiveSupervisor {
171
172
  // Shared with the round runner: the Session registered by the panel when the
172
173
  // queen takes over. Nothing is dispatched until this is set.
173
174
  this.queenSession = options.queenSession ?? { sessionId: null };
175
+ this.recoverOrphans = typeof options.recoverOrphans === 'function' ? options.recoverOrphans : undefined;
174
176
  this.queenBoundary = options.queenBoundary ?? { count: 0, last: null };
175
177
  this.readMode = typeof options.readMode === 'function' ? options.readMode : undefined;
176
178
  this.onAnomaly = typeof options.onAnomaly === 'function' ? options.onAnomaly : undefined;
@@ -271,6 +273,11 @@ export class HiveSupervisor {
271
273
  mode: null,
272
274
  frozenSkipped: 0,
273
275
  lastSkipReason: null,
276
+ // First-tick orphan-claim recovery: claims left by the previous process.
277
+ orphanRecoveryDone: false,
278
+ claimedButOrphaned: 0,
279
+ orphanRecovered: 0,
280
+ orphanRecoveryAt: null,
274
281
  };
275
282
  if (this.configPaused.has(key)) {
276
283
  entry.paused = true;
@@ -382,6 +389,38 @@ export class HiveSupervisor {
382
389
  return this.status();
383
390
  }
384
391
 
392
+ /**
393
+ * Live worker Session ids across every registered repository. The panel uses
394
+ * this to exempt worker conversations from the queen role/prompt and guard.
395
+ * @returns {string[]}
396
+ */
397
+ workerSessionIds() {
398
+ const ids = new Set();
399
+ for (const entry of this.repos.values()) {
400
+ for (const worker of this.#workers(entry.repo)) {
401
+ if (typeof worker?.sessionId === 'string' && worker.sessionId !== '') ids.add(worker.sessionId);
402
+ }
403
+ }
404
+ return [...ids];
405
+ }
406
+
407
+ /**
408
+ * Whether a Session is one of the supervisor's card workers. This is the
409
+ * authoritative registry check used by the queen tool guard and the panel;
410
+ * guard fallbacks based on Session header lineage cover the short window
411
+ * before a provider-reported child id reaches activeRuns.
412
+ * @param {string} sessionId
413
+ * @returns {boolean}
414
+ */
415
+ isWorkerSession(sessionId) {
416
+ if (typeof sessionId !== 'string' || sessionId === '') return false;
417
+ for (const entry of this.repos.values()) {
418
+ for (const worker of this.#workers(entry.repo)) {
419
+ if (worker?.sessionId === sessionId) return true;
420
+ }
421
+ }
422
+ return false;
423
+ }
385
424
  /**
386
425
  * Read every card of one repository and compute the gate phase that governs
387
426
  * dispatch. Falls back to an explicit phase when the board read fails; a
@@ -485,6 +524,9 @@ export class HiveSupervisor {
485
524
  const waiting = this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
486
525
  ? 'no-queen-session'
487
526
  : null;
527
+ const repoSnapshots = [...this.repos.values()]
528
+ .map((entry) => this.#snapshot(entry))
529
+ .sort((a, b) => a.repo.localeCompare(b.repo));
488
530
  return {
489
531
  started: this.started,
490
532
  // The queen Session registered by the panel; every card worker is parented
@@ -508,9 +550,12 @@ export class HiveSupervisor {
508
550
  // Undelivered anomaly digests waiting for a live queen Session.
509
551
  pendingAnomalies: this.#pendingAnomalyCount(),
510
552
  repoCount: this.repos.size,
511
- repos: [...this.repos.values()]
512
- .map((entry) => this.#snapshot(entry))
513
- .sort((a, b) => a.repo.localeCompare(b.repo)),
553
+ // Worker Session ids across all repositories: the panel exempts them from
554
+ // queen-mode prompt injection and the guard exempts their tool calls.
555
+ workerSessionIds: this.workerSessionIds(),
556
+ // Aggregate of the per-repository orphan-claim counts.
557
+ claimedButOrphaned: repoSnapshots.reduce((sum, repo) => sum + repo.claimedButOrphaned, 0),
558
+ repos: repoSnapshots,
514
559
  };
515
560
  }
516
561
 
@@ -540,6 +585,41 @@ export class HiveSupervisor {
540
585
  const signal = this.abortController?.signal;
541
586
  try {
542
587
  if (entry.paused) return { repo: entry.repo, state: entry.state };
588
+
589
+ // First tick after (re)start: claims held by this runner identity but not
590
+ // backed by a live worker are from the previous process. Release their
591
+ // announcements, reopen them (attempt+1) and dispatch them below. Claims
592
+ // of other agents are never touched.
593
+ if (!entry.orphanRecoveryDone && typeof this.recoverOrphans === 'function') {
594
+ try {
595
+ const activeCardIds = new Set(this.#workers(entry.repo).map((worker) => worker.cardId));
596
+ const recovered = await this.recoverOrphans(entry.repo, { signal, activeCardIds });
597
+ entry.orphanRecoveryDone = true;
598
+ entry.orphanRecoveryAt = this.now();
599
+ entry.claimedButOrphaned = Array.isArray(recovered?.orphans)
600
+ ? recovered.orphans.length
601
+ : Number.isInteger(recovered?.orphans) ? recovered.orphans : 0;
602
+ entry.orphanRecovered = Array.isArray(recovered?.recovered) ? recovered.recovered.length : entry.claimedButOrphaned;
603
+ if (entry.claimedButOrphaned > 0) {
604
+ this.#log('info', 'recovered orphaned claims in ' + entry.repo + ':', entry.orphanRecovered + '/' + entry.claimedButOrphaned);
605
+ }
606
+ const failed = Array.isArray(recovered?.failed) ? recovered.failed : [];
607
+ if (failed.length > 0) {
608
+ entry.lastError = 'orphan claim recovery failed for ' + failed.map((item) => item?.id).join(', ');
609
+ this.#log('warn', 'orphan claim recovery left claims behind', entry.lastError);
610
+ }
611
+ } catch (error) {
612
+ // Retry on the next tick; an unreadable/reopen-failing board must not
613
+ // be treated as a normal empty round or consume the failure budget.
614
+ entry.lastError = 'orphan claim recovery failed: ' + messageOf(error);
615
+ entry.environmentError = isDeferrableError(error) ? messageOf(error) : null;
616
+ entry.state = STATES.BACKOFF;
617
+ entry.lastCheckAt = this.now();
618
+ entry.nextAttemptAt = this.now() + this.intervalMs;
619
+ return { repo: entry.repo, state: entry.state, error: entry.lastError };
620
+ }
621
+ }
622
+
543
623
  // One parent only: the queen Session registered by the panel. Before that
544
624
  // registration the supervisor waits; it never picks another Session.
545
625
  if (this.queenSession.sessionId === null || this.queenSession.sessionId === undefined) {
@@ -727,6 +807,12 @@ export class HiveSupervisor {
727
807
  consecutiveFailures: entry.consecutiveFailures,
728
808
  lastCards: entry.lastCards,
729
809
  lastResults: entry.lastResults,
810
+ // Claims left by this runner identity after a restart; they are recovered
811
+ // on the first tick and shown here so a panel can distinguish them from
812
+ // live work in the meantime.
813
+ claimedButOrphaned: Number.isInteger(entry.claimedButOrphaned) ? entry.claimedButOrphaned : 0,
814
+ orphanRecovered: Number.isInteger(entry.orphanRecovered) ? entry.orphanRecovered : 0,
815
+ orphanRecoveryAt: iso(entry.orphanRecoveryAt),
730
816
  backlog: { ...entry.backlog },
731
817
  roles: copyRoles(entry.roles),
732
818
  // Live workers currently running in this repository: sessionId/start time
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "DSH host plugin for Hive: a resident supervisor that runs one DSH subagent per ready task card, with per-role worker limits, pause/resume and Hive tools.",
5
5
  "type": "module",
6
6
  "main": "./index.js",