dsh-hive-panel 0.1.0 → 0.1.2

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/lib/queen.js CHANGED
@@ -1,22 +1,29 @@
1
1
  /**
2
2
  * dsh-hive-panel — queen activation (host half).
3
3
  *
4
- * One in-memory mode per Session: after a successful `hive init` the panel
5
- * host half calls {@link createQueen}'s controller, which reads
6
- * `<cwd>/.hive/roles/queen.md` and publishes it as the `hive:queen`
7
- * system-prompt section for that Session only.
4
+ * Queen mode is a per-Session, in-process switch. It is turned on in three
5
+ * ways:
6
+ * - automatically, by the host half when `op=snapshot` finds
7
+ * `refs/hive/v1` in the Session cwd (`config.autoQueen`, default true);
8
+ * - manually, by `POST /api/hive?op=action&name=queen-on`;
9
+ * - by a successful allowlisted `init` action (legacy path).
8
10
  *
9
- * Why a system-prompt section instead of an inbox message: sections are
10
- * re-evaluated on every `ctx.systemPrompt.assemble()` (the next model step
11
- * already sees the text), never enter the durable history, and therefore can
12
- * never be shadowed by compaction. The role text is workspace-controlled and
13
- * therefore LOW-TRUST: it is length-capped and annotated with its source path
14
- * before it reaches the prompt.
11
+ * A Session can leave queen mode with `/queen off`, or
12
+ * `POST /api/hive?op=action&name=queen-off`. That exit is *explicit*: the
13
+ * Session is remembered in `suppressed`, so the snapshot polling loop will
14
+ * not silently turn auto-queen back on. `/queen on` / `name=queen-on`
15
+ * clears the suppression again. Process restart forgets everything
16
+ * (fail-safe) — an initialised repository revives auto-queen on its next
17
+ * snapshot.
15
18
  *
16
- * Scope rules (see docs/QUEEN-ACTIVATION.md):
17
- * - only the Session the user acted in, keyed by `agent.session.id`;
18
- * - process restart forgets everything (fail-safe);
19
- * - `/queen off`, `op=action&name=queen-off`, and `agent/disposed` clear it.
19
+ * The role text is published as the `hive:queen` system-prompt section,
20
+ * evaluated on every `ctx.systemPrompt.assemble()` and returning text only
21
+ * for the marked `agent.session.id`. It never enters the durable session
22
+ * history, so compaction cannot shadow it.
23
+ *
24
+ * The workspace role file is LOW-TRUST: the injected text names its absolute
25
+ * source path, says it is untrusted, and is capped at 4096 characters
26
+ * (annotation included).
20
27
  *
21
28
  * @module dsh-hive-panel/queen
22
29
  */
@@ -35,9 +42,14 @@ export const QUEEN_MAX_CHARS = 4096
35
42
  /** Workspace-relative role file written by `hive init`. */
36
43
  export const QUEEN_ROLE_PATH = path.join('.hive', 'roles', 'queen.md')
37
44
 
38
- /** Panel action name that exits queen mode without a slash command. */
45
+ /** Panel action names that toggle queen mode without a slash command. */
46
+ export const QUEEN_ON_ACTION = 'queen-on'
39
47
  export const QUEEN_OFF_ACTION = 'queen-off'
40
48
 
49
+ /** Stable provenance values reported in the snapshot `queen.source` field. */
50
+ export const QUEEN_SOURCE_AUTO = 'auto'
51
+ export const QUEEN_SOURCE_MANUAL = 'manual'
52
+
41
53
  /** Built-in role used when the workspace file is missing or unreadable. */
42
54
  export const QUEEN_FALLBACK_ROLE = '# Queen\n\nYou plan, you do not code. Split goals into cards; do not edit files or commit.\n'
43
55
 
