dsh-team-bots 0.2.465 → 0.3.12

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.
@@ -32,6 +32,21 @@ export const PROVIDER_UNAVAILABLE_CODES = new Set([
32
32
  // 额度耗尽不在此列——它没有可等的短窗口,必须换模型。
33
33
  const WAITABLE_CODES = new Set(['RATE_LIMIT', 'QUOTA'])
34
34
 
35
+ // 可派生备用运行的内部运行种类(DSHBOTS-358):任务运行 + 总监验收/受阻处理 + 记忆审查。
36
+ // 这些运行都在项目工作台内部流转,重跑不会重复打扰用户,因此与任务运行同口径切备用模型。
37
+ // 聊天类(chat / solo_chat / dm / vision 等)不在此列:自动重跑会重复发消息、打扰用户。
38
+ export const INTERNAL_FALLBACK_KINDS = new Set(['task', 'review', 'handle', 'memory_review'])
39
+
40
+ // 运行链标识:任务链按 task_id,记忆审查链按来源运行 id(memory_review 不挂任务)。
41
+ function fallbackChainKey(run ) {
42
+ if (!run) return null
43
+ if (run.kind === 'memory_review') {
44
+ return run.trigger_ref ? { scope: 'memory', sourceRunId: run.trigger_ref } : null
45
+ }
46
+ if (run.task_id) return { scope: 'task', taskId: run.task_id }
47
+ return null
48
+ }
49
+
35
50
  export function isProviderUnavailableCode(code) {
36
51
  return Boolean(code) && PROVIDER_UNAVAILABLE_CODES.has(String(code).toUpperCase())
37
52
  }
@@ -63,12 +78,22 @@ export const modelFallbackMethods = {
63
78
  },
64
79
 
65
80
  // 这条运行链是否已经用过备用模型(每条链只切一次)。
81
+ // 链按运行种类分桶(DSHBOTS-358):任务链、验收链、受阻处理链、记忆审查链各自独立——
82
+ // 施工轮用过备用不代表总监验收轮不能再切,反之亦然。
66
83
  fallbackUsedInChain(run) {
67
84
  if (run?.model_provider) return true
68
- if (!run?.task_id) return false
85
+ const chain = fallbackChainKey(run)
86
+ if (!chain) return false
87
+ if (chain.scope === 'memory') {
88
+ const row = this.store.get(
89
+ `SELECT id FROM runs WHERE kind = 'memory_review' AND trigger_ref = ? AND model_provider IS NOT NULL LIMIT 1`,
90
+ chain.sourceRunId,
91
+ )
92
+ return Boolean(row)
93
+ }
69
94
  const row = this.store.get(
70
- 'SELECT id FROM runs WHERE task_id = ? AND model_provider IS NOT NULL LIMIT 1',
71
- run.task_id,
95
+ 'SELECT id FROM runs WHERE kind = ? AND task_id = ? AND model_provider IS NOT NULL LIMIT 1',
96
+ run.kind, chain.taskId,
72
97
  )
73
98
  return Boolean(row)
74
99
  },
@@ -78,28 +103,43 @@ export const modelFallbackMethods = {
78
103
  const fallback = this.botFallbackModel(bot)
79
104
  if (!fallback) return null
80
105
  if (!shouldFallbackOn(error)) return null
81
- // 只对任务运行派生:私信/群聊/单聊自动重跑会重复发消息、打扰用户。
82
- if (run.kind !== 'task' || !run.task_id) return null
106
+ // 只对内部运行派生(DSHBOTS-358):私信/群聊/单聊自动重跑会重复发消息、打扰用户。
107
+ if (!INTERNAL_FALLBACK_KINDS.has(run.kind)) return null
108
+ const chain = fallbackChainKey(run)
109
+ if (!chain) return null
83
110
  if (this.fallbackUsedInChain(run)) return null
84
- const task = this.store.get('SELECT * FROM tasks WHERE id = ?', run.task_id)
85
- if (!task || ['done', 'canceled'].includes(task.status)) return null
86
- // 任务已有排队/运行中的运行(唯一索引 one_active_run_per_task)就不再派生。
87
- const active = this.store.get(
88
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
89
- run.task_id,
90
- )
91
- if (active) return null
111
+ if (chain.scope === 'task') {
112
+ const task = this.store.get('SELECT * FROM tasks WHERE id = ?', chain.taskId)
113
+ if (!task || ['done', 'canceled'].includes(task.status)) return null
114
+ // 任务已有排队/运行中的运行(唯一索引 one_active_run_per_task)就不再派生。
115
+ const active = this.store.get(
116
+ "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
117
+ chain.taskId,
118
+ )
119
+ if (active) return null
120
+ } else {
121
+ // 记忆审查链:同一条来源运行已有排队/运行中的审查运行就不再派生。
122
+ const active = this.store.get(
123
+ "SELECT id FROM runs WHERE kind = 'memory_review' AND trigger_ref = ? AND status IN ('queued', 'running')",
124
+ chain.sourceRunId,
125
+ )
126
+ if (active) return null
127
+ }
92
128
  const runId = id('run')
93
129
  const createdAt = nowIso()
94
130
  const attempt = (Number(run.attempt) || 1) + 1
131
+ // 派生运行沿用原运行的种类与形态(DSHBOTS-358):验收/受阻处理/记忆审查各自保持
132
+ // 原有语义与提示词通道,只是换一套模型重跑同一条链。
133
+ const kind = run.kind
134
+ const mode = run.mode ?? (kind === 'task' ? 'write' : 'read')
95
135
  try {
96
136
  this.store.transaction(() => {
97
137
  this.store.run(
98
138
  `INSERT INTO runs(id, project_id, bot_id, task_id, parent_run_id, kind, mode, write_scopes, trigger_type,
99
139
  trigger_ref, status, attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
100
- VALUES (?, ?, ?, ?, ?, 'task', ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?)`,
140
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?)`,
101
141
  runId, run.project_id, run.bot_id, run.task_id, run.id,
102
- run.mode ?? 'write', run.write_scopes ?? null,
142
+ kind, mode, run.write_scopes ?? null,
103
143
  run.trigger_type, run.trigger_ref, attempt, `model_fallback:${run.id}`,
104
144
  fallback.provider, fallback.model, fallback.effort, createdAt,
105
145
  )
@@ -350,7 +350,7 @@ export const projectsMethods = {
350
350
  updates.status = patch.status
351
351
  }
352
352
  if (patch.replyMode !== undefined) {
353
- if (!['owner_first', 'everyone'].includes(patch.replyMode)) throw badRequest('群聊回复模式无效')
353
+ if (!['owner_first', 'everyone', 'mentioned_only'].includes(patch.replyMode)) throw badRequest('群聊回复模式无效')
354
354
  }
355
355
  const ownerId = updates.owner_bot_id ?? project.owner_bot_id
356
356
  const memberIds = patch.memberIds === undefined
@@ -223,7 +223,22 @@ export const runFinishMethods = {
223
223
  return
224
224
  }
225
225
  if (run.kind === 'memory_review') {
226
- await this.completeMemoryReview(run, status === 'succeeded' ? cleanOutput : '', error)
226
+ // DSHBOTS-358:记忆审查撞 provider 额度墙时切备用模型重跑同一条审查链,
227
+ // 规则沉淀兜底留到备用链也失败时再做,避免同一次交付落两份记忆。
228
+ const fallback = status === 'failed'
229
+ ? this.spawnModelFallback({ run: refreshed, bot, error })
230
+ : null
231
+ if (fallback) {
232
+ this.insertMessage({
233
+ projectId: run.project_id,
234
+ senderType: 'bot',
235
+ senderId: bot.id,
236
+ body: `已达限额(${error?.code ?? '未知错误'}),已切换备用模型 ${fallback.fallback.ref} 继续记忆审查。`,
237
+ runId,
238
+ })
239
+ } else {
240
+ await this.completeMemoryReview(run, status === 'succeeded' ? cleanOutput : '', error)
241
+ }
227
242
  if (this.rate[run.project_id]) delete this.rate[run.project_id]
228
243
  return
229
244
  }
@@ -281,7 +296,21 @@ export const runFinishMethods = {
281
296
  }
282
297
  if (run.kind === 'review' || run.kind === 'handle') {
283
298
  const label = run.kind === 'review' ? '验收' : '受阻处理'
284
- if (run.task_id) {
299
+ // DSHBOTS-358:总监验收/受阻处理撞 provider 额度墙时切备用模型重跑同一条链
300
+ // (与任务运行同口径);派生成功就不发失败消息、不触发退回重派链。
301
+ const fallback = status === 'failed'
302
+ ? this.spawnModelFallback({ run: refreshed, bot, error })
303
+ : null
304
+ if (fallback) {
305
+ this.insertMessage({
306
+ projectId: project.id,
307
+ senderType: 'bot',
308
+ senderId: bot.id,
309
+ body: `已达限额(${error?.code ?? '未知错误'}),已切换备用模型 ${fallback.fallback.ref} 继续${label}。`,
310
+ taskId: run.task_id,
311
+ runId,
312
+ })
313
+ } else if (run.task_id) {
285
314
  // 委派核验运行(DSHBOTS-107)成功时,结论以任务评论写回(复用 addComment 通道:
286
315
  // 评论+事件+审计一次落全)。不改任务状态、不代为裁决——accept/return 仍归 owner。
287
316
  if (run.trigger_type === 'review_delegate' && status === 'succeeded' && cleanOutput) {
@@ -343,11 +372,7 @@ export const runFinishMethods = {
343
372
  // 子代理施工硬闸已解除(原 DSHBOTS-311):交付不再要求子代理施工账目,
344
373
  // 施工方式由 bot 自选(亲做或派「bot 名+任务号」子代理),账本(D-294)仍照记。
345
374
  this.store.transaction(() => {
346
- this.store.run(
347
- `UPDATE tasks SET status = 'in_review', version = version + 1, updated_at = ?
348
- WHERE id = ? AND status NOT IN ('done', 'canceled')`,
349
- endedAt, task.id,
350
- )
375
+ this.setTaskStatus(task.id, 'in_review', { type: 'bot', id: bot.id })
351
376
  this.store.run(
352
377
  'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
353
378
  id('cmt'), task.id, 'bot', bot.id,
@@ -479,10 +504,7 @@ export const runFinishMethods = {
479
504
  runId,
480
505
  })
481
506
  } else if (run.task_id) {
482
- this.store.run(
483
- "UPDATE tasks SET status = 'blocked', version = version + 1, updated_at = ? WHERE id = ? AND status NOT IN ('done', 'canceled')",
484
- endedAt, run.task_id,
485
- )
507
+ this.setTaskStatus(run.task_id, 'blocked', { type: 'bot', id: bot.id })
486
508
  this.addTaskEvent(run.task_id, 'run_failed', { type: 'bot', id: bot.id }, { runId, error })
487
509
  // 额度耗尽没有「退避后自动重试」这回事:主备都限额就是终点,任务转受阻。
488
510
  const quotaNote = quotaExhausted
@@ -192,20 +192,31 @@ export const runsMethods = {
192
192
  }
193
193
  // owner 任务运行挂起项(review/handle/review_delegate,DSHBOTS-290 busy 闸):
194
194
  // 只读任务运行,按入队时快照建回,列面与 enqueueOwnerTaskRun 一致。
195
+ // DSHBOTS-358:额度路由快照随挂起项带回来,建回时同样落 model_* 三列。
195
196
  if (item.kind === 'owner_task') {
197
+ const routing = item.routing ?? {}
196
198
  try {
197
199
  this.store.run(
198
200
  `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
199
- attempt, idempotency_key, queued_at)
200
- VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
201
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
202
+ VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?, ?, ?, ?)`,
201
203
  runId, item.projectId, bot.id, item.taskId, item.runKind, item.triggerType, item.taskId,
202
- `${item.triggerType}:${item.taskId}:${Date.now()}:${runId}`, createdAt,
204
+ `${item.triggerType}:${item.taskId}:${Date.now()}:${runId}`,
205
+ routing.mode === 'fallback' ? routing.provider ?? null : null,
206
+ routing.mode === 'fallback' ? routing.model ?? null : null,
207
+ routing.mode === 'fallback' ? routing.effort ?? null : null,
208
+ createdAt,
203
209
  )
204
210
  } catch (error ) {
205
211
  if (String(error).includes('UNIQUE')) return null
206
212
  throw error
207
213
  }
208
214
  this.insertRunEvent(runId, 'queued', 'bot 空闲,挂起的 owner 任务运行建回(验收/接管)')
215
+ if (routing.mode === 'fallback') {
216
+ this.insertRunEvent(runId, 'quota_fallback', `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref ?? ''}`)
217
+ } else if (routing.mode === 'wait') {
218
+ this.insertRunEvent(runId, 'quota_wait', `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`)
219
+ }
209
220
  return runId
210
221
  }
211
222
  const spec = item.kind === 'chat'
@@ -560,10 +571,7 @@ export const runsMethods = {
560
571
  id('evt'), runId, 'canceled', '运行已取消', nowIso(),
561
572
  )
562
573
  if (updateTask && run.task_id) {
563
- this.store.run(
564
- "UPDATE tasks SET status = 'todo', version = version + 1, updated_at = ? WHERE id = ? AND status = 'in_progress'",
565
- nowIso(), run.task_id,
566
- )
574
+ this.setTaskStatus(run.task_id, 'todo', { type: 'system', id: 'system' }, { ifIs: 'in_progress' })
567
575
  this.addTaskEvent(run.task_id, 'run_canceled', { type: 'system', id: 'system' }, { runId })
568
576
  }
569
577
  return this.runRow(runId)
@@ -12,7 +12,7 @@
12
12
  import { createHash } from 'node:crypto'
13
13
  import { join } from 'node:path'
14
14
  import { scanProjectSkills } from '../../project-skills.js'
15
- import { parseDisabledSkills } from '../../util.js'
15
+ import { parseDisabledSkills, jsonParse } from '../../util.js'
16
16
  import { dmPrompt, replyDeliveryPrompt } from '../../botmsg.js'
17
17
  import { rolloverPendingKey, rolloverSummaryKey } from '../../config.js'
18
18
  import { taskDeadlineInfo } from '../tasks.js'
@@ -329,6 +329,24 @@ You can spawn child agents (\`subagent\` / \`subagent_fork\`) or named teammates
329
329
  ].join('\n')
330
330
  },
331
331
 
332
+ // 验收边界沉淀提醒块(搭车投递,吸收 dsh-agent-team acceptance-boundary 理念):
333
+ // 标记由 noteTaskAccepted 落(验收通过的负责人 × 项目),在这里渲染一次性提醒并清空——
334
+ // 附着在本就要跑的这一轮提示词里,不产生额外轮次,不注入会话日志。上限 3 条防积压。
335
+ acceptReminderBlock(bot, project) {
336
+ const key = `accept_remind:${bot.id}:${project.id}`
337
+ const list = jsonParse(this.store.setting(key), [])
338
+ if (!Array.isArray(list) || !list.length) return ''
339
+ this.store.setSetting(key, '[]')
340
+ const lines = list.slice(0, 3)
341
+ .map(item => `- ${item.identifier}(${item.title ?? ''},验收于 ${item.at ?? ''})`)
342
+ .join('\n')
343
+ return `
344
+
345
+ # Accepted tasks — persist durable conclusions
346
+ Tasks you executed below have been accepted. If any durable fact, decision or lesson worth keeping across tasks emerged and is not yet in memory, persist it now with team_remember (short topic, self-contained content; one-off process detail does not belong there). This notice appears once; skip silently if nothing qualifies.
347
+ ${lines}`
348
+ },
349
+
332
350
  // 单聊会话的身份段:没有项目上下文,工作区是 bot 自己的 _the_bots/<dir>。
333
351
  soloPromptFor(bot) {
334
352
  const workspace = bot.solo_dir ? join(this.config.workspace, '_the_bots', bot.solo_dir) : join(this.config.workspace, '_the_bots')
@@ -685,7 +703,7 @@ ${parallelMergeBody(this.config.maxTeammates)}` : ''
685
703
  const deliverablesLine = readDeliverables(task.deliverables).length
686
704
  ? `\nDeliverables (file paths): ${readDeliverables(task.deliverables).join(', ')}`
687
705
  : ''
688
- return `${header}${subtaskDisciplineBlock}${splittingGuidanceBlock}
706
+ return `${header}${subtaskDisciplineBlock}${splittingGuidanceBlock}${this.acceptReminderBlock(bot, project)}
689
707
 
690
708
  Do the task in the project workspace. End with a delivery report (≤${this.config.deliveryReportMaxChars} chars): what changed, verification performed, blockers or risks — not just a plan. Never paste file contents into the report or chat — reference paths; reviewers open the files.${parallel}${parallelMerge}
691
709
 
@@ -700,7 +718,7 @@ ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteB
700
718
  sessionId,
701
719
  // 审批卡片(kind='approval')是给人看的 UI 锚点,不进 bot 上下文;旧行迁移后回填 'text'。
702
720
  table: 'messages',
703
- columns: 'id, sender_type, sender_id, body, task_id',
721
+ columns: 'id, sender_type, sender_id, body, task_id, mentions_json',
704
722
  where: "project_id = ? AND kind = 'text'",
705
723
  params: [project.id],
706
724
  excludeId: chatMessage?.id,
@@ -708,9 +726,16 @@ ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteB
708
726
  // P3-1:无信息量 system 短状态不进尾窗;合批消息已在专门段落呈现,同样不进尾窗(不双份)。
709
727
  const mergedIds = new Set((extraMessages ?? []).map(item => item.id))
710
728
  const visible = recent.filter(item => !mergedIds.has(item.id) && !(item.sender_type === 'system' && NOISE_SYSTEM_BODY.test(item.body)))
729
+ // 分级注入(吸收 dsh-agent-team 直接信号/背景折叠理念):@本 bot 的消息与人的消息
730
+ // 保持 240 全文(@我的另加标记);其他 bot 的闲聊折叠成 80 字背景摘要,降噪省 token。
731
+ const botId = (bot ).id
711
732
  const context = visible.map((item) => {
712
- const body = item.body.length > 240 ? `${item.body.slice(0, 240)}…` : item.body
713
- return `- [m_${item.id.slice(-6)}] ${item.sender_type}:${item.sender_id}${item.task_id ? ' (task thread)' : ''}: ${body}`
733
+ const mentions = jsonParse(item.mentions_json, [])
734
+ const directed = Array.isArray(mentions) && mentions.includes(botId)
735
+ const limit = item.sender_type === 'bot' && !directed ? 80 : 240
736
+ const body = item.body.length > limit ? `${item.body.slice(0, limit)}…` : item.body
737
+ const mark = directed ? ' [→你]' : (item.sender_type === 'bot' && !directed ? ' (背景)' : '')
738
+ return `- [m_${item.id.slice(-6)}] ${item.sender_type}:${item.sender_id}${item.task_id ? ' (task thread)' : ''}${mark}: ${body}`
714
739
  }).join('\n')
715
740
  const recentBlock = context
716
741
  ? `${incremental ? 'New project messages since your last turn (ids are for team_recall):' : 'Recent project messages (truncated, ids are for team_recall):'}\n${context}`
@@ -753,7 +778,7 @@ Reply as ${bot.name} in the project group. Keep it under ${this.config.chatReply
753
778
 
754
779
  # Group message
755
780
  ${(chatMessage?.body ?? '(no message)').slice(0, 4_000)}
756
- ${this.mergedMessagesBlock(extraMessages)}${quoteLine}${this.rolloverSummaryBlock(bot, project, sessionId)}
781
+ ${this.mergedMessagesBlock(extraMessages)}${quoteLine}${this.rolloverSummaryBlock(bot, project, sessionId)}${this.acceptReminderBlock(bot, project)}
757
782
  ${recentBlock}
758
783
 
759
784
  Open tasks:
@@ -8,6 +8,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
10
  import { MAX_RATE_LIMIT_RETRIES, isQuotaExhausted, isRetryChainError } from './backoff.js'
11
+ import { INTERNAL_FALLBACK_KINDS } from './model-fallback.js'
11
12
  import { ensureTaskRelationsSchema, unsatisfiedBlockedDeps } from './task-relations.js'
12
13
  import { TASK_BUDGET_ROUNDS, TRANSITIONS, taskDeadlineInfo } from './tasks.js'
13
14
  import { effectiveWriteScopes, writeScopesOverlap } from './write-scopes.js'
@@ -632,8 +633,11 @@ export const schedulerMethods = {
632
633
  }
633
634
  // DSHBOTS-241 额度闸门:主 provider 仍在耗尽期、且本次没走备用模型的任务运行不领取——
634
635
  // 留 queued,恢复时间过后下一拍自动回主模型(避免每拍撞同一堵墙)。
636
+ // DSHBOTS-358:闸门扩到内部运行种类(任务/验收/受阻处理/记忆审查),
637
+ // mode='wait' 的内部运行同样留 queued 等恢复,不空转撞墙。
635
638
  // 走备用的运行(model_provider 非空)不受此闸影响,主备两套额度各自独立。
636
- if (run.kind === 'task' && !run.model_provider) {
639
+ // 聊天类运行不在此列:照发现行下发,失败文案与重试口径不动。
640
+ if (INTERNAL_FALLBACK_KINDS.has(run.kind) && !run.model_provider) {
637
641
  const quota = this.botQuotaState(run.bot_id, bot.provider)
638
642
  if (quota?.exhausted) {
639
643
  const alreadyNoted = this.store.get(
@@ -722,10 +726,7 @@ export const schedulerMethods = {
722
726
  }
723
727
  }
724
728
  if (run.task_id && run.kind === 'task') {
725
- this.store.run(
726
- "UPDATE tasks SET status = 'in_progress', version = version + 1, updated_at = ? WHERE id = ? AND status NOT IN ('done', 'canceled')",
727
- nowIso(), run.task_id,
728
- )
729
+ this.setTaskStatus(run.task_id, 'in_progress', { type: 'system', id: 'system' })
729
730
  this.addTaskEvent(run.task_id, 'run_started', { type: 'system', id: 'system' }, { runId: run.id })
730
731
  }
731
732
  void this.executeRun(run.id)
@@ -343,6 +343,13 @@ export const taskDispatchMethods = {
343
343
  if (input.taskId || input.task) {
344
344
  const task = this.resolveBotTask(project, input.taskId ?? input.task)
345
345
  if (['done', 'canceled'].includes(task.status)) throw conflict(`任务 ${project.key}-${task.number} 已结束,不能重派`)
346
+ // 变更栅栏(吸收 dsh-agent-team mutation-fence 理念):改卡可选带 expected_version
347
+ // (bot 最后看到的卡 version)。不匹配即拒,拒绝附最近变更事实,写者可就地重新
348
+ // 裁决;不带该参数保持既有 last-write-wins 行为(看板 UI 有自己的刷新闭环)。
349
+ if (input.expected_version !== undefined
350
+ && Number(input.expected_version) !== Number(task.version)) {
351
+ throw this.staleTaskConflict(task, input.expected_version)
352
+ }
346
353
  // 核验纪律派单闸(DSHBOTS-303):重派/改卡按生效卡面(本次传入优先,缺省回落原卡)。
347
354
  this.assertNotVerificationDispatch(project, member.id, input.title ?? task.title, input.description ?? task.description)
348
355
  // 派单策略闸(DSHBOTS-314):重派按原卡声明写范围同闸(重派不改写范围,D-232 口径)。
@@ -352,6 +359,9 @@ export const taskDispatchMethods = {
352
359
  // 写范围不在此口改:入队运行快照与调度闸门消费的不是同一份数据,
353
360
  // 改范围走工作台 taskUpdateScopes(含排队运行快照同步),不在这里开第二入口。
354
361
  const patch = {}
362
+ // 栅栏双保险:上面的预检与 updateTask 的 CAS 之间卡仍可能被并发更新,改卡补丁
363
+ // 一并携带 expected_version,由 updateTask 的 CAS 兜底拦截。
364
+ if (input.expected_version !== undefined) patch.version = input.expected_version
355
365
  if (input.title !== undefined) patch.title = input.title
356
366
  if (input.description !== undefined) patch.description = input.description
357
367
  if (input.priority !== undefined) patch.priority = input.priority
@@ -384,6 +394,20 @@ export const taskDispatchMethods = {
384
394
  + '未声明会让该任务的写运行与同项目其他写运行全部串行,一条任务即可堵死队列。',
385
395
  )
386
396
  }
397
+ // 大卡拆分闸(产品化派单纪律):写范围条目超过 maxWriteScopesPerTask 时拒绝整卡
398
+ // 派发——超大范围卡与同项目一切写运行按保守串行互斥,一条卡即可吃掉整队并行能力
399
+ // (2026-11-13 生产实测 run_parallel 触发率仅 26%,主因即大范围声明)。拒绝文案
400
+ // 按 D-269 口径 = 原因 + 替代命令(parent_task_id 拆子卡,子卡范围不相交即并行)。
401
+ const maxScopes = Number(this.config.maxWriteScopesPerTask)
402
+ if (scopes.length > maxScopes) {
403
+ throw badRequest(
404
+ `写范围 ${scopes.length} 条超过单卡上限 ${maxScopes}(maxWriteScopesPerTask),大卡必须拆分:`
405
+ + '先建一张主卡(或复用既有卡)拿任务号,再按独立部分拆子卡——每张子卡一次 '
406
+ + 'team_assign_task,传 parent_task_id=主卡任务号,write_scopes 只覆盖该部分且互不相交;'
407
+ + `范围有依赖顺序时用 blocked_by 串联。拆完后子卡可并行施工。`
408
+ + '确需单卡大范围时调大 DSH_TEAM_MAX_WRITE_SCOPES / maxWriteScopesPerTask。',
409
+ )
410
+ }
387
411
  // 同写范围重复卡拦截(DSHBOTS-82):同项目已有「写范围完全一致」的在办卡时直接拒绝,
388
412
  // 避免同一文件上叠 N 张排队卡空转。force_duplicate 是逃生口:跳过检测,但留审计痕迹。
389
413
  // 紧急豁免(DSHBOTS-126):priority='urgent' 的新卡放行——紧急任务无视排队立即施工,
@@ -10,6 +10,7 @@
10
10
  // 微信推送文案排版集中在 src/wechat/format.js(DSHBOTS-211)。
11
11
 
12
12
  import { taskCreated, taskDone } from '../wechat/format.js'
13
+ import { jsonParse, nowIso } from '../util.js'
13
14
 
14
15
  export const taskNotifyMethods = {
15
16
  // 「任务进入进行中」的唯一落点。
@@ -123,4 +124,21 @@ export const taskNotifyMethods = {
123
124
  this.logger.warn?.('dsh-team: 任务创建通知失败 %s: %s', identifier, error?.message ?? error)
124
125
  }
125
126
  },
127
+ // 验收边界沉淀提醒(吸收 dsh-agent-team acceptance-boundary 理念,搭车投递形态):
128
+ // 验收通过只落一个 per-(bot, project) 待提醒标记(上限 3 条),负责人在该项目的下一次
129
+ // 运行提示词里渲染一次性提醒块(见 prompt.ts acceptReminderBlock)并清标记——零额外
130
+ // 轮次、不往会话日志注入外来消息、不依赖会话存续(steer 形态的三个毛病都没有)。
131
+ noteTaskAccepted(task) {
132
+ const project = this.projectRow(task.project_id)
133
+ const identifier = `${project.key}-${task.number}`
134
+ if (!task.assignee_bot_id) return false
135
+ const key = `accept_remind:${task.assignee_bot_id}:${project.id}`
136
+ const list = jsonParse(this.store.setting(key), [])
137
+ const safe = Array.isArray(list) ? list : []
138
+ const next = [...safe.filter(item => item?.identifier !== identifier), {
139
+ identifier, title: task.title ?? '', at: nowIso(),
140
+ }].slice(-3)
141
+ this.store.setSetting(key, JSON.stringify(next))
142
+ return true
143
+ },
126
144
  }
@@ -55,6 +55,28 @@ export const taskReviewMethods = {
55
55
  )
56
56
  },
57
57
 
58
+ // 执行者不得验收(builder≠verifier,吸收自 dsh-agent-team 的协作理念):
59
+ // bot 验收时校验该 bot 从未担任过本卡负责人——含当前 assignee 与历史派单
60
+ // (task_events 的 created/assigned 事件)。工作台 owner(人)与看板/看门狗
61
+ // (system)不受此闸:信任边界归人,机械闸只拦 bot 自审自发。
62
+ assertAcceptorNotExecutor(task, project, actorBotId) {
63
+ const identifier = `${project.key}-${task.number}`
64
+ const executed = task.assignee_bot_id === actorBotId || !!this.store.get(
65
+ `SELECT 1 FROM task_events WHERE task_id = ?
66
+ AND ((type = 'assigned' AND json_extract(data_json, '$.botId') = ?)
67
+ OR (type = 'created' AND json_extract(data_json, '$.assigneeBotId') = ?))
68
+ LIMIT 1`,
69
+ task.id, actorBotId, actorBotId,
70
+ )
71
+ if (executed) {
72
+ throw conflict(
73
+ `任务 ${identifier} 的验收者就是它的执行者,执行者不得验收:`
74
+ + '把该卡验收交给未执行过本卡的 bot(team_assign_task 重派验收方),'
75
+ + '或由工作台 owner 在看板/管理通道直接验收。',
76
+ )
77
+ }
78
+ },
79
+
58
80
  /** 验收/退回的共用流程:owner Bot 会话与微信管理员共用。 */
59
81
  async applyReview(task, project, decision, comment, actor) {
60
82
  const identifier = `${project.key}-${task.number}`
@@ -67,6 +89,9 @@ export const taskReviewMethods = {
67
89
  + '若卡面或目标有误,用 team_assign_task 重派原任务(task=原任务号,附 title/description 即改卡)修正。',
68
90
  )
69
91
  }
92
+ if (decision === 'accept' && actor?.type === 'bot') {
93
+ this.assertAcceptorNotExecutor(task, project, actor.id)
94
+ }
70
95
  if (decision === 'accept') {
71
96
  await this.updateTask(task.id, { status: 'done' }, actor)
72
97
  if (comment) await this.addComment(task.id, comment, actor)
@@ -77,6 +102,8 @@ export const taskReviewMethods = {
77
102
  body: `任务 ${identifier} 验收通过。`,
78
103
  taskId: task.id,
79
104
  })
105
+ // 验收边界沉淀提醒:落待提醒标记,负责人下次在该项目运行时搭车渲染(零额外轮次)。
106
+ this.noteTaskAccepted(this.taskRow(task.id))
80
107
  } else {
81
108
  const reason = text(comment, 20_000)
82
109
  if (!reason) throw badRequest('退回任务必须说明原因')
@@ -169,6 +196,12 @@ export const taskReviewMethods = {
169
196
  if (active.trigger_type === 'review_delegate') return { runId: active.id, reused: true }
170
197
  throw conflict(`任务 ${identifier} 已有运行在排队或执行,请先停止再委派核验`)
171
198
  }
199
+ // DSHBOTS-358:额度路由(与任务运行同口径)——主 provider 耗尽时走备用模型,
200
+ // 无可用备用则留 queued 等恢复;路由快照写进运行行的 model_* 三列。
201
+ const routing = this.quotaRoutingForBot(owner)
202
+ const routeProvider = routing.mode === 'fallback' ? routing.provider : null
203
+ const routeModel = routing.mode === 'fallback' ? routing.model : null
204
+ const routeEffort = routing.mode === 'fallback' ? routing.effort : null
172
205
  // busy 闸(DSHBOTS-290):总监忙时不落 runs 行(撞 one_active_run_per_bot),挂待
173
206
  // 处理队列空闲建回(insertHeldMessageRun 的 owner_task 分支);返回 deferred 让
174
207
  // 手动入口与 outbox 自动入口都能感知「已挂起」而非失败。
@@ -176,6 +209,11 @@ export const taskReviewMethods = {
176
209
  this.holdPendingMessage(owner.id, project.id, {
177
210
  kind: 'owner_task', messageId: `owner_task:${task.id}:review_delegate`, taskId: task.id,
178
211
  projectId: project.id, runKind: 'review', triggerType: 'review_delegate', queuedAt: nowIso(),
212
+ routing: routing.mode === 'fallback'
213
+ ? { mode: 'fallback', provider: routing.provider, model: routing.model, effort: routing.effort, ref: routing.ref }
214
+ : routing.mode === 'wait'
215
+ ? { mode: 'wait', resetAt: routing.resetAt }
216
+ : { mode: 'primary' },
179
217
  })
180
218
  return { runId: null, deferred: true }
181
219
  }
@@ -183,15 +221,21 @@ export const taskReviewMethods = {
183
221
  const createdAt = nowIso()
184
222
  this.store.run(
185
223
  `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
186
- attempt, idempotency_key, queued_at)
187
- VALUES (?, ?, ?, ?, 'review', 'read', 'review_delegate', ?, 'queued', 1, ?, ?)`,
188
- runId, project.id, owner.id, task.id, task.id, `review_delegate:${task.id}:${Date.now()}:${runId}`, createdAt,
224
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
225
+ VALUES (?, ?, ?, ?, 'review', 'read', 'review_delegate', ?, 'queued', 1, ?, ?, ?, ?, ?)`,
226
+ runId, project.id, owner.id, task.id, task.id, `review_delegate:${task.id}:${Date.now()}:${runId}`,
227
+ routeProvider, routeModel, routeEffort, createdAt,
189
228
  )
190
229
  this.store.run(
191
230
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
192
231
  id('evt'), runId, 'queued',
193
232
  `${origin === 'auto' ? '交付后自动' : 'owner'}委派子代理核验(${actor.type}:${actor.id})`, createdAt,
194
233
  )
234
+ if (routing.mode === 'fallback') {
235
+ this.insertRunEvent(runId, 'quota_fallback', `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}`)
236
+ } else if (routing.mode === 'wait') {
237
+ this.insertRunEvent(runId, 'quota_wait', `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`)
238
+ }
195
239
  this.audit(actor, origin === 'auto' ? 'review.auto_delegate' : 'task.review_delegate', 'task', task.id, { runId })
196
240
  void this.tick()
197
241
  return { runId, reused: false }
@@ -179,9 +179,21 @@ export const taskRunMethods = {
179
179
  // busy 闸(DSHBOTS-290):owner 忙时 review/handle 运行同样不落 runs 行(撞
180
180
  // one_active_run_per_bot),挂待处理队列空闲建回——与 enqueueTaskRun 同口径。
181
181
  // DSHBOTS-300:挂起项提为 hold 闭包,busy 分支与查后插竞态兜底共用。
182
+ // DSHBOTS-358:额度路由(与任务运行同口径)——主 provider 耗尽时走备用模型,
183
+ // 无可用备用则留 queued 等恢复;路由快照写进运行行的 model_* 三列。
184
+ // 路由在 busy 闸之前算好:挂起项要带同一份快照,空闲建回时列面与直插一致。
185
+ const routing = this.quotaRoutingForBot(owner)
186
+ const routeProvider = routing.mode === 'fallback' ? routing.provider : null
187
+ const routeModel = routing.mode === 'fallback' ? routing.model : null
188
+ const routeEffort = routing.mode === 'fallback' ? routing.effort : null
182
189
  const hold = () => this.holdPendingMessage(owner.id, project.id, {
183
190
  kind: 'owner_task', messageId: `owner_task:${current.id}:${kind}`, taskId: current.id,
184
191
  projectId: project.id, runKind: kind, triggerType, queuedAt: createdAt,
192
+ routing: routing.mode === 'fallback'
193
+ ? { mode: 'fallback', provider: routing.provider, model: routing.model, effort: routing.effort, ref: routing.ref }
194
+ : routing.mode === 'wait'
195
+ ? { mode: 'wait', resetAt: routing.resetAt }
196
+ : { mode: 'primary' },
185
197
  })
186
198
  if (this.botBusy(owner.id, project.id)) {
187
199
  hold()
@@ -190,10 +202,11 @@ export const taskRunMethods = {
190
202
  try {
191
203
  this.store.run(
192
204
  `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, ?, ?)`,
205
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
206
+ VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?, ?, ?, ?)`,
195
207
  runId, project.id, owner.id, task.id, kind, triggerType, task.id,
196
- `${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
208
+ `${kind}:${task.id}:${Date.now()}:${runId}`,
209
+ routeProvider, routeModel, routeEffort, createdAt,
197
210
  )
198
211
  } catch (error ) {
199
212
  // DSHBOTS-304:双投胜利方同任务 active 运行已在→合并返回其 id 消算(同 enqueueTaskRun)。
@@ -211,6 +224,21 @@ export const taskRunMethods = {
211
224
  kind === 'review' ? '任务交付,转总监验收' : '任务受阻,转总监处理',
212
225
  createdAt,
213
226
  )
227
+ // DSHBOTS-358:内部运行同样接额度路由——主 provider 耗尽时直接走备用模型;
228
+ // 无可用备用则留 queued 等恢复(调度器额度闸门兜底),不再照常下发撞墙。
229
+ if (routing.mode === 'fallback') {
230
+ this.insertRunEvent(
231
+ runId,
232
+ 'quota_fallback',
233
+ `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}(预计 ${this.botQuotaState(owner.id, owner.provider)?.resetAt ?? '未知'} 恢复)`,
234
+ )
235
+ } else if (routing.mode === 'wait') {
236
+ this.insertRunEvent(
237
+ runId,
238
+ 'quota_wait',
239
+ `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`,
240
+ )
241
+ }
214
242
  void this.tick()
215
243
  return runId
216
244
  },