dsh-team-bots 0.3.80 → 0.3.105

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 (50) 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-migrations.js +5 -1
  6. package/src/db.js +52 -0
  7. package/src/feishu/channel.js +15 -11
  8. package/src/feishu/format.js +37 -1
  9. package/src/runtime.js +13 -1
  10. package/src/service.js +5 -0
  11. package/src/services/approvals.js +7 -2
  12. package/src/services/bots.js +8 -1
  13. package/src/services/chat-stores.js +564 -0
  14. package/src/services/chat.js +60 -28
  15. package/src/services/core.js +33 -12
  16. package/src/services/feishu.js +1 -1
  17. package/src/services/memory.js +14 -12
  18. package/src/services/model-fallback.js +3 -1
  19. package/src/services/notify.js +18 -8
  20. package/src/services/projects.js +25 -19
  21. package/src/services/questions.js +37 -12
  22. package/src/services/review-watchdog.js +31 -12
  23. package/src/services/run-finish.js +21 -14
  24. package/src/services/runs.js +29 -41
  25. package/src/services/runtime/context-window.js +6 -4
  26. package/src/services/runtime/lifecycle.js +1 -0
  27. package/src/services/runtime/prompt.js +21 -9
  28. package/src/services/runtime/sandbox-policy.js +1 -1
  29. package/src/services/runtime/session.js +27 -15
  30. package/src/services/runtime/trajectory.js +3 -1
  31. package/src/services/scheduler.js +48 -49
  32. package/src/services/system.js +9 -7
  33. package/src/services/task-review.js +27 -19
  34. package/src/services/task-runs.js +40 -21
  35. package/src/services/tasks.js +18 -10
  36. package/src/services/terminal.js +25 -14
  37. package/src/services/vision-proxy.js +67 -9
  38. package/src/services/wechat.js +24 -8
  39. package/src/subagent-ledger.js +23 -6
  40. package/src/usage-reconcile.js +93 -32
  41. package/src/usage.js +125 -50
  42. package/src/util.js +17 -0
  43. package/src/wechat/channel.js +3 -1
  44. package/src/wechat/commands.js +13 -1
  45. package/ui/modules/events-click.js +14 -1
  46. package/ui/modules/file-preview.js +22 -10
  47. package/ui/modules/markdown.js +10 -8
  48. package/ui/modules/tasks.js +1 -1
  49. package/ui/styles/cards.css +13 -0
  50. package/ui/styles/modal.css +4 -0
@@ -234,8 +234,9 @@ export const sessionMethods = {
234
234
  return run
235
235
  },
236
236
  // kind 'task' = 任务 worker 会话(全局链走 workerPreset);其余 = 控制面/单聊/核验会话
