dsh-hive-runner 1.0.10 → 1.0.13

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,51 @@ 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.13] - 2026-12-05
11
+
12
+ ### Added
13
+
14
+ - Progress checkpoints delivered to the queen: the patrol now reports progress, not
15
+ only anomalies. Triggers: a drained queue (no pending/claimed, at least
16
+ `checkpointDrainMs` since the last checkpoint), all tasks done / gate phase advance /
17
+ `releaseReady` flip, or no ready task for `checkpointIdleMs` while unfinished goals
18
+ remain. The digest carries done/failed/pending/claimed/total counts, recent completed
19
+ titles, gate phase/releaseReady, a bounded last-10-minute event summary and the
20
+ instruction to evaluate the goal (split the next batch, or summarize and ask the human
21
+ to confirm release). A state signature deduplicates it; no live queen Session keeps
22
+ checkpoints pending (`status.pendingCheckpoints`) until the next patrol/registration.
23
+ - New config keys `checkpointDrainMs` / `checkpointIdleMs` (defaults 600000).
24
+
25
+ ## [1.0.12] - 2026-12-05
26
+
27
+ ### Fixed
28
+
29
+ - The queen can use `run_code` again: PTC mode exposes only `run_code` and the
30
+ mutation list wrongly vetoed it, leaving the queen with no callable tool. `run_code`
31
+ is removed from `QUEEN_MUTATING_TOOLS`; its nested `tools.write` / `tools.edit` /
32
+ `tools.bash` dispatches still pass the same Agent into the shared PTC pipeline, so
33
+ `ctx.tools.guard` vetoes the nested mutation before the body runs. Direct
34
+ write/edit/bash/apply_patch/notebook/office/terminal calls remain vetoed.
35
+ - Boundary denial text now says `女王可以用 hive_* 与只读工具,实现请交给 worker`
36
+ instead of suggesting a workflow that leaves the PTC queen tool-less.
37
+
38
+ ## [1.0.11] - 2026-12-05
39
+
40
+ ### Fixed
41
+
42
+ - Worker Sessions are no longer mistaken for the queen. The supervisor exposes
43
+ `isWorkerSession(sessionId)` / `workerSessionIds()` (backed by `activeRuns`, with
44
+ status top-level `workerSessionIds` for the panel); local providers reserve the
45
+ child Session id before activation and put it in `activeRuns`, closing the
46
+ just-activated window. The queen tool guard returns before any classification for
47
+ worker Sessions, with `origin: "subagent"`, positive `delegationDepth`, or
48
+ `parentSession === queenSessionId` as the restart/provider fallback, so a worker's
49
+ write/edit/bash and subagent tools keep working while the queen is still denied.
50
+
51
+ ### Published
52
+
53
+ - npm: `dsh-hive-runner@1.0.11` on 2026-12-05.
54
+
10
55
  ## [1.0.10] - 2026-12-05
11
56
 
12
57
  ### Fixed
@@ -25,6 +70,10 @@ iterations of the plugin before this repository was published.
25
70
  repository (plus an aggregate `claimedButOrphaned` at the top level), so a panel
26
71
  can distinguish recovered stale claims from real in-flight work.
27
72
 
73
+ ### Published
74
+
75
+ - npm: `dsh-hive-runner@1.0.10` on 2026-12-05.
76
+
28
77
  ## [1.0.9] - 2026-12-05
29
78
 
30
79
  ### Removed
package/README.md CHANGED
@@ -104,19 +104,25 @@ The tool surface keeps the boundary: none of the queen's tools claims or finishe
104
104
  commits code. The boundary is enforced, not just documented: the runner registers a
105
105
  DSH `ctx.tools.guard`, so a queen Session calling a delegation tool (`subagent`,
106
106
  `subagent_fork`, `subagent_claude_code`) or a mutation tool (`write`, `edit`, `bash`,
107
- `apply_patch`, notebook/office/terminal/run_code tools, ...) directly gets a failed
108
- tool result telling her `女王不改代码,请用 hive_tasks 建任务,执行交给 supervisor`;
107
+ `apply_patch`, notebook/office/terminal tools, ...) directly gets a failed
108
+ tool result telling her `女王可以用 hive_* 与只读工具,实现请交给 worker`;
109
109
  read-only tools (`read`, `grep`, `glob`, `web_*`, `hive_*`, `list_agents`, ...) stay
