dsh-hive-runner 1.0.14 → 1.0.16

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,58 @@ 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.16] - 2026-12-05
11
+
12
+ ### Fixed — hard repository isolation (release blocker)
13
+
14
+ - Queen registration is now a repo → latest-Session mapping (`setQueenSession`,
15
+ HTTP `op=queen` with `repo`; a single-repo deployment may omit it, a one-argument
16
+ panel call infers the repo from the live Session cwd). `status.queens` exposes the
17
+ mapping and each repo reports `queenSessionId`/`unmanaged`.
18
+ - Dispatch and parenting are per repo: only a repo with a registered queen dispatches;
19
+ unmanaged repos never dispatch. The round runner passes the repo to the parent
20
+ provider so workers use that repo's queen agent.
21
+ - Delivery is per repo: anomaly digests are grouped by repo and checkpoints are only
22
+ delivered to the matching queen; no match stays pending. No cross-repo fallback.
23
+ - Tool layer is mechanically enforced: every `hive_*` tool with a `repo` parameter
24
+ rejects a queen call whose repo differs from the Session cwd (omitted means cwd)
25
+ before the body runs, with `女王只能操作自己所在的仓库`, and increments status
26
+ `crossRepoBlocked` / `lastCrossRepoBlocked`.
27
+ - Event writers require an absolute repo and reject a `.hive` symlink that would
28
+ redirect the append outside the repository. Orphan recovery remains per repo and
29
+ per runner identity.
30
+ - `.hive` events/checkpoints and anomaly delivery no longer leak between repos;
31
+ concurrency (pause and role limits) stays isolated per repository.
32
+
33
+ ### Tests
34
+
35
+ - New per-layer isolation suite: dispatch/unmanaged, latest-queen-per-repo, pause and
36
+ role-limit isolation, notifier/anomaly/checkpoint delivery, tool-scope rejection for
37
+ `hive_tasks`/`hive_intervene`/`hive_arch_review`/`hive_board`/`hive_events`,
38
+ event-path symlink escape, recovery, and grouped status. 258 tests pass.
39
+
40
+ ## [1.0.15] - 2026-12-05
41
+
42
+ ### Fixed
43
+
44
+ - Queen tool visibility is now diagnosed and observable. On queen registration (and
45
+ retried by the patrol if the agent was not live yet) the plugin lists
46
+ `ctx.tools.schemas(queenAgent)` once, logs `queen visible tools (<n>): ...`, and
47
+ exposes `queenTools` / `queenToolsSessionId` / `queenToolsListedAt` /
48
+ `queenToolsError` in status. Investigation: under PTC the model request declares only
49
+ `run_code`; the plugin tools are registered globally and are bound inside `run_code`
50
+ (live session log shows successful `hive_arch_review` PTC dispatches). The earlier
51
+ "no tools" report came from the boundary guard blocking `run_code` before 1.0.12, not
52
+ from a per-agent registration failure.
53
+ - Added a tool-independent host fallback:
54
+ `hiveSupervisor.recordArchReview(repo, { card, verdict, findings, summary })` writes
55
+ the same durable `arch_review` event through the shared host writer, so a caller can
56
+ repair reviews when an agent tool is unavailable; `hive_events` verifies it.
57
+
58
+ ### Published
59
+
60
+ - npm: `dsh-hive-runner@1.0.15` on 2026-12-05.
61
+
10
62
  ## [1.0.14] - 2026-12-05
11
63
 
12
64
  ### Fixed
@@ -28,6 +80,10 @@ iterations of the plugin before this repository was published.
28
80
  - `patrolMs` is still accepted as a legacy alias for `patrolIntervalMs`; both keys are
29
81
  reported on the resolved config.
30
82
 
83
+ ### Published
84
+
85
+ - npm: `dsh-hive-runner@1.0.14` on 2026-12-05.
86
+
31
87
  ## [1.0.13] - 2026-12-05
32
88
 
33
89
  ### Added
package/SPEC.md CHANGED
@@ -54,14 +54,21 @@ wrong method -> `405` (`hive/method-not-allowed`).
54
54
  "repoRoleConcurrency": {},
55
55
  "defaultRoleConcurrency": 5,
56
56
  "capacityRetryMs": 2000,
57
+ "queens": [{ "repo": "/abs/repo", "sessionId": "queen-session-id" }],
57
58
  "queenSessionId": "queen-session-id",
58
59
  "waiting": null,
59
60
  "queenBoundaryViolations": 0,
61
+ "crossRepoBlocked": 0,
62
+ "lastCrossRepoBlocked": null,
60
63
  "lastQueenBoundaryViolation": null,
61
64
  "lastTickAt": "2026-12-04T00:00:00.000Z",
62
65
  "lastDiscoverError": null,
63
66
  "pendingAnomalies": 0,
64
67
  "repoCount": 1,
68
+ "queenTools": ["hive_arch_review", "run_code"],
69
+ "queenToolsSessionId": "queen-session-id",
70
+ "queenToolsListedAt": "2026-12-05T09:00:00.000Z",
71
+ "queenToolsError": null,
65
72
  "claimedButOrphaned": 0,
66
73
  "workerSessionIds": ["worker-session-id"],
67
74
  "repos": [
@@ -79,6 +86,8 @@ wrong method -> `405` (`hive/method-not-allowed`).
79
86
  "consecutiveFailures": 0,
80
87
  "lastCards": 0,
81
88
  "lastResults": 0,
89
+ "queenSessionId": "queen-session-id",
90
+ "unmanaged": false,
82
91
  "waiting": null,
83
92
  "claimedButOrphaned": 0,
84
93
  "orphanRecovered": 0,
@@ -122,12 +131,18 @@ wrong method -> `405` (`hive/method-not-allowed`).
122
131
  - `backlog` — aggregate `{ queued, inFlight, completed }` for the current or last drain.
123
132
  - `pendingCheckpoints` — progress checkpoints queued while no live queen Session was
124
133
  available; the next patrol/queen registration flushes them.
134
+ - `queenTools` — one-shot diagnostic list of tool schema names visible to the registered
135
+ queen Agent, with `queenToolsSessionId`, `queenToolsListedAt`, `queenToolsError`.
125
136
  - `repos` / `repoCount` — the status-visible repository registry. `hiveSupervisor.addRepo(repo)`
126
137
  adds one at runtime (absolute path, must be an initialized Hive repository; idempotent;
127
138
  rejects a relative or uninitialized path).
128
- - `queenSessionId` — the queen conversation registered by the panel; agents are
129
- parented to that Session while it is live (see §8). `waiting` is
130
- `"no-queen-session"` until that registration happens.
139
+ - `queens` — repo → queen Session mapping (`[{ repo, sessionId }]`, latest per repo).
140
+ Workers are parented only to the queen of their repo. `queenSessionId`/`waiting`
141
+ are a single-queen compatibility view (global id is `null` with several queens).
142
+ - `crossRepoBlocked` / `lastCrossRepoBlocked` — queen hive_* calls rejected because
143
+ `repo` did not resolve to the Session cwd (`女王只能操作自己所在的仓库`).
144
+ - Per-repo `queenSessionId`/`unmanaged` — a repo with no matching queen is unmanaged,
145
+ never dispatched to and never notified.
131
146
  - `waiting` — per repository (and top level) `"no-queen-session"` before the queen
132
147
  Session is registered; then `null`. It is a startup-order hint, never an error.
133
148
  - `claimedButOrphaned` / `orphanRecovered` / `orphanRecoveryAt` — after a supervisor
@@ -392,6 +407,17 @@ counts + gate + recent completed ids); a change re-arms it. With no live queen
392
407
  Session it stays pending (`status.pendingCheckpoints`) and is flushed by the next
393
408
  patrol or queen registration.
394
409
 
410
+ A host-side fallback writes the same durable event without the agent tool:
411
+ `hiveSupervisor.recordArchReview(repo, { card, verdict, findings, summary })`; the
412
+ read-only `hive_events` tool verifies the appended event.
413
+
414
+ All queen actions are repository-scoped mechanically. Every `hive_*` tool with a
415
+ `repo` parameter is wrapped: for a registered queen the repo must resolve to the
416
+ Session cwd (omitted means cwd), otherwise the tool fails before its body with
417
+ `女王只能操作自己所在的仓库` and `crossRepoBlocked` increments. Anomaly/checkpoint
418
+ delivery is grouped per repo and only goes to that repo's queen; no match stays
419
+ pending. Repositories without a queen are unmanaged and never dispatch. Event writers
420
+ validate the absolute repo path and reject symlink escapes.
395
421
  ### 8.6.2 Queen tool boundary
396
422
 
397
423
  DSH's `ctx.tools.guard` lets a plugin veto a tool call after pre-execute policy and
package/docs/DESIGN.md CHANGED
@@ -43,14 +43,21 @@ Response:
43
43
  "repoRoleConcurrency": {},
44
44
  "defaultRoleConcurrency": 5,
45
45
  "capacityRetryMs": 2000,
