dsh-team-bots 0.2.364 → 0.2.395

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.
Files changed (49) hide show
  1. package/README.md +12 -2
  2. package/docs/README.zh.md +12 -2
  3. package/docs/assets/global-config.png +0 -0
  4. package/docs/assets/global-config.zh.png +0 -0
  5. package/docs/assets/tasks.png +0 -0
  6. package/docs/assets/tasks.zh.png +0 -0
  7. package/docs/assets/usage.png +0 -0
  8. package/docs/assets/usage.zh.png +0 -0
  9. package/index.js +2 -0
  10. package/package.json +1 -1
  11. package/src/config.js +55 -10
  12. package/src/db-migrations.js +144 -9
  13. package/src/paths.js +12 -0
  14. package/src/services/approvals.js +12 -2
  15. package/src/services/core.js +2 -1
  16. package/src/services/notify.js +24 -8
  17. package/src/services/questions.js +16 -3
  18. package/src/services/run-finish.js +18 -3
  19. package/src/services/runs.js +369 -34
  20. package/src/services/runtime/prompt.js +106 -89
  21. package/src/services/runtime/session.js +266 -72
  22. package/src/services/scheduler.js +26 -118
  23. package/src/services/task-dispatch.js +39 -0
  24. package/src/services/task-review.js +37 -0
  25. package/src/services/task-runs.js +46 -14
  26. package/src/services/wechat.js +23 -21
  27. package/src/subagent-ledger.js +165 -0
  28. package/src/wechat/commands.js +3 -1
  29. package/ui/app.js +4 -14
  30. package/ui/i18n/en/chat.js +11 -11
  31. package/ui/i18n/en/common.js +0 -12
  32. package/ui/i18n/en/nav.js +0 -4
  33. package/ui/i18n/en/settings.js +14 -9
  34. package/ui/i18n/en/tasks.js +0 -1
  35. package/ui/i18n/en/usage.js +4 -7
  36. package/ui/i18n/zh/chat.js +11 -11
  37. package/ui/i18n/zh/common.js +0 -12
  38. package/ui/i18n/zh/nav.js +0 -4
  39. package/ui/i18n/zh/settings.js +13 -9
  40. package/ui/i18n/zh/tasks.js +0 -1
  41. package/ui/i18n/zh/usage.js +4 -7
  42. package/ui/modules/cards.js +19 -5
  43. package/ui/modules/composer.js +16 -3
  44. package/ui/modules/i18n.js +10 -0
  45. package/ui/modules/modal-forms.js +15 -8
  46. package/ui/modules/settings.js +9 -0
  47. package/ui/modules/util.js +0 -2
  48. package/ui/styles/frame.css +0 -28
  49. package/ui/styles/wide.css +0 -3
