dsh-hive-runner 1.0.1 → 1.0.3

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,38 @@ 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.3] - 2026-12-05
11
+
12
+ ### Fixed
13
+
14
+ - The queen tool boundary no longer depends on the panel having registered one
15
+ `queenSessionId`. The guard now also recognizes an ordinary non-worker Session
16
+ whose cwd contains `.hive/roles/queen.md` (a Hive-initialized repository),
17
+ registers that Session as queen idempotently (so the panel can show it), and
18
+ vetoes its direct `subagent`/`subagent_fork`/`subagent_claude_code` calls. An
19
+ explicit `/queen off` command event suppresses the veto (`/queen on` re-enables
20
+ it), uninitialized repositories and worker/child Sessions stay allowed, and the
21
+ existing registered-queen path is kept as compatibility.
22
+
23
+ ## [1.0.2] - 2026-12-05
24
+
25
+ ### Tests
26
+
27
+ - Integration test proving the queen tool guard is scoped to the queen's own tool calls:
28
+ a direct `subagent` tool call from the queen Session is denied while the supervisor
29
+ can still dispatch a worker from the same queen Session (`ctx.subagents.startActivation`
30
+ is a service call, not a tool call) and that worker Session can delegate again; the
31
+ guard invocation count proves the dispatch path bypasses the guard. 210 tests pass.
32
+
33
+ ### Documentation
34
+
35
+ - README, SPEC and docs/DESIGN state the boundary explicitly: only the queen's own tool
36
+ calls are vetoed, never the swarm dispatch or a worker's subagent capability.
37
+
38
+ ### Published
39
+
40
+ - npm: `dsh-hive-runner@1.0.2` on 2026-12-05.
41
+
10
42
  ## [1.0.1] - 2026-12-05
11
43
 
12
44
  ### Added
@@ -17,8 +49,13 @@ iterations of the plugin before this repository was published.
17
49
  `女王不改代码,请用 hive_tasks 建任务`, the attempt is appended to
18
50
  `<repo>/.hive/events.jsonl` as `queen_boundary_violation`, pushed as a
19
51
  `queen-boundary-violation` anomaly digest, and counted in status
20
- (`queenBoundaryViolations` / `lastQueenBoundaryViolation`). Workers keep their
21
- subagent tools.
52
+ (`queenBoundaryViolations` / `lastQueenBoundaryViolation`). The veto covers only
53
+ the queen's own tool calls: supervisor dispatch via `ctx.subagents.startActivation`
54
+ and a worker's own subagent calls are not tool calls and keep working.
55
+ ### Published
56
+
57
+ - npm: `dsh-hive-runner@1.0.1` on 2026-12-05.
58
+
22
59
  ## [1.0.0] - 2026-12-04
23
60
 
24
61
  ### Stable
package/README.md CHANGED
@@ -105,8 +105,15 @@ commits code. The boundary is enforced, not just documented: the runner register
105
105
  DSH `ctx.tools.guard`, so a queen Session calling `subagent`, `subagent_fork` or
106
106
  `subagent_claude_code` directly gets a failed tool result telling her
107
107
  `女王不改代码,请用 hive_tasks 建任务`, and the attempt is recorded as a
108
- `queen_boundary_violation` event (with an anomaly digest for self-correction). Task
108
+ `queen_boundary_violation` event (with an anomaly digest for self-correction). The
109
+ guard recognizes the queen by registration or by an ordinary chat Session whose cwd
110
+ is a Hive-initialized repository (`.hive/roles/queen.md`), so it works without the
111
+ panel; `/queen off` explicitly exempts that Session, and detection registers it
112
+ idempotently so the panel can show it. Task
109
113
  metadata (add/reopen/retry/rm), roles and lessons are coordination state, not code.
114
+ The veto covers only the queen's own tool calls: supervisor dispatch
115
+ (`ctx.subagents.startActivation`) and a worker's own subagent calls are not tool
116
+ calls and remain allowed.
110
117
 
