dsh-team-bots 0.2.338 → 0.2.364

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.
@@ -10,14 +10,48 @@ import { rolloverSummaryKey } from '../config.js'
10
10
  import {
11
11
  isQuotaExhausted,
12
12
  isRateLimitError,
13
+ isRetryChainError,
14
+ isTransientNetworkError,
13
15
  MAX_RATE_LIMIT_RETRIES,
14
16
  needsSynthesizedBackoff,
17
+ needsTransientBackoff,
15
18
  rateLimitBackoffMs,
19
+ transientBackoffMs,
16
20
  } from './backoff.js'
17
21
  import { ensureAttentionSchema, normalizeAttention } from './attention-schema.js'
18
22
  import { completeVisionRun, maybeSpawnVisionAfterFailure } from './vision-proxy.js'
19
23
  import { chatReply } from '../wechat/format.js'
20
24
 
25
+ // ── 失败终态白名单分类(DSHBOTS-267)──────────────────────────────────────
26
+ // run 失败终态进入群聊/微信回推前,先按结构化信号归入有限白名单类别,对外只透出
27
+ // 「类别+一句话摘要」;原始错误串、文件路径、请求正文不整段透传(完整信息仍落
28
+ // runs.error_message 与 run_events,供 owner 查询)。分类信号复用 D-266 的
29
+ // isTransientNetworkError(TRANSIENT_PATTERN)与既有限流/额度分类,不重复造。
30
+ // 优先级:配额 > 限流 > 沙箱拒绝 > 超时 > 网络 > 内部错误 > 未知。
31
+ const SANDBOX_DENIED_PATTERN = /(EPERM|EACCES|sandbox|file access denied|access denied)/i
32
+ const TIMEOUT_PATTERN = /timed[\s_-]?out|timeout|超时/i
33
+ const INTERNAL_PATTERN = /(internal error|EINTERNAL|INTERNAL_ERROR)/i
34
+ const FAILURE_CATEGORY_NOTICES = {
35
+ quota: { label: '配额', summary: '模型额度耗尽,已按额度策略切换备用或转受阻。' },
36
+ rate_limited: { label: '限流', summary: '上游限流,已按退避策略自动处理。' },
37
+ sandbox_denied: { label: '沙箱拒绝', summary: '文件或命令操作被沙箱策略拒绝。' },
38
+ timeout: { label: '超时', summary: '上游响应超时。' },
39
+ network: { label: '网络', summary: '网络瞬态失败,已按退避策略自动重试。' },
40
+ internal: { label: '内部错误', summary: '服务内部错误。' },
41
+ unknown: { label: '未知', summary: '运行失败,完整原因见运行日志。' },
42
+ }
43
+ export function classifyFailure(error) {
44
+ const raw = `${String(error?.code ?? '')} ${String(error?.message ?? '')}`
45
+ if (isQuotaExhausted(error)) return FAILURE_CATEGORY_NOTICES.quota
46
+ if (isRateLimitError(error)) return FAILURE_CATEGORY_NOTICES.rate_limited
47
+ if (SANDBOX_DENIED_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.sandbox_denied
48
+ if (TIMEOUT_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.timeout
49
+ if (isTransientNetworkError(error)) return FAILURE_CATEGORY_NOTICES.network
50
+ if (INTERNAL_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.internal
51
+ return FAILURE_CATEGORY_NOTICES.unknown
52
+ }
53
+
54
+
21
55
  export const runFinishMethods = {
22
56
  // 自动核验委派(DSHBOTS-113):交付迁移 in_review 的同一事务内调用。开关关闭或
23
57
  // 迁移未生效(任务已终态)时静默跳过;项目无可用总监属结构性前提缺失,审计留痕后
@@ -68,7 +102,14 @@ export const runFinishMethods = {
68
102
  // DSHBOTS-99:额度耗尽(已达到限额)不合成指数退避——额度窗口用尽,退避重打撞同一堵墙。
69
103
  const attemptNo = Math.max(1, Number(run.attempt) || 1)
70
104
  const quotaExhausted = isQuotaExhausted(error)
71
- const synthesizedMs = needsSynthesizedBackoff(error) ? rateLimitBackoffMs(attemptNo) : null
105
+ // DSHBOTS-266:网络瞬态失败(ECONNRESET/5xx/408 等过性错误)同判合成退避,
106
+ // 与限流共用同一 retry_after_ms 落库与 plan_wait 派生链;真 Retry-After 仍优先。
107
+ const transientBackoff = needsTransientBackoff(error)
108
+ const synthesizedMs = needsSynthesizedBackoff(error)
109
+ ? rateLimitBackoffMs(attemptNo)
110
+ : transientBackoff
111
+ ? transientBackoffMs(attemptNo)
112
+ : null
72
113
  // 额度耗尽时 provider 真给的重置时间照样保留(信息不丢,供 UI 显示额度恢复时间),
73
114
  // 但它不再触发对主模型的自动重试(见下方失败分支与 scheduler.retryExpiredPlanWaits)。
74
115
  const retryAfterMs = Number(error?.retryAfterMs) > 0 ? Number(error.retryAfterMs) : synthesizedMs
@@ -120,8 +161,10 @@ export const runFinishMethods = {
120
161
  const suffix = attemptNo < MAX_RATE_LIMIT_RETRIES ? '后重试' : '后转总监处理'
121
162
  this.insertRunEvent(
122
163
  runId,
123
- 'rate_limit_backoff',
124
- `上游限流(${error?.code})未返回 Retry-After,第 ${attemptNo} 次退避,约 ${Math.round(synthesizedMs / 1000)} 秒${suffix}`,
164
+ transientBackoff ? 'transient_backoff' : 'rate_limit_backoff',
165
+ transientBackoff
166
+ ? `网络瞬态失败(${String(error?.code ?? error?.message ?? '未知错误').slice(0, 60)}),第 ${attemptNo} 次退避,约 ${Math.round(synthesizedMs / 1000)} 秒${suffix}`
167
+ : `上游限流(${error?.code})未返回 Retry-After,第 ${attemptNo} 次退避,约 ${Math.round(synthesizedMs / 1000)} 秒${suffix}`,
125
168
  )
126
169
  }
127
170
  // 结构化提问(attention):只在 bot 显式给出时落库,规范超长/超量后写入;
@@ -213,7 +256,8 @@ export const runFinishMethods = {
213
256
  senderId: bot.id,
214
257
  body: status === 'succeeded'
215
258
  ? (cleanOutput || `总监已完成${label}。`)
216
- : `总监${label}运行失败:${error?.message ?? '未知错误'}`,
259
+ // DSHBOTS-267:失败只透出白名单类别+摘要,不透传原始错误串。
260
+ : `总监${label}运行失败(${classifyFailure(error).label}):${classifyFailure(error).summary}`,
217
261
  taskId: run.task_id,
218
262
  runId,
219
263
  })
@@ -250,7 +294,7 @@ export const runFinishMethods = {
250
294
  projectId: project.id,
251
295
  senderType: 'bot',
252
296
  senderId: bot.id,
253
- body: `总监${label}运行失败:${error?.message ?? '未知错误'}`,
297
+ body: `总监${label}运行失败(${classifyFailure(error).label}):${classifyFailure(error).summary}`,
254
298
  runId,
255
299
  })
256
300
  }
@@ -361,7 +405,9 @@ export const runFinishMethods = {
361
405
  // 禁止立刻重打上游——不切备用模型(备用可能走同一网关),也不立刻排总监处理运行。
362
406
  // DSHBOTS-99:额度耗尽(已达到限额)不走这条路径——不指数退避、无条件先试备用模型;
363
407
  // 瞬时限流的等待语义原样保留。
364
- const backoffWaitMs = isRateLimitError(error) && retryAfterMs > 0 ? retryAfterMs : 0
408
+ // DSHBOTS-266:网络瞬态失败(ECONNRESET/5xx/408 等)进同一退避链——等待期内同样
409
+ // 不切备用不排 handle,plan_retry 到期派生接管重试;attempt≤3,第 4 次照常转 blocked。
410
+ const backoffWaitMs = isRetryChainError(error) && retryAfterMs > 0 ? retryAfterMs : 0
365
411
  // 额度耗尽不做自动重试:重置时间只当信息留着,不据此重打主模型。
366
412
  const willRetry = !quotaExhausted && backoffWaitMs > 0 && attemptNo < MAX_RATE_LIMIT_RETRIES
367
413
  // 主 provider 不可用:临时切备用模型继续跑这条任务。派生成功后任务不置 blocked、
@@ -401,16 +447,22 @@ export const runFinishMethods = {
401
447
  const quotaNote = quotaExhausted
402
448
  ? `\n已达限额(${error?.code ?? '未知错误'}),主备模型均不可用,任务转为受阻${quotaResetNote}。`
403
449
  : ''
450
+ // 退避提示按失败类别措辞:瞬态抖动与限流都是「退避后自动重试」,不混用限流文案。
451
+ const backoffKind = isTransientNetworkError(error) ? '网络瞬态失败' : '上游限流'
452
+ const backoffVerb = isTransientNetworkError(error) ? '退避' : '指数退避'
404
453
  const backoffNote = backoffWaitMs > 0
405
454
  ? (willRetry
406
- ? `\n上游限流,第 ${attemptNo} 次指数退避,约 ${Math.round(backoffWaitMs / 1000)} 秒后自动重试。`
407
- : `\n上游限流,已达自动重试上限,约 ${Math.round(backoffWaitMs / 1000)} 秒后转总监处理。`)
455
+ ? `\n${backoffKind},第 ${attemptNo} 次${backoffVerb},约 ${Math.round(backoffWaitMs / 1000)} 秒后自动重试。`
456
+ : `\n${backoffKind},已达自动重试上限,约 ${Math.round(backoffWaitMs / 1000)} 秒后转总监处理。`)
408
457
  : ''
458
+ // DSHBOTS-267:失败只透出白名单类别+摘要;原始错误串不进群聊(完整信息已落
459
+ // runs.error_message 与 run_events)。quotaNote/backoffNote 仅含结构化错误码。
460
+ const failure = classifyFailure(error)
409
461
  this.insertMessage({
410
462
  projectId: project.id,
411
463
  senderType: 'bot',
412
464
  senderId: bot.id,
413
- body: `任务执行失败:${error?.message ?? '未知错误'}\n运行 ID:${runId}${quotaNote}${backoffNote}`,
465
+ body: `任务执行失败(${failure.label}):${failure.summary}\n运行 ID:${runId}${quotaNote}${backoffNote}`,
414
466
  taskId: run.task_id,
415
467
  runId,
416
468
  })
@@ -428,26 +480,28 @@ export const runFinishMethods = {
428
480
  })
429
481
  }
430
482
  } else if (run.kind === 'chat') {
483
+ // DSHBOTS-267:群聊与微信回推共用同一份分类文案,不含原始错误串。
484
+ const failureBody = `运行失败(${classifyFailure(error).label}):${classifyFailure(error).summary}`
431
485
  this.insertMessage({
432
486
  projectId: project.id,
433
487
  senderType: 'bot',
434
488
  senderId: bot.id,
435
- body: `运行失败:${error?.message ?? '未知错误'}`,
489
+ body: failureBody,
436
490
  runId,
437
491
  })
438
- this.notifyWechatChat(bot, run, `运行失败:${error?.message ?? '未知错误'}`, true)
492
+ this.notifyWechatChat(bot, run, failureBody, true)
439
493
  } else if (run.kind === 'solo_chat') {
440
- const failure = `运行失败:${error?.message ?? '未知错误'}`
494
+ const failureBody = `运行失败(${classifyFailure(error).label}):${classifyFailure(error).summary}`
441
495
  this.insertSoloMessage({
442
496
  botId: bot.id,
443
497
  senderType: 'bot',
444
498
  senderId: bot.id,
445
- body: failure,
499
+ body: failureBody,
446
500
  runId,
447
501
  })
448
502
  // DSHBOTS-258:微信通道的 solo 直达失败提示同样推回(notifyWechatChat 内部按
449
503
  // trigger_type='wechat' 门禁,普通 UI 单聊不推)。
450
- this.notifyWechatChat(bot, run, failure, true)
504
+ this.notifyWechatChat(bot, run, failureBody, true)
451
505
  }
