dsh-hive-runner 1.0.15 → 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,36 @@ 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
+
10
40
  ## [1.0.15] - 2026-12-05
11
41
 
12
42
  ### Fixed
@@ -25,6 +55,10 @@ iterations of the plugin before this repository was published.
25
55
  the same durable `arch_review` event through the shared host writer, so a caller can
26
56
  repair reviews when an agent tool is unavailable; `hive_events` verifies it.
27
57
 
58
+ ### Published
59
+
60
+ - npm: `dsh-hive-runner@1.0.15` on 2026-12-05.
61
+
28
62
  ## [1.0.14] - 2026-12-05
29
63
 
30
64
  ### Fixed
package/SPEC.md CHANGED
@@ -54,9 +54,12 @@ 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,
@@ -83,6 +86,8 @@ wrong method -> `405` (`hive/method-not-allowed`).
83
86
  "consecutiveFailures": 0,
84
87
  "lastCards": 0,
85
88
  "lastResults": 0,
89
+ "queenSessionId": "queen-session-id",
90
+ "unmanaged": false,
86
91
  "waiting": null,
87
92
  "claimedButOrphaned": 0,
88
93
  "orphanRecovered": 0,
@@ -131,9 +136,13 @@ wrong method -> `405` (`hive/method-not-allowed`).
131
136
  - `repos` / `repoCount` — the status-visible repository registry. `hiveSupervisor.addRepo(repo)`
132
137
  adds one at runtime (absolute path, must be an initialized Hive repository; idempotent;
133
138
  rejects a relative or uninitialized path).
134
- - `queenSessionId` — the queen conversation registered by the panel; agents are
135
- parented to that Session while it is live (see §8). `waiting` is
136
- `"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.
137
146
  - `waiting` — per repository (and top level) `"no-queen-session"` before the queen
138
147
  Session is registered; then `null`. It is a startup-order hint, never an error.
139
148
  - `claimedButOrphaned` / `orphanRecovered` / `orphanRecoveryAt` — after a supervisor
@@ -402,6 +411,13 @@ A host-side fallback writes the same durable event without the agent tool:
402
411
  `hiveSupervisor.recordArchReview(repo, { card, verdict, findings, summary })`; the
403
412
  read-only `hive_events` tool verifies the appended event.
404
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.
405
421
  ### 8.6.2 Queen tool boundary
406
422
 
407
423
  DSH's `ctx.tools.guard` lets a plugin veto a tool call after pre-execute policy and
package/docs/DESIGN.md CHANGED
@@ -43,10 +43,13 @@ 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,
@@ -73,6 +76,8 @@ Response:
73
76
  "consecutiveFailures": 0,
74
77
  "lastCards": 0,
75
78
  "lastResults": 0,
79
+ "queenSessionId": "queen-session-id",
80
+ "unmanaged": false,
76
81
  "waiting": null,
77
82
  "claimedButOrphaned": 0,
78
83
  "orphanRecovered": 0,
@@ -124,12 +129,14 @@ Response:
124
129
  - `repos` / `repoCount` — the repositories the supervisor currently tracks; this is the
125
130
  status-visible registry the panel renders. Runtime additions go through
126
131
  `hiveSupervisor.addRepo(repo)` (absolute path, initialized Hive repository, idempotent).
127
- - `queenSessionId` — the queen conversation registered by the panel **or detected by
128
- the queen tool guard** when an ordinary initialized-repo Session calls a subagent
129
- tool; agents are parented to that Session while its Agent is live. `waiting` is
130
- `"no-queen-session"` until the registration arrives (startup-order hint, not an
131
- error); the registration is only replaced by a new registration. Status workers and
132
- 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.
133
140
  - `queenBoundaryViolations` — how many direct `subagent`/`subagent_fork`/
134
141
  `subagent_claude_code` calls from the queen Session the tool guard has vetoed;
135
142
  `lastQueenBoundaryViolation` is `{ tool, sessionId, at, repo }` for the most recent.
@@ -194,7 +201,9 @@ required; an uninitialized path is rejected), so a repo outside `config.repos` a
194
201
  startup-order hint, not an error. While registered, its live Agent is the parent;
195
202
  if it cannot be resolved the round falls back to `parentSession` / the first live
196
203
  Agent, and defers with `hive/no-parent-agent` when no Agent is live.
197
- - 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: ... }`.
198
207
  - Missing `sessionId` -> `400` `hive/missing-session-id`; non-POST -> `405`.
199
208
  ## 3. Per-repository limits
200
209
 
@@ -376,6 +385,32 @@ writes the same durable `arch_review` event through the shared host writer. The
376
385
  `hive_events` tool remains read-only and can verify the event; a host/panel caller can
