dsh-hive-panel 1.0.3 → 1.0.5

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
@@ -4,6 +4,51 @@ All notable changes to this project are documented in this file. The format is
4
4
  based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [1.0.5] - 2026-12-05
8
+
9
+ ### Fixed
10
+
11
+ - **The queen repository is registered with the supervisor from the first prompt
12
+ assembly.** When a Session's cwd is an initialised repository, the queen injection now
13
+ also calls `hiveSupervisor.addRepo(cwd)` with the full path, so a repository outside
14
+ the static `repos` config is supervised immediately instead of only after the panel is
15
+ opened. Registration is idempotent; relative or uninitialised paths are ignored.
16
+ - **The injected queen invariants now cover mutation tools and claim.** The
17
+ `QUEEN_INVARIANTS` block names the forbidden tools explicitly — `write`, `edit`,
18
+ `bash`, `cua` … — and states that `claim` is a worker action; read-only and
19
+ `hive_*` tools stay allowed. This sits above the untrusted workspace role file, so an
20
+ older `hive init` contract cannot widen the queen's tool surface.
21
+
22
+ ### Tests
23
+
24
+ - 41 checks cover the `addRepo` registration path, initialised-marker discovery, the
25
+ widened invariants copy and the unchanged suppression rules.
26
+
27
+ ## [1.0.4] - 2026-12-05
28
+
29
+ ### Fixed
30
+
31
+ - **Queen mode no longer depends on the panel being opened.** The `hive:queen`
32
+ system-prompt section is rendered on the first prompt assembly for any Session whose
33
+ working directory is an initialised Hive repository: it resolves the Session cwd,
34
+ registers the queen Session id with the resident `dsh-hive-runner` supervisor and
35
+ injects the trusted invariants + workspace role there. Subagent Sessions (workers) are
36
+ excluded, an earlier `/queen off` keeps the Session suppressed, and the panel only
37
+ mirrors the state instead of owning it.
38
+ - The injected text still reads `<cwd>/.hive/roles/queen.md` as untrusted workspace
39
+ input below the plugin-owned invariants; the 24576-character role cap and the fallback
40
+ role are unchanged.
41
+
42
+ ### Tests
43
+
44
+ - 39 checks cover cwd-based auto-injection with the panel never opened, supervisor
45
+ registration, subagent exclusion, `/queen off` suppression and the unchanged
46
+ invariants / role cap paths.
47
+
48
+ ### Published
49
+
50
+ - npm: `dsh-hive-panel@1.0.4` on 2026-12-05.
51
+
7
52
  ## [1.0.3] - 2026-12-05
8
53
 
9
54
  ### Fixed
@@ -18,6 +63,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
18
63
  - The budget calculation counts the invariants block; the role cap stays 24576 and the
19
64
  truncation marker still applies to the workspace body.
20
65
 
66
+ ### Published
67
+
68
+ - npm: `dsh-hive-panel@1.0.3` on 2026-12-05.
69
+
21
70
  ## [1.0.2] - 2026-12-05
22
71
 
23
72
  ### Fixed
package/README.md CHANGED
@@ -39,11 +39,11 @@ the Hive CLI writes them.
39
39
  | --- | --- |
40
40
  | **A Hive tab in the conversation** | The board lanes (pending, claimed, done, failed), the header agents count, the event drawer and task details, scoped to the Session's repository |
41
41
  | **Initialise from the tab** | Run `hive init` on an uninitialised repository and start using it immediately |
42
- | **Queen mode** | An initialised repository makes the current Session the queen automatically: it plans and coordinates, splits goals into fine-grained tasks that each carry an acceptance command, then orders, supervises, reviews and reports — it never writes code. The injected contract also forbids implementing the work (no `subagent`/`subagent_fork`/`subagent_claude_code` or direct execution tools): a goal becomes Hive tasks and the supervisor dispatches them. A header badge shows whether the Queen is active. `/queen off` exits; `/queen on` or the **Let the Queen take over** button re-enters |
42
+ | **Queen mode** | An initialised repository makes the current Session the queen automatically on its first message — no need to open the panel, and it survives a DSH restart: it plans and coordinates, splits goals into fine-grained tasks that each carry an acceptance command, then orders, supervises, reviews and reports — it never writes code. The injected contract also forbids implementing the work (no `subagent`/`subagent_fork`/`subagent_claude_code` or direct execution tools): a goal becomes Hive tasks and the supervisor dispatches them. A header badge shows whether the Queen is active. `/queen off` exits; `/queen on` or the **Let the Queen take over** button re-enters |
43
43
  | **Task actions** | Claim, complete, fail, retry and delete a task from its details; create tasks, ask the Queen for a task plan and pause or resume claiming from the toolbar |
44
44
  | **Task details** | ID, role, state and file scope, plus the last run: output, the **Also writing** overlap announcements and the lessons read. **Open agent chat** jumps to that worker's conversation when DSH can navigate to it |
45
45
  | **Settings** | The toolbar gear opens per-role concurrency limits (0–999, 0 pauses the role; needs `dsh-hive-runner`) and role management (add a role with adapter, model and responsibilities; delete a role) |
