dsh-team-bots 0.3.79 → 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 (46) 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 +3 -0
  6. package/src/db.js +53 -0
  7. package/src/runtime.js +13 -1
  8. package/src/service.js +5 -0
  9. package/src/services/approvals.js +7 -2
  10. package/src/services/bots.js +8 -1
  11. package/src/services/chat-stores.js +564 -0
  12. package/src/services/chat.js +60 -28
  13. package/src/services/core.js +30 -10
  14. package/src/services/feishu.js +1 -1
  15. package/src/services/memory.js +14 -12
  16. package/src/services/model-fallback.js +3 -1
  17. package/src/services/notify.js +18 -8
  18. package/src/services/projects.js +25 -19
  19. package/src/services/questions.js +2 -1
  20. package/src/services/review-watchdog.js +31 -12
  21. package/src/services/run-finish.js +17 -13
  22. package/src/services/runs.js +29 -41
  23. package/src/services/runtime/context-window.js +6 -4
  24. package/src/services/runtime/lifecycle.js +1 -0
  25. package/src/services/runtime/prompt.js +21 -9
  26. package/src/services/runtime/sandbox-policy.js +1 -1
  27. package/src/services/runtime/session.js +22 -13
  28. package/src/services/runtime/trajectory.js +3 -1
  29. package/src/services/scheduler.js +63 -54
  30. package/src/services/system.js +9 -7
  31. package/src/services/task-dispatch.js +28 -21
  32. package/src/services/task-review.js +34 -25
  33. package/src/services/task-runs.js +40 -21
  34. package/src/services/tasks.js +34 -18
  35. package/src/services/terminal.js +25 -14
  36. package/src/services/vision-proxy.js +9 -6
  37. package/src/services/wechat.js +1 -1
  38. package/src/subagent-ledger.js +23 -6
  39. package/src/usage-reconcile.js +93 -32
  40. package/src/usage.js +125 -50
  41. package/ui/i18n/en/settings.js +1 -0
  42. package/ui/i18n/zh/settings.js +1 -0
  43. package/ui/modules/modal-forms.js +8 -8
  44. package/ui/modules/tasks.js +1 -1
  45. package/ui/styles/cards.css +13 -0
  46. package/ui/styles/modal.css +2 -0
@@ -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()
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { badRequest, conflict, notFound } from '../errors.js'
8
8
  import { clampNumber, id, nowIso, projectKey, TASK_ID_PATTERN, text } from '../util.js'
9
- import { parseDeliverables, parseWriteScopes, parseWriteScopesFromDescription, readDeliverables, readWriteScopes } from './write-scopes.js'
9
+ import { filterIgnoredWriteScopes, parseDeliverables, parseWriteScopes, parseWriteScopesFromDescription, readDeliverables, readWriteScopes } from './write-scopes.js'
10
10
  import { ensureAttentionSchema, parseAttention } from './attention-schema.js'
11
11
  import { SANDBOX_OVERRIDES } from './file-policy.js'
12
12
  import { ensureTaskSandboxSchema } from './task-sandbox-schema.js'
