dsh-team-bots 0.3.80 → 0.3.98

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 (40) hide show
  1. package/cordis.patch.yml +100 -0
  2. package/index.js +5 -2
  3. package/package.json +1 -1
  4. package/src/api.js +5 -1
  5. package/src/db.js +52 -0
  6. package/src/runtime.js +13 -1
  7. package/src/service.js +5 -0
  8. package/src/services/approvals.js +7 -2
  9. package/src/services/bots.js +8 -1
  10. package/src/services/chat-stores.js +564 -0
  11. package/src/services/chat.js +60 -28
  12. package/src/services/core.js +30 -10
  13. package/src/services/feishu.js +1 -1
  14. package/src/services/memory.js +14 -12
  15. package/src/services/model-fallback.js +3 -1
  16. package/src/services/notify.js +18 -8
  17. package/src/services/projects.js +25 -19
  18. package/src/services/questions.js +2 -1
  19. package/src/services/review-watchdog.js +31 -12
  20. package/src/services/run-finish.js +17 -13
  21. package/src/services/runs.js +29 -41
  22. package/src/services/runtime/context-window.js +6 -4
  23. package/src/services/runtime/lifecycle.js +1 -0
  24. package/src/services/runtime/prompt.js +21 -9
  25. package/src/services/runtime/sandbox-policy.js +1 -1
  26. package/src/services/runtime/session.js +22 -13
  27. package/src/services/runtime/trajectory.js +3 -1
  28. package/src/services/scheduler.js +48 -49
  29. package/src/services/system.js +9 -7
  30. package/src/services/task-review.js +27 -19
  31. package/src/services/task-runs.js +40 -21
  32. package/src/services/tasks.js +18 -10
  33. package/src/services/terminal.js +25 -14
  34. package/src/services/vision-proxy.js +9 -6
  35. package/src/services/wechat.js +1 -1
  36. package/src/subagent-ledger.js +23 -6
  37. package/src/usage-reconcile.js +93 -32
  38. package/src/usage.js +125 -50
  39. package/ui/modules/tasks.js +1 -1
  40. package/ui/styles/cards.css +13 -0
@@ -229,7 +229,7 @@ export const schedulerMethods = {
229
229
  const reviewRunId = this.enqueueMemoryReview(project, bot, task, sourceRun.id)
230
230
  if (!reviewRunId) {
231
231
  // 记忆审查未启用:按规则沉淀兜底,保证任务交付有沉淀。
232
- this.learnFromTask(project, bot, task, sourceRun.output ?? '', sourceRun.id)
232
+ this.learnFromTask(project, bot, task, this.runOutputOf(sourceRun) ?? '', sourceRun.id)
233
233
  }
234
234
  return reviewRunId
235
235
  }
@@ -340,9 +340,13 @@ export const schedulerMethods = {
340
340
  <= CAST(strftime('%s', 'now') AS REAL)
341
341
  AND CAST(strftime('%s', COALESCE(r.ended_at, r.queued_at)) AS REAL) + r.retry_after_ms / 1000.0
342
342
  > CAST(strftime('%s', 'now') AS REAL) - ${PLAN_RETRY_MAX_LATE_SECONDS}
343
- AND NOT EXISTS(SELECT 1 FROM run_events e WHERE e.run_id = r.id AND e.type = 'plan_retry')`,
343
+ `,
344
344
  )