46
- | **Supervisor status** | When [dsh-hive-runner](https://github.com/d86e/dsh-hive-runner) is installed, the toolbar shows the current repository's supervisor state (idle, running, backoff, paused) with the running agent count, and **Resume** while paused |
46
+ | **Supervisor status** | When [dsh-hive-runner](https://github.com/d86e/dsh-hive-runner) is installed, the toolbar shows the current repository's supervisor state (idle, running, backoff, paused) with the running agent count, and **Resume** while paused. A repository that becomes the queen is added to the supervisor automatically, so it starts dispatching even when it is not listed in the runner's `repos` config |
47
47
  | **Read-only by default** | Watching the board is safe out of the box; mutations (including settings writes) are opt-in |
48
48
 
49
49
  ## Requirements
@@ -165,7 +165,7 @@ Restart DSH after changing the config.
165
165
 
166
166
  | Key | Default | Meaning |
167
167
  | --- | --- | --- |
168
- | `autoQueen` | `true` | Make the current Session the queen automatically when a snapshot sees an initialised repository. Set to `false` to enter queen mode only with `init`, `/queen on` or the **Let the Queen take over** button |
168
+ | `autoQueen` | `true` | Make the current Session the queen automatically when its cwd has `.hive/roles/queen.md` (first prompt assembly) or when a snapshot sees an initialised repository. Set to `false` to enter queen mode only with `init`, `/queen on` or the **Let the Queen take over** button |
169
169
  | `writable` | `false` | Allow mutating actions (init, add, plan, claim, done, fail, retry, remove, mode, roles-add, roles-remove, ...). When false the board is still readable and mutations are hidden or rejected |
170
170
  | `bins.hive` | `hive` from PATH | `hive` executable: PATH name or absolute path. When missing, retried through `npx -y -p @d86e/hive -p hive-consensus -p hive-tasks -p hive-runner -p merge-on-commit hive` |
171
171
  | `bins.tasks` | `hive-tasks` from PATH | `hive-tasks` executable; npx fallback `-p hive-tasks` |
@@ -261,8 +261,11 @@ and saving role limits in Settings is written by `dsh-hive-runner` to
261
261
  `.hive/limits.json`. Queen mode stores nothing.
262
262
 
263
263
  **Can several Sessions use it at once?** Yes. Each Session is scoped to its own working
264
- directory. Queen mode is per Session: any Session that snapshots an initialised repository
265
- enters it automatically unless that Session ran `/queen off` or `autoQueen` is `false`.
264
+ directory. Queen mode is per Session: any Session whose cwd has
265
+ `.hive/roles/queen.md` enters it on the first prompt assembly, and any Session that
266
+ snapshots an initialised repository enters it automatically — unless that Session ran
267
+ `/queen off` or `autoQueen` is `false`. Opening the panel is not required, and the
268
+ supervisor registration happens on the same first assembly.
266
269
 
267
270
  ## Security
268
271
 
@@ -280,8 +283,12 @@ enters it automatically unless that Session ran `/queen off` or `autoQueen` is `
280
283
  low-trust input: it is labelled as untrusted, has a built-in coordinator fallback and is
281
284
  capped at 24576 characters. A plugin-owned **trusted invariants** block is always injected
282
285
  above it (never call `subagent`/`subagent_fork`/`subagent_claude_code` or execution tools to
283
- implement; goals become Hive tasks; discussion creates tasks only when asked to execute), so
284
- a stale or custom workspace role file cannot remove the production boundary.
286
+ implement; never call `write`/`edit`/`apply_patch`/`bash`/`cua` or any file-mutating or
287
+ command-executing tool; tasks and state use only `hive_*` tools; `claim`/`done`/`fail` are
288
+ worker actions the queen must not call; implementation is delegated to the supervisor). The
289
+ tool-boundary sentence is injected in English and Chinese, so an older `hive init` role file
290
+ gets it without re-running init. Goals become Hive tasks; discussion creates tasks only when
291
+ asked to execute, so a stale or custom workspace role file cannot remove the boundary.
285
292
  - If you expose DSH Web beyond your machine, add authentication or a reverse proxy at the
286
293
  DSH layer first.
287
294
 
package/SPEC.md CHANGED
@@ -302,42 +302,72 @@ never appends Session events.
302
302
 
303
303
  Activation:
304
304
 
305
- 1. **Auto (default).** Before returning a `200` snapshot, the host probes
306
- `refs/hive/v1` in the Session cwd. When the ref exists, `autoQueen` is not
307
- `false`, and the Session was not explicitly closed, an inactive Session is marked
308
- queen with `source: "auto"`. An already active Session is not rewritten.
309
- 2. **`init` action.** A successful `init` followed by the `refs/hive/v1` probe marks
310
- the Session with `source: "manual"`.
311
- 3. **`queen-on` action / `/queen on`.** Explicit activation; re-reads the role file
305
+ 1. **First prompt assembly (default, panel-independent).** The `hive:queen` section
306
+ evaluates on every `ctx.systemPrompt.assemble()` with the Session's `agent`. While
307
+ the Session is not active/suppressed and `autoQueen` is not `false`, a cwd that
308
+ contains `.hive/roles/queen.md` auto-marks the Session (`source: "auto"`), injects
309
+ the role + trusted invariants, and registers it with the supervisor. This is the
310
+ path that keeps a restarted DSH, or a Session that never opened the panel, on the
311
+ queen contract instead of a plain coding agent; only that Session's cwd is read.
312
+ Subagent Sessions (`header.origin === "subagent"` or a positive
313
+ `header.delegationDepth`) are excluded: card workers share the repository cwd and
314
+ must never be auto-queened or overwrite the supervisor's queen registration.
315
+ 2. **Snapshot auto (default).** Before returning a `200` snapshot, the host probes
316
+ `refs/hive/v1` and the `hive init` marker files in the Session cwd. When the repo
317
+ is initialised, `autoQueen` is not `false`, and the Session was not explicitly
318
+ closed, an inactive Session is marked queen with `source: "auto"` (panel display,
319
+ no prompt required). An already active Session is not rewritten.
320
+ 3. **`init` action.** A successful `init` followed by the repo probe marks the
321
+ Session with `source: "manual"`.
322
+ 4. **`queen-on` action / `/queen on`.** Explicit activation; re-reads the role file
312
323
  and clears a previous explicit exit.
313
324
 
314
325
  Deactivation:
315
326
 
316
327
  - `/queen off` (calling Session only), `queen-off` action, or `agent/disposed`.
317
- - Exit is idempotent and explicit: the Session is remembered as suppressed, so snapshot
318
- auto-activation does not turn it back on. `queen-on` / `/queen on` lifts it.
328
+ - Exit is idempotent and explicit: the Session is remembered as suppressed, so neither
329
+ prompt nor snapshot auto-activation turns it back on. `queen-on` / `/queen on` lifts it.
319
330
  - Process restart forgets both activation and suppression (fail-safe).
320
331
 
321
332
  Configuration: `autoQueen` on the plugin entry config, default `true`; when `false`
322
- snapshots never auto-activate and only `init` / `queen-on` / `/queen on` activate.
323
-
324
- Runner registration: every successful activation (auto, `init`, `queen-on` /
325
- `/queen on`) also registers the Session id with the resident supervisor when one is
326
- mounted (`ctx.get('hiveSupervisor').setQueenSession(id)`). Registration is in-memory and
327
- idempotent and is repeated on every snapshot, so a plugin restart restores it; the
328
- supervisor then parents task workers to that conversation.
329
-
330
- Injection: a system-prompt section `hive:queen` (order 520) that renders text only for
331
- the marked Session and an empty string for every other Session, evaluated on each prompt
332
- assembly. It does not enter the conversation history.
333
+ neither prompt assembly nor snapshots auto-activate, and only `init` / `queen-on` /
334
+ `/queen on` activate.
335
+
336
+ Runner registration: every successful activation (prompt auto, snapshot auto, `init`,
337
+ `queen-on` / `/queen on`) registers the Session id with the resident supervisor when one
338
+ is mounted (`ctx.get('hiveSupervisor').setQueenSession(id)`). Prompt auto-activation runs
339
+ the registration on the first assembly, so the supervisor is ready even when no panel is
340
+ open; registration is in-memory, idempotent and repeated on each activation/snapshot, so a
341
+ plugin restart restores it. The supervisor then parents task workers to that conversation.
342
+
343
+ Repository registration: the same registrar also adds the Session's cwd to the supervisor
344
+ (with `hiveSupervisor.addRepo(repo)`) so a repository that was never in
345
+ `config.repos` is still dispatched. It only runs when that cwd has
346
+ `.hive/roles/queen.md` (an initialised queen repository); `addRepo` is idempotent by
347
+ normalised path, so prompt assemblies, snapshots and init/queen-on may all repeat it
348
+ safely. The registration is deliberately **one-way**: `/queen off`, agent disposal,
349
+ plugin unload and process restart never remove it, and the supervisor's
350
+ `status().repos` list (what the panel's supervisor strip renders) shows the repository.
351
+ When the mounted supervisor predates `addRepo`, the repository step is skipped with a
352
+ log line and only the queen Session is registered.
353
+
354
+ Injection: a system-prompt section `hive:queen` (order 520) evaluated on each prompt
355
+ assembly with the Session's `agent`; it auto-activates from the agent's cwd on the first
356
+ assembly (see Activation 1), renders role + invariants for the marked Session and an empty
357
+ string for every other Session. It does not enter the conversation history.
333
358
 
334
359
  Role text: `<cwd>/.hive/roles/queen.md`, prefixed with an "untrusted role file" label
335
360
  naming the absolute source path, capped at 24576 characters and marked `[truncated]`
336
361
  when cut; a built-in fallback is labelled when the file is missing. Between the label and the
337
362
  workspace body the plugin always injects a **trusted invariants** block (`QUEEN_INVARIANTS`):
338
363
  never call `subagent`/`subagent_fork`/`subagent_claude_code` or execution tools to implement;
339
- goals become Hive tasks and the supervisor dispatches them; discussion creates tasks only when
340
- the human asks to execute. It is plugin-owned and cannot be overridden by the workspace file.
364
+ never call `write`/`edit`/`apply_patch`/`bash`/`cua` or any other file-mutating or
365
+ command-executing tool; tasks and state use only `hive_*` tools; `claim`/`done`/`fail` are
366
+ worker actions the queen must not call; implementation is delegated to the supervisor. The
367
+ tool-boundary sentence is injected in English and Chinese, so a repository initialised by an
368
+ older `hive init` (whose role file predates this contract) gets it without re-running init.
369
+ Goals become Hive tasks and the supervisor dispatches them; discussion creates tasks only when
370
+ the human asks to execute. The block is plugin-owned and cannot be overridden by the workspace file.
341
371
  The fallback and the exit hint both carry the coordinator contract (fine-grained tasks,
342
372
  acceptance commands, supervise/review/report, `hive-queen` skill) and never grant code-writing.
343
373
 
@@ -355,5 +385,8 @@ acceptance commands, supervise/review/report, `hive-queen` skill) and never gran
355
385
  Host APIs used: `connection.fetch.register`, `sessions`, `workingDirectory`, `shell`,
356
386
  `systemPrompt.section`, `commands.register` (and `agents` in the inject list), plus
357
387
  `ctx.effect` and `ctx.on('agent/disposed')`. `sandboxPolicy`, `sessionPersistence`
358
- and `hiveSupervisor` are optional and read through `ctx.get`. A DSH upgrade can change
359
- any of these: re-run `npm run check` against the installed DSH before releasing.
388
+ and `hiveSupervisor` are optional and read through `ctx.get`. The supervisor contract
389
+ used here is `setQueenSession(sessionId)` plus the optional `addRepo(repo)` /
390
+ `hasRepo(repo)` from dsh-hive-runner's `HiveSupervisor` (feature-detected; older
391
+ supervisors get no repository registration). A DSH upgrade can change any of these:
392
+ re-run `npm run check` against the installed DSH before releasing.
package/docs/DESIGN.md CHANGED
@@ -287,7 +287,23 @@ token(PATH 名或绝对路径)。
287
287
 
288
288
  ## 6. 女王激活(`lib/queen.js`)
289
289
 
290
- - **自动触发(默认)**:`op=snapshot` 返回前已经跑过 `refs/hive/v1` 探针;若仓库已初始化、
290
+ - **与面板解耦的自动注入(默认)**:`hive:queen` system-prompt section 每次
291
+ `ctx.systemPrompt.assemble()` 都会带着该会话的 `agent` 求值。若会话未激活、未被
292
+ `/queen off` 抑制、`autoQueen !== false`,且其 cwd 存在 `.hive/roles/queen.md`,
293
+ 就在**首次组装时**自动 mark(source auto)、注入角色文本 + `QUEEN_INVARIANTS`,并调用
294
+ `registerQueenSession(sessionId)` 向 `ctx.get('hiveSupervisor')` 幂等登记。这条路径不需要
295
+ 打开面板,所以 DSH 重启后面板没开、或用户直接对 chat 说目标时,会话仍是女王而不是普通
296
+ coding agent;只看**当前会话的 cwd**,不同仓库互不影响。同一钩子还会把该会话 cwd
297
+ 通过 `hiveSupervisor.addRepo(cwd)` 登记给 supervisor(仅当 cwd 有
298
+ `.hive/roles/queen.md`;`addRepo` 按规范化路径幂等去重),否则 supervisor 只对
299
+ `config.repos` 里的仓库派发、从面板 init/queen-on 打开的新仓库永远不会被跑。登记是
300
+ **单向**的:`/queen off`、agent dispose、插件卸载、进程重启都不会 `removeRepo`;
301
+ supervisor 的 `status().repos`(面板 supervisor 条的数据源)随即可见该仓库。
302
+ 旧版 supervisor 没有 `addRepo` 时跳过仓库登记并记一条日志,仍登记 queen Session。
303
+ subagent 会话
304
+ (`session.header.origin === 'subagent'` 或 `delegationDepth > 0`)被排除:卡 worker 与父会话
305
+ 共享仓库 cwd,若自动注入会污染 worker 并把 supervisor 的 queen 登记顶掉。
306
+ - **面板触发的自动标记**:`op=snapshot` 返回前已经跑过 `refs/hive/v1` 探针;若仓库已初始化、
291
307
  `config.autoQueen !== false` 且该 Session 没有被显式关闭,则调用
292
308
  `queen.autoMark({ sessionId, cwd })`。`autoMark` 幂等:已激活的 Session 不重读/重写角色文件,
293
309
  被显式关闭的 Session 直接跳过。这样在 CLI 里已经 `hive init` 过的仓库(如 queen-sandbox)
@@ -309,7 +325,9 @@ token(PATH 名或绝对路径)。
309
325
  “`[hive:queen] role loaded from <绝对路径> … untrusted`” 开头,随后是无条件注入的
310
326
  **插件自有 trusted invariants**(禁止 subagent/直接执行实现;目标只转成 Hive 任务;讨论只在
311
327
  人类明确要执行时建任务)——旧版 `hive init` 写出的工作区角色文件无法覆盖它,因此生产红线不依赖
312
- 仓库是否重新 init。总长 **≤ 24576 字符**;超长截断并标注
328
+ 仓库是否重新 init。invariants 另含**工具边界**(中英各一句):禁止 `write`/`edit`/`apply_patch`/
329
+ `bash`/`cua` 等修改文件或执行命令的工具,任务与状态只用 `hive_*` 工具,`claim`/`done`/`fail` 是
330
+ worker 动作女王不得调用,实现交给 supervisor;这样老仓库不重跑 init 也能拿到该边界。总长 **≤ 24576 字符**;超长截断并标注
313
331
  `[truncated]`。文件缺失时用内置兜底角色,并标注 `missing; built-in fallback`;兜底与退出提示
314
332
  都写明协调者契约(细粒度卡、每卡必须有验收命令、排序/监督/审查/汇报,永不写码)。
315
333
  - **不污染会话日志**:不 append 自定义 session 事件(第三方未知事件会让 resume 拒绝解释日志),
@@ -424,7 +442,7 @@ npm run check
424
442
  # ok - node --check lib/queen.js
425
443
  # ok - node --check lib/client.js
426
444
  # ...
427
- # 37 checks passed
445
+ # 41 checks passed
428
446
  ```
429
447
 
430
448
  覆盖:语法、package/bundle 声明、无代理残留、client bundle 的 `/api/hive` URL 与 Session 注入、
@@ -436,7 +454,11 @@ Connection Fetch 路由注册、快照走 `ctx.shell` 且 cwd/policy 正确、
436
454
  `roles` 快照(角色列表 + 持久限额)、`roles-add`(含 description)的参数校验/argv/仓库 cwd、
437
455
  重复角色的 CLI stderr 透传、`roles-remove` 的 argv/非法名/只读 403/CLI 失败透传,以及 `remove` 的卡片 id 校验;
438
456
  另有 `initialised` 只靠 `.hive/roles.yaml`/`.hive/config.json` 即为 true、init 动作后立即 true、
439
- 两者与 ref 都无才为 false,以及 client bundle 的 init 成功即时切面检查。
457
+ 两者与 ref 都无才为 false,以及 client bundle 的 init 成功即时切面检查;prompt 首次组装自动注入
458
+ (含 `QUEEN_INVARIANTS`、supervisor 幂等登记、跨仓库隔离)、`/queen off` 后不注入、
459
+ `autoQueen=false` 不注入、未初始化仓库不注入;prompt/init/queen-on 路径对
460
+ `hiveSupervisor.addRepo` 的登记(幂等去重、只登记有 queen.md 的仓库、退出与卸载不删除);
461
+ invariants 的工具边界断言(write/edit/apply_patch/bash/cua/claim、hive_*、中英两句)。
440
462
 
441
463
  不启动、不重启任何 DSH 进程,也不写运行中的 `~/.dsh`。
442
464
 
package/lib/index.js CHANGED
@@ -30,7 +30,7 @@
30
30
  */
31
31
  import fs from 'node:fs'
32
32
  import path from 'node:path'
33
- import { createQueen, QUEEN_OFF_ACTION, QUEEN_ON_ACTION } from './queen.js'
33
+ import { createQueen, hasQueenRole, QUEEN_OFF_ACTION, QUEEN_ON_ACTION } from './queen.js'
34
34
 
35
35
  /** Cordis plugin name used in logs and fiber diagnostics. */
36
36
  export const name = 'hive-panel'
@@ -821,13 +821,68 @@ function createLog(ctx) {
821
821
  }
822
822
  }
823
823
 
824
+ /**
825
+ * Build the registrar that tells the resident Hive runner which Session is the
826
+ * queen and which repository it drives.
827
+ *
828
+ * The supervisor only dispatches repositories it tracks, so a Session that
829
+ * becomes queen by prompt auto-injection (or a panel init/queen-on) must also
830
+ * add its cwd. When the mounted supervisor exposes `addRepo(repo)` (the
831
+ * `hiveSupervisor` service in dsh-hive-runner does; it is idempotent by
832
+ * normalised path and its `status().repos` list then shows the repository) we
833
+ * register the cwd first; otherwise the repo step is skipped and only the
834
+ * queen Session is registered. Nothing is removed on unload/exit: the repo
835
+ * registration is deliberately one-way.
836
+ *
837
+ * @param {object} ctx - host Cordis context (may expose `hiveSupervisor`).
838
+ * @param {(message: string, error?: unknown) => void} [log] - diagnostics sink.
839
+ * @returns {(sessionId: string, cwd?: string) => boolean} true when a runner accepted the id.
840
+ */
841
+ export function createQueenSessionRegistrar(ctx, log = () => {}) {
842
+ return function registerQueenSession(sessionId, cwd) {
843
+ if (typeof sessionId !== 'string' || sessionId === '') return false
844
+ let runner
845
+ try {
846
+ runner = ctx.get('hiveSupervisor')
847
+ } catch (error) {
848
+ log('hive-runner queen registration lookup failed', error)
849
+ return false
850
+ }
851
+ if (runner === undefined) return false
852
+
853
+ // Repository step: only an initialised repository (queen role file present)
854
+ // is added; addRepo is idempotent, so repeated activations/snapshots are safe.
855
+ if (typeof cwd === 'string' && cwd !== '' && hasQueenRole(cwd)) {
856
+ if (typeof runner.addRepo === 'function') {
857
+ try {
858
+ runner.addRepo(cwd)
859
+ } catch (error) {
860
+ log('hive-runner repository registration failed: ' + cwd, error)
861
+ }
862
+ } else if (typeof runner.hasRepo === 'function' && runner.hasRepo(cwd) !== true) {
863
+ log('hive-runner supervisor does not expose addRepo(); repository not registered: ' + cwd)
864
+ }
865
+ }
866
+
867
+ if (typeof runner.setQueenSession !== 'function') return false
868
+ try {
869
+ runner.setQueenSession(sessionId)
870
+ return true
871
+ } catch (error) {
872
+ log('hive-runner queen registration failed', error)
873
+ return false
874
+ }
875
+ }
876
+ }
877
+
824
878
  /**
825
879
  * Build the transport-independent host bridge: op + payload -> JSON outcome.
826
880
  *
827
881
  * @param {object} ctx - host Cordis context carrying
828
882
  * connection/sessions/workingDirectory/shell (+ optional sandboxPolicy/sessionPersistence).
829
- * @param {{ writable?: boolean, autoQueen?: boolean, bins?: object, queen?: object, timeoutMs?: number, actionTimeoutMs?: number, log?: Function }} [config]
830
- * `autoQueen` (default true) lets an initialised snapshot mark the Session as queen.
883
+ * @param {{ writable?: boolean, autoQueen?: boolean, bins?: object, queen?: object, registerQueenSession?: Function, timeoutMs?: number, actionTimeoutMs?: number, log?: Function }} [config]
884
+ * `autoQueen` (default true) lets an initialised snapshot mark the Session as queen;
885
+ * `registerQueenSession` registers the queen Session with the Hive supervisor.
831
886
  * @returns {{
832
887
  * snapshot: (sessionId: string, signal?: AbortSignal) => Promise<object>,
833
888
  * actions: (sessionId: string) => Promise<object>,
@@ -1002,31 +1057,10 @@ export function createBridge(ctx, config = {}) {
1002
1057
  }
1003
1058
  }
1004
1059
 
1005
- /**
1006
- * Register the queen Session with the resident Hive runner (when mounted).
1007
- * The runner parents every card worker to exactly this Session; before this
1008
- * registration it waits instead of dispatching. Registration is in-memory and
1009
- * idempotent, so every panel snapshot re-registers after a restart.
1010
- * @param {string} sessionId live Session id of the queen conversation
1011
- */
1012
- function registerQueenSession(sessionId) {
1013
- if (typeof sessionId !== 'string' || sessionId === '') return false
1014
- let runner
1015
- try {
1016
- runner = ctx.get('hiveSupervisor')
1017
- } catch (error) {
1018
- log('hive-runner queen registration lookup failed', error)
1019
- return false
1020
- }
1021
- if (runner === undefined || typeof runner.setQueenSession !== 'function') return false
1022
- try {
1023
- runner.setQueenSession(sessionId)
1024
- return true
1025
- } catch (error) {
1026
- log('hive-runner queen registration failed', error)
1027
- return false
1028
- }
1029
- }
1060
+ /** The prompt auto-injection and the panel paths share one supervisor registrar. */
1061
+ const registerQueenSession = typeof config.registerQueenSession === 'function'
1062
+ ? config.registerQueenSession
1063
+ : createQueenSessionRegistrar(ctx, log)
1030
1064
 
1031
1065
  /**
1032
1066
  * Auto-activate queen mode for an initialised Session before a snapshot is
@@ -1095,7 +1129,7 @@ export function createBridge(ctx, config = {}) {
1095
1129
  const initialised = isHiveInitialised(cwd, refsText)
1096
1130
  if (initialised) autoActivateQueen(sessionId, cwd)
1097
1131
  payload.queen = queenSnapshot(sessionId, cwd)
1098
- if (payload.queen.active) registerQueenSession(sessionId)
1132
+ if (payload.queen.active) registerQueenSession(sessionId, cwd)
1099
1133
  if (!initialised) {
1100
1134
  payload.events = readEvents(cwd)
1101
1135
  return payload
@@ -1160,7 +1194,7 @@ export function createBridge(ctx, config = {}) {
1160
1194
  if (!isHiveInitialised(cwd, refsText)) return false
1161
1195
  try {
1162
1196
  queen.mark({ sessionId, cwd })
1163
- registerQueenSession(sessionId)
1197
+ registerQueenSession(sessionId, cwd)
1164
1198
  return true
1165
1199
  } catch (error) {
1166
1200
  log('queen activation failed', error)
@@ -1180,7 +1214,7 @@ export function createBridge(ctx, config = {}) {
1180
1214
  throw new HiveRequestError('hive/queen-unavailable', 'queen controller is unavailable', 500)
1181
1215
  }
1182
1216
  queen.mark({ sessionId, cwd, source: 'manual' })
1183
- registerQueenSession(sessionId)
1217
+ registerQueenSession(sessionId, cwd)
1184
1218
  return { status: 200, body: { ok: true, code: 0, stdout: '', stderr: '' } }
1185
1219
  }
1186
1220
  if (actionName === QUEEN_OFF_ACTION) {
@@ -1318,13 +1352,22 @@ export function createFetchHandler(bridge) {
1318
1352
  export function apply(ctx, config = {}) {
1319
1353
  const settings = config !== null && typeof config === 'object' ? config : {}
1320
1354
  const log = createLog(ctx)
1321
- const queen = createQueen(ctx, { log })
1355
+ const autoQueen = settings.autoQueen !== false
1356
+ // One registrar for both activation paths: the system-prompt section (works
1357
+ // without the panel open) and the panel snapshot/init actions.
1358
+ const registerQueenSession = createQueenSessionRegistrar(ctx, log)
1359
+ const queen = createQueen(ctx, {
1360
+ log,
1361
+ autoQueen,
1362
+ onAutoActivate: (sessionId, cwd) => { registerQueenSession(sessionId, cwd) },
1363
+ })
1322
1364
  ctx.effect(() => () => { queen.dispose() }, 'hive-panel: queen state')
1323
1365
  const bridge = createBridge(ctx, {
1324
1366
  writable: settings.writable === true,
1325
- autoQueen: settings.autoQueen !== false,
1367
+ autoQueen,
1326
1368
  bins: settings.bins,
1327
1369
  queen,
1370
+ registerQueenSession,
1328
1371
  log,
1329
1372
  timeoutMs: settings.timeoutMs,
1330
1373
  actionTimeoutMs: settings.actionTimeoutMs,
package/lib/queen.js CHANGED
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * dsh-hive-panel — queen activation (host half).
3
3
  *
4
- * Queen mode is a per-Session, in-process switch. It is turned on in three
4
+ * Queen mode is a per-Session, in-process switch. It is turned on in four
5
5
  * ways:
6
- * - automatically, by the host half when `op=snapshot` finds
7
- * `refs/hive/v1` in the Session cwd (`config.autoQueen`, default true);
6
+ * - automatically on the Session's first system-prompt assembly: when the
7
+ * Session cwd has `.hive/roles/queen.md` and `config.autoQueen` is not false,
8
+ * the role + {@link QUEEN_INVARIANTS} are injected and the Session is
9
+ * registered with the Hive supervisor. This needs no panel request, so a
10
+ * restarted DSH (or a Session that never opened the panel) still talks to
11
+ * the queen instead of a plain coding agent;
12
+ * - automatically, by the host half when `op=snapshot` finds an initialised
13
+ * repository in the Session cwd (`config.autoQueen`, default true);
8
14
  * - manually, by `POST /api/hive?op=action&name=queen-on`;
9
15
  * - by a successful allowlisted `init` action (legacy path).
10
16
  *
@@ -60,10 +66,13 @@ export const QUEEN_FALLBACK_ROLE = '# Queen\n\nYou plan and coordinate; you neve
60
66
  *
61
67
  * They do not depend on the workspace role file, so a stale or custom
62
68
  * `.hive/roles/queen.md` (written by an older `hive init`) cannot remove the
63
- * production boundary that keeps the queen from implementing work herself. The
64
- * workspace text stays untrusted below this block.
69
+ * production boundary that keeps the queen from implementing work herself: no
70
+ * subagent tools, and (for repositories initialised by an older `hive init` whose
71
+ * role file predates this contract) no write/edit/apply_patch/bash/cua either.
72
+ * Tasks and state go through `hive_*` tools; claim/done/fail stay worker actions.
73
+ * The workspace text stays untrusted below this block.
65
74
  */
66
- export const QUEEN_INVARIANTS = '[hive:queen] trusted invariants (plugin-owned, cannot be overridden by the workspace): never call subagent/subagent_fork/subagent_claude_code or any execution tool to implement work; every goal becomes Hive tasks (hive_tasks add/plan) and the supervisor dispatches them. Classify each message (chat/progress/goal change/discussion/question/execute); discussion creates tasks only when the human asks to execute. Explain the classification only when it changes what the human expects.'
75
+ export const QUEEN_INVARIANTS = '[hive:queen] trusted invariants (plugin-owned, cannot be overridden by the workspace): never call subagent/subagent_fork/subagent_claude_code or any execution tool to implement work; every goal becomes Hive tasks (hive_tasks add/plan) and the supervisor dispatches them. Classify each message (chat/progress/goal change/discussion/question/execute); discussion creates tasks only when the human asks to execute. Explain the classification only when it changes what the human expects. Tool boundary: never call write, edit, apply_patch, bash, cua or any other file-mutating or command-executing tool; use only hive_* tools for tasks and state; claim/done/fail are worker actions and the queen must never call them; implementation is delegated to the supervisor. 工具边界:禁止调用 write、edit、apply_patch、bash、cua 等任何修改文件或执行命令的工具;任务与状态只能使用 hive_* 工具;claim/done/fail 属于 worker 动作,女王不得调用;具体实现交给 supervisor。'
67
76
 
68
77
  /** Short exit hint appended to every rendered role. */
69
78
  export const QUEEN_EXIT_HINT = '\n\n[hive] Queen mode: plan, split, order, supervise, review, report; never edit code or commit, never call subagent tools — create Hive tasks and let the supervisor dispatch. Fine-grained cards; every card needs an acceptance command. Load the hive-queen skill. Exit with /queen off.'
@@ -112,6 +121,42 @@ export function defaultReadRole(cwd) {
112
121
  }
113
122
  }