46
+ "queens": [{ "repo": "/abs/repo", "sessionId": "queen-session-id" }],
46
47
  "queenSessionId": "queen-session-id",
47
48
  "waiting": null,
48
49
  "queenBoundaryViolations": 0,
49
50
  "lastQueenBoundaryViolation": null,
51
+ "crossRepoBlocked": 0,
52
+ "lastCrossRepoBlocked": null,
50
53
  "lastTickAt": "2026-12-04T00:00:00.000Z",
51
54
  "lastDiscoverError": null,
52
55
  "pendingAnomalies": 0,
53
56
  "pendingCheckpoints": 0,
57
+ "queenTools": ["hive_arch_review", "run_code"],
58
+ "queenToolsSessionId": "queen-session-id",
59
+ "queenToolsListedAt": "2026-12-05T09:00:00.000Z",
60
+ "queenToolsError": null,
54
61
  "repoCount": 1,
55
62
  "claimedButOrphaned": 0,
56
63
  "workerSessionIds": ["worker-session-id"],
@@ -69,6 +76,8 @@ Response:
69
76
  "consecutiveFailures": 0,
70
77
  "lastCards": 0,
71
78
  "lastResults": 0,
79
+ "queenSessionId": "queen-session-id",
80
+ "unmanaged": false,
72
81
  "waiting": null,
73
82
  "claimedButOrphaned": 0,
74
83
  "orphanRecovered": 0,
@@ -113,15 +122,21 @@ Response:
113
122
  last drain.
114
123
  - `pendingCheckpoints` — progress checkpoints queued while no live queen Session was
115
124
  available; the next patrol/queen registration flushes them.
125
+ - `queenTools` — one-shot diagnostic: the tool schema names visible to the registered
126
+ queen Agent (`ctx.tools.schemas(agent)`), plus `queenToolsSessionId`,
127
+ `queenToolsListedAt` and `queenToolsError`. Under the PTC preset the model-facing
128
+ request only exposes `run_code`; this list proves `hive_*` bindings exist inside it.
116
129
  - `repos` / `repoCount` — the repositories the supervisor currently tracks; this is the
117
130
  status-visible registry the panel renders. Runtime additions go through
118
131
  `hiveSupervisor.addRepo(repo)` (absolute path, initialized Hive repository, idempotent).
119
- - `queenSessionId` — the queen conversation registered by the panel **or detected by
120
- the queen tool guard** when an ordinary initialized-repo Session calls a subagent
121
- tool; agents are parented to that Session while its Agent is live. `waiting` is
122
- `"no-queen-session"` until the registration arrives (startup-order hint, not an
123
- error); the registration is only replaced by a new registration. Status workers and
124
- run records carry `parentSource: "queen"` when the registered Session parented them.
132
+ - `queens` — the repo → queen Session mapping (`[{ repo, sessionId }]`, latest
133
+ registration per repo). Workers are parented only to the queen of their own
134
+ repository; `queenSessionId`/`waiting` are a single-queen compatibility view and the
135
+ global id is `null` when several queens are registered.
136
+ - `crossRepoBlocked` / `lastCrossRepoBlocked` — mechanical rejections of a queen hive_*
137
+ call whose `repo` differed from her cwd (exact error: `女王只能操作自己所在的仓库`).
138
+ - Per-repository `queenSessionId` and `unmanaged` — a repo without a matching queen is
139
+ `unmanaged: true`; it is never dispatched to and receives no notification.
125
140
  - `queenBoundaryViolations` — how many direct `subagent`/`subagent_fork`/
126
141
  `subagent_claude_code` calls from the queen Session the tool guard has vetoed;
127
142
  `lastQueenBoundaryViolation` is `{ tool, sessionId, at, repo }` for the most recent.
@@ -186,7 +201,9 @@ required; an uninitialized path is rejected), so a repo outside `config.repos` a
186
201
  startup-order hint, not an error. While registered, its live Agent is the parent;
187
202
  if it cannot be resolved the round falls back to `parentSession` / the first live
188
203
  Agent, and defers with `hive/no-parent-agent` when no Agent is live.
189
- - Returns `{ ok: true, op: "queen", queenSessionId, waiting: null, repos: ... }`.
204
+ - Body `{ sessionId, repo }` (repo is required when several repositories are
205
+ configured; a single-repo deployment may omit it). Returns
206
+ `{ ok: true, op: "queen", queens, queenSessionId, waiting: null, repos: ... }`.
190
207
  - Missing `sessionId` -> `400` `hive/missing-session-id`; non-POST -> `405`.
191
208
  ## 3. Per-repository limits
192
209
 
@@ -346,6 +363,54 @@ queen Session the checkpoint is kept in the controller's pending list (status
346
363
  `pendingCheckpoints`) and flushed by the next patrol or queen registration; it never
347
364
  falls through to an anomaly digest.
348
365
 
366
+ ### Tool visibility diagnostic and host fallback
367
+
368
+ Under the PTC preset the model-facing request declares only `run_code`; the plugin's
369
+ `hive_*` tools are still registered globally by `apply()` and are visible to the agent
370
+ as schemas inside `run_code` (`tool/ptc-dispatch-start` events for `hive_arch_review`
371
+ prove this on the live queen session). The 1.0.11 queen saw `run_code` denied by an
372
+ earlier version of the boundary guard and concluded that no tools existed; 1.0.12
373
+ allows `run_code`, and its nested `write`/`bash` calls remain vetoed. No per-agent
374
+ registration path change is needed for a correctly mounted plugin.
375
+
376
+ To make this observable, the plugin lists `ctx.tools.schemas(queenAgent)` once per
377
+ registered queen Session, logs the names, and exposes them as `queenTools` /
378
+ `queenToolsSessionId` / `queenToolsListedAt` / `queenToolsError` in status. If the
379
+ agent is not live yet, the patrol retries the listing; the log line is
380
+ `queen visible tools (<n>): ...`.
381
+
382
+ If a queen Session genuinely cannot reach the tool, the host has a tool-independent
383
+ fallback: `hiveSupervisor.recordArchReview(repo, { card, verdict, findings, summary })`
384
+ writes the same durable `arch_review` event through the shared host writer. The
385
+ `hive_events` tool remains read-only and can verify the event; a host/panel caller can
386
+ also invoke the service method directly.
387
+
388
+ ### Repository isolation (hard, mechanical)
389
+
390
+ Every layer is scoped by repository; the model is never trusted for this:
391
+
392
+ 1. **Delivery**: anomalies are grouped per repo and each digest/checkpoint is delivered
393
+ only through that repo's queen (`repo → sessionId`); no matching queen queues the
394
+ entry as pending. A notifier can never fall back to another repo's Session.
395
+ 2. **Tools**: every `hive_*` tool with a `repo` parameter is wrapped; for a queen Session
396
+ the repo must resolve to the Session cwd (omitted means cwd), otherwise the call
397
+ fails before the body with `女王只能操作自己所在的仓库` and increments
398
+ `crossRepoBlocked`. This covers `hive_tasks`, `hive_intervene`,
399
+ `hive_arch_review`, `hive_board`, `hive_events`, `hive_run_round`, etc.
400
+ 3. **Dispatch**: `#runEntry` looks up `queenFor(repo)`; repositories without one are
401
+ `unmanaged` and never dispatch. The round runner passes the repo to the parent
402
+ provider, so a worker's parent is that repo's queen agent.
403
+ 4. **Concurrency**: pause and role limits are per repository; pausing repo A does not
404
+ stop repo B.
405
+ 5. **Status**: `queens` is the mapping, each repo carries `queenSessionId`/`unmanaged`
406
+ and its own `workers`; there is no global worker/queen aggregate that could be read
407
+ as cross-repo ownership.
408
+ 6. **Events**: writers append only under `<repo>/.hive/events.jsonl`; the repo must be an
409
+ absolute path, and the resolved log path is checked after symlink resolution so a
410
+ `.hive` symlink cannot redirect the append outside the repository.
411
+ 7. **Recovery**: orphan claims are recovered per repository, restricted to this
412
+ runner's identity and excluding live active cards.
413
+
349
414
  ### Tool boundary: hard veto through `ctx.tools.guard`
350
415
 
351
416
  DSH does expose a plugin-side tool veto. `ToolsService.guard(guard)` registers a
package/index.js CHANGED
@@ -42,10 +42,16 @@ import { createHiveRunnerRoute } from './lib/http.js';
42
42
  import { RepoLimits } from './lib/limits.js';
43
43
  import { createAnomalyFeed } from './lib/anomalies.js';
44
44
  import { createCheckpointController } from './lib/checkpoint.js';
45
- import { createQueenNotifier, deliverToSession } from './lib/notify.js';
45
+ import { createQueenNotifier, deliverToSession, resolveAgent } from './lib/notify.js';
46
46
  import { createPatrol } from './lib/patrol.js';
47
47
  import { drainQueue } from './lib/queue.js';