377
386
  also invoke the service method directly.
378
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
+
379
414
  ### Tool boundary: hard veto through `ctx.tools.guard`
380
415
 
381
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,22 +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.
108
113
  // One-shot diagnostic: schema names visible to the queen agent (under PTC the
109
114
  // model sees only run_code, but tools.hive_* exist inside run_code).
110
115
  const queenTools = { names: [], sessionId: null, listedAt: null, error: null };
111
116
  /** Queen boundary violations observed by the tool guard (status observability). */
112
117
  const queenBoundary = { count: 0, last: null };
118
+ /** Mechanical cross-repo rejections of queen hive_* calls. */
119
+ const crossRepoBlocked = { count: 0, last: null };
113
120
  let parentProviderImpl;
114
121
  const runner = createRoundRunner({
115
122
  ctx,
116
123
  config: resolved,
117
124
  commands,
118
125
  limitFor: (repo, role) => limits.limitFor(repo, role),
119
- parentProvider: (explicit) => parentProviderImpl(explicit),
126
+ parentProvider: (explicit, repo) => parentProviderImpl(explicit, repo),
120
127
  onAnomaly: (event) => recordAnomaly(event),
121
128
  // A finished worker or a settled card asks for a near-real-time checkpoint
122
129
  // check instead of waiting for the next patrol tick.
@@ -127,8 +134,10 @@ export function apply(ctx, config = {}) {
127
134
  },
128
135
  log,
129
136
  });
130
- parentProviderImpl = async (explicit) => {
131
- 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);
132
141
  const agent = sessionId === null ? undefined : ctx.get('agents')?.get?.(sessionId);
133
142
  return { agent, source: 'queen', sessionId };
134
143
  };
