dsh-team-bots 0.2.347 → 0.2.393

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 (52) 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 +2 -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 +71 -1
  17. package/src/services/proposals.js +36 -1
  18. package/src/services/questions.js +16 -3
  19. package/src/services/run-finish.js +18 -3
  20. package/src/services/runs.js +369 -34
  21. package/src/services/runtime/prompt.js +135 -88
  22. package/src/services/runtime/session.js +260 -72
  23. package/src/services/scheduler.js +135 -97
  24. package/src/services/task-dispatch.js +112 -5
  25. package/src/services/task-review.js +19 -1
  26. package/src/services/task-runs.js +53 -15
  27. package/src/services/tasks.js +81 -0
  28. package/src/services/wechat.js +23 -21
  29. package/src/subagent-ledger.js +165 -0
  30. package/src/tools.js +5 -5
  31. package/src/wechat/commands.js +3 -1
  32. package/ui/app.js +4 -14
  33. package/ui/i18n/en/chat.js +11 -11
  34. package/ui/i18n/en/common.js +0 -12
  35. package/ui/i18n/en/nav.js +0 -4
  36. package/ui/i18n/en/settings.js +14 -9
  37. package/ui/i18n/en/tasks.js +0 -1
  38. package/ui/i18n/en/usage.js +4 -7
  39. package/ui/i18n/zh/chat.js +11 -11
  40. package/ui/i18n/zh/common.js +0 -12
  41. package/ui/i18n/zh/nav.js +0 -4
  42. package/ui/i18n/zh/settings.js +13 -9
  43. package/ui/i18n/zh/tasks.js +0 -1
  44. package/ui/i18n/zh/usage.js +4 -7
  45. package/ui/modules/cards.js +19 -5
  46. package/ui/modules/composer.js +16 -3
  47. package/ui/modules/i18n.js +10 -0
  48. package/ui/modules/modal-forms.js +15 -8
  49. package/ui/modules/settings.js +9 -0
  50. package/ui/modules/util.js +0 -2
  51. package/ui/styles/frame.css +0 -28
  52. package/ui/styles/wide.css +0 -3
@@ -9,8 +9,10 @@ import { applyRetention, reconcileUsage } from '../usage-reconcile.js'
9
9
  import { id, jsonParse, nowIso, text } from '../util.js'
10
10
  import { MAX_RATE_LIMIT_RETRIES, isQuotaExhausted, isRetryChainError } from './backoff.js'
11
11
  import { ensureTaskRelationsSchema, unsatisfiedBlockedDeps } from './task-relations.js'
12
+ import { TASK_BUDGET_ROUNDS, TRANSITIONS, taskDeadlineInfo } from './tasks.js'
12
13
  import { effectiveWriteScopes, writeScopesOverlap } from './write-scopes.js'
13
14
  import { runReviewWatchdog } from './review-watchdog.js'
15
+ import { staleCardHit } from './notify.js'
14
16
 
15
17
  // plan_wait 到期派生的宽限上界:退避到期超过这个时长视为时过境迁,不再自动续跑。
16
18
  const PLAN_RETRY_MAX_LATE_SECONDS = 24 * 3600