111
118
  ### When the queen hears from the supervisor
112
119
 
package/SPEC.md CHANGED
@@ -346,15 +346,20 @@ delivers nothing.
346
346
  ### 8.6.1 Queen tool boundary
347
347
 
348
348
  DSH's `ctx.tools.guard` lets a plugin veto a tool call after pre-execute policy and
349
- before the body. The runner registers one global guard: when the calling Session id
350
- equals `queenSessionId` and the tool is `subagent`, `subagent_fork` or
351
- `subagent_claude_code`, the call fails with
349
+ before the body. The runner registers one global guard. A Session is recognized as
350
+ queen when its id equals `queenSessionId` **or** it is an ordinary non-worker Session
351
+ whose cwd contains `.hive/roles/queen.md`; an explicit latest `/queen off` command event
352
+ suppresses the veto for that Session (`/queen on` re-enables it). For the tool
353
+ `subagent`, `subagent_fork` or `subagent_claude_code` the call fails with
352
354
  `女王不改代码,请用 hive_tasks 建任务(检测到 <tool> 调用,已拦截...)`; the body never
353
355
  runs. The attempt is appended to `<repo>/.hive/events.jsonl` with
354
356
  `kind: "queen_boundary_violation"` (`ts`, `actor`, `tool`, `message`, `sessionId`),
355
357
  pushed as a `queen-boundary-violation` anomaly so the digest reaches the queen, and
356
- counted in status (`queenBoundaryViolations`, `lastQueenBoundaryViolation`). Workers
357
- and other Sessions keep their subagent tools.
358
+ counted in status (`queenBoundaryViolations`, `lastQueenBoundaryViolation`). A cwd-
359
+ recognized queen is also registered through `setQueenSession()` (idempotent) so the
360
+ panel can display it. The guard sees model-requested tool executions only; supervisor dispatch through
361
+ `ctx.subagents.startActivation` and a worker's own subagent calls do not pass through
362
+ it, so the swarm and worker delegation keep working.
358
363
 
359
364
  ## 8.7 Gates and release readiness
360
365
 
package/docs/DESIGN.md CHANGED
@@ -104,8 +104,9 @@ Response:
104
104
  against `live`).
105
105
  - `backlog` — aggregate `{ queued, inFlight, completed }` for the current or
106
106
  last drain.
107
- - `queenSessionId` — the queen conversation registered by the panel; agents are
108
- parented to that Session while its Agent is live. `waiting` is
107
+ - `queenSessionId` — the queen conversation registered by the panel **or detected by
108
+ the queen tool guard** when an ordinary initialized-repo Session calls a subagent
109
+ tool; agents are parented to that Session while its Agent is live. `waiting` is
109
110
  `"no-queen-session"` until the registration arrives (startup-order hint, not an
110
111
  error); the registration is only replaced by a new registration. Status workers and
111
112
  run records carry `parentSource: "queen"` when the registered Session parented them.
@@ -288,7 +289,18 @@ needed and is not implemented.
288
289
  `ctx.effect`:
289
290
 
290
291
  - predicate: the tool name is `subagent`, `subagent_fork` or `subagent_claude_code`, and
291
- `exec.agent.session.id` equals the registered `queenSessionId`;
292
+ the calling Session is a queen in one of two ways:
293
+ 1. `exec.agent.session.id` equals the registered `queenSessionId` (legacy/explicit
294
+ panel registration), or
295
+ 2. it is an ordinary **non-worker** Session whose cwd contains
296
+ `.hive/roles/queen.md` (a Hive-initialized repository) — this works even when
297
+ the panel never registered it or the user talks to a new chat session;
298
+ - an explicitly `/queen off`-suppressed Session is always allowed: the latest
299
+ `command/run { name: "queen", args: "off" | "on" }` event in the Session log wins
300
+ (the scan also covers events that happened before the plugin restarted);
301
+ - when path 2 recognizes a Session, the guard calls the supervisor's
302
+ `setQueenSession()` (idempotent) so the panel can display it and future workers
303
+ use it as parent;
292
304
  - denial: `女王不改代码,请用 hive_tasks 建任务(检测到 <tool> 调用,已拦截;请把工作
293
305
  拆成任务卡并交给 hive_tasks。)`, with `info.code = QUEEN_BOUNDARY_VIOLATION`;