110
- available. The attempt is recorded as a `queen_boundary_violation` event (with an
110
+ available. `run_code` is allowed (it is the PTC transport), while a nested
111
+ write/edit/bash dispatch inside the program still passes the same guard and is
112
+ vetoed. The attempt is recorded as a `queen_boundary_violation` event (with an
111
113
  anomaly digest for self-correction). The
112
114
  guard recognizes the queen by registration or by an ordinary chat Session whose cwd
113
115
  is a Hive-initialized repository (`.hive/roles/queen.md`), so it works without the
114
116
  panel; `/queen off` explicitly exempts that Session, and detection registers it
115
117
  idempotently so the panel can show it. Task
116
118
  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.
119
+ Worker Sessions are exempt first: the guard asks the supervisor's
120
+ `isWorkerSession(sessionId)` registry (activeRuns, including a child id reserved
121
+ before activation) and falls back to `parentSession === queenSessionId` or
122
+ `origin: "subagent"`, so a card worker keeps write/edit/bash even when its cwd is
123
+ the initialized repository. The veto covers only the queen's own tool calls;
124
+ supervisor dispatch (`ctx.subagents.startActivation`) and a worker's own subagent
125
+ calls are not tool calls and remain allowed.
120
126
 
121
127
  ### When the queen hears from the supervisor
122
128
 
@@ -146,6 +152,15 @@ Two guarantees keep this quiet:
146
152
  gone the digest stays in the pending list: `hive_anomalies` lists and acknowledges it,
147
153
  `hive_supervisor_status` reports `pendingAnomalies`, and the next registered queen
148
154
  Session flushes the queue. `notifyQueen: false` keeps the pending list only.
155
+ Progress is reported separately from anomalies: when the queue drains (and at least
156
+ `checkpointDrainMs`, default 10 minutes, passed since the last checkpoint), when every
157
+ task is done or a gate phase advances, or when no task is ready for
158
+ `checkpointIdleMs` (default 10 minutes) while work remains, the queen gets a checkpoint
159
+ digest with task counts, recently completed titles, gate state and the last 10 minutes
160
+ of events. It asks her to evaluate the goal and either split the next batch or summarize
161
+ and ask the human to confirm release. The same state is sent once; a state change
162
+ re-arms it. With no live queen Session the checkpoint stays pending
163
+ (`pendingCheckpoints` in status) and is flushed on the next patrol/registration.
149
164
 
150
165
  ### The gates the queen orchestrates
151
166
 
@@ -284,6 +299,8 @@ written to `docs/CONVENTIONS.md` / `AGENTS.md` / an ADR, not just remembered in
284
299
  | `anomalyDebounceMs` | `3000` | coalescing window before one digest is sent |
285
300
  | `anomalyMax` | `50` | bound on the undelivered anomaly queue |
286
301
  | `archReviewGraceMs` | `600000` (10 min) | grace before a done task without an `arch_review` event is flagged |
302
+ | `checkpointDrainMs` | `600000` (10 min) | minimum gap between drained-queue progress checkpoints |
303
+ | `checkpointIdleMs` | `600000` (10 min) | no-ready time before the idle progress checkpoint fires |
287
304
  | `rolesBin` | `null` | executable for `hive roles` (umbrella `@d86e/hive`); falls back to `hiveBin` |
288
305
 
289
306
  ## Requirements
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`、
@@ -203,6 +207,8 @@ outstanding/failed 与 `releaseReady`、`reason`)。`releaseReady` 为 true
203
207
  | `anomalyDebounceMs` | `3000` | 合并成一条摘要前的防抖时间 |
204
208
  | `anomalyMax` | `50` | 待投递异常队列上限 |
205
209
  | `archReviewGraceMs` | `600000`(10 分钟) | done 任务缺少 `arch_review` 事件多久后被标记 |
210
+ | `checkpointDrainMs` | `600000`(10 分钟) | 队列排空后两次进度 checkpoint 的最小间隔 |
211
+ | `checkpointIdleMs` | `600000`(10 分钟) | 无 ready 任务多久后触发 idle 进度 checkpoint |
206
212
  | `rolesBin` | `null` | `hive roles` 的可执行文件(umbrella `@d86e/hive`),默认退回 `hiveBin` |
207
213
 
208
214
  ## 环境要求
package/SPEC.md CHANGED
@@ -63,6 +63,7 @@ wrong method -> `405` (`hive/method-not-allowed`).
63
63
  "pendingAnomalies": 0,
64
64
  "repoCount": 1,
65
65
  "claimedButOrphaned": 0,
66
+ "workerSessionIds": ["worker-session-id"],
66
67
  "repos": [
67
68
  {
68
69
  "repo": "/abs/repo",
@@ -119,6 +120,8 @@ wrong method -> `405` (`hive/method-not-allowed`).
119
120
  immediately.
120
121
  - `roles[role].queued` — fetched tasks waiting for a slot; they do not count as live.
121
122
  - `backlog` — aggregate `{ queued, inFlight, completed }` for the current or last drain.
123
+ - `pendingCheckpoints` — progress checkpoints queued while no live queen Session was
124
+ available; the next patrol/queen registration flushes them.
122
125
  - `repos` / `repoCount` — the status-visible repository registry. `hiveSupervisor.addRepo(repo)`
123
126
  adds one at runtime (absolute path, must be an initialized Hive repository; idempotent;
124
127
  rejects a relative or uninitialized path).
@@ -132,6 +135,9 @@ wrong method -> `405` (`hive/method-not-allowed`).
132
135
  identity (not by another agent) and not backed by a live worker, then reopens them
133
136
  with reason `orphaned by supervisor restart`; the values are the detected and
134
137
  reopened counts and the recovery time. The top-level status aggregates the counts.
138
+ - `workerSessionIds` — worker Session ids across repositories, also available via
139
+ `hiveSupervisor.isWorkerSession(sessionId)` / `workerSessionIds()`; the panel uses
140
+ this to keep worker conversations out of queen mode.
135
141
  - `workers` — the agents currently running in this repository, each with
136
142
  `cardId`, `role`, `agent`, `sessionId`, `agentName`, `parentSource` (`queen`),
137
143
  `startedAt`, `lastOutputAt`,
@@ -368,7 +374,22 @@ Agent exists the digest is *not* marked delivered: it stays pending, is listed b
368
374
  flushed by the next `setQueenSession` registration or patrol tick. A healthy swarm
369
375
  delivers nothing.
370
376
 
371
- ### 8.6.1 Queen tool boundary
377
+ ### 8.6.1 Progress checkpoints
378
+
379
+ The patrol also sends a progress digest to the queen (not just anomalies): (1) the
380
+ queue is drained — no pending/claimed tasks, including failed ones — and at least
381
+ `checkpointDrainMs` (default 10 min) passed since the last checkpoint; (2) all tasks
382
+ are done or the gate phase advanced / `releaseReady` became true; (3) no ready task
383
+ exists while unfinished tasks remain, continuously for `checkpointIdleMs` (default
384
+ 10 min). The digest carries done/failed/pending/claimed/total counts, recent completed
385
+ task titles, gate phase/releaseReady, a bounded last-10-minute event summary, the
386
+ trigger, and the instruction: `评估目标是否达成:未达成请继续拆解下一批任务并说明依据;
387
+ 达成请汇总结果并请人类确认发布。`. The same state is sent once (state signature =
388
+ counts + gate + recent completed ids); a change re-arms it. With no live queen
389
+ Session it stays pending (`status.pendingCheckpoints`) and is flushed by the next
390
+ patrol or queen registration.
391
+
392
+ ### 8.6.2 Queen tool boundary
372
393
 
373
394
  DSH's `ctx.tools.guard` lets a plugin veto a tool call after pre-execute policy and
374
395
  before the body. The runner registers one global guard. A Session is recognized as
@@ -377,15 +398,22 @@ whose cwd contains `.hive/roles/queen.md`; an explicit latest `/queen off` comma
377
398
  suppresses the veto for that Session (`/queen on` re-enables it). Two tool classes are
378
399
  vetoed: delegation (`subagent`, `subagent_fork`, `subagent_claude_code`) and mutation
379
400
  (an explicit `QUEEN_MUTATING_TOOLS` name list: write/edit/apply_patch/str_replace_editor,
380
- bash/pwsh/run_code, notebook/office/terminal/ralph/create_worktree and common aliases).
381
- Read-only tools (read/grep/glob/web_*/hive_*/list_agents/...) stay allowed. The call
382
- fails with `女王不改代码,请用 hive_tasks 建任务,执行交给 supervisor(检测到 <tool>
401
+ bash/pwsh, notebook/office/terminal/ralph/create_worktree and common aliases).
402
+ Read-only tools (read/grep/glob/web_*/hive_*/list_agents/...) stay allowed. `run_code`
403
+ is allowed because PTC is the queen's transport; its nested write/edit/bash calls carry
404
+ the same Agent and go through the shared pipeline's guard, so they are still vetoed.
405
+ The call fails with `女王可以用 hive_* 与只读工具,实现请交给 worker(检测到 <tool>
383
406
  调用,已拦截)`; the body never runs. The attempt is appended to `<repo>/.hive/events.jsonl` with
384
407
  `kind: "queen_boundary_violation"` (`ts`, `actor`, `tool`, `message`, `sessionId`),
385
408
  pushed as a `queen-boundary-violation` anomaly so the digest reaches the queen, and
386
409
  counted in status (`queenBoundaryViolations`, `lastQueenBoundaryViolation`). A cwd-
387
410
  recognized queen is also registered through `setQueenSession()` (idempotent) so the
388
- panel can display it. The guard sees model-requested tool executions only; supervisor dispatch through
411
+ panel can display it. Worker Sessions are exempt from the whole boundary: the guard
412
+ first asks `hiveSupervisor.isWorkerSession(sessionId)` (activeRuns, including the
413
+ reserved child id before activation) and falls back to header lineage
414
+ (`origin: "subagent"`, positive `delegationDepth`, or `parentSession === queenSessionId`),
415
+ returning before any queen classification so write/edit/bash work normally. The guard
416
+ sees model-requested tool executions only; supervisor dispatch through
389
417
  `ctx.subagents.startActivation` and a worker's own subagent calls do not pass through
390
418
  it, so the swarm and worker delegation keep working.
391
419
 
package/cordis.patch.yml CHANGED
@@ -91,6 +91,13 @@
91
91
  # card with no review after this grace (the queen reviews finished cards
92
92
  # at the next patrol).
93
93
  archReviewGraceMs: 600000
94
+ # Progress checkpoints (not just anomalies): when the queue drains, all
95
+ # cards are done, a gate advances, or no ready card exists while goals
96
+ # remain, the queen gets a digest asking whether the goal is achieved.
97
+ # checkpointDrainMs is the minimum gap for a drained-queue checkpoint;
98
+ # checkpointIdleMs is the no-ready duration before the idle checkpoint.
99
+ checkpointDrainMs: 600000
100
+ checkpointIdleMs: 600000
94
101
  # Subagent provider used to run card workers (spawn is the shipped
95
102
  # in-process fresh-child backend).
96
103
  provider: spawn
package/docs/DESIGN.md CHANGED
@@ -50,8 +50,10 @@ Response:
50
50
  "lastTickAt": "2026-12-04T00:00:00.000Z",
51
51
  "lastDiscoverError": null,
52
52
  "pendingAnomalies": 0,
53
+ "pendingCheckpoints": 0,
53
54
  "repoCount": 1,
54
55
  "claimedButOrphaned": 0,
56
+ "workerSessionIds": ["worker-session-id"],
55
57
  "repos": [
56
58
  {
57
59
  "repo": "/abs/repo",
@@ -109,6 +111,8 @@ Response:
109
111
  against `live`).
110
112
  - `backlog` — aggregate `{ queued, inFlight, completed }` for the current or
111
113
  last drain.
114
+ - `pendingCheckpoints` — progress checkpoints queued while no live queen Session was
115
+ available; the next patrol/queen registration flushes them.
112
116
  - `repos` / `repoCount` — the repositories the supervisor currently tracks; this is the
113
117
  status-visible registry the panel renders. Runtime additions go through
114
118
  `hiveSupervisor.addRepo(repo)` (absolute path, initialized Hive repository, idempotent).
@@ -127,6 +131,12 @@ Response:
127
131
  `orphaned by supervisor restart`) before normal dispatch; `claimedButOrphaned`
128
132
  is the count found, `orphanRecovered` the count reopened. Claims owned by other
129
133
  agents are not touched. Top-level status aggregates the per-repo counts.
134
+ - `workerSessionIds` — all live worker Session ids across repositories. The panel
135
+ reads this (or calls the `hiveSupervisor.isWorkerSession(sessionId)` /
136
+ `workerSessionIds()` service methods) to exempt worker conversations from queen
137
+ prompt injection and the queen tool guard. A local provider's child id is reserved
138
+ and placed in `activeRuns` before activation, so the just-activated window is
139
+ covered too.
130
140
  - `workers` — live agents in this repository: `cardId`, `role`, `agent`,
131
141
  `sessionId`, `agentName`, `startedAt`, `lastOutputAt`, `heartbeat`
132
142
  (`ok`/`warn`), `claimDeadline`, `timeoutAt`. The Session id is written into the
@@ -255,6 +265,7 @@ auto-pause failure budget; status exposes `claimedButOrphaned`,
255
265
  | `lib/anomalies.js` | Supervision anomaly feed: coalescing per (kind, repo, task id), bounded queue, pending/delivered state, compact digest |
256
266
  | `lib/notify.js` | Queen message injection: resolve the live Agent for the registered Session and deliver one identified user-role message (followup/steer/inject) |
257
267
  | `lib/patrol.js` | 5-minute queen patrol: run the optional audit hook, scan supervisor status for auto-pause/environment/heartbeat/timeout anomalies, flush one digest, stay silent when healthy |
268
+ | `lib/checkpoint.js` | Progress checkpoints: drained/all-done/gate-advance/idle triggers, task/event digest, state-signature dedup and pending queue |
258
269
  | `lib/gates.js` | Gate pipeline: tag classification (`gate:group`, `gate:overall`), phase computation (base -> group -> overall -> released/no-overall), release readiness and dispatch filtering |
259
270
  | `lib/audit.js` | Patrol audit: done tasks without an `arch_review` event become `arch-review-missing` anomalies; more than three `queen_intervention` events on one stuck task write `queen_escalation` and raise the red-flag anomaly |
260
271
  | `lib/events.js` | `.hive/events.jsonl` append/read plus the `arch_review`, `queen_intervention`, `queen_escalation` and `queen_boundary_violation` event contracts |
@@ -307,6 +318,26 @@ lessons, and the supervisor feeds it anomalies. The design constraints:
307
318
  `hive_anomalies` / `GET ?op=pending`; the next queen registration or patrol flushes
308
319
  it. This is the documented degradation path when no Session is live.
309
320
 
321
+ ### Progress checkpoints
322
+
323
+ A patrol also reports progress, not only problems. `lib/checkpoint.js` runs from the
324
+ patrol inspect hook for every registered repository and sends a checkpoint when:
325
+
326
+ 1. the queue is drained (no pending/claimed tasks, including failed ones) and at
327
+ least `checkpointDrainMs` (default 10 min) passed since the last checkpoint;
328
+ 2. all tasks are done, or the gate phase advanced / `releaseReady` flipped true;
329
+ 3. no ready task exists while unfinished tasks remain, continuously for
330
+ `checkpointIdleMs` (default 10 min).
331
+
332
+ The digest contains `done/failed/pending/claimed/total`, the last completed task
333
+ titles, gate phase/releaseReady/reason, a bounded summary of events from the last
334
+ 10 minutes, the trigger, and the instruction `评估目标是否达成:未达成请继续拆解下一批任务并说明依据;达成请汇总结果并请人类确认发布。`.
335
+ It is delivered through the queen notifier. The state signature (counts + gate +
336
+ releaseReady + recent completed ids) deduplicates it: the same state is sent once and
337
+ only a state change re-arms it. Without a live queen Session the checkpoint is kept in
338
+ the controller's pending list (status `pendingCheckpoints`) and flushed by the next
339
+ patrol or queen registration; it never falls through to an anomaly digest.
340
+
310
341
  ### Tool boundary: hard veto through `ctx.tools.guard`
311
342
 
312
343
  DSH does expose a plugin-side tool veto. `ToolsService.guard(guard)` registers a
@@ -323,9 +354,15 @@ needed and is not implemented.
323
354
  - predicate: the tool is in one of two classes — delegation (`subagent`,
324
355
  `subagent_fork`, `subagent_claude_code`) or mutation (the explicit
325
356
  `QUEEN_MUTATING_TOOLS` list: `write`/`edit`/`apply_patch`/`str_replace_editor`,
326
- `bash`/`pwsh`/`run_code`, notebook editors, `create_worktree`, `office_*`, `ralph*`,
357
+ `bash`/`pwsh`, notebook editors, `create_worktree`, `office_*`, `ralph*`,
327
358
  `terminal_*`, and common aliases). Read-only tools (`read`, `grep`, `glob`,
328
359
  `web_*`, `hive_*`, `list_agents`, ...) are not in the list and stay allowed.
360
+ `run_code` is **not** in the list: under the PTC preset it is the queen's only
361
+ transport. Its nested `tools.write`/`tools.edit`/`tools.bash` calls carry the same
362
+ Agent in `ToolExecutionInput` and go through `executor.prepare()` in the PTC
363
+ executor, which invokes the shared pipeline's `tools.checkGuards()` before the body
364
+ (ptc.ts nested dispatch + pipeline.ts guard check). The nested mutation is thus
365
+ still vetoed; only the outer `run_code` call is allowed.
329
366
  DSH does not expose a mutability bit on a tool execution, so the name list is
330
367
  explicit and must be extended when a new mutation tool is composed. The calling
331
368
  Session is a queen in one of two ways:
@@ -340,7 +377,7 @@ needed and is not implemented.
340
377
  - when path 2 recognizes a Session, the guard calls the supervisor's
341
378
  `setQueenSession()` (idempotent) so the panel can display it and future workers
342
379
  use it as parent;
343
- - denial: `女王不改代码,请用 hive_tasks 建任务,执行交给 supervisor(检测到 <tool>
380
+ - denial: `女王可以用 hive_* 与只读工具,实现请交给 worker(检测到 <tool>
344
381
  调用,已拦截)`, with `info.code = QUEEN_BOUNDARY_VIOLATION`;
345
382
  - the attempt is appended to `<repo>/.hive/events.jsonl` as
346
383
  `{ ts, actor: "hive-runner", kind: "queen_boundary_violation", tool, message,
@@ -348,14 +385,18 @@ needed and is not implemented.
348
385
  - it also becomes a `queen-boundary-violation` anomaly, so the coalesced anomaly digest
349
386
  tells the queen to self-correct; `status` exposes `queenBoundaryViolations` and
350
387
  `lastQueenBoundaryViolation`;
351
- - it only vetoes **model-requested tool calls from the queen Session**. The
352
- supervisor's swarm dispatch (`ctx.subagents.startActivation`) is a service call,
353
- not a tool execution, so it bypasses `tools.guard` and keeps working from the same
354
- queen Session; worker/child Sessions and their own subagent tools are unaffected
355
- (PTC nested tool calls share the same pipeline and are covered by the predicate).
388
+ - it only vetoes **model-requested tool calls from the queen Session**. Worker
389
+ Sessions are checked first and get **every tool back** (write/edit/bash/...) so a
390
+ card can actually run: the supervisor's `isWorkerSession(sessionId)` registry
391
+ (activeRuns, including a locally reserved child id before activation) is
392
+ authoritative; the Session header (`origin: "subagent"`, positive
393
+ `delegationDepth`, or `parentSession === queenSessionId`) is the restart/provider
394
+ fallback. The supervisor's swarm dispatch (`ctx.subagents.startActivation`) is a
395
+ service call, not a tool execution, so it bypasses `tools.guard` as well.
356
396
 
357
397
  Tests: `test/queen-boundary.test.js` covers all three delegation tools and the
358
- mutation tools (write/edit/bash/notebook/run_code denied; read/grep/web/hive allowed),
398
+ mutation tools (write/edit/bash/notebook denied; read/grep/web/hive/run_code allowed)
399
+ and the nested write/bash veto via the shared PTC pipeline,
359
400
  the queen-only
360
401
  predicate, cwd-role detection and auto-registration, `/queen off` suppression,
361
402
  uninitialized repositories, worker/other Sessions, the durable event, the anomaly and
package/index.js CHANGED
@@ -41,6 +41,7 @@ import { createArchReviewAudit } from './lib/audit.js';
41
41
  import { createHiveRunnerRoute } from './lib/http.js';
42
42
  import { RepoLimits } from './lib/limits.js';
43
43
  import { createAnomalyFeed } from './lib/anomalies.js';
44
+ import { createCheckpointController } from './lib/checkpoint.js';
44
45
  import { createQueenNotifier, deliverToSession } from './lib/notify.js';
45
46
  import { createPatrol } from './lib/patrol.js';
46
47
  import { drainQueue } from './lib/queue.js';
@@ -127,6 +128,8 @@ export function apply(ctx, config = {}) {
127
128
  const anomalies = createAnomalyFeed({ max: resolved.anomalyMax });
128
129
  /** @type {ReturnType<typeof createPatrol> | undefined} */
129
130
  let patrol;
131
+ /** @type {ReturnType<typeof createCheckpointController> | undefined} */
132
+ let checkpoint;
130
133
  function recordAnomaly(event) {
131
134
  try {
132
135
  anomalies.push(event);
@@ -197,6 +200,8 @@ export function apply(ctx, config = {}) {
197
200
  onViolation: recordQueenBoundaryViolation,
198
201
  onQueenDetected: registerDetectedQueen,
199
202
  resolveCwd: resolveQueenBoundaryCwd,
203
+ // Authoritative worker registry (activeRuns, incl. reserved child ids).
204
+ isWorkerSession: (sessionId) => supervisor.isWorkerSession(sessionId),
200
205
  log,
201
206
  })));
202
207
 
@@ -239,8 +244,10 @@ export function apply(ctx, config = {}) {
239
244
  onAnomaly: (event) => recordAnomaly(event),
240
245
  onQueenSession: () => {
241
246
  if (patrol !== undefined) patrol.flushPending();
247
+ if (checkpoint !== undefined) checkpoint.flushPending();
242
248
  },
243
249
  pendingAnomalies: () => anomalies.pendingCount(),
250
+ pendingCheckpoints: () => (checkpoint === undefined ? 0 : checkpoint.pendingCount()),
244
251
  logger: console,
245
252
  debug: resolved.debug,
246
253
  });
@@ -266,7 +273,36 @@ export function apply(ctx, config = {}) {
266
273
  log('warn', 'arch review audit failed for ' + repo + ': ' + (error instanceof Error ? error.message : String(error)));
267
274
  }
268
275
  }
