dsh-hive-runner 0.8.0 → 1.0.1

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,44 @@ 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.1] - 2026-12-05
11
+
12
+ ### Added
13
+
14
+ - The queen Session can no longer delegate coding directly: a global DSH
15
+ `ctx.tools.guard` vetoes `subagent`, `subagent_fork` and `subagent_claude_code`
16
+ calls from the registered queen Session. The failed tool result says
17
+ `女王不改代码,请用 hive_tasks 建任务`, the attempt is appended to
18
+ `<repo>/.hive/events.jsonl` as `queen_boundary_violation`, pushed as a
19
+ `queen-boundary-violation` anomaly digest, and counted in status
20
+ (`queenBoundaryViolations` / `lastQueenBoundaryViolation`). Workers keep their
21
+ subagent tools.
22
+ ## [1.0.0] - 2026-12-04
23
+
24
+ ### Stable
25
+
26
+ - The host-plugin surface is frozen for the 1.x line: the Hive tools (`hive_run_round`,
27
+ `hive_tasks` with `add/edit/split/supersede/claim/done/fail/retry/rm`, `hive_board`,
28
+ `hive_supervisor_status`), `hive_intervene`, the same-origin status / pause / resume /
29
+ limits route and its JSON shapes, the `hiveSupervisor` service, and every config key
30
+ (`repos`, `autoDiscover`, `discoverRoots`, `intervalMs`, `idleBackoffMs`,
31
+ `maxConcurrentRepos`, `roleConcurrency`, `defaultRoleConcurrency`, `paused`,
32
+ `agent`, `ttl`, `provider`, `parentSession`, `cwd`, `tasksBin`, `hiveBin`,
33
+ `gitBin`, the timeouts and `debug`) keep their names and semantics during 1.x; new
34
+ config keys and snapshot fields may be added, removals wait for a future major.
35
+ - The on-disk contracts stay stable: `<repo>/.hive/limits.json`, the `.hive/runs/`
36
+ last-run records and the events written through hive-tasks.
37
+
38
+ ### Compatibility
39
+
40
+ - DSH 0.2.2-rc.5, Node >=22, peer `@deepseek-ai/dsh-tools`. Upgrading from 0.8.x needs
41
+ no config or repository change; persisted limits and run records are read as before, and
42
+ the four 0.8 tools keep their names, arguments and JSON output.
43
+
44
+ ### Published
45
+
46
+ - npm: `dsh-hive-runner@1.0.0` on 2026-12-04.
47
+
10
48
  ## [0.8.0] - 2026-12-04
11
49
 
12
50
  ### Added
@@ -45,6 +83,10 @@ iterations of the plugin before this repository was published.
45
83
  rules, the panel's agent-concurrency and resume controls, intervention/arch-review
46
84
  event shapes, the Node 22.19 floor and the current test count. No behaviour change.
47
85
 
86
+ ### Published
87
+
88
+ - npm: `dsh-hive-runner@0.8.0` on 2026-12-04.
89
+
48
90
  ## [0.7.0] - 2026-12-04
49
91
 
50
92
  The queen becomes a coordinator: the supervisor now feeds her the anomalies she has to
package/README.md CHANGED
@@ -101,8 +101,12 @@ she must act on. The authoritative contract is `<repo>/.hive/roles/queen.md` (wr
101
101
 
102
102
  The tool surface keeps the boundary: none of the queen's tools claims or finishes a task
103
103
  (`hive-tasks claim` / `done` belong to agents and the supervisor), and none edits or
104
- commits code. The queen contract forbids code edits; task metadata
105
- (add/reopen/retry/rm), roles and lessons are coordination state, not code.
104
+ commits code. The boundary is enforced, not just documented: the runner registers a
105
+ DSH `ctx.tools.guard`, so a queen Session calling `subagent`, `subagent_fork` or
106
+ `subagent_claude_code` directly gets a failed tool result telling her
107
+ `女王不改代码,请用 hive_tasks 建任务`, and the attempt is recorded as a
108
+ `queen_boundary_violation` event (with an anomaly digest for self-correction). Task
109
+ metadata (add/reopen/retry/rm), roles and lessons are coordination state, not code.
106
110
 
107
111
  ### When the queen hears from the supervisor
108
112
 
@@ -317,8 +321,8 @@ DSH 0.2.2-rc.5):
317
321
  <details>