294
306
  - the attempt is appended to `<repo>/.hive/events.jsonl` as
@@ -297,11 +309,17 @@ needed and is not implemented.
297
309
  - it also becomes a `queen-boundary-violation` anomaly, so the coalesced anomaly digest
298
310
  tells the queen to self-correct; `status` exposes `queenBoundaryViolations` and
299
311
  `lastQueenBoundaryViolation`;
300
- - worker/child Sessions are unaffected, and PTC nested calls go through the same
301
- pipeline, so they are covered too.
312
+ - it only vetoes **model-requested tool calls from the queen Session**. The
313
+ supervisor's swarm dispatch (`ctx.subagents.startActivation`) is a service call,
314
+ not a tool execution, so it bypasses `tools.guard` and keeps working from the same
315
+ queen Session; worker/child Sessions and their own subagent tools are unaffected
316
+ (PTC nested tool calls share the same pipeline and are covered by the predicate).
302
317
 
303
318
  Tests: `test/queen-boundary.test.js` covers all three vetoed tools, the queen-only
304
- predicate, the durable event, and the status counters.
319
+ predicate, cwd-role detection and auto-registration, `/queen off` suppression,
320
+ uninitialized repositories, worker/other Sessions, the durable event, the anomaly and
321
+ the status counters; `test/queen-boundary-dispatch.test.js` proves supervisor dispatch
322
+ and worker delegation bypass the guard.
305
323
 
306
324
  The queen must not edit code or commit: delivery is otherwise prompt-level
307
325
  coordination, and the `hive_arch_review` tool only appends an event.
package/index.js CHANGED
@@ -164,11 +164,39 @@ export function apply(ctx, config = {}) {
164
164
  if (last !== null) log('warn', 'queen boundary violation blocked:', violation.tool, 'session', violation.sessionId);
165
165
  }
166
166
 