276
+ // Progress checkpoints: drained/all-done/gate-advance/idle goals. Delivery
277
+ // is direct; failures stay pending in the checkpoint controller.
278
+ try {
279
+ await checkpoint.tick();
280
+ checkpoint.flushPending();
281
+ } catch (error) {
282
+ log('warn', 'checkpoint tick failed', error);
283
+ }
284
+ },
285
+ log,
286
+ });
287
+
288
+ checkpoint = createCheckpointController({
289
+ supervisor,
290
+ notifier: resolved.notifyQueen ? notifier : undefined,
291
+ loadBoard: async (repo) => {
292
+ const tasks = await commands.list(repo, {});
293
+ let ready = null;
294
+ try {
295
+ ready = await commands.ready(repo, { limit: 500 });
296
+ } catch {
297
+ // Without a ready list only the idle-no-ready trigger is disabled; the
298
+ // drained/all-done/gate triggers still work from the full board.
299
+ ready = null;
300
+ }
301
+ return { tasks, ready };
269
302
  },
303
+ loadEvents: (repo) => readEvents(repo, { limit: 100 }),
304
+ drainMs: resolved.checkpointDrainMs,
305
+ idleMs: resolved.checkpointIdleMs,
270
306
  log,
271
307
  });
272
308
 
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Queen checkpoint: a progress digest, not just an anomaly digest.
3
+ *
4
+ * The patrol reports problems (failed/timed-out/stalled workers). This module
5
+ * reports *progress* so the queen reacts when work finishes: a drained queue,
6
+ * all tasks done, a gate phase advancing, or a long idle period with no ready
7
+ * work while goals remain. It injects one digest with task statistics, recent
8
+ * completions, gate state, recent events, and an explicit next action.
9
+ *
10
+ * Spam control: the digest is keyed by a state signature (counts + gate +
11
+ * release readiness + recent completed ids). The same state is delivered at most
12
+ * once; a state change immediately re-arms it. When no queen Session is live the
13
+ * digest is queued (pending) and flushed by the next patrol/queen registration.
14
+ *
15
+ * @module dsh-hive-runner/checkpoint
16
+ */
17
+
18
+ /** Default minimum gap between queue-drained checkpoints. */
19
+ export const DEFAULT_CHECKPOINT_DRAIN_MS = 10 * 60_000;
20
+ /** Default no-ready period before the idle checkpoint fires. */
21
+ export const DEFAULT_CHECKPOINT_IDLE_MS = 10 * 60_000;
22
+ /** Default event window shown in the digest. */
23
+ export const DEFAULT_CHECKPOINT_EVENT_WINDOW_MS = 10 * 60_000;
24
+
25
+ /** Exact model-facing decision request appended to every checkpoint. */
26
+ export const CHECKPOINT_INSTRUCTION = '评估目标是否达成:未达成请继续拆解下一批任务并说明依据;达成请汇总结果并请人类确认发布。';
27
+
28
+ const PHASE_ORDER = ['base', 'group', 'overall', 'released'];
29
+
30
+ function phaseRank(phase) {
31
+ const index = PHASE_ORDER.indexOf(phase);
32
+ return index === -1 ? 0 : index + 1;
33
+ }
34
+
35
+ function isoAt(value) {
36
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
37
+ if (typeof value === 'string') {
38
+ const parsed = Date.parse(value);
39
+ if (Number.isFinite(parsed)) return parsed;
40
+ }
41
+ return 0;
42
+ }
43
+
44
+ function titleOf(task) {
45
+ return typeof task?.title === 'string' && task.title.trim() !== '' ? task.title.trim() : String(task?.id ?? '?');
46
+ }
47
+
48
+ /** Task counts and recent completions from one board snapshot. */
49
+ export function taskCheckpointStats(tasks) {
50
+ const list = Array.isArray(tasks) ? tasks : [];
51
+ const stats = { total: 0, done: 0, failed: 0, pending: 0, claimed: 0, superseded: 0 };
52
+ const completed = [];
53
+ for (const task of list) {
54
+ if (task === null || typeof task !== 'object') continue;
55
+ stats.total += 1;
56
+ if (task.state === 'done') {
57
+ stats.done += 1;
58
+ completed.push({ id: String(task.id ?? ''), title: titleOf(task), at: isoAt(task.doneAt ?? task.updatedAt ?? task.finishedAt) });
59
+ } else if (task.state === 'failed') stats.failed += 1;
60
+ else if (task.state === 'claimed') stats.claimed += 1;
61
+ else if (task.state === 'superseded') stats.superseded += 1;
62
+ else stats.pending += 1;
63
+ }
64
+ completed.sort((a, b) => b.at - a.at);
65
+ return { ...stats, recentCompleted: completed.slice(0, 5) };
66
+ }
67
+
68
+ /** Bounded event summary for the checkpoint's "recent events" line. */
69
+ export function summarizeCheckpointEvents(events, { since = 0, maxKinds = 6 } = {}) {
70
+ const list = Array.isArray(events) ? events : [];
71
+ const counts = new Map();
72
+ let window = 0;
73
+ for (const event of list) {
74
+ if (event === null || typeof event !== 'object') continue;
75
+ if (isoAt(event.ts ?? event.at) < since) continue;
76
+ window += 1;
77
+ const kind = typeof event.kind === 'string' && event.kind !== '' ? event.kind : 'event';
78
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
79
+ }
80
+ if (window === 0) return 'none in the last window';
81
+ return [...counts.entries()]
82
+ .sort((a, b) => b[1] - a[1])
83
+ .slice(0, maxKinds)
84
+ .map(([kind, count]) => kind + '×' + String(count))
85
+ .join(', ');
86
+ }
87
+
88
+ /** Build the complete injected checkpoint body. */
89
+ export function renderCheckpoint({ repo, stats, gate, recentEvents, trigger, at }) {
90
+ const gatePhase = typeof gate?.phase === 'string' ? gate.phase : 'unknown';
91
+ const releaseReady = gate?.releaseReady === true;
92
+ const titles = stats.recentCompleted.length > 0
93
+ ? stats.recentCompleted.map((task) => JSON.stringify(task.title)).join(', ')
94
+ : '(none)';
95
+ return [
96
+ '[hive-runner] checkpoint — ' + String(repo),
97
+ 'Trigger: ' + String(trigger),
98
+ 'Tasks: done=' + stats.done + ' failed=' + stats.failed + ' pending=' + stats.pending
99
+ + ' claimed=' + stats.claimed + ' total=' + stats.total,
100
+ 'Recently completed: ' + titles,
101
+ 'Gate: phase=' + gatePhase + ' releaseReady=' + String(releaseReady)
102
+ + (typeof gate?.reason === 'string' && gate.reason !== '' ? ' — ' + gate.reason : ''),
103
+ 'Events (last window): ' + recentEvents,
104
+ 'At: ' + new Date(at).toISOString(),
105
+ '',
106
+ CHECKPOINT_INSTRUCTION,
107
+ ].join('\n');
108
+ }
109
+
110
+ /**
111
+ * Create the checkpoint controller used by the patrol.
112
+ * @param {{
113
+ * supervisor?: { status: () => object },
114
+ * loadBoard: (repo: string) => Promise<{ tasks?: object[], ready?: object[] | null }>,
115
+ * loadEvents?: (repo: string) => Promise<object[]> | object[],
116
+ * notifier?: { deliver: (body: string) => { delivered: boolean, via?: string, reason?: string } },
117
+ * now?: () => number,
118
+ * drainMs?: number,
119
+ * idleMs?: number,
120
+ * eventWindowMs?: number,
121
+ * log?: (level: string, ...args: unknown[]) => void,
122
+ * }} options
123
+ */
124
+ export function createCheckpointController({
125
+ supervisor,
126
+ loadBoard,
127
+ loadEvents = () => [],
128
+ notifier,
129
+ now = () => Date.now(),
130
+ drainMs = DEFAULT_CHECKPOINT_DRAIN_MS,
131
+ idleMs = DEFAULT_CHECKPOINT_IDLE_MS,
132
+ eventWindowMs = DEFAULT_CHECKPOINT_EVENT_WINDOW_MS,
133
+ log = () => {},
134
+ } = {}) {
135
+ if (typeof loadBoard !== 'function') throw new TypeError('createCheckpointController: loadBoard is required');
136
+ const states = new Map();
137
+ const pending = [];
138
+
139
+ function stateFor(repo) {
140
+ let state = states.get(repo);
141
+ if (state === undefined) {
142
+ state = {
143
+ lastCheckpointAt: 0,
144
+ lastSignature: null,
145
+ lastGatePhase: undefined,
146
+ lastReleaseReady: undefined,
147
+ noReadySince: null,
148
+ };
149
+ states.set(repo, state);
150
+ }
151
+ return state;
152
+ }
153
+
154
+ function deliver(entry) {
155
+ if (notifier === undefined || typeof notifier.deliver !== 'function') {
156
+ return { delivered: false, reason: 'no-notifier' };
157
+ }
158
+ try {
159
+ const result = notifier.deliver(entry.body);
160
+ if (result !== undefined && result.delivered === true) {
161
+ return { delivered: true, via: result.via ?? null };
162
+ }
163
+ return { delivered: false, reason: result?.reason ?? 'not-delivered' };
164
+ } catch (error) {
165
+ log('warn', 'checkpoint delivery failed', error);
166
+ return { delivered: false, reason: 'delivery-threw' };
167
+ }
168
+ }
169
+
170
+ function signatureOf(stats, gate) {
171
+ return JSON.stringify({
172
+ done: stats.done,
173
+ failed: stats.failed,
174
+ pending: stats.pending,
175
+ claimed: stats.claimed,
176
+ phase: typeof gate?.phase === 'string' ? gate.phase : null,
177
+ releaseReady: gate?.releaseReady === true,
178
+ completed: stats.recentCompleted.map((task) => task.id),
179
+ });
180
+ }
181
+
182
+ async function tick() {
183
+ const results = [];
184
+ if (supervisor === undefined || typeof supervisor.status !== 'function') return results;
185
+ let status;
186
+ try {
187
+ status = supervisor.status();
188
+ } catch (error) {
189
+ log('warn', 'checkpoint could not read supervisor status', error);
190
+ return results;
191
+ }
192
+ if (status === null || typeof status !== 'object' || !Array.isArray(status.repos)) return results;
193
+ const at = now();
194
+ for (const repoStatus of status.repos) {
195
+ if (repoStatus === null || typeof repoStatus !== 'object') continue;
196
+ const repo = typeof repoStatus.repo === 'string' ? repoStatus.repo : '';
197
+ if (repo === '') continue;
198
+ let board;
199
+ try {
200
+ board = await loadBoard(repo);
201
+ } catch (error) {
202
+ log('warn', 'checkpoint could not read board for ' + repo, error);
203
+ continue;
204
+ }
205
+ if (board === null || typeof board !== 'object') continue;
206
+ const stats = taskCheckpointStats(board.tasks);
207
+ const gate = repoStatus.gate ?? null;
208
+ const phase = typeof gate?.phase === 'string' ? gate.phase : null;
209
+ const releaseReady = gate?.releaseReady === true;
210
+ const state = stateFor(repo);
211
+
212
+ // "No ready work while goals remain" needs the ready count; a loader may
213
+ // not provide it (legacy/test), in which case this trigger is skipped.
214
+ const readyCount = Array.isArray(board.ready) ? board.ready.length : null;
215
+ const unfinished = stats.pending + stats.claimed > 0;
216
+ if (readyCount !== null && unfinished && readyCount === 0) {
217
+ if (state.noReadySince === null) state.noReadySince = at;
218
+ } else {
219
+ state.noReadySince = null;
220
+ }
221
+
222
+ const drained = stats.total > 0 && stats.pending === 0 && stats.claimed === 0;
223
+ const allDone = stats.total > 0 && stats.done === stats.total;
224
+ const gateAdvanced = state.lastGatePhase !== undefined
225
+ && (phaseRank(phase) > phaseRank(state.lastGatePhase)
226
+ || (state.lastReleaseReady === false && releaseReady === true));
227
+ const reasons = [];
228
+ if (allDone) reasons.push('all-done');
229
+ else if (drained && at - state.lastCheckpointAt >= drainMs) reasons.push('queue-drained');
230
+ if (gateAdvanced) reasons.push('gate-advanced');
231
+ if (state.noReadySince !== null && at - state.noReadySince >= idleMs) reasons.push('no-ready');
232
+
233
+ const signature = signatureOf(stats, gate);
234
+ if (reasons.length > 0 && signature !== state.lastSignature) {
235
+ let events = [];
236
+ try {
237
+ events = await loadEvents(repo);
238
+ } catch (error) {
239
+ log('warn', 'checkpoint could not read events for ' + repo, error);
240
+ }
241
+ const body = renderCheckpoint({
242
+ repo,
243
+ stats,
244
+ gate,
245
+ recentEvents: summarizeCheckpointEvents(events, { since: at - eventWindowMs }),
246
+ trigger: reasons.join('+'),
247
+ at,
248
+ });
249
+ const entry = { repo, body, signature, at, trigger: reasons.join('+') };
250
+ const delivery = deliver(entry);
251
+ state.lastSignature = signature;
252
+ state.lastCheckpointAt = at;
253
+ if (delivery.delivered) {
254
+ log('info', 'checkpoint delivered to queen', repo, reasons.join('+'));
255
+ results.push({ repo, trigger: entry.trigger, delivered: true, via: delivery.via ?? null });
256
+ } else {
257
+ pending.push(entry);
258
+ log('info', 'checkpoint queued (no live queen)', repo, delivery.reason);
259
+ results.push({ repo, trigger: entry.trigger, delivered: false, reason: delivery.reason ?? 'not-delivered' });
260
+ }
261
+ }
262
+ state.lastGatePhase = phase;
263
+ state.lastReleaseReady = releaseReady;
264
+ }
265
+ return results;
266
+ }
267
+
268
+ function flushPending() {
269
+ let delivered = 0;
270
+ for (const entry of [...pending]) {
271
+ const result = deliver(entry);
272
+ if (result.delivered) {
273
+ pending.splice(pending.indexOf(entry), 1);
274
+ delivered += 1;
275
+ log('info', 'pending checkpoint delivered', entry.repo);
276
+ }
277
+ }
278
+ return { delivered, pending: pending.length };
279
+ }
280
+
281
+ return {
282
+ tick,
283
+ flushPending,
284
+ pendingCount: () => pending.length,
285
+ pending: () => pending.map((entry) => ({ ...entry })),
286
+ size: () => states.size,
287
+ };
288
+ }
package/lib/config.js CHANGED
@@ -32,6 +32,10 @@ export const DEFAULT_ANOMALY_DEBOUNCE_MS = 3_000;
32
32
  export const DEFAULT_ANOMALY_MAX = 50;