@@ -91,21 +103,33 @@ export function defaultReadRole(cwd) {
91
103
  *
92
104
  * Registers the `hive:queen` prompt section (renders nothing for every other
93
105
  * Session), the `/queen` slash command, and the `agent/disposed` cleanup.
94
- * The returned controller is used by the host bridge:
95
- * - `mark({ sessionId, cwd })` after a successful `hive init`;
96
- * - `clear(sessionId)` for `/queen off` and the `queen-off` action;
97
- * - `textFor(sessionId)` for verification.
106
+ *
107
+ * Controller semantics:
108
+ * - `autoMark({sessionId, cwd})` — snapshot auto-activation: no-op (not a
109
+ * rewrite) when already active, returns false when the Session was
110
+ * explicitly closed or is already active, marks with source `auto` otherwise;
111
+ * - `mark({sessionId, cwd, source})` — explicit activation (`queen-on`,
112
+ * `init`, `/queen on`); always re-reads the role file and clears the
113
+ * explicit-off suppression;
114
+ * - `disable(sessionId)` — explicit exit (`queen-off`, `/queen off`);
115
+ * idempotent and suppresses future auto-activation;
116
+ * - `snapshotFor(sessionId)` — `{ active, source }` for the snapshot field.
98
117
  *
99
118
  * @param {object} ctx - host Cordis context (systemPrompt/commands/on).
100
119
  * @param {{ readRole?: typeof defaultReadRole, maxChars?: number, log?: (message: string, error?: unknown) => void }} [options]
101
- * @returns {{ mark: Function, clear: Function, has: Function, textFor: Function, size: Function, dispose: Function }}
120
+ * @returns {{
121
+ * mark: Function, autoMark: Function, disable: Function, clear: Function,
122
+ * has: Function, snapshotFor: Function, textFor: Function, size: Function, dispose: Function
123
+ * }}
102
124
  */
103
125
  export function createQueen(ctx, options = {}) {
104
126
  const readRole = typeof options.readRole === 'function' ? options.readRole : defaultReadRole
105
127
  const maxChars = Number.isSafeInteger(options.maxChars) && options.maxChars > 0 ? options.maxChars : QUEEN_MAX_CHARS
106
128
  const log = typeof options.log === 'function' ? options.log : () => {}
107
- /** @type {Map<string, string>} SessionId -> rendered role text; the only mode state. */
129
+ /** @type {Map<string, { text: string, source: 'auto' | 'manual' }>} SessionId -> rendered role text. */
108
130
  const roles = new Map()
131
+ /** @type {Set<string>} Sessions the user explicitly took out of queen mode. */
132
+ const suppressed = new Set()
109
133
  const disposers = []
110
134
 
111
135
  /** Register one service contribution and bind its disposer to this fiber. */
@@ -122,6 +146,20 @@ export function createQueen(ctx, options = {}) {
122
146
  disposers.push(dispose)
123
147
  }
124
148
 
149
+ function setRole(sessionId, cwd, source) {
150
+ if (typeof sessionId !== 'string' || sessionId === '') throw new TypeError('queen: sessionId is required')
151
+ if (typeof cwd !== 'string' || cwd === '') throw new TypeError('queen: cwd is required')
152
+ const text = formatQueenRole(cwd, readRole, maxChars)
153
+ roles.set(sessionId, { text, source: source === QUEEN_SOURCE_AUTO ? QUEEN_SOURCE_AUTO : QUEEN_SOURCE_MANUAL })
154
+ suppressed.delete(sessionId)
155
+ return text
156
+ }
157
+
158
+ function forget(sessionId) {
159
+ roles.delete(sessionId)
160
+ suppressed.delete(sessionId)
161
+ }
162
+
125
163
  if (ctx.systemPrompt !== undefined && typeof ctx.systemPrompt.section === 'function') {
126
164
  bind(() => ctx.systemPrompt.section({
127
165
  name: QUEEN_SECTION,
@@ -130,7 +168,8 @@ export function createQueen(ctx, options = {}) {
130
168
  text: ({ agent }) => {
131
169
  if (agent === undefined) return ''
132
170
  const sessionId = agent.session?.id
133
- return typeof sessionId === 'string' ? (roles.get(sessionId) ?? '') : ''
171
+ if (typeof sessionId !== 'string') return ''
172
+ return roles.get(sessionId)?.text ?? ''
134
173
  },
135
174
  }), 'hive-panel: queen system-prompt section')
136
175
  }
@@ -138,18 +177,35 @@ export function createQueen(ctx, options = {}) {
138
177
  if (ctx.commands !== undefined && typeof ctx.commands.register === 'function') {
139
178
  bind(() => ctx.commands.register({
140
179
  name: 'queen',
141
- description: '退出 Hive 女王模式',
142
- input: { hint: 'off' },
180
+ description: '进入/退出 Hive 女王模式(/queen on | off)',
181
+ input: { hint: 'on | off' },
143
182
  handler: ({ agent, rawInput }) => {
144
183
  const sessionId = agent?.session?.id
145
- if (rawInput !== undefined && rawInput.trim() === 'off') {
146
- if (typeof sessionId === 'string') roles.delete(sessionId)
184
+ if (typeof sessionId !== 'string') {
185
+ return { kind: 'error', text: 'queen: no Session for this command' }
186
+ }
187
+ const verb = rawInput === undefined ? '' : rawInput.trim()
188
+ if (verb === 'off') {
189
+ disable(sessionId)
147
190
  return { kind: 'success', text: '女王模式已关闭。' }
148
191
  }
149
- const active = typeof sessionId === 'string' && roles.has(sessionId)
192
+ if (verb === 'on') {
193
+ let cwd
194
+ try {
195
+ cwd = ctx.workingDirectory?.get?.(agent.session)
196
+ } catch {
197
+ cwd = undefined
198
+ }
199
+ if (typeof cwd !== 'string' || cwd === '') {
200
+ return { kind: 'error', text: 'queen: cannot resolve the Session working directory' }
201
+ }
202
+ mark({ sessionId, cwd, source: QUEEN_SOURCE_MANUAL })
203
+ return { kind: 'success', text: '女王模式已开启。' }
204
+ }
205
+ const active = roles.has(sessionId)
150
206
  return {
151
207
  kind: 'success',
152
- text: active ? '当前在女王模式;/queen off 退出。' : '当前不在女王模式。',
208
+ text: active ? '当前在女王模式;/queen off 退出。' : '当前不在女王模式;/queen on 开启。',
153
209
  }
154
210
  },
155
211
  }), 'hive-panel: /queen command')
@@ -159,33 +215,63 @@ export function createQueen(ctx, options = {}) {
159
215
  try {
160
216
  ctx.on('agent/disposed', ({ agent }) => {
161
217
  const sessionId = agent?.session?.id
162
- if (typeof sessionId === 'string') roles.delete(sessionId)
218
+ if (typeof sessionId === 'string') forget(sessionId)
163
219
  })
164
220
  } catch (error) {
165
221
  log('hive-panel: agent/disposed listener failed', error)
166
222
  }
167
223
  }
168
224
 
225
+ /** Explicit activation: re-reads the role file and clears the explicit-off flag. */
226
+ function mark({ sessionId, cwd, source = QUEEN_SOURCE_MANUAL }) {
227
+ return setRole(sessionId, cwd, source)
228
+ }
229
+
230
+ /** Auto activation from the snapshot loop: idempotent, honours explicit-off. */
231
+ function autoMark({ sessionId, cwd }) {
232
+ if (typeof sessionId !== 'string' || sessionId === '') return false
233
+ if (suppressed.has(sessionId)) return false
234
+ if (roles.has(sessionId)) return false
235
+ setRole(sessionId, cwd, QUEEN_SOURCE_AUTO)
236
+ return true
237
+ }
238
+
239
+ /** Explicit exit: idempotent and remembered so snapshots cannot re-enable it. */
240
+ function disable(sessionId) {
241
+ if (typeof sessionId !== 'string' || sessionId === '') return false
242
+ const wasActive = roles.delete(sessionId)
243
+ suppressed.add(sessionId)
244
+ return wasActive
245
+ }
246
+
247
+ /** Remove without suppressing (fiber teardown/tests). */
248
+ function clear(sessionId) {
249
+ return roles.delete(sessionId)
250
+ }
251
+
169
252
  return {
170
- /** Mark one Session as queen; re-reads the role file every time. */
171
- mark({ sessionId, cwd }) {
172
- if (typeof sessionId !== 'string' || sessionId === '') throw new TypeError('queen.mark: sessionId is required')
173
- if (typeof cwd !== 'string' || cwd === '') throw new TypeError('queen.mark: cwd is required')
174
- const text = formatQueenRole(cwd, readRole, maxChars)
175
- roles.set(sessionId, text)
176
- return text
177
- },
178
- /** Clear one Session (idempotent). */
179
- clear(sessionId) {
180
- return roles.delete(sessionId)
181
- },
253
+ mark,
254
+ autoMark,
255
+ disable,
256
+ clear,
182
257
  /** Whether one Session currently renders queen mode. */
183
258
  has(sessionId) {
184
259
  return roles.has(sessionId)
185
260
  },
261
+ /** Stable snapshot view: `{ active, source }` (`source` null when inactive). */
262
+ snapshotFor(sessionId) {
263
+ const entry = roles.get(sessionId)
264
+ return entry === undefined
265
+ ? { active: false, source: null }
266
+ : { active: true, source: entry.source }
267
+ },
186
268
  /** The exact text one Session renders ('' when not queen). */
187
269
  textFor(sessionId) {
188
- return roles.get(sessionId) ?? ''
270
+ return roles.get(sessionId)?.text ?? ''
271
+ },
272
+ /** Whether the user explicitly left queen mode in this process. */
273
+ isSuppressed(sessionId) {
274
+ return suppressed.has(sessionId)
189
275
  },
190
276
  /** Number of marked Sessions (diagnostics/verification). */
191
277
  size() {
@@ -194,6 +280,7 @@ export function createQueen(ctx, options = {}) {
194
280
  /** Drop every registration and all mode state. */
195
281
  dispose() {
196
282
  roles.clear()
283
+ suppressed.clear()
197
284
  for (const dispose of disposers.splice(0)) {
198
285
  try {
199
286
  void dispose()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-panel",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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",
@@ -19,6 +19,9 @@
19
19
  * 10. A successful init + refs/hive/v1 marks that Session as queen, renders the
20
20
  * capped <cwd>/.hive/roles/queen.md through ctx.systemPrompt.section, never
21
21
  * leaks to another Session, and exits via /queen off or name=queen-off.
22
+ * 11. An initialised repo auto-enters queen mode from op=snapshot (source
23
+ * "auto"), explicit off suppresses re-activation, queen-off is idempotent,
24
+ * and config autoQueen=false leaves activation to name=queen-on.
22
25
  */
23
26
  import assert from 'node:assert/strict'
24
27
  import { spawnSync } from 'node:child_process'
@@ -296,10 +299,11 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
296
299
  assert.equal(outcome.body.stats.total, 1)
297
300
  assert.equal(outcome.body.events.length, 2)
298
301
  assert.equal(outcome.body.events[0].kind, 'task_done', 'events must be newest-first')
299
- for (const key of ['at', 'repo', 'initialised', 'mode', 'board', 'tasks', 'stats', 'events', 'writable']) {
302
+ for (const key of ['at', 'repo', 'initialised', 'mode', 'board', 'tasks', 'stats', 'events', 'writable', 'queen']) {
300
303
  assert.ok(Object.prototype.hasOwnProperty.call(outcome.body, key), 'snapshot is missing ' + key)
301
304
  }
302
- assert.deepEqual(Object.keys(outcome.body).sort(), ['at', 'board', 'events', 'initialised', 'mode', 'repo', 'stats', 'tasks', 'writable'])
305
+ assert.deepEqual(Object.keys(outcome.body).sort(), ['at', 'board', 'events', 'initialised', 'mode', 'queen', 'repo', 'stats', 'tasks', 'writable'])
306
+ assert.deepEqual(outcome.body.queen, { active: true, source: 'auto', repo }, 'an initialised repo must auto-enter queen mode from the snapshot')
303
307
  const commands = shim.executions.map(execution => execution.command)
304
308
  assert.ok(commands.includes(host.snapshotCliCommands().board), 'snapshot never ran hive board --json')
305
309
  assert.ok(commands.includes(host.snapshotCliCommands().tasks), 'snapshot never ran hive-tasks list --json')
@@ -313,7 +317,7 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
313
317
  assert.ok(execution.command.startsWith("'hive'") || execution.command.startsWith("'hive-tasks'") || execution.command.startsWith("'git'"))
314
318
  }
315
319
  ok('GET op=snapshot runs fixed Hive CLI commands in the Session cwd under its sandbox policy')
316
- ok('snapshot keeps the { at, repo, initialised, mode, board, tasks, stats, events, writable } contract')
320
+ ok('snapshot keeps the { at, repo, initialised, mode, board, tasks, stats, events, writable, queen } contract')
317
321
  }
318
322
 
319
323
  // ── 6b. uninitialised repo: no Hive CLI fan-out ─────────────────────────────
@@ -362,8 +366,10 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
362
366
  assert.equal(catalog.status, 200)
363
367
  assert.equal(catalog.body.writable, false)
364
368
  assert.equal(catalog.body.repo, repo)
369
+ assert.equal(catalog.body.autoQueen, true)
370
+ assert.ok(catalog.body.actions.includes('queen-on'))
365
371
  assert.ok(catalog.body.actions.includes('queen-off'))
366
- assert.equal(catalog.body.actions.length, 17)
372
+ assert.equal(catalog.body.actions.length, 18)
367
373
  const unknown = await call(route, { query: { op: 'nope', sessionId: 's-live' } })
368
374
  assert.equal(unknown.status, 400)
369
375
  assert.equal(unknown.body.error.code, 'hive/unknown-op')
@@ -491,6 +497,82 @@ async function call(route, { method = 'GET', query = {}, body } = {}) {
491
497
  ok('a 20k role file is truncated to 4096 characters and marked truncated')
492
498
  }
493
499
 
500
+ // ── 12c. snapshot auto-queen / explicit off / queen-on ─────────────────────
501
+ {
502
+ const shim = createCtx({ live, cwdOf })
503
+ host.apply(shim.ctx, {})
504
+ const route = shim.routes.get('/api/hive')
505
+ const section = shim.sections.find(entry => entry.name === 'hive:queen')
506
+ const agent = { session: { id: 's-live' } }
507
+ const snapshot = () => call(route, { query: { op: 'snapshot', sessionId: 's-live' } })
508
+
509
+ assert.equal(section.text({ agent }), '')
510
+ const first = await snapshot()
511
+ assert.equal(first.status, 200)
512
+ assert.deepEqual(first.body.queen, { active: true, source: 'auto', repo })
513
+ assert.match(section.text({ agent }), /You plan, you do not code/)
514
+
515
+ // Repeated polling is idempotent: the auto state stays, it never flips source.
516
+ const second = await snapshot()
517
+ assert.deepEqual(second.body.queen, { active: true, source: 'auto', repo })
518
+
519
+ // Explicit off is remembered; the next snapshot must not re-activate.
520
+ const offFirst = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-off', sessionId: 's-live' }, body: {} })
521
+ assert.equal(offFirst.status, 200)
522
+ assert.deepEqual(offFirst.body, { ok: true, code: 0, stdout: '', stderr: '' })
523
+ const offSecond = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-off', sessionId: 's-live' }, body: {} })
524
+ assert.equal(offSecond.status, 200, 'queen-off must be idempotent')
525
+ assert.deepEqual(offSecond.body, { ok: true, code: 0, stdout: '', stderr: '' })
526
+ const afterOff = await snapshot()
527
+ assert.deepEqual(afterOff.body.queen, { active: false, source: null, repo })
528
+ assert.equal(section.text({ agent }), '')
529
+
530
+ // queen-on re-enables explicitly and marks the source manual.
531
+ const on = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-on', sessionId: 's-live' }, body: {} })
532
+ assert.equal(on.status, 200)
533
+ assert.deepEqual(on.body, { ok: true, code: 0, stdout: '', stderr: '' })
534
+ assert.deepEqual((await snapshot()).body.queen, { active: true, source: 'manual', repo })
535
+ // /queen off suppresses auto again; /queen on re-enables manually.
536
+ const commandOff = shim.commands.get('queen').handler({ agent, rawInput: ' off ', signal: {}, attachments: [], commandId: 'cmd-2' })
537
+ assert.equal(commandOff.kind, 'success')
538
+ assert.deepEqual((await snapshot()).body.queen, { active: false, source: null, repo })
539
+ const commandOn = shim.commands.get('queen').handler({ agent, rawInput: ' on ', signal: {}, attachments: [], commandId: 'cmd-3' })
540
+ assert.equal(commandOn.kind, 'success')
541
+ assert.deepEqual((await snapshot()).body.queen, { active: true, source: 'manual', repo })
542
+ ok('snapshot auto-queens an initialised repo; explicit off suppresses it (idempotent); queen-on and /queen on re-enable')
543
+ }
544
+
545
+ // ── 12d. autoQueen=false, manual activation, stable error codes ────────────
546
+ {
547
+ const shim = createCtx({ live, cwdOf })
548
+ host.apply(shim.ctx, { autoQueen: false })
549
+ const route = shim.routes.get('/api/hive')
550
+ const section = shim.sections.find(entry => entry.name === 'hive:queen')
551
+ const agent = { session: { id: 's-live' } }
552
+ const snapshot = () => call(route, { query: { op: 'snapshot', sessionId: 's-live' } })
553
+
554
+ const idle = await snapshot()
555
+ assert.deepEqual(idle.body.queen, { active: false, source: null, repo })
556
+ assert.equal(section.text({ agent }), '')
557
+ const catalog = await call(route, { query: { op: 'actions', sessionId: 's-live' } })
558
+ assert.equal(catalog.body.autoQueen, false)
559
+
560
+ const manual = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-on', sessionId: 's-live' }, body: {} })
561
+ assert.equal(manual.status, 200)
562
+ assert.deepEqual((await snapshot()).body.queen, { active: true, source: 'manual', repo })
563
+ assert.deepEqual((await snapshot()).body.queen, { active: true, source: 'manual', repo }, 'a manual activation must not be downgraded to auto')
564
+
565
+ const missing = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-on', sessionId: 'nope' }, body: {} })
566
+ assert.equal(missing.status, 400)
567
+ assert.equal(missing.body.ok, false)
568
+ assert.equal(missing.body.code, 2)
569
+ assert.match(missing.body.stderr, /^hive\/session-unknown: /)
570
+ const unknown = await call(route, { method: 'POST', query: { op: 'action', name: 'queen-nope', sessionId: 's-live' }, body: {} })
571
+ assert.equal(unknown.status, 400)
572
+ assert.match(unknown.body.stderr, /^hive\/unknown-action: /)
573
+ ok('autoQueen=false leaves snapshots inactive until name=queen-on; queen errors carry hive/* codes')
574
+ }
575
+
494
576
  // ── 13. queen state never enters the durable session log ───────────────────
495
577
  {
496
578
  const queenSource = await readFile(files.queen, 'utf8')