237
- //(全局链走 routerPreset)。bot.agent_preset 非空时逐 bot 覆盖,两级都留空时 kind
238
- // 决定用哪个全局链。可选 preset 只从宿主 roster 里实际可用(非 broken)的里挑。
237
+ //(全局链走 routerPreset)。bot.agent_preset 非空时逐 bot 覆盖,两级都留空或指向不可用
238
+ // preset 时用插件自带预设,再回落 standard。可选 preset 只从宿主 roster 里实际可用
239
+ //(非 broken)的里挑;插件不改动宿主全局默认。
239
240
  async defaultAgentPreset(kind, bot = null) {
240
241
  const botPreset = String(bot?.agent_preset ?? '').trim()
241
242
  const wanted = botPreset
@@ -247,8 +248,8 @@ export const sessionMethods = {
247
248
  if (!presets) return {}
248
249
  const list = await presets.list()
249
250
  const available = (list ?? []).filter(preset => preset.broken === undefined).map(preset => preset.id)
250
- // 只有确认存在的 preset 才会被选中;Router 缺省沿用 standard,避免装错配置直接起不来。
251
- const pick = [wanted, 'standard'].find(id => id && available.includes(id))
251
+ // 未配置(或配置失效)时用插件自带预设,再回落 standard,避免装错配置直接起不来。
252
+ const pick = [wanted, 'team-bots', 'standard'].find(id => id && available.includes(id))
252
253
  return pick ? { agentPreset: pick } : {}
253
254
  } catch {
254
255
  return {}
@@ -289,11 +290,16 @@ export const sessionMethods = {
289
290
  // type='subagent_spawned' 计数(DSHBOTS-294 账本落账)。无账本记录返回 0,不误触发。
290
291
  sessionSubagentCount(sessionId) {
291
292
  if (!sessionId) return 0
292
- return this.store.get(
293
- `SELECT COUNT(*) AS n FROM run_events re JOIN runs r ON r.id = re.run_id
294
- WHERE r.session_id = ? AND re.type = 'subagent_spawned'`,
295
- sessionId,
296
- )?.n ?? 0
293
+ // 事件住各运行归属的聊天库(chat-db-split Phase 3):按会话名下运行逐库计数合并。
294
+ const runs = this.store.all('SELECT id, project_id, bot_id FROM runs WHERE session_id = ?', sessionId)
295
+ let n = 0
296
+ for (const run of runs) {
297
+ n += this.chatStoreForRun(run).get(
298
+ "SELECT COUNT(*) AS n FROM run_events WHERE run_id = ? AND type = 'subagent_spawned'",
299
+ run.id,
300
+ )?.n ?? 0
301
+ }
302
+ return n
297
303
  },
298
304
  // 结转判定(DSHBOTS-145 / DSHBOTS-286):旧会话是否该让位。返回 true 表示旧绑定已
299
305
  // alias 化、调用方走新建路径;false 表示继续复用旧会话。
@@ -357,7 +363,7 @@ export const sessionMethods = {
357
363
  queuedAt,
358
364
  )
359
365
  if (!inserted.changes) return runId
360
- this.store.run(
366
+ this.chatStoreForRun({ project_id: project?.id ?? null, bot_id: bot.id }).run(
361
367
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
362
368
  id('evt'),
363
369
  runId,
@@ -422,7 +428,7 @@ export const sessionMethods = {
422
428
  queuedAt,
423
429
  )
424
430
  if (!inserted.changes) return runId
425
- this.store.run(
431
+ this.chatStoreForRun({ project_id: project?.id ?? null, bot_id: bot.id }).run(
426
432
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
427
433
  id('evt'),
428
434
  runId,
@@ -814,7 +820,7 @@ export const sessionMethods = {
814
820
  this.sessionCreates.delete(key)
815
821
  }
816
822
  },
817
- async startRun({ run, bot, project, task, chatMessage, extraMessages, sessionKind } ) {
823
+ async startRun({ run, bot, project, task, chatMessage, extraMessages, sessionKind } ) {
818
824
  if (!this.ctx?.sessionController) throw new AppError('DSH_UNAVAILABLE', 'DSH Session 服务不可用')
819
825
  // 备用模型覆盖:派生运行在 runs 行里带 model_* 三列,指明这条运行改用备用模型下发。
820
826
  // 不带 override 的运行照旧走 Bot 主模型——「运行结束自动回退」就靠这条默认路径实现。
@@ -836,6 +842,8 @@ export const sessionMethods = {
836
842
  sessionId,
837
843
  bot: effectiveBot,
838
844
  projectId: project?.id ?? null,
845
+ // 聊天分库(chat-db-split Phase 1):本运行的正文库(轨迹记账/附图读取用)。
846
+ chatStore: this.chatStoreForRun(run),
839
847
  // 任务归因(DSHBOTS-212):记账时透传到 usage_events.task_id;
840
848
  // 非任务运行为 null,沿用既有「无任务归因」口径。
841
849
  taskId: run.task_id ?? null,
@@ -874,14 +882,18 @@ export const sessionMethods = {
874
882
  'UPDATE runs SET session_id = ?, started_at = ?, last_progress_at = ? WHERE id = ?',
875
883
  sessionId, startedAt, startedAt, run.id,
876
884
  )
877
- this.store.run(
885
+ this.chatStoreForRun(run).run(
878
886
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
879
887
  id('evt'), run.id, 'started', `Session ${sessionId}`, new Date().toISOString(),
880
888
  )
881
889
  try {
882
890
  // 聊天附图:首条 prompt 一并带上 image 分片,模型这轮就能看到用户发的图。
883
- // 宿主会把不能吃图片的模型降级成占位文本,插件不判模型能力。
884
- const imageParts = chatMessage?.id ? imageContentPartsForMessage(this.store, chatMessage.id) : []
891
+ // 宿主对吃不了图片的模型直接抛 attachment-invalid(不降级),所以续答运行
892
+ // (image_offload=1)跳过附图,转写正文已由提示词近期窗口带入。
893
+ // 附图随消息住在聊天库里(chat-db-split Phase 1)。
894
+ const imageParts = chatMessage?.id && !run.image_offload
895
+ ? imageContentPartsForMessage(pending.chatStore ?? this.store, chatMessage.id)
896
+ : []
885
897
  await this.ctx.sessionController.prompt({
886
898
  requestId: randomUUID(),
887
899
  sessionId,
@@ -119,12 +119,14 @@ export const trajectoryMethods = {
119
119
  if (!pending.toolNames) pending.toolNames = new Map()
120
120
  const entries = this.trajectoryEntries(pending, event, options)
121
121
  if (!entries.length) return
122
+ // 聊天分库(chat-db-split Phase 1):轨迹落运行归属的聊天库;无归属信息时回落顶库。
123
+ const store = pending.chatStore ?? this.store
122
124
  const createdAt = Number.isFinite(event?.time) ? new Date(event.time).toISOString() : nowIso()
123
125
  for (const entry of entries) {
124
126
  if ((pending.trajectoryCount ?? 0) >= TRAJECTORY_MAX_ENTRIES) return
125
127
  pending.trajectoryCount = (pending.trajectoryCount ?? 0) + 1
126
128
  pending.trajectorySeq = (pending.trajectorySeq ?? 0) + 1
127
- this.store.run(
129
+ store.run(
128
130
  'INSERT INTO run_trajectory(id, run_id, seq, kind, title, detail, turn, step, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
129
131
  id('traj'), pending.runId, pending.trajectorySeq, entry.kind, entry.title,
130
132
  truncateDetail(this.maskForStorage(entry.detail)),
@@ -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()