318
322
  <summary>Manual profile edit (same result, only needed when the CLI is unavailable)</summary>
319
323
 
320
- While DSH Desktop is not running, add `"dsh-hive-panel": ">=0.2.3"` and
321
- `"dsh-hive-runner": "^0.8.0"` to the profile's `dependencies`, add both names to
324
+ While DSH Desktop is not running, add `"dsh-hive-panel": "^1.0.0"` and
325
+ `"dsh-hive-runner": "^1.0.0"` to the profile's `dependencies`, add both names to
322
326
  `dsh.profile.bundles`, then `cd ~/.dsh/profiles/desktop && pnpm install`.
323
327
 
324
328
  </details>
package/README.zh-CN.md CHANGED
@@ -236,7 +236,7 @@ outstanding/failed 与 `releaseReady`、`reason`)。`releaseReady` 为 true
236
236
  <details>
237
237
  <summary>手工改 profile(效果相同,仅在 CLI 不可用时使用)</summary>
238
238
 
239
- 在 DSH Desktop 退出时,把 `"dsh-hive-panel": ">=0.2.3"` 与 `"dsh-hive-runner": "^0.8.0"`
239
+ 在 DSH Desktop 退出时,把 `"dsh-hive-panel": "^1.0.0"` 与 `"dsh-hive-runner": "^1.0.0"`
240
240
  加进 profile 的 `dependencies`、把两个包名加进 `dsh.profile.bundles`,然后
241
241
  `cd ~/.dsh/profiles/desktop && pnpm install`。
242
242
 
package/SPEC.md CHANGED
@@ -56,6 +56,8 @@ wrong method -> `405` (`hive/method-not-allowed`).
56
56
  "capacityRetryMs": 2000,
57
57
  "queenSessionId": "queen-session-id",
58
58
  "waiting": null,
59
+ "queenBoundaryViolations": 0,
60
+ "lastQueenBoundaryViolation": null,
59
61
  "lastTickAt": "2026-12-04T00:00:00.000Z",
60
62
  "lastDiscoverError": null,
61
63
  "pendingAnomalies": 0,