345
345
  for (const run of expired) {
346
+ // 幂等闸(Phase 3 起事件住聊天库):已派生过的运行跳过。
347
+ if (this.runChatStore(run).get(
348
+ "SELECT 1 AS ok FROM run_events WHERE run_id = ? AND type = 'plan_retry'", run.id,
349
+ )) continue
346
350
  // DSHBOTS-266:重试链判定(限流码 ∪ 网络瞬态)在 JS 做;非链内错误码不派生(现状不变)。
347
351
  if (!isRetryChainError({ code: run.error_code, message: run.error_message })) continue
348
352
  // DSHBOTS-99:额度耗尽(已达到限额)的运行不再自动派生重试——额度窗口用尽时重打主模型
@@ -370,11 +374,8 @@ export const schedulerMethods = {
370
374
  runId, run.project_id, run.bot_id, run.task_id, run.id, run.task_id,
371
375
  (run.attempt ?? 1) + 1, `plan_retry:${run.id}`, run.write_scopes, createdAt,
372
376
  )
373
- this.store.run(
374
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
375
- id('evt'), run.id, 'plan_retry',
376
- `限流重试到期,派生新运行 ${runId}(attempt ${(run.attempt ?? 1) + 1})`, createdAt,
377
- )
377
+ this.insertRunEvent(run.id, 'plan_retry',
378
+ `限流重试到期,派生新运行 ${runId}(attempt ${(run.attempt ?? 1) + 1})`)
378
379
  } catch (error ) {
379
380
  // idempotency_key UNIQUE 撞车 = 另一个 tick 已派生过,跳过即可。
380
381
  if (String(error).includes('UNIQUE')) continue
@@ -395,15 +396,13 @@ export const schedulerMethods = {
395
396
  runId,
396
397
  )
397
398
  if (Number(changed?.changes ?? 0) !== 1) return false
398
- const alreadyNoted = this.store.get(
399
+ const run = this.store.get('SELECT id, project_id, bot_id FROM runs WHERE id = ?', runId)
400
+ const alreadyNoted = run && this.runChatStore(run).get(
399
401
  "SELECT 1 AS ok FROM run_events WHERE run_id = ? AND type = 'stale_superseded'",
400
402
  runId,
401
403
  )
402
404
  if (!alreadyNoted) {
403
- this.store.run(
404
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
405
- id('evt'), runId, 'stale_superseded', '任务已结束,排队运行被清理(SUPERSEDED)', nowIso(),
406
- )
405
+ this.insertRunEvent(runId, 'stale_superseded', '任务已结束,排队运行被清理(SUPERSEDED)')
407
406
  }
408
407
  return true
409
408
  },
@@ -484,14 +483,11 @@ export const schedulerMethods = {
484
483
  "UPDATE runs SET status = 'canceled', ended_at = ?, error_code = 'TASK_DEADLINE', error_message = ? WHERE id = ? AND status = 'queued'",
485
484
  now, body, runId,
486
485
  )
487
- this.store.run(
488
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
489
- id('evt'), runId, 'task_deadline', `整卡死线已到(${deadlineIso}),拒绝启动新施工运行`, now,
490
- )
491
- this.store.run(
486
+ this.insertRunEvent(runId, 'task_deadline', `整卡死线已到(${deadlineIso}),拒绝启动新施工运行`)
487
+ this.store.afterCommit(() => this.groupChatStore(project.id).run(
492
488
  'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
493
489
  commentId, task.id, 'system', 'system', body, now,
494
- )
490
+ ))
495
491
  this.addTaskEvent(task.id, 'commented', { type: 'system', id: 'system' }, { commentId, deadline: deadlineIso, runId })
496
492
  })