48
- import { createQueenBoundaryGuard, recordQueenBoundaryViolation as recordQueenBoundaryAttempt } from './lib/queen-boundary.js';
48
+ import {
49
+ createQueenBoundaryGuard,
50
+ hasQueenRole,
51
+ isQueenSuppressed,
52
+ recordQueenBoundaryViolation as recordQueenBoundaryAttempt,
53
+ } from './lib/queen-boundary.js';
54
+ import { createQueenHiveScopeEnforcer } from './lib/queen-scope.js';
49
55
  import { createRoundRunner } from './lib/round.js';
50
56
  import { readRunRecord } from './lib/runs.js';
51
57
  import { HiveSupervisor } from './lib/supervisor.js';
@@ -101,19 +107,23 @@ export function apply(ctx, config = {}) {
101
107
  if (typeof write === 'function') write.call(console, '[hive-runner]', ...args);
102
108
  else console.warn('[hive-runner]', ...args);
103
109
  };
104
- // The panel registers the queen conversation here (setQueenSession, also via
105
- // POST ?op=queen). Every worker is parented to exactly that Session; before
106
- // registration the supervisor does not dispatch at all.
107
- const queenSession = { sessionId: null };
110
+ // The panel registers one queen per repository (setQueenSession(sessionId, repo),
111
+ // also via POST ?op=queen). Workers are parented only to that repo's queen; a
112
+ // repository with no registered queen is unmanaged and never dispatches.
113
+ // One-shot diagnostic: schema names visible to the queen agent (under PTC the
114
+ // model sees only run_code, but tools.hive_* exist inside run_code).
115
+ const queenTools = { names: [], sessionId: null, listedAt: null, error: null };
108
116
  /** Queen boundary violations observed by the tool guard (status observability). */
109
117
  const queenBoundary = { count: 0, last: null };
118
+ /** Mechanical cross-repo rejections of queen hive_* calls. */
119
+ const crossRepoBlocked = { count: 0, last: null };
110
120
  let parentProviderImpl;
111
121
  const runner = createRoundRunner({
112
122
  ctx,
113
123
  config: resolved,
114
124
  commands,
115
125
  limitFor: (repo, role) => limits.limitFor(repo, role),
116
- parentProvider: (explicit) => parentProviderImpl(explicit),
126
+ parentProvider: (explicit, repo) => parentProviderImpl(explicit, repo),
117
127
  onAnomaly: (event) => recordAnomaly(event),
118
128
  // A finished worker or a settled card asks for a near-real-time checkpoint
119
129
  // check instead of waiting for the next patrol tick.
@@ -124,8 +134,10 @@ export function apply(ctx, config = {}) {
124
134
  },
125
135
  log,
126
136
  });