167
+ /** Resolve the effective cwd of a tool-calling Session for queen detection. */
168
+ function resolveQueenBoundaryCwd(agent, session) {
169
+ const headerCwd = session?.header?.cwd;
170
+ if (typeof headerCwd === 'string' && headerCwd !== '') return headerCwd;
171
+ try {
172
+ const cwd = ctx.get('workingDirectory')?.get?.(session ?? agent?.session);
173
+ if (typeof cwd === 'string' && cwd !== '') return cwd;
174
+ } catch {
175
+ // Fall through: without a cwd the Session cannot be recognized as queen.
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /** Idempotently register a cwd-recognized queen so the panel can show it. */
181
+ function registerDetectedQueen(sessionId, cwd) {
182
+ try {
183
+ if (supervisor.queenSession.sessionId === sessionId) return;
184
+ supervisor.setQueenSession(sessionId);
185
+ log('info', 'auto-registered initialized queen session', sessionId, 'cwd', cwd);
186
+ } catch (error) {
187
+ log('warn', 'auto-registering detected queen failed', error);
188
+ }
189
+ }
190
+
167
191
  // DSH tools.guard is evaluated after pre-execute policy/approval and before a
168
192
  // tool body; returning a denial makes the call fail without executing it.
193
+ // Recognition is registration OR an ordinary initialized-repo Session; a
194
+ // /queen off command event suppresses both paths.
169
195
  ctx.effect(() => ctx.tools.guard(createQueenBoundaryGuard({
170
196
  queenSession,
171
197
  onViolation: recordQueenBoundaryViolation,
198
+ onQueenDetected: registerDetectedQueen,
199
+ resolveCwd: resolveQueenBoundaryCwd,
172
200
  log,
173
201
  })));
174
202
 
@@ -9,13 +9,25 @@
9
9
  * and tells the queen to create Hive cards instead, and the attempt is recorded
10
10
  * as a `queen_boundary_violation` event plus a supervision anomaly.
11
11
  *
12
- * Matching is by the registered queen Session id, so card workers (which are
13
- * child sessions) keep their normal subagent tools.
12
+ * A queen Session is recognized in two ways, so the veto does not depend on the
13
+ * panel having registered a Session first:
14
+ * 1. the registered `queenSessionId` (legacy/explicit registration), or
15
+ * 2. an ordinary (non-worker) Session whose cwd carries
16
+ * `.hive/roles/queen.md` and that has not run `/queen off`.
17
+ * The second path also registers the Session as queen (idempotent) so the panel
18
+ * can show it. Card workers are subagent-origin Sessions and keep their normal
19
+ * subagent tools.
14
20
  *
15
21
  * @module dsh-hive-runner/queen-boundary
16
22
  */
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+
17
26
  import { ANOMALY_KINDS } from './anomalies.js';
18
27
 
28
+ /** Repository-relative queen role file: its presence marks a Hive-initialised repo. */
29
+ export const QUEEN_ROLE_FILE = path.join('.hive', 'roles', 'queen.md');
30
+
19
31
  /** Tools a queen Session may never call directly. */
20
32
  export const QUEEN_FORBIDDEN_TOOLS = Object.freeze([
21
33
  'subagent',
@@ -74,6 +86,58 @@ export function recordQueenBoundaryViolation(violation, {
74
86
  return state.last;
75
87
  }
76
88
 
89
+ /**
90
+ * Whether a cwd carries the Hive queen role file, i.e. the repository was
91
+ * initialised with `hive init`.
92
+ * @param {string} cwd
93
+ * @returns {boolean}
94
+ */
95
+ export function hasQueenRole(cwd) {
96
+ if (typeof cwd !== 'string' || cwd === '') return false;
97
+ try {
98
+ return fs.existsSync(path.join(cwd, QUEEN_ROLE_FILE));
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Latest slash-command state for the queen controller: `on`, `off`, or null.
106
+ * Command lifecycle events are log-only; scanning backward makes suppression
107
+ * survive plugin restarts without a panel request.
108
+ * @param {object} session DSH Session
109
+ * @returns {'on' | 'off' | null}
110
+ */
111
+ export function latestQueenCommand(session) {
112
+ let events = [];
113
+ try {
114
+ if (typeof session?.snapshotEvents === 'function') events = session.snapshotEvents();
115
+ } catch {
116
+ return null;
117
+ }
118
+ for (let index = events.length - 1; index >= 0; index -= 1) {
119
+ const event = events[index];
120
+ if (event?.type !== 'command/run' || event.data?.name !== 'queen') continue;
121
+ const verb = String(event.data.args ?? '').trim().toLowerCase();
122
+ if (verb === 'off') return 'off';
123
+ if (verb === 'on') return 'on';
124
+ }
125
+ return null;
126
+ }
127
+
128
+ /** Whether the user explicitly left queen mode in this Session. */
129
+ export function isQueenSuppressed(session) {
130
+ return latestQueenCommand(session) === 'off';
131
+ }
132
+
133
+ /** Whether a Session is a card worker / delegation child, never the queen. */
134
+ export function isWorkerSession(session) {
135
+ const header = session?.header;
136
+ if (header === null || typeof header !== 'object') return false;
137
+ return header.origin === 'subagent'
138
+ || (Number.isInteger(header.delegationDepth) && header.delegationDepth > 0);
139
+ }
140
+
77
141
  /** Structured error identity recorded on the failed tool result. */
78
142
  export const QUEEN_BOUNDARY_ERROR = Object.freeze({
79
143
  name: 'QueenBoundaryViolation',
@@ -82,22 +146,72 @@ export const QUEEN_BOUNDARY_ERROR = Object.freeze({
82
146
 
83
147
  /**
84
148
  * Build the guard registered through `ctx.tools.guard`.
85
- * @param {{ queenSession: { sessionId: string | null }, onViolation?: (violation: object) => void, log?: (level: string, ...args: unknown[]) => void }} options
86
- * @returns {(exec: { name: string, agent?: { session?: { id?: string, header?: { cwd?: string } } } }) => object | undefined}
149
+ * @param {{
150
+ * queenSession: { sessionId: string | null },
151
+ * onViolation?: (violation: object) => void,
152
+ * onQueenDetected?: (sessionId: string, cwd: string) => void,
153
+ * resolveCwd?: (agent: object, session: object) => string | null,
154
+ * hasRole?: (cwd: string) => boolean,
155
+ * isSuppressed?: (session: object) => boolean,
156
+ * log?: (level: string, ...args: unknown[]) => void,
157
+ * }} options
158
+ * @returns {(exec: { name: string, agent?: { session?: object } }) => object | undefined}
87
159
  */
88
- export function createQueenBoundaryGuard({ queenSession, onViolation, log = () => {} } = {}) {
160
+ export function createQueenBoundaryGuard({
161
+ queenSession,
162
+ onViolation,
163
+ onQueenDetected,
164
+ resolveCwd,
165
+ hasRole = hasQueenRole,
166
+ isSuppressed = isQueenSuppressed,
167
+ log = () => {},
168
+ } = {}) {
89
169
  return function queenBoundaryGuard(exec) {
90
170
  if (exec === null || typeof exec !== 'object') return undefined;
91
171
  if (!QUEEN_FORBIDDEN_TOOLS.includes(exec.name)) return undefined;
92
- const sessionId = exec.agent?.session?.id;
172
+ const session = exec.agent?.session;
173
+ const sessionId = session?.id;
174
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined;
175
+
93
176
  const queenSessionId = queenSession?.sessionId;
94
- if (typeof queenSessionId !== 'string' || queenSessionId === '' || sessionId !== queenSessionId) return undefined;
177
+ const registered = typeof queenSessionId === 'string' && queenSessionId !== '' && sessionId === queenSessionId;
178
+ // Worker/child Sessions never need the (possibly long) log scan and are
179
+ // outside the queen boundary.
180
+ if (!registered && isWorkerSession(session)) return undefined;
181
+
182
+ // `/queen off` wins over both recognition paths.
183
+ let suppressed = false;
184
+ try {
185
+ suppressed = typeof isSuppressed === 'function' ? isSuppressed(session) === true : false;
186
+ } catch {
187
+ suppressed = false;
188
+ }
189
+ if (suppressed) return undefined;
190
+
191
+ let cwd = null;
192
+ try {
193
+ if (typeof resolveCwd === 'function') cwd = resolveCwd(exec.agent, session);
194
+ else if (typeof session?.header?.cwd === 'string') cwd = session.header.cwd;
195
+ } catch {
196
+ cwd = null;
197
+ }
198
+ const initialised = !isWorkerSession(session) && hasRole(cwd);
199
+ if (!registered && !initialised) return undefined;
200
+
201
+ if (!registered && initialised && typeof onQueenDetected === 'function') {
202
+ try {
203
+ onQueenDetected(sessionId, cwd);
204
+ } catch (error) {
205
+ log('warn', 'queen session auto-registration failed', error);
206
+ }
207
+ }
95
208
 
96
209
  const violation = {
97
210
  sessionId,
98
211
  tool: exec.name,
99
212
  at: Date.now(),
100
- repo: typeof exec.agent?.session?.header?.cwd === 'string' ? exec.agent.session.header.cwd : null,
213
+ repo: typeof cwd === 'string' && cwd !== '' ? cwd : null,
214
+ detectedBy: registered ? 'registration' : 'cwd-role',
101
215
  };
102
216
  try {
103
217
  if (typeof onViolation === 'function') onViolation(violation);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
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",