@@ -193,8 +202,8 @@ export function apply(ctx, config = {}) {
193
202
  /** Idempotently register a cwd-recognized queen so the panel can show it. */
194
203
  function registerDetectedQueen(sessionId, cwd) {
195
204
  try {
196
- if (supervisor.queenSession.sessionId === sessionId) return;
197
- supervisor.setQueenSession(sessionId);
205
+ if (supervisor.queenFor(cwd) === sessionId) return;
206
+ supervisor.setQueenSession(sessionId, cwd);
198
207
  log('info', 'auto-registered initialized queen session', sessionId, 'cwd', cwd);
199
208
  } catch (error) {
200
209
  log('warn', 'auto-registering detected queen failed', error);
@@ -240,7 +249,8 @@ export function apply(ctx, config = {}) {
240
249
  // Recognition is registration OR an ordinary initialized-repo Session; a
241
250
  // /queen off command event suppresses both paths.
242
251
  ctx.effect(() => ctx.tools.guard(createQueenBoundaryGuard({
243
- queenSession,
252
+ isRegisteredQueen: (sessionId) => supervisor.isQueenSession(sessionId),
253
+ queenSessionIds: () => supervisor.queenSessionIds(),
244
254
  onViolation: recordQueenBoundaryViolation,
245
255
  onQueenDetected: registerDetectedQueen,
246
256
  resolveCwd: resolveQueenBoundaryCwd,
@@ -249,7 +259,11 @@ export function apply(ctx, config = {}) {
249
259
  log,
250
260
  })));
251
261
 
252
- const notifier = createQueenNotifier({ ctx, queenSession, log });
262
+ const notifier = createQueenNotifier({
263
+ ctx,
264
+ resolveSessionId: (repo) => supervisor.queenFor(repo),
265
+ log,
266
+ });
253
267
  // Done cards must carry an arch_review event; the patrol audits the board and
254
268
  // turns a missing review into an arch-review-missing anomaly.
255
269
  const archReviewAudit = createArchReviewAudit({
@@ -282,9 +296,13 @@ export function apply(ctx, config = {}) {
282
296
  runCard: runner.runCard,
283
297
  preflight: runner.preflight,
284
298
  activeRuns: (repo) => runner.activeRuns(repo),
285
- queenSession,
299
+ resolveQueenRepo: (sessionId) => {
300
+ const agent = ctx.get('agents')?.get?.(sessionId);
301
+ return resolveQueenBoundaryCwd(agent, agent?.session);
302
+ },
286
303
  queenBoundary,
287
304
  queenTools: () => queenTools,
305
+ crossRepoBlocked: () => crossRepoBlocked,
288
306
  archReview: (repo, review) => recordArchReviewHost(repo, review),
289
307
  readMode: (repo) => commands.mode(repo),
290
308
  onAnomaly: (event) => recordAnomaly(event),
@@ -327,7 +345,7 @@ export function apply(ctx, config = {}) {
327
345
  }
328
346
  // Retry the one-shot tool listing if the panel registered before the agent
329
347
  // was live (status/queenTools then contains an error until this succeeds).
330
- if (supervisor.queenSession.sessionId !== null) inspectQueenTools(supervisor.queenSession.sessionId);
348
+ for (const queen of supervisor.queens()) inspectQueenTools(queen.sessionId);
331
349
  // Progress checkpoints: drained/all-done/gate-advance/idle goals. Delivery
332
350
  // is direct; failures stay pending in the checkpoint controller.
333
351
  try {
@@ -356,6 +374,7 @@ export function apply(ctx, config = {}) {
356
374
  return { tasks, ready };
357
375
  },
358
376
  loadEvents: (repo) => readEvents(repo, { limit: 100 }),
377
+ queenForRepo: (repo) => supervisor.queenFor(repo),
359
378
  drainMs: resolved.checkpointDrainMs,
360
379
  idleMs: resolved.checkpointIdleMs,
361
380
  log,
@@ -394,6 +413,22 @@ export function apply(ctx, config = {}) {
394
413
  );
395
414
  }
396
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
+
397
432
  /** Register one model-facing tool whose result is rendered as one text block. */
398
433
  function registerTextTool({ name, description, parameters = {}, execute }) {
399
434
  ctx.tools.register(defineTool({
@@ -401,7 +436,7 @@ export function apply(ctx, config = {}) {
401
436
  description,
402
437
  parameters,
403
438
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
404
- execute,
439
+ execute: async (args = {}, exec = {}) => execute(enforceQueenHiveScope(name, parameters, args, exec), exec),
405
440
  }));
406
441
  }
407
442
 
@@ -426,8 +461,8 @@ export function apply(ctx, config = {}) {
426
461
  const repo = repoOf(args);
427
462
  const signal = exec?.signal;
428
463
  const session = exec?.agent?.session;
429
- if (supervisor.queenSession.sessionId === null) {
430
- 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');
431
466
  }
432
467
  runner.preflight(repo);
433
468
  const cards = await runner.listReady(repo, { signal, session });
@@ -953,6 +988,11 @@ export function apply(ctx, config = {}) {
953
988
  if (typeof args.sessionId !== 'string' || args.sessionId === '') {
954
989
  throw new Error('hive_intervene guide needs sessionId (see hive_tasks show lastRun.sessionId)');
955
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
+ }
956
996
  delivery = deliverToSession({ ctx }, args.sessionId, '[hive queen guidance]' + NL + NL + args.reason, { prefer: 'steer' });
957
997
  if (delivery.delivered !== true) {
958
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)
@@ -142,6 +143,7 @@ export class HiveSupervisor {
142
143
  * @param {(sessionId: string) => void} [options.onQueenSession] called after a queen Session registers
143
144
  * @param {() => { names?: string[], sessionId?: string | null, listedAt?: string | null, error?: string | null }} [options.queenTools] diagnostic: tools visible to the queen agent
144
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
145
147
  * @param {() => number} [options.pendingAnomalies] undelivered queen anomalies reported in status
146
148
  * @param {() => number} [options.pendingCheckpoints] undelivered progress checkpoints reported in status
147
149
  * @param {Console} [options.logger]
@@ -173,8 +175,13 @@ export class HiveSupervisor {
173
175
  this.runCard = options.runCard;
174
176
  this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
175
177
  this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
176
- // Shared with the round runner: the Session registered by the panel when the
177
- // 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;
178
185
  this.queenSession = options.queenSession ?? { sessionId: null };
179
186
  this.recoverOrphans = typeof options.recoverOrphans === 'function' ? options.recoverOrphans : undefined;
180
187
  this.queenBoundary = options.queenBoundary ?? { count: 0, last: null };
@@ -184,6 +191,7 @@ export class HiveSupervisor {
184
191
  this.onQueenSession = typeof options.onQueenSession === 'function' ? options.onQueenSession : undefined;
185
192
  this.queenTools = typeof options.queenTools === 'function' ? options.queenTools : undefined;
186
193
  this.archReview = typeof options.archReview === 'function' ? options.archReview : undefined;
194
+ this.crossRepoBlocked = typeof options.crossRepoBlocked === 'function' ? options.crossRepoBlocked : undefined;
187
195
  this.pendingAnomalies = typeof options.pendingAnomalies === 'function' ? options.pendingAnomalies : undefined;
188
196
  this.pendingCheckpoints = typeof options.pendingCheckpoints === 'function' ? options.pendingCheckpoints : undefined;
189
197
  this.discover = options.discover;
@@ -371,25 +379,57 @@ export class HiveSupervisor {
371
379
  }
372
380
 
373
381
  /**
374
- * Register the queen Session that owns every worker. The panel calls this when
375
- * 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.
376
386
  * @param {string} sessionId live DSH Session id of the queen conversation
387
+ * @param {string} [repo] repository this queen controls
377
388
  * @returns {object} supervisor status
378
389
  */
379
- setQueenSession(sessionId) {
390
+ setQueenSession(sessionId, repo) {
380
391
  if (typeof sessionId !== 'string' || sessionId.trim() === '') {
381
392
  throw new TypeError('setQueenSession: sessionId must be a non-empty string');
382
393
  }
383
- this.queenSession.sessionId = sessionId.trim();
384
- for (const entry of this.repos.values()) {
385
- entry.waiting = null;
386
- 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)');
411
+ }
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
+ }
387
427
  }
388
- this.#log('info', 'registered queen session', this.queenSession.sessionId);
389
- // Let the plugin flush anomalies accumulated while no queen was live.
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.
390
430
  if (this.onQueenSession !== undefined) {
391
431
  try {
392
- this.onQueenSession(this.queenSession.sessionId);
432
+ this.onQueenSession(id, key);
393
433
  } catch (error) {
394
434
  this.#log('warn', 'queen-session hook failed', messageOf(error));
395
435
  }
@@ -397,6 +437,47 @@ export class HiveSupervisor {
397
437
  return this.status();
398
438
  }
399
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
+
400
481
  /**
401
482
  * Host-side fallback for the queen's arch-review tool. The normal path is the
402
483
  * registered hive_arch_review tool (inside run_code under PTC); this method
@@ -559,22 +640,33 @@ export class HiveSupervisor {
559
640
 
560
641
  /** Serializable supervisor + per-repository status. */
561
642
  status() {
562
- const waiting = this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
563
- ? 'no-queen-session'
564
- : 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';
565
652
  const repoSnapshots = [...this.repos.values()]
566
653
  .map((entry) => this.#snapshot(entry))
567
654
  .sort((a, b) => a.repo.localeCompare(b.repo));
568
655
  return {
569
656
  started: this.started,
570
- // The queen Session registered by the panel; every card worker is parented
571
- // to it. Until it is registered nothing is dispatched.
572
- 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,
573
662
  waiting,
574
663
  // Direct subagent calls from the queen are vetoed by the tool guard; the
575
664
  // counter/last attempt is observability, not a scheduling decision.
576
665
  queenBoundaryViolations: Number.isInteger(this.queenBoundary?.count) ? this.queenBoundary.count : 0,
577
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,
578
670
  intervalMs: this.intervalMs,
579
671
  idleBackoffMs: this.idleBackoffMs,
580
672
  maxConcurrentRepos: this.maxConcurrentRepos,
@@ -662,14 +754,15 @@ export class HiveSupervisor {
662
754
  }
663
755
  }
664
756
 
665
- // One parent only: the queen Session registered by the panel. Before that
666
- // registration the supervisor waits; it never picks another Session.
667
- 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) {
668
761
  entry.state = STATES.IDLE;
669
762
  entry.lastError = null;
670
763
  entry.lastCheckAt = this.now();
671
764
  entry.nextAttemptAt = this.now() + this.intervalMs;
672
- 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 };
673
766
  }
674
767
  if (typeof this.listReady !== 'function') throw new Error('supervisor has no listReady implementation');
675
768
  if (typeof this.runCard !== 'function') throw new Error('supervisor has no runCard implementation');
@@ -835,6 +928,7 @@ export class HiveSupervisor {
835
928
  }
836
929
 
837
930
  #snapshot(entry) {
931
+ const repoQueen = this.queenFor(entry.repo);
838
932
  return {
839
933
  repo: entry.repo,
840
934
  state: entry.state,
@@ -860,9 +954,9 @@ export class HiveSupervisor {
860
954
  // Live workers currently running in this repository: sessionId/start time
861
955
  // let the panel jump to the conversation or diagnose a stuck card.
862
956
  workers: this.#workers(entry.repo),
863
- waiting: this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
864
- ? 'no-queen-session'
865
- : null,
957
+ queenSessionId: repoQueen,
958
+ unmanaged: repoQueen === null,
959
+ waiting: repoQueen === null ? 'no-queen-session' : null,
866
960
  limitsError: entry.limitsError ?? null,
867
961
  environmentError: entry.environmentError ?? null,
868
962
  mode: entry.mode ?? null,
@@ -874,6 +968,16 @@ export class HiveSupervisor {
874
968
  };
875
969
  }
876
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
+ }
877
981
  /** Tool visibility diagnostic for status; observability never throws. */
878
982
  #queenToolsStatus() {
879
983
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "1.0.15",
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",