dsh-hive-panel 1.0.3 → 1.0.4

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,27 @@ 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.4] - 2026-12-05
8
+
9
+ ### Fixed
10
+
11
+ - **Queen mode no longer depends on the panel being opened.** The `hive:queen`
12
+ system-prompt section is rendered on the first prompt assembly for any Session whose
13
+ working directory is an initialised Hive repository: it resolves the Session cwd,
14
+ registers the queen Session id with the resident `dsh-hive-runner` supervisor and
15
+ injects the trusted invariants + workspace role there. Subagent Sessions (workers) are
16
+ excluded, an earlier `/queen off` keeps the Session suppressed, and the panel only
17
+ mirrors the state instead of owning it.
18
+ - The injected text still reads `<cwd>/.hive/roles/queen.md` as untrusted workspace
19
+ input below the plugin-owned invariants; the 24576-character role cap and the fallback
20
+ role are unchanged.
21
+
22
+ ### Tests
23
+
24
+ - 39 checks cover cwd-based auto-injection with the panel never opened, supervisor
25
+ registration, subagent exclusion, `/queen off` suppression and the unchanged
26
+ invariants / role cap paths.
27
+
7
28
  ## [1.0.3] - 2026-12-05
8
29
 
9
30
  ### Fixed
@@ -18,6 +39,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
18
39
  - The budget calculation counts the invariants block; the role cap stays 24576 and the
19
40
  truncation marker still applies to the workspace body.
20
41
 
42
+ ### Published
43
+
44
+ - npm: `dsh-hive-panel@1.0.3` on 2026-12-05.
45
+
21
46
  ## [1.0.2] - 2026-12-05
22
47
 
23
48
  ### Fixed
package/README.md CHANGED
@@ -39,7 +39,7 @@ 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) |
@@ -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
 
package/SPEC.md CHANGED
@@ -302,34 +302,48 @@ 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
+ Injection: a system-prompt section `hive:queen` (order 520) evaluated on each prompt
344
+ assembly with the Session's `agent`; it auto-activates from the agent's cwd on the first
345
+ assembly (see Activation 1), renders role + invariants for the marked Session and an empty
346
+ string for every other Session. It does not enter the conversation history.
333
347
 
334
348
  Role text: `<cwd>/.hive/roles/queen.md`, prefixed with an "untrusted role file" label
335
349
  naming the absolute source path, capped at 24576 characters and marked `[truncated]`
package/docs/DESIGN.md CHANGED
@@ -287,7 +287,16 @@ 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**,不同仓库互不影响。subagent 会话
297
+ (`session.header.origin === 'subagent'` 或 `delegationDepth > 0`)被排除:卡 worker 与父会话
298
+ 共享仓库 cwd,若自动注入会污染 worker 并把 supervisor 的 queen 登记顶掉。
299
+ - **面板触发的自动标记**:`op=snapshot` 返回前已经跑过 `refs/hive/v1` 探针;若仓库已初始化、
291
300
  `config.autoQueen !== false` 且该 Session 没有被显式关闭,则调用
292
301
  `queen.autoMark({ sessionId, cwd })`。`autoMark` 幂等:已激活的 Session 不重读/重写角色文件,
293
302
  被显式关闭的 Session 直接跳过。这样在 CLI 里已经 `hive init` 过的仓库(如 queen-sandbox)
@@ -424,7 +433,7 @@ npm run check
424
433
  # ok - node --check lib/queen.js
425
434
  # ok - node --check lib/client.js
426
435
  # ...