@@ -45,14 +47,6 @@ export function runHoldsWriteLock({ kind, mode, taskStatus } = {} ) {
45
47
  // task_run 的先写者赢是防重复派生闸,同样保持默认(先写者赢)不动。
46
48
  const OUTBOX_COALESCE_KINDS = new Set(['review_delegate_auto'])
47
49
 
48
- // 入站消息合批(DSHBOTS-231):只合并「人发的消息运行」——同一条绑定道内、仍在排队的
49
- // chat / solo_chat 运行。任务运行、派生运行(review/handle/memory_review/vision)与私信
50
- // (dm/dm_reply,各自有按消息的回信契约)都不参与:合并它们会破坏既有的投递语义。
51
- const RUN_COALESCE_KINDS = new Set(['chat', 'solo_chat'])
52
- // 默认保守上限:一次运行最多合并 5 条消息、且只合并入队时间相差 30 秒内的排队消息。
53
- const COALESCE_MAX_MESSAGES_DEFAULT = 5
54
- const COALESCE_WINDOW_MS_DEFAULT = 30_000
55
-
56
50
  export const schedulerMethods = {
57
51
 
58
52
  // outbox:把「状态变更 → 建运行」这一跳变成可重放的持久交接。
@@ -268,90 +262,17 @@ export const schedulerMethods = {
268
262
  throw error
269
263
  },
270
264
 
271
- // 同一条会话上的运行必须串行(原注释意图);DSHBOTS-219 分身模型:串行键从「bot」
272
- // 放细到「会话绑定维度」(= 一条分身通道)——单聊/各项目群聊/私信互不阻塞,
273
- // 一路 pending(如单聊提权审批)不再挡死同一 bot 的其它通道。
274
- // 键与 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 串行域互不替代。
275
273
  claimKey(run) {
276
274
  if (run.kind === 'task' && run.task_id) return `task:${run.task_id}`
277
- return this.sessionLaneKey(run)
278
- },
279
- // 会话绑定的通道键(纯查库推导,无副作用):task / solo / dm / project 四类绑定各归各道。
280
- bindingLaneKey(binding) {
281
- if (binding.kind === 'task' && binding.task_id) return `task:${binding.task_id}`
282
- if (binding.kind === 'solo') return `solo:${binding.bot_id}`
283
- if (binding.kind === 'dm') return `dm:${binding.bot_id}:${binding.project_id}`
284
- return `project:${binding.bot_id}:${binding.project_id}`
285
- },
286
- // 非任务运行的通道键:按该运行实际会落到的会话推导(与 ensureSession 的 kind0 同一套映射)。
287
- // solo_chat 与无项目 vision 落 solo 会话;chat/review/handle/memory_review 与带项目 vision
288
- // 落项目会话;dm 落私信会话;dm_reply 按来信 origin 回对应会话(task_id 留空躲唯一索引,
289
- // 任务通道只能从 bot_messages 解);rollover_summary 复用指定旧会话,按该会话当前绑定
290
- // 的通道键对齐(防与复用同一会话的群聊并发——runtime 的 pending 按会话一对一)。
291
- sessionLaneKey(run) {
292
- if (run.kind === 'solo_chat' || (run.kind === 'vision' && !run.project_id)) return `solo:${run.bot_id}`
293
- if (run.kind === 'rollover_summary') {
294
- if (!run.session_id) return `bot:${run.bot_id}`
295
- const binding = this.store.get('SELECT * FROM session_bindings WHERE session_id = ?', run.session_id)
296
- return binding ? this.bindingLaneKey(binding) : `session:${run.session_id}`
297
- }
298
- if (run.kind === 'dm_reply') {
299
- const message = run.trigger_ref
300
- ? this.store.get('SELECT origin_kind, origin_task_id FROM bot_messages WHERE id = ?', run.trigger_ref)
301
- : null
302
- if (message?.origin_kind === 'task' && message.origin_task_id) return `task:${message.origin_task_id}`
303
- if (message?.origin_kind === 'dm') return `dm:${run.bot_id}:${run.project_id}`
304
- return `project:${run.bot_id}:${run.project_id}`
305
- }
306
- if (run.kind === 'dm') return `dm:${run.bot_id}:${run.project_id}`
307
- return `project:${run.bot_id}:${run.project_id}`
308
- },
309
-
310
- // 入站消息合批(DSHBOTS-231):领取一条运行后,把同一条绑定道内仍在排队的消息运行合并
311
- // 进来——被合并的运行置 canceled(error_code='MERGED'),消息 id 记入本运行的
312
- // merged_messages,executeRun 据此把多条消息一次性注入同一轮上下文,不再一条消息一次运行。
313
- // 只在 claimKey 相同的通道内合并,D-219 的四道解耦语义不变;合并窗口与条数上限走 settings。
314
- // 并发安全:被合并的运行用「queued → canceled」原子更新抢占,抢不到(另一拍已领取)就跳过。
315
- coalesceQueuedRuns(run) {
316
- if (!RUN_COALESCE_KINDS.has(run.kind)) return []
317
- const max = Number(this.store.setting('coalesce_max_messages', String(COALESCE_MAX_MESSAGES_DEFAULT)))
318
- if (!Number.isFinite(max) || max <= 1) return []
319
- const windowMs = Number(this.store.setting('coalesce_window_ms', String(COALESCE_WINDOW_MS_DEFAULT)))
320
- const claimedQueuedAt = Date.parse(run.queued_at)
321
- const laneKey = this.claimKey(run)
322
- const candidates = this.store.all(
323
- `SELECT * FROM runs WHERE status = 'queued' AND id != ? AND kind = ?
324
- ORDER BY queued_at LIMIT 100`,
325
- run.id, run.kind,
326
- )
327
- const mergedIds = []
328
- const mergedRuns = []
329
- for (const candidate of candidates) {
330
- if (mergedIds.length >= max - 1) break
331
- if (!candidate.trigger_ref) continue
332
- if (this.claimKey(candidate) !== laneKey) continue
333
- const queuedAt = Date.parse(candidate.queued_at)
334
- if (!Number.isFinite(queuedAt) || !Number.isFinite(claimedQueuedAt)) continue
335
- if (queuedAt < claimedQueuedAt || queuedAt - claimedQueuedAt > windowMs) continue
336
- const changed = this.store.run(
337
- `UPDATE runs SET status = 'canceled', ended_at = ?, error_code = 'MERGED', error_message = ?
338
- WHERE id = ? AND status = 'queued'`,
339
- nowIso(), `消息已合并进运行 ${run.id},不再单独执行`, candidate.id,
340
- )
341
- if (Number(changed?.changes ?? 0) !== 1) continue
342
- mergedIds.push(candidate.trigger_ref)
343
- mergedRuns.push(candidate)
344
- }
345
- if (!mergedIds.length) return []
346
- this.store.run('UPDATE runs SET merged_messages = ? WHERE id = ?', JSON.stringify(mergedIds), run.id)
347
- this.insertRunEvent(
348
- run.id, 'runs_merged',
349
- `同通道 ${mergedIds.length} 条排队消息合并进本次运行:${mergedIds.map(item => item.slice(-6)).join('、')}`,
350
- )
351
- for (const candidate of mergedRuns) {
352
- this.insertRunEvent(candidate.id, 'merged_into', `排队消息已合并进运行 ${run.id}`)
353
- }
354
- return mergedRuns
275
+ return `bot:${run.bot_id}:${run.project_id ?? '~solo'}`
355
276
  },
356
277
 
357
278
  // 运行超时由 runtime 的定时器负责;这里补充“还活着但没有任何进展”的判定。
@@ -496,6 +417,101 @@ export const schedulerMethods = {
496
417
  return canceled
497
418
  },
498
419
 
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
424
+ // 验收守门同拍接入,不新增常驻进程);判定与防重见 notify.ts 的纯函数与每日上限。
425
+ // 逐卡容错:单卡异常只 warn,不拖垮整轮扫描。
426
+ scanStaleCards() {
427
+ const rows = this.store.all(
428
+ `SELECT t.id, t.status, t.updated_at, t.number,
429
+ p.id AS project_id, p.key AS project_key, p.owner_bot_id
430
+ FROM tasks t JOIN projects p ON p.id = t.project_id
431
+ WHERE t.status IN ('in_review', 'blocked', 'todo', 'backlog') AND p.status = 'active'`,
432
+ )
433
+ const reminded = []
434
+ for (const row of rows) {
435
+ try {
436
+ const hit = staleCardHit(row)
437
+ if (!hit) continue
438
+ const delivered = this.notifyStaleCardOwner({
439
+ project: { id: row.project_id, key: row.project_key, owner_bot_id: row.owner_bot_id },
440
+ task: row,
441
+ hit,
442
+ })
443
+ if (delivered) reminded.push(row.id)
444
+ } catch (error ) {
445
+ this.logger.warn?.('dsh-team: 滞留扫描单卡失败 %s: %s', row.id, error?.message ?? error)
446
+ }
447
+ }
448
+ return reminded
449
+ },
450
+
451
+ // 任务级死线判定(DSHBOTS-274):纯同步——领取路径不得为此引入 await 边界, // 否则 claim 与状态写之间会开窗(tests/members.test.js 站内竞态教训)。
452
+ taskPastDeadline(task) {
453
+ const { deadlineMs } = taskDeadlineInfo(this.store, task)
454
+ return deadlineMs !== null && Date.now() > deadlineMs
455
+ },
456
+
457
+ // 任务级死线升级(DSHBOTS-274;DSHBOTS-281 口径升级):超线的 queued 施工运行拒绝启动
458
+ // ——运行置 canceled(TASK_DEADLINE,run_events 留 task_deadline 锚),卡面落系统评论
459
+ // (D-269 口径=原因+事实:点名项目总监,重派即自动重置死线窗口,不再写转接 owner 的话术),
460
+ // status 转 blocked(走 updateTask 单一状态流转漏斗,非法转换只评论不转),并复用系统消息
461
+ // 通道通知项目总监(notify.ts insertMessage 同款,进任务线程 + mentions 点名 owner_bot_id)。
462
+ // 幂等:enqueueTaskRun 同卡同时只有一条活跃运行,运行取消后不再进候选,每次派发至多升级
463
+ // 一次;重派即新窗口(基准=最新 queued_at),新窗口内预算×2 耗尽仍照常拦截。
464
+ async escalateTaskPastDeadline(task, runId) {
465
+ const { deadlineMs } = taskDeadlineInfo(this.store, task)
466
+ if (deadlineMs === null || Date.now() <= deadlineMs) return false
467
+ const project = this.projectRow(task.project_id)
468
+ const identifier = `${project?.key ?? 'T'}-${task.number}`
469
+ const deadlineIso = new Date(deadlineMs).toISOString()
470
+ // 点名总监(projects.owner_bot_id):留痕正文带总监花名,mentions 同点位名,收件人即第一负责人。
471
+ const directorName = project?.owner_bot_id
472
+ ? this.botRow(project.owner_bot_id)?.name ?? '总监'
473
+ : '总监'
474
+ const windowMinutes = Number(task.time_budget_minutes) * TASK_BUDGET_ROUNDS
475
+ const body = `【${identifier}】超时中止(预算×${TASK_BUDGET_ROUNDS})已到,任务未关单:总监 ${directorName} 重派即自动重置死线窗口(新窗口剩余 ${windowMinutes} 分钟),请消化处理(死线 ${deadlineIso})。`
476
+ const now = nowIso()
477
+ const commentId = id('cmt')
478
+ this.store.transaction(() => {
479
+ this.store.run(
480
+ "UPDATE runs SET status = 'canceled', ended_at = ?, error_code = 'TASK_DEADLINE', error_message = ? WHERE id = ? AND status = 'queued'",
481
+ now, body, runId,
482
+ )
483
+ this.store.run(
484
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
485
+ id('evt'), runId, 'task_deadline', `整卡死线已到(${deadlineIso}),拒绝启动新施工运行`, now,
486
+ )
487
+ this.store.run(
488
+ 'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
489
+ commentId, task.id, 'system', 'system', body, now,
490
+ )
491
+ this.addTaskEvent(task.id, 'commented', { type: 'system', id: 'system' }, { commentId, deadline: deadlineIso, runId })
492
+ })
493
+ if (TRANSITIONS[task.status]?.has('blocked')) {
494
+ try {
495
+ await this.updateTask(task.id, { status: 'blocked' }, { type: 'system', id: 'system' })
496
+ } catch (error ) {
497
+ this.logger.warn?.('dsh-team: 死线转 blocked 失败 %s: %s', identifier, error?.message ?? error)
498
+ }
499
+ }
500
+ try {
501
+ this.insertMessage({
502
+ projectId: task.project_id,
503
+ senderType: 'system',
504
+ senderId: 'system',
505
+ taskId: task.id,
506
+ body,
507
+ mentions: project?.owner_bot_id ? [project.owner_bot_id] : [],
508
+ })
509
+ } catch (error ) {
510
+ this.logger.warn?.('dsh-team: 死线总监通知失败 %s: %s', identifier, error?.message ?? error)
511
+ }
512
+ return true
513
+ },
514
+
499
515
  async tick() {
500
516
  if (this.ticking || !this.started) return
501
517
  this.ticking = true
@@ -510,17 +526,23 @@ export const schedulerMethods = {
510
526
  this.retryExpiredPlanWaits()
511
527
  // 陈旧排队运行守卫(DSHBOTS-110):先于候选查询清掉任务已终态的 queued 任务运行。
512
528
  this.cancelStaleQueuedTaskRuns()
529
+ // 争用口径 A 收口(DSHBOTS-289):bot 空闲时把挂起消息建回运行(合批成一条),
530
+ // 建回的 queued 行随本拍候选查询一并领取。
531
+ this.drainPendingMessages()
513
532
  // 验收滞留守门(DSHBOTS-194):in_review 卡静置超阈值即注入 owner 系统提醒;
514
533
  // 内部自容错(异常只 warn),阈值 0 = 关闭时直接返回。
515
534
  runReviewWatchdog(this)
535
+ // 滞留阈值兜底扫描(DSHBOTS-280;DSHBOTS-295 扩待执行宽档):in_review/blocked/
536
+ // 待执行(todo/backlog)超 24h/48h/72h 三档向 owner 只提醒不自动处置;
537
+ // 内部逐卡容错(单卡异常只 warn)。
538
+ this.scanStaleCards()
516
539
  const activeRows = this.store.all(
517
540
  // 写占用只看「进行中」的任务(DSHBOTS-73,用户口径):join tasks 取任务当前状态,
518
541
  // 任务不在 in_progress 的写运行不再占槽——离开进行中即释放占用/锁定。
519
542
  // 非任务运行 LEFT JOIN 出的 task_status 为空,按运行自身判定,不受这条闸门影响。
520
- // trigger_ref/session_id 供 claimKey 通道推导(dm_reply 按来信 origin、rollover_summary
521
- // 按旧会话绑定)——在跑侧与候选侧必须算出同一个键,串行才不失效(DSHBOTS-219)。
543
+ // claimKey 串行域 = (bot, 工作区)(DSHBOTS-308):键只读 bot_id/project_id(均在列面),
544
+ // 在跑侧与候选侧算的是同一 run 行的同一列,串行不失效(承 DSHBOTS-219 口径)。
522
545
  `SELECT r.bot_id, r.kind, r.task_id, r.project_id, r.mode, r.write_scopes, r.trigger_type,
523
- r.trigger_ref, r.session_id,
524
546
  t.status AS task_status
525
547
  FROM runs r LEFT JOIN tasks t ON t.id = r.task_id
526
548
  WHERE r.status = 'running'`,
@@ -546,13 +568,19 @@ export const schedulerMethods = {
546
568
  if (activeTotal >= maxRuns + 1) return
547
569
  // 出队顺序:任务运行按任务优先级(urgent 先),其余运行视同 high——用户交互不能被任务积压拖死;
548
570
  // 同优先级按入队时间,保证 FIFO 不饿死老运行。
571
+ // DSHBOTS-272 用户提问不被静默压后:不动用户运行的档位(同车道先入队的 review/handle
572
+ // 等人机运行契约不变,见 tests/avatar-lanes.test.js),改为把通知/伙伴唤醒触发的 chat
573
+ // 运行(触发消息 sender_type='bot')降到机器流量档——同车道内用户提问(tier 1)必然
574
+ // 先于它领取,即使提问后到;通知备忘让位于一切人机交互与 urgent/high 任务。
549
575
  // 候选过滤(DSHBOTS-110):任务已终态(done/canceled)的 queued 任务运行不再领取;
550
576
  // 只排 kind='task',非任务运行不受影响。LEFT JOIN 出 NULL 的孤儿任务运行不过滤。
551
577
  const candidates = this.store.all(
552
578
  `SELECT r.* FROM runs r LEFT JOIN tasks t ON t.id = r.task_id
579
+ LEFT JOIN messages m ON m.id = r.trigger_ref
553
580
  WHERE r.status = 'queued'
554
581
  AND NOT (r.kind = 'task' AND COALESCE(t.status, '') IN ('done', 'canceled'))
555
582
  ORDER BY CASE
583
+ WHEN r.kind = 'chat' AND m.sender_type = 'bot' THEN 2
556
584
  WHEN r.kind <> 'task' OR t.priority IS NULL THEN 1
557
585
  WHEN t.priority = 'urgent' THEN 0
558
586
  WHEN t.priority = 'high' THEN 1
@@ -581,7 +609,8 @@ export const schedulerMethods = {
581
609
  // DSHBOTS-112:单聊读图代理运行与 solo_chat 同样不带 project_id,豁免项目闸门。
582
610
  // DSHBOTS-145:结转摘要运行同理——单聊摘要运行不带 project_id,只有项目摘要运行
583
611
  // 才需要项目上下文;否则 solo 摘要会被误判 MISSING_CONTEXT 直接失败。
584
- const needsProject = run.kind === 'rollover_summary'
612
+ // DSHBOTS-286:闲时压缩运行同理。
613
+ const needsProject = run.kind === 'rollover_summary' || run.kind === 'session_compact'
585
614
  ? Boolean(run.project_id)
586
615
  : run.kind !== 'solo_chat' && !(run.kind === 'vision' && !run.project_id)
587
616
  const project = run.project_id ? this.store.get('SELECT * FROM projects WHERE id = ?', run.project_id) : null
@@ -642,15 +671,24 @@ export const schedulerMethods = {
642
671
  }
643
672
  continue
644
673
  }
674
+ // 任务级死线(DSHBOTS-274):施工运行(kind='task')领取前检查整卡死线——
675
+ // 死线 = 派发基准 + time_budget_minutes × TASK_BUDGET_ROUNDS(默认 2 轮,
676
+ // 延期阀见 tasks.ts updateTask)。超线即拒绝启动新施工运行并自动升级
677
+ // (评论 + blocked + owner 通知,escalateTaskPastDeadline);
678
+ // review/handle 等派生运行不走此闸(kind!=='task' 豁免,死线只拦施工轮)。
679
+ // 判定同步、升级异步放行:不为本闸在领取路径引入 await 边界。
680
+ if (taskRow && this.taskPastDeadline(taskRow)) {
681
+ void this.escalateTaskPastDeadline(taskRow, run.id).catch(error => this.logger.warn?.('dsh-team: 死线升级失败 %s: %s', run.id, error?.message ?? error))
682
+ continue
683
+ }
645
684
  }
646
685
  const claimed = this.store.run(
647
686
  "UPDATE runs SET status = 'running', started_at = ?, last_progress_at = ? WHERE id = ? AND status = 'queued'",
648
687
  nowIso(), nowIso(), run.id,
649
688
  )
650
689
  if (Number(claimed.changes) !== 1) continue
651
- // 入站消息合批(DSHBOTS-231):领取后把同通道仍在排队的消息并进本次运行,
652
- // 被合并的运行置 canceled/MERGED,消息 id 落到 merged_messages 供 executeRun 注入。
653
- this.coalesceQueuedRuns(run)
690
+ // 消息合批(DSHBOTS-290 语义回补):合批在 bot 空闲建回时完成(drainPendingMessages,
691
+ // 含 D-272 用户提问保护/窗口/上限),领取侧不二次合批——窗口/上限已在建回侧消费。
654
692
  // 借用了人的消息保底槽(超出并发上限放行):记事件并占住额外槽,下一次归还前不再放第二条。
655
693
  if (human && activeTotal >= maxRuns) {
656
694
  humanSlotTaken = true
@@ -11,6 +11,18 @@ import { filterIgnoredWriteScopes, parseWriteScopes, parseWriteScopesFromDescrip
11
11
  import { resolveSandboxOverride } from './file-policy.js'
12
12
  import { ensureTaskSandboxSchema } from './task-sandbox-schema.js'
13
13
 
14
+ // 勘误并卡提示(DSHBOTS-276,P1 派单质量前置)的判定常量:新卡标题含修正类关键词 +
15
+ // 同项目同承接人近 7 天 done 卡写范围有交集,双条件同时命中才在卡面描述尾部追加并卡提示行。
16
+ // 仅提示不拦截:D-82 重复卡闸、D-270 领取闸等既有拒绝行为一概不变。
17
+ const CORRECTION_TITLE_RE = /修正|勘误|补充|改写/
18
+ const RECENT_DONE_WINDOW_MS = 7 * 86_400_000
19
+
20
+ // 核验纪律派单闸关键词(DSHBOTS-303,保守集合,取舍锚):只取「核验/审计/复核」三词。
21
+ // 「验收」单用常出现在实施卡(如「跑通验收流程」),「验证」是普遍实施动词(如「跑通验证
22
+ // 流程」)——纳入即误伤实施卡,均不含;「红验证/子代理核验/验收核验」等复合词已被「核验」
23
+ // 覆盖。成员卡面自校要求(交付前自跑测试)不含三词,天然不命中。
24
+ export const VERIFICATION_TASK_KEYWORDS = ['核验', '审计', '复核']
25
+
14
26
  export const taskDispatchMethods = {
15
27
  // 派发门禁(DSHBOTS-262):暂停中的 Bot 不接新卡——新建派单、改派、重派一律拒绝,
16
28
  // 先恢复(bot status → active)再派;归档/移除等其余不可用态沿用 assertMember 既有口径。
@@ -19,12 +31,61 @@ export const taskDispatchMethods = {
19
31
  if (bot?.status === 'paused') throw badRequest(`Bot ${bot.name} 已暂停,先恢复再派卡`)
20
32
  this.assertMember(projectId, botId)
21
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
+ },
59
+ // 无主卡领取开工的写范围声明闸门(DSHBOTS-270):与 assignFromBot「派单必须声明写
60
+ // 范围」同口径的预判——卡面清单优先,空则从描述「写范围:」行兜底解析
61
+ // (parseWriteScopesFromDescription),再过忽略规则清洗(全部命中 .gitignore 被剔除
62
+ // = 实际未声明)。拒绝文案按 D-269 口径 = 原因 + 替代命令;带声明的卡直接放行。
63
+ assertClaimScopes(task, project) {
64
+ const declared = readWriteScopes(task.write_scopes)
65
+ const scopes = filterIgnoredWriteScopes(
66
+ declared.length ? declared : parseWriteScopesFromDescription(task.description),
67
+ this.projectWorkDir(project),
68
+ ).kept
69
+ if (scopes.length) return
70
+ throw badRequest(
71
+ `领取开工必须声明写范围:任务 ${project.key}-${task.number} 未声明写范围,`
72
+ + '其写运行会与同项目其他写运行全部保守串行,一条卡即可堵死队列。'
73
+ + '请先补声明再领取:用工作台 update_task / task_update_scopes 给该卡补 write_scopes,'
74
+ + '或在卡面描述里写一行「写范围:a, b」(由 parseWriteScopesFromDescription 兜底解析);'
75
+ + '补声明后重新领取即可按声明范围并行。',
76
+ )
77
+ },
22
78
  // sandboxOverride 选项(DSHBOTS-156):undefined=不动(重派未传 sandbox 时保留旧覆盖);
23
79
  // null=显式清掉回落 bot 配置档(重派传 sandbox='inherit');字符串=收紧档(派发入口已校验)。
24
80
  async assignTask(taskId, botId, actor = this.actor(), { autoStart = true, sandboxOverride } = {} ) {
25
81
  const task = this.taskRow(taskId)
26
82
  const project = this.projectRow(task.project_id)
27
83
  this.assertDispatchTarget(project.id, botId)
84
+ // 共享板无主卡声明闸门(DSHBOTS-270):无主卡获得 owner 即领取开工——assignTask 稍后
85
+ // 会排 task_run outbox 进施工,未声明写范围的写运行被调度器按「未声明」保守串行
86
+ // (scheduler 既定语义不动),既堵自己也占道。与总监派单同口径在入口拒绝;
87
+ // 改派(卡已有 owner)与 autoStart=false 的重派/存量补挂流程不在此口。
88
+ if (!task.assignee_bot_id && autoStart !== false) this.assertClaimScopes(task, project)
28
89
  const active = this.store.get(
29
90
  "SELECT id, kind FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
30
91
  taskId,
@@ -188,7 +249,14 @@ export const taskDispatchMethods = {
188
249
  if (!binding) throw forbidden('只有项目群中的 Bot 可以执行该操作')
189
250
  if (!binding.project_id) throw forbidden('单聊会话不在项目中,无法管理任务')
190
251
  const project = this.projectRow(binding.project_id)
191
- if (project.owner_bot_id !== binding.bot_id) throw forbidden('只有项目总监 Bot 可以执行该操作')
252
+ // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 替代命令/正确下一步。
253
+ if (project.owner_bot_id !== binding.bot_id) {
254
+ throw forbidden(
255
+ '只有项目总监 Bot 可以执行该操作:总监命令(如 team_assign_task 派单/重派、'
256
+ + 'team_review_task 验收关单、team_block_task 强制受阻)由项目 owner 总监 Bot 调用;'
257
+ + '成员请在项目群内向总监请求代为执行。',
258
+ )
259
+ }
192
260
  return { binding, project, actor: { type: 'bot', id: binding.bot_id } }
193
261
  },
194
262
  // 派单侧同写范围重复检测(DSHBOTS-82):同一文件上叠 N 张小卡时,各卡各立各排,
@@ -210,6 +278,26 @@ export const taskDispatchMethods = {
210
278
  }
211
279
  return null
212
280
  },
281
+ // 勘误并卡引导(DSHBOTS-276):找同项目同承接人「近 7 天内 done」且写范围与本次声明有
282
+ // 交集(元素级,路径前缀不展开——与 D-82 完全一致检测同一口径的读取函数)的最近一张卡。
283
+ // 时间基准用 COALESCE(completed_at, updated_at):done 终态时刻优先(D-69 回填保证存量行有值)。
284
+ findRecentDoneOverlapTask(projectId, assigneeBotId, scopes) {
285
+ const target = new Set(scopes)
286
+ if (!target.size) return null
287
+ const since = new Date(Date.now() - RECENT_DONE_WINDOW_MS).toISOString()
288
+ const candidates = this.store.all(
289
+ `SELECT id, number, title, write_scopes FROM tasks
290
+ WHERE project_id = ? AND assignee_bot_id = ? AND status = 'done'
291
+ AND COALESCE(completed_at, updated_at) >= ?
292
+ ORDER BY COALESCE(completed_at, updated_at) DESC`,
293
+ projectId, assigneeBotId, since,
294
+ )
295
+ for (const row of candidates) {
296
+ const other = readWriteScopes(row.write_scopes)
297
+ if (other.some(scope => target.has(scope))) return row
298
+ }
299
+ return null
300
+ },
213
301
  // 派单清洗(DSHBOTS-168):写范围声明的程序化质量闸门,三入口共用——
214
302
  // createTask(owner 派单路径权威清洗)、assignFromBot(经 createTask 同一清洗)、
215
303
  // taskUpdateScopes(改卡入口)。两步:
@@ -239,9 +327,15 @@ export const taskDispatchMethods = {
239
327
  const sandboxOverride = input.sandbox === undefined
240
328
  ? undefined
241
329
  : resolveSandboxOverride(this.botRow(member.id), input.sandbox)
330
+ // 核验纪律派单闸(DSHBOTS-303)——新卡面;重派分支再按「改后生效卡面」补一道。
331
+ this.assertNotVerificationDispatch(project, member.id, input.title, input.description)
242
332
  if (input.taskId || input.task) {
243
333
  const task = this.resolveBotTask(project, input.taskId ?? input.task)
244
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))
245
339
  // 任务卡修正闭环(DSHBOTS-232 ①):重派可同时改卡面(标题/描述/优先级)——先经
246
340
  // updateTask 落卡,卡面变化由其统一触发点通知负责人修正,再走原重派链路。
247
341
  // 写范围不在此口改:入队运行快照与调度闸门消费的不是同一份数据,
@@ -264,6 +358,8 @@ export const taskDispatchMethods = {
264
358
  // 闸门按清洗后清单预判(DSHBOTS-168):全部命中忽略规则 = 实际未声明,落上面的
265
359
  // 拒绝。原清单透传 createTask 做权威清洗+审计(审计需真实 taskId),此处只预览不落账。
266
360
  const scopes = filterIgnoredWriteScopes(parsedScopes, this.projectWorkDir(project)).kept
361
+ // 派单策略闸(DSHBOTS-314):写卡派只读 bot 在入口拒绝;重派分支按原卡声明补一道。
362
+ this.assertWritableDispatch(member.id, scopes)
267
363
  if (!scopes.length) {
268
364
  throw badRequest(
269
365
  '派单必须声明写范围:传 write_scopes 路径数组,或在描述里写一行「写范围:a, b」。'
@@ -278,16 +374,27 @@ export const taskDispatchMethods = {
278
374
  const forceDuplicate = input.force_duplicate === true
279
375
  const urgentExempt = input.priority === 'urgent'
280
376
  if (duplicate && !forceDuplicate && !urgentExempt) {
377
+ // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 替代命令(改卡重派而非新开卡)。
281
378
  throw conflict(
282
- `已存在同写范围任务 ${project.key}-${duplicate.number} ${duplicate.title},请勿重复派单;`
283
- + '若需合并多张小卡,请在原任务描述追加清单后重派原任务。'
284
- + '紧急任务(priority=urgent)豁免此拦截,可立即派单施工。',
379
+ `已存在同写范围任务 ${project.key}-${duplicate.number} ${duplicate.title},请勿重复派单:`
380
+ + '请用 team_assign_task 重派原任务改卡(task=原任务号,附 title/description 即修正卡面),不要为新内容新开卡;'
381
+ + '确需第二张同范围卡时传 force_duplicate=true(每次使用留审计);紧急任务(priority=urgent)豁免此拦截,可立即派单施工。',
285
382
  )
286
383
  }
384
+ // 勘误并卡提示(DSHBOTS-276,不强制):双条件命中(标题关键词 + 近期 done 卡写范围交集)
385
+ // 时在卡面描述尾部追加一行并卡建议。仅追加描述,不拦截派单、不改任何拒绝行为;
386
+ // 未命中时描述原样透传,createTask 路径零变化。
387
+ let description = input.description
388
+ if (CORRECTION_TITLE_RE.test(String(input.title ?? ''))) {
389
+ const overlap = this.findRecentDoneOverlapTask(project.id, member.id, scopes)
390
+ if (overlap) {
391
+ description = `${input.description ? `${input.description}\n` : ''}(note: recent done card ${project.key}-${overlap.number} overlaps these scopes — consider merging follow-up corrections into one card)`
392
+ }
393
+ }
287
394
  const task = await this.createTask({
288
395
  projectId: project.id,
289
396
  title: input.title,
290
- description: input.description,
397
+ description,
291
398
  assigneeBotId: member.id,
292
399
  priority: input.priority,
293
400
  // 透传原始清单(DSHBOTS-168):清洗+审计由 createTask 统一做(审计挂真实 taskId)。
@@ -21,7 +21,15 @@ export const taskReviewMethods = {
21
21
  /** 验收/退回的共用流程:owner Bot 会话与微信管理员共用。 */
22
22
  async applyReview(task, project, decision, comment, actor) {
23
23
  const identifier = `${project.key}-${task.number}`
24
- if (task.status !== 'in_review') throw conflict(`任务 ${identifier} 不在待验收状态`)
24
+ // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 替代命令/正确下一步(工具调用返回层,
25
+ // 与 run-finish 群聊/微信失败终态白名单契约不同层,互不影响)。
26
+ if (task.status !== 'in_review') {
27
+ throw conflict(
28
+ `任务 ${identifier} 不在待验收状态(当前 ${task.status}):`
29
+ + 'team_review_task 只验收已交付(in_review)的卡,请先等负责人交付;'
30
+ + '若卡面或目标有误,用 team_assign_task 重派原任务(task=原任务号,附 title/description 即改卡)修正。',
31
+ )
32
+ }
25
33
  if (decision === 'accept') {
26
34
  await this.updateTask(task.id, { status: 'done' }, actor)
27
35
  if (comment) await this.addComment(task.id, comment, actor)
@@ -124,6 +132,16 @@ export const taskReviewMethods = {
124
132
  if (active.trigger_type === 'review_delegate') return { runId: active.id, reused: true }
125
133
  throw conflict(`任务 ${identifier} 已有运行在排队或执行,请先停止再委派核验`)
126
134
  }
135
+ // busy 闸(DSHBOTS-290):总监忙时不落 runs 行(撞 one_active_run_per_bot),挂待
136
+ // 处理队列空闲建回(insertHeldMessageRun 的 owner_task 分支);返回 deferred 让
137
+ // 手动入口与 outbox 自动入口都能感知「已挂起」而非失败。
138
+ if (this.botBusy(owner.id, project.id)) {
139
+ this.holdPendingMessage(owner.id, project.id, {
140
+ kind: 'owner_task', messageId: `owner_task:${task.id}:review_delegate`, taskId: task.id,
141
+ projectId: project.id, runKind: 'review', triggerType: 'review_delegate', queuedAt: nowIso(),
142
+ })
143
+ return { runId: null, deferred: true }
144
+ }
127
145
  const runId = id('run')
128
146
  const createdAt = nowIso()
129
147
  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,
@@ -147,7 +157,13 @@ export const taskRunMethods = {
147
157
  return runId
148
158
  },
149
159
  enqueueOwnerTaskRun(task, kind) {
150
- const project = this.projectRow(task.project_id)
160
+ // 验收竞态收敛(DSHBOTS-275):入队前终态预检——任务已 done/canceled 时直接跳过,
161
+ // 不产生 review/handle run 行(GS 实测交付排队与 owner 关单竞态空跑约 1/8)。
162
+ // 以库内最新状态为准(调用方传入的 task 行可能已过期);入队后才到终态的残留排队运行
163
+ // 仍由 cancelSupersededQueuedRuns「任务已结束,排队运行被清理」兜底清理,语义不变。
164
+ const current = this.taskRow(task.id)
165
+ if (!current || current.status === 'done' || current.status === 'canceled') return null
166
+ const project = this.projectRow(current.project_id)
151
167
  const owner = project.owner_bot_id
152
168
  ? this.store.get("SELECT * FROM bots WHERE id = ? AND status = 'active'", project.owner_bot_id)
153
169
  : null
@@ -160,13 +176,35 @@ export const taskRunMethods = {
160
176
  const runId = id('run')
161
177
  const createdAt = nowIso()
162
178
  const triggerType = kind === 'review' ? 'review_requested' : 'blocked_handoff'
163
- this.store.run(
164
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
165
- attempt, idempotency_key, queued_at)
166
- VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
167
- runId, project.id, owner.id, task.id, kind, triggerType, task.id,
168
- `${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
169
- )
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
+ }
170
208
  this.store.run(
171
209
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
172
210
  id('evt'), runId, 'queued',