497
493
  if (TRANSITIONS[task.status]?.has('blocked')) {
@@ -522,6 +518,8 @@ export const schedulerMethods = {
522
518
  // 有工作或窗口到期则照常全量。提醒类扫描(滞留卡/验收守门)与到期重试派生在慢拍粒度
523
519
  // (默认 15s)下运行,阈值均为分钟级,无感;入队路径的事件唤醒 tick() 与测试直调不经此门。
524
520
  tickIdleGate() {
521
+ // 已停机不再探库:停机后底层库已关闭,这里的读会抛错并变成未处理的 rejection。
522
+ if (this.stopped || !this.started) return null
525
523
  const idleMs = Number(this.config.schedulerIdleIntervalMs ?? 15_000)
526
524
  if (Date.now() - this.lastFullTickAt < idleMs) {
527
525
  const probe = this.store.get(
@@ -536,7 +534,7 @@ export const schedulerMethods = {
536
534
  },
537
535
 
538
536
  async tick() {
539
- if (this.ticking || !this.started) return
537
+ if (this.ticking || !this.started || this.stopped) return
540
538
  this.ticking = true
541
539
  this.lastFullTickAt = Date.now()
542
540
  try {
@@ -608,21 +606,18 @@ export const schedulerMethods = {
608
606
  // 候选过滤(DSHBOTS-110):任务已终态(done/canceled)的 queued 任务运行不再领取;
609
607
  // 只排 kind='task',非任务运行不受影响。LEFT JOIN 出 NULL 的孤儿任务运行不过滤。
610
608
  const candidates = this.store.all(
611
- `SELECT r.*, t.ignored_write_scopes AS task_ignored_scopes FROM runs r LEFT JOIN tasks t ON t.id = r.task_id
612
- LEFT JOIN messages m ON m.id = r.trigger_ref
609
+ `SELECT r.*, t.priority AS task_priority, t.ignored_write_scopes AS task_ignored_scopes
610
+ FROM runs r LEFT JOIN tasks t ON t.id = r.task_id
613
611
  WHERE r.status = 'queued'
614
612
  AND NOT (r.kind = 'task' AND COALESCE(t.status, '') IN ('done', 'canceled'))
615
- ORDER BY CASE
616
- WHEN r.kind = 'chat' AND m.sender_type = 'bot' THEN 2
617
- WHEN r.kind <> 'task' OR t.priority IS NULL THEN 1
618
- WHEN t.priority = 'urgent' THEN 0
619
- WHEN t.priority = 'high' THEN 1
620
- WHEN t.priority = 'medium' THEN 2
621
- WHEN t.priority = 'low' THEN 3
622
- ELSE 4
623
- END, r.queued_at
624
- LIMIT 50`,
613
+ LIMIT 200`,
625
614
  )
615
+ // 出队定档移到 JS:分库后 messages 住各聊天库(顶库 messages 已空,
616
+ // 旧 LEFT JOIN 恒 NULL,DSHBOTS-272 的机器流量档自 Phase 1 起失效)——
617
+ // 群聊运行改按触发消息的 sender_type 实测定档,任务优先级档照旧。
618
+ for (const run of candidates) run.claim_tier = this.claimTierOf(run)
619
+ candidates.sort((a, b) =>
620
+ (a.claim_tier - b.claim_tier) || String(a.queued_at ?? '').localeCompare(String(b.queued_at ?? '')))
626
621
  for (const run of candidates) {
627
622
  const human = isHumanRun(run)
628
623
  if (activeTotal >= maxRuns + (human && !humanSlotTaken ? 1 : 0)) break
@@ -670,7 +665,7 @@ export const schedulerMethods = {
670
665
  if (INTERNAL_FALLBACK_KINDS.has(run.kind) && !run.model_provider) {
671
666
  const quota = this.botQuotaState(run.bot_id, bot.provider)
672
667
  if (quota?.exhausted) {
673
- const alreadyNoted = this.store.get(
668
+ const alreadyNoted = this.runChatStore(run).get(
674
669
  "SELECT 1 AS ok FROM run_events WHERE run_id = ? AND type = 'quota_wait'",
675
670
  run.id,
676
671
  )
@@ -697,18 +692,14 @@ export const schedulerMethods = {
697
692
  const taskRow = this.store.get('SELECT * FROM tasks WHERE id = ?', run.task_id)
698
693
  const blockers = unsatisfiedBlockedDeps(this.store, taskRow)
699
694
  if (blockers.length) {
700
- const alreadyNoted = this.store.get(
695
+ const alreadyNoted = this.runChatStore(run).get(
701
696
  "SELECT 1 AS ok FROM run_events WHERE run_id = ? AND type = 'task_blocked_dep'",
702
697
  run.id,
703
698
  )
704
699
  if (!alreadyNoted) {
705
700
  const projectKeyRow = this.store.get('SELECT key FROM projects WHERE id = ?', run.project_id)
706
- this.store.run(
707
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
708
- id('evt'), run.id, 'task_blocked_dep',
709
- `依赖未完结,暂缓领取:${blockers.map(row => `${projectKeyRow?.key ?? 'T'}-${row.number}`).join('、')}`,
710
- nowIso(),
711
- )
701
+ this.insertRunEvent(run.id, 'task_blocked_dep',
702
+ `依赖未完结,暂缓领取:${blockers.map(row => `${projectKeyRow?.key ?? 'T'}-${row.number}`).join('、')}`)
712
703
  }
713
704
  continue
714
705
  }
@@ -733,10 +724,7 @@ export const schedulerMethods = {
733
724
  // 借用了人的消息保底槽(超出并发上限放行):记事件并占住额外槽,下一次归还前不再放第二条。
734
725
  if (human && activeTotal >= maxRuns) {
735
726
  humanSlotTaken = true
736
- this.store.run(
737
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
738
- id('evt'), run.id, 'human_slot', '并发已满,借人的消息保底槽放行', nowIso(),
739
- )
727
+ this.insertRunEvent(run.id, 'human_slot', '并发已满,借人的消息保底槽放行')
740
728
  }
741
729
  activeTotal += 1
742
730
  activeKeys.add(claimKey)
@@ -749,10 +737,7 @@ export const schedulerMethods = {
749
737
  list.push(writeScopes)
750
738
  activeWriteScopes.set(run.project_id, list)
751
739
  if (parallel) {
752
- this.store.run(
753
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
754
- id('evt'), run.id, 'run_parallel', '写范围与同项目在跑的写运行不重叠,并行放行', nowIso(),
755
- )
740
+ this.insertRunEvent(run.id, 'run_parallel', '写范围与同项目在跑的写运行不重叠,并行放行')
756
741
  }
757
742
  }
758
743
  if (run.task_id && run.kind === 'task') {
@@ -779,12 +764,26 @@ export const schedulerMethods = {
779
764
  runEventDays: Number(this.store.setting('retention_run_event_days', '0') || 0),
780
765
  messageDays: Number(this.store.setting('retention_message_days', '0') || 0),
781
766
  reconciliationDays: Number(this.store.setting('retention_reconciliation_days', '30') || 0),
782
- })
783
- const reconciliation = reconcileUsage(this.store, { days: 30, expiredBefore: retention.usage.before })
767
+ }, this.allChatStores())
768
+ const reconciliation = reconcileUsage(this.store, { days: 30, expiredBefore: retention.usage.before, chatStoreFor: run => this.runChatStore(run) })
784
769
  const reapedMessages = this.reapStuckMessages()
785
770
  return { reconciliation, retention, reapedMessages }
786
771
  },
787
772
 
773
+ // 领取定档(DSHBOTS-272 口径,分库修正):任务运行按任务优先级(urgent 先),
774
+ // 其余运行视同 high;群聊运行的触发消息来自 bot(@mention 派发)时降到机器流量档,
775
+ // 同车道内用户提问(tier 1)必然先于它领取。sender_type 住聊天库,按运行归属实测。
776
+ claimTierOf(run) {
777
+ if (run.kind === 'chat') {
778
+ const sender = run.project_id && run.trigger_ref
779
+ ? this.groupChatStore(run.project_id).get('SELECT sender_type FROM messages WHERE id = ?', run.trigger_ref)?.sender_type
780
+ : null
781
+ return sender === 'bot' ? 2 : 1
782
+ }
783
+ if (run.kind !== 'task' || !run.task_priority) return 1
784
+ return { urgent: 0, high: 1, medium: 2, low: 3 }[run.task_priority] ?? 4
785
+ },
786
+
788
787
  // 私信卡死回收:消息停在 pending 说明入队或投递链路断了。
789
788
  // 没有 outbox 行的补一条,终态 failed 的行重置后重排,
790
789
  // 免得一条私信永远停在「已入库但没人投递」的状态。
@@ -89,8 +89,9 @@ const systemMethodsBase = {
89
89
  // runs 不含 updated_at:新运行看行数、启动/结束看 started_at/ended_at;
90
90
  // last_progress_at 的巡检心跳不进签名——它不改变视图载荷,计入会重新引入高频失效。
91
91
  sig(`SELECT COUNT(*) AS n, COALESCE(MAX(queued_at), '') || COALESCE(MAX(started_at), '') || COALESCE(MAX(ended_at), '') AS m FROM runs`),
92
- stamp('messages', 'rowid'),
93
- stamp('solo_messages', 'rowid'),
92
+ // 聊天正文已分库(chat-db-split Phase 1):messages/solo_messages 的签名由各聊天库
93
+ // 的本连接累计变更数承接,任一库的写都会推进版本;读路径不触库。
94
+ ...this.chatVersionParts(),
94
95
  // bot_messages 的 status/reply 变更不推 rowid,靠 replied_at 捕捉。
95
96
  sig(`SELECT COUNT(*) AS n, COALESCE(MAX(COALESCE(replied_at, created_at)), '') AS m FROM bot_messages`),
96
97
  stamp('memories', 'updated_at'),
@@ -236,7 +237,8 @@ const systemMethodsBase = {
236
237
  if (project) {
237
238
  const group = this.groupOf(project.id)
238
239
  view.project = this.projectView(project)
239
- const messages = this.store.all(
240
+ // 聊天正文住项目聊天库(chat-db-split Phase 1)。
241
+ const messages = this.groupChatStore(project.id).all(
240
242
  `SELECT * FROM (SELECT * FROM messages WHERE project_id = ? ORDER BY created_at DESC LIMIT 200) ORDER BY created_at ASC`,
241
243
  project.id,
242
244
  )
@@ -286,11 +288,11 @@ const systemMethodsBase = {
286
288
  // 归档契约(DSHBOTS-174):默认视图(归档窗口交集,或两维全关时的 200 条回退上限)隐去的
287
289
  // 更早消息数。被隐去的都严格早于窗口最旧一条,UI 据此点亮「加载更早」入口,经 messagesPage
288
290
  // 游标必可翻回;无隐去时 count=0 / hasMore=false,入口不出现。
289
- const soloWindow = soloVisibleMessages(this.store, soloBot.id, {
291
+ const soloWindow = soloVisibleMessages(this.soloChatStore(soloBot.id), soloBot.id, {
290
292
  days: this.config.dmArchiveDays,
291
293
  keep: this.config.dmKeepRecent,
292
294
  })
293
- const soloTotal = Number(this.store.get('SELECT COUNT(*) AS count FROM solo_messages WHERE bot_id = ?', soloBot.id)?.count ?? 0)
295
+ const soloTotal = Number(this.soloChatStore(soloBot.id).get('SELECT COUNT(*) AS count FROM solo_messages WHERE bot_id = ?', soloBot.id)?.count ?? 0)
294
296
  const archivedCount = Math.max(0, soloTotal - soloWindow.length)
295
297
  // 单聊卡片条目(DSHBOTS-218):提问/审批在单聊会话里发起时落 solo_messages 卡片锚点,
296
298
  // 状态查 questions/approvals 表(project_id 为空的那批)。
@@ -432,7 +434,7 @@ const systemMethodsBase = {
432
434
  // 单聊分页与默认视图同源取数(DSHBOTS-171):翻页不过归档窗口,被归档的更早消息
433
435
  // 仍可见——「归档」只是默认视图隐去,不是删除。群聊保持原口径,不受私信归档影响。
434
436
  if (isSolo) {
435
- const page = soloVisibleMessages(this.store, soloBotId, { beforeCreatedAt, beforeId, limit: pageSize })
437
+ const page = soloVisibleMessages(this.soloChatStore(soloBotId), soloBotId, { beforeCreatedAt, beforeId, limit: pageSize })
436
438
  return {
437
439
  messages: page.messages.map(row => this.soloMessageView(row)),
438
440
  hasMore: page.hasMore,
@@ -440,7 +442,7 @@ const systemMethodsBase = {
440
442
  }
441
443
  // 游标口径:取「严格早于游标」的最近 pageSize 条(第 pageSize+1 条仅作 hasMore 探位,不进结果)。
442
444
  // 先按 DESC 取回、slice 掉探位行、再翻回 ASC——顺序不能反,否则会丢掉紧邻游标的那条。
443
- const rows = this.store.all(
445
+ const rows = this.groupChatStore(projectId).all(
444
446
  `SELECT * FROM messages
445
447
  WHERE project_id = ? AND (created_at < ? OR (created_at = ? AND id < ?))
446
448
  ORDER BY created_at DESC, id DESC
@@ -8,7 +8,7 @@
8
8
  import { badRequest, conflict, forbidden } from '../errors.js'
9
9
  import { bool } from '../config.js'
10
10
  import { REVIEWER_BOT_NAME } from '../seed-bots.js'
11
- import { id, nowIso, text } from '../util.js'
11
+ import { id, nowIso, text, jsonParse} from '../util.js'
12
12
  import { parseWriteScopes, readWriteScopes } from './write-scopes.js'
13
13
  import { effectiveSandbox } from './runtime/sandbox-policy.js'
14
14
 
@@ -54,30 +54,36 @@ export const taskReviewMethods = {
54
54
  // 仅机器人路径:微信管理员/看板 owner 走 applyReview,不经过本闸。
55
55
  assertReviewSubagentVerified(sessionId, project, task, comment) {
56
56
  if (comment?.includes('兜底验收')) return
57
- // run_events 无 run_id 索引:先筛 runs 再 EXISTS,量级与旧「当运行」查询相同。
58
- const windowStart = this.store.get(
57
+ // run_events 住各运行归属的聊天库(Phase 3):先筛 runs 再逐运行查归属库,量级与旧「当运行」查询相同。
58
+ const windowStart = this.groupChatStore(task.project_id).get(
59
59
  `SELECT MAX(created_at) AS t FROM task_events WHERE task_id = ?
60
60
  AND (type = 'run_succeeded' OR (type = 'status' AND json_extract(data_json, '$.to') = 'in_review'))`,
61
61
  task.id,
62
62
  )?.t ?? ''
63
63
  // 核验分档:本评审周期的交付运行为只读档(事件载荷 runId 指回交付运行)时免子代理
64
64
  // 账目——与自动委派豁免同口径;无交付运行锚(如纯看板流转)时保持强制,不放宽。
65
- const delivered = this.store.get(
66
- `SELECT r.* FROM task_events e JOIN runs r ON r.id = json_extract(e.data_json, '$.runId')
67
- WHERE e.task_id = ? AND e.type = 'run_succeeded' AND e.created_at >= ?
68
- ORDER BY e.created_at DESC LIMIT 1`,
65
+ // Phase 3:task_events 住项目聊天库(runs 仍顶库):先取事件,再回顶库取运行行。
66
+ const chat = this.groupChatStore(task.project_id)
67
+ const event = chat.get(
68
+ `SELECT data_json FROM task_events WHERE task_id = ? AND type = 'run_succeeded' AND created_at >= ?
69
+ ORDER BY created_at DESC LIMIT 1`,
69
70
  task.id, windowStart,
70
71
  )
72
+ const deliveredRunId = event ? (jsonParse(event.data_json, {}) ?? {}).runId : null
73
+ const delivered = deliveredRunId
74
+ ? this.store.get('SELECT * FROM runs WHERE id = ?', deliveredRunId)
75
+ : null
71
76
  if (delivered && this.readOnlyDelivery(delivered, task)) return
72
- const ledger = this.store.get(
73
- `SELECT 1 AS hit FROM runs r
74
- WHERE ((r.task_id = ? AND r.bot_id = ?) OR r.session_id = ?
75
- OR (r.task_id = ? AND r.trigger_type = 'review_delegate'))
76
- AND EXISTS (SELECT 1 FROM run_events e
77
- WHERE e.run_id = r.id AND e.type = 'subagent_spawned' AND e.created_at >= ?)
78
- LIMIT 1`,
79
- task.id, project.owner_bot_id, sessionId, task.id, windowStart,
77
+ const candidates = this.store.all(
78
+ `SELECT id, project_id, bot_id FROM runs
79
+ WHERE (task_id = ? AND bot_id = ?) OR session_id = ?
80
+ OR (task_id = ? AND trigger_type = 'review_delegate')`,
81
+ task.id, project.owner_bot_id, sessionId, task.id,
80
82
  )
83
+ const ledger = candidates.some(run => this.runChatStore(run).get(
84
+ "SELECT 1 AS hit FROM run_events WHERE run_id = ? AND type = 'subagent_spawned' AND created_at >= ?",
85
+ run.id, windowStart,
86
+ ))
81
87
  if (ledger) return
82
88
  // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 正确下一步。
83
89
  throw badRequest(
@@ -163,7 +169,7 @@ export const taskReviewMethods = {
163
169
  )
164
170
  if (runningWrite) throw badRequest('任务有运行中的写运行,先等运行结束或取消,再修改写范围')
165
171
  const queuedWrites = this.store.all(
166
- "SELECT id FROM runs WHERE task_id = ? AND status = 'queued' AND mode = 'write'",
172
+ "SELECT id, project_id, bot_id FROM runs WHERE task_id = ? AND status = 'queued' AND mode = 'write'",
167
173
  taskId,
168
174
  )
169
175
  const from = readWriteScopes(task.write_scopes)
@@ -262,15 +268,17 @@ export const taskReviewMethods = {
262
268
  }
263
269
  throw error
264
270
  }
265
- this.store.run(
271
+ this.runChatStore({ project_id: project.id, bot_id: verifier.id }).run(
266
272
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
267
273
  id('evt'), runId, 'queued',
268
274
  `${origin === 'auto' ? '交付后自动' : 'owner'}委派子代理核验(${actor.type}:${actor.id})`, createdAt,
269
275
  )
270
276
  if (routing.mode === 'fallback') {
271
- this.insertRunEvent(runId, 'quota_fallback', `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}`)
277
+ const run = this.store.get('SELECT * FROM runs WHERE id = ?', runId)
278
+ this.insertRunEvent(run.id, 'quota_fallback', `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}`)
272
279
  } else if (routing.mode === 'wait') {
273
- this.insertRunEvent(runId, 'quota_wait', `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`)
280
+ const run = this.store.get('SELECT * FROM runs WHERE id = ?', runId)
281
+ this.insertRunEvent(run.id, 'quota_wait', `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`)
274
282
  }
275
283
  this.audit(actor, origin === 'auto' ? 'review.auto_delegate' : 'task.review_delegate', 'task', task.id, { runId })
276
284
  void this.tick()
@@ -20,7 +20,7 @@ export const taskRunMethods = {
20
20
  return await this.pauseRunsForBoard(taskId)
21
21
  }
22
22
  const runs = this.store.all(
23
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running') AND mode = 'write'",
23
+ "SELECT * FROM runs WHERE task_id = ? AND status IN ('queued', 'running') AND mode = 'write'",
24
24
  taskId,
25
25
  )
26
26
  const errorMessage = `任务离开「进行中」(${fromStatus ?? '-'} → ${toStatus ?? '-'}),写运行中止,写占用已释放`
@@ -30,7 +30,10 @@ export const taskRunMethods = {
30
30
  'UPDATE runs SET error_code = ?, error_message = ? WHERE id = ?',
31
31
  'TASK_LEFT_IN_PROGRESS', errorMessage, run.id,
32
32
  )
33
- this.insertRunEvent(run.id, 'task_left_in_progress', errorMessage)
33
+ this.runChatStore(run).run(
34
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
35
+ id('evt'), run.id, 'task_left_in_progress', errorMessage, nowIso(),
36
+ )
34
37
  }
35
38
  return runs.length
36
39
  },
@@ -55,15 +58,17 @@ export const taskRunMethods = {
55
58
  const body = text(bodyInput, 20_000)
56
59
  if (!body) throw badRequest('评论不能为空')
57
60
  const commentId = id('cmt')
61
+ const chat = this.groupChatStore(task.project_id)
58
62
  this.store.transaction(() => {
59
- this.store.run(
63
+ // 评论写经 afterCommit 跟随外层提交/回滚(addTaskEvent 同理,内部已挂)。
64
+ this.store.afterCommit(() => chat.run(
60
65
  'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
61
66
  commentId, taskId, actor.type, actor.id, body, nowIso(),
62
- )
67
+ ))
63
68
  this.addTaskEvent(taskId, 'commented', actor, { commentId })
64
69
  this.audit(actor, 'task.comment', 'task', taskId, { commentId })
65
70
  })
66
- const comment = this.store.get('SELECT * FROM task_comments WHERE id = ?', commentId)
71
+ const comment = chat.get('SELECT * FROM task_comments WHERE id = ?', commentId)
67
72
  const steered = await this.steerRunningTaskRun(task, comment, actor)
68
73
  return { ...comment, steered }
69
74
  },
@@ -82,7 +87,7 @@ export const taskRunMethods = {
82
87
  run.session_id,
83
88
  `New comment on ${project?.key ?? 'TASK'}-${task.number} from ${author}:\n${comment.body}\n\nIf this changes the plan, adjust the work in progress; otherwise keep going and mention it in the delivery report.`,
84
89
  )
85
- this.store.run(
90
+ this.runChatStore(run).run(
86
91
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
87
92
  id('evt'), run.id, 'steered', `评论直通(${author})`, nowIso(),
88
93
  )
@@ -134,25 +139,34 @@ export const taskRunMethods = {
134
139
  if (this.activeRunByTaskId(task.id)) return this.activeRunByTaskId(task.id)
135
140
  throw error
136
141
  }
137
- this.store.run(
142
+ // run_events 住运行归属的聊天库(chat-db-split Phase 3):取回 run 行统一路由,
143
+ // queued 沿用与 runs.queued_at 同刻的 createdAt。
144
+ const run = this.store.get('SELECT * FROM runs WHERE id = ?', runId)
145
+ const chatStore = this.runChatStore(run)
146
+ chatStore.run(
138
147
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
139
148
  id('evt'), runId, 'queued', `由 ${actor.type}:${actor.id} 触发`, createdAt,
140
149
  )
141
150
  if (routing.mode === 'fallback') {
142
- this.insertRunEvent(
143
- runId,
144
- 'quota_fallback',
151
+ chatStore.run(
152
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
153
+ id('evt'), runId, 'quota_fallback',
145
154
  `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}(预计 ${this.botQuotaState(bot.id, bot.provider)?.resetAt ?? '未知'} 恢复)`,
155
+ nowIso(),
146
156
  )
147
157
  } else if (routing.mode === 'wait') {
148
- this.insertRunEvent(
149
- runId,
150
- 'quota_wait',
158
+ chatStore.run(
159
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
160
+ id('evt'), runId, 'quota_wait',
151
161
  `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`,
162
+ nowIso(),
152
163
  )
153
164
  }
154
165
  if (triggerType === 'board_resume') {
155
- this.insertRunEvent(runId, 'board_resume', '看板拖入执行中,系统指令自动开工')
166
+ chatStore.run(
167
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
168
+ id('evt'), runId, 'board_resume', '看板拖入执行中,系统指令自动开工', nowIso(),
169
+ )
156
170
  }
157
171
  return runId
158
172
  },
@@ -218,7 +232,10 @@ export const taskRunMethods = {
218
232
  }
219
233
  throw error
220
234
  }
221
- this.store.run(
235
+ // 同 enqueueTaskRun:run_events 按运行归属聊天库路由,queued 沿用 createdAt。
236
+ const ownerRun = this.store.get('SELECT * FROM runs WHERE id = ?', runId)
237
+ const chatStore = this.runChatStore(ownerRun)
238
+ chatStore.run(
222
239
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
223
240
  id('evt'), runId, 'queued',
224
241
  kind === 'review' ? '任务交付,转总监验收' : '任务受阻,转总监处理',
@@ -227,16 +244,18 @@ export const taskRunMethods = {
227
244
  // DSHBOTS-358:内部运行同样接额度路由——主 provider 耗尽时直接走备用模型;
228
245
  // 无可用备用则留 queued 等恢复(调度器额度闸门兜底),不再照常下发撞墙。
229
246
  if (routing.mode === 'fallback') {
230
- this.insertRunEvent(
231
- runId,
232
- 'quota_fallback',
247
+ chatStore.run(
248
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
249
+ id('evt'), runId, 'quota_fallback',
233
250
  `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}(预计 ${this.botQuotaState(owner.id, owner.provider)?.resetAt ?? '未知'} 恢复)`,
251
+ nowIso(),
234
252
  )
235
253
  } else if (routing.mode === 'wait') {
236
- this.insertRunEvent(
237
- runId,
238
- 'quota_wait',
254
+ chatStore.run(
255
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
256
+ id('evt'), runId, 'quota_wait',
239
257
  `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`,
258
+ nowIso(),
240
259
  )
241
260
  }
242
261
  void this.tick()
@@ -235,10 +235,14 @@ export const tasksMethods = {
235
235
  return this.taskView(this.taskRow(taskId))
236
236
  },
237
237
  addTaskEvent(taskId, type, actor, data = {}) {
238
- this.store.run(
238
+ // 任务事件住任务所属项目的聊天库(chat-db-split Phase 3):task 行在顶库,按 project_id 路由。
239
+ const projectId = this.store.get('SELECT * FROM tasks WHERE id = ?', taskId)?.project_id
240
+ // afterCommit:调用方常包在顶库事务里(setTaskStatus 等)——聊天库写跟随顶库
241
+ // 提交/回滚,外层回滚不残留事件(Phase 3 跨库原子性收口)。
242
+ this.store.afterCommit(() => this.groupChatStore(projectId).run(
239
243
  'INSERT INTO task_events(id, task_id, type, actor_type, actor_id, data_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
240
244
  id('tevt'), taskId, type, actor.type, actor.id, JSON.stringify(data), nowIso(),
241
- )
245
+ ))
242
246
  },
243
247
  // 统一状态迁移落点(吸收 dsh-agent-team「账本为权威、投影可重放」理念):所有直接改
244
248
  // tasks.status 的路径都经此走——同一事务内 UPDATE + 权威 'status' 事件(from/to),
@@ -267,7 +271,7 @@ export const tasksMethods = {
267
271
  taskProjectionDrift() {
268
272
  const drifted = []
269
273
  for (const task of this.store.all('SELECT id, number, project_id, status FROM tasks')) {
270
- const events = this.store.all(
274
+ const events = this.groupChatStore(task.project_id).all(
271
275
  `SELECT type, data_json FROM task_events WHERE task_id = ?
272
276
  AND (type = 'created' OR (type = 'status' AND json_extract(data_json, '$.field') = 'status'))
273
277
  ORDER BY created_at, rowid`,
@@ -292,7 +296,8 @@ export const tasksMethods = {
292
296
  // 增量非一一对应(交付是一事件一增量,updateTask 是一增量多事件),故按时间取最近
293
297
  // N 条而非按版本切割。
294
298
  taskChangesSince(taskId, limit = 5) {
295
- const rows = this.store.all(
299
+ const projectId = this.store.get('SELECT * FROM tasks WHERE id = ?', taskId)?.project_id
300
+ const rows = this.groupChatStore(projectId).all(
296
301
  'SELECT type, actor_type, actor_id, data_json, created_at FROM task_events WHERE task_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?',
297
302
  taskId, limit,
298
303
  )
@@ -356,7 +361,7 @@ export const tasksMethods = {
356
361
  blockedBy: deps.blockedBy,
357
362
  depsSatisfied: deps.depsSatisfied,
358
363
  blockedByNames: deps.blockedByNames,
359
- comments: Number(this.store.get('SELECT COUNT(*) AS count FROM task_comments WHERE task_id = ?', task.id)?.count ?? 0),
364
+ comments: Number(this.groupChatStore(task.project_id).get('SELECT COUNT(*) AS count FROM task_comments WHERE task_id = ?', task.id)?.count ?? 0),
360
365
  latestRun: runs[0] ?? null,
361
366
  runs,
362
367
  stage,
@@ -565,7 +570,7 @@ export const tasksMethods = {
565
570
  // 指派者名(DSHBOTS-257):/detail 卡片直读 assigneeName,在此按 assignee_bot_id
566
571
  // 解析(同 task-notify 口径),不进 taskView 列表热路径(每卡一次 bots 查询)。
567
572
  assigneeName: task.assignee_bot_id ? this.botRow(task.assignee_bot_id)?.name ?? null : null,
568
- comments: this.store.all(
573
+ comments: this.groupChatStore(task.project_id).all(
569
574
  'SELECT author_type, author_id, body, created_at FROM task_comments WHERE task_id = ? ORDER BY created_at DESC LIMIT 3',
570
575
  task.id,
571
576
  ).reverse(),
@@ -574,8 +579,9 @@ export const tasksMethods = {
574
579
  async taskDetail(taskId) {
575
580
  const task = this.taskRow(taskId)
576
581
  const project = this.projectRow(task.project_id)
577
- const comments = this.store.all('SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at', taskId)
578
- const events = this.store.all('SELECT * FROM task_events WHERE task_id = ? ORDER BY created_at', taskId)
582
+ // 评论与事件住任务所属项目的聊天库(chat-db-split Phase 3);runs/依赖仍在顶库。
583
+ const comments = this.groupChatStore(task.project_id).all('SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at', taskId)
584
+ const events = this.groupChatStore(task.project_id).all('SELECT * FROM task_events WHERE task_id = ? ORDER BY created_at', taskId)
579
585
  const runs = this.store.all("SELECT * FROM runs WHERE task_id = ? AND COALESCE(error_code, '') <> 'SUPERSEDED' ORDER BY queued_at DESC", taskId)
580
586
  const dependencies = this.store.all(
581
587
  'SELECT t.id, t.number, t.title, t.status FROM task_dependencies d JOIN tasks t ON t.id = d.depends_on_task_id WHERE d.task_id = ?',
@@ -587,12 +593,14 @@ export const tasksMethods = {
587
593
  // 只挂 taskDetail 单卡详情,不进 taskView 列表热路径(每卡一次聚合会放大列表查询)。
588
594
  const subtreeIds = taskSubtreeIds(this.store, taskId)
589
595
  const budgetCurrency = this.budgetCurrency()
596
+ // 任务用量明细住该任务项目的聊天库(chat-db-split Phase 2);子树 id 集来自顶库 tasks。
597
+ const usageStore = this.groupChatStore(project.id)
590
598
  return {
591
599
  ...this.taskView(task),
592
600
  projectKey: project.key,
593
601
  usage: {
594
- own: taskUsageTotals(this.store, taskId, budgetCurrency),
595
- total: taskTreeUsageTotals(this.store, taskId, budgetCurrency),
602
+ own: taskUsageTotals(usageStore, taskId, budgetCurrency, this.store),
603
+ total: taskTreeUsageTotals(usageStore, taskId, budgetCurrency, subtreeIds, this.store),
596
604
  subtaskCount: subtreeIds.length - 1,
597
605
  },
598
606
  comments: comments.map(comment => ({