33
33
  /** Grace before a done card without an arch_review event is flagged. */
34
34
  export const DEFAULT_ARCH_REVIEW_GRACE_MS = 10 * 60_000;
35
+ /** Minimum gap between queue-drained progress checkpoints sent to the queen. */
36
+ export const DEFAULT_CHECKPOINT_DRAIN_MS = 10 * 60_000;
37
+ /** No-ready time before the idle progress checkpoint fires. */
38
+ export const DEFAULT_CHECKPOINT_IDLE_MS = 10 * 60_000;
35
39
  /** Default role -> concurrent live-worker cap, per repository. */
36
40
  export const DEFAULT_ROLE_CONCURRENCY = Object.freeze({ coder: 5, tester: 5 });
37
41
  /** Fallback cap for roles not listed in `roleConcurrency` (also finite). */
@@ -76,6 +80,11 @@ const DEFAULTS = Object.freeze({
76
80
  // A done card must carry an arch_review event; flag it after this grace (the
77
81
  // queen reviews finished cards at the next patrol).
78
82
  archReviewGraceMs: DEFAULT_ARCH_REVIEW_GRACE_MS,
83
+ // Progress checkpoints (not anomalies): the queen is asked to evaluate the
84
+ // goal when the queue drains, all cards are done, a gate advances, or no
85
+ // ready work exists while goals remain.
86
+ checkpointDrainMs: DEFAULT_CHECKPOINT_DRAIN_MS,
87
+ checkpointIdleMs: DEFAULT_CHECKPOINT_IDLE_MS,
79
88
  provider: 'spawn',
80
89
  parentSession: null,
81
90
  cwd: null,
@@ -282,6 +291,8 @@ export function resolveConfig(config = {}) {
282
291
  fail('defaultRoleConcurrency must be an integer in 0..999 (0 pauses unlisted roles)');
283
292
  }
284
293
  cfg.capacityRetryMs = positiveNumber(cfg.capacityRetryMs, 'capacityRetryMs');
294
+ cfg.checkpointDrainMs = positiveNumber(cfg.checkpointDrainMs, 'checkpointDrainMs');
295
+ cfg.checkpointIdleMs = positiveNumber(cfg.checkpointIdleMs, 'checkpointIdleMs');
285
296
  cfg.cardTimeoutMs = positiveNumber(cfg.cardTimeoutMs, 'cardTimeoutMs');
286
297
  cfg.heartbeatWarnMs = positiveNumber(cfg.heartbeatWarnMs, 'heartbeatWarnMs');
287
298
  cfg.heartbeatIntervalMs = positiveNumber(cfg.heartbeatIntervalMs, 'heartbeatIntervalMs');
package/lib/events.js CHANGED
@@ -108,7 +108,7 @@ export const ESCALATION_KIND = 'queen_escalation';
108
108
  /** Event kind written when the queen tries to delegate coding directly. */
109
109
  export const QUEEN_BOUNDARY_KIND = 'queen_boundary_violation';
110
110
  /** Model-facing correction carried by a boundary violation. */
111
- export const QUEEN_BOUNDARY_MESSAGE = '女王不改代码,请用 hive_tasks 建任务,执行交给 supervisor';
111
+ export const QUEEN_BOUNDARY_MESSAGE = '女王可以用 hive_* 与只读工具,实现请交给 worker';
112
112
  /** Intervention actions the queen may record. */
113
113
  export const INTERVENTION_ACTIONS = Object.freeze([
114
114
  'reopen', 'split', 'reassign', 'pause', 'fail', 'guide', 'remove', 'rebuild', 'escalate',
@@ -51,7 +51,10 @@ export const QUEEN_MUTATING_TOOLS = Object.freeze([
51
51
  'str_replace_editor',
52
52
  'bash',
53
53
  'pwsh',
54
- 'run_code',
54
+ // NOTE: run_code is intentionally NOT here. Under the PTC preset it is the
55
+ // queen's only transport; its nested tool dispatches still run through the
56
+ // shared tool pipeline with the queen's Agent, so write/edit/bash remain
57
+ // vetoed inside the program (see docs/DESIGN.md).
55
58
  'create_worktree',
56
59
  'notebook',
57
60
  'notebook_edit',
@@ -70,7 +73,7 @@ export const QUEEN_MUTATING_TOOLS = Object.freeze([
70
73
  ]);
71
74
 
72
75
  /** Model-facing correction for a blocked queen tool call. */
73
- export const QUEEN_BOUNDARY_MESSAGE = '女王不改代码,请用 hive_tasks 建任务,执行交给 supervisor';
76
+ export const QUEEN_BOUNDARY_MESSAGE = '女王可以用 hive_* 与只读工具,实现请交给 worker';
74
77
 
75
78
  /**
76
79
  * Classify a tool name inside the queen boundary.
@@ -180,12 +183,23 @@ export function isQueenSuppressed(session) {
180
183
  return latestQueenCommand(session) === 'off';
181
184
  }
182
185
 
183
- /** Whether a Session is a card worker / delegation child, never the queen. */
184
- export function isWorkerSession(session) {
186
+ /**
187
+ * Session-header heuristic for a card worker / delegation child, never the
188
+ * queen. The authoritative check is the supervisor's activeRuns registry; this
189
+ * covers the window before a provider-reported child id reaches it and worker
190
+ * Sessions that survive a plugin restart.
191
+ * @param {object} session
192
+ * @param {string | null} [queenSessionId]
193
+ * @returns {boolean}
194
+ */
195
+ export function isWorkerSession(session, queenSessionId) {
185
196
  const header = session?.header;
186
197
  if (header === null || typeof header !== 'object') return false;
187
- return header.origin === 'subagent'
188
- || (Number.isInteger(header.delegationDepth) && header.delegationDepth > 0);
198
+ if (header.origin === 'subagent') return true;
199
+ if (Number.isInteger(header.delegationDepth) && header.delegationDepth > 0) return true;
200
+ return typeof queenSessionId === 'string'
201
+ && queenSessionId !== ''
202
+ && header.parentSession === queenSessionId;
189
203
  }
190
204
 
191
205
  /** Structured error identity recorded on the failed tool result. */
@@ -203,6 +217,7 @@ export const QUEEN_BOUNDARY_ERROR = Object.freeze({
203
217
  * resolveCwd?: (agent: object, session: object) => string | null,
204
218
  * hasRole?: (cwd: string) => boolean,
205
219
  * isSuppressed?: (session: object) => boolean,
220
+ * isWorkerSession?: (sessionId: string, session: object) => boolean,
206
221
  * log?: (level: string, ...args: unknown[]) => void,
207
222
  * }} options
208
223
  * @returns {(exec: { name: string, agent?: { session?: object } }) => object | undefined}
@@ -214,21 +229,34 @@ export function createQueenBoundaryGuard({
214
229
  resolveCwd,
215
230
  hasRole = hasQueenRole,
216
231
  isSuppressed = isQueenSuppressed,
232
+ isWorkerSession: isKnownWorkerSession,
217
233
  log = () => {},
218
234
  } = {}) {
219
235
  return function queenBoundaryGuard(exec) {
220
236
  if (exec === null || typeof exec !== 'object') return undefined;
221
- const toolClass = queenBoundaryToolClass(exec.name);
222
- if (toolClass === null) return undefined;
223
237
  const session = exec.agent?.session;
224
238
  const sessionId = session?.id;
225
239
  if (typeof sessionId !== 'string' || sessionId === '') return undefined;
226
240
 
227
241
  const queenSessionId = queenSession?.sessionId;
228
242
  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;
243
+ // Workers are never the queen: the supervisor's activeRuns registry is
244
+ // authoritative (including a child id reserved before activation), and
245
+ // the Session header covers the provider/restart window. A worker gets
246
+ // every tool back, before any queen recognition or log scan.
247
+ let worker = false;
248
+ try {
249
+ worker = typeof isKnownWorkerSession === 'function'
250
+ ? isKnownWorkerSession(sessionId, session) === true
251
+ : false;
252
+ } catch {
253
+ worker = false;
254
+ }
255
+ if (!worker) worker = isWorkerSession(session, queenSessionId);
256
+ if (worker) return undefined;
257
+
258
+ const toolClass = queenBoundaryToolClass(exec.name);
259
+ if (toolClass === null) return undefined;
232
260
 
233
261
  // `/queen off` wins over both recognition paths.
234
262
  let suppressed = false;
@@ -246,7 +274,7 @@ export function createQueenBoundaryGuard({
246
274
  } catch {
247
275
  cwd = null;
248
276
  }
249
- const initialised = !isWorkerSession(session) && hasRole(cwd);
277
+ const initialised = hasRole(cwd);
250
278
  if (!registered && !initialised) return undefined;
251
279
 
252
280
  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';
@@ -546,6 +548,22 @@ export function createRoundRunner({
546
548
  // claim identity and this card's instance while the worker is alive, so
547
549
  // its own `hive guard` / `hive release` calls agree with the runner's.
548
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
+
549
567
  // Hard per-card timeout: abort the worker at the deadline.
550
568
  timeoutTimer = setTimeout(() => {
551
569
  if (settled) return;
@@ -569,6 +587,7 @@ export function createRoundRunner({
569
587
  parent: owner,
570
588
  signal: workerSignal,
571
589
  delivery: 'caller',
590
+ ...(reservedChildId === undefined ? {} : { childId: reservedChildId }),
572
591
  }),
573
592
  abortWait.then(() => null),
574
593
  ]);
package/lib/supervisor.js CHANGED
@@ -140,6 +140,7 @@ export class HiveSupervisor {
140
140
  * @param {(event: object) => void} [options.onAnomaly] supervision event sink (queen digest)
141
141
  * @param {(sessionId: string) => void} [options.onQueenSession] called after a queen Session registers
142
142
  * @param {() => number} [options.pendingAnomalies] undelivered queen anomalies reported in status
143
+ * @param {() => number} [options.pendingCheckpoints] undelivered progress checkpoints reported in status
143
144
  * @param {Console} [options.logger]
144
145
  * @param {boolean} [options.debug]
145
146
  */
@@ -178,6 +179,7 @@ export class HiveSupervisor {
178
179
  this.onAnomaly = typeof options.onAnomaly === 'function' ? options.onAnomaly : undefined;
179
180
  this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
180
181
  this.pendingAnomalies = typeof options.pendingAnomalies === 'function' ? options.pendingAnomalies : undefined;
182
+ this.pendingCheckpoints = typeof options.pendingCheckpoints === 'function' ? options.pendingCheckpoints : undefined;
181
183
  this.discover = options.discover;
182
184
  this.logger = options.logger === undefined ? console : options.logger;
183
185
  this.debug = options.debug === true;
@@ -389,6 +391,38 @@ export class HiveSupervisor {
389
391
  return this.status();
390
392
  }
391
393
 
394
+ /**
395
+ * Live worker Session ids across every registered repository. The panel uses
396
+ * this to exempt worker conversations from the queen role/prompt and guard.
397
+ * @returns {string[]}
398
+ */
399
+ workerSessionIds() {
400
+ const ids = new Set();
401
+ for (const entry of this.repos.values()) {
402
+ for (const worker of this.#workers(entry.repo)) {
403
+ if (typeof worker?.sessionId === 'string' && worker.sessionId !== '') ids.add(worker.sessionId);
404
+ }
405
+ }
406
+ return [...ids];
407
+ }
408
+
409
+ /**
410
+ * Whether a Session is one of the supervisor's card workers. This is the
411
+ * authoritative registry check used by the queen tool guard and the panel;
412
+ * guard fallbacks based on Session header lineage cover the short window
413
+ * before a provider-reported child id reaches activeRuns.
414
+ * @param {string} sessionId
415
+ * @returns {boolean}
416
+ */
417
+ isWorkerSession(sessionId) {
418
+ if (typeof sessionId !== 'string' || sessionId === '') return false;
419
+ for (const entry of this.repos.values()) {
420
+ for (const worker of this.#workers(entry.repo)) {
421
+ if (worker?.sessionId === sessionId) return true;
422
+ }
423
+ }
424
+ return false;
425
+ }
392
426
  /**
393
427
  * Read every card of one repository and compute the gate phase that governs
394
428
  * dispatch. Falls back to an explicit phase when the board read fails; a
@@ -515,9 +549,14 @@ export class HiveSupervisor {
515
549
  capacityRetryMs: this.capacityRetryMs,
516
550
  lastTickAt: iso(this.lastTickAt),
517
551
  lastDiscoverError: this.lastDiscoverError,
518
- // Undelivered anomaly digests waiting for a live queen Session.
552
+ // Undelivered anomaly digests / progress checkpoints waiting for a live
553
+ // queen Session.
519
554
  pendingAnomalies: this.#pendingAnomalyCount(),
555
+ pendingCheckpoints: this.#pendingCheckpointCount(),
520
556
  repoCount: this.repos.size,
557
+ // Worker Session ids across all repositories: the panel exempts them from
558
+ // queen-mode prompt injection and the guard exempts their tool calls.
559
+ workerSessionIds: this.workerSessionIds(),
521
560
  // Aggregate of the per-repository orphan-claim counts.
522
561
  claimedButOrphaned: repoSnapshots.reduce((sum, repo) => sum + repo.claimedButOrphaned, 0),
523
562
  repos: repoSnapshots,
@@ -817,6 +856,16 @@ export class HiveSupervisor {
817
856
  }
818
857
  }
819
858
 
859
+ /** Undelivered progress checkpoint count; observability never throws. */
860
+ #pendingCheckpointCount() {
861
+ try {
862
+ const value = typeof this.pendingCheckpoints === 'function' ? this.pendingCheckpoints() : 0;
863
+ return Number.isInteger(value) && value >= 0 ? value : 0;
864
+ } catch {
865
+ return 0;
866
+ }
867
+ }
868
+
820
869
  /** Best-effort live worker list for status; observability never throws. */
821
870
  #workers(repo) {
822
871
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "1.0.10",
3
+ "version": "1.0.13",
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",