427
- # 37 checks passed
436
+ # 39 checks passed
428
437
  ```
429
438
 
430
439
  覆盖:语法、package/bundle 声明、无代理残留、client bundle 的 `/api/hive` URL 与 Session 注入、
@@ -436,7 +445,9 @@ Connection Fetch 路由注册、快照走 `ctx.shell` 且 cwd/policy 正确、
436
445
  `roles` 快照(角色列表 + 持久限额)、`roles-add`(含 description)的参数校验/argv/仓库 cwd、
437
446
  重复角色的 CLI stderr 透传、`roles-remove` 的 argv/非法名/只读 403/CLI 失败透传,以及 `remove` 的卡片 id 校验;
438
447
  另有 `initialised` 只靠 `.hive/roles.yaml`/`.hive/config.json` 即为 true、init 动作后立即 true、
439
- 两者与 ref 都无才为 false,以及 client bundle 的 init 成功即时切面检查。
448
+ 两者与 ref 都无才为 false,以及 client bundle 的 init 成功即时切面检查;prompt 首次组装自动注入
449
+ (含 `QUEEN_INVARIANTS`、supervisor 幂等登记、跨仓库隔离)、`/queen off` 后不注入、
450
+ `autoQueen=false` 不注入、未初始化仓库不注入。
440
451
 
441
452
  不启动、不重启任何 DSH 进程,也不写运行中的 `~/.dsh`。
442
453
 
package/lib/index.js CHANGED
@@ -821,13 +821,46 @@ 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. The runner parents every card worker to exactly this Session; before
827
+ * the registration it waits instead of dispatching. Registration is in-memory
828
+ * and idempotent, so the prompt auto-injection and every panel snapshot may
829
+ * re-register safely after a restart.
830
+ *
831
+ * @param {object} ctx - host Cordis context (may expose `hiveSupervisor`).
832
+ * @param {(message: string, error?: unknown) => void} [log] - diagnostics sink.
833
+ * @returns {(sessionId: string) => boolean} true when a runner accepted the id.
834
+ */
835
+ export function createQueenSessionRegistrar(ctx, log = () => {}) {
836
+ return function registerQueenSession(sessionId) {
837
+ if (typeof sessionId !== 'string' || sessionId === '') return false
838
+ let runner
839
+ try {
840
+ runner = ctx.get('hiveSupervisor')
841
+ } catch (error) {
842
+ log('hive-runner queen registration lookup failed', error)
843
+ return false
844
+ }
845
+ if (runner === undefined || typeof runner.setQueenSession !== 'function') return false
846
+ try {
847
+ runner.setQueenSession(sessionId)
848
+ return true
849
+ } catch (error) {
850
+ log('hive-runner queen registration failed', error)
851
+ return false
852
+ }
853
+ }
854
+ }
855
+
824
856
  /**
825
857
  * Build the transport-independent host bridge: op + payload -> JSON outcome.
826
858
  *
827
859
  * @param {object} ctx - host Cordis context carrying
828
860
  * 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.
861
+ * @param {{ writable?: boolean, autoQueen?: boolean, bins?: object, queen?: object, registerQueenSession?: Function, timeoutMs?: number, actionTimeoutMs?: number, log?: Function }} [config]
862
+ * `autoQueen` (default true) lets an initialised snapshot mark the Session as queen;
863
+ * `registerQueenSession` registers the queen Session with the Hive supervisor.
831
864
  * @returns {{
832
865
  * snapshot: (sessionId: string, signal?: AbortSignal) => Promise<object>,
833
866
  * actions: (sessionId: string) => Promise<object>,
@@ -1002,31 +1035,10 @@ export function createBridge(ctx, config = {}) {
1002
1035
  }
1003
1036
  }
1004
1037
 
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
- }
1038
+ /** The prompt auto-injection and the panel paths share one supervisor registrar. */
1039
+ const registerQueenSession = typeof config.registerQueenSession === 'function'
1040
+ ? config.registerQueenSession
1041
+ : createQueenSessionRegistrar(ctx, log)
1030
1042
 
1031
1043
  /**
1032
1044
  * Auto-activate queen mode for an initialised Session before a snapshot is
@@ -1318,13 +1330,22 @@ export function createFetchHandler(bridge) {
1318
1330
  export function apply(ctx, config = {}) {
1319
1331
  const settings = config !== null && typeof config === 'object' ? config : {}
1320
1332
  const log = createLog(ctx)
1321
- const queen = createQueen(ctx, { log })
1333
+ const autoQueen = settings.autoQueen !== false
1334
+ // One registrar for both activation paths: the system-prompt section (works
1335
+ // without the panel open) and the panel snapshot/init actions.
1336
+ const registerQueenSession = createQueenSessionRegistrar(ctx, log)
1337
+ const queen = createQueen(ctx, {
1338
+ log,
1339
+ autoQueen,
1340
+ onAutoActivate: (sessionId) => { registerQueenSession(sessionId) },
1341
+ })
1322
1342
  ctx.effect(() => () => { queen.dispose() }, 'hive-panel: queen state')
1323
1343
  const bridge = createBridge(ctx, {
1324
1344
  writable: settings.writable === true,
1325
- autoQueen: settings.autoQueen !== false,
1345
+ autoQueen,
1326
1346
  bins: settings.bins,
1327
1347
  queen,
1348
+ registerQueenSession,
1328
1349
  log,
1329
1350
  timeoutMs: settings.timeoutMs,
1330
1351
  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
  *
@@ -112,6 +118,42 @@ export function defaultReadRole(cwd) {
112
118
  }
113
119
  }
114
120
 
121
+ /**
122
+ * Whether a Session cwd carries the queen role file. Prompt-based auto-injection
123
+ * requires it, so a merely initialised repository does not turn every Session
124
+ * into a queen until `hive init` has written the role contract.
125
+ * @param {string} cwd - effective Session working directory.
126
+ * @returns {boolean} true when `<cwd>/.hive/roles/queen.md` exists.
127
+ */
128
+ export function hasQueenRole(cwd) {
129
+ if (typeof cwd !== 'string' || cwd === '') return false
130
+ try {
131
+ return fs.existsSync(path.join(cwd, QUEEN_ROLE_PATH))
132
+ } catch {
133
+ return false
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Whether a Session may become the queen automatically.
139
+ *
140
+ * Subagent Sessions (card workers, delegated children) share the repository cwd
141
+ * with their parent. Auto-queening them would inject the queen contract into a
142
+ * worker and overwrite the supervisor's queen registration, so only top-level
143
+ * Sessions qualify. `SessionHeader.origin === 'subagent'` and a positive
144
+ * `delegationDepth` are the durable markers.
145
+ *
146
+ * @param {object} session - DSH Session (or a test stub).
147
+ * @returns {boolean} false only for known subagent Sessions.
148
+ */
149
+ export function isTopLevelSession(session) {
150
+ const header = session !== null && typeof session === 'object' ? session.header : undefined
151
+ if (header === null || typeof header !== 'object') return true
152
+ if (header.origin === 'subagent') return false
153
+ if (Number.isSafeInteger(header.delegationDepth) && header.delegationDepth > 0) return false
154
+ return true
155
+ }
156
+
115
157
  /**
116
158
  * Create the queen controller for one plugin fiber.
117
159
  *
@@ -119,6 +161,12 @@ export function defaultReadRole(cwd) {
119
161
  * Session), the `/queen` slash command, and the `agent/disposed` cleanup.
120
162
  *
121
163
  * Controller semantics:
164
+ * - prompt auto-injection: the `hive:queen` section evaluates every assembly
165
+ * with the Session's `agent`; while the Session is neither active nor
166
+ * suppressed and `autoQueen` is true, a cwd that has
167
+ * `.hive/roles/queen.md` is auto-marked (source `auto`) and
168
+ * `onAutoActivate(sessionId, cwd)` runs — this is where the host half
169
+ * registers the Session with the Hive supervisor;
122
170
  * - `autoMark({sessionId, cwd})` — snapshot auto-activation: no-op (not a
123
171
  * rewrite) when already active, returns false when the Session was
124
172
  * explicitly closed or is already active, marks with source `auto` otherwise;
@@ -126,11 +174,18 @@ export function defaultReadRole(cwd) {
126
174
  * `init`, `/queen on`); always re-reads the role file and clears the
127
175
  * explicit-off suppression;
128
176
  * - `disable(sessionId)` — explicit exit (`queen-off`, `/queen off`);
129
- * idempotent and suppresses future auto-activation;
177
+ * idempotent and suppresses prompt/snapshot auto-activation;
130
178
  * - `snapshotFor(sessionId)` — `{ active, source }` for the snapshot field.
131
179
  *
132
- * @param {object} ctx - host Cordis context (systemPrompt/commands/on).
133
- * @param {{ readRole?: typeof defaultReadRole, maxChars?: number, log?: (message: string, error?: unknown) => void }} [options]
180
+ * @param {object} ctx - host Cordis context (systemPrompt/commands/on/workingDirectory).
181
+ * @param {{
182
+ * readRole?: typeof defaultReadRole,
183
+ * hasRole?: typeof hasQueenRole,
184
+ * maxChars?: number,
185
+ * autoQueen?: boolean,
186
+ * onAutoActivate?: (sessionId: string, cwd: string) => void,
187
+ * log?: (message: string, error?: unknown) => void
188
+ * }} [options]
134
189
  * @returns {{
135
190
  * mark: Function, autoMark: Function, disable: Function, clear: Function,
136
191
  * has: Function, snapshotFor: Function, textFor: Function, size: Function, dispose: Function
@@ -138,7 +193,10 @@ export function defaultReadRole(cwd) {
138
193
  */
139
194
  export function createQueen(ctx, options = {}) {
140
195
  const readRole = typeof options.readRole === 'function' ? options.readRole : defaultReadRole
196
+ const hasRole = typeof options.hasRole === 'function' ? options.hasRole : hasQueenRole
141
197
  const maxChars = Number.isSafeInteger(options.maxChars) && options.maxChars > 0 ? options.maxChars : QUEEN_MAX_CHARS
198
+ const autoQueen = options.autoQueen !== false
199
+ const onAutoActivate = typeof options.onAutoActivate === 'function' ? options.onAutoActivate : () => {}
142
200
  const log = typeof options.log === 'function' ? options.log : () => {}
143
201
  /** @type {Map<string, { text: string, source: 'auto' | 'manual' }>} SessionId -> rendered role text. */
144
202
  const roles = new Map()
@@ -179,11 +237,34 @@ export function createQueen(ctx, options = {}) {
179
237
  name: QUEEN_SECTION,
180
238
  order: QUEEN_ORDER,
181
239
  // Re-evaluated on every assembly; only the marked Session renders text.
240
+ // While inactive this is also the panel-independent auto-activation point:
241
+ // the first assembly of a Session whose cwd has .hive/roles/queen.md
242
+ // injects the role without any browser request.
182
243
  text: ({ agent }) => {
183
244
  if (agent === undefined) return ''
184
245
  const sessionId = agent.session?.id
185
246
  if (typeof sessionId !== 'string') return ''
186
- return roles.get(sessionId)?.text ?? ''
247
+ const active = roles.get(sessionId)
248
+ if (active !== undefined) return active.text
249
+ if (!autoQueen || suppressed.has(sessionId)) return ''
250
+ // A card worker / delegated child shares the repo cwd but must never
251
+ // become the queen (and must never overwrite the supervisor's queen id).
252
+ if (!isTopLevelSession(agent.session)) return ''
253
+ let cwd
254
+ try {
255
+ cwd = ctx.workingDirectory?.get?.(agent.session)
256
+ } catch (error) {
257
+ log('queen: cannot resolve the Session working directory', error)
258
+ return ''
259
+ }
260
+ if (typeof cwd !== 'string' || cwd === '' || !hasRole(cwd)) return ''
261
+ const text = setRole(sessionId, cwd, QUEEN_SOURCE_AUTO)
262
+ try {
263
+ onAutoActivate(sessionId, cwd)
264
+ } catch (error) {
265
+ log('queen: auto-activation hook failed', error)
266
+ }
267
+ return text
187
268
  },
188
269
  }), 'hive-panel: queen system-prompt section')
189
270
  }
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.4",
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,83 @@ 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 supervisor = { setQueenSession(sessionId) { calls.push(sessionId) } }
921
+ const shim = createCtx({
922
+ live: new Map([
923
+ ['s-auto', { id: 's-auto', header: { id: 's-auto', cwd: repo } }],
924
+ ['s-plain', { id: 's-plain', header: { id: 's-plain', cwd: other } }],
925
+ ['s-worker', { id: 's-worker', header: { id: 's-worker', cwd: repo, origin: 'subagent', delegationDepth: 1 } }],
926
+ ]),
927
+ cwdOf: session => (session.id === 's-plain' ? other : repo),
928
+ // Keep the repos uninitialised at the snapshot layer so this test observes
929
+ // the prompt auto-injection path, not the panel snapshot auto-activation.
930
+ shell: spec => (spec.command.includes("'for-each-ref'") ? { exitCode: 0, stdout: '' } : defaultShellResult(spec)),
931
+ supervisor,
932
+ })
933
+ host.apply(shim.ctx, {})
934
+ const section = shim.sections.find(entry => entry.name === 'hive:queen')
935
+ const autoAgent = { session: { id: 's-auto' } }
936
+ const plainAgent = { session: { id: 's-plain' } }
937
+
938
+ // No panel/snapshot request happened: the very first assembly injects.
939
+ const text = section.text({ agent: autoAgent })
940
+ assert.match(text, /You plan and coordinate; you never write code/)
941
+ assert.ok(text.includes(join(repo, '.hive', 'roles', 'queen.md')), 'the auto-injected text must name its role file')
942
+ assert.ok(text.includes('[hive:queen] trusted invariants'), 'prompt auto-injection must carry the trusted invariants')
943
+ assert.deepEqual(calls, ['s-auto'], 'prompt auto-injection must register the queen Session with the supervisor')
944
+ assert.equal(section.text({ agent: autoAgent }), text, 'repeat assemblies reuse the same injection')
945
+ assert.deepEqual(calls, ['s-auto'], 'the supervisor registration must be idempotent')
946
+ assert.equal(section.text({ agent: plainAgent }), '', 'a Session whose cwd has no queen role file must not be injected')
947
+ assert.deepEqual(calls, ['s-auto'], 'a Session in another repository is never registered')
948
+ // Card workers / delegated children share the repo cwd but must never be queens.
949
+ const workerAgent = { session: { id: 's-worker', header: { id: 's-worker', cwd: repo, origin: 'subagent', delegationDepth: 1 } } }
950
+ assert.equal(section.text({ agent: workerAgent }), '', 'a subagent Session must never be auto-queened')
951
+ assert.deepEqual(calls, ['s-auto'], 'a subagent Session must never overwrite the supervisor queen registration')
952
+
953
+ // The panel still sees the state through the normal snapshot field.
954
+ const snap = await call(shim.routes.get('/api/hive'), { query: { op: 'snapshot', sessionId: 's-auto' } })
955
+ assert.deepEqual(snap.body.queen, { active: true, source: 'auto', repo })
956
+ const plainSnap = await call(shim.routes.get('/api/hive'), { query: { op: 'snapshot', sessionId: 's-plain' } })
957
+ assert.deepEqual(plainSnap.body.queen, { active: false, source: null, repo: other })
958
+ ok('the first system-prompt assembly auto-injects the queen and registers the supervisor, without a panel request')
959
+ }
960
+
961
+ // ── 11c. prompt auto-injection respects /queen off, autoQueen and init state ──
962
+ {
963
+ // /queen off suppresses prompt auto-injection for that Session only.
964
+ const shim = createCtx({ live, cwdOf })
965
+ host.apply(shim.ctx, {})
966
+ const section = shim.sections.find(entry => entry.name === 'hive:queen')
967
+ const agent = { session: { id: 's-live' } }
968
+ assert.match(section.text({ agent }), /You plan and coordinate/)
969
+ const off = shim.commands.get('queen').handler({ agent, rawInput: ' off ', signal: {}, attachments: [], commandId: 'cmd-off' })
970
+ assert.equal(off.kind, 'success')
971
+ assert.equal(section.text({ agent }), '', '/queen off must stop prompt auto-injection')
972
+ assert.equal(section.text({ agent }), '', 'the explicit-off suppression must stick across assemblies')
973
+
974
+ // autoQueen=false disables prompt auto-injection entirely; manual /queen on still works.
975
+ const offShim = createCtx({ live, cwdOf })
976
+ host.apply(offShim.ctx, { autoQueen: false })
977
+ const offSection = offShim.sections.find(entry => entry.name === 'hive:queen')
978
+ assert.equal(offSection.text({ agent }), '', 'autoQueen=false must not inject a queen')
979
+ const manual = offShim.commands.get('queen').handler({ agent, rawInput: ' on ', signal: {}, attachments: [], commandId: 'cmd-on' })
980
+ assert.equal(manual.kind, 'success')
981
+ assert.match(offSection.text({ agent }), /You plan and coordinate/, 'manual /queen on still activates with autoQueen=false')
982
+
983
+ // An uninitialised repository has no .hive/roles/queen.md and is never injected.
984
+ const plainShim = createCtx({
985
+ live: new Map([['s-plain', { id: 's-plain', header: { id: 's-plain', cwd: other } }]]),
986
+ cwdOf: () => other,
987
+ })
988
+ host.apply(plainShim.ctx, {})
989
+ const plainSection = plainShim.sections.find(entry => entry.name === 'hive:queen')
990
+ assert.equal(plainSection.text({ agent: { session: { id: 's-plain' } } }), '', 'an uninitialised repo must not inject a queen')
991
+ ok('prompt auto-injection honours /queen off, autoQueen=false and uninitialised repositories')
992
+ }
993
+
915
994
  // ── 12. queen activation / scope / exit ─────────────────────────────────────
916
995
  {
917
996
  const shim = createCtx({
@@ -935,7 +1014,9 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
935
1014
  assert.ok(queenModule.QUEEN_EXIT_HINT.includes('never call subagent tools'), 'the exit hint must repeat the implementation ban')
936
1015
  const agent = { session: { id: 's-live' } }
937
1016
  const otherAgent = { session: { id: 's-other' } }
938
- assert.equal(queenSection.text({ agent }), '')
1017
+ // The cwd has .hive/roles/queen.md, so the first assembly auto-injects (12a);
1018
+ // init keeps the Session queen and remains idempotent.
1019
+ assert.match(queenSection.text({ agent }), /You plan and coordinate/)
939
1020
  const init = await call(route, { method: 'POST', query: { op: 'action', name: 'init', sessionId: 's-live' }, body: {} })
940
1021
  assert.equal(init.status, 200)
941
1022
  assert.equal(init.body.ok, true)
@@ -1003,7 +1084,9 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
1003
1084
  const agent = { session: { id: 's-live' } }
1004
1085
  const snapshot = () => call(route, { query: { op: 'snapshot', sessionId: 's-live' } })
1005
1086
 
1006
- assert.equal(section.text({ agent }), '')
1087
+ // The prompt section auto-injects before any panel request (12a); the
1088
+ // snapshot still reports the same auto source.
1089
+ assert.match(section.text({ agent }), /You plan and coordinate/)
1007
1090
  const first = await snapshot()
1008
1091
  assert.equal(first.status, 200)
1009
1092
  assert.deepEqual(first.body.queen, { active: true, source: 'auto', repo })