114
123
 
124
+ /**
125
+ * Whether a Session cwd carries the queen role file. Prompt-based auto-injection
126
+ * requires it, so a merely initialised repository does not turn every Session
127
+ * into a queen until `hive init` has written the role contract.
128
+ * @param {string} cwd - effective Session working directory.
129
+ * @returns {boolean} true when `<cwd>/.hive/roles/queen.md` exists.
130
+ */
131
+ export function hasQueenRole(cwd) {
132
+ if (typeof cwd !== 'string' || cwd === '') return false
133
+ try {
134
+ return fs.existsSync(path.join(cwd, QUEEN_ROLE_PATH))
135
+ } catch {
136
+ return false
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Whether a Session may become the queen automatically.
142
+ *
143
+ * Subagent Sessions (card workers, delegated children) share the repository cwd
144
+ * with their parent. Auto-queening them would inject the queen contract into a
145
+ * worker and overwrite the supervisor's queen registration, so only top-level
146
+ * Sessions qualify. `SessionHeader.origin === 'subagent'` and a positive
147
+ * `delegationDepth` are the durable markers.
148
+ *
149
+ * @param {object} session - DSH Session (or a test stub).
150
+ * @returns {boolean} false only for known subagent Sessions.
151
+ */
152
+ export function isTopLevelSession(session) {
153
+ const header = session !== null && typeof session === 'object' ? session.header : undefined
154
+ if (header === null || typeof header !== 'object') return true
155
+ if (header.origin === 'subagent') return false
156
+ if (Number.isSafeInteger(header.delegationDepth) && header.delegationDepth > 0) return false
157
+ return true
158
+ }
159
+
115
160
  /**
116
161
  * Create the queen controller for one plugin fiber.
117
162
  *
@@ -119,6 +164,12 @@ export function defaultReadRole(cwd) {
119
164
  * Session), the `/queen` slash command, and the `agent/disposed` cleanup.
120
165
  *
121
166
  * Controller semantics:
167
+ * - prompt auto-injection: the `hive:queen` section evaluates every assembly
168
+ * with the Session's `agent`; while the Session is neither active nor
169
+ * suppressed and `autoQueen` is true, a cwd that has
170
+ * `.hive/roles/queen.md` is auto-marked (source `auto`) and
171
+ * `onAutoActivate(sessionId, cwd)` runs — this is where the host half
172
+ * registers the Session with the Hive supervisor;
122
173
  * - `autoMark({sessionId, cwd})` — snapshot auto-activation: no-op (not a
123
174
  * rewrite) when already active, returns false when the Session was
124
175
  * explicitly closed or is already active, marks with source `auto` otherwise;
@@ -126,11 +177,18 @@ export function defaultReadRole(cwd) {
126
177
  * `init`, `/queen on`); always re-reads the role file and clears the
127
178
  * explicit-off suppression;
128
179
  * - `disable(sessionId)` — explicit exit (`queen-off`, `/queen off`);
129
- * idempotent and suppresses future auto-activation;
180
+ * idempotent and suppresses prompt/snapshot auto-activation;
130
181
  * - `snapshotFor(sessionId)` — `{ active, source }` for the snapshot field.
131
182
  *
132
- * @param {object} ctx - host Cordis context (systemPrompt/commands/on).
133
- * @param {{ readRole?: typeof defaultReadRole, maxChars?: number, log?: (message: string, error?: unknown) => void }} [options]
183
+ * @param {object} ctx - host Cordis context (systemPrompt/commands/on/workingDirectory).
184
+ * @param {{
185
+ * readRole?: typeof defaultReadRole,
186
+ * hasRole?: typeof hasQueenRole,
187
+ * maxChars?: number,
188
+ * autoQueen?: boolean,
189
+ * onAutoActivate?: (sessionId: string, cwd: string) => void,
190
+ * log?: (message: string, error?: unknown) => void
191
+ * }} [options]
134
192
  * @returns {{
135
193
  * mark: Function, autoMark: Function, disable: Function, clear: Function,
136
194
  * has: Function, snapshotFor: Function, textFor: Function, size: Function, dispose: Function
@@ -138,7 +196,10 @@ export function defaultReadRole(cwd) {
138
196
  */
139
197
  export function createQueen(ctx, options = {}) {
140
198
  const readRole = typeof options.readRole === 'function' ? options.readRole : defaultReadRole
199
+ const hasRole = typeof options.hasRole === 'function' ? options.hasRole : hasQueenRole
141
200
  const maxChars = Number.isSafeInteger(options.maxChars) && options.maxChars > 0 ? options.maxChars : QUEEN_MAX_CHARS
201
+ const autoQueen = options.autoQueen !== false
202
+ const onAutoActivate = typeof options.onAutoActivate === 'function' ? options.onAutoActivate : () => {}
142
203
  const log = typeof options.log === 'function' ? options.log : () => {}
143
204
  /** @type {Map<string, { text: string, source: 'auto' | 'manual' }>} SessionId -> rendered role text. */
144
205
  const roles = new Map()
@@ -179,11 +240,34 @@ export function createQueen(ctx, options = {}) {
179
240
  name: QUEEN_SECTION,
180
241
  order: QUEEN_ORDER,
181
242
  // Re-evaluated on every assembly; only the marked Session renders text.
243
+ // While inactive this is also the panel-independent auto-activation point:
244
+ // the first assembly of a Session whose cwd has .hive/roles/queen.md
245
+ // injects the role without any browser request.
182
246
  text: ({ agent }) => {
183
247
  if (agent === undefined) return ''
184
248
  const sessionId = agent.session?.id
185
249
  if (typeof sessionId !== 'string') return ''
186
- return roles.get(sessionId)?.text ?? ''
250
+ const active = roles.get(sessionId)
251
+ if (active !== undefined) return active.text
252
+ if (!autoQueen || suppressed.has(sessionId)) return ''
253
+ // A card worker / delegated child shares the repo cwd but must never
254
+ // become the queen (and must never overwrite the supervisor's queen id).
255
+ if (!isTopLevelSession(agent.session)) return ''
256
+ let cwd
257
+ try {
258
+ cwd = ctx.workingDirectory?.get?.(agent.session)
259
+ } catch (error) {
260
+ log('queen: cannot resolve the Session working directory', error)
261
+ return ''
262
+ }
263
+ if (typeof cwd !== 'string' || cwd === '' || !hasRole(cwd)) return ''
264
+ const text = setRole(sessionId, cwd, QUEEN_SOURCE_AUTO)
265
+ try {
266
+ onAutoActivate(sessionId, cwd)
267
+ } catch (error) {
268
+ log('queen: auto-activation hook failed', error)
269
+ }
270
+ return text
187
271
  },
188
272
  }), 'hive-panel: queen system-prompt section')
189
273
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-panel",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Hive board and queen mode inside DSH Web: a conversation view scoped to the Session's repository, with allowlisted task-card actions over DSH's shell seam.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -294,12 +294,14 @@ function createCtx(options = {}) {
294
294
  },