@@ -47,14 +47,6 @@ export function runHoldsWriteLock({ kind, mode, taskStatus } = {} ) {
47
47
  // task_run 的先写者赢是防重复派生闸,同样保持默认(先写者赢)不动。
48
48
  const OUTBOX_COALESCE_KINDS = new Set(['review_delegate_auto'])
49
49
 
50
- // 入站消息合批(DSHBOTS-231):只合并「人发的消息运行」——同一条绑定道内、仍在排队的
51
- // chat / solo_chat 运行。任务运行、派生运行(review/handle/memory_review/vision)与私信
52
- // (dm/dm_reply,各自有按消息的回信契约)都不参与:合并它们会破坏既有的投递语义。
53
- const RUN_COALESCE_KINDS = new Set(['chat', 'solo_chat'])
54
- // 默认保守上限:一次运行最多合并 5 条消息、且只合并入队时间相差 30 秒内的排队消息。
55
- const COALESCE_MAX_MESSAGES_DEFAULT = 5
56
- const COALESCE_WINDOW_MS_DEFAULT = 30_000
57
-
58
50
  export const schedulerMethods = {
59
51
 
60
52
  // outbox:把「状态变更 → 建运行」这一跳变成可重放的持久交接。
@@ -270,105 +262,17 @@ export const schedulerMethods = {
270
262
  throw error
271
263
  },
272
264
 
273
- // 同一条会话上的运行必须串行(原注释意图);DSHBOTS-219 分身模型:串行键从「bot」
274
- // 放细到「会话绑定维度」(= 一条分身通道)——单聊/各项目群聊/私信互不阻塞,
275
- // 一路 pending(如单聊提权审批)不再挡死同一 bot 的其它通道。
276
- // 键与 ensureSession 的绑定元组一一对应,同一会话的两条运行必得同键,串行不失效。
265
+ // 串行键(DSHBOTS-308,DSHBOTS-289 的 bot 全局串行收窄):串行域 = (bot, 工作区),
266
+ // domain 取 run.project_id ?? '~solo'(与 D-299 one_bot_binding 的 COALESCE 口径一致,
267
+ // 项目外 solo/单聊落 bot 自有工作区)。跨工作区并行由 owner 拍板;同域运行仍互斥。
268
+ // domain 以 run.project_id 为准:dm_reply 入队处即落 origin 推导的 project_id
269
+ // (deliverBotReply 写 message.project_id,见 runs.ts),键推导不读 trigger_ref/session_id。
270
+ // 施工运行(kind='task')豁免 bot 串行域(单 bot 多任务并行):串行键按任务维度取
271
+ // task:<id>,同任务至多一条(one_active_run_per_task 同口径),同 bot 不同任务可并行;
272
+ // 并行安全由写范围闸门兜底(声明重叠即串行),与 bot 串行域互不替代。
277
273
  claimKey(run) {
278
274
  if (run.kind === 'task' && run.task_id) return `task:${run.task_id}`
279
- return this.sessionLaneKey(run)
280
- },
281
- // 会话绑定的通道键(纯查库推导,无副作用):task / solo / dm / project 四类绑定各归各道。
282
- bindingLaneKey(binding) {
283
- if (binding.kind === 'task' && binding.task_id) return `task:${binding.task_id}`
284
- if (binding.kind === 'solo') return `solo:${binding.bot_id}`
285
- if (binding.kind === 'dm') return `dm:${binding.bot_id}:${binding.project_id}`
286
- return `project:${binding.bot_id}:${binding.project_id}`
287
- },
288
- // 非任务运行的通道键:按该运行实际会落到的会话推导(与 ensureSession 的 kind0 同一套映射)。
289
- // solo_chat 与无项目 vision 落 solo 会话;chat/review/handle/memory_review 与带项目 vision
290
- // 落项目会话;dm 落私信会话;dm_reply 按来信 origin 回对应会话(task_id 留空躲唯一索引,
291
- // 任务通道只能从 bot_messages 解);rollover_summary 复用指定旧会话,按该会话当前绑定
292
- // 的通道键对齐(防与复用同一会话的群聊并发——runtime 的 pending 按会话一对一)。
293
- sessionLaneKey(run) {
294
- if (run.kind === 'solo_chat' || (run.kind === 'vision' && !run.project_id)) return `solo:${run.bot_id}`
295
- if (run.kind === 'rollover_summary') {
296
- if (!run.session_id) return `bot:${run.bot_id}`
297
- const binding = this.store.get('SELECT * FROM session_bindings WHERE session_id = ?', run.session_id)
298
- return binding ? this.bindingLaneKey(binding) : `session:${run.session_id}`
299
- }
300
- if (run.kind === 'dm_reply') {
301
- const message = run.trigger_ref
302
- ? this.store.get('SELECT origin_kind, origin_task_id FROM bot_messages WHERE id = ?', run.trigger_ref)
303
- : null
304
- if (message?.origin_kind === 'task' && message.origin_task_id) return `task:${message.origin_task_id}`
305
- if (message?.origin_kind === 'dm') return `dm:${run.bot_id}:${run.project_id}`
306
- return `project:${run.bot_id}:${run.project_id}`
307
- }
308
- if (run.kind === 'dm') return `dm:${run.bot_id}:${run.project_id}`
309
- return `project:${run.bot_id}:${run.project_id}`
310
- },
311
-
312
- // DSHBOTS-272 用户提问运行判定:kind='chat' 且触发消息是人发的(messages.sender_type='user')。
313
- // 通知降级(notify.ts 成员通知落群聊流)与 bot 回复 @mention 唤醒(run-finish.ts)触发的
314
- // chat 运行,触发消息 sender_type='bot',不算用户提问;出队置顶与合批保护只给人发的提问用。
315
- isUserQuestionRun(run) {
316
- if (run?.kind !== 'chat' || !run.trigger_ref) return false
317
- const message = this.store.get('SELECT sender_type FROM messages WHERE id = ?', run.trigger_ref)
318
- return message?.sender_type === 'user'
319
- },
320
-
321
- // 入站消息合批(DSHBOTS-231):领取一条运行后,把同一条绑定道内仍在排队的消息运行合并
322
- // 进来——被合并的运行置 canceled(error_code='MERGED'),消息 id 记入本运行的
323
- // merged_messages,executeRun 据此把多条消息一次性注入同一轮上下文,不再一条消息一次运行。
324
- // 只在 claimKey 相同的通道内合并,D-219 的四道解耦语义不变;合并窗口与条数上限走 settings。
325
- // 并发安全:被合并的运行用「queued → canceled」原子更新抢占,抢不到(另一拍已领取)就跳过。
326
- coalesceQueuedRuns(run) {
327
- if (!RUN_COALESCE_KINDS.has(run.kind)) return []
328
- const max = Number(this.store.setting('coalesce_max_messages', String(COALESCE_MAX_MESSAGES_DEFAULT)))
329
- if (!Number.isFinite(max) || max <= 1) return []
330
- const windowMs = Number(this.store.setting('coalesce_window_ms', String(COALESCE_WINDOW_MS_DEFAULT)))
331
- const claimedQueuedAt = Date.parse(run.queued_at)
332
- const laneKey = this.claimKey(run)
333
- // DSHBOTS-272 合批保护:用户提问(触发消息 sender_type='user')不并入非用户触发的运行——
334
- // 并入后提问只能挤在 Merged messages 段、没有直接回答锚点(事故形态=通知运行回一条轻备忘
335
- // 就算处理完)。留队保住「一条提问一条正式回复」;出队序已把用户提问置顶,下一拍即领取。
336
- const claimedIsUserQuestion = this.isUserQuestionRun(run)
337
- const candidates = this.store.all(
338
- `SELECT * FROM runs WHERE status = 'queued' AND id != ? AND kind = ?
339
- ORDER BY queued_at LIMIT 100`,
340
- run.id, run.kind,
341
- )
342
- const mergedIds = []
343
- const mergedRuns = []
344
- for (const candidate of candidates) {
345
- if (mergedIds.length >= max - 1) break
346
- if (!candidate.trigger_ref) continue
347
- if (this.claimKey(candidate) !== laneKey) continue
348
- // DSHBOTS-272:候选是用户提问而本运行非用户触发(通知/伙伴唤醒)→ 不并,见上方注释。
349
- if (!claimedIsUserQuestion && this.isUserQuestionRun(candidate)) continue
350
- const queuedAt = Date.parse(candidate.queued_at)
351
- if (!Number.isFinite(queuedAt) || !Number.isFinite(claimedQueuedAt)) continue
352
- if (queuedAt < claimedQueuedAt || queuedAt - claimedQueuedAt > windowMs) continue
353
- const changed = this.store.run(
354
- `UPDATE runs SET status = 'canceled', ended_at = ?, error_code = 'MERGED', error_message = ?
355
- WHERE id = ? AND status = 'queued'`,
356
- nowIso(), `消息已合并进运行 ${run.id},不再单独执行`, candidate.id,
357
- )
358
- if (Number(changed?.changes ?? 0) !== 1) continue
359
- mergedIds.push(candidate.trigger_ref)
360
- mergedRuns.push(candidate)
361
- }
362
- if (!mergedIds.length) return []
363
- this.store.run('UPDATE runs SET merged_messages = ? WHERE id = ?', JSON.stringify(mergedIds), run.id)
364
- this.insertRunEvent(
365
- run.id, 'runs_merged',
366
- `同通道 ${mergedIds.length} 条排队消息合并进本次运行:${mergedIds.map(item => item.slice(-6)).join('、')}`,
367
- )
368
- for (const candidate of mergedRuns) {
369
- this.insertRunEvent(candidate.id, 'merged_into', `排队消息已合并进运行 ${run.id}`)
370
- }
371
- return mergedRuns
275
+ return `bot:${run.bot_id}:${run.project_id ?? '~solo'}`
372
276
  },
373
277
 
374
278
  // 运行超时由 runtime 的定时器负责;这里补充“还活着但没有任何进展”的判定。
@@ -513,9 +417,10 @@ export const schedulerMethods = {
513
417
  return canceled
514
418
  },
515
419
 
516
- // 滞留阈值兜底扫描(DSHBOTS-280):in_review 超 24h / blocked 超 48h 的卡向项目
517
- // owner 发一条滞留提醒(notify.ts notifyStaleCardOwner),只提醒不自动处置——
518
- // 不自动关单、不自动转状态、不重派。选点:复用 scheduler 周期 tick(与 D-194
420
+ // 滞留阈值兜底扫描(DSHBOTS-280;DSHBOTS-295 扩待执行宽档):in_review 超 24h /
421
+ // blocked 超 48h / 待执行(backlog/todo,D-295 调查:tasks 表无 'pending' 态)超 72h
422
+ // 的卡向项目 owner 发一条滞留提醒(notify.ts notifyStaleCardOwner),只提醒不自动
423
+ // 处置——不自动关单、不自动转状态、不重派。选点:复用 scheduler 周期 tick(与 D-194
519
424
  // 验收守门同拍接入,不新增常驻进程);判定与防重见 notify.ts 的纯函数与每日上限。
520
425
  // 逐卡容错:单卡异常只 warn,不拖垮整轮扫描。
521
426
  scanStaleCards() {
@@ -523,7 +428,7 @@ export const schedulerMethods = {
523
428
  `SELECT t.id, t.status, t.updated_at, t.number,
524
429
  p.id AS project_id, p.key AS project_key, p.owner_bot_id
525
430
  FROM tasks t JOIN projects p ON p.id = t.project_id
526
- WHERE t.status IN ('in_review', 'blocked') AND p.status = 'active'`,
431
+ WHERE t.status IN ('in_review', 'blocked', 'todo', 'backlog') AND p.status = 'active'`,
527
432
  )
528
433
  const reminded = []
529
434
  for (const row of rows) {
@@ -621,20 +526,23 @@ export const schedulerMethods = {
621
526
  this.retryExpiredPlanWaits()
622
527
  // 陈旧排队运行守卫(DSHBOTS-110):先于候选查询清掉任务已终态的 queued 任务运行。
623
528
  this.cancelStaleQueuedTaskRuns()
529
+ // 争用口径 A 收口(DSHBOTS-289):bot 空闲时把挂起消息建回运行(合批成一条),
530
+ // 建回的 queued 行随本拍候选查询一并领取。
531
+ this.drainPendingMessages()
624
532
  // 验收滞留守门(DSHBOTS-194):in_review 卡静置超阈值即注入 owner 系统提醒;
625
533
  // 内部自容错(异常只 warn),阈值 0 = 关闭时直接返回。
626
534
  runReviewWatchdog(this)
627
- // 滞留阈值兜底(DSHBOTS-280):in_review/blocked 超 24h/48h 向 owner 只提醒
628
- // 不自动处置;内部逐卡容错(单卡异常只 warn)。
535
+ // 滞留阈值兜底扫描(DSHBOTS-280;DSHBOTS-295 扩待执行宽档):in_review/blocked/
536
+ // 待执行(todo/backlog)超 24h/48h/72h 三档向 owner 只提醒不自动处置;
537
+ // 内部逐卡容错(单卡异常只 warn)。
629
538
  this.scanStaleCards()
630
539
  const activeRows = this.store.all(
631
540
  // 写占用只看「进行中」的任务(DSHBOTS-73,用户口径):join tasks 取任务当前状态,
632
541
  // 任务不在 in_progress 的写运行不再占槽——离开进行中即释放占用/锁定。
633
542
  // 非任务运行 LEFT JOIN 出的 task_status 为空,按运行自身判定,不受这条闸门影响。
634
- // trigger_ref/session_id 供 claimKey 通道推导(dm_reply 按来信 origin、rollover_summary
635
- // 按旧会话绑定)——在跑侧与候选侧必须算出同一个键,串行才不失效(DSHBOTS-219)。
543
+ // claimKey 串行域 = (bot, 工作区)(DSHBOTS-308):键只读 bot_id/project_id(均在列面),
544
+ // 在跑侧与候选侧算的是同一 run 行的同一列,串行不失效(承 DSHBOTS-219 口径)。
636
545
  `SELECT r.bot_id, r.kind, r.task_id, r.project_id, r.mode, r.write_scopes, r.trigger_type,
637
- r.trigger_ref, r.session_id,
638
546
  t.status AS task_status
639
547
  FROM runs r LEFT JOIN tasks t ON t.id = r.task_id
640
548
  WHERE r.status = 'running'`,
@@ -701,7 +609,8 @@ export const schedulerMethods = {
701
609
  // DSHBOTS-112:单聊读图代理运行与 solo_chat 同样不带 project_id,豁免项目闸门。
702
610
  // DSHBOTS-145:结转摘要运行同理——单聊摘要运行不带 project_id,只有项目摘要运行
703
611
  // 才需要项目上下文;否则 solo 摘要会被误判 MISSING_CONTEXT 直接失败。
704
- const needsProject = run.kind === 'rollover_summary'
612
+ // DSHBOTS-286:闲时压缩运行同理。
613
+ const needsProject = run.kind === 'rollover_summary' || run.kind === 'session_compact'
705
614
  ? Boolean(run.project_id)
706
615
  : run.kind !== 'solo_chat' && !(run.kind === 'vision' && !run.project_id)
707
616
  const project = run.project_id ? this.store.get('SELECT * FROM projects WHERE id = ?', run.project_id) : null
@@ -778,9 +687,8 @@ export const schedulerMethods = {
778
687
  nowIso(), nowIso(), run.id,
779
688
  )
780
689
  if (Number(claimed.changes) !== 1) continue
781
- // 入站消息合批(DSHBOTS-231):领取后把同通道仍在排队的消息并进本次运行,
782
- // 被合并的运行置 canceled/MERGED,消息 id 落到 merged_messages 供 executeRun 注入。
783
- this.coalesceQueuedRuns(run)
690
+ // 消息合批(DSHBOTS-290 语义回补):合批在 bot 空闲建回时完成(drainPendingMessages,
691
+ // 含 D-272 用户提问保护/窗口/上限),领取侧不二次合批——窗口/上限已在建回侧消费。
784
692
  // 借用了人的消息保底槽(超出并发上限放行):记事件并占住额外槽,下一次归还前不再放第二条。
785
693
  if (human && activeTotal >= maxRuns) {
786
694
  humanSlotTaken = true
@@ -17,6 +17,12 @@ import { ensureTaskSandboxSchema } from './task-sandbox-schema.js'
17
17
  const CORRECTION_TITLE_RE = /修正|勘误|补充|改写/
18
18
  const RECENT_DONE_WINDOW_MS = 7 * 86_400_000
19
19
 
20
+ // 核验纪律派单闸关键词(DSHBOTS-303,保守集合,取舍锚):只取「核验/审计/复核」三词。
21
+ // 「验收」单用常出现在实施卡(如「跑通验收流程」),「验证」是普遍实施动词(如「跑通验证
22
+ // 流程」)——纳入即误伤实施卡,均不含;「红验证/子代理核验/验收核验」等复合词已被「核验」
23
+ // 覆盖。成员卡面自校要求(交付前自跑测试)不含三词,天然不命中。
24
+ export const VERIFICATION_TASK_KEYWORDS = ['核验', '审计', '复核']
25
+
20
26
  export const taskDispatchMethods = {
21
27
  // 派发门禁(DSHBOTS-262):暂停中的 Bot 不接新卡——新建派单、改派、重派一律拒绝,
22
28
  // 先恢复(bot status → active)再派;归档/移除等其余不可用态沿用 assertMember 既有口径。
@@ -25,6 +31,31 @@ export const taskDispatchMethods = {
25
31
  if (bot?.status === 'paused') throw badRequest(`Bot ${bot.name} 已暂停,先恢复再派卡`)
26
32
  this.assertMember(projectId, botId)
27
33
  },
34
+ // 派单策略闸(DSHBOTS-314):写卡(write_scopes 非空)不派 file_policy=read-only 的
35
+ // bot——否则执行到落盘才撞只读沙箱(近期多次会话中断的真实根因之一),前移到派单时
36
+ // 显式拦截。无策略值按可写放行(锚:兼容存量空值);owner 备选「按预设自动降级」不
37
+ // 采用,拒绝回执更显式、卡面归属与预期一致,后续要自动降级再立卡。
38
+ assertWritableDispatch(botId, writeScopes) {
39
+ if (!writeScopes?.length) return
40
+ if (this.botRow(botId)?.file_policy !== 'read-only') return
41
+ const name = this.store.get('SELECT name FROM bots WHERE id = ?', botId)?.name ?? botId
42
+ throw badRequest(
43
+ `assignee ${name} 为只读策略,不能承接写任务:改派可写 bot、或调整该 bot 文件策略后重派(DSHBOTS-314 派单策略闸)。`,
44
+ )
45
+ },
46
+ // 核验纪律派单闸(DSHBOTS-303):核验/审计/复核类卡不派成员 bot(owner 硬口径)——
47
+ // 该类工作由总监(owner bot)自有子代理执行。与 D-302 提示词边界守门(review-auto 源码锚)
48
+ // 构成双层防线:提示词管会话内指引,本闸管派单行为。派给 director 本身不受限。
49
+ // 标题/描述任一命中关键词即视为核验类;重派改卡按改后生效卡面判定。
50
+ assertNotVerificationDispatch(project, botId, title, description) {
51
+ if (botId === project.owner_bot_id) return
52
+ const text = `${title ?? ''}\n${description ?? ''}`
53
+ if (!VERIFICATION_TASK_KEYWORDS.some(word => text.includes(word))) return
54
+ throw badRequest(
55
+ '核验/审计/复核类任务由总监(owner bot)自有子代理执行,不派成员 bot;'
56
+ + `如确为实施类工作请改标题/描述措辞(命中关键词:${VERIFICATION_TASK_KEYWORDS.join('、')})。`,
57
+ )
58
+ },
28
59
  // 无主卡领取开工的写范围声明闸门(DSHBOTS-270):与 assignFromBot「派单必须声明写
29
60
  // 范围」同口径的预判——卡面清单优先,空则从描述「写范围:」行兜底解析
30
61
  // (parseWriteScopesFromDescription),再过忽略规则清洗(全部命中 .gitignore 被剔除
@@ -296,9 +327,15 @@ export const taskDispatchMethods = {
296
327
  const sandboxOverride = input.sandbox === undefined
297
328
  ? undefined
298
329
  : resolveSandboxOverride(this.botRow(member.id), input.sandbox)
330
+ // 核验纪律派单闸(DSHBOTS-303)——新卡面;重派分支再按「改后生效卡面」补一道。
331
+ this.assertNotVerificationDispatch(project, member.id, input.title, input.description)
299
332
  if (input.taskId || input.task) {
300
333
  const task = this.resolveBotTask(project, input.taskId ?? input.task)
301
334
  if (['done', 'canceled'].includes(task.status)) throw conflict(`任务 ${project.key}-${task.number} 已结束,不能重派`)
335
+ // 核验纪律派单闸(DSHBOTS-303):重派/改卡按生效卡面(本次传入优先,缺省回落原卡)。
336
+ this.assertNotVerificationDispatch(project, member.id, input.title ?? task.title, input.description ?? task.description)
337
+ // 派单策略闸(DSHBOTS-314):重派按原卡声明写范围同闸(重派不改写范围,D-232 口径)。
338
+ this.assertWritableDispatch(member.id, readWriteScopes(task.write_scopes))
302
339
  // 任务卡修正闭环(DSHBOTS-232 ①):重派可同时改卡面(标题/描述/优先级)——先经
303
340
  // updateTask 落卡,卡面变化由其统一触发点通知负责人修正,再走原重派链路。
304
341
  // 写范围不在此口改:入队运行快照与调度闸门消费的不是同一份数据,
@@ -321,6 +358,8 @@ export const taskDispatchMethods = {
321
358
  // 闸门按清洗后清单预判(DSHBOTS-168):全部命中忽略规则 = 实际未声明,落上面的
322
359
  // 拒绝。原清单透传 createTask 做权威清洗+审计(审计需真实 taskId),此处只预览不落账。
323
360
  const scopes = filterIgnoredWriteScopes(parsedScopes, this.projectWorkDir(project)).kept
361
+ // 派单策略闸(DSHBOTS-314):写卡派只读 bot 在入口拒绝;重派分支按原卡声明补一道。
362
+ this.assertWritableDispatch(member.id, scopes)
324
363
  if (!scopes.length) {
325
364
  throw badRequest(
326
365
  '派单必须声明写范围:传 write_scopes 路径数组,或在描述里写一行「写范围:a, b」。'
@@ -15,9 +15,36 @@ export const taskReviewMethods = {
15
15
  const { project, actor } = this.ownerContextFor(sessionId)
16
16
  if (!['accept', 'return'].includes(input.decision)) throw badRequest('验收结果只能是 accept 或 return')
17
17
  const task = this.resolveBotTask(project, input.task)
18
+ // 验收机械闸(DSHBOTS-318)只拦真验收动作(in_review 卡):非待验收状态保持既有
19
+ // 校验顺序,仍由 applyReview 抛 in_review conflict,闸不抢跑。
20
+ if (task.status === 'in_review') this.assertReviewSubagentVerified(sessionId, input.comment)
18
21
  return this.applyReview(task, project, input.decision, input.comment, actor)
19
22
  },
20
23
 
24
+ // 验收机械闸(DSHBOTS-318):把「验收必须经由子代理」从提示约束升级为机械约束——
25
+ // owner bot 的 team_review_task 前置校验调用方当前活跃运行的子代理账目
26
+ // (run_events 的 subagent_spawned),无账目即拒绝;comment 显式注明「兜底验收」
27
+ // 放行(对应 router 硬流程第 4 条:子代理失败重试一次仍失败时 director 兜底)。
28
+ // 仅机器人路径:微信管理员/看板 owner 走 applyReview,不经过本闸。
29
+ assertReviewSubagentVerified(sessionId, comment) {
30
+ if (comment?.includes('兜底验收')) return
31
+ const run = this.store.get(
32
+ "SELECT id FROM runs WHERE session_id = ? AND status IN ('running', 'queued') ORDER BY queued_at DESC LIMIT 1",
33
+ sessionId,
34
+ )
35
+ const ledger = run && this.store.get(
36
+ "SELECT id FROM run_events WHERE run_id = ? AND type = 'subagent_spawned' LIMIT 1",
37
+ run.id,
38
+ )
39
+ if (ledger) return
40
+ // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 正确下一步。
41
+ throw badRequest(
42
+ '当前运行没有子代理账目(subagent_spawned),验收必须先经子代理核验:'
43
+ + '先派验收子代理(subagent/subagent_fork)做范围比对/目标测试/红线预测,把结论作为 comment;'
44
+ + '如需 director 兜底,在 comment 里注明「兜底验收」。',
45
+ )
46
+ },
47
+
21
48
  /** 验收/退回的共用流程:owner Bot 会话与微信管理员共用。 */
22
49
  async applyReview(task, project, decision, comment, actor) {
23
50
  const identifier = `${project.key}-${task.number}`
@@ -132,6 +159,16 @@ export const taskReviewMethods = {
132
159
  if (active.trigger_type === 'review_delegate') return { runId: active.id, reused: true }
133
160
  throw conflict(`任务 ${identifier} 已有运行在排队或执行,请先停止再委派核验`)
134
161
  }
162
+ // busy 闸(DSHBOTS-290):总监忙时不落 runs 行(撞 one_active_run_per_bot),挂待
163
+ // 处理队列空闲建回(insertHeldMessageRun 的 owner_task 分支);返回 deferred 让
164
+ // 手动入口与 outbox 自动入口都能感知「已挂起」而非失败。
165
+ if (this.botBusy(owner.id, project.id)) {
166
+ this.holdPendingMessage(owner.id, project.id, {
167
+ kind: 'owner_task', messageId: `owner_task:${task.id}:review_delegate`, taskId: task.id,
168
+ projectId: project.id, runKind: 'review', triggerType: 'review_delegate', queuedAt: nowIso(),
169
+ })
170
+ return { runId: null, deferred: true }
171
+ }
135
172
  const runId = id('run')
136
173
  const createdAt = nowIso()
137
174
  this.store.run(
@@ -117,13 +117,23 @@ export const taskRunMethods = {
117
117
  const fallbackProvider = routing.mode === 'fallback' ? routing.provider : null
118
118
  const fallbackModel = routing.mode === 'fallback' ? routing.model : null
119
119
  const fallbackEffort = routing.mode === 'fallback' ? routing.effort : null
120
- this.store.run(
121
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
122
- attempt, idempotency_key, write_scopes, model_provider, model_model, model_effort, queued_at)
123
- VALUES (?, ?, ?, ?, 'task', 'write', ?, ?, 'queued', 1, ?, ?, ?, ?, ?, ?)`,
124
- runId, task.project_id, task.assignee_bot_id, task.id, triggerType, task.id,
125
- `task:${task.id}:${Date.now()}:${runId}`, writeScopes, fallbackProvider, fallbackModel, fallbackEffort, createdAt,
126
- )
120
+ // 单 bot 多任务并行(任务运行豁免 bot 串行域):任务运行直插 queued,不再查 bot 忙
121
+ // 挂待处理队列——重复施工由 one_active_run_per_task 唯一索引兜底(上方 active 预检 +
122
+ // 下方 catch 合并),写安全由调度器写范围闸门兜底。消息族/owner_task 照旧走 busy 闸。
123
+ try {
124
+ this.store.run(
125
+ `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
126
+ attempt, idempotency_key, write_scopes, model_provider, model_model, model_effort, queued_at)
127
+ VALUES (?, ?, ?, ?, 'task', 'write', ?, ?, 'queued', 1, ?, ?, ?, ?, ?, ?)`,
128
+ runId, task.project_id, task.assignee_bot_id, task.id, triggerType, task.id,
129
+ `task:${task.id}:${Date.now()}:${runId}`, writeScopes, fallbackProvider, fallbackModel, fallbackEffort, createdAt,
130
+ )
131
+ } catch (error ) {
132
+ // 查后插竞态撞 one_active_run_per_task(bot 维度索引已不含 task 运行)——双投胜利方
133
+ // 的同任务 active 运行已在→合并返回其 id 消算,不抛不挂起(D-304 口径沿用到任务维度)。
134
+ if (this.activeRunByTaskId(task.id)) return this.activeRunByTaskId(task.id)
135
+ throw error
136
+ }
127
137
  this.store.run(
128
138
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
129
139
  id('evt'), runId, 'queued', `由 ${actor.type}:${actor.id} 触发`, createdAt,
@@ -166,13 +176,35 @@ export const taskRunMethods = {
166
176
  const runId = id('run')
167
177
  const createdAt = nowIso()
168
178
  const triggerType = kind === 'review' ? 'review_requested' : 'blocked_handoff'
169
- this.store.run(
170
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
171
- attempt, idempotency_key, queued_at)
172
- VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
173
- runId, project.id, owner.id, task.id, kind, triggerType, task.id,
174
- `${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
175
- )
179
+ // busy 闸(DSHBOTS-290):owner 忙时 review/handle 运行同样不落 runs 行(撞
180
+ // one_active_run_per_bot),挂待处理队列空闲建回——与 enqueueTaskRun 同口径。
181
+ // DSHBOTS-300:挂起项提为 hold 闭包,busy 分支与查后插竞态兜底共用。
182
+ const hold = () => this.holdPendingMessage(owner.id, project.id, {
183
+ kind: 'owner_task', messageId: `owner_task:${current.id}:${kind}`, taskId: current.id,
184
+ projectId: project.id, runKind: kind, triggerType, queuedAt: createdAt,
185
+ })
186
+ if (this.botBusy(owner.id, project.id)) {
187
+ hold()
188
+ return null
189
+ }
190
+ try {
191
+ this.store.run(
192
+ `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
193
+ attempt, idempotency_key, queued_at)
194
+ VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
195
+ runId, project.id, owner.id, task.id, kind, triggerType, task.id,
196
+ `${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
197
+ )
198
+ } catch (error ) {
199
+ // DSHBOTS-304:双投胜利方同任务 active 运行已在→合并返回其 id 消算(同 enqueueTaskRun)。
200
+ if (this.isRunBotUniqueViolation(error)) {
201
+ const merged = this.activeRunByTaskId(task.id)
202
+ if (merged) return merged
203
+ hold()
204
+ return null
205
+ }
206
+ throw error
207
+ }
176
208
  this.store.run(
177
209
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
178
210
  id('evt'), runId, 'queued',
@@ -6,7 +6,7 @@
6
6
  import { createRequire } from 'node:module'
7
7
  import { AppError, conflict } from '../errors.js'
8
8
  import { WechatIlinkError } from '../wechat/commands.js'
9
- import { jsonParse, parseMentions } from '../util.js'
9
+ import { jsonParse } from '../util.js'
10
10
  import { answerFailed, answerReceipt, approvalCard, questionCard, wechatToken } from '../wechat/format.js'
11
11
 
12
12
  // 微信登录二维码:服务端直接出 SVG,UI 注入即可,无需前端 QR 库(vendor/qrcode,MIT)。
@@ -127,14 +127,15 @@ export const wechatMethods = {
127
127
  },
128
128
 
129
129
  /**
130
- * 微信直达对话(DSHBOTS-208 起,258 四次拍板后收敛为绝对二值路由):
131
- * /tr 显式转发(key 非空)→ 消息以工作台用户身份插入项目群聊并触发 chat 运行,
132
- * 运行结束的 bot 回复由 run-finish 按 trigger_type='wechat' 推回微信管理员;
133
- * 自由文本(key 为空)→ 一律投项目外 director 专属工作区单聊(不随 direct_project_key
134
- * 绑定、active 项目数变化,路由层无绑定/项目数判断分支),返回
135
- * { director, messageId, firstContact };解析不到 director(通道异常)→ { error: 'no_director' }。
136
- * 项目无可定向 Bot(无 mention 且总监不可用)→ { error: 'no_owner', project };
137
- * 群聊直达成功 → { project, messageId, runBots };显式 key 未命中 → null。
130
+ * 微信直达对话(DSHBOTS-208 起,258 四次拍板,299 会话域三分后收敛为单一去向):
131
+ * 微信通道一律落 director 专属工作区 solo 会话(A 口径:微信=用户↔director 直接通信)——
132
+ * 自由文本(key 为空)与 /tr <key> 显式转发(key 非空)都投 director 的 solo_messages
133
+ * 并触发 solo_chat 运行(trigger_type='wechat',运行收尾按此把回复推回微信管理员,
134
+ * run-finish 回程链路对 chat/solo 两类同门禁,语义不回退);
135
+ * /tr 的 key 命中项目后在正文携带 [项目 KEY] 上下文,director 自行把工作派进对应项目,
136
+ * 不再以工作台用户身份插项目群聊触发 chat 运行(原路径 trigger_type='wechat' 的
137
+ * chat 运行落项目控制面会话,违反三分域);key 未命中 → null;解析不到 director
138
+ * (通道异常)→ { error: 'no_director' }。
138
139
  */
139
140
  async wechatChat(key, body) {
140
141
  let project = null
@@ -146,22 +147,23 @@ export const wechatMethods = {
146
147
  if (!project) return null
147
148
  } else {
148
149
  // DSHBOTS-258 绝对口径:自由文本永远走 director 专属工作区,用户不直接进群。
149
- // 路由层不出现 direct_project_key 绑定判断,也不出现 active 项目数量判断——
150
- // 唯一分流条件是 /tr 显式转发(key 非空)。解析不到 director 属通道异常,
151
- // 独立 no_director 出口(不复用 no_target:那是「需要用户选项目」的语义链)。
152
150
  const director = this.wechatDirectorBot()
153
151
  if (director) return this.wechatDirectorChat(director, String(body ?? ''))
154
152
  return { error: 'no_director' }
155
153
  }
156
- const members = this.membersOf(project.id).filter(bot => bot.status === 'active')
157
- const text = String(body ?? '')
158
- // 无 mention 时 sendMessage 兜底定向 owner_bot_id:总监必须可用,否则消息发出无人接。
159
- if (parseMentions(text, members).length === 0
160
- && !members.some(bot => bot.id === project.owner_bot_id)) {
161
- return { error: 'no_owner', project }
162
- }
163
- const result = await this.sendMessage(project.id, text, { type: 'user', id: this.localUserId }, null, [], { origin: 'wechat' })
164
- return { project, ...result }
154
+ // DSHBOTS-299 A 口径:/tr 显式转发同落 director 专属工作区——正文带 [项目 KEY]
155
+ // 上下文(与自由文本的 [微信管理员] 前缀同链路),由 director 以团队工具派单进项目。
156
+ const director = this.wechatDirectorBot()
157
+ if (!director) return { error: 'no_director', project }
158
+ const adminPeerId = this.wechat?.status?.()?.adminPeerId ?? null
159
+ const result = await this.sendSoloMessage(
160
+ director.id,
161
+ `${WECHAT_SOLO_SOURCE_MARK}[项目 ${project.key}] ${String(body ?? '')}`,
162
+ { type: 'user', id: adminPeerId ?? 'user:wechat' },
163
+ [],
164
+ { origin: 'wechat' },
165
+ )
166
+ return { project, director, messageId: result?.messageId ?? null }
165
167
  },
166
168
 
167
169
  /**
@@ -0,0 +1,165 @@
1
+ // DSHBOTS-294 子代理账本(ADR §4.2.1):宿主事件缝 → 所属 task 运行的 run_events。
2
+ // 双缝互补:tools 瀑布带 caller agent(父归属权威源,任务号标签在参数里);
3
+ // subagent/start|end 带 stopReason+lastAssistantMessage(终态摘要源,载荷无父身份,
4
+ // 靠 tools/result 配对或唯一 running task 运行兜底归属)。子代理不占 runs 行(§4.2)。
5
+ import { id, nowIso } from './util.js'
6
+
7
+ const SUBAGENT_TOOLS = new Set(['subagent', 'subagent_fork'])
8
+ const SUMMARY_LIMIT = 400
9
+ const STASH_LIMIT = 64
10
+
11
+ // 任务号标签(DSHBOTS-292 约定标签=任务号,如 DSHBOTS-294):优先 description,其次 prompt。
12
+ export function taskLabelOf(args) {
13
+ const source = typeof args?.description === 'string' ? args.description
14
+ : typeof args?.prompt === 'string' ? args.prompt : ''
15
+ const match = source.match(/\b[A-Z][A-Z0-9]{1,10}-\d{1,6}\b/)
16
+ if (match) return match[0]
17
+ const trimmed = source.trim()
18
+ return trimmed ? trimmed.slice(0, 60) : null
19
+ }
20
+
21
+ const truncate = (text) => {
22
+ const value = typeof text === 'string' ? text : text == null ? '' : JSON.stringify(text)
23
+ return value.length > SUMMARY_LIMIT ? `${value.slice(0, SUMMARY_LIMIT)}…` : value
24
+ }
25
+
26
+ // 在插件根 ctx 注册事件监听(根级注册面实测见 tests/subagent-ledger.test.ts)。
27
+ export function installSubagentLedger(ctx, store, logger) {
28
+ // callId → 派发时快照(tools/result 按 callId 配对父归属)
29
+ const byCall = new Map()
30
+ // botId → 未消费的标签栈(subagent/end 兜底归属时取最近一次派发的标签)
31
+ const labelsByBot = new Map()
32
+ // 暂存 subagent/end 载荷:childId → info,tools/result 到达时按 id 出现在结果 JSON 里配对
33
+ const endsByChild = new Map()
34
+
35
+ const ownerRunOf = (agentSessionId) => {
36
+ const binding = agentSessionId
37
+ ? store.get('SELECT * FROM session_bindings WHERE session_id = ?', agentSessionId)
38
+ : undefined
39
+ if (!binding?.bot_id) return null
40
+ const run = store.get(
41
+ "SELECT id FROM runs WHERE bot_id = ? AND kind = 'task' AND status = 'running' ORDER BY started_at DESC LIMIT 1",
42
+ binding.bot_id,
43
+ )
44
+ return run ? { botId: binding.bot_id, runId: run.id } : null
45
+ }
46
+
47
+ const record = (runId, type, message) => store.run(
48
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
49
+ id('rev'), runId, type, message, nowIso(),
50
+ )
51
+
52
+ const stashLabel = (botId, label) => {
53
+ const list = labelsByBot.get(botId) ?? []
54
+ list.push(label)
55
+ if (list.length > STASH_LIMIT) list.shift()
56
+ labelsByBot.set(botId, list)
57
+ }
58
+
59
+ const takeLabel = (botId) => {
60
+ const list = labelsByBot.get(botId)
61
+ const label = list?.shift()
62
+ if (list && list.length === 0) labelsByBot.delete(botId)
63
+ return label ?? null
64
+ }
65
+
66
+ const endsAt = (childId, info) => {
67
+ if (endsByChild.size >= STASH_LIMIT) endsByChild.delete(endsByChild.keys().next().value)
68
+ endsByChild.set(childId, info)
69
+ }
70
+
71
+ // subagent/end 的兜底归属:事件时刻全库恰好一个 bot 有 running task 运行、且该 bot
72
+ // 无待配对的工具瀑布调用(tools/result 会按 callId 精确落账,优先于兜底)才落账。
73
+ const soleRunningTaskRun = () => {
74
+ const rows = store.all("SELECT bot_id, id FROM runs WHERE kind = 'task' AND status = 'running'")
75
+ return rows.length === 1 ? rows[0] : null
76
+ }
77
+
78
+ const resultSummary = (result) => {
79
+ if (result == null) return '-'
80
+ if (typeof result === 'string') return truncate(result)
81
+ const parts = []
82
+ for (const key of ['stopReason', 'status', 'error', 'code', 'message']) {
83
+ if (result[key] != null) parts.push(`${key}=${truncate(String(result[key]))}`)
84
+ }
85
+ return parts.length > 0 ? parts.join(' ') : truncate(result)
86
+ }
87
+
88
+ const offs = []
89
+ const on = (name, listener) => {
90
+ const off = ctx.on?.(name, listener)
91
+ if (off) offs.push(off)
92
+ return off
93
+ }
94
+
95
+ on('tools/pre-execute', async (exec, next) => {
96
+ try {
97
+ if (SUBAGENT_TOOLS.has(exec?.name)) {
98
+ const owner = ownerRunOf(exec?.agent?.session?.id)
99
+ if (owner) {
100
+ const label = taskLabelOf(exec?.arguments)
101
+ record(owner.runId, 'subagent_spawned', `${exec.name} label=${label ?? '-'} bot=${owner.botId}`)
102
+ byCall.set(exec.callId, { ...owner, label })
103
+ stashLabel(owner.botId, label)
104
+ }
105
+ }
106
+ } catch (error) {
107
+ logger?.warn?.('dsh-team: subagent ledger pre-execute: %s', (error )?.message ?? error)
108
+ }
109
+ return next()
110
+ })
111
+
112
+ on('subagent/start', (info) => {
113
+ try {
114
+ if (info?.id) endsAt(info.id, { started: true })
115
+ } catch {}
116
+ })
117
+
118
+ on('subagent/end', (info) => {
119
+ try {
120
+ if (!info?.id) return
121
+ endsAt(info.id, info)
122
+ const sole = soleRunningTaskRun()
123
+ const pendingCall = sole ? [...byCall.values()].some(entry => entry.botId === sole.bot_id) : false
124
+ if (!sole || pendingCall) return
125
+ endsByChild.delete(info.id)
126
+ const label = takeLabel(sole.bot_id)
127
+ record(sole.id, 'subagent_result',
128
+ `label=${label ?? '-'} stop=${info.stopReason ?? '-'} summary=${truncate(info.lastAssistantMessage ?? '')}`)
129
+ } catch (error) {
130
+ logger?.warn?.('dsh-team: subagent ledger end: %s', (error )?.message ?? error)
131
+ }
132
+ })
133
+
134
+ on('tools/result', (exec, result) => {
135
+ try {
136
+ if (!SUBAGENT_TOOLS.has(exec?.name)) return
137
+ const entry = byCall.get(exec?.callId)
138
+ if (!entry) return
139
+ byCall.delete(exec?.callId)
140
+ // 配对暂存的 subagent/end:child id 出现在结果 JSON 里即认领其终态摘要
141
+ let matched = null
142
+ const haystack = JSON.stringify(result ?? {})
143
+ for (const [childId, info] of endsByChild) {
144
+ if (haystack.includes(childId)) {
145
+ matched = info
146
+ endsByChild.delete(childId)
147
+ break
148
+ }
149
+ }
150
+ const stop = matched?.stopReason
151
+ const summary = matched?.lastAssistantMessage ?? resultSummary(result?.value ?? result)
152
+ record(entry.runId, 'subagent_result',
153
+ `label=${entry.label ?? '-'} stop=${stop ?? '-'} summary=${truncate(summary ?? '')}`)
154
+ } catch (error) {
155
+ logger?.warn?.('dsh-team: subagent ledger result: %s', (error )?.message ?? error)
156
+ }
157
+ })
158
+
159
+ return () => {
160
+ for (const off of offs) off()
161
+ byCall.clear()
162
+ labelsByBot.clear()
163
+ endsByChild.clear()
164
+ }
165
+ }