@@ -173,16 +173,17 @@ export const tasksMethods = {
173
173
  ensureTaskSandboxSchema(this.store)
174
174
  let number
175
175
  this.store.transaction(() => {
176
- // 派单清洗(DSHBOTS-168):ignored 机械移除 + 一级目录驳回,与建档同事务——
177
- // 清洗后清单即落库清单(运行快照天然继承),审计挂真实 taskId 不产生孤儿行。
178
- const writeScopes = this.normalizeDispatchScopes(project, parsedScopes, { actor, taskId })
176
+ // 派单清洗:ignored 染色 + 一级目录驳回,与建档同事务——有效清单与染色清单
177
+ // 分别落 write_scopes / ignored_write_scopes(运行快照天然继承有效清单),
178
+ // 审计挂真实 taskId 不产生孤儿行。
179
+ const { scopes: writeScopes, ignored } = this.normalizeDispatchScopes(project, parsedScopes, { actor, taskId })
179
180
  const relations = validateTaskRelations({ store: this.store, projectId: project.id, taskId, parentTaskId, blockedBy })
180
181
  number = Number(this.store.get('SELECT COALESCE(MAX(number), 0) + 1 AS n FROM tasks WHERE project_id = ?', project.id)?.n ?? 1)
181
182
  this.store.run(
182
183
  `INSERT INTO tasks(id, project_id, number, title, description, status, priority, assignee_bot_id,
183
184
  creator_type, creator_id, review_target, source_message_id, parent_id, parent_task_id, blocked_by, position, due_at, estimate,
184
- time_budget_minutes, write_scopes, deliverables, sandbox_override, version, created_at, updated_at, completed_at, canceled_at)
185
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?)`,
185
+ time_budget_minutes, write_scopes, ignored_write_scopes, deliverables, sandbox_override, version, created_at, updated_at, completed_at, canceled_at)
186
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?)`,
186
187
  taskId, project.id, number, title, text(input.description, 40_000), status, priority,
187
188
  assigneeId, actor.type, actor.id, actor.type === 'bot' ? 'owner_bot' : 'user',
188
189
  input.sourceMessageId ?? null, input.parentId ?? null,
@@ -190,6 +191,7 @@ export const tasksMethods = {
190
191
  Number.isFinite(Number(input.position)) ? Number(input.position) : number,
191
192
  input.dueAt ? new Date(input.dueAt).toISOString() : null,
192
193
  clampNumber(input.estimate, 0, 1000, null), timeBudgetMinutes, JSON.stringify(writeScopes),
194
+ JSON.stringify(ignored),
193
195
  JSON.stringify(deliverables),
194
196
  sandboxOverride, createdAt, createdAt,
195
197
  completedAt, canceledAt,
@@ -233,10 +235,14 @@ export const tasksMethods = {
233
235
  return this.taskView(this.taskRow(taskId))
234
236
  },
235
237
  addTaskEvent(taskId, type, actor, data = {}) {
236
- 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(
237
243
  'INSERT INTO task_events(id, task_id, type, actor_type, actor_id, data_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
238
244
  id('tevt'), taskId, type, actor.type, actor.id, JSON.stringify(data), nowIso(),
239
- )
245
+ ))
240
246
  },
241
247
  // 统一状态迁移落点(吸收 dsh-agent-team「账本为权威、投影可重放」理念):所有直接改
242
248
  // tasks.status 的路径都经此走——同一事务内 UPDATE + 权威 'status' 事件(from/to),
@@ -265,7 +271,7 @@ export const tasksMethods = {
265
271
  taskProjectionDrift() {
266
272
  const drifted = []
267
273
  for (const task of this.store.all('SELECT id, number, project_id, status FROM tasks')) {
268
- const events = this.store.all(
274
+ const events = this.groupChatStore(task.project_id).all(
269
275
  `SELECT type, data_json FROM task_events WHERE task_id = ?
270
276
  AND (type = 'created' OR (type = 'status' AND json_extract(data_json, '$.field') = 'status'))
271
277
  ORDER BY created_at, rowid`,
@@ -290,7 +296,8 @@ export const tasksMethods = {
290
296
  // 增量非一一对应(交付是一事件一增量,updateTask 是一增量多事件),故按时间取最近
291
297
  // N 条而非按版本切割。
292
298
  taskChangesSince(taskId, limit = 5) {
293
- 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(
294
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 ?',
295
302
  taskId, limit,
296
303
  )
@@ -335,7 +342,7 @@ export const tasksMethods = {
335
342
  task.id,
336
343
  )
337
344
  const project = this.store.get('SELECT key FROM projects WHERE id = ?', task.project_id)
338
- const { write_scopes: rawScopes, deliverables: rawDeliverables, time_budget_minutes: rawTimeBudget, ...rest } = task
345
+ const { write_scopes: rawScopes, ignored_write_scopes: rawIgnoredScopes, deliverables: rawDeliverables, time_budget_minutes: rawTimeBudget, ...rest } = task
339
346
  // 阶段按事实推导(task-stage 块):与 latestRun 同源;attention 取最近运行的待回答提问。
340
347
  const attention = runs[0] ? parseAttention(runs[0].attention_json) : null
341
348
  const stage = taskStage(task, runs[0] ?? null, attention)
@@ -345,6 +352,8 @@ export const tasksMethods = {
345
352
  identifier: `${project?.key ?? 'T'}-${task.number}`,
346
353
  labels,
347
354
  writeScopes: readWriteScopes(rawScopes),
355
+ // 染色写范围(命中 .gitignore):进卡面展示但不参与并行锁判定。
356
+ ignoredWriteScopes: readWriteScopes(rawIgnoredScopes),
348
357
  deliverables: readDeliverables(rawDeliverables),
349
358
  // 时效要求(分钟):null=发布方未提;供 UI 展示与提示词注入共用一个口径。
350
359
  timeBudgetMinutes: Number.isFinite(rawTimeBudget) ? rawTimeBudget : null,
@@ -352,7 +361,7 @@ export const tasksMethods = {
352
361
  blockedBy: deps.blockedBy,
353
362
  depsSatisfied: deps.depsSatisfied,
354
363
  blockedByNames: deps.blockedByNames,
355
- 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),
356
365
  latestRun: runs[0] ?? null,
357
366
  runs,
358
367
  stage,
@@ -441,7 +450,11 @@ export const tasksMethods = {
441
450
  if (patch.dueAt !== undefined) updates.due_at = patch.dueAt ? new Date(patch.dueAt).toISOString() : null
442
451
  if (patch.estimate !== undefined) updates.estimate = clampNumber(patch.estimate, 0, 1000, null)
443
452
  if (patch.writeScopes !== undefined) {
444
- updates.write_scopes = JSON.stringify(parseWriteScopes(patch.writeScopes))
453
+ // 与派单入口同口径拆分:命中 .gitignore 的条目染色进 ignored_write_scopes,
454
+ // 有效范围进 write_scopes 参与并行锁。
455
+ const { kept, removed } = filterIgnoredWriteScopes(parseWriteScopes(patch.writeScopes), this.projectWorkDir(this.projectRow(task.project_id)))
456
+ updates.write_scopes = JSON.stringify(kept)
457
+ updates.ignored_write_scopes = JSON.stringify(removed)
445
458
  }
446
459
  if (patch.deliverables !== undefined) {
447
460
  updates.deliverables = JSON.stringify(parseDeliverables(patch.deliverables))
@@ -557,7 +570,7 @@ export const tasksMethods = {
557
570
  // 指派者名(DSHBOTS-257):/detail 卡片直读 assigneeName,在此按 assignee_bot_id
558
571
  // 解析(同 task-notify 口径),不进 taskView 列表热路径(每卡一次 bots 查询)。
559
572
  assigneeName: task.assignee_bot_id ? this.botRow(task.assignee_bot_id)?.name ?? null : null,
560
- comments: this.store.all(
573
+ comments: this.groupChatStore(task.project_id).all(
561
574
  'SELECT author_type, author_id, body, created_at FROM task_comments WHERE task_id = ? ORDER BY created_at DESC LIMIT 3',
562
575
  task.id,
563
576
  ).reverse(),
@@ -566,8 +579,9 @@ export const tasksMethods = {
566
579
  async taskDetail(taskId) {
567
580
  const task = this.taskRow(taskId)
568
581
  const project = this.projectRow(task.project_id)
569
- const comments = this.store.all('SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at', taskId)
570
- 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)
571
585
  const runs = this.store.all("SELECT * FROM runs WHERE task_id = ? AND COALESCE(error_code, '') <> 'SUPERSEDED' ORDER BY queued_at DESC", taskId)
572
586
  const dependencies = this.store.all(
573
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 = ?',
@@ -579,12 +593,14 @@ export const tasksMethods = {
579
593
  // 只挂 taskDetail 单卡详情,不进 taskView 列表热路径(每卡一次聚合会放大列表查询)。
580
594
  const subtreeIds = taskSubtreeIds(this.store, taskId)
581
595
  const budgetCurrency = this.budgetCurrency()
596
+ // 任务用量明细住该任务项目的聊天库(chat-db-split Phase 2);子树 id 集来自顶库 tasks。
597
+ const usageStore = this.groupChatStore(project.id)
582
598
  return {
583
599
  ...this.taskView(task),
584
600
  projectKey: project.key,
585
601
  usage: {
586
- own: taskUsageTotals(this.store, taskId, budgetCurrency),
587
- total: taskTreeUsageTotals(this.store, taskId, budgetCurrency),
602
+ own: taskUsageTotals(usageStore, taskId, budgetCurrency, this.store),
603
+ total: taskTreeUsageTotals(usageStore, taskId, budgetCurrency, subtreeIds, this.store),
588
604
  subtaskCount: subtreeIds.length - 1,
589
605
  },
590
606
  comments: comments.map(comment => ({
@@ -44,14 +44,15 @@ export const terminalMethods = {
44
44
  if (!clean) throw badRequest('命令不能为空')
45
45
  if (clean.length > TERMINAL_COMMAND_MAX) throw badRequest(`命令过长(最多 ${TERMINAL_COMMAND_MAX} 字符)`)
46
46
  // 同项目同时只允许一条运行:检查与插入之间无 await,单线程内不会交错。
47
- if (this.store.get("SELECT id FROM terminal_commands WHERE project_id = ? AND status = 'running'", project.id)) {
47
+ if (this.groupChatStore(project.id).get("SELECT id FROM terminal_commands WHERE project_id = ? AND status = 'running'", project.id)) {
48
48
  throw conflict('该项目已有终端命令在运行,请先停止或等待它结束')
49
49
  }
50
50
  const commandId = id('term')
51
51
  const createdAt = nowIso()
52
52
  // 命令与聊天消息同一姿势:可能拼进密钥值,入库(行、审计)前先过掩码,密钥原文不落库。
53
53
  const storableCommand = this.maskSecretValues(clean)
54
- this.store.run(
54
+ // 终端命令住各项目聊天库(chat-db-split Phase 3):按 project_id 路由。
55
+ this.groupChatStore(project.id).run(
55
56
  `INSERT INTO terminal_commands(id, project_id, command, status, created_at) VALUES (?, ?, ?, 'running', ?)`,
56
57
  commandId, project.id, storableCommand, createdAt,
57
58
  )
@@ -87,10 +88,18 @@ export const terminalMethods = {
87
88
  this.finishTerminalCommand(commandId, 'failed', null, `命令执行失败:${error?.message ?? error}`)
88
89
  })
89
90
  this.audit(actor, 'terminal.run', 'project', project.id, { command: storableCommand })
90
- return this.terminalCommandView(this.store.get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
91
+ return this.terminalCommandView(this.groupChatStore(project.id).get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
92
+ },
93
+ // 命令行住各项目聊天库,commandId 不含项目信息:跨库扇出找行(库数是个位数、主键查)。
94
+ terminalCommandRow(commandId) {
95
+ for (const chatStore of this.allChatStores()) {
96
+ const row = chatStore.get('SELECT * FROM terminal_commands WHERE id = ?', commandId)
97
+ if (row) return row
98
+ }
99
+ return null
91
100
  },
92
101
  cancelTerminalCommand(commandId, actor = this.actor()) {
93
- const row = this.store.get('SELECT * FROM terminal_commands WHERE id = ?', commandId)
102
+ const row = this.terminalCommandRow(commandId)
94
103
  if (!row) throw notFound('终端命令不存在')
95
104
  if (row.status !== 'running') throw conflict('命令已结束,无需停止')
96
105
  const entry = this.terminalActive.get(commandId)
@@ -102,16 +111,16 @@ export const terminalMethods = {
102
111
  killTerminalGroup(entry.child)
103
112
  }
104
113
  this.audit(actor, 'terminal.cancel', 'terminal_command', commandId, {})
105
- return this.terminalCommandView(this.store.get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
114
+ return this.terminalCommandView(this.groupChatStore(row.project_id).get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
106
115
  },
107
116
  terminalState(projectId) {
108
117
  // 顺手清理:每项目只保留最近 TERMINAL_HISTORY_LIMIT 条,不新增定时器。
109
- this.store.run(
118
+ this.groupChatStore(projectId).run(
110
119
  `DELETE FROM terminal_commands WHERE project_id = ? AND id NOT IN (
111
120
  SELECT id FROM terminal_commands WHERE project_id = ? ORDER BY created_at DESC LIMIT ?)`,
112
121
  projectId, projectId, TERMINAL_HISTORY_LIMIT,
113
122
  )
114
- const history = this.store.all(
123
+ const history = this.groupChatStore(projectId).all(
115
124
  'SELECT * FROM terminal_commands WHERE project_id = ? ORDER BY created_at DESC LIMIT ?',
116
125
  projectId, TERMINAL_HISTORY_LIMIT,
117
126
  ).map(row => this.terminalCommandView(row))
@@ -140,18 +149,20 @@ export const terminalMethods = {
140
149
  const output = this.maskSecretValues(String(entry?.buffer ?? '').slice(-TERMINAL_OUTPUT_CAP))
141
150
  // 服务停机竞态:子进程在 store 关闭后才退出时,收尾写库失败只告警,不再炸进程。
142
151
  try {
143
- const row = this.store.get('SELECT project_id FROM terminal_commands WHERE id = ?', commandId)
144
- this.store.run(
145
- `UPDATE terminal_commands SET status = ?, exit_code = ?, output = ?, error_message = ?, ended_at = ? WHERE id = ?`,
146
- status, exitCode, output, errorMessage, nowIso(), commandId,
147
- )
148
- if (row) this.trimTerminalHistory(row.project_id)
152
+ const row = this.terminalCommandRow(commandId)
153
+ if (row) {
154
+ this.groupChatStore(row.project_id).run(
155
+ `UPDATE terminal_commands SET status = ?, exit_code = ?, output = ?, error_message = ?, ended_at = ? WHERE id = ?`,
156
+ status, exitCode, output, errorMessage, nowIso(), commandId,
157
+ )
158
+ this.trimTerminalHistory(row.project_id)
159
+ }
149
160
  } catch (error ) {
150
161
  this.logger.warn?.(`dsh-team: terminal command ${commandId} 收尾落库失败:${error?.message ?? error}`)
151
162
  }
152
163
  },
153
164
  trimTerminalHistory(projectId) {
154
- this.store.run(
165
+ this.groupChatStore(projectId).run(
155
166
  `DELETE FROM terminal_commands WHERE project_id = ? AND id NOT IN (
156
167
  SELECT id FROM terminal_commands WHERE project_id = ? ORDER BY created_at DESC LIMIT ?)`,
157
168
  projectId, projectId, TERMINAL_HISTORY_LIMIT,
@@ -76,7 +76,9 @@ export function spawnVisionProxyRun(service, { bot, message, target }) {
76
76
  runId, message.project_id ?? null, bot.id, message.id, idempotencyKey,
77
77
  proxy.provider, proxy.model, createdAt,
78
78
  )
79
- service.store.run(
79
+ // run_events 住运行归属的聊天库(chat-db-split Phase 3):路由行取自本回调刚
80
+ // 插入的 runs 参数(project_id/bot_id),与 runs 插入同回调保持撞车不落事件。
81
+ service.runChatStore({ id: runId, project_id: message.project_id ?? null, bot_id: bot.id }).run(
80
82
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
81
83
  id('evt'), runId, 'queued',
82
84
  `主模型无视觉,派生读图代理运行(${proxy.ref})转写消息 ${message.id} 的图片`,
@@ -97,11 +99,12 @@ export function spawnVisionProxyRun(service, { bot, message, target }) {
97
99
  // 主动评估入口(sendMessage / sendSoloMessage 落库投递后 fire-and-forget 调用):
98
100
  // 消息带图 && 主模型确定无视觉 → 已配置代理则派生转写运行;未配置则只记
99
101
  // vision.fallback 审计(按现状报错,不派生不重试)。任何异常只告警,绝不阻塞发送。
100
- export async function considerVisionProxy(service, { bot, message }) {
102
+ // messageStore(chat-db-split Phase 1):附图所在聊天库,由调用方随消息上下文带入。
103
+ export async function considerVisionProxy(service, { bot, message, messageStore = null }) {
101
104
  try {
102
105
  if (!bot || !message?.id) return null
103
106
  if (bot.status !== 'active') return null
104
- if (!messageHasImages(service.store, message.id)) return null
107
+ if (!messageHasImages(messageStore ?? service.store, message.id)) return null
105
108
  if (!await modelLacksImageSupport(service.runtime, bot)) return null
106
109
  const target = visionProxyTarget(service.config)
107
110
  if (!target) {
@@ -125,14 +128,14 @@ export function maybeSpawnVisionAfterFailure(service, { run, bot, error }) {
125
128
  if (!isImageUnsupportedError(error)) return null
126
129
  if (run?.kind !== 'chat' && run?.kind !== 'solo_chat') return null
127
130
  const message = run.trigger_ref
128
- ? service.store.get(
131
+ ? service.runChatStore(run).get(
129
132
  run.kind === 'chat'
130
133
  ? 'SELECT * FROM messages WHERE id = ?'
131
134
  : 'SELECT * FROM solo_messages WHERE id = ?',
132
135
  run.trigger_ref,
133
136
  )
134
137
  : null
135
- if (!message || !messageHasImages(service.store, message.id)) return null
138
+ if (!message || !messageHasImages(service.runChatStore(run), message.id)) return null
136
139
  const target = visionProxyTarget(service.config)
137
140
  if (!target) {
138
141
  service.audit({ type: 'bot', id: bot.id }, 'vision.fallback', 'bot', bot.id, {
@@ -154,7 +157,7 @@ export function maybeSpawnVisionAfterFailure(service, { run, bot, error }) {
154
157
  export async function completeVisionRun(service, { run, bot, status, output, error }) {
155
158
  const actor = { type: 'bot', id: bot?.id }
156
159
  const message = run.trigger_ref
157
- ? service.store.get(
160
+ ? service.runChatStore(run).get(
158
161
  run.project_id
159
162
  ? 'SELECT * FROM messages WHERE id = ?'
160
163
  : 'SELECT * FROM solo_messages WHERE id = ?',
@@ -160,7 +160,7 @@ export const wechatMethods = {
160
160
  async wechatDirectorChat(director, body) {
161
161
  const adminPeerId = this.wechat?.status?.()?.adminPeerId ?? null
162
162
  const actor = { type: 'user', id: adminPeerId ?? 'user:wechat' }
163
- const firstContact = !this.store.get(
163
+ const firstContact = !this.soloChatStore(director.id).get(
164
164
  "SELECT id FROM solo_messages WHERE bot_id = ? AND sender_type = 'user' AND sender_id = ? LIMIT 1",
165
165
  director.id,
166
166
  actor.id,
@@ -1,4 +1,6 @@
1
- // DSHBOTS-294 子代理账本(ADR §4.2.1):宿主事件缝 → 所属 task 运行的 run_events。
1
+ // DSHBOTS-294 子代理账本(ADR §4.2.1):宿主事件缝 → 所属 task 运行的 run_events
2
+ // (chat-db-split Phase 3 起事件住运行归属聊天库,路由器 { forRun } 由调用方注入,
3
+ // 未注入时回落顶库,行为与分库前一致)。
2
4
  // 双缝互补:tools 瀑布带 caller agent(父归属权威源,任务号标签在参数里);
3
5
  // subagent/start|end 带 stopReason+lastAssistantMessage(终态摘要源,载荷无父身份,
4
6
  // 靠 tools/result 配对或唯一 running task 运行兜底归属)。子代理不占 runs 行(§4.2)。
@@ -8,6 +10,13 @@ const SUBAGENT_TOOLS = new Set(['subagent', 'subagent_fork'])
8
10
  const SUMMARY_LIMIT = 400
9
11
  const STASH_LIMIT = 64
10
12
 
13
+ // bot → 在跑子代理计数(内存态,仅本轮进程内准确):总览 bots 页的「任务中」判定用。
14
+ const runningByBot = new Map()
15
+
16
+ export function runningSubagentCount(botId) {
17
+ return runningByBot.get(botId) ?? 0
18
+ }
19
+
11
20
  // 任务号标签(DSHBOTS-292 约定标签=任务号,如 DSHBOTS-294):优先 description,其次 prompt。
12
21
  export function taskLabelOf(args) {
13
22
  const source = typeof args?.description === 'string' ? args.description
@@ -24,7 +33,7 @@ const truncate = (text) => {
24
33
  }
25
34
 
26
35
  // 在插件根 ctx 注册事件监听(根级注册面实测见 tests/subagent-ledger.test.ts)。
27
- export function installSubagentLedger(ctx, store, logger) {
36
+ export function installSubagentLedger(ctx, store, logger, chatStores = null) {
28
37
  // callId → 派发时快照(tools/result 按 callId 配对父归属)
29
38
  const byCall = new Map()
30
39
  // botId → 未消费的标签栈(subagent/end 兜底归属时取最近一次派发的标签)
@@ -51,10 +60,16 @@ export function installSubagentLedger(ctx, store, logger) {
51
60
  return run ? { botId: binding.bot_id, runId: run.id } : null
52
61
  }
53
62
 
54
- const record = (runId, type, message) => store.run(
55
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
56
- id('rev'), runId, type, message, nowIso(),
57
- )
63
+ // 事件住运行归属聊天库(Phase 3):只有 runId,先取路由列再走注入的路由器;
64
+ // 运行行已不在(删除竞态)或未注入路由器时回落顶库留痕,不丢审计线索。
65
+ const record = (runId, type, message) => {
66
+ const run = store.get('SELECT id, project_id, bot_id FROM runs WHERE id = ?', runId)
67
+ const target = run && chatStores?.forRun ? chatStores.forRun(run) : store
68
+ target.run(
69
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
70
+ id('rev'), runId, type, message, nowIso(),
71
+ )
72
+ }
58
73
 
59
74
  const stashLabel = (botId, label) => {
60
75
  const list = labelsByBot.get(botId) ?? []
@@ -108,6 +123,7 @@ export function installSubagentLedger(ctx, store, logger) {
108
123
  record(owner.runId, 'subagent_spawned', `${exec.name} label=${label ?? '-'} bot=${owner.botId}`)
109
124
  byCall.set(exec.callId, { ...owner, label })
110
125
  stashLabel(owner.botId, label)
126
+ runningByBot.set(owner.botId, (runningByBot.get(owner.botId) ?? 0) + 1)
111
127
  }
112
128
  }
113
129
  } catch (error) {
@@ -144,6 +160,7 @@ export function installSubagentLedger(ctx, store, logger) {
144
160
  const entry = byCall.get(exec?.callId)
145
161
  if (!entry) return
146
162
  byCall.delete(exec?.callId)
163
+ runningByBot.set(entry.botId, Math.max(0, (runningByBot.get(entry.botId) ?? 1) - 1))
147
164
  // 配对暂存的 subagent/end:child id 出现在结果 JSON 里即认领其终态摘要
148
165
  let matched = null
149
166
  const haystack = JSON.stringify(result ?? {})