@@ -234,11 +236,9 @@ with the supervisor (`POST /api/hive-runner?op=queen { sessionId }` or
234
236
  next panel access re-registers it after a restart. Before registration the supervisor
235
237
  does not dispatch: the round is skipped and status reports
236
238
  `waiting: "no-queen-session"` (a startup-order hint, not an error). While the
237
- registered Session is live, every activation uses exactly its Agent. If that Agent
238
- cannot be resolved any more (for example the Session was closed), parent resolution
239
- falls back to `config.parentSession` and then to the first live Agent; when no Agent is
240
- live the round defers with `hive/no-parent-agent` and the task is not failed. Once
241
- registered, dispatch does not depend on any other user session being live.
239
+ registered Session is live, every activation uses exactly its Agent. There is no
240
+ fallback to another Session or to the first live Agent; once registered, dispatch
241
+ does not depend on any other user session being live.
242
242
 
243
243
  Before every drain the supervisor requires a Hive-initialised repository whose
244
244
  `<repo>/.git/hooks/pre-commit` runs merge-on-commit (it mentions merge-on-commit or moc).
@@ -343,6 +343,19 @@ Agent exists the digest is *not* marked delivered: it stays pending, is listed b
343
343
  flushed by the next `setQueenSession` registration or patrol tick. A healthy swarm
344
344
  delivers nothing.
345
345
 
346
+ ### 8.6.1 Queen tool boundary
347
+
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
352
+ `女王不改代码,请用 hive_tasks 建任务(检测到 <tool> 调用,已拦截...)`; the body never
353
+ runs. The attempt is appended to `<repo>/.hive/events.jsonl` with
354
+ `kind: "queen_boundary_violation"` (`ts`, `actor`, `tool`, `message`, `sessionId`),
355
+ 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
+
346
359
  ## 8.7 Gates and release readiness
347
360
 
348
361
  Gate ordering is tag-based, never a new task state. `gate:group` tasks dispatch only when
package/docs/DESIGN.md CHANGED
@@ -45,6 +45,8 @@ Response:
45
45
  "capacityRetryMs": 2000,
46
46
  "queenSessionId": "queen-session-id",
47
47
  "waiting": null,
48
+ "queenBoundaryViolations": 0,
49
+ "lastQueenBoundaryViolation": null,
48
50
  "lastTickAt": "2026-12-04T00:00:00.000Z",
49
51
  "lastDiscoverError": null,
50
52
  "pendingAnomalies": 0,
@@ -107,6 +109,9 @@ Response:
107
109
  `"no-queen-session"` until the registration arrives (startup-order hint, not an
108
110
  error); the registration is only replaced by a new registration. Status workers and
109
111
  run records carry `parentSource: "queen"` when the registered Session parented them.
112
+ - `queenBoundaryViolations` — how many direct `subagent`/`subagent_fork`/
113
+ `subagent_claude_code` calls from the queen Session the tool guard has vetoed;
114
+ `lastQueenBoundaryViolation` is `{ tool, sessionId, at, repo }` for the most recent.
110
115
  - `workers` — live agents in this repository: `cardId`, `role`, `agent`,
111
116
  `sessionId`, `agentName`, `startedAt`, `lastOutputAt`, `heartbeat`
112
117
  (`ok`/`warn`), `claimDeadline`, `timeoutAt`. The Session id is written into the
@@ -219,7 +224,8 @@ consuming the failure budget.
219
224
  | `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 |
220
225
  | `lib/gates.js` | Gate pipeline: tag classification (`gate:group`, `gate:overall`), phase computation (base -> group -> overall -> released/no-overall), release readiness and dispatch filtering |
221
226
  | `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 |
222
- | `lib/events.js` | `.hive/events.jsonl` append/read plus the `arch_review`, `queen_intervention` and `queen_escalation` event contracts |
227
+ | `lib/events.js` | `.hive/events.jsonl` append/read plus the `arch_review`, `queen_intervention`, `queen_escalation` and `queen_boundary_violation` event contracts |
228
+ | `lib/queen-boundary.js` | `ctx.tools.guard` veto for queen → `subagent`/`subagent_fork`/`subagent_claude_code`; returns the correction and reports the attempt |
223
229
  | `lib/limits.js` | `<repo>/.hive/limits.json` read/write/hot-reload and precedence helpers |
224
230
  | `lib/config.js` | Config defaults/validation (`patrolMs`, `notifyQueen`, `anomaly*`, `rolesBin`), role map parsing, effective-limit helpers |
225
231
  | `lib/commands.js` | Allowlisted `hive-tasks` / `hive` / `git` / acceptance commands with shell quoting; queen verbs list/add/edit/split/supersede/reopen/retry/rm/lesson/roles |
@@ -268,6 +274,34 @@ lessons, and the supervisor feeds it anomalies. The design constraints:
268
274
  `hive_anomalies` / `GET ?op=pending`; the next queen registration or patrol flushes
269
275
  it. This is the documented degradation path when no Session is live.
270
276
 
271
- The queen must not edit code or commit: delivery is prompt-level coordination, and
272
- the `hive_arch_review` tool only appends an event. Hard enforcement would be a DSH
273
- `ctx.tools.restrict` decision outside this plugin.
277
+ ### Tool boundary: hard veto through `ctx.tools.guard`
278
+
279
+ DSH does expose a plugin-side tool veto. `ToolsService.guard(guard)` registers a
280
+ monotonic denial evaluated by the shared Native/PTC tool pipeline after
281
+ `tools/pre-execute` policy and approval, and **before the tool body runs**. Returning
282
+ `{ reason, info }` materializes a failed tool result (`Error: <reason>`) with that
283
+ structured identity, so the call never executes. This is a real interception, not a
284
+ post-hoc notification; the fallback (supervisor message + status counter) is not
285
+ needed and is not implemented.
286
+
287
+ `lib/queen-boundary.js` registers one global guard from `apply()` inside a
288
+ `ctx.effect`:
289
+
290
+ - predicate: the tool name is `subagent`, `subagent_fork` or `subagent_claude_code`, and
291
+ `exec.agent.session.id` equals the registered `queenSessionId`;
292
+ - denial: `女王不改代码,请用 hive_tasks 建任务(检测到 <tool> 调用,已拦截;请把工作
293
+ 拆成任务卡并交给 hive_tasks。)`, with `info.code = QUEEN_BOUNDARY_VIOLATION`;
294
+ - the attempt is appended to `<repo>/.hive/events.jsonl` as
295
+ `{ ts, actor: "hive-runner", kind: "queen_boundary_violation", tool, message,
296
+ "sessionId" }` through `appendQueenBoundaryViolation`;
297
+ - it also becomes a `queen-boundary-violation` anomaly, so the coalesced anomaly digest
298
+ tells the queen to self-correct; `status` exposes `queenBoundaryViolations` and
299
+ `lastQueenBoundaryViolation`;
300
+ - worker/child Sessions are unaffected, and PTC nested calls go through the same
301
+ pipeline, so they are covered too.
302
+
303
+ Tests: `test/queen-boundary.test.js` covers all three vetoed tools, the queen-only
304
+ predicate, the durable event, and the status counters.
305
+
306
+ The queen must not edit code or commit: delivery is otherwise prompt-level
307
+ coordination, and the `hive_arch_review` tool only appends an event.
package/index.js CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  appendArchReview,
29
29
  appendEscalation,
30
30
  appendIntervention,
31
+ appendQueenBoundaryViolation,
31
32
  ESCALATION_KIND,
32
33
  escalatedCards,
33
34
  INTERVENTION_ESCALATE_AFTER,
@@ -43,6 +44,7 @@ import { createAnomalyFeed } from './lib/anomalies.js';
43
44
  import { createQueenNotifier, deliverToSession } from './lib/notify.js';
44
45
  import { createPatrol } from './lib/patrol.js';
45
46
  import { drainQueue } from './lib/queue.js';
47
+ import { createQueenBoundaryGuard, recordQueenBoundaryViolation as recordQueenBoundaryAttempt } from './lib/queen-boundary.js';
46
48
  import { createRoundRunner } from './lib/round.js';
47
49
  import { readRunRecord } from './lib/runs.js';
48
50
  import { HiveSupervisor } from './lib/supervisor.js';
@@ -102,6 +104,8 @@ export function apply(ctx, config = {}) {
102
104
  // POST ?op=queen). Every worker is parented to exactly that Session; before
103
105
  // registration the supervisor does not dispatch at all.
104
106
  const queenSession = { sessionId: null };
107
+ /** Queen boundary violations observed by the tool guard (status observability). */
108
+ const queenBoundary = { count: 0, last: null };
105
109
  let parentProviderImpl;
106
110
  const runner = createRoundRunner({
107
111
  ctx,
@@ -132,6 +136,42 @@ export function apply(ctx, config = {}) {
132
136
  }
133
137
  if (patrol !== undefined && resolved.notifyQueen) patrol.scheduleFlush();
134
138
  }
139
+
140
+ /** Resolve the repository of the violating queen Session (header first). */
141
+ function repoOfQueenViolation(violation) {
142
+ if (typeof violation?.repo === 'string' && violation.repo !== '') return violation.repo;
143
+ try {
144
+ const agent = ctx.get('agents')?.get?.(violation?.sessionId);
145
+ const headerCwd = agent?.session?.header?.cwd;
146
+ if (typeof headerCwd === 'string' && headerCwd !== '') return headerCwd;
147
+ const cwd = ctx.get('workingDirectory')?.get?.(agent?.session);
148
+ if (typeof cwd === 'string' && cwd !== '') return cwd;
149
+ } catch {
150
+ // Observability must never affect the veto.
151
+ }
152
+ return null;
153
+ }
154
+
155
+ /** Record one blocked queen → subagent attempt: event + anomaly + counter. */
156
+ function recordQueenBoundaryViolation(violation) {
157
+ const last = recordQueenBoundaryAttempt(violation, {
158
+ repo: repoOfQueenViolation(violation),
159
+ state: queenBoundary,
160
+ appendEvent: appendQueenBoundaryViolation,
161
+ recordAnomaly,
162
+ log,
163
+ });
164
+ if (last !== null) log('warn', 'queen boundary violation blocked:', violation.tool, 'session', violation.sessionId);
165
+ }
166
+
167
+ // DSH tools.guard is evaluated after pre-execute policy/approval and before a
168
+ // tool body; returning a denial makes the call fail without executing it.
169
+ ctx.effect(() => ctx.tools.guard(createQueenBoundaryGuard({
170
+ queenSession,
171
+ onViolation: recordQueenBoundaryViolation,
172
+ log,
173
+ })));
174
+
135
175
  const notifier = createQueenNotifier({ ctx, queenSession, log });
136
176
  // Done cards must carry an arch_review event; the patrol audits the board and
137
177
  // turns a missing review into an arch-review-missing anomaly.
@@ -165,6 +205,7 @@ export function apply(ctx, config = {}) {
165
205
  preflight: runner.preflight,
166
206
  activeRuns: (repo) => runner.activeRuns(repo),
167
207
  queenSession,
208
+ queenBoundary,
168
209
  readMode: (repo) => commands.mode(repo),
169
210
  onAnomaly: (event) => recordAnomaly(event),
170
211
  onQueenSession: () => {
package/lib/anomalies.js CHANGED
@@ -35,6 +35,8 @@ export const ANOMALY_KINDS = Object.freeze({
35
35
  ARCH_REVIEW_MISSING: 'arch-review-missing',
36
36
  /** A card the queen intervened on repeatedly needs a human decision. */
37
37
  ESCALATION: 'queen-escalation',
38
+ /** The queen tried to delegate coding directly; the tool guard vetoed it. */
39
+ QUEEN_BOUNDARY_VIOLATION: 'queen-boundary-violation',
38
40
  });
39
41
 
40
42
  const SEVERITY = Object.freeze({
@@ -47,6 +49,7 @@ const SEVERITY = Object.freeze({
47
49
  [ANOMALY_KINDS.ENVIRONMENT]: 'warn',
48
50
  [ANOMALY_KINDS.ARCH_REVIEW_MISSING]: 'warn',
49
51
  [ANOMALY_KINDS.ESCALATION]: 'error',
52
+ [ANOMALY_KINDS.QUEEN_BOUNDARY_VIOLATION]: 'warn',
50
53
  });
51
54
 
52
55
  /** Default coalescing window: the same condition inside it updates one entry. */
package/lib/events.js CHANGED
@@ -105,6 +105,10 @@ export function appendArchReview(repo, review = {}) {
105
105
  export const INTERVENTION_KIND = 'queen_intervention';
106
106
  /** Event kind written when a card needs a human decision. */
107
107
  export const ESCALATION_KIND = 'queen_escalation';
108
+ /** Event kind written when the queen tries to delegate coding directly. */
109
+ export const QUEEN_BOUNDARY_KIND = 'queen_boundary_violation';
110
+ /** Model-facing correction carried by a boundary violation. */
111
+ export const QUEEN_BOUNDARY_MESSAGE = '女王不改代码,请用 hive_tasks 建任务';
108
112
  /** Intervention actions the queen may record. */
109
113
  export const INTERVENTION_ACTIONS = Object.freeze([
110
114
  'reopen', 'split', 'reassign', 'pause', 'fail', 'guide', 'remove', 'rebuild', 'escalate',
@@ -185,6 +189,29 @@ export function appendEscalation(repo, escalation = {}) {
185
189
  return appendEvent(repo, event);
186
190
  }
187
191
 
192
+ /**
193
+ * Append one queen_boundary_violation event: the queen called a subagent tool
194
+ * directly, the tool guard vetoed it, and the queen was told to create cards.
195
+ * @param {string} repo
196
+ * @param {{ tool: string, sessionId?: string, message?: string, actor?: string, at?: number }} violation
197
+ * @returns {object} the stored event
198
+ */
199
+ export function appendQueenBoundaryViolation(repo, violation = {}) {
200
+ const tool = text(violation.tool, 80);
201
+ if (tool === '') throw new TypeError('a queen boundary violation must name the blocked tool');
202
+ const event = {
203
+ ts: new Date(Number.isFinite(violation.at) ? violation.at : Date.now()).toISOString(),
204
+ actor: text(violation.actor ?? 'hive-runner', 64) || 'hive-runner',
205
+ kind: QUEEN_BOUNDARY_KIND,
206
+ tool,
207
+ message: text(violation.message ?? QUEEN_BOUNDARY_MESSAGE, 600) || QUEEN_BOUNDARY_MESSAGE,
208
+ };
209
+ if (typeof violation.sessionId === 'string' && violation.sessionId !== '') {
210
+ event.sessionId = text(violation.sessionId, 128);
211
+ }
212
+ return appendEvent(repo, event);
213
+ }
214
+
188
215
  /** Count queen_intervention events per card id. */
189
216
  export function interventionCounts(events) {
190
217
  const counts = new Map();
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Queen boundary guard: the queen coordinates, it does not delegate coding.
3
+ *
4
+ * DSH exposes a monotonic tool guard (`ctx.tools.guard`) evaluated after the
5
+ * pre-execute policy and approval seam, before a tool body runs. Registering one
6
+ * global guard lets this plugin veto a queen Session's direct
7
+ * `subagent`/`subagent_fork`/`subagent_claude_code` calls: the tool body never
8
+ * runs, the model receives a failed tool result whose text names the violation
9
+ * and tells the queen to create Hive cards instead, and the attempt is recorded
10
+ * as a `queen_boundary_violation` event plus a supervision anomaly.
11
+ *
12
+ * Matching is by the registered queen Session id, so card workers (which are
13
+ * child sessions) keep their normal subagent tools.
14
+ *
15
+ * @module dsh-hive-runner/queen-boundary
16
+ */
17
+ import { ANOMALY_KINDS } from './anomalies.js';
18
+
19
+ /** Tools a queen Session may never call directly. */
20
+ export const QUEEN_FORBIDDEN_TOOLS = Object.freeze([
21
+ 'subagent',
22
+ 'subagent_fork',
23
+ 'subagent_claude_code',
24
+ ]);
25
+
26
+ /** Model-facing correction. */
27
+ export const QUEEN_BOUNDARY_MESSAGE = '女王不改代码,请用 hive_tasks 建任务';
28
+
29
+ /**
30
+ * Record one vetoed attempt: bump the shared counter, append the durable
31
+ * `queen_boundary_violation` event and push the queen-facing anomaly.
32
+ * Side effects are best-effort; a failure never changes the veto itself.
33
+ * @param {{ tool: string, sessionId?: string, at?: number }} violation
34
+ * @param {{ repo?: string | null, state: { count: number, last: object | null }, appendEvent?: Function, recordAnomaly?: Function, log?: Function }} options
35
+ * @returns {object | null} the recorded `last` entry
36
+ */
37
+ export function recordQueenBoundaryViolation(violation, {
38
+ repo = null,
39
+ state,
40
+ appendEvent,
41
+ recordAnomaly,
42
+ log = () => {},
43
+ } = {}) {
44
+ if (state === undefined || state === null) return null;
45
+ const at = Number.isFinite(violation?.at) ? violation.at : Date.now();
46
+ state.count = (Number.isInteger(state.count) ? state.count : 0) + 1;
47
+ state.last = {
48
+ tool: violation?.tool,
49
+ sessionId: violation?.sessionId,
50
+ at: new Date(at).toISOString(),
51
+ repo: typeof repo === 'string' && repo !== '' ? repo : null,
52
+ };
53
+ if (typeof appendEvent === 'function' && typeof repo === 'string' && repo !== '') {
54
+ try {
55
+ appendEvent(repo, { tool: violation?.tool, sessionId: violation?.sessionId, at });
56
+ } catch (error) {
57
+ log('warn', 'queen boundary event append failed', error);
58
+ }
59
+ }
60
+ if (typeof recordAnomaly === 'function') {
61
+ try {
62
+ recordAnomaly({
63
+ kind: ANOMALY_KINDS.QUEEN_BOUNDARY_VIOLATION,
64
+ repo: state.last.repo ?? '',
65
+ summary: QUEEN_BOUNDARY_MESSAGE
66
+ + '(已拦截 ' + String(violation?.tool) + ' 调用,请把工作写成任务卡)',
67
+ detail: 'queen session ' + String(violation?.sessionId) + ' called ' + String(violation?.tool),
68
+ at,
69
+ });
70
+ } catch (error) {
71
+ log('warn', 'queen boundary anomaly push failed', error);
72
+ }
73
+ }
74
+ return state.last;
75
+ }
76
+
77
+ /** Structured error identity recorded on the failed tool result. */
78
+ export const QUEEN_BOUNDARY_ERROR = Object.freeze({
79
+ name: 'QueenBoundaryViolation',
80
+ code: 'QUEEN_BOUNDARY_VIOLATION',
81
+ });
82
+
83
+ /**
84
+ * 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}
87
+ */
88
+ export function createQueenBoundaryGuard({ queenSession, onViolation, log = () => {} } = {}) {
89
+ return function queenBoundaryGuard(exec) {
90
+ if (exec === null || typeof exec !== 'object') return undefined;
91
+ if (!QUEEN_FORBIDDEN_TOOLS.includes(exec.name)) return undefined;
92
+ const sessionId = exec.agent?.session?.id;
93
+ const queenSessionId = queenSession?.sessionId;
94
+ if (typeof queenSessionId !== 'string' || queenSessionId === '' || sessionId !== queenSessionId) return undefined;
95
+
96
+ const violation = {
97
+ sessionId,
98
+ tool: exec.name,
99
+ at: Date.now(),
100
+ repo: typeof exec.agent?.session?.header?.cwd === 'string' ? exec.agent.session.header.cwd : null,
101
+ };
102
+ try {
103
+ if (typeof onViolation === 'function') onViolation(violation);
104
+ } catch (error) {
105
+ log('warn', 'queen boundary violation recording failed', error);
106
+ }
107
+ return {
108
+ reason: QUEEN_BOUNDARY_MESSAGE
109
+ + '(检测到 ' + exec.name + ' 调用,已拦截;请不要自己派活或改代码,把工作拆成任务卡并交给 hive_tasks。)',
110
+ info: { ...QUEEN_BOUNDARY_ERROR },
111
+ };
112
+ };
113
+ }
package/lib/supervisor.js CHANGED
@@ -108,6 +108,7 @@ export class HiveSupervisor {
108
108
  * @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
109
109
  * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
110
110
  * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
111
+ * @param {{ count: number, last: object | null }} [options.queenBoundary] queen boundary violation counters
111
112
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
112
113
  * @param {() => Promise<string[]>} [options.discover]
113
114
  * @param {(event: object) => void} [options.onAnomaly] supervision event sink (queen digest)
@@ -145,6 +146,7 @@ export class HiveSupervisor {
145
146
  // Shared with the round runner: the Session registered by the panel when the
146
147
  // queen takes over. Nothing is dispatched until this is set.
147
148
  this.queenSession = options.queenSession ?? { sessionId: null };
149
+ this.queenBoundary = options.queenBoundary ?? { count: 0, last: null };
148
150
  this.readMode = typeof options.readMode === 'function' ? options.readMode : undefined;
149
151
  this.onAnomaly = typeof options.onAnomaly === 'function' ? options.onAnomaly : undefined;
150
152
  this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
@@ -436,6 +438,10 @@ export class HiveSupervisor {
436
438
  // to it. Until it is registered nothing is dispatched.
437
439
  queenSessionId: this.queenSession.sessionId ?? null,
438
440
  waiting,
441
+ // Direct subagent calls from the queen are vetoed by the tool guard; the
442
+ // counter/last attempt is observability, not a scheduling decision.
443
+ queenBoundaryViolations: Number.isInteger(this.queenBoundary?.count) ? this.queenBoundary.count : 0,
444
+ lastQueenBoundaryViolation: this.queenBoundary?.last ?? null,
439
445
  intervalMs: this.intervalMs,
440
446
  idleBackoffMs: this.idleBackoffMs,
441
447
  maxConcurrentRepos: this.maxConcurrentRepos,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "0.8.0",
3
+ "version": "1.0.1",
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",