127
- parentProviderImpl = async (explicit) => {
128
- const sessionId = queenSession.sessionId;
137
+ parentProviderImpl = async (explicit, repo) => {
138
+ const sessionId = typeof repo === 'string' && repo !== ''
139
+ ? supervisor.queenFor(repo)
140
+ : (supervisor.queens()[0]?.sessionId ?? null);
129
141
  const agent = sessionId === null ? undefined : ctx.get('agents')?.get?.(sessionId);
130
142
  return { agent, source: 'queen', sessionId };
131
143
  };
@@ -190,20 +202,55 @@ export function apply(ctx, config = {}) {
190
202
  /** Idempotently register a cwd-recognized queen so the panel can show it. */
191
203
  function registerDetectedQueen(sessionId, cwd) {
192
204
  try {
193
- if (supervisor.queenSession.sessionId === sessionId) return;
194
- supervisor.setQueenSession(sessionId);
205
+ if (supervisor.queenFor(cwd) === sessionId) return;
206
+ supervisor.setQueenSession(sessionId, cwd);
195
207
  log('info', 'auto-registered initialized queen session', sessionId, 'cwd', cwd);
196
208
  } catch (error) {
197
209
  log('warn', 'auto-registering detected queen failed', error);
198
210
  }
199
211
  }
200
212
 
213
+ /**
214
+ * One-shot diagnostic: list the tool schemas the queen agent actually sees.
215
+ * Under the PTC preset the model-facing request only exposes run_code; this
216
+ * listing proves whether hive_* definitions are bound inside run_code.
217
+ * Logged once per registered queen Session and exposed in status.queenTools.
218
+ * @param {string} sessionId
219
+ */
220
+ function inspectQueenTools(sessionId) {
221
+ if (typeof sessionId !== 'string' || sessionId === '') return;
222
+ if (queenTools.sessionId === sessionId && queenTools.listedAt !== null) return;
223
+ let agent;
224
+ try {
225
+ agent = ctx.get('agents')?.get?.(sessionId);
226
+ } catch (error) {
227
+ queenTools.error = 'queen-agent-lookup-failed';
228
+ log('warn', 'queen tool listing: agent lookup failed', error);
229
+ return;
230
+ }
231
+ if (agent === undefined) {
232
+ queenTools.error = 'queen-agent-not-live';
233
+ return;
234
+ }
235
+ try {
236
+ const names = ctx.tools.schemas(agent).map((tool) => tool.name).sort();
237
+ queenTools.names = names;
238
+ queenTools.sessionId = sessionId;
239
+ queenTools.listedAt = new Date().toISOString();
240
+ queenTools.error = null;
241
+ log('info', 'queen visible tools (' + names.length + '): ' + names.join(', '));
242
+ } catch (error) {
243
+ queenTools.error = 'schema-listing-failed: ' + (error instanceof Error ? error.message : String(error));
244
+ log('warn', 'queen tool listing failed', error);
245
+ }
246
+ }
201
247
  // DSH tools.guard is evaluated after pre-execute policy/approval and before a
202
248
  // tool body; returning a denial makes the call fail without executing it.
203
249
  // Recognition is registration OR an ordinary initialized-repo Session; a
204
250
  // /queen off command event suppresses both paths.
205
251
  ctx.effect(() => ctx.tools.guard(createQueenBoundaryGuard({
206
- queenSession,
252
+ isRegisteredQueen: (sessionId) => supervisor.isQueenSession(sessionId),
253
+ queenSessionIds: () => supervisor.queenSessionIds(),
207
254
  onViolation: recordQueenBoundaryViolation,
208
255
  onQueenDetected: registerDetectedQueen,
209
256
  resolveCwd: resolveQueenBoundaryCwd,
@@ -212,7 +259,11 @@ export function apply(ctx, config = {}) {
212
259
  log,
213
260
  })));
214
261
 
215
- const notifier = createQueenNotifier({ ctx, queenSession, log });
262
+ const notifier = createQueenNotifier({
263
+ ctx,
264
+ resolveSessionId: (repo) => supervisor.queenFor(repo),
265
+ log,
266
+ });
216
267
  // Done cards must carry an arch_review event; the patrol audits the board and
217
268
  // turns a missing review into an arch-review-missing anomaly.
218
269
  const archReviewAudit = createArchReviewAudit({
@@ -245,8 +296,14 @@ export function apply(ctx, config = {}) {
245
296
  runCard: runner.runCard,
246
297
  preflight: runner.preflight,
247
298
  activeRuns: (repo) => runner.activeRuns(repo),
248
- queenSession,
299
+ resolveQueenRepo: (sessionId) => {
300
+ const agent = ctx.get('agents')?.get?.(sessionId);
301
+ return resolveQueenBoundaryCwd(agent, agent?.session);
302
+ },
249
303
  queenBoundary,
304
+ queenTools: () => queenTools,
305
+ crossRepoBlocked: () => crossRepoBlocked,
306
+ archReview: (repo, review) => recordArchReviewHost(repo, review),
250
307
  readMode: (repo) => commands.mode(repo),
251
308
  onAnomaly: (event) => recordAnomaly(event),
252
309
  onGateChange: (event) => {
@@ -254,7 +311,8 @@ export function apply(ctx, config = {}) {
254
311
  void checkpoint.requestTick({ repo: event.repo }).catch((error) => log('warn', 'checkpoint gate tick failed', error));
255
312
  }
256
313
  },
257
- onQueenSession: () => {
314
+ onQueenSession: (sessionId) => {
315
+ inspectQueenTools(sessionId);
258
316
  if (patrol !== undefined) patrol.flushPending();
259
317
  if (checkpoint !== undefined) checkpoint.flushPending();
260
318
  },
@@ -285,6 +343,9 @@ export function apply(ctx, config = {}) {
285
343
  log('warn', 'arch review audit failed for ' + repo + ': ' + (error instanceof Error ? error.message : String(error)));
286
344
  }
287
345
  }
346
+ // Retry the one-shot tool listing if the panel registered before the agent
347
+ // was live (status/queenTools then contains an error until this succeeds).
348
+ for (const queen of supervisor.queens()) inspectQueenTools(queen.sessionId);
288
349
  // Progress checkpoints: drained/all-done/gate-advance/idle goals. Delivery
289
350
  // is direct; failures stay pending in the checkpoint controller.
290
351
  try {
@@ -313,6 +374,7 @@ export function apply(ctx, config = {}) {
313
374
  return { tasks, ready };
314
375
  },
315
376
  loadEvents: (repo) => readEvents(repo, { limit: 100 }),
377
+ queenForRepo: (repo) => supervisor.queenFor(repo),
316
378
  drainMs: resolved.checkpointDrainMs,
317
379
  idleMs: resolved.checkpointIdleMs,
318
380
  log,
@@ -351,6 +413,22 @@ export function apply(ctx, config = {}) {
351
413
  );
352
414
  }
353
415
 
416
+ /**
417
+ * Mechanical red line: a queen may call hive_* only for her own cwd repository.
418
+ * Enforced before every tool body; an omitted repo defaults to the queen cwd.
419
+ */
420
+ const enforceQueenHiveScope = createQueenHiveScopeEnforcer({
421
+ isQueenSession: (sessionId) => supervisor.isQueenSession(sessionId),
422
+ resolveCwd: (agent, session) => resolveQueenBoundaryCwd(agent, session),
423
+ hasQueenRole,
424
+ isSuppressed: isQueenSuppressed,
425
+ onBlocked: (info) => {
426
+ crossRepoBlocked.count += 1;
427
+ crossRepoBlocked.last = info;
428
+ },
429
+ log,
430
+ });
431
+
354
432
  /** Register one model-facing tool whose result is rendered as one text block. */
355
433
  function registerTextTool({ name, description, parameters = {}, execute }) {
356
434
  ctx.tools.register(defineTool({
@@ -358,7 +436,7 @@ export function apply(ctx, config = {}) {
358
436
  description,
359
437
  parameters,
360
438
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
361
- execute,
439
+ execute: async (args = {}, exec = {}) => execute(enforceQueenHiveScope(name, parameters, args, exec), exec),
362
440
  }));
363
441
  }
364
442
 
@@ -383,8 +461,8 @@ export function apply(ctx, config = {}) {
383
461
  const repo = repoOf(args);
384
462
  const signal = exec?.signal;
385
463
  const session = exec?.agent?.session;
386
- if (supervisor.queenSession.sessionId === null) {
387
- throw new Error('waiting: no-queen-session — open the Hive panel and initialise the repository first');
464
+ if (supervisor.queenFor(repo) === null) {
465
+ throw new Error('waiting: no-queen-session for ' + repo + ' — open the Hive panel and initialise that repository first');
388
466
  }
389
467
  runner.preflight(repo);
390
468
  const cards = await runner.listReady(repo, { signal, session });
@@ -601,6 +679,39 @@ export function apply(ctx, config = {}) {
601
679
  },
602
680
  });
603
681
 
682
+ /**
683
+ * Shared arch-review writer used by the hive_arch_review tool and the
684
+ * host-side hiveSupervisor.recordArchReview() fallback. Appends the durable
685
+ * event; never edits the card.
686
+ * @param {string | undefined} repoArg
687
+ * @param {{ card?: string, verdict?: string, findings?: string[], summary?: string }} review
688
+ * @param {{ signal?: AbortSignal, agent?: object }} [exec]
689
+ * @returns {Promise<object>} the appended event
690
+ */
691
+ async function recordArchReviewHost(repoArg, review = {}, exec = {}) {
692
+ const repo = repoArg === undefined || repoArg === null || repoArg === ''
693
+ ? resolved.cwd
694
+ : normalizeRepoKey(String(repoArg));
695
+ if (repo !== resolved.cwd && !supervisor.hasRepo(repo)) {
696
+ throw new Error('repo ' + JSON.stringify(repo) + ' is not a configured Hive repository');
697
+ }
698
+ const cardId = typeof review.card === 'string' ? review.card.trim() : '';
699
+ if (cardId === '') throw new Error('hive_arch_review needs card');
700
+ const card = await commands.show(repo, cardId, {
701
+ signal: exec?.signal,
702
+ session: exec?.agent?.session,
703
+ });
704
+ if (card === null || card === undefined) throw new Error('no such card: ' + cardId);
705
+ if (card.state !== 'done') {
706
+ throw new Error('architecture review runs after acceptance: card ' + card.id + ' is ' + card.state + ', not done');
707
+ }
708
+ return appendArchReview(repo, {
709
+ card: card.id,
710
+ verdict: review.verdict,
711
+ findings: review.findings,
712
+ summary: review.summary,
713
+ });
714
+ }
604
715
  registerTextTool({
605
716
  name: 'hive_arch_review',
606
717
  description:
@@ -620,22 +731,7 @@ export function apply(ctx, config = {}) {
620
731
  summary: { type: 'string', description: 'One-line summary of the review.' },
621
732
  },
622
733
  execute: async (args = {}, exec) => {
623
- const repo = repoOf(args);
624
- if (typeof args.card !== 'string' || args.card.trim() === '') throw new Error('hive_arch_review needs card');
625
- const card = await commands.show(repo, args.card.trim(), {
626
- signal: exec?.signal,
627
- session: exec?.agent?.session,
628
- });
629
- if (card === null || card === undefined) throw new Error('no such card: ' + args.card);
630
- if (card.state !== 'done') {
631
- throw new Error('architecture review runs after acceptance: card ' + card.id + ' is ' + card.state + ', not done');
632
- }
633
- const event = appendArchReview(repo, {
634
- card: card.id,
635
- verdict: args.verdict,
636
- findings: args.findings,
637
- summary: args.summary,
638
- });
734
+ const event = await recordArchReviewHost(args.repo, args, exec);
639
735
  return jsonText({ ok: true, event });
640
736
  },
641
737
  });
@@ -892,6 +988,11 @@ export function apply(ctx, config = {}) {
892
988
  if (typeof args.sessionId !== 'string' || args.sessionId === '') {
893
989
  throw new Error('hive_intervene guide needs sessionId (see hive_tasks show lastRun.sessionId)');
894
990
  }
991
+ const targetAgent = resolveAgent(ctx, args.sessionId);
992
+ const targetCwd = resolveQueenBoundaryCwd(targetAgent, targetAgent?.session);
993
+ if (typeof targetCwd !== 'string' || normalizeRepoKey(targetCwd) !== normalizeRepoKey(repo)) {
994
+ throw new Error('女王只能操作自己所在的仓库');
995
+ }
895
996
  delivery = deliverToSession({ ctx }, args.sessionId, '[hive queen guidance]' + NL + NL + args.reason, { prefer: 'steer' });
896
997
  if (delivery.delivered !== true) {
897
998
  throw new Error('cannot deliver guidance: ' + String(delivery.reason ?? 'unknown'));
package/lib/checkpoint.js CHANGED
@@ -129,6 +129,7 @@ export function renderCheckpoint({ repo, stats, gate, recentEvents, trigger, at,
129
129
  * eventWindowMs?: number,
130
130
  * cacheMs?: number,
131
131
  * errorBackoffMs?: number,
132
+ * queenForRepo?: (repo: string) => string | null,
132
133
  * log?: (level: string, ...args: unknown[]) => void,
133
134
  * }} options
134
135
  */
@@ -145,6 +146,7 @@ export function createCheckpointController({
145
146
  eventWindowMs = DEFAULT_CHECKPOINT_EVENT_WINDOW_MS,
146
147
  cacheMs = DEFAULT_CHECKPOINT_CACHE_MS,
147
148
  errorBackoffMs = DEFAULT_CHECKPOINT_ERROR_BACKOFF_MS,
149
+ queenForRepo,
148
150
  log = () => {},
149
151
  } = {}) {
150
152
  if (typeof loadBoard !== 'function') throw new TypeError('createCheckpointController: loadBoard is required');
@@ -176,7 +178,7 @@ export function createCheckpointController({
176
178
  return { delivered: false, reason: 'no-notifier' };
177
179
  }
178
180
  try {
179
- const result = notifier.deliver(entry.body);
181
+ const result = notifier.deliver(entry.body, entry.repo);
180
182
  if (result !== undefined && result.delivered === true) {
181
183
  return { delivered: true, via: result.via ?? null };
182
184
  }
@@ -300,7 +302,14 @@ export function createCheckpointController({
300
302
  startup: !firstCheckpointCreated,
301
303
  });
302
304
  const entry = { repo, body, signature, at, trigger: reasons.join('+') };
303
- const delivery = deliver(entry);
305
+ // Hard repo isolation: a checkpoint may only go to the queen registered
306
+ // for this repository. No match -> pending, never another repo's queen.
307
+ const targetQueen = typeof queenForRepo === 'function' ? queenForRepo(repo) : undefined;
308
+ const unmatched = typeof queenForRepo === 'function'
309
+ && (typeof targetQueen !== 'string' || targetQueen === '');
310
+ const delivery = unmatched
311
+ ? { delivered: false, reason: 'no-queen-for-repo' }
312
+ : deliver(entry);
304
313
  state.lastSignature = signature;
305
314
  state.lastCheckpointAt = at;
306
315
  state.hasCheckpoint = true;
@@ -323,6 +332,10 @@ export function createCheckpointController({
323
332
  function flushPending() {
324
333
  let delivered = 0;
325
334
  for (const entry of [...pending]) {
335
+ if (typeof queenForRepo === 'function') {
336
+ const target = queenForRepo(entry.repo);
337
+ if (typeof target !== 'string' || target === '') continue;
338
+ }
326
339
  const result = deliver(entry);
327
340
  if (result.delivered) {
328
341
  pending.splice(pending.indexOf(entry), 1);
package/lib/events.js CHANGED
@@ -37,6 +37,8 @@ function text(value, max) {
37
37
  /** Resolve the event log path, rejecting a repo that is not a usable directory path. */
38
38
  export function eventsPath(repo) {
39
39
  if (typeof repo !== 'string' || repo.trim() === '') throw new TypeError('eventsPath: repo is required');
40
+ if (repo.includes('\u0000')) throw new TypeError('eventsPath: repo must not contain NUL bytes');
41
+ if (!path.isAbsolute(repo.trim())) throw new TypeError('eventsPath: repo must be an absolute path');
40
42
  return path.resolve(repo, EVENTS_FILE);
41
43
  }
42
44
 
@@ -71,8 +73,14 @@ export function appendEvent(repo, event) {
71
73
  throw new TypeError('appendEvent: event must be an object');
72
74
  }
73
75
  const file = eventsPath(repo);
74
- fs.mkdirSync(path.dirname(file), { recursive: true });
75
- fs.appendFileSync(file, JSON.stringify(event) + '\n');
76
+ // Resolve symlinks before writing: a `.hive` symlink must never redirect the
77
+ // append outside the repository that owns the event log.
78
+ const root = fs.realpathSync(repo);
79
+ const dir = path.join(root, path.dirname(EVENTS_FILE));
80
+ fs.mkdirSync(dir, { recursive: true });
81
+ const realDir = fs.realpathSync(dir);
82
+ if (realDir !== dir) throw new Error('event path escapes repository: ' + repo);
83
+ fs.appendFileSync(path.join(realDir, path.basename(file)), JSON.stringify(event) + '\n');
76
84
  return event;
77
85
  }
78
86
 
package/lib/http.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * POST /api/hive-runner?op=pause { repo }
12
12
  * POST /api/hive-runner?op=resume { repo }
13
13
  * POST /api/hive-runner?op=limits { repo, roleLimits: { role: number } }
14
- * POST /api/hive-runner?op=queen { sessionId }
14
+ * POST /api/hive-runner?op=queen { sessionId, repo }
15
15
  */
16
16
  import { normalizeRepoKey } from './config.js';
17
17
  import { UnknownRepoError } from './supervisor.js';
@@ -117,8 +117,25 @@ export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
117
117
  if (typeof sessionId !== 'string' || sessionId.trim() === '') {
118
118
  return failure(op, 'hive/missing-session-id', 'sessionId is required (JSON body field)', 400);
119
119
  }
120
+ const explicitRepo = typeof payload.repo === 'string'
121
+ ? payload.repo
122
+ : url.searchParams.get('repo');
123
+ let repo = typeof explicitRepo === 'string' && explicitRepo.trim() !== '' ? explicitRepo.trim() : null;
124
+ if (repo === null) {
125
+ // Single-repository deployments keep the old payload shape; multi-repo
126
+ // callers must name the repository they are registering the queen for.
127
+ try {
128
+ const status = supervisor.status();
129
+ if (Array.isArray(status?.repos) && status.repos.length === 1) repo = status.repos[0].repo;
130
+ } catch {
131
+ repo = null;
132
+ }
133
+ }
134
+ if (repo === null) {
135
+ return failure(op, 'hive/missing-repo', 'repo is required with sessionId when more than one repository is configured', 400);
136
+ }
120
137
  try {
121
- return json({ ok: true, op: 'queen', ...supervisor.setQueenSession(sessionId) });
138
+ return json({ ok: true, op: 'queen', ...supervisor.setQueenSession(sessionId, repo) });
122
139
  } catch (error) {
123
140
  return failure(op, 'hive/invalid-session-id', error instanceof Error ? error.message : String(error), 400);
124
141
  }
package/lib/notify.js CHANGED
@@ -102,17 +102,28 @@ export function deliverToSession({ ctx } = {}, sessionId, body, delivery = {}) {
102
102
 
103
103
  /**
104
104
  * Create the delivery facade.
105
- * @param {{ ctx: object, queenSession: { sessionId: string|null }, log?: (level: string, ...args: unknown[]) => void }} options
106
- * @returns {{ deliver: (body: string) => { delivered: boolean, via?: string, reason?: string }, hasLiveQueen: () => boolean }}
105
+ * @param {{ ctx: object, queenSession?: { sessionId: string|null }, resolveSessionId?: (repo: string|undefined) => string|null, log?: (level: string, ...args: unknown[]) => void }} options
106
+ * @returns {{ deliver: (body: string, repo?: string) => { delivered: boolean, via?: string, reason?: string }, hasLiveQueen: (repo?: string) => boolean }}
107
107
  */
108
- export function createQueenNotifier({ ctx, queenSession, log = () => {} } = {}) {
109
- const target = () => resolveQueenAgent(ctx, queenSession);
108
+ export function createQueenNotifier({ ctx, queenSession, resolveSessionId, log = () => {} } = {}) {
109
+ function sessionFor(repo) {
110
+ if (typeof resolveSessionId === 'function') {
111
+ const resolved = resolveSessionId(repo);
112
+ return typeof resolved === 'string' && resolved !== '' ? resolved : null;
113
+ }
114
+ const legacy = queenSession?.sessionId;
115
+ return typeof legacy === 'string' && legacy !== '' ? legacy : null;
116
+ }
117
+ const target = (repo) => {
118
+ const sessionId = sessionFor(repo);
119
+ return sessionId === null ? undefined : resolveAgent(ctx, sessionId);
120
+ };
110
121
 
111
- function deliver(body) {
122
+ function deliver(body, repo) {
112
123
  if (typeof body !== 'string' || body.trim() === '') {
113
124
  return { delivered: false, reason: 'empty-digest' };
114
125
  }
115
- const agent = target();
126
+ const agent = target(repo);
116
127
  if (agent === undefined) return { delivered: false, reason: 'no-live-queen-session' };
117
128
  const message = createQueenMessage(body);
118
129
  try {
@@ -138,7 +149,7 @@ export function createQueenNotifier({ ctx, queenSession, log = () => {} } = {})
138
149
 
139
150
  return {
140
151
  deliver,
141
- hasLiveQueen: () => target() !== undefined,
152
+ hasLiveQueen: (repo) => target(repo) !== undefined,
142
153
  };
143
154
  }
144
155
 
package/lib/patrol.js CHANGED
@@ -76,26 +76,56 @@ export function createPatrol(options = {}) {
76
76
  if (notifier === undefined || typeof notifier.deliver !== 'function') {
77
77
  return { delivered: false, count: pending.length, reason: 'no-notifier' };
78
78
  }
79
- let result;
80
- try {
81
- result = notifier.deliver(renderDigest(pending));
82
- } catch (error) {
83
- log('warn', 'queen digest delivery failed', error);
84
- return { delivered: false, count: pending.length, reason: 'delivery-threw' };
79
+ // Hard repo isolation: group by repository and deliver each digest only to
80
+ // that repo's queen. Entries without a repository stay pending; a digest
81
+ // never reaches a queen registered for another repository.
82
+ const groups = new Map();
83
+ for (const entry of pending) {
84
+ const repo = typeof entry.repo === 'string' && entry.repo !== '' ? entry.repo : '';
85
+ if (repo === '') continue;
86
+ if (!groups.has(repo)) groups.set(repo, []);
87
+ groups.get(repo).push(entry);
85
88
  }
86
- if (result !== undefined && result.delivered === true) {
89
+ let deliveredCount = 0;
90
+ let via = null;
91
+ let lastReason = null;
92
+ for (const [repo, entries] of groups) {
93
+ let result;
87
94
  try {
88
- feed.markDelivered(pending.map((entry) => entry.id));
95
+ result = notifier.deliver(renderDigest(entries), repo);
89
96
  } catch (error) {
90
- log('warn', 'marking anomalies delivered failed', error);
97
+ log('warn', 'queen digest delivery failed', error);
98
+ lastReason = 'delivery-threw';
99
+ continue;
100
+ }
101
+ if (result !== undefined && result.delivered === true) {
102
+ try {
103
+ feed.markDelivered(entries.map((entry) => entry.id));
104
+ } catch (error) {
105
+ log('warn', 'marking anomalies delivered failed', error);
106
+ }
107
+ deliveredCount += entries.length;
108
+ via = result.via ?? via;
109
+ } else {
110
+ lastReason = result?.reason ?? 'not-delivered';
91
111
  }
92
- return { delivered: true, count: pending.length, via: result.via ?? null, reason: null };
112
+ }
113
+ let stillPending = 0;
114
+ try {
115
+ const rest = feed.pending();
116
+ stillPending = Array.isArray(rest) ? rest.length : 0;
117
+ } catch {
118
+ stillPending = pending.length - deliveredCount;
119
+ }
120
+ if (deliveredCount > 0) {
121
+ return { delivered: true, count: deliveredCount, pending: stillPending, via, reason: null };
93
122
  }
94
123
  return {
95
124
  delivered: false,
96
- count: pending.length,
125
+ count: deliveredCount,
126
+ pending: stillPending,
97
127
  via: null,
98
- reason: result?.reason ?? 'not-delivered',
128
+ reason: lastReason ?? 'no-live-queen-session',
99
129
  };
100
130
  }
101
131
 
@@ -189,7 +189,7 @@ export function isQueenSuppressed(session) {
189
189
  * covers the window before a provider-reported child id reaches it and worker
190
190
  * Sessions that survive a plugin restart.
191
191
  * @param {object} session
192
- * @param {string | null} [queenSessionId]
192
+ * @param {string | string[] | null} [queenSessionId]
193
193
  * @returns {boolean}
194
194
  */
195
195
  export function isWorkerSession(session, queenSessionId) {
@@ -197,9 +197,8 @@ export function isWorkerSession(session, queenSessionId) {
197
197
  if (header === null || typeof header !== 'object') return false;
198
198
  if (header.origin === 'subagent') return true;
199
199
  if (Number.isInteger(header.delegationDepth) && header.delegationDepth > 0) return true;
200
- return typeof queenSessionId === 'string'
201
- && queenSessionId !== ''
202
- && header.parentSession === queenSessionId;
200
+ const ids = Array.isArray(queenSessionId) ? queenSessionId : [queenSessionId];
201
+ return ids.some((id) => typeof id === 'string' && id !== '' && header.parentSession === id);
203
202
  }
204
203
 
205
204
  /** Structured error identity recorded on the failed tool result. */
@@ -211,7 +210,9 @@ export const QUEEN_BOUNDARY_ERROR = Object.freeze({
211
210
  /**
212
211
  * Build the guard registered through `ctx.tools.guard`.
213
212
  * @param {{
214
- * queenSession: { sessionId: string | null },
213
+ * queenSession?: { sessionId: string | null },
214
+ * isRegisteredQueen?: (sessionId: string) => boolean,
215
+ * queenSessionIds?: () => string[],
215
216
  * onViolation?: (violation: object) => void,
216
217
  * onQueenDetected?: (sessionId: string, cwd: string) => void,
217
218
  * resolveCwd?: (agent: object, session: object) => string | null,
@@ -224,6 +225,8 @@ export const QUEEN_BOUNDARY_ERROR = Object.freeze({
224
225
  */
225
226
  export function createQueenBoundaryGuard({
226
227
  queenSession,
228
+ isRegisteredQueen,
229
+ queenSessionIds,
227
230
  onViolation,
228
231
  onQueenDetected,
229
232
  resolveCwd,
@@ -239,7 +242,23 @@ export function createQueenBoundaryGuard({
239
242
  if (typeof sessionId !== 'string' || sessionId === '') return undefined;
240
243
 
241
244
  const queenSessionId = queenSession?.sessionId;
242
- const registered = typeof queenSessionId === 'string' && queenSessionId !== '' && sessionId === queenSessionId;
245
+ let registered = typeof queenSessionId === 'string' && queenSessionId !== '' && sessionId === queenSessionId;
246
+ if (!registered && typeof isRegisteredQueen === 'function') {
247
+ try {
248
+ registered = isRegisteredQueen(sessionId) === true;
249
+ } catch {
250
+ registered = false;
251
+ }
252
+ }
253
+ let knownQueens = queenSessionId;
254
+ if (typeof queenSessionIds === 'function') {
255
+ try {
256
+ const list = queenSessionIds();
257
+ if (Array.isArray(list)) knownQueens = list;
258
+ } catch {
259
+ // Keep the legacy single id.
260
+ }
261
+ }
243
262
  // Workers are never the queen: the supervisor's activeRuns registry is
244
263
  // authoritative (including a child id reserved before activation), and
245
264
  // the Session header covers the provider/restart window. A worker gets
@@ -252,7 +271,7 @@ export function createQueenBoundaryGuard({
252
271
  } catch {
253
272
  worker = false;
254
273
  }
255
- if (!worker) worker = isWorkerSession(session, queenSessionId);
274
+ if (!worker) worker = isWorkerSession(session, knownQueens);
256
275
  if (worker) return undefined;
257
276
 
258
277
  const toolClass = queenBoundaryToolClass(exec.name);
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Mechanical repository scope for queen hive_* calls.
3
+ *
4
+ * A queen Session may only operate on the repository it lives in: the explicit
5
+ * `repo` argument must resolve to its cwd, and an omitted repo defaults to cwd.
6
+ * This is enforced in the registered tool wrapper before any tool body runs.
7
+ *
8
+ * @module dsh-hive-runner/queen-scope
9
+ */
10
+ import path from 'node:path';
11
+
12
+ /** Exact rejection text (red-line requirement). */
13
+ export const QUEEN_REPO_SCOPE_MESSAGE = '女王只能操作自己所在的仓库';
14
+
15
+ /**
16
+ * @param {{
17
+ * isQueen: boolean,
18
+ * cwd?: string | null,
19
+ * repo?: string | null,
20
+ * hasRepoParam?: boolean,
21
+ * }} options
22
+ * @returns {{ allowed: boolean, repo: string | null, message?: string }}
23
+ */
24
+ export function enforceQueenRepoScope({ isQueen = false, cwd = null, repo = null, hasRepoParam = true } = {}) {
25
+ if (isQueen !== true || hasRepoParam !== true) return { allowed: true, repo: repo ?? cwd ?? null };
26
+ if (typeof cwd !== 'string' || cwd.trim() === '') {
27
+ return { allowed: false, repo: null, message: QUEEN_REPO_SCOPE_MESSAGE };
28
+ }
29
+ const own = path.resolve(cwd);
30
+ const requested = typeof repo === 'string' && repo.trim() !== '' ? path.resolve(repo) : own;
31
+ if (requested !== own) return { allowed: false, repo: requested, message: QUEEN_REPO_SCOPE_MESSAGE };
32
+ return { allowed: true, repo: own };
33
+ }
34
+
35
+ export default enforceQueenRepoScope;
36
+ /**
37
+ * Build the mechanical hive_* wrapper used by the plugin. Queen Sessions may
38
+ * only pass a repo equal to their cwd; omitted repo defaults to cwd.
39
+ * @param {{
40
+ * isQueenSession?: (sessionId: string) => boolean,
41
+ * resolveCwd?: (agent: object | undefined, session: object | undefined) => string | null,
42
+ * hasQueenRole?: (cwd: string) => boolean,
43
+ * isSuppressed?: (session: object) => boolean,
44
+ * onBlocked?: (info: object) => void,
45
+ * log?: (level: string, ...args: unknown[]) => void,
46
+ * }} hooks
47
+ * @returns {(name: string, parameters: object, args: object, exec?: object) => object}
48
+ */
49
+ export function createQueenHiveScopeEnforcer({
50
+ isQueenSession,
51
+ resolveCwd,
52
+ hasQueenRole,
53
+ isSuppressed,
54
+ onBlocked,
55
+ log = () => {},
56
+ } = {}) {
57
+ return function enforce(name, parameters, args, exec = {}) {
58
+ if (typeof name !== 'string' || !name.startsWith('hive_')) return args;
59
+ const session = exec?.agent?.session;
60
+ const sessionId = session?.id;
61
+ if (typeof sessionId !== 'string' || sessionId === '') return args;
62
+ let cwd = null;
63
+ try {
64
+ cwd = typeof resolveCwd === 'function' ? resolveCwd(exec.agent, session) : null;
65
+ } catch {
66
+ cwd = null;
67
+ }
68
+ let queen = false;
69
+ try {
70
+ queen = typeof isQueenSession === 'function' && isQueenSession(sessionId) === true;
71
+ } catch {
72
+ queen = false;
73
+ }
74
+ if (!queen && typeof hasQueenRole === 'function' && typeof cwd === 'string' && cwd !== '') {
75
+ try {
76
+ queen = hasQueenRole(cwd) === true;
77
+ } catch {
78
+ queen = false;
79
+ }
80
+ }
81
+ if (!queen) return args;
82
+ try {
83
+ if (typeof isSuppressed === 'function' && isSuppressed(session) === true) return args;
84
+ } catch {
85
+ // Conservative: enforce scope.
86
+ }
87
+ const hasRepoParam = parameters !== null && typeof parameters === 'object'
88
+ && Object.prototype.hasOwnProperty.call(parameters, 'repo');
89
+ if (!hasRepoParam) return args;
90
+ const repo = typeof args?.repo === 'string' ? args.repo : null;
91
+ const scope = enforceQueenRepoScope({ isQueen: true, cwd, repo, hasRepoParam: true });
92
+ if (!scope.allowed) {
93
+ try {
94
+ onBlocked?.({ tool: name, repo, cwd, at: new Date().toISOString() });
95
+ } catch {
96
+ // Counting must never change the veto.
97
+ }
98
+ log('warn', 'queen cross-repository tool call blocked:', name, 'cwd', cwd, 'repo', repo);
99
+ throw new Error(QUEEN_REPO_SCOPE_MESSAGE);
100
+ }
101
+ return repo === null ? { ...(args ?? {}), repo: scope.repo } : args;
102
+ };
103
+ }
package/lib/round.js CHANGED
@@ -308,9 +308,9 @@ export function createRoundRunner({
308
308
  * @param {object} [explicit] caller agent (tool-triggered rounds)
309
309
  * @returns {Promise<{ agent: object, source: string, sessionId?: string }>}
310
310
  */
311
- async function parentFor(explicit) {
311
+ async function parentFor(explicit, repo) {
312
312
  if (typeof parentProvider === 'function') {
313
- const provided = await parentProvider(explicit);
313
+ const provided = await parentProvider(explicit, repo);
314
314
  if (provided !== undefined && provided !== null && provided.agent !== undefined) return provided;
315
315
  }
316
316
  const agent = resolveParent(explicit);
@@ -848,7 +848,7 @@ export function createRoundRunner({
848
848
  return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
849
849
  }
850
850
  const id = card.id;
851
- const ownerInfo = await parentFor(parent);
851
+ const ownerInfo = await parentFor(parent, repo);
852
852
  const owner = ownerInfo.agent;
853
853
  let fresh = card;
854
854
  try {
package/lib/supervisor.js CHANGED
@@ -132,7 +132,8 @@ export class HiveSupervisor {
132
132
  * @param {(request: object) => Promise<object>} [options.runCard]
133
133
  * @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
134
134
  * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
135
- * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
135
+ * @param {{ sessionId: string | null }} [options.queenSession] legacy single/wildcard queen registration (tests/back-compat)
136
+ * @param {(sessionId: string) => string | null} [options.resolveQueenRepo] infer a queen's repository from its Session cwd
136
137
  * @param {(repo: string, options: object) => Promise<object>} [options.recoverOrphans] first-tick orphan claim recovery
137
138
  * @param {{ count: number, last: object | null }} [options.queenBoundary] queen boundary violation counters
138
139
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
@@ -140,6 +141,9 @@ export class HiveSupervisor {
140
141
  * @param {(event: object) => void} [options.onAnomaly] supervision event sink (queen digest)
141
142
  * @param {(event: object) => void} [options.onGateChange] gate phase/release-readiness change sink
142
143
  * @param {(sessionId: string) => void} [options.onQueenSession] called after a queen Session registers
144
+ * @param {() => { names?: string[], sessionId?: string | null, listedAt?: string | null, error?: string | null }} [options.queenTools] diagnostic: tools visible to the queen agent
145
+ * @param {(repo: string, review: object) => Promise<object>} [options.archReview] host-side arch_review fallback
146
+ * @param {() => { count?: number, last?: object | null }} [options.crossRepoBlocked] queen cross-repo rejection counter
143
147
  * @param {() => number} [options.pendingAnomalies] undelivered queen anomalies reported in status
144
148
  * @param {() => number} [options.pendingCheckpoints] undelivered progress checkpoints reported in status
145
149
  * @param {Console} [options.logger]
@@ -171,8 +175,13 @@ export class HiveSupervisor {
171
175
  this.runCard = options.runCard;
172
176
  this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
173
177
  this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
174
- // Shared with the round runner: the Session registered by the panel when the
175
- // queen takes over. Nothing is dispatched until this is set.
178
+ // Per-repository queen registry (repo -> latest Session id). The legacy
179
+ // single `queenSession` remains a test/back-compat wildcard only when it was
180
+ // explicitly supplied; production registration must name the repository.
181
+ this.queenSessions = new Map();
182
+ this.resolveQueenRepo = typeof options.resolveQueenRepo === 'function' ? options.resolveQueenRepo : undefined;
183
+ this.legacyQueen = options.queenSession !== undefined;
184
+ this.allowLegacyWildcard = options.queenSession !== undefined;
176
185
  this.queenSession = options.queenSession ?? { sessionId: null };
177
186
  this.recoverOrphans = typeof options.recoverOrphans === 'function' ? options.recoverOrphans : undefined;
178
187
  this.queenBoundary = options.queenBoundary ?? { count: 0, last: null };
@@ -180,6 +189,9 @@ export class HiveSupervisor {
180
189
  this.onAnomaly = typeof options.onAnomaly === 'function' ? options.onAnomaly : undefined;
181
190
  this.onGateChange = typeof options.onGateChange === 'function' ? options.onGateChange : undefined;
182
191
  this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
192
+ this.queenTools = typeof options.queenTools === 'function' ? options.queenTools : undefined;
193
+ this.archReview = typeof options.archReview === 'function' ? options.archReview : undefined;
194
+ this.crossRepoBlocked = typeof options.crossRepoBlocked === 'function' ? options.crossRepoBlocked : undefined;
183
195
  this.pendingAnomalies = typeof options.pendingAnomalies === 'function' ? options.pendingAnomalies : undefined;
184
196
  this.pendingCheckpoints = typeof options.pendingCheckpoints === 'function' ? options.pendingCheckpoints : undefined;
185
197
  this.discover = options.discover;
@@ -367,25 +379,57 @@ export class HiveSupervisor {
367
379
  }
368
380
 
369
381
  /**
370
- * Register the queen Session that owns every worker. The panel calls this when
371
- * its init/queen activation succeeds; until then no card is dispatched.
382
+ * Register the queen Session that owns one repository. The panel passes the
383
+ * repository (session cwd); a one-argument call is legacy/back-compat and
384
+ * either infers the repository from the live Session or becomes a wildcard
385
+ * only when explicitly configured by tests.
372
386
  * @param {string} sessionId live DSH Session id of the queen conversation
387
+ * @param {string} [repo] repository this queen controls
373
388
  * @returns {object} supervisor status
374
389
  */
375
- setQueenSession(sessionId) {
390
+ setQueenSession(sessionId, repo) {
376
391
  if (typeof sessionId !== 'string' || sessionId.trim() === '') {
377
392
  throw new TypeError('setQueenSession: sessionId must be a non-empty string');
378
393
  }
379
- this.queenSession.sessionId = sessionId.trim();
380
- for (const entry of this.repos.values()) {
381
- entry.waiting = null;
382
- entry.nextAttemptAt = this.now();
394
+ const id = sessionId.trim();
395
+ let key = null;
396
+ if (typeof repo === 'string' && repo.trim() !== '') {
397
+ key = normalizeRepoKey(repo);
398
+ } else if (typeof this.resolveQueenRepo === 'function') {
399
+ try {
400
+ const inferred = this.resolveQueenRepo(id);
401
+ if (typeof inferred === 'string' && inferred.trim() !== '') key = normalizeRepoKey(inferred);
402
+ } catch (error) {
403
+ this.#log('warn', 'resolving queen repository failed', messageOf(error));
404
+ }
405
+ }
406
+ if (key === null && !this.allowLegacyWildcard) {
407
+ // A production registration must name a repo or have a live Session cwd;
408
+ // only an explicitly configured legacy queen (tests/back-compat) may be a
409
+ // wildcard. Never let an unresolved production queen touch every repo.
410
+ throw new TypeError('setQueenSession: repo is required (the queen agent must be live to infer cwd)');
383
411
  }
384
- this.#log('info', 'registered queen session', this.queenSession.sessionId);
385
- // Let the plugin flush anomalies accumulated while no queen was live.
412
+ this.queenSession.sessionId = id;
413
+ if (key === null) {
414
+ this.legacyQueen = true;
415
+ for (const entry of this.repos.values()) {
416
+ entry.waiting = null;
417
+ entry.nextAttemptAt = this.now();
418
+ }
419
+ } else {
420
+ this.queenSessions.set(key, id);
421
+ this.queenSession.repo = key;
422
+ const entry = this.repos.get(key);
423
+ if (entry !== undefined) {
424
+ entry.waiting = null;
425
+ entry.nextAttemptAt = this.now();
426
+ }
427
+ }
428
+ this.#log('info', 'registered queen session', id, key === null ? '(legacy wildcard)' : 'for ' + key);
429
+ // Let the plugin flush anomalies/checkpoints accumulated for this repository.
386
430
  if (this.onQueenSession !== undefined) {
387
431
  try {
388
- this.onQueenSession(this.queenSession.sessionId);
432
+ this.onQueenSession(id, key);
389
433
  } catch (error) {
390
434
  this.#log('warn', 'queen-session hook failed', messageOf(error));
391
435
  }
@@ -393,6 +437,63 @@ export class HiveSupervisor {
393
437
  return this.status();
394
438
  }
395
439
 
440
+ /** Latest queen Session for one repository (explicit map, then legacy wildcard). */
441
+ queenFor(repo) {
442
+ let key;
443
+ try {
444
+ key = normalizeRepoKey(repo);
445
+ } catch {
446
+ return null;
447
+ }
448
+ const mapped = this.queenSessions.get(key);
449
+ if (typeof mapped === 'string' && mapped !== '') return mapped;
450
+ if (this.legacyQueen) {
451
+ const legacy = this.queenSession?.sessionId;
452
+ if (typeof legacy === 'string' && legacy !== '') return legacy;
453
+ }
454
+ return null;
455
+ }
456
+
457
+ /** All mapped queens, one latest Session per repository. */
458
+ queens() {
459
+ return [...this.queenSessions.entries()]
460
+ .map(([repo, sessionId]) => ({ repo, sessionId }))
461
+ .sort((a, b) => a.repo.localeCompare(b.repo));
462
+ }
463
+
464
+ /** Whether this Session is registered for any repository. */
465
+ isQueenSession(sessionId) {
466
+ if (typeof sessionId !== 'string' || sessionId === '') return false;
467
+ if (this.legacyQueen && this.queenSession?.sessionId === sessionId) return true;
468
+ for (const id of this.queenSessions.values()) if (id === sessionId) return true;
469
+ return false;
470
+ }
471
+
472
+ /** Every registered queen Session id (map + legacy wildcard). */
473
+ queenSessionIds() {
474
+ const ids = new Set(this.queenSessions.values());
475
+ if (this.legacyQueen && typeof this.queenSession?.sessionId === 'string' && this.queenSession.sessionId !== '') {
476
+ ids.add(this.queenSession.sessionId);
477
+ }
478
+ return [...ids];
479
+ }
480
+
481
+ /**
482
+ * Host-side fallback for the queen's arch-review tool. The normal path is the
483
+ * registered hive_arch_review tool (inside run_code under PTC); this method
484
+ * lets a host/panel/CLI caller record the same event when the agent tool is
485
+ * unavailable.
486
+ * @param {string} repo
487
+ * @param {{ card: string, verdict: string, findings?: string[], summary?: string }} review
488
+ * @returns {Promise<object>}
489
+ */
490
+ async recordArchReview(repo, review) {
491
+ if (typeof this.archReview !== 'function') {
492
+ throw new Error('host arch-review fallback is not configured');
493
+ }
494
+ return this.archReview(repo, review);
495
+ }
496
+
396
497
  /**
397
498
  * Live worker Session ids across every registered repository. The panel uses
398
499
  * this to exempt worker conversations from the queen role/prompt and guard.
@@ -539,22 +640,33 @@ export class HiveSupervisor {
539
640
 
540
641
  /** Serializable supervisor + per-repository status. */
541
642
  status() {
542
- const waiting = this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
543
- ? 'no-queen-session'
544
- : null;
643
+ const queens = this.queens();
644
+ // Single-queen compatibility view; with several queens the per-repo
645
+ // `queens` list is authoritative and the global field is intentionally null.
646
+ const singleQueenId = queens.length === 1
647
+ ? queens[0].sessionId
648
+ : (queens.length === 0 && this.legacyQueen ? (this.queenSession?.sessionId ?? null) : null);
649
+ const anyQueen = queens.length > 0
650
+ || (this.legacyQueen && typeof this.queenSession?.sessionId === 'string' && this.queenSession.sessionId !== '');
651
+ const waiting = anyQueen ? null : 'no-queen-session';
545
652
  const repoSnapshots = [...this.repos.values()]
546
653
  .map((entry) => this.#snapshot(entry))
547
654
  .sort((a, b) => a.repo.localeCompare(b.repo));
548
655
  return {
549
656
  started: this.started,
550
- // The queen Session registered by the panel; every card worker is parented
551
- // to it. Until it is registered nothing is dispatched.
552
- queenSessionId: this.queenSession.sessionId ?? null,
657
+ // Per-repository queens: workers are parented only to the queen registered
658
+ // for their repository. `queenSessionId`/`waiting` remain top-level
659
+ // back-compat hints (the last registration / no queen at all).
660
+ queens,
661
+ queenSessionId: singleQueenId,
553
662
  waiting,
554
663
  // Direct subagent calls from the queen are vetoed by the tool guard; the
555
664
  // counter/last attempt is observability, not a scheduling decision.
556
665
  queenBoundaryViolations: Number.isInteger(this.queenBoundary?.count) ? this.queenBoundary.count : 0,
557
666
  lastQueenBoundaryViolation: this.queenBoundary?.last ?? null,
667
+ // Mechanical cross-repository rejections of queen hive_* calls.
668
+ crossRepoBlocked: this.#crossRepoBlockedCount(),
669
+ lastCrossRepoBlocked: this.crossRepoBlocked?.()?.last ?? null,
558
670
  intervalMs: this.intervalMs,
559
671
  idleBackoffMs: this.idleBackoffMs,
560
672
  maxConcurrentRepos: this.maxConcurrentRepos,
@@ -569,6 +681,8 @@ export class HiveSupervisor {
569
681
  // queen Session.
570
682
  pendingAnomalies: this.#pendingAnomalyCount(),
571
683
  pendingCheckpoints: this.#pendingCheckpointCount(),
684
+ // One-shot diagnostic: which tool names the registered queen agent can see.
685
+ ...this.#queenToolsStatus(),
572
686
  repoCount: this.repos.size,
573
687
  // Worker Session ids across all repositories: the panel exempts them from
574
688
  // queen-mode prompt injection and the guard exempts their tool calls.
@@ -640,14 +754,15 @@ export class HiveSupervisor {
640
754
  }
641
755
  }
642
756
 
643
- // One parent only: the queen Session registered by the panel. Before that
644
- // registration the supervisor waits; it never picks another Session.
645
- if (this.queenSession.sessionId === null || this.queenSession.sessionId === undefined) {
757
+ // Per-repository parent: only the queen registered for this repo may own
758
+ // its workers. A repo without one is unmanaged and never dispatches.
759
+ const repoQueen = this.queenFor(entry.repo);
760
+ if (repoQueen === null) {
646
761
  entry.state = STATES.IDLE;
647
762
  entry.lastError = null;
648
763
  entry.lastCheckAt = this.now();
649
764
  entry.nextAttemptAt = this.now() + this.intervalMs;
650
- return { repo: entry.repo, state: entry.state, waiting: 'no-queen-session' };
765
+ return { repo: entry.repo, state: entry.state, waiting: 'no-queen-session', unmanaged: true };
651
766
  }
652
767
  if (typeof this.listReady !== 'function') throw new Error('supervisor has no listReady implementation');
653
768
  if (typeof this.runCard !== 'function') throw new Error('supervisor has no runCard implementation');
@@ -813,6 +928,7 @@ export class HiveSupervisor {
813
928
  }
814
929
 
815
930
  #snapshot(entry) {
931
+ const repoQueen = this.queenFor(entry.repo);
816
932
  return {
817
933
  repo: entry.repo,
818
934
  state: entry.state,
@@ -838,9 +954,9 @@ export class HiveSupervisor {
838
954
  // Live workers currently running in this repository: sessionId/start time
839
955
  // let the panel jump to the conversation or diagnose a stuck card.
840
956
  workers: this.#workers(entry.repo),
841
- waiting: this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
842
- ? 'no-queen-session'
843
- : null,
957
+ queenSessionId: repoQueen,
958
+ unmanaged: repoQueen === null,
959
+ waiting: repoQueen === null ? 'no-queen-session' : null,
844
960
  limitsError: entry.limitsError ?? null,
845
961
  environmentError: entry.environmentError ?? null,
846
962
  mode: entry.mode ?? null,
@@ -852,6 +968,33 @@ export class HiveSupervisor {
852
968
  };
853
969
  }
854
970
 
971
+ /** Cross-repo rejection count for status; observability never throws. */
972
+ #crossRepoBlockedCount() {
973
+ try {
974
+ const info = typeof this.crossRepoBlocked === 'function' ? this.crossRepoBlocked() : null;
975
+ const count = info?.count;
976
+ return Number.isInteger(count) && count >= 0 ? count : 0;
977
+ } catch {
978
+ return 0;
979
+ }
980
+ }
981
+ /** Tool visibility diagnostic for status; observability never throws. */
982
+ #queenToolsStatus() {
983
+ try {
984
+ const info = typeof this.queenTools === 'function' ? this.queenTools() : null;
985
+ if (info === null || typeof info !== 'object') {
986
+ return { queenTools: [], queenToolsSessionId: null, queenToolsListedAt: null, queenToolsError: null };
987
+ }
988
+ return {
989
+ queenTools: Array.isArray(info.names) ? info.names : [],
990
+ queenToolsSessionId: typeof info.sessionId === 'string' ? info.sessionId : null,
991
+ queenToolsListedAt: typeof info.listedAt === 'string' ? info.listedAt : null,
992
+ queenToolsError: typeof info.error === 'string' ? info.error : null,
993
+ };
994
+ } catch {
995
+ return { queenTools: [], queenToolsSessionId: null, queenToolsListedAt: null, queenToolsError: 'status-read-failed' };
996
+ }
997
+ }
855
998
  /** Emit one supervision event without letting the sink break scheduling. */
856
999
  #anomaly(event) {
857
1000
  if (this.onAnomaly === undefined) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "1.0.14",
3
+ "version": "1.0.16",
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",