452
506
  }
453
507
  if (run.project_id && this.rate[run.project_id]) delete this.rate[run.project_id]
@@ -511,8 +565,11 @@ export const runFinishMethods = {
511
565
  )
512
566
  // 护栏二:链路深度 ≤2——深度达 2 的 bot 回复不再派发。
513
567
  if (this.chatMentionChainDepth(run) >= 2) return []
514
- const dispatched = targets.slice(0, 3)
568
+ // DSHBOTS-267 防循环上限(chat 路径):每次 @ 唤醒即一条伙伴提醒,与 notify 路径
569
+ // 共用同一 run_events 配额流;超限目标静默丢弃(allowPartnerNotice 内 warn 留痕)。
570
+ const dispatched = targets.slice(0, 3).filter(target => this.allowPartnerNotice(run.id, target.id))
515
571
  for (const target of dispatched) {
572
+ this.recordPartnerNotice(run.id, target.id)
516
573
  this.enqueueOutbox({
517
574
  kind: 'chat_run',
518
575
  payload: { projectId: project.id, botId: target.id, messageId, origin: null },
@@ -12,6 +12,7 @@ import { scanProjectSkills } from '../../project-skills.js'
12
12
  import { id, nowIso, parseDisabledSkills } from '../../util.js'
13
13
  import { dmPrompt, replyDeliveryPrompt } from '../../botmsg.js'
14
14
  import { rolloverPendingKey, rolloverSummaryKey } from '../../config.js'
15
+ import { taskDeadlineInfo } from '../tasks.js'
15
16
  import { readWriteScopes } from '../write-scopes.js'
16
17
  import { sanitizeTmpBotDirName } from '../../paths.js'
17
18
 
@@ -450,14 +451,25 @@ ${(chatMessage?.body ?? '(no text)').slice(0, 2_000)}`
450
451
  // 时效要求(DSHBOTS-125/131):time_budget_minutes 未传/NULL 则完全不注入。
451
452
  // 任务派生运行(review/handle/memory_review)与该任务共用同一时效上限,提示词必须同步告知,
452
453
  // 否则运行会在代理不知情的情况下被超时中止。
453
- const timeBudgetBlockFor = (row) => {
454
+ // 任务级死线(DSHBOTS-274):deadline 只由施工分支(下方 if (task))传入,追加剩余时间一行;
455
+ // 预算耗尽改收尾轮口径。review/handle/memory_review 分支不传 deadline(死线豁免,不注入该行)。
456
+ const timeBudgetBlockFor = (row, deadline = null) => {
454
457
  const timeBudget = Number(row?.timeBudgetMinutes ?? row?.time_budget_minutes)
455
- return Number.isFinite(timeBudget) && timeBudget > 0 ? `
458
+ if (!(Number.isFinite(timeBudget) && timeBudget > 0)) return ''
459
+ let deadlineLine = ''
460
+ if (deadline?.deadlineMs !== null && deadline?.deadlineMs !== undefined) {
461
+ const remainingMs = deadline.deadlineMs - Date.now()
462
+ deadlineLine = remainingMs > 0
463
+ ? `Deadline: ${new Date(deadline.deadlineMs).toISOString()} / ${Math.ceil(remainingMs / 60_000)} min remaining.`
464
+ : `Deadline: ${new Date(deadline.deadlineMs).toISOString()} passed — 超线,本轮是收尾轮,优先可交付小步。`
465
+ }
466
+ return `
456
467
 
457
468
  # Time budget
458
469
  This task must be delivered within ${timeBudget} minutes; the run is aborted when the budget expires.
459
470
  Plan the depth of your work accordingly. If you judge the task cannot be finished within that time, deliver a usable partial result on schedule and state clearly in your delivery report the remaining work and why the budget could not be met.
460
- The effective timeout is the smaller of this budget and the global run timeout (runTimeoutMs).` : ''
471
+ The effective timeout is the smaller of this budget and the global run timeout (runTimeoutMs).
472
+ ${deadlineLine}`.trimEnd()
461
473
  }
462
474
  if ((run.kind === 'review' || run.kind === 'handle') && task) {
463
475
  // 超长防护(DSHBOTS-113,事故 m_33bddb;DSHBOTS-140 扩到 owner review / handle):
@@ -586,7 +598,8 @@ ${(sourceRun?.output ?? '').slice(0, 4000)}`
586
598
  // (8k 截断 + 盲区标记),建卡上限 40k 的长卡不再整段进提示词。
587
599
  const description = truncateTaskDescription(task.description)
588
600
  // 时效要求(DSHBOTS-125/131):time_budget_minutes 未传/NULL 则完全不注入,提示词与无时效任务一致。
589
- const timeBudgetBlock = timeBudgetBlockFor(task)
601
+ // 任务级死线(DSHBOTS-274):施工分支传入整卡死线,时效段追加剩余时间/收尾轮口径。
602
+ const timeBudgetBlock = timeBudgetBlockFor(task, taskDeadlineInfo(this.store, task))
590
603
  // 紧急豁免(DSHBOTS-126):urgent 任务卡追加豁免指令(用户口径 m08196-2)——
591
604
  // 无视车道排队立即开工;非 urgent 完全不注入,保持既有车道纪律。
592
605
  const urgentExemptionBlock = task.priority === 'urgent' ? `
@@ -611,6 +624,16 @@ Before closing: if this task cannot be finished in one run or new closing condit
611
624
  # Splitting for speed
612
625
  Split only when all hold: the task has 2+ independent parts, parts have disjoint write scopes, and the joined cost of split cards stays below one-run delivery. One card per part: parent_task_id to this task, blocked_by where order matters. Not the project owner? Propose the split in your delivery report. Example: API card (src/api/) + docs card, run concurrently.`
613
626
  // splitting-guidance:end
627
+ // delivery-selfcheck:start —— 交付前自校段(DSHBOTS-276,P1 派单质量前置):治 GS 实测
628
+ // 34% 补丁/返工卡——交付报告缺自跑验证证据。所有任务卡无条件注入,置于卡头
629
+ // Status 与 Description 之间(D-269 只追加手法):不动既有锚点前缀与 D-274 时效段
630
+ // (tests/prompt-budget ≤1900 静态前缀不打红、8k 截断「描述后即结尾」断言不打红、
631
+ // tests/prompt-prefix-order 段序不打红——三守门实测后选定此位)。
632
+ const deliverySelfcheckBlock = `
633
+
634
+ # Delivery self-check
635
+ Before reporting delivery, self-run the reproducible verification and put the evidence in the delivery report: the exact test/build commands you ran with their results, the list of files you changed, and the counts or links the acceptance criteria name (grep hits, test pass counts, commit hashes). Verify your own claims first — re-run the target tests and re-check the anchors yourself; do not report delivery on unverified work. Self-checking is always cheaper than rework: a delivery report without evidence will be returned.`
636
+ // delivery-selfcheck:end
614
637
  // recovery note(DSHBOTS-135):宿主重启重排队的运行(core.js 置 recovery=1)追加恢复提醒,
615
638
  // 对齐 superagent 原型语义——核实现状再续做、不重复外部动作。startRun 注入后即刻清零,
616
639
  // 本段只在重排队后的第一次执行出现。与时效段(D-125)、豁免段(D-126)、纪律段(D-132)互不干扰。
@@ -634,7 +657,7 @@ When the deliverable includes images, put the files in the workspace and referen
634
657
  # Assigned task ${project.key}-${task.number}
635
658
  Title: ${task.title}
636
659
  Priority: ${task.priority}
637
- Status: ${task.status}
660
+ Status: ${task.status}${deliverySelfcheckBlock}
638
661
  Description:
639
662
  ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteBlock}`
640
663
  }
@@ -674,9 +697,16 @@ ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteB
674
697
 
675
698
  # WeChat direct conversation
676
699
  This message is from the project owner on WeChat — a real multi-turn conversation, not a one-off command. The project session is shared, so keep continuity across turns instead of restarting context each time. If the owner asks you to get work done, actually create and assign the task (team_assign_task — cards carry the project KEY-N number; do not create project-less task-N cards on the host shared board) instead of only acknowledging it. If you need the owner to decide something, use ask_user_question: it is forwarded to their WeChat and their reply comes back to you.` : ''
700
+ // DSHBOTS-272 用户提问锚点:触发消息是人发的(sender_type='user')才注入;通知降级与
701
+ // bot @mention 唤醒触发的运行(sender_type='bot')不注入——事故根因之一是通知内容与用户
702
+ // 提问同窗时无优先级指示,bot 回了条轻备忘就算处理完。
703
+ const ownerQuestionBlock = chatMessage?.sender_type === 'user' ? `
704
+
705
+ # Owner question priority
706
+ This message is from the project owner — answer it directly in this reply. Background notifications in context must not substitute for the answer; handle them only after (or skip to next turn).` : ''
677
707
  return `${header}
678
708
 
679
- Reply as ${bot.name} in the project group. Keep it under ${this.config.chatReplyMaxChars} characters unless the user asked for a full write-up. If the message requires another bot to do work, use team_assign_task instead of pretending to assign it. Use team_recall with a m_/c_/run id when you need the full text of a truncated item.${wechatBlock}
709
+ Reply as ${bot.name} in the project group. Keep it under ${this.config.chatReplyMaxChars} characters unless the user asked for a full write-up. If the message requires another bot to do work, use team_assign_task instead of pretending to assign it. Use team_recall with a m_/c_/run id when you need the full text of a truncated item.${wechatBlock}${ownerQuestionBlock}
680
710
 
681
711
  # Group message
682
712
  ${(chatMessage?.body ?? '(no message)').slice(0, 4_000)}
@@ -7,10 +7,12 @@ import { effectiveRunLimits } from '../config.js'
7
7
  import { badRequest } from '../errors.js'
8
8
  import { applyRetention, reconcileUsage } from '../usage-reconcile.js'
9
9
  import { id, jsonParse, nowIso, text } from '../util.js'
10
- import { MAX_RATE_LIMIT_RETRIES, RATE_LIMIT_CODES, isQuotaExhausted } from './backoff.js'
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
@@ -307,6 +309,15 @@ export const schedulerMethods = {
307
309
  return `project:${run.bot_id}:${run.project_id}`
308
310
  },
309
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
+
310
321
  // 入站消息合批(DSHBOTS-231):领取一条运行后,把同一条绑定道内仍在排队的消息运行合并
311
322
  // 进来——被合并的运行置 canceled(error_code='MERGED'),消息 id 记入本运行的
312
323
  // merged_messages,executeRun 据此把多条消息一次性注入同一轮上下文,不再一条消息一次运行。
@@ -319,6 +330,10 @@ export const schedulerMethods = {
319
330
  const windowMs = Number(this.store.setting('coalesce_window_ms', String(COALESCE_WINDOW_MS_DEFAULT)))
320
331
  const claimedQueuedAt = Date.parse(run.queued_at)
321
332
  const laneKey = this.claimKey(run)
333
+ // DSHBOTS-272 合批保护:用户提问(触发消息 sender_type='user')不并入非用户触发的运行——
334
+ // 并入后提问只能挤在 Merged messages 段、没有直接回答锚点(事故形态=通知运行回一条轻备忘
335
+ // 就算处理完)。留队保住「一条提问一条正式回复」;出队序已把用户提问置顶,下一拍即领取。
336
+ const claimedIsUserQuestion = this.isUserQuestionRun(run)
322
337
  const candidates = this.store.all(
323
338
  `SELECT * FROM runs WHERE status = 'queued' AND id != ? AND kind = ?
324
339
  ORDER BY queued_at LIMIT 100`,
@@ -330,6 +345,8 @@ export const schedulerMethods = {
330
345
  if (mergedIds.length >= max - 1) break
331
346
  if (!candidate.trigger_ref) continue
332
347
  if (this.claimKey(candidate) !== laneKey) continue
348
+ // DSHBOTS-272:候选是用户提问而本运行非用户触发(通知/伙伴唤醒)→ 不并,见上方注释。
349
+ if (!claimedIsUserQuestion && this.isUserQuestionRun(candidate)) continue
333
350
  const queuedAt = Date.parse(candidate.queued_at)
334
351
  if (!Number.isFinite(queuedAt) || !Number.isFinite(claimedQueuedAt)) continue
335
352
  if (queuedAt < claimedQueuedAt || queuedAt - claimedQueuedAt > windowMs) continue
@@ -398,9 +415,10 @@ export const schedulerMethods = {
398
415
  }
399
416
  },
400
417
  // 限流失败的自动重试(DSHBOTS-24;DSHBOTS-38 放开到 3 次并支持合成退避):
401
- // 失败 run 带 retry_after_ms(provider 真发过 Retry-After,或限流无头时 finishRun 合成的指数退避),
402
- // 到期派生一次新运行。限流码链最多跑到 attempt=3(1→2→3),之后转常规失败处置;
403
- // 非 RATE_LIMIT_CODES 的错误码不进本路径(维持只认限流码的原状)。
418
+ // 失败 run 带 retry_after_ms(provider 真发过 Retry-After,或限流/瞬态无头时 finishRun 合成的指数退避),
419
+ // 到期派生一次新运行。重试链最多跑到 attempt=3(1→2→3),之后转常规失败处置;
420
+ // DSHBOTS-266:链内错误判定移到下方 JS——限流码集合之外,网络瞬态失败(ECONNRESET/5xx/408
421
+ // 等,错误码/正文双匹配,见 backoff.ts 的 isRetryChainError)同样进本路径;SQL 表达不了该正则。
404
422
  // 只针对任务运行——solo/私信运行显示 plan_wait 状态但不自动派生,避免对同一个对话者重复发信。
405
423
  // 过期超过 24h 视为时过境迁不派生(服务停摆/长期搁置后不补跑旧任务)。
406
424
  // 幂等闸:task_id 非空 + 原 run 无 plan_retry 事件;idempotency_key UNIQUE 兜底并发 tick。
@@ -410,15 +428,15 @@ export const schedulerMethods = {
410
428
  `SELECT r.* FROM runs r
411
429
  WHERE r.status = 'failed' AND r.retry_after_ms IS NOT NULL
412
430
  AND r.task_id IS NOT NULL AND r.attempt < ${MAX_RATE_LIMIT_RETRIES}
413
- AND r.error_code IN (${[...RATE_LIMIT_CODES].map(() => '?').join(', ')})
414
431
  AND CAST(strftime('%s', COALESCE(r.ended_at, r.queued_at)) AS REAL) + r.retry_after_ms / 1000.0
415
432
  <= CAST(strftime('%s', 'now') AS REAL)
416
433
  AND CAST(strftime('%s', COALESCE(r.ended_at, r.queued_at)) AS REAL) + r.retry_after_ms / 1000.0
417
434
  > CAST(strftime('%s', 'now') AS REAL) - ${PLAN_RETRY_MAX_LATE_SECONDS}
418
435
  AND NOT EXISTS(SELECT 1 FROM run_events e WHERE e.run_id = r.id AND e.type = 'plan_retry')`,
419
- ...RATE_LIMIT_CODES,
420
436
  )
421
437
  for (const run of expired) {
438
+ // DSHBOTS-266:重试链判定(限流码 ∪ 网络瞬态)在 JS 做;非链内错误码不派生(现状不变)。
439
+ if (!isRetryChainError({ code: run.error_code, message: run.error_message })) continue
422
440
  // DSHBOTS-99:额度耗尽(已达到限额)的运行不再自动派生重试——额度窗口用尽时重打主模型
423
441
  // 只会再撞一次额度,任务已经转受阻,不能让它自己空转。
424
442
  // 备用链上的运行同理:每条链只切一次备用,plan_retry 派生出来的是主模型运行,等于绕开限额口径。
@@ -495,6 +513,100 @@ export const schedulerMethods = {
495
513
  return canceled
496
514
  },
497
515
 
516
+ // 滞留阈值兜底扫描(DSHBOTS-280):in_review 超 24h / blocked 超 48h 的卡向项目
517
+ // owner 发一条滞留提醒(notify.ts notifyStaleCardOwner),只提醒不自动处置——
518
+ // 不自动关单、不自动转状态、不重派。选点:复用 scheduler 周期 tick(与 D-194
519
+ // 验收守门同拍接入,不新增常驻进程);判定与防重见 notify.ts 的纯函数与每日上限。
520
+ // 逐卡容错:单卡异常只 warn,不拖垮整轮扫描。
521
+ scanStaleCards() {
522
+ const rows = this.store.all(
523
+ `SELECT t.id, t.status, t.updated_at, t.number,
524
+ p.id AS project_id, p.key AS project_key, p.owner_bot_id
525
+ FROM tasks t JOIN projects p ON p.id = t.project_id
526
+ WHERE t.status IN ('in_review', 'blocked') AND p.status = 'active'`,
527
+ )
528
+ const reminded = []
529
+ for (const row of rows) {
530
+ try {
531
+ const hit = staleCardHit(row)
532
+ if (!hit) continue
533
+ const delivered = this.notifyStaleCardOwner({
534
+ project: { id: row.project_id, key: row.project_key, owner_bot_id: row.owner_bot_id },
535
+ task: row,
536
+ hit,
537
+ })
538
+ if (delivered) reminded.push(row.id)
539
+ } catch (error ) {
540
+ this.logger.warn?.('dsh-team: 滞留扫描单卡失败 %s: %s', row.id, error?.message ?? error)
541
+ }
542
+ }
543
+ return reminded
544
+ },
545
+
546
+ // 任务级死线判定(DSHBOTS-274):纯同步——领取路径不得为此引入 await 边界, // 否则 claim 与状态写之间会开窗(tests/members.test.js 站内竞态教训)。
547
+ taskPastDeadline(task) {
548
+ const { deadlineMs } = taskDeadlineInfo(this.store, task)
549
+ return deadlineMs !== null && Date.now() > deadlineMs
550
+ },
551
+
552
+ // 任务级死线升级(DSHBOTS-274;DSHBOTS-281 口径升级):超线的 queued 施工运行拒绝启动
553
+ // ——运行置 canceled(TASK_DEADLINE,run_events 留 task_deadline 锚),卡面落系统评论
554
+ // (D-269 口径=原因+事实:点名项目总监,重派即自动重置死线窗口,不再写转接 owner 的话术),
555
+ // status 转 blocked(走 updateTask 单一状态流转漏斗,非法转换只评论不转),并复用系统消息
556
+ // 通道通知项目总监(notify.ts insertMessage 同款,进任务线程 + mentions 点名 owner_bot_id)。
557
+ // 幂等:enqueueTaskRun 同卡同时只有一条活跃运行,运行取消后不再进候选,每次派发至多升级
558
+ // 一次;重派即新窗口(基准=最新 queued_at),新窗口内预算×2 耗尽仍照常拦截。
559
+ async escalateTaskPastDeadline(task, runId) {
560
+ const { deadlineMs } = taskDeadlineInfo(this.store, task)
561
+ if (deadlineMs === null || Date.now() <= deadlineMs) return false
562
+ const project = this.projectRow(task.project_id)
563
+ const identifier = `${project?.key ?? 'T'}-${task.number}`
564
+ const deadlineIso = new Date(deadlineMs).toISOString()
565
+ // 点名总监(projects.owner_bot_id):留痕正文带总监花名,mentions 同点位名,收件人即第一负责人。
566
+ const directorName = project?.owner_bot_id
567
+ ? this.botRow(project.owner_bot_id)?.name ?? '总监'
568
+ : '总监'
569
+ const windowMinutes = Number(task.time_budget_minutes) * TASK_BUDGET_ROUNDS
570
+ const body = `【${identifier}】超时中止(预算×${TASK_BUDGET_ROUNDS})已到,任务未关单:总监 ${directorName} 重派即自动重置死线窗口(新窗口剩余 ${windowMinutes} 分钟),请消化处理(死线 ${deadlineIso})。`
571
+ const now = nowIso()
572
+ const commentId = id('cmt')
573
+ this.store.transaction(() => {
574
+ this.store.run(
575
+ "UPDATE runs SET status = 'canceled', ended_at = ?, error_code = 'TASK_DEADLINE', error_message = ? WHERE id = ? AND status = 'queued'",
576
+ now, body, runId,
577
+ )
578
+ this.store.run(
579
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
580
+ id('evt'), runId, 'task_deadline', `整卡死线已到(${deadlineIso}),拒绝启动新施工运行`, now,
581
+ )
582
+ this.store.run(
583
+ 'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
584
+ commentId, task.id, 'system', 'system', body, now,
585
+ )
586
+ this.addTaskEvent(task.id, 'commented', { type: 'system', id: 'system' }, { commentId, deadline: deadlineIso, runId })
587
+ })
588
+ if (TRANSITIONS[task.status]?.has('blocked')) {
589
+ try {
590
+ await this.updateTask(task.id, { status: 'blocked' }, { type: 'system', id: 'system' })
591
+ } catch (error ) {
592
+ this.logger.warn?.('dsh-team: 死线转 blocked 失败 %s: %s', identifier, error?.message ?? error)
593
+ }
594
+ }
595
+ try {
596
+ this.insertMessage({
597
+ projectId: task.project_id,
598
+ senderType: 'system',
599
+ senderId: 'system',
600
+ taskId: task.id,
601
+ body,
602
+ mentions: project?.owner_bot_id ? [project.owner_bot_id] : [],
603
+ })
604
+ } catch (error ) {
605
+ this.logger.warn?.('dsh-team: 死线总监通知失败 %s: %s', identifier, error?.message ?? error)
606
+ }
607
+ return true
608
+ },
609
+
498
610
  async tick() {
499
611
  if (this.ticking || !this.started) return
500
612
  this.ticking = true
@@ -512,6 +624,9 @@ export const schedulerMethods = {
512
624
  // 验收滞留守门(DSHBOTS-194):in_review 卡静置超阈值即注入 owner 系统提醒;
513
625
  // 内部自容错(异常只 warn),阈值 0 = 关闭时直接返回。
514
626
  runReviewWatchdog(this)
627
+ // 滞留阈值兜底(DSHBOTS-280):in_review/blocked 超 24h/48h 向 owner 只提醒
628
+ // 不自动处置;内部逐卡容错(单卡异常只 warn)。
629
+ this.scanStaleCards()
515
630
  const activeRows = this.store.all(
516
631
  // 写占用只看「进行中」的任务(DSHBOTS-73,用户口径):join tasks 取任务当前状态,
517
632
  // 任务不在 in_progress 的写运行不再占槽——离开进行中即释放占用/锁定。
@@ -545,13 +660,19 @@ export const schedulerMethods = {
545
660
  if (activeTotal >= maxRuns + 1) return
546
661
  // 出队顺序:任务运行按任务优先级(urgent 先),其余运行视同 high——用户交互不能被任务积压拖死;
547
662
  // 同优先级按入队时间,保证 FIFO 不饿死老运行。
663
+ // DSHBOTS-272 用户提问不被静默压后:不动用户运行的档位(同车道先入队的 review/handle
664
+ // 等人机运行契约不变,见 tests/avatar-lanes.test.js),改为把通知/伙伴唤醒触发的 chat
665
+ // 运行(触发消息 sender_type='bot')降到机器流量档——同车道内用户提问(tier 1)必然
666
+ // 先于它领取,即使提问后到;通知备忘让位于一切人机交互与 urgent/high 任务。
548
667
  // 候选过滤(DSHBOTS-110):任务已终态(done/canceled)的 queued 任务运行不再领取;
549
668
  // 只排 kind='task',非任务运行不受影响。LEFT JOIN 出 NULL 的孤儿任务运行不过滤。
550
669
  const candidates = this.store.all(
551
670
  `SELECT r.* FROM runs r LEFT JOIN tasks t ON t.id = r.task_id
671
+ LEFT JOIN messages m ON m.id = r.trigger_ref
552
672
  WHERE r.status = 'queued'
553
673
  AND NOT (r.kind = 'task' AND COALESCE(t.status, '') IN ('done', 'canceled'))
554
674
  ORDER BY CASE
675
+ WHEN r.kind = 'chat' AND m.sender_type = 'bot' THEN 2
555
676
  WHEN r.kind <> 'task' OR t.priority IS NULL THEN 1
556
677
  WHEN t.priority = 'urgent' THEN 0
557
678
  WHEN t.priority = 'high' THEN 1
@@ -641,6 +762,16 @@ export const schedulerMethods = {
641
762
  }
642
763
  continue
643
764
  }
765
+ // 任务级死线(DSHBOTS-274):施工运行(kind='task')领取前检查整卡死线——
766
+ // 死线 = 派发基准 + time_budget_minutes × TASK_BUDGET_ROUNDS(默认 2 轮,
767
+ // 延期阀见 tasks.ts updateTask)。超线即拒绝启动新施工运行并自动升级
768
+ // (评论 + blocked + owner 通知,escalateTaskPastDeadline);
769
+ // review/handle 等派生运行不走此闸(kind!=='task' 豁免,死线只拦施工轮)。
770
+ // 判定同步、升级异步放行:不为本闸在领取路径引入 await 边界。
771
+ if (taskRow && this.taskPastDeadline(taskRow)) {
772
+ void this.escalateTaskPastDeadline(taskRow, run.id).catch(error => this.logger.warn?.('dsh-team: 死线升级失败 %s: %s', run.id, error?.message ?? error))
773
+ continue
774
+ }
644
775
  }
645
776
  const claimed = this.store.run(
646
777
  "UPDATE runs SET status = 'running', started_at = ?, last_progress_at = ? WHERE id = ? AND status = 'queued'",