295
295
  }
296
296
  const sessionPersistence = stored.size === 0 ? undefined : { async stat(id) { return stored.get(id) } }
297
+ const supervisor = options.supervisor
297
298
  const ctx = {
298
299
  effect(run) { const dispose = run(); effects.push(dispose); return dispose },
299
300
  get(name) {
300
301
  if (name === 'shell') return shell
301
302
  if (name === 'sandboxPolicy') return sandboxPolicy
302
303
  if (name === 'sessionPersistence') return sessionPersistence
304
+ if (name === 'hiveSupervisor') return supervisor
303
305
  return undefined
304
306
  },
305
307
  sessions: { get(id) { return live.get(id) } },
@@ -912,6 +914,142 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
912
914
  ok('without ctx.shell the plugin refuses to mount (no child_process fallback)')
913
915
  }
914
916
 
917
+ // ── 11b. prompt auto-injection works without the panel ─────────────────────
918
+ {
919
+ const calls = []
920
+ const repos = []
921
+ const removals = []
922
+ const supervisor = {
923
+ setQueenSession(sessionId) { calls.push(sessionId) },
924
+ addRepo(repo) { if (!repos.includes(repo)) repos.push(repo); return { repo } },
925
+ hasRepo(repo) { return repos.includes(repo) },
926
+ removeRepo(repo) { removals.push(repo) },
927
+ }
928
+ const shim = createCtx({
929
+ live: new Map([
930
+ ['s-auto', { id: 's-auto', header: { id: 's-auto', cwd: repo } }],
931
+ ['s-plain', { id: 's-plain', header: { id: 's-plain', cwd: other } }],
932
+ ['s-worker', { id: 's-worker', header: { id: 's-worker', cwd: repo, origin: 'subagent', delegationDepth: 1 } }],
933
+ ]),
934
+ cwdOf: session => (session.id === 's-plain' ? other : repo),
935
+ // Keep the repos uninitialised at the snapshot layer so this test observes
936
+ // the prompt auto-injection path, not the panel snapshot auto-activation.
937
+ shell: spec => (spec.command.includes("'for-each-ref'") ? { exitCode: 0, stdout: '' } : defaultShellResult(spec)),
938
+ supervisor,
939
+ })
940
+ host.apply(shim.ctx, {})
941
+ const section = shim.sections.find(entry => entry.name === 'hive:queen')
942
+ const autoAgent = { session: { id: 's-auto' } }
943
+ const plainAgent = { session: { id: 's-plain' } }
944
+
945
+ // No panel/snapshot request happened: the very first assembly injects.
946
+ const text = section.text({ agent: autoAgent })
947
+ assert.match(text, /You plan and coordinate; you never write code/)
948
+ assert.ok(text.includes(join(repo, '.hive', 'roles', 'queen.md')), 'the auto-injected text must name its role file')
949
+ assert.ok(text.includes('[hive:queen] trusted invariants'), 'prompt auto-injection must carry the trusted invariants')
950
+ assert.deepEqual(calls, ['s-auto'], 'prompt auto-injection must register the queen Session with the supervisor')
951
+ assert.deepEqual(repos, [repo], 'prompt auto-injection must register the queen repository with the supervisor')
952
+ assert.equal(section.text({ agent: autoAgent }), text, 'repeat assemblies reuse the same injection')
953
+ assert.deepEqual(calls, ['s-auto'], 'the supervisor registration must be idempotent')
954
+ assert.deepEqual(repos, [repo], 'the supervisor repository registration must be deduplicated')
955
+ assert.equal(section.text({ agent: plainAgent }), '', 'a Session whose cwd has no queen role file must not be injected')
956
+ assert.deepEqual(calls, ['s-auto'], 'a Session in another repository is never registered')
957
+ assert.deepEqual(repos, [repo], 'an uninitialised repository is never registered as a supervisor repo')
958
+ // Card workers / delegated children share the repo cwd but must never be queens.
959
+ const workerAgent = { session: { id: 's-worker', header: { id: 's-worker', cwd: repo, origin: 'subagent', delegationDepth: 1 } } }
960
+ assert.equal(section.text({ agent: workerAgent }), '', 'a subagent Session must never be auto-queened')
961
+ assert.deepEqual(calls, ['s-auto'], 'a subagent Session must never overwrite the supervisor queen registration')
962
+
963
+ // The panel still sees the state through the normal snapshot field.
964
+ const snap = await call(shim.routes.get('/api/hive'), { query: { op: 'snapshot', sessionId: 's-auto' } })
965
+ assert.deepEqual(snap.body.queen, { active: true, source: 'auto', repo })
966
+ const plainSnap = await call(shim.routes.get('/api/hive'), { query: { op: 'snapshot', sessionId: 's-plain' } })
967
+ assert.deepEqual(plainSnap.body.queen, { active: false, source: null, repo: other })
968
+ assert.deepEqual(repos, [repo], 'the snapshot path must not register an uninitialised repository either')
969
+ assert.deepEqual(removals, [], 'no path may remove a repository registration')
970
+ ok('the first system-prompt assembly auto-injects the queen and registers the repo + supervisor, without a panel request')
971
+ }
972
+
973
+ // ── 11c. prompt auto-injection respects /queen off, autoQueen and init state ──
974
+ {
975
+ // /queen off suppresses prompt auto-injection for that Session only.
976
+ const shim = createCtx({ live, cwdOf })
977
+ host.apply(shim.ctx, {})
978
+ const section = shim.sections.find(entry => entry.name === 'hive:queen')
979
+ const agent = { session: { id: 's-live' } }
980
+ assert.match(section.text({ agent }), /You plan and coordinate/)
981
+ const off = shim.commands.get('queen').handler({ agent, rawInput: ' off ', signal: {}, attachments: [], commandId: 'cmd-off' })
982
+ assert.equal(off.kind, 'success')
983
+ assert.equal(section.text({ agent }), '', '/queen off must stop prompt auto-injection')
984
+ assert.equal(section.text({ agent }), '', 'the explicit-off suppression must stick across assemblies')
985
+
986
+ // autoQueen=false disables prompt auto-injection entirely; manual /queen on still works.
987
+ const offShim = createCtx({ live, cwdOf })
988
+ host.apply(offShim.ctx, { autoQueen: false })
989
+ const offSection = offShim.sections.find(entry => entry.name === 'hive:queen')
990
+ assert.equal(offSection.text({ agent }), '', 'autoQueen=false must not inject a queen')
991
+ const manual = offShim.commands.get('queen').handler({ agent, rawInput: ' on ', signal: {}, attachments: [], commandId: 'cmd-on' })
992
+ assert.equal(manual.kind, 'success')
993
+ assert.match(offSection.text({ agent }), /You plan and coordinate/, 'manual /queen on still activates with autoQueen=false')
994
+
995
+ // An uninitialised repository has no .hive/roles/queen.md and is never injected.
996
+ const plainShim = createCtx({
997
+ live: new Map([['s-plain', { id: 's-plain', header: { id: 's-plain', cwd: other } }]]),
998
+ cwdOf: () => other,
999
+ })
1000
+ host.apply(plainShim.ctx, {})
1001
+ const plainSection = plainShim.sections.find(entry => entry.name === 'hive:queen')
1002
+ assert.equal(plainSection.text({ agent: { session: { id: 's-plain' } } }), '', 'an uninitialised repo must not inject a queen')
1003
+ ok('prompt auto-injection honours /queen off, autoQueen=false and uninitialised repositories')
1004
+ }
1005
+
1006
+ // ── 11d. panel init/queen-on register the queen repo with the supervisor ───
1007
+ {
1008
+ const repos = []
1009
+ const removals = []
1010
+ const sessions = []
1011
+ const supervisor = {
1012
+ addRepo(repo) { if (!repos.includes(repo)) repos.push(repo); return { repo } },
1013
+ hasRepo(repo) { return repos.includes(repo) },
1014
+ removeRepo(repo) { removals.push(repo) },
1015
+ setQueenSession(sessionId) { sessions.push(sessionId) },
1016
+ }
1017
+ const shim = createCtx({
1018
+ live: new Map([
1019
+ ['s-live', { id: 's-live', header: { id: 's-live', cwd: repo } }],
1020
+ ['s-other', { id: 's-other', header: { id: 's-other', cwd: other } }],
1021
+ ]),
1022
+ cwdOf,
1023
+ supervisor,
1024
+ })
1025
+ host.apply(shim.ctx, { writable: true })
1026
+ const route = shim.routes.get('/api/hive')
1027
+
1028
+ const init = await call(route, { method: 'POST', query: { op: 'action', name: 'init', sessionId: 's-live' }, body: {} })
1029
+ assert.equal(init.status, 200)
1030
+ assert.equal(init.body.ok, true)
1031
+ assert.deepEqual(repos, [repo], 'the init action must register the queen cwd with the supervisor')
1032
+ assert.deepEqual(sessions, ['s-live'], 'the init action must also register the queen Session')
1033
+
1034
+ // Repeated activation (queen-on + snapshot) is deduplicated by the supervisor.
1035
+ await call(route, { method: 'POST', query: { op: 'action', name: 'queen-on', sessionId: 's-live' }, body: {} })
1036
+ await call(route, { query: { op: 'snapshot', sessionId: 's-live' } })
1037
+ assert.deepEqual(repos, [repo], 're-registering the same repo must stay a single entry')
1038
+
1039
+ // Only repositories with .hive/roles/queen.md are registered.
1040
+ const otherOn = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-on', sessionId: 's-other' }, body: {} })
1041
+ assert.equal(otherOn.status, 200)
1042
+ assert.deepEqual(repos, [repo], 'an uninitialised repository must never be added to the supervisor')
1043
+ assert.deepEqual([...new Set(sessions)], ['s-live', 's-other'], 'the fallback queen Session still registers itself (idempotent at the supervisor)')
1044
+
1045
+ // Leaving queen mode never removes the repository registration (one-way).
1046
+ await call(route, { method: 'POST', query: { op: 'action', name: 'queen-off', sessionId: 's-live' }, body: {} })
1047
+ await call(route, { query: { op: 'snapshot', sessionId: 's-live' } })
1048
+ assert.deepEqual(repos, [repo], 'queen-off must not drop the repository registration')
1049
+ assert.deepEqual(removals, [], 'the panel must never call removeRepo on exit/unload')
1050
+ ok('panel init/queen-on register the queen cwd with the supervisor (idempotent, initialised repos only, one-way)')
1051
+ }
1052
+
915
1053
  // ── 12. queen activation / scope / exit ─────────────────────────────────────
916
1054
  {
917
1055
  const shim = createCtx({
@@ -935,7 +1073,9 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
935
1073
  assert.ok(queenModule.QUEEN_EXIT_HINT.includes('never call subagent tools'), 'the exit hint must repeat the implementation ban')
936
1074
  const agent = { session: { id: 's-live' } }
937
1075
  const otherAgent = { session: { id: 's-other' } }
938
- assert.equal(queenSection.text({ agent }), '')
1076
+ // The cwd has .hive/roles/queen.md, so the first assembly auto-injects (12a);
1077
+ // init keeps the Session queen and remains idempotent.
1078
+ assert.match(queenSection.text({ agent }), /You plan and coordinate/)
939
1079
  const init = await call(route, { method: 'POST', query: { op: 'action', name: 'init', sessionId: 's-live' }, body: {} })
940
1080
  assert.equal(init.status, 200)
941
1081
  assert.equal(init.body.ok, true)
@@ -946,6 +1086,17 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
946
1086
  assert.ok(text.length <= 24576, 'the role text must be capped at 24576 characters')
947
1087
  assert.ok(text.includes('[hive:queen] trusted invariants'), 'the trusted invariants block must be injected')
948
1088
  assert.match(text, /never call subagent/, 'the trusted invariants must forbid subagent implementation')
1089
+ // Tool boundary: an old repository whose role file predates this contract must
1090
+ // still be forbidden from mutating files or running commands.
1091
+ for (const keyword of ['write', 'edit', 'apply_patch', 'bash', 'cua']) {
1092
+ assert.ok(queenModule.QUEEN_INVARIANTS.includes(keyword), 'QUEEN_INVARIANTS must ban ' + keyword)
1093
+ assert.ok(text.includes(keyword), 'the injected queen text must ban ' + keyword)
1094
+ }
1095
+ assert.ok(queenModule.QUEEN_INVARIANTS.includes('claim'), 'QUEEN_INVARIANTS must reserve claim/done/fail for workers')
1096
+ assert.ok(text.includes('claim/done/fail are worker actions'), 'the injected text must say claim/done/fail are worker actions')
1097
+ assert.ok(text.includes('hive_*'), 'the injected text must route tasks and state through hive_* tools')
1098
+ assert.ok(text.includes('工具边界'), 'the injected invariants must carry the Chinese tool-boundary line')
1099
+ assert.ok(text.includes('never call write, edit, apply_patch, bash, cua'), 'the English tool-boundary sentence must be injected')
949
1100
  assert.ok(text.indexOf('trusted invariants') < text.indexOf('Exit with /queen off.'), 'invariants come before the exit hint')
950
1101
  assert.ok(text.includes('Fine-grained cards; every card needs an acceptance command.'), 'the exit hint must carry the coordinator contract')
951
1102
  assert.ok(text.includes('Exit with /queen off.'), 'the exit hint must name /queen off')
@@ -972,6 +1123,7 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
972
1123
  assert.match(fallbackText, /Load the hive-queen skill/)
973
1124
  assert.ok(fallbackText.length <= 24576)
974
1125
  assert.ok(fallbackText.includes('[hive:queen] trusted invariants'), 'the fallback path must keep the trusted invariants')
1126
+ ok('the trusted invariants ban file/command tools (write/edit/apply_patch/bash/cua, claim) and route state through hive_* tools')
975
1127
  ok('init + refs/hive/v1 marks only that Session; /queen off and name=queen-off both clear it; a missing role file uses the coordinator fallback')
976
1128
  }
977
1129
 
@@ -1003,7 +1155,9 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
1003
1155
  const agent = { session: { id: 's-live' } }
1004
1156
  const snapshot = () => call(route, { query: { op: 'snapshot', sessionId: 's-live' } })
1005
1157
 
1006
- assert.equal(section.text({ agent }), '')
1158
+ // The prompt section auto-injects before any panel request (12a); the
1159
+ // snapshot still reports the same auto source.
1160
+ assert.match(section.text({ agent }), /You plan and coordinate/)
1007
1161
  const first = await snapshot()
1008
1162
  assert.equal(first.status, 200)
1009
1163
  assert.deepEqual(first.body.queen, { active: